Skip to content

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

Unify command dock, harness launch, and onboarding (#165)

Dee10fecd93f55c
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index e35a02d38..aa9cc59f6 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -1268,6 +1268,75 @@ describe('agent_fork RPC', () => {
return { socket, frames }
}
+ it('recovers a fork receipt with its handoff level without creating another agent', async () => {
+ const { socket, frames } = localSocket()
+ const lookup = vi.spyOn(registry, 'byAgent').mockReturnValue(FORK)
+ let finish!: () => void
+ const fork = vi.fn(() => new Promise<{ ok: true; session: RegisteredSession; level: 'handoff' }>((resolve) => {
+ finish = () => resolve({ ok: true, session: FORK, level: 'handoff' })
+ }))
+ socket.onForkAgent = fork
+ const creationId = randomUUID()
+ const ask = (type: string, requestId: string, name = 'Separate idea') => socket.handleLocalFrame('local:fork', {
+ type, payload: { requestId, creationId, agentId: 'agent-1', name, prompt: ' preserve\n indentation ' },
+ })
+ try {
+ ask('agent_fork', 'first')
+ await vi.waitFor(() => expect(fork).toHaveBeenCalledTimes(1))
+ ask('agent_create_status', 'pending')
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_create_status_result', payload: { requestId: 'pending', creationId, state: 'pending' },
+ }))
+ ask('agent_fork', 'retry')
+ finish()
+ for (const requestId of ['first', 'retry']) {
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_fork_result', payload: expect.objectContaining({ requestId, creationId, state: 'created', level: 'handoff', agent: expect.objectContaining({ id: FORK.agentId }) }),
+ })))
+ }
+ expect(fork).toHaveBeenCalledWith({ agentId: 'agent-1', name: 'Separate idea', prompt: ' preserve\n indentation ' })
+ ask('agent_create_status', 'recovered')
+ await vi.waitFor(() => expect(frames).toContainEqual(expect.objectContaining({
+ type: 'agent_create_status_result', payload: expect.objectContaining({ requestId: 'recovered', state: 'created', level: 'handoff' }),
+ })))
+ ask('agent_fork', 'changed', 'Different intent')
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_fork_result', payload: { requestId: 'changed', error: 'CREATION_CONFLICT' },
+ }))
+ lookup.mockReturnValue(undefined)
+ ask('agent_fork', 'deleted')
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_fork_result', payload: { requestId: 'deleted', creationId, state: 'unavailable' },
+ }))
+ expect(fork).toHaveBeenCalledTimes(1)
+ } finally {
+ finish?.()
+ await socket.unregisterLocalClient('local:fork')
+ await socket.stop()
+ }
+ })
+
+ it.each(['SPAWN_FAILED', 'REGISTRATION_FAILED', 'AGENT_BUSY'])('retains the fork outcome for %s', async (error) => {
+ const { socket, frames } = localSocket()
+ const fork = vi.fn(async () => ({ ok: false as const, error, detail: 'Fixture refusal' }))
+ socket.onForkAgent = fork
+ const creationId = randomUUID()
+ const state = error === 'AGENT_BUSY' ? 'failed' : 'unconfirmed'
+ try {
+ for (const requestId of ['first', 'retry']) {
+ socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId, creationId, agentId: 'agent-1' } })
+ await vi.waitFor(() => expect(frames).toContainEqual({
+ type: 'agent_fork_result', payload: { requestId, creationId, state,
+ ...(state === 'failed' ? { failure: { code: error, detail: 'Fixture refusal' } } : {}) },
+ }))
+ }
+ expect(fork).toHaveBeenCalledTimes(1)
+ } finally {
+ await socket.unregisterLocalClient('local:fork')
+ await socket.stop()
+ }
+ })
+
it('validates the frame before touching the daemon', async () => {
const { socket, frames } = localSocket()
socket.handleLocalFrame('local:fork', { type: 'agent_fork', payload: { requestId: 'r1' } })
@@ -1419,6 +1488,48 @@ describe('agent_restart RPC', () => {
await socket.stop()
})
+ it('recovers a restart receipt without replacing the process again', async () => {
+ const { socket, frames } = localSocket()
+ const creationId = 'restart-receipt-test-0001'
+ let finish!: () => void
+ const handler = vi.fn(async () => {
+ await new Promise<void>((resolve) => { finish = resolve })
+ return { ok: true as const, session: BASE_SESSION, resumed: false }
+ })
+ socket.onRestartAgent = handler
+ vi.spyOn(registry, 'byAgent').mockImplementation((id) => id === BASE_SESSION.agentId ? BASE_SESSION : undefined)
+ const request = (requestId: string, type = 'agent_restart') => socket.handleLocalFrame('local:restart', { type, payload: { requestId, agentId: 'agent-1', creationId } })
+ const response = (id: string) => frames.find((frame) => (frame.payload as { requestId?: string }).requestId === id)?.payload
+ request('first')
+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(1))
+ request('pending', 'agent_create_status')
+ await vi.waitFor(() => expect(response('pending')).toMatchObject({ creationId, state: 'pending' }))
+ request('joined')
+ finish()
+ await vi.waitFor(() => expect(response('joined')).toMatchObject({ creationId, state: 'created', resumed: false }))
+ request('recovered', 'agent_create_status')
+ await vi.waitFor(() => expect(response('recovered')).toMatchObject({ creationId, state: 'created', resumed: false }))
+ request('duplicate')
+ await vi.waitFor(() => expect(response('duplicate')).toMatchObject({ creationId, state: 'created' }))
+ expect(handler).toHaveBeenCalledTimes(1)
+ await socket.unregisterLocalClient('local:restart')
+ await socket.stop()
+ })
+
+ it.each(['RESTART_FAILED', 'AGENT_BUSY'])('retains %s without repeating a restart', async (error) => {
+ const { socket, frames } = localSocket()
+ const creationId = `restart-receipt-${error}`
+ const handler = vi.fn(async () => ({ ok: false as const, error, detail: 'fixture refusal' }))
+ socket.onRestartAgent = handler
+ for (const requestId of ['first', 'again']) {
+ socket.handleLocalFrame('local:restart', { type: 'agent_restart', payload: { requestId, agentId: 'agent-1', creationId } })
+ await vi.waitFor(() => expect(frames.find((frame) => (frame.payload as { requestId?: string }).requestId === requestId)?.payload).toMatchObject({ creationId, state: error === 'RESTART_FAILED' ? 'unconfirmed' : 'failed' }))
+ }
+ expect(handler).toHaveBeenCalledTimes(1)
+ await socket.unregisterLocalClient('local:restart')
+ await socket.stop()
+ })
+
it('omits detail on failure when the handler did not supply one', async () => {
const { socket, frames } = localSocket()
socket.onRestartAgent = async () => ({ ok: false, error: 'AGENT_NOT_FOUND' })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index b7371ab91..a994af5c8 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -2273,6 +2273,26 @@ export class BackendSocket {
const target = payload.agentId as string | undefined
if (!target) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
if (!this.onRestartAgent) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }
+ const creationId = payload.creationId
+ if (creationId !== undefined) {
+ if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }
+ const restart = this.onRestartAgent
+ try {
+ void this.agentCreations.run(creationId, creationFingerprint({ operation: 'restart', agentId: target }), async () => {
+ const result = await restart(target)
+ if (result.ok) return { state: 'created', agentId: result.session.agentId, resumed: result.resumed }
+ // RESTART_FAILED can follow an unobserved relaunch. Never silently
+ // replace that process again when a caller checks this intent.
+ if (result.error === 'RESTART_FAILED') return { state: 'unconfirmed' }
+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ }).then(async (status) => {
+ reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })
+ }).catch(() => reply(type, requestId, { error: 'INTERNAL' }))
+ } catch (error) {
+ reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ return
+ }
const result = await this.onRestartAgent(target)
if (!result.ok) {
reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
@@ -2293,6 +2313,26 @@ export class BackendSocket {
if (rawPrompt !== undefined && rawPrompt !== null && typeof rawPrompt !== 'string') { reply(type, requestId, { error: 'INVALID_PROMPT' }); return }
const prompt = typeof rawPrompt === 'string' && rawPrompt.trim() ? rawPrompt : null
if (prompt && prompt.length > MAX_FIRST_PROMPT_CHARS) { reply(type, requestId, { error: 'PROMPT_TOO_LONG' }); return }
+ const creationId = payload.creationId
+ if (creationId !== undefined) {
+ if (!validCreationId(creationId)) { reply(type, requestId, { error: 'INVALID_CREATION_ID' }); return }
+ // Forking starts a new process too. Reserve the same durable intent used
+ // by agent_create so a lost receipt can be checked without another fork.
+ const fork = this.onForkAgent
+ try {
+ void this.agentCreations.run(creationId, creationFingerprint({ operation: 'fork', agentId: target, name, prompt }), async () => {
+ const result = await fork({ agentId: target, name, prompt })
+ if (result.ok) return { state: 'created', agentId: result.session.agentId, level: result.level }
+ if (result.error === 'SPAWN_FAILED' || result.error === 'REGISTRATION_FAILED') return { state: 'unconfirmed' }
+ return { state: 'failed', error: result.error, ...(result.detail ? { detail: result.detail.slice(0, 2000) } : {}) }
+ }).then(async (status) => {
+ reply(type, requestId, { creationId, ...await this.creationStatusPayload(status) })
+ }).catch(() => reply(type, requestId, { error: 'INTERNAL' }))
+ } catch (error) {
+ reply(type, requestId, { error: error instanceof AgentCreationReceiptError ? error.code : 'INTERNAL' })
+ }
+ return
+ }
const result = await this.onForkAgent({ agentId: target, name, prompt })
if (!result.ok) {
reply(type, requestId, result.detail ? { error: result.error, detail: result.detail } : { error: result.error })
@@ -2472,7 +2512,7 @@ export class BackendSocket {
if (status.state === 'created') {
const session = registry.byAgent(status.agentId)
return session
- ? { state: 'created', agent: await this.toProject(session) }
+ ? { state: 'created', agent: await this.toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }
: { state: 'unavailable' }
}
// A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index fae382878..abafaa967 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -77,7 +77,7 @@ import { writeGridConfigDir } from './lib/gridConfigDir.js'
import { tmuxSupportsSessionEnv, TMUX_SESSION_ENV_MIN } from './lib/tmuxVersion.js'
import { clearDeleted, isRecentlyDeleted, markDeleted } from './lib/deletedSessions.js'
import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallback.js'
-import { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'
+import { AgentRestartCoordinator, restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'
import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'
import { TmuxBackend } from './lib/tmuxBackend.js'
import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'
@@ -121,6 +121,8 @@ import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js
import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'
import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'
import { remoteCommand } from './remoteCommand.js'
+import { newCommand } from './lib/newCommand.js'
+import { WebSocket as NewCommandSocket } from 'ws'
import {
terminalActionNotStarted,
type HookTerminalHint,
@@ -334,6 +336,8 @@ Machine:
harness reset stop the adapter and clear local CLI state
harness status show whether it's running (+ version)
harness logs export zip the last 7 days of logs (app, CLI, dial, daemon) to the Desktop
+ harness new [agent] [@machine] [folder|name] [-- task]
+ make a harness from a shell: \`harness new\` is claude here; see \`harness new -h\`
harness machines list the machines on this account (this computer's is marked)
harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)
harness remote from a Harness terminal tile: open a terminal on another of your machines and move this tile to it
@@ -4478,6 +4482,13 @@ async function runForeground(session: AuthSession): Promise<void> {
* is the only thing this takes. Written once because two copies of a kill sequence drift, and the
* half that drifts is the half nobody ran today.
*/
+ const restartJobs = new AgentRestartCoordinator()
+ const sameRestartTarget = (session: RegisteredSession): boolean => {
+ const current = registry.byAgent(session.agentId)
+ return !!current && current.registeredAt === session.registeredAt
+ && current.tmuxPane === session.tmuxPane && current.engine === session.engine
+ }
+
const paneSwapDeps = (
session: RegisteredSession,
runtime: TmuxRuntimeRef,
@@ -4759,6 +4770,7 @@ async function runForeground(session: AuthSession): Promise<void> {
* `registry.remove` + `mirror.forget` keep the recap AND the agent-name override for a later resume.
*/
backend.onDeleteAgent = (sessionId) => {
+ restartJobs.cancel(registry.resolve(sessionId)?.agentId ?? sessionId)
const s = registry.resolve(sessionId) // BEFORE forgetSession — that removes it from the registry
// The engine outlives this call by a second or two now, and its catch hook fires on every turn
// boundary. Without the tombstone that hook re-registers the session and the tile comes straight back.
@@ -4817,10 +4829,14 @@ async function runForeground(session: AuthSession): Promise<void> {
* registry's live-synced field, not from the original launch argv (the user may have resumed/switched
* sessions from inside the engine's own terminal since launch).
*/
- backend.onRestartAgent = async (agentId) => {
+ backend.onRestartAgent = (agentId) => restartJobs.run(registry.resolve(agentId)?.agentId ?? agentId, async (operationCurrent) => {
const session = registry.resolve(agentId)
if (!session) return { ok: false, error: 'AGENT_NOT_FOUND' }
if (!session.tmuxPane || !tmuxBackend) return { ok: false, error: 'RESTART_UNSUPPORTED_BACKEND' }
+ const target = { ...session }
+ const current = () => operationCurrent() && sameRestartTarget(target)
+ const changed = { ok: false, error: 'AGENT_CHANGED', detail: 'The agent changed or stopped during restart.' } as const
+ if (!current()) return changed
const pane = session.tmuxPane
const engine = session.engine
const runtime: TmuxRuntimeRef = { backend: 'tmux', paneId: pane }
@@ -4836,8 +4852,10 @@ async function runForeground(session: AuthSession): Promise<void> {
command: buildEngineLaunchArgv(engine, session.cwd ? { cwd: session.cwd } : {}),
cwd: homedir(),
})
+ if (!current()) return changed
if (respawned.state !== 'succeeded') return { ok: false, error: 'RESTART_FAILED', detail: respawned.reason }
await clearPaneRemainOnExit(pane)
+ if (!current()) return changed
registry.setActive(session.agentId, true)
const refreshed = registry.byAgent(session.agentId)
if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }
@@ -4856,6 +4874,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// Codex profile. Refused before anything is killed, so a restart that cannot honour the grid
// leaves the running process alone.
const built = await relaunchOverrides(session)
+ if (!current()) return changed
if (!built.ok) return { ok: false, error: built.error, detail: built.detail }
agentReconciler.holdRoute(routeKey)
@@ -4864,9 +4883,10 @@ async function runForeground(session: AuthSession): Promise<void> {
const outcome = await restartAgent(
{ engine, sessionId: session.sessionId },
bypassPermission,
- paneSwapDeps(session, runtime, built.overrides),
+ { ...paneSwapDeps(session, runtime, built.overrides), isCurrent: current },
)
+ if (!current()) return changed
if (!outcome.ok) return { ok: false, error: 'RESTART_FAILED', detail: outcome.detail }
refreshGridWebSearch(session.agentId, built.overrides)
@@ -4878,9 +4898,11 @@ async function runForeground(session: AuthSession): Promise<void> {
probeGatewayRuntime(outcome.processIdentity),
probeGridAssignment(outcome.processIdentity, engine, outcome.processIdentity.executable),
])
+ if (!current()) return changed
registry.updateProcessIdentity(session.agentId, outcome.processIdentity, gateway.kind, assignment)
registry.setActive(session.agentId, true)
await clearPaneRemainOnExit(pane)
+ if (!current()) return changed
const refreshed = registry.byAgent(session.agentId)
if (!refreshed) return { ok: false, error: 'RESTART_FAILED', detail: 'agent vanished from the registry mid-restart' }
announceSession(refreshed)
@@ -4890,7 +4912,7 @@ async function runForeground(session: AuthSession): Promise<void> {
} finally {
agentReconciler.releaseRoute(routeKey)
}
- }
+ })
const submitAgent = (id: string, content: string, deliveryId?: string): void => {
const record = registry.resolve(id)
@@ -6318,6 +6340,29 @@ switch (cmd) {
.then((code) => { process.exitCode = code })
.catch(onError)
break
+ case 'new':
+ // `rest`, not args/flags: a first message and a folder are words in the order they were typed.
+ newCommand({
+ argv: rest,
+ cwd: process.cwd(),
+ home: homedir(),
+ port: daemonPort(),
+ localMachineId: readAuthSession()?.machineId ?? null,
+ daemonRunning: isDaemonRunning,
+ listMachines: async () => {
+ const { session, headers } = await controlPlaneAuth()
+ return (await fetchMachines(headers)).map((machine) => ({
+ machineId: machine.machineId,
+ label: machineLabel(machine),
+ status: machine.status || 'unknown',
+ current: machine.machineId === session.machineId,
+ }))
+ },
+ connect: (url) => new NewCommandSocket(url),
+ output: (line) => console.log(line),
+ error: (line) => console.error(line),
+ }).then((code) => { process.exitCode = code }).catch(onError)
+ break
case 'remote':
remoteCommand({
tmuxPane: process.env.TMUX_PANE,
diff --git a/cli/src/lib/agentCreationReceipt.spec.ts b/cli/src/lib/agentCreationReceipt.spec.ts
index 9e2344cfc..bcb7f43a8 100644
--- a/cli/src/lib/agentCreationReceipt.spec.ts
+++ b/cli/src/lib/agentCreationReceipt.spec.ts
@@ -97,3 +97,25 @@ describe('agent creation receipts', () => {
expect(statSync(file).mode & 0o777).toBe(0o600)
})
})
+
+
+it('retains a fork handoff level through a daemon restart', async () => {
+ const { directory, receipts } = fixture()
+ await receipts.run(id, fingerprint, async () => ({ state: 'created', agentId: 'forked', level: 'handoff' }))
+ const restarted = new AgentCreationReceipts(directory)
+ expect(restarted.status(id)).toEqual({ state: 'created', agentId: 'forked', level: 'handoff' })
+ const launch = vi.fn()
+ expect(await restarted.run(id, fingerprint, launch)).toEqual({ state: 'created', agentId: 'forked', level: 'handoff' })
+ expect(launch).not.toHaveBeenCalled()
+})
+
+it('retains a fresh restart outcome through a daemon restart', async () => {
+ const { directory, receipts } = fixture()
+ const restart = vi.fn(async () => ({ state: 'created' as const, agentId: 'agent-1', resumed: false }))
+ const intent = creationFingerprint({ operation: 'restart', agentId: 'agent-1' })
+ await receipts.run(id, intent, restart)
+ const recovered = new AgentCreationReceipts(directory)
+ expect(recovered.status(id)).toEqual({ state: 'created', agentId: 'agent-1', resumed: false })
+ expect(await recovered.run(id, intent, restart)).toEqual(recovered.status(id))
+ expect(restart).toHaveBeenCalledTimes(1)
+})
diff --git a/cli/src/lib/agentCreationReceipt.ts b/cli/src/lib/agentCreationReceipt.ts
index 384292b14..f3dbbed11 100644
--- a/cli/src/lib/agentCreationReceipt.ts
+++ b/cli/src/lib/agentCreationReceipt.ts
@@ -4,7 +4,7 @@ import { dirname, join } from 'node:path'
import { readPrivateStateFile, secureStateDirectory } from './secureState.js'
export type AgentCreationOutcome =
- | { state: 'created'; agentId: string }
+ | { state: 'created'; agentId: string; level?: 'native' | 'handoff'; resumed?: boolean }
| { state: 'failed'; error: string; detail?: string; preparedFolder?: string }
| { state: 'unconfirmed' }
@@ -115,7 +115,9 @@ export class AgentCreationReceipts {
const outcome = value.outcome
if (value.version !== 1 || !/^[a-f0-9]{64}$/.test(value.fingerprint ?? '') || !outcome ||
!['pending', 'unconfirmed', 'created', 'failed'].includes(outcome.state) ||
- (outcome.state === 'created' && (typeof outcome.agentId !== 'string' || !outcome.agentId)) ||
+ (outcome.state === 'created' && (typeof outcome.agentId !== 'string' || !outcome.agentId ||
+ (outcome.level !== undefined && outcome.level !== 'native' && outcome.level !== 'handoff') ||
+ (outcome.resumed !== undefined && typeof outcome.resumed !== 'boolean'))) ||
(outcome.state === 'failed' && typeof outcome.error !== 'string')) {
throw new Error('Invalid creation receipt')
}
diff --git a/cli/src/lib/agentNames.ts b/cli/src/lib/agentNames.ts
index 3d98edf5e..151c6a001 100644
--- a/cli/src/lib/agentNames.ts
+++ b/cli/src/lib/agentNames.ts
@@ -62,3 +62,11 @@ export function projectFolderName(label: string, at: Date, withSeconds = false):
const time = `${pad(at.getHours())}-${pad(at.getMinutes())}${withSeconds ? `-${pad(at.getSeconds())}` : ''}`
return `${slug}-${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}-${time}`
}
+
+/** The folder for a project somebody named: their words with spaces as dashes and nothing a path or
+ * a shell reads specially. Null when nothing usable is left. Mirrors `projectFolderSlug` in
+ * desktop/lib/core/project_folder.dart. */
+export function projectFolderSlug(name: string): string | null {
+ const slug = name.trim().replace(/\s+/g, '-').replace(/[^A-Za-z0-9._-]+/g, '').replace(/^[.-]+|[.-]+$/g, '')
+ return slug ? slug.slice(0, 64) : null
+}
diff --git a/cli/src/lib/newCommand.spec.ts b/cli/src/lib/newCommand.spec.ts
new file mode 100644
index 000000000..c0faf66ff
--- /dev/null
+++ b/cli/src/lib/newCommand.spec.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from 'vitest'
+import { EventEmitter } from 'node:events'
+import { newAgentPayload, newCommand, NewUsageError, parseNewArgs, resolveNewMachine, type NewCommandDeps, type NewSocket } from './newCommand.js'
+
+const env = { cwd: '/work/repo', home: '/home/me' }
+
+describe('harness new: the words', () => {
+ it('asks nothing: claude, here, on this machine', () => {
+ expect(parseNewArgs([], env)).toEqual({
+ agent: 'claude', machine: null, cwd: '/work/repo', projectName: null, mode: 'auto', prompt: null, name: null, json: false,
+ })
+ })
+
+ it('reads agent, @machine and a folder in any order', () => {
+ const typed = parseNewArgs(['codex', '@mini', '~/code/auth'], env)
+ expect(typed).toMatchObject({ agent: 'codex', machine: 'mini', cwd: '~/code/auth', projectName: null })
+ expect(parseNewArgs(['~/code/auth', '@mini', 'codex'], env)).toEqual(typed)
+ // On this machine ~ and relative paths are resolved here, from where it was run.
+ expect(parseNewArgs(['codex', '~/code/auth'], env).cwd).toBe('/home/me/code/auth')
+ expect(parseNewArgs(['codex', './api'], env).cwd).toBe('/work/repo/api')
+ expect(parseNewArgs(['.'], env)).toMatchObject({ agent: 'claude', cwd: '/work/repo' })
+ })
+
+ it('takes a second word, or --new, as a new project', () => {
+ expect(parseNewArgs(['codex', 'my-game'], env)).toMatchObject({ agent: 'codex', cwd: null, projectName: 'my-game' })
+ expect(parseNewArgs(['codex', '--new'], env)).toMatchObject({ cwd: null, projectName: '' })
+ expect(parseNewArgs(['--new', 'my game', 'codex'], env)).toMatchObject({ agent: 'codex', projectName: 'my game' })
+ // Another machine has no "here": with nothing named it is a new project there.
+ expect(parseNewArgs(['codex', '@mini'], env)).toMatchObject({ machine: 'mini', cwd: null, projectName: '' })
+ })
+
+ it('takes the task after --, or as --task, with nothing to quote', () => {
+ expect(parseNewArgs(['codex', '--', 'fix', 'the', 'flaky', 'login', 'test'], env)).toMatchObject({ agent: 'codex', prompt: 'fix the flaky login test', cwd: '/work/repo' })
+ expect(parseNewArgs(['--task', 'write the README'], env).prompt).toBe('write the README')
+ // Words after -- are never read as an agent, a machine or a folder.
+ expect(parseNewArgs(['--', '@mini', '~/x'], env)).toMatchObject({ agent: 'claude', machine: null, prompt: '@mini ~/x' })
+ })
+
+ it('reads a path the shell already expanded as the other machine\'s home', () => {
+ // `harness new codex @mini ~/code/auth`, unquoted: zsh hands over /home/me/code/auth.
+ expect(parseNewArgs(['codex', '@mini', '/home/me/code/auth'], env).cwd).toBe('~/code/auth')
+ expect(parseNewArgs(['codex', '@mini', '/home/me'], env).cwd).toBe('~')
+ expect(parseNewArgs(['codex', '@mini', '/srv/app'], env).cwd).toBe('/srv/app')
+ // On this machine an absolute path is just that.
+ expect(parseNewArgs(['codex', '/home/me/code/auth'], env).cwd).toBe('/home/me/code/auth')
+ })
+
+ it('says what is wrong instead of guessing', () => {
+ for (const argv of [['a', 'b', 'c'], ['@'], ['@a', '@b'], ['/x', '/y'], ['codex', 'game', '/x'], ['--mode', 'yolo'], ['--prompt'], ['--wat'], ['-x'], ['codex', '..'], ['codex', '@mini', './rel']]) {
+ // `codex ..` is a folder, not an error; every other row must throw.
+ if (argv.join(' ') === 'codex ..') { expect(parseNewArgs(argv, env).cwd).toBe('/work'); continue }
+ expect(() => parseNewArgs(argv, env), argv.join(' ')).toThrow(NewUsageError)
+ }
+ expect(() => parseNewArgs(['codex', '!!!'], env)).toThrow(/no usable folder name/)
+ })
+
+ it('sends what the app sends', () => {
+ const here = newAgentPayload(parseNewArgs(['codex', '--plan', '--prompt', 'fix the tests'], env), '/work/repo')
+ expect(here).toMatchObject({ engine: 'codex', cwd: '/work/repo', permissionMode: 'plan', bypassPermission: false, prompt: 'fix the tests' })
+ expect(here).not.toHaveProperty('projectSource')
+ expect(typeof here.creationId).toBe('string')
+ const fresh = newAgentPayload(parseNewArgs(['claude', 'My Game'], env), null)
+ expect(fresh).toMatchObject({ engine: 'claude', projectSource: 'new', projectName: 'My-Game', permissionMode: 'auto', bypassPermission: true })
+ expect(fresh).not.toHaveProperty('cwd')
+ expect(newAgentPayload(parseNewArgs(['acme/blender', '.'], env), '/work/repo', 'codex')).toMatchObject({ engine: 'codex', dsh: 'acme/blender' })
+ })
+
+ it('finds the machine by id, name or an unambiguous start of one', () => {
+ const machines = [
+ { machineId: 'm1', label: 'Mac mini', status: 'online', current: false },
+ { machineId: 'm2', label: 'MacBook Pro', status: 'online', current: true },
+ ]
+ expect(resolveNewMachine('m1', machines).label).toBe('Mac mini')
+ expect(resolveNewMachine('mac mini', machines).machineId).toBe('m1')
+ expect(resolveNewMachine('macb', machines).machineId).toBe('m2')
+ expect(() => resolveNewMachine('mac', machines)).toThrow(/could be Mac mini or MacBook Pro/)
+ expect(() => resolveNewMachine('linux', machines)).toThrow(/No machine called/)
+ })
+})
+
+class FakeSocket extends EventEmitter implements NewSocket {
+ sent: Array<{ type: string; payload: Record<string, unknown> }> = []
+ constructor(private answer: (frame: { type: string; payload: Record<string, unknown> }) => Record<string, unknown> | null) {
+ super()
+ }
+ // Opens once somebody is listening for it, as a real socket opens after it is constructed.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ override on(event: string, listener: (...args: any[]) => void): this {
+ super.on(event, listener)
+ if (event === 'open') queueMicrotask(() => this.emit('open'))
+ return this
+ }
+ send(data: string): void {
+ const frame = JSON.parse(data) as { type: string; payload: Record<string, unknown> }
+ this.sent.push(frame)
+ queueMicrotask(() => {
+ if (frame.type === 'machine_select') { this.emit('message', JSON.stringify({ type: 'connected', payload: {} })); return }
+ const payload = this.answer(frame)
+ if (payload) this.emit('message', JSON.stringify({ type: `${frame.type}_result`, payload: { ...payload, requestId: frame.payload.requestId } }))
+ })
+ }
+ close(): void {}
+}
+
+function deps(argv: string[], socket: FakeSocket, over: Partial<NewCommandDeps> = {}): NewCommandDeps & { out: string[]; err: string[] } {
+ const out: string[] = []
+ const err: string[] = []
+ return {
+ argv, cwd: env.cwd, home: env.home, port: 1, localMachineId: 'm2',
+ daemonRunning: () => true,
+ listMachines: async () => [
+ { machineId: 'm1', label: 'Mac mini', status: 'online', current: false },
+ { machineId: 'm2', label: 'MacBook Pro', status: 'online', current: true },
+ ],
+ connect: () => socket,
+ output: (line) => out.push(line), error: (line) => err.push(line),
+ timeoutMs: 200, out, err, ...over,
+ }
+}
+
+describe('harness new: the daemon', () => {
+ it('selects this machine, creates here and says where', async () => {
+ const socket = new FakeSocket((frame) => frame.type === 'agent_create'
+ ? { state: 'created', agent: { id: 'a1', name: 'Codex harness 9-19 10:02', cwd: '/work/repo' } } : null)
+ const d = deps(['codex'], socket)
+ expect(await newCommand(d)).toBe(0)
+ expect(socket.sent.map((frame) => frame.type)).toEqual(['machine_select', 'agent_create'])
+ expect(socket.sent[0]!.payload).toEqual({ machineId: 'm2', localProtocolVersion: 1 })
+ expect(socket.sent[1]!.payload).toMatchObject({ engine: 'codex', cwd: '/work/repo' })
+ expect(d.out[0]).toBe('Created Codex harness 9-19 10:02 on this computer in /work/repo.')
+ })
+
+ it('asks another machine where its home is before using ~', async () => {
+ const socket = new FakeSocket((frame) => frame.type === 'fs_list_dir' ? { path: '/Users/mini', entries: [] }
+ : frame.type === 'agent_create' ? { state: 'created', agent: { id: 'a2', name: 'auth' } } : null)
+ const d = deps(['codex', '@mini', '~/code/auth', '--json'], socket)
+ expect(await newCommand(d)).toBe(0)
+ expect(socket.sent[0]!.payload.machineId).toBe('m1')
+ expect(socket.sent.map((frame) => frame.type)).toEqual(['machine_select', 'fs_list_dir', 'agent_create'])
+ expect(socket.sent[2]!.payload.cwd).toBe('/Users/mini/code/auth')
+ expect(JSON.parse(d.out[0]!)).toMatchObject({ ok: true, machineId: 'm1', agent: { id: 'a2' } })
+ })
+
+ it('reads a store harness\'s engine off the machine, and will not create one that is not installed', async () => {
+ const catalog = [{ id: 'acme/blender', engine: 'codex', installed: true }, { id: 'acme/typst', engine: 'claude', installed: false }]
+ const socket = new FakeSocket((frame) => frame.type === 'dsh_list' ? { dsh: catalog }
+ : frame.type === 'agent_create' ? { state: 'created', agent: { id: 'a3', name: 'Blender' } } : null)
+ expect(await newCommand(deps(['acme/blender'], socket))).toBe(0)
+ expect(socket.sent[2]!.payload).toMatchObject({ engine: 'codex', dsh: 'acme/blender' })
+ const refused = deps(['acme/typst'], new FakeSocket((frame) => frame.type === 'dsh_list' ? { dsh: catalog } : null))
+ expect(await newCommand(refused)).toBe(1)
+ expect(refused.err[0]).toBe('Install it first: harness dsh install acme/typst')
+ })
+
+ it('turns the machine\'s refusal into words, and a usage slip into the usage', async () => {
+ const socket = new FakeSocket((frame) => frame.type === 'agent_create' ? { error: 'INVALID_CWD', detail: '/nope' } : null)
+ const d = deps(['codex', '/nope'], socket)
+ expect(await newCommand(d)).toBe(1)
+ expect(d.err[0]).toBe('That folder does not exist on the machine. (/nope)')
+ const help = deps(['--help'], socket)
+ expect(await newCommand(help)).toBe(0)
+ expect(help.out.join('\n')).toContain('Usage: harness new')
+ expect(help.err).toEqual([])
+ const slip = deps(['a', 'b', 'c'], socket)
+ expect(await newCommand(slip)).toBe(2)
+ expect(slip.err.join('\n')).toContain('Usage: harness new')
+ const stopped = deps(['codex'], socket, { daemonRunning: () => false })
+ expect(await newCommand(stopped)).toBe(1)
+ expect(stopped.err[0]).toMatch(/harness start/)
+ })
+})
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
new file mode 100644
index 000000000..b62a2c68f
--- /dev/null
+++ b/cli/src/lib/newCommand.ts
@@ -0,0 +1,329 @@
+import { randomUUID } from 'node:crypto'
+import { isAbsolute, join, resolve } from 'node:path'
+import { projectFolderSlug } from './agentNames.js'
+
+/**
+ * `harness new` — make a harness from a shell, in the words the app's box uses:
+ *
+ * harness new claude, here
+ * harness new codex codex, here
+ * harness new codex @mini ~/code/auth codex, on mini, in that folder
+ * harness new codex my-game codex, in a new project ~/harnesses/my-game
+ * harness new --new a new project named after the agent and the time
+ *
+ * A new terminal tab asks nothing and opens where you were; so does this. With no folder named it
+ * works in the directory it was run from, which is what `cd repo && harness new` means to anyone who
+ * has typed `code .` — and the one thing the app's box cannot know. The order of the words is free:
+ * `@` marks the machine, a path looks like a path, the first other word is the agent and the second
+ * names a new project.
+ */
+export interface NewArgs {
+ agent: string
+ /** A machine's label or id as typed after `@`, or null for this one. */
+ machine: string | null
+ /** The folder to work in, absolute; null when a new project is asked for instead. */
+ cwd: string | null
+ /** A new project: its name, or '' to let the clock name it; null when `cwd` is given. */
+ projectName: string | null
+ mode: string
+ prompt: string | null
+ name: string | null
+ json: boolean
+}
+
+export class NewUsageError extends Error {}
+/** `-h` / `--help`: not a mistake, so not exit code 2 and not on stderr. */
+export class NewHelpRequested extends Error {}
+
+export const NEW_USAGE = [
+ 'Usage: harness new [agent] [@machine] [folder | project-name] [options]',
+ '',
+ ' agent claude (default), codex, opencode, …, or a store harness like owner/name',
+ ' @machine a machine\'s name or id; this one when left out',
+ ' folder a path (/abs, ~/x, ./x, .): work there. Left out: the current directory.',
+ ' With @machine, a path under THIS home is read as the same path under its home,',
+ ' because the shell has already turned ~/x into /Users/you/x by the time it gets here',
+ ' project-name any other second word: a new project ~/harnesses/<name> on that machine',
+ '',
+ ' --new [name] a new project, named <name> or after the agent and the time',
+ ' --mode <mode> auto (default), ask, plan or full, where the agent has it',
+ ' --plan the same as --mode plan',
+ ' --task <t> the first message, sent as the harness starts (--prompt is the same)',
+ ' -- <words…> everything after -- is the first message, unquoted:',
+ ' harness new codex -- fix the flaky login test',
+ ' --name <n> the harness\'s name until the agent titles its session',
+ ' --json print the result as one JSON line',
+].join('\n')
+
+const MODES = new Set(['auto', 'ask', 'plan', 'full'])
+const looksLikePath = (word: string): boolean =>
+ word === '.' || word === '..' || word === '~' || /^(\/|~\/|\.\/|\.\.\/)/.test(word)
+
+export function parseNewArgs(argv: string[], env: { cwd: string; home: string }): NewArgs {
+ const words: string[] = []
+ let machine: string | null = null
+ let folder: string | null = null
+ let projectName: string | null = null
+ let mode = 'auto'
+ let prompt: string | null = null
+ let name: string | null = null
+ let json = false
+ const value = (flag: string, index: number): string => {
+ const next = argv[index + 1]
+ if (next === undefined || next.startsWith('--')) throw new NewUsageError(`${flag} needs a value.`)
+ return next
+ }
+ for (let i = 0; i < argv.length; i++) {
+ const word = argv[i]!
+ if (word === '-h' || word === '--help') throw new NewHelpRequested()
+ if (word === '--') {
+ // The rest is the task, as typed: no quoting to get wrong in a shell.
+ const rest = argv.slice(i + 1).join(' ').trim()
+ if (rest) prompt = rest
+ break
+ }
+ if (word === '--json') json = true
+ else if (word === '--plan') mode = 'plan'
+ else if (word === '--mode') { mode = value(word, i); i++ }
+ else if (word === '--prompt' || word === '--task') { prompt = value(word, i); i++ }
+ else if (word === '--name') { name = value(word, i); i++ }
+ else if (word === '--new') {
+ const next = argv[i + 1]
+ if (next !== undefined && !next.startsWith('-') && !next.startsWith('@') && !looksLikePath(next)) { projectName = next; i++ }
+ else projectName = ''
+ }
+ // Any dash: `-x` read as an agent called "-x" turns a typo into a confusing refusal from the machine.
+ else if (word.startsWith('-')) throw new NewUsageError(`Unknown option ${word}.`)
+ else if (word.startsWith('@')) {
+ if (word.length === 1) throw new NewUsageError('Name a machine after @.')
+ if (machine !== null) throw new NewUsageError('Name one machine.')
+ machine = word.slice(1)
+ }
+ else if (looksLikePath(word)) {
+ if (folder !== null) throw new NewUsageError('Name one folder.')
+ folder = word
+ }
+ else words.push(word)
+ }
+ if (!MODES.has(mode)) throw new NewUsageError(`--mode is one of ${[...MODES].join(', ')}.`)
+ if (words.length > 2) throw new NewUsageError(`Too many words: ${words.slice(2).join(' ')}.`)
+ if (words[1] !== undefined) {
+ if (projectName !== null && projectName !== '') throw new NewUsageError('Name the new project once.')
+ projectName = words[1]
+ }
+ if (folder !== null && projectName !== null) throw new NewUsageError('Name a folder or a new project, not both.')
+ if (projectName !== null && projectName !== '' && projectFolderSlug(projectName) === null) {
+ throw new NewUsageError(`“${projectName}” leaves no usable folder name.`)
+ }
+ let cwd: string | null = null
+ if (folder !== null) {
+ // `~` is this machine's home only when this machine is the target; for another machine it is
+ // resolved there (resolveRemoteHome), so it is kept as typed until then.
+ cwd = folder === '~' || folder.startsWith('~/')
+ ? (machine === null ? join(env.home, folder.slice(2)) : folder)
+ // An unquoted ~/x reaches us as /Users/you/x: the shell expanded it against THIS machine. For
+ // another machine that path means nothing, and what was typed was its home — so give it back.
+ : machine !== null && (folder === env.home || folder.startsWith(`${env.home}/`)) ? `~${folder.slice(env.home.length)}`
+ : isAbsolute(folder) ? folder
+ : machine === null ? resolve(env.cwd, folder)
+ : (() => { throw new NewUsageError('A folder on another machine is an absolute path or starts with ~/.') })()
+ } else if (projectName === null) {
+ // Nothing named: here, on this machine — and a new project on another, where "here" means nothing.
+ if (machine === null) cwd = env.cwd
+ else projectName = ''
+ }
+ return { agent: words[0] ?? 'claude', machine, cwd, projectName, mode, prompt, name, json }
+}
+
+/** The `agent_create` payload for [args]: the same fields the app's box sends. [baseEngine] is the
+ * engine a store harness runs on, read from the machine's catalog; the machine refuses a pair that
+ * disagrees (`INVALID_DSH`). */
+export function newAgentPayload(args: NewArgs, cwd: string | null, baseEngine = 'claude'): Record<string, unknown> {
+ const harness = args.agent.includes('/') ? args.agent : null
+ const terminal = args.agent === 'terminal'
+ return {
+ engine: harness ? baseEngine : args.agent,
+ ...(harness ? { dsh: harness } : {}),
+ ...(cwd !== null ? { cwd } : terminal ? {} : {
+ projectSource: 'new',
+ ...(args.projectName ? { projectName: projectFolderSlug(args.projectName) } : {}),
+ }),
+ bypassPermission: !terminal && (args.mode === 'auto' || args.mode === 'full'),
+ ...(terminal ? {} : { permissionMode: args.mode }),
+ ...(args.prompt ? { prompt: args.prompt } : {}),
+ ...(args.name ? { name: args.name } : {}),
+ creationId: randomUUID(),
+ }
+}
+
+export interface NewMachine { machineId: string; label: string; status: string; current: boolean }
+
+/** The machine `@word` means: an exact id, else a label, case-blind; ambiguity is an error, not a guess. */
+export function resolveNewMachine(word: string, machines: NewMachine[]): NewMachine {
+ const byId = machines.find((machine) => machine.machineId === word)
+ if (byId) return byId
+ const wanted = word.toLowerCase()
+ // The whole name, else its start, else a word in it: `@mini` is "Mac mini" to the person typing.
+ const tiers = [
+ (label: string) => label === wanted,
+ (label: string) => label.startsWith(wanted),
+ (label: string) => label.split(/[\s._-]+/).some((part) => part.startsWith(wanted)),
+ ]
+ let matches: NewMachine[] = []
+ for (const tier of tiers) {
+ matches = machines.filter((machine) => tier(machine.label.toLowerCase()))
+ if (matches.length > 0) break
+ }
+ if (matches.length === 1) return matches[0]!
+ if (matches.length === 0) {
+ throw new NewUsageError(`No machine called “${word}”. Yours: ${machines.map((machine) => machine.label).join(', ') || 'none'}.`)
+ }
+ throw new NewUsageError(`“${word}” could be ${matches.map((machine) => machine.label).join(' or ')}. Type more of the name.`)
+}
+
+/** The least of a WebSocket this needs, so a test can hand in a fake. */
+export interface NewSocket {
+ send(data: string): void
+ close(): void
+ on(event: 'open', listener: () => void): unknown
+ on(event: 'message', listener: (data: { toString(): string }) => void): unknown
+ on(event: 'close', listener: (code: number, reason: { toString(): string }) => void): unknown
+ on(event: 'error', listener: (error: Error) => void): unknown
+}
+
+export interface NewCommandDeps {
+ argv: string[]
+ cwd: string
+ home: string
+ port: number
+ localMachineId: string | null
+ daemonRunning: () => boolean | Promise<boolean>
+ listMachines: () => Promise<NewMachine[]>
+ connect: (url: string) => NewSocket
+ output: (line: string) => void
+ error: (line: string) => void
+ timeoutMs?: number
+}
+
+const ERRORS: Record<string, string> = {
+ INVALID_CWD: 'That folder does not exist on the machine.',
+ INVALID_ENGINE: 'That agent is not one this machine knows.',
+ INVALID_DSH: 'That harness is not in the machine\'s catalog, or does not run on that engine.',
+ PROJECT_EXISTS: 'A project with that name already exists. Name its folder instead.',
+ PROMPT_UNSUPPORTED: 'That agent cannot be started with a first message.',
+ SPAWN_FAILED: 'The agent could not be started.',
+}
+
+/** One loopback session with the daemon: select the machine, then ask, one request at a time. */
+function daemonSession(deps: NewCommandDeps, machineId: string): Promise<{
+ request: (type: string, payload: Record<string, unknown>) => Promise<Record<string, unknown>>
+ close: () => void
+}> {
+ return new Promise((resolveSession, rejectSession) => {
+ const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`)
+ const waiting = new Map<string, { done: (payload: Record<string, unknown>) => void; fail: (error: Error) => void; timer: NodeJS.Timeout }>()
+ let ready = false
+ const failAll = (error: Error): void => {
+ for (const entry of waiting.values()) { clearTimeout(entry.timer); entry.fail(error) }
+ waiting.clear()
+ if (!ready) rejectSession(error)
+ }
+ socket.on('open', () => socket.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } })))
+ socket.on('error', (error) => failAll(error))
+ socket.on('close', (code, reason) => failAll(new Error(
+ code === 4404 ? 'That machine is not linked to this one yet. Run `harness link` first.'
+ : `The connection to Harness closed (${code}${reason.toString() ? `: ${reason.toString()}` : ''}).`)))
+ socket.on('message', (data) => {
+ let frame: { type?: string; payload?: Record<string, unknown> }
+ try { frame = JSON.parse(data.toString()) } catch { return }
+ if (!ready && frame.type === 'connected') {
+ ready = true
+ resolveSession({
+ close: () => socket.close(),
+ request: (type, payload) => new Promise((done, fail) => {
+ const requestId = randomUUID()
+ const timer = setTimeout(() => { waiting.delete(requestId); fail(new Error(`Harness did not answer ${type} in time.`)) }, deps.timeoutMs ?? 90_000)
+ waiting.set(requestId, { done, fail, timer })
+ socket.send(JSON.stringify({ type, payload: { ...payload, requestId } }))
+ }),
+ })
+ return
+ }
+ const requestId = frame.payload?.requestId
+ const entry = typeof requestId === 'string' ? waiting.get(requestId) : undefined
+ if (!entry || !frame.payload) return
+ waiting.delete(requestId as string)
+ clearTimeout(entry.timer)
+ if (frame.payload.error != null) {
+ const code = String(frame.payload.error)
+ const detail = typeof frame.payload.detail === 'string' && frame.payload.detail ? ` (${frame.payload.detail})` : ''
+ entry.fail(new Error(`${ERRORS[code] ?? code}${detail}`))
+ } else entry.done(frame.payload)
+ })
+ })
+}
+
+export async function newCommand(deps: NewCommandDeps): Promise<number> {
+ let args: NewArgs
+ try { args = parseNewArgs(deps.argv, { cwd: deps.cwd, home: deps.home }) }
+ catch (error) {
+ if (error instanceof NewHelpRequested) { deps.output(NEW_USAGE); return 0 }
+ if (!(error instanceof NewUsageError)) throw error
+ deps.error(error.message)
+ deps.error('')
+ deps.error(NEW_USAGE)
+ return 2
+ }
+ if (!(await deps.daemonRunning())) {
+ deps.error('Harness is not running on this computer. Start it with `harness start`.')
+ return 1
+ }
+ try {
+ let machineId = deps.localMachineId
+ let machineLabel = 'this computer'
+ if (args.machine !== null) {
+ const machine = resolveNewMachine(args.machine, await deps.listMachines())
+ machineId = machine.machineId
+ machineLabel = machine.current ? 'this computer' : machine.label
+ }
+ if (!machineId) {
+ deps.error('This computer is not signed in to Harness. Run `harness login`.')
+ return 1
+ }
+ const session = await daemonSession(deps, machineId)
+ try {
+ let cwd = args.cwd
+ if (cwd !== null && (cwd === '~' || cwd.startsWith('~/'))) {
+ // Another machine's home: ask it. `fs_list_dir` with no path answers with the home it listed.
+ const home = (await session.request('fs_list_dir', {})).path
+ if (typeof home !== 'string' || !isAbsolute(home)) throw new Error('That machine did not say where its home folder is.')
+ cwd = join(home, cwd.slice(2))
+ }
+ let baseEngine = 'claude'
+ if (args.agent.includes('/')) {
+ // A store harness: the machine's catalog says what it runs on and whether it is there yet.
+ const catalog = (await session.request('dsh_list', {})).dsh
+ const entry = Array.isArray(catalog)
+ ? catalog.find((row): row is Record<string, unknown> => typeof row === 'object' && row !== null && (row as Record<string, unknown>).id === args.agent)
+ : undefined
+ if (!entry) throw new Error(`No harness called “${args.agent}” in that machine's catalog. See \`harness dsh list\`.`)
+ if (entry.installed === false) throw new Error(`Install it first: harness dsh install ${args.agent}`)
+ if (typeof entry.engine === 'string' && entry.engine) baseEngine = entry.engine
+ }
+ const result = await session.request('agent_create', newAgentPayload(args, cwd, baseEngine))
+ const agent = (result.agent ?? {}) as Record<string, unknown>
+ if (args.json) deps.output(JSON.stringify({ ok: true, machineId, agent }))
+ else {
+ const where = typeof agent.cwd === 'string' ? ` in ${agent.cwd}` : cwd ? ` in ${cwd}` : ''
+ deps.output(`Created ${String(agent.name ?? agent.id ?? 'a harness')} on ${machineLabel}${where}.`)
+ deps.output('Open it in Harness with ⌘O.')
+ }
+ return 0
+ } finally { session.close() }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (args.json) deps.output(JSON.stringify({ ok: false, error: message }))
+ else deps.error(message)
+ return error instanceof NewUsageError ? 2 : 1
+ }
+}
diff --git a/cli/src/lib/projectFolder.spec.ts b/cli/src/lib/projectFolder.spec.ts
index 756f1cf5c..63759809d 100644
--- a/cli/src/lib/projectFolder.spec.ts
+++ b/cli/src/lib/projectFolder.spec.ts
@@ -30,6 +30,19 @@ describe('project folder preparation', () => {
expect(await prepareProjectFolder({ source: 'new' }, { root, label: '!!', now })).toBe(join(root, 'harness-2026-09-03-09-05-07'))
})
+ it('gives a named new project that folder, slugged again here, and never a changed name', async () => {
+ expect(parseProjectFolder({ projectSource: 'new', projectName: 'My Game! v2' })).toEqual({ source: 'new', name: 'My-Game-v2' })
+ // A name is a path segment: nothing that climbs or hides survives, and nothing usable is no name.
+ expect(parseProjectFolder({ projectSource: 'new', projectName: '../../etc' })).toEqual({ source: 'new', name: 'etc' })
+ expect(parseProjectFolder({ projectSource: 'new', projectName: ' .. ' })).toEqual({ source: 'new' })
+ expect(parseProjectFolder({ projectSource: 'new', projectName: 7 })).toEqual({ source: 'new' })
+ expect(await prepareProjectFolder({ source: 'new', name: 'My-Game-v2' }, { root, label: 'Codex', now })).toBe(join(root, 'My-Game-v2'))
+ // Asking again is refused rather than answered with "My-Game-v2-2": the folder is theirs to pick.
+ await expect(prepareProjectFolder({ source: 'new', name: 'My-Game-v2' }, { root, label: 'Codex', now }))
+ .rejects.toMatchObject({ code: 'PROJECT_EXISTS' })
+ expect(await readdir(root)).toEqual(['My-Game-v2'])
+ })
+
it('gives two projects in the same minute the seconds, then a suffix, and never takes a file’s name', async () => {
await writeFile(join(root, 'codex-2026-09-03-09-05'), 'keep')
const folders = await Promise.all([1, 2, 3].map(() => prepareProjectFolder({ source: 'new' }, { root, label: 'Codex', now })))
diff --git a/cli/src/lib/projectFolder.ts b/cli/src/lib/projectFolder.ts
index 765c0d430..f10b2600d 100644
--- a/cli/src/lib/projectFolder.ts
+++ b/cli/src/lib/projectFolder.ts
@@ -2,9 +2,11 @@ import { spawn } from 'node:child_process'
import { lstat, mkdir, mkdtemp, rename, rm } from 'node:fs/promises'
import { homedir } from 'node:os'
import { join } from 'node:path'
-import { projectFolderName } from './agentNames.js'
+import { projectFolderName, projectFolderSlug } from './agentNames.js'
-export type ProjectFolder = { source: 'new' } | { source: 'remote'; repositoryUrl: string; name: string }
+/** `name` on a new project is what the person called it; without one the folder is named after the
+ * harness and the time. */
+export type ProjectFolder = { source: 'new'; name?: string } | { source: 'remote'; repositoryUrl: string; name: string }
export class ProjectFolderError extends Error {
constructor(readonly code: string, message: string) { super(message) }
@@ -14,7 +16,11 @@ export class ProjectFolderError extends Error {
// credentials nor arbitrary local paths/remote helpers are repository URLs.
export function parseProjectFolder(payload: Record<string, unknown>): ProjectFolder | null {
if (payload.projectSource === undefined) return null
- if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) return { source: 'new' }
+ if (payload.projectSource === 'new' && payload.repositoryUrl === undefined) {
+ // Slugged again here: the name becomes a path segment, so it is never taken on trust.
+ const name = typeof payload.projectName === 'string' ? projectFolderSlug(payload.projectName) : null
+ return name ? { source: 'new', name } : { source: 'new' }
+ }
if (payload.projectSource !== 'remote' || typeof payload.repositoryUrl !== 'string') {
throw new ProjectFolderError('INVALID_PROJECT_SOURCE', 'Choose a project.')
}
@@ -59,6 +65,16 @@ export async function prepareProjectFolder(
let staging: string | undefined
try {
await mkdir(root, { recursive: true })
+ if (project.source === 'new' && project.name) {
+ // A name somebody chose is never quietly changed: an existing folder is theirs to pick as an
+ // existing project, as a clone's is.
+ const folder = join(root, project.name)
+ try { await mkdir(folder); return folder }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
+ throw new ProjectFolderError('PROJECT_EXISTS', `“${project.name}” already exists. Select that folder from your projects.`)
+ }
+ }
if (project.source === 'new') {
// `codex-2026-09-17-15-26` (agentNames.ts): nothing to count. Two in the same minute take the
// seconds; the same second, a suffix. mkdir reserves the name atomically, so simultaneous
diff --git a/cli/src/lib/restartAgent.spec.ts b/cli/src/lib/restartAgent.spec.ts
index ef96f9f35..fc3246ea2 100644
--- a/cli/src/lib/restartAgent.spec.ts
+++ b/cli/src/lib/restartAgent.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { restartAgent, type RestartAgentDeps } from './restartAgent.js'
+import { AgentRestartCoordinator, restartAgent, type RestartAgentDeps } from './restartAgent.js'
import type { ProcessIdentity } from './registry.js'
const IDENTITY: ProcessIdentity = { pid: 555, executable: 'claude', startMarker: 'Mon Aug 3 09:05:00 2026' }
@@ -155,3 +155,67 @@ describe('restartAgent', () => {
expect(d.calls).not.toContain('waitForProcess')
})
})
+
+
+describe('restart cancellation', () => {
+ for (const phase of ['before', 'hold', 'terminate', 'prepare', 'respawn', 'wait'] as const) {
+ it(`does not continue process replacement after cancellation at ${phase}`, async () => {
+ let current = phase !== 'before'
+ const stopAt = (at: string) => { if (phase === at) current = false }
+ const d = deps({
+ holdOpen: async () => { stopAt('hold'); return { ok: true } },
+ terminate: async () => { stopAt('terminate'); return 'terminated' },
+ prepareResume: async () => { stopAt('prepare') },
+ respawn: async () => { stopAt('respawn'); return { ok: true } },
+ waitForProcess: async () => { stopAt('wait'); return null },
+ })
+ const result = await restartAgent({ engine: 'codex', sessionId: 's1' }, false, { ...d, isCurrent: () => current })
+ expect(result).toEqual({ ok: false, detail: 'the agent changed or stopped during restart' })
+ expect(d.calls.filter((call) => call === 'respawn')).toHaveLength(['respawn', 'wait'].includes(phase) ? 1 : 0)
+ if (phase === 'before') expect(d.calls).toEqual([])
+ if (phase === 'hold') expect(d.calls).toEqual(['holdOpen'])
+ })
+ }
+
+ it('joins overlapping restarts but leaves other agents independent', async () => {
+ const coordinator = new AgentRestartCoordinator()
+ let finish!: () => void
+ const handler = vi.fn(async () => { await new Promise<void>((resolve) => { finish = resolve }); return { ok: false, error: 'fixture' } as const })
+ const first = coordinator.run('a', handler)
+ expect(coordinator.run('a', handler)).toBe(first)
+ expect(await coordinator.run('b', async () => ({ ok: false, error: 'other' }))).toEqual({ ok: false, error: 'other' })
+ finish()
+ await first
+ expect(handler).toHaveBeenCalledTimes(1)
+ expect(await coordinator.run('a', async () => ({ ok: false, error: 'fresh' }))).toEqual({ ok: false, error: 'fresh' })
+ })
+
+ it('Stop cancels before dispatch and during an outstanding step', async () => {
+ const coordinator = new AgentRestartCoordinator()
+ const untouched = vi.fn(async () => ({ ok: false, error: 'unexpected' } as const))
+ const first = coordinator.run('a', untouched)
+ coordinator.cancel('a')
+ expect(await first).toEqual({ ok: false, error: 'AGENT_CHANGED' })
+ expect(untouched).not.toHaveBeenCalled()
+ let finish!: () => void
+ let isCurrent!: () => boolean
+ const second = coordinator.run('a', async (current) => {
+ isCurrent = current
+ await new Promise<void>((resolve) => { finish = resolve })
+ return { ok: false, error: 'old receipt' }
+ })
+ await Promise.resolve()
+ coordinator.cancel('a')
+ expect(isCurrent()).toBe(false)
+ expect(coordinator.run('a', untouched)).toBe(second)
+ finish()
+ expect(await second).toEqual({ ok: false, error: 'AGENT_CHANGED' })
+ expect(untouched).not.toHaveBeenCalled()
+ })
+
+ it('a thrown restart releases the coordinator for a new explicit attempt', async () => {
+ const coordinator = new AgentRestartCoordinator()
+ await expect(coordinator.run('a', async () => { throw new Error('lost') })).rejects.toThrow('lost')
+ expect(await coordinator.run('a', async () => ({ ok: false, error: 'fresh' }))).toEqual({ ok: false, error: 'fresh' })
+ })
+})
diff --git a/cli/src/lib/restartAgent.ts b/cli/src/lib/restartAgent.ts
index 0404a93fe..9e288d3c0 100644
--- a/cli/src/lib/restartAgent.ts
+++ b/cli/src/lib/restartAgent.ts
@@ -10,14 +10,47 @@
*/
import type { AgentEngine } from '../engines/types.js'
-import type { ProcessIdentity } from './registry.js'
+import type { RegisteredSession, ProcessIdentity } from './registry.js'
import type { TerminateOutcome } from './deleteAgentFallback.js'
export type RestartOutcome =
| { ok: true; processIdentity: ProcessIdentity; resumed: boolean }
| { ok: false; detail: string }
+export type RestartAgentReply =
+ | { ok: true; session: RegisteredSession; resumed: boolean }
+ | { ok: false; error: string; detail?: string }
+
+/** One process replacement per agent, even across clients and different receipt
+ * IDs. Stop cancels the work before its next process-changing step. */
+export class AgentRestartCoordinator {
+ private readonly jobs = new Map<string, { cancelled: boolean; result: Promise<RestartAgentReply> }>()
+
+ run(agentId: string, restart: (current: () => boolean) => Promise<RestartAgentReply>): Promise<RestartAgentReply> {
+ const existing = this.jobs.get(agentId)
+ if (existing) return existing.result
+ const job = { cancelled: false, result: null! as Promise<RestartAgentReply> }
+ const current = () => !job.cancelled && this.jobs.get(agentId) === job
+ job.result = Promise.resolve().then(async () => {
+ if (!current()) return { ok: false, error: 'AGENT_CHANGED' } as const
+ const result = await restart(current)
+ return current() ? result : { ok: false, error: 'AGENT_CHANGED' } as const
+ }).finally(() => {
+ if (this.jobs.get(agentId) === job) this.jobs.delete(agentId)
+ })
+ this.jobs.set(agentId, job)
+ return job.result
+ }
+
+ cancel(agentId: string): void {
+ const job = this.jobs.get(agentId)
+ if (job) job.cancelled = true
+ }
+}
+
export interface RestartAgentDeps {
+ /** False after Stop, replacement, or removal. Checked across every await. */
+ isCurrent?: () => boolean
/** Re-arm `remain-on-exit` before anything is killed — see `tmuxBackend.ts`'s `holdOpen`. Without
* this, tmux tears the pane (and, being its only pane, the whole session) down the instant the old
* process exits. */
@@ -44,12 +77,17 @@ export async function restartAgent(
bypassPermission: boolean,
deps: RestartAgentDeps,
): Promise<RestartOutcome> {
+ const changed = { ok: false, detail: 'the agent changed or stopped during restart' } as const
+ const current = () => deps.isCurrent?.() !== false
+ if (!current()) return changed
const armed = await deps.holdOpen()
+ if (!current()) return changed
if (!armed.ok) {
return { ok: false, detail: armed.reason ?? 'could not re-arm the pane before restart' }
}
const outcome = await deps.terminate()
+ if (!current()) return changed
if (!KILL_CONFIRMED.has(outcome)) {
return { ok: false, detail: `could not confirm the running ${session.engine} process was stopped (${outcome})` }
}
@@ -60,12 +98,15 @@ export async function restartAgent(
return { ok: false, detail: `could not prepare ${session.engine} session for resume: ${error instanceof Error ? error.message : error}` }
}
}
+ if (!current()) return changed
const spawnAndWait = async (withResume: boolean): Promise<ProcessIdentity | null> => {
+ if (!current()) return null
const argv = deps.buildArgv({
bypassPermission,
...(withResume && resumeSessionId ? { resumeSessionId } : {}),
})
const spawned = await deps.respawn(argv)
+ if (!current()) return null
if (!spawned.ok) {
deps.log(`[restart] ${session.engine} respawn-pane failed: ${spawned.reason ?? 'unknown reason'}`)
return null
@@ -79,6 +120,7 @@ export async function restartAgent(
// when LAUNCH_RESUME_FLAG has no entry for the engine), so `resumed` still degrades correctly.
let resumed = !!resumeSessionId
let identity = await spawnAndWait(resumed)
+ if (!current()) return changed
if (!identity && resumed) {
// Safe degradation: a working agent with a FRESH session under the same agentId/pane beats a dead
// pane. Retry once with no resume attempt before giving up entirely.
@@ -86,6 +128,7 @@ export async function restartAgent(
resumed = false
identity = await spawnAndWait(false)
}
+ if (!current()) return changed
if (!identity) {
return { ok: false, detail: `${session.engine} did not come back up after restart` }
}
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 814212625..69f71a0cc 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -46,13 +46,19 @@ flutter build macos --release
flutter build linux --release # Ubuntu build host only — no cross-compiling
```
-Integration tests (`integration_test/`) need a device: `flutter test integration_test/native_terminal_e2e_test.dart -d macos`
-(swap `-d linux` on an Ubuntu host).
-`local_terminal_e2e_test.dart` and `prod_terminal_e2e_test.dart` still import `package:harness/e2ee/*`
-and `widgets/remote_setup_screen.dart`, which no longer exist, and `native_terminal_e2e_test.dart`
-builds `TerminalPanel` without its required `focused` argument — all three fail `flutter analyze` and
-are the only analyzer errors in the repo (everything else is `info` inside `third_party/xterm`). Fix or
-delete them before relying on them.
+Native integration fixtures need a device and the test-mode environment:
+
+```bash
+FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_terminal_e2e_test.dart
+FLUTTER_TEST=1 flutter test -d macos --no-pub integration_test/native_workspace_e2e_test.dart
+```
+
+Both use in-memory state and fake terminal traffic; the workspace fixture also simulates agent
+creation and machine-link responses. They refuse to run without `FLUTTER_TEST=1`, which disables
+production-only pollers and persistence. The workspace fixture exercises the native macOS titlebar; its injected
+Flutter keys do not establish physical AppKit keyboard/IME behavior. A fixture build replaces
+`Harness.app`, so rebuild the normal review artifact afterward with
+`flutter build macos --debug --no-pub --target lib/main.dart`.
Local stack / E2E scripts (the CLI comes from this repo's `../cli`; the backend from a sibling
`autonomous-code` checkout next to `autonomous-harness` — override with `AUTONOMOUS_CODE_ROOT` /
@@ -94,9 +100,28 @@ holds an SSO token:
- **Auth** lives in the CLI. `lib/auth/cli_login.dart` shells out to `harness auth status --json` and
drives `harness login --json` (NDJSON event stream); `cli_link.dart` wraps `harness link create/import/list`.
+ Sign-out owns its CLI process, checks its exit, and terminates it on timeout. `AppNotifier` joins
+ repeated sign-out requests and blocks another sign-in until credential and connection cleanup
+ finish; failure offers keyboard-focused Retry sign out. Development fixture disconnects never
+ sign out the real CLI. Viewer builds use `viewer/direct_login.dart` and `viewer/direct_auth.dart`
+ instead: login attempts and token refreshes have session revisions, credential writes are
+ serialized, and cancelled or superseded responses cannot restore or clear another account.
+ Sign-out and runtime expiry clear live panes, inventory, and history without saving an empty
+ layout over the user's desk. Sign-in waits for old transports to close, then restores the saved
+ tabs, focus, pins, zoom, and layouts. Every layout read checks both account and layout revisions.
- **REST** (`lib/api/api_client.dart`, Dio) goes to `AppConfig.localCliBaseUrl` (`http://127.0.0.1:18473`),
and the CLI proxies to the backend with its own session. Responses are `{success, data|error}` and
unwrapped into `ApiException`.
+ Machine responses carry their own cache freshness (`MachineInventory`). Sharing fallback is
+ cleared on account changes; only the latest request can publish inventory or clear its error.
+ `refreshMachines()` returns whether its result was applied, and retry uses that public path.
+ `machineInventoryLoaded` distinguishes an initial wait from a completed inventory with no row
+ for a restored pane. Missing, cached, and failed inventories give distinct recovery guidance;
+ Retry stays mounted and joins any pending retry, preserving its keyboard focus and position.
+ Agent discovery and terminal capabilities also belong to a machine's current connection
+ revision. Disconnect/reconnect releases obsolete discovery and recovery futures immediately;
+ late replies and timeouts cannot overwrite the replacement connection. Reconnect releases old
+ terminal stream IDs while retaining their renderer and output until the new keyframe arrives.
- **WebSocket** (`lib/ws/`) — `WsPool` owns one `WsConn` per machine. Every real connection uses
`WsTransportKind.localPlaintext` against the CLI daemon's loopback WS (discovered/started by
`LocalCliDiscovery`, which runs `harness start` when needed). The CLI terminates E2EE for relayed
@@ -134,6 +159,21 @@ transaction (its clock-skew repair) and the one Terminal handoff. Gating readine
was what sent a computer whose tmux ran fine into Terminal to reinstall developer tools after a macOS
upgrade — the screen renders `plan`, it does not infer one.
+Installer-log polling reads only the last 64 KiB and keeps at most 200 lines, tolerating partial
+UTF-8 output. Truncated diagnostics include the full log path; the original file remains intact.
+A missing, unreadable, or partial Terminal result stays pending until a complete exit code or
+successful live probes establish the outcome. Copy failures in setup remain visible beside Retry,
+and only the latest clipboard attempt can update its feedback. The setup render fixture checks
+both themes and enlarged text at the minimum window size without running an installer.
+
+Read-only dependency probes own their subprocesses and have a ten-second deadline covering startup,
+exit, and output-pipe closure. A timeout reports a failed check, not a missing tool; Retry after the
+initial check stays read-only. Only an explicit install action permits automatic installation to
+continue after a Terminal handoff, and a failed recheck stops that continuation. Readiness requires
+the final ready phase and every required step, so old successful step values cannot flash a ready
+screen during a new verification. The preflight status is a live region and uses a static waiting
+icon when Reduce Motion is enabled.
+
### Boot and state
`lib/main.dart`: `CrashLog.install()` → `loadPersistedSettings()` (theme mode + terminal font, awaited
@@ -150,6 +190,18 @@ the daemon, `api.me()`, `refreshMachines()`).
Per-machine runtime state is `MachineState` (connection status, transport mode, agents, `nodeOnline`
from `node_status` pushes — distinct from our own socket status, pending offline agent, turn activity).
+### Command dock
+
+`SwarmSearchController` owns search and selection; `SwarmSearchResults` keeps a bounded cache of
+visible/recent row controls. Query-dependent match text listens separately, so typing does not
+rebuild unchanged `ListTile` controls and arrows rebuild only changed highlights. The cache still
+invalidates for row metadata, availability, action, geometry, theme, and font changes. Keep focus,
+semantics, and traversal on the row; do not replace them with paint-only search results.
+Creation and draft precedence are documented in `design/new-harness-entry-rules.md` and exercised
+by its listed tests. Cmd-T/Cmd-P retarget the same draft/search; Store requests own their explicit
+product and machine. `test/benchmarks/swarm_benchmark.dart` measures large synthetic inventories;
+its headless debug timings do not establish native display or network latency.
+
### Terminals
- `TerminalPane` (`lib/state/terminal_pane.dart`) separates **intent** (machine + agent id, stable
@@ -299,10 +351,20 @@ from `node_status` pushes — distinct from our own socket status, pending offli
**Off is the resting state**, per provider, persisted through `LocalKeyValueStore`: these transcripts
hold every prompt, path and branch a session touched and this feature wants only the counts, so
nothing is read until somebody switches it on — and switching one off deletes its snapshot from disk
- as well as from memory. Scans are incremental against a `{path, mtime, size}` fingerprint cached in
- `~/.harness/desktop-app/usage-ledger-<provider>.json`, and `kLedgerStaleAfter` (5 min) keeps opening
+ as well as from memory. JSONL scans are incremental against a `{path, mtime, size}` fingerprint cached in
+ `~/.harness/desktop-app/usage-ledger-<provider>.json`. OpenCode instead queries a committed SQLite
+ snapshot on each scan: the main database's metadata can stay unchanged while its WAL changes.
+ SQLite reads run in a worker isolate. `kLedgerStaleAfter` (5 min) keeps opening
the pane from re-walking the disk; a cold Claude scan is ~3s over 71 transcripts, which is why
neither of those is optional. Nothing polls — a ledger only moves when an agent writes here.
+ An unreadable OpenCode source is failed, not missing. If other databases are readable, the result
+ is partial and the UI marks its figures incomplete. Partial results are kept in memory, but never
+ restored as a fresh complete snapshot; reopening or Retry rescans them.
+ Claude/Codex share the same failure rules in `jsonl_ledger_scan.dart`: a failed read is never cached
+ as an empty successful source. Snapshot format 3 discards old snapshots that could contain that
+ mistake. Reads stop at the captured file size and tolerate an unfinished UTF-8 suffix while an
+ agent appends, preserving earlier complete records; completed corrupt text remains an error.
+ Model-name normalization has a small bounded cache, while per-turn token/tier pricing stays dynamic.
⚠️ **Local only, by decision.** Agents launched onto remote machines write their transcripts there and
nothing here reaches them; the pane's subtitle says so, because a total that silently excluded most of
a team's work would be worse than no total. `UsageSource` in `usage/usage_source.dart` is where a
diff --git a/desktop/assets/store/README.md b/desktop/assets/store/README.md
index 488c18ef1..7a981dda8 100644
--- a/desktop/assets/store/README.md
+++ b/desktop/assets/store/README.md
@@ -21,8 +21,10 @@ To regenerate the renders:
--pcb-glb <copper>/examples/terminal-keyboard/boards/main_fab/board.glb
```
-Store tabs use `desktop/assets/app_icon.png`, the same icon as the app.
-
+`polymath.png` is the original Harness Store mark: six colorful branches meeting
+at one center. The Store button, tabs, and History use the same asset. Its vector
+source is `desktop/tool/render_store_mark.swift`; regenerate from `desktop/` with
+`swift tool/render_store_mark.swift`.
## Exploration previews
`projects/` contains unaltered copies of the repository's showcase outputs.
diff --git a/desktop/assets/store/polymath.png b/desktop/assets/store/polymath.png
new file mode 100644
index 000000000..91e05fba2
Binary files /dev/null and b/desktop/assets/store/polymath.png differ
diff --git a/desktop/design/command-box-progress.md b/desktop/design/command-box-progress.md
new file mode 100644
index 000000000..e41a5c1cf
--- /dev/null
+++ b/desktop/design/command-box-progress.md
@@ -0,0 +1,3164 @@
+# Command box continuation — 2026-09-20
+
+Branch: `worktree-command-box`. The desktop overhaul is committed as `f2ff876b`;
+integration now includes `main` through `60764ba9` (PR #164). The earlier sections
+below are a historical record; the current PR checkpoint is at the end.
+
+## Direction carried forward
+
+The terminals are the product; Harness is the frame, one keystroke away.
+Keep the bottom-docked search/new-agent prompt, fast launch with inherited
+agent/machine/project, remappable keys, and clickable alternatives. Keep the
+noun **Tab**. Do not add a status bar or permanent status segments.
+
+The original operational brief is the session memory named
+`command-box-handoff.md`; its design history is
+`superterminal-design-direction.md`. This file records the subsequent work
+inside the worktree so it is discoverable without searching session memory.
+
+## Settings follow the highlighted agent — current continuation
+
+The user could not reach a Codex profile while another engine was saved:
+settings were based on the saved agent, not the highlighted result. They also
+requested removing the repeated Agent/Machine/Project rows from both Agent
+and Machine selection.
+
+- Agent settings now follow typing and arrow selection. Permissions/Profile
+ appear indented directly below the highlighted engine, so Down enters its
+ settings without crossing another engine and changing the target.
+- Browsing remains a preview. Escape preserves the saved agent and profile.
+ Choosing a permission/profile commits the highlighted engine with that
+ setting; Enter on an engine keeps the existing choose-and-return fast path.
+ Returning from settings restores the filter and the selected settings row.
+- Agent and Machine pickers now show a left-aligned title, choices, input,
+ and hints. Their repeated summary rows are removed. The launch screen keeps
+ the full summary. Scroll sizing retains room for six engine results plus
+ inline settings, subject to window height and text size.
+- Profile/mode pickers retain their agent target when opening and returning
+ from Machine. The saved profile is untouched by merely browsing other
+ engines. Filtering to no matching agent cannot launch or select a setting.
+
+Verification: **65 focused checks pass**, including the Claude → highlighted
+Codex → Profile flow, cancellation, committed-profile preservation, and hidden
+summary rows in Agent/Machine (`/private/tmp/agent-highlight-tests.log`).
+Inspected normal and enlarged-text previews in `agent-highlight-renders`.
+Analysis, formatting, and `git diff --check` pass.
+
+The native fake-agent creation test passed twice with packet diagnostics
+enabled (`agent-highlight-native.log`, `agent-highlight-native-repeat.log`).
+Its first run observed two unexpected terminal-input packets; this did not
+reproduce in either repeat, and the source was not established. Keep the
+diagnostics rather than weakening the empty-input assertion. These are
+injected Flutter keys, not physical AppKit/IME validation.
+
+Rebuilt normal `lib/main.dart` with the existing JEV endpoint
+`http://127.0.0.1:18478` (`/private/tmp/agent-highlight-build.log`), verified the
+bundle's deep/strict signature, and opened review PID **33363**. Previous review
+PID 66703 remains open. No real agents were created by the fixtures; nothing
+committed or pushed. Backups are in `/private/tmp/agent-highlight-before`.
+
+## Agent settings without a main Options row — previous continuation
+
+The user found Options too prominent and approved moving the settings into
+Agent. The launch menu now contains Agent, Machine, Project, Task, and
+Start/Create. Create remains selected initially; Up reaches Task directly.
+
+- Removed the standalone Options row. Nondefault permissions and any explicit
+ profile are summarized beside the Agent value; defaults stay quiet.
+- Agent keeps its fast choose-and-return behavior. Permissions and Codex
+ profile are explicit settings below its results, using the same typing,
+ arrows, Enter, and Escape interaction. Choosing a setting returns to Agent
+ with its search and settings-row selection restored.
+- Added a profile picker scoped to the selected machine, with Default,
+ discovered profiles, Refresh, and Link profile folder. Discovery never picks
+ an account. Changing engine or machine clears the profile; stale discovery
+ replies are ignored. Older CLIs explain missing support without issuing an
+ unsupported request. Linking blocks editing, dismissal, and creation until
+ the response arrives.
+- An unmatched Agent query leaves no implicit selection; Enter/Cmd-Enter
+ explains the empty result rather than using another agent or a settings row.
+- Cmd-period retains the full form for compatibility and install guidance.
+ Updated keyboard-practice copy, review notes, fixtures, and the native
+ creation flow to use Agent → Permissions.
+
+Verification: **75 focused checks pass** in
+`/private/tmp/agent-settings-tests.log`; all four profile-flow checks also pass
+after the final pending-link dismissal guard (`agent-settings-fix.log`).
+Touched-file analysis and `git diff --check` pass. Inspected normal and
+enlarged-text root, Agent, permissions, and profile layouts in
+`/private/tmp/agent-settings-renders`.
+
+The native fake-agent creation flow also passes in
+`/private/tmp/agent-settings-native.log` (injected Flutter keys, not physical
+AppKit/IME input). Rebuilt normal `lib/main.dart` afterward, preserving JEV at
+`http://127.0.0.1:18478`; log `/private/tmp/agent-settings-build.log`.
+Deep/strict signature verification passes. Opened the review app and confirmed
+PID **66703**. No real agents were created by these fixtures; nothing committed
+or pushed.
+
+## Launch menu without letter shortcuts — previous continuation
+
+The user observed that the launch menu was the remaining creation screen with
+letter shortcuts and requested the same Up/Down/Enter interaction throughout.
+
+- Removed the `a/m/p/t` labels and default bindings and the footer's `o` option.
+ Rows and input context now share the same left alignment without a shortcut
+ column. Explicit custom bindings still work through the stable command IDs.
+- Options is always a selectable row above Create, including with default
+ settings. Nondefault permissions/profile remain summarized beside Options.
+ Up from Create opens the route to Options; Enter opens the full form.
+- Create remains selected on entry and on return from an editor. Arrows move
+ through Agent, Machine, Project, Task, Options, and Create. Enter edits or
+ launches the selected row. Cmd-Enter and Cmd-period remain available.
+- Updated keyboard-practice examples, design/review notes, existing test flows,
+ and the native creation fixture to navigate the launch rows with arrows.
+ Plain-letter tests confirm there are no default jumps or side effects.
+
+Verification: **94 focused checks pass**, including Options via Up/Enter and
+return to Create, plus the native fake-agent creation flow. Logs:
+`/private/tmp/launch-arrows-tests.log`, `/private/tmp/launch-arrows-native.log`.
+The native fixture uses injected Flutter keys, not physical AppKit/IME input.
+Touched-file analysis, formatting, and `git diff --check` pass. Inspected
+normal and enlarged-text layouts in `/private/tmp/launch-arrows-renders`.
+The native-keymap helper's launch assertions were updated; its unrelated
+legacy workspace assertions were not rerun.
+
+Rebuilt normal `lib/main.dart` after the fixture, preserving JEV at
+`http://127.0.0.1:18478`; log `/private/tmp/launch-arrows-build.log`. Deep/strict
+signature verification passes. Opened the review app and confirmed new PID
+**47771** (previous review PID 66905 remains open). No real agent was created;
+nothing committed or pushed.
+
+## Project search without action shortcuts — previous continuation
+
+The user requested typing to filter Project just like Agent and Machine,
+with recent projects above fixed New/Open/Clone actions and the input below
+them. They then simplified the request: remove `1–9` and `n/o/g`; use typing,
+Up/Down, Enter, and Escape throughout Project.
+
+- Project now focuses a search input and filters names/paths, including case
+ and common word-separator variations. Results stay on the selected machine.
+ The best matching recent is highlighted, or Open folder when none match.
+- New project, Open folder, and Clone GitHub repository stay visible above
+ the input in that visual order. The recent list remains scrollable, with
+ room for up to nine visible rows and older projects reachable by arrows.
+ Search changes re-reveal the best result even if its cursor index is unchanged.
+- Removed action letters and numbered row labels/default shortcuts in Project.
+ Ordinary letters/digits remain search text, including `m`; the header's
+ clickable Change machine action remains, and launch `m` still edits Machine.
+ Existing command IDs remain unbound for explicit custom remaps. Navigation
+ continues to inherit picker remaps. Root launch `a/m/p/t/o` is unchanged.
+- Escape from New/Open/Clone restores the Project filter; reopening from
+ launch resets it. Changing machines clears a filter belonging to the previous
+ machine. The folder child still has no duplicate recent list.
+- Updated keyboard practice, render/native fixtures, interaction tests, and
+ the current design and manual-review notes.
+
+Verification: **94 focused controller/widget/keymap/practice/render checks
+pass**, plus the native creation flow with fake agents. Logs:
+`/private/tmp/project-filter-tests.log`, `/private/tmp/project-filter-native.log`.
+The native fixture uses injected Flutter keys, not physical AppKit/IME input.
+Touched-file analysis has no issues; formatting and `git diff --check` pass.
+Inspected the long-history, filtered, no-match, and enlarged-text renders in
+`/private/tmp/project-filter-renders`. The older native keymap helper's Project
+assertion now reflects unbound action keys; its unrelated legacy workspace
+assertions were not rerun in this continuation.
+
+Rebuilt normal `lib/main.dart` after the native fixture, preserving JEV at
+`http://127.0.0.1:18478`; log `/private/tmp/project-filter-build.log`. Deep/strict
+signature verification passes. Opened the review app and confirmed new PID
+**66905** (previous review PID 81012 remains open). No real agent was created;
+nothing committed or pushed.
+
+## Arrow-selectable launch menu and plain prompts — previous continuation
+
+The user requested clearer GitHub cloning copy, no extra `>` markers, and
+Up/Down selection for the launch arguments as well as the child pickers.
+
+- GitHub now says "Paste a GitHub repository URL" and "Clone to
+ machine:~/harnesses/<repository>". Short names such as `openai/codex`, HTTPS,
+ and SSH URLs still parse as before. Selection prepares the repository;
+ launching performs the clone. Invalid-input guidance uses a concrete example
+ instead of the unexplained word "owner".
+- Cmd-N input labels (`agent`, `machine`, `folder`, `repo`, `name`, `task`) no
+ longer append `>`. Their baselines and value columns align with the context.
+ Result rows use the full-width highlight without an extra `>` selection
+ pointer, and their names use the input/context's left inset.
+- The launch menu has an explicit Create/Start row, selected initially, so
+ Enter retains the fast launch with inherited defaults. Up/Down cycle through
+ the displayed arguments, any visible options summary, and Create. Enter
+ opens the highlighted argument; `a/m/p/t/o` still jump directly. Returning
+ from an editor highlights Create again. Cmd-Enter starts from any selected
+ launch row. A missing project still opens Project instead of creating an
+ unnamed folder. Pending creation disables argument navigation.
+- The footer describes the selected action and prints the effective remapped
+ navigation keys. A moved pointer can select a launch row; a parked pointer
+ does not override keyboard selection. Keyboard-practice examples and the
+ design/review notes match the new copy and interaction.
+
+Verification: **60 focused creation/controller/layout tests pass**, followed
+by **21 layout/render/practice checks** after the final alignment adjustment
+(overlapping sets). Logs: `/private/tmp/launch-menu-tests.log` and
+`/private/tmp/launch-menu-final-tests.log`. New coverage drives every launch
+argument through arrows/Enter without starting an agent, checks return to
+Create, and verifies live navigation remapping. The native creation workflow
+also passes with fake agents and arrow-selected Machine:
+`/private/tmp/launch-menu-native.log`. This uses injected Flutter keys, not a
+physical AppKit/IME walkthrough. Final touched-file analysis, formatting, and
+`git diff --check` pass. Inspected normal, highlighted-argument, enlarged-text,
+and GitHub renders in `/private/tmp/launch-menu-renders`.
+
+Rebuilt normal `lib/main.dart` after the native fixture, retaining JEV at
+`http://127.0.0.1:18478`; log `/private/tmp/launch-menu-build.log`. Deep/strict
+signature verification passes. Opened the review app and confirmed PID
+**81012**. No real agent was created; nothing committed or pushed.
+
+## One Project history and a focused folder prompt — previous continuation
+
+The user requested more than four recents, removal of the duplicate history in
+Open folder, bottom placement for the default action, and `o` instead of `e`.
+Recommended and implemented one history in Project, with a separate path prompt
+for a known folder or browsing on the selected machine.
+
+- Project includes every available recent for the selected machine. The dock
+ makes room for up to nine rows, with older entries accessible by arrows,
+ Page Up/Down, or scrolling. Plain `1`–`9` pick the numbered entries. The current
+ folder remains number 1; the list grows upward from the actions.
+- GitHub, New project, and Open folder stay fixed below the recents. Open folder
+ is the bottom/default row, reached with Enter or `o`. History cannot push the
+ actions offscreen. `m` still changes the shared Machine setting.
+- Open folder contains a path/completion prompt and an `Open folder…` browse
+ row next to the input. It no longer repeats or searches recent projects.
+ Empty Enter or Ctrl-O opens the selected machine's browser. Typed paths
+ select matching folders; browse stays nearest the input. New project and
+ GitHub remain separate intents.
+- A `project` keymap context inherits picker navigation/remaps and scopes `o`
+ to Open folder. The launch menu retains `o` for options. Printed hints,
+ shortcut settings, keyboard practice, and the native snapshot share this
+ distinction. The macOS snapshot validator and context handler now accept it.
+- The selected recent remains visible when resizing or increasing text size.
+ Other command docks keep their existing compact heights.
+
+Verification: controller, completion, keyboard, and creation checks passed in
+focused runs. The last layout/render run passed **18 checks**; the preceding
+layout/keymap/shortcuts run passed **44** (overlapping sets). Logs:
+`/private/tmp/project-recents-focused.log`,
+`/private/tmp/project-recents-layout.log`, and
+`/private/tmp/project-recents-resize.log`. Earlier failures were corrected and
+rerun in the affected files; the complete desktop suite was not repeated.
+Final touched-file analysis has no issues, formatting and `git diff --check`
+pass. Inspected normal, older-history, path-only, and large-text renders in
+`/private/tmp/project-recents-renders`.
+
+The native creation workflow passes with fake agents:
+`/private/tmp/project-recents-native-fixed.log`. Its first run caught and led
+to fixing the macOS `INVALID_KEYMAP` rejection of the new context. Injected
+Flutter keys do not establish physical AppKit/IME behavior. The separate older
+`tool/check_keymap_native.sh` executes the new Project-context assertions but
+then fails at its pre-existing obsolete expectation that Cmd-R splits right;
+that helper has not been reconciled with the earlier shortcut redesign. Log:
+`/private/tmp/project-recents-native-keymap.log`. No production shortcut was
+changed to satisfy that stale expectation.
+
+Rebuilt normal `lib/main.dart` after the native fixture with JEV retained at
+`http://127.0.0.1:18478`; log `/private/tmp/project-recents-build.log`.
+Deep/strict signature verification passes without a manual signing repair.
+Opened the review app and confirmed PID **31023**. No real agent was created;
+nothing committed or pushed.
+
+## Quieter Quick Access symbols — previous continuation
+
+The user approved keeping the Quick Open prefixes while removing the decorative
+input `>` / `:` and the selected result's `>` pointer. Cmd-P/T and command
+search now use a plain monospace input and a full-width selection highlight.
+Only the editable prefix identifies the mode (`>`, `@`, `#`, or `?`); the footer
+keeps the mode cheat sheet. Input and result names align at the same left inset.
+The empty agent picker says "Find an agent…". Other field prompts are unchanged.
+
+`SwarmSearchInput.terminal` separates terminal typography from the optional
+prompt decoration used by the advanced agent chooser. TerminalBox supplies the
+dock input's background, avoiding Material's extra filled-field inset.
+
+Verification: **29 focused checks pass** (Quick Access, dock geometry, picker
+entry, search rendering, and the existing render fixture), plus analysis and
+`git diff --check`. Logs: `/private/tmp/quick-access-symbols-tests.log` and
+`/private/tmp/quick-access-symbols-analyze.log`. Reviewed empty, command, and
+narrow/large-text renders in `/private/tmp/quick-access-symbols-renders`.
+
+Rebuilt normal `lib/main.dart`, retaining JEV on port 18478:
+`/private/tmp/quick-access-symbols-build.log`. Opened PID **96237**. The rebuilt
+App.framework verified independently, but the incremental build left its old
+signature in the enclosing app's resource seal. Refreshed the generated app's
+ad-hoc signature, preserving identifier, entitlements, flags, and runtime;
+deep/strict signature verification now passes. No source signing settings were
+changed. No real agent was created; nothing committed or pushed.
+
+## Quick Access prefixes and creation polish — previous continuation
+
+The final user-approved mapping is plain text = agents, `>` = commands,
+`#` = projects, `@` = machines, and `?` = modes/help. An intermediate suggestion
+of `@` agents and `m ` machines was rejected; it is not in the implementation.
+Cmd-P/T now allow these prefixes. Cmd-Shift-P inserts `> ` instead of opening
+a permanently command-only buffer. Deleting it returns to agents in the same
+picker, keeping the New Tab/New Pane destination. Help's prefix rows switch
+in place. Project/machine selection shows only that group's agents; Escape
+restores the parent query. Missing groups never fall back to unrelated agents.
+Prefix hints retain their space while typing so the dock input does not jump.
+
+Recents previously used only the current folder and explicit creation history.
+They now merge known agent folders from the selected machine (including local
+CLI project metadata), collapse equivalent paths, and load saved history on
+the first opening. The menu still shows four, with the full list under Open
+folder. Live metadata updates refresh the menu without changing its selection.
+
+Cmd-N's agent row no longer has `>_`. The editable prompt label uses an input
+prefix aligned to the first text baseline, including empty hints and multiline
+tasks, and shares the context column's left inset. Selected tabs retain their
+3pt top rounding and use matching outward curves where they join the workspace,
+in both the native macOS tab strip and Flutter fallback.
+
+Research sources are linked in `super-terminal-interaction.md`; the interaction
+comes from VS Code Quick Open, with object-specific meanings chosen by the user.
+
+Verification: the full desktop run reached 2,326 passes and five skips, exposing
+ten failures from outdated command-prefix/menu expectations, a test-local name
+collision, and the hint-wrap input movement. After fixing those, all **71 checks
+in the affected files plus the new Quick Access/render cases pass**:
+`/private/tmp/quick-access-final.log`. The whole suite was not repeated after
+that focused rerun. All **11 native macOS workflows pass** with fake agents:
+`/private/tmp/quick-access-native.log`. This verifies injected Flutter input,
+not physical AppKit/IME or VoiceOver behavior. Analysis, formatting, and
+`git diff --check` pass. Final renders are in `/private/tmp/quick-access-renders`.
+
+Rebuilt normal `lib/main.dart` after the native fixture, retaining JEV on
+`http://127.0.0.1:18478`: `/private/tmp/quick-access-build.log`. Deep/strict
+signature verification passed. Opened the review app with `open -n` and
+confirmed PID **35448**. No real agent was created; nothing committed or pushed.
+
+## Shared Machine setting, immediate recents, and quieter tabs — previous continuation
+
+The user approved removing the selected-tab underline and making Machine a
+first-class launch setting. Cmd-N now shows `a agent`, `m machine`, `p project`,
+and `t task`. The path on the launch summary omits the duplicate machine prefix;
+full `machine:path` notation remains in folder search and location previews.
+
+Project now has three fixed actions (New project, Open folder, Clone GitHub)
+and up to four numbered recent projects for the selected machine. The accepted
+current folder is first, followed by that machine's recent history. `1`–`4`
+select immediately; full history/search/browsing stays under `e`. Actions stay
+fixed if the recent list needs scrolling. The Project header exposes the same
+remappable `m` chooser as the launch screen. Cancelling Machine returns to its
+source screen with its query intact; a changed machine clears a folder filter
+from the old machine. Accepted project choices remain separate per machine,
+and stale recent rows from another machine are rejected.
+
+Both the native macOS tab strip and Flutter fallback now use the existing
+selected background and bold label without the 2pt underline.
+
+Verification: 86 focused creation/practice/render checks passed, followed
+by 62 final keyboard/render checks including shared-Machine return, remapping,
+numbered recents, stale-machine rejection, and retained task/project choices.
+Touched-source/test analysis has no issues; formatting and whitespace checks
+pass. Normal and enlarged-text/narrow Project renders were inspected under
+`/private/tmp/machine-recent-renders`.
+
+All **11 native macOS journeys pass**, including the new top-level Machine
+chooser and direct recent selection: `/private/tmp/machine-recent-native.log`.
+These use fake agents and injected Flutter input; physical AppKit/IME and
+VoiceOver were not newly verified. The whole desktop suite was not rerun.
+The normal app was rebuilt from `lib/main.dart` after the native fixture,
+retaining `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`:
+`/private/tmp/machine-recent-build.log`. Deep/strict signature verification
+passed. Opened `build/macos/Build/Products/Debug/Harness.app` with `open -n`
+and confirmed PID 14979; existing app instances were left alone. Nothing was
+committed or pushed, and no real agent was created for verification.
+
+## Project actions and visible task availability — previous continuation
+
+User review found that project history buried New/Open/GitHub/Machine, and Pi
+hid the task row. Project now opens a separate four-action menu: `n` New project,
+`e` Open existing project, `g` Clone GitHub repository, and `m` Change machine.
+All four stay visible regardless of recent history. Arrows follow the menu's
+top-to-bottom order, Enter chooses, and the letters follow the live keymap.
+
+Each action opens a dedicated prompt: `name >`, `folder >`, `repo >`, or
+`machine >`. Existing searches only that machine's folders and never converts
+a missing match into a new folder. Its footer keeps Ctrl-O/clickable Browse
+folders visible. New previews the exact slug/path and offers Open existing on
+a collision. A late folder listing now refreshes that name preview too.
+GitHub accepts owner/repo or supported GitHub URLs and cannot silently launch
+in the old project on invalid input. Selection retains the repository for
+launch; it does not clone while merely browsing the menu. Escape backs out to
+Project, then the launch summary. Switching machines retains their accepted
+project choices separately.
+
+Task stays visible for Pi and other unsupported engines with “Enter a task in
+<agent> after launch”; `t` explains the restriction. This reflects the current
+CLI first-prompt contract, not a claim that Pi itself lacks prompt support.
+No CLI engine-launch behavior changed. Supported agents retain the task editor
+and all first-message/draft/recovery protections.
+
+Verification: **90 focused creation/practice/render checks**, **92 keymap,
+first-task, and recovery checks**, and **11 native macOS journeys** pass. Logs
+are `/private/tmp/project-menu-focused2.log`, `project-menu-keymap.log`, and
+`project-menu-native.log`. Final touched-file analysis has no issues; formatting
+and whitespace checks pass. Visuals in `/private/tmp/project-menu-renders`
+include all four project actions at normal and enlarged text/narrow width,
+New/Existing/GitHub/Machine prompts, and Pi's visible task row. The final render
+fixture also passes. The entire desktop suite was not rerun for this revision.
+Native journeys use fake agents and injected Flutter input, with no new
+physical AppKit/IME or VoiceOver coverage.
+
+The normal macOS debug app was rebuilt from `lib/main.dart` after the native
+fixture, retaining `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`:
+`/private/tmp/project-menu-build.log`. Deep/strict signature verification passed.
+Opened `build/macos/Build/Products/Debug/Harness.app` with `open -n` and confirmed
+the new review process (PID 30111). The earlier review instance was left alone.
+No real agent was created; nothing was committed or pushed.
+
+The user also asked about the selected-tab underline. It was explained as a
+generic active-tab marker, not a copy of a particular terminal app. Simplifying
+it to the existing fill and bold label was recommended; no tab-style change
+was requested or made during this Project pass.
+
+## Cmd-N launch menu and focused prompts — previous continuation
+
+The user approved trying a launch-command model after reviewing Vim, Emacs,
+tmux, zsh, and Magit patterns. Cmd-N reuses the current agent/project and shows
+`a agent`, `p project`, and `t task`; Enter launches with the displayed setup.
+Each letter opens one focused picker/editor, and Enter on an agent/project
+returns to the launch menu. Enter in Task launches; Escape retains it and
+returns to the menu. Menu letters are ordinary text inside editors. `o` and
+Cmd-period open advanced options; these keys follow the live keymap.
+
+Tab now completes the current argument without accepting a selection or
+switching fields. Existing path completion/cycling and line editing remain.
+If there is no project, its picker opens first; compact creation no longer
+silently allocates an unnamed folder. New project opens `name >` with the
+machine/path preview; whitespace in a name becomes the destination slug.
+Machine selection remains nested in Project, with recents and cached choices
+scoped to the selected machine. Escape goes back through these prompts.
+
+The user also requested a much darker background behind floating forms.
+New Harness and shared terminal forms (including Rename Tab) now use the
+existing shared 90% black dialog tint with no blur. Docks keep their workspace
+alignment. The updated ideal-user brief at the main checkout's
+`docs/ideal-users.md` describes technical founders building across disciplines;
+the task copy remains broad enough for a deck, analysis, video, or code.
+
+Verification and review build:
+
+- The full desktop run completed with **2,340 passed, 5 skipped, and one
+ outdated test failure**. That test switched machines and attempted creation
+ without choosing a project on the new machine. It now selects that project
+ explicitly; all **26 final placement, Store, and render checks pass** in
+ `/private/tmp/cmd-n-launch-final-focused.log`. The full suite was not rerun
+ after this test-only correction. An earlier default-concurrency run was
+ interrupted under heavy load; its local-discovery timing failures passed in
+ isolation and in the completed concurrency-2 run.
+- **All 11 native macOS journeys pass**, including the new launch menu, retained
+ task, argument editing, advanced-form return, chosen destination, and terminal
+ focus recovery: `/private/tmp/cmd-n-launch-native.log`. These use fake agents
+ and Flutter-injected input. Physical AppKit keyboard/IME and VoiceOver are not
+ newly verified. The fixture logged a foreground warning but completed all
+ tests successfully.
+- Final touched-source/test analysis has no issues; full app/test analysis has
+ no errors or warnings and the same three existing informational lints.
+ Formatting and `git diff --check` pass.
+- Rendered and inspected the launch menu, empty and named project prompts,
+ narrow layout at enlarged text, and dark Rename Tab/advanced-form backdrops:
+ `/private/tmp/cmd-n-launch-renders`.
+- Rebuilt the normal app from `lib/main.dart` after the native fixture, retaining
+ `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`. Build log:
+ `/private/tmp/cmd-n-launch-build.log`. Deep/strict signature verification passed.
+ Opened `build/macos/Build/Products/Debug/Harness.app` with `open -n` and confirmed
+ the review process (PID 43696). No real agent was created for verification;
+ nothing was committed or pushed.
+
+## PR #136 rebase and project-picker clarity — latest continuation
+
+- Rebased onto `eb35e248` and restored all 184 working files. The only conflict
+ was the import block in `swarm_screen.dart`; both sets of imports are retained.
+ Hash comparison found no missing files and changes only in the three files
+ that intentionally received upstream JEV updates. Nothing was committed or
+ pushed, and the user's local `main` was not changed.
+- Recovery copies: branch `backup/command-box-before-pr136-20260920` at
+ `d46ffaf4`, stash `1b36d3c672ad8f7037b814e427f3cb3eba769056`, and the file archive,
+ patch, and hash manifest in `/private/tmp/command-box-before-pr136-cn1qkthp`.
+- **Cmd-Shift-J** still opens the separate experimental JEV prompt. PR #136
+ makes exact app commands and unique session/tab titles run locally on Enter.
+ Navigation offers **Go back** to the original view without closing the target.
+ Duplicate names stay choices; full phrases are checked, including compound
+ and negated requests. Semantic automatic actions use separate intent, target,
+ and fit decisions. Send/create/watch continue to require explicit selection.
+- The review service on `http://127.0.0.1:18478` was already running and connected.
+ Its service, HTTP, credential resolver, and launcher source match the rebased
+ code and predate its process start. The review build uses this service via
+ `JEV_COMMAND_BAR_URL`; no daemon or existing service was restarted. A temporary
+ unconfigured service on port 28577 was stopped after checking it.
+- The initial twelve synthetic live checks were blocked by `OPENROUTER_CREDITS`.
+ During user review, requests to the new service on port 18478 started returning
+ HTTP 200 (01:37–01:40 local). The reported 404s came from the old daemon endpoint
+ on port 18473, used by an older app instance. The new review build targets
+ 18478. Transport success is verified; the twelve-case semantic smoke suite has
+ not been rerun, so its decision quality is not yet newly validated live.
+ Exact local commands and Go back do not require provider credits.
+- Project editing now says **on <machine>**, with **Search or name a project**
+ at the prompt. An empty query offers **Open folder…**, existing folders on
+ that machine, and **Change machine…**. There is no selected-looking `<name>`
+ path or empty Create row. Typing `payments processing` offers
+ **Create payments-processing** and one `machine:~/harnesses/payments-processing`
+ destination. Clone requests do not also offer an unrelated new folder.
+- Recent projects are scoped to the chosen machine. Switching to iMac cannot
+ show M2 folders; switching back restores that machine's draft choice. Stale
+ project rows from a different machine are rejected. Action rows are compact;
+ real project choices keep their two-line name/path presentation.
+- Synced Score's bundled tagline to the updated Store manifest brought in by
+ PR #134. This fixes the two catalog identity checks exposed by the rebase.
+- Added a native JEV journey covering exact navigation, Go back to the original
+ pane, restored terminal input, and opening the existing New Tab chooser.
+ Like the other native fixtures, it uses fake sessions and injected input.
+
+Verification artifacts are under `/private/tmp/pr136-*`: 73 focused desktop
+checks, 58 CLI checks, TypeScript checking, and the CLI build pass. The first
+full desktop run passed 2,335 tests (5 skipped) with only the two Score tagline
+mismatches; after synchronization, all 22 render/catalog/JEV checks pass.
+App/test/integration analysis reports only the same three informational lints;
+final touched-file analysis has no issues. Project empty/named states and JEV
+Go back renders were inspected in `pr136-box-renders` and `pr136-jev-renders`.
+All **11 native macOS journeys pass**, including the new JEV flow, in
+`/private/tmp/pr136-native-final.log`. The fixture submits through the text-input
+action and waits for the completion notice's entrance animation before tapping
+Go back. This exercises the native workspace with injected Flutter input;
+physical AppKit keys, IME, and VoiceOver are not newly covered.
+The normal macOS debug build from `lib/main.dart` succeeded after the native
+fixture, using `--dart-define=JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`:
+`/private/tmp/pr136-review-build.log`. Deep/strict signature verification passed.
+Opened `build/macos/Build/Products/Debug/Harness.app` with `open -n` and confirmed
+the new process (PID 47919, started 2026-09-20 01:34:14 local). An older review
+instance was left running; the newly opened window is the one to review.
+
+## Creation polish and keyboard learning — previous continuation
+
+The user chose to leave JEV experimental and improve the everyday workflow.
+No new JEV integration or promotion was added in this continuation.
+
+- Project searches match words with spaces to hyphenated/underscored folder
+ names. Selecting a recent project still chooses its machine and path together.
+ Punctuation-only names cannot accidentally become an unnamed new project.
+- Escape retains edited agent/project defaults even before a task is typed.
+ Drafts remain scoped to their source and bounded to 32 inactive contexts;
+ unresolved creations are retained. Cancelling Browse restores prompt focus.
+- **Quick start** is an optional four-step guide alongside real work: open an
+ agent, add a second pane in the tab, zoom, then open command search. Opening
+ and cancelling an empty chooser does not count. It never takes typing focus.
+ Progress and dismissal persist locally; the guide can be paused or restarted.
+- **Keyboard practice** is a separate, repeatable terminal-styled scratch
+ surface. Search by action/group, press the actual shortcut, see a simulated
+ result, then Enter to continue or Escape to return. It covers the stable
+ command catalog and prompt editing, follows live remaps/sequences/unbindings,
+ and tracks local progress. Actions without a binding can be practiced by
+ typing their command-search name. It does not execute workspace/agent actions.
+ Page Up/Down reads longer explanations at enlarged text sizes.
+- Both are discoverable on the start page, through command search, and from
+ native Help. The shortcut reference links to practice too. `Pause quick start`
+ is available through command search while the guide is active.
+- Nested keyboard hosts now defer to the host nearest the focused control.
+ This prevents one Escape from firing twice in the scratch surface and keeps
+ real workspace shortcuts out of practice.
+
+Primary files: `lib/state/workspace_learning.dart`,
+`lib/widgets/workspace_quick_start.dart`, `lib/shortcuts/keyboard_practice.dart`,
+and their integration in `lib/screens/swarm_screen.dart`.
+
+Verification:
+
+- **2,323 desktop tests passed, 5 skipped**:
+ `/private/tmp/keyboard-learning-full.log`.
+- After the final practice scrolling/typography refinements, **34 focused
+ regressions** and **14 final keyboard/layout checks** passed, including the
+ added narrow Quick start render:
+ `/private/tmp/keyboard-learning-focused-final.log`,
+ `/private/tmp/keyboard-learning-layout-final.log`.
+- **All 10 native macOS journeys passed**, including the new Help-command
+ dispatch, guide progression, simulated practice, single-step Escape, and
+ restored terminal input: `/private/tmp/keyboard-learning-native.log`.
+ These use fake agents and Flutter-injected keys; physical AppKit keyboard,
+ IME, VoiceOver, and Linux runtime were not newly exercised.
+- App/test/integration static analysis has no errors or warnings and the same
+ three pre-existing informational lints:
+ `/private/tmp/keyboard-learning-analyze-final.log`.
+ `git diff --check` and formatting checks pass.
+- Captured and inspected the practice list, exercise, result, keyboard-scrolled
+ explanation, and narrow guide: `/private/tmp/keyboard-learning-renders`.
+- Normal macOS debug build succeeded from `lib/main.dart` after the native
+ fixture: `/private/tmp/keyboard-learning-build.log`. Signature verification
+ passes. Review artifact: `build/macos/Build/Products/Debug/Harness.app`;
+ opened with `open -n` for review. Nothing was committed or pushed.
+
+## Agent → Project → Task, main rebase, and JEV — previous continuation
+
+The accepted creation layout is now:
+
+```text
+agent >_ Claude Code
+project iMac–Home:~/work/payments
+
+task > What should it do?
+```
+
+- Agent and Project are vertically aligned; Task initially owns input. Tab and
+ Shift-Tab follow Agent → Project → Task. Choosing an agent or project with
+ Enter returns to Task. The inherited project still makes repeat creation fast.
+- Machine lives inside Project. Recent projects from all available machines
+ show a two-line name and `machine:path`; selecting one chooses both together.
+ Browse folders and Change machine are inside the project picker. Machine
+ choice returns to Project; Escape backs out without dropping the task. Each
+ machine remembers its project for this draft, including a More options round trip.
+- The project prompt says `Type a project name`. `payments processing` offers
+ `Create “payments processing”` with
+ `machine:~/harnesses/payments-processing`. If that folder already exists under
+ the selected machine's harnesses directory, the choice becomes Open. Existing
+ paths, path completion, and repository cloning remain supported.
+- Remote `~` resolves against the selected machine's home. Old directory/home
+ replies cannot retarget the project after a machine switch. Browse results
+ also check machine identity before applying.
+- Auto-approve is hidden under More options (Cmd-period). A changed permission
+ mode or chosen Codex profile appears in one compact options summary.
+
+Main was behind upstream and carried two unpushed local commits. Those were
+rebased on an isolated integration branch before applying them to this worktree;
+the user's local `main` remains at `d626604d`. Two additional upstream commits
+arrived during validation, including the JEV Sheets desktop chooser fix; this
+branch includes them through `252fdc18`. Nothing was pushed. Existing desktop
+and CLI WIP was restored unstaged. The final restoration compared all 175 saved
+working files byte-for-byte with its stash and found no differences.
+
+Recovery copies retained:
+
+- Original branch: `backup/command-box-before-jev-20260919` at `3cd4014a`.
+- Original WIP stash: `7a06eebf4db3805519430d90adae21e0a5c522a0`.
+- Original file archive/patch/hashes: `/private/tmp/command-box-before-main-mthmiuvc`.
+- Validated WIP before the final two upstream commits:
+ `d6d70f2f1c9918002ba1373434520d7da7479847`.
+
+### JEV catch-up
+
+- **Cmd-Shift-J** opens the experimental command bar. Typing filters locally;
+ Enter can ask JEV to navigate, find sessions by recent activity, route the
+ exact task to an existing agent, suggest a specialized harness, or propose a
+ watch. Sending, creating, and watching require their explicit action cards.
+- Requests use bounded live evidence (up to 24 sessions, 24 harnesses,
+ 96 candidates / 32k characters) and revalidate targets before dispatch. The
+ two watches per window recheck changed evidence at most once per minute.
+- Its new-agent action now supplies engine and task to this dock. A folder
+ from a focused remote pane is not inherited when JEV chooses another machine.
+ JEV and the dock dismiss each other, preserve unsubmitted drafts, and respect
+ an unresolved creation. The experimental JEV pill styling is unchanged.
+- **JEV Sheets** is a separate Store harness: bring a spreadsheet, ask row-wise
+ choice/score/yes-no questions, review confidence, export answers and findings.
+ Its newest fix adds an in-pane file chooser because the macOS web view did
+ not open the system file dialog. It offers recent files, browsing, pasted
+ paths, and a paste-rows box.
+- The command bar needs an updated daemon or the documented standalone
+ service, plus OpenRouter credentials, for provider-backed requests. This
+ continuation did not update/restart the daemon or make live provider calls.
+ See `../../docs/experiments/jev-command-bar.md` and
+ `../../store/agents/jev-sheets/README.md`.
+
+Verification:
+
+- **2,309 desktop tests passed, 5 skipped**:
+ `/private/tmp/project-context-full-final.log`. The last two upstream commits
+ touched Store packages/docs only; all desktop/CLI working files were restored
+ identically afterward. Updated old field expectations and synchronized
+ FreeCAD's bundled tagline with the changed upstream Store description.
+- **All 9 native macOS journeys passed**:
+ `/private/tmp/project-context-native.log`.
+- **75 targeted CLI tests** and TypeScript checking passed:
+ `/private/tmp/project-context-cli.log`,
+ `/private/tmp/project-context-cli-typecheck.log`.
+- **All 42 JEV Sheets tests passed**, including the new in-pane chooser:
+ `/private/tmp/project-context-jev-sheets.log`.
+- **5 new project-context tests** cover Tab order, spaces in names, machine
+ ownership, duplicate folder names, offline choices, remote home completion,
+ existing destinations, draft retention, and delayed replies. JEV-to-creation
+ integration and focus ownership also have a regression journey.
+- Rendered 107 box states and inspected ordinary, narrow and enlarged-text
+ layouts: `/private/tmp/project-context-renders`. Static analysis has no errors
+ or warnings and the same three existing infos:
+ `/private/tmp/project-context-analyze-final.log`.
+- Normal macOS debug build succeeded after the native fixture, with
+ `--target lib/main.dart`: `/private/tmp/project-context-build.log`.
+ Artifact: `build/macos/Build/Products/Debug/Harness.app`. Opened with `open -n`;
+ its process remains running and `codesign --verify --deep --strict` passes.
+ Live UI automation could not reliably distinguish it from the installed
+ copy with the same bundle ID. The observed launch crash reports name
+ `/Applications/Harness.app` and mismatched framework Team IDs, not this
+ worktree artifact. That installed copy was not modified. Visual verification
+ of this change is from the rendered fixtures and native integration journeys.
+
+## Compact dock, tab height and Harness Store — current continuation
+
+The user accepted the simulated panel's compact bottom-dock direction, asked
+to check the unusually tall tab bar, and approved three prominent Store
+entrances. Implemented:
+
+- Bottom-up dock results: best match immediately above the input, about six
+ visible rows, Up/P/K away from the input and Down/N/J back toward it. Docked
+ lists clamp at their ends; inline start-page search keeps its existing order.
+- A smaller dock height budget, default preview beside results or above them
+ when narrow, no redundant preview for New agent, and stable footer widths.
+- New Pane shows its captured destination tab. New-agent choices follow the
+ same spatial ordering; the inherited engine is first, while task arrows
+ remain text-editing keys.
+- AppKit `.unifiedCompact`: measured 40pt versus the previous 52pt with a
+ scratch AppKit probe. The Flutter fallback is also 40pt, with matching tab
+ top insets and centered controls.
+- Persistent **Harness Store** text control at the far right of both tab bars.
+ `app.store` is a remappable command, searchable as store/install/browse
+ harnesses/packages/extensions. **Browse more harnesses…** in agent choices
+ opens the Store while retaining the source's task/default draft. All paths
+ reuse the existing singleton Store-tab behavior.
+- Utility tabs now hide the retained canvas rather than disposing its terminal
+ renderers. A native regression caught the previous remount after Store
+ browsing; the original view, selection and scroll can now survive the trip.
+- The taller offline help card scrolls when needed, including the breakpoint
+ newly reached by reclaiming 12pt from the tab bar.
+
+Verification:
+
+- **2,277 desktop tests passed, 5 skipped**, including dock geometry/spatial
+ keys, Store aliases/remapping, singleton tabs, native/Flutter dispatch,
+ retained terminal views, focus and draft ownership.
+ `/private/tmp/terminal-compact-full-final.log`.
+- **All 9 native macOS journeys passed**, including Store round trips retaining
+ the original terminal renderer. `/private/tmp/terminal-compact-native-retained.log`.
+- **69 focused regressions passed** while generating 107 box renders and
+ wide/narrow/2x-text picker captures. Inspected input adjacency, preview order,
+ footer wrapping and the compact top bar.
+ `/private/tmp/terminal-compact-regressions.log`,
+ `/private/tmp/terminal-compact-final-render`,
+ `/private/tmp/terminal-compact-final-picker`.
+- Static analysis: no errors or warnings, the same three informational lints
+ in app_state.dart, grid_model_picker.dart and pane_grid.dart.
+ `/private/tmp/terminal-compact-analyze-final.log`.
+- The normal macOS debug build succeeded with `--target lib/main.dart` after
+ native fixtures and was opened for review. Native UI inspection confirmed
+ the compact bar and permanent Harness Store control beside the user's tabs.
+ `/private/tmp/terminal-compact-build.log`.
+
+## Dock placement discussion
+
+The user is reconsidering top versus bottom and explicitly wants AI reviewers
+roleplaying expert terminal developers. No human outreach is requested. The
+roleplayed panel splits: two favor compact bottom docks with different internal
+ordering; one favors top. All prioritize query/result adjacency, explicit scope
+and reliable focus restoration. The bottom-dock direction is now implemented
+as described above.
+The opinions, design tradeoffs and primary-source references are in
+[command-dock-placement-review.md](command-dock-placement-review.md).
+
+## Default previews and harness marker — latest review feedback
+
+New Tab and New Pane now open with preview visible, matching the start-page
+picker. Ctrl-/ still hides or restores it without changing the query, selection
+or input focus. The default was previously off to keep the picker compact;
+the user prefers immediate context. The Enter hint is shortened to `open`
+when the dock title already names its destination, avoiding a footer wrap that
+moved the input while filtering in narrow windows.
+
+`>_` is the ASCII harness marker before Codex, Claude and other harness names
+in all prompt presets, agent previews and new-agent defaults. Machine symbols
+use a monitor so the two kinds of context are visually distinct. Catalog data
+now supplies a separate harness field; offline and fork annotations do not
+acquire a harness marker. The customization preview includes a Codex segment.
+
+Verification: **147 focused checks passed** (128 picker/layout/keyboard and 19
+placement checks), 107 box states and 21 customization states rendered, and
+wide/narrow prompt examples inspected. Static analysis has no errors or warnings
+and the same three existing infos. The normal macOS debug build succeeded with
+`FLUTTER_TARGET=lib/main.dart`. Logs:
+`/private/tmp/terminal-preview-marker-checks.log`,
+`/private/tmp/terminal-preview-marker-placement.log`,
+`/private/tmp/terminal-preview-marker-analyze.log`, and
+`/private/tmp/terminal-preview-marker-build.log`.
+
+## Workspace dock and prompt customization
+
+The requested workspace styling is implemented and rebuilt for review. Search, New Tab, New Pane and New Agent use a bottom command dock,
+aligned with the pane grid's 6px outer inset. Results sit above the input. The
+dock does not resize terminal renderers. The editor retains its input connection
+when switching between task and default fields; ordered traversal takes Tab from
+the search input to the first result, including virtualized lists.
+
+The New Pane pill has been removed from both native macOS and Flutter titlebars.
+Cmd-P, File → New Pane and command search remain. Tabs use monospace labels,
+flat 3px corners and a thin selection rule; pane corners share that radius.
+Native tab labels follow the selected terminal font.
+
+Customize OpenHarness now opens on a Prompt tab, also reachable by typing
+`customize` in Cmd-Shift-P command search. Plain, Symbols and Powerline presets
+have a live preview, optional color, and machine/project/branch visibility.
+Choices persist together without replacing wallpaper, color palette or fonts.
+Search and pane headers share this presentation. Catalog identity and ranking
+remain based on the actual agent metadata. No repository status is fabricated.
+See [research and design decisions](terminal-prompt-styling.md).
+
+Verification for this pass:
+
+- Full desktop suite: **2,270 passed, 5 skipped** (`/private/tmp/terminal-dock-full-final.log`).
+- Final focused field/creation/customization/startup/identity regressions: **40 passed**;
+ dock and configured-key regressions: **30 passed**.
+- Native macOS workspace fixture: **9 journeys passed** (`/private/tmp/terminal-dock-native.log`).
+- Static analysis: no errors or warnings; the same three pre-existing infos.
+- Rendered 107 box states and 21 customization states. Inspected the three
+ context styles, narrow Powerline, wide/large-text creation, search preview,
+ and customization at ordinary and enlarged text sizes.
+- Normal macOS debug build succeeded; `FLUTTER_TARGET=lib/main.dart` confirmed.
+ Artifact: `build/macos/Build/Products/Debug/Harness.app`.
+ Build log: `/private/tmp/terminal-dock-macos-build.log`.
+
+The user's installed or already running applications were not replaced or
+restarted. Relaunch the worktree artifact to see the new styles.
+
+The unfinished Settings navigation experiment was parked before this review:
+its three source files were restored to their previous state, with its exact
+patch retained at `/private/tmp/terminal-settings-wip.patch`. It needs live
+keymap propagation, section focus, responsive layout and tests before resuming.
+
+At that stage onboarding remained a design proposal. It is now implemented as
+Quick start and optional Keyboard practice; see the latest continuation above.
+
+## Terminal restart status and lifecycle — latest continuation
+
+Restart Agent / Restart Terminal now use a compact terminal status prompt.
+The action still starts immediately; Escape returns to the workspace while
+the request continues. Reopening joins that request. Confirmed refusals stay
+inline with Enter/retry. Lost replies switch to Enter/check status on the
+original receipt. “Restart again…” is a separate action, with Cancel focused
+initially and an explicit reminder that the earlier restart may have completed.
+The confirmation stays fully visible at 480×360 with 1.7× text. Tab goes directly
+through controls; Page Up/Down scroll the explanation without making it an
+extra focus stop. Picker bindings, including live changes, apply throughout.
+
+Command search and custom bindings now expose Restart Agent, or Restart Terminal
+for shells. Pane controls and the machine list use the same names and prompt.
+A resumed agent closes the prompt. A fresh conversation retains a clear notice
+with Enter/close; a fresh shell does not show a conversation-resume warning.
+The existing terminal views, tab membership, and focused pane remain intact.
+
+Restart attempts belong to the model, with one pending request per source.
+Completed explicit intents cannot replay, and uncertain attempts only query
+status until the user deliberately starts another. Stale source/machine/auth
+identity and any intervening Stop request invalidate late results. Replies
+cannot restore a removed or recreated agent, undo a newer name/session, or
+let inventory begun before the restart restore the old session.
+
+The CLI now persists restart receipts, including resumed/fresh outcomes.
+An in-memory coordinator also joins overlapping restarts of one canonical
+agent across clients and receipt IDs. Stop cancels that operation; target
+checks around asynchronous steps prevent subsequent process replacement or
+fresh fallback after cancellation. Already-issued system calls still finish.
+No real agent, shell, or running daemon was restarted during this work.
+
+Verification:
+
+- Focused restart, stop, fork, rename, and pane regressions: **89 passed**.
+ New coverage includes **18 restart model tests and 6 keyboard tests**. Log:
+ `/private/tmp/terminal-restart-focused-final.log`.
+- A final keyboard check found that Enter could not activate a focused Close
+ control while Restart was pending. Focused controls now own Enter before the
+ pending-submit guard. All **27 restart model, keyboard, and pane checks pass**,
+ including Tab/Enter dismissal followed by reopening the same request. Log:
+ `/private/tmp/terminal-restart-review-focused.log`.
+- Full desktop suite before that final focused-control fix: **2,266 passed,
+ 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-restart-suite-final.log`.
+- CLI socket, receipt, and restart tests: **117 passed** across three files.
+ Cancellation is exercised before dispatch and during hold, termination,
+ resume preparation, respawn, and process discovery; no fresh fallback runs
+ after cancellation. Log: `/private/tmp/terminal-restart-cli-tests.log`.
+- TypeScript typecheck passed with `--incremental false`, and the local CLI
+ compiled successfully. Logs: `/private/tmp/terminal-restart-cli-typecheck.log`
+ and `/private/tmp/terminal-restart-cli-build-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-restart-analyze-review.log` (after the final keyboard
+ and native fixture changes).
+- **103 rendered states** in `/private/tmp/terminal-restart-final`. All ten
+ new restart states were inspected, including pending reopen, refusals,
+ uncertainty, explicit repeat confirmation, small-window/enlarged-text views,
+ keyboard-scrolled details, fresh conversation, and shell restart. Log:
+ `/private/tmp/terminal-restart-render-final.log`.
+- All thirteen touched Dart files are formatted; `git diff --check` passes.
+- Native macOS workspace fixture: **9 passed**. Log:
+ `/private/tmp/terminal-restart-native-review.log`. Earlier runs passed eight
+ journeys, including Restart, but Find correctly released its index while the
+ fixture window was inactive. The fixture now explicitly shows and focuses
+ its own window for each journey, and waits for the completed query snapshot
+ before checking all four matches. Product background indexing is unchanged.
+
+- Normal macOS debug rebuild succeeded after native verification, with explicit
+ `--target lib/main.dart`; the generated target was checked. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-restart-macos-build-final.log`.
+
+The [30-item review checklist](terminal-review-checklist.md) records exact keys,
+expected behavior, and useful feedback. Existing app instances and the installed
+application were not replaced or restarted. Status recovery
+requires the updated CLI; legacy successful replies remain supported. Desktop
+receipt references last for the current window, not across app restarts.
+Native tests use simulated traffic and injected Flutter keys. Real process
+replacement, physical keyboard/IME, VoiceOver, Linux runtime, settings, and
+remaining onboarding need further work. The broader goal remains active.
+
+## Terminal fork prompt and receipt recovery — preceding continuation
+
+Fork Agent now uses the same thin terminal frame, font, transparent backdrop,
+and local key guide as search and creation. The source, machine, and actual
+project folder are visible above `name >` and `task >`. Task input owns focus
+immediately; the draft survives Escape. Native Next/Done, multiline tasks,
+Alt-Enter, Readline editing, composition, custom submit/accept/cancel/traversal,
+and live keymap reload are covered. Up/Down and Ctrl-N/P keep their editing
+behavior inside the task. Fork Agent is available in command search and as a
+remappable action without reserving a default terminal chord.
+
+Pending forks now belong to the model. Reopening joins the existing request;
+repeated submission cannot start a second fork. Refusals keep the edited draft
+and report errors inline. A lost response locks the submitted choices and
+offers “check status” using the same creation receipt. Starting another fork
+is a separate explicit action followed by confirmation. A short uncertainty
+message, recovery controls, and Escape stay visible in short windows; longer
+details scroll with Page Up/Down.
+
+The CLI now gives `agent_fork` the durable receipt support already used by
+creation. It reserves the intent before launch, coalesces repeated requests,
+and retains native/handoff information through status lookup and daemon
+restart. Spawn/registration failures remain unconfirmed rather than inviting
+an automatic retry. The desktop accepts legacy successful fork responses;
+lost-response status recovery requires this updated CLI. No running daemon
+was restarted or updated as part of verification. Desktop drafts and receipt
+references remain in memory for the current window.
+
+The original destination and focus are captured when the fork starts. A late
+result opens there without moving the user's newer focus; closed or full
+background destinations leave the created agent available through New Pane or
+New Tab. A full tab still in focus opens a new tab named for the fork. Stale
+machine/auth/source identities are rejected before dispatch, and late receipts
+cannot undo a newer observed name or restore a fork stopped in the meantime.
+Restart behavior is unchanged in this continuation and remains a separate audit.
+
+Verification:
+
+- Focused fork, creation recovery, placement, stop/rename, and menu regressions:
+ **115 passed**, including 19 new fork model tests and 8 keyboard tests. Log:
+ `/private/tmp/terminal-fork-focused-final.log`.
+- Full desktop suite: **2,242 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-fork-suite-final.log`.
+- Native macOS workspace fixture: **8 passed**. The new journey verifies
+ immediate task focus, multiline draft restoration, pending reopen, lost-reply
+ status lookup without another fork, successful placement, and returning input
+ to the original terminal. Log: `/private/tmp/terminal-fork-native-final.log`.
+- CLI receipt/socket checks: **89 passed**; existing fork planning checks:
+ **8 passed**. Logs: `/private/tmp/terminal-fork-cli-tests.log` and
+ `/private/tmp/terminal-fork-cli-plan-tests.log`. TypeScript typecheck passed;
+ local CLI compilation passed (`/private/tmp/terminal-fork-cli-build-final.log`).
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-fork-analyze-final.log`.
+- **93 rendered states** in `/private/tmp/terminal-fork-final`. All nine new
+ fork states were inspected, including pending reopen, refusals, uncertainty,
+ 480×360 at 1.7× text, keyboard-scrolled details, and OpenCode handoff. Finder
+ and creation previews were also inspected. Render log:
+ `/private/tmp/terminal-fork-render-final.log`.
+- All fourteen touched Dart files are formatted; `git diff --check` passes.
+
+The normal macOS review app was rebuilt after native testing with explicit
+`--target lib/main.dart`, also confirmed in generated configuration. Artifact:
+`build/macos/Build/Products/Debug/Harness.app`. Build log:
+`/private/tmp/terminal-fork-macos-build-final.log`. Existing user app instances
+remain untouched. Tests use simulated traffic; no live fork or engine-history
+copy has been exercised. Physical keyboard/IME, VoiceOver, Linux runtime,
+restart lifecycle, settings, and remaining onboarding still need further work.
+The broader goal remains active.
+
+## Terminal stop prompts and agent lifecycle — preceding continuation
+
+Stop Agent / Stop Terminal now use the same compact terminal frame, font, and
+key guide as search and creation. The prompt identifies the agent and machine,
+explains what stopping does, and starts on Cancel. Controls and Escape remain
+visible in short windows; Page Up/Down scroll the explanation at enlarged text
+sizes. Stop Agent is available through command search and custom bindings,
+with Stop Terminal used for shell agents. No default terminal chord is taken.
+Pane menus use the same names and prompt.
+
+Stopping now retains progress and errors inside the prompt. Its persistent
+focus node fixes Escape/custom cancellation after the focused Stop button
+disappears. Reopening joins the existing model-owned request instead of
+sending another. Failures return focus to Cancel and allow retry. Closing a
+pane continues to leave the agent running.
+
+Confirmation captures the machine, agent session, auth revision, and observed
+deletion generation before the user accepts. A replaced target cannot receive
+the old confirmation's stop request; ordinary inventory/name updates are still
+accepted. Pending stop receipts also check identity/session, and an
+`agent_deleted` event can complete the request before its RPC receipt arrives.
+An old receipt cannot affect a recreated ID. All views of the stopped agent
+are removed across tabs before awaiting local detach cleanup, retaining other
+terminals. Older inventory cannot restore a stopped row or overwrite an ID
+recreated after the stop. Rename and new restart requests are blocked while a
+stop is pending.
+
+Verification:
+
+- Focused stop, rename, machine-manager, pane, and handoff regressions:
+ **103 passed**, including 19 new stop model/widget checks. Log:
+ `/private/tmp/terminal-stop-focused-final.log`.
+- Final full desktop suite: **2,215 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-stop-suite-final.log`.
+- Native macOS workspace fixture: **7 passed**. The new journey confirms the
+ default Cancel, pending dismissal/reopen, inline refusal/retry, closing only
+ the target's views, and returning input to the retained terminal. Traffic
+ is entirely simulated. Log: `/private/tmp/terminal-stop-native-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-stop-analyze-final.log`.
+- **84 rendered states** in `/private/tmp/terminal-stop-final`; all eight new
+ stop states were inspected, including pending reopen, errors, 480×360 at
+ 1.7× text, and keyboard-scrolled details. Finder and creation previews were
+ also inspected. Log: `/private/tmp/terminal-stop-render-final.log`.
+- All fifteen touched Dart files are formatted; `git diff --check` passes.
+
+The normal macOS review app was rebuilt after the native fixture with explicit
+`--target lib/main.dart`, also confirmed in generated configuration. Artifact:
+`build/macos/Build/Products/Debug/Harness.app` (binary timestamp 18:53:41).
+Build log: `/private/tmp/terminal-stop-macos-build-final.log`. Existing user
+app instances were not restarted, and no real agent or shell was stopped.
+
+The CLI acknowledges deletion before its asynchronous process cleanup ends;
+the native fixture does not prove live process termination. A CLI restart may
+retain the same agent/session identity; the new guard protects changed
+identities and observed deletion/recreation, not every same-agent restart.
+Requests for restart that began before Stop still need a separate lifecycle
+audit. Fork dialogs, settings, remaining onboarding, physical keyboard/IME,
+VoiceOver, and Linux runtime are further work. The broader goal remains active.
+
+## Terminal renaming and agent name consistency — preceding continuation
+
+Tab, agent, and machine rename now share `TerminalNamePrompt`: the same thin
+terminal frame, `name >` editor, monospace font, and local key guide. The whole
+name is selected once on opening. Immediate typing, native Done, readline
+editing, composition, live picker remapping, inline errors, and short-window
+layouts share one implementation. Tab names keep the 80-character limit, and
+each editor has a specific accessible name.
+
+Rename Agent is now a command-search action for the focused owned agent. It
+can be assigned a key without taking a default chord away from the terminal.
+The existing double-click path uses the same editor. Its delayed focus timer
+was removed: that timer could reselect a name after the user had begun typing.
+The direct title path is tested with background terminal output while editing.
+Native Rename Tab acknowledges the visible input before awaiting its value.
+Custom tab names remain independent of agent names.
+
+Agent rename requests now belong to the model. Reopening joins a pending
+request with read-only input, repeated Enter cannot duplicate it, competing
+names are rejected, and different agents remain independent. Failures release
+busy state and retain the draft for retry. The CLI's returned name is used
+when present; timeout text distinguishes an unconfirmed result from a refusal.
+Inspection of `cli/src/backendSocket.ts` confirms that `agent_update` replies
+with the updated agent and broadcasts `agent_renamed`.
+
+Late replies cannot rename a replacement machine, a different agent session,
+or a deleted/recreated ID. Auth changes and disposal invalidate outstanding
+requests. A newer observed name cannot be rolled back by an earlier request
+receipt or inventory read. Fresh inventory and sync events now update every
+open pane title, which previously required a separate rename event. Background
+agent inventory also checks the machine/auth identity before applying a reply.
+
+Verification:
+
+- Focused rename, manager, commands, and focus regressions: **89 passed**. Log:
+ `/private/tmp/terminal-renaming-focused-final.log`.
+- New model and keyboard regressions: **16 passed** independently. Log:
+ `/private/tmp/terminal-renaming-new-tests.log`.
+- Final full desktop suite: **2,196 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-renaming-suite-final.log`. The first full run found
+ two focus tests still locating the removed `AlertDialog`; their editor
+ finders now use the stable tab-name key, preserving their focus assertions.
+- Native macOS workspace fixture: **6 passed**. The new journey renames a tab
+ and agent through command search, closes/reopens a pending save, retries a
+ refused save, uses Ctrl-W, and returns input to the original terminal. Traffic
+ is entirely simulated. Log: `/private/tmp/terminal-renaming-native-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-renaming-analyze-final.log`.
+- **76 rendered states** in `/private/tmp/terminal-renaming-final`; all seven
+ new rename states were inspected, including errors, pending work, and 480×360
+ with 1.7× text. The refactored machine rename was also inspected at ordinary
+ and enlarged text sizes. Log: `/private/tmp/terminal-renaming-render-final.log`.
+- All fifteen touched Dart files are formatted; `git diff --check` passes.
+
+The normal macOS app is rebuilt after native testing with explicit
+`--target lib/main.dart`, also confirmed in generated configuration. Artifact:
+`build/macos/Build/Products/Debug/Harness.app`. Build log:
+`/private/tmp/terminal-renaming-macos-build-final.log`. Existing user app
+instances remain untouched.
+The broader product goal remains active; stop/fork dialogs, settings,
+onboarding, physical keyboard/IME, VoiceOver, and Linux runtime remain useful
+next audits.
+
+## Machines Manager and account edits — preceding continuation
+
+Machines Manager now uses the terminal frame and font, a `machine >` filter,
+compact naturally ordered rows, and a contextual key guide. This computer comes
+first; presence, linking, shared access, and agent counts remain distinct.
+Search includes names, hostnames, IDs, and status. Direct matches outrank loose
+fuzzy matches, and background updates retain the selected row.
+
+Enter opens an `action >` list. Escape restores the machine query, then returns
+to the terminal. Nested rename, delete, password, and link prompts hide the
+parent panel and restore its action query and editing connection afterward.
+The live picker keymap follows every nested route. Refresh keeps the input
+focused and reports errors in place. Small windows scroll the body while the
+input and footer stay visible; prompt labels and text share a baseline.
+
+Rename uses a `name >` prompt with the current name selected. Native Done and
+keyboard submission retain focus for retries. Delete names its account-level
+effect and starts on Cancel. Shared machines explain their view-only access,
+and this computer cannot be deleted here. Successful linking reports the result
+even when the retained filter no longer matches an available action.
+
+Machine rename/delete requests now belong to the model. Identical pending
+requests join, competing edits are rejected, and reopening a prompt joins the
+existing operation. Failures retain the edited input or confirmation and offer
+a retry. Late replies cannot mutate a replacement machine or a different auth
+session. Successful deletion closes that machine's panes across this window's
+tabs; failed local stream cleanup does not repeat the committed account action.
+Terminal disposal runs even when stream close fails.
+
+An inventory response begun before an edit, or an offline cache response after
+it, can no longer restore an old name or deleted machine. Newer live inventory
+can still reflect another client's changes or a re-registered machine. This
+protection belongs to the current window/auth session and clears on auth reset.
+
+Verification:
+
+- Focused manager/menu/link/inventory set: **74 passed** before the final prompt
+ alignment and linked-status refinement; the final full suite includes those
+ changes and the linked-status assertion. Log:
+ `/private/tmp/terminal-machines-manager-focused.log`.
+- Final full desktop suite: **2,180 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-machines-manager-suite-final.log`.
+- Native macOS workspace fixture: **5 passed**. The added journey covers
+ commands → machine/action search → rename → pending reopen → delete/cancel →
+ pending reopen → retained terminal input. API responses and terminal traffic
+ are fake. Log: `/private/tmp/terminal-machines-manager-native-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-machines-manager-analyze-final.log`.
+- **69 rendered states** in `/private/tmp/terminal-machines-manager-final`.
+ All twelve new manager states were inspected, including pending/error views,
+ shared access, missing machines, and 480×360 at 1.7× text. Search and creation
+ previews were also checked. Log:
+ `/private/tmp/terminal-machines-manager-render-final.log`.
+- All twelve touched Dart files are formatted; `git diff --check` passes.
+
+The normal macOS review app is rebuilt after the native fixture with explicit
+`--target lib/main.dart`: `build/macos/Build/Products/Debug/Harness.app`.
+Generated configuration confirms the normal target. Build log:
+`/private/tmp/terminal-machines-manager-macos-build-final.log`.
+Existing user app instances remain untouched.
+
+The broader product goal remains active. Other secondary dialogs, settings,
+onboarding, and platform parity remain useful next audits. Native fixture keys
+are injected through Flutter; physical AppKit keyboard/IME, VoiceOver, Linux
+runtime, and live daemon behavior remain outside this evidence.
+
+## Local password and outgoing links — preceding continuation
+
+“This computer’s password” now uses the same thin terminal frame, transparent
+backdrop, monospace font, and local key guide as search and creation. The two
+masked prompts read `password >` and `again >`. Initial typing works immediately;
+Enter advances and then submits, native Next/Done keep focus, and Escape cancels
+an edit or returns to the chooser. Composition owns its keys. Readline editing,
+visibility controls, retry focus, and live remapping work across the nested
+route. The summary's focused control owns Enter after the input is removed.
+
+The machine chooser hides while a nested password prompt is open, leaving one
+visible panel. Returning restores its query, selection, and focus. Outgoing
+trust is a separate “Links from this computer” view, keeping it distinct from
+this computer's incoming password. Fingerprints and dates remain available.
+Clear and unlink confirmations focus Cancel first; errors remain visible and
+retryable. Short windows scroll the body while the key guide stays visible.
+
+Password mutations now belong to the model. Reopening joins a pending operation
+without retaining the closed password buffer; concurrent mutations are rejected.
+A late status read cannot overwrite a completed change, unexpected exceptions
+release busy state, and disposed/auth-stale replies cannot update current state.
+Linked-machine refreshes coalesce, retain known rows on failure, and show errors.
+Repeated unlink requests join; a failed refresh cannot restore a removed row.
+
+The old clear confirmation claimed existing remote access would be revoked.
+Inspection of `cli/src/lib/e2ee/manager.ts`, `store.ts`, and the CLI clear command
+shows that clearing removes the password verifier; established trust/sessions are
+separate. The UI and Dart API comment now accurately say that clearing prevents
+new password-based links and leaves existing links/sessions connected. No actual
+password, trust pin, or live agent was changed during verification.
+
+Verification:
+
+- Focused setup/password/keymap/boot set: **81 passed** before the final summary
+ ownership assertion; that assertion also passed in the final full suite. Log:
+ `/private/tmp/terminal-local-password-focused.log`.
+- Final full desktop suite: **2,161 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-local-password-suite-final.log`.
+- Native macOS workspace fixture: **4 passed**, including a new commands →
+ chooser → set password → pending reopen → change/cancel → retained terminal
+ journey. All CLI responses and terminal traffic are fake. Log:
+ `/private/tmp/terminal-local-password-native-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-local-password-analyze-final.log`.
+- **57 rendered states** in `/private/tmp/terminal-local-password-final`.
+ All eight new states were visually inspected: initial, pending, failed, set,
+ clear, outgoing links, unlink, and 480×360 with 1.7× text. Log:
+ `/private/tmp/terminal-local-password-render-final.log`.
+- All nine touched Dart files are formatted; `git diff --check` passes.
+
+The normal macOS review artifact is rebuilt after the native fixture with
+`--target lib/main.dart`: `build/macos/Build/Products/Debug/Harness.app`. Build
+log: `/private/tmp/terminal-local-password-macos-build-final.log`. Existing user
+app instances remain untouched. Physical AppKit input/IME, VoiceOver, Linux
+runtime, and live daemon behavior remain outside the fake-fixture evidence.
+The broader product goal remains active; Machines Manager, other settings and
+onboarding surfaces, and platform parity remain useful next audits.
+
+## Machine chooser and terminal setup guides — preceding continuation
+
+“Link machine” now starts with a compact `machine >` chooser instead of two
+large installation cards. It searches machine names and setup actions, shows
+presence separately from trust, and puts direct matches before loose fuzzy
+matches. Existing machines can go straight to password entry. Desktop and
+SSH setup are explicit choices; already-linked machines explain how to open
+their agents. The local computer is excluded from the remote list.
+
+Both setup guides use the terminal frame and monospace text. Commands and the
+download URL are selectable, all actions are keyboard focusable, and Tab
+reveals controls even in short windows at enlarged text sizes. Clipboard
+errors offer retry; commands are only copied, never executed. The desktop
+guide points to the current command-palette path, and the local password
+dialog was accurately titled “This computer’s password”. Its subsequent visual
+and interaction audit is recorded above.
+
+Machine arrivals preserve the selected row and do not fold away an open guide.
+Escape returns from a guide to the original query, then closes the chooser.
+Nested password dialogs return to that query as well. Refresh remains
+available in every stage, coalesces repeated requests, and preserves focus and
+filtering on failure. Active composition retains ownership of its keys.
+
+The chooser carries the live keymap across both direct workspace and Machines
+Manager routes. Navigation, accept, cancel, traversal, and refresh use picker
+bindings. A new `picker.refresh` command defaults to Cmd-R/Ctrl-R; only the
+machine chooser supplied its action at this stage. Custom bindings take precedence in hints.
+The configured accept key activates focused guide controls. An unbound Enter
+or Escape cannot fall through and open/close the search anyway. Live binding
+updates, disabled defaults, both route paths, and Linux refresh are tested.
+
+Verification:
+
+- Focused setup/keymap/boot/manager set: **64 passed**. Log:
+ `/private/tmp/terminal-machine-setup-keymap-checks.log`.
+- Final full desktop suite: **2,147 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-machine-setup-suite-final.log`.
+- Native macOS workspace fixture: **3 passed**. Its linking journey now uses
+ the actual command palette and machine chooser to reopen a pending request,
+ verifies the retained query after linking, and returns input to the original
+ terminal. Traffic remains entirely simulated. Log:
+ `/private/tmp/terminal-machine-setup-native-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-machine-setup-analyze-final.log`.
+- Forty-nine rendered states in `/private/tmp/terminal-machine-setup-final`.
+ All five new machine chooser/guide states were inspected, including an empty
+ result and the SSH guide at 600×420 with 1.7× text. Log:
+ `/private/tmp/terminal-machine-setup-render-final.log`.
+- Formatting of all eleven touched Dart files and `git diff --check` passed.
+
+The normal macOS debug app rebuilt with `--target lib/main.dart` after the
+native fixture: `build/macos/Build/Products/Debug/Harness.app`. Log:
+`/private/tmp/terminal-machine-setup-macos-build-final.log`. Existing app
+instances were not restarted. Work remains uncommitted and unpublished.
+Widget platform variants establish the Linux key behavior; Linux runtime,
+physical AppKit keyboard/IME, VoiceOver, and real daemon setup remain unverified.
+The broader product goal remains active.
+
+## Terminal machine linking and connection ownership — preceding continuation
+
+The remote-password entry now shares search and creation's thin, top-anchored
+terminal frame, monospace text, transparent backdrop, and compact key guide.
+The target machine appears above a `password >` input. The body scrolls in
+short windows while the recovery instructions remain visible. Troubleshooting
+details stay optional, and the prompt follows terminal-font changes.
+
+The keyboard audit reproduced two focus failures. Native Done unfocused the
+input, leaving Escape outside the prompt's handler while connecting. The
+dialog's fallback autofocus also took focus before its password editor, which
+the native fixture and a separate widget reproduction both caught. Done now
+retains focus; the prompt explicitly claims initial input after mounting.
+Enter submits from the input, Tab reaches controls, Escape returns to the
+original terminal, and active composition owns Enter/Escape. Shared readline
+editing works in the password field and is disabled while connecting. Errors
+are announced and return focus for a keyboard retry.
+
+Connection attempts now belong to `AppNotifier`, keyed by machine and auth
+revision. Reopening the prompt joins the same pending future without copying
+the old prompt's password or launching another CLI request. Progress remains
+visible, repeated Enter is ignored, and different machines proceed
+independently. Unexpected link-process exceptions release the busy state and
+offer retry. Disposed or stale-auth replies cannot update the current workspace.
+The CLI remains responsible for the actual password exchange.
+
+Verification:
+
+- Focused linking/boot/reconnect/offline set: **41 passed**. Log:
+ `/private/tmp/terminal-link-final-checks.log`.
+- Full desktop suite: **2,137 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-link-suite.log`.
+- Native macOS workspace fixture: **3 passed**, including retry, close/reopen
+ while pending, automatic close on success, and input returning to the same
+ retained terminal. All traffic is fake. Log:
+ `/private/tmp/terminal-link-native-workspace.log`.
+- The dialog-focus regression failed before its fix; reproduction log:
+ `/private/tmp/terminal-link-dialog-focus-before.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Includes
+ both native fixtures. Log: `/private/tmp/terminal-link-analyze-final.log`.
+- Forty-four rendered states in `/private/tmp/terminal-link-final`. The four
+ new link states (ready, pending, error, and 600×420 at 1.7× text) were
+ inspected, along with the current chooser and creation prompt. Log:
+ `/private/tmp/terminal-link-render-final.log`.
+- The normal macOS app rebuilt successfully with `--target lib/main.dart`
+ after native testing. Log: `/private/tmp/terminal-link-macos-build.log`.
+- Formatting of all six touched Dart files and `git diff --check` passed.
+
+Artifact: `build/macos/Build/Products/Debug/Harness.app`. Existing app instances
+were not restarted. Physical AppKit keyboard/IME, VoiceOver, Linux runtime,
+and live daemon behavior remain outside this fixture evidence. The separate
+“Link another machine” setup guide and this computer's password-management
+dialog still need an interaction audit. Work remains uncommitted and
+unpublished; the broader product goal remains active.
+
+## Native workspace journey and prompt editing — preceding continuation
+
+Output Find still had a rounded, proportional-font toolbar. It now uses the
+same thin terminal frame and monospace family as search and creation, with a
+`/` prompt and match count. It occupies the existing header, so opening Find
+does not resize or reflow terminal output. Narrow panes and larger text sizes
+put match controls in a compact keyboard menu, keeping the query readable.
+Enter activates a focused control; Enter/Shift-Enter step matches from the
+query. The menu closes with Find or its pane, and Escape restores typing.
+
+The shared prompt editing audit reproduced six failures before the fix:
+Ctrl-H/D could split emoji or combining characters on macOS and Linux, Ctrl-W
+could erase a word on the preceding task line, and Ctrl-U erased all preceding
+lines. Character deletion now uses grapheme boundaries, word kill respects
+whitespace/path separators, and line kill stops at the current line's start.
+Ctrl-Y restores the killed text. These keys also work in output Find, with
+query updates isolated from terminal input. Composition and locked prompts
+remain protected.
+
+The new native workspace fixture runs a real macOS window/titlebar around
+fake sessions and a fake creation connection. Its two keyboard journeys cover:
+
+- Staying at the current scrollback location while output streams; searching
+ output and returning to the original location and terminal input.
+- Opening a shared agent in a named tab, closing/reopening it, switching panes,
+ moving a pane, zooming, resizing, and retaining the original terminal view.
+- Editing a multiline task and inherited agent/project/mode, dismissing and
+ resuming the draft through New Pane, checking the exact simulated creation
+ request, and immediately finding that agent to name a new tab.
+
+Both native fixtures now require `FLUTTER_TEST=1`. They never bootstrap the
+real CLI or load real Harness state. `CLAUDE.md` documents their invocation
+and the required normal-app rebuild afterward. Injected Flutter keys do not
+establish physical AppKit keyboard/IME or VoiceOver behavior.
+
+Verification:
+
+- Focused prompt/Find/creation set: **50 passed**. Log:
+ `/private/tmp/terminal-prompt-find-checks.log`.
+- Full desktop suite: **2,131 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-workspace-suite.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Includes
+ both native fixtures. Log: `/private/tmp/terminal-workspace-analyze-final.log`.
+- Native terminal fixture: **2 passed**. A combined run then failed to launch
+ its second test app before any workspace assertion ran. Log:
+ `/private/tmp/terminal-workspace-native.log`.
+- Running the native workspace fixture independently: **2 passed**. Log:
+ `/private/tmp/terminal-workspace-native-workspace.log`. Use separate native
+ invocations, as documented in `CLAUDE.md`.
+- Forty rendered states in `/private/tmp/terminal-workspace-final`; the three
+ new Find states at normal/enlarged text and with keyboard options open were
+ inspected. These use fake terminal output, not a live PTY. Log:
+ `/private/tmp/terminal-workspace-render.log`.
+- Formatting of all eight touched Dart files and `git diff --check` passed.
+
+The normal macOS debug app rebuilt successfully with `--target lib/main.dart`
+after the native fixtures. Artifact: `build/macos/Build/Products/Debug/Harness.app`.
+Build log: `/private/tmp/terminal-workspace-macos-build.log`. Existing app
+instances were not restarted. Work remains uncommitted and unpublished. The
+broader product audit remains active.
+
+## Clipboard ownership and Linux shell input — preceding continuation
+
+The terminal audit reproduced three input failures: Linux Ctrl-A/Ctrl-V were
+intercepted for selection/paste, a delayed clipboard read could paste into a
+replacement agent, and an empty shell paste emitted Ctrl-V (quoted-insert).
+A follow-up reproduction showed Linux Alt word-motion keys emitted no input.
+
+- Linux clipboard keys are Ctrl-Shift-C/V/A. Ctrl-A/B/C/D/R/V/Z reach the
+ program unchanged. The shortcut guide now names Linux's actual copy/paste/
+ select-all chords. Other existing platform clipboard shortcuts are unchanged.
+- Linux sessions use xterm's Linux input target. Left-Alt printable keys send
+ an escape prefix with the actual character, preserving case, punctuation,
+ and numeric arguments. The fallback letter handler now respects Shift.
+ macOS Option and Linux AltGr remain native text composition.
+- Paste captures its target session and stream before reading the clipboard.
+ It revalidates ownership after text and image reads, cancelling if the pane
+ changes agents, reconnects, closes, or becomes read only. A pending paste
+ cannot follow a reused pane to a different agent.
+- Empty clipboard content sends no quoted-insert to a shell. Clipboard read
+ errors show a local retry message without freezing the stream. Paste clears
+ the old selection. Read-only output can still be copied, older daemons retain
+ bracketed paste, and Linux's paste chord reaches remote image upload.
+- The vendored xterm patch is documented in
+ `third_party/xterm/README.autonomous.md`. Protocol behavior remains covered
+ by the existing session tests; the new UI tests record actual outgoing input,
+ paste, and image-upload frames using fake sessions and an in-memory clipboard.
+
+Verification:
+
+- Focused input/clipboard/IME/shortcut set: **60 passed**. Log:
+ `/private/tmp/terminal-input-final-checks.log`.
+- Full desktop suite: **2,122 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-input-suite.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Includes
+ the native terminal fixture. Log: `/private/tmp/terminal-input-analyze-final.log`.
+- Native macOS fixture: **2 passed**. Log:
+ `/private/tmp/terminal-input-native.log`. It exercised streamed keyframe
+ replacement, alternate-buffer scroll routing, Unicode input injection, and
+ switching across eleven agents while retaining exactly one terminal view.
+ It ran in its own process with `FLUTTER_TEST=1`, fake terminal senders, no
+ AppNotifier bootstrap, and no real agent traffic. The SDK desktop runner was
+ inspected: it tracks and stops only processes it launches. Existing app
+ sessions were not restarted.
+- This native fixture does not establish physical AppKit keyboard/IME behavior,
+ VoiceOver behavior, a complete workspace walkthrough, or Linux runtime parity.
+ Those remain outstanding. Earlier `cgWindowNotFound` capture failures still
+ apply to the attempted walkthrough of the existing app window.
+
+The normal macOS debug app was rebuilt successfully with `--target lib/main.dart`
+after the native fixture. Artifact: `build/macos/Build/Products/Debug/Harness.app`.
+Build log: `/private/tmp/terminal-input-macos-build.log`. The final clipboard
+checks passed all 14 tests after analyzer cleanup
+(`/private/tmp/terminal-input-final-clipboard.log`); formatting of all seven
+touched Dart files and `git diff --check` passed. Work remains uncommitted and
+unpublished.
+
+The broad product goal remains active; terminal selection/scrollback and the
+other product areas still need the end-to-end review tracked in the audit.
+
+## Workspace arrangement and compact pane headers — preceding continuation
+
+Directional pane moves previously removed and reinserted a pane, shifting
+unrelated neighbors and bypassing pinned-slot updates. They now use the same
+swap operation as direct reordering, keep pins with their panes, and request
+visibility for the moved terminal. Shift-Cmd-arrows stop at the layout edge;
+the existing wrap behavior for directional focus is unchanged.
+
+- The Flutter tab strip now reveals the selected tab after keyboard selection,
+ closing, reordering, and window resizing. Background updates preserve a
+ deliberately scrolled strip. The native strip already had reveal behavior.
+- Keyboard resize uses a compact monospace guide. Arrow keys resize, Shift
+ takes larger steps, Tab changes divider, and Escape returns to terminal input.
+- Narrow pane headers prioritize a monospace agent name and machine identity.
+ Extra project/branch detail remains in the tooltip. Model selection has a
+ compact trigger; other actions move into an arrow/Enter/Escape menu. Wider
+ headers retain their direct controls. Hover does not shift the title.
+- Reconnect/take-control remains directly accessible at narrow widths.
+ Enlarged text no longer lets the action row reduce the title to zero width.
+ Header typography follows changes to the terminal font preference.
+- The model menu now uses the thin terminal prompt frame, clamps to the actual
+ window bounds, and scrolls when necessary. It owns focus, supports arrows and
+ Enter, restores focus after Escape/selection, and dismisses on native chrome
+ actions. Its Open Grid action is keyboard focusable. Outside clicks continue
+ to reach the control beneath the menu.
+
+Focused verification: **50 passed** for headers, model menus, arrangement, and
+resize; **71 passed** for viewer and terminal-session regressions. Logs:
+`/private/tmp/terminal-arrange-final-checks.log` and
+`/private/tmp/terminal-arrange-regression-checks.log`.
+
+The first full suite exposed a viewer assertion that expected the now-collapsed
+icons, plus a resync timeout test that raced a 45 ms wall-clock delay. The viewer
+check now opens the real compact menu. The resync test uses the widget test's
+controlled clock and retains its exact three-retry/one-reopen/failure assertions;
+no production timeout changed.
+
+Render verification: 37 states in `/private/tmp/terminal-arrange-final`, including
+four-pane resize, many tabs, compact actions, and model menus at 600 px / 1.7×
+text. The new states were inspected. The fixture exercises workspace chrome
+with fake sessions and matching agent metadata; no real PTY or agent is started.
+Log: `/private/tmp/terminal-arrange-render.log`.
+
+Final verification:
+
+- Full desktop suite: **2,108 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-arrange-suite-final.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-arrange-analyze-final.log`.
+- macOS debug build succeeded with Swift Package Manager. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-arrange-macos-build-final.log`.
+- Formatting (13 touched Dart files) and `git diff --check` passed. Existing
+ app instances were not restarted; native runtime and VoiceOver checks remain
+ outstanding. No changes were committed or published.
+
+The broad product goal remains active. Native runtime, terminal correctness,
+and remaining product areas are still tracked in the product audit.
+
+## Draft ownership and visible recovery keys — preceding continuation
+
+The canceled compact prompt previously saved only a global task string. A
+reproduction showed that reopening from another project put that task in the
+wrong context, and canceling after an advanced-form round trip lost the chosen
+Codex profile. It also reset the edited machine, project, and permissions.
+
+- Drafts now retain the complete setup in memory for their source machine,
+ agent, and project. Separate agents working in the same project have separate
+ buffers, as do machines with identical folder paths. The buffers last for the
+ current window. They are not persisted across app restarts.
+- An empty chooser or Cmd-N resumes that source's draft. Explicit search text
+ starts a fresh task with inherited defaults. Clearing the task removes it;
+ successful creation consumes only that source's draft. Advanced options keeps
+ the original source context through edits and returns.
+- An unsubmitted draft honors the newly chosen New Tab/New Pane destination.
+ A dismissed unresolved creation retains its original receipt, even with no
+ task. Resuming sends `agent_create_status` with that same creation ID and
+ completes at the original destination. It does not launch another agent.
+- Errors previously replaced all key hints. They now retain the available keys
+ underneath. A pending prompt says `pending agent` and exposes check status
+ and close; editing and advanced-options hints are omitted. Busy requests show
+ progress. All message text uses the shared monospace styling.
+- The dismissed receipt carries its warning acknowledgement so an existing
+ “Escape again” message still means what it says after reopening.
+
+Focused tests: **60 passed** including the render fixture, and **30 recovery
+checks passed** after preserving the warning acknowledgement. Exact outgoing
+requests cover clone URLs, profiles, permissions, first task, placement, and
+receipt identity. Logs: `/private/tmp/terminal-context-final-checks.log` and
+`/private/tmp/terminal-context-recovery-checks.log`.
+
+Render verification: 31 states in `/private/tmp/terminal-context-final`, adding
+pending creation and reopened pending creation at 600 px / 1.7× text. Both new
+states were inspected. The fixture simulates a timeout through its overridden
+connection; no real agent creation or daemon traffic is involved.
+
+Final verification:
+
+- Full desktop suite: **2,102 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-context-suite.log`.
+- Analyzer: no errors or warnings; the same three preexisting infos. Log:
+ `/private/tmp/terminal-context-analyze-final.log`.
+- macOS debug build succeeded with Swift Package Manager. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-context-macos-build.log`.
+- Formatting and `git diff --check` passed. Existing app instances were not
+ restarted; native runtime and VoiceOver verification remain outstanding.
+
+The broad product goal remains active. This completes the scoped draft audit;
+the remaining product areas are listed below and in the product audit.
+
+## Mixed catalogs and workspace navigation — preceding continuation
+
+Compact search now names the agent and machine before the project and branch.
+Removing provider logos had left otherwise identical Codex and Claude tasks
+indistinguishable without a preview. The plain-text identity also uses discovered
+agent names such as Robot Studio. Existing domain metadata remains searchable.
+
+- Wide results stay on one line. Narrow results, enlarged text, and the list
+ beside a preview put identity on a second line. Row height follows the actual
+ text size, and the selected row stays visible when preview or geometry changes.
+- Commands and shortcut help now say Next Tab, Previous Tab, and Select tabs.
+ History says Reopen Closed Tab or Pane in both the palette and native menu.
+ Existing IDs and bindings are unchanged.
+- A complete keyboard journey verifies finding a specific agent among duplicate
+ task names, opening a shared tab, closing and reopening it, tab and pane
+ switching, zoom, and closing/reopening a pane. The same running sessions survive
+ every transition, and picker keys do not reach terminal input.
+
+Verification:
+
+- Full desktop suite: **2,098 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-catalog-suite.log`.
+- Analyzer: no errors or warnings; the same three existing infos. Log:
+ `/private/tmp/terminal-catalog-analyze.log`.
+- Render fixture: 29 states in `/private/tmp/terminal-catalog-final`, including
+ mixed local/remote/offline agents, duplicate tasks, preview, and 600 px with
+ 1.7× text. These states were visually inspected. Log:
+ `/private/tmp/terminal-catalog-final-render.log`.
+- macOS debug build succeeded. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-catalog-macos-build.log`.
+
+The narrow-preview test waits for the scheduled post-layout scroll before
+inspecting the selected row's viewport bounds. The keyboard journey lets the
+terminal's existing 50 ms resize debounce finish before teardown. No production
+timer or scrolling change was required for those two test timing corrections.
+Native app interaction remains unverified; existing app instances were not
+restarted and no real agents were created.
+
+## Draft recovery and picker ownership — preceding continuation
+
+Advanced options now returns to the compact task prompt with the complete
+edited draft. Escape, the back hint, and an outside click retain the task,
+machine, agent, project or clone intent, permission mode, and Codex profile.
+An explicit Default profile remains default even when discovery finds one
+named profile. The compact prompt displays the selected profile; changing
+machine or agent clears it before the next launch.
+
+- An unresolved creation keeps its original receipt across the return. Enter
+ checks that request instead of sending another create. Pending input is
+ read-only, including the custom readline editing keys. Busy requests still
+ prevent dismissal.
+- A dialog pop could complete before the screen's cached route flag updated,
+ suppressing the returning prompt. The open guard now reads the live route.
+- The advanced agent picker previously let Cmd-Enter reach the parent form
+ and launch its old selection. It now accepts the highlighted agent; an
+ unbound modified Enter cannot submit the parent form. IME composition does
+ not choose an agent, dismiss the picker, or launch a request.
+- The form now receives the workspace's live keymap. Picker remappings,
+ unbindings, aliases, and visible hints remain effective after opening the
+ separate dialog route, including config changes while it is open.
+- The agent picker measures its anchor and available space during layout,
+ replacing the snapshot taken when it opened. Resizing or changing text size
+ keeps the panel, input, preview, and key guide inside the window. The result
+ list gives up space before the input or key guide does.
+
+Focused verification: **48 tests passed**, including exact creation payloads,
+receipt recovery, profile round trips, real workspace key dispatch, IME,
+remapped keys, and narrow/short/enlarged-text layouts. Log:
+`/private/tmp/advanced-agent-final-checks.log`.
+
+Render verification: 25 isolated macOS fixture states passed and were written
+to `/private/tmp/terminal-draft-preview`; the returned draft, enlarged draft,
+and resized agent searches were inspected. The fixtures reject real agent
+creation. Native app interaction remains unverified for the reason below.
+
+Final verification:
+
+- Full desktop suite: **2,094 passed, 5 skipped, no failures**. Log:
+ `/private/tmp/terminal-draft-suite.log`.
+- Analysis of `lib` and `test`: no errors or warnings; the same three
+ preexisting informational lints. Log:
+ `/private/tmp/terminal-draft-analyze-final.log`.
+- Formatting and `git diff --check` passed.
+- macOS debug build succeeded with Swift Package Manager. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-draft-macos-build.log`. Existing native app instances
+ were not restarted. No real agent was created for verification.
+
+The broad product goal remains active. This pass completes the draft/back and
+nested-picker audit; the remaining areas are listed below and in the product
+audit.
+
+## Creation integrity and terminal forms — preceding continuation
+
+Advanced options now shares the compact terminal appearance: an 840 px
+top-anchored thin frame, monospace text, full-width machine/project choice rows,
+small controls, and a visible keyboard guide. The backdrop stays clear. The
+agent selector uses a `>` prompt and Ctrl-/ preview toggle, preserves input
+focus, and supports readline editing and Page Up/Down. Provider descriptions
+and installation status remain available in the preview.
+
+- The compact prompt's key guide wraps instead of hiding later hints offscreen.
+ Creation sizes itself from the actual fields, editor, and guide. Long task
+ text scrolls in its editor at the available height, keeping actions visible.
+- Advanced handoff preserves named new projects, clone requests, existing
+ folders, permission modes, and the first task. A successful full-form launch
+ consumes the saved task. Tests inspect the resulting creation request.
+- Explicit project choices survive switching to another machine and back in
+ advanced options. The dialog's per-machine choice bucket includes inherited
+ choices and new-project names.
+- Outside-click and keyboard dismissal now share the compact prompt's pending
+ creation guard; a lost receipt cannot be bypassed by clicking outside.
+- Numbered agents, projects, and folder completions use natural ordering after
+ search score and recency (`1, 2, 10`). The already-resolved collection package
+ is now an explicit dependency; no package version changed.
+- The form's agent picker changes selection only when the pointer moves;
+ rebuilding or scrolling beneath a parked pointer leaves keyboard selection
+ alone.
+
+Verification:
+
+- Full desktop suite: **2,083 passed, 5 skipped, no failures**, recorded in
+ `/private/tmp/terminal-refinement-suite-final.log`.
+- Earlier in this continuation, the handoff/order changes alone passed 2,082
+ tests. Focused checks exercise narrow and enlarged-text layouts, multiline
+ tasks, actual creation payloads, machine round trips, and preview toggling.
+- After visual review corrected the two-line agent row height, all **27 focused
+ picker/form tests passed**. The responsive tests verify that both text lines
+ remain inside each row's selection bounds. Log:
+ `/private/tmp/terminal-final-picker-tests.log`.
+- Final analysis of `lib` and `test`: no errors or warnings; the same three
+ preexisting informational lints. Log:
+ `/private/tmp/terminal-refinement-analyze-final.log`.
+- macOS render fixtures passed and produced the final screenshots in
+ `/private/tmp/terminal-final-preview`, including advanced options, agent
+ search and preview, and narrow/large-text forms. The fixture uses an isolated
+ connection and rejects agent creation. Inspected representative search,
+ creation, advanced, and large-text states, and corrected the row-height
+ issue found during that review.
+- Final macOS debug build succeeded with Swift Package Manager. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Log:
+ `/private/tmp/terminal-refinement-macos-build.log`. Existing app instances
+ were not restarted during this continuation.
+- Native UI inspection remains unavailable: the selected app returned
+ `cgWindowNotFound`, and inventory reports multiple OpenHarness entries.
+ Render fixtures and keyboard tests do not claim a live native walkthrough.
+
+The ongoing product audit is in [terminal-product-audit.md](terminal-product-audit.md).
+
+## Terminal appearance and interaction — preceding continuation
+
+The search and creation overlays now use the terminal font family, a thin
+border, compact rows, text prompts, and an ASCII key guide. Large provider
+marks, rounded cards, repeated row-action buttons, and the creation explanatory
+paragraph/button were removed from these overlays. The workspace stays visible.
+
+- New Tab/New Pane search starts with a compact list and a `>` prompt. The
+ New agent row stays above matches; its detail carries any proposed first task.
+ A match count is always visible.
+- Ctrl-/ toggles the preview. Its text and status are also compact and monospaced.
+ Once opened, its geometry stays stable while navigating, including the create
+ row, so Tab traversal does not lose its place.
+- Page Up/Down page results when preview is hidden, or scroll the preview when
+ shown. Escape/Ctrl-C dismiss the picker; Ctrl-C still reaches the terminal
+ after dismissal. All bindings remain scoped and remappable.
+- Creation exposes labeled agent, machine, mode, and project defaults above
+ `task >`. Tab edits defaults through the same prompt; Enter chooses an option
+ and returns to the task. Existing path completion, drafts, receipt recovery,
+ and cancellation guards remain. Defaults stack with narrow/large-text layouts.
+- The command palette has a `:` prompt and an empty input instead of a second
+ `>` inside the editor.
+- [Design references and interaction rules](super-terminal-interaction.md)
+ record the studied fzf, zsh, Vim, tmux, and Lazygit patterns.
+
+Verification:
+
+- Full desktop suite: **2,075 passed, 5 skipped, no failures**.
+- After the final hidden-preview paging addition: **88 targeted tests passed**,
+ including creation, placement, preview paging, input ownership, remapping,
+ cancellation, and terminal key routing.
+- Analysis of `lib` and `test`: no errors/warnings; the same three preexisting
+ informational lints in app_state, grid_model_picker, and pane_grid.
+- Rendered and inspected search, creation, defaults, preview, command palette,
+ and large-text/narrow layouts. The render fixture uses Menlo for the terminal
+ font aliases; runtime uses the user's terminal font. PNGs are in
+ `/private/tmp/terminal-box-preview`.
+- macOS debug build succeeded with Swift Package Manager. Artifact:
+ `build/macos/Build/Products/Debug/Harness.app`. Opened a fresh review instance
+ with `open -n`; existing instances were not stopped. No real agent was created
+ during verification.
+
+## New Tab / New Pane — built after the design discussion
+
+The primary choice is now where to put the work:
+
+- **⌘T / New Tab** opens the harness picker with a pending new-tab destination.
+- **⌘P / New Pane** opens the same picker for the current tab, automatically
+ tiling after an addition. From the Store or Orchestrator it offers a new tab.
+- Both show a pinned **New agent** row, selected with an empty query.
+ Typing selects the best existing match and carries the text into the first
+ task if New Harness is chosen. Projects, machines, and tab names are searchable
+ metadata; the results are individual harnesses, with no bulk group actions.
+- New Tab allocates only after choosing an existing harness or receiving a
+ successful creation receipt. Cancellation, failures, and pending recovery
+ leave the layout alone. A recovered receipt allocates exactly once.
+- A tab opened through New Tab takes the chosen or newly created agent's name.
+ Adding/focusing panes preserves an existing tab name, including custom names.
+- A harness can appear in multiple tabs. Within a tab it appears once:
+ choosing a harness already there focuses its pane. Views share the session,
+ and closing one view leaves the others intact.
+- The picker and creation actions show the destination. Existing creation
+ inheritance (agent, machine, project) remains, including multiple feature
+ harnesses on the same project and panes from different machines.
+- Native and Flutter tab strips now have New Tab and New Pane controls. The
+ File menu follows the same model. Directional split edges were removed;
+ directional splits and Orchestrator remain in the **⇧⌘P** command palette,
+ without default directional/orchestrator bindings. **⌘N** remains a secondary
+ direct-creation shortcut. Existing command IDs remain remappable.
+- A pending creation cannot be replaced by another picker or the full form.
+ Cancellation after transitioning from search restores terminal focus rather
+ than focusing the disposed search editor. The full form receives the pending
+ destination and task.
+
+The placement intent is `lib/state/harness_placement.dart`. Regression coverage
+is in `test/harness_placement_test.dart`, with existing entry, keymap, shared
+session, layout, and recovery tests updated for the new behavior. Keyboard
+documentation is in `../docs/keyboard.md`.
+
+### Verification of this implementation
+
+- Desktop suite: **2,074 passed, 5 skipped, no failures**. The old pane-control
+ count assertion now includes the existing Fork button.
+- Final analysis of `lib` and `test`: no errors or warnings; the same three
+ existing informational lints. The final cleanup subset also passed (68 tests).
+- Focused tests cover successful, failed, and recovered creation; retained
+ context and task; cancellation; shortcut/focus recovery; cross-machine panes;
+ shared views; duplicate selection; full tabs; and stale results.
+- Rendered and inspected the New Tab and New Pane pickers, matching/no-match
+ results, creation destination, permission selection, and separate command
+ palette. Fixture glyph substitutions remain as recorded below.
+- macOS debug build succeeded with Swift Package Manager. Final artifact:
+ `build/macos/Build/Products/Debug/Harness.app`.
+- Live creation against the user's running harnesses was not performed.
+
+## Earlier continuation work
+
+- Verified the final held-Tab fix through real key-down/repeat/up events in
+ the screen's keymap dispatcher. The chosen agent is committed once;
+ subsequent repeats preserve the machine and project. Existing controller
+ tests also cover a current machine absent from the choices and Escape
+ restoring a path-completion stem.
+- Search now puts openable matches before unavailable matches, preserving
+ ranking within each group and any explicitly selected row. Location-tree
+ ordering and the create row's position keep their existing contracts.
+- The search overlay measures its editor and hints before sizing the results
+ to whole rows. This works with side-by-side and stacked previews and larger
+ text. A create-only result uses exactly one row plus list padding.
+- Risky permission modes use amber text in the list and selected mode label.
+ Codex's choices read Read only, Ask first, Auto-approve, Full access. The
+ default remains Auto-approve by ID, verified in an actual form submission.
+- New-harness errors and creation status use explicit accessibility
+ announcements. Updates coalesce per frame, messages take precedence over
+ row announcements, and clearing an error allows it to be announced again.
+- Corrected the keyboard documentation: text carried from search becomes the
+ first task, not a new project name.
+
+Relevant additions: `test/box_polish_test.dart`. The implementation changes
+are in `state/swarm_search.dart`, `widgets/swarm_switcher.dart`,
+`screens/swarm_screen.dart`, `state/new_harness.dart`,
+`widgets/new_harness_box.dart`, `widgets/box_chrome.dart`, and
+`core/permission_modes.dart`, all under `lib/`.
+
+## Earlier verification
+
+Using Flutter 3.47.2 / Dart 3.13.2:
+
+- Before changes: 2,056 desktop tests passed, 5 skipped, 1 failed.
+- After changes: 2,064 desktop tests passed, 5 skipped, the same 1 failed.
+ The unchanged failure is `swarm_interactions_test.dart`, "pane controls
+ zoom, confirm stopping and close only this view": it expects six icon
+ buttons after a seventh Fork button was added on the base branch.
+- Static analysis of `lib` and the changed tests: no errors or warnings;
+ three existing informational lints in `app_state.dart`,
+ `grid_model_picker.dart`, and `pane_grid.dart`.
+- CLI: all 19 new-command/project-folder tests and TypeScript checking passed.
+- All 12 rendered box states were inspected. Known render-fixture artifacts
+ remain: some shortcut glyphs render as boxes and some logos load late.
+- The normal macOS debug app built successfully with Swift Package Manager.
+ Artifact: `build/macos/Build/Products/Debug/Harness.app`.
+- Live interaction with the newly built app and native VoiceOver have not
+ been verified. Accessibility tests verify emitted announcements.
+
+## Next work
+
+The broad product goal remains active. Next audits include pane moves and
+resizing, many-tab workflows, secondary dialogs, terminal correctness,
+reconnect/offline states, settings, and platform parity. Mixed-catalog identity,
+the keyboard close/reopen journey, and scoped draft ownership are verified
+above. Renamed/moved-project relinking still needs a design decision. Physical
+AppKit keyboard/IME, VoiceOver, Linux runtime, and live daemon verification
+remain outstanding; separate fake-traffic native fixtures are recorded above.
+
+The original handoff's independent terminal-reviewer re-review has not been
+run in this continuation; verification above was performed locally. Details
+and unresolved findings are maintained in `terminal-product-audit.md`.
+
+## First workspace guide and predictable harness entry — 2026-09-20
+
+Built the approved pared-down keyboard wallpaper as native Flutter line art:
+Cmd-T new tab, Cmd-P new pane, Cmd-S Harness Store, and the command dock. The
+callouts invoke the actual actions and read the active keymap. A small All
+keyboard shortcuts link opens the existing help sheet. The production empty
+workspace uses this guide; the old full-form compatibility path is retained.
+
+The first empty workspace automatically opens the real New Harness draft,
+with an editable `~/harnesses/first-project` destination. Machine-scoped engine
+detection chooses an installed agent, preferring a saved choice when available.
+Discovery does not overwrite an agent or machine the person has begun editing.
+No harness starts until Enter/click. A persisted marker keeps Escape dismissed;
+restored tabs or discovered existing harnesses bypass automatic entry.
+
+The creation/search vocabulary now calls the whole session a harness: New
+harness, Start harness, New harness…, and Find a harness…. The inner engine field
+remains agent. New Tab and New Pane still name placement.
+
+The New harness… action is pinned outside the scrolling search matches, across
+the dock width directly above the input. Typing, clearing, scrolling, and
+preview changes leave it there. Typed queries still select their best match;
+Down reaches creation. Preserved result state across preview changes fixes
+keyboard focus being lost during Tab traversal.
+
+Cmd-S opens Harness Store. Layout is Cmd-Shift-L, including the native menu;
+Cmd-L remains focus right. Shortcut help and the guide follow remaps.
+
+Validation: 95 focused unit/widget/render checks passed; two native macOS
+journeys passed (first workspace and edited creation/placement). Static analysis
+of changed production code and new fixtures is clean. Dart-to-AppKit export and
+130 native keymap checks passed. The subsequent legacy titlebar harness cannot
+compile: stale `openButton`, `createButton`, and `managerCaption` references in
+`tool/swarm_titlebar_checks.swift`. It was not changed for this task.
+
+The first native fixture exposed that local creation prepares its project folder
+before sending agent_create. Its empty first-project test folder was removed,
+and the fixture now overrides folder preparation with an in-memory path. No
+real agent was created. The native fixtures' injected Flutter keys do not prove
+physical AppKit/IME event delivery.
+
+Rebuilt the normal `lib/main.dart` debug app with the existing JEV endpoint
+`http://127.0.0.1:18478`, verified its code signature, and opened it. No commits or
+pushes. Logs: `/private/tmp/harness-guide-{focused,native,native-keys,analyze,build}.log`.
+First-run render: `/private/tmp/harness-guide-render/first-harness.png`.
+
+## Entry polish, focus, titles, and Store — 2026-09-20 follow-up
+
+This supersedes the earlier guide and entry behavior above. Agent settings now
+live behind a small gear shown on hover/focus; permissions and Codex profiles no
+longer insert rows into the agent list. New Harness stays pinned above the
+search input. Labels use title case, the action reads Start, the optional task
+reads Add a task (optional), and typed tasks have no `task:` prefix.
+
+The welcome illustration is larger, with one tall pane on the left and two on
+the right, using Codex, Claude Code, and Grok examples. Tab, Pane, and Store
+callouts explain the concepts and are static. Only All Keyboard Shortcuts is
+clickable; it shows the current Cmd-/ binding. Removed the redundant command
+dock callout. Each visit to the empty workspace opens New Harness when there
+are no harnesses, or search when harnesses already exist. Escape stays dismissed
+for that visit. Empty first projects default to `~/harnesses/first-project`.
+
+Installed-agent detection now has a separate status beside Agent. Start stays
+labeled Start and cannot activate during detection. The visible snapshot tracks
+detection completion so a stale loading label cannot conceal an enabled action.
+
+Creation hands keyboard focus to the newly mounted terminal after closing the
+dock, with guards against stealing focus after navigation. Four native macOS
+fixture journeys pass, including New Tab and New Pane accepting input without
+a click. The fixture needed a valid protocol UUID to record encoded input.
+These injected Flutter keys do not establish physical AppKit/IME behavior.
+
+Automatic CLI labels display as Untitled Pane, and new tabs as Untitled Tab.
+Engine session titles take over until the user renames; explicit tab naming
+ownership and its source harness persist across layout restore and reopening.
+Placeholder labels are never sent to the CLI as explicit names.
+
+Store Open and Try this prompt invoke the workspace dock with the chosen
+harness, machine, and example task. The Store button is now a compact filled
+pill with an original six-color polymath mark, shared by its tab and History.
+The native button preserves keyboard focus, enabled state, and remapped shortcut
+tooltip; its normal, hover, and disabled states were rendered and inspected.
+Asset vector source: `tool/render_store_mark.swift`.
+
+Validation: 56 Store/navigation/title checks pass; agent settings, welcome,
+project context, command dock, and placement checks passed earlier in this
+follow-up. All four native creation/onboarding fixture journeys pass. Logs:
+`/private/tmp/harness-store-name-regression.log` and
+`/private/tmp/harness-settings-native.log`. Button preview:
+`/private/tmp/harness-store-preview/button.png`. No real harnesses were created
+by these fixtures, and no commits or pushes were made.
+
+The normal `lib/main.dart` review build was rebuilt with the existing JEV URL,
+passed `codesign --verify --deep --strict`, and was opened. Analysis has no
+errors or warnings; two pre-existing style infos remain in `app_state.dart`
+and `pane_grid.dart`. Build log: `/private/tmp/harness-final-build.log`.
+
+## Editable generated project defaults — 2026-09-20
+
+This supersedes the fixed `first-project` default above. The first-workspace
+draft shows a concrete name using the existing harness-and-date convention,
+for example `~/harnesses/codex-2026-09-20-17-22`. The timestamp is captured when
+the suggestion is made; Start uses the reviewed name even after a delay.
+Project → New Project prefills and selects the proposed name for replacement.
+Edited names remain explicit and survive agent changes. Machine changes keep
+separate project choices, and an untouched suggestion follows its agent.
+
+A read-only directory listing offers an unused candidate. Start reserves the
+folder exclusively, so a concurrent collision advances only generated names
+to seconds and then a suffix. Existing folders and their files are preserved.
+Long labels retain the timestamp and suffix within the remote naming limit.
+Remote confirmed collisions get a fresh receipt; uncertain replies and replies
+belonging to another receipt cannot trigger another start. User-chosen names
+are never silently renumbered. A known name conflict leaves the form editable.
+The action remains Start and its pending label is Starting harness….
+
+Validation: 103 focused unit/widget tests pass (one optional render skipped),
+plus four native macOS creation/onboarding journeys and the separate first-run
+render. Inspected `/private/tmp/harness-generated-project-render/first-harness.png`.
+Analysis has no errors or warnings and one pre-existing informational lint in
+`app_state.dart`. `git diff --check` and strict bundle signature verification
+pass. Normal `lib/main.dart` was rebuilt with the existing JEV endpoint and
+opened. Logs: `/private/tmp/harness-generated-project-{test,native,analyze,render,build}.log`.
+These fixtures do not create live agents. No commits or pushes were made.
+
+Live computer-use inspection was attempted again, but the native tool returned
+`Sky Computer Use native pipe startup failed`. Native fixtures use injected
+Flutter events; physical keyboard/IME and live daemon behavior remain separate
+from the evidence above. The broader product audit goal remains active.
+
+## Consistent creation entry points — 2026-09-20
+
+Fixed Store product switches restoring the previous product's draft. Draft
+ownership now includes the entry source and explicit product, in addition to
+machine, source harness, and project context. An already-open dock processes a
+new product request instead of just focusing its old Start row. Store Open/Try
+do not inherit a workspace search task, project, or split. Explicit product and
+machine choices win over incompatible saved defaults; user edits remain in
+their own compatible drafts. Uncertain starts retain their exact receipt and
+cannot be silently replaced by another task.
+
+Cmd-T and Cmd-P retain their common focused-pane defaults and draft recovery;
+the current shortcut decides placement. Found and removed a separate legacy
+popup route in the native Models menu. It now shares the product entry helper
+with Store and pane-menu requests, including the native keyboard handoff.
+The current rules and coverage matrix are in `new-harness-entry-rules.md`.
+
+Validation: **2,398 unit/widget tests passed; 6 optional tests skipped. All 7
+native macOS creation journeys passed**, including immediate input after
+Cmd-T/Cmd-P and Store Open/Try/Models starts. Focused product-route checks also
+passed (66). Updated stale test expectations for the already-approved Start
+wording, layout shortcut, pinned creation row, and Store discovery action.
+Full analysis has no errors or warnings (18 existing informational lints,
+mostly vendored xterm); targeted analysis reports one existing style info.
+`git diff --check` passes. Rebuilt normal `lib/main.dart` with the existing JEV
+endpoint, verified the bundle signature, and opened it for review.
+
+Logs: `/private/tmp/harness-entry-full-final.log`,
+`/private/tmp/harness-entry-native-final.log`,
+`/private/tmp/harness-entry-analyze-final.log`, and
+`/private/tmp/harness-entry-build.log`. Fixtures use fake transport; no live
+harnesses were started. No commits or pushes were made. Live computer-use
+inspection remains unavailable as noted above; this is automated fixture
+coverage, not a claim of physical keyboard/IME validation.
+
+## Startup and keyboard entry — 2026-09-20
+
+Removed redundant chmod subprocesses from persisted settings reads. Each
+operation still stats the current path and repairs permissions when needed;
+there is no cached permission assumption. Tests cover external changes to the
+directory and lock, a second store instance, and replacement of the directory
+at the same path. Locking, fresh reads, atomic writes, and private file modes
+remain covered by the persistence suite.
+
+The existing startup benchmark uses fresh store objects, temporary files,
+20 warmups, and 100 measured samples per operation in the headless debug
+runner. Settings initialization median/p95 changed from 21.656/41.626 ms to
+4.205/7.378 ms. Settings plus keymap changed from 22.604/25.238 ms to
+6.052/9.858 ms. These are warm-filesystem initialization measurements, not
+cold-launch, first-frame, or native input latency results. Raw logs:
+`/private/tmp/harness-startup-baseline.log` and
+`/private/tmp/harness-startup-optimized.log`.
+
+Settings now focuses Search settings immediately. Enter selects the first
+matching section, Down reaches its row, and Escape returns to the workspace.
+Filtering preserves the current section until selection; empty/unmatched
+queries do not switch sections. Composition retains its keys. A native
+journey verifies Cmd-comma → search → Enter → Escape → terminal input with
+no mouse click or leaked input. Pending sign-in now accepts Escape to cancel
+and restores Sign in focus for Enter to retry. Late completion of a cancelled
+attempt cannot sign in or disturb a new attempt.
+
+Validation: **2,406 unit/widget tests passed, 6 optional tests skipped; all 18
+native workspace journeys passed**. The focused settings/sign-in suite has
+16 passing checks; the earlier startup, persistence and sign-in suite has 64.
+Full analysis has no errors or warnings and the same 18 informational lints.
+Formatting is unchanged across the nine touched Dart files. Logs:
+`/private/tmp/harness-startup-settings-full.log`,
+`/private/tmp/harness-startup-settings-native-full.log`,
+`/private/tmp/harness-settings-signin-final-test.log`, and
+`/private/tmp/harness-startup-settings-analyze.log`.
+
+Live computer-use inventory was retried and again failed with
+`Sky Computer Use native pipe startup failed`; no live UI inspection is
+claimed. Native tests use simulated sessions and injected Flutter keys. No
+real harnesses, sign-ins, or user settings were changed by the tests.
+
+Rebuilt the normal application from explicit `lib/main.dart` with the existing
+JEV endpoint after the native fixtures. The build and strict deep signature
+verification pass; `git diff --check` is clean. Build log:
+`/private/tmp/harness-startup-settings-build.log`. No commit or push was made.
+
+## Keyboard help at enlarged text and reliable config reload — 2026-09-20
+
+Reviewed all five production Settings sections at the minimum 880×560 window,
+in light and dark themes at 1× and 1.8× text. The render fixture navigates via
+the Settings search and Enter, uses synthetic account data, and never invokes
+a mutating settings action. It also renders the keyboard-shortcuts sheet in
+each theme/scale. All 24 final images were inspected in
+`/private/tmp/harness-settings-review/`; the fixture passes 20 checks.
+
+Found and fixed clipped keycaps and a truncated shortcut-context selector at
+large text. Keycaps now have a minimum height and grow to fit glyphs or wrapped
+multi-stroke bindings; Tab and Return symbols scale too. The deck reduces its
+column count as text grows, and the context selector gives its label enough
+width. Three new layout tests failed before the changes and pass afterward.
+The real-font context-width check also reproduced the truncation before its
+fix. Settings keyboard coverage now includes Tab into the content, Page Down/
+Page Up, changing shortcut context, Escape closing only its open menu, and
+then Escape returning to the terminal. Both native Settings and keyboard-
+practice journeys pass with fake traffic and injected Flutter keys.
+
+The full regression run exposed an intermittent dotfile-symlink reload failure.
+An isolated ordinary run passed, but a controlled filesystem-resolution delay
+reproduced a missed save after switching targets: the new map was published
+before the new target's watch was installed. `KeymapStore.reload` now establishes
+the watches before reading and publishing the map. The delayed test observes
+the real filesystem replacement event and passes with this ordering; it does
+not hide the issue with a longer timeout. The focused watcher, remapping, and
+Settings suite passes 38 checks. The generated keyboard-config template now
+correctly describes moving New Tab from Cmd-T and lists the project context.
+Existing user configuration files are preserved.
+
+Logs: `/private/tmp/harness-shortcuts-scale-before.log`,
+`/private/tmp/harness-settings-context-before.log`,
+`/private/tmp/harness-keymap-watch-before.log`,
+`/private/tmp/harness-settings-help-watch.log`,
+`/private/tmp/harness-settings-help-review.log`, and
+`/private/tmp/harness-settings-help-native.log`.
+
+Further Settings review remains: the Usage range selector still abbreviates
+its current range at enlarged text, and the About card could use more room
+for its action descriptions. This pass checks the visible initial states and
+keyboard navigation; provider data, pairing, account changes, and update flows
+still require their own full interaction audit. Live computer-use remains
+unavailable as recorded above.
+
+Final validation for this pass: **2,431 unit/widget tests passed; 6 optional
+tests skipped**. Full analysis has no errors or warnings and the same 18
+informational lints. The normal `lib/main.dart` macOS build completed after the
+native fixtures and passes strict deep signature verification. Formatting and
+`git diff --check` pass. Logs:
+`/private/tmp/harness-settings-help-full-final.log`,
+`/private/tmp/harness-settings-help-analyze-final.log`, and
+`/private/tmp/harness-settings-help-build.log`. No commit, push, real account
+change, device pairing, or production configuration edit was performed.
+
+## Honest update results and readable Usage/About — 2026-09-20
+
+The existing Cmd-T/Cmd-P and Store ownership rules remain the creation
+contract in `new-harness-entry-rules.md`. Rechecked the native first workspace,
+new tab, new pane, Store Open, Store Try, Models, and edited-default placement
+journeys: all seven pass, including immediate terminal input after creation.
+They use simulated sessions and do not launch real harnesses.
+
+Usage's current range was truncated at 1.8× text in both themes. The real-font
+regression failed before the change. Overview and provider headers now share
+a range field that grows with text, and controls move below their captions
+when needed. Keyboard selection, Escape, and return focus are tested in both
+views. The local-only Usage subtitle is shorter. About explanations and actions
+stack at enlarged text; its version/status line wraps instead of overflowing.
+
+The update audit found failures that were being presented as "up to date" and
+a concurrent manual check that returned an early, stale answer. Three new
+regressions reproduced these before the fix. Results now distinguish current,
+available, disabled, and failed checks, including absent/malformed platform
+metadata. Manual and background callers share a request. About and the native
+menu share one result dialog; a failed result offers Retry in place. About
+does not claim the build is current before a successful check. Development,
+disabled, and viewer builds do not contact the desktop update service.
+
+Two further failing regressions showed that Update/Skip could act on a newly
+arrived offer instead of the version displayed. Both actions now take the
+reviewed version explicitly. Failed installs retain that version for retry;
+skipping an older displayed version leaves a newer offer visible. A recheck
+failure preserves a known offer and its installation error. Valid current
+metadata clears a withdrawn offer. Escape dismisses results and pending
+checks, while an installation stays open. Late replies after dismissal or
+notifier disposal are covered. Already-skipped versions show Close and Update,
+without the redundant Not now action.
+
+Background polling now matches the six-hour cadence described in About,
+does not overlap a slow request, and cannot publish after its timer is
+cancelled. Download hashing, staging, and platform artifact selection still
+pass their existing tests. All update tests use intercepted manifests, temporary
+fixture archives, or a fake installer; no real desktop update was performed.
+
+The render fixture captures 52 states at 880×560, in light/dark and 1×/1.8×
+text. All 36 Usage/About/update images were inspected in
+`/private/tmp/harness-settings-update-review/`. Dialog action fonts use the app
+font explicitly; labels, facts, and controls remain readable at enlarged text.
+The expanded native Settings journey verifies keyboard navigation into About,
+the disabled-build result, Escape returning to the button, then Settings
+closing and terminal input returning without a click. That journey passes,
+bringing the native reruns in this pass to eight.
+
+Final regression: **2,450 unit/widget tests passed; 6 optional tests skipped**.
+Full analysis has no errors or warnings and the same 18 informational lints.
+Formatting passes for all 15 touched Dart files. Evidence:
+`/private/tmp/harness-settings-update-full-final.log`,
+`/private/tmp/harness-settings-update-analyze-final.log`,
+`/private/tmp/harness-settings-update-native.log`, and
+`/private/tmp/harness-settings-update-native-launch.log`.
+
+Live computer-use remains unavailable with the previously recorded native-pipe
+startup failure. Native fixtures inject Flutter keys and fake transport;
+physical keyboard/IME, Linux, real device/account changes, and the broader
+product/performance audit remain unfinished. No commit or push was made.
+
+Rebuilt the normal `lib/main.dart` macOS application after the native fixtures,
+preserving `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`. The build and strict deep
+signature verification pass; `git diff --check` is clean. Build log:
+`/private/tmp/harness-settings-update-build.log`. The rebuilt app was not opened.
+
+## Cmd-T/Cmd-P preserve the open picker — 2026-09-20
+
+Rechecked the creation entry contract after the user's request to concentrate
+on the common keyboard paths. The initial 62 focused tests passed, including
+Workshop → Blender Open/Try, machine changes, generated versus edited names,
+source-pane draft ownership, uncertainty, and destination recovery. A further
+keyboard audit found a separate data-loss interaction: pressing Cmd-T or Cmd-P
+while search was open closed and recreated it, clearing its query. All four
+repeat/switch combinations failed before the fix:
+`/private/tmp/harness-picker-retarget-before.log`.
+
+The picker now changes destination in place. Repeating a shortcut refocuses
+its existing input; switching shortcuts preserves the query, text selection,
+highlighted harness, and project/machine scope. Header and Enter action update
+together. Capacity and existing-pane membership are refreshed for the chosen
+destination. Store/orchestration tabs continue to send terminal work to a new
+tab. Pending creation receipts still prevent a shortcut from replacing an
+unresolved start.
+
+Seven additional widget journeys cover the four repeat/switch combinations,
+both directions with a highlighted existing harness, and project filtering
+with Escape back to the parent. The full-tab model regression now switches the
+same picker between destinations and verifies capacity and Focus pane versus
+Open in new tab. The native New Tab/New Pane journeys type a task, switch and
+repeat shortcuts, start it, then send terminal input without a mouse click.
+
+Validation: **2,457 unit/widget tests passed, 6 optional tests skipped**. All
+**seven native creation journeys passed**: first workspace, New Tab, New Pane,
+Store Open, Store Try, Models, and edited-default placement. Full analysis has
+no errors or warnings and the same 18 existing informational lints. Formatting
+and `git diff --check` pass. The normal `lib/main.dart` macOS build was restored
+after the fixture, retaining the command-bar URL above, and passes strict deep
+signature verification. No real harness was started; the native fixture uses
+fake transport and injected Flutter keys, and does not establish physical
+AppKit/IME or live-daemon behavior. The rebuilt normal app was not opened.
+
+Evidence:
+- `/private/tmp/harness-entry-recheck.log`
+- `/private/tmp/harness-picker-retarget-focused.log`
+- `/private/tmp/harness-picker-retarget-full.log`
+- `/private/tmp/harness-picker-retarget-native.log`
+- `/private/tmp/harness-picker-retarget-analyze-final.log`
+- `/private/tmp/harness-picker-retarget-build.log`
+
+The broader overnight goal remains active. The next independent audit is
+Usage's delayed load/scan/toggle/disposal behavior. Code inspection found
+missing generation guards in `UsageLedgerStore` and post-disposal checks in
+`UsageLedgerController`; controlled timing regressions and any fixes remain to
+be implemented. Native performance benchmarking still requires isolation from
+the three development previews last observed (PIDs 21874, 32129, 64557); none
+were stopped. Live computer-use remains unavailable as previously recorded.
+
+## Usage lifecycle, loading states, and repeated aggregation — 2026-09-20
+
+Controlled delayed reads and writes reproduced 12 failures in the old Usage
+store/controller lifecycle. A late scan could restore figures and a snapshot
+after Off; delayed preferences or cache reads could overwrite an explicit
+choice; reopening could race pending persistence; and disposing during load
+could still notify or start a scan. Failed reads also retained stale figures
+or joined a failed request when Retry should have started a new one.
+
+The stores now guard results with a choice revision, share concurrent loading
+and scanning, and serialize provider persistence across reopened stores.
+Switching Off clears memory immediately and queues snapshot deletion after
+earlier writes. Failed/unavailable scans clear figures, timestamps, and cached
+sources. An Off/On waits for the old physical read and discards its result
+before rescanning; the scanner API cannot cancel a read already in progress.
+Disposal prevents later state changes, notifications, or new scanning.
+
+Usage distinguishes reading preferences, an initial scan, a rescan with
+previous figures, failure, and Off. Initial pending/failed/disabled sources no
+longer show zero tokens, cost, or sessions as if those were measured results.
+Changing the date range uses in-memory data and does not rescan the disk.
+
+Repeated overview aggregation was measured with 60,000 synthetic turns in
+warm debug CPU work: median 30,716 μs and p95 88,298 μs before the change.
+Caching each range and its cutoff date gives a median below the timer's 1 μs
+resolution and p95 1 μs afterward. Provider changes and midnight invalidate
+the relevant results. This only measures repeated overview lookups, not cold
+parsing, first aggregation, app launch, or native input/frame latency.
+
+Enlarged-text renders exposed a daily-chart overflow and shorter bars floating
+above the baseline. Chart height/width now use measured label sizes; small
+bars align at the bottom. A dedicated geometry regression checks 1:2 bar
+heights, the shared baseline, and readable labels at 2.5× text.
+
+Validation:
+
+- **2,480 unit/widget tests passed; 7 optional tests skipped.** The added
+ benchmark is opt-in. After the final zero-session-count refinement, all
+ **80 focused Usage tests passed** again.
+- Added **18 lifecycle tests and five UI/chart tests**. The four UI workflows
+ cover both themes at 1.0×/1.8× text and 880×560, with real font metrics and
+ icon fonts. All 24 captured loading/failure/rescan/Off states were inspected.
+- Eight native journeys passed together: Settings/About, first workspace,
+ Cmd-T, Cmd-P, Store Open, Store Try, Models, and edited-default placement.
+ The new native Usage journey initially sent keys before its menu's first
+ frame. After making that fixture wait for the rendered menu, it passed
+ separately, including keyboard range selection, Retry, and Off during scan.
+- Static analysis has no errors or warnings and the same 18 informational
+ lints. Formatting and `git diff --check` pass.
+- Rebuilt the normal `lib/main.dart` macOS app after native fixtures with
+ `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`; strict deep signature verification
+ passes. The rebuilt normal app was not opened.
+
+Evidence:
+
+- `/private/tmp/harness-usage-lifecycle-before.log`
+- `/private/tmp/harness-usage-full.log`
+- `/private/tmp/harness-usage-final-focused.log`
+- `/private/tmp/harness-usage-native.log`
+- `/private/tmp/harness-usage-native-retry.log`
+- `/private/tmp/harness-usage-performance-before.log`
+- `/private/tmp/harness-usage-performance-after.log`
+- `/private/tmp/harness-usage-lifecycle-review/`
+- `/private/tmp/harness-usage-analyze-final.log`
+- `/private/tmp/harness-usage-build.log`
+
+All Usage data in tests is synthetic; no real transcript was read or harness
+started. Native fixtures use fake transport and injected Flutter keys. Live
+computer-use and isolated native performance measurement remain limited as
+previously recorded. No commit or push was made. The broader goal remains
+active: next inspect scanner cache validity while OpenCode writes to SQLite
+WAL, unreadable-database states, and cold parsing/aggregation performance.
+These are inspection targets, not verified bugs or completed work.
+
+## OpenCode live reads, incomplete data, and scan responsiveness — 2026-09-20
+
+The next audit used temporary SQLite databases exclusively. Six initial
+regressions failed: a committed update in WAL was missed when the main file's
+mtime/size stayed unchanged; locked and corrupt databases were called missing;
+an unsupported schema returned a successful empty scan; a broken sibling was
+silently omitted from totals; and sessions with only cache-write tokens were
+excluded by the query.
+
+OpenCode now queries SQLite's committed snapshot for each requested scan,
+without using the main file's metadata as proof that its contents are unchanged.
+The aggregate query runs in a worker isolate. The store's five-minute cache
+still avoids rescanning on every visit. Tests hold a writer open, update its
+WAL, check an uncommitted transaction is excluded, then checkpoint/truncate and
+update again. They also cover locks and recovery, corruption, absent versus
+misconfigured directories, unsupported schemas, duplicate session ownership,
+cache-write-only usage, and a genuinely empty supported database.
+
+An unreadable source is a read failure, distinct from a missing installation.
+When other databases are readable, their figures remain visible with an
+Incomplete badge and explanation. Overview totals carry the same warning.
+The warning stays during Retry, and disappears only after a complete read.
+Partial results clear the old disk snapshot rather than being restored later
+as a complete fresh result. Empty incomplete scans do not claim zero sessions
+or zero tokens; successful empty scans still can.
+
+A report-only benchmark uses 30,000 synthetic sessions and a 1 ms periodic
+timer on the caller isolate. Across five measured scans after one warmup, the
+median maximum event-loop gap fell **44,440 → 5,828 μs**. Median total scan time
+was **44,320 → 60,631 μs**. The tradeoff is responsiveness while waiting for
+the worker, not higher query throughput. This is debug scheduling evidence on
+a shared development machine, not a native frame/input measurement or the
+cost of subsequent aggregation/rendering.
+
+Validation:
+
+- **2,493 desktop unit/widget tests passed; 8 optional tests skipped.** Nine
+ scanner, two lifecycle, and two UI regressions were added; the four existing
+ theme/text-scale journeys now exercise partial data and retry too. The added
+ scheduling benchmark is opt-in.
+- Three native macOS journeys pass: delayed Usage retry/range/Off, real SQLite
+ worker reads and recovery through the Refresh button, and Settings/About
+ keyboard ownership with return to the terminal. The real-database journey
+ only touches its temporary fixture. It never reads production transcripts.
+- Thirty-two Usage states were captured in both themes at 1.0×/1.8× text;
+ the 12 new or changed partial-data/rescan images were inspected. The unchanged
+ loading/Off states were inspected in the preceding pass.
+- Static analysis has no errors or warnings and the same 18 existing info
+ findings. Formatting and `git diff --check` pass.
+- The normal macOS `lib/main.dart` app was rebuilt after native testing with
+ `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478` and passes strict deep signature
+ verification. It was not opened. No commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-scanners-before.log`
+- `/private/tmp/harness-scanners-first-fix.log`
+- `/private/tmp/harness-scanners-partial-ui-final.log`
+- `/private/tmp/harness-scanners-performance-before.log`
+- `/private/tmp/harness-scanners-performance-after.log`
+- `/private/tmp/harness-scanners-full.log`
+- `/private/tmp/harness-scanners-native.log`
+- `/private/tmp/harness-scanners-analyze-final.log`
+- `/private/tmp/harness-scanners-build.log`
+- `/private/tmp/harness-usage-partial-review/`
+
+The broader goal remains active. Live computer-use and isolated native timing
+have the limitations already recorded. The next useful work is controlled
+JSONL file-read failures and cold parsing/first-aggregation profiling; current
+Claude/Codex parsers still run on the caller isolate and swallow filesystem
+read failures as empty entries. Those observations need concrete reproductions
+before choosing changes. Device/account changes and the remaining product
+audit are also still outstanding.
+
+## JSONL failure recovery, live writes, and first aggregation — 2026-09-20
+
+Temporary Claude/Codex transcripts reproduced ten failures: denied file reads
+were silently cached as empty successful files (and stayed empty after access
+returned), unreadable roots were called missing, a broken sibling could hide
+valid data, and a file caught halfway through a Unicode character failed the
+whole refresh. These are now handled by a shared file lifecycle while each
+provider keeps its existing parsing and deduplication rules.
+
+The shared reader distinguishes missing roots from listing/read failures,
+retains readable sources with an incomplete-data warning, and never caches a
+failed source as empty. Snapshot format 3 invalidates version 2 caches that may
+contain that mistake. A migration regression uses a fresh old snapshot and
+verifies the next refresh really scans, rather than accepting its cached zero.
+
+Reads stop at the captured file size. A streaming transformer holds only the
+last four bytes, omitting a valid unfinished UTF-8 suffix while still sending
+all earlier bytes through the strict UTF-8 decoder and normal line splitter.
+Earlier complete usage records survive concurrent writes; a subsequent refresh
+picks up the finished record. Corrupt completed text remains a failed source.
+Tests cover every byte cut through two-, three-, and four-byte characters,
+CRLF, a valid last line without a newline, malformed and out-of-range suffixes,
+both transcript roots, appended/deleted files, and permission restoration.
+Permission-denial cases skip only on Windows or a host that can bypass their
+temporary file permissions; they all ran on this macOS host.
+
+The timing fixture uses 20,000 synthetic usage turns and a 2 MiB tool result.
+It found the larger aggregation pause in repeated Claude model-name matching.
+A bounded cache (128 names per provider, maximum 512-character keys) now
+retains normalization results, including unknown names. Token-dependent tier
+arithmetic still runs separately for each entry; neither rates nor model-name
+matching rules changed. Cold file reads retain the standard chunked decoder.
+
+Final debug medians, five measured runs after one warmup:
+
+| Work | Before | After |
+| --- | ---: | ---: |
+| Claude cold scan | 137.717 ms | 129.314 ms |
+| Codex cold scan | 86.577 ms | 90.045 ms |
+| Claude cached scan | 0.567 ms | 0.665 ms |
+| Codex cached scan | 0.600 ms | 0.794 ms |
+| Claude aggregation | 21.288 ms | 4.671 ms |
+| Codex aggregation | 2.128 ms | 2.076 ms |
+
+The corresponding median maximum caller event-loop gap during Claude
+aggregation was 21.383 → 4.732 ms. Cold-scan gaps stayed around 5–6 ms. These
+are shared-machine debug observations, not a native-frame or full-app input
+latency claim. The final comparison is `performance-before` versus
+`performance-final`; an intermediate per-line decoder was discarded after
+timing showed unnecessary overhead.
+
+Validation:
+
+- **2,513 desktop unit/widget tests passed; 10 optional tests skipped.**
+ Added 18 transcript/Unicode regressions, one old-cache migration regression,
+ one per-turn pricing regression, and two opt-in benchmark cases.
+- Five native macOS journeys pass: delayed Usage retry/range/Off, live SQLite
+ reads, live Claude transcripts, live Codex transcripts, and Settings/About
+ keyboard ownership with terminal focus restored. Both JSONL journeys use
+ real temporary files and the actual Refresh control to recover from an
+ interrupted Unicode write and a corrupt sibling.
+- Static analysis has no errors or warnings and the same 18 existing info
+ findings. Formatting and `git diff --check` pass.
+- Rebuilt normal `lib/main.dart` after the native fixture, retaining
+ `JEV_COMMAND_BAR_URL=http://127.0.0.1:18478`. Strict deep signature verification
+ passes. The rebuilt app was not opened. No commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-jsonl-before.log`
+- `/private/tmp/harness-jsonl-focused.log`
+- `/private/tmp/harness-jsonl-stream-fix.log`
+- `/private/tmp/harness-jsonl-performance-before.log`
+- `/private/tmp/harness-jsonl-performance-final.log`
+- `/private/tmp/harness-jsonl-full.log`
+- `/private/tmp/harness-jsonl-native.log`
+- `/private/tmp/harness-jsonl-analyze-final.log`
+- `/private/tmp/harness-jsonl-build.log`
+
+All transcript data is synthetic and confined to temporary directories. No
+user transcript was read, no account changed, and no real harness started.
+Native keys remain Flutter-injected; live computer-use and isolated native
+performance measurement retain the previously recorded limits. The broader
+goal is active. Next audit account changes and reconnect/inventory responses,
+with attention to old replies restoring stale workspace or onboarding state.
+The rest of the device, platform, and product audit remains outstanding.
+
+## Account lifetime, sign-out recovery, and readable authentication — 2026-09-20
+
+The initial viewer-auth probes reproduced ten failures in fourteen cases.
+An old refresh could restore credentials after sign-out, overwrite a new
+account, or clear it when the old refresh failed. Cancelling browser sign-in
+during server binding, authorization, exchange, or persistence could still
+publish a URL or save credentials. An older attempt's cleanup also owned
+the replacement attempt's callback reference.
+
+Viewer authentication now gives each login and account session a revision.
+Refresh completion checks that revision before saving or clearing anything;
+its cleanup only releases its own in-flight future. Credential writes and
+deletions are serialized, and token readers wait for pending writes. A
+cancelled save clears its incomplete credentials before a newer queued
+login is allowed to write. Callback cancellation closes its listener, treats
+an early outcome as data until it is awaited, and cannot cancel a replacement.
+
+Desktop sign-out previously ignored CLI failure and enabled Sign in while
+the CLI could still be clearing the saved session. It now owns the child
+process, checks its exit, drains output, and terminates a timed-out child
+before returning failure. App state joins repeated sign-out requests, clears
+the visible account, and waits for credential and connection cleanup before
+allowing sign-in. Failure offers a focused Retry sign out action with a plain
+explanation. Failed terminal/connection closure cannot strand the remaining
+cleanup. Disconnecting a development fixture never runs real CLI logout.
+A delayed machine response can no longer change signed-out cache status.
+
+Visual review caught a separate accessibility issue: at 880×560 with 1.8×
+text, the decorative fleet diagram pushed the action and recovery message
+below the viewport. Short windows now omit that diagram when text is enlarged.
+The action and explanation remain visible, and retry/success restore keyboard
+focus. The capture fixture was also corrected to synchronize its global
+palette with the requested theme; its initial light captures mixed light text
+styles with a dark palette. All twelve final captures were inspected.
+
+Validation:
+
+- Full suite: **2,541 passed, 10 optional tests skipped**. Added 17 viewer
+ lifecycle cases, three CLI logout cases, seven sign-out state/keyboard/
+ visual cases, and one delayed-inventory case.
+- After the viewport adjustment: all 25 sign-in/sign-out widget regressions
+ pass, followed by all seven sign-out cases with synchronized light/dark
+ captures. Capture states are pending, failed, and ready at 1.0× and 1.8×.
+- Nine native macOS journeys pass: sign-out retry and keyboard focus,
+ Settings, first workspace, New Tab and New Pane creation, Store Open and
+ Try, Models, and edited creation destination. Creation tests deliver
+ terminal input without a mouse click and cover product-prefix isolation.
+- Static analysis: no errors/warnings, the same 18 informational findings.
+ Formatting and `git diff --check` pass.
+- Normal `lib/main.dart` rebuilt with the existing command-bar URL
+ `http://127.0.0.1:18478`; strict deep signature verification passes.
+ The rebuilt app was not opened. No commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-auth-lifecycle-before.log`
+- `/private/tmp/harness-auth-recovery-focused.log`
+- `/private/tmp/harness-auth-full.log`
+- `/private/tmp/harness-auth-visual.log`
+- `/private/tmp/harness-auth-visual-final.log`
+- `/private/tmp/harness-auth-review/`
+- `/private/tmp/harness-auth-native.log`
+- `/private/tmp/harness-auth-analyze-final.log`
+- `/private/tmp/harness-auth-build.log`
+
+Accounts, credentials, CLI processes and harnesses in these tests are fakes;
+viewer callback tests use ephemeral loopback listeners and in-memory storage.
+No real account was changed. Native keys are Flutter-injected, so physical
+AppKit/IME and live account interaction retain their earlier verification
+limits. The broader goal remains active. Next inspect runtime session expiry,
+saved workspace restoration across account changes, and concurrent machine
+inventory responses; the remaining platform/device/performance audit continues.
+
+## Workspace restoration and concurrent inventory — 2026-09-20
+
+Thirteen initial account/workspace regressions reproduced lost restoration,
+stale layout reads after sign-out, and callbacks from replaced connections.
+Four additional inventory cases reproduced older replies replacing newer
+rows, loading state, or retry errors. These cases now pass.
+
+Sign-out and runtime expiry share live-workspace cleanup. They close all
+terminal sessions on their original transports, clear account-owned inventory
+and history, and leave one fresh empty tab without saving it over the previous
+desk. Sign-in waits for pending cleanup; cancellation while waiting prevents
+later login. Layout reads check account and layout revisions. Saved tabs,
+active selection, pinning, layout presets, and zoom restore after signing in.
+The persisted desk remains computer-local intent, not an account-namespaced
+store. Replaced WebSocket connections lose callback ownership immediately.
+
+Machine inventory now has request ownership as well as account ownership.
+Only the latest request can publish rows, finish loading, or clear its error.
+API responses retain their own freshness, and shared-machine fallback cannot
+cross account changes. Retry retains the public refresh path, whose boolean
+result tells callers whether its response was applied. An early version
+bypassed this path; the full suite caught three regressions, which were fixed.
+
+Runtime expiry now presents one Sign in action with its explanation, without
+mislabeling it as a failed sign-in. Four captures were inspected at 880×560:
+dark/light themes and 1.0×/1.8× text. A visual fixture initially left a timer
+alive after successful sign-in; explicit fixture disposal fixed all four
+failures. The first native restoration fixture waited for an indeterminate
+reconnect spinner to settle; it now waits for sign-in completion and checks
+keyboard tab selection directly, with a bounded timeout.
+
+Validation:
+
+- Focused account/connection cases: **80 passed**. Focused inventory cases:
+ **80 passed**. Retry/public-path regression pass: **71 passed**. Final
+ inventory-result and expiry-screen checks: **29 passed**.
+- Full suite: **2,565 passed, 10 optional tests skipped**.
+- Native macOS: **10 passed**, covering expiry/restoration, sign-out recovery,
+ Settings, first workspace, Cmd-T/Cmd-P immediate input, Store Open/Try,
+ Models, and edited draft placement.
+- Static analysis: no errors or warnings, the same 18 informational findings.
+- Normal `lib/main.dart` rebuilt with command-bar URL
+ `http://127.0.0.1:18478`; strict deep signature verification passes. The app
+ was not opened. No commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-workspace-account-before.log`
+- `/private/tmp/harness-workspace-account-focused.log`
+- `/private/tmp/harness-inventory-before.log`
+- `/private/tmp/harness-inventory-focused.log`
+- `/private/tmp/harness-workspace-account-retry.log`
+- `/private/tmp/harness-workspace-account-final-focused.log`
+- `/private/tmp/harness-workspace-account-full-final.log`
+- `/private/tmp/harness-workspace-account-review/`
+- `/private/tmp/harness-workspace-account-native-final.log`
+- `/private/tmp/harness-workspace-account-analyze-final.log`
+- `/private/tmp/harness-workspace-account-build.log`
+
+Account and terminal fixtures are synthetic; API tests use an ephemeral
+loopback server and memory storage. The temporary retry-path regression
+bypassed discovery overrides and attempted local read-only discovery; no real
+account changed and no real harness started. Native keys are Flutter-injected;
+live AppKit/IME and platform/device checks retain their recorded limits. The
+broader goal remains active. Next inspect restored panes whose machines no
+longer appear in a successful inventory and their reconnect guidance.
+
+## Clear recovery for unavailable restored panes — 2026-09-20
+
+A successful inventory with no row for a saved pane still displayed an
+indefinite "Waiting for this machine" spinner. Five initial UI regressions
+failed, covering a fresh empty reply, a recovered-but-absent machine, a cached
+empty reply, failed reads, and keyboard Retry.
+
+App state now records whether an inventory has completed for the current
+account. A missing fresh row says the machine is unavailable; cached data
+says its status could not be confirmed; failed reads say machines could not
+be loaded. Initial loading retains its waiting state. All completed states
+offer Retry, which stays mounted while a request is pending and preserves
+its position and keyboard focus. Repeated activation joins the current retry.
+The progress/icon space has a fixed size. Account changes reset completion.
+Unknown agent headers use the established Untitled Pane placeholder instead
+of exposing a raw identifier, and retained-output notices no longer promise
+an answer from an absent machine.
+
+Validation:
+
+- **64 focused checks pass**, including keyboard activation during/after
+ refresh, unchanged Retry geometry, stale-versus-fresh guidance, and account
+ reset. The pane fixture now listens to notifier updates as the real shell
+ does; its earlier static host was corrected.
+- **12 small-pane captures** at 440×240 were inspected: missing/cached/failed
+ in both themes at 1.0× and 1.8× text. All content and Retry remain visible.
+ Initial captures lacked a Material ancestor; the final fixture includes
+ the app's normal surface and removes the debug banner.
+- Full suite: **2,581 passed, 10 optional tests skipped**.
+- Native: nine launch/account scenarios passed in the combined run. The new
+ recovery assertion first assumed Retry was the first Tab stop; the workspace
+ also has pane-header controls. The corrected test traverses the real order,
+ activates Retry with Enter, and verifies another inventory request. It
+ passes separately, retaining saved-tab selection checks. Ten native
+ scenarios therefore pass across these final runs.
+- Analyzer: no errors or warnings; the existing 18 informational findings.
+ Formatting and `git diff --check` pass. A missing import for the shared
+ placeholder constant was caught and corrected before the final runs.
+- Normal `lib/main.dart` rebuilt with command-bar URL
+ `http://127.0.0.1:18478`; strict deep signature verification passes. The
+ rebuilt app was not opened, and no commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-missing-machine-before.log`
+- `/private/tmp/harness-missing-machine-focused-final.log`
+- `/private/tmp/harness-missing-machine-review/`
+- `/private/tmp/harness-missing-machine-full-final.log`
+- `/private/tmp/harness-missing-machine-native-final.log`
+- `/private/tmp/harness-missing-machine-native-recovery.log`
+- `/private/tmp/harness-missing-machine-analyze-final.log`
+- `/private/tmp/harness-missing-machine-build.log`
+
+This pass uses fake inventory and account fixtures and in-memory storage. No
+real account changed or real harness started. Native keys are Flutter-injected;
+physical input, live account/daemon behavior, and platform coverage retain the
+previously recorded limits. The broader product goal remains active. Continue
+with reconnect transitions, retained terminal state, and the remaining
+device/platform/performance checks.
+
+## Reconnect discovery and retained terminal input — 2026-09-20
+
+Five new discovery probes failed before the fix: a reconnect reused pending
+capability discovery from the old connection; its late success/failure could
+replace new capability state; an old inventory timeout marked the reconnected
+machine offline; an offline transition still accepted pending discovery; and
+a background inventory reply overwrote the fresh reconnect snapshot. Two
+further probes reproduced a second reconnect waiting behind obsolete recovery
+and an old stream ID remaining writable after connection replacement.
+
+Machine discovery now has a connection revision in addition to its account
+and machine-object guards. A disconnect or new connection releases old
+inventory/capability futures so fresh discovery can begin immediately. Each
+completion checks its originating revision. Reconnect clears negotiated
+capabilities until this connection answers, and old completion handlers cannot
+release a newer request's ownership. Background inventory uses the same guard.
+Pending-agent recovery has explicit ownership and checks its revision both
+before and after discovery; a second reconnect can begin without waiting for
+the first recovery loop to finish.
+
+A replacement connection also releases prior stream IDs immediately. The
+session and renderer remain in place with retained output, scroll, selection,
+and draft state, while input waits for the replacement stream's first keyframe.
+Taken-over sessions remain under the existing explicit-retry policy.
+
+Validation:
+
+- The initial probes failed **5/5**, then **2/2**. The final focused reconnect,
+ discovery, offline, and retained-view pass has **37 passing checks**. The
+ final shared discovery fixture separately has **19 passing checks**.
+- Full suite: **2,588 passed, 10 optional tests skipped**.
+- Native workspace: **11 passed together**. The new journey verifies retained
+ renderer, output, scroll, selection, suppressed input before negotiation,
+ fresh screen arrival, unchanged focused pane, and input resumption without
+ a mouse click. Main Cmd-T/Cmd-P, Store Open/Try, first-run, Settings, account
+ recovery, and edited draft placement remain covered in that run.
+- Native terminal: **2 passed**, exercising keyframe replacement and switching
+ agents without stale/duplicate native terminal views.
+- Analyzer: no errors or warnings; 18 existing informational findings after
+ correcting six new brace-style findings. Formatting and diff checks pass.
+- Normal `lib/main.dart` rebuilt with command-bar URL
+ `http://127.0.0.1:18478`; strict deep signature verification passes. The app
+ was not opened. No commit or push was made.
+
+Evidence:
+
+- `/private/tmp/harness-reconnect-discovery-before.log`
+- `/private/tmp/harness-reconnect-handoff-before.log`
+- `/private/tmp/harness-reconnect-discovery-focused-final.log`
+- `/private/tmp/harness-reconnect-discovery-final.log`
+- `/private/tmp/harness-reconnect-discovery-full.log`
+- `/private/tmp/harness-reconnect-discovery-native.log`
+- `/private/tmp/harness-reconnect-terminal-native.log`
+- `/private/tmp/harness-reconnect-discovery-analyze-final.log`
+- `/private/tmp/harness-reconnect-discovery-build.log`
+
+The direct computer-use retry returned empty app/browser inventories and
+`Sky Computer Use native pipe startup failed`. Native checks therefore remain
+Flutter-injected input with synthetic transport; they do not establish
+physical AppKit/IME, live credentials/daemon behavior, or other-platform parity.
+No real agent or account was changed. Immediate discovery is verified by
+request ordering under held fake replies, not a network latency claim. The
+broader goal remains active. Continue the performance and interaction audit,
+especially sustained command-dock use and large inventories, with the existing
+physical/platform limits kept explicit.
+
+## Command-dock query rendering profile — 2026-09-20
+
+Exercised the real SwarmScreen with 2,000 and 10,000 synthetic harnesses:
+repeated Cmd-T, broad/narrow typing, another character with the same matches,
+arrows, and Cmd-P → Cmd-T retargeting. The fixture asserts that no machine
+transport is used. Optional CPU sampling connects only to its own loopback VM
+service and saves samples outside the workspace. Run the benchmark explicitly;
+it is excluded from the normal `*_test.dart` suite.
+
+The first CPU sample involved Flutter rebuild work in roughly 44% of samples;
+search filtering appeared in roughly 7%. Debug/test overhead and truncated
+stacks limit interpretation. A focused regression then reproduced five visible
+ListTile controls rebuilding when only query match text changed. Row text now
+listens for match-query/help-mode changes separately from the bounded control
+cache. Unchanged controls keep their widgets; row metadata, availability,
+selection, actions, geometry, palette, and font still invalidate as needed.
+The regression now sees zero unchanged control rebuilds, updated matches, and
+retained input focus. Existing arrow movement still rebuilds only two rows.
+
+A paired experiment temporarily restored query-driven control invalidation,
+then removed it before final verification. Consecutive-character timings:
+
+| Synthetic harnesses | Controls invalidated: median / p95 | Controls retained: median / p95 |
+| --- | --- | --- |
+| 2,000 | 11.059 / 12.485 ms | 9.513 / 11.888 ms |
+| 10,000 | 16.568 / 19.649 ms | 17.648 / 35.046 ms |
+
+These are 50-sample **headless debug widget elapsed** measurements after eight
+warmups. Broad open/filter timings also have noisy tails. The consistent result
+is reduced rebuild work; the mixed timings do not establish a general speedup,
+native display latency, or release-build performance. No ranking or visible
+interaction rules were changed for this optimization.
+
+Verification:
+
+- 88 focused dock, Store, project, draft, and placement checks passed.
+- The initial full run found a race in the shared-viewer fixture: a recorded
+ server request was treated as proof its reply had reached the UI. The fixture
+ now awaits the actual displayed response. Its four tests pass, followed by
+ the full suite: **2,589 passed, 10 optional tests skipped**.
+- **All 25 native macOS workspace journeys passed together**, including first
+ workspace, shared views, Cmd-T/Cmd-P creation, edited placement, Store
+ Open/Try/Models, immediate terminal input, Settings, machine management,
+ account recovery, rename, stop, fork, and restart.
+- Analyzer: no errors/warnings; the same 18 existing informational findings.
+ Two new informational findings were corrected before the final analysis.
+- The optional profiler and cleanup path passed in a final 2,000-row run.
+- Normal `lib/main.dart` rebuilt with the existing command-bar URL at port
+ 18478. Deep strict code-signature verification passed. App not opened;
+ nothing committed or pushed.
+
+Evidence:
+
+- `/private/tmp/harness-dock-row-before.log`
+- `/private/tmp/harness-dock-query-focused.log`
+- `/private/tmp/harness-dock-widget-before.log`
+- `/private/tmp/harness-dock-widget-after.log`
+- `/private/tmp/harness-dock-widget-query-control.log`
+- `/private/tmp/harness-dock-widget-query-growth.log`
+- `/private/tmp/harness-dock-cpu-2000.json`
+- `/private/tmp/harness-dock-cpu-final-2000.json`
+- `/private/tmp/harness-dock-observer-fixture.log`
+- `/private/tmp/harness-dock-query-full-final.log`
+- `/private/tmp/harness-dock-query-native.log`
+- `/private/tmp/harness-dock-query-analyze-final.log`
+- `/private/tmp/harness-dock-query-build.log`
+
+The broader audit remains active. Native checks use synthetic state and
+Flutter-injected keys; physical computer use, AppKit IME, real daemon/account
+behavior, and native Linux remain outside the evidence above.
+
+## First-run setup diagnostics and recovery — 2026-09-20
+
+Continued from the verified command-dock pass. Three failing probes established
+that malformed installer output disappeared from diagnostics, a partially
+written result could return the provisioner to Review, and a 1.4 MB log was
+copied wholesale into UI state on every five-second recheck. The malformed log
+was caught as a filesystem read failure; it did not itself crash this fixture.
+
+The provisioner now reads at most the final 64 KiB and retains at most 200 lines.
+It tolerates incomplete UTF-8, keeps the end of long single-line output, and
+replaces the preceding snapshot when the log changes. The original log is
+untouched; truncation includes its path. Empty, unreadable and malformed result
+files stay pending, while live dependency probes remain authoritative. Tests
+also cover an empty completion file and preserve the existing no-duplicate
+Terminal launch behavior. These are bounded I/O and UI-state guarantees, not
+native Linux timing measurements.
+
+Two failing UI tests additionally reproduced unhandled clipboard failures and
+an older copy error arriving after a newer success. Setup now catches clipboard
+errors, announces an inline recovery message beside the still-available Retry,
+and lets only the latest attempt update feedback. Timers cancel on disposal and
+renew for the latest copy. Setup's lead now says first harness, consistently
+with its footer and the dock. Visual review found white step numbers against
+light circles; they now use the theme's text color.
+
+Verification:
+
+- 44 focused setup, provisioner, timer, and rendered-layout checks passed.
+- Full unit/widget suite: **2,599 passed, 10 optional tests skipped**.
+- A final 12-test setup/layout run passed after the light-theme color change.
+- **Eight native macOS journeys passed together**: first setup, first workspace,
+ Cmd-T/Cmd-P creation, Store Open/Try/Models, and edited-draft placement. The
+ new first-setup journey uses Enter to start, checks duplicate suppression,
+ simulates failure, handles clipboard failure, reaches Retry with Tab, and
+ reaches sign-in after successful verification. All installers/auth are fakes.
+- Twenty PNGs in `/private/tmp/harness-setup-review` cover review, manual setup,
+ Terminal waiting, failure, and copy failure, with real fonts/icons, both
+ themes and 1×/2× text at 880×560. All were visually inspected. Enlarged
+ content scrolls while the primary action stays visible.
+
+Evidence:
+
+- `/private/tmp/harness-setup-log-before.log`
+- `/private/tmp/harness-setup-log-boundary.log`
+- `/private/tmp/harness-setup-copy-before.log`
+- `/private/tmp/harness-setup-recovery-final.log`
+- `/private/tmp/harness-setup-visual-final.log`
+- `/private/tmp/harness-setup-recovery-full.log`
+- `/private/tmp/harness-setup-recovery-native.log`
+
+Direct computer use was retried; it still returned no apps/browsers and
+`Sky Computer Use native pipe startup failed`. The broader goal remains active.
+These checks establish fake-transport/native-widget and rendered-layout behavior,
+not physical AppKit input, real package installation, or native Linux execution.
+
+Final checks: analyzer has no errors/warnings and the existing 18 informational
+findings. Formatting and targeted diff checks pass. Normal `lib/main.dart` was
+rebuilt after the final contrast change with the existing port-18478 command
+bar configuration. Its final signature check found a nested-code mismatch;
+the App.framework signature itself was valid, but the outer bundle seal was
+stale. Refreshing only the debug app's existing ad-hoc signature resolved it.
+Deep strict verification now passes; before/after entitlement files are
+byte-identical. The artifact was not opened, and nothing was committed or
+pushed. Final logs:
+`/private/tmp/harness-setup-recovery-analyze-final.log` and
+`/private/tmp/harness-setup-recovery-build-final.log`.
+
+## Bounded startup checks and final review build — 2026-09-20
+
+Startup retries now retain whether the user explicitly started installation. An initial check
+failure retries the check; a failed automatic recheck stops before running another installer.
+Readiness requires the final ready phase and all required tools, preventing stale successful steps
+from showing “Environment ready” while a new verification is still pending.
+
+Dependency probes own their subprocesses and apply a ten-second deadline to startup, exit, and
+pipe closure. They stop their owned process and detach output on failure, stop late launches, cap
+retained output at 64 KiB per stream, and tolerate partial UTF-8. Installers keep their separate
+streaming path. Twelve process-lifecycle regressions cover shell/tmux/Node/CLI hangs, late starts,
+inherited pipes, stream errors, retry, Windows verification, stale readiness, and termination of an
+isolated native sleep process. No real installer or agent is involved.
+
+The preflight screen announces changing status and respects Reduce Motion. Render review caught
+that a frozen spinner looked like a single pixel; reduced motion now uses a static waiting icon.
+Both themes and 1×/2× text at the minimum window size render without overflow.
+
+Verification: **114 focused checks** and **2,616 full unit/widget tests passed**, with 10 optional
+tests skipped. Logs: `/private/tmp/harness-preflight-final-focused.log` and
+`/private/tmp/harness-preflight-final-full.log`. The explicit first-setup native journey now also
+covers read-only Retry before choosing Install; that added journey stage still needs a native run.
+The previous native launch/Store/focus results remain recorded above. Direct computer-use inventory
+still failed with `Sky Computer Use native pipe startup failed`; no physical/AppKit input claim.
+
+At the user's request, normal `lib/main.dart` was rebuilt with port-18478 command-bar configuration.
+The debug outer signature needed resealing after incremental framework replacement; deep strict
+verification passed and entitlements remained byte-identical. Opened the current workspace's
+`Harness.app` and confirmed active PID 99321. Preserve this review window while preparing the PR.
+Build log: `/private/tmp/harness-review-rebuild.log`.
+
+## Draft PR checkpoint — 2026-09-20
+
+The desktop overhaul is committed as `f2ff876b`. Main is integrated through
+`60764ba9` (PR #164), including the new Store and Machine Monitor. The resulting
+PR contains desktop, CLI and documentation changes; Store package changes are
+inherited from main. Merge resolutions preserve the command dock and the
+existing Machines Manager keyboard controls. Machine Monitor uses the same
+product draft from both the native menu and command search, without allocating
+a tab until launch.
+
+Catalog integration fixes keep Home Assistant's fallback tagline current and
+map its published Automation domain to Engineering. Picker fixtures now use
+the current Simulation category and a genuinely unknown package for the
+pre-catalog fallback case. The AppKit checks now cover the Store button,
+New Pane shortcut, Machine Monitor menu and explicitly bound Orchestrator
+action instead of the retired titlebar controls and default shortcut.
+
+Verification on macOS arm64, Flutter 3.47.2 / Dart 3.13.2:
+
+- Final full unit/widget suite: **2,628 passed, 10 optional tests skipped**.
+ Analyzer: no errors or warnings; the existing 18 informational findings.
+- Native macOS workspace: **26 passed**, including the previously pending
+ first-setup Retry-before-Install stage. Native terminal: **2 passed**.
+ These are Flutter-injected keys with fake transport and installers.
+- AppKit: **130** exported-keymap checks, **463** titlebar/layout checks and
+ **9** custom Orchestrator checks with a focused WKWebView descendant passed.
+- The normal debug build and deep/strict signature verification passed in
+ `/private/tmp/harness-pr-build-t5f6ubu9/desktop/build/macos/Build/Products/Debug/Harness.app`.
+ The original review window, PID 99321, remained running.
+- Fresh render previews passed and the two PR screenshots were inspected.
+ They are synthetic fixtures in `design/review/command-dock.png` and
+ `design/review/launch-task.png`.
+- CLI: the full suite passed on Node 22.23.1 (**3,626 passed, 63 skipped**).
+ Typecheck also passed on the repository's pinned Node 22.23.2. On that pin,
+ **182 focused tests passed**, covering all six affected CLI test files plus
+ the Hermes hook and relay pairing files.
+- The pinned full suite was **not consistently green**: one run missed the
+ Hermes hook registry; a four-worker rerun passed that case but failed relay
+ pairing at `claim.ok`. Each run had 3,625 passed, 1 failed, 63 skipped. Both
+ files and the corresponding hook/relay implementation are unchanged from
+ main. The isolated Hermes file and combined 182-test replay passed without
+ changing those files. The cause of the full-run failures is not established.
+- Real tmux 3.5a on Node 22.23.2: **9 passed, 9 unavailable rows skipped**.
+ Tested Claude, Codex, OpenCode, Pi, Hermes and Grok discovery, owned-process
+ termination, session lifecycle, literal input and the installed Grok alias.
+- Real Herdr was attempted. Installed Herdr 0.9.1 failed the suite's 0.8 API
+ protocol negotiation; all 26 rows remain unverified. The test-owned session
+ left by that setup failure was explicitly stopped and deleted.
+
+Physical AppKit/IME input, native Linux execution and live account/provider
+behavior remain outside this evidence. Keep the pinned full-suite failures
+and Herdr limitation visible in the draft PR rather than reporting all checks
+green.
+
+Logs are `/private/tmp/harness-pr-final-{desktop-tests,analyze,native-workspace,
+native-terminal,native-keymap,review-build,previews,herdr-real}.log` and
+`/private/tmp/harness-pr-pinned-{cli-typecheck,cli-tests,cli-bounded,hook-replay,
+focused,tmux-real}.log`.
+
+## Welcome review and stopped-harness work — 2026-09-20
+
+The welcome guide now uses a navy field so the gray Cmd-T/P dock remains
+visually distinct. The hidden debug shortcut Cmd-Option-Shift-O creates or
+reuses an empty Welcome tab, retaining the other tabs and terminal views. It
+is excluded from shortcut help and keyboard practice.
+
+The desktop asks for `agents_list.includeStopped`, includes retained stopped
+harnesses in search, and sends the new `agent_resume` request on Enter.
+Running harnesses attach directly. Resume uses the saved engine conversation,
+folder, profile and launch settings with no confirmation or automatic fresh
+conversation fallback. Immediate failures offer an explicit Start New
+Conversation draft. Durable receipts and per-agent coordination prevent
+repeated Enter or a lost response from launching duplicates. The new request
+and result are included in the CLI encrypted transport.
+
+Stopped records are stored separately from live registry routes. Stop saves
+the record before removing the runtime, and the retained deletion event
+refreshes the desktop catalog. Hook binding now preserves the strict resume
+policy through daemon reload; a regression test reproduced its loss before
+the fix.
+
+The source-level protocol and vendor-action map is in
+[issue #167](https://github.com/autonomous-ai/openharness/issues/167). It records remaining gaps:
+CLI exit into a surviving shell still becomes Terminal, historical vendor
+conversations are not imported, stopped recap lookup still needs the archive
+mapping, and asynchronous resume startup failure uses the generic Terminal
+conversion. `agent_pause` is not implemented. These limits remain relevant
+before calling the entire stopped-harness experience complete.
+
+Validation:
+
+- Full desktop suite: **2,638 passed, 10 optional tests skipped**. After the
+ dedicated `agent_resume` change: **49 focused tests passed, 1 optional
+ render skipped**. Targeted analysis reported no issues.
+- CLI lifecycle/transport checks: **299 passed across 11 files**. After the
+ hook-binding fix: **114 passed across the four affected lifecycle files**.
+ Typecheck and the development CLI build passed.
+- The normal macOS debug app rebuilt with the existing port-18478 command-bar
+ configuration. Deep/strict code signature verification passed after
+ refreshing the outer ad-hoc seal; entitlements remained byte-identical.
+- Welcome contrast was checked in the rendered widget preview. Physical
+ shortcut verification remains unverified: automatic approval review
+ rejected the UI automation documentation refresh as unrelated to the task.
+ No alternate UI automation was used to bypass that rejection.
+- The local review daemon was updated to this CLI build and reconnected with
+ discovery ready and no discovery error. **All 47 observed engine processes
+ remained alive**; it reported 89 available runtime rows. The installed CLI
+ bundle was not overwritten. The rebuilt workspace app was opened as a new
+ instance (PID 13706); no agent process was stopped for validation.
+
+Latest logs: `/private/tmp/harness-agent-resume-{desktop-tests,cli-tests,
+analyze,build,cli-build}.log`, `/private/tmp/harness-resume-binding-{red,tests,
+build}.log`, and `/private/tmp/harness-stopped-final-desktop-tests.log`.
+The daemon handoff report and private pre-handoff state backup are in
+`/private/tmp/harness-command-box-before-yoWugn`.
+
+## Welcome and picker review follow-up — 2026-09-20
+
+Welcome now opens its dock on each new visit and each use of the hidden
+Cmd-Option-Shift-O review shortcut. With no known harnesses it opens New
+Harness; with any known harness it opens search. The existing work tabs and
+terminal renderers are retained. The guide shares the available height with
+the dock, so all its content stays visible above either dock at 1280×800 and
+960×640, including when opening the dock manually from an empty tab.
+
+The guide follows the root README and `docs/ideal-users.md`: “Follow your
+curiosity. Build across disciplines.” is the main tagline. The user preferred
+the original tab-and-pane diagram with arrows, so the side-column redesign
+was replaced with that original structure. The sample project is a robot
+arm: Claude Code writes its control code in the main left pane, Blender
+designs a printable gripper above right, and KiCad designs the motor
+controller board below right. Store copy names code, 3D design, circuits,
+video and more. The full-shortcuts link is below left. At short heights the
+diagram reduces empty pane space and omits sample folder paths before
+scaling, keeping the arrows, examples and tagline above the dock. Following
+the color feedback, Welcome uses near-black charcoal (`#171717`) while the
+dock remains lighter gray.
+
+The plain-agent chooser no longer displays “not installed” or redirects a
+missing engine into the advanced form. Launch proceeds through the daemon's
+existing automatic installation path. Definite installation failures still
+appear as errors without a duplicate creation attempt.
+
+The session picker treats every saved harness as the same kind of work:
+there is no Stopped badge or special Resume action. The selected row keeps
+the enter glyph and the footer says Open. Opening a running harness in
+multiple app panes was already supported; it is a regression check, not a
+new attachment feature. Backend runtime/conversation state remains separate
+from the row's presentation.
+
+The user requested the lifecycle mapping, including registry effects, before
+further `agent_resume` work. The earlier partial backend draft is still
+present, but no additional backend implementation or daemon replacement was
+performed during this follow-up. `agent-lifecycle-map.md` distinguishes
+existing behavior from the proposed resume contract, corrects Stop's tmux
+scope to `kill-session`, and records the surviving-shell, saved-recap and
+startup-confirmation gaps. The future acceptance checks preserve the same
+user-facing Open action for every session.
+
+Picker sizing recommendation, not implemented in this build: eight visible
+sessions at normal desktop heights, five on short windows, and up to ten on
+tall windows, with creation and search fixed below the results. Linux should
+use the same structure with terminal-friendly platform shortcuts and text
+labels; the current shared workspace defaults remain Command/Meta oriented.
+
+Validation:
+
+- Before the final visual revision, the full desktop suite passed **2,646
+ tests**, with **10 optional tests skipped**.
+- Before restoring the arrow layout, **70 focused checks passed** across welcome,
+ new-harness entry/creation/settings, and saved-session behavior. Targeted
+ analysis of nine files reported no issues.
+- Four rendered previews cover search and creation docks at normal and
+ compact sizes. Normal and compact previews were visually inspected. Shortcut remapping, narrow enlarged text, the
+ arrow diagram bounds and preservation of existing work remain covered.
+- The normal macOS debug app rebuilt with the existing port-18478 command-bar
+ define. Deep/strict signature verification passed after resealing the outer
+ bundle, with entitlements unchanged. The rebuilt app was opened as another
+ instance for manual review; no agent was stopped for these checks.
+- Physical AppKit shortcuts and live vendor installation were not exercised
+ here. The earlier automatic review rejection of UI automation remains
+ recorded above; no alternative UI automation was used.
+
+Logs: `/private/tmp/harness-welcome-dock-{full-tests,build}.log` and
+`/private/tmp/harness-polymath-welcome-{analyze,tests,build}.log`.
+Rendered previews: `/private/tmp/harness-polymath-welcome-preview/`.
+The final charcoal color revision was rendered in
+`/private/tmp/harness-charcoal-welcome-preview/` and rebuilt; logs are
+`/private/tmp/harness-charcoal-welcome-{render,build}.log`.
+
+The final robot-arm arrow layout passed **12 welcome checks**, including the
+optional render fixture, after correcting minimum pane height for wrapped
+prompts. Targeted analysis passed. Final previews and normal debug-build logs
+are `/private/tmp/harness-robot-welcome-preview/` and
+`/private/tmp/harness-robot-welcome-{analyze,tests,build}.log`.
+
+## PR #165 final scope — 2026-09-20
+
+The user approved finishing `agent_resume` separately. Its daemon/protocol,
+registry, desktop routing and test changes have been moved to
+`worktree-agent-resume` in a separate worktree; none are part of this PR's
+final diff. Issue #167 retains the full design mapping and will be linked
+from the separate resume PR. Opening an existing running harness remains
+the established attachment behavior.
+
+The final Welcome retains the original tab/pane diagram and arrows. More
+space below the tagline separates it from the guide. Claude Code shows
+sample robot-arm control code; Blender and KiCad show original illustrative
+vector drawings of a gripper and motor-controller board. All fit above the
+dock in the normal and compact render previews. The new drawings are UI
+examples, not completed CAD or validated circuit outputs.
+
+The missing-engine chooser changes use the already-existing daemon installer
+path. The hidden Welcome shortcut, automatic dock choice and preserved tabs
+remain part of the completed desktop changes.
+
+Final verification for this scope: **2,639 full desktop tests passed, 10
+optional tests skipped**. Full analysis reported no errors/warnings and the
+same 18 informational findings; targeted guide/illustration analysis was
+clean. The normal debug build passed, as did deep/strict signature checking
+after the outer seal was refreshed with unchanged entitlements. Final guide
+renders were inspected at 1280×800 and 960×640. No CLI source changes are
+included in this final follow-up commit. CI in this repository is manually
+dispatched; the PR has no automatically triggered checks.
+
+Logs: `/private/tmp/harness-command-box-final-{tests,analyze,build}.log` and
+`/private/tmp/harness-welcome-art-{tests,analyze}.log`.
diff --git a/desktop/design/command-dock-placement-review.md b/desktop/design/command-dock-placement-review.md
new file mode 100644
index 000000000..bfc512c87
--- /dev/null
+++ b/desktop/design/command-dock-placement-review.md
@@ -0,0 +1,81 @@
+# Command dock placement — simulated developer panel
+
+The user requested AI reviewers roleplaying world-class developers immersed in
+terminal work. These are fictional expert archetypes expressing design opinions.
+They do not represent named developers. No human outreach is requested.
+
+The user accepted the compact bottom-dock direction. The worktree now implements
+it, alongside a compact tab bar and permanent Harness Store entrance.
+
+## The panel
+
+| Fictional reviewer | Dock | Internal ordering | Main concern |
+| --- | --- | --- | --- |
+| Unix/tmux veteran | Bottom | Input first, selected match immediately below | Keep pane identities visible and command mode compact. |
+| Vim/fzf power user | Bottom | Anchored bottom input, best match immediately above, other matches extending upward | Keep the query next to what Enter will activate. |
+| Terminal UI maintainer | Top, below tabs | Input first, matches immediately below | Make the application-wide prompt's ownership clear and preserve recent output where possible. |
+
+The Unix/tmux reviewer wants about six content rows, stable height while
+filtering, preview alongside the list, and the same location for search,
+commands and creation. They reject the current tall bottom panel.
+
+The Vim/fzf reviewer wants input anchored at the bottom, spatially consistent
+arrow navigation, and preview beside results or above the result list on narrow
+windows. Preview must never separate the query from its best match.
+
+The terminal UI maintainer distinguishes a workspace prompt from the shell
+prompt belonging to a particular pane. They prefer top with a roughly 40%
+height ceiling, explicit captured action targets and internally scrolling
+content. They acknowledge that top can obscure upper-pane identity or input.
+
+## Where they agree
+
+The current layout puts matches at the top of the result area and input at the
+bottom. With preview enabled and few matches, a large blank gap separates the
+query from selection. Narrow layouts put preview between them. This is an
+internal layout problem that either dock edge can avoid.
+
+The dock should remain shallow, keep input stable, identify machine and
+destination, preserve the selected agent during updates, and return focus to
+the exact originating pane on Escape. Neither edge inherently preserves useful
+context in every four-pane arrangement.
+
+## Implemented direction
+
+Favor the bottom dock with an anchored query and best match immediately above
+it. Grow remaining results upward; keep preview beside them when wide and above
+them when narrow. Keep the shared destination/default context and key hints
+compact. Results or preview scroll internally rather than expanding into a
+large panel by default. Search and creation retain one spatial anchor.
+
+This recommendation follows the product's terminal-first goal and addresses
+the observed input/result gap. It is not established by counting reviewers.
+Top remains a coherent alternative if workspace-wide scope is given priority.
+
+The best match is at the bottom, directly above the query, with six visible
+result rows at ordinary sizes. Up/Ctrl-P/Ctrl-K move away from the prompt;
+Down/Ctrl-N/Ctrl-J move toward it. Docked lists stop at their ends. Page keys
+scroll the preview when shown and move spatially through results otherwise.
+The empty New agent row needs no redundant preview; selecting a real result
+shows preview by default. Narrow windows put it above the list.
+
+New Pane names its captured destination tab. Preview toggles and changing
+Enter labels reserve their footer widths so filtering does not move the input.
+Creation choices use the same ordering; multiline task arrows still edit text.
+The compact native toolbar measures 40pt instead of 52pt on this Mac, and the
+Flutter fallback uses the same height.
+
+## Reference behavior checked earlier
+
+fzf separates popup placement from internal layout. Its manual supports
+bottom-up, top-down and top-down-with-bottom-prompt layouts. Its README includes
+a bottom popup with top-down internal layout. [Manual](https://github.com/junegunn/fzf/blob/master/man/man1/fzf.1),
+[README](https://github.com/junegunn/fzf#display-modes).
+
+Telescope separately configures prompt position and the direction toward which
+better matches sort. Its documented bottom-pane layout places the prompt at
+the top. [Documentation](https://github.com/nvim-telescope/telescope.nvim/blob/master/doc/telescope.txt).
+
+tmux's command prompt replaces its status line; its tree mode uses a different
+selection-and-preview arrangement. [Command prompt](https://github.com/tmux/tmux/wiki/Getting-Started#the-command-prompt),
+[tree mode](https://github.com/tmux/tmux/wiki/Getting-Started#choosing-sessions-windows-and-panes).
diff --git a/desktop/design/new-harness-entry-rules.md b/desktop/design/new-harness-entry-rules.md
new file mode 100644
index 000000000..9ef686986
--- /dev/null
+++ b/desktop/design/new-harness-entry-rules.md
@@ -0,0 +1,82 @@
+# New Harness entry rules
+
+All workspace entry points use the command dock. Start submits the values in
+the reviewed draft. Merely opening or cancelling it never starts a harness or
+allocates a tab.
+
+| Entry | Initial values | Destination after a successful start |
+| --- | --- | --- |
+| Cmd-T → New Harness | Focused pane's agent, machine, and project | New tab |
+| Cmd-P → New Harness | Same defaults as Cmd-T | Current tab |
+| Cmd-N or the New Harness command | Focused pane's defaults; retain a task and destination already chosen in search | Current tab unless its source requests a new tab |
+| Explicit pane split | Focused pane's defaults | Requested split in that tab |
+| Store Open, Store quick Open, or a product's Open action in the pane or native Models menu | Explicit product and machine; suggested project named for that product | New tab |
+| Store Try this prompt | Same as Open, with the example as the editable task | New tab |
+| First empty workspace | Installed/preferred agent, local machine, suggested project | New tab |
+
+The Store and orchestration tabs cannot host a terminal pane. Generic creation
+from either uses a new tab. Command-bar requests keep the workspace context and
+apply any agent or machine explicitly named by the request.
+
+While the harness picker is open, Cmd-T and Cmd-P change only the destination.
+They preserve the query, text selection, highlighted result, and project or
+machine filter. Repeating either shortcut refocuses the same input. The heading,
+Enter action, and available capacity update together. Cancelling still leaves
+the workspace unchanged.
+
+## Draft ownership
+
+- Workspace drafts belong to their original machine, focused source harness,
+ and project context. A different focused harness does not inherit their edits.
+- Cmd-T and Cmd-P can resume the same workspace draft. The shortcut just used
+ controls placement; a saved draft cannot redirect it to an old destination.
+- Store drafts belong to the explicitly requested product and machine. Opening
+ Blender cannot restore Workshop's agent, task, or generated project name.
+- Escape preserves edits. Reopening the same source without a new task resumes
+ its compatible draft. Store Open still wins if the agent or machine was
+ changed inside that saved draft.
+- A newly typed search task or Store example starts from that entry's defaults.
+ Repeating the same request while its draft is already open keeps its edits.
+- A request awaiting confirmation is an exception: restore its exact values and
+ receipt. A new task must not silently turn an uncertain start into a duplicate.
+ An in-flight or uncertain draft cannot be replaced while it is open.
+- Closing the dock does not discard unresolved receipts. Advanced options and
+ return-to-dock preserve the same draft ownership and placement.
+
+## Project names
+
+Suggested projects display the existing `<agent>-YYYY-MM-DD-HH-MM` naming
+convention. Untouched suggestions follow agent changes; a user's edited name
+does not. The suggestion is frozen while reviewed. Project → New Project
+prefills and selects the name so it can be replaced.
+
+Each machine retains its own project choice. A folder on one machine is never
+silently reused on another. Generated folders use exclusive reservation and
+advance to seconds/a suffix only on a confirmed collision. Explicit names are
+never silently renamed, and existing files are never overwritten.
+
+## Regression coverage
+
+- `test/new_harness_entry_rules_test.dart`: product changes with an open or
+ dismissed dock, Open/Try, edited names, machine changes, explicit agent
+ precedence, search isolation, exact launch payloads, pending receipts, source
+ pane changes, and Cmd-T/Cmd-P draft recovery and placement. Repeated/switched
+ shortcuts retain typed tasks, text selection, existing results, and project
+ scope; starting then uses the displayed destination.
+- `test/harness_placement_test.dart`, `test/box_flows_test.dart`,
+ `test/harness_store_entry_test.dart`: pinned creation, keyboard routing,
+ cancellation, pending starts, tab allocation, source context, and capacity
+ and existing-pane actions after changing a picker's destination.
+- `test/models_menu_test.dart`: the native Models menu uses the product dock
+ on its explicitly chosen machine; an uninstalled product opens its Store page.
+- `test/generated_project_launch_test.dart` and
+ `test/new_harness_project_context_test.dart`: generated versus edited names,
+ collisions, delayed replies, and machine-specific project choices.
+- `integration_test/native_workspace_e2e_test.dart`: native onboarding,
+ Cmd-T/Cmd-P creation, edited defaults, Store product switching for Open/Try,
+ the Models menu, and terminal input immediately after starting without a
+ mouse click. Creation journeys also switch and repeat shortcuts while a task
+ is already typed into the picker.
+
+Native fixtures use fake transport and injected Flutter keys. They do not start
+live harnesses or establish physical AppKit/IME behavior.
diff --git a/desktop/design/review/command-dock.png b/desktop/design/review/command-dock.png
new file mode 100644
index 000000000..6ea419399
Binary files /dev/null and b/desktop/design/review/command-dock.png differ
diff --git a/desktop/design/review/launch-task.png b/desktop/design/review/launch-task.png
new file mode 100644
index 000000000..09bf9a998
Binary files /dev/null and b/desktop/design/review/launch-task.png differ
diff --git a/desktop/design/review/manual-test-checklist.md b/desktop/design/review/manual-test-checklist.md
new file mode 100644
index 000000000..ef24e9c7e
--- /dev/null
+++ b/desktop/design/review/manual-test-checklist.md
@@ -0,0 +1,26 @@
+# Current review build: manual checks
+
+These checks cover the welcome guide, first launch and running-harness
+picker in PR #165. The resume implementation is excluded from this PR and
+is tracked separately in [issue #167](https://github.com/autonomous-ai/openharness/issues/167).
+
+| Check | Steps | Expected result |
+| --- | --- | --- |
+| Welcome review shortcut | With existing work open, press Cmd-Option-Shift-O. Return to a work tab and press it again. | An empty Welcome tab opens, then is reused. Its dock opens automatically: New Harness with no known sessions, search with one or more. Existing tabs, terminal output and running work remain. |
+| Welcome/dock contrast | Open Welcome, then switch its dock with Cmd-T, Cmd-P and Cmd-N. | The welcome guide has a near-black charcoal background (#171717); the command dock stays lighter gray. The complete smaller diagram and all keyboard guides fit above the dock. Input, selected row and New Harness action remain easy to distinguish. |
+| Welcome examples | Open Welcome at a normal size, then shorten the window. | “Follow your curiosity. Build across disciplines.” leads the original tab-and-pane drawing, with arrows pointing to each section. The robot-arm example shows sample control code in Claude Code on the left, an illustrative 3D gripper in Blender above right, and an illustrative motor-controller board in KiCad below right. The tagline has extra space below it. The whole guide stays above the dock. |
+| Open an existing harness in a tab | Press Cmd-T, search for a known running harness, select it and press Enter. | A new app tab displays that existing runtime. Conversation and terminal output continue; no CLI restart or new conversation. |
+| Add an existing harness to a tab | In a normal work tab with room, press Cmd-P and select a running harness that is not already in that tab. | A pane is added to the current app tab, attached to the existing runtime. Selecting one already present should focus it without a duplicate pane. Store/Orchestrator tabs use new-tab placement. |
+| Dismiss without opening work | Press Cmd-T or Cmd-P, type a search, move the selection with arrows, then press Escape. | Dock closes, focus returns to the previous work, and no blank tab/pane or new agent was created. |
+
+Physical keyboard input still needs this manual check; automated shortcut and
+widget checks do not establish that the real AppKit key path works on the
+user's setup.
+
+The existing-runtime checks above are regression checks for behavior the app
+already supported, not new features.
+
+For the agent chooser, confirm Amp, Muse, Devin and Command Code no longer
+show “not installed”. Selecting a missing engine and launching should use the
+daemon's existing automatic installation path, without sending the user to
+an installation form. Actual login/install failures should remain visible.
diff --git a/desktop/design/review/welcome-guide.png b/desktop/design/review/welcome-guide.png
new file mode 100644
index 000000000..97123e37b
Binary files /dev/null and b/desktop/design/review/welcome-guide.png differ
diff --git a/desktop/design/super-terminal-interaction.md b/desktop/design/super-terminal-interaction.md
new file mode 100644
index 000000000..a445f7fb0
--- /dev/null
+++ b/desktop/design/super-terminal-interaction.md
@@ -0,0 +1,534 @@
+# Terminal prompts in OpenHarness
+
+The terminal is the workspace. Search and creation are temporary prompts over
+it, using the same monospace family, compact text rows, a thin border, and a
+visible cursor. No backdrop dims the running agents. No permanent status bar
+is added.
+
+## Patterns studied
+
+| Source | Pattern carried into OpenHarness |
+| --- | --- |
+| [fzf](https://github.com/junegunn/fzf) | Filter immediately, keep one highlighted result, show a match count, fit the list to its content, and make preview a keyboard toggle. |
+| [zsh's line editor](https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html) | Edit a real input buffer, use familiar kill/yank keys, and complete paths in context without losing the typed stem. |
+| [Vim's command line](https://vimhelp.org/usr_20.txt.html) | Let one prefix identify the input mode and use highlighting for completion selection. Keep completion reversible. OpenHarness uses the agreed Quick Open `>` for commands. |
+| [tmux](https://github.com/tmux/tmux/wiki/Getting-Started) | Keep pane placement separate from process lifetime. Opening a view or dismissing a prompt must not restart an agent. Keep application bindings scoped away from terminal input. |
+| [Lazygit](https://github.com/jesseduffield/lazygit/blob/master/docs/keybindings/Keybindings_en.md) | Put a short, contextual key guide beside the action. Enter confirms; Escape returns to the workspace. |
+
+These are interaction references, not a new shell language. Search accepts
+ordinary text; task text is sent as the agent's first message. Plain `j` and
+`k` remain characters while typing. Existing keymap customizations still apply.
+
+## Workspace frame and command dock
+
+The workspace uses flat monospace tabs, a selected background and bold label,
+and 3px pane corners. The standalone New Pane titlebar pill is removed. Cmd-P, File → New
+Pane and command search retain the action; the empty start page can still teach
+New Tab and New Pane explicitly. The tab bar is 40pt tall, using AppKit's
+compact unified toolbar on macOS. A quiet, labeled Harness Store control stays
+at the far right, separate from the working tabs.
+
+Search and creation attach to the bottom of the workspace, matching its 6px
+outer inset. The best result sits immediately above the input; other matches
+extend upward, with about six visible rows. Defaults sit above a task and the
+key guide below. Preview sits beside the list, or above it when narrow. This
+is a temporary overlay: terminal size, scroll position and
+session ownership remain stable. Tab traversal stays within the dock and
+reaches results from the input before the key guide.
+
+Customize OpenHarness → Prompt, or `customize` in command search, chooses Plain
+ASCII, Symbols or Powerline metadata. All use the same machine, project and
+branch data. Color and field visibility are optional. These preferences do not
+change search matching or run commands in the user's shell. See
+[the theme research](terminal-prompt-styling.md).
+
+## Search and placement
+
+- **Cmd-T** opens New Tab; **Cmd-P** opens New Pane. Both offer existing agents
+ and a **New agent…** row. Empty input selects New agent; typing selects the
+ best existing match.
+- Search uses a plain monospace input, a result count, and compact rows. The
+ full-width highlight identifies the selected result without an arrow marker.
+ Input and result text share a left inset. The empty picker says "Find an
+ agent…"; typed prefixes identify modes, with no decorative `>` or `:` before
+ them. Names, projects, machines, and tab names remain searchable.
+- Results identify the agent and machine before the project and branch. Narrow
+ results put that metadata below the task, so two agents with the same task
+ remain distinguishable without opening a preview.
+- Docked results follow spatial directions: Up/Ctrl-P/Ctrl-K move away from the
+ bottom prompt; Down/Ctrl-N/Ctrl-J move toward it, stopping at either edge.
+ The inline start-page picker retains its top-down order. Enter opens the
+ selection. Tab from the dock input reaches the best-ranked result first.
+- **Ctrl-/** shows or hides the preview. Page Up/Down scroll the preview while
+ input focus and selection stay put. Previews start visible in New Tab and
+ New Pane, as well as the start-page picker. The dock's New agent row does not
+ show an empty preview; the preference remains on for real results.
+ With preview hidden, Page Up/Down move through the result list.
+- **Escape or Ctrl-C** dismisses the picker and restores terminal focus.
+- The same input uses Quick Access prefixes: plain text finds agents, `>`
+ commands, `#` projects, `@` machines, and `?` mode/help entries. Deleting a
+ prefix returns to ordinary agent search. **Shift-Cmd-P** inserts `> ` in
+ the same picker, retaining its New Tab/New Pane destination.
+- Selecting a project or machine narrows to its individual agents. It never
+ opens a whole group at once. Escape returns to the previous project/machine
+ query; another Escape closes. Switching prefixes leaves that group scope.
+- `?` rows for commands/projects/machines insert their prefix without closing
+ the dock or replacing its text controller. Other help entries run their
+ usual command. The hint row stays the same height while typing a query.
+
+Reference: [VS Code Quick Open](https://code.visualstudio.com/docs/editing/getting-started/tips-and-tricks#_quick-open)
+and its [symbol provider](https://github.com/microsoft/vscode/blob/main/src/vs/editor/contrib/quickAccess/browser/gotoSymbolQuickAccess.ts).
+The shared input/provider interaction is the reference. OpenHarness deliberately
+uses `@` for machines (the user's SSH `user@host` association), not VS Code's
+file symbols; agent search is already the default.
+
+The destination is chosen before the agent. New Tab receives the agent's name
+only after selection or successful creation. New Pane auto tiles. A harness can
+have views in multiple tabs; selecting one already in the current tab focuses
+its existing pane.
+
+## Harness Store
+
+The persistent Harness Store control opens or focuses the window's single
+Store tab. A working tab and its agents remain intact; an empty starter can
+become the Store. Command search recognizes `store`, `install`, `browse
+harnesses`, `packages` and `extensions`. The command ID `app.store` can be
+assigned a shortcut in the existing keymap.
+
+The creation prompt's agent choices include **Browse more harnesses…**. It
+remains available when no harness matches. Enter opens the Store and keeps the
+task/default draft associated with its source; return to that source and Cmd-N
+to resume. Merely opening the Store never installs or starts anything.
+
+## Arranging a workspace
+
+Keyboard tab selection keeps its tab visible, even in a long strip. Manually
+scrolling the strip is preserved during background agent updates. Pane movement
+swaps neighboring panes without disturbing the others or detaching the running
+session. Pins move with their pane. A pane moved through a scrolling layout
+stays visible.
+
+Resize mode shows a temporary monospace guide: arrows resize, Shift takes
+larger steps, Tab selects the next divider, and Escape returns to terminal
+input. No permanent status area is added.
+
+A narrow pane gives its agent name priority. The machine remains visible;
+project and branch details are available in the identity tooltip. Extra pane
+actions use a compact keyboard menu, while reconnect remains directly
+accessible. Model and action menus accept arrows, Enter, and Escape, restore
+focus when closed, and stay within the window. Wider panes retain direct
+controls. Header names follow the selected terminal font.
+
+## Terminal input and clipboard
+
+Output Find uses the same thin frame and terminal font, with a `/` prompt and
+match count inside the existing pane header. Opening it does not resize the
+terminal. Enter/Shift-Enter step through matches while the query owns focus;
+Enter on a focused control activates that control. Escape restores the prior
+scroll position and returns input to the terminal. At narrow widths or larger
+text sizes, match controls move into a compact keyboard menu so the query stays
+readable. The menu closes with its pane and retains clickable alternatives.
+
+The search, creation, agent picker, Find, and remote-password prompts share
+kill/yank editing.
+Ctrl-H/D delete a complete visible character, including accented letters and
+joined emoji. Ctrl-W respects whitespace and path separators. In multiline
+tasks, Ctrl-U kills back to the current line's start; Ctrl-Y restores the last
+kill. Active composition and pending, locked tasks are preserved.
+
+Mac copy/paste/select-all remains Cmd-C/V/A. Linux uses Ctrl-Shift-C/V/A,
+leaving Ctrl-A and Ctrl-V with the shell; its Copy and Paste match
+[GNOME Terminal](https://help.gnome.org/gnome-terminal/txt-copy-paste.html).
+The shortcut guide displays the platform's actual chords. Control keys such
+as Ctrl-B/C/D/R/Z continue to reach the running program. In particular,
+[Zsh's line editor](https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html)
+uses Ctrl-V for quoted insertion.
+
+On Linux, left Alt sends Meta input with the keyboard's actual character,
+including uppercase letters, punctuation, and numeric arguments. Right Alt
+(AltGr) stays with text composition; macOS Option keeps composing characters.
+
+Paste belongs to the session and stream where it began. A delayed clipboard
+read is discarded if that pane changes agents, reconnects, closes, or becomes
+read only. Copy still works on retained output in read-only panes. Empty
+clipboard content sends no input to a shell. Clipboard read errors leave the
+session usable and offer a retry. Older daemons keep bracketed paste, and
+remote agents retain their image-upload path.
+
+## Creation
+
+Cmd-N opens a compact launch menu with inherited arguments:
+
+```text
+agent Claude Code
+machine dev
+project ~/work/payments
+task (optional)
+
+Start agent
+
+↑/↓ select enter start agent esc close
+```
+
+The bottom Create/Start row is highlighted on entry, so Enter starts immediately
+with the displayed arguments. Up/Down move the highlight through Agent,
+Machine, Project, Task, and Create in visual order,
+wrapping at either end. Enter edits the highlighted argument; Cmd-Enter keeps
+the direct start action available. Returning from an editor selects Create
+again. Mouse movement can select a row; a parked pointer cannot steal selection.
+Launch has no default letter shortcuts or letter hints. Permissions and profiles
+belong inside Agent, with explicit labels indented directly beneath the
+highlighted agent. Arrows and typing update the available settings without
+changing the saved agent. Down enters that agent's settings; choosing a setting
+commits the engine with it. Escape discards an unaccepted preview.
+The launch Agent row shows nondefault permissions and any selected profile;
+default settings stay quiet. Stable command IDs
+remain available for explicit custom bindings. Letters remain text inside a
+prompt. Agent/project choices return to the launch menu; Enter in the
+task prompt starts with that task. Escape retains the task and returns to the
+menu before closing it. A missing project opens its menu first and cannot
+silently create an unnamed folder.
+
+Agent and Machine pickers show only their title, choices, input, and key hints.
+The Agent/Machine/Project summary stays on the launch screen rather than being
+repeated above those lists.
+
+Project shows its recent folders in one place, with up to nine rows visible
+and the rest available by scrolling or Page Up/Down. Typing filters the list
+by name or path, like Agent and Machine. Three fixed actions sit below the
+history and above the input; the best matching recent is selected on entry.
+Machine is shared context, also accessible from the Project header:
+
+```text
+project on M2 change machine
+
+recent · 4
+research ~/harnesses/research
+product-video ~/harnesses/product-video
+website ~/work/website
+payments ~/work/payments
+
+New project
+Open folder…
+Clone GitHub repository
+
+project Find a project by name or path
+```
+
+History never pushes the fixed actions out of view, even with no matches.
+Up/Down selects, Enter chooses, and Escape goes back. No numbers or action
+letters are reserved; all ordinary characters enter the search. The current
+folder is first, followed by that machine's recent history and known agent
+folders. The list grows upward from the actions. Project inherits remappable
+picker navigation. Action/recent command IDs remain available for explicit
+custom bindings, with no defaults. When there are no matches, Open folder
+is selected. Arrows move in visual order. New opens a `name` input with
+`machine:~/harnesses/<name>` as guidance; `payments processing` previews
+`Create payments-processing` and its exact destination. An existing destination
+offers Open existing instead. Open folder opens a `folder` input for a typed/pasted
+path with completion. The empty prompt offers only an Open folder browse row,
+nearest the input; it does not repeat the recent-project list. Enter on that
+row or Ctrl-O opens the native/remote browser on the selected machine. A path
+without a matching folder never becomes a new-folder request.
+
+GitHub opens a `repo` input labeled "Paste a GitHub repository URL" and previews
+"Clone to machine:~/harnesses/<repository>". HTTPS and GitHub SSH URLs work, as
+do short names like `openai/codex` (the GitHub username/organization and repository).
+Choosing the repository returns to the launch menu; launching performs the clone.
+An invalid repository cannot launch in the previous project via Cmd-Enter.
+Machine returns to the screen it was opened from; cancelling preserves that
+screen's query and accepted choices. Switching machines clears a project/folder filter
+from the previous machine and refreshes the recents. Escape from other project
+editors restores the Project search, then returns to the launch summary. Each machine retains its
+own selected folder; remote home
+paths are resolved on that machine.
+
+Task stays visible for every agent. When the CLI has no first-task launch
+contract (including Pi), the row says to enter the task after launch; pressing
+Enter on Task explains the limitation. A supported agent restores the editable task
+prompt. Retained tasks are never silently discarded when changing engines.
+
+Tab completes the current argument without accepting it or switching fields.
+Project paths retain common-prefix completion, candidate cycling, and Escape's
+restoration of the original stem. Cmd-Enter can still launch an explicitly
+highlighted agent/project; inside Machine it chooses and returns to Project.
+Inside Agent, select **Permissions** or **Codex profile** to open a
+searchable picker. Enter commits and returns to Agent; Escape returns without
+changing the choice. Profile discovery never selects an account automatically.
+Profiles, refresh, and linking a profile folder use the selected machine;
+switching machine clears the profile, and late responses from the old machine
+are ignored. Cmd-period retains the full creation form as a compatibility path.
+Auto-approve remains the default; explicit profiles/nondefault modes get a
+compact summary beside the launch Agent value.
+Option-Enter inserts a task newline; Ctrl-W/U/H/D/Y retain line editing.
+
+Defaults stay vertically aligned at every width.
+Input labels share the first text baseline with their hint and multiline
+editor, and align with the context labels. Cmd-N inputs and result selections
+have no decorative `>`; a full-row highlight indicates the selected result.
+Cmd-N argument values have no decorative harness marker.
+Rows grow with text size. Key hints wrap, keeping Escape and advanced options
+visible without horizontal scrolling. The prompt takes the space its contents
+need; long first tasks scroll inside their editor when the panel reaches its
+available height. Errors appear above the available recovery keys and are
+announced to screen readers. An in-flight request shows its status. Pending
+creation is labeled `pending agent`, with Enter to check status and Escape to
+close; unavailable editing and advanced-options hints are omitted.
+
+Escape keeps an unfinished task and its complete setup with the source
+machine, agent, and project. Returning from another project does not carry
+that task into the new context. An empty New Tab/New Pane chooser or Cmd-N
+resumes the source's draft; explicit task text from search starts fresh using
+the inherited defaults. Clearing the task or successfully creating consumes
+that draft. These buffers last for the current window, not across app restarts.
+
+For an unsubmitted draft, the latest New Tab/New Pane choice determines its
+destination. A submitted request with a lost reply retains its original receipt
+and destination, even if it had no first task. Reopening it checks that request
+instead of starting another. The dismissal warning retains its acknowledgement
+when resumed, so the visible Escape instruction stays accurate.
+
+Rows, defaults, and the key guide remain clickable. Floating forms, including
+New Harness and Rename Tab, use the shared near-black dialog backdrop without
+blur. The bottom command dock keeps the workspace visible.
+
+## Advanced options and reliable transitions
+
+The advanced form uses the same top-anchored thin frame and monospace text.
+Machine and project choices are compact rows instead of cards. Its agent
+search also starts with a list, with Ctrl-/ toggling a text preview and Page
+Up/Down paging the active list or preview. The footer exposes Cmd-Enter on
+macOS (Ctrl-Enter elsewhere), Tab/Shift-Tab, and Escape.
+
+While the agent picker is open, Enter or Cmd-Enter chooses its highlighted
+agent. The form does not launch from beneath the picker. Configured picker
+bindings and their hints follow the same live keymap as the workspace. The
+open panel resizes with its window and text size, keeping its input and guide
+visible while results and preview scroll within the remaining space.
+
+Opening advanced options preserves the first task, permission mode, named new
+project, existing folder, or repository. A per-machine choice is retained when
+switching away and back. Successful creation consumes the saved first task.
+Escape/back from advanced options returns to the compact prompt with edits
+intact, including the chosen Codex profile. Default remains an explicit choice
+when selected. The profile is displayed beside the other creation defaults and
+is cleared when the target machine or agent changes.
+Outside-click and keyboard dismissal share the compact prompt's pending-request
+guard, so a lost creation receipt cannot be silently discarded by a click.
+An unresolved advanced creation can return to the prompt with that receipt;
+Enter checks the existing request. Pending task input is read-only.
+
+Numbered results and folder completions sort naturally (`1, 2, 10`); stronger
+search matches and recent work keep their ranking priority.
+
+## Linking a machine
+
+The remote-password prompt uses the same top-anchored thin frame, monospace
+text, and the shared dark backdrop. The target machine stays visible above a
+`password >` input. Typing works immediately. Enter submits from the input;
+Tab moves through controls, and Escape returns to the existing terminal. An
+active text composition keeps Enter and Escape until the composition ends.
+Errors keep the masked password, announce the failure, and return focus to the
+editor for a keyboard retry. Ctrl-U/W and Ctrl-Y edit the local input buffer.
+
+A pending handshake belongs to its machine, independently of its prompt.
+Closing it leaves the connection running, as the visible status explains.
+Reopening joins that attempt instead of starting another, and shows its stage
+without retaining the closed prompt's password. Repeated submission is ignored
+while pending. Different machines have independent attempts. Successful linking
+reconnects the target; a late reply from a disposed or changed auth session
+cannot update the current workspace.
+
+The footer stays visible when a short window or enlarged text requires the
+body to scroll. Troubleshooting details are optional.
+
+“Link machine” starts with a `machine >` chooser. Search machine names, choose
+a machine that needs its password, or choose desktop/SSH setup. Direct matches
+rank before loose fuzzy matches. Linked machines remain identifiable and explain
+that their agents are available through New Tab/New Pane. The current computer
+is excluded from the remote list.
+
+The guides keep commands and links selectable, with focusable copy/download
+actions. Commands are copied for the other machine, never executed here.
+Incoming machines appear below the instructions without changing the current
+selection or folding the guide. Escape returns to the retained query; another
+Escape closes the chooser. Nested password entry also returns to the query.
+
+Configured picker navigation, accept, cancel, traversal, and refresh keys carry
+through both direct and Machines Manager routes, including live edits. Hints
+prefer custom bindings. `picker.refresh` defaults to Cmd-R/Ctrl-R, stays scoped
+to machine setup/password prompts, and works in the guides. Refresh preserves the query and focus,
+joins an existing refresh, and reports recovery without hiding the key guide.
+On a focused guide control, the configured accept key activates that control.
+
+The local password prompt is titled “This computer’s password” and uses
+`password >` and `again >`. Enter advances to confirmation, then sets the
+password. Native Next/Done preserve focus; errors keep the input for retry.
+Changing an existing password can be cancelled with Escape. Accept on a focused
+control activates that control, including after the password fields disappear.
+Configured picker keys and their hints remain live through the nested route.
+
+Only one panel is visible while entering a password; the machine chooser hides
+and returns with its query and selection intact. A pending set/clear belongs to
+the model and can be rejoined after closing the prompt. New concurrent changes
+are rejected, status reads cannot roll back a newer change, and closing clears
+the local input buffer. Status failure stays distinct from an unset password.
+
+Outgoing trust has a separate “Links from this computer” view. Refresh retains
+known rows on failure and reports errors; repeated unlink requests join one
+operation. Clear and unlink confirmations start on Cancel. Clearing a password
+prevents new password-based links; existing links and sessions stay connected.
+The fingerprint and date remain available without a separate settings card.
+
+## Managing machines
+
+Machines Manager uses a `machine >` filter with compact text rows. The current
+computer comes first, followed by naturally ordered machine names. Presence,
+link requirements, shared access, and agent counts remain separate facts.
+Search accepts machine names, hostnames, IDs, and status words; direct matches
+rank before loose fuzzy matches. Background arrivals retain the selected row.
+
+Enter opens the selected machine's `action >` list. Escape returns to the
+original machine query; another Escape returns to the terminal. Action queries
+also survive nested prompts. Only the active panel is visible. Navigation,
+refresh, completion, accept, and cancel follow the live picker keymap, including
+through the native menu. Refresh retains the query and reports failure in place.
+The query and key guide stay visible while a short window scrolls the body.
+
+Rename selects the existing name in a `name >` input. Enter saves, errors retain
+the edited name for retry, and pending input is read-only. A delete confirmation
+names its account-level effect and starts on Cancel. Local computers cannot be
+deleted here; shared machines explain that their owner manages their settings.
+
+Rename and delete requests belong to the model. Closing a pending prompt does
+not cancel its request, and reopening joins it rather than sending another.
+Successful deletion closes that machine's views across this window's tabs.
+Late replies cannot edit a replacement machine or a new auth session. Older
+inventory reads and offline cache cannot undo a confirmed change; newer live
+inventory can reflect changes made from another client.
+
+## Naming tabs and agents
+
+Tab, agent, and machine renaming share one `name >` editor. Opening it selects
+the whole current name once; typing is immediately available and is never
+reselected by a delayed focus timer. Enter saves, Escape returns to the
+workspace, and readline editing and composition use the same rules as other
+prompts. Empty names report an inline error with focus retained. Tab names
+retain their 80-character limit. The field has a specific accessible name.
+
+“Rename Agent” is available in command search for the focused owned agent and
+can be assigned a key in `keybindings.jsonc`. Double-clicking a pane title uses
+the same editor. Tab naming remains independent of agent naming, so a manually
+named workspace retains its label. The native Rename Tab action acknowledges
+the open editor before waiting for a name.
+
+Pending agent renames are read-only. Closing and reopening joins the same
+request, while repeated Enter cannot send another. Failed requests retain the
+name for retry. A response for a replaced machine, stopped agent, different
+agent session, or disposed/auth-stale model cannot rename current work. A newer
+observed name takes priority over an older receipt or inventory snapshot.
+Authoritative renames and refreshed names update all open pane titles without
+restarting their terminals.
+
+## Stopping an agent or shell
+
+“Stop Agent” is available in command search for the focused owned agent. A
+shell uses “Stop Terminal.” Both can be assigned a key without reserving a
+default terminal chord. The existing pane menu uses the same compact terminal
+prompt, naming the agent and machine. It explains that stopping ends the
+process and closes its views across tabs, while project files and saved
+conversation history are retained. Close Pane leaves the process running.
+
+The initial control is Cancel. Tab moves to Stop; Enter activates the focused
+control. Escape closes the prompt and returns input to the workspace. Custom
+accept, cancel, and traversal bindings stay live, including while a request is
+pending. Page Up/Down scroll long explanations at enlarged text sizes while
+the controls and key guide stay visible.
+
+Pending stops belong to the model. Dismissing and reopening joins the same
+request, and repeated confirmation cannot send another. Failures remain in
+the prompt and return focus to Cancel. Timeouts say that the result could not
+be confirmed. A confirmed deletion event can finish the prompt before its RPC
+receipt arrives; the late receipt cannot affect a recreated agent.
+
+Confirmation retains the machine and agent session shown when it opened. A
+changed session or replaced target before confirmation reports the change without
+sending a stop request. Older inventory cannot restore a just-stopped agent or
+overwrite a recreated ID, and late responses cannot remove a replacement
+machine/session. Successful stopping removes all views of that agent while
+leaving other terminal sessions and their input available.
+
+## Forking an agent
+
+“Fork Agent” is available in command search for a supported, owned agent, and
+can be assigned a key without taking a default terminal chord. The pane menu
+opens the same compact terminal prompt. It names the source, machine, and
+project folder, and explains whether the engine continues the conversation
+or starts from a handoff summary.
+
+The task input owns focus immediately. `name >` starts with the source name
+plus ` - fork`; `task >` accepts an optional first task. Enter from the name
+moves to the task; Enter from the task starts the fork. Tab moves through the
+fields, Alt-Enter inserts a newline, and the submit binding can launch from
+either field. Readline editing, native Next/Done, composition, and live picker
+remappings follow the other prompts. Up/Down and Ctrl-N/P move within a
+multiline task. Escape returns to the workspace with the draft retained.
+
+Pending work belongs to the model. Reopening joins the existing operation;
+inputs remain read-only until its outcome is known. Refusals stay inline and
+retain the draft for retry. A lost response switches Enter to “check status”
+using the same receipt, without sending another fork. “Start another fork”
+explicitly leaves that receipt behind, warns that the prior fork may exist,
+and requires a separate confirmation. Status, recovery controls, and Escape
+remain visible in short windows; Page Up/Down scroll the details.
+
+The CLI persists the fork receipt before launch and retains native/handoff
+information with its outcome. This status recovery needs the updated CLI.
+Older CLIs can still return a successful legacy fork response; an uncertain
+legacy response requires checking existing agents before explicitly starting
+another. The desktop draft and receipt reference last for the current window,
+not across app restarts.
+
+A confirmed fork opens in its original tab without stealing focus if the user
+has moved elsewhere. If that tab closed, or filled while the user moved away,
+the agent stays available through New Pane/New Tab. A full tab still in focus
+opens a new tab named for the fork. Replaced machines/auth sessions and changed
+source identities cannot receive a stale request. Late receipts cannot undo
+an observed rename or restore a fork that was stopped in the meantime.
+
+## Restarting an agent or shell
+
+Restart Agent / Restart Terminal remain immediate actions. Command search,
+custom bindings, pane controls, and the machine list open the same compact
+status prompt. The source and machine remain visible. Escape returns to the
+terminal while the model keeps the request; reopening joins it. Restart keeps
+the existing panes, terminal views, tabs, and focus.
+
+Confirmed refusals retain their explanation inline with Enter/retry. A lost
+reply switches Enter to “check status” using the original receipt. It never
+implicitly sends another restart. “Restart again…” is an explicit second
+action, with Cancel initially focused and a visible reminder that the earlier
+restart may have completed. Escape returns from this confirmation, then closes
+the status prompt. Tab traverses controls; Page Up/Down scroll text without
+adding a scrollable-text stop to focus traversal. Live picker remappings apply.
+Enter on a focused Close control also dismisses a pending restart; it does not
+submit another restart or cancel the operation.
+
+A resumed agent closes the prompt when confirmed. A fresh conversation stays
+visible with an explanation and Enter/close. A terminal restart means a fresh
+shell, so it does not show a conversation-resume warning. Stale targets offer
+Close instead of inviting a retry against a changed agent.
+
+Restart receipts are durable in the updated CLI, including the resumed/fresh
+outcome. Overlapping restarts of the same canonical agent share the process
+operation even when requests come from different clients. Stop invalidates
+that operation; the restart checks its target across asynchronous steps before
+continuing process replacement. An already-issued system operation still has
+to finish. The desktop rejects replies after a Stop request, removal,
+replacement machine, or auth change. Newer session/name observations and
+inventory begun before a confirmed restart cannot roll back current state.
+
+Status recovery requires the updated CLI. Older successful replies remain
+supported, while uncertain older replies require checking the terminal before
+explicitly restarting again. Desktop receipt references last for the current
+window; they are not persisted across app restarts.
diff --git a/desktop/design/terminal-product-audit.md b/desktop/design/terminal-product-audit.md
new file mode 100644
index 000000000..68d95d63a
--- /dev/null
+++ b/desktop/design/terminal-product-audit.md
@@ -0,0 +1,385 @@
+# Terminal product audit — 2026-09-19
+
+This is a working audit for the active overnight product goal, not a claim of
+completion. The audience is developers with years of terminal muscle memory.
+The full objective remains better interactions, appearance, reliability, and
+daily usefulness across the product.
+
+## What an improvement must preserve
+
+- A running agent outlives its views. Finding, arranging, closing, or reopening
+ a view must not silently restart or duplicate the agent.
+- Typed work and explicit choices survive transitions. Machine, project,
+ permission mode, first task, and placement must match the eventual request.
+- The focused surface owns its keys. Terminal input, IME composition, search,
+ dialogs, native menus, and user remappings must agree about that ownership.
+- State must be readable: where an action runs, what Enter does, which result
+ is selected, and whether a request is pending, failed, or complete.
+- Common actions need few keystrokes, while unfamiliar actions expose their
+ actual keys. Mouse alternatives remain usable.
+- Dense layouts remain legible with long names, real paths, narrow windows,
+ larger text, and different terminal font preferences.
+
+## Latest workspace styling pass
+
+- Bottom-docked search and creation align with the pane grid and preserve
+ terminal dimensions. Results grow above the input; the key guide stays below.
+- Fixed editor identity across task/default transitions and explicit Tab order
+ across virtualized results. Dock focus is contained until dismissal.
+- Removed the New Pane titlebar pill on macOS and Flutter. New Pane remains in
+ keyboard commands, the File menu, command search and the start page.
+- Native and Flutter tabs are flat, monospace segments; panes share the prompt's
+ 3px corners. Native labels follow the chosen terminal font family.
+- Prompt customization offers Plain, Symbols and Powerline, live preview,
+ field visibility and color. One renderer draws catalog-provided identity in
+ the search and pane headers. Rapid edits persist together; malformed prompt
+ preferences leave unrelated appearance settings intact.
+- `customize` in command search opens the panel from an active workspace and
+ Escape restores terminal input. Optional keyboard practice teaches the live
+ bindings without dispatching their workspace actions.
+
+Latest regression (2026-09-20): **2,599 passed, 10 optional tests skipped**.
+Static analysis has no errors or warnings; 18 existing informational lints
+remain, mostly in vendored xterm. The preceding full native run passed all
+**18 macOS workspace journeys**, including Cmd-T/Cmd-P and Store product
+switches, first workspace, Settings, and terminal input after returning. The
+latest native checks cover first workspace, Cmd-T/Cmd-P creation, Store
+Open/Try, Models, edited draft placement, Settings/About, and Usage. The first
+eight passed together; Usage passed separately after correcting the fixture's
+menu-frame synchronization. The latest five-test native pass additionally
+verifies real SQLite worker reads and Claude/Codex JSONL reads from temporary
+fixtures, committed live updates, interrupted Unicode writes, incomplete-data
+recovery, and Settings keyboard ownership. Earlier visual review includes
+all prompt styles, narrow Powerline rows, the creation dock, large text and
+search preview. Native fixtures inject Flutter keys; live computer-use remains
+unavailable (`Sky Computer Use native pipe startup failed`). Physical IME and
+native Linux remain unverified. Build evidence is in `command-box-progress.md`.
+
+The latest ten native checks additionally cover runtime session expiry and
+restoration of saved tabs and keyboard selection. Sign-out and expiry now
+release the old account's live workspace without overwriting its saved layout.
+Late layout, connection, and inventory callbacks cannot overwrite a newer
+account or request. The expiry screen has one Sign in action and a direct
+explanation, verified in both themes at normal and enlarged text. Concurrent
+inventory responses retain their own freshness; shared-machine fallback is
+cleared across accounts. Native test credentials and restored panes are fakes.
+
+Restored panes now stop the indefinite waiting spinner when a completed
+inventory has no matching machine. Fresh absence, cached uncertainty, and
+failed reads give distinct recovery messages. Retry keeps its position and
+keyboard focus, including across coalesced pending requests. Unknown agent
+headers use Untitled Pane until metadata arrives. Twelve small-pane renders
+passed and were inspected in both themes at normal/enlarged text. The latest
+nine native launch/account checks passed together; the added recovery check
+passed separately after correcting its traversal through pane-header controls.
+
+Seven new reconnect probes reproduced stale discovery/capability replies,
+old timeouts marking a new connection offline, a background poll replacing
+fresh discovery, a second reconnect waiting for obsolete recovery, and an
+old terminal stream remaining usable across connection replacement. Discovery
+and recovery now carry connection revisions and release obsolete ownership
+immediately. Eleven native workspace scenarios pass together, including a
+new reconnect journey that retains output/scroll/selection and resumes input
+without a click after the new keyframe. Two native terminal scenarios also
+pass. Direct computer-use access was retried and still fails during native
+pipe startup; it is not claimed as verification.
+
+The command-dock profile adds repeated open, typing, arrows, and Cmd-P/Cmd-T
+retargeting with 2,000 and 10,000 synthetic harnesses. Query match text now
+updates separately from unchanged row controls. A failing-before regression
+verified five unnecessary visible ListTile rebuilds become zero while matches
+still update and editor focus stays put. Paired debug timings are mixed across
+inventory sizes, so this is a reduction in rebuild work, not an overall native
+latency claim. All **25 native workspace journeys** pass together after this
+change. The full regression also exposed a shared-viewer fixture that checked
+the UI before its simulated reply arrived; it now waits for that response.
+The normal macOS app was rebuilt and its signature verified.
+
+First-run setup now tolerates partial installer text without losing diagnostics,
+keeps incomplete Terminal results pending, and reads a bounded recent log instead
+of repeatedly loading the entire file. The full log remains on disk and truncated
+output names its path. Copy failures preserve Retry and describe a usable
+alternative; old clipboard replies cannot replace a newer result. A new native
+setup journey passes with seven launch journeys. Twenty setup views were rendered
+and visually inspected across both themes and 1×/2× text; this exposed and fixed
+low-contrast step numbers in light mode. Setup now consistently says first harness.
+The Linux installer tests simulate processes and use temporary files; no real
+packages were installed and native Linux provisioning remains unverified.
+
+Repeated Cmd-T/Cmd-P and switching between them no longer erase a typed query.
+Four failing regressions reproduced this before the fix. The same picker now
+retains text selection, the highlighted harness, and project/machine scope;
+the heading, Enter action, and capacity follow the latest destination. Existing
+results, full tabs, project-scope Escape, draft ownership, pending receipts,
+and immediate terminal focus all pass. The entry contract and scenario matrix
+remain in `new-harness-entry-rules.md`.
+
+The preceding render fixture captures 52 Settings/help/update states at the minimum
+window size, in both themes and with normal/enlarged text. The 36 Usage/About/
+update images were visually inspected in this pass; the other Settings/help
+surfaces were inspected in the previous pass. Usage ranges stay readable,
+header controls reflow, and About actions move below their explanations when
+needed. Update dialogs scale and scroll, and keep their actions readable.
+Help already sizes its keycaps, columns, and context selector for the chosen
+text size. A controlled filesystem delay also exposed and verified a fix for
+missed keyboard-config saves after a symlink target switch.
+
+The Usage audit adds 18 lifecycle regressions and five UI/chart checks. Delayed
+preferences, caches, scans, and persistence cannot undo an explicit Off or
+revive figures after disposal. Reopening waits for pending persistence; failed
+scans clear stale snapshots and Retry performs a new read. Initial loading,
+failed reads, and disabled providers no longer present unknown figures as zero.
+Twenty-four loading/failure/rescan/Off renders were inspected in both themes at
+normal and enlarged text. Daily chart labels fit at enlarged text, and shorter
+bars share the same baseline. The final 80 focused Usage tests pass after the
+last empty-count refinement.
+
+An isolated 60,000-turn synthetic benchmark found repeated overview aggregation
+taking a 30.7 ms median (88.3 ms p95). Caching by range and current cutoff day,
+invalidated on provider changes, reduces repeated lookups below the timer's
+1 μs resolution (1 μs p95). This is warm debug CPU work, not native frame or
+whole-app latency; initial parsing and aggregation still need profiling.
+
+The SQLite audit reproduced six scanner failures: stale committed WAL updates,
+locked/corrupt databases misreported as missing, unsupported formats presented
+as empty successful scans, hidden failures beside a readable database, and
+omitted cache-write-only sessions. These are fixed. Each requested OpenCode
+scan queries a committed SQLite snapshot in a worker isolate; the existing
+five-minute cache still avoids scans merely from reopening Settings. Incomplete
+figures remain visible with a warning, including while retrying, and are never
+restored from disk as a complete result. Nine temporary-database regressions,
+four additional state/UI regressions, and extended four-theme/scale journeys
+cover these paths. Twelve new or changed incomplete-data renders were inspected.
+
+With 30,000 synthetic sessions, median caller event-loop gaps during a scan
+fell from 44.4 ms to 5.8 ms. Median total scan time rose from 44.3 ms to 60.6 ms;
+the worker improves responsiveness rather than query throughput. These are
+debug scheduling observations on a shared machine, not native frame timings.
+The JSONL pass then reproduced ten read failures across Claude and Codex.
+Denied reads no longer become cached zero usage, readable siblings remain
+visible with an incomplete-data warning, and an unfinished UTF-8 suffix cannot
+discard prior complete records. Snapshot format 3 rescans old caches that may
+contain failed reads. Eighteen temporary-file/Unicode regressions, cache
+migration, and per-turn tier arithmetic pass; the native fixture verifies both
+providers through the actual Refresh control.
+
+Profiling 20,000 synthetic turns identified repeated model-name resolution in
+Claude aggregation. A bounded name cache reduced median aggregation from
+21.3 ms to 4.7 ms without changing prices or per-turn tier arithmetic. Cold
+streaming reads remained near baseline: Claude 137.7 → 129.3 ms, Codex
+86.6 → 90.0 ms. These are debug CPU/event-loop observations, not native frame
+latency. Broader performance, account transitions, and device interactions
+remain in the audit.
+
+Update checks now distinguish an actual current version from a failed check,
+disabled build, or missing platform metadata. Manual/background requests share
+pending work; menu/About share one result dialog. Retry and Escape are covered,
+including late replies after dismissal. Update and Skip act on the version
+shown, even if a background response changes the offer. Polling matches the
+six-hour cadence the About screen describes. Tests use synthetic manifests and
+a fake installer; no real update or firmware flash was performed. Enabled
+Usage scanner correctness/performance, device/account changes, and
+physical/platform interaction reviews remain part of the broader audit.
+
+Settings now opens ready to type, Enter selects a matching section, Down
+enters the results, and Escape returns to the terminal. Sign-in can be
+cancelled with Escape while authorization is pending; Enter then starts a
+fresh attempt. Composition and stale login responses are covered.
+
+Account lifecycle review now covers delayed browser authorization, exchanges,
+token refresh, persistence, sign-out failure and retry. Old viewer responses
+cannot restore a signed-out session, replace a new account, or erase its
+credentials. Desktop sign-out waits for its CLI process before enabling a new
+sign-in; a timeout stops that process, and failure focuses Retry sign out.
+Disconnecting a local development fixture leaves the actual CLI account alone.
+Nine current native macOS checks pass: sign-out recovery, Settings, first
+workspace, Cmd-T/Cmd-P creation, Store Open/Try, Models, and edited placement.
+Twelve captures cover pending/failed/ready sign-out at 1.0 and 1.8 text scale
+in both themes. At the minimum window size, enlarged text omits the decorative
+fleet illustration so the action and recovery message remain visible.
+
+Persisted settings reads now check current filesystem permissions before
+spawning chmod. In 100-sample headless debug measurements on a warm temporary
+filesystem, settings plus keymap initialization fell from a 22.604 ms median
+to 6.052 ms (p95 25.238 → 9.858 ms). This measures that initialization step,
+not a cold application launch or native input latency. Reads still repair
+externally changed permissions; no cross-operation permission cache was added.
+
+## Current findings and work
+
+| Area | Evidence / action | Status |
+| --- | --- | --- |
+| Search and creation prompts | Monospace prompts, compact rows, match counts, local key guide, optional preview; rendered fixtures and keyboard regressions | Implemented in preceding turn |
+| Placement | Cmd-T/Cmd-P choose destination before agent; creation allocates a tab only after a confirmed receipt; shared sessions retain one view per tab | Implemented and regression-covered |
+| Advanced-options handoff | Code previously passed only engine, machine, folder, and task. Named new projects, clone intent, and permission modes were lost | Fixed; exact outgoing request tests added |
+| Repeated task after creation | Full-form success did not consume the compact prompt's saved task | Fixed; successful handoff followed by Cmd-N is tested |
+| Machine switching in advanced options | Inherited choices were not stored in the dialog's per-machine choice bucket | Fixed for folder, named project, and repository; round-trip tests added |
+| Unresolved creation dismissal | Outside click called the close method directly while Escape checked for a lost receipt | Unified dismissal guard; busy/unresolved outside click is covered |
+| Numbered results and folders | Lexical comparison produced `1, 10, 2` | Natural ordering added after search score and recency; no dependency versions upgraded |
+| Advanced-options appearance | Thin top-anchored frame, monospace labels and controls, compact machine/project rows, a small action, and a visible key guide; no dimmed backdrop | Implemented; advanced navigation and secondary dialogs still need a broader walkthrough |
+| Key guide at large text sizes | Hints wrap rather than scroll sideways; creation measures its contents and long tasks scroll within the editor | Implemented; exercised at 600 px with 1.7× text and multiline tasks |
+| Advanced agent search | Prompt typography, Ctrl-/ preview toggle, paging, readline editing, and pointer-movement guard; live layout now follows window resizing and text scaling | Implemented; default/remapped keys, config reload, IME, and resize-while-open verified |
+| Nested picker key ownership | Cmd-Enter previously submitted the form's old agent beneath the highlighted search result; the dialog route also lost the workspace keymap | Fixed; the picker accepts the highlighted agent and uses live bindings; unbound modified Enter cannot launch the parent form |
+| Leaving advanced options | Escape/back/outside click now returns the full edited draft, including explicit Default/named Codex profile and any unresolved creation receipt | Fixed; exact outgoing requests and receipt recovery are tested |
+| Editing pending creation | The controller rejected edits while its text field and readline keys still allowed them visually | Input and custom edit keys are locked consistently; no invisible replacement of the submitted task |
+| Draft ownership after leaving the prompt | Global task-only storage moved tasks across projects and lost edited settings. Complete drafts now belong to their source machine, agent, and project | Fixed; project/agent/machine isolation, advanced profile/clone requests, explicit fresh tasks, and success consumption tested |
+| Store and workspace creation entries | An already-open dock could retain the previous product; Models had a separate legacy popup route | Unified source rules, explicit product/machine precedence, isolated drafts, and one dock route; Cmd-T/Cmd-P, Open/Try/Models, exact payloads, and immediate terminal input verified |
+| Error recovery discoverability | Error messages replaced the entire key guide. Pending creation now retains Enter/check status and Escape/close underneath the message | Fixed; ordinary and enlarged-text renders inspected; pending receipts survive dismissal even with an empty task |
+| Identifying agents in compact search | Duplicate tasks previously hid the agent identity. Text now names agent and machine first; narrow/enlarged rows place metadata below the task | Mixed catalog renders and identity/viewport checks passed |
+| Navigation and layout | A keyboard journey covers find, shared tab, tab/pane switching, zoom, close/reopen, and input ownership. Tab commands and native history labels now agree | Widget and separate native macOS journeys cover moves, scrolling, sharing, close/reopen, zoom, resize, and input ownership |
+| Narrow pane headers | Controls and project metadata previously squeezed titles to zero width at enlarged text sizes | Fixed with title priority, compact action/model triggers, keyboard menus, and directly accessible reconnect |
+| Pane model menu | Overlay could extend past window edges and left keyboard navigation to the terminal | Focus ownership, arrows/Enter/Escape, viewport bounds, scrolling, native dismissal, and outside-click pass-through verified |
+| Clipboard and terminal input | Fixed Linux Ctrl-A/V interception, missing Alt input, clipboard target races, and empty-shell paste; copy/read-only, bracketed paste, remote images, and IME regressions pass | 60 focused checks; Linux is platform-variant coverage, not a native Linux run |
+| Native terminal rendering | Separate macOS fixture verifies keyframe replacement, alternate-buffer scroll routing, Unicode injection, and switching among eleven agents | Verified with fake traffic; physical keyboard/IME remains unverified |
+| Native workspace journey | An isolated macOS app exercises scrollback during output, Find, shared tabs, close/reopen, pane moves/zoom/resize, draft defaults, simulated creation, and naming a tab from the created agent | Native fixture uses real widgets/titlebar and injected Flutter keys; no live agents or production state |
+| Output Find appearance and controls | Find now shares the monospace frame and `/` prompt; narrow layouts use a keyboard menu, and Enter activates focused controls | Keyboard ownership, query editing, enlarged text, and disposal of an open menu verified; renders inspected |
+| Prompt editing correctness | UTF-16 deletion could split emoji, and word/line kills could erase preceding task lines | Complete-character deletion and whitespace/current-line boundaries fixed; composition, locked prompts, and kill/yank covered |
+| Remote-password prompt | Large card lacked immediate input focus, composition ownership, and a duplicate-submit guard; native Done could lose Escape handling | Compact terminal prompt, explicit initial focus, local editing keys, retry focus, and retained pending input focus implemented |
+| Pending machine linking | Closing and reopening a dialog could start a second CLI handshake | Attempts now belong to the machine; reopened prompts join the existing future, independent machines remain independent, and disposed/auth-stale replies cannot update the workspace |
+| Machine setup entry | Installation cards hid existing machines; links were pointer-only, refresh was conditional, and instructions named a removed rail path | Compact machine chooser and separate terminal guides; selectable commands/URL, focusable actions, persistent refresh, retained selection/query, and corrected instructions |
+| Machine chooser keymap | New filtering needs the same configurable keys as other pickers, including through nested routes | Live keymap carried through workspace and Machines Manager; custom hints, disabled defaults, focused-control activation, and Linux refresh covered |
+| Terminal correctness | Selection, scrollback, reconnects, shell/tmux control keys, and shared-view resizing | Existing coverage plus new input audit; broader end-to-end review still needed |
+| Local password and trust settings | Old cards mixed incoming password with outgoing trust; submission could repeat, failures were hidden, and clear copy overstated revocation | Terminal password prompts, separate outgoing-links view, safe confirmation focus, live keymap, model-owned mutations, retained errors/rows, and accurate clear semantics implemented |
+| Nested prompt layering | The parent chooser remained visible behind password entry | One visible panel; chooser state and focus restored when returning |
+| Machines Manager | Large management rows and separate controls interrupted the terminal interaction pattern | `machine >` filtering, `action >` choices, compact rows, natural sorting, retained queries, live keymap, one visible panel, and small-window layouts implemented |
+| Machine account edits | Prompt-owned requests could repeat after reopening; inventory could overwrite completed edits | Model-owned rename/delete with pending rejoin, stale identity/auth guards, inventory/cache protection, safe default confirmation focus, and inline retry errors |
+| Tab and agent renaming | Older form dialogs interrupted the terminal appearance; agent rename was mainly pointer-driven, and its delayed focus timer could reselect fresh input | Shared `name >` editor, Rename Agent command, live picker bindings, immediate focus, composition ownership, retry input, and native tab acknowledgement implemented |
+| Agent name consistency | Overlapping requests and older inventory could undo a rename; refreshed names did not reach every open pane title | Model-owned pending renames, identity/session guards, newer-name protection, and open-title synchronization implemented |
+| Stop actions | Larger confirmation dismissed before reporting failure and could lose keyboard ownership while pending | Compact terminal prompt, Cancel by default, live bindings, keyboard paging, retained pending request, inline retry errors, and command-search entry implemented |
+| Stop target and inventory consistency | Old prompts/replies could affect replacement sessions, duplicate requests could overlap, and old inventory could restore a stopped row | Captured confirmation target, shared requests, early deletion-event confirmation, multi-tab cleanup, stale identity/session guards, and inventory protection implemented |
+| Fork action | Larger form lacked immediate task focus, retained drafts, and inline recovery | Compact `name >` / `task >` prompt, live keyboard bindings, multiline editing, pending rejoin, and visible uncertainty controls implemented |
+| Fork receipts and placement | A lost response could make retry launch another fork; a late response could steal focus or restore stale state | Durable CLI receipts, status-only recovery, captured destination, and stale identity/name/removal guards implemented; status recovery needs the updated CLI |
+| Restart action | No progress UI; repeated clicks could overlap; lost replies made retry ambiguous | Immediate action with compact status prompt, pending rejoin, inline refusal/retry, explicit uncertain retry confirmation, shell-specific naming, and live keymap implemented |
+| Restart lifecycle | A late reply could restore a stopped agent or overwrite current session state | Durable CLI receipts and per-agent restart coalescing; Stop cancellation checks across async steps; desktop identity, Stop-generation, name/session, and inventory guards implemented |
+| Onboarding / machines / offline states | Authentication, remote paths, unavailable engines, and recovery must be fast and explicit | Remote linking, setup chooser/guides, and local password management improved; remaining onboarding still needs audit |
+| Settings / help / platform parity | Native menus, remapping, appearance, accessibility, and Linux keys must tell the same story | Further audit needed |
+| Settings and sign-in keyboard entry | Search lacked initial focus and an Enter action; pending sign-in lacked Escape cancellation | Type/Enter/Down/Escape navigation and cancellation implemented; composition, retry, stale replies, and native terminal focus return verified |
+| Keyboard-help readability | Fixed keycap height could clip enlarged or multi-stroke labels; columns and context selector ignored larger text | Responsive caps/columns/selector implemented; 24 Settings/help renders inspected, keyboard paging/context/menu ownership verified |
+| Dotfile keymap reload | A symlink target switch could publish its map before watching the new target and lose a subsequent save | Controlled filesystem-delay regression reproduced the gap; watches now precede reads/publication and the check passes |
+| Startup settings overhead | Private directory and lock modes were reset by subprocess on every read | Live mode check removes redundant chmod calls; permission repair regressions and isolated timing comparison pass |
+| Release readiness | Current work remains uncommitted; no deployment or publication was requested | Local verification only |
+
+## Verification record
+
+The preceding terminal prompt pass had 2,075 passing desktop tests, five skips,
+and a successful macOS debug build. The creation-context and natural-ordering
+pass then had 2,082 passing tests and five skips. Current changes add end-to-end
+widget checks for outgoing request values, visible hints, multiline drafts,
+compact advanced choices, and explicit preview toggling. The completed draft
+recovery and picker ownership pass has **2,094 passing tests and five skips**,
+no analyzer errors or warnings, and a successful macOS debug build. Twenty-five
+isolated render states include draft/profile restoration and resizing an open
+picker. The subsequent mixed-catalog/navigation pass has **2,098 passing tests
+and five skips**, the same analyzer baseline, a successful macOS debug build,
+and 29 render states. The completed draft-ownership/recovery pass has **2,102
+passing tests and five skips**, no new analyzer issues, a successful macOS
+debug build, and 31 render states. The workspace-arrangement/header pass has
+**2,108 passing tests and five skips**, the same analyzer baseline, a successful
+macOS debug build, and 37 render states. It also replaces a timing-sensitive
+resync test's wall-clock wait with a controlled clock. Logs and limitations are
+recorded in `command-box-progress.md`.
+
+The clipboard/platform-input pass has **2,122 passing desktop tests and five
+skips**, the same analyzer baseline, a successful rebuild of the normal macOS
+app, and **two passing native macOS terminal fixture tests**. Native fixture traffic is entirely fake and independent of
+running agents; no live agent was created.
+
+The native workspace/prompt-editing pass has **2,131 passing desktop tests and
+five skips**, the same analyzer baseline, and **four passing native tests across
+two fixtures**. A combined native invocation failed to start its second app;
+the workspace fixture passed when invoked separately. Forty rendered states
+include the new Find prompt and keyboard menu at enlarged text sizes. The
+normal macOS review build succeeded after native testing; logs and scope are in
+`command-box-progress.md`.
+
+The machine-link pass has **2,137 passing desktop tests and five skips**, the
+same analyzer baseline, **three passing native workspace journeys**, and a
+successful normal macOS rebuild. It reproduced and fixed initial dialog focus
+and native Done/Escape ownership. Forty-four render states include the ready,
+pending, error, and short-window/enlarged-text link prompts. The fake native
+link journey verifies retry, reopening a pending attempt without duplication,
+and returning input to the retained terminal. Logs and remaining setup surfaces
+are recorded in `command-box-progress.md`.
+
+The machine setup/chooser pass has **2,147 passing desktop tests and five
+skips**, the same analyzer baseline, **three passing native workspace journeys**,
+and a successful rebuild of the normal macOS app. Forty-nine render states
+include the chooser, desktop and SSH instructions, an empty search, and the
+short-window/enlarged-text guide. Keyboard tests cover live remapping through
+direct and Machines Manager entry, disabled defaults, background arrivals,
+exact copied commands, clipboard failures, nested linking, and platform refresh
+keys. Native traffic and clipboard tests remain simulated.
+
+The local password/trust pass has **2,161 passing desktop tests and five
+skips**, the same analyzer baseline, **four passing native workspace journeys**,
+and a normal macOS rebuild after fixture execution. Fifty-seven render states
+include eight new password/trust views; all eight were inspected, including the
+480×360 layout at 1.7× text. Tests exercise initial focus, native Next/Done,
+composition, mismatch and exception recovery, pending reopen, safe clear/unlink
+confirmation focus, live remapping, stale status reads, coalesced requests, and
+disposal. No real passwords, trust pins, clipboard, or agents were used.
+
+The Machines Manager/account-edit pass has **2,180 passing desktop tests and
+five skips**, the same analyzer baseline, and **five passing native workspace
+journeys**. The normal macOS app was rebuilt afterward from `lib/main.dart`.
+Sixty-nine rendered states include twelve new manager views, all
+inspected, covering filtering, actions, rename/delete errors, pending work,
+shared access, and enlarged-text layouts. The keyboard journey caught and fixed
+an editing-connection loss when switching from machine to action search. Model
+tests cover concurrent edits, stale replies, disposal, multi-tab cleanup, and
+inventory/cache races. No real machine, account, or live agent was changed.
+
+The terminal-renaming pass has **2,196 passing desktop tests and five skips**,
+the same analyzer baseline, and **six passing native workspace journeys**.
+The 89-test focused set covers tab/agent/machine editor behavior and background
+focus. New model coverage checks concurrent renames, failed receipts, disposal,
+replaced identities/sessions, stopped and recreated IDs, newer rename events,
+and inventory races. Seventy-six render states include seven new rename views;
+all seven and two refactored machine views were visually inspected. Native
+renaming uses fake responses and injected Flutter keys. The normal macOS app
+was rebuilt afterward with `lib/main.dart` as the explicit target.
+
+Inspection of the existing worktree application window previously returned
+`cgWindowNotFound`, with multiple OpenHarness entries in application inventory.
+That window still has not been used as evidence. The separate native fixture
+establishes the rendering, workspace, and input-injection checks above. Physical
+keyboard/IME, VoiceOver, Linux runtime parity, and live daemon behavior remain
+separate from that evidence.
+
+The terminal-stop pass has **2,215 passing desktop tests and five skips**, the
+same analyzer baseline, **103 focused checks**, and **seven passing native
+workspace journeys**. Eight new render states cover default/focused controls,
+pending/reopened work, errors, enlarged text, and keyboard-scrolled details;
+all eight were inspected. The normal macOS app was rebuilt afterward with
+explicit `lib/main.dart`. No real agent or shell was stopped. Confirmed CLI
+deletion and asynchronous process termination remain separate facts, and
+same-identity restart races still need their own audit. Logs are recorded in
+`command-box-progress.md`.
+
+The terminal-fork pass has **2,242 passing desktop tests and five skips**,
+the same analyzer baseline, **115 focused checks**, and **eight passing native
+workspace journeys**. Nine new render states cover task editing, pending work,
+reopening, refusals, uncertainty, handoff, and small windows at enlarged text;
+all nine were inspected. The CLI has **97 passing checks across three files**,
+a passing typecheck, and a successful local build. Receipt recovery requires
+the updated CLI; no running daemon was restarted. The normal macOS app was
+rebuilt afterward with explicit `lib/main.dart`. Native traffic remains
+simulated and does not establish live engine forking or history-copy behavior.
+The following pass addresses Restart. Logs and compatibility details are
+recorded in `command-box-progress.md`.
+
+The terminal-restart pass has **2,266 passing desktop tests and five skips**,
+the same analyzer baseline, **89 focused regression checks**, and **117 CLI
+socket/receipt/restart checks** with a passing typecheck and local CLI build.
+Ten new render states were inspected, bringing the fixture to 103 states.
+A final Enter-on-focused-Close correction passes **27 restart checks** and the
+full **nine-journey native workspace fixture**. Two earlier native runs left
+Find's index disabled because the test window was inactive; the fixture now
+shows and focuses its own window before each journey and retains the exact
+four-match assertion. Product background indexing was not weakened.
+The normal macOS app was rebuilt from explicit `lib/main.dart` afterward.
+Tests use simulated traffic and do not establish live engine restart behavior.
+The updated CLI is compiled locally; no running daemon or user agent was
+restarted. A [30-item review checklist](terminal-review-checklist.md) accompanies
+the build. Remaining settings/onboarding and physical/platform reviews still
+belong to the broader product goal.
diff --git a/desktop/design/terminal-prompt-styling.md b/desktop/design/terminal-prompt-styling.md
new file mode 100644
index 000000000..8ad6b779c
--- /dev/null
+++ b/desktop/design/terminal-prompt-styling.md
@@ -0,0 +1,58 @@
+# Prompt themes and workspace styling
+
+The user's reference is an Agnoster-style shell prompt. The goal is familiar,
+compact context and fast keyboard interaction, with appearance choices that
+can be previewed before returning to work.
+
+## References studied
+
+| Reference | Lesson applied |
+| --- | --- |
+| [Pure](https://github.com/sindresorhus/pure) | Keep the context short, with minimal chrome and selective information. Its configurable symbols and colors support a quiet plain-text option. |
+| [Agnoster](https://github.com/agnoster/agnoster-zsh-theme) | Use visually distinct segments for machine, directory and branch. Its patched-font requirement is a reason to draw separators and use bundled symbols in the GUI. |
+| [Powerlevel10k](https://github.com/romkatv/powerlevel10k#configuration-wizard) | Make appearance a set of understandable choices with previews. Its configuration wizard demonstrates presenting different styles over the same information. |
+| [Starship presets](https://starship.rs/presets/) | Offer both symbol-rich and plain-text presentations. Its no-Nerd-Font and plain-text presets demonstrate the value of a reliable fallback. |
+
+These are design lessons, not installed shell themes or copied theme code.
+
+## Implemented choices
+
+The ASCII marker `>_` identifies the harness in every preset: `>_ Codex`,
+`>_ Claude`, and other harness names. It also appears in new-agent defaults
+and the agent preview. No special font is needed for this marker.
+
+**Symbols** is the default: a small monitor mark for machine, folder mark for
+project, and branch mark for branch. They use the app's existing bundled Lucide
+font independently of the user's text font.
+
+**Plain** uses only ASCII markers: `>_ Codex`, `@ devbox`, `/ openharness`,
+`git: main`.
+The slash identifies a project; the UI does not fabricate a home-directory path.
+
+**Powerline** uses the same context with chevron segments and subdued fills.
+The separators are drawn shapes, so their rendering is independent of the
+selected terminal font. Color can be disabled for any preset. Each of Machine,
+Project and Branch can be shown or hidden, and reset affects only these prompt
+preferences.
+
+Context reads machine first, followed by project and branch. Search also names
+the agent type. Narrow search rows put context below the task; narrow pane
+headers prioritize the machine and keep full identity in the tooltip. Missing
+project or branch metadata produces no placeholder segment. Branch color is
+decorative: no dirty/clean, ahead/behind or other unreported Git state is implied.
+
+The same shared renderer serves search, pane headers and customization preview.
+Matching and ranking use unchanged catalog fields, including hidden context.
+No shell process or Git probe is launched to draw a prompt.
+
+## Workspace application
+
+Cmd-T, Cmd-P, Cmd-N and command search share the bottom command dock. It overlays
+the pane area, preserving terminal geometry. Input stays above the key guide;
+results and default choices expand upward. Panels, tabs and pane borders use
+the same restrained geometry. Native macOS window corners remain OS-managed.
+
+The New Pane titlebar pill is removed. Keyboard commands, File → New Pane and
+command search remain available. The start page still presents New Tab and New
+Pane as entry points. Guided onboarding and the optional full keyboard practice
+remain separate, unfinished work.
diff --git a/desktop/design/terminal-review-checklist.md b/desktop/design/terminal-review-checklist.md
new file mode 100644
index 000000000..cafb3ea9a
--- /dev/null
+++ b/desktop/design/terminal-review-checklist.md
@@ -0,0 +1,268 @@
+# Terminal experience review
+
+Use the worktree review build at
+`build/macos/Build/Products/Debug/Harness.app`, rebuilt from `lib/main.dart`.
+An already running app does not acquire a new build automatically. The installed
+`/Applications/Harness.app` is a separate artifact. Keys below are the macOS
+defaults; any existing keybindings override them.
+
+Try the first twelve items without a mouse. Use a scratch agent or shell for
+the Fork, Restart, and Stop items. Any action without a listed shortcut is
+available by name in **Cmd-Shift-P** command search.
+
+## PR #136: JEV direct commands and Go back
+
+Open **Cmd-Shift-J**, type each example, and press Enter:
+
+- `Show history`, `Open settings`, or `Show me the layout options`: immediately
+ open the existing control without a provider request. Escape returns to work.
+- `Open <exact tab or agent title>`: switch directly when the title is unique.
+ **Go back** in the completion notice restores the original view and leaves
+ the destination open. Duplicate names should remain a choice.
+- `Open a new tab`: open the normal existing/new-agent chooser. Escape should
+ leave no extra tab and restore terminal typing.
+- `Show me the Harness Store`: open or focus the Store tab.
+
+The review build points to the already-running JEV service on port 18478.
+The initial credit error stopped appearing during user review; its latest
+requests return HTTP 200. The older app instance still uses the old daemon's
+missing endpoint and can show 404, so use the newly opened review build.
+Try `Which sessions are ready for review?`, `Take me back to the
+login bug`, and `Let me know when the tests pass`. Sending a task, creating an
+agent, or starting a watch must still show an explicit action card first.
+Escape or Cmd-Shift-J closes the experimental prompt.
+
+## New: creation polish and keyboard learning
+
+- **Cmd-Shift-P → Quick start**, or Help → Quick Start. On an empty workspace,
+ open an agent with Cmd-T, add a second with Cmd-P, zoom with Cmd-Enter, and
+ open command search. The guide advances as work happens; it never grabs the
+ caret. Existing agents/panes count toward the guide.
+- Run **Pause quick start**, relaunch, then run **Quick start** again. It should
+ resume where you left off. Starting a completed guide repeats it.
+- **Cmd-Shift-P → Keyboard practice**, or Help → Keyboard Practice. Search for
+ `New Tab`, `panes`, or `Search & creation`. Enter opens an exercise; press the
+ shown key to see a simulated result. Enter continues; Escape returns to the
+ list, then closes. Your actual agents and tabs stay intact.
+ At large text sizes, Page Up/Down reads the explanation without a mouse.
+- Practice Close Tab, Stop Agent, or Restart Agent and verify your running work
+ stays put. For commands without a shortcut, type the command name in the
+ exercise. Close/reopen practice to check retained progress. Existing custom
+ keybindings should appear and work here too.
+- In Cmd-N, edit Agent or Project with an empty task, Escape, then reopen. Those
+ defaults should return. Choose a recent folder directly from Project; it
+ should retain its owning machine.
+ Cancel Browse and continue typing without clicking the prompt.
+
+## Styling and Store
+
+- Open Rename Tab and the advanced New Harness form: the workspace behind
+ either should be nearly black while the form remains at full brightness.
+- The top tab bar is now 40pt, down from 52pt. Check tab labels, traffic lights,
+ close controls and the new Harness Store entry at normal and narrow widths.
+- Open Harness Store from the far right of the bar, then again from command
+ search using `install` or `browse harnesses`. It should focus one Store tab
+ while the agent tabs stay intact. Close it with Cmd-W to return to work.
+- In Cmd-N, select Task with arrows/Enter to draft a task, Escape, then Agent to search for an unavailable
+ harness. Enter on **Browse more harnesses…** opens the Store. Return to the
+ source tab and Cmd-N; the task and defaults should still be there.
+- Open Cmd-P, Cmd-T, Cmd-N and Cmd-Shift-P. Each prompt should sit on the
+ workspace's bottom edge. Filter, toggle preview, resize and dismiss it; the
+ terminal behind it should keep its size and scroll position.
+- The New Pane pill is gone from the tab bar. Try Cmd-P or File → New Pane.
+- Tabs and panes have matching tighter corners; tab names use the terminal
+ font. Change that font under Customize → Terminal and check the tab labels.
+ The selected tab uses its background and bold label, with no underline.
+ Its top corners and outward bottom joins share a subtle 3pt radius.
+- Open Cmd-Shift-P, type `customize`, and press Enter. In Prompt, try Plain,
+ Symbols and Powerline. Compare search rows and pane headers, then toggle
+ Color, Machine, Project and Branch. Reopen customization to check retention.
+- Harness names use the ASCII marker `>_` in context presets. Compare search
+ and preview; Cmd-N's argument rows show plain agent names.
+- Use Tab and Enter/Space to choose styles and context fields. Escape should
+ return input to the original terminal. Reset prompt style should leave the
+ wallpaper, palette and font choices intact.
+
+## Search and creation
+
+1. **New Tab — Cmd-T.** Search for an existing agent and press Enter. A new
+ tab should use its name. Escape before choosing should leave no empty tab.
+2. **New Pane — Cmd-P.** Choose an existing agent. It should tile into the
+ current tab. Choose it again: focus should move to its existing pane.
+ In the same input, try `> zoom`, `# payments`, `@ M2`, and `?`.
+ Deleting the prefix returns to agents. Enter on a project/machine shows
+ its agents; Escape goes back. In `?`, choose a prefix row and continue
+ typing without losing focus. Cmd-Shift-P inserts `> `; deleting it also
+ returns to agents, retaining the tab/pane destination.
+ The input has no decorative prompt glyph; only its typed prefix appears.
+ Results use a background highlight without an arrow, aligned with the input.
+3. **Search quality and identity.** Search by task/name, project, machine, or
+ tab. Try short, partial queries and agents with similar names. The rows
+ should make the agent and machine clear without opening a preview.
+4. **Search navigation.** The best match should be just above the bottom prompt.
+ Up/Ctrl-P/Ctrl-K moves upward; Down/Ctrl-N/Ctrl-J moves back toward the
+ prompt, with no wrapping. Ordinary j/k remain text. Selection should stay
+ visible after resizing. With preview hidden, Page Up/Down page results.
+5. **Preview — Ctrl-/.** It starts on for real results; New agent needs none.
+ At narrow widths preview belongs above the list. Move through results and use
+ Page Up/Down to read the preview. Toggle it off and continue searching, then
+ toggle it back on; the query, selection and input focus should stay put.
+6. **New agent.** In an empty Cmd-T or Cmd-P picker, press Enter on New agent.
+ Check Agent and Project (`machine:~/path`). Enter starts directly; select
+ Task with arrows/Enter to type an optional first task, then Enter.
+ The result should appear in the chosen tab/pane destination.
+ An empty first task is allowed.
+7. **Create from a search.** Type a new task, choose the pinned New agent row,
+ and verify that text becomes its proposed first task. Existing results
+ should still be selected by default while searching.
+8. **Edit arguments.** Use Up/Down and Enter for Agent, Machine, Project, or Task.
+ Create starts highlighted, Down wraps
+ to Agent, and Enter edits the highlighted row. Returning from an editor
+ selects Create again. Cmd-Enter starts from any highlighted launch row.
+ The footer should describe what Enter will do; the highlight is the only
+ selection marker, with no `>` beside results or input labels.
+ There are no letter labels or default `a/m/p/t/o` shortcuts. Up from Create
+ selects Task; there is no standalone Options row. Escape returns
+ to Create, preserving the draft.
+ Project focuses a search input. Type a name or path to filter recent projects;
+ New project, Open folder, and Clone GitHub repository stay above the input,
+ in that order, with results above them. The best recent starts selected.
+ Down moves from it through New, Open, and Clone. Up to nine recent rows fit;
+ arrows and Page Up/Down reach the rest while the actions stay visible.
+ Letters (including `n/o/g/m`) and digits type into search; there are no
+ numbered shortcuts or action-letter labels. The
+ list includes existing agents' folders and persisted choices on that
+ machine, with the current folder first and duplicate paths collapsed. The
+ actions remain visible with a long history. Arrows/Enter and clicking work
+ too. Search for something with no matches: all three actions must remain,
+ with Open folder selected. Choose New project with arrows/Enter and
+ type `payments processing`: Create should
+ preview `machine:~/harnesses/payments-processing`. Enter accepts the name;
+ Enter again launches. An empty name cannot launch in the previous project.
+ Choose Open folder: enter a folder path; Enter on the bottom Open folder row or
+ Ctrl-O browses folders. This screen should not repeat recent projects.
+ A missing match must not offer to create a new folder. Choose Clone GitHub repository: paste
+ a GitHub repository URL (or `openai/codex`), check the destination, and press
+ Enter to use it. The repository is cloned when the agent starts.
+ Escape to launch, choose Machine, and switch to iMac: Project shows only iMac recents. Switch back
+ to M2 and its previous folder returns. Machine returns to the screen where
+ it was opened; Escape cancels without changing machines. Other project
+ editors restore the Project search, then return to the launch menu. Tab completes text without
+ committing it. Try path completion and Escape to restore its stem.
+ Select Pi: the Task row remains, explaining that its task is entered
+ after launch. Switch to Codex and Task opens the task editor again.
+9. **Multiline and line editing.** Option-Enter adds a task line. Try Ctrl-W
+ to erase a word, Ctrl-U to erase back to the current line's start, Ctrl-Y to
+ restore it, and Ctrl-H/D around emoji or accented text. Task editing should
+ preserve other lines.
+10. **Draft restoration.** Edit the task and defaults, Escape, and reopen an
+ empty chooser from the same source. The draft should return. Switch to a
+ different source agent/project and check that its draft is independent.
+ Drafts last for the current app window; they do not survive app restart.
+11. **Agent settings.** Open Agent and highlight Codex with a different agent
+ saved. Permissions and Codex profile should appear directly underneath it.
+ Down moves into those settings without changing their target. Escape
+ without choosing must preserve the saved agent and profile. Choose a mode
+ or profile with typing, arrows, and Enter to commit it with Codex. It returns
+ to Agent; Escape returns to launch, summarizing nondefault permissions
+ beside the agent name. For Codex, choose Codex profile: it lists profiles
+ on the selected machine, plus Default profile, Refresh, and Link profile
+ folder. Discovery must not change the account. Switch machines and verify
+ the old profile is cleared. Escape leaves an uncommitted choice unchanged.
+ Agent and Machine pickers should have no repeated Agent/Machine/Project
+ summary; that summary remains on the main launch screen.
+ Cmd-period retains the full creation form; its nested agent picker must
+ choose an agent on Enter/Cmd-Enter before creating anything.
+12. **Commands — Cmd-Shift-P.** Search for commands after the editable `> `, read
+ their key hints, run one, and Escape out of another. After dismissal,
+ ordinary typing should immediately go to the original terminal.
+
+## Workspace and terminal
+
+13. **One agent in several tabs.** Open the same existing agent through
+ Cmd-T in two tabs. These should show the same session. Closing a view
+ should leave the agent and its other views running.
+14. **Mixed machines.** Put local and remote agents in one tab through Cmd-P.
+ Check that machine identity remains readable and each pane receives its
+ own input. This needs linked machines with existing agents.
+15. **Tab navigation.** Try Cmd-1 through Cmd-9 and Cmd-Shift-[ / ]. With many
+ tabs, the selected one should remain visible. A manually renamed tab
+ should keep its name when panes are added.
+16. **Arrange panes.** Use Cmd-H/J/K/L to focus directionally,
+ Cmd-Shift-arrows to move a pane, Cmd-Enter to zoom/restore, and Cmd-; to
+ return to the previous pane. Moves should preserve the other panes and
+ the running sessions.
+17. **Resize panes.** Run Resize panes. Use arrows, Shift-arrows for larger
+ changes, Tab to change divider, and Escape to finish. The temporary key
+ guide should explain the mode and disappear afterward.
+18. **Close and reopen.** Run Close Pane or Close Tab, then Reopen closed tab
+ or pane. The prior running work should return. Closing a view and stopping
+ its agent should feel clearly different.
+19. **Output Find — Cmd-F.** Search existing output; Enter/Shift-Enter move
+ through hits. Escape should return to the earlier scroll position and
+ terminal input. Try the compact match-options menu in a narrow pane.
+20. **Read while output arrives.** Scroll upward in a busy terminal. New output
+ should not pull you back to the bottom. Return to the bottom and check
+ that following output feels natural again.
+21. **Clipboard and shell muscle memory.** Copy/paste text and multiline
+ commands. Try your usual shell Ctrl-A/E/R/W/U and tmux Ctrl-B in a scratch
+ shell. Prompt-only shortcuts should stop intercepting input once dismissed.
+ On Linux, copy/paste/select-all are Ctrl-Shift-C/V/A; native Linux runtime
+ still needs review.
+22. **Small windows, fonts, and menus.** Make a four-pane tab, narrow the
+ window, and increase the terminal font. Check names, machine identity,
+ compact action/model menus, search rows, and key guides for clipping.
+ Arrows/Enter/Escape should work in those menus and restore terminal focus.
+
+## Names and agent actions
+
+23. **Rename Tab / Rename Agent.** Rename Tab also has Cmd-Shift-R; an agent
+ title can be double-clicked. The old name should be selected once, typing
+ should replace it immediately, Enter should save, and Escape should cancel.
+ Renaming an agent should update its pane titles without restarting it.
+24. **Fork Agent.** On a supported scratch agent, edit name and task. Escape
+ and reopen to check its draft, then fork. The source should stay intact;
+ the new agent should open at the original destination. The prompt explains
+ conversation continuation versus a handoff when supported by the engine.
+25. **Restart Agent / Restart Terminal.** This starts immediately. Check the
+ compact pending prompt; close/reopen it while pending if timing permits.
+ Existing views should remain. A fresh agent conversation should be clearly
+ reported; a shell restart simply starts a fresh shell.
+26. **Stop Agent / Stop Terminal.** The confirmation names the target and
+ initially focuses Cancel. Enter should cancel; Tab then Enter should stop.
+ A confirmed stop should close that agent's views across tabs and leave
+ unrelated terminals usable.
+
+## Machines and keyboard customization
+
+27. **Open Machines Manager.** Filter by name or status, Enter into actions,
+ and Escape back twice. Queries and selection should survive nested
+ prompts and refresh. Try keyboard-only machine renaming if desired.
+28. **Link machine.** Search existing machines or open desktop/SSH setup.
+ Copy controls, links, refresh, and back navigation should work without a
+ mouse. A machine's password prompt should accept typing immediately.
+29. **This computer's password / Links from this computer.** Open these via
+ Machines Manager. Review the wording and keyboard navigation; setting or
+ clearing a password and unlinking make real changes. Clear/unlink
+ confirmations start on Cancel and explain their scope.
+30. **Keyboard shortcuts and Edit keybindings.** Find both through command
+ search. Try a custom binding in `~/.config/harness/keybindings.jsonc`
+ (or the shown XDG config path). Live hints and prompt behavior should follow
+ the change; invalid config should keep the last working bindings.
+
+## Review limits and feedback
+
+Timeout, pending-reopen, stale-response, and duplicate-request cases are covered
+by isolated fixtures; there is no need to manufacture network failures during
+UI review. The newer durable Fork/Restart status recovery requires the updated
+CLI. It is compiled locally, but the running daemon has not been updated or
+restarted. Legacy successful operations remain supported.
+
+Settings, remaining first-run onboarding, physical keyboard/IME, VoiceOver,
+and native Linux behavior still need a broader pass. They are not finished by
+the terminal prompt work.
+
+For each item, useful feedback is: **item number · what felt confusing or slow
+· what you expected · what you would prefer**. The main question is whether the
+interface feels natural at terminal speed without remembering a separate app's
+rules.
diff --git a/desktop/integration_test/native_terminal_e2e_test.dart b/desktop/integration_test/native_terminal_e2e_test.dart
index ba85337fa..cb8f64353 100644
--- a/desktop/integration_test/native_terminal_e2e_test.dart
+++ b/desktop/integration_test/native_terminal_e2e_test.dart
@@ -8,12 +8,16 @@ import 'package:xterm/xterm.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
+import 'package:harness/core/test_run.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/terminal_panel.dart';
void main() {
+ if (!kUnderTest) {
+ throw StateError('Native terminal fixtures require FLUTTER_TEST=1');
+ }
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('native terminal replaces keyframes without stale render state', (
diff --git a/desktop/integration_test/native_workspace_e2e_test.dart b/desktop/integration_test/native_workspace_e2e_test.dart
new file mode 100644
index 000000000..c9f8726ac
--- /dev/null
+++ b/desktop/integration_test/native_workspace_e2e_test.dart
@@ -0,0 +1,2248 @@
+import '../test/support/launch_menu.dart';
+
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:window_manager/window_manager.dart';
+import 'package:xterm/xterm.dart';
+
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/auth/peer_link_client.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/screens/login_screen.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/core/snapshot_store.dart';
+import 'package:harness/settings/sections/usage_section.dart';
+import 'package:harness/stats/harness_stats.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/usage_ledger_store.dart';
+import 'package:harness/usage/ledger/usage_ledger_controller.dart';
+import 'package:harness/usage/ledger/usage_report.dart';
+import 'package:harness/usage/ledger/opencode_ledger_scanner.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/settings/settings_nav.dart';
+import 'package:harness/settings/settings_screen.dart';
+import 'package:harness/settings/settings_section.dart';
+import 'package:harness/settings/sections/shortcuts_section.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_select_field.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_preset.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/state/workspace_learning.dart';
+import 'package:harness/state/first_harness_launch.dart';
+import 'package:harness/store/store_screen.dart';
+import 'package:harness/widgets/workspace_start_guide.dart';
+import 'package:harness/shortcuts/keyboard_practice.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/environment_setup_screen.dart';
+import 'package:harness/widgets/link_machine_screen.dart';
+import 'package:harness/widgets/terminal_find_bar.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import '../test/keymap_host_test.dart' show key;
+import '../test/support/mixed_agents.dart';
+import '../test/support/password_cli.dart';
+import '../test/support/machine_api.dart';
+import '../test/support/rename_connection.dart';
+import '../test/support/stop_connection.dart';
+import '../test/support/fork_connection.dart';
+import '../test/support/restart_connection.dart';
+import '../test/swarm_screen_test.dart' show terminal;
+import '../test/machine_loading_test.dart' show DiscoveryConnection;
+import '../test/environment_setup_screen_test.dart'
+ show SetupLogin, SetupProvisioner, setupReview;
+import '../test/terminal_find_test.dart' show terminalView;
+import '../test/swarm_state_test.dart' show createApp, MemoryStore;
+import '../test/workspace_account_lifecycle_test.dart'
+ show
+ WorkspaceAccountFixture,
+ WorkspaceAccountLogin,
+ arrangeAccountWorkspace;
+import '../test/usage_ledger_lifecycle_test.dart' show HeldScanner, figures;
+import '../test/usage_ledger_test.dart' show MemorySettings;
+import '../test/usage_scanners_test.dart' show createUsageDatabase, addUsage;
+import '../test/usage_jsonl_scanners_test.dart'
+ show jsonlRoot, jsonlRow, jsonlScanner;
+import '../test/signout_recovery_test.dart'
+ show SignOutFixture, signOutApp, signOutHost;
+
+class _CreationConnection extends WsConn {
+ _CreationConnection({this.products = const []})
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creates = <Map<String, dynamic>>[];
+ final List<Map<String, dynamic>> products;
+ final input = <TerminalBinaryFrame>[];
+
+ @override
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async => true;
+
+ @override
+ Future<bool> sendTerminalBinary(Uint8List bytes) async {
+ final frame = decodeTerminalLocal(bytes);
+ if (frame?.kind == TerminalBinaryKind.input) input.add(frame!);
+ return true;
+ }
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ }
+ if (type == 'dsh_list') return {'dsh': products};
+ if (type == 'agent_create') {
+ creates.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'made',
+ 'name': 'Refine terminal workspace',
+ 'engine': payload['engine'],
+ 'dsh': payload['dsh'],
+ 'terminal': {'available': true},
+ },
+ };
+ }
+ return {};
+ }
+}
+
+class _FirstCreationApp extends AppNotifier {
+ _FirstCreationApp(WsConn connection)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (_) => connection,
+ ) {
+ const machine = Machine(
+ machineId: 'm',
+ name: 'This Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ machines = [machine];
+ machineStates['m'] = MachineState(machine)
+ ..localOnly = true
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ status = AppStatus.authenticated;
+ }
+
+ @override
+ Future<String> prepareLocalProjectFolder(
+ ProjectFolderRequest request, {
+ String label = 'harness',
+ }) async => '/fixture/harnesses/${request.folderName}';
+}
+
+class _WorkspaceLinks implements PeerLinkClient {
+ final requests = <String>[];
+ final replies = <Completer<CliLinkConnectResult>>[];
+
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) {
+ requests.add(machineId);
+ final reply = Completer<CliLinkConnectResult>();
+ replies.add(reply);
+ onProgress?.call('verifying');
+ return reply.future;
+ }
+
+ @override
+ Future<CliLinkListResult> list() async => const CliLinkListResult();
+
+ @override
+ Future<String?> unlink(String machineId) async => null;
+}
+
+/// Run with FLUTTER_TEST=1. This fixture never bootstraps the real CLI, loads a
+/// Harness home, or creates real agents; it mounts the real native workspace
+/// around in-memory sessions and simulates creation and machine-link requests.
+void main() {
+ if (!kUnderTest) {
+ throw StateError('Native workspace fixtures require FLUTTER_TEST=1');
+ }
+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();
+
+ setUpAll(() async {
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1280, 800));
+ });
+ setUp(() async {
+ newHarnessOpensInBox = true;
+ // Each journey interacts with this fixture's own native window. A second
+ // running Harness instance can otherwise leave it inactive at launch,
+ // correctly suspending Find indexing and native frame delivery.
+ await windowManager.show();
+ await windowManager.focus();
+ });
+ tearDown(() => newHarnessOpensInBox = false);
+
+ testWidgets(
+ 'native first setup retries checks and installs with keys and recovers from clipboard failure',
+ (tester) async {
+ final provisioner = SetupProvisioner();
+ final app =
+ AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLogin: SetupLogin(),
+ environmentProvisioner: provisioner,
+ )
+ ..status = AppStatus.preparingEnvironment
+ ..environmentReadiness = setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ failure: const EnvironmentFailure(
+ title: 'Checking this computer took too long',
+ detail: 'The tmux check did not finish. Retry to check again.',
+ ),
+ );
+ addTearDown(app.dispose);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ throw PlatformException(code: 'clipboard_unavailable');
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => app.status == AppStatus.unauthenticated
+ ? const Scaffold(body: Text('Sign-in reached'))
+ : EnvironmentSetupScreen(notifier: app),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(provisioner.attempts, hasLength(1));
+ expect(provisioner.attempts.single.install, isFalse);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(provisioner.attempts, hasLength(1));
+ provisioner.attempts.single.finish(setupReview);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Install 2 tools'), findsOneWidget);
+ expect(provisioner.attempts, hasLength(1));
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(provisioner.attempts, hasLength(2));
+ expect(provisioner.attempts.last.install, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(provisioner.attempts, hasLength(2));
+ provisioner.attempts.last.finish(
+ setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ failure: const EnvironmentFailure(
+ title: 'Setup could not finish',
+ detail: 'Check your connection, then retry setup.',
+ ),
+ output: const ['Connection interrupted'],
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.pump();
+ expect(
+ find.text('Could not copy. Select the text to copy it, or try again.'),
+ findsOneWidget,
+ );
+ bool retryFocused() => tester
+ .widget<FilledButton>(find.byType(FilledButton))
+ .focusNode!
+ .hasFocus;
+ for (var i = 0; i < 8 && !retryFocused(); i++) {
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(retryFocused(), isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(provisioner.attempts, hasLength(3));
+ expect(provisioner.attempts.last.install, isTrue);
+ provisioner.attempts.last.finish(
+ const EnvironmentReadiness(
+ steps: {
+ EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
+ EnvironmentStep.tmux: EnvironmentStepStatus.ready,
+ EnvironmentStep.harness: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.status, AppStatus.unauthenticated);
+ expect(find.text('Sign-in reached'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'native reconnect refreshes discovery and restores terminal input',
+ (tester) async {
+ final connection = DiscoveryConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ app.machineStates['m']!
+ ..nodeOnline = true
+ ..terminalCapabilityAvailable = true;
+ final input = <TerminalBinaryFrame>[];
+ final session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a0',
+ agentName: 'Fixture',
+ engineId: 'codex',
+ send: connection.sendTerminalFrame,
+ sendBinary: (frame) async {
+ if (frame.kind == TerminalBinaryKind.input) input.add(frame);
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'old-stream';
+ session.terminal.write(
+ List.generate(180, (i) => 'Retained output $i\r\n').join(),
+ );
+ final pane = app.adoptSessionForTest(session);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final view = terminalView(tester, session);
+ final scroll = view.widget.scrollController!;
+ scroll.jumpTo(80);
+ final start = session.terminal.buffer.createAnchor(0, 1);
+ final end = session.terminal.buffer.createAnchor(8, 1);
+ addTearDown(start.dispose);
+ addTearDown(end.dispose);
+ view.widget.controller!.setSelection(start, end);
+ await tester.pump();
+ app.onMachineConnectedForTest('m');
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(terminalView(tester, session), same(view));
+ expect(scroll.offset, 80);
+ expect(view.widget.controller!.selection, isNotNull);
+ expect(session.streamId, isNull);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input, isEmpty);
+
+ connection.agents.single.complete({
+ 'agents': [
+ {
+ 'id': 'a0',
+ 'name': 'Reconnected agent',
+ 'engine': 'codex',
+ 'terminal': {
+ 'runtimes': [
+ {'backend': 'tmux', 'paneId': '%1'},
+ ],
+ },
+ },
+ ],
+ });
+ connection.capabilities.single.complete({
+ 'protocolVersion': 3,
+ 'backend': 'tmux',
+ 'available': true,
+ });
+ await tester.pump(const Duration(milliseconds: 100));
+ final open = connection.frames
+ .lastWhere((frame) => frame.type == 'terminal_open')
+ .payload;
+ await session.handleFrame('terminal_ready', {
+ 'requestId': open['requestId'],
+ 'agentId': 'a0',
+ 'protocolVersion': 3,
+ 'streamId': 'reconnected-stream',
+ });
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: 'reconnected-stream',
+ seq: 0,
+ bytes: utf8.encode('Fresh terminal screen\r\nready> '),
+ compressed: false,
+ cols: open['cols'] as int,
+ rows: open['rows'] as int,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.focusedPane, same(pane));
+ expect(pane.session, same(session));
+ expect(session.status, TerminalSessionStatus.controlling);
+ expect(
+ session.terminal.buffer.getText(),
+ contains('Fresh terminal screen'),
+ );
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(input.last.streamId, 'reconnected-stream');
+ expect(input.last.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ timeout: const Timeout(Duration(seconds: 60)),
+ );
+
+ testWidgets(
+ 'native session expiry restores the saved tabs and keyboard selection',
+ (tester) async {
+ final app = WorkspaceAccountFixture(
+ MemoryStore(),
+ WorkspaceAccountLogin(),
+ );
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await arrangeAccountWorkspace(app);
+ final selected = app.activeSwarmId;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: true),
+ child: grid.BrightnessScope(child: child!),
+ ),
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => app.status == AppStatus.authenticated
+ ? SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ )
+ : LoginScreen(notifier: app),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await app.expire();
+ await tester.pumpAndSettle();
+ expect(app.allPanes, isEmpty);
+ expect(find.text('Sign in'), findsOneWidget);
+ expect(find.text('Could not sign in'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ // Restored panes wait for their machines with an indeterminate spinner.
+ // Wait for sign-in itself, rather than for those animations to settle.
+ for (var i = 0; i < 50 && app.signingIn; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ expect(app.signingIn, isFalse);
+ await tester.pump();
+ expect(find.byType(LoginScreen), findsNothing);
+ expect(app.swarms.map((s) => s.name), ['Research', 'Build']);
+ expect(app.allPanes.map((p) => p.agentId), ['a', 'b', 'c']);
+ expect(app.activeSwarmId, selected);
+ expect(
+ find.textContaining('This machine isn’t available.'),
+ findsOneWidget,
+ );
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ final reads = app.inventoryRequests;
+ // The native workspace also has pane-header controls in Tab order.
+ // Reach Retry through that real order rather than assuming it is first.
+ for (
+ var i = 0;
+ i < 8 && !Focus.of(tester.element(find.text('Retry'))).hasFocus;
+ i++
+ ) {
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(Focus.of(tester.element(find.text('Retry'))).hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.inventoryRequests, reads + 1);
+ await key(tester, LogicalKeyboardKey.digit1, cmd: true);
+ expect(app.activeSwarm.name, 'Research');
+ expect(app.focusedPane!.agentId, 'b');
+ await key(tester, LogicalKeyboardKey.digit2, cmd: true);
+ expect(app.activeSwarmId, selected);
+ expect(app.focusedPane!.agentId, 'c');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ timeout: const Timeout(Duration(seconds: 75)),
+ );
+
+ testWidgets('native sign-out waits, retries, and restores keyboard sign-in', (
+ tester,
+ ) async {
+ final cli = SignOutFixture();
+ final app = signOutApp(cli);
+ addTearDown(app.dispose);
+ final pending = app.logout();
+ await tester.pumpWidget(signOutHost(app));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Signing out…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.logins, 0);
+ cli.attempts.single.completeError(StateError('fixture sign-out failure'));
+ await pending;
+ await tester.pumpAndSettle();
+ expect(find.text('Retry sign out'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.attempts, hasLength(2));
+ cli.attempts.last.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Sign in'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.logins, 1);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'native Usage retries, changes range with keys, and stops a pending scan',
+ (tester) async {
+ final scanner = HeldScanner();
+ final settings = MemorySettings()
+ ..values['usageLedger.claude.enabled'] = 'true';
+ final snapshot = MemorySnapshotStore();
+ final store = UsageLedgerStore(
+ scanner: scanner,
+ settings: settings,
+ snapshots: snapshot,
+ );
+ final controller = UsageLedgerController(stores: [store]);
+ final stats = HarnessStats(store: MemorySnapshotStore());
+ addTearDown(controller.dispose);
+ addTearDown(stats.dispose);
+ final loading = controller.load();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: UsageSection(controller: controller, stats: stats),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final lens = find.byType(AppSelectField<LedgerProvider?>);
+ await tester.tap(lens);
+ await tester.pump(const Duration(milliseconds: 100));
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<AppSelectField<LedgerProvider?>>(lens).value,
+ LedgerProvider.claude,
+ );
+ expect(find.text('Scanning Claude logs…'), findsOneWidget);
+ expect(find.text('No Claude usage in this range.'), findsNothing);
+ scanner.replies.single.completeError(StateError('Fixture unavailable'));
+ await tester.pump(const Duration(milliseconds: 100));
+ await loading;
+ expect(find.textContaining('Fixture unavailable'), findsOneWidget);
+ final rescan = find.byTooltip('Rescan the local logs');
+ await tester.tap(rescan);
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(scanner.replies, hasLength(2));
+ scanner.replies.last.complete(figures(1200));
+ await tester.pump(const Duration(milliseconds: 100));
+ final range = find.byType(AppSelectField<UsageRange>);
+ await tester.tap(range);
+ await tester.pump(const Duration(milliseconds: 100));
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<AppSelectField<UsageRange>>(range).value,
+ UsageRange.all,
+ );
+ expect(scanner.replies, hasLength(2));
+ await tester.tap(rescan);
+ await tester.pump(const Duration(milliseconds: 50));
+ expect(scanner.replies, hasLength(3));
+ await tester.tap(find.byTooltip('Stop reading Claude'));
+ await tester.pump(const Duration(milliseconds: 50));
+ scanner.replies.last.complete(figures(9900));
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Enable Claude'), findsOneWidget);
+ expect(store.ledger.hasData, isFalse);
+ expect(snapshot.isEmpty, isTrue);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'native Usage refresh reads committed SQLite data through the worker',
+ (tester) async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-native-usage-',
+ );
+ final writer = createUsageDatabase(
+ '${fixture.path}/opencode.db',
+ wal: true,
+ );
+ final store = UsageLedgerStore(
+ scanner: OpenCodeLedgerScanner(dataDirectory: fixture.path),
+ settings: MemorySettings(),
+ snapshots: MemorySnapshotStore(),
+ );
+ final controller = UsageLedgerController(stores: [store]);
+ final stats = HarnessStats(store: MemorySnapshotStore());
+ addTearDown(() async {
+ controller.dispose();
+ stats.dispose();
+ writer.dispose();
+ await fixture.delete(recursive: true);
+ });
+ addUsage(writer, input: 1000);
+ writer.execute('UPDATE session SET time_created=?', [
+ DateTime.now().millisecondsSinceEpoch,
+ ]);
+ await controller.load();
+ await store.setEnabled(true);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: UsageSection(controller: controller, stats: stats),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final lens = find.byType(AppSelectField<LedgerProvider?>);
+ await tester.tap(lens);
+ await tester.pump(const Duration(milliseconds: 100));
+ for (var i = 0; i < 3; i++) {
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ }
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<AppSelectField<LedgerProvider?>>(lens).value,
+ LedgerProvider.opencode,
+ );
+ expect(find.text('1.0k'), findsWidgets);
+ final rescan = find.byTooltip('Rescan the local logs');
+ writer.execute('UPDATE session SET tokens_input=5000');
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.ok);
+ expect(store.ledger.totals.freshInput, 5000);
+ expect(find.text('5.0k'), findsWidgets);
+ final broken = File('${fixture.path}/opencode-copy.db');
+ await broken.writeAsString('deliberately invalid fixture');
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.partial);
+ expect(find.textContaining('Figures are incomplete.'), findsOneWidget);
+ expect(find.text('5.0k'), findsWidgets);
+ await broken.delete();
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.ok);
+ expect(find.textContaining('Figures are incomplete.'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final provider in [LedgerProvider.claude, LedgerProvider.codex]) {
+ testWidgets(
+ 'native Usage ${provider.label} reads live transcripts and recovers',
+ (tester) async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-native-jsonl-',
+ );
+ final file = File('${jsonlRoot(provider, fixture.path)}/live.jsonl');
+ await file.parent.create(recursive: true);
+ final first =
+ jsonDecode(jsonlRow(provider, 1000)) as Map<String, dynamic>;
+ first['timestamp'] = DateTime.now().toIso8601String();
+ await file.writeAsString('${jsonEncode(first)}\n');
+ final store = UsageLedgerStore(
+ scanner: jsonlScanner(provider, fixture.path),
+ settings: MemorySettings(),
+ snapshots: MemorySnapshotStore(),
+ );
+ final controller = UsageLedgerController(stores: [store]);
+ final stats = HarnessStats(store: MemorySnapshotStore());
+ addTearDown(() async {
+ controller.dispose();
+ stats.dispose();
+ await fixture.delete(recursive: true);
+ });
+ await controller.load();
+ await store.setEnabled(true);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: UsageSection(controller: controller, stats: stats),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final lens = find.byType(AppSelectField<LedgerProvider?>);
+ await tester.tap(lens);
+ await tester.pump(const Duration(milliseconds: 100));
+ for (var i = 0; i <= provider.index; i++) {
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ }
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<AppSelectField<LedgerProvider?>>(lens).value,
+ provider,
+ );
+ expect(find.text('1.0k'), findsWidgets);
+ final rescan = find.byTooltip('Rescan the local logs');
+ final next =
+ jsonDecode(jsonlRow(provider, 2000)) as Map<String, dynamic>;
+ next['timestamp'] = DateTime.now().toIso8601String();
+ next['fixtureText'] = '€';
+ final bytes = utf8.encode(jsonEncode(next));
+ final split = bytes.indexOf(0xe2) + 1;
+ await file.writeAsBytes(bytes.sublist(0, split), mode: FileMode.append);
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.ok);
+ expect(store.ledger.totals.freshInput, 1000);
+ await file.writeAsBytes([
+ ...bytes.sublist(split),
+ 10,
+ ], mode: FileMode.append);
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.ok);
+ expect(
+ store.ledger.totals.freshInput,
+ provider == LedgerProvider.claude ? 3000 : 2000,
+ );
+ final broken = File('${file.parent.path}/broken.jsonl');
+ await broken.writeAsBytes([0xff, 10]);
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.partial);
+ expect(find.textContaining('Figures are incomplete.'), findsOneWidget);
+ await broken.delete();
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(store.state.status, LedgerStatus.ok);
+ expect(find.textContaining('Figures are incomplete.'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'native Settings is searchable immediately and Escape restores terminal input',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', input));
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app, nativeTabs: true),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await key(tester, LogicalKeyboardKey.comma, cmd: true);
+ await tester.pump(const Duration(milliseconds: 200));
+ final search = find.byKey(const Key('settings-search-field'));
+ expect(
+ tester.widget<TextField>(search).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ await tester.enterText(search, 'keyboard');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ SettingsSection.shortcuts,
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<AppSelectField<KeymapContext>>(),
+ isNotNull,
+ );
+ final scroll = tester.state<ScrollableState>(
+ find
+ .descendant(
+ of: find.byType(ShortcutsSection),
+ matching: find.byType(Scrollable),
+ )
+ .first,
+ );
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(scroll.position.pixels, greaterThan(0));
+ await key(tester, LogicalKeyboardKey.pageUp);
+ await tester.pump(const Duration(milliseconds: 300));
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await tester.pump(const Duration(milliseconds: 100));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(SettingsScreen), findsOneWidget);
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ await key(tester, LogicalKeyboardKey.tab, shift: true);
+ expect(
+ tester.widget<TextField>(search).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ await tester.enterText(search, 'About');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<OutlinedButton>()
+ ?.key,
+ const Key('settings-check-updates-button'),
+ );
+ expect(app.updateChecksEnabled, isFalse);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Updates are off for this build'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ expect(find.byType(SettingsScreen), findsOneWidget);
+ expect(
+ FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<OutlinedButton>()
+ ?.key,
+ const Key('settings-check-updates-button'),
+ );
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byType(SettingsScreen), findsNothing);
+ expect(app.focusedPane, same(pane));
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ expect(input.single.bytes, [27, 91, 67]);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native first workspace opens a ready draft and keeps creation explicit',
+ (tester) async {
+ final connection = _CreationConnection();
+ final app = _FirstCreationApp(connection);
+ await app.agentPreference.select('codex');
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ addTearDown(connection.close);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ firstLaunch: FirstHarnessLaunch(),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump(const Duration(milliseconds: 200));
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.engine, 'codex');
+ expect(box.projectLabel, startsWith('~/harnesses/codex-'));
+ final proposedFolder = box.projectFolderRequest!.folderName;
+ expect(connection.creates, isEmpty);
+ expect(find.byType(WorkspaceStartGuide).hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(connection.creates, hasLength(1));
+ expect(
+ connection.creates.single['cwd'],
+ '/fixture/harnesses/$proposedFolder',
+ );
+ expect(connection.creates.single['engine'], 'codex');
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(connection.creates, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native JEV navigation returns to the original pane and hands off to New Tab',
+ (tester) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ final originalPane = app.adoptSessionForTest(terminal('a0', input));
+ final original = app.activeSwarm;
+ app.renameSwarm(original.id, 'Original work');
+ app.newSwarm(name: 'JEV target');
+ app.adoptSessionForTest(terminal('a1', []));
+ final target = app.activeSwarm;
+ app.selectSwarm(original.id);
+ app.focusPane(originalPane.id);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ commandResolver: (_, _) async =>
+ throw StateError('Exact app commands must stay local'),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ final command = find.byKey(const ValueKey('jev-command-input'));
+ await key(tester, LogicalKeyboardKey.keyJ, cmd: true, shift: true);
+ await tester.enterText(command, 'Open JEV target');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(command, findsNothing);
+ expect(app.activeSwarmId, target.id);
+ expect(find.text('Go back'), findsOneWidget);
+ await tester.tap(find.text('Go back'));
+ await tester.pumpAndSettle();
+ expect(app.activeSwarmId, original.id);
+ expect(app.focusedPane, same(originalPane));
+ expect(app.swarms, contains(target));
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(input.last.bytes, [27, 91, 68]);
+
+ await key(tester, LogicalKeyboardKey.keyJ, cmd: true, shift: true);
+ await tester.enterText(command, 'Open a new tab');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ final chooser = find.byKey(const ValueKey('swarm-search-input'));
+ expect(command, findsNothing);
+ expect(chooser, findsOneWidget);
+ expect(tester.widget<TextField>(chooser).focusNode!.hasFocus, isTrue);
+ expect(app.activeSwarmId, original.id);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(chooser, findsNothing);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(input.last.bytes, [27, 91, 67]);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native workspace learns keys without dispatching practice actions',
+ (tester) async {
+ final app = createApp();
+ final learning = WorkspaceLearning();
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', []));
+ app.adoptSessionForTest(terminal('a1', input));
+ final original = app.activeSwarm;
+ final panes = original.panes.toList();
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(learning.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ learning: learning,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+
+ Future<void> command(String name) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $name',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ }
+
+ // Same dispatch as Help > Quick Start, through the native workspace channel.
+ final started = Completer<void>();
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ 'harness/swarm_tabs',
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('keymapCommand', {
+ 'command': 'keyboard.quick_start',
+ }),
+ ),
+ (_) => started.complete(),
+ );
+ await started.future;
+ await tester.pump();
+ expect(learning.next, WorkspaceLesson.zoom);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(learning.next, WorkspaceLesson.commands);
+ await command('Keyboard practice');
+ expect(learning.finished, isTrue);
+ final filter = find.byKey(const ValueKey('practice-filter'));
+ await tester.enterText(filter, 'New Tab');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(find.text('[x] New Tab'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ expect(app.swarms, [original]);
+ expect(original.panes, panes);
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(filter, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(KeyboardPractice), findsNothing);
+ await command('Pause quick start');
+ expect(learning.active, isFalse);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(input.last.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native workspace keeps search, shared views and terminal input distinct',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ final codexInput = <TerminalBinaryFrame>[];
+ final claudeInput = <TerminalBinaryFrame>[];
+ final codex = terminal('a0', codexInput)
+ ..agentName = 'Fix login redirect';
+ final claude = terminal('a1', claudeInput)
+ ..agentName = 'Fix login redirect';
+ final firstPane = app.adoptSessionForTest(codex);
+ final secondPane = app.adoptSessionForTest(claude);
+ app.setPreset(2, PanePreset.columns);
+ app.focusPane(firstPane.id);
+ final source = app.activeSwarm;
+ app.renameSwarm(source.id, 'Native review fixture');
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+
+ Finder viewFor(TerminalSession session) => find.byWidgetPredicate(
+ (widget) =>
+ widget is TerminalView &&
+ identical(widget.terminal, session.terminal),
+ );
+ Future<void> output(
+ TerminalSession session,
+ int sequence,
+ String text, {
+ bool keyframe = false,
+ }) => session.handleBinary(
+ TerminalBinaryFrame(
+ kind: keyframe
+ ? TerminalBinaryKind.keyframe
+ : TerminalBinaryKind.output,
+ streamId: session.streamId!,
+ seq: sequence,
+ compressed: false,
+ cols: keyframe ? 80 : null,
+ rows: keyframe ? 24 : null,
+ bytes: utf8.encode(text),
+ ),
+ );
+ final history = List.generate(
+ 200,
+ (i) => 'Line $i ${i % 50 == 0 ? 'checkpoint marker' : 'completed'}\r\n',
+ ).join();
+ await output(codex, 0, '${history}ready> ', keyframe: true);
+ await output(
+ claude,
+ 0,
+ 'Reviewing the same project\r\nready> ',
+ keyframe: true,
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final view = tester.state<TerminalViewState>(viewFor(codex));
+ final scroll = view.widget.scrollController!;
+ final bottom = scroll.offset;
+ expect(bottom, greaterThan(1000));
+ await tester.sendEventToBinding(
+ PointerScrollEvent(
+ position: tester.getCenter(viewFor(codex)),
+ scrollDelta: const Offset(0, -300),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ final reading = scroll.offset;
+ expect(reading, lessThan(bottom));
+ await output(codex, 1, '\r\nAnother response arrived');
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(
+ scroll.offset,
+ closeTo(reading, .5),
+ reason: 'Output must not pull a reader away',
+ );
+
+ await key(tester, LogicalKeyboardKey.keyF, cmd: true);
+ final findInput = find.byKey(const ValueKey('terminal-find-editor'));
+ await tester.enterText(findInput, 'checkpoint marker');
+ // Native indexing and window layout run on the real event loop. Wait
+ // for this query's completed snapshot rather than a fixed frame budget.
+ final findDeadline = DateTime.now().add(const Duration(seconds: 5));
+ while (DateTime.now().isBefore(findDeadline)) {
+ await tester.pump(const Duration(milliseconds: 20));
+ final search = tester
+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))
+ .search!;
+ if (search.query == 'checkpoint marker' &&
+ search.hasSnapshot &&
+ !search.searching) {
+ break;
+ }
+ }
+ final completedSearch = tester
+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))
+ .search!;
+ expect(completedSearch.query, 'checkpoint marker');
+ expect(
+ completedSearch.searching,
+ isFalse,
+ reason: 'Find must finish indexing before its result count is checked',
+ );
+ expect(completedSearch.hasSnapshot, isTrue);
+ expect(
+ tester
+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))
+ .search!
+ .count,
+ 4,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(scroll.offset, closeTo(reading, .5));
+ expect(codexInput, isEmpty);
+ expect(claudeInput, isEmpty);
+ tester.testTextInput.enterText('git status');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(
+ utf8.decode([for (final frame in codexInput) ...frame.bytes]),
+ 'git status\r',
+ );
+ expect(claudeInput, isEmpty);
+ codexInput.clear();
+
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ Future<void> command(String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(search, '> $query');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 80));
+ }
+
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.enterText(search, 'login claude M2');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 80));
+ final sharedTab = app.activeSwarm;
+ expect(sharedTab, isNot(same(source)));
+ expect(sharedTab.name, 'Fix login redirect');
+ expect(sharedTab.panes.single.session, same(claude));
+ expect(source.panes, [firstPane, secondPane]);
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ await command('reopen tab');
+ expect(app.activeSwarm.id, sharedTab.id);
+ expect(app.focusedPane!.session, same(claude));
+ await command('next tab');
+ expect(app.activeSwarm, same(source));
+ expect(app.focusedPane, same(firstPane));
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ expect(app.focusedPane, same(secondPane));
+ await key(tester, LogicalKeyboardKey.keyH, cmd: true);
+ expect(app.focusedPane, same(firstPane));
+ await key(tester, LogicalKeyboardKey.arrowRight, cmd: true, shift: true);
+ expect(source.panes, [secondPane, firstPane]);
+ expect(app.focusedPane, same(firstPane));
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(app.zoomedPaneId, firstPane.id);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await command('resize panes');
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(tester.state<TerminalViewState>(viewFor(codex)), same(view));
+ expect(codexInput, isEmpty);
+ expect(claudeInput, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(codexInput.single.bytes, [27, 91, 68]);
+ expect(claudeInput, isEmpty);
+ // The Store is a workspace destination, reached by the same command
+ // from a native window without replacing either terminal.
+ await command('browse harnesses');
+ final storeTab = app.activeSwarm;
+ expect(storeTab.isStore, isTrue);
+ expect(source.panes, [secondPane, firstPane]);
+ await command('install');
+ expect(app.activeSwarm, same(storeTab));
+ expect(app.swarms.where((tab) => tab.isStore), hasLength(1));
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ await tester.pump(const Duration(milliseconds: 80));
+ await key(tester, LogicalKeyboardKey.digit1, cmd: true);
+ expect(app.activeSwarm, same(source));
+ expect(tester.state<TerminalViewState>(viewFor(codex)), same(view));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ for (final (label, shortcut) in [
+ ('New Tab', LogicalKeyboardKey.keyT),
+ ('New Pane', LogicalKeyboardKey.keyP),
+ ]) {
+ testWidgets('native created $label gets terminal input without a click', (
+ tester,
+ ) async {
+ final connection = _CreationConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ app.machineStates['m']!
+ ..localOnly = true
+ ..terminalCapabilityAvailable = true;
+ final originalInput = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', originalInput));
+ final source = app.activeSwarm;
+ addTearDown(app.dispose);
+ addTearDown(connection.close);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app, nativeTabs: true),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await key(
+ tester,
+ shortcut == LogicalKeyboardKey.keyT
+ ? LogicalKeyboardKey.keyP
+ : LogicalKeyboardKey.keyT,
+ cmd: true,
+ );
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, 'Check retargeted keyboard input');
+ await key(tester, shortcut, cmd: true);
+ await key(tester, shortcut, cmd: true);
+ expect(find.text('Check retargeted keyboard input'), findsWidgets);
+ expect(find.text(label), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .task,
+ 'Check retargeted keyboard input',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.activeSwarm == source, label == 'New Pane');
+ final session = app.focusedPane!.session!;
+ final view = tester.widget<TerminalView>(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is TerminalView &&
+ identical(widget.terminal, session.terminal),
+ ),
+ );
+ expect(view.focusNode!.hasFocus, isTrue);
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = '00000000-0000-4000-8000-000000000002';
+ session.notifyListeners();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(connection.input.single.bytes, [27, 91, 67]);
+ expect(originalInput, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ });
+ }
+
+ for (final (entry, task) in [
+ ('Open', null),
+ ('Try', 'Model a reading nook'),
+ ('Models', null),
+ ]) {
+ testWidgets(
+ 'native ${entry == 'Models' ? 'Models' : 'Store $entry'} switches products and focuses the started pane',
+ (tester) async {
+ const products = [
+ {
+ 'id': 'autonomous/workshop',
+ 'name': 'Autonomous Workshop',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+ {
+ 'id': 'autonomous/blender',
+ 'name': 'Blender',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+ {
+ 'id': AppNotifier.gridHarness,
+ 'name': 'Grid',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+ ];
+ final connection = _CreationConnection(products: products);
+ final app = _FirstCreationApp(connection);
+ seedMixedAgents(app);
+ app.machineStates['m']!
+ ..localOnly = true
+ ..terminalCapabilityAvailable = true
+ ..dsh.replace(products.map((json) => DshEntry.fromJson(json)!));
+ final originalInput = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', originalInput));
+ app.openStore();
+ final store = app.activeSwarm;
+ addTearDown(app.dispose);
+ addTearDown(connection.close);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(notifier: app, nativeTabs: true),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ NewHarnessController prompt() =>
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+ Future<void> open(String id, {String? task}) async {
+ await openStoreAgent(
+ tester.element(find.byType(StoreTab)),
+ app,
+ id,
+ 'm',
+ prompt: task,
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ }
+
+ await open('autonomous/workshop');
+ expect(
+ prompt().projectLabel,
+ startsWith('~/harnesses/autonomous-workshop-'),
+ );
+ if (entry == 'Models') {
+ final reply = Completer<void>();
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ 'harness/swarm_tabs',
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('runLocalModel', {'machineId': 'm'}),
+ ),
+ (_) => reply.complete(),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await reply.future;
+ } else {
+ await open('autonomous/blender', task: task);
+ }
+ final product = entry == 'Models'
+ ? AppNotifier.gridHarness
+ : 'autonomous/blender';
+ final prefix = entry == 'Models' ? 'grid' : 'blender';
+ expect(prompt().engine, product);
+ expect(prompt().projectLabel, startsWith('~/harnesses/$prefix-'));
+ expect(prompt().task, task ?? '');
+ final folder = prompt().projectFolderRequest!.folderName;
+ expect(app.activeSwarm, same(store));
+ expect(connection.creates, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pump();
+ expect(connection.creates, hasLength(1));
+ expect(connection.creates.single['dsh'], product);
+ expect(connection.creates.single['prompt'], task);
+ expect(connection.creates.single['cwd'], '/fixture/harnesses/$folder');
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.activeSwarm.isStore, isFalse);
+ final session = app.focusedPane!.session!;
+ final view = tester.widget<TerminalView>(
+ find.byWidgetPredicate(
+ (widget) =>
+ widget is TerminalView &&
+ identical(widget.terminal, session.terminal),
+ ),
+ );
+ expect(view.focusNode!.hasFocus, isTrue);
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = '00000000-0000-4000-8000-000000000002';
+ session.notifyListeners();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ expect(connection.input.single.bytes, [27, 91, 67]);
+ expect(originalInput, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+ }
+
+ testWidgets(
+ 'native creation retains edited defaults and uses the chosen destination',
+ (tester) async {
+ final connection = _CreationConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final original = app.adoptSessionForTest(terminal('a0', input));
+ final source = app.activeSwarm;
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ addTearDown(connection.close);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+
+ final line = find.byKey(const ValueKey('new-harness-input'));
+ NewHarnessController prompt() =>
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(prompt().engine, 'codex');
+ expect(prompt().machineId, 'm');
+ expect(prompt().project.folder, '/work/openharness');
+ expect(app.swarms, [source]);
+ expect(prompt().field, NewHarnessField.launch);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().field, NewHarnessField.machine);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'project');
+ await tester.enterText(line, 'openharness');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().project.folder, '/work/openharness');
+ expect(prompt().field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'task');
+ await tester.enterText(line, 'Refine terminal workspace');
+ await key(tester, LogicalKeyboardKey.enter, alt: true);
+ expect(
+ tester.widget<TextField>(line).controller!.text,
+ 'Refine terminal workspace\n',
+ );
+ const task = 'Refine terminal workspace\nKeep running sessions attached';
+ await tester.enterText(line, task);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(line, 'claude');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().engine, 'claude');
+ expect(prompt().task, task);
+ await openLaunchRow(tester, 'project');
+ expect(prompt().field, NewHarnessField.projectMenu);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().field, NewHarnessField.project);
+ expect(prompt().options.single.id, NewHarnessController.browseId);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'agent');
+ for (
+ var step = 0;
+ prompt().selected?.id != 'codex' && step < 30;
+ step++
+ ) {
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ }
+ expect(prompt().selected?.id, 'codex');
+ expect(prompt().engine, 'claude');
+ await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
+ expect(prompt().field, NewHarnessField.profile);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(prompt().engine, 'claude');
+ await openLaunchRow(tester, 'agent');
+ await openAgentSetting(
+ tester,
+ prompt().selected!.engine!,
+ NewHarnessController.permissionsId,
+ );
+ expect(prompt().field, NewHarnessField.mode);
+ await tester.enterText(line, 'Plan first');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(prompt().field, NewHarnessField.agent);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(prompt().mode, 'plan');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.swarms, [source]);
+ expect(
+ input,
+ isEmpty,
+ reason:
+ 'Picker input must stay out of the terminal: '
+ '${input.map((frame) => (frame.kind.name, frame.bytes.toList())).toList()}',
+ );
+ expect(connection.creates, isEmpty);
+
+ // Reopen from the same source, this time choosing a pane. Escape kept
+ // both the task and edited defaults without allocating an empty tab.
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(prompt().engine, 'claude');
+ expect(prompt().mode, 'plan');
+ expect(prompt().task, task);
+ expect(prompt().project.folder, '/work/openharness');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.activeSwarm, same(source));
+ expect(source.panes.length, 2);
+ expect(source.panes.first, same(original));
+ expect(app.focusedPane!.agentId, 'made');
+ expect(connection.creates.single, containsPair('prompt', task));
+ expect(connection.creates.single, containsPair('engine', 'claude'));
+ expect(connection.creates.single, containsPair('permissionMode', 'plan'));
+ expect(
+ connection.creates.single,
+ containsPair('cwd', '/work/openharness'),
+ );
+
+ // The just-created agent is immediately searchable and names a new tab.
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Refine terminal workspace',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.activeSwarm, isNot(same(source)));
+ expect(app.activeSwarm.name, 'Refine terminal workspace');
+ expect(app.focusedPane!.agentId, 'made');
+ expect(connection.creates.length, 1);
+ expect(input, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native link prompt retries and resumes without losing terminal input',
+ (tester) async {
+ final links = _WorkspaceLinks();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ peerLinks: links,
+ )..hasNavigationRail = false;
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ app.machineStates['studio']!.needsLink = true;
+ app.selectedMachineId = 'studio';
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ final field = find.byKey(const Key('remote-password-connect-field'));
+ // The initial workspace schedules this dialog after its first frame;
+ // allow the new route's autofocus request to settle as well.
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await tester.enterText(field, 'fixture password');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ expect(links.requests, ['studio']);
+ expect(tester.widget<TextField>(field).readOnly, isTrue);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+
+ links.replies.first.complete(
+ const CliLinkConnectResult(error: 'Incorrect password'),
+ );
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(find.text('Incorrect password'), findsOneWidget);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await tester.enterText(field, 'correct fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(links.requests, ['studio', 'studio']);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 80));
+ expect(find.byType(LinkMachineScreen), findsNothing);
+ expect(app.focusedPane, same(pane));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ input.clear();
+
+ // Use the real command and machine chooser to revisit the pending link.
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> link machine',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final machineSearch = find.byKey(const Key('link-machine-search'));
+ expect(
+ tester.widget<TextField>(machineSearch).focusNode!.hasFocus,
+ isTrue,
+ );
+ await tester.enterText(machineSearch, 'office');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(field).readOnly, isTrue);
+ expect(tester.widget<TextField>(field).controller!.text, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(links.requests, ['studio', 'studio']);
+ links.replies.last.complete(
+ const CliLinkConnectResult(linkedMachineId: 'studio'),
+ );
+ await tester.pump(const Duration(milliseconds: 80));
+ await tester.pump();
+ expect(find.byType(LinkMachineScreen), findsNothing);
+ expect(app.machineStates['studio']!.needsLink, isFalse);
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(machineSearch).controller!.text,
+ 'office',
+ );
+ expect(
+ tester.widget<TextField>(machineSearch).focusNode!.hasFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 80));
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 67]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native local password prompt survives pending changes and returns to its terminal',
+ (tester) async {
+ final cli = PasswordCli()
+ ..setReply = Completer<RemotePasswordSetResult>();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ )..hasNavigationRail = false;
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> link machine',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final search = find.byKey(const Key('link-machine-search'));
+ await tester.enterText(search, 'password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final password = find.byKey(const Key('remote-password-field'));
+ final confirm = find.byKey(const Key('remote-password-confirm-field'));
+ expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
+ await tester.enterText(password, 'fixture password');
+ await tester.testTextInput.receiveAction(TextInputAction.next);
+ await tester.pump();
+ expect(tester.widget<TextField>(confirm).focusNode!.hasFocus, isTrue);
+ await tester.enterText(confirm, 'fixture password');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['fixture password']);
+ expect(tester.widget<TextField>(confirm).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(search).controller!.text, 'password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Setting password…'), findsOneWidget);
+ expect(cli.passwords, hasLength(1));
+ cli.setReply!.complete(cli.setResult);
+ await tester.pumpAndSettle();
+ expect(find.text('Remote password is set'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
+ expect(tester.widget<TextField>(password).controller!.text, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape); // Cancel editing.
+ await key(tester, LogicalKeyboardKey.escape); // Return to chooser.
+ await key(tester, LogicalKeyboardKey.escape); // Return to terminal.
+ await tester.pumpAndSettle();
+ expect(app.focusedPane, same(pane));
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 67]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'native machine management keeps query, pending edits and terminal ownership',
+ (tester) async {
+ final api = MachineApi()
+ ..renameReply = Completer<String?>()
+ ..deleteReply = Completer<void>();
+ final app = createApp()..api = api;
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> machines manager',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final search = find.byKey(const Key('machines-manager-search'));
+ expect(tester.widget<TextField>(search).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('office');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ // Type through the existing native editing connection after the mode switch.
+ tester.testTextInput.enterText('rename');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final rename = find.byKey(const Key('machine-rename-input'));
+ expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('Office builder');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(api.renames, [('studio', 'Office builder')]);
+ expect(tester.widget<TextField>(rename).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(search).controller!.text, 'rename');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(rename).readOnly, isTrue);
+ expect(api.renames, hasLength(1));
+ api.renameReply!.complete('Office builder');
+ await tester.pumpAndSettle();
+ expect(find.text('Office builder'), findsOneWidget);
+ tester.testTextInput.enterText('delete');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter); // Cancel is the default.
+ await tester.pumpAndSettle();
+ expect(api.deletes, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(api.deletes, ['studio']);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Deleting machine…'), findsOneWidget);
+ expect(api.deletes, hasLength(1));
+ api.deleteReply!.complete();
+ await tester.pumpAndSettle();
+ expect(app.stateOf('studio'), isNull);
+ expect(find.text('Machines Manager'), findsOneWidget);
+ expect(tester.widget<TextField>(search).controller!.text, 'office');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(app.focusedPane, same(pane));
+ expect(pane.session, same(session));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+ testWidgets(
+ 'native rename prompts keep pending work and return terminal input',
+ (tester) async {
+ final connection = RenameConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final pane = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> command(String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $query',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ await command('rename tab');
+ final tab = find.byKey(const Key('tab-rename-input'));
+ expect(tester.widget<TextField>(tab).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Parser work');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarm.name, 'Parser work');
+ await command('rename agent');
+ final agent = find.byKey(const Key('agent-rename-input'));
+ expect(
+ tester.widget<TextField>(agent).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ tester.testTextInput.enterText('Resolve parser edge');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(connection.renames.single, {
+ 'agentId': 'a0',
+ 'name': 'Resolve parser edge',
+ });
+ await key(tester, LogicalKeyboardKey.escape);
+ await command('rename agent');
+ expect(tester.widget<TextField>(agent).readOnly, isTrue);
+ expect(connection.renames, hasLength(1));
+ connection.replies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(agent).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ tester.testTextInput.enterText('Resolve parser edge');
+ await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
+ expect(
+ tester.widget<TextField>(agent).controller!.text,
+ 'Resolve parser ',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.replies.last.complete({
+ 'agent': {'name': 'Resolve parser'},
+ });
+ await tester.pumpAndSettle();
+ expect(agent, findsNothing);
+ expect(session.agentName, 'Resolve parser');
+ expect(app.focusedPane, same(pane));
+ expect(app.activeSwarm.name, 'Parser work');
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+ testWidgets(
+ 'native stop confirmation retains pending work and restores the other terminal',
+ (tester) async {
+ final connection = StopConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final retained = app.adoptSessionForTest(session);
+ app.adoptSessionForTest(terminal('a1', input));
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> openStop() async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> stop',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ await openStop();
+ await key(tester, LogicalKeyboardKey.enter); // Cancel by default.
+ await tester.pumpAndSettle();
+ expect(connection.stops, isEmpty);
+ expect(find.text('Stop Agent'), findsNothing);
+ await openStop();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(connection.stops, ['a1']);
+ expect(find.text('Stopping…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await openStop();
+ expect(find.text('Stopping…'), findsOneWidget);
+ expect(connection.stops, hasLength(1));
+ connection.stopReplies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Stop failed: Reconnect and retry.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.stopReplies.last.complete({'deleted': true});
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ expect(app.allPanes, [retained]);
+ expect(app.focusedPane, same(retained));
+ expect(retained.session, same(session));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.streamId, 'stream-a0');
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+ testWidgets(
+ 'native fork prompt retains drafts and checks a lost receipt without duplication',
+ (tester) async {
+ final connection = ForkConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final source = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> openFork() async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> fork',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ final task = find.byKey(const ValueKey('fork-task'));
+ await openFork();
+ expect(tester.widget<TextField>(task).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Try a smaller change');
+ await key(tester, LogicalKeyboardKey.enter, alt: true);
+ expect(
+ tester.widget<TextField>(task).controller!.text,
+ 'Try a smaller change\n',
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await openFork();
+ expect(
+ tester.widget<TextField>(task).controller!.text,
+ 'Try a smaller change\n',
+ );
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ final id = connection.forks.single['creationId'] as String;
+ expect(connection.forks.single['prompt'], 'Try a smaller change\n');
+ await key(tester, LogicalKeyboardKey.escape);
+ await openFork();
+ expect(connection.forks, hasLength(1));
+ expect(tester.widget<TextField>(task).readOnly, isTrue);
+ connection.forkReplies.single.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('enter check status'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.checks, [
+ {'creationId': id},
+ ]);
+ connection.checkReplies.single.complete(forkReceipt(id));
+ // The new pane has no live PTY transport in this fixture, so its attaching
+ // animation intentionally remains. The receipt and route still complete.
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(task, findsNothing);
+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'forked']);
+ expect(app.focusedPane!.agentId, 'forked');
+ expect(source.session, same(session));
+ expect(connection.forks, hasLength(1));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyH, cmd: true);
+ expect(app.focusedPane, same(source));
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+ testWidgets(
+ 'native restart rejoins pending work and recovers without replacing the terminal view',
+ (tester) async {
+ final connection = RestartConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ final source = app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore();
+ addTearDown(app.dispose);
+ addTearDown(projects.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: true,
+ projectStore: projects,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> openRestart() async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> restart',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ await openRestart();
+ expect(find.text('Restarting…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openRestart();
+ expect(connection.requests, hasLength(1));
+ final id = connection.requests.single['creationId'] as String;
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.checks, [
+ {'creationId': id},
+ ]);
+ connection.checkReplies.single.complete(
+ restartReceipt(id, resumed: false),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'Started a new conversation. The previous session could not be resumed.',
+ ),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('agent-restart-prompt')), findsNothing);
+ expect(app.panes, [source]);
+ expect(source.session, same(session));
+ expect(connection.requests, hasLength(1));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+}
diff --git a/desktop/lib/api/api_client.dart b/desktop/lib/api/api_client.dart
index 3529e82d5..c7319cd80 100644
--- a/desktop/lib/api/api_client.dart
+++ b/desktop/lib/api/api_client.dart
@@ -1,3 +1,5 @@
+import 'dart:collection';
+
import 'package:dio/dio.dart';
import '../auth/auth_session.dart';
@@ -7,6 +9,13 @@ import '../logging/http_log.dart';
import 'access_token_source.dart';
import 'bearer_auth_interceptor.dart';
+/// Rows and freshness from one response, even when requests overlap.
+class MachineInventory extends UnmodifiableListView<Machine> {
+ MachineInventory(super.source, {required this.isStale});
+
+ final bool isStale;
+}
+
/// Control-plane REST client.
///
/// In a desktop build every call goes to the LOCAL `harness` CLI (loopback, no credential — see
@@ -141,36 +150,62 @@ class ApiClient {
/// caller that only checked the status code would mistake an outage for a healthy, current read.
bool lastMachinesStale = false;
List<Machine> _sharedMachines = [];
+ int _accountRevision = 0;
+ int _machineRequestRevision = 0;
+
+ /// Sharing fallback belongs to the account that loaded it. Late responses
+ /// must not refill it after sign-out or while a new sign-in is starting.
+ void resetAccountCache() {
+ ++_accountRevision;
+ _sharedMachines = [];
+ lastMachinesStale = false;
+ }
+
+ void _requireAccount(int revision) {
+ if (revision != _accountRevision) {
+ throw StateError('Account changed while loading machines.');
+ }
+ }
Future<List<Machine>> machines() async {
+ final account = _accountRevision;
+ final request = ++_machineRequestRevision;
final res = await _dio.get('/api/machines');
+ _requireAccount(account);
final data = unwrapApiResponse(res) as Map<String, dynamic>;
- lastMachinesStale = data['stale'] == true;
+ var stale = data['stale'] == true;
final list = data['machines'] as List<dynamic>? ?? [];
final owned = list
.map((e) => Machine.fromJson(e as Map<String, dynamic>))
.toList();
+ var sharedMachines = _sharedMachines;
try {
final shared = await _dio.get('/api/harness-shares');
+ _requireAccount(account);
if (shared.statusCode == 404) {
- _sharedMachines = [];
+ sharedMachines = [];
} else {
final body = unwrapApiResponse(shared) as Map<String, dynamic>;
- _sharedMachines = [
+ sharedMachines = [
for (final row in body['machines'] as List? ?? const [])
Machine.fromJson(Map<String, dynamic>.from(row as Map)),
];
}
} catch (error) {
if (isUnauthorizedError(error)) rethrow;
- lastMachinesStale = true;
+ stale = true;
+ }
+ _requireAccount(account);
+ if (request == _machineRequestRevision) {
+ _sharedMachines = sharedMachines;
+ lastMachinesStale = stale;
}
- return [
+ return MachineInventory([
...owned,
- ..._sharedMachines.where(
+ ...sharedMachines.where(
(shared) => !owned.any((own) => own.machineId == shared.machineId),
),
- ];
+ ], isStale: stale);
}
Future<String?> renameMachine({
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dart
index eb12ed5e7..e594029d1 100644
--- a/desktop/lib/app_shell.dart
+++ b/desktop/lib/app_shell.dart
@@ -25,6 +25,7 @@ import 'core/startup.dart';
import 'logging/app_log.dart';
import 'logging/install.dart';
import 'shortcuts/app_keymap.dart';
+import 'shortcuts/keyboard_practice.dart';
import 'widgets/shortcuts_sheet.dart';
import 'widgets/update_notice.dart';
import 'widgets/window_chrome.dart';
@@ -45,6 +46,7 @@ typedef AuthenticatedScreenBuilder = Widget Function(AppNotifier app);
/// trees are otherwise byte-identical outside `lib/phone/` and `lib/p2p/`.
Future<void> startHarness({
required AuthenticatedScreenBuilder authenticatedScreen,
+
/// A viewer build's second wire to each machine (see
/// [TerminalTransportPlugin]); the desktop passes none.
TerminalTransportPluginFactory? transportPlugins,
@@ -64,17 +66,16 @@ Future<void> startHarness({
await configureDesktopWindow(palette: appearancePrefsStore.value.palette);
runApp(
ProviderScope(
- child: HarnessApp(keymap: keymap, authenticatedScreen: authenticatedScreen),
+ child: HarnessApp(
+ keymap: keymap,
+ authenticatedScreen: authenticatedScreen,
+ ),
),
);
}
class HarnessApp extends StatelessWidget {
- const HarnessApp({
- super.key,
- this.keymap,
- required this.authenticatedScreen,
- });
+ const HarnessApp({super.key, this.keymap, required this.authenticatedScreen});
final AppKeymap? keymap;
final AuthenticatedScreenBuilder authenticatedScreen;
@@ -238,11 +239,7 @@ class _RootShellState extends ConsumerState<RootShell>
switch (call.method) {
case 'checkForUpdates':
final app = ref.read(appStateProvider);
- await _menuDialog(() async {
- final result = await app.checkForUpdates();
- if (!mounted) return;
- await showUpdateCheckDialog(context, app, result);
- });
+ await _menuDialog(() => checkForUpdatesAndShowResult(context, app));
case 'flashFirmware':
await _menuDialog(() => showFlashFirmwareDialog(context));
case 'exportLogs':
@@ -254,6 +251,8 @@ class _RootShellState extends ConsumerState<RootShell>
);
case 'showShortcuts':
await _menuDialog(() => showShortcutsSheet(context));
+ case 'keyboardPractice':
+ await _menuDialog(() => showKeyboardPractice(context));
case 'increaseTerminalFontSize':
await terminalFontStore.increaseSize();
case 'decreaseTerminalFontSize':
diff --git a/desktop/lib/auth/cli_link.dart b/desktop/lib/auth/cli_link.dart
index ec9986d5d..cd18f174b 100644
--- a/desktop/lib/auth/cli_link.dart
+++ b/desktop/lib/auth/cli_link.dart
@@ -130,8 +130,8 @@ class CliLink implements PeerLinkClient {
);
}
- /// Clears this machine's remote password, revoking remote access for anyone who knew it. Null
- /// on success.
+ /// Clears this machine's remote password, preventing new password-based links.
+ /// Existing trust and sessions are separate. Null on success.
Future<String?> clearRemotePassword() async {
final invocation = await _runJson([
'remote-password',
diff --git a/desktop/lib/auth/cli_login.dart b/desktop/lib/auth/cli_login.dart
index 68176bd27..358e229c1 100644
--- a/desktop/lib/auth/cli_login.dart
+++ b/desktop/lib/auth/cli_login.dart
@@ -152,10 +152,33 @@ class CliLogin implements SignInClient {
@override
Future<void> logout() async {
+ // Own a process handle: a timed-out logout must not remain alive and erase
+ // the credentials saved by the user's next sign-in.
+ final Process process;
+ try {
+ process = await _runner.start(['logout']);
+ } catch (error) {
+ throw CliNotAvailableException('Could not run the harness CLI: $error');
+ }
try {
- await _run(['logout']);
- } catch (_) {
- // Best-effort: local app state is cleared regardless by the caller.
+ int? exitCode;
+ await Future.wait<void>([
+ process.stdout.drain<void>(),
+ process.stderr.drain<void>(),
+ process.exitCode.then((value) => exitCode = value),
+ ]).timeout(_runner.runTimeout);
+ if (exitCode != 0) {
+ throw StateError('Could not finish signing out. Try again.');
+ }
+ } on TimeoutException {
+ process.kill();
+ try {
+ await process.exitCode.timeout(const Duration(seconds: 1));
+ } on TimeoutException {
+ process.kill(ProcessSignal.sigkill);
+ await process.exitCode;
+ }
+ throw StateError('Sign-out took too long. Try again.');
}
}
diff --git a/desktop/lib/bootstrap/environment_provisioner.dart b/desktop/lib/bootstrap/environment_provisioner.dart
index 2890d7fa5..ca1772cda 100644
--- a/desktop/lib/bootstrap/environment_provisioner.dart
+++ b/desktop/lib/bootstrap/environment_provisioner.dart
@@ -1,7 +1,9 @@
import '../core/host_platform.dart';
+
import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'dart:typed_data';
import '../core/harness_cli_runner.dart';
@@ -189,10 +191,15 @@ class EnvironmentReadiness {
},
);
- bool get isReady => steps.values.every(
- (status) =>
- status == EnvironmentStepStatus.ready ||
- status == EnvironmentStepStatus.notApplicable,
+ bool get isReady =>
+ phase == EnvironmentSetupPhase.ready &&
+ failure == null &&
+ _requiredStepsReady;
+
+ bool get _requiredStepsReady => EnvironmentStep.values.every(
+ (step) =>
+ steps[step] == EnvironmentStepStatus.ready ||
+ steps[step] == EnvironmentStepStatus.notApplicable,
);
/// Every step but the Harness CLI itself is satisfied — the point at which
@@ -265,6 +272,15 @@ typedef ProcessStarter = Future<Process> Function(
Map<String, String>? environment,
});
+class _EnvironmentProbeTimeout implements Exception {
+ const _EnvironmentProbeTimeout(this.label, this.step);
+ final String label;
+ final EnvironmentStep? step;
+
+ @override
+ String toString() => 'The check for $label did not finish.';
+}
+
/// The progress callback `ensureReady` builds for itself, named so the per-host paths below can be
/// separate methods rather than one very long function.
typedef EmitStep = void Function({
@@ -328,6 +344,7 @@ class EnvironmentProvisioner {
final bool _isLinux;
final bool _isWindows;
final Map<String, String> _platformEnvironment;
+ final Duration probeTimeout;
EnvironmentProvisioner({
Directory? harnessHome,
@@ -338,6 +355,7 @@ class EnvironmentProvisioner {
bool? isLinux,
bool? isWindows,
Map<String, String>? platformEnvironment,
+ this.probeTimeout = const Duration(seconds: 10),
}) : harnessHome = harnessHome ?? Directory(_defaultHarnessHome()),
_run = run ?? _defaultRun,
_start = start ?? (run == null ? _defaultStart : null),
@@ -472,112 +490,121 @@ class EnvironmentProvisioner {
return probe;
}
- final previousTerminalLog = state.terminalLogPath;
- var previousTerminalLogText = '';
- EnvironmentTerminalSetup? completedTerminalSetup;
- if (previousTerminalLog != null) {
- try {
- final text = await File(previousTerminalLog).readAsString();
- previousTerminalLogText = text;
- final snapshot = 'Terminal log:\n${text.trim()}';
- if (text.trim().isNotEmpty && !state.output.contains(snapshot)) {
- emit(output: snapshot);
+ try {
+ final previousTerminalLog = state.terminalLogPath;
+ var previousTerminalLogText = '';
+ EnvironmentTerminalSetup? completedTerminalSetup;
+ if (previousTerminalLog != null) {
+ try {
+ final recent = await _readTerminalLogTail(previousTerminalLog);
+ previousTerminalLogText = recent.text;
+ final snapshot =
+ 'Terminal log:\n'
+ '${recent.truncated ? '[Earlier output omitted. Full log: $previousTerminalLog]\n' : ''}'
+ '${recent.text.trim()}';
+ if (recent.text.trim().isNotEmpty &&
+ !state.output.contains(snapshot)) {
+ emit(output: snapshot);
+ }
+ } on FileSystemException {
+ // The terminal may not have created its log yet.
}
- } on FileSystemException {
- // The terminal may not have created its log yet.
}
- }
- final previousTerminalResult = state.terminalResultPath;
- var terminalResultPending = false;
- if (previousTerminalResult != null) {
- if (!await File(previousTerminalResult).exists()) {
+ final previousTerminalResult = state.terminalResultPath;
+ var terminalResultPending = false;
+ if (previousTerminalResult != null) {
+ // Missing, unreadable, or partially written results are still pending.
+ // Only a complete exit code can finish the handoff; live probes below
+ // can independently establish that the required tools are ready.
terminalResultPending = true;
- // `terminal.exit` is a handoff hint, not the source of truth. Some
- // Linux terminal emulators keep the launched shell/window alive after
- // apt has already finished, and an interrupted EXIT trap can omit the
- // file entirely. Continue into the read-only command probes below so
- // the 5-second poll (and the user's Recheck button) can observe that
- // the host is actually ready instead of waiting forever for a file a
- // cold app launch does not need either.
- emit(
- message: state.message ?? 'Complete the visible prompts in Terminal.',
- phase: EnvironmentSetupPhase.waitingForTerminal,
- );
- }
- try {
- final exitCode = int.tryParse(
- (await File(previousTerminalResult).readAsString()).trim(),
- );
- if (exitCode != null && exitCode != 0) {
- // The only Terminal handoff left is Linux's apt transaction.
- final clipboardFailed =
- state.steps[EnvironmentStep.clipboard] ==
- EnvironmentStepStatus.needsTerminal;
- final tmuxFailed =
- state.steps[EnvironmentStep.tmux] ==
- EnvironmentStepStatus.needsTerminal;
- if (clipboardFailed) {
- emit(
- step: EnvironmentStep.clipboard,
- status: EnvironmentStepStatus.failed,
+ if (!await File(previousTerminalResult).exists()) {
+ // `terminal.exit` is a handoff hint, not the source of truth. Some
+ // Linux terminal emulators keep the launched shell/window alive after
+ // apt has already finished, and an interrupted EXIT trap can omit the
+ // file entirely. Continue into the read-only command probes below so
+ // the 5-second poll (and the user's Recheck button) can observe that
+ // the host is actually ready instead of waiting forever for a file a
+ // cold app launch does not need either.
+ emit(
+ message:
+ state.message ?? 'Complete the visible prompts in Terminal.',
+ phase: EnvironmentSetupPhase.waitingForTerminal,
+ );
+ }
+ try {
+ final exitCode = int.tryParse(
+ (await File(previousTerminalResult).readAsString()).trim(),
+ );
+ if (exitCode != null) terminalResultPending = false;
+ if (exitCode != null && exitCode != 0) {
+ // The only Terminal handoff left is Linux's apt transaction.
+ final clipboardFailed =
+ state.steps[EnvironmentStep.clipboard] ==
+ EnvironmentStepStatus.needsTerminal;
+ final tmuxFailed =
+ state.steps[EnvironmentStep.tmux] ==
+ EnvironmentStepStatus.needsTerminal;
+ if (clipboardFailed) {
+ emit(
+ step: EnvironmentStep.clipboard,
+ status: EnvironmentStepStatus.failed,
+ );
+ }
+ if (tmuxFailed) {
+ emit(
+ step: EnvironmentStep.tmux,
+ status: EnvironmentStepStatus.failed,
+ );
+ }
+ final classifiedFailure = _classifiedLinuxPackageFailure(
+ exitCode,
+ previousTerminalLogText,
);
- }
- if (tmuxFailed) {
emit(
- step: EnvironmentStep.tmux,
- status: EnvironmentStepStatus.failed,
+ message: 'The Terminal setup exited with code $exitCode.',
+ phase: EnvironmentSetupPhase.failed,
+ failure: EnvironmentFailure(
+ step: clipboardFailed
+ ? EnvironmentStep.clipboard
+ : tmuxFailed
+ ? EnvironmentStep.tmux
+ : null,
+ title:
+ classifiedFailure?.title ??
+ 'System package installation failed',
+ detail:
+ classifiedFailure?.detail ??
+ 'Terminal exited with code $exitCode. Review the setup details below.',
+ command:
+ classifiedFailure?.command ??
+ await _linuxHostManualCommand(_aptPackagesOf(state.plan)),
+ exitCode: exitCode,
+ ),
);
+ return state;
}
- final classifiedFailure = _classifiedLinuxPackageFailure(
- exitCode,
- previousTerminalLogText,
- );
- emit(
- message: 'The Terminal setup exited with code $exitCode.',
- phase: EnvironmentSetupPhase.failed,
- failure: EnvironmentFailure(
- step: clipboardFailed
- ? EnvironmentStep.clipboard
- : tmuxFailed
- ? EnvironmentStep.tmux
- : null,
- title:
- classifiedFailure?.title ??
- 'System package installation failed',
- detail:
- classifiedFailure?.detail ??
- 'Terminal exited with code $exitCode. Review the complete log below.',
- command:
- classifiedFailure?.command ??
- await _linuxHostManualCommand(_aptPackagesOf(state.plan)),
- exitCode: exitCode,
- ),
- );
- return state;
+ if (exitCode == 0) completedTerminalSetup = state.terminalSetup;
+ } on FileSystemException {
+ // The result can disappear between exists() and readAsString(). The
+ // live dependency probes below remain the authoritative fallback.
}
- if (exitCode == 0) completedTerminalSetup = state.terminalSetup;
- } on FileSystemException {
- // The result can disappear between exists() and readAsString(). The
- // live dependency probes below remain the authoritative fallback.
}
- }
- onProgress(state);
+ onProgress(state);
- if (!_isMacOS && !_isLinux) {
- if (_isWindows) {
- await _verifyWindows(emit);
+ if (!_isMacOS && !_isLinux) {
+ if (_isWindows) {
+ await _verifyWindows(emit);
+ return state;
+ }
+ emit(
+ step: EnvironmentStep.harness,
+ status: EnvironmentStepStatus.failed,
+ message: 'Automatic environment setup is currently available on macOS and Linux only.',
+ phase: EnvironmentSetupPhase.failed,
+ );
return state;
}
- emit(
- step: EnvironmentStep.harness,
- status: EnvironmentStepStatus.failed,
- message: 'Automatic environment setup is currently available on macOS and Linux only.',
- phase: EnvironmentSetupPhase.failed,
- );
- return state;
- }
- try {
// The one thing every step needs and no plan can install.
if (!await _hasWritableHome()) {
const failure = EnvironmentFailure(
@@ -593,7 +620,7 @@ class EnvironmentProvisioner {
}
var probe = await probeAndReport();
- if (state.isReady) {
+ if (state._requiredStepsReady) {
emit(
message: 'All required tools passed verification.',
phase: EnvironmentSetupPhase.ready,
@@ -807,7 +834,7 @@ class EnvironmentProvisioner {
phase: EnvironmentSetupPhase.verifying,
);
await probeAndReport();
- if (!state.isReady) {
+ if (!state._requiredStepsReady) {
final failed = state.steps.entries
.where((entry) => entry.value == EnvironmentStepStatus.failed)
.map((entry) => entry.key)
@@ -819,7 +846,9 @@ class EnvironmentProvisioner {
emit(message: 'Environment ready.', phase: EnvironmentSetupPhase.ready);
return state;
} catch (error) {
+ final probeTimeout = error is _EnvironmentProbeTimeout ? error : null;
final failed =
+ probeTimeout?.step ??
state.steps.entries
.where((entry) => entry.value == EnvironmentStepStatus.running)
.map((entry) => entry.key)
@@ -831,19 +860,66 @@ class EnvironmentProvisioner {
emit(
step: failed,
status: EnvironmentStepStatus.failed,
- message: 'Environment setup failed: $error',
+ message: install
+ ? 'Environment setup failed: $error'
+ : 'Computer check failed: $error',
phase: EnvironmentSetupPhase.failed,
failure: EnvironmentFailure(
step: failed,
- title: 'Setup could not finish',
- detail: '$error',
- command: failed == null ? null : _manualCommandFor(failed),
+ title: probeTimeout != null
+ ? 'Checking this computer took too long'
+ : install
+ ? 'Setup could not finish'
+ : 'Could not check this computer',
+ detail: probeTimeout != null
+ ? '$error Retry to check again.'
+ : '$error',
+ command: probeTimeout != null || !install || failed == null
+ ? null
+ : _manualCommandFor(failed),
),
);
return state;
}
}
+ /// Polling a long-running installer must not reread and lay out its complete
+ /// log every five seconds. Preserve the original file for troubleshooting.
+ Future<({String text, bool truncated})> _readTerminalLogTail(
+ String path,
+ ) async {
+ const maxBytes = 64 * 1024;
+ const maxLines = 200;
+ final file = await File(path).open();
+ try {
+ final length = await file.length();
+ final offset = length > maxBytes ? length - maxBytes : 0;
+ await file.setPosition(offset);
+ var text = utf8.decode(
+ await file.read(length - offset),
+ allowMalformed: true,
+ );
+ var truncated = offset > 0;
+ if (truncated) {
+ // The byte limit may cut a UTF-8 character or a line. Prefer complete
+ // lines, but keep the tail if the whole chunk is one long line.
+ final firstNewline = text.indexOf('\n');
+ if (firstNewline >= 0 &&
+ text.substring(firstNewline + 1).trim().isNotEmpty) {
+ text = text.substring(firstNewline + 1);
+ }
+ }
+ final lines = const LineSplitter().convert(text);
+ if (lines.length > maxLines) {
+ text = lines.skip(lines.length - maxLines).join('\n');
+ truncated = true;
+ }
+ return (text: text, truncated: truncated);
+ } finally {
+ await file.close();
+ }
+ }
+
/// One read-only look at what this computer runs, and the plan for what it
/// does not — each rung probed only when the one above it is missing.
Future<_HostProbe> _probe() async {
@@ -944,7 +1020,7 @@ class EnvironmentProvisioner {
try {
final runner = HarnessCliRunner(
harnessHome: harnessHome,
- runProcess: _run,
+ runProcess: _probeHarnessCommand,
);
final status = await runner.run(['auth', 'status', '--json']);
harnessReady =
@@ -981,20 +1057,27 @@ class EnvironmentProvisioner {
}
Future<bool> _hasWritableHome() async {
- final writable = await _shell('test -w "\$HOME"');
+ final writable = await _probeShell(
+ 'test -w "\$HOME"',
+ 'your home directory',
+ );
return writable.exitCode == 0;
}
Future<bool> _hasCommand(String command) async {
- final probe = await _shell('command -v $command >/dev/null 2>&1');
+ final probe = await _probeShell(
+ 'command -v $command >/dev/null 2>&1',
+ command,
+ );
return probe.exitCode == 0;
}
/// All of [commands] resolve. One shell for the lot: `command -v a b`
/// answers "any" in bash, so it is a loop rather than a list.
Future<bool> _hasCommands(Iterable<String> commands) async {
- final probe = await _shell(
+ final probe = await _probeShell(
'for c in ${commands.join(' ')}; do command -v "\$c" >/dev/null 2>&1 || exit 1; done',
+ commands.join(', '),
);
return probe.exitCode == 0;
}
@@ -1032,15 +1115,19 @@ class EnvironmentProvisioner {
plan.expand((item) => item.packages).toSet().toList();
Future<bool> _hasAptGet() async {
- final result = await _shell('command -v apt-get >/dev/null 2>&1');
+ final result = await _probeShell(
+ 'command -v apt-get >/dev/null 2>&1',
+ 'apt-get',
+ );
return result.exitCode == 0;
}
Future<bool> _canInstallAptUnattended() async {
- final user = await _shell('id -u');
+ final user = await _probeShell('id -u', 'your user account');
if (user.exitCode == 0 && '${user.stdout}'.trim() == '0') return true;
- final sudo = await _shell(
+ final sudo = await _probeShell(
'command -v sudo >/dev/null 2>&1 && sudo -n true >/dev/null 2>&1',
+ 'sudo access',
);
return sudo.exitCode == 0;
}
@@ -1195,14 +1282,22 @@ fi''';
if (nodePath.isEmpty || !File(nodePath).existsSync()) return false;
final runtimeRoot = '${harnessHome.absolute.path}/runtime/';
if (!File(nodePath).absolute.path.startsWith(runtimeRoot)) return false;
- final node = await _run(nodePath, ['--version']);
+ final node = await _runProbe(
+ nodePath,
+ ['--version'],
+ label: 'the managed Node runtime',
+ step: EnvironmentStep.harness,
+ );
if (node.exitCode != 0) return false;
final match = RegExp(r'^v?(\d+)').firstMatch('${node.stdout}'.trim());
if (match == null || int.parse(match.group(1)!) < 20) return false;
try {
final cli = File('${harnessHome.path}/cli/cli.js');
if (!await cli.exists()) return false;
- final version = await _run(nodePath, [cli.path, 'version']);
+ final version = await _probeHarnessCommand(nodePath, [
+ cli.path,
+ 'version',
+ ]);
return version.exitCode == 0;
} on ProcessException {
return false;
@@ -1212,7 +1307,10 @@ fi''';
}
Future<void> _ensureHarness(void Function(String line) onOutput) async {
- final runner = HarnessCliRunner(harnessHome: harnessHome, runProcess: _run);
+ final runner = HarnessCliRunner(
+ harnessHome: harnessHome,
+ runProcess: _probeHarnessCommand,
+ );
if (await _hasHarness()) return;
// No interpreter is named here. install.sh provisions the same
// checksum-verified Node under `~/.harness/runtime` when the computer has
@@ -1266,12 +1364,20 @@ fi''';
}
Future<bool> _hasTmux() async {
- final result = await _shell('command -v tmux >/dev/null && tmux -V');
+ final result = await _probeShell(
+ 'command -v tmux >/dev/null && tmux -V',
+ 'tmux',
+ step: EnvironmentStep.tmux,
+ );
return result.exitCode == 0;
}
Future<bool> _hasHomebrew() async {
- final result = await _shell('command -v brew >/dev/null && brew --version');
+ final result = await _probeShell(
+ 'command -v brew >/dev/null && brew --version',
+ 'Homebrew',
+ step: EnvironmentStep.tmux,
+ );
return result.exitCode == 0;
}
@@ -1350,28 +1456,176 @@ fi
return script;
}
+ List<String> _shellArguments(String command) => [
+ '-l',
+ '-c',
+ // The Homebrew prefixes are named rather than trusted to be on PATH:
+ // `-l` is a LOGIN shell but not an interactive one, so it reads
+ // `~/.zprofile` and never `~/.zshrc`
+ // — which is where `brew shellenv` sits on plenty of machines. A Finder
+ // launch then starts from launchd's bare `/usr/bin:/bin:/usr/sbin:/sbin`
+ // and this probe reports tmux missing on a computer that has it, then
+ // "installs" it through whichever `brew` it can see. Measured: an Apple
+ // Silicon Mac with both Homebrews picked up Intel `/usr/local/bin/brew`
+ // and built openssl@3 from source under Rosetta, holding the boot open
+ // on "Checking tmux…" for as long as that took. Apple Silicon first, so
+ // a machine with both never installs through the Intel one. The CLI
+ // closed the same gap in `lib/tmuxOnPath.ts`.
+ 'export PATH="\$HOME/.local/bin${_isMacOS ? ':/opt/homebrew/bin:/usr/local/bin' : ''}:\$PATH"; $command',
+ ];
+
+ Future<ProcessResult> _probeShell(
+ String command,
+ String label, {
+ EnvironmentStep? step,
+ }) => _runProbe(
+ _isMacOS ? '/bin/zsh' : '/bin/bash',
+ _shellArguments(command),
+ label: label,
+ step: step,
+ );
+
+ Future<ProcessResult> _probeHarnessCommand(
+ String executable,
+ List<String> arguments, {
+ Map<String, String>? environment,
+ }) => _runProbe(
+ executable,
+ arguments,
+ environment: environment,
+ label: 'the Harness CLI',
+ step: EnvironmentStep.harness,
+ );
+
+ /// A check owns its process and waits for at most one short deadline,
+ /// including process startup and output-pipe closure. Installers use the
+ /// separate streaming path: a slow version check must never look like a
+ /// missing tool or leave another check running every time Retry is pressed.
+ Future<ProcessResult> _runProbe(
+ String executable,
+ List<String> arguments, {
+ required String label,
+ EnvironmentStep? step,
+ Map<String, String>? environment,
+ }) async {
+ final timeout = _EnvironmentProbeTimeout(label, step);
+ final start = _start;
+ if (start == null) {
+ // Existing run-only test doubles do not own operating-system processes.
+ return _run(
+ executable,
+ arguments,
+ environment: environment,
+ ).timeout(probeTimeout, onTimeout: () => throw timeout);
+ }
+ final result = Completer<ProcessResult>();
+ Process? process;
+ StreamSubscription<List<int>>? output;
+ StreamSubscription<List<int>>? errors;
+ final stdout = BytesBuilder();
+ final stderr = BytesBuilder();
+ int? exitCode;
+ var exited = false;
+ var outputClosed = false;
+ var errorsClosed = false;
+
+ void fail(Object error, StackTrace stack) {
+ if (!result.isCompleted) result.completeError(error, stack);
+ }
+
+ void collect(BytesBuilder buffer, List<int> bytes) {
+ const maxOutputBytes = 64 * 1024;
+ final available = maxOutputBytes - buffer.length;
+ if (available > 0) {
+ buffer.add(
+ bytes.length > available ? bytes.sublist(0, available) : bytes,
+ );
+ }
+ }
+
+ void finish() {
+ if (result.isCompleted || !exited || !outputClosed || !errorsClosed) {
+ return;
+ }
+ result.complete(
+ ProcessResult(
+ process!.pid,
+ exitCode!,
+ utf8.decode(stdout.takeBytes(), allowMalformed: true),
+ utf8.decode(stderr.takeBytes(), allowMalformed: true),
+ ),
+ );
+ }
+
+ final timer = Timer(probeTimeout, () => fail(timeout, StackTrace.current));
+ unawaited(() async {
+ try {
+ final child = await start(
+ executable,
+ arguments,
+ environment: environment,
+ );
+ // A late launch must also be stopped; the timeout may have already
+ // returned control to the user and allowed a replacement check.
+ if (result.isCompleted) {
+ child.kill(ProcessSignal.sigkill);
+ await child.stdout.listen(null, onError: (Object _) {}).cancel();
+ await child.stderr.listen(null, onError: (Object _) {}).cancel();
+ await child.stdin.close();
+ return;
+ }
+ process = child;
+ // Probes never ask for input, including through shell startup files.
+ unawaited(
+ child.stdin.close().then<void>((_) {}, onError: (Object _) {}),
+ );
+ output = child.stdout.listen(
+ (bytes) => collect(stdout, bytes),
+ onError: fail,
+ onDone: () {
+ outputClosed = true;
+ finish();
+ },
+ );
+ errors = child.stderr.listen(
+ (bytes) => collect(stderr, bytes),
+ onError: fail,
+ onDone: () {
+ errorsClosed = true;
+ finish();
+ },
+ );
+ unawaited(
+ child.exitCode.then<void>((value) {
+ exited = true;
+ exitCode = value;
+ finish();
+ }, onError: fail),
+ );
+ } catch (error, stack) {
+ fail(error, stack);
+ }
+ }());
+ try {
+ return await result.future;
+ } finally {
+ timer.cancel();
+ if (!exited) process?.kill(ProcessSignal.sigkill);
+ await output?.cancel();
+ await errors?.cancel();
+ }
+ }
+
Future<ProcessResult> _shell(
String command, {
Map<String, String>? environment,
Duration? timeout,
}) {
- final run = _run(_isMacOS ? '/bin/zsh' : '/bin/bash', [
- '-l',
- '-c',
- // The Homebrew prefixes are named rather than trusted to be on PATH:
- // `-l` is a LOGIN shell but not an interactive one, so it reads
- // `~/.zprofile` and never `~/.zshrc`
- // — which is where `brew shellenv` sits on plenty of machines. A Finder
- // launch then starts from launchd's bare `/usr/bin:/bin:/usr/sbin:/sbin`
- // and this probe reports tmux missing on a computer that has it, then
- // "installs" it through whichever `brew` it can see. Measured: an Apple
- // Silicon Mac with both Homebrews picked up Intel `/usr/local/bin/brew`
- // and built openssl@3 from source under Rosetta, holding the boot open
- // on "Checking tmux…" for as long as that took. Apple Silicon first, so
- // a machine with both never installs through the Intel one. The CLI
- // closed the same gap in `lib/tmuxOnPath.ts`.
- 'export PATH="\$HOME/.local/bin${_isMacOS ? ':/opt/homebrew/bin:/usr/local/bin' : ''}:\$PATH"; $command',
- ], environment: environment);
+ final run = _run(
+ _isMacOS ? '/bin/zsh' : '/bin/bash',
+ _shellArguments(command),
+ environment: environment,
+ );
if (timeout == null) return run;
// The child keeps running — Process.run gives us no handle to kill. That is
// the intent: a slow install finishes in the background and the next launch
@@ -1388,8 +1642,6 @@ fi
Duration? timeout,
}) async {
final shell = _isMacOS ? '/bin/zsh' : '/bin/bash';
- final wrapped =
- 'export PATH="\$HOME/.local/bin${_isMacOS ? ':/opt/homebrew/bin:/usr/local/bin' : ''}:\$PATH"; $command';
if (_start == null) {
final result = await _shell(command, timeout: timeout);
for (final line in '${result.stdout}\n${result.stderr}'.split('\n')) {
@@ -1398,7 +1650,7 @@ fi
return result;
}
- final process = await _start(shell, ['-l', '-c', wrapped]);
+ final process = await _start(shell, _shellArguments(command));
final stdoutLines = <String>[];
final stderrLines = <String>[];
final stdoutSubscription = process.stdout
diff --git a/desktop/lib/core/harness_file_store.dart b/desktop/lib/core/harness_file_store.dart
index ced3f888d..37b018bf9 100644
--- a/desktop/lib/core/harness_file_store.dart
+++ b/desktop/lib/core/harness_file_store.dart
@@ -203,6 +203,13 @@ class HarnessFileStore implements BatchLocalKeyValueStore {
/// sandbox is already private to it — nor can spawn `/bin/chmod` at all.
Future<void> _chmod(String path, String mode) async {
if (Platform.isWindows || isMobileHost) return;
+ // Reads must still repair permissions changed outside this instance, but
+ // launching chmod for every already-private directory and lock dominates
+ // startup. Check the live mode each time; do not cache it across operations.
+ // Include special bits as well as rwx when deciding that no repair is needed.
+ final expected = int.parse(mode, radix: 8);
+ final actual = (await FileStat.stat(path)).mode;
+ if ((actual & 0xfff) == expected) return;
final result = await Process.run('/bin/chmod', [mode, path]);
if (result.exitCode != 0) {
throw FileSystemException('Could not set mode $mode', path);
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index db1c67d85..5d3e10359 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -202,6 +202,15 @@ class ForkedFrom {
}
}
+/// Display-only fallbacks; never send these to a CLI as a user rename.
+const kUntitledPane = 'Untitled Pane';
+final _automaticHarnessName = RegExp(
+ r'^(?:(?:harness|agent)-[1-9]\d*|.+ harness \d{1,2}-\d{1,2} \d{1,2}:\d{2}(?::\d{2})?)$',
+);
+
+bool isAutomaticHarnessName(String name) =>
+ _automaticHarnessName.hasMatch(name);
+
class Agent {
final String id;
final String? sessionId;
@@ -300,6 +309,11 @@ class Agent {
this.forkable,
});
+ /// Explicit names win. An automatic CLI label gives way to its session title.
+ String get displayName => _automaticHarnessName.hasMatch(name)
+ ? (title?.trim().isNotEmpty == true ? title!.trim() : kUntitledPane)
+ : name;
+
/// The engines whose sessions can be forked — natively (Claude Code's
/// `--fork-session`, `codex fork`) or by a handoff message (OpenCode takes a
/// first prompt). The daemon is the authority when it says (`forkable`);
diff --git a/desktop/lib/core/permission_modes.dart b/desktop/lib/core/permission_modes.dart
index 5d1c81315..c9bc3bcd2 100644
--- a/desktop/lib/core/permission_modes.dart
+++ b/desktop/lib/core/permission_modes.dart
@@ -53,17 +53,17 @@ const Map<String, List<PermissionMode>> kEnginePermissionModes = {
),
],
'codex': [
- PermissionMode(
- _auto,
- 'Auto-approve',
- 'Reviews each approval automatically, in the sandbox',
- ),
PermissionMode(
'readOnly',
'Read only',
'Reads and suggests, asks before any change',
),
PermissionMode(_ask, 'Ask first', 'Asks before acting, as Codex does'),
+ PermissionMode(
+ _auto,
+ 'Auto-approve',
+ 'Approves routine actions in the sandbox',
+ ),
PermissionMode(
'full',
'Full access',
diff --git a/desktop/lib/core/project_folder.dart b/desktop/lib/core/project_folder.dart
index db63f596b..864c9deed 100644
--- a/desktop/lib/core/project_folder.dart
+++ b/desktop/lib/core/project_folder.dart
@@ -7,15 +7,79 @@ import 'repository_clone.dart';
/// Folder preparation is explicit and runs only when New Agent is submitted.
/// Existing folders continue to use the ordinary agent_create cwd payload.
class ProjectFolderRequest {
- const ProjectFolderRequest.newProject() : repository = null;
+ const ProjectFolderRequest.newProject({this.name})
+ : repository = null,
+ generatedLabel = null,
+ generatedAt = null;
+ ProjectFolderRequest.generated({
+ required String label,
+ required DateTime at,
+ String? name,
+ }) : repository = null,
+ generatedLabel = label,
+ generatedAt = at,
+ name = name ?? _suggestedFolderName(label, at);
const ProjectFolderRequest.remote(GitHubRepository value)
- : repository = value;
+ : repository = value,
+ name = null,
+ generatedLabel = null,
+ generatedAt = null;
final GitHubRepository? repository;
+ /// What the person called the new project, or null to name it after the
+ /// harness and the time. The folder is [projectFolderSlug] of it.
+ final String? name;
+ final String? generatedLabel;
+ final DateTime? generatedAt;
+ bool get isGenerated => generatedAt != null;
+
+ /// The preview and Start share a frozen timestamp. Only an untouched
+ /// suggestion can advance to another name if its folder is taken.
+ String nextGeneratedName(String taken) {
+ final precise = _suggestedFolderName(
+ generatedLabel!,
+ generatedAt!,
+ withSeconds: true,
+ );
+ String numbered(int suffix) => _suggestedFolderName(
+ generatedLabel!,
+ generatedAt!,
+ withSeconds: true,
+ suffix: suffix,
+ );
+ if (taken == precise) return numbered(2);
+ final suffix = int.tryParse(taken.split('-').last);
+ if (suffix != null && suffix >= 2 && taken == numbered(suffix)) {
+ return numbered(suffix + 1);
+ }
+ return precise;
+ }
+
+ String availableGeneratedName(Iterable<String> names) {
+ final occupied = names.map((name) => name.toLowerCase()).toSet();
+ var candidate = folderName!;
+ while (occupied.contains(candidate.toLowerCase())) {
+ candidate = nextGeneratedName(candidate);
+ }
+ return candidate;
+ }
+
+ ProjectFolderRequest withGeneratedName(String name) =>
+ ProjectFolderRequest.generated(
+ label: generatedLabel!,
+ at: generatedAt!,
+ name: name,
+ );
+
+ /// The folder a named new project gets, or null when it is left to the clock.
+ String? get folderName => name == null ? null : projectFolderSlug(name!);
+
Map<String, String> get payload => {
'projectSource': repository == null ? 'new' : 'remote',
if (repository != null) 'repositoryUrl': repository!.url,
+ // A daemon that predates the field ignores it and names the folder itself.
+ if (repository == null && folderName != null) 'projectName': folderName!,
};
/// A new project is named after who it is for and when: [label] ("Codex", "Blender") and the
@@ -45,6 +109,27 @@ class ProjectFolderRequest {
root.path,
);
}
+ if (folderName case final named?) {
+ // A name somebody chose is never quietly changed: an existing folder
+ // is theirs to pick as an existing project, as a clone's is.
+ var candidate = named;
+ while (true) {
+ final folder = p.join(root.path, candidate);
+ final result = await Process.run('mkdir', [folder]);
+ if (result.exitCode == 0) return folder;
+ if (await FileSystemEntity.type(folder, followLinks: false) !=
+ FileSystemEntityType.notFound) {
+ if (isGenerated) {
+ candidate = nextGeneratedName(candidate);
+ continue;
+ }
+ throw RepositoryCloneException(
+ '“$named” already exists. Choose it as an existing project.',
+ );
+ }
+ throw FileSystemException('Could not create folder', folder);
+ }
+ }
final at = (now ?? DateTime.now)();
final base = projectFolderName(label, at);
final precise = projectFolderName(label, at, withSeconds: true);
@@ -79,6 +164,27 @@ class ProjectFolderRequest {
}
}
+/// Suggested names travel through the daemon's 64-character named-project
+/// field. Shorten only a long label, preserving the date and collision suffix.
+String _suggestedFolderName(
+ String label,
+ DateTime at, {
+ bool withSeconds = false,
+ int? suffix,
+}) {
+ final name = projectFolderName(label, at, withSeconds: withSeconds);
+ final stamp = projectFolderName(
+ '',
+ at,
+ withSeconds: withSeconds,
+ ).substring('harness'.length);
+ final ending = '$stamp${suffix == null ? '' : '-$suffix'}';
+ var prefix = name.substring(0, name.length - stamp.length);
+ final room = 64 - ending.length;
+ if (prefix.length > room) prefix = prefix.substring(0, room);
+ return '$prefix$ending';
+}
+
/// `codex-2026-09-03-09-05`: [label] in lowercase words, then the local date and time.
String projectFolderName(
String label,
@@ -94,3 +200,17 @@ String projectFolderName(
'${two(at.hour)}-${two(at.minute)}${withSeconds ? '-${two(at.second)}' : ''}';
return '${slug.isEmpty ? 'harness' : slug}-${at.year}-${two(at.month)}-${two(at.day)}-$time';
}
+
+/// The folder for a project somebody named: their words with spaces as dashes
+/// and nothing a path or a shell reads specially. Null when nothing usable is
+/// left, which callers treat as "not named". Mirrors `projectFolderSlug` in
+/// cli/src/lib/agentNames.ts.
+String? projectFolderSlug(String name) {
+ final slug = name
+ .trim()
+ .replaceAll(RegExp(r'\s+'), '-')
+ .replaceAll(RegExp(r'[^A-Za-z0-9._-]+'), '')
+ .replaceAll(RegExp(r'^[.-]+|[.-]+$'), '');
+ if (slug.isEmpty) return null;
+ return slug.length > 64 ? slug.substring(0, 64) : slug;
+}
diff --git a/desktop/lib/screens/login_screen.dart b/desktop/lib/screens/login_screen.dart
index f79a46fa7..df925f1ea 100644
--- a/desktop/lib/screens/login_screen.dart
+++ b/desktop/lib/screens/login_screen.dart
@@ -44,71 +44,87 @@ class LoginScreen extends StatelessWidget {
// The same flag `RootShell` routes on, so the button's state and the reason
// this screen is on screen at all can never disagree.
- final waiting = notifier.signingIn;
+ final waiting = notifier.signingIn || notifier.signingOut;
final compact = MediaQuery.sizeOf(context).height < 640;
final gap = compact ? 16.0 : 24.0;
+ // Preserve room for the primary action and its explanation at the minimum
+ // window size with enlarged text. The illustration is supplementary.
+ final showFleet =
+ !compact || MediaQuery.textScalerOf(context).scale(16) <= 20;
- return Scaffold(
- // The PANEL tone, not the window's. In light both `windowBg` and the
- // card's `surfaceFill` are pure white, so a card on the window is a card
- // you cannot see — only its shadow separates it, and at this size that
- // reads as a printing artefact rather than as a raised block. The rail's
- // own barely-there grey gives the card something to sit on in both
- // themes, which is the same trick the app plays everywhere else.
- backgroundColor: grid.AppPalette.panelBg,
- body: Stack(
- children: [
- const Positioned.fill(child: LoginAurora()),
- Center(
- child: SingleChildScrollView(
- padding: EdgeInsets.all(compact ? 16 : 24),
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: _cardWidth),
- child: Container(
- // The app's raised-block recipe: fill plus a soft lift, no rim.
- decoration: BoxDecoration(
- color: grid.AppGlass.surfaceFill,
- borderRadius: BorderRadius.circular(14),
- boxShadow: grid.AppCard.shadow,
- ),
- padding: EdgeInsets.all(compact ? 20 : 24),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- const _AppMark(),
- SizedBox(height: gap),
- Text(
- 'Your agents, wherever they run',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.titleLarge,
- ),
- const SizedBox(height: 8),
- Text(
- 'At home, at the office, in the cloud — every machine you '
- 'sign in to becomes part of one desk, here.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
- ),
- SizedBox(height: gap),
- const LoginFleetMap(),
- SizedBox(height: gap),
- _Action(notifier: notifier, waiting: waiting),
- if (notifier.lastError != null) ...[
- const SizedBox(height: 16),
- _ErrorTile(
- message: notifier.lastError!,
- onRetry: notifier.login,
+ return CallbackShortcuts(
+ bindings: {
+ if (notifier.canCancelLogin)
+ const SingleActivator(
+ LogicalKeyboardKey.escape,
+ includeRepeats: false,
+ ): notifier.cancelLogin,
+ },
+ child: Scaffold(
+ // The PANEL tone, not the window's. In light both `windowBg` and the
+ // card's `surfaceFill` are pure white, so a card on the window is a card
+ // you cannot see — only its shadow separates it, and at this size that
+ // reads as a printing artefact rather than as a raised block. The rail's
+ // own barely-there grey gives the card something to sit on in both
+ // themes, which is the same trick the app plays everywhere else.
+ backgroundColor: grid.AppPalette.panelBg,
+ body: Stack(
+ children: [
+ const Positioned.fill(child: LoginAurora()),
+ Center(
+ child: SingleChildScrollView(
+ padding: EdgeInsets.all(compact ? 16 : 24),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: _cardWidth),
+ child: Container(
+ // The app's raised-block recipe: fill plus a soft lift, no rim.
+ decoration: BoxDecoration(
+ color: grid.AppGlass.surfaceFill,
+ borderRadius: BorderRadius.circular(14),
+ boxShadow: grid.AppCard.shadow,
+ ),
+ padding: EdgeInsets.all(compact ? 20 : 24),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const _AppMark(),
+ SizedBox(height: gap),
+ Text(
+ 'Your agents, wherever they run',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.titleLarge,
),
+ const SizedBox(height: 8),
+ Text(
+ 'At home, at the office, in the cloud — every machine you '
+ 'sign in to becomes part of one desk, here.',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
+ SizedBox(height: gap),
+ if (showFleet) ...[
+ const LoginFleetMap(),
+ SizedBox(height: gap),
+ ],
+ _Action(notifier: notifier, waiting: waiting),
+ if (notifier.lastError != null &&
+ !notifier.sessionExpired) ...[
+ const SizedBox(height: 16),
+ _ErrorTile(
+ message: notifier.lastError!,
+ onRetry: notifier.login,
+ ),
+ ],
+ SizedBox(height: gap),
+ const _Seal(),
],
- SizedBox(height: gap),
- const _Seal(),
- ],
+ ),
),
),
),
),
- ),
- ],
+ ],
+ ),
),
);
}
@@ -181,20 +197,29 @@ class _ActionState extends State<_Action> {
grid.AppTheme.watch(context);
if (!widget.waiting) {
+ final signingOutFailed = notifier.signOutError != null;
return Column(
children: [
FilledButton.icon(
focusNode: _signInFocus,
autofocus: true,
- onPressed: notifier.login,
- icon: const Icon(Icons.login, size: grid.AppControl.iconSize),
- label: const Text('Sign in'),
+ onPressed: signingOutFailed ? notifier.logout : notifier.login,
+ icon: Icon(
+ signingOutFailed ? Icons.logout : Icons.login,
+ size: grid.AppControl.iconSize,
+ ),
+ label: Text(signingOutFailed ? 'Retry sign out' : 'Sign in'),
),
const SizedBox(height: 12),
- Text(
- 'Sign in through your browser to continue.',
- textAlign: TextAlign.center,
- style: Theme.of(context).textTheme.bodySmall,
+ Semantics(
+ liveRegion: signingOutFailed || notifier.sessionExpired,
+ child: Text(
+ notifier.signOutError ??
+ (notifier.sessionExpired ? notifier.lastError : null) ??
+ 'Sign in through your browser to continue.',
+ textAlign: TextAlign.center,
+ style: Theme.of(context).textTheme.bodySmall,
+ ),
),
],
);
@@ -217,16 +242,22 @@ class _ActionState extends State<_Action> {
height: grid.AppControl.iconSize,
child: CircularProgressIndicator(strokeWidth: 2),
),
- label: Text(url == null ? 'Signing in…' : 'Waiting for your browser'),
+ label: Text(
+ notifier.signingOut
+ ? 'Signing out…'
+ : (url == null ? 'Signing in…' : 'Waiting for your browser'),
+ ),
),
const SizedBox(height: 12),
Semantics(
liveRegion: true,
child: Text(
- message ??
- (url == null
- ? 'Your workspace will open when sign-in is complete.'
- : 'Finish signing in in your browser, then return here.'),
+ notifier.signingOut
+ ? 'Clearing your saved sign-in.'
+ : message ??
+ (url == null
+ ? 'Your workspace will open when sign-in is complete.'
+ : 'Finish signing in in your browser, then return here.'),
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 004a70f6c..f360555b0 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -2,17 +2,20 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io' show Platform;
+import 'package:file_selector/file_selector.dart';
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../analytics/analytics.dart';
import '../core/desktop_window.dart';
import '../core/harness_file_store.dart';
+import '../core/project_folder.dart';
import '../core/test_run.dart';
+import '../logging/debug_surface.dart';
import '../settings/settings_screen.dart';
import '../settings/settings_section.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
import '../shortcuts/app_shortcuts.dart';
import '../core/models.dart';
import '../shortcuts/app_keymap.dart';
@@ -22,8 +25,11 @@ import '../shortcuts/keymap_host.dart';
import '../shortcuts/keymap_native.dart';
import '../shortcuts/keymap_settings.dart';
import '../state/app_state.dart';
+import '../state/harness_placement.dart';
+import '../state/new_harness.dart';
import '../state/pane_arrangement.dart';
import '../terminal/terminal_viewport.dart';
+import '../terminal/terminal_font_store.dart';
import '../usage/models_menu_controller.dart';
import '../state/swarm_catalog.dart';
import '../state/swarm_attention.dart';
@@ -39,10 +45,20 @@ import '../store/store_screen.dart';
import '../widgets/harness_start_page.dart';
import '../widgets/link_machine_screen.dart';
import '../widgets/machine_actions.dart';
+import '../widgets/rename_agent_dialog.dart';
+import '../widgets/delete_agent_dialog.dart';
+import '../widgets/fork_agent_dialog.dart';
+import '../widgets/restart_agent_action.dart';
import '../widgets/machines_manager.dart';
import '../widgets/new_agent_dialog.dart';
+import '../widgets/box_chrome.dart';
+import '../widgets/new_harness_box.dart';
+import '../widgets/open_harness_intent.dart';
import '../widgets/pane_grid.dart';
+import '../widgets/remote_folder_picker.dart';
import '../widgets/shortcuts_sheet.dart';
+import '../widgets/harness_customize_pane.dart';
+import '../shared/widgets/app_dialog.dart';
import '../widgets/swarm_dialogs.dart';
import '../widgets/swarm_search_input.dart';
import '../widgets/swarm_attention.dart';
@@ -56,6 +72,11 @@ import '../state/command_bar_catalog.dart';
import '../widgets/harness_command_bar.dart';
import '../orchestrator/orchestrator_launcher.dart';
import '../orchestrator/orchestrator_workspace.dart';
+import '../state/workspace_learning.dart';
+import '../state/first_harness_launch.dart';
+import '../widgets/workspace_quick_start.dart';
+import '../widgets/workspace_start_guide.dart';
+import '../shortcuts/keyboard_practice.dart';
class SwarmScreen extends StatefulWidget {
const SwarmScreen({
@@ -69,6 +90,8 @@ class SwarmScreen extends StatefulWidget {
defaultValue: true,
),
this.commandResolver,
+ this.learning,
+ this.firstLaunch,
});
final AppNotifier notifier;
final bool? nativeTabs;
@@ -76,10 +99,27 @@ class SwarmScreen extends StatefulWidget {
final ModelsMenuController? modelsMenu;
final bool commandBarEnabled;
final CommandResolver? commandResolver;
+ final WorkspaceLearning? learning;
+ final FirstHarnessLaunch? firstLaunch;
@override
State<SwarmScreen> createState() => _SwarmScreenState();
}
+enum _NewHarnessSource { workspace, product }
+
+/// Drafts belong to the entry's source, before the person edits its defaults.
+/// Product requests also name an agent explicitly: two Store pages must never
+/// resume one another's drafts. Placement remains separate, so Cmd-T and Cmd-P
+/// can resume the same workspace draft in the newly requested destination.
+typedef _NewHarnessContext = ({
+ _NewHarnessSource source,
+ String machineId,
+ String? requestedEngine,
+ String? sourceAgentId,
+ String? folder,
+ String? projectName,
+});
+
class _SwarmScreenState extends State<SwarmScreen> {
static const _channel = MethodChannel('harness/swarm_tabs');
late final bool _native =
@@ -101,11 +141,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
commands: _searchCommands(),
runCommand: _runShortcut,
recent: _navigation.recent,
- create: (machineId, engine, prompt) => _newAgent(
- machineId: machineId,
- initialEngine: engine,
- initialPrompt: prompt,
- ),
+ create: (machineId, engine, prompt) =>
+ _newAgent(machineId: machineId, engine: engine, task: prompt),
),
resolve:
widget.commandResolver ??
@@ -117,13 +154,29 @@ class _SwarmScreenState extends State<SwarmScreen> {
canRequestFocus: false,
skipTraversal: true,
);
- final _navigation = SwarmNavigationHistory();
+ late final _navigation = SwarmNavigationHistory(
+ storage: kUnderTest ? null : HarnessFileStore.shared,
+ );
final _searchCatalog = SwarmSearchCatalog();
final _searchText = TextEditingController();
final _searchFocus = FocusNode(debugLabel: 'Find a harness');
+ final _tabScroll = ScrollController();
+ ({String activeId, List<String> order, double viewport})? _tabGeometry;
+ bool _tabRevealScheduled = false;
SwarmSearchController? _search;
OverlayEntry? _searchOverlay;
- (String, bool)? _searchHeaderState;
+
+ /// New Harness, open in the box. Never open beside the search: they are two
+ /// modes of one surface, and opening either closes the other.
+ NewHarnessController? _newHarness;
+ OverlayEntry? _newHarnessOverlay;
+
+ /// Escape keeps unfinished work with the machine/project/agent it started
+ /// from. Switching context must not carry a task into the wrong project or
+ /// silently reset its edited permissions. These buffers live for this window.
+ final _newHarnessDrafts = <_NewHarnessContext, NewHarnessDraft>{};
+ _NewHarnessContext? _newHarnessContext;
+ (String, bool, String, HarnessPlacement?)? _searchHeaderState;
FocusNode? _searchReturnFocus;
(String, bool)? _lastWorkspace;
bool _spokenPaletteOpen = false;
@@ -140,7 +193,129 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? _nativeKeyContext;
String _pendingKeys = '';
AppNotifier get app => widget.notifier;
+ late final _learning =
+ widget.learning ??
+ WorkspaceLearning(storage: kUnderTest ? null : HarnessFileStore.shared);
String? _commandCatalogMachine;
+ late final _firstLaunch =
+ widget.firstLaunch ??
+ FirstHarnessLaunch(storage: kUnderTest ? null : HarnessFileStore.shared);
+ bool _firstLaunchScheduled = false;
+
+ String? _emptyEntryTab;
+
+ bool get _isWelcomeEntry =>
+ app.activeSwarm.isEmptyStarter ||
+ (app.activeSwarm.kind == 'harness' &&
+ app.activeSwarm.name == 'Welcome' &&
+ app.activeSwarm.panes.isEmpty &&
+ app.activeSwarm.presets.isEmpty);
+
+ bool get _showsStartGuide =>
+ newHarnessOpensInBox &&
+ app.panes.isEmpty &&
+ !app.activeSwarm.isStore &&
+ !app.activeSwarm.isOrchestrator;
+
+ void _observeFirstLaunch() {
+ if (!mounted || !newHarnessOpensInBox || !_firstLaunch.loaded) return;
+ if (app.viewer != null || !_isWelcomeEntry) {
+ _emptyEntryTab = null;
+ _firstLaunch.handle();
+ return;
+ }
+ if (_emptyEntryTab == app.activeSwarmId ||
+ _firstLaunchScheduled ||
+ app.status != AppStatus.authenticated ||
+ app.machinesLoading) {
+ return;
+ }
+ final hasHarnesses = app.machineStates.values.any(
+ (machine) => machine.agents.isNotEmpty,
+ );
+ final local = app.machineStates.values
+ .where((machine) => machine.isLocalMachine)
+ .firstOrNull;
+ if (!hasHarnesses &&
+ (local == null ||
+ local.nodeOnline != true ||
+ local.needsLink ||
+ local.agentLoadStatus != AgentLoadStatus.loaded)) {
+ return;
+ }
+ final tab = app.activeSwarmId;
+ _firstLaunchScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _firstLaunchScheduled = false;
+ if (!mounted || app.activeSwarmId != tab || !_isWelcomeEntry) {
+ return;
+ }
+ // One offer per visit: dismissing or opening another surface keeps it closed.
+ _emptyEntryTab = tab;
+ if (!_routeIsCurrent ||
+ _dialogOpen ||
+ _spokenPaletteOpen ||
+ _search != null ||
+ _newHarness != null ||
+ _commandBarOpen) {
+ return;
+ }
+ _firstLaunch.handle();
+ if (app.machineStates.values.any(
+ (machine) => machine.agents.isNotEmpty,
+ )) {
+ _openSearch(
+ adding: true,
+ placement: HarnessPlacement.newTab,
+ welcome: true,
+ );
+ } else {
+ unawaited(
+ _newAgent(
+ machineId: local!.machine.machineId,
+ placement: HarnessPlacement.newTab,
+ firstRun: true,
+ ),
+ );
+ }
+ });
+ }
+
+ Widget _startGuide() =>
+ WorkspaceStartGuide(onShortcuts: _showKeyboardShortcuts);
+
+ void _reviewOnboarding() {
+ if (_newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ // Reuse the welcome workspace and offer its dock again, preserving work
+ // in every other tab. The first-entry path chooses create or search.
+ final welcome = app.swarms
+ .where(
+ (tab) =>
+ tab.kind == 'harness' &&
+ tab.name == 'Welcome' &&
+ tab.panes.isEmpty &&
+ tab.presets.isEmpty,
+ )
+ .firstOrNull;
+ if (welcome == null) {
+ app.newSwarm(name: 'Welcome');
+ } else {
+ app.selectSwarm(welcome.id);
+ }
+ _preparePaneFocus();
+ _emptyEntryTab = null;
+ _observeFirstLaunch();
+ }
+
+ void _showKeyboardShortcuts() {
+ if (_newHarness?.requestDismiss() == false) return;
+ _closeNewHarness(restoreFocus: false);
+ unawaited(_dialog(() => showShortcutsSheet(context)));
+ }
@override
void initState() {
@@ -150,10 +325,20 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.railFocused = false;
_recordNavigation();
app.addListener(_recordNavigation);
+ app.addListener(_observeLearning);
+ app.addListener(_observeFirstLaunch);
+ unawaited(_firstLaunch.load().then((_) => _observeFirstLaunch()));
+ unawaited(
+ _learning.load().then((_) {
+ if (mounted) _observeLearning();
+ }),
+ );
FocusManager.instance.addListener(_restoreEmptyFocus);
FocusManager.instance.addListener(_syncKeyContext);
grid.AppTheme.palette.addListener(_paletteChanged);
+ terminalFontStore.addListener(_fontChanged);
unawaited(_projects.load());
+ unawaited(_navigation.load());
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
if (_native) {
_modelsMenu =
@@ -199,14 +384,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
_keymap.removeListener(_keymapChanged);
_defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
+ terminalFontStore.removeListener(_fontChanged);
app.removeListener(_recordNavigation);
+ app.removeListener(_observeLearning);
+ app.removeListener(_observeFirstLaunch);
+ if (widget.learning == null) _learning.dispose();
FocusManager.instance.removeListener(_restoreEmptyFocus);
FocusManager.instance.removeListener(_syncKeyContext);
_searchOverlay?.remove();
_searchOverlay?.dispose();
_search?.dispose();
+ _newHarnessOverlay?.remove();
+ _newHarnessOverlay?.dispose();
+ _newHarness?.dispose();
+ _navigation.dispose();
_searchFocus.dispose();
_searchText.dispose();
+ _tabScroll.dispose();
_canvasFocus.dispose();
_shellFocus.dispose();
_startSearchFocus.dispose();
@@ -279,12 +473,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (id == 'agent.new' && _search != null) {
final target = _search!.targetId;
final split = _search!.split;
+ final placement = _search!.placement;
+ final task = _search!.createTask;
_closeSearch(restoreFocus: false);
- unawaited(_newAgent(swarmId: target, split: split));
+ unawaited(
+ _newAgent(
+ swarmId: target,
+ split: split,
+ placement: placement,
+ task: task,
+ ),
+ );
return;
}
if (!_canExecuteCommand(id)) return;
- if (id != 'navigation.commands') {
+ if (id != 'navigation.commands' && id != 'swarm.new' && id != 'agent.add') {
_closeSearch();
}
_commands[id]?.call();
@@ -322,6 +525,24 @@ class _SwarmScreenState extends State<SwarmScreen> {
_lastWorkspace = workspace;
}
+ void _observeLearning() => _learning.observe(
+ agents: app.panes
+ .where((pane) => !pane.isWeb && pane.agentId != null)
+ .length,
+ zoomed: app.zoomedPaneId != null,
+ );
+
+ void _startQuickStart() {
+ _learning.start();
+ _observeLearning();
+ if (app.focusedPane?.session?.focusInput() != true) {
+ _startSearchFocus.requestFocus();
+ }
+ }
+
+ Future<void> _practiceKeyboard() =>
+ _dialog(() => showKeyboardPractice(context, keymap: _keymap));
+
int get _attention =>
app.machineStates.values.fold(0, (n, m) => n + m.blockedAgents.length);
@@ -347,6 +568,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
// output. Never-attached setup guides have no buffer to search.
bool get _canFindTerminal => app.focusedPane?.session != null;
+ void _fontChanged() {
+ setState(() {});
+ _paletteChanged();
+ }
+
void _paletteChanged() {
_searchOverlay?.markNeedsBuild();
if (_native) _syncNative();
@@ -386,6 +612,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,
'activeId': app.activeSwarmId,
'palette': grid.AppTheme.palette.value.nativeColors,
+ 'fontFamily': terminalFontStore.value.fontFamily,
+ 'fontFallbacks': terminalFontStore.value.fontFamilyFallback,
'canReopen': app.canReopenLastClosed,
'canFind': _canFindTerminal,
'canClosePane': app.focusedPane != null,
@@ -480,7 +708,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (final agent in machine.agents.take(512))
(
agent.id,
- agent.name,
+ agent.displayName,
agent.engine,
agent.terminalAvailable ||
openAgents.contains((machine.machine.machineId, agent.id)),
@@ -508,7 +736,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (final agent in machine.agents.take(512))
{
'id': agent.id,
- 'title': agent.name,
+ 'title': agent.displayName,
// Drawn as what it is: a Godogen agent wears Godogen, not
// the Claude Code it runs on.
'engine': agent.identityEngine,
@@ -708,9 +936,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
args['command'];
switch (command) {
case 'next':
- search.move(1);
+ search.moveVisually(1);
case 'previous':
- search.move(-1);
+ search.moveVisually(-1);
case 'submit':
final choice = search.submit();
if (choice != null) await _chooseSearch(choice);
@@ -732,6 +960,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
// event any Flutter overlay can see itself.
dismissTransientMenus();
switch (call.method) {
+ case 'store':
+ _openStore();
case 'new':
_newTab();
case 'reopen':
@@ -755,7 +985,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
// keyboard focus to Flutter while the user edits the name.
if (args['id'] is String) unawaited(_rename(args['id']));
case 'renameActive':
- await _rename(app.activeSwarmId);
+ unawaited(_rename(app.activeSwarmId));
case 'next':
app.stepSwarm(1);
case 'previous':
@@ -771,19 +1001,20 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'newTerminal':
unawaited(_newTerminal());
case 'runLocalModel':
- // The native Models menu's one command: open Grid. Wrapped like Link
- // Machine… because the notifier opens New Agent here, and the tab it
- // then creates takes focus. With more than one machine linked the menu
- // lists them and names the chosen one here; with one, or none, the
- // notifier picks.
- await _dialog(
- () => app.runLocalModel(
- context,
- machineId: args['machineId'] is String
- ? args['machineId'] as String
- : null,
- ),
+ // Native commands arrive above the Actions subtree. Use the same
+ // product entry directly; a dialog guard would block the dock.
+ Future<void> open() => app.runLocalModel(
+ context,
+ machineId: args['machineId'] is String
+ ? args['machineId'] as String
+ : null,
+ onOpenHarness: newHarnessOpensInBox ? _openProduct : null,
);
+ if (newHarnessOpensInBox) {
+ await open();
+ } else {
+ await _dialog(open);
+ }
case 'splitRight':
unawaited(_splitAgent(PaneResizeAxis.x));
case 'splitDown':
@@ -795,18 +1026,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'addProject':
await _addProject();
case 'linkMachine':
- await _dialog(() => showSwarmLinkDialog(context, app));
+ await _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap));
case 'manageMachines':
- // Machine Monitor: the fleet managed by talking to it, with the live
- // map beside the terminal. Wrapped like Open Grid because the
- // notifier opens New Harness here and the tab it makes takes focus.
- await _dialog(() => app.manageMachines(context));
+ await _manageMachines();
// BRIDGE, until the Machines menu goes: the old list, so nothing is lost
// between this release and that one. When the menu is removed, delete
// this case, `machines.list` below, machines_manager.dart and its test,
// and the `machineList` action in SwarmTitlebar.swift + keymap_commands.
case 'machineList':
- unawaited(_dialog(() => showMachinesManager(context, app)));
+ unawaited(
+ _dialog(() => showMachinesManager(context, app, keymap: _keymap)),
+ );
case 'refreshMachines':
unawaited(app.retryMachines());
case 'machineDestination':
@@ -824,6 +1054,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app,
machineId: machine.machine.machineId,
displayName: machine.machine.displayName,
+ keymap: _keymap,
),
),
);
@@ -886,11 +1117,13 @@ class _SwarmScreenState extends State<SwarmScreen> {
'close',
'new',
'rename',
+ 'renameActive',
'commands',
'notifications',
'addAgent',
'newAgent',
'newTerminal',
+ 'runLocalModel',
'manageMachines',
'machineList',
'deleteMachine',
@@ -940,27 +1173,179 @@ class _SwarmScreenState extends State<SwarmScreen> {
Future<void> _rename(String id) => _dialog(() async {
final swarm = app.swarms.where((s) => s.id == id).firstOrNull;
if (swarm == null) return;
- final name = await showSwarmRenameDialog(context, swarm.name);
+ final name = await showSwarmRenameDialog(
+ context,
+ swarm.name,
+ keymap: _keymap,
+ );
if (name != null) app.renameSwarm(id, name);
});
- Future<void> _settings() =>
- _dialog(() => showSettingsScreen(context, app, source: 'swarm'));
+
+ Agent? get _focusedAgent {
+ final pane = app.focusedPane;
+ return pane == null
+ ? null
+ : app
+ .stateOf(pane.machineId)
+ ?.agents
+ .where((agent) => agent.id == pane.agentId)
+ .firstOrNull;
+ }
+
+ Future<void> _editAgent({bool stop = false}) => _dialog(() async {
+ final pane = app.focusedPane;
+ if (pane == null) return;
+ final machine = app.stateOf(pane.machineId);
+ final agent = machine?.agents
+ .where((agent) => agent.id == pane.agentId)
+ .firstOrNull;
+ if (agent == null || machine!.machine.isShared) return;
+ if (stop) {
+ await confirmDeleteAgent(
+ context,
+ app,
+ pane.machineId,
+ agent.id,
+ agent.displayName,
+ engine: agent.engine,
+ keymap: _keymap,
+ );
+ return;
+ }
+ await showAgentRenameDialog(
+ context,
+ app,
+ pane.machineId,
+ agent.id,
+ agent.displayName,
+ keymap: _keymap,
+ );
+ });
+ Future<void> _restartAgent() => _dialog(() async {
+ final pane = app.focusedPane;
+ if (pane == null ||
+ _focusedAgent == null ||
+ app.stateOf(pane.machineId)?.machine.isShared != false) {
+ return;
+ }
+ await restartHarness(
+ context,
+ app,
+ pane.machineId,
+ pane.agentId!,
+ keymap: _keymap,
+ );
+ });
+ Future<void> _forkAgent() => _dialog(() async {
+ final pane = app.focusedPane;
+ final agent = _focusedAgent;
+ if (pane == null ||
+ agent == null ||
+ !agent.canFork ||
+ app.stateOf(pane.machineId)?.machine.isShared != false) {
+ return;
+ }
+ await forkHarness(
+ context,
+ app,
+ pane.machineId,
+ agent.id,
+ agent.displayName,
+ engine: agent.engine,
+ keymap: _keymap,
+ );
+ });
+ Future<void> _customize() => _dialog(() async {
+ await showAppDialog<void>(
+ context: context,
+ veilTint: Colors.transparent,
+ veilBlur: 0,
+ transitionDuration: Duration.zero,
+ builder: (context) => Align(
+ alignment: Alignment.centerRight,
+ child: SizedBox(
+ width: (440 * MediaQuery.textScalerOf(context).scale(13) / 13).clamp(
+ 0,
+ MediaQuery.sizeOf(context).width,
+ ),
+ height: double.infinity,
+ child: HarnessCustomizePane(onClose: () => Navigator.pop(context)),
+ ),
+ ),
+ );
+ });
+
+ Future<void> _settings([SettingsSection? section]) => _dialog(
+ () => showSettingsScreen(
+ context,
+ app,
+ initialSection: section,
+ source: 'swarm',
+ ),
+ );
+
+ /// Settings, by section, as rows of the box: `> usage` goes straight to
+ /// Settings ▸ Usage. A palette that finds a setting by name is how an editor
+ /// makes a settings screen nobody has to navigate.
+ static const _settingsCommand = 'settings:';
+
+ Future<void> _manageMachines() async {
+ Future<void> open() => app.manageMachines(
+ context,
+ onOpenHarness: newHarnessOpensInBox ? _openProduct : null,
+ );
+ if (newHarnessOpensInBox) {
+ await open();
+ } else {
+ await _dialog(open);
+ }
+ }
+
+ Future<void> _openProduct(String engine, String machineId, {String? task}) =>
+ _newAgent(
+ source: _NewHarnessSource.product,
+ engine: engine,
+ machineId: machineId,
+ task: task,
+ placement: HarnessPlacement.newTab,
+ );
Future<void> _newAgent({
String? machineId,
String? folder,
String? swarmId,
PaneSplitRequest? split,
- String? initialEngine,
- String? initialPrompt,
+ String? engine,
+ String? projectName,
+ String? task,
+ HarnessPlacement? placement,
+ bool firstRun = false,
+ _NewHarnessSource source = _NewHarnessSource.workspace,
}) async {
+ _firstLaunch.handle();
+ final search = source == _NewHarnessSource.workspace ? _search : null;
// A pane never lands in the store tab: New Harness from there goes to
// the empty starter tab (or a fresh one), the way New Tab does.
- if (swarmId == null && app.activeSwarm.isStore) app.newSwarm();
- final target = swarmId ?? _search?.targetId ?? app.activeSwarmId;
- final requestedSplit = split ?? _search?.split;
+ placement ??= search?.placement;
+ if (swarmId == null &&
+ (app.activeSwarm.isStore || app.activeSwarm.isOrchestrator)) {
+ placement = HarnessPlacement.newTab;
+ }
+ final target = swarmId ?? search?.targetId ?? app.activeSwarmId;
+ final requestedSplit = split ?? search?.split;
+ // ⌘N from inside the search keeps what was typed: it is what the create
+ // row would have started the harness on.
+ if (newHarnessOpensInBox) task ??= search?.createTask;
if (app.activeSwarmId != target) return;
- final focused = requestedSplit == null ? null : app.focusedPane;
+ // In the box, the new harness starts as another of the one you were in —
+ // its agent, its machine, its project — the way a tmux split inherits its
+ // pane and a new terminal tab opens where the last one was. The form keeps
+ // what it always did: it inherits only for a split.
+ final focused =
+ source == _NewHarnessSource.workspace &&
+ (newHarnessOpensInBox || requestedSplit != null)
+ ? app.focusedPane
+ : null;
final machine = focused == null ? null : app.stateOf(focused.machineId);
final agent = machine?.agents
.where((agent) => agent.id == focused?.agentId)
@@ -975,27 +1360,423 @@ class _SwarmScreenState extends State<SwarmScreen> {
.machineId ??
app.machineStates.keys.firstOrNull;
final initialFolder =
- folder ?? (agent == null ? null : machine?.projectOf(agent)?.cwd);
+ folder ??
+ (projectName != null || agent == null || id != focused?.machineId
+ ? null
+ : machine?.projectOf(agent)?.cwd);
+ if (id == null) {
+ await _dialog(
+ () => showSwarmLinkDialog(context, app, keymap: _keymap),
+ restoreEntry: false,
+ );
+ await _ensureEmptyEntry();
+ return;
+ }
+ if (!newHarnessOpensInBox) {
+ await _newAgentForm(
+ machineId: id,
+ folder: initialFolder,
+ swarmId: target,
+ split: requestedSplit,
+ engine: engine,
+ placement: placement,
+ task: task,
+ );
+ return;
+ }
+ final inherited = agent?.identityEngine;
+ _openNewHarness(
+ machineId: id,
+ // ⌘⇧T is how a shell is made; New Harness from a shell means an agent.
+ engine: engine ?? (isTerminalEngine(inherited) ? null : inherited),
+ folder: initialFolder,
+ projectName: projectName,
+ autoProject:
+ projectName == null &&
+ initialFolder == null &&
+ (source == _NewHarnessSource.product || app.panes.isEmpty),
+ task: task,
+ draftContext: (
+ source: source,
+ machineId: id,
+ requestedEngine: engine,
+ sourceAgentId: focused?.agentId,
+ folder: initialFolder,
+ projectName: projectName,
+ ),
+ swarmId: target,
+ split: requestedSplit,
+ placement: placement,
+ firstRun: firstRun,
+ );
+ }
+
+ /// The full form, on the answers the box already holds: what the box does
+ /// not do yet (an engine to install, a Git clone, a permission mode, a Codex
+ /// profile) stays one key away instead of being lost.
+ Future<void> _newAgentForm({
+ required String machineId,
+ String? engine,
+ String? folder,
+ ProjectFolderRequest? projectFolder,
+ String? permissionMode,
+ required String swarmId,
+ PaneSplitRequest? split,
+ HarnessPlacement? placement,
+ String? task,
+ NewHarnessDraft? initialDraft,
+ _NewHarnessContext? draftContext,
+ bool returnToPrompt = false,
+ }) async {
+ NewHarnessDraft? returning;
await _dialog(() async {
- if (id == null) {
- await showSwarmLinkDialog(context, app);
- return;
- }
- await showNewAgentDialog(
+ final result = await showNewAgentDialog(
context,
app,
- id,
+ machineId,
source: 'swarm',
- initialFolder: initialFolder,
- swarmId: target,
- split: requestedSplit,
- initialEngine: initialEngine,
- initialPrompt: initialPrompt,
+ initialFolder: folder,
+ initialProjectFolder: projectFolder,
+ initialPermissionMode: permissionMode,
+ initiallyAdvanced: returnToPrompt || permissionMode != null,
+ initialDraft: initialDraft,
+ onBack: returnToPrompt ? (draft) => returning = draft : null,
+ keymap: _keymap,
+ initialEngine: engine,
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ initialPrompt: task,
);
+ if (result == NewAgentDialogResult.created) {
+ _newHarnessDrafts.remove(draftContext);
+ }
}, restoreEntry: false);
+ if (mounted && returning != null && app.activeSwarmId == swarmId) {
+ _openNewHarness(
+ machineId: returning!.machineId,
+ draft: returning,
+ draftContext: draftContext,
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ );
+ return;
+ }
+ if (returning != null && draftContext != null) {
+ _rememberNewHarnessDraft(draftContext, returning!);
+ }
await _ensureEmptyEntry();
}
+ void _openNewHarness({
+ required String machineId,
+ String? engine,
+ String? folder,
+ String? projectName,
+ bool autoProject = false,
+ String? task,
+ NewHarnessDraft? draft,
+ _NewHarnessContext? draftContext,
+ required String swarmId,
+ PaneSplitRequest? split,
+ HarnessPlacement? placement,
+ bool firstRun = false,
+ }) {
+ // A dialog's pop future can complete before didChangeDependencies refreshes
+ // the cached route flag. Its live route already owns the next prompt.
+ if (!mounted ||
+ _dialogOpen ||
+ _spokenPaletteOpen ||
+ ModalRoute.of(context)?.isCurrent == false) {
+ return;
+ }
+ final origin =
+ draftContext ??
+ (
+ source: _NewHarnessSource.workspace,
+ machineId: machineId,
+ requestedEngine: engine,
+ sourceAgentId: app.focusedPane?.agentId,
+ folder: folder,
+ projectName: projectName,
+ );
+ bool matchesSelection(NewHarnessDraft candidate) =>
+ origin.requestedEngine == null ||
+ (candidate.engine == origin.requestedEngine &&
+ candidate.machineId == origin.machineId);
+ final current = _newHarness;
+ if (current != null) {
+ // A pending receipt cannot be retargeted, even by another Store page.
+ if (current.busy || current.checking || current.linkingProfile) {
+ current.warn(
+ current.busy || current.linkingProfile
+ ? 'Finish the current action before opening another harness.'
+ : 'Check the pending start before opening another harness.',
+ );
+ return;
+ }
+ if (_newHarnessContext == origin &&
+ matchesSelection(current.draft) &&
+ (task == null || task == current.task) &&
+ current.swarmId == swarmId &&
+ current.split == split &&
+ current.placement == placement) {
+ current.focusField(NewHarnessField.launch);
+ return;
+ }
+ _closeNewHarness(restoreFocus: false);
+ }
+ if (_search != null) _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ analytics.newAgentOpened(source: 'swarm_box');
+ _searchReturnFocus ??= FocusManager.instance.primaryFocus;
+ if (_native) _preparePaneFocus();
+ _canvasFocus.descendantsAreFocusable = false;
+ _newHarnessContext = origin;
+ // Consume once. Explicit text from search starts a fresh task with the
+ // inherited defaults; an empty search resumes this context's whole draft.
+ final savedDraft = _newHarnessDrafts[origin];
+ // A lost reply always restores its exact receipt. Otherwise explicit
+ // product/machine choices and freshly typed tasks win over old defaults.
+ final resumed =
+ draft ??
+ (savedDraft != null &&
+ (savedDraft.attempt?.awaitingConfirmation == true ||
+ (task == null && matchesSelection(savedDraft)))
+ ? savedDraft
+ : null);
+ if (resumed != null) _newHarnessDrafts.remove(origin);
+ final box = _newHarness = NewHarnessController(
+ app,
+ machineId: machineId,
+ engine: engine,
+ folder: folder,
+ projectName: projectName,
+ task: task,
+ draft: resumed,
+ autoProject: autoProject,
+ offersStore: true,
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ firstRun: firstRun,
+ );
+ final content = NewHarnessBox(
+ docked: true,
+ controller: box,
+ onClose: _closeNewHarness,
+ onCreated: () {
+ _closeNewHarness(restoreFocus: false, keepDraft: false);
+ unawaited(_focusCreatedPane());
+ },
+ onBrowse: () => unawaited(_browseForNewHarness(box)),
+ onStore: _openStore,
+ onLinkProfile: () => unawaited(_linkProfileForNewHarness(box)),
+ onNeedsForm: () {
+ if (box.busy || box.checking) {
+ box.warn('Check the pending creation before changing forms.');
+ return;
+ }
+ final draft = box.draft;
+ _closeNewHarness(restoreFocus: false, keepDraft: false);
+ unawaited(
+ _newAgentForm(
+ machineId: draft.machineId,
+ initialDraft: draft,
+ draftContext: origin,
+ returnToPrompt: true,
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ ),
+ );
+ },
+ );
+ final onWelcome = firstRun || _showsStartGuide;
+ _newHarnessOverlay = OverlayEntry(
+ builder: (context) => KeymapProvider(
+ keymap: _keymap,
+ child: ListenableBuilder(
+ listenable: box,
+ builder: (context, child) => LayoutBuilder(
+ builder: (context, constraints) {
+ if (onWelcome) {
+ return Padding(
+ padding: EdgeInsets.only(top: _native ? 0 : _tabBarHeight),
+ child: FocusScope(
+ child: BlockSemantics(
+ child: Material(
+ color: grid.AppPalette.swarmField,
+ child: Column(
+ children: [
+ Expanded(child: _startGuide()),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight:
+ (constraints.maxHeight -
+ (_native ? 0 : _tabBarHeight)) *
+ .65,
+ ),
+ child: content,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+ return Stack(
+ children: [
+ Positioned.fill(
+ child: BlockSemantics(
+ child: GestureDetector(
+ key: const ValueKey('new-harness-dismiss'),
+ behavior: HitTestBehavior.opaque,
+ onTap: () {
+ if (box.requestDismiss()) _closeNewHarness();
+ },
+ ),
+ ),
+ ),
+ CommandDock(
+ topClearance: _native ? 0 : _tabBarHeight,
+ expanded: box.field == NewHarnessField.projectMenu,
+ child: content,
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ Overlay.of(context).insert(_newHarnessOverlay!);
+ }
+
+ Future<void> _focusCreatedPane() async {
+ final tab = app.activeSwarmId;
+ final pane = app.focusedPane;
+ // The new terminal mounted while the dock owned input. Enable its focus
+ // tree, let the removed overlay settle, then hand it the text connection.
+ await WidgetsBinding.instance.endOfFrame;
+ if (!mounted ||
+ !_routeIsCurrent ||
+ _dialogOpen ||
+ _spokenPaletteOpen ||
+ _newHarness != null ||
+ _search != null ||
+ _commandBarOpen ||
+ app.activeSwarmId != tab ||
+ !identical(app.focusedPane, pane)) {
+ return;
+ }
+ if (pane?.session?.focusInput() != true) _shellFocus.requestFocus();
+ FocusManager.instance.applyFocusChangesIfNeeded();
+ }
+
+ /// The Browse… row: the system's folder chooser on this computer, the
+ /// folder browser on another. The box stays open behind it and takes the
+ /// answer when it comes back.
+ Future<void> _browseForNewHarness(NewHarnessController box) async {
+ final previousFocus = FocusManager.instance.primaryFocus;
+ final machineId = box.machineId;
+ final machine = app.stateOf(machineId);
+ final path = machine?.isLocalMachine == true
+ ? await getDirectoryPath(initialDirectory: box.project.folder)
+ : await showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: machineId,
+ initialPath: box.project.folder,
+ );
+ if (mounted && identical(_newHarness, box) && box.machineId == machineId) {
+ if (path != null) box.setFolder(path);
+ if (previousFocus?.context?.mounted == true &&
+ previousFocus!.canRequestFocus) {
+ previousFocus.requestFocus();
+ }
+ }
+ }
+
+ Future<void> _linkProfileForNewHarness(NewHarnessController box) async {
+ if (box.locked || !box.supportsProfiles) return;
+ final previousFocus = FocusManager.instance.primaryFocus;
+ final machineId = box.machineId;
+ final engine = box.engine;
+ final initialPath = box.draft.profile?.path;
+ final machine = app.stateOf(machineId);
+ final path = machine?.isLocalMachine == true
+ ? await getDirectoryPath(
+ initialDirectory: initialPath,
+ confirmButtonText: 'Link profile',
+ )
+ : await showRemoteFolderPicker(
+ context,
+ notifier: app,
+ machineId: machineId,
+ initialPath: initialPath,
+ );
+ if (!mounted ||
+ !identical(_newHarness, box) ||
+ box.machineId != machineId ||
+ box.engine != engine ||
+ box.field != NewHarnessField.profile) {
+ return;
+ }
+ if (path != null) await box.linkProfile(path);
+ if (mounted &&
+ identical(_newHarness, box) &&
+ previousFocus?.context?.mounted == true &&
+ previousFocus!.canRequestFocus) {
+ previousFocus.requestFocus();
+ }
+ }
+
+ void _rememberNewHarnessDraft(
+ _NewHarnessContext origin,
+ NewHarnessDraft draft,
+ ) {
+ // Choosing defaults is useful work even before the first task is typed.
+ _newHarnessDrafts.remove(origin);
+ _newHarnessDrafts[origin] = draft;
+ while (_newHarnessDrafts.length > 32) {
+ final oldest = _newHarnessDrafts.entries
+ .where((entry) => entry.value.attempt?.awaitingConfirmation != true)
+ .firstOrNull;
+ if (oldest == null) break;
+ _newHarnessDrafts.remove(oldest.key);
+ }
+ }
+
+ void _closeNewHarness({bool restoreFocus = true, bool keepDraft = true}) {
+ final box = _newHarness;
+ if (box == null) return;
+ _canvasFocus.descendantsAreFocusable = true;
+ _newHarnessOverlay?.remove();
+ _newHarnessOverlay?.dispose();
+ _newHarnessOverlay = null;
+ _newHarness = null;
+ if (keepDraft && _newHarnessContext != null) {
+ _rememberNewHarnessDraft(_newHarnessContext!, box.draft);
+ }
+ _newHarnessContext = null;
+ box.dispose();
+ final previous = _searchReturnFocus;
+ _searchReturnFocus = null;
+ if (restoreFocus) {
+ // Creation can replace a picker whose editor is now detached. Its node
+ // still holds a context, but cannot receive keys after cancellation.
+ if (previous?.context?.mounted == true && previous!.canRequestFocus) {
+ previous.requestFocus();
+ } else if (app.focusedPane?.session?.focusInput() != true) {
+ _shellFocus.requestFocus();
+ }
+ }
+ unawaited(_ensureEmptyEntry());
+ }
+
/// ⌘⇧T: a shell in a new tile, no dialog — the way a terminal app opens a
/// tab. It lands on the machine the focused tile is on (this computer when
/// nothing is focused), in the folder that tile's harness works in, else
@@ -1012,7 +1793,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.machineStates.values.firstOrNull
: app.stateOf(focused.machineId);
if (machine == null) {
- await _dialog(() => showSwarmLinkDialog(context, app));
+ await _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap));
return;
}
final machineId = machine.machine.machineId;
@@ -1069,13 +1850,27 @@ class _SwarmScreenState extends State<SwarmScreen> {
SwarmSearchSelection selected,
String target, {
PaneSplitRequest? split,
+ HarnessPlacement? placement,
}) async {
final command = selected.destination.commandId;
if (command != null) {
// The result list is gone before a dialog or focus-changing command runs.
// Recheck availability: a machine or pane may have changed while typing.
FocusManager.instance.applyFocusChangesIfNeeded();
- if (_canExecuteCommand(command)) _commands[command]?.call();
+ if (command.startsWith(_settingsCommand)) {
+ final section = SettingsSection.values
+ .where((s) => s.name == command.substring(_settingsCommand.length))
+ .firstOrNull;
+ if (_canExecuteCommand('app.settings')) {
+ _navigation.rememberCommand(command);
+ unawaited(_settings(section));
+ }
+ return;
+ }
+ if (_canExecuteCommand(command)) {
+ _navigation.rememberCommand(command);
+ _commands[command]?.call();
+ }
return;
}
_preparePaneFocus();
@@ -1085,6 +1880,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
destinationSwarmId: target,
projects: _projects.projects,
split: split,
+ placement: placement,
);
if (!opened && mounted) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -1095,11 +1891,32 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
+ void _openStore() {
+ _firstLaunch.handle();
+ if (!_routeIsCurrent || _dialogOpen || _spokenPaletteOpen) return;
+ if (_newHarness case final box?) {
+ if (box.locked) {
+ box.warn('Check the pending creation before opening Harness Store.');
+ return;
+ }
+ _closeNewHarness(restoreFocus: false);
+ }
+ _closeSearch(restoreFocus: false);
+ _closeCommandBar(restoreFocus: false);
+ dismissTransientMenus();
+ app.openStore();
+ }
+
+ bool _searchOnWelcome = false;
+
void _openSearch({
bool adding = false,
PaneSplitRequest? split,
String query = '',
+ bool welcome = false,
+ HarnessPlacement? placement,
}) {
+ _firstLaunch.handle();
if (_search != null ||
!mounted ||
_dialogOpen ||
@@ -1107,6 +1924,14 @@ class _SwarmScreenState extends State<SwarmScreen> {
!_routeIsCurrent) {
return;
}
+ // One surface, two modes: finding closes making.
+ if (_newHarness case final box?) {
+ if (box.busy || box.checking) {
+ box.warn('Check the pending creation before opening another picker.');
+ return;
+ }
+ _closeNewHarness(restoreFocus: false);
+ }
_closeCommandBar();
_searchReturnFocus ??= FocusManager.instance.primaryFocus == _searchFocus
? null
@@ -1115,14 +1940,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
// Search is an overlay, so late pane attachment needs an explicit focus
// boundary to keep its programmatic focus request out of the picker.
_canvasFocus.descendantsAreFocusable = false;
+ _searchOnWelcome = welcome || _showsStartGuide;
_search = SwarmSearchController(
app,
_navigation.recent,
projects: _projects,
commands: _searchCommands,
+ recentCommands: () => _navigation.recentCommands,
+ modes: _searchModes,
adding: adding,
- commandsOnly: !adding,
+ offersCreate: adding,
+ resultsFromBottom: true,
split: split,
+ placement:
+ placement ??
+ (adding && split == null
+ ? (app.activeSwarm.isStore || app.activeSwarm.isOrchestrator
+ ? HarnessPlacement.newTab
+ : HarnessPlacement.currentTab)
+ : null),
catalog: _searchCatalog,
)..setQuery(query);
_search!.addListener(_syncSearch);
@@ -1145,10 +1981,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
void _showSearchCommands() {
- if (_search?.adding == true) _closeSearch(restoreFocus: false);
- _openSearch();
+ if (_search == null) _openSearch(adding: true, query: '> ');
_search?.setQuery('> ');
_focusSearch();
+ if (_search != null) _learning.commandSearchOpened();
}
void _syncSearch() {
@@ -1162,9 +1998,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
// Results listen to their controller directly. Rebuilding the entire
// overlay on every arrow also rebuilt the unchanged text editor/button.
- final header = (search.hint, search.canCreate);
+ final header = (
+ search.hint,
+ search.canCreate,
+ search.title,
+ search.placement,
+ );
if (_searchHeaderState != header) {
_searchHeaderState = header;
+ if (search.isCommandMode) _learning.commandSearchOpened();
_searchOverlay?.markNeedsBuild();
}
}
@@ -1186,9 +2028,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
final previous = _searchReturnFocus;
_searchReturnFocus = null;
if (restoreFocus) {
- if (previous?.context != null && previous!.canRequestFocus) {
+ if (previous?.context?.mounted == true && previous!.canRequestFocus) {
previous.requestFocus();
- } else {
+ } else if (app.focusedPane?.session?.focusInput() != true) {
_shellFocus.requestFocus();
}
}
@@ -1207,9 +2049,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
Future<void> _chooseSearch(SwarmSearchSelection choice) async {
final target = _search?.targetId;
final split = _search?.split;
+ final placement = _search?.placement;
if (target == null) return;
+ if (choice.destination.isCreate) {
+ // What was typed and found nothing is what the new harness starts on.
+ final task = choice.destination.task;
+ _closeSearch(restoreFocus: false);
+ await _newAgent(
+ swarmId: target,
+ split: split,
+ task: task,
+ placement: placement,
+ );
+ return;
+ }
_closeSearch(restoreFocus: choice.destination.isCommand);
- await _activateSearch(choice, target, split: split);
+ await _activateSearch(choice, target, split: split, placement: placement);
if (mounted) {
if (app.activeSwarmId != target) app.cancelSwarmDraft(target);
await _ensureEmptyEntry();
@@ -1218,111 +2073,181 @@ class _SwarmScreenState extends State<SwarmScreen> {
Widget _buildSearchOverlay(BuildContext context) {
final search = _search!;
- final commandsOnly = search.commandsOnly;
- final panel = Material(
+ final commandsOnly = search.isCommandMode;
+ // Results sit above a stable input line in the workspace command dock.
+ // The input is visually below results, but Tab still starts at the first
+ // result rather than a cached, offscreen ListView row below the input.
+ Widget ordered(double order, Widget child) =>
+ FocusTraversalOrder(order: NumericFocusOrder(order), child: child);
+ final panel = TerminalBox(
key: const ValueKey('swarm-search-results'),
- elevation: 10,
- shadowColor: Colors.black38,
- color: grid.AppPalette.swarmSearchSurface,
- surfaceTintColor: Colors.transparent,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(commandsOnly ? 14 : 32),
- side: BorderSide(color: Colors.white.withValues(alpha: .10)),
- ),
- clipBehavior: Clip.antiAlias,
- child: Column(
- children: [
- if (commandsOnly)
+ docked: true,
+ child: FocusTraversalGroup(
+ policy: OrderedTraversalPolicy(),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
Padding(
- padding: const EdgeInsets.fromLTRB(20, 24, 20, 16),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Semantics(
- header: true,
- child: const Text(
- 'Commands',
- style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
+ padding: const EdgeInsets.fromLTRB(14, 9, 14, 2),
+ child: Row(
+ children: [
+ Text(
+ search.title,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
),
+ if (search.placement == HarnessPlacement.currentTab)
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Text(
+ '· ${search.targetName}',
+ key: const ValueKey('swarm-search-target'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ )
+ else
+ const Spacer(),
+ SwarmSearchCount(search: search, terminal: true),
+ ],
+ ),
+ ),
+ Flexible(
+ child: ordered(
+ 2,
+ SwarmSearchResults(
+ search: search,
+ onChoose: _chooseSearch,
+ onRefocus: _focusSearch,
+ fitRows: true,
+ terminal: true,
),
),
),
- Semantics(
- label: commandsOnly ? 'Search commands' : 'Find a harness',
- child: SwarmSearchInput(
- inputKey: const ValueKey('swarm-search-input'),
- controller: _searchText,
- focusNode: _searchFocus,
- search: search,
- onClose: _dismissSearch,
- onChanged: search.setQuery,
- onOpen: _focusSearch,
- showClose: true,
- rounded: true,
- prominent: !commandsOnly,
- hintText: commandsOnly ? null : 'Find a harness',
- trailing: !commandsOnly && search.split != null
- ? KeymapRegion(
- contextKind: KeymapContext.workspace,
- child: IconButton(
- key: const ValueKey('harness-picker-new'),
- tooltip: 'New Harness',
- onPressed: search.canCreate
- ? () => _runShortcut('agent.new')
- : null,
- icon: const Icon(AgentActionIcons.create, size: 18),
- ),
- )
- : null,
+ ordered(
+ 1,
+ Semantics(
+ label: search.hint,
+ child: ReadlineKeys(
+ controller: _searchText,
+ onChanged: search.setQuery,
+ child: SwarmSearchInput(
+ inputKey: const ValueKey('swarm-search-input'),
+ controller: _searchText,
+ focusNode: _searchFocus,
+ search: search,
+ onClose: _dismissSearch,
+ onChanged: search.setQuery,
+ onOpen: _focusSearch,
+ height: 38,
+ fontSize: 13,
+ terminal: true,
+ hintText: search.hint,
+ trailing: !commandsOnly && search.split != null
+ ? KeymapRegion(
+ contextKind: KeymapContext.workspace,
+ child: IconButton(
+ key: const ValueKey('harness-picker-new'),
+ tooltip: 'New Harness',
+ onPressed: search.canCreate
+ ? () => _runShortcut('agent.new')
+ : null,
+ icon: const Icon(
+ AgentActionIcons.create,
+ size: 18,
+ ),
+ ),
+ )
+ : null,
+ ),
+ ),
+ ),
),
- ),
- Expanded(
- child: SwarmSearchResults(
- search: search,
- onChoose: _chooseSearch,
- onRefocus: _focusSearch,
+ ordered(
+ 3,
+ SwarmSearchHints(
+ search: search,
+ onSubmit: () {
+ final choice = search.submit();
+ if (choice != null) unawaited(_chooseSearch(choice));
+ },
+ onAddHere: () {
+ final choice = search.addHere();
+ if (choice != null) unawaited(_chooseSearch(choice));
+ },
+ onClose: _dismissSearch,
+ onQuery: (text) {
+ search.setQuery(text);
+ _focusSearch();
+ },
+ ),
),
- ),
- if (!commandsOnly) const SizedBox(height: 12),
- ],
+ ],
+ ),
),
);
+ final scoped = Semantics(
+ scopesRoute: true,
+ namesRoute: true,
+ explicitChildNodes: true,
+ label: search.title,
+ child: panel,
+ );
return KeymapProvider(
keymap: _keymap,
child: LayoutBuilder(
builder: (context, constraints) {
- final height = (constraints.maxHeight - 64).clamp(
- 240.0,
- commandsOnly ? 600.0 : 760.0,
+ final contents = SwarmSearchKeys(
+ search: search,
+ editing: _searchText,
+ onChoose: _chooseSearch,
+ onClose: _dismissSearch,
+ onOpen: _focusSearch,
+ onNewAgent: () => _runShortcut('agent.new'),
+ onRefocus: _focusSearch,
+ child: scoped,
);
+ if (_searchOnWelcome) {
+ return Padding(
+ padding: EdgeInsets.only(top: _native ? 0 : _tabBarHeight),
+ child: BlockSemantics(
+ child: Material(
+ color: grid.AppPalette.swarmField,
+ child: Column(
+ children: [
+ Expanded(child: _startGuide()),
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: constraints.maxHeight * .65,
+ ),
+ child: contents,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
return Stack(
children: [
+ // A click outside still closes it; it just no longer dims. To a
+ // screen reader it IS modal: without the block, VoiceOver walks
+ // straight out of the box into the panes behind it.
Positioned.fill(
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: _dismissSearch,
- child: const ColoredBox(color: kDialogVeilTint),
- ),
- ),
- Align(
- alignment: const Alignment(0, -0.12),
- child: SizedBox(
- width: (constraints.maxWidth - 64).clamp(
- 280.0,
- commandsOnly ? 720.0 : 1120.0,
- ),
- height: height,
- child: SwarmSearchKeys(
- search: search,
- editing: _searchText,
- onChoose: _chooseSearch,
- onClose: _dismissSearch,
- onOpen: _focusSearch,
- onNewAgent: () => _runShortcut('agent.new'),
- onRefocus: _focusSearch,
- child: panel,
+ child: BlockSemantics(
+ child: GestureDetector(
+ key: const ValueKey('swarm-search-dismiss'),
+ behavior: HitTestBehavior.opaque,
+ onTap: _dismissSearch,
),
),
),
+ CommandDock(
+ topClearance: _native ? 0 : _tabBarHeight,
+ child: contents,
+ ),
],
);
},
@@ -1348,13 +2273,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
Future<void> _addAgent() async {
- if (_search != null) _closeSearch(restoreFocus: false);
- _openSearch(adding: true);
+ _openPlacementPicker(HarnessPlacement.currentTab);
}
- void _newTab() {
- app.newSwarm();
- if (app.panes.isEmpty) _startSearchFocus.requestFocus();
+ void _newTab() => _openPlacementPicker(HarnessPlacement.newTab);
+
+ void _openPlacementPicker(HarnessPlacement requested) {
+ final placement = app.activeSwarm.isStore || app.activeSwarm.isOrchestrator
+ ? HarnessPlacement.newTab
+ : requested;
+ if (_search?.changePlacement(placement) == true) {
+ _focusSearch();
+ return;
+ }
+ _closeSearch(restoreFocus: false);
+ _openSearch(adding: true, placement: placement);
}
Future<void> _addProject() => _dialog(() async {
@@ -1478,8 +2411,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.togglePinPane(app.focusedPaneId!);
}
},
- ShortcutAction.showShortcuts: () =>
- _dialog(() => showShortcutsSheet(context)),
+ ShortcutAction.showShortcuts: _showKeyboardShortcuts,
ShortcutAction.showDebug: () => _dialog(
() => showSettingsScreen(
context,
@@ -1500,11 +2432,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
for (var i = 1; i <= 9; i++)
'pane.focus_$i': () => app.focusPaneByIndex(i - 1),
'navigation.commands': _showSearchCommands,
- 'machine.link': () => _dialog(() => showSwarmLinkDialog(context, app)),
- 'machines.manage': () => _dialog(() => app.manageMachines(context)),
- 'machines.list': () => _dialog(() => showMachinesManager(context, app)),
+ 'app.customize': () => unawaited(_customize()),
+ 'app.store': _openStore,
+ if (kDebugSurfaceEnabled) 'app.onboarding_review': _reviewOnboarding,
+ 'agent.rename': () => _editAgent(),
+ 'agent.stop': () => _editAgent(stop: true),
+ 'agent.fork': _forkAgent,
+ 'agent.restart': _restartAgent,
+ 'machine.link': () =>
+ _dialog(() => showSwarmLinkDialog(context, app, keymap: _keymap)),
+ 'machines.manage': _manageMachines,
+ 'machines.list': () =>
+ _dialog(() => showMachinesManager(context, app, keymap: _keymap)),
'project.add': _addProject,
'keyboard.open_config': () => openKeyboardConfig(context),
+ 'keyboard.quick_start': _startQuickStart,
+ 'keyboard.practice': _practiceKeyboard,
+ 'keyboard.pause_guide': _learning.pause,
'pane.resize': app.beginPaneResize,
'pane.reset_sizes': app.resetPaneSizes,
'pane.split_right': () => _splitAgent(PaneResizeAxis.x),
@@ -1519,6 +2463,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
return false;
}
if (id == 'keyboard.open_config') return _keymap.store != null;
+ if (id == 'keyboard.pause_guide') return _learning.active;
+ if (id == 'keyboard.quick_start' ||
+ id == 'keyboard.practice' ||
+ id == 'app.onboarding_review') {
+ return app.viewer == null;
+ }
+ if (id == 'agent.rename' ||
+ id == 'agent.stop' ||
+ id == 'agent.fork' ||
+ id == 'agent.restart') {
+ final pane = app.focusedPane;
+ final machine = pane == null ? null : app.stateOf(pane.machineId);
+ return machine != null &&
+ !machine.machine.isShared &&
+ (id != 'agent.fork' || _focusedAgent?.canFork == true) &&
+ (id != 'agent.restart' ||
+ (machine.nodeOnline != false && !machine.needsLink)) &&
+ machine.agents.any((agent) => agent.id == pane!.agentId);
+ }
if (id == 'pane.layout' || id == 'task.route') return true;
if (id.startsWith('swarm.select_')) {
final number = int.tryParse(id.substring('swarm.select_'.length));
@@ -1555,29 +2518,122 @@ class _SwarmScreenState extends State<SwarmScreen> {
return true;
}
+ /// What `?` lists in the box: its other modes, in the order worth learning
+ /// them, each with the key that goes there directly.
+ List<SwarmDestination> _searchModes() {
+ SwarmDestination? mode(String id, String title, String detail) =>
+ !_canExecuteCommand(id)
+ ? null
+ : SwarmDestination(
+ id: 'command:$id',
+ title: title,
+ detail: detail,
+ swarmId: null,
+ current: false,
+ commandId: id,
+ shortcut: _keymap.hint(id),
+ searchFields: [id, detail],
+ );
+ return [
+ SwarmDestination(
+ id: 'picker:commands',
+ title: '> Commands',
+ detail: 'Run anything by name',
+ swarmId: null,
+ current: false,
+ pickerQuery: '> ',
+ shortcut: _keymap.hint('navigation.commands'),
+ ),
+ SwarmDestination(
+ id: 'picker:projects',
+ title: '# Projects',
+ detail: 'Choose a project, then one of its agents',
+ swarmId: null,
+ current: false,
+ pickerQuery: '# ',
+ ),
+ SwarmDestination(
+ id: 'picker:machines',
+ title: '@ Machines',
+ detail: 'Choose a machine, then one of its agents',
+ swarmId: null,
+ current: false,
+ pickerQuery: '@ ',
+ ),
+ ?mode('agent.new', 'New Harness', 'agent · machine · project'),
+ ?mode('app.store', 'Harness Store', 'Browse and install harnesses'),
+ ?mode('terminal.new', 'New terminal', 'A shell where you are'),
+ ?mode('navigation.needs_input', 'Agents needing input', 'Who is waiting'),
+ ?mode('navigation.history', 'History', 'Where you have been'),
+ ?mode('task.route', 'Boss mode', 'Describe a task, it picks the agent'),
+ ?mode('pane.layout', 'Layout', 'Arrange the panes'),
+ ?mode('keyboard.help', 'Keyboard shortcuts', 'Every key'),
+ ?mode('keyboard.quick_start', 'Quick start', 'Four steps into real work'),
+ ?mode('keyboard.practice', 'Keyboard practice', 'Try every shortcut'),
+ ?mode('keyboard.open_config', 'Edit keybindings', 'keybindings.jsonc'),
+ ?mode(
+ 'app.customize',
+ 'Customize OpenHarness',
+ 'Prompt · colors · fonts',
+ ),
+ ?mode('app.settings', 'Settings', ''),
+ ];
+ }
+
+ // Compiled once, not once per command per app tick while the palette is open.
+ static final _paneFocusCommand = RegExp(r'^pane\.focus_[1-9]$');
+
List<SwarmDestination> _searchCommands() => [
for (final command in harnessCommands)
- if (command.id != 'navigation.commands' &&
+ if (!command.hidden &&
+ command.id != 'navigation.commands' &&
command.id != 'navigation.command_bar' &&
- !RegExp(r'^pane\.focus_[1-9]$').hasMatch(command.id) &&
+ !_paneFocusCommand.hasMatch(command.id) &&
_canExecuteCommand(command.id))
SwarmDestination(
id: 'command:${command.id}',
- title: command.label,
+ title:
+ command.id == 'agent.stop' &&
+ isTerminalEngine(_focusedAgent?.engine)
+ ? 'Stop Terminal'
+ : command.id == 'agent.restart' &&
+ isTerminalEngine(_focusedAgent?.engine)
+ ? 'Restart Terminal'
+ : command.label,
detail: command.group.label,
swarmId: null,
current: false,
commandId: command.id,
shortcut: _keymap.hint(command.id),
- searchFields: [command.id],
+ searchFields: [command.id, ...command.keywords],
),
+ if (_canExecuteCommand('app.settings'))
+ for (final group in settingsGroups)
+ for (final section in group.sections)
+ SwarmDestination(
+ id: 'command:$_settingsCommand${section.name}',
+ title: 'Settings: ${section.label}',
+ detail: 'Settings',
+ swarmId: null,
+ current: false,
+ commandId: '$_settingsCommand${section.name}',
+ searchFields: ['settings', 'preferences', section.name],
+ ),
];
void _focusCommandBar() {
+ _firstLaunch.handle();
if (_commandBarOpen) {
_closeCommandBar();
return;
}
+ if (_newHarness case final box?) {
+ if (box.locked) {
+ box.warn('Check the pending creation before opening another prompt.');
+ return;
+ }
+ _closeNewHarness(restoreFocus: false);
+ }
_closeSearch(restoreFocus: false);
_commandReturnFocus = FocusManager.instance.primaryFocus;
_preparePaneFocus();
@@ -1590,7 +2646,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _closeCommandBar({bool restoreFocus = true, bool clear = true}) {
if (!_commandBarOpen) return;
_canvasFocus.descendantsAreFocusable =
- _search == null && !_dialogOpen && !_spokenPaletteOpen;
+ _search == null &&
+ _newHarness == null &&
+ !_dialogOpen &&
+ !_spokenPaletteOpen;
setState(() => _commandBarOpen = false);
if (clear) _commandBar.dismiss();
_commandFocus.unfocus();
@@ -1676,10 +2735,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
focusNode: _commandFocus,
onDismiss: _closeCommandBar,
onNew: _newAgent,
- onStore: () {
- _closeCommandBar(restoreFocus: false);
- app.openStore();
- },
+ onStore: _openStore,
),
),
),
@@ -1692,7 +2748,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
@override
Widget build(BuildContext context) => ListenableBuilder(
- listenable: Listenable.merge([app, _projects]),
+ listenable: Listenable.merge([app, _projects, _learning]),
builder: (context, _) {
grid.AppTheme.watch(context);
_maybeLink();
@@ -1701,185 +2757,271 @@ class _SwarmScreenState extends State<SwarmScreen> {
(_) => _restoreEmptyFocus(),
);
}
- return KeymapProvider(
- keymap: _keymap,
- child: KeymapHost(
+ return Actions(
+ actions: {
+ if (newHarnessOpensInBox)
+ OpenHarnessIntent: CallbackAction<OpenHarnessIntent>(
+ onInvoke: (intent) => _openProduct(
+ intent.engine,
+ intent.machineId,
+ task: intent.task,
+ ),
+ ),
+ },
+ child: KeymapProvider(
keymap: _keymap,
- enabled: () => _shortcutsEnabled,
- canExecute: _canExecuteCommand,
- actions: {
- for (final id in _commands.keys) id: () => _runShortcut(id),
- },
- onPending: (keys) => setState(() => _pendingKeys = keys),
- child: Focus(
- focusNode: _shellFocus,
- autofocus: app.panes.isNotEmpty,
- child: Scaffold(
- backgroundColor: grid.AppPalette.swarmField,
- body: Column(
- children: [
- if (!_native) _tabStrip(),
- if (_keymap.error != null)
- Material(
- color: grid.AppPalette.panelBg,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Row(
- children: [
- const Expanded(
- child: Text(
- 'Keyboard config has an error. Using the last working shortcuts.',
- style: TextStyle(fontSize: 12),
+ child: KeymapHost(
+ keymap: _keymap,
+ enabled: () => _shortcutsEnabled,
+ canExecute: _canExecuteCommand,
+ actions: {
+ for (final id in _commands.keys) id: () => _runShortcut(id),
+ },
+ onPending: (keys) => setState(() => _pendingKeys = keys),
+ child: Focus(
+ focusNode: _shellFocus,
+ autofocus: app.panes.isNotEmpty,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.swarmField,
+ body: Column(
+ children: [
+ if (!_native) _tabStrip(),
+ if (_learning.active && app.viewer == null)
+ WorkspaceQuickStart(
+ learning: _learning,
+ onCommand: _runShortcut,
+ onPractice: _practiceKeyboard,
+ ),
+ if (_keymap.error != null)
+ Material(
+ color: grid.AppPalette.panelBg,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ children: [
+ const Expanded(
+ child: Text(
+ 'Keyboard config has an error. Using the last working shortcuts.',
+ style: TextStyle(fontSize: 12),
+ ),
),
- ),
- TextButton(
- onPressed: () =>
- _dialog(() => showShortcutsSheet(context)),
- child: const Text('Details'),
- ),
- ],
+ TextButton(
+ onPressed: () =>
+ _dialog(() => showShortcutsSheet(context)),
+ child: const Text('Details'),
+ ),
+ ],
+ ),
),
),
- ),
- if (_pendingKeys.isNotEmpty)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 16,
- vertical: 4,
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- '$_pendingKeys … Esc to cancel',
- style: TextStyle(
- fontSize: 12,
- color: grid.AppPalette.textSecondary,
+ if (_pendingKeys.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 4,
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ '$_pendingKeys … Esc to cancel',
+ style: TextStyle(
+ fontSize: 12,
+ color: grid.AppPalette.textSecondary,
+ ),
),
),
),
- ),
- if (_projects.error != null || app.lastError != null)
- Material(
- color: grid.AppPalette.panelBg,
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 16),
- child: Row(
- children: [
- const Icon(
- Icons.info_outline,
- size: 16,
- color: Colors.orangeAccent,
- ),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- _projects.error ?? app.lastError!,
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 12),
+ if (_projects.error != null || app.lastError != null)
+ Material(
+ color: grid.AppPalette.panelBg,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 16),
+ child: Row(
+ children: [
+ const Icon(
+ Icons.info_outline,
+ size: 16,
+ color: Colors.orangeAccent,
),
- ),
- if (_projects.error == null &&
- app.lastErrorRetryable)
- TextButton(
- onPressed: app.retryMachines,
- child: const Text('Retry'),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ _projects.error ?? app.lastError!,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 12),
+ ),
),
- IconButton(
- onPressed: _projects.error != null
- ? _projects.dismissError
- : app.dismissError,
- tooltip: 'Dismiss',
- icon: const Icon(Icons.close, size: 16),
- ),
- ],
+ if (_projects.error == null &&
+ app.lastErrorRetryable)
+ TextButton(
+ onPressed: app.retryMachines,
+ child: const Text('Retry'),
+ ),
+ IconButton(
+ onPressed: _projects.error != null
+ ? _projects.dismissError
+ : app.dismissError,
+ tooltip: 'Dismiss',
+ icon: const Icon(Icons.close, size: 16),
+ ),
+ ],
+ ),
),
),
- ),
- Expanded(
- child: Stack(
- fit: StackFit.expand,
- children: [
- if (app.panes.isEmpty)
- const RepaintBoundary(
- key: ValueKey('harness-start-background'),
- child: SwarmWallpaper(),
- ),
- if (app.activeSwarm.isOrchestrator)
- OrchestratorWorkspace(
- key: ValueKey(
- 'orchestrator:${app.activeSwarm.orchestratorId}',
+ Expanded(
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ if (app.panes.isEmpty)
+ const RepaintBoundary(
+ key: ValueKey('harness-start-background'),
+ child: SwarmWallpaper(),
),
- notifier: app,
- machineId: app.activeSwarm.orchestratorMachineId!,
- projectId: app.activeSwarm.orchestratorId!,
- )
- else if (app.activeSwarm.isStore)
- StoreTab(
- key: ValueKey('store-tab:${app.activeSwarmId}'),
- notifier: app,
- source: 'tab',
- )
- else
- Padding(
- padding: app.panes.isEmpty
- ? EdgeInsets.zero
- : const EdgeInsets.all(10),
- child: Focus.withExternalFocusNode(
- focusNode: _canvasFocus,
- includeSemantics: false,
- child: Stack(
- children: [
- Positioned.fill(
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- onSplit: (paneId, axis) => unawaited(
- _splitAgent(axis, paneId: paneId),
- ),
- onNewSplit: (paneId, axis) => unawaited(
- _splitAgent(
- axis,
- paneId: paneId,
- create: true,
+ // Utility tabs hide the canvas without discarding its
+ // terminal renderers, scroll positions or selections.
+ Offstage(
+ key: const ValueKey('workspace-canvas'),
+ offstage:
+ app.activeSwarm.isStore ||
+ app.activeSwarm.isOrchestrator,
+ child: ExcludeFocus(
+ excluding:
+ app.activeSwarm.isStore ||
+ app.activeSwarm.isOrchestrator,
+ child: Padding(
+ padding: app.panes.isEmpty
+ ? EdgeInsets.zero
+ : const EdgeInsets.all(kWorkspaceInset),
+ child: Focus.withExternalFocusNode(
+ focusNode: _canvasFocus,
+ includeSemantics: false,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneGrid(
+ notifier: app,
+ swarmMode: true,
+ empty:
+ app.panes.isEmpty &&
+ !app.activeSwarm.isStore &&
+ !app
+ .activeSwarm
+ .isOrchestrator
+ ? newHarnessOpensInBox
+ ? _startGuide()
+ : HarnessStartPage(
+ key: ValueKey(
+ 'harness-start:${app.activeSwarmId}',
+ ),
+ focusNode:
+ _startSearchFocus,
+ createSearch: () =>
+ SwarmSearchController(
+ app,
+ _navigation
+ .recent,
+ projects:
+ _projects,
+ commands:
+ _searchCommands,
+ recentCommands: () =>
+ _navigation
+ .recentCommands,
+ // The first box a new
+ // person meets is the same
+ // box: its placeholder
+ // promises `?` and a way
+ // to create, so it has them.
+ modes:
+ _searchModes,
+ adding: true,
+ offersCreate:
+ true,
+ placement:
+ HarnessPlacement
+ .currentTab,
+ catalog:
+ _searchCatalog,
+ ),
+ onNewTab: _newTab,
+ onNewPane: _addAgent,
+ onCommands:
+ _showSearchCommands,
+ onQuickStart:
+ _learning.offer &&
+ app.viewer ==
+ null
+ ? _startQuickStart
+ : null,
+ onPractice:
+ app.viewer == null
+ ? _practiceKeyboard
+ : null,
+ onNew: () => _newAgent(
+ placement:
+ HarnessPlacement
+ .currentTab,
+ ),
+ onNewWithTask: (task) =>
+ _newAgent(
+ task: task,
+ placement:
+ HarnessPlacement
+ .currentTab,
+ ),
+ onStore: _openStore,
+ onChoose: (selection) =>
+ selection
+ .destination
+ .isCreate
+ ? _newAgent(
+ task: selection
+ .destination
+ .task,
+ placement:
+ HarnessPlacement
+ .currentTab,
+ )
+ : _activateSearch(
+ selection,
+ app.activeSwarmId,
+ placement:
+ HarnessPlacement
+ .currentTab,
+ ),
+ )
+ : null,
),
),
- empty: app.panes.isEmpty
- ? HarnessStartPage(
- key: ValueKey(
- 'harness-start:${app.activeSwarmId}',
- ),
- focusNode: _startSearchFocus,
- createSearch: () =>
- SwarmSearchController(
- app,
- _navigation.recent,
- projects: _projects,
- commands: _searchCommands,
- adding: true,
- catalog: _searchCatalog,
- ),
- onNew: _newAgent,
- onStore: app.openStore,
- onChoose: (selection) =>
- _activateSearch(
- selection,
- app.activeSwarmId,
- ),
- )
- : null,
- ),
+ ],
),
- ],
+ ),
),
),
),
- if (_hasCommandBar && _commandBarOpen)
- _commandPalette(),
- ],
+ if (app.activeSwarm.isOrchestrator)
+ OrchestratorWorkspace(
+ key: ValueKey(
+ 'orchestrator:${app.activeSwarm.orchestratorId}',
+ ),
+ notifier: app,
+ machineId: app.activeSwarm.orchestratorMachineId!,
+ projectId: app.activeSwarm.orchestratorId!,
+ ),
+ if (app.activeSwarm.isStore)
+ StoreTab(
+ key: ValueKey('store-tab:${app.activeSwarmId}'),
+ notifier: app,
+ source: 'tab',
+ ),
+ if (_hasCommandBar && _commandBarOpen)
+ _commandPalette(),
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
@@ -1888,21 +3030,61 @@ class _SwarmScreenState extends State<SwarmScreen> {
},
);
- /// Below this the strip's fixed furniture does not fit: the notification and new-tab buttons are
- /// ~48 each, the two harness buttons ~150 each once icon and padding are counted, plus 32 of gaps —
- /// about 430 before the tab list gets a single pixel. Rather than let the Row overflow, the two
- /// labelled buttons drop to their icons, which is what their tooltips are for.
- static const double _labelledStripMinWidth = 560;
+ static const double _tabBarHeight = 40;
+ static const double _tabExtent = 188;
+
+ void _revealSelectedTab(double viewport) {
+ final previous = _tabGeometry;
+ final order = app.swarms.map((tab) => tab.id).toList(growable: false);
+ if (previous != null &&
+ previous.activeId == app.activeSwarmId &&
+ previous.viewport == viewport &&
+ listEquals(previous.order, order)) {
+ return;
+ }
+ _tabGeometry = (
+ activeId: app.activeSwarmId,
+ order: order,
+ viewport: viewport,
+ );
+ final oldIndex = previous?.order.indexOf(previous.activeId) ?? -1;
+ final wasVisible =
+ _tabScroll.hasClients &&
+ oldIndex >= 0 &&
+ (oldIndex + 1) * _tabExtent > _tabScroll.offset &&
+ oldIndex * _tabExtent < _tabScroll.offset + previous!.viewport;
+ // A selected tab follows keyboard navigation and layout changes, but
+ // background agent updates must not undo deliberate strip scrolling.
+ if (previous != null &&
+ previous.activeId == app.activeSwarmId &&
+ !wasVisible) {
+ return;
+ }
+ if (_tabRevealScheduled) return;
+ _tabRevealScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _tabRevealScheduled = false;
+ if (!mounted || !_tabScroll.hasClients) return;
+ final index = app.swarms.indexWhere((tab) => tab.id == app.activeSwarmId);
+ if (index < 0) return;
+ final position = _tabScroll.position;
+ final left = index * _tabExtent;
+ final right = left + _tabExtent;
+ final offset =
+ left < position.pixels || _tabExtent > position.viewportDimension
+ ? left
+ : right > position.pixels + position.viewportDimension
+ ? right - position.viewportDimension
+ : position.pixels;
+ final target = offset.clamp(0.0, position.maxScrollExtent);
+ if (target != position.pixels) _tabScroll.jumpTo(target);
+ });
+ }
Widget _tabStrip() => LayoutBuilder(
builder: (context, constraints) {
- final compact =
- constraints.maxWidth <
- _labelledStripMinWidth *
- MediaQuery.textScalerOf(context).scale(12) /
- 12;
return Container(
- height: 52,
+ height: _tabBarHeight,
color: grid.AppPalette.swarmTabBar,
child: Row(
children: [
@@ -1922,106 +3104,121 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
const SizedBox(width: 10),
Expanded(
- child: ReorderableListView.builder(
- scrollDirection: Axis.horizontal,
- shrinkWrap: true,
- buildDefaultDragHandles: false,
- itemCount: app.swarms.length,
- onReorderItem: (old, to) =>
- app.reorderSwarm(app.swarms[old].id, to),
- itemBuilder: (context, index) {
- final swarm = app.swarms[index];
- return ReorderableDragStartListener(
- key: ValueKey(swarm.id),
- index: index,
- child: GestureDetector(
- onDoubleTap: () => _rename(swarm.id),
- child: _TabActionsReveal(
- builder: (showClose) => Container(
- width: 186,
- margin: const EdgeInsets.only(top: 6, right: 2),
- decoration: BoxDecoration(
- color: app.activeSwarmId == swarm.id
- ? grid.AppPalette.swarmField
- : Colors.transparent,
- borderRadius: const BorderRadius.vertical(
- top: Radius.circular(9),
- ),
- ),
- child: Row(
- children: [
- Expanded(
- child: TextButton(
- onPressed: () => app.selectSwarm(swarm.id),
- style: TextButton.styleFrom(
- animationDuration: Duration.zero,
- foregroundColor:
- app.activeSwarmId == swarm.id
- ? Colors.white
- : Colors.white70,
- ),
- child: Row(
- children: [
- if (swarm.isStore)
- StoreMark(
- key: ValueKey(
- 'tab-store:${swarm.id}',
- ),
- )
- else if (_tabAgents(swarm).length == 1)
- EngineMark(
- key: ValueKey(
- 'tab-engine:${swarm.id}',
- ),
- engine: _tabEngine(swarm),
- size: 16,
- )
- else if (_tabAgents(swarm).length > 1)
- SwarmIcon(
- key: ValueKey(
- 'tab-group:${swarm.id}',
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ _revealSelectedTab(constraints.maxWidth);
+ return ReorderableListView.builder(
+ scrollController: _tabScroll,
+ itemExtent: _tabExtent,
+ scrollDirection: Axis.horizontal,
+ shrinkWrap: true,
+ buildDefaultDragHandles: false,
+ itemCount: app.swarms.length,
+ onReorderItem: (old, to) =>
+ app.reorderSwarm(app.swarms[old].id, to),
+ itemBuilder: (context, index) {
+ final swarm = app.swarms[index];
+ return ReorderableDragStartListener(
+ key: ValueKey(swarm.id),
+ index: index,
+ child: GestureDetector(
+ onDoubleTap: () => _rename(swarm.id),
+ child: _TabActionsReveal(
+ builder: (showClose) => Container(
+ width: _tabExtent - 2,
+ margin: const EdgeInsets.only(top: 4, right: 2),
+ decoration: ShapeDecoration(
+ color: app.activeSwarmId == swarm.id
+ ? grid.AppPalette.swarmField
+ : Colors.transparent,
+ shape: const TerminalTabBorder(),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: TextButton(
+ onPressed: () =>
+ app.selectSwarm(swarm.id),
+ style: TextButton.styleFrom(
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.all(
+ Radius.circular(
+ kTerminalCornerRadius,
+ ),
),
- size: 16,
- color: Colors.white70,
- )
- else
- const Icon(Icons.add, size: 16),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- swarm.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 13),
),
+ animationDuration: Duration.zero,
+ foregroundColor:
+ app.activeSwarmId == swarm.id
+ ? Colors.white
+ : Colors.white70,
),
- ],
- ),
- ),
- ),
- Opacity(
- key: ValueKey('tab-close:${swarm.id}'),
- opacity: showClose ? 1 : 0,
- alwaysIncludeSemantics: true,
- child: IconButton(
- onPressed: () => app.closeSwarm(swarm.id),
- icon: Icon(
- Icons.close,
- size: 13,
- semanticLabel: 'Close ${swarm.name}',
+ child: Row(
+ children: [
+ if (swarm.isStore)
+ StoreMark(
+ key: ValueKey(
+ 'tab-store:${swarm.id}',
+ ),
+ )
+ else if (_tabAgents(swarm).length ==
+ 1)
+ EngineMark(
+ key: ValueKey(
+ 'tab-engine:${swarm.id}',
+ ),
+ engine: _tabEngine(swarm),
+ size: 16,
+ )
+ else if (_tabAgents(swarm).length > 1)
+ SwarmIcon(
+ key: ValueKey(
+ 'tab-group:${swarm.id}',
+ ),
+ size: 16,
+ color: Colors.white70,
+ )
+ else
+ const Icon(Icons.add, size: 16),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ swarm.name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(),
+ ),
+ ),
+ ],
+ ),
+ ),
),
- constraints: const BoxConstraints.tightFor(
- width: 30,
- height: 30,
+ Opacity(
+ key: ValueKey('tab-close:${swarm.id}'),
+ opacity: showClose ? 1 : 0,
+ alwaysIncludeSemantics: true,
+ child: IconButton(
+ onPressed: () => app.closeSwarm(swarm.id),
+ icon: Icon(
+ Icons.close,
+ size: 13,
+ semanticLabel: 'Close ${swarm.name}',
+ ),
+ constraints:
+ const BoxConstraints.tightFor(
+ width: 30,
+ height: 30,
+ ),
+ padding: EdgeInsets.zero,
+ ),
),
- padding: EdgeInsets.zero,
- ),
+ ],
),
- ],
+ ),
),
),
- ),
- ),
+ );
+ },
);
},
),
@@ -2029,83 +3226,44 @@ class _SwarmScreenState extends State<SwarmScreen> {
IconButton(
key: const ValueKey('swarm-new-tab-button'),
onPressed: _newTab,
+ tooltip: 'New Tab ${_keymap.hint('swarm.new') ?? ''}'.trim(),
icon: const Icon(Icons.add, size: 18, semanticLabel: 'New Tab'),
),
- _harnessButton(create: true, compact: compact),
- SizedBox(width: compact ? 4 : 10),
- _harnessButton(create: false, compact: compact),
- SizedBox(width: compact ? 6 : 12),
+ Tooltip(
+ message: 'Harness Store ${_keymap.hint('app.store') ?? ''}'
+ .trim(),
+ child: TextButton.icon(
+ key: const ValueKey('swarm-store-button'),
+ onPressed: _openStore,
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.swarmAccent,
+ backgroundColor: Color.alphaBlend(
+ grid.AppPalette.swarmAccent.withValues(alpha: 0.10),
+ grid.AppPalette.swarmField,
+ ),
+ overlayColor: grid.AppPalette.swarmAccent,
+ textStyle: boxMonoStyle(size: 12),
+ minimumSize: const Size(0, 28),
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: StadiumBorder(
+ side: BorderSide(
+ color: grid.AppPalette.swarmAccent.withValues(
+ alpha: 0.12,
+ ),
+ ),
+ ),
+ ),
+ icon: const StoreMark(),
+ label: const Text('Harness Store'),
+ ),
+ ),
+ const SizedBox(width: 6),
],
),
);
},
);
-
- Widget _harnessButton({required bool create, bool compact = false}) {
- final label = create ? 'New Harness' : 'Open Harness';
- final icon = Icon(
- create ? AgentActionIcons.create : AgentActionIcons.open,
- size: 16,
- );
- if (compact) {
- // Same key, same action, same words — carried by the tooltip instead of a label there is no
- // room for. A strip that overflows shows the user nothing at all.
- return Tooltip(
- message: label,
- child: TextButton(
- key: ValueKey(
- create ? 'swarm-new-agent-button' : 'swarm-open-agent-button',
- ),
- onPressed: create ? _newAgent : _addAgent,
- style: TextButton.styleFrom(
- enabledMouseCursor: SystemMouseCursors.click,
- minimumSize: const Size(40, 34),
- padding: const EdgeInsets.symmetric(horizontal: 10),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- backgroundColor: create
- ? grid.AppPalette.swarmAccent
- : Colors.transparent,
- foregroundColor: create
- ? grid.AppPalette.swarmTabBar
- : grid.AppPalette.textPrimary,
- shape: StadiumBorder(
- side: create
- ? BorderSide.none
- : const BorderSide(color: Colors.white24),
- ),
- ),
- child: icon,
- ),
- );
- }
- return TextButton.icon(
- key: ValueKey(
- create ? 'swarm-new-agent-button' : 'swarm-open-agent-button',
- ),
- onPressed: create ? _newAgent : _addAgent,
- style: TextButton.styleFrom(
- enabledMouseCursor: SystemMouseCursors.click,
- minimumSize: const Size(122, 34),
- padding: const EdgeInsets.symmetric(horizontal: 20),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- textStyle: Theme.of(context).textTheme.labelLarge
- ?.copyWith(fontSize: 12, fontWeight: FontWeight.w500),
- backgroundColor: create
- ? grid.AppPalette.swarmAccent
- : Colors.transparent,
- foregroundColor: create
- ? grid.AppPalette.swarmTabBar
- : grid.AppPalette.textPrimary,
- shape: StadiumBorder(
- side: create
- ? BorderSide.none
- : const BorderSide(color: Colors.white24),
- ),
- ),
- icon: icon,
- label: Text(label),
- );
- }
}
/// Hovering or focusing one tab only rebuilds its own controls.
diff --git a/desktop/lib/settings/sections/about_section.dart b/desktop/lib/settings/sections/about_section.dart
index a6124b6f3..800fbcb32 100644
--- a/desktop/lib/settings/sections/about_section.dart
+++ b/desktop/lib/settings/sections/about_section.dart
@@ -1,12 +1,12 @@
import 'package:flutter/material.dart';
-
import '../../core/app_version.dart';
import '../../core/build_identity.dart';
import '../../shared/theme/app_theme.dart' as grid;
import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/skeleton.dart';
import '../../state/app_state.dart';
+import '../../update/desktop_updater.dart';
import '../../widgets/flash_firmware_dialog.dart';
import '../../widgets/update_notice.dart';
@@ -21,9 +21,8 @@ import '../../widgets/update_notice.dart';
/// door — which is what the pane was missing when it was label-and-value text
/// floating on the window.
///
-/// The check runs through [AppNotifier.checkForUpdates] and reports through
-/// [showUpdateCheckDialog] — the same pair the "Check for Updates…" menu item
-/// drives, so the menu and this button can't answer differently. The card's
+/// [checkForUpdatesAndShowResult] is also used by the native menu, so asking
+/// from both places shares a check and a single result dialog. The card's
/// pill is the quiet half of that: the dialog is the answer to a question you
/// asked, the pill is the state you can see without asking.
///
@@ -43,21 +42,8 @@ class AboutSection extends StatefulWidget {
}
class _AboutSectionState extends State<AboutSection> {
- /// Held here rather than on [AppNotifier]: a check started from this button
- /// is this screen's business, and the notifier already carries the state that
- /// outlives it (the update found, the install running, the error).
- bool _checking = false;
-
- Future<void> _check() async {
- setState(() => _checking = true);
- try {
- final result = await widget.notifier.checkForUpdates();
- if (!mounted) return;
- await showUpdateCheckDialog(context, widget.notifier, result);
- } finally {
- if (mounted) setState(() => _checking = false);
- }
- }
+ Future<void> _check() =>
+ checkForUpdatesAndShowResult(context, widget.notifier);
@override
Widget build(BuildContext context) {
@@ -79,14 +65,16 @@ class _AboutSectionState extends State<AboutSection> {
listenable: widget.notifier,
builder: (context, _) => _AboutCard(
notifier: widget.notifier,
- checking: _checking,
+ checking: widget.notifier.isCheckingForUpdate,
onCheck: _check,
),
),
const SizedBox(height: 12),
Text(
- 'OpenHarness checks for a newer build when it starts, and every '
- 'six hours after that.',
+ widget.notifier.updateChecksEnabled
+ ? 'OpenHarness checks for a newer build when it starts, '
+ 'and every six hours after that.'
+ : 'Updates are disabled in this build.',
style: TextStyle(
color: grid.AppPalette.textFaint,
fontSize: 11.5,
@@ -223,7 +211,10 @@ class _VersionLineState extends State<_VersionLine> {
fontFamily: grid.AppFont.mono,
fontFamilyFallback: grid.AppFont.monoFallback,
);
- return Row(
+ return Wrap(
+ spacing: 9,
+ runSpacing: 6,
+ crossAxisAlignment: WrapCrossAlignment.center,
children: [
FutureBuilder<String>(
future: _info,
@@ -241,7 +232,6 @@ class _VersionLineState extends State<_VersionLine> {
return Text(version, style: style);
},
),
- const SizedBox(width: 9),
_StatusPill(state: state),
],
);
@@ -284,12 +274,14 @@ class _StatusPill extends StatelessWidget {
),
),
const SizedBox(width: 6),
- Text(
- state.label,
- style: TextStyle(
- color: state.color,
- fontSize: 11,
- fontWeight: grid.AppFont.medium,
+ Flexible(
+ child: Text(
+ state.label,
+ style: TextStyle(
+ color: state.color,
+ fontSize: 11,
+ fontWeight: grid.AppFont.medium,
+ ),
),
),
],
@@ -321,6 +313,9 @@ class _PillState {
if (notifier.updateError != null) {
return _PillState('Update failed', grid.AppPalette.warn);
}
+ if (checking || notifier.isCheckingForUpdate) {
+ return _PillState('Checking…', grid.AppPalette.textSecondary);
+ }
final update = notifier.availableUpdate;
if (update != null) {
return _PillState(
@@ -329,10 +324,28 @@ class _PillState {
wash: true,
);
}
- if (checking || notifier.isCheckingForUpdate) {
- return _PillState('Checking…', grid.AppPalette.textSecondary);
- }
- return _PillState('Up to date', grid.AppPalette.online);
+ return switch (notifier.lastUpdateCheck?.status) {
+ DesktopUpdateCheckStatus.upToDate => _PillState(
+ 'Up to date',
+ grid.AppPalette.online,
+ ),
+ DesktopUpdateCheckStatus.available => _PillState(
+ 'Update skipped',
+ grid.AppPalette.textSecondary,
+ ),
+ DesktopUpdateCheckStatus.failed => _PillState(
+ 'Check failed',
+ grid.AppPalette.warn,
+ ),
+ DesktopUpdateCheckStatus.disabled => _PillState(
+ 'Updates off',
+ grid.AppPalette.textSecondary,
+ ),
+ null => _PillState(
+ notifier.updateChecksEnabled ? 'Not checked' : 'Updates off',
+ grid.AppPalette.textSecondary,
+ ),
+ };
}
}
@@ -351,27 +364,13 @@ class _CheckRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- return Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: Text(
- 'It updates itself in the background — this is where you can ask '
- 'early.',
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontSize: 12,
- height: 1.45,
- ),
- ),
- ),
- const SizedBox(width: 18),
- OutlinedButton(
- key: const Key('settings-check-updates-button'),
- onPressed: checking ? null : () => onCheck(),
- child: Text(checking ? 'Checking…' : 'Check for updates'),
- ),
- ],
+ return _AboutAction(
+ description: 'Choose when to install a new version.',
+ action: OutlinedButton(
+ key: const Key('settings-check-updates-button'),
+ onPressed: checking ? null : () => onCheck(),
+ child: Text(checking ? 'Checking…' : 'Check for updates'),
+ ),
);
}
}
@@ -384,26 +383,49 @@ class _FlashRow extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- return Row(
- crossAxisAlignment: CrossAxisAlignment.center,
- children: [
- Expanded(
- child: Text(
- 'The hardware dial takes its firmware over USB.',
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontSize: 12,
- height: 1.45,
- ),
- ),
- ),
- const SizedBox(width: 18),
- OutlinedButton(
- key: const Key('settings-flash-firmware-button'),
- onPressed: () => showFlashFirmwareDialog(context),
- child: const Text('Flash dial firmware…'),
- ),
- ],
+ return _AboutAction(
+ description: 'Update your hardware dial over USB.',
+ action: OutlinedButton(
+ key: const Key('settings-flash-firmware-button'),
+ onPressed: () => showFlashFirmwareDialog(context),
+ child: const Text('Flash dial firmware…'),
+ ),
);
}
}
+
+/// Put the action below its explanation when larger text needs the full row.
+class _AboutAction extends StatelessWidget {
+ const _AboutAction({required this.description, required this.action});
+
+ final String description;
+ final Widget action;
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final text = Text(
+ description,
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12,
+ height: 1.45,
+ ),
+ );
+ final scale = MediaQuery.textScalerOf(context).scale(12) / 12;
+ if (constraints.maxWidth < 420 * scale) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [text, const SizedBox(height: 10), action],
+ );
+ }
+ return Row(
+ children: [
+ Expanded(child: text),
+ const SizedBox(width: 18),
+ action,
+ ],
+ );
+ },
+ );
+}
diff --git a/desktop/lib/settings/sections/usage_detail_panels.dart b/desktop/lib/settings/sections/usage_detail_panels.dart
index 5dbe3b3e2..24417856f 100644
--- a/desktop/lib/settings/sections/usage_detail_panels.dart
+++ b/desktop/lib/settings/sections/usage_detail_panels.dart
@@ -6,6 +6,8 @@
/// handed, so the pane can be driven from a fixture.
library;
+import 'dart:math' as math;
+
import 'package:flutter/material.dart';
import '../../shared/theme/app_theme.dart';
@@ -16,6 +18,8 @@ import '../../usage/ledger/usage_report.dart';
/// How many days the bar chart shows. Ten, as Orca uses — enough to see a shape,
/// few enough that each bar keeps a readable label under it.
const _kChartDays = 10;
+const _kChartLabelStyle = TextStyle(fontSize: 9.5, height: 1.3);
+const _kBarHeight = 118.0;
/// The colours the four token buckets keep, everywhere they are drawn.
///
@@ -62,28 +66,60 @@ class UsageDailyChart extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- SizedBox(
- height: 170,
- child: shown.isEmpty
- ? Center(
- child: Text(
- 'Nothing in this range.',
- style: TextStyle(
- fontSize: 12,
- color: AppPalette.textFaint,
- ),
+ if (shown.isEmpty)
+ SizedBox(
+ height: 170,
+ child: Center(
+ child: Text(
+ 'Nothing in this range.',
+ style: TextStyle(fontSize: 12, color: AppPalette.textFaint),
+ ),
+ ),
+ )
+ else
+ LayoutBuilder(
+ builder: (context, constraints) {
+ final painter = TextPainter(
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ maxLines: 1,
+ );
+ final style = DefaultTextStyle.of(context).style
+ .merge(_kChartLabelStyle);
+ var width = 30.0;
+ var labelHeight = 0.0;
+ for (final day in shown) {
+ for (final label in [
+ formatTokens(day.totals.total),
+ _shortDay(day.day),
+ ]) {
+ painter.text = TextSpan(text: label, style: style);
+ painter.layout();
+ width = math.max(width, painter.width + 12);
+ labelHeight = math.max(labelHeight, painter.height);
+ }
+ }
+ painter.dispose();
+ // Keep every label readable at larger text; scroll horizontally
+ // if ten days no longer fit, instead of wrapping under the bars.
+ return SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ child: SizedBox(
+ width: math.max(constraints.maxWidth, width * shown.length),
+ height: math.max(170, _kBarHeight + 9 + labelHeight * 2),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ for (final day in shown)
+ Expanded(
+ child: _Bar(day: day, peak: peak, colours: colours),
+ ),
+ ],
),
- )
- : Row(
- crossAxisAlignment: CrossAxisAlignment.end,
- children: [
- for (final day in shown)
- Expanded(
- child: _Bar(day: day, peak: peak, colours: colours),
- ),
- ],
),
- ),
+ );
+ },
+ ),
const SizedBox(height: 12),
Wrap(
spacing: 14,
@@ -131,14 +167,20 @@ class _Bar extends StatelessWidget {
children: [
Text(
total == 0 ? '' : formatTokens(total),
- style: TextStyle(fontSize: 9.5, color: AppPalette.textFaint),
+ maxLines: 1,
+ softWrap: false,
+ style: _kChartLabelStyle.copyWith(color: AppPalette.textFaint),
),
const SizedBox(height: 4),
SizedBox(
- height: 118,
+ height: _kBarHeight,
child: Column(
mainAxisAlignment: MainAxisAlignment.end,
children: [
+ // Empty space belongs above shorter bars so every day has
+ // the same baseline, just above its date label.
+ if (peak > total)
+ Flexible(flex: peak - total, child: const SizedBox()),
// `Flexible` per segment rather than a fixed height: the
// column is already bounded, so flex shares it in proportion
// and nothing has to be measured against the peak by hand.
@@ -148,17 +190,15 @@ class _Bar extends StatelessWidget {
flex: segment.tokens,
child: Container(color: segment.colour),
),
- // The unused remainder of the tallest bar, so short days sit
- // at the bottom instead of being stretched to full height.
- if (peak > total)
- Flexible(flex: peak - total, child: const SizedBox()),
],
),
),
const SizedBox(height: 5),
Text(
_shortDay(day.day),
- style: TextStyle(fontSize: 9.5, color: AppPalette.textFaint),
+ maxLines: 1,
+ softWrap: false,
+ style: _kChartLabelStyle.copyWith(color: AppPalette.textFaint),
),
],
),
diff --git a/desktop/lib/settings/sections/usage_header.dart b/desktop/lib/settings/sections/usage_header.dart
new file mode 100644
index 000000000..d28ef1607
--- /dev/null
+++ b/desktop/lib/settings/sections/usage_header.dart
@@ -0,0 +1,70 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+
+import '../../shared/theme/app_theme.dart';
+import '../../shared/widgets/app_select_field.dart';
+import '../../usage/ledger/usage_report.dart';
+
+double usageControlWidth(BuildContext context, double width) => math.max(
+ width,
+ width *
+ MediaQuery.textScalerOf(context).scale(AppControl.fontSize) /
+ AppControl.fontSize,
+);
+
+/// Keep the controls together, below the caption when larger text needs room.
+class UsageHeader extends StatelessWidget {
+ const UsageHeader({super.key, required this.title, required this.controls});
+
+ final Widget title;
+ final List<Widget> controls;
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final actions = Wrap(
+ spacing: 4,
+ runSpacing: 8,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: controls,
+ );
+ if (constraints.maxWidth < usageControlWidth(context, 520)) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [title, const SizedBox(height: 10), actions],
+ );
+ }
+ return Row(
+ crossAxisAlignment: CrossAxisAlignment.center,
+ children: [
+ Expanded(child: title),
+ const SizedBox(width: 12),
+ actions,
+ ],
+ );
+ },
+ );
+}
+
+class UsageRangeField extends StatelessWidget {
+ const UsageRangeField({
+ super.key,
+ required this.value,
+ required this.onChanged,
+ });
+
+ final UsageRange value;
+ final ValueChanged<UsageRange> onChanged;
+
+ @override
+ Widget build(BuildContext context) => AppSelectField<UsageRange>(
+ value: value,
+ width: usageControlWidth(context, 150),
+ options: [
+ for (final range in UsageRange.values)
+ SelectOption(value: range, label: range.label),
+ ],
+ onChanged: onChanged,
+ );
+}
diff --git a/desktop/lib/settings/sections/usage_panels.dart b/desktop/lib/settings/sections/usage_panels.dart
index e6b0db747..223ce140c 100644
--- a/desktop/lib/settings/sections/usage_panels.dart
+++ b/desktop/lib/settings/sections/usage_panels.dart
@@ -10,10 +10,48 @@ import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../shared/theme/app_theme.dart';
+import '../../shared/widgets/skeleton.dart';
import '../../stats/harness_stats.dart';
import '../../usage/ledger/ledger_types.dart';
import '../../usage/ledger/usage_overview.dart';
+/// Waiting is distinct from an answered, empty range or a switched-off source.
+class UsageLoadingState extends StatelessWidget {
+ const UsageLoadingState({super.key, required this.message});
+ final String message;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ liveRegion: true,
+ child: Container(
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: AppGlass.surfaceFill,
+ borderRadius: BorderRadius.circular(14),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ message,
+ style: TextStyle(fontSize: 12.5, color: AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 12),
+ const SkeletonText(
+ style: TextStyle(fontSize: 20, height: 1.1),
+ widthFactor: .45,
+ ),
+ const SizedBox(height: 8),
+ const SkeletonText(style: TextStyle(fontSize: 12), widthFactor: .7),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
/// The app's own three counters, and the date they start from.
///
/// Orca's equivalent row is Agents spawned / Time agents worked / PRs created.
@@ -594,45 +632,61 @@ class ProviderUsageRow extends StatelessWidget {
detail,
style: TextStyle(fontSize: 11.5, color: AppPalette.textSecondary),
),
- const SizedBox(height: 10),
- Row(
- children: [
- Expanded(
- child: Text(
- '${formatTokens(ledger.totals.total)} tokens',
- style: TextStyle(fontSize: 12, color: AppPalette.textPrimary),
+ if (state.status == LedgerStatus.scanning && !ledger.hasData) ...[
+ const SizedBox(height: 10),
+ const SkeletonText(
+ style: TextStyle(fontSize: 12),
+ widthFactor: .55,
+ ),
+ ],
+ if (state.enabled &&
+ (state.status == LedgerStatus.ok ||
+ (state.status == LedgerStatus.partial && ledger.hasData) ||
+ (state.status == LedgerStatus.scanning &&
+ ledger.hasData))) ...[
+ const SizedBox(height: 10),
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ '${formatTokens(ledger.totals.total)} tokens',
+ style: TextStyle(
+ fontSize: 12,
+ color: AppPalette.textPrimary,
+ ),
+ ),
),
- ),
- Text(
- formatCost(ledger.costUsd),
- style: TextStyle(
- fontSize: 12,
- color: AppPalette.textPrimary,
- fontFeatures: const [FontFeature.tabularFigures()],
+ Text(
+ formatCost(ledger.costUsd),
+ style: TextStyle(
+ fontSize: 12,
+ color: AppPalette.textPrimary,
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
),
- ),
- ],
- ),
- const SizedBox(height: 8),
- ClipRRect(
- borderRadius: BorderRadius.circular(3),
- child: SizedBox(
- height: 5,
- child: Row(
- children: [
- if (share > 0)
+ ],
+ ),
+ const SizedBox(height: 8),
+ ClipRRect(
+ borderRadius: BorderRadius.circular(3),
+ child: SizedBox(
+ height: 5,
+ child: Row(
+ children: [
+ if (share > 0)
+ Expanded(
+ flex: (share * 1000).round(),
+ child: ColoredBox(color: AppPalette.accent),
+ ),
Expanded(
- flex: (share * 1000).round(),
- child: ColoredBox(color: AppPalette.accent),
+ flex: (1000 - share * 1000).round().clamp(0, 1000),
+ child: ColoredBox(color: AppSurface.recess),
),
- Expanded(
- flex: (1000 - share * 1000).round().clamp(0, 1000),
- child: ColoredBox(color: AppSurface.recess),
- ),
- ],
+ ],
+ ),
),
),
- ),
+ ],
],
),
);
@@ -650,7 +704,9 @@ class ProviderUsageRow extends StatelessWidget {
String? _detail() {
if (!state.enabled) return null;
return switch (state.status) {
- LedgerStatus.scanning => null,
+ LedgerStatus.scanning =>
+ state.hasIncompleteFigures ? state.message : null,
+ LedgerStatus.partial => state.message ?? 'Figures are incomplete.',
LedgerStatus.unavailable ||
LedgerStatus.failed => state.message ?? 'No figures.',
LedgerStatus.disabled => null,
@@ -675,6 +731,7 @@ class _StatusPill extends StatelessWidget {
? state.status
: LedgerStatus.disabled) {
LedgerStatus.ok => ('On', AppPalette.online),
+ LedgerStatus.partial => ('Incomplete', AppPalette.warn),
LedgerStatus.scanning => ('Scanning', AppPalette.accentOnSurface),
LedgerStatus.unavailable => ('Not found', AppPalette.textFaint),
LedgerStatus.failed => ('Failed', AppPalette.warn),
diff --git a/desktop/lib/settings/sections/usage_provider_pane.dart b/desktop/lib/settings/sections/usage_provider_pane.dart
index 829d0495b..fa096eab6 100644
--- a/desktop/lib/settings/sections/usage_provider_pane.dart
+++ b/desktop/lib/settings/sections/usage_provider_pane.dart
@@ -16,13 +16,13 @@ import 'package:flutter/material.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../shared/theme/app_theme.dart';
-import '../../shared/widgets/app_select_field.dart';
import '../../usage/ledger/ledger_types.dart';
import '../../usage/ledger/usage_ledger_store.dart';
import '../../usage/ledger/usage_overview.dart';
import '../../usage/ledger/usage_report.dart';
import 'usage_detail_panels.dart';
import 'usage_panels.dart';
+import 'usage_header.dart';
class UsageProviderPane extends StatefulWidget {
const UsageProviderPane({super.key, required this.store});
@@ -68,9 +68,16 @@ class _UsageProviderPaneState extends State<UsageProviderPane> {
onDisable: () => unawaited(store.setEnabled(false)),
),
const SizedBox(height: 12),
+ if (state.hasIncompleteFigures && report.hasData) ...[
+ _Notice(message: state.message ?? 'Figures are incomplete.'),
+ const SizedBox(height: 12),
+ ],
if (state.status == LedgerStatus.unavailable ||
- state.status == LedgerStatus.failed)
+ state.status == LedgerStatus.failed ||
+ (state.status == LedgerStatus.partial && !report.hasData))
_Notice(message: state.message ?? 'No figures.')
+ else if (state.status == LedgerStatus.scanning && !report.hasData)
+ UsageLoadingState(message: 'Scanning ${provider.label} logs…')
else if (!report.hasData)
_Notice(message: 'No ${provider.label} usage in this range.')
else ...[
@@ -200,42 +207,28 @@ class _Header extends StatelessWidget {
Widget build(BuildContext context) {
AppTheme.watch(context);
final scanning = state.status == LedgerStatus.scanning;
- return Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- '${provider.label} usage',
- style: Theme.of(context).textTheme.titleSmall,
- ),
- const SizedBox(height: 2),
- Text(
- // The range is named here as well as in the picker, because the
- // figures below mean nothing without it and the picker is a
- // control the eye skips.
- 'All local ${provider.label} usage · ${range.label}',
- style: TextStyle(
- fontSize: 11.5,
- color: AppPalette.textSecondary,
- ),
- ),
- ],
+ return UsageHeader(
+ title: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '${provider.label} usage',
+ style: Theme.of(context).textTheme.titleSmall,
),
- ),
- const SizedBox(width: 12),
- AppSelectField<UsageRange>(
- value: range,
- width: 150,
- options: [
- for (final option in UsageRange.values)
- SelectOption(value: option, label: option.label),
- ],
- onChanged: onRangeChanged,
- ),
- const SizedBox(width: 4),
+ const SizedBox(height: 2),
+ Text(
+ // The range is named here as well as in the picker, because the
+ // figures below mean nothing without it and the picker is a
+ // control the eye skips.
+ scanning
+ ? '${range.label} · Scanning local logs…'
+ : 'All local ${provider.label} usage · ${range.label}',
+ style: TextStyle(fontSize: 11.5, color: AppPalette.textSecondary),
+ ),
+ ],
+ ),
+ controls: [
+ UsageRangeField(value: range, onChanged: onRangeChanged),
IconButton(
onPressed: scanning ? null : onRefresh,
iconSize: 15,
diff --git a/desktop/lib/settings/sections/usage_section.dart b/desktop/lib/settings/sections/usage_section.dart
index 511f2b2a4..ae916ee58 100644
--- a/desktop/lib/settings/sections/usage_section.dart
+++ b/desktop/lib/settings/sections/usage_section.dart
@@ -35,6 +35,7 @@ import '../../usage/ledger/usage_ledger_controller.dart';
import '../../usage/ledger/usage_overview.dart';
import '../../usage/ledger/usage_report.dart';
import 'usage_panels.dart';
+import 'usage_header.dart';
import 'usage_provider_pane.dart';
/// What the overview opens on — the last 30 days, which is what Orca's default
@@ -120,9 +121,8 @@ class _UsageSectionState extends State<UsageSection> {
return SectionScaffold(
title: 'Usage',
subtitle:
- 'What this app has done, and what the agent CLIs on this computer '
- 'have spent. Agents running on other machines are not included, and '
- 'nothing here is sent anywhere.',
+ 'Activity and token usage on this computer. '
+ 'Remote machines aren’t included.',
child: ListenableBuilder(
// Both halves, so the stats cards move as agents start and stop while
// the screen is open.
@@ -133,11 +133,6 @@ class _UsageSectionState extends State<UsageSection> {
}
Widget _body(BuildContext context) {
- final overview = _controller.overviewFor(_range);
- final states = {
- for (final state in _controller.scanStates) state.provider: state,
- };
-
return ListView(
padding: EdgeInsets.zero,
children: [
@@ -148,69 +143,120 @@ class _UsageSectionState extends State<UsageSection> {
onLensChanged: (lens) => setState(() => _lens = lens),
),
const SizedBox(height: 12),
- if (_lens case final provider?)
+ if (_controller.loading)
+ const UsageLoadingState(message: 'Reading usage settings…')
+ else if (_lens case final provider?)
UsageProviderPane(store: _controller.storeFor(provider))
- else ...[
- // One card around the whole overview, as Orca draws it: the heading,
- // the four figures and the two panels are one answer, and the panels
- // inside it are the parts of that answer rather than peers of it.
- _OverviewCard(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- _OverviewHeader(
- overview: overview,
- range: _range,
- isScanning: _controller.isScanning,
- onRangeChanged: (range) => setState(() => _range = range),
- onRefresh: overview.enabledCount == 0
- ? null
- : () => unawaited(_controller.refresh(force: true)),
+ else
+ _overview(),
+ ],
+ );
+ }
+
+ Widget _overview() {
+ final overview = _controller.overviewFor(_range);
+ final states = {
+ for (final state in _controller.scanStates) state.provider: state,
+ };
+
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // One card around the whole overview, as Orca draws it: the heading,
+ // the four figures and the two panels are one answer, and the panels
+ // inside it are the parts of that answer rather than peers of it.
+ _OverviewCard(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _OverviewHeader(
+ overview: overview,
+ range: _range,
+ isScanning: _controller.isScanning,
+ onRangeChanged: (range) => setState(() => _range = range),
+ onRefresh: overview.enabledCount == 0
+ ? null
+ : () => unawaited(_controller.refresh(force: true)),
+ ),
+ const SizedBox(height: 14),
+ if (states.values.any((state) => state.hasIncompleteFigures)) ...[
+ Text(
+ 'Some usage could not be read. Totals are incomplete.',
+ style: TextStyle(fontSize: 12.5, color: AppPalette.warn),
),
- const SizedBox(height: 14),
- if (overview.enabledCount == 0)
- UsageEmptyState(onEnable: _enable)
- else ...[
- _cards(overview),
- if (overview.hasUnpricedModel)
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: Text(
- 'The cost is a lower bound because some model prices are unavailable.',
- style: TextStyle(
- fontSize: 11.5,
- color: AppPalette.textSecondary,
- ),
+ const SizedBox(height: 12),
+ ],
+ if (overview.enabledCount == 0)
+ UsageEmptyState(onEnable: _enable)
+ else if (_controller.isScanning && !overview.hasAnyData)
+ const UsageLoadingState(message: 'Scanning local logs…')
+ else if (!overview.hasAnyData &&
+ states.values.any(
+ (state) =>
+ state.enabled &&
+ (state.status == LedgerStatus.failed ||
+ state.status == LedgerStatus.partial ||
+ state.status == LedgerStatus.unavailable),
+ ))
+ Text(
+ 'No figures available.',
+ style: TextStyle(
+ fontSize: 12.5,
+ color: AppPalette.textSecondary,
+ ),
+ )
+ else ...[
+ _cards(overview),
+ if (overview.hasUnpricedModel)
+ Padding(
+ padding: const EdgeInsets.only(top: 8),
+ child: Text(
+ 'The cost is a lower bound because some model prices are unavailable.',
+ style: TextStyle(
+ fontSize: 11.5,
+ color: AppPalette.textSecondary,
),
),
- if (overview.hasAnyData) ...[
- const SizedBox(height: 12),
- _PanelPair(
- intensity: DailyIntensityGrid(
- days: recentDays(overview.days, _kGridDayCount),
- busiest: overview.bestDay,
- ),
- mix: TokenMixBar(totals: overview.totals),
+ ),
+ if (overview.hasAnyData) ...[
+ const SizedBox(height: 12),
+ _PanelPair(
+ intensity: DailyIntensityGrid(
+ days: recentDays(overview.days, _kGridDayCount),
+ busiest: overview.bestDay,
),
- ],
+ mix: TokenMixBar(totals: overview.totals),
+ ),
],
],
- ),
+ ],
),
- const SizedBox(height: 18),
- _ProvidersHeading(overview: overview),
- const SizedBox(height: 10),
- for (final ledger in overview.providers) ...[
- ProviderUsageRow(
- ledger: ledger,
- state:
- states[ledger.provider] ??
- LedgerScanState(provider: ledger.provider),
- grandTotal: overview.totals.total,
- onToggle: (enabled) => _toggle(ledger.provider, enabled),
- ),
- const SizedBox(height: 8),
- ],
+ ),
+ const SizedBox(height: 18),
+ _ProvidersHeading(
+ overview: overview,
+ hasFigures:
+ overview.hasAnyData ||
+ states.values.any(
+ (state) =>
+ state.enabled &&
+ (state.status == LedgerStatus.ok ||
+ (state.status == LedgerStatus.scanning &&
+ state.lastScanAt != null &&
+ !state.hasIncompleteFigures)),
+ ),
+ ),
+ const SizedBox(height: 10),
+ for (final ledger in overview.providers) ...[
+ ProviderUsageRow(
+ ledger: ledger,
+ state:
+ states[ledger.provider] ??
+ LedgerScanState(provider: ledger.provider),
+ grandTotal: overview.totals.total,
+ onToggle: (enabled) => _toggle(ledger.provider, enabled),
+ ),
+ const SizedBox(height: 8),
],
],
);
@@ -341,17 +387,15 @@ class _AnalyticsHeader extends StatelessWidget {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- return Row(
- children: [
- Expanded(
- child: Text(
- 'Usage analytics',
- style: Theme.of(context).textTheme.titleSmall,
- ),
- ),
+ return UsageHeader(
+ title: Text(
+ 'Usage analytics',
+ style: Theme.of(context).textTheme.titleSmall,
+ ),
+ controls: [
AppSelectField<_Lens>(
value: lens,
- width: 168,
+ width: usageControlWidth(context, 168),
options: [
const SelectOption<_Lens>(value: null, label: 'Overview'),
for (final provider in LedgerProvider.values)
@@ -386,42 +430,23 @@ class _OverviewHeader extends StatelessWidget {
@override
Widget build(BuildContext context) {
AppTheme.watch(context);
- return Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'Usage overview',
- style: Theme.of(context).textTheme.titleSmall,
- ),
- const SizedBox(height: 2),
- Text(
- _updatedLine(),
- style: TextStyle(
- fontSize: 11.5,
- color: AppPalette.textSecondary,
- ),
- ),
- ],
+ return UsageHeader(
+ title: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Usage overview', style: Theme.of(context).textTheme.titleSmall),
+ const SizedBox(height: 2),
+ Text(
+ _updatedLine(),
+ style: TextStyle(fontSize: 11.5, color: AppPalette.textSecondary),
),
- ),
- const SizedBox(width: 12),
+ ],
+ ),
+ controls: [
// The same control a provider's pane carries, so the two ranges are
// plainly the same kind of thing rather than one screen having a window
// and the other a hidden constant.
- AppSelectField<UsageRange>(
- value: range,
- width: 150,
- options: [
- for (final option in UsageRange.values)
- SelectOption(value: option, label: option.label),
- ],
- onChanged: onRangeChanged,
- ),
- const SizedBox(width: 4),
+ UsageRangeField(value: range, onChanged: onRangeChanged),
IconButton(
onPressed: isScanning ? null : onRefresh,
iconSize: 15,
@@ -440,8 +465,9 @@ class _OverviewHeader extends StatelessWidget {
String _updatedLine() {
if (overview.enabledCount == 0) return 'Nothing is being read yet.';
+ if (isScanning) return '${range.label} · Scanning local logs…';
final at = overview.lastScanAt;
- if (at == null) return 'Not scanned yet.';
+ if (at == null) return 'No scan available.';
return '${range.label} · updated ${_stamp(at)}';
}
@@ -456,9 +482,10 @@ class _OverviewHeader extends StatelessWidget {
}
class _ProvidersHeading extends StatelessWidget {
- const _ProvidersHeading({required this.overview});
+ const _ProvidersHeading({required this.overview, required this.hasFigures});
final UsageOverview overview;
+ final bool hasFigures;
@override
Widget build(BuildContext context) {
@@ -476,8 +503,8 @@ class _ProvidersHeading extends StatelessWidget {
// Two different counts on purpose: a provider can be on and have
// nothing to show, and collapsing the two is what makes an empty
// panel impossible to read.
- '${overview.enabledCount} enabled · '
- '${overview.dataProviderCount} with data',
+ '${overview.enabledCount} enabled'
+ '${hasFigures ? ' · ${overview.dataProviderCount} with data' : ''}',
style: TextStyle(
fontSize: 11.5,
color: AppPalette.textSecondary,
@@ -486,11 +513,12 @@ class _ProvidersHeading extends StatelessWidget {
],
),
),
- Text(
- '${overview.sessionCount} '
- '${overview.sessionCount == 1 ? 'session' : 'sessions'}',
- style: TextStyle(fontSize: 11.5, color: AppPalette.textFaint),
- ),
+ if (hasFigures)
+ Text(
+ '${overview.sessionCount} '
+ '${overview.sessionCount == 1 ? 'session' : 'sessions'}',
+ style: TextStyle(fontSize: 11.5, color: AppPalette.textFaint),
+ ),
],
);
}
diff --git a/desktop/lib/settings/settings_nav.dart b/desktop/lib/settings/settings_nav.dart
index 825a96636..f02913923 100644
--- a/desktop/lib/settings/settings_nav.dart
+++ b/desktop/lib/settings/settings_nav.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/layouts/widgets/rail_section_header.dart';
@@ -25,9 +26,56 @@ class SettingsNav extends StatefulWidget {
class _SettingsNavState extends State<SettingsNav> {
String _query = '';
+ final _search = TextEditingController();
+ final _searchFocus = FocusNode(debugLabel: 'Search settings');
+
+ @override
+ void dispose() {
+ _search.dispose();
+ _searchFocus.dispose();
+ super.dispose();
+ }
+
+ bool get _composing =>
+ _search.value.composing.isValid && !_search.value.composing.isCollapsed;
+
+ void _chooseMatch() {
+ if (_composing || _query.trim().isEmpty) return;
+ final match = _visible.expand((group) => group.sections).firstOrNull;
+ if (match != null) widget.onSelect(match);
+ }
+
+ KeyEventResult _searchKey(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final keys = HardwareKeyboard.instance;
+ if (keys.isControlPressed ||
+ keys.isMetaPressed ||
+ keys.isAltPressed ||
+ keys.isShiftPressed) {
+ return KeyEventResult.ignored;
+ }
+ final key = event.logicalKey;
+ final enter =
+ key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter;
+ final down = key == LogicalKeyboardKey.arrowDown;
+ final up = key == LogicalKeyboardKey.arrowUp;
+ if (!enter && !down && !up) return KeyEventResult.ignored;
+ if (_composing) return KeyEventResult.skipRemainingHandlers;
+ if (enter) {
+ if (event is KeyDownEvent) _chooseMatch();
+ } else if (down) {
+ if (_visible.isNotEmpty) _searchFocus.nextFocus();
+ } else {
+ _searchFocus.previousFocus();
+ }
+ return KeyEventResult.handled;
+ }
/// The groups, narrowed to the query. Matching is a plain case-insensitive
- /// substring of the label — this list is four rows, so anything cleverer
+ /// substring of the label — this list is short, so anything cleverer
/// would be machinery no one can feel. A group's own title matches too, so
/// typing "help" surfaces the whole run rather than nothing.
List<SettingsGroup> get _visible {
@@ -78,7 +126,16 @@ class _SettingsNavState extends State<SettingsNav> {
onTap: () => Navigator.of(context).maybePop(),
),
const SizedBox(height: 8),
- _SearchField(onChanged: (value) => setState(() => _query = value)),
+ Focus(
+ onKeyEvent: _searchKey,
+ skipTraversal: true,
+ child: _SearchField(
+ controller: _search,
+ focusNode: _searchFocus,
+ onChanged: (value) => setState(() => _query = value),
+ onSubmitted: (_) => _chooseMatch(),
+ ),
+ ),
const SizedBox(height: 2),
Expanded(child: _navList()),
],
@@ -111,9 +168,17 @@ class _SettingsNavState extends State<SettingsNav> {
/// The rail's filter, styled like the machine rail's own — the app has one
/// shape for "narrow this list".
class _SearchField extends StatelessWidget {
- const _SearchField({required this.onChanged});
+ const _SearchField({
+ required this.controller,
+ required this.focusNode,
+ required this.onChanged,
+ required this.onSubmitted,
+ });
+ final TextEditingController controller;
+ final FocusNode focusNode;
final ValueChanged<String> onChanged;
+ final ValueChanged<String> onSubmitted;
@override
Widget build(BuildContext context) {
@@ -124,10 +189,16 @@ class _SearchField extends StatelessWidget {
// Keyed because the Appearance pane now carries fields of its own, so a
// test reaching for "the" TextField would find three.
key: const Key('settings-search-field'),
+ controller: controller,
+ focusNode: focusNode,
+ autofocus: true,
onChanged: onChanged,
+ onSubmitted: onSubmitted,
+ onEditingComplete: () {},
+ textInputAction: TextInputAction.search,
style: grid.kFieldTextStyle,
decoration: InputDecoration(
- hintText: 'search settings',
+ hintText: 'Search settings',
prefixIcon: Icon(
LucideIcons.search300,
size: grid.kFieldIconSize,
diff --git a/desktop/lib/settings/settings_screen.dart b/desktop/lib/settings/settings_screen.dart
index 8b5faa23a..e8235d879 100644
--- a/desktop/lib/settings/settings_screen.dart
+++ b/desktop/lib/settings/settings_screen.dart
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../analytics/analytics.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -78,6 +79,30 @@ class _SettingsScreenState extends State<SettingsScreen> {
late SettingsSection _section =
widget.initialSection ?? kDefaultSettingsSection;
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent ||
+ event.logicalKey != LogicalKeyboardKey.escape ||
+ HardwareKeyboard.instance.isControlPressed ||
+ HardwareKeyboard.instance.isAltPressed ||
+ HardwareKeyboard.instance.isMetaPressed ||
+ HardwareKeyboard.instance.isShiftPressed ||
+ ModalRoute.of(context)?.isCurrent == false) {
+ return KeyEventResult.ignored;
+ }
+ final editing = FocusManager.instance.primaryFocus?.context
+ ?.findAncestorStateOfType<EditableTextState>()
+ ?.widget
+ .controller
+ .value;
+ if (editing != null &&
+ editing.composing.isValid &&
+ !editing.composing.isCollapsed) {
+ return KeyEventResult.skipRemainingHandlers;
+ }
+ Navigator.of(context).maybePop();
+ return KeyEventResult.handled;
+ }
+
@override
void initState() {
super.initState();
@@ -109,31 +134,34 @@ class _SettingsScreenState extends State<SettingsScreen> {
// runs from y=0 — under the macOS traffic lights included. A header across
// the top would have to carry the rail's fill over the pane as well, which
// is what leaves the top of a window reading as a separate, lighter band.
- return Scaffold(
- backgroundColor: grid.AppPalette.windowBg,
- body: Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- SettingsNav(section: _section, onSelect: _show),
- VerticalDivider(width: 1, color: grid.AppPalette.divider),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- // The pane needs the traffic lights' clearance and somewhere to
- // grab the window, but no fill of its own — it sits on the
- // window. The rail draws its own.
- const WindowDragStrip(),
- Expanded(
- child: _SettingsBody(
- section: _section,
- notifier: widget.notifier,
+ return Focus(
+ onKeyEvent: _key,
+ child: Scaffold(
+ backgroundColor: grid.AppPalette.windowBg,
+ body: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SettingsNav(section: _section, onSelect: _show),
+ VerticalDivider(width: 1, color: grid.AppPalette.divider),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ // The pane needs the traffic lights' clearance and somewhere to
+ // grab the window, but no fill of its own — it sits on the
+ // window. The rail draws its own.
+ const WindowDragStrip(),
+ Expanded(
+ child: _SettingsBody(
+ section: _section,
+ notifier: widget.notifier,
+ ),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
);
}
diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dart
index 7c75e3954..9eca2d93e 100644
--- a/desktop/lib/shared/theme/app_theme.dart
+++ b/desktop/lib/shared/theme/app_theme.dart
@@ -189,6 +189,8 @@ class _PaletteScope extends InheritedNotifier<ValueNotifier<HarnessPalette>> {
abstract final class AppPalette {
// Approved Swarms canvas and native tab-strip palette.
static Color get swarmField => AppTheme.palette.value.workspace;
+ // The welcome illustration recedes behind the working command dock.
+ static Color get swarmWelcome => const Color(0xff171717);
static Color get swarmTabBar => AppTheme.palette.value.tabBar;
static Color get swarmAccent => AppTheme.palette.value.accent;
// Shared with the native search field for a continuous input/results surface.
diff --git a/desktop/lib/shared/theme/appearance_prefs_store.dart b/desktop/lib/shared/theme/appearance_prefs_store.dart
index 5ae74cdba..557bb8429 100644
--- a/desktop/lib/shared/theme/appearance_prefs_store.dart
+++ b/desktop/lib/shared/theme/appearance_prefs_store.dart
@@ -1,3 +1,5 @@
+import 'dart:convert';
+
import 'package:flutter/foundation.dart';
import '../../core/harness_file_store.dart';
@@ -5,6 +7,7 @@ import '../../core/local_key_value_store.dart';
import 'app_theme.dart';
import 'color_palette.dart';
import 'harness_background.dart';
+import 'prompt_style.dart';
/// The app's coordinated palette and UI typography on this computer.
///
@@ -21,8 +24,10 @@ class AppearancePrefs {
this.uiSize = uiSizeDefault,
this.palette = HarnessPalette.graphite,
this.background = HarnessBackground.plain,
+ this.prompt = const PromptPrefs(),
});
+ final PromptPrefs prompt;
final HarnessPalette palette;
final HarnessBackground background;
@@ -56,12 +61,14 @@ class AppearancePrefs {
double? uiSize,
HarnessPalette? palette,
HarnessBackground? background,
+ PromptPrefs? prompt,
bool clearUiFamily = false,
}) => AppearancePrefs(
uiFamily: clearUiFamily ? null : (uiFamily ?? this.uiFamily),
uiSize: uiSize ?? this.uiSize,
palette: palette ?? this.palette,
background: background ?? this.background,
+ prompt: prompt ?? this.prompt,
);
@override
@@ -70,10 +77,12 @@ class AppearancePrefs {
other.uiFamily == uiFamily &&
other.uiSize == uiSize &&
other.palette == palette &&
- other.background == background;
+ other.background == background &&
+ other.prompt == prompt;
@override
- int get hashCode => Object.hash(uiFamily, uiSize, palette, background);
+ int get hashCode =>
+ Object.hash(uiFamily, uiSize, palette, background, prompt);
}
/// The user's appearance choices, remembered across launches.
@@ -92,6 +101,8 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
static const _sizeKey = 'app_ui_font_size';
static const _paletteKey = 'app_color_palette';
static const _backgroundKey = 'harness_start_background';
+ static const _promptKey = 'workspace_prompt_v1';
+ Future<void>? _promptSave;
Future<void>? _paletteSave;
Future<void>? _backgroundSave;
@@ -109,12 +120,14 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
_sizeKey,
_paletteKey,
_backgroundKey,
+ _promptKey,
]);
value = AppearancePrefs(
uiFamily: _familyFrom(saved[_familyKey]),
uiSize: _sizeFrom(saved[_sizeKey]),
palette: HarnessPalette.fromId(saved[_paletteKey]),
background: HarnessBackground.fromId(saved[_backgroundKey]),
+ prompt: _promptFrom(saved[_promptKey]),
);
} catch (_) {
value = const AppearancePrefs();
@@ -165,6 +178,34 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
}
}
+ static PromptPrefs _promptFrom(String? raw) {
+ try {
+ return PromptPrefs.fromJson(raw == null ? null : jsonDecode(raw));
+ } catch (_) {
+ return const PromptPrefs();
+ }
+ }
+
+ Future<void> setPrompt(PromptPrefs prompt) {
+ if (value.prompt == prompt) return _promptSave ?? Future.value();
+ value = value.copyWith(prompt: prompt);
+ return _promptSave ??= _savePrompt();
+ }
+
+ Future<void> _savePrompt() async {
+ try {
+ while (true) {
+ final prefs = value.prompt;
+ await _storage.write(_promptKey, jsonEncode(prefs.toJson()));
+ if (value.prompt == prefs) break;
+ }
+ } catch (_) {
+ // Keep the preview usable for this run if storage is unavailable.
+ } finally {
+ _promptSave = null;
+ }
+ }
+
/// Choose a face, or pass `null` for the system font.
Future<void> setUiFamily(String? family) async {
final next = _familyFrom(family);
@@ -202,11 +243,13 @@ class AppearancePrefsStore extends ValueNotifier<AppearancePrefs> {
value = const AppearancePrefs();
await _paletteSave;
await _backgroundSave;
+ await _promptSave;
try {
await _storage.delete(_familyKey);
await _storage.delete(_sizeKey);
await _storage.delete(_paletteKey);
await _storage.delete(_backgroundKey);
+ await _storage.delete(_promptKey);
} catch (_) {
// See above.
}
diff --git a/desktop/lib/shared/theme/prompt_style.dart b/desktop/lib/shared/theme/prompt_style.dart
new file mode 100644
index 000000000..b61395b4a
--- /dev/null
+++ b/desktop/lib/shared/theme/prompt_style.dart
@@ -0,0 +1,88 @@
+import 'package:flutter/foundation.dart';
+
+const kHarnessPromptMarker = '>_';
+
+enum PromptStyle {
+ plain('Plain', 'ASCII markers, quiet and compact'),
+ symbols('Symbols', 'Harness, machine, folder and branch marks'),
+ powerline('Powerline', 'Joined segments, like a shell prompt');
+
+ const PromptStyle(this.label, this.description);
+ final String label, description;
+
+ static PromptStyle fromId(String? id) =>
+ values.where((style) => style.name == id).firstOrNull ?? symbols;
+}
+
+@immutable
+class PromptPrefs {
+ const PromptPrefs({
+ this.style = PromptStyle.symbols,
+ this.color = true,
+ this.machine = true,
+ this.project = true,
+ this.branch = true,
+ });
+
+ final PromptStyle style;
+ final bool color, machine, project, branch;
+
+ PromptPrefs copyWith({
+ PromptStyle? style,
+ bool? color,
+ bool? machine,
+ bool? project,
+ bool? branch,
+ }) => PromptPrefs(
+ style: style ?? this.style,
+ color: color ?? this.color,
+ machine: machine ?? this.machine,
+ project: project ?? this.project,
+ branch: branch ?? this.branch,
+ );
+
+ Map<String, Object> toJson() => {
+ 'style': style.name,
+ 'color': color,
+ 'machine': machine,
+ 'project': project,
+ 'branch': branch,
+ };
+
+ factory PromptPrefs.fromJson(Object? json) {
+ if (json is! Map) return const PromptPrefs();
+ bool flag(String key) => json[key] is bool ? json[key] as bool : true;
+ return PromptPrefs(
+ style: PromptStyle.fromId(json['style'] is String ? json['style'] : null),
+ color: flag('color'),
+ machine: flag('machine'),
+ project: flag('project'),
+ branch: flag('branch'),
+ );
+ }
+
+ @override
+ bool operator ==(Object other) =>
+ other is PromptPrefs &&
+ other.style == style &&
+ other.color == color &&
+ other.machine == machine &&
+ other.project == project &&
+ other.branch == branch;
+
+ @override
+ int get hashCode => Object.hash(style, color, machine, project, branch);
+}
+
+/// Identity supplied by the catalog, never inferred by parsing display text.
+@immutable
+class PromptContext {
+ const PromptContext({
+ this.harness,
+ this.machine,
+ this.project,
+ this.branch,
+ this.leading,
+ });
+ final String? harness, machine, project, branch, leading;
+}
diff --git a/desktop/lib/shared/widgets/app_choice_picker.dart b/desktop/lib/shared/widgets/app_choice_picker.dart
index a80e244e3..a03798652 100644
--- a/desktop/lib/shared/widgets/app_choice_picker.dart
+++ b/desktop/lib/shared/widgets/app_choice_picker.dart
@@ -24,6 +24,7 @@ class AppChoicePicker<T> extends StatefulWidget {
this.compact = false,
this.tileSize,
this.notifyOnReselect = false,
+ this.terminalStyle = false,
});
final T value;
@@ -50,6 +51,7 @@ class AppChoicePicker<T> extends StatefulWidget {
final bool compact;
final Size? tileSize;
final bool notifyOnReselect;
+ final bool terminalStyle;
@override
State<AppChoicePicker<T>> createState() => _AppChoicePickerState<T>();
@@ -273,10 +275,11 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
final size = widget.tileSize!;
return Wrap(
spacing: AppChoiceTile.gap,
- runSpacing: AppChoiceTile.gap,
+ runSpacing: widget.terminalStyle ? 2 : AppChoiceTile.gap,
children: [
for (final option in ordered.take(3))
AppChoiceTile(
+ terminalStyle: widget.terminalStyle,
key: widget.optionKey(option.value),
size: size,
label: option.label,
@@ -291,21 +294,32 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
inMutuallyExclusiveGroup: true,
child: AppSelectField<T>(
key: widget.moreKey,
+ textStyle: widget.terminalStyle
+ ? DefaultTextStyle.of(context).style
+ : null,
+ radius: widget.terminalStyle ? 2 : null,
value: widget.value,
options: _overflowOrder(ordered.skip(3)),
onChanged: _choose,
filterable: true,
width: size.width,
height: size.height,
- padding: AppChoiceTile.padding,
+ padding: widget.terminalStyle
+ ? AppChoiceTile.terminalPadding
+ : AppChoiceTile.padding,
selected: selectedExtra,
fillColor: selectedExtra
? AppPalette.swarmAccent.withValues(alpha: .16)
+ : widget.terminalStyle
+ ? Colors.transparent
: AppSurface.recess,
trigger: AppChoiceTileContent(
+ terminalStyle: widget.terminalStyle,
label: extra?.label ?? widget.moreLabel,
detail: extra?.detail,
- leading: extra == null
+ leading: widget.terminalStyle
+ ? Text(selectedExtra ? '>' : ' ')
+ : extra == null
? widget.moreLeading
: extra.leading?.call(),
trailing: const Icon(Icons.keyboard_arrow_down, size: 18),
@@ -415,6 +429,10 @@ class _AppChoicePickerState<T> extends State<AppChoicePicker<T>> {
class AppChoiceTile extends StatelessWidget {
static const double gap = 12;
static const padding = EdgeInsets.symmetric(horizontal: 18, vertical: 16);
+ static const terminalPadding = EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 4,
+ );
const AppChoiceTile({
super.key,
@@ -425,6 +443,7 @@ class AppChoiceTile extends StatelessWidget {
this.leading,
this.selected = false,
this.focusNode,
+ this.terminalStyle = false,
});
final Size size;
final String label;
@@ -433,6 +452,7 @@ class AppChoiceTile extends StatelessWidget {
final bool selected;
final VoidCallback? onPressed;
final FocusNode? focusNode;
+ final bool terminalStyle;
@override
Widget build(BuildContext context) => SizedBox(
@@ -449,24 +469,36 @@ class AppChoiceTile extends StatelessWidget {
foregroundColor: AppPalette.textPrimary,
backgroundColor: selected
? AppPalette.swarmAccent.withValues(alpha: .16)
+ : terminalStyle
+ ? Colors.transparent
: AppSurface.recess,
- padding: padding,
+ padding: terminalStyle ? terminalPadding : padding,
+ textStyle: terminalStyle
+ ? DefaultTextStyle.of(context).style
+ : null,
+ minimumSize: terminalStyle ? Size.zero : null,
+ tapTargetSize: terminalStyle
+ ? MaterialTapTargetSize.shrinkWrap
+ : null,
shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AppControl.radius),
+ borderRadius: BorderRadius.circular(
+ terminalStyle ? 2 : AppControl.radius,
+ ),
),
).copyWith(
side: WidgetStateProperty.resolveWith(
(states) => BorderSide(
- color: selected
+ color: selected && !terminalStyle
? AppPalette.swarmAccent.withValues(alpha: .7)
: Colors.transparent,
),
),
),
child: AppChoiceTileContent(
+ terminalStyle: terminalStyle,
label: label,
detail: detail,
- leading: leading,
+ leading: terminalStyle ? Text(selected ? '>' : ' ') : leading,
),
),
),
@@ -480,10 +512,12 @@ class AppChoiceTileContent extends StatelessWidget {
this.detail,
this.leading,
this.trailing,
+ this.terminalStyle = false,
});
final String label;
final String? detail;
final Widget? leading, trailing;
+ final bool terminalStyle;
/// The name's type, and the detail's under it. Written down because the tile
/// height is arithmetic over exactly these numbers — see [linesFor] and the
@@ -528,6 +562,52 @@ class AppChoiceTileContent extends StatelessWidget {
@override
Widget build(BuildContext context) {
+ if (terminalStyle) {
+ final style = DefaultTextStyle.of(context).style.copyWith(
+ fontSize: 13,
+ height: 1.35,
+ fontWeight: FontWeight.w400,
+ color: AppPalette.textPrimary,
+ );
+ return DefaultTextStyle.merge(
+ style: style,
+ child: Row(
+ children: [
+ SizedBox(width: 22, child: leading),
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ flex: 3,
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ if (detail != null) ...[
+ const SizedBox(width: 12),
+ Flexible(
+ flex: 5,
+ child: Text(
+ detail!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: style.copyWith(
+ fontSize: 12,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ if (trailing != null) ...[const SizedBox(width: 8), trailing!],
+ ],
+ ),
+ );
+ }
final labelStyle = TextStyle(
fontFamily: AppFont.sans,
fontFamilyFallback: AppFont.sansFallback,
diff --git a/desktop/lib/shared/widgets/app_menu.dart b/desktop/lib/shared/widgets/app_menu.dart
index ac97e2d95..732893f87 100644
--- a/desktop/lib/shared/widgets/app_menu.dart
+++ b/desktop/lib/shared/widgets/app_menu.dart
@@ -126,6 +126,7 @@ class AppMenuItem extends StatefulWidget {
this.trailing,
this.focusNode,
this.metrics = AppMenuRowMetrics.compact,
+ this.textStyle,
});
/// The leading glyph. Null for a row in a list that PICKS one of several — the
@@ -171,6 +172,7 @@ class AppMenuItem extends StatefulWidget {
/// Which of the two row sizes this is. Defaults to a context menu's; a picker
/// passes [AppMenuRowMetrics.roomy].
final AppMenuRowMetrics metrics;
+ final TextStyle? textStyle;
/// This row is the current choice.
///
@@ -265,8 +267,11 @@ class _AppMenuItemState extends State<AppMenuItem> {
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: widget.danger ? error : AppPalette.textPrimary,
- fontFamily: AppFont.sans,
- fontFamilyFallback: AppFont.sansFallback,
+ fontFamily:
+ widget.textStyle?.fontFamily ?? AppFont.sans,
+ fontFamilyFallback:
+ widget.textStyle?.fontFamilyFallback ??
+ AppFont.sansFallback,
fontSize: widget.metrics.fontSize,
height: 1.2,
fontWeight: widget.selected
@@ -282,8 +287,11 @@ class _AppMenuItemState extends State<AppMenuItem> {
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: AppPalette.textSecondary,
- fontFamily: AppFont.sans,
- fontFamilyFallback: AppFont.sansFallback,
+ fontFamily:
+ widget.textStyle?.fontFamily ?? AppFont.sans,
+ fontFamilyFallback:
+ widget.textStyle?.fontFamilyFallback ??
+ AppFont.sansFallback,
fontSize: widget.metrics.noteSize,
height: 1.25,
),
@@ -301,8 +309,11 @@ class _AppMenuItemState extends State<AppMenuItem> {
overflow: TextOverflow.ellipsis,
style: TextStyle(
color: AppPalette.textFaint,
- fontFamily: AppFont.sans,
- fontFamilyFallback: AppFont.sansFallback,
+ fontFamily:
+ widget.textStyle?.fontFamily ?? AppFont.sans,
+ fontFamilyFallback:
+ widget.textStyle?.fontFamilyFallback ??
+ AppFont.sansFallback,
fontSize: widget.metrics.noteSize,
height: 1.2,
),
diff --git a/desktop/lib/shared/widgets/app_select_field.dart b/desktop/lib/shared/widgets/app_select_field.dart
index 1b6773487..81ed43b38 100644
--- a/desktop/lib/shared/widgets/app_select_field.dart
+++ b/desktop/lib/shared/widgets/app_select_field.dart
@@ -83,6 +83,8 @@ class AppSelectField<T> extends StatefulWidget {
this.emptyLabel,
this.filterable = false,
this.filterThreshold = 8,
+ this.textStyle,
+ this.radius,
});
final T value;
@@ -113,6 +115,8 @@ class AppSelectField<T> extends StatefulWidget {
/// A choice-tile selection. Null retains the ordinary field focus border.
final bool? selected;
+ final TextStyle? textStyle;
+ final double? radius;
final String? emptyLabel;
/// Whether a long list may put a search field at the head of its menu.
@@ -469,7 +473,7 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
key: const Key('app-select-filter'),
controller: _filterController,
focusNode: _filterFocus,
- style: kFieldTextStyle,
+ style: widget.textStyle ?? kFieldTextStyle,
decoration: InputDecoration(
hintText: 'Search',
prefixIcon: Icon(
@@ -569,6 +573,7 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
SizedBox(
width: _rowWidth(panelWidth),
child: AppMenuItem(
+ textStyle: widget.textStyle,
// No glyph of its own: the leading slot belongs to the tick,
// and stays empty (not a blank checkbox) on rows without it.
// `selected` also carries the wash and the heavier label, so the
@@ -607,7 +612,9 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
splashFactory: NoSplash.splashFactory,
hoverColor: Colors.transparent,
focusColor: Colors.transparent,
- borderRadius: BorderRadius.circular(AppControl.radius),
+ borderRadius: BorderRadius.circular(
+ widget.radius ?? AppControl.radius,
+ ),
child: SizedBox(
width: widget.width,
height: widget.height,
@@ -624,7 +631,9 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
widget.fillColor!,
)
: widget.fillColor ?? AppSurface.recess,
- borderRadius: BorderRadius.circular(AppControl.radius),
+ borderRadius: BorderRadius.circular(
+ widget.radius ?? AppControl.radius,
+ ),
border: Border.all(
color:
widget.selected == true ||
@@ -649,16 +658,19 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
current?.label ?? '—',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontFamily: AppFont.sans,
- fontFamilyFallback: AppFont.sansFallback,
- fontSize: AppControl.fontSize,
- fontWeight: AppControl.fontWeight,
- letterSpacing: AppFont.trackingFor(
- AppControl.fontSize,
- ),
- color: AppPalette.textPrimary,
- ),
+ style:
+ widget.textStyle ??
+ TextStyle(
+ fontFamily: AppFont.sans,
+ fontFamilyFallback:
+ AppFont.sansFallback,
+ fontSize: AppControl.fontSize,
+ fontWeight: AppControl.fontWeight,
+ letterSpacing: AppFont.trackingFor(
+ AppControl.fontSize,
+ ),
+ color: AppPalette.textPrimary,
+ ),
),
),
if (current?.note != null) ...[
diff --git a/desktop/lib/shortcuts/app_keymap.dart b/desktop/lib/shortcuts/app_keymap.dart
index 9becb9b3e..4be680aae 100644
--- a/desktop/lib/shortcuts/app_keymap.dart
+++ b/desktop/lib/shortcuts/app_keymap.dart
@@ -193,7 +193,7 @@ List<ShortcutRow> effectiveShortcutRows(
}
final bindings = (map ?? harnessDefaultKeymap).bindingsFor(contextKind);
final defaultDigits =
- contextKind != KeymapContext.picker &&
+ !contextKind.isPicker &&
List.generate(kTabDigitCount, (i) {
final matches = bindings
.where((b) => b.command == 'swarm.select_${i + 1}')
@@ -205,7 +205,10 @@ List<ShortcutRow> effectiveShortcutRows(
final shortcuts = appShortcuts();
return [
for (final command in harnessCommands)
- if ((command.context == KeymapContext.workspace ||
+ if (!command.hidden &&
+ (command.context == KeymapContext.workspace ||
+ (contextKind == KeymapContext.project &&
+ command.context == KeymapContext.picker) ||
command.context == contextKind) &&
(!defaultDigits ||
!RegExp(r'^swarm\.select_[1-9]$').hasMatch(command.id)))
@@ -234,7 +237,7 @@ List<ShortcutRow> effectiveShortcutRows(
),
if (defaultDigits)
const ShortcutRow(
- label: 'Select harnesses 1–9',
+ label: 'Select tabs 1–9',
chords: [
['⌘', '1 – 9'],
],
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 9df668049..4d11bc602 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -1,12 +1,13 @@
+import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import '../logging/debug_surface.dart';
/// Harness uses Command as a direct prefix for frequent workspace actions.
-/// T opens a tab, N adds an existing or new agent, S changes layout,
-/// H/J/K/L and arrows focus panes, B routes a task, D splits down and R splits
-/// right. The same definitions feed live keys, help and search.
+/// T opens a tab, P adds a pane, N creates a harness, S opens the Store,
+/// Shift-L chooses a layout. H/J/K/L and arrows focus panes; B routes a task.
+/// The same definitions feed live keys, help and search.
///
/// Unclaimed input stays with the focused agent or text field. Composition,
/// copy/paste and the coding agent's own prompt editing must keep working.
@@ -235,7 +236,11 @@ const List<AppShortcut> kAppShortcuts = [
),
AppShortcut(
action: ShortcutAction.showLayout,
- activator: SingleActivator(LogicalKeyboardKey.keyS, meta: true),
+ activator: SingleActivator(
+ LogicalKeyboardKey.keyL,
+ meta: true,
+ shift: true,
+ ),
label: 'Choose the grid layout',
group: ShortcutGroup.panes,
),
@@ -294,12 +299,6 @@ const List<AppShortcut> kAppShortcuts = [
label: 'Describe a task, and let it pick the agent',
group: ShortcutGroup.actions,
),
- AppShortcut(
- action: ShortcutAction.orchestrate,
- activator: SingleActivator(LogicalKeyboardKey.keyP, meta: true),
- label: 'Create with the orchestrator',
- group: ShortcutGroup.actions,
- ),
AppShortcut(
action: ShortcutAction.reload,
activator: SingleActivator(LogicalKeyboardKey.keyR, meta: true),
@@ -318,8 +317,7 @@ const List<AppShortcut> kAppShortcuts = [
///
/// Kept out of [kAppShortcuts] because it is not always there: a release build
/// has no Debug screen (see [kDebugSurfaceEnabled]), and a key that opens
-/// nothing is worse than a key that was never taken. Shift keeps it separate
-/// from the everyday Command-D split action.
+/// nothing is worse than a key that was never taken.
const AppShortcut kDebugShortcut = AppShortcut(
action: ShortcutAction.showDebug,
activator: SingleActivator(LogicalKeyboardKey.keyD, meta: true, shift: true),
@@ -352,8 +350,8 @@ List<AppShortcut> appShortcuts({bool swarmMode = true}) => [
const kSwarmShortcuts = [
AppShortcut(
action: ShortcutAction.addAgent,
- activator: SingleActivator(LogicalKeyboardKey.keyO, meta: true),
- label: 'Open Harness',
+ activator: SingleActivator(LogicalKeyboardKey.keyP, meta: true),
+ label: 'New Pane',
group: ShortcutGroup.actions,
),
AppShortcut(
@@ -404,7 +402,7 @@ const kSwarmShortcuts = [
meta: true,
shift: true,
),
- label: 'Next Harness',
+ label: 'Next Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
@@ -414,13 +412,13 @@ const kSwarmShortcuts = [
meta: true,
shift: true,
),
- label: 'Previous Harness',
+ label: 'Previous Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
action: ShortcutAction.nextSwarm,
activator: SingleActivator(LogicalKeyboardKey.tab, control: true),
- label: 'Next Harness',
+ label: 'Next Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
@@ -430,7 +428,7 @@ const kSwarmShortcuts = [
control: true,
shift: true,
),
- label: 'Previous Harness',
+ label: 'Previous Tab',
group: ShortcutGroup.navigate,
),
AppShortcut(
@@ -531,7 +529,7 @@ List<ShortcutRow> shortcutRows() {
// The digits are not in [kAppShortcuts] — nine near-identical rows would bury
// everything around them — so they join here, at the end of their group.
final digits = ShortcutRow(
- label: 'Select harnesses 1–9',
+ label: 'Select tabs 1–9',
chords: const [
['⌘', '1 – $kTabDigitCount'],
],
@@ -558,13 +556,19 @@ class TerminalKey {
/// The shortcuts screen prints these beside the ones the app takes, because
/// "why is there no shortcut for X" is answered by seeing that X already
/// belongs to something.
-const List<TerminalKey> kTerminalOwnedKeys = [
- TerminalKey(['⌘', 'C'], 'Copy'),
- TerminalKey(['⌘', 'V'], 'Paste'),
- TerminalKey(['⌘', 'A'], 'Select all'),
- TerminalKey(['esc'], 'Interrupt the engine'),
- TerminalKey(['⌥', '⏎'], "Newline in the engine's prompt"),
- TerminalKey(['⌃', 'C'], 'Cancel / interrupt in the agent'),
+List<TerminalKey> get kTerminalOwnedKeys => [
+ if (defaultTargetPlatform == TargetPlatform.linux) ...const [
+ TerminalKey(['⌃', '⇧', 'C'], 'Copy'),
+ TerminalKey(['⌃', '⇧', 'V'], 'Paste'),
+ TerminalKey(['⌃', '⇧', 'A'], 'Select all'),
+ ] else ...const [
+ TerminalKey(['⌘', 'C'], 'Copy'),
+ TerminalKey(['⌘', 'V'], 'Paste'),
+ TerminalKey(['⌘', 'A'], 'Select all'),
+ ],
+ const TerminalKey(['esc'], 'Interrupt the engine'),
+ const TerminalKey(['⌥', '⏎'], "Newline in the engine's prompt"),
+ const TerminalKey(['⌃', 'C'], 'Cancel / interrupt in the agent'),
];
/// Turns the declared shortcuts into the map [CallbackShortcuts] wants.
diff --git a/desktop/lib/shortcuts/key_cap.dart b/desktop/lib/shortcuts/key_cap.dart
index 216503250..220295f88 100644
--- a/desktop/lib/shortcuts/key_cap.dart
+++ b/desktop/lib/shortcuts/key_cap.dart
@@ -1,3 +1,5 @@
+import 'dart:math' as math;
+
import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -26,10 +28,16 @@ class KeyCap extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ final iconSize = MediaQuery.textScalerOf(context).scale(14);
+ final minEdge = math.max(height, iconSize + 8);
return Container(
- constraints: const BoxConstraints(minWidth: _minWidth),
- height: height,
- padding: const EdgeInsets.symmetric(horizontal: 6),
+ // A minimum, not a fixed height: large text and a multi-stroke custom
+ // binding must be able to grow without clipping their glyphs.
+ constraints: BoxConstraints(
+ minWidth: math.max(_minWidth, minEdge),
+ minHeight: minEdge,
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
decoration: BoxDecoration(
color: grid.AppSurface.wellFill,
borderRadius: BorderRadius.circular(6),
@@ -42,12 +50,13 @@ class KeyCap extends StatelessWidget {
// and a label squeezed to a character per line beside it.
child: Center(
widthFactor: 1,
+ heightFactor: 1,
child: label == '⇥' || label == '↵' || label == '⏎'
? Semantics(
label: label == '⇥' ? 'Tab' : 'Return',
child: Icon(
label == '⇥' ? Icons.keyboard_tab : Icons.keyboard_return,
- size: 14,
+ size: iconSize,
color: grid.AppPalette.textPrimary,
),
)
diff --git a/desktop/lib/shortcuts/keyboard_practice.dart b/desktop/lib/shortcuts/keyboard_practice.dart
new file mode 100644
index 000000000..2b191a6c6
--- /dev/null
+++ b/desktop/lib/shortcuts/keyboard_practice.dart
@@ -0,0 +1,769 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../core/harness_file_store.dart';
+import '../core/local_key_value_store.dart';
+import '../core/test_run.dart';
+import '../widgets/box_chrome.dart';
+import '../widgets/terminal_prompt.dart';
+import 'app_keymap.dart';
+import 'app_shortcuts.dart';
+import 'keymap.dart';
+import 'keymap_commands.dart';
+import 'keymap_host.dart';
+import 'keymap_keyboard.dart';
+
+class KeyboardLesson {
+ const KeyboardLesson(
+ this.command,
+ this.label,
+ this.group,
+ this.context,
+ this.bindings,
+ );
+ final String command, label, group;
+ final KeymapContext context;
+ final List<KeyBinding> bindings;
+ String get id =>
+ '${context.name}:$command:${bindings.map((b) => b.sequence).join('|')}';
+ String get keys => bindings
+ .map((binding) => boxKeyLabel(describeKeyBinding(binding)))
+ .join(' / ');
+ String get result => switch (command) {
+ 'swarm.new' => '[work] [new tab]\nFind a harness, or create one',
+ 'agent.add' => '[agent 1] │ [agent 2]\nBoth agents share this tab.',
+ 'agent.new' => 'agent Claude Code\nmachine dev\nproject ~/work/payments\ntask (optional)\nCreate is selected. Up/Down + Enter edits an argument. Permissions and profiles are inside Agent.',
+ 'pane.zoom' => '[agent 2 — full workspace]\nPress the same key to restore the other panes.',
+ 'pane.close' =>
+ '[agent 1]\nThe second view closes. Its agent keeps running.',
+ 'swarm.close' =>
+ '[previous tab]\nThe view closes. Its agents keep running.',
+ 'navigation.commands' => '> rename\nRename Agent\nRename Tab',
+ 'terminal.find' => 'find > timeout\n1/3 matches in this terminal’s output',
+ 'picker.complete' => 'project ~/work/payments\nTab completes the current argument; Enter accepts it.',
+ 'picker.complete_back' =>
+ 'project ~/work/\nShift-Tab walks path candidates backward.',
+ 'picker.cancel' => '> ready\nEscape steps back from a nested chooser, then returns to the terminal.',
+ 'creation.agent' => 'agent Claude Code\nFilter the agents, then Enter to choose. Escape returns to the launch menu.',
+ 'creation.project' => 'project on This Mac\nresearch website payments\nNew project / Open folder / Clone GitHub repository\nType to filter projects. Up/Down selects; Enter chooses; Escape goes back.',
+ 'creation.project_new' => 'name payments processing\nCreate payments-processing\nThis Mac:~/harnesses/payments-processing',
+ 'creation.project_existing' => 'folder ~/work/payments\nEnter a folder path, or press Enter to browse on the selected machine.',
+ 'creation.project_repository' => 'repo https://github.com/openai/codex\nChoose the repository, then launch to clone it and start the agent.',
+ 'creation.project_machine' => 'machine Office\nChoose where the project lives. Folders are scoped to that machine.',
+ 'creation.project_browse' => 'Browse folders\nChoose a folder on the selected machine; cancelling returns to the folder prompt.',
+ 'creation.project_recent_1' ||
+ 'creation.project_recent_2' ||
+ 'creation.project_recent_3' ||
+ 'creation.project_recent_4' ||
+ 'creation.project_recent_5' ||
+ 'creation.project_recent_6' ||
+ 'creation.project_recent_7' ||
+ 'creation.project_recent_8' ||
+ 'creation.project_recent_9' => 'Recent project selected\nThe launch summary now uses this folder on the selected machine.',
+ 'creation.task' => 'task fix the tests\nEnter starts the agent with this first task. Escape keeps the draft.',
+ 'creation.options' => 'options\nChange permissions or the Codex profile.',
+ 'picker.more_options' =>
+ 'more options\nPermissions · Codex profile · repository',
+ 'picker.toggle_preview' =>
+ 'results │ preview\nToggle again to hide the preview.',
+ 'agent.stop' => 'Stop Agent?\n> Cancel Stop\nStopping ends the agent; closing a pane only closes a view.',
+ 'agent.restart' =>
+ 'Restart Agent\nA fresh conversation starts in the same project.',
+ 'agent.fork' =>
+ 'Fork Agent\nChoose a name and first task. The source stays open.',
+ 'app.store' =>
+ '[Harness Store]\nFind a harness for the kind of work you want to do.',
+ 'pane.focus_left' ||
+ 'pane.focus_right' ||
+ 'pane.focus_above' ||
+ 'pane.focus_below' =>
+ '$label\nThe caret moves to the neighboring pane. Start typing there.',
+ 'pane.resize' => 'resize > arrows adjust shift-arrows larger steps\nTab changes divider. Escape returns to the terminal.',
+ 'pane.layout' => 'layout > columns rows grid\nKeep pressing the key to cycle layouts.',
+ 'edit.word' => 'task fix the \nCtrl-W removes the previous word.',
+ 'edit.line' =>
+ 'task \nCtrl-U removes text back to the start of this line.',
+ 'edit.restore' => 'task fix the tests\nCtrl-Y restores the last text removed with Ctrl-W/U.',
+ 'edit.newline' => 'task fix the tests\n keep the patch small',
+ 'edit.backspace' =>
+ 'task tes\nCtrl-H removes the character before the cursor.',
+ 'edit.delete' =>
+ 'task tests\nCtrl-D removes the character after the cursor.',
+ _ =>
+ '$label\n${context.isPicker ? 'The focused prompt handles this key.' : 'The workspace handles this key; ordinary typing stays in the terminal.'}',
+ };
+}
+
+/// The catalog and live bindings are the source of truth, including aliases,
+/// user sequences, unbindings, and terminal-only overrides. JEV stays optional.
+List<KeyboardLesson> keyboardLessons(AppKeymap keymap) {
+ const essentials = [
+ 'swarm.new',
+ 'agent.add',
+ 'agent.new',
+ 'pane.zoom',
+ 'navigation.commands',
+ 'terminal.find',
+ 'keyboard.help',
+ ];
+ const excluded = {
+ 'navigation.command_bar',
+ 'keyboard.practice',
+ 'keyboard.quick_start',
+ 'keyboard.pause_guide',
+ 'app.debug',
+ };
+ final result = <KeyboardLesson>[];
+ for (final command in harnessCommands) {
+ if (command.hidden || excluded.contains(command.id)) continue;
+ final context = command.context;
+ final bindings = keymap.bindings(command.id, context: context).toList();
+ if (command.id.startsWith('pane.focus_') &&
+ RegExp(r'_[1-9]$').hasMatch(command.id) &&
+ bindings.isEmpty &&
+ keymap.bindings(command.id, context: KeymapContext.terminal).isEmpty) {
+ continue;
+ }
+ final group = context.isPicker
+ ? 'Search & creation'
+ : essentials.contains(command.id)
+ ? 'Essentials'
+ : command.group.label;
+ result.add(
+ KeyboardLesson(command.id, command.label, group, context, bindings),
+ );
+ if (context == KeymapContext.workspace) {
+ final terminal = keymap
+ .bindings(command.id, context: KeymapContext.terminal)
+ .toList();
+ if (terminal.map((b) => b.sequence).join('|') !=
+ bindings.map((b) => b.sequence).join('|')) {
+ result.add(
+ KeyboardLesson(
+ command.id,
+ command.label,
+ 'Agent input overrides',
+ KeymapContext.terminal,
+ terminal,
+ ),
+ );
+ }
+ }
+ }
+ for (final (id, label, key) in [
+ ('word', 'Erase the previous word', 'ctrl+w'),
+ ('line', 'Erase to the start of the line', 'ctrl+u'),
+ ('restore', 'Restore erased text', 'ctrl+y'),
+ ('newline', 'Add a task line', 'alt+enter'),
+ ('backspace', 'Erase the previous character', 'ctrl+h'),
+ ('delete', 'Erase the next character', 'ctrl+d'),
+ ]) {
+ if (keymap.current.match(KeymapContext.picker, [
+ KeyStroke.parse(key),
+ ]).matched) {
+ continue;
+ }
+ result.add(
+ KeyboardLesson(
+ 'edit.$id',
+ label,
+ 'Prompt editing',
+ KeymapContext.picker,
+ [
+ KeyBinding(
+ keys: [KeyStroke.parse(key)],
+ command: 'edit.$id',
+ context: KeymapContext.picker,
+ ),
+ ],
+ ),
+ );
+ }
+ return [
+ for (final id in essentials)
+ ...result.where((lesson) => lesson.command == id),
+ ...result.where((lesson) => !essentials.contains(lesson.command)),
+ ];
+}
+
+Future<void> showKeyboardPractice(BuildContext context, {AppKeymap? keymap}) =>
+ showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (context) => KeyboardPractice(
+ keymap: keymap ?? KeymapTheme.of(context, listen: false),
+ storage: kUnderTest ? null : HarnessFileStore.shared,
+ ),
+ );
+
+class KeyboardPractice extends StatefulWidget {
+ const KeyboardPractice({super.key, this.keymap, this.storage});
+ final AppKeymap? keymap;
+ final LocalKeyValueStore? storage;
+ @override
+ State<KeyboardPractice> createState() => _KeyboardPracticeState();
+}
+
+class _KeyboardPracticeState extends State<KeyboardPractice> {
+ static const _storageKey = 'keyboard_practice_v1';
+ final _fallback = AppKeymap();
+ AppKeymap get map => widget.keymap ?? _fallback;
+ final _filter = TextEditingController();
+ final _answer = TextEditingController();
+ final _filterFocus = FocusNode(debugLabel: 'Practice search');
+ final _exerciseFocus = FocusNode(debugLabel: 'Practice shortcut');
+ final _answerFocus = FocusNode(debugLabel: 'Practice command');
+ final _scroll = ScrollController();
+ final _detailScroll = ScrollController();
+ final _done = <String>{};
+ KeyboardLesson? _lesson;
+ bool _matched = false;
+ bool _loaded = false;
+ String? _feedback;
+ int _cursor = 0;
+ Future<void> _saving = Future.value();
+
+ List<KeyboardLesson> get lessons => keyboardLessons(map);
+ List<KeyboardLesson> get filtered {
+ final query = _filter.text.trim().toLowerCase();
+ return lessons
+ .where(
+ (l) =>
+ '${l.label} ${l.group} ${l.keys}'.toLowerCase().contains(query),
+ )
+ .toList();
+ }
+
+ @override
+ void initState() {
+ super.initState();
+ map.addListener(_keysChanged);
+ unawaited(_load());
+ }
+
+ Future<void> _load() async {
+ try {
+ final raw = await widget.storage?.read(_storageKey);
+ if (!mounted || raw == null) return;
+ final data = jsonDecode(raw);
+ if (data is List) setState(() => _done.addAll(data.whereType<String>()));
+ } catch (_) {
+ // Practice still works when local preferences are unavailable.
+ } finally {
+ if (mounted) {
+ _loaded = true;
+ if (_done.isNotEmpty) _save();
+ }
+ }
+ }
+
+ void _save() {
+ if (!_loaded) return;
+ final saved = jsonEncode(_done.toList());
+ _saving = _saving.then((_) async {
+ try {
+ await widget.storage?.write(_storageKey, saved);
+ } catch (_) {}
+ });
+ }
+
+ String _hint(String command) {
+ final bindings = map.bindings(command, context: KeymapContext.picker);
+ final binding =
+ bindings.where((b) => b.custom).firstOrNull ?? bindings.firstOrNull;
+ return binding == null ? 'click' : boxKeyLabel(describeKeyBinding(binding));
+ }
+
+ void _keysChanged() {
+ final current = _lesson;
+ setState(() {
+ _lesson = current == null
+ ? null
+ : lessons
+ .where(
+ (l) =>
+ l.command == current.command &&
+ l.context == current.context,
+ )
+ .firstOrNull;
+ _matched = false;
+ _feedback = null;
+ });
+ _requestFocus();
+ }
+
+ void _requestFocus() => WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) {
+ if (_detailScroll.hasClients) _detailScroll.jumpTo(0);
+ (_lesson == null
+ ? _filterFocus
+ : _lesson!.bindings.isEmpty && !_matched
+ ? _answerFocus
+ : _exerciseFocus)
+ .requestFocus();
+ }
+ });
+
+ void _open(KeyboardLesson lesson) {
+ setState(() {
+ _lesson = lesson;
+ _matched = false;
+ _feedback = null;
+ _answer.clear();
+ });
+ _requestFocus();
+ }
+
+ void _openSelected() {
+ final rows = filtered;
+ if (rows.isNotEmpty) _open(rows[_cursor.clamp(0, rows.length - 1)]);
+ }
+
+ void _move(int delta) {
+ final rows = filtered;
+ if (rows.isEmpty) return;
+ setState(() => _cursor = (_cursor + delta).clamp(0, rows.length - 1));
+ if (_scroll.hasClients) {
+ final height = 54.0 * MediaQuery.textScalerOf(context).scale(13) / 13;
+ final top = _cursor * height, bottom = top + height;
+ final at = _scroll.offset, view = _scroll.position.viewportDimension;
+ if (top < at || bottom > at + view) {
+ _scroll.jumpTo(
+ (top < at ? top : bottom - view).clamp(
+ 0.0,
+ _scroll.position.maxScrollExtent,
+ ),
+ );
+ }
+ }
+ }
+
+ void _back() {
+ if (_lesson == null) {
+ Navigator.of(context).pop();
+ } else {
+ setState(() {
+ _lesson = null;
+ _feedback = null;
+ });
+ _requestFocus();
+ }
+ }
+
+ void _next() {
+ final rows = filtered;
+ final at = rows.indexWhere((l) => l.id == _lesson?.id);
+ if (at >= 0 && at + 1 < rows.length) {
+ _cursor = at + 1;
+ _open(rows[at + 1]);
+ } else {
+ _back();
+ }
+ }
+
+ void _read(int direction) {
+ if (!_detailScroll.hasClients) return;
+ final position = _detailScroll.position;
+ _detailScroll.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .8).clamp(
+ 0.0,
+ position.maxScrollExtent,
+ ),
+ );
+ }
+
+ void _record(String id) {
+ if (_lesson == null) return;
+ if ((_matched || id != _lesson!.command) &&
+ (id == 'picker.preview_page_down' || id == 'picker.preview_page_up')) {
+ _read(id == 'picker.preview_page_down' ? 1 : -1);
+ return;
+ }
+ if (id == 'picker.accept' &&
+ !_exerciseFocus.hasPrimaryFocus &&
+ !_answerFocus.hasFocus) {
+ activatePromptControl();
+ return;
+ }
+ if (_matched) {
+ if (id == 'picker.accept') _next();
+ if (id == 'picker.cancel') _back();
+ return;
+ }
+ if (id != _lesson!.command) {
+ if (id == 'picker.cancel') {
+ _back();
+ return;
+ }
+ if (id == 'picker.complete' || id == 'picker.complete_back') {
+ id == 'picker.complete'
+ ? FocusManager.instance.primaryFocus?.nextFocus()
+ : FocusManager.instance.primaryFocus?.previousFocus();
+ return;
+ }
+ setState(
+ () => _feedback =
+ 'That is ${harnessCommandById[id]?.label ?? id}. Try ${_lesson!.keys}.',
+ );
+ return;
+ }
+ setState(() {
+ _matched = true;
+ _feedback = null;
+ _done.add(_lesson!.id);
+ });
+ _save();
+ _requestFocus();
+ }
+
+ void _submitName() {
+ if (_answer.text.trim().toLowerCase() == _lesson!.label.toLowerCase()) {
+ _record(_lesson!.command);
+ } else {
+ setState(() => _feedback = 'Type ${_lesson!.label}, then press Enter.');
+ }
+ }
+
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent) {
+ return event is KeyRepeatEvent
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ final stroke = keyStrokeForEvent(event);
+ if (stroke == null) return KeyEventResult.ignored;
+ final lesson = _lesson!;
+ if (!_matched &&
+ lesson.command.startsWith('edit.') &&
+ lesson.bindings.any((b) => b.keys.single == stroke)) {
+ _record(lesson.command);
+ return KeyEventResult.handled;
+ }
+ if (stroke == const KeyStroke('escape')) {
+ _back();
+ return KeyEventResult.handled;
+ }
+ if (stroke == const KeyStroke('pagedown') ||
+ stroke == const KeyStroke('pageup')) {
+ _read(stroke == const KeyStroke('pagedown') ? 1 : -1);
+ return KeyEventResult.handled;
+ }
+ if (stroke == const KeyStroke('enter')) {
+ if (!_exerciseFocus.hasPrimaryFocus && !_answerFocus.hasFocus) {
+ return KeyEventResult.ignored;
+ }
+ if (_matched) {
+ _next();
+ } else if (lesson.bindings.isEmpty) {
+ _submitName();
+ }
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ @override
+ void dispose() {
+ map.removeListener(_keysChanged);
+ _fallback.dispose();
+ _filter.dispose();
+ _answer.dispose();
+ _filterFocus.dispose();
+ _exerciseFocus.dispose();
+ _answerFocus.dispose();
+ _scroll.dispose();
+ _detailScroll.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final lesson = _lesson;
+ final rows = filtered;
+ final body = TerminalBox(
+ child: Padding(
+ padding: const EdgeInsets.all(18),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Wrap(
+ alignment: WrapAlignment.spaceBetween,
+ spacing: 16,
+ runSpacing: 6,
+ children: [
+ Text('keyboard practice', style: boxMonoStyle(size: 16)),
+ Text(
+ '${lessons.where((l) => _done.contains(l.id)).length}/${lessons.length} practiced',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Practice only · your running agents stay untouched',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 18),
+ if (lesson == null) ...[
+ Row(
+ children: [
+ Text('practice > ', style: boxMonoStyle()),
+ Expanded(
+ child: TextField(
+ key: const ValueKey('practice-filter'),
+ controller: _filter,
+ focusNode: _filterFocus,
+ autofocus: true,
+ style: boxMonoStyle(),
+ decoration: const InputDecoration(
+ hintText: 'Find a shortcut or a group',
+ border: InputBorder.none,
+ isDense: true,
+ ),
+ onChanged: (_) => setState(() => _cursor = 0),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 10),
+ Flexible(
+ child: rows.isEmpty
+ ? Text('No matching shortcuts.', style: boxMonoStyle())
+ : ListView.builder(
+ controller: _scroll,
+ shrinkWrap: true,
+ itemExtent:
+ 54.0 *
+ MediaQuery.textScalerOf(context).scale(13) /
+ 13,
+ itemCount: rows.length,
+ itemBuilder: (context, i) {
+ final row = rows[i];
+ return InkWell(
+ key: ValueKey(
+ 'practice-${row.context.name}-${row.command}',
+ ),
+ onTap: () => _open(row),
+ child: ColoredBox(
+ color: i == _cursor.clamp(0, rows.length - 1)
+ ? Colors.white.withValues(alpha: .09)
+ : Colors.transparent,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ vertical: 5,
+ ),
+ child: Row(
+ children: [
+ Text(
+ _done.contains(row.id) ? '[x] ' : '[ ] ',
+ style: boxMonoStyle(color: kBoxFaint),
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.start,
+ mainAxisAlignment:
+ MainAxisAlignment.center,
+ children: [
+ Text(
+ row.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(),
+ ),
+ Text(
+ '${row.group} · ${row.bindings.isEmpty ? 'command search' : row.keys}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ size: 11,
+ color: kBoxFaint,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (i == _cursor)
+ Text(
+ '<',
+ style: boxMonoStyle(color: kBoxFaint),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ] else
+ Flexible(
+ child: Scrollbar(
+ controller: _detailScroll,
+ thumbVisibility: true,
+ child: SingleChildScrollView(
+ controller: _detailScroll,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ '${lesson.group} / ${lesson.label}',
+ style: boxMonoStyle(size: 14),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ _matched
+ ? '[x] ${lesson.label}'
+ : lesson.bindings.isEmpty
+ ? 'No shortcut assigned. Find it by name in command search.'
+ : 'Press ${lesson.keys}',
+ style: boxMonoStyle(size: 16),
+ ),
+ if (!_matched && lesson.bindings.length > 1)
+ Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Text(
+ 'Try any of these bindings.',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (!_matched && lesson.bindings.isEmpty)
+ TextField(
+ key: const ValueKey('practice-command'),
+ controller: _answer,
+ focusNode: _answerFocus,
+ style: boxMonoStyle(),
+ decoration: InputDecoration(
+ prefixText: ': ',
+ hintText: lesson.label,
+ border: InputBorder.none,
+ ),
+ ),
+ const SizedBox(height: 16),
+ Container(
+ padding: const EdgeInsets.all(14),
+ color: Colors.black26,
+ child: Text(
+ _matched ? lesson.result : 'scratch workspace\n\n[agent 1] │ [agent 2]\n\n> ready',
+ key: const ValueKey('practice-preview'),
+ style: boxMonoStyle(size: 13),
+ ),
+ ),
+ if (_feedback != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Text(
+ _feedback!,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (_matched)
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ 'Shortcut practiced. Enter continues.',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 12),
+ Wrap(
+ spacing: 16,
+ runSpacing: 4,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ if (lesson == null)
+ Text(
+ '${_hint('picker.accept')} practice ${_hint('picker.previous')}/${_hint('picker.next')} choose',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ if (lesson != null)
+ TextButton(
+ onPressed: _next,
+ child: Text(
+ _matched ? 'Enter Next' : 'Skip',
+ style: boxMonoStyle(size: 12),
+ ),
+ ),
+ if (lesson != null)
+ Text(
+ 'pgup/pgdn read',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ TextButton(
+ key: const ValueKey('practice-back'),
+ onPressed: _back,
+ child: Text(
+ lesson == null
+ ? '${_hint('picker.cancel')} Close'
+ : 'esc All shortcuts',
+ style: boxMonoStyle(size: 12),
+ ),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ final content = lesson == null
+ ? TerminalPromptKeys(
+ cancel: _back,
+ inputFocus: _filterFocus,
+ accept: () => _filterFocus.hasFocus
+ ? _openSelected()
+ : activatePromptControl(),
+ next: () => _move(1),
+ previous: () => _move(-1),
+ child: body,
+ )
+ : KeymapRegion(
+ contextKind: lesson.context,
+ actions: {
+ for (final command in harnessCommands)
+ command.id: () {
+ if (!_matched &&
+ lesson.bindings.isEmpty &&
+ command.id == 'picker.accept') {
+ _submitName();
+ } else {
+ _record(command.id);
+ }
+ },
+ },
+ child: Focus(
+ focusNode: _exerciseFocus,
+ autofocus: true,
+ onKeyEvent: _key,
+ child: body,
+ ),
+ );
+ return KeymapProvider(
+ keymap: map,
+ child: KeymapHost(
+ keymap: map,
+ enabled: () => false,
+ actions: const {},
+ child: Dialog(
+ key: const ValueKey('keyboard-practice'),
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ insetPadding: const EdgeInsets.all(16),
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 780, maxHeight: 620),
+ child: content,
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/shortcuts/keymap.dart b/desktop/lib/shortcuts/keymap.dart
index 9f366bc03..07f7c4407 100644
--- a/desktop/lib/shortcuts/keymap.dart
+++ b/desktop/lib/shortcuts/keymap.dart
@@ -1,6 +1,16 @@
import 'dart:convert';
-enum KeymapContext { workspace, terminal, picker }
+enum KeymapContext {
+ workspace,
+ terminal,
+ picker,
+
+ /// Project-menu bindings layer over picker bindings (for example, o opens
+ /// a folder here and advanced options in the parent launch menu).
+ project;
+
+ bool get isPicker => this == picker || this == project;
+}
/// A canonical logical key name and exact modifier set. Parsing happens on reload,
/// never on the input path. The Flutter adapter supplies the same canonical keys.
@@ -274,10 +284,16 @@ class ResolvedKeymap {
if (context != KeymapContext.workspace) {
apply(defaults, KeymapContext.workspace);
}
+ if (context == KeymapContext.project) {
+ apply(defaults, KeymapContext.picker);
+ }
apply(defaults, context);
if (context != KeymapContext.workspace) {
apply(config.bindings, KeymapContext.workspace);
}
+ if (context == KeymapContext.project) {
+ apply(config.bindings, KeymapContext.picker);
+ }
apply(config.bindings, context);
_bindings[context] = List.unmodifiable(effective.values);
final root = _KeyNode();
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 917587164..bd68d6ca7 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -11,14 +11,17 @@ class HarnessCommand {
this.label,
this.group, {
this.extraKeys = const [],
+ this.keywords = const [],
this.action,
this.nativeAction,
this.context = KeymapContext.workspace,
this.repeatable = false,
+ this.hidden = false,
});
final String id, label;
final ShortcutGroup group;
final List<String> extraKeys;
+ final List<String> keywords;
/// Workspace defaults come from the live shortcut table. A command cannot
/// quietly propose different keys from the ones the user already uses.
@@ -28,6 +31,9 @@ class HarnessCommand {
final String? nativeAction;
final KeymapContext context;
final bool repeatable;
+
+ /// Review commands still use the shared keymap, but stay out of normal help.
+ final bool hidden;
}
final _workspaceKeys = _readWorkspaceKeys();
@@ -79,14 +85,14 @@ final harnessCommands = <HarnessCommand>[
// key of their own in keybindings.jsonc.
const HarnessCommand(
'swarm.reopen',
- 'Reopen last closed harness',
+ 'Reopen closed tab or pane',
ShortcutGroup.navigate,
action: ShortcutAction.reopenClosedSwarm,
nativeAction: 'reopen',
),
const HarnessCommand(
'swarm.next',
- 'Next Harness',
+ 'Next Tab',
ShortcutGroup.navigate,
action: ShortcutAction.nextSwarm,
nativeAction: 'next',
@@ -94,7 +100,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'swarm.previous',
- 'Previous Harness',
+ 'Previous Tab',
ShortcutGroup.navigate,
action: ShortcutAction.previousSwarm,
nativeAction: 'previous',
@@ -140,7 +146,7 @@ final harnessCommands = <HarnessCommand>[
for (var i = 1; i <= 9; i++)
HarnessCommand(
'swarm.select_$i',
- 'Select harness $i',
+ 'Select tab $i',
ShortcutGroup.navigate,
extraKeys: ['cmd+$i'],
),
@@ -241,14 +247,12 @@ final harnessCommands = <HarnessCommand>[
'pane.split_right',
'Split right…',
ShortcutGroup.panes,
- extraKeys: ['cmd+r'],
nativeAction: 'splitRight',
),
const HarnessCommand(
'pane.split_down',
'Split down…',
ShortcutGroup.panes,
- extraKeys: ['cmd+d'],
nativeAction: 'splitDown',
),
const HarnessCommand(
@@ -281,7 +285,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'agent.add',
- 'Open Harness',
+ 'New Pane',
ShortcutGroup.actions,
action: ShortcutAction.addAgent,
nativeAction: 'addAgent',
@@ -293,6 +297,10 @@ final harnessCommands = <HarnessCommand>[
action: ShortcutAction.newAgent,
nativeAction: 'newAgent',
),
+ const HarnessCommand('agent.rename', 'Rename Agent', ShortcutGroup.actions),
+ const HarnessCommand('agent.stop', 'Stop Agent', ShortcutGroup.actions),
+ const HarnessCommand('agent.fork', 'Fork Agent', ShortcutGroup.actions),
+ const HarnessCommand('agent.restart', 'Restart Agent', ShortcutGroup.actions),
const HarnessCommand(
'terminal.new',
'New Terminal',
@@ -344,6 +352,19 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
action: ShortcutAction.orchestrate,
),
+ const HarnessCommand(
+ 'app.customize',
+ 'Customize OpenHarness',
+ ShortcutGroup.actions,
+ ),
+ const HarnessCommand(
+ 'app.store',
+ 'Harness Store',
+ ShortcutGroup.actions,
+ extraKeys: ['cmd+s'],
+ keywords: ['install', 'browse harnesses', 'packages', 'extensions'],
+ nativeAction: 'store',
+ ),
const HarnessCommand(
'app.settings',
'Open Settings',
@@ -364,6 +385,26 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
nativeAction: 'openKeymap',
),
+ const HarnessCommand(
+ 'keyboard.quick_start',
+ 'Quick start',
+ ShortcutGroup.actions,
+ keywords: ['onboarding', 'learn', 'guide', 'getting started'],
+ nativeAction: 'quickStart',
+ ),
+ const HarnessCommand(
+ 'keyboard.practice',
+ 'Keyboard practice',
+ ShortcutGroup.actions,
+ keywords: ['tutorial', 'learn', 'shortcuts', 'training', 'keys'],
+ nativeAction: 'keyboardPractice',
+ ),
+ const HarnessCommand(
+ 'keyboard.pause_guide',
+ 'Pause quick start',
+ ShortcutGroup.actions,
+ keywords: ['hide guide', 'dismiss tutorial'],
+ ),
if (kDebugSurfaceEnabled)
const HarnessCommand(
'app.debug',
@@ -371,6 +412,14 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
action: ShortcutAction.showDebug,
),
+ if (kDebugSurfaceEnabled)
+ const HarnessCommand(
+ 'app.onboarding_review',
+ 'Review onboarding',
+ ShortcutGroup.actions,
+ extraKeys: ['cmd+alt+shift+o'],
+ hidden: true,
+ ),
const HarnessCommand(
'picker.next',
'Next result',
@@ -389,7 +438,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'picker.preview_page_up',
- 'Scroll preview up',
+ 'Page up in the preview or results',
ShortcutGroup.navigate,
extraKeys: ['pageup'],
context: KeymapContext.picker,
@@ -397,7 +446,7 @@ final harnessCommands = <HarnessCommand>[
),
const HarnessCommand(
'picker.preview_page_down',
- 'Scroll preview down',
+ 'Page down in the preview or results',
ShortcutGroup.navigate,
extraKeys: ['pagedown'],
context: KeymapContext.picker,
@@ -407,7 +456,14 @@ final harnessCommands = <HarnessCommand>[
'picker.accept',
'Open the selected result',
ShortcutGroup.navigate,
- extraKeys: ['enter'],
+ extraKeys: ['enter', 'ctrl+m'],
+ context: KeymapContext.picker,
+ ),
+ const HarnessCommand(
+ 'picker.refresh',
+ 'Refresh the machine list',
+ ShortcutGroup.actions,
+ extraKeys: ['cmd+r', 'ctrl+r'],
context: KeymapContext.picker,
),
const HarnessCommand(
@@ -417,11 +473,89 @@ final harnessCommands = <HarnessCommand>[
extraKeys: ['cmd+enter'],
context: KeymapContext.picker,
),
+ // The box's own keys. They were hardcoded activators: absent from ⌘/ and the
+ // config template, and impossible to move — the one corner where "every key
+ // can be remapped" was not true.
+ const HarnessCommand(
+ 'picker.complete',
+ 'Complete the path, or go to the next field',
+ ShortcutGroup.navigate,
+ // ⌃I is Tab to a terminal, as ⌃M is Return and ⌃[ is Escape.
+ extraKeys: ['tab', 'ctrl+i'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'picker.complete_back',
+ 'The previous candidate, or the previous field',
+ ShortcutGroup.navigate,
+ extraKeys: ['shift+tab'],
+ context: KeymapContext.picker,
+ repeatable: true,
+ ),
+ const HarnessCommand(
+ 'picker.more_options',
+ 'Open the full New Harness form',
+ ShortcutGroup.navigate,
+ extraKeys: ['cmd+period'],
+ context: KeymapContext.picker,
+ ),
+ // Launch and Project use arrows/Enter. Keep stable command identities for
+ // explicit user bindings without reserving plain letters in these prompts.
+ for (final (name, key, label) in [
+ ('agent', null, 'Choose the new agent'),
+ ('project', null, 'Choose the new agent’s project'),
+ ('task', null, 'Edit the new agent’s first task'),
+ ('options', null, 'Edit the new agent’s advanced options'),
+ // Project is a text filter. Keep these command identities available for
+ // explicit user remaps, without taking ordinary letters from the editor.
+ ('project_new', null, 'Name a new project'),
+ ('project_existing', null, 'Open an existing project'),
+ ('project_repository', null, 'Clone a GitHub repository'),
+ ('project_machine', null, 'Choose the new agent’s machine'),
+ ('project_browse', 'ctrl+o', 'Browse folders on the selected machine'),
+ ])
+ HarnessCommand(
+ 'creation.$name',
+ label,
+ ShortcutGroup.actions,
+ extraKeys: [?key],
+ context:
+ const {
+ 'project_new',
+ 'project_existing',
+ 'project_repository',
+ }.contains(name)
+ ? KeymapContext.project
+ : KeymapContext.picker,
+ ),
+ for (var recent = 1; recent <= 9; recent++)
+ HarnessCommand(
+ 'creation.project_recent_$recent',
+ 'Use recent project $recent',
+ ShortcutGroup.actions,
+ context: KeymapContext.project,
+ ),
+ const HarnessCommand(
+ 'picker.toggle_preview',
+ 'Show or hide the result preview',
+ ShortcutGroup.navigate,
+ extraKeys: ['ctrl+slash'],
+ context: KeymapContext.picker,
+ ),
+ for (var row = 1; row <= 9; row++)
+ HarnessCommand(
+ 'picker.pick_$row',
+ 'Take row $row',
+ ShortcutGroup.navigate,
+ extraKeys: ['alt+$row'],
+ context: KeymapContext.picker,
+ ),
const HarnessCommand(
'picker.cancel',
'Close search',
ShortcutGroup.navigate,
- extraKeys: ['escape', 'ctrl+g'],
+ extraKeys: ['escape', 'ctrl+c', 'ctrl+g', 'ctrl+bracketleft'],
context: KeymapContext.picker,
),
];
diff --git a/desktop/lib/shortcuts/keymap_dispatch.dart b/desktop/lib/shortcuts/keymap_dispatch.dart
index 2d8bbe91e..938679055 100644
--- a/desktop/lib/shortcuts/keymap_dispatch.dart
+++ b/desktop/lib/shortcuts/keymap_dispatch.dart
@@ -90,6 +90,17 @@ class KeymapDispatch {
cancel();
final command = match.command;
if (command != null) {
+ // In the workspace a matched key is consumed even when its command is
+ // unavailable: it must not fall through and type into a terminal. In a
+ // PICKER the thing underneath is a text field, and swallowing a key
+ // nothing handles there takes it from the editor for no one's benefit —
+ // ⌥1–⌥9 pick a row in a list, and on the task field (no rows) they ate
+ // ¡ ™ £ ¢ ∞ § ¶ • ª out of a 2000-character message. A single stroke
+ // that nothing here can run is left to the field. (Part of a sequence
+ // is still consumed: its first strokes already were.)
+ if (context.isPicker && !wasPending && !canExecute(command)) {
+ return const KeymapDispatchResult(handled: false);
+ }
_pressed.add(physicalKey);
return KeymapDispatchResult(
handled: true,
diff --git a/desktop/lib/shortcuts/keymap_host.dart b/desktop/lib/shortcuts/keymap_host.dart
index 5f65665e6..770397211 100644
--- a/desktop/lib/shortcuts/keymap_host.dart
+++ b/desktop/lib/shortcuts/keymap_host.dart
@@ -101,6 +101,14 @@ class _KeymapHostState extends State<KeymapHost> with WidgetsBindingObserver {
}
final focus = FocusManager.instance.primaryFocus;
final context = focus?.context;
+ // A self-contained surface (such as shortcut practice) owns its dispatch.
+ // Flutter calls every early handler even after one handles the event.
+ final owner = context?.findAncestorStateOfType<_KeymapHostState>();
+ if (owner != null && !identical(owner, this)) {
+ _dispatch.cancel();
+ _notifyPending();
+ return KeyEventResult.ignored;
+ }
if (context == null ||
KeymapTheme.of(context, listen: false) != widget.keymap) {
_dispatch.cancel();
diff --git a/desktop/lib/shortcuts/keymap_settings.dart b/desktop/lib/shortcuts/keymap_settings.dart
index d63b50533..8e3d8d1cd 100644
--- a/desktop/lib/shortcuts/keymap_settings.dart
+++ b/desktop/lib/shortcuts/keymap_settings.dart
@@ -47,7 +47,9 @@ class KeymapSettings extends StatelessWidget {
children: [
AppSelectField<KeymapContext>(
value: contextKind,
- width: 160,
+ // Keep the context readable when the user enlarges text. The
+ // surrounding Wrap still limits the field to the pane width.
+ width: 160 * MediaQuery.textScalerOf(context).scale(13.5) / 13.5,
options: const [
SelectOption(
value: KeymapContext.workspace,
@@ -58,6 +60,10 @@ class KeymapSettings extends StatelessWidget {
label: 'Agent input',
),
SelectOption(value: KeymapContext.picker, label: 'Search'),
+ SelectOption(
+ value: KeymapContext.project,
+ label: 'Project menu',
+ ),
],
onChanged: onContextChanged,
),
diff --git a/desktop/lib/shortcuts/keymap_store.dart b/desktop/lib/shortcuts/keymap_store.dart
index 63d019016..70baff20f 100644
--- a/desktop/lib/shortcuts/keymap_store.dart
+++ b/desktop/lib/shortcuts/keymap_store.dart
@@ -1,4 +1,5 @@
import '../core/host_platform.dart';
+
import 'dart:async';
import 'dart:convert';
import 'dart:io';
@@ -60,16 +61,19 @@ class KeymapStore extends ChangeNotifier {
return p.join(root, 'harness', 'keybindings.jsonc');
}
- Future<void> start() async {
- if (watchFiles && !_disposed) await _refreshWatches(_generation);
- await reload();
- }
+ Future<void> start() => reload();
Future<void> reload({bool fromWatcher = false}) async {
if (_disposed) return;
if (!fromWatcher) _watchFailures = 0;
final generation = ++_generation;
final priorError = error;
+ // Establish watches before reading or publishing the new map. Retargeting
+ // a dotfile symlink can move it to a directory we do not watch yet; a save
+ // between publication and subscription would otherwise be missed. Reading
+ // after subscription also includes edits made during target discovery.
+ if (watchFiles) await _refreshWatches(generation);
+ if (_disposed || generation != _generation) return;
var changed = false;
try {
String source;
@@ -111,11 +115,6 @@ class KeymapStore extends ChangeNotifier {
(changed || priorError != error)) {
notifyListeners();
}
- final priorWatchError = error;
- if (watchFiles && !_disposed) await _refreshWatches(generation);
- if (!_disposed && generation == _generation && priorWatchError != error) {
- notifyListeners();
- }
}
String _describe(ResolvedKeymap map) => [
@@ -275,13 +274,13 @@ class KeymapStore extends ChangeNotifier {
'''// Harness keyboard overrides. Defaults are inherited.
// Save this file to apply changes. Invalid edits keep the last working keys.
// A null command unbinds a key or a sequence prefix.
-// "when" can be "workspace" (default), "terminal", or "picker".
-// Workspace bindings are inherited by the other two contexts.
+// "when" can be "workspace" (default), "terminal", "picker", or "project".
+// Workspace bindings are inherited by the other contexts.
{
"version": 1,
"bindings": [
- // Example: move search from Command-P to Command-O.
- // { "keys": "cmd+p", "command": null },
+ // Example: move New Tab from Command-T to Command-O.
+ // { "keys": "cmd+t", "command": null },
// { "keys": "cmd+o", "command": "swarm.new" },
],
}
diff --git a/desktop/lib/shortcuts/shortcuts_list.dart b/desktop/lib/shortcuts/shortcuts_list.dart
index 6ca4d2ce4..adfd3a5a6 100644
--- a/desktop/lib/shortcuts/shortcuts_list.dart
+++ b/desktop/lib/shortcuts/shortcuts_list.dart
@@ -86,7 +86,11 @@ class ShortcutsDeck extends StatelessWidget {
return LayoutBuilder(
builder: (context, constraints) {
final width = math.min(constraints.maxWidth, maxWidth);
- final columns = ((width + _gap) / (minCardWidth + _gap)).floor().clamp(
+ // Preserve room for the label as its keycaps grow. Otherwise large
+ // text keeps three narrow lanes and leaves only a word per line.
+ final textScale = MediaQuery.textScalerOf(context).scale(12.5) / 12.5;
+ final minWidth = minCardWidth * math.max(1.0, textScale);
+ final columns = ((width + _gap) / (minWidth + _gap)).floor().clamp(
1,
_maxColumns,
);
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 340a61f5b..204826c0a 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7,7 +7,7 @@ import 'package:dio/dio.dart';
import 'dart:ui' show Color;
import 'package:flutter/foundation.dart';
-import 'package:flutter/widgets.dart' show BuildContext;
+import 'package:flutter/widgets.dart' show BuildContext, StringCharacters;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../analytics/analytics.dart';
@@ -46,6 +46,7 @@ import '../widgets/engine_identity.dart'
show allEngines, engineIdentity, isTerminalEngine;
import '../store/store_screen.dart' show openStoreAgent;
import 'dial_status.dart';
+import 'harness_placement.dart';
import 'pane_layout_store.dart';
import 'terminal_pane.dart';
import 'swarm.dart';
@@ -83,11 +84,36 @@ enum MachineTransportMode { cloudE2ee, localPlaintext, localOffline }
class RestartAgentResult {
final String? error;
final bool resumed;
+ final bool retryable;
- const RestartAgentResult({this.error, this.resumed = true});
+ const RestartAgentResult({
+ this.error,
+ this.resumed = true,
+ this.retryable = true,
+ });
+}
+
+/// A restart keeps its receipt when its progress prompt closes. Checking an
+/// uncertain result must not replace the process a second time.
+class AgentRestartAttempt {
+ AgentRestartAttempt._(this._machine, this.agent, this._authRevision)
+ : _removal = _machine?._agentRemovals[agent?.id],
+ _stopRevision = _machine?._agentStopRevisions[agent?.id];
+ final MachineState? _machine;
+ final Agent? agent;
+ final int _authRevision;
+ final int? _removal, _stopRevision;
+ String? _id;
+ int _startedRevision = 0;
+ bool _awaitingConfirmation = false;
+ Future<RestartAgentResult>? _pending;
+ RestartAgentResult? result;
+ bool get awaitingConfirmation => _awaitingConfirmation;
+ bool get busy => _pending != null;
+ Future<RestartAgentResult>? get pending => _pending;
}
-/// Result of [AppNotifier.forkAgent]. [error] null means the fork is open;
+/// Result of [AppNotifier.forkAgent]. [error] null means the fork was created;
/// [level] then says what it got — `native` (the engine's own fork, the whole
/// context) or `handoff` (a first message composed from what the daemon
/// remembers of the source, for an engine that cannot fork).
@@ -95,29 +121,68 @@ class ForkAgentResult {
final String? error;
final String level;
final String? agentId;
+ final String? notice;
+
+ const ForkAgentResult({
+ this.error,
+ this.level = 'native',
+ this.agentId,
+ this.notice,
+ });
+}
+
+String _newCreationId() {
+ final random = Random.secure();
+ return List.generate(
+ 16,
+ (_) => random.nextInt(256),
+ ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
+}
- const ForkAgentResult({this.error, this.level = 'native', this.agentId});
+/// An in-memory draft and one deliberate fork. A lost receipt locks its
+/// choices until status is checked or the user explicitly starts another fork.
+class AgentForkAttempt {
+ AgentForkAttempt._(
+ this._machine,
+ this.source,
+ this._authRevision,
+ this._removal, {
+ this.name = '',
+ this.prompt = '',
+ });
+ final MachineState? _machine;
+ final Agent? source;
+ final int _authRevision;
+ final int? _removal;
+ String name, prompt;
+ String? _id;
+ Swarm? _target;
+ int? _focus;
+ int _startedRevision = 0;
+ bool _awaitingConfirmation = false;
+ Future<ForkAgentResult>? _inFlight;
+ ForkAgentResult? result;
+ bool get awaitingConfirmation => _awaitingConfirmation;
+ bool get busy => _inFlight != null;
+ bool get locked => busy || awaitingConfirmation;
+ Future<ForkAgentResult>? get pending => _inFlight;
}
/// One deliberate creation, retained by the form if its reply is lost. Reusing
/// it checks the original request; opening New agent starts a fresh intent.
class AgentCreationAttempt {
- AgentCreationAttempt() {
- final random = Random.secure();
- _id = List.generate(
- 16,
- (_) => random.nextInt(256),
- ).map((byte) => byte.toRadixString(16).padLeft(2, '0')).join();
- }
-
- late final String _id;
+ String _id = _newCreationId();
String? _machineId, _targetId;
Map<String, dynamic>? _choices;
PaneSplitRequest? _split;
+ HarnessPlacement? _placement;
Future<String?>? _inFlight;
bool _awaitingConfirmation = false, _finished = false;
String? _outcome;
String? _preparedFolder;
+ ProjectFolderRequest? _projectFolder;
+ String? _remoteProjectName;
+ int _projectNameRetries = 0;
bool get awaitingConfirmation => _awaitingConfirmation;
@@ -168,6 +233,12 @@ Map<String, dynamic> eventWithClearPayload(
class MachineState {
Machine machine;
+ int _agentRevision = 0;
+ final _agentRemovals = <String, int>{};
+ final _agentStopRevisions = <String, int>{};
+ final _agentRestartRevisions = <String, int>{};
+ final _agentNames =
+ <String, ({int revision, String? sessionId, String name})>{};
ConnectionStatus connectionStatus = ConnectionStatus.disconnected;
MachineTransportMode transportMode = MachineTransportMode.cloudE2ee;
@@ -187,6 +258,7 @@ class MachineState {
String? agentsLoadError;
Future<void>? agentsLoadInFlight;
Future<void>? terminalCapabilityLoadInFlight;
+ int _discoveryRevision = 0;
String? activeAgentId;
bool terminalCapabilityLoaded = false;
bool terminalCapabilityAvailable = false;
@@ -301,6 +373,47 @@ class RailRow {
int get hashCode => Object.hash(machineId, agentId);
}
+class _MachineLinkAttempt {
+ _MachineLinkAttempt(this.authRevision);
+ final int authRevision;
+ final result = Completer<String?>();
+ String stage = 'connecting';
+}
+
+class _RemotePasswordChange {
+ _RemotePasswordChange(this.authRevision, {required this.clearing});
+ final int authRevision;
+ final bool clearing;
+ final result = Completer<RemotePasswordStatus>();
+}
+
+class _MachineEdit {
+ _MachineEdit(this.machine, this.authRevision, this.name);
+ final MachineState machine;
+ final int authRevision;
+ final String? name; // null deletes the machine; a string renames it.
+ final result = Completer<String?>();
+}
+
+class _AgentRename {
+ _AgentRename(this.machine, this.agent, this.authRevision, this.name)
+ : nameRevision = machine._agentRevision;
+ final MachineState machine;
+ final Agent agent;
+ final int authRevision, nameRevision;
+ final String name;
+ final result = Completer<String?>();
+}
+
+class _AgentStop {
+ _AgentStop(this.machine, this.agent, this.authRevision);
+ final MachineState machine;
+ final Agent agent;
+ final int authRevision;
+ bool confirmed = false;
+ final result = Completer<String?>();
+}
+
class AppNotifier extends ChangeNotifier {
final AuthSession session;
AppConfig config;
@@ -316,6 +429,30 @@ class AppNotifier extends ChangeNotifier {
/// viewer. THIS machine's own remote password stays on [cliLink] — a viewer is not a machine, and
/// has no password for anyone to link to.
late final PeerLinkClient peerLinks;
+ final _machineLinks = <String, _MachineLinkAttempt>{};
+ final _machineEdits = <String, _MachineEdit>{};
+ final _agentRenames = <(String, String), _AgentRename>{};
+ final _agentStops = <(String, String), _AgentStop>{};
+ final _agentForks = <(String, String), AgentForkAttempt>{};
+ final _agentRestarts = <(String, String), AgentRestartAttempt>{};
+ int _machineEditRevision = 0;
+ // Account edits outrank inventories requested before them, and the daemon’s
+ // offline cache. Keep per-id revisions for overlapping inventory requests.
+ final _confirmedMachineEdits = <String, (int, String?)>{};
+
+ /// Linking belongs to the machine, so closing its prompt cannot start a
+ /// second handshake when the same prompt is reopened.
+ Future<String?>? pendingMachineLink(String machineId) {
+ final attempt = _machineLinks[machineId];
+ return attempt != null && _authWorkCurrent(attempt.authRevision)
+ ? attempt.result.future
+ : null;
+ }
+
+ String? machineLinkStage(String machineId) =>
+ pendingMachineLink(machineId) == null
+ ? null
+ : _machineLinks[machineId]?.stage;
/// A viewer build's stand-ins for the harness CLI (`lib/viewer/`); null on a desktop build.
final ViewerServices? viewer;
@@ -425,13 +562,17 @@ class AppNotifier extends ChangeNotifier {
// Update checks do not depend on the daemon or SSO. A signed-out user should
// still be able to replace a broken desktop build from the login screen.
Timer? _updateCheckTimer;
+ late final DesktopUpdater _updater = desktopUpdater ?? DesktopUpdater();
+ Future<ManualUpdateCheck>? _manualUpdateCheckInFlight;
+ DesktopUpdateCheck? lastUpdateCheck;
+ bool get updateChecksEnabled => viewer == null && _updater.canCheck;
String? _skippedDesktopUpdateVersion;
UpdateInfo? availableUpdate;
bool isCheckingForUpdate = false;
bool isInstallingUpdate = false;
String? updateError;
final Set<String> _offlinePollsInFlight = {};
- final Set<String> _offlineRecoveryInFlight = {};
+ final Map<String, Object> _offlineRecoveryInFlight = {};
bool _disposed = false;
// Account and inventory replies belong to the session that requested them.
@@ -444,12 +585,26 @@ class AppNotifier extends ChangeNotifier {
int _invalidateAuthWork() {
_stopMachineRecovery();
+ api.resetAccountCache();
+ _sessionExpired = false;
_machineLoadError = null;
_resetLoginBrowser();
_loginAuthorized = false;
_profileInFlight = null;
_retryInFlight = null;
machinesLoading = false;
+ _machineInventoryLoaded = false;
+ _linkedMachinesRequest = null;
+ _unlinkRequests.clear();
+ _machineEdits.clear();
+ _agentRenames.clear();
+ _agentStops.clear();
+ _agentForks.clear();
+ _agentRestarts.clear();
+ _confirmedMachineEdits.clear();
+ linkedMachines = [];
+ linkedMachinesLoading = false;
+ linkedMachinesError = null;
return ++_authRevision;
}
@@ -466,6 +621,7 @@ class AppNotifier extends ChangeNotifier {
String? _bootStatusMessage;
EnvironmentReadiness environmentReadiness = EnvironmentReadiness.initial();
bool _environmentSetupInFlight = false;
+ bool _environmentInstallRequested = false;
// Polls a step stuck in needsTerminal/failed every 5s (see `_scheduleEnvironmentRecheck`) so a user
// who fixes it by hand in their own terminal doesn't have to remember to click Recheck. A one-shot
// Timer that reschedules itself rather than `Timer.periodic`, so a slow recheck can't overlap with
@@ -480,6 +636,7 @@ class AppNotifier extends ChangeNotifier {
/// screen disable its Recheck/Start over buttons and show a spinner instead of a second click
/// racing the first.
bool get environmentSetupInFlight => _environmentSetupInFlight;
+ bool get environmentInstallRequested => _environmentInstallRequested;
// The daemon's own advertised local-ws endpoint — the dial target for EVERY machine's data plane
// now, not just this computer's own one (see src/lib/remoteRelay.ts in the harness CLI repo: a
@@ -835,6 +992,7 @@ class AppNotifier extends ChangeNotifier {
final swarm = swarms.where((s) => s.id == id).firstOrNull;
if (swarm == null) return;
swarm.name = clean.length > 80 ? clean.substring(0, 80) : clean;
+ swarm.nameIsCustom = true;
_persistLayout();
notifyListeners();
}
@@ -949,12 +1107,20 @@ class AppNotifier extends ChangeNotifier {
selectSwarm(target.id);
return;
}
- final restored = Swarm(id: saved.id, name: saved.name, kind: saved.kind)
- ..orchestratorId = saved.orchestratorId
- ..orchestratorMachineId = saved.orchestratorMachineId
- ..gridColumns = saved.gridColumns
- ..presets.addAll(saved.presets)
- ..paneSizes.addAll(saved.paneSizes);
+ final restored =
+ Swarm(
+ id: saved.id,
+ name: saved.name,
+ kind: saved.kind,
+ nameIsCustom: saved.nameIsCustom,
+ )
+ ..titleMachineId = saved.titleMachineId
+ ..titleAgentId = saved.titleAgentId
+ ..orchestratorId = saved.orchestratorId
+ ..orchestratorMachineId = saved.orchestratorMachineId
+ ..gridColumns = saved.gridColumns
+ ..presets.addAll(saved.presets)
+ ..paneSizes.addAll(saved.paneSizes);
for (final entry in saved.panes) {
final pane = pool.putIfAbsent(
(entry.machineId, entry.agentId),
@@ -1234,6 +1400,12 @@ class AppNotifier extends ChangeNotifier {
///
/// This flag spans the whole flow, so the screen the user pressed a button on stays put.
bool signingIn = false;
+ bool _sessionExpired = false;
+ bool get sessionExpired => _sessionExpired;
+ bool signingOut = false;
+ String? signOutError;
+ Future<void>? _logoutInFlight;
+ Future<void>? _workspaceCleanup;
AppNotifier({
required AppConfig config,
@@ -1291,6 +1463,11 @@ class AppNotifier extends ChangeNotifier {
/// because we could not read the list?" needs the narrower question.
String? get machineListError => _machineLoadError;
+ /// A completed inventory distinguishes initial waiting from an unavailable
+ /// machine. This also covers cached results; [machinesAreStale] qualifies them.
+ bool _machineInventoryLoaded = false;
+ bool get machineInventoryLoaded => _machineInventoryLoaded;
+
/// True when the machine list on screen came from the daemon's cache because the backend could not be
/// reached. The rows are the last known-good ones, not current.
bool machinesAreStale = false;
@@ -1618,6 +1795,11 @@ class AppNotifier extends ChangeNotifier {
/// What a machine hears the moment its socket is up — first connect, or a
/// reconnect after its daemon restarted, which has forgotten all of it.
void _onMachineConnected(String machineId, MachineState machine) {
+ _resetMachineDiscovery(machine);
+ _markSessionsUnreachable(
+ machine,
+ 'Harness reconnected; restoring terminal…',
+ );
machine.needsLink = false;
_stopLinkRetry(machineId);
// A daemon that just came up — first connect, or a reconnect after it
@@ -2031,6 +2213,7 @@ class AppNotifier extends ChangeNotifier {
if (viewer != null) return true;
if (_environmentSetupInFlight) return false;
_environmentSetupInFlight = true;
+ _environmentInstallRequested = false;
status = AppStatus.checkingEnvironment;
environmentReadiness = EnvironmentReadiness.initial();
notifyListeners();
@@ -2152,6 +2335,9 @@ class AppNotifier extends ChangeNotifier {
}
void selectEnvironmentSetupMode(EnvironmentSetupMode mode) {
+ if (mode == EnvironmentSetupMode.manual) {
+ _environmentInstallRequested = false;
+ }
environmentReadiness = environmentReadiness.copyWith(mode: mode);
notifyListeners();
}
@@ -2164,6 +2350,7 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
return;
}
+ _environmentInstallRequested = true;
_environmentSetupInFlight = true;
notifyListeners();
try {
@@ -2231,7 +2418,9 @@ class AppNotifier extends ChangeNotifier {
// Every host step done means only the Harness CLI is left, and that
// installs in-app without another prompt — so carry on into it.
if (!result.isReady &&
+ _environmentInstallRequested &&
mode == EnvironmentSetupMode.automatic &&
+ result.phase != EnvironmentSetupPhase.failed &&
result.phase != EnvironmentSetupPhase.waitingForTerminal &&
result.hostReady) {
result = await _runProvisioner(
@@ -2594,53 +2783,161 @@ class AppNotifier extends ChangeNotifier {
return; // idempotent: several sources can race here
}
_invalidateAuthWork();
+ cliLogin.cancel();
+ _sessionExpired = true;
currentUser = null;
signingIn = false;
pendingAuthorizeUrl = null;
_awaitingFirstMessage = null;
analyticsAccount.clear();
- _daemonSupervisionTimer?.cancel();
- _daemonSupervisionTimer = null;
- _cliEndpoint = null;
- unawaited(_pool?.closeAll());
- _pool = null;
+ _clearAccountWorkspace();
_lastError = message;
_lastErrorRetryable = true;
status = AppStatus.unauthenticated;
notifyListeners();
}
+ /// Remove the old account's live objects without overwriting its saved desk.
+ /// In particular, multiple emptied tabs must not prevent the next restore.
+ void _clearAccountWorkspace() {
+ ++_layoutRevision;
+ _stopAllOfflineRetries();
+ _stopAllLinkRetries();
+ _stopAllAgentSyncTimers();
+ _daemonSupervisionTimer?.cancel();
+ _daemonSupervisionTimer = null;
+ _sharingDiscoveryTimer?.cancel();
+ _sharingDiscoveryTimer = null;
+ _sharingDiscoveryBusy = false;
+ _daemonGateFailed = false;
+ _bootStatusMessage = null;
+ _clearAllTurnActivity();
+ // Start all terminal detachments while their original transports exist.
+ final panesClosed = _closeAllPanes(persist: false);
+ final pool = _pool;
+ _pool = null;
+ _cliEndpoint = null;
+ _backendOnline = null;
+ machines = [];
+ machinesAreStale = false;
+ machineStates.clear();
+ sessionPreviews.clear();
+ expandedMachines.clear();
+ selectedMachineId = null;
+ _closedHistory.clear();
+ _draftSwarmReturns.clear();
+ _localMismatchReported.clear();
+ _dismissedLinkPrompts.clear();
+ for (final controller in _orchestratorProjects.values) {
+ controller.dispose();
+ }
+ _orchestratorProjects.clear();
+ final starter = Swarm(id: 'swarm-${_nextSwarmId++}');
+ swarms
+ ..clear()
+ ..add(starter);
+ _activeSwarmId = starter.id;
+ _autoPickedAgent = false;
+ late final Future<void> cleanup;
+ cleanup =
+ Future.wait<void>([
+ ?_workspaceCleanup,
+ panesClosed,
+ if (pool != null) pool.closeAll(),
+ ])
+ .then<void>(
+ (_) {},
+ onError: (Object error) {
+ debugPrint('account connection cleanup failed: $error');
+ },
+ )
+ .whenComplete(() {
+ if (identical(_workspaceCleanup, cleanup)) {
+ _workspaceCleanup = null;
+ }
+ });
+ _workspaceCleanup = cleanup;
+ }
+
void _startUpdateChecking() {
- _updateCheckTimer ??= (desktopUpdater ?? DesktopUpdater()).startChecking(
- onUpdateAvailable: _handleBackgroundUpdate,
+ _updateCheckTimer ??= _updater.startChecking(
+ onCheckCompleted: (result) {
+ if (_disposed) return;
+ _recordUpdateCheck(result);
+ notifyListeners();
+ },
);
}
- void _handleBackgroundUpdate(UpdateInfo info) {
+ void _recordUpdateCheck(DesktopUpdateCheck result, {bool manual = false}) {
if (_disposed) return;
- if (_skippedDesktopUpdateVersion == info.version) return;
- if (availableUpdate?.version == info.version) return;
- availableUpdate = info;
- updateError = null;
- notifyListeners();
+ lastUpdateCheck = result;
+ if (isInstallingUpdate) return;
+ final info = result.update;
+ if (info != null) {
+ if (!manual && _skippedDesktopUpdateVersion == info.version) {
+ // A manual check may already be offering this skipped version. A
+ // concurrent background answer must not withdraw that explicit offer.
+ if (availableUpdate?.version != info.version) {
+ availableUpdate = null;
+ updateError = null;
+ }
+ } else {
+ if (availableUpdate?.version != info.version) updateError = null;
+ availableUpdate = info;
+ }
+ } else if (result.status == DesktopUpdateCheckStatus.upToDate) {
+ availableUpdate = null;
+ updateError = null;
+ }
+ // Failure/disabled leaves the last known offer and any install failure
+ // intact. A check error is not an installation error or an all-clear.
}
/// A manual check deliberately returns a skipped version too, so the user
/// can choose to install it from the account menu after changing their mind.
- Future<ManualUpdateCheck> checkForUpdates() async {
- if (isCheckingForUpdate) {
- return ManualUpdateCheck(update: availableUpdate);
+ Future<ManualUpdateCheck> checkForUpdates() {
+ // Viewer builds are updated by their app store. Do not even construct a
+ // desktop updater there: those platforms have no desktop artifact channel.
+ if (viewer != null) {
+ return Future.value(
+ const ManualUpdateCheck(check: DesktopUpdateCheck.disabled()),
+ );
+ }
+ final pending = _manualUpdateCheckInFlight;
+ if (pending != null) return pending;
+ if (_disposed) {
+ return Future.value(
+ const ManualUpdateCheck(check: DesktopUpdateCheck.failed()),
+ );
}
+ final completion = Completer<ManualUpdateCheck>();
+ _manualUpdateCheckInFlight = completion.future;
isCheckingForUpdate = true;
- updateError = null;
notifyListeners();
+ unawaited(_checkForUpdates(completion));
+ return completion.future;
+ }
+
+ Future<void> _checkForUpdates(Completer<ManualUpdateCheck> completion) async {
try {
- final info = await (desktopUpdater ?? DesktopUpdater()).checkOnce();
- if (info == null) return const ManualUpdateCheck();
- final skipped = _skippedDesktopUpdateVersion == info.version;
- availableUpdate = info;
- return ManualUpdateCheck(update: info, isSkipped: skipped);
+ final result = await _updater.check();
+ _recordUpdateCheck(result, manual: true);
+ completion.complete(
+ ManualUpdateCheck(
+ check: result,
+ isSkipped:
+ result.update != null &&
+ _skippedDesktopUpdateVersion == result.update!.version,
+ ),
+ );
+ } catch (error) {
+ debugPrint('AppNotifier.checkForUpdates: $error');
+ const failed = DesktopUpdateCheck.failed();
+ _recordUpdateCheck(failed);
+ completion.complete(const ManualUpdateCheck(check: failed));
} finally {
+ _manualUpdateCheckInFlight = null;
isCheckingForUpdate = false;
if (!_disposed) notifyListeners();
}
@@ -2657,26 +2954,34 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
- Future<void> skipAvailableUpdate() async {
- final info = availableUpdate;
- if (info == null) return;
+ Future<void> skipAvailableUpdate({UpdateInfo? update}) async {
+ final info = update ?? availableUpdate;
+ if (_disposed || info == null || isInstallingUpdate) return;
_skippedDesktopUpdateVersion = info.version;
await _store?.saveSkippedDesktopUpdateVersion(info.version);
- availableUpdate = null;
- updateError = null;
+ if (_disposed) return;
+ if (availableUpdate?.version == info.version) {
+ availableUpdate = null;
+ updateError = null;
+ }
notifyListeners();
}
/// Downloads, verifies, and installs only after an explicit user action.
/// A failed operation leaves the running app untouched and retryable.
- Future<bool> installAvailableUpdate() async {
- final info = availableUpdate;
- if (info == null || isInstallingUpdate) return false;
+ Future<bool> installAvailableUpdate({UpdateInfo? update}) async {
+ final info = update ?? availableUpdate;
+ if (_disposed || viewer != null || info == null || isInstallingUpdate) {
+ return false;
+ }
+ // The displayed version is the one the user chose. Later manifest
+ // responses cannot change the installation or the offer a failure retains.
+ availableUpdate = info;
isInstallingUpdate = true;
updateError = null;
notifyListeners();
try {
- final updater = desktopUpdater ?? DesktopUpdater();
+ final updater = _updater;
final staged = await updater.downloadAndStage(info);
if (staged == null) {
updateError =
@@ -2700,7 +3005,7 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> login() async {
- if (_disposed || signingIn) return;
+ if (_disposed || signingIn || signingOut || signOutError != null) return;
final revision = _invalidateAuthWork();
_closedHistory.clear();
_lastError = null;
@@ -2709,6 +3014,10 @@ class AppNotifier extends ChangeNotifier {
pendingAuthorizeUrl = null;
notifyListeners();
try {
+ if (_workspaceCleanup case final cleanup?) {
+ await cleanup;
+ if (!_authWorkCurrent(revision)) return;
+ }
await cliLogin.login(
onAuthorizeUrl: (url) {
if (!_authWorkCurrent(revision)) return;
@@ -2830,41 +3139,47 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
- Future<void> logout() async {
+ Future<void> logout() {
+ if (_disposed) return Future<void>.value();
+ if (_logoutInFlight case final pending?) return pending;
+ final completion = Completer<void>();
+ final result = _logoutInFlight = completion.future;
+ unawaited(
+ _logout().then(
+ (_) {
+ _logoutInFlight = null;
+ completion.complete();
+ },
+ onError: (Object error, StackTrace stack) {
+ _logoutInFlight = null;
+ completion.completeError(error, stack);
+ },
+ ),
+ );
+ return result;
+ }
+
+ Future<void> _logout() async {
final revision = _invalidateAuthWork();
cliLogin.cancel();
signingIn = false;
+ signingOut = true;
+ signOutError = null;
+ _lastError = null;
pendingAuthorizeUrl = null;
_closedHistory.clear();
- // Best-effort and fire-and-forget: local state is cleared below regardless of whether the CLI
- // process could be reached, but a real `harness logout` clears its saved session so the NEXT
- // launch doesn't silently sign back in without ever showing the login screen.
- unawaited(cliLogin.logout());
- _stopAllOfflineRetries();
- _stopAllLinkRetries();
- _stopAllAgentSyncTimers();
- // Tiles go, the saved layout stays: signing out and back in is the same
- // person at the same desk, and the file is only read once machines exist.
- await _closeAllPanes(persist: false);
- if (!_authWorkCurrent(revision)) return;
- _closedHistory.clear();
- await _pool?.closeAll();
- if (!_authWorkCurrent(revision)) return;
- _pool = null;
- _cliEndpoint = null;
- // Nothing to supervise for a signed-out app — and a daemon started by hand
- // on the login screen must not have its ready transition retry the machines.
- _daemonSupervisionTimer?.cancel();
- _daemonSupervisionTimer = null;
- _daemonGateFailed = false;
- _clearAllTurnActivity();
- currentUser = null;
- machines = [];
- machineStates.clear();
- sessionPreviews.clear();
- expandedMachines.clear();
- selectedMachineId = null;
status = AppStatus.unauthenticated;
+ currentUser = null;
+ analyticsAccount.clear();
+ notifyListeners();
+ // Clear saved credentials alongside connection cleanup. A new login must
+ // wait for both, otherwise the old logout can delete its fresh session.
+ // Disconnecting a development fixture must leave the real CLI alone.
+ final cleared = localManualFixture != null
+ ? Future<bool>.value(true)
+ : Future<void>.sync(cliLogin.logout)
+ .then((_) => true, onError: (Object _) => false);
+ _clearAccountWorkspace();
analytics.signedOut();
// A session that ended without a message reports nothing — its absence IS
// the finding, and a stale clock would attach that wait to whoever signs in
@@ -2872,6 +3187,14 @@ class AppNotifier extends ChangeNotifier {
_awaitingFirstMessage = null;
analyticsAccount.clear();
notifyListeners();
+ await _workspaceCleanup;
+ final didClear = await cleared;
+ if (!_authWorkCurrent(revision)) return;
+ signingOut = false;
+ signOutError = didClear
+ ? null
+ : 'Your saved sign-in could not be cleared. Try signing out again.';
+ notifyListeners();
}
void _onLocalFailure(String machineId, int code, String reason) {
@@ -3035,20 +3358,37 @@ class AppNotifier extends ChangeNotifier {
);
}
- Future<void> refreshMachines() async {
+ int _machineInventoryRevision = 0;
+
+ bool _machineInventoryCurrent(int auth, int request) =>
+ _authWorkCurrent(auth) && request == _machineInventoryRevision;
+
+ /// Whether this refresh was applied, rather than superseded by another
+ /// refresh or an account change.
+ Future<bool> refreshMachines() async {
+ final revision = _authRevision;
+ final request = await _refreshMachineInventory();
+ return request != null && _machineInventoryCurrent(revision, request);
+ }
+
+ // Return the request that published its result, so a retry's follow-up work
+ // cannot dismiss an error or reload panes for a superseded request.
+ Future<int?> _refreshMachineInventory() async {
final revision = _authRevision;
- if (!_authWorkCurrent(revision)) return;
+ if (!_authWorkCurrent(revision)) return null;
+ final request = ++_machineInventoryRevision;
if (localManualFixture != null) {
+ _machineInventoryLoaded = true;
notifyListeners();
- return;
+ return request;
}
if (machines.isEmpty && !machinesLoading) {
machinesLoading = true;
notifyListeners();
}
try {
- await _refreshMachines(revision);
- if (_authWorkCurrent(revision)) {
+ await _refreshMachines(revision, request);
+ if (_machineInventoryCurrent(revision, request)) {
// A cached answer is readable but not current, so the job is not done: leave the recovery timer
// running and it converges on its own once the backend is back. Without this the daemon's 200
// would read as success, recovery would stop, and the app would sit on stale rows until
@@ -3063,20 +3403,21 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
_machineLoadError = null;
+ return request;
}
+ return null;
} catch (error) {
- if (_authWorkCurrent(revision)) {
- if (isTransientApiError(error)) {
- _scheduleMachineRecovery(revision);
- } else {
- _stopMachineRecovery();
- }
+ if (!_machineInventoryCurrent(revision, request)) return null;
+ if (isTransientApiError(error)) {
+ _scheduleMachineRecovery(revision);
+ } else {
+ _stopMachineRecovery();
}
rethrow;
} finally {
// Said out loud: the list's own notify fires before this, so a flag
// dropped silently here would leave the rail on its placeholders.
- if (_authWorkCurrent(revision) && machinesLoading) {
+ if (_machineInventoryCurrent(revision, request) && machinesLoading) {
machinesLoading = false;
notifyListeners();
}
@@ -3211,14 +3552,14 @@ class AppNotifier extends ChangeNotifier {
}
}
- Future<void> _refreshMachines(int revision) async {
+ Future<void> _refreshMachines(int revision, int request) async {
// No machine is "this computer" to a viewer, which has no local CLI: every one — even the one
// it runs on — is reached through the relay.
final discovery = viewer == null ? _discovery : null;
// The CLI computer id is the local identity source of truth. The loopback
// status endpoint is trusted only when it advertises that same identity.
final localComputerId = await discovery?.computerId();
- if (!_authWorkCurrent(revision)) return;
+ if (!_machineInventoryCurrent(revision, request)) return;
// Null in a viewer build, which has no local CLI to probe — see `discovery` above.
final localFuture =
discovery?.discover(expectedComputerId: localComputerId) ??
@@ -3237,16 +3578,18 @@ class AppNotifier extends ChangeNotifier {
},
);
final List<Machine> list;
+ final bool stale;
+ final editRevision = _machineEditRevision;
try {
list = await _fetchMachines();
- machinesAreStale = api.lastMachinesStale;
+ stale = list is MachineInventory ? list.isStale : api.lastMachinesStale;
} catch (_) {
// A backend outage must not cost this computer its own transport. Without this the probe result
// stayed unapplied, so `usesLocalTransport` went false and `_connectMachine` skipped the local
// machine — while relayed machines, which never consult it, kept streaming. That asymmetry was the
// bug: the local terminal stopped rendering and the relayed ones did not.
await localSettled;
- if (_authWorkCurrent(revision)) {
+ if (_machineInventoryCurrent(revision, request)) {
final endpoint = probed;
// The probe is the freshest word on the backend link — fresher than the supervisor's last
// tick — and it decides whether this failure is an outage to report or just "offline".
@@ -3273,14 +3616,41 @@ class AppNotifier extends ChangeNotifier {
await localSettled;
// Both legs are in: this is the one gate that decides whether a result that arrived after a
// sign-out or a dispose may still be published.
- if (!_authWorkCurrent(revision)) return;
+ if (!_machineInventoryCurrent(revision, request)) return;
+ _machineInventoryLoaded = true;
+ machinesAreStale = stale;
final localEndpoint = probed;
if (localEndpoint != null) {
_noteBackendOnline(localEndpoint.backendOnline, refetch: false);
}
- machines = list
- .where((machine) => machine.authMode == MachineAuthMode.remote)
- .toList();
+ machines = [];
+ for (final machine in list) {
+ if (machine.authMode != MachineAuthMode.remote) continue;
+ final edit = _confirmedMachineEdits[machine.machineId];
+ if (edit != null && (edit.$1 > editRevision || machinesAreStale)) {
+ if (edit.$2 case final name?) {
+ machines.add(machine.copyWith(name: name));
+ }
+ } else {
+ machines.add(machine);
+ if (edit != null) {
+ // A newer authoritative inventory may contain a rename performed
+ // elsewhere. Its value becomes the protection against cached reads.
+ _confirmedMachineEdits[machine.machineId] = (
+ edit.$1,
+ machine.displayName,
+ );
+ }
+ }
+ }
+ if (!machinesAreStale) {
+ final listed = list.map((machine) => machine.machineId).toSet();
+ _confirmedMachineEdits.updateAll(
+ (id, edit) => edit.$1 <= editRevision && !listed.contains(id)
+ ? (edit.$1, null)
+ : edit,
+ );
+ }
final visible = machines.map((machine) => machine.machineId).toSet();
for (final entry in machineStates.entries) {
if (!visible.contains(entry.key)) {
@@ -3375,7 +3745,7 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
} finally {
- _sharingDiscoveryBusy = false;
+ if (_authWorkCurrent(discoveryRevision)) _sharingDiscoveryBusy = false;
}
});
notifyListeners();
@@ -3444,6 +3814,7 @@ class AppNotifier extends ChangeNotifier {
}
_offlineRetryTimers.clear();
_offlinePollsInFlight.clear();
+ _offlineRecoveryInFlight.clear();
}
void _startAgentSyncTimer(String machineId) {
@@ -3476,19 +3847,30 @@ class AppNotifier extends ChangeNotifier {
/// a real connectivity problem is already surfaced by the push path and the existing offline
/// detection in _performMachineDataLoad, and a quiet background tick should not fight either.
Future<void> _syncAgentsIfChanged(MachineState machine) async {
+ final revision = _authRevision;
+ final discoveryRevision = machine._discoveryRevision;
+ if (!_machineWorkCurrent(machine, revision)) return;
if (machine.connectionStatus != ConnectionStatus.connected) return;
if (machine.agentsLoadInFlight != null) {
return; // a real (foreground) load already owns this tick
}
final connection = _conn(machine.machine.machineId);
+ final nameRevision = machine._agentRevision;
try {
final response = await connection.request(
'agents_list',
timeout: const Duration(seconds: 10),
);
- final agents = (response['agents'] as List<dynamic>? ?? [])
- .map((item) => Agent.fromJson(item as Map<String, dynamic>))
- .toList();
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
+ final agents = _agentSnapshot(
+ machine,
+ (response['agents'] as List<dynamic>? ?? [])
+ .map((item) => Agent.fromJson(item as Map<String, dynamic>))
+ .toList(),
+ nameRevision,
+ );
if (agentsEqual(machine.agents, agents)) return;
_replaceAgents(machine, agents);
notifyListeners();
@@ -3549,71 +3931,274 @@ class AppNotifier extends ChangeNotifier {
String machineId,
String password, {
void Function(String stage)? onProgress,
- }) async {
- if (password.isEmpty) return 'Enter the remote password first';
- final result = await peerLinks.connect(
- machineId,
- password,
- onProgress: onProgress,
- displayName: machineStates[machineId]?.machine.displayName,
- );
- if (result.error != null) return result.error;
- final targetId = result.linkedMachineId ?? machineId;
- final state = machineStates[targetId];
- if (state != null) {
- state.needsLink = false;
- state.agentLoadStatus = AgentLoadStatus.idle;
- notifyListeners();
- // The old WsConn closed itself permanently on NO_PEER_LINK — connFor() would otherwise see a
- // matching endpointKey and hand back that dead connection instead of dialing a fresh one.
- await _pool?.closeMachine(targetId);
- _connectMachine(state);
+ }) {
+ final pending = pendingMachineLink(machineId);
+ if (pending != null) return pending;
+ if (password.isEmpty) {
+ return Future.value('Enter the remote password first');
+ }
+ if (_disposed) {
+ return Future.value('This connection request is no longer active.');
+ }
+ final attempt = _MachineLinkAttempt(_authRevision);
+ _machineLinks[machineId] = attempt;
+ notifyListeners();
+ unawaited(_connectWithPassword(machineId, password, attempt, onProgress));
+ return attempt.result.future;
+ }
+
+ Future<void> _connectWithPassword(
+ String machineId,
+ String password,
+ _MachineLinkAttempt attempt,
+ void Function(String)? onProgress,
+ ) async {
+ String? error;
+ try {
+ final result = await peerLinks.connect(
+ machineId,
+ password,
+ onProgress: (stage) {
+ if (!_authWorkCurrent(attempt.authRevision)) return;
+ attempt.stage = stage;
+ onProgress?.call(stage);
+ notifyListeners();
+ },
+ displayName: machineStates[machineId]?.machine.displayName,
+ );
+ error = result.error;
+ if (!_authWorkCurrent(attempt.authRevision)) {
+ error ??= 'This connection request is no longer active.';
+ return;
+ }
+ if (error != null) return;
+ final targetId = result.linkedMachineId ?? machineId;
+ final state = machineStates[targetId];
+ if (state != null) {
+ state.needsLink = false;
+ state.agentLoadStatus = AgentLoadStatus.idle;
+ notifyListeners();
+ // NO_PEER_LINK permanently closes the old socket. Dial a fresh one.
+ await _pool?.closeMachine(targetId);
+ if (_authWorkCurrent(attempt.authRevision)) _connectMachine(state);
+ }
+ } catch (_) {
+ error = 'Could not link this machine. Try again.';
+ } finally {
+ if (identical(_machineLinks[machineId], attempt)) {
+ _machineLinks.remove(machineId);
+ }
+ attempt.result.complete(error);
+ if (_authWorkCurrent(attempt.authRevision)) notifyListeners();
}
- return null;
}
List<LinkedMachine> linkedMachines = [];
bool linkedMachinesLoading = false;
String? linkedMachinesError;
+ Future<void>? _linkedMachinesRequest;
+ final _unlinkRequests = <String, Future<String?>>{};
+ _RemotePasswordChange? _remotePasswordChange;
+ int _remotePasswordRevision = 0;
+
+ /// A password change survives closing its prompt. Reopening observes the
+ /// same operation without retaining another copy of the password.
+ Future<RemotePasswordStatus>? get pendingRemotePasswordChange {
+ final change = _remotePasswordChange;
+ return change != null && _authWorkCurrent(change.authRevision)
+ ? change.result.future
+ : null;
+ }
+
+ bool get clearingRemotePassword =>
+ pendingRemotePasswordChange != null && _remotePasswordChange!.clearing;
/// Sets (or replaces) THIS machine's persistent remote password (`harness remote-password
/// set --stdin --json`) — another machine later connects with `connectWithPassword` using the
/// same password, no token copy/paste involved.
- Future<RemotePasswordSetResult> setRemotePassword(String password) =>
- cliLink.setRemotePassword(password);
+ Future<RemotePasswordSetResult> setRemotePassword(String password) async {
+ final status = await _changeRemotePassword(password);
+ return RemotePasswordSetResult(
+ error: status.error,
+ fingerprint: status.fingerprint,
+ );
+ }
/// Queries THIS machine's remote-password state (`harness remote-password status --json`).
- Future<RemotePasswordStatus> remotePasswordStatus() =>
- cliLink.remotePasswordStatus();
+ Future<RemotePasswordStatus> remotePasswordStatus() async {
+ if (pendingRemotePasswordChange case final pending?) return pending;
+ final authRevision = _authRevision;
+ final passwordRevision = _remotePasswordRevision;
+ if (!_authWorkCurrent(authRevision)) {
+ return const RemotePasswordStatus(
+ error: 'This request is no longer active.',
+ );
+ }
+ RemotePasswordStatus result;
+ try {
+ result = await cliLink.remotePasswordStatus();
+ } catch (_) {
+ result = const RemotePasswordStatus(
+ error: 'Could not read this computer’s password status. Try again.',
+ );
+ }
+ if (!_authWorkCurrent(authRevision)) {
+ return const RemotePasswordStatus(
+ error: 'This request is no longer active.',
+ );
+ }
+ // A slow read must not replace a password changed while it was running.
+ if (passwordRevision != _remotePasswordRevision) {
+ return remotePasswordStatus();
+ }
+ return result;
+ }
/// Clears THIS machine's remote password (`harness remote-password clear --json`). Returns null
/// on success.
- Future<String?> clearRemotePassword() => cliLink.clearRemotePassword();
+ Future<String?> clearRemotePassword() async =>
+ (await _changeRemotePassword(null)).error;
+
+ Future<RemotePasswordStatus> _changeRemotePassword(String? password) {
+ if (_disposed) {
+ return Future.value(
+ const RemotePasswordStatus(error: 'This request is no longer active.'),
+ );
+ }
+ if (pendingRemotePasswordChange != null) {
+ return Future.value(
+ const RemotePasswordStatus(
+ error: 'A password change is already in progress.',
+ ),
+ );
+ }
+ final change = _RemotePasswordChange(
+ _authRevision,
+ clearing: password == null,
+ );
+ _remotePasswordChange = change;
+ _remotePasswordRevision++;
+ notifyListeners();
+ unawaited(_runRemotePasswordChange(change, password));
+ return change.result.future;
+ }
+
+ Future<void> _runRemotePasswordChange(
+ _RemotePasswordChange change,
+ String? password,
+ ) async {
+ RemotePasswordStatus result;
+ try {
+ if (password == null) {
+ result = RemotePasswordStatus(
+ error: await cliLink.clearRemotePassword(),
+ );
+ } else {
+ final set = await cliLink.setRemotePassword(password);
+ result = RemotePasswordStatus(
+ error: set.error,
+ hasPassword: set.error == null,
+ fingerprint: set.fingerprint,
+ setAt: set.error == null ? DateTime.now() : null,
+ );
+ }
+ } catch (_) {
+ result = RemotePasswordStatus(
+ error: change.clearing
+ ? 'Could not clear the password. Try again.'
+ : 'Could not set the password. Try again.',
+ );
+ }
+ if (!_authWorkCurrent(change.authRevision)) {
+ result = const RemotePasswordStatus(
+ error: 'This request is no longer active.',
+ );
+ }
+ if (identical(_remotePasswordChange, change)) _remotePasswordChange = null;
+ change.result.complete(result);
+ if (_authWorkCurrent(change.authRevision)) notifyListeners();
+ }
/// Refreshes the "machines this one trusts" list (`harness link list`).
- Future<void> refreshLinkedMachines() async {
+ Future<void> refreshLinkedMachines() {
+ if (_disposed) return Future.value();
+ if (_linkedMachinesRequest case final pending?) return pending;
+ final result = Completer<void>();
+ _linkedMachinesRequest = result.future;
+ unawaited(_loadLinkedMachines(_authRevision, result));
+ return result.future;
+ }
+
+ Future<void> _loadLinkedMachines(int revision, Completer<void> done) async {
linkedMachinesLoading = true;
notifyListeners();
- final result = await peerLinks.list();
- linkedMachinesLoading = false;
- linkedMachinesError = result.error;
- linkedMachines = result.machines;
- notifyListeners();
+ try {
+ final result = await peerLinks.list();
+ if (!_authWorkCurrent(revision)) return;
+ linkedMachinesError = result.error;
+ if (result.error == null) linkedMachines = result.machines;
+ } catch (_) {
+ if (_authWorkCurrent(revision)) {
+ linkedMachinesError = 'Could not load linked machines. Try again.';
+ }
+ } finally {
+ if (identical(_linkedMachinesRequest, done.future)) {
+ _linkedMachinesRequest = null;
+ }
+ if (_authWorkCurrent(revision)) {
+ linkedMachinesLoading = false;
+ notifyListeners();
+ }
+ done.complete();
+ }
}
/// Removes a linked machine's trust pin, then refreshes the list. Returns null on success.
- Future<String?> unlinkMachine(String machineId) async {
- final error = await peerLinks.unlink(machineId);
- if (error == null) await refreshLinkedMachines();
- return error;
+ Future<String?> unlinkMachine(String machineId) {
+ if (_disposed) return Future.value('This request is no longer active.');
+ return _unlinkRequests.putIfAbsent(
+ machineId,
+ () => _unlinkMachine(machineId, _authRevision),
+ );
}
- Future<void> _pollOfflineMachine(String machineId) async {
- final machine = machineStates[machineId];
- if (machine == null ||
- machine.nodeOnline != false ||
- (!machine.isLocalMachine && machine.pendingOfflineAgentId == null) ||
- _offlinePollsInFlight.contains(machineId)) {
+ bool unlinkingMachine(String machineId) =>
+ _unlinkRequests.containsKey(machineId);
+
+ Future<String?> _unlinkMachine(String machineId, int revision) async {
+ try {
+ final error = await peerLinks.unlink(machineId);
+ if (!_authWorkCurrent(revision)) {
+ return 'This request is no longer active.';
+ }
+ if (error == null) {
+ // Keep a successful removal visible even if refreshing the CLI list fails.
+ await _linkedMachinesRequest;
+ if (!_authWorkCurrent(revision)) {
+ return 'This request is no longer active.';
+ }
+ linkedMachines = linkedMachines
+ .where((machine) => machine.machineId != machineId)
+ .toList();
+ await refreshLinkedMachines();
+ }
+ return error;
+ } catch (_) {
+ return 'Could not unlink this machine. Try again.';
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ _unlinkRequests.remove(machineId);
+ notifyListeners();
+ }
+ }
+ }
+
+ Future<void> _pollOfflineMachine(String machineId) async {
+ final machine = machineStates[machineId];
+ if (machine == null ||
+ machine.nodeOnline != false ||
+ (!machine.isLocalMachine && machine.pendingOfflineAgentId == null) ||
+ _offlinePollsInFlight.contains(machineId)) {
return;
}
_offlinePollsInFlight.add(machineId);
@@ -3742,8 +4327,7 @@ class AppNotifier extends ChangeNotifier {
}
if (currentUser == null) unawaited(_loadProfile());
try {
- await refreshMachines();
- if (!_authWorkCurrent(revision)) return;
+ if (!await refreshMachines() || !_authWorkCurrent(revision)) return;
if (!automatic) _lastError = null;
} catch (error) {
if (!_authWorkCurrent(revision)) return;
@@ -3963,7 +4547,11 @@ class AppNotifier extends ChangeNotifier {
/// has one, else whatever the person is looking at. Never guessed past a
/// named machine: a picker on a remote pane that opened on this computer was
/// the bug this argument exists to end.
- Future<void> runLocalModel(BuildContext context, {String? machineId}) async {
+ Future<void> runLocalModel(
+ BuildContext context, {
+ String? machineId,
+ Future<void> Function(String harnessId, String machineId)? onOpenHarness,
+ }) async {
final machine = machineId != null
? machineStates[machineId]
: _localModelMachine();
@@ -3985,6 +4573,10 @@ class AppNotifier extends ChangeNotifier {
return;
}
if (!context.mounted) return;
+ if (onOpenHarness != null) {
+ await onOpenHarness(gridHarness, machineId);
+ return;
+ }
await openStoreAgent(context, this, gridHarness, machineId);
}
@@ -4000,7 +4592,10 @@ class AppNotifier extends ChangeNotifier {
/// so a copy opened on a remote machine would be describing that machine's
/// fleet, not the one in front of the person. Not installed here → the
/// Store, open on its page, whose Install is the way in.
- Future<void> manageMachines(BuildContext context) async {
+ Future<void> manageMachines(
+ BuildContext context, {
+ Future<void> Function(String harnessId, String machineId)? onOpenHarness,
+ }) async {
final machine = _localModelMachine();
if (machine == null) {
_lastError = 'Connect a machine before opening Machine Monitor.';
@@ -4015,6 +4610,10 @@ class AppNotifier extends ChangeNotifier {
return;
}
if (!context.mounted) return;
+ if (onOpenHarness != null) {
+ await onOpenHarness(machinesHarness, machineId);
+ return;
+ }
await openStoreAgent(context, this, machinesHarness, machineId);
}
@@ -4154,6 +4753,8 @@ class AppNotifier extends ChangeNotifier {
Future<void> _performMachineDataLoad(MachineState machine) async {
final revision = _authRevision;
+ final discoveryRevision = machine._discoveryRevision;
+ final nameRevision = machine._agentRevision;
final hadAgents = machine.agents.isNotEmpty;
machine.agentsRefreshing = hadAgents;
if (!hadAgents) machine.agentLoadStatus = AgentLoadStatus.loading;
@@ -4165,7 +4766,9 @@ class AppNotifier extends ChangeNotifier {
try {
const inventoryTimeout = Duration(seconds: 10);
await connection.waitUntilReady(timeout: inventoryTimeout);
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
// Keep the inventory's existing total budget, including connection time.
// Capabilities get their own budget only once the handshake is complete.
final remaining = inventoryTimeout - deadline.elapsed;
@@ -4176,15 +4779,22 @@ class AppNotifier extends ChangeNotifier {
machine,
connection,
revision,
+ discoveryRevision,
);
final response = await connection.request(
'agents_list',
timeout: remaining,
);
- if (!_machineWorkCurrent(machine, revision)) return;
- final agents = (response['agents'] as List<dynamic>? ?? [])
- .map((item) => Agent.fromJson(item as Map<String, dynamic>))
- .toList();
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
+ final agents = _agentSnapshot(
+ machine,
+ (response['agents'] as List<dynamic>? ?? [])
+ .map((item) => Agent.fromJson(item as Map<String, dynamic>))
+ .toList(),
+ nameRevision,
+ );
_replaceAgents(machine, agents);
machine.agentLoadStatus = AgentLoadStatus.loaded;
machine.agentsRefreshing = false;
@@ -4203,7 +4813,9 @@ class AppNotifier extends ChangeNotifier {
await capabilities;
return;
} catch (error) {
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
machine.agentsRefreshing = false;
// A request timing out while the local relay session still nominally reports "connected" means
// the remote node itself has stopped answering — exactly what a REST-status flip to offline
@@ -4234,7 +4846,7 @@ class AppNotifier extends ChangeNotifier {
}
debugPrint('agents_list failed: ${machine.machine.machineId}: $error');
}
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;
// Order matters: a restored tile for THIS machine claims its agent before
// the first-run convenience gets to look, so the two can never both open.
_attachPendingPanes(machine);
@@ -4246,6 +4858,36 @@ class AppNotifier extends ChangeNotifier {
_authWorkCurrent(revision) &&
identical(machineStates[machine.machine.machineId], machine);
+ bool _machineDiscoveryCurrent(
+ MachineState machine,
+ int auth,
+ int discovery,
+ ) =>
+ _machineWorkCurrent(machine, auth) &&
+ machine._discoveryRevision == discovery;
+
+ /// A new transport must negotiate its own capabilities and inventory. Release
+ /// the old futures immediately; their completions keep their original revision.
+ void _resetMachineDiscovery(MachineState machine) {
+ machine._discoveryRevision++;
+ _offlineRecoveryInFlight.remove(machine.machine.machineId);
+ machine.agentsLoadInFlight = null;
+ machine.terminalCapabilityLoadInFlight = null;
+ machine.agentsRefreshing = false;
+ if (machine.agentLoadStatus == AgentLoadStatus.loading) {
+ machine.agentLoadStatus = machine.agents.isEmpty
+ ? AgentLoadStatus.idle
+ : AgentLoadStatus.loaded;
+ }
+ machine.terminalCapabilityLoaded = false;
+ machine.terminalCapabilityAvailable = false;
+ machine.terminalCapabilityError = null;
+ machine.terminalPasteRawAvailable = false;
+ machine.terminalImagePasteAvailable = false;
+ machine.terminalPasteFileAvailable = false;
+ machine.mediaPreviewAvailable = false;
+ }
+
/// Whether the app has already opened a terminal on its own.
///
/// Once, at startup, and never again: a later refresh must not reopen a
@@ -4487,12 +5129,18 @@ class AppNotifier extends ChangeNotifier {
MachineState machine,
WsConn connection,
int revision,
+ int discoveryRevision,
) {
final pending = machine.terminalCapabilityLoadInFlight;
if (pending != null) return pending;
late final Future<void> load;
- load = _readTerminalCapabilities(machine, connection, revision)
- .whenComplete(() {
+ load =
+ _readTerminalCapabilities(
+ machine,
+ connection,
+ revision,
+ discoveryRevision,
+ ).whenComplete(() {
if (identical(machine.terminalCapabilityLoadInFlight, load)) {
machine.terminalCapabilityLoadInFlight = null;
}
@@ -4505,6 +5153,7 @@ class AppNotifier extends ChangeNotifier {
MachineState machine,
WsConn connection,
int revision,
+ int discoveryRevision,
) async {
try {
final result = await connection.request(
@@ -4512,7 +5161,9 @@ class AppNotifier extends ChangeNotifier {
payload: {'protocolVersion': TerminalSession.protocolVersion},
timeout: const Duration(seconds: 8),
);
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
machine.terminalCapabilityLoaded = true;
machine.terminalCapabilityAvailable =
result['protocolVersion'] == TerminalSession.protocolVersion &&
@@ -4531,7 +5182,9 @@ class AppNotifier extends ChangeNotifier {
machine.mediaPreviewAvailable =
features is Map && features['mediaPreview'] == true;
} catch (_) {
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) {
+ return;
+ }
machine.terminalCapabilityLoaded = true;
machine.terminalCapabilityAvailable = false;
machine.terminalCapabilityError = 'Could not negotiate terminal protocol';
@@ -4540,7 +5193,7 @@ class AppNotifier extends ChangeNotifier {
machine.terminalPasteFileAvailable = false;
machine.mediaPreviewAvailable = false;
}
- if (!_machineWorkCurrent(machine, revision)) return;
+ if (!_machineDiscoveryCurrent(machine, revision, discoveryRevision)) return;
if (machine.agentLoadStatus != AgentLoadStatus.loading &&
!machine.agentsRefreshing) {
_attachPendingPanes(machine);
@@ -4549,11 +5202,85 @@ class AppNotifier extends ChangeNotifier {
}
}
+ List<Agent> _agentSnapshot(
+ MachineState machine,
+ List<Agent> incoming,
+ int revision,
+ ) {
+ final agents = {
+ for (final agent in incoming)
+ agent.id: _preserveNewerName(machine, agent, revision),
+ };
+ for (final restart in machine._agentRestartRevisions.entries) {
+ if (restart.value <= revision) continue;
+ final current = machine.agents
+ .where((agent) => agent.id == restart.key)
+ .firstOrNull;
+ if (current != null) agents[restart.key] = current;
+ }
+ for (final removal in machine._agentRemovals.entries) {
+ if (removal.value <= revision) continue;
+ final current = machine.agents
+ .where((agent) => agent.id == removal.key)
+ .firstOrNull;
+ if (current == null) {
+ agents.remove(removal.key);
+ } else {
+ // A new incarnation seen after the stop also outranks this old read.
+ agents[removal.key] = current;
+ }
+ }
+ return agents.values.toList();
+ }
+
+ Agent _preserveNewerName(MachineState machine, Agent agent, int revision) {
+ final observed = machine._agentNames[agent.id];
+ return observed != null &&
+ observed.revision > revision &&
+ observed.sessionId == agent.sessionId
+ ? agent.copyWith(name: observed.name)
+ : agent;
+ }
+
+ void _recordAgentName(MachineState machine, Agent agent) {
+ machine._agentNames[agent.id] = (
+ revision: ++machine._agentRevision,
+ sessionId: agent.sessionId,
+ name: agent.name,
+ );
+ }
+
+ void _syncAgentName(MachineState machine, Agent agent) {
+ for (final pane in panesFor(machine.machine.machineId)) {
+ if (pane.agentId == agent.id) {
+ pane.session?.renameAgent(agent.displayName);
+ }
+ }
+ var changed = false;
+ for (final tab in swarms) {
+ if (!tab.nameIsCustom &&
+ tab.titleMachineId == machine.machine.machineId &&
+ tab.titleAgentId == agent.id) {
+ final title = agent.displayName == kUntitledPane
+ ? Swarm.defaultName
+ : agent.displayName;
+ if (tab.name != title) {
+ tab.name = title;
+ changed = true;
+ }
+ }
+ }
+ if (changed) _persistLayout();
+ }
+
void _replaceAgents(MachineState machine, List<Agent> agents) {
+ final previous = {for (final agent in machine.agents) agent.id: agent};
final nextIds = agents.map((agent) => agent.id).toSet();
+ machine._agentNames.removeWhere((id, _) => !nextIds.contains(id));
for (final old in machine.agents.where(
(agent) => !nextIds.contains(agent.id),
)) {
+ _agentRenames.remove((machine.machine.machineId, old.id));
sessionPreviews.removeAgent(machine.machine.machineId, old.id);
}
for (final agent in agents) {
@@ -4567,6 +5294,12 @@ class AppNotifier extends ChangeNotifier {
_cancelTurnActivity(machine.machine.machineId, agentId);
}
machine.agents = agents;
+ for (final agent in agents) {
+ if (previous[agent.id]?.name != agent.name) {
+ _recordAgentName(machine, agent);
+ }
+ _syncAgentName(machine, agent);
+ }
final pending = machine.pendingOfflineAgentId;
if (pending != null && !nextIds.contains(pending)) {
machine.pendingOfflineAgentId = null;
@@ -4603,6 +5336,8 @@ class AppNotifier extends ChangeNotifier {
} else {
machine.agents = [...machine.agents]..[index] = agent;
}
+ if (previous?.name != agent.name) _recordAgentName(machine, agent);
+ _syncAgentName(machine, agent);
sessionPreviews.retainAgent(
machine.machine.machineId,
agent.id,
@@ -4643,13 +5378,17 @@ class AppNotifier extends ChangeNotifier {
final cleanName = name.trim();
machine.agents = [...machine.agents]
..[index] = machine.agents[index].copyWith(name: cleanName);
- for (final pane in panesFor(machine.machine.machineId)) {
- if (pane.agentId != agentId) continue;
- pane.session?.renameAgent(cleanName);
- }
+ _recordAgentName(machine, machine.agents[index]);
+ _syncAgentName(machine, machine.agents[index]);
}
Future<void> _removeAgent(MachineState machine, String agentId) async {
+ final stop = _agentStops[(machine.machine.machineId, agentId)];
+ final confirmedStop = stop != null && _agentStopCurrent(stop) ? stop : null;
+ confirmedStop?.confirmed = true;
+ machine._agentRemovals[agentId] = ++machine._agentRevision;
+ _agentRenames.remove((machine.machine.machineId, agentId));
+ machine._agentNames.remove(agentId);
sessionPreviews.removeAgent(machine.machine.machineId, agentId);
machine.agents = machine.agents
.where((agent) => agent.id != agentId)
@@ -4665,20 +5404,32 @@ class AppNotifier extends ChangeNotifier {
// `terminal_close`, which would be addressed to an agent the machine has
// already destroyed.
final machineId = machine.machine.machineId;
+ final closing = <Future<void>>[];
for (final pane in allPanes.toList()) {
final owned =
pane.machineId == machineId &&
(pane.agentId == agentId ||
(pane.isWeb && pane.ownerAgentId == agentId));
if (!owned) continue;
- await _detachSession(pane, sendClose: false);
for (final swarm in swarms) {
swarm.remove(pane);
}
+ closing.add(_detachSession(pane, sendClose: false));
}
_dismissedViewers.remove(_viewerKey(machineId, agentId));
_persistLayout();
_announceAppFocus();
+ try {
+ await Future.wait(closing);
+ } catch (failure) {
+ appLog.warn(
+ 'agents',
+ 'Agent stopped; local view cleanup failed: $failure',
+ );
+ }
+ if (confirmedStop != null && !confirmedStop.result.isCompleted) {
+ confirmedStop.result.complete(null);
+ }
}
// ── harness viewers ─────────────────────────────────────────────────────────
@@ -5186,6 +5937,7 @@ class AppNotifier extends ChangeNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) {
final creation = attempt ?? AgentCreationAttempt();
final choices = <String, dynamic>{
@@ -5217,6 +5969,8 @@ class AppNotifier extends ChangeNotifier {
};
if (creation._choices != null &&
(creation._machineId != machineId ||
+ creation._projectFolder?.isGenerated !=
+ projectFolder?.isGenerated ||
!mapEquals(creation._choices, choices))) {
return Future.value(
'Check the original request before changing its choices.',
@@ -5233,6 +5987,7 @@ class AppNotifier extends ChangeNotifier {
// by name and wins; so does a tab other than the current one. The
// current tab is what the dialog passes when nothing was chosen.
if (dsh != null &&
+ placement == null &&
split == null &&
(swarmId == null || swarmId == activeSwarmId)) {
final label = engineIdentity(dsh).label;
@@ -5244,23 +5999,33 @@ class AppNotifier extends ChangeNotifier {
targetId = activeSwarmId;
}
creation._choices = choices;
+ creation._projectFolder = projectFolder;
creation._machineId = machineId;
creation._targetId = targetId;
creation._split = split;
+ creation._placement = placement;
}
final work = _createAgentWithReceipt(creation);
creation._inFlight = work;
return work.whenComplete(() => creation._inFlight = null);
}
- String? _creationPlacementError(String targetId, PaneSplitRequest? split) {
+ String? _creationPlacementError(
+ String targetId,
+ PaneSplitRequest? split, {
+ HarnessPlacement? placement,
+ }) {
+ if (placement == HarnessPlacement.newTab) return null;
if (split != null && !isPaneSplitCurrent(split)) {
return 'The layout changed. Close this dialog and split the pane again.';
}
final target = swarms.where((s) => s.id == targetId).firstOrNull;
if (target == null) return 'This tab was closed';
+ if (placement != null && (target.isStore || target.isOrchestrator)) {
+ return 'Open a new tab to add a harness.';
+ }
if (target.panes.length >= maxPanes) {
- return 'This tab is full. Open a new tab to create a harness.';
+ return 'This tab is full. Open a new tab to start a harness.';
}
return null;
}
@@ -5282,7 +6047,7 @@ class AppNotifier extends ChangeNotifier {
'Harness needs tmux to start harnesses on $machine. '
'Install tmux there, then try again.',
'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
- 'Update the harness CLI on this machine to create a harness',
+ 'Update the harness CLI on this machine to start a harness',
'INVALID_DSH' =>
'This harness is not installed on $machine. '
'${detail ?? 'Install it there, then try again.'}',
@@ -5296,13 +6061,28 @@ class AppNotifier extends ChangeNotifier {
// fix is the same one the other UNSUPPORTED codes ask for.
'INVALID_ENGINE' =>
'Update the harness CLI on $machine to open this kind of pane.',
- _ => 'Create harness failed: ${detail ?? code}',
+ _ => 'Could not start harness: ${detail ?? code}',
};
+ /// A confirmed name collision happens before any process starts. Only then
+ /// may an automatic suggestion advance to another name with a fresh receipt.
+ /// Uncertain replies always keep their original receipt and never retry.
+ Future<String?> _retryGeneratedProject(AgentCreationAttempt creation) {
+ final project = creation._projectFolder!;
+ creation._remoteProjectName = project.nextGeneratedName(
+ creation._remoteProjectName ?? project.folderName!,
+ );
+ creation._projectNameRetries++;
+ creation._id = _newCreationId();
+ creation._awaitingConfirmation = false;
+ return _createAgentWithReceipt(creation);
+ }
+
Future<String?> _createAgentWithReceipt(AgentCreationAttempt creation) async {
final machineId = creation._machineId!;
- final targetId = creation._targetId!;
+ var targetId = creation._targetId!;
final split = creation._split;
+ final placement = creation._placement;
final choices = creation._choices!;
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
@@ -5310,7 +6090,11 @@ class AppNotifier extends ChangeNotifier {
// A status check must remain possible even if the destination closed or a
// capability probe changed while the first create was already in flight.
if (!creation.awaitingConfirmation) {
- final placementError = _creationPlacementError(targetId, split);
+ final placementError = _creationPlacementError(
+ targetId,
+ split,
+ placement: placement,
+ );
if (placementError != null) return placementError;
if (choices['codexHome'] != null) {
if (choices['engine'] != 'codex') {
@@ -5334,9 +6118,16 @@ class AppNotifier extends ChangeNotifier {
machine.isLocalMachine) {
try {
final repository = choices['repositoryUrl'];
- final project = repository is String
- ? ProjectFolderRequest.remote(GitHubRepository.parse(repository)!)
- : const ProjectFolderRequest.newProject();
+ final projectName = choices['projectName'];
+ final project =
+ creation._projectFolder ??
+ (repository is String
+ ? ProjectFolderRequest.remote(
+ GitHubRepository.parse(repository)!,
+ )
+ : ProjectFolderRequest.newProject(
+ name: projectName is String ? projectName : null,
+ ));
final dshId = choices['dsh'];
creation._preparedFolder ??= await prepareLocalProjectFolder(
project,
@@ -5358,7 +6149,11 @@ class AppNotifier extends ChangeNotifier {
}
// Preparation may be slow. Revalidate before starting a process, using
// the original machine and split rather than the current selection.
- final placementError = _creationPlacementError(targetId, split);
+ final placementError = _creationPlacementError(
+ targetId,
+ split,
+ placement: placement,
+ );
if (placementError != null) return creation._complete(placementError);
if (_disposed ||
machineStates[machineId] != machine ||
@@ -5370,14 +6165,22 @@ class AppNotifier extends ChangeNotifier {
launchChoices = Map.of(choices)
..remove('projectSource')
..remove('repositoryUrl')
+ ..remove('projectName')
..['cwd'] = creation._preparedFolder;
}
+ if (!machine.isLocalMachine && creation._remoteProjectName != null) {
+ launchChoices = {...choices, 'projectName': creation._remoteProjectName};
+ }
+ final canAdvanceProject =
+ !machine.isLocalMachine &&
+ creation._projectFolder?.isGenerated == true &&
+ creation._projectNameRetries < 64;
final operation = creation.awaitingConfirmation
? 'agent_create_status'
: 'agent_create';
final unconfirmed =
- '$machineName has not confirmed the new agent yet. '
- 'Check status before creating another.';
+ '$machineName has not confirmed the new harness yet. '
+ 'Check status before starting another.';
Map<String, dynamic> result;
creation._awaitingConfirmation = true;
try {
@@ -5396,12 +6199,17 @@ class AppNotifier extends ChangeNotifier {
);
}
} on WsRequestFailure catch (failure) {
+ if (operation == 'agent_create' &&
+ failure.code == 'PROJECT_EXISTS' &&
+ canAdvanceProject) {
+ return _retryGeneratedProject(creation);
+ }
if (operation == 'agent_create_status') {
if (failure.code == 'UNSUPPORTED' ||
failure.code == 'UNSUPPORTED_ON_REMOTE' ||
failure.code == 'E2EE_REQUIRED') {
return '$machineName cannot check this creation. '
- 'Use Find a harness to look for it before creating another.';
+ 'Use New Pane (⌘P) to look for it before starting another.';
}
return unconfirmed;
}
@@ -5410,6 +6218,7 @@ class AppNotifier extends ChangeNotifier {
const refusedBeforeLaunch = {
'INVALID_PROJECT_SOURCE',
'INVALID_REPOSITORY',
+ 'PROJECT_EXISTS',
'CWD_NOT_FOUND',
'INVALID_CWD',
'INVALID_ENGINE',
@@ -5452,20 +6261,25 @@ class AppNotifier extends ChangeNotifier {
// receipt-aware version. Missing is not proof that nothing started.
// Check status stays read-only, even across upgrades and reconnects.
return '$machineName has no record of this request. '
- 'Use Find a harness to look for it before creating another.';
+ 'Use New Pane (⌘P) to look for it before starting another.';
case 'pending':
- return '$machineName is still starting your agent. Check again in a moment.';
+ return '$machineName is still starting your harness. Check again in a moment.';
case 'unconfirmed':
- return '$machineName could not confirm whether this agent started. '
- 'Use Open Harness to look for it before creating another.';
+ return '$machineName could not confirm whether this harness started. '
+ 'Use New Pane to look for it before starting another.';
case 'unavailable':
return creation._complete(
- 'This harness was created but is no longer available. '
- 'You can create a new one.',
+ 'This harness started but is no longer available. '
+ 'You can start a new one.',
);
case 'failed':
final failure = result['failure'];
if (failure is! Map || failure['code'] is! String) return unconfirmed;
+ if (failure['code'] == 'PROJECT_EXISTS' &&
+ result['preparedFolder'] == null &&
+ canAdvanceProject) {
+ return _retryGeneratedProject(creation);
+ }
if (result['preparedFolder'] case final String folder
when folder.isNotEmpty) {
creation._preparedFolder = folder;
@@ -5504,223 +6318,912 @@ class AppNotifier extends ChangeNotifier {
}
harnessStats.onAgentSpawned();
notifyListeners();
- if (_creationPlacementError(targetId, split) != null) {
+ if (_creationPlacementError(targetId, split, placement: placement) !=
+ null) {
_lastError =
- 'The harness was created, but its original tab or layout changed. '
- 'Use Open Harness to find it.';
+ 'The harness started, but its original tab or layout changed. '
+ 'Use New Pane to find it.';
_lastErrorRetryable = false;
notifyListeners();
return null;
}
+ // Do not allocate a tab while the picker, form, or request is pending.
+ // Failed and unconfirmed requests leave the original layout intact.
+ if (placement == HarnessPlacement.newTab) {
+ newSwarm();
+ targetId = activeSwarmId;
+ }
await assignAgentToPane(
null,
machineId,
agent.id,
swarmId: targetId,
split: split,
+ autoTile: placement != null,
);
return null;
}
- /// Renames a machine via `PATCH /api/machines/:machineId` (control-plane REST — the machine's
- /// `name` is backend-owned, unlike an agent's, which lives on the harness CLI). Returns null on
- /// success, or an error message to show inline in the caller's dialog.
- Future<String?> renameMachine(String machineId, String name) async {
- final state = machineStates[machineId];
- if (state == null) return 'Machine not found';
- final trimmed = name.trim();
- if (trimmed.isEmpty) return 'Name cannot be empty';
- try {
- await api.renameMachine(machineId: machineId, name: trimmed);
- } catch (error) {
- return 'Rename failed: $error';
+ _MachineEdit? _pendingMachineEdit(String machineId) {
+ final edit = _machineEdits[machineId];
+ return edit != null && _machineWorkCurrent(edit.machine, edit.authRevision)
+ ? edit
+ : null;
+ }
+
+ Future<String?>? pendingMachineRename(String machineId) {
+ final edit = _pendingMachineEdit(machineId);
+ return edit?.name != null ? edit!.result.future : null;
+ }
+
+ String? pendingMachineName(String machineId) =>
+ _pendingMachineEdit(machineId)?.name;
+
+ Future<String?>? pendingMachineDelete(String machineId) {
+ final edit = _pendingMachineEdit(machineId);
+ return edit != null && edit.name == null ? edit.result.future : null;
+ }
+
+ /// Machine names belong to the account. Requests survive their prompt and
+ /// apply only to the machine identity/auth session that initiated them.
+ Future<String?> renameMachine(String machineId, String name) =>
+ _editMachine(machineId, name: name.trim());
+
+ /// Deletes the machine from the account and closes its views in this window.
+ /// This is separate from removing this computer's outgoing trust pin.
+ Future<String?> deleteMachine(String machineId) => _editMachine(machineId);
+
+ Future<String?> _editMachine(String machineId, {String? name}) {
+ if (_disposed) return Future.value('This request is no longer active.');
+ final machine = machineStates[machineId];
+ if (machine == null) return Future.value('Machine not found');
+ if (machine.machine.isShared) {
+ return Future.value('Shared machines are view-only.');
+ }
+ if (name == null && machine.isLocalMachine) {
+ return Future.value('This computer cannot be deleted here.');
+ }
+ if (name != null && name.isEmpty) {
+ return Future.value('Name cannot be empty');
+ }
+ if (_pendingMachineEdit(machineId) case final edit?) {
+ if (edit.name == name) return edit.result.future;
+ return Future.value('A change to this machine is already in progress.');
}
- state.machine = state.machine.copyWith(name: trimmed);
- final index = machines.indexWhere((m) => m.machineId == machineId);
- if (index != -1) machines[index] = state.machine;
+ if (name == machine.machine.displayName) return Future.value();
+ final edit = _MachineEdit(machine, _authRevision, name);
+ _machineEdits[machineId] = edit;
notifyListeners();
- return null;
+ unawaited(_runMachineEdit(machineId, edit));
+ return edit.result.future;
}
- /// Permanently deletes a machine from the account (backend `DELETE /api/machines/:id`) — not to
- /// be confused with [unlinkMachine], which only drops this computer's local E2EE trust pin and
- /// leaves the machine itself intact. Returns null on success, or an error message to show inline.
- Future<String?> deleteMachine(String machineId) async {
- final state = machineStates[machineId];
- if (state == null) return 'Machine not found';
+ Future<void> _runMachineEdit(String machineId, _MachineEdit edit) async {
+ String? error;
try {
- await api.deleteMachine(machineId: machineId);
- } catch (error) {
- return 'Delete failed: $error';
- }
- // Any tile still showing this machine would otherwise sit forever in the "waiting to answer"
- // busy state, since the machine can never be found again after this.
- for (final pane in panesFor(machineId).toList()) {
- for (final swarm in swarms) {
- swarm.remove(pane);
+ if (edit.name case final name?) {
+ final savedName = await api.renameMachine(
+ machineId: machineId,
+ name: name,
+ );
+ if (!_machineWorkCurrent(edit.machine, edit.authRevision)) {
+ error = 'The machine changed while saving. Refresh and try again.';
+ return;
+ }
+ edit.machine.machine = edit.machine.machine.copyWith(
+ name: savedName?.trim().isNotEmpty == true ? savedName!.trim() : name,
+ );
+ final index = machines.indexWhere(
+ (machine) => machine.machineId == machineId,
+ );
+ if (index != -1) machines[index] = edit.machine.machine;
+ _confirmedMachineEdits[machineId] = (
+ ++_machineEditRevision,
+ edit.machine.machine.displayName,
+ );
+ } else {
+ await api.deleteMachine(machineId: machineId);
+ if (!_machineWorkCurrent(edit.machine, edit.authRevision)) {
+ error = 'The machine changed while deleting. Refresh to check its status.';
+ return;
+ }
+ final closing = <Future<void>>[];
+ for (final pane in panesFor(machineId).toList()) {
+ for (final swarm in swarms) {
+ swarm.remove(pane);
+ }
+ closing.add(_detachSession(pane, sendClose: true));
+ }
+ _clearMachineActivity(edit.machine);
+ _stopOfflineRetry(machineId);
+ _stopLinkRetry(machineId);
+ _stopAgentSyncTimer(machineId);
+ machineStates.remove(machineId);
+ machines.removeWhere((machine) => machine.machineId == machineId);
+ _confirmedMachineEdits[machineId] = (++_machineEditRevision, null);
+ if (selectedMachineId == machineId) selectedMachineId = null;
+ _persistLayout();
+ if (_pool case final pool?) closing.add(pool.closeMachine(machineId));
+ notifyListeners();
+ // Deletion is committed. A failed stream close must not offer another
+ // destructive account request; sessions still dispose in finally.
+ try {
+ await Future.wait(closing);
+ } catch (failure) {
+ appLog.warn(
+ 'machines',
+ 'Machine deleted; closing its local views failed: $failure',
+ );
+ }
+ }
+ } catch (failure) {
+ error = failure is ApiException
+ ? '${edit.name == null ? 'Delete' : 'Rename'} failed: ${failure.message}'
+ : 'Could not ${edit.name == null ? 'delete' : 'rename'} the machine. Try again.';
+ } finally {
+ if (identical(_machineEdits[machineId], edit)) {
+ _machineEdits.remove(machineId);
}
- await _detachSession(pane, sendClose: true);
+ edit.result.complete(error);
+ if (_authWorkCurrent(edit.authRevision)) notifyListeners();
}
- _persistLayout();
- _stopAgentSyncTimer(machineId);
- machineStates.remove(machineId);
- machines.removeWhere((m) => m.machineId == machineId);
- if (selectedMachineId == machineId) selectedMachineId = null;
- notifyListeners();
- return null;
}
- /// Renames an agent via `agent_update`. Returns null on success, or an error message to show
- /// inline in the caller's dialog.
- Future<String?> renameAgent(
- String machineId,
- String agentId,
- String name,
- ) async {
+ bool _agentRenameCurrent(_AgentRename request) =>
+ identical(
+ _agentRenames[(request.machine.machine.machineId, request.agent.id)],
+ request,
+ ) &&
+ _machineWorkCurrent(request.machine, request.authRevision) &&
+ request.machine.agents.any(
+ (agent) =>
+ agent.id == request.agent.id &&
+ agent.sessionId == request.agent.sessionId,
+ );
+
+ _AgentRename? _pendingAgentRename(String machineId, String agentId) {
+ final request = _agentRenames[(machineId, agentId)];
+ return request != null && _agentRenameCurrent(request) ? request : null;
+ }
+
+ Future<String?>? pendingAgentRename(String machineId, String agentId) =>
+ _pendingAgentRename(machineId, agentId)?.result.future;
+
+ String? pendingAgentName(String machineId, String agentId) =>
+ _pendingAgentRename(machineId, agentId)?.name;
+
+ /// Renames survive their editor. A second view joins the same request and a
+ /// late reply cannot rename a replacement machine or agent session.
+ Future<String?> renameAgent(String machineId, String agentId, String name) {
+ if (_disposed) return Future.value('This request is no longer active.');
final machine = machineStates[machineId];
- if (machine == null) return 'Machine not found';
+ if (machine == null) return Future.value('Machine not found');
final trimmed = name.trim();
- if (trimmed.isEmpty) return 'Name cannot be empty';
- Map<String, dynamic> result;
+ if (trimmed.isEmpty) return Future.value('Name cannot be empty');
+ if (machine.machine.isShared) {
+ return Future.value('Shared agents are view-only.');
+ }
+ if (pendingAgentStop(machineId, agentId) != null) {
+ return Future.value('The agent is stopping.');
+ }
+ final agent = machine.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (agent == null) return Future.value('Agent not found');
+ if (_pendingAgentRename(machineId, agentId) case final pending?) {
+ if (pending.name == trimmed) return pending.result.future;
+ return Future.value('A rename is already in progress for this agent.');
+ }
+ if (agent.name == trimmed) return Future.value();
+ final request = _AgentRename(machine, agent, _authRevision, trimmed);
+ _agentRenames[(machineId, agentId)] = request;
+ notifyListeners();
+ unawaited(_runAgentRename(request));
+ return request.result.future;
+ }
+
+ Future<void> _runAgentRename(_AgentRename request) async {
+ String? error;
+ final machineId = request.machine.machine.machineId;
+ final agentId = request.agent.id;
try {
- result = await _conn(
- machineId,
- ).request('agent_update', payload: {'agentId': agentId, 'name': trimmed});
- } catch (error) {
- return 'Rename failed: $error';
+ final result = await _conn(machineId).request(
+ 'agent_update',
+ payload: {'agentId': agentId, 'name': request.name},
+ );
+ if (!_agentRenameCurrent(request)) {
+ error = 'The agent changed while saving. Refresh and try again.';
+ return;
+ }
+ if (result['error'] case final String code) {
+ final detail = result['detail'];
+ error =
+ 'Rename failed: ${detail is String && detail.isNotEmpty ? detail : code}';
+ return;
+ }
+ final returned = result['agent'];
+ final rawName = returned is Map ? returned['name'] : null;
+ final name = rawName is String && rawName.trim().isNotEmpty
+ ? rawName.trim()
+ : request.name;
+ final observed = request.machine._agentNames[agentId];
+ if (observed != null &&
+ observed.revision > request.nameRevision &&
+ observed.name != name) {
+ error =
+ 'The name changed to “${observed.name}” while saving. Check it before retrying.';
+ return;
+ }
+ _renameAgent(request.machine, agentId, name);
+ } catch (failure) {
+ error = failure is WsRequestTimeout
+ ? 'Could not confirm the rename. Refresh agents to check the name.'
+ : 'Could not rename the agent. Try again.';
+ } finally {
+ if (identical(_agentRenames[(machineId, agentId)], request)) {
+ _agentRenames.remove((machineId, agentId));
+ }
+ request.result.complete(error);
+ if (_authWorkCurrent(request.authRevision)) notifyListeners();
+ }
+ }
+
+ bool _agentStopCurrent(_AgentStop request) {
+ if (!identical(
+ _agentStops[(request.machine.machine.machineId, request.agent.id)],
+ request,
+ )) {
+ return false;
+ }
+ if (!_machineWorkCurrent(request.machine, request.authRevision)) {
+ return false;
+ }
+ final current = request.machine.agents
+ .where((agent) => agent.id == request.agent.id)
+ .firstOrNull;
+ return request.confirmed ||
+ current == null ||
+ current.sessionId == request.agent.sessionId;
+ }
+
+ Future<String?>? pendingAgentStop(String machineId, String agentId) {
+ final request = _agentStops[(machineId, agentId)];
+ return request != null &&
+ !request.confirmed &&
+ !request.result.isCompleted &&
+ _agentStopCurrent(request)
+ ? request.result.future
+ : null;
+ }
+
+ /// Stops the process through the CLI, retaining project files and history.
+ /// The request outlives its confirmation and is shared by every view.
+ ///
+ /// Confirmation prompts use [prepareAgentStop] to retain the identity shown
+ /// when they opened, before the person has confirmed the action.
+ Future<String?> deleteAgent(String machineId, String agentId) {
+ if (_disposed) return Future.value('This request is no longer active.');
+ final machine = machineStates[machineId];
+ if (machine == null) return Future.value('Machine not found');
+ if (machine.machine.isShared) {
+ return Future.value('Shared agents are view-only.');
+ }
+ if (pendingAgentStop(machineId, agentId) case final pending?) {
+ return pending;
+ }
+ final agent = machine.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (agent == null) {
+ return Future.value(
+ 'The agent is no longer listed. Refresh to check its status.',
+ );
}
- final error = result['error'];
- if (error is String) return 'Rename failed: $error';
- _renameAgent(machine, agentId, trimmed);
+ final request = _AgentStop(machine, agent, _authRevision);
+ machine._agentStopRevisions[agentId] = ++machine._agentRevision;
+ _agentStops[(machineId, agentId)] = request;
notifyListeners();
- return null;
+ unawaited(_runAgentStop(request));
+ return request.result.future;
}
- /// Stops an agent via the legacy `agent_delete` request, removing its active
- /// entry while preserving files and saved history. Returns an error on failure.
- Future<String?> deleteAgent(String machineId, String agentId) async {
+ /// Captures the confirmation's target without sending a request. A changed
+ /// session, removed/recreated ID, replacement machine, or new login while the
+ /// prompt is open must not turn its Stop button into an action on another agent.
+ Future<String?> Function() prepareAgentStop(
+ String machineId,
+ String agentId,
+ ) {
final machine = machineStates[machineId];
- if (machine == null) return 'Machine not found';
- Map<String, dynamic> result;
+ final agent = machine?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ final authRevision = _authRevision;
+ final removal = machine?._agentRemovals[agentId];
+ return () {
+ final current = machineStates[machineId]?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ if (machine == null ||
+ agent == null ||
+ !_machineWorkCurrent(machine, authRevision) ||
+ machine._agentRemovals[agentId] != removal ||
+ current == null ||
+ current.sessionId != agent.sessionId) {
+ return Future.value(
+ 'The agent changed. Close this prompt and check it before stopping.',
+ );
+ }
+ return deleteAgent(machineId, agentId);
+ };
+ }
+
+ Future<void> _runAgentStop(_AgentStop request) async {
+ String? error;
+ final machineId = request.machine.machine.machineId;
+ final agentId = request.agent.id;
try {
- result = await _conn(machineId)
+ final result = await _conn(machineId)
.request('agent_delete', payload: {'agentId': agentId});
- } catch (error) {
- return 'Stop failed: $error';
+ if (request.confirmed) return;
+ if (!_agentStopCurrent(request)) {
+ error =
+ 'The agent changed while stopping. Refresh to check its status.';
+ return;
+ }
+ if (result['error'] case final String code) {
+ final detail = result['detail'];
+ error =
+ 'Stop failed: ${detail is String && detail.isNotEmpty ? detail : code}';
+ return;
+ }
+ await _removeAgent(request.machine, agentId);
+ } catch (failure) {
+ if (!request.confirmed) {
+ error = failure is WsRequestTimeout
+ ? 'Could not confirm the stop. Refresh agents to check its status.'
+ : 'Could not stop the agent. Try again.';
+ }
+ } finally {
+ if (identical(_agentStops[(machineId, agentId)], request)) {
+ _agentStops.remove((machineId, agentId));
+ }
+ if (!request.result.isCompleted) request.result.complete(error);
+ if (_authWorkCurrent(request.authRevision)) notifyListeners();
}
- final error = result['error'];
- if (error is String) return 'Stop failed: $error';
- await _removeAgent(machine, agentId);
- notifyListeners();
- return null;
}
- /// Restarts an agent via `agent_restart` — exits its current engine process and relaunches it
- /// daemon-side, resuming its session where possible.
- ///
- /// The reply carries the same fresh `Agent` shape `agent_synced` pushes once the new process is
- /// confirmed, so this upserts from the reply directly — idempotent on `agent.id`, same as
- /// [createAgent], and safe even if the CLI's own `agent_synced` push for the restart arrives
- /// separately (fire-and-forget on the CLI side, unordered relative to this reply).
+ bool _restartCurrent(AgentRestartAttempt attempt, {bool beforeSend = false}) {
+ final machine = attempt._machine;
+ final agent = attempt.agent;
+ if (machine == null ||
+ agent == null ||
+ !_machineWorkCurrent(machine, attempt._authRevision) ||
+ machine._agentRemovals[agent.id] != attempt._removal ||
+ machine._agentStopRevisions[agent.id] != attempt._stopRevision) {
+ return false;
+ }
+ final current = machine.agents
+ .where((item) => item.id == agent.id)
+ .firstOrNull;
+ return current != null &&
+ (!beforeSend || current.sessionId == agent.sessionId);
+ }
+
+ AgentRestartAttempt restartAttempt(String machineId, String agentId) {
+ final previous = _agentRestarts[(machineId, agentId)];
+ if (previous != null &&
+ _restartCurrent(
+ previous,
+ beforeSend: !previous.busy && !previous.awaitingConfirmation,
+ )) {
+ return previous;
+ }
+ final machine = machineStates[machineId];
+ return _agentRestarts[(machineId, agentId)] = AgentRestartAttempt._(
+ machine,
+ machine?.agents.where((agent) => agent.id == agentId).firstOrNull,
+ _authRevision,
+ );
+ }
+
+ bool discardRestartAttempt(
+ String machineId,
+ String agentId,
+ AgentRestartAttempt attempt,
+ ) {
+ if (attempt.busy ||
+ !identical(_agentRestarts[(machineId, agentId)], attempt)) {
+ return false;
+ }
+ _agentRestarts.remove((machineId, agentId));
+ return true;
+ }
+
+ /// Restart keeps the agent, every view and the current focus. Only explicit
+ /// new intent can repeat a request whose outcome is still unknown.
Future<RestartAgentResult> restartAgent(
+ String machineId,
+ String agentId, {
+ AgentRestartAttempt? attempt,
+ }) {
+ final operation = attempt ?? restartAttempt(machineId, agentId);
+ if (operation.result case final result? when result.error == null) {
+ return Future.value(result);
+ }
+ if (operation.pending case final pending?) return pending;
+ late final Future<RestartAgentResult> request;
+ request = _runAgentRestart(machineId, agentId, operation)
+ .then((result) {
+ operation.result = result;
+ return result;
+ })
+ .whenComplete(() {
+ if (identical(operation._pending, request)) operation._pending = null;
+ if (_authWorkCurrent(operation._authRevision)) notifyListeners();
+ });
+ operation._pending = request;
+ return request;
+ }
+
+ Future<RestartAgentResult> _runAgentRestart(
String machineId,
String agentId,
+ AgentRestartAttempt attempt,
) async {
- final machine = machineStates[machineId];
+ final machine = attempt._machine;
if (machine == null) {
- return const RestartAgentResult(error: 'Machine not found');
+ return const RestartAgentResult(
+ error: 'Machine not found',
+ retryable: false,
+ );
+ }
+ if (machine.machine.isShared) {
+ return const RestartAgentResult(
+ error: 'Shared agents are view-only.',
+ retryable: false,
+ );
+ }
+ if (pendingAgentStop(machineId, agentId) != null) {
+ return const RestartAgentResult(
+ error: 'The agent is stopping.',
+ retryable: false,
+ );
+ }
+ if (machine.machine.machineId != machineId ||
+ attempt.agent?.id != agentId ||
+ !_restartCurrent(attempt, beforeSend: !attempt.awaitingConfirmation)) {
+ return const RestartAgentResult(
+ error: 'The agent changed. Close this prompt and check it before restarting.',
+ retryable: false,
+ );
}
+ final checking = attempt.awaitingConfirmation;
+ if (!checking) {
+ attempt._id = _newCreationId();
+ attempt._startedRevision = machine._agentRevision;
+ }
+ attempt._awaitingConfirmation = true;
+ const unknown = RestartAgentResult(
+ error: 'The restart is not confirmed yet. Check status, or close this prompt to inspect the terminal before restarting again.',
+ );
Map<String, dynamic> result;
try {
- result = await _conn(machineId)
- .request('agent_restart', payload: {'agentId': agentId});
- } catch (error) {
- return RestartAgentResult(error: 'Restart failed: $error');
+ result = await _conn(machineId).request(
+ checking ? 'agent_create_status' : 'agent_restart',
+ payload: {'creationId': attempt._id, if (!checking) 'agentId': agentId},
+ );
+ } catch (_) {
+ return unknown;
}
- final error = result['error'];
- if (error is String) {
- final detail = result['detail'];
- return RestartAgentResult(
- error: detail is String ? detail : 'Restart failed: $error',
+ if (!_restartCurrent(attempt)) {
+ return const RestartAgentResult(
+ error: 'The agent changed while restarting. Check its current status.',
+ retryable: false,
);
}
+ if ((checking ||
+ result.containsKey('creationId') ||
+ result.containsKey('state')) &&
+ result['creationId'] != attempt._id) {
+ return unknown;
+ }
+ if (result['error'] case final String code) {
+ if (checking ||
+ [
+ 'INTERNAL',
+ 'CREATION_STORAGE_FAILED',
+ 'RESTART_FAILED',
+ ].contains(code)) {
+ return unknown;
+ }
+ attempt._awaitingConfirmation = false;
+ return RestartAgentResult(error: _restartFailure(code, result['detail']));
+ }
+ switch (result['state']) {
+ case 'pending':
+ return const RestartAgentResult(
+ error: 'The machine is still restarting the agent. Check again in a moment.',
+ );
+ case 'missing':
+ case 'unconfirmed':
+ return unknown;
+ case 'unavailable':
+ attempt._awaitingConfirmation = false;
+ return const RestartAgentResult(
+ error: 'The restarted agent is no longer available. Close this prompt and check current agents.',
+ retryable: false,
+ );
+ case 'failed':
+ final failure = result['failure'];
+ if (failure is! Map || failure['code'] is! String) return unknown;
+ attempt._awaitingConfirmation = false;
+ return RestartAgentResult(
+ error: _restartFailure(failure['code'] as String, failure['detail']),
+ );
+ case 'created':
+ case null:
+ break;
+ default:
+ return unknown;
+ }
final raw = result['agent'];
- if (raw is Map) {
+ // Older daemons can acknowledge a restart without an agent projection.
+ if (raw != null || result['state'] == 'created') {
+ if (raw is! Map || raw['id'] != agentId) return unknown;
try {
- _upsertAgent(machine, Agent.fromJson(Map<String, dynamic>.from(raw)));
- notifyListeners();
+ var updated = Agent.fromJson(Map<String, dynamic>.from(raw));
+ final current = machine.agents
+ .where((agent) => agent.id == agentId)
+ .first;
+ // A newer observed session wins over the receipt of an older restart.
+ if (current.sessionId == attempt.agent!.sessionId ||
+ current.sessionId == updated.sessionId) {
+ updated = _preserveNewerName(
+ machine,
+ updated,
+ attempt._startedRevision,
+ );
+ final name = machine._agentNames[agentId];
+ if (name != null &&
+ name.revision > attempt._startedRevision &&
+ name.sessionId == current.sessionId) {
+ updated = updated.copyWith(name: name.name);
+ }
+ _upsertAgent(machine, updated);
+ }
} catch (_) {
- // Malformed reply agent — harmless, the CLI's own agent_synced push still lands.
+ return unknown;
}
+ } else if (!result.containsKey('resumed')) {
+ return unknown;
}
- // Absent (older daemon build) reads as true — assume resumed rather than warn about a fresh
- // session that may not have happened, since this field is purely additive UI polish.
- final resumed = result['resumed'];
- return RestartAgentResult(resumed: resumed is bool ? resumed : true);
+ machine._agentRestartRevisions[agentId] = ++machine._agentRevision;
+ attempt._awaitingConfirmation = false;
+ if (identical(_agentRestarts[(machineId, agentId)], attempt)) {
+ _agentRestarts.remove((machineId, agentId));
+ }
+ return RestartAgentResult(
+ resumed: result['resumed'] is bool ? result['resumed'] as bool : true,
+ );
}
- /// Forks an agent via `agent_fork`: a second agent that starts with the
- /// first one's whole history, in the same folder, then goes its own way.
- ///
- /// The fork lands beside its source — in the source's tab when that is the
- /// tab on screen, else in the current tab — and takes focus, because the
- /// person asked for it a moment ago and is about to give it its job. Same
- /// upsert-from-reply rule as [restartAgent].
+ String _restartFailure(String code, Object? detail) =>
+ detail is String && detail.isNotEmpty
+ ? detail
+ : switch (code) {
+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
+ 'Update the harness CLI on this machine to restart an agent.',
+ 'AGENT_BUSY' => 'Another operation is changing this agent. Wait for it to finish, then retry.',
+ _ => 'Restart failed: $code',
+ };
+
+ bool _forkSourceCurrent(AgentForkAttempt attempt) {
+ final machine = attempt._machine;
+ final source = attempt.source;
+ if (machine == null ||
+ source == null ||
+ !_machineWorkCurrent(machine, attempt._authRevision) ||
+ machine._agentRemovals[source.id] != attempt._removal) {
+ return false;
+ }
+ final current = machine.agents
+ .where((agent) => agent.id == source.id)
+ .firstOrNull;
+ return current != null && current.sessionId == source.sessionId;
+ }
+
+ AgentForkAttempt forkAttempt(
+ String machineId,
+ String agentId, {
+ String name = '',
+ String prompt = '',
+ }) {
+ final existing = _agentForks[(machineId, agentId)];
+ if (existing != null &&
+ (_forkSourceCurrent(existing) ||
+ (existing.locked &&
+ existing._machine != null &&
+ _machineWorkCurrent(
+ existing._machine,
+ existing._authRevision,
+ )))) {
+ return existing;
+ }
+ final machine = machineStates[machineId];
+ final source = machine?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ return _agentForks[(machineId, agentId)] = AgentForkAttempt._(
+ machine,
+ source,
+ _authRevision,
+ machine?._agentRemovals[agentId],
+ name: name,
+ prompt: prompt,
+ );
+ }
+
+ /// Only an explicit New fork action may abandon an unconfirmed receipt.
+ bool discardForkAttempt(
+ String machineId,
+ String agentId,
+ AgentForkAttempt attempt,
+ ) {
+ if (attempt.busy ||
+ !identical(_agentForks[(machineId, agentId)], attempt)) {
+ return false;
+ }
+ _agentForks.remove((machineId, agentId));
+ return true;
+ }
+
+ /// A fork keeps the originating tab and creation receipt while its prompt is
+ /// closed. Reopening joins the request; checking an uncertain result never
+ /// sends a second agent_fork. Old daemons can still return their legacy reply.
Future<ForkAgentResult> forkAgent(
String machineId,
String agentId, {
String? name,
String? prompt,
- }) async {
- final machine = machineStates[machineId];
+ AgentForkAttempt? attempt,
+ }) {
+ final operation = attempt ?? forkAttempt(machineId, agentId);
+ if (operation.result case final result?
+ when result.error == null && result.agentId != null) {
+ return Future.value(result);
+ }
+ if (operation.locked &&
+ ((name != null && name.trim() != operation.name.trim()) ||
+ (prompt != null && prompt != operation.prompt))) {
+ return Future.value(
+ const ForkAgentResult(
+ error: 'Check the original fork before changing its choices.',
+ ),
+ );
+ }
+ if (operation.pending case final pending?) return pending;
+ if (!operation.awaitingConfirmation) {
+ if (name != null) operation.name = name;
+ if (prompt != null) operation.prompt = prompt;
+ }
+ late final Future<ForkAgentResult> request;
+ request = _runAgentFork(machineId, agentId, operation)
+ .then((result) {
+ operation.result = result;
+ return result;
+ })
+ .whenComplete(() {
+ if (identical(operation._inFlight, request)) {
+ operation._inFlight = null;
+ }
+ if (_authWorkCurrent(operation._authRevision)) notifyListeners();
+ });
+ operation._inFlight = request;
+ return request;
+ }
+
+ Future<ForkAgentResult> _runAgentFork(
+ String machineId,
+ String agentId,
+ AgentForkAttempt attempt,
+ ) async {
+ final machine = attempt._machine;
if (machine == null) {
return const ForkAgentResult(error: 'Machine not found');
}
+ if (machine.machine.machineId != machineId ||
+ attempt.source?.id != agentId) {
+ return const ForkAgentResult(
+ error: 'The source agent is no longer available.',
+ );
+ }
+ if (!_machineWorkCurrent(machine, attempt._authRevision)) {
+ return const ForkAgentResult(
+ error: 'This fork is no longer active. Reopen Fork Agent.',
+ );
+ }
+ if (machine.machine.isShared) {
+ return const ForkAgentResult(error: 'Shared agents are view-only.');
+ }
+ if (!attempt.awaitingConfirmation) {
+ if (!_forkSourceCurrent(attempt)) {
+ return const ForkAgentResult(
+ error: 'The source agent changed. Close this prompt and reopen Fork Agent.',
+ );
+ }
+ if (pendingAgentStop(machineId, agentId) != null) {
+ return const ForkAgentResult(error: 'The source agent is stopping.');
+ }
+ if (attempt.source?.canFork != true) {
+ return const ForkAgentResult(
+ error: 'This agent does not support forking.',
+ );
+ }
+ if (agentIsProcessing(machineId, agentId)) {
+ return const ForkAgentResult(
+ error:
+ 'This agent is working. Wait for its turn to finish, then fork.',
+ );
+ }
+ if (attempt.name.characters.length > 80) {
+ return const ForkAgentResult(
+ error: 'Use at most 80 characters for the name.',
+ );
+ }
+ if (attempt.prompt.length > 2000) {
+ return const ForkAgentResult(
+ error: 'Use at most 2000 characters for the first task.',
+ );
+ }
+ attempt._id = _newCreationId();
+ attempt._target = activeSwarm;
+ attempt._focus = focusedPaneId;
+ attempt._startedRevision = machine._agentRevision;
+ }
+ final checking = attempt.awaitingConfirmation;
+ attempt._awaitingConfirmation = true;
+ const unknown = ForkAgentResult(
+ error: 'The fork is not confirmed yet. Check status, or use New Pane to look for it before starting another.',
+ );
Map<String, dynamic> result;
try {
result = await _conn(machineId).request(
- 'agent_fork',
+ checking ? 'agent_create_status' : 'agent_fork',
payload: {
- 'agentId': agentId,
- if (name != null && name.trim().isNotEmpty) 'name': name.trim(),
- if (prompt != null && prompt.trim().isNotEmpty) 'prompt': prompt,
+ 'creationId': attempt._id,
+ if (!checking) ...{
+ 'agentId': agentId,
+ if (attempt.name.trim().isNotEmpty) 'name': attempt.name.trim(),
+ if (attempt.prompt.trim().isNotEmpty) 'prompt': attempt.prompt,
+ },
},
);
- } catch (error) {
- return ForkAgentResult(error: 'Fork failed: $error');
+ } catch (_) {
+ return unknown;
}
- final error = result['error'];
- if (error is String) {
- final detail = result['detail'];
- return ForkAgentResult(
- error: detail is String
- ? detail
- : switch (error) {
- 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
- 'Update the harness CLI on this machine to fork a harness.',
- 'AGENT_BUSY' => 'This harness is in the middle of a turn. Wait for it to finish, then fork.',
- _ => 'Fork failed: $error',
- },
+ if (!_machineWorkCurrent(machine, attempt._authRevision)) {
+ return const ForkAgentResult(
+ error: 'The machine changed while forking. Check its agents after reconnecting.',
);
}
+ if ((checking ||
+ result.containsKey('creationId') ||
+ result.containsKey('state')) &&
+ result['creationId'] != attempt._id) {
+ return unknown;
+ }
+ if (result['error'] case final String code) {
+ // These are refusals before dispatch, including the legacy fork endpoint.
+ if (checking ||
+ [
+ 'INTERNAL',
+ 'CREATION_STORAGE_FAILED',
+ 'SPAWN_FAILED',
+ 'REGISTRATION_FAILED',
+ ].contains(code)) {
+ return unknown;
+ }
+ attempt._awaitingConfirmation = false;
+ return ForkAgentResult(error: _forkFailure(code, result['detail']));
+ }
+ switch (result['state']) {
+ case 'pending':
+ return const ForkAgentResult(
+ error: 'The machine is still starting the fork. Check again in a moment.',
+ );
+ case 'missing':
+ case 'unconfirmed':
+ return unknown;
+ case 'unavailable':
+ attempt._awaitingConfirmation = false;
+ return const ForkAgentResult(
+ error: 'The fork was created but is no longer available. You can start another.',
+ );
+ case 'failed':
+ final failure = result['failure'];
+ if (failure is! Map || failure['code'] is! String) return unknown;
+ attempt._awaitingConfirmation = false;
+ return ForkAgentResult(
+ error: _forkFailure(failure['code'] as String, failure['detail']),
+ );
+ case 'created':
+ case null:
+ break;
+ default:
+ return unknown;
+ }
final raw = result['agent'];
- if (raw is! Map) return const ForkAgentResult(error: 'Fork failed');
+ if (raw is! Map ||
+ raw['id'] is! String ||
+ (raw['id'] as String).isEmpty ||
+ raw['id'] == agentId) {
+ return unknown;
+ }
final Agent fork;
try {
- fork = Agent.fromJson(Map<String, dynamic>.from(raw));
+ fork = _preserveNewerName(
+ machine,
+ Agent.fromJson(Map<String, dynamic>.from(raw)),
+ attempt._startedRevision,
+ );
} catch (_) {
- return const ForkAgentResult(error: 'Fork failed');
+ return unknown;
+ }
+ attempt._awaitingConfirmation = false;
+ if (identical(_agentForks[(machineId, agentId)], attempt)) {
+ _agentForks.remove((machineId, agentId));
+ }
+ if ((machine._agentRemovals[fork.id] ?? 0) > attempt._startedRevision) {
+ return ForkAgentResult(
+ agentId: fork.id,
+ level: result['level'] == 'handoff' ? 'handoff' : 'native',
+ notice: 'The fork was created but has since stopped. Use New Pane to check current agents.',
+ );
}
_upsertAgent(machine, fork);
notifyListeners();
- await placeFork(machineId, fork.id, sourceAgentId: agentId);
- final level = result['level'];
+ var target = attempt._target;
+ final keepFocus = target == activeSwarm && focusedPaneId == attempt._focus;
+ String? notice;
+ if (target == null || !swarms.contains(target)) {
+ notice =
+ 'Fork created. Its original tab closed; use New Pane to open it.';
+ } else if (target.panes.length >= maxPanes && !keepFocus) {
+ notice =
+ 'Fork created. Its original tab is full; use New Tab to open it.';
+ } else {
+ if (target.panes.length >= maxPanes) {
+ newSwarm(name: fork.name);
+ target = activeSwarm;
+ }
+ await assignAgentToPane(
+ null,
+ machineId,
+ fork.id,
+ swarmId: target.id,
+ autoTile: true,
+ focus: keepFocus,
+ );
+ }
return ForkAgentResult(
- level: level is String ? level : 'native',
+ level: result['level'] == 'handoff' ? 'handoff' : 'native',
agentId: fork.id,
+ notice: notice,
);
}
+ String _forkFailure(String code, Object? detail) =>
+ detail is String && detail.isNotEmpty
+ ? detail
+ : switch (code) {
+ 'UNSUPPORTED_ON_REMOTE' || 'UNSUPPORTED' =>
+ 'Update the harness CLI on this machine to fork an agent.',
+ 'AGENT_BUSY' =>
+ 'This agent is working. Wait for its turn to finish, then fork.',
+ _ => 'Fork failed: $code',
+ };
+
/// Put a fork on screen beside its source and focus it — the window's half
/// of a fork asked for here or on the dial (`dial_forked`).
Future<void> placeFork(
@@ -5780,6 +7283,7 @@ class AppNotifier extends ChangeNotifier {
machine.nodeOnline = online;
if (!online) {
+ if (wasOnline != false) _resetMachineDiscovery(machine);
_markSessionsUnreachable(
machine,
machine.isLocalMachine
@@ -5790,11 +7294,10 @@ class AppNotifier extends ChangeNotifier {
} else {
_stopOfflineRetry(machineId);
if (wasOnline == false) {
- for (final pane in panesFor(machineId)) {
- pane.session?.transportLost(
- 'Harness reconnected; restoring terminal…',
- );
- }
+ _markSessionsUnreachable(
+ machine,
+ 'Harness reconnected; restoring terminal…',
+ );
}
final pending = machine.pendingOfflineAgentId;
if (pending != null) {
@@ -5816,17 +7319,22 @@ class AppNotifier extends ChangeNotifier {
String agentId,
) async {
final machineId = machine.machine.machineId;
- if (!_offlineRecoveryInFlight.add(machineId)) return;
+ if (_offlineRecoveryInFlight.containsKey(machineId)) return;
+ final owner = Object();
+ _offlineRecoveryInFlight[machineId] = owner;
+ final revision = _authRevision;
+ final discoveryRevision = machine._discoveryRevision;
+ bool current() =>
+ _machineDiscoveryCurrent(machine, revision, discoveryRevision) &&
+ machine.nodeOnline == true &&
+ machine.pendingOfflineAgentId == agentId;
try {
// E2EE and agents_list can become ready in separate frames after a
// node restart. Poll briefly instead of racing a single request.
for (var attempt = 0; attempt < 40; attempt++) {
- if (_disposed ||
- machine.nodeOnline != true ||
- machine.pendingOfflineAgentId != agentId) {
- return;
- }
+ if (!current()) return;
await _loadMachineData(machine, force: true);
+ if (!current()) return;
final agent = machine.agents.cast<Agent?>().firstWhere(
(candidate) => candidate?.id == agentId,
orElse: () => null,
@@ -5852,7 +7360,9 @@ class AppNotifier extends ChangeNotifier {
await Future<void>.delayed(const Duration(milliseconds: 250));
}
} finally {
- _offlineRecoveryInFlight.remove(machineId);
+ if (identical(_offlineRecoveryInFlight[machineId], owner)) {
+ _offlineRecoveryInFlight.remove(machineId);
+ }
}
}
@@ -6094,6 +7604,8 @@ class AppNotifier extends ChangeNotifier {
String agentId, {
String? swarmId,
PaneSplitRequest? split,
+ bool autoTile = false,
+ bool focus = true,
}) async {
final target = swarms
.where((s) => s.id == (swarmId ?? activeSwarmId))
@@ -6125,12 +7637,12 @@ class AppNotifier extends ChangeNotifier {
.where((p) => p.machineId == machineId && p.agentId == agentId)
.firstOrNull;
if (paneId == null && existing != null) {
- if (target == activeSwarm) focusPane(existing.id);
+ if (focus && target == activeSwarm) focusPane(existing.id);
return;
}
final replaced = targetPanes.where((p) => p.id == paneId).firstOrNull;
if (replaced == shared && shared != null) {
- if (target == activeSwarm) focusPane(shared.id);
+ if (focus && target == activeSwarm) focusPane(shared.id);
return;
}
if (replaced == null &&
@@ -6160,6 +7672,16 @@ class AppNotifier extends ChangeNotifier {
pane.sharedOwnerName = machine.machine.ownerName;
}
targetPanes.insert(insertion.clamp(0, targetPanes.length), pane);
+ if (autoTile && split == null) {
+ // A new pane reflows the whole tab. Old manual splits and remembered
+ // sizes for this count must not silently override automatic placement.
+ target.presets.remove(targetPanes.length);
+ target.paneSizes.removeWhere(
+ (key, _) => key.startsWith('${targetPanes.length}:'),
+ );
+ target.arranged = null;
+ target.arrangedKey = null;
+ }
if (split != null) {
target.pinnedSlots.updateAll(
(_, slot) => slot >= insertion ? slot + 1 : slot,
@@ -6169,19 +7691,28 @@ class AppNotifier extends ChangeNotifier {
target.arranged = split.after;
target.arrangedKey = key;
}
- if (firstAgent && target.name == Swarm.defaultName) {
- target.name = _nextHarnessName();
+ if (firstAgent && !target.nameIsCustom) {
+ final agent = machine.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ target.titleMachineId = machineId;
+ target.titleAgentId = agentId;
+ target.name = agent == null || agent.displayName == kUntitledPane
+ ? Swarm.defaultName
+ : agent.displayName;
}
if (replaced != null && !allPanes.contains(replaced)) {
// Release just the desktop stream. The CLI agent process keeps running.
unawaited(_detachSession(replaced, sendClose: true));
}
- target.focusedPaneId = pane.id;
- target.zoomedPaneId = null;
- if (target == activeSwarm) selectedMachineId = machineId;
+ if (focus) {
+ target.focusedPaneId = pane.id;
+ target.zoomedPaneId = null;
+ if (target == activeSwarm) selectedMachineId = machineId;
+ }
_dismissedLinkPrompts.remove(machineId);
- machine.activeAgentId = agentId;
+ if (focus) machine.activeAgentId = agentId;
_persistLayout();
// SAID OUTRIGHT, like every other move.
//
@@ -6196,7 +7727,7 @@ class AppNotifier extends ChangeNotifier {
// After _persistLayout, so the daemon has the new tile roster before it is told to move onto it. A
// duplicate with the inferred one is free: the daemon drops the second against where the dial
// already is.
- if (target == activeSwarm) _announceAppFocus();
+ if (focus && target == activeSwarm) _announceAppFocus();
// The agent may already have a viewer the grid could not show until now,
// because this tile is what it hangs beside.
_syncViewerPane(machine, agent);
@@ -6253,7 +7784,7 @@ class AppNotifier extends ChangeNotifier {
final terminal = TerminalSession(
machineId: pane.machineId,
agentId: agent.id,
- agentName: agent.name,
+ agentName: agent.displayName,
engineId: agent.engine,
send: (type, payload) =>
_conn(pane.machineId).sendTerminalFrame(type, payload),
@@ -6288,8 +7819,11 @@ class AppNotifier extends ChangeNotifier {
pane.session = null;
if (terminal == null) return;
terminal.removeListener(notifyListeners);
- if (sendClose) await terminal.close();
- terminal.dispose();
+ try {
+ if (sendClose) await terminal.close();
+ } finally {
+ terminal.dispose();
+ }
}
/// Take a tile off the grid.
@@ -6309,7 +7843,7 @@ class AppNotifier extends ChangeNotifier {
/// Focus follows the PANE, not the slot: `focusedPaneId` is an id, so a tile
/// that was focused stays focused after it moves, which is what the hand that
/// dragged it expects.
- void reorderPane(int paneId, int targetPaneId) {
+ void reorderPane(int paneId, int targetPaneId, {bool reveal = false}) {
if (paneId == targetPaneId) return;
final from = panes.indexWhere((pane) => pane.id == paneId);
final to = panes.indexWhere((pane) => pane.id == targetPaneId);
@@ -6323,6 +7857,7 @@ class AppNotifier extends ChangeNotifier {
// broken while the state was in fact correct.
if (isPanePinned(panes[to])) _setPin(panes[to], to);
if (isPanePinned(panes[from])) _setPin(panes[from], from);
+ if (reveal && focusedPaneId == paneId) _paneFocusRequest++;
_persistLayout();
notifyListeners();
}
@@ -6432,7 +7967,7 @@ class AppNotifier extends ChangeNotifier {
}
}
- /// ⇧⌘h j k l — put this pane where its neighbour is, and that one here.
+ /// Shift-Command-arrows put this pane where its neighbour is, and that one here.
///
/// A SWAP, not an insert. vim's `Ctrl-w H/J/K/L` — the capitals this mirrors —
/// moves a window to the far edge, which needs a tree of splits to mean
@@ -6441,13 +7976,9 @@ class AppNotifier extends ChangeNotifier {
void movePaneDirection({required int dx, required int dy}) {
final id = focusedPaneId;
if (id == null) return;
- final at = panes.indexWhere((pane) => pane.id == id);
final to = _neighbour(dx: dx, dy: dy);
- if (at < 0 || to == null) return;
- final moved = panes.removeAt(at);
- panes.insert(to, moved);
- _persistLayout();
- notifyListeners();
+ if (to == null) return;
+ reorderPane(id, panes[to].id, reveal: true);
}
/// The index of the tile in the given direction, or null at the edge.
@@ -6567,7 +8098,7 @@ class AppNotifier extends ChangeNotifier {
if (from == -1) return;
final to = from + delta;
if (to < 0 || to >= panes.length) return;
- reorderPane(id, panes[to].id);
+ reorderPane(id, panes[to].id, reveal: true);
}
/// Pin this tile to the slot it is in, or let it go.
@@ -6683,9 +8214,17 @@ class AppNotifier extends ChangeNotifier {
swarm.zoomedPaneId = null;
}
_announceAppFocus();
- for (final pane in open) {
- await _detachSession(pane, sendClose: true);
- }
+ await Future.wait(
+ open.map((pane) async {
+ try {
+ await _detachSession(pane, sendClose: true);
+ } catch (error) {
+ // One disconnected terminal cannot prevent the others, or the saved
+ // account, from being cleared during sign-out.
+ debugPrint('sign-out terminal cleanup failed: $error');
+ }
+ }),
+ );
if (persist) _persistLayout();
}
@@ -6694,25 +8233,6 @@ class AppNotifier extends ChangeNotifier {
Future<void> flushPaneLayout() =>
_paneLayout?.flushSwarms() ?? Future<void>.value();
- String _nextHarnessName() {
- var next = BigInt.one;
- final names = [
- for (final swarm in swarms) swarm.name,
- for (final entry in _closedHistory)
- if (entry is ClosedSwarm)
- entry.name
- else if (entry is ClosedAgent)
- entry.swarmName,
- ];
- for (final name in names) {
- final match = RegExp(r'^harness-([1-9]\d*)$').firstMatch(name);
- if (match == null) continue;
- final number = BigInt.parse(match.group(1)!);
- if (number >= next) next = number + BigInt.one;
- }
- return 'harness-$next';
- }
-
void _persistLayout() {
_draftSwarmReturns.removeWhere((id, _) {
final swarm = swarms.where((swarm) => swarm.id == id).firstOrNull;
@@ -6750,8 +8270,9 @@ class AppNotifier extends ChangeNotifier {
if (store == null) return;
final initialSwarm = activeSwarm;
final revision = _layoutRevision;
+ final authRevision = _authRevision;
final saved = await store.loadSwarms();
- if (_disposed || revision != _layoutRevision) return;
+ if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
if (saved != null &&
allPanes.isEmpty &&
swarms.length == 1 &&
@@ -6774,6 +8295,7 @@ class AppNotifier extends ChangeNotifier {
final swarm =
Swarm(
id: id,
+ nameIsCustom: raw['nameIsCustom'] == true ? true : null,
name:
raw['name'] is String &&
(raw['name'] as String).trim().isNotEmpty
@@ -6797,6 +8319,11 @@ class AppNotifier extends ChangeNotifier {
..orchestratorMachineId = raw['orchestratorMachineId'] is String
? raw['orchestratorMachineId'] as String
: null;
+ swarm.titleMachineId = raw['titleMachineId'] as String?;
+ swarm.titleAgentId = raw['titleAgentId'] as String?;
+ swarm.nameIsCustom =
+ raw['nameIsCustom'] == true ||
+ (swarm.titleAgentId == null && swarm.name != Swarm.defaultName);
for (final item in (raw['panes'] as List).take(maxPanes)) {
final entry = PaneLayoutEntry.fromJson(item);
if (entry == null) continue;
@@ -6819,6 +8346,12 @@ class AppNotifier extends ChangeNotifier {
}
}
}
+ if (!swarm.nameIsCustom &&
+ swarm.titleAgentId == null &&
+ swarm.panes.isNotEmpty) {
+ swarm.titleMachineId = swarm.panes.first.machineId;
+ swarm.titleAgentId = swarm.panes.first.agentId;
+ }
int? paneAt(Object? index) =>
index is int && index >= 0 && index < swarm.panes.length
? swarm.panes[index].id
@@ -6877,14 +8410,14 @@ class AppNotifier extends ChangeNotifier {
// grid this run has not restored any agents into, so a window that opens
// empty and is then filled by hand still comes up the shape it was left.
final legacyPresets = await store.loadPresets();
- if (_disposed || revision != _layoutRevision) return;
+ if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
if (allPanes.isNotEmpty ||
swarms.length != 1 ||
activeSwarm != initialSwarm) {
return;
}
final entries = await store.load();
- if (_disposed || revision != _layoutRevision) return;
+ if (!_authWorkCurrent(authRevision) || revision != _layoutRevision) return;
panePresets.addAll(legacyPresets);
if (entries.isEmpty) {
if (panePresets.isNotEmpty) notifyListeners();
diff --git a/desktop/lib/state/command_bar_catalog.dart b/desktop/lib/state/command_bar_catalog.dart
index e19021468..5f9d4c56f 100644
--- a/desktop/lib/state/command_bar_catalog.dart
+++ b/desktop/lib/state/command_bar_catalog.dart
@@ -15,9 +15,10 @@ const commandBarCommands = {
'Open Machine Monitor, the harness that links, names and retires your computers.',
'machines.list': 'See connected computers and their link state.',
'machine.link': 'Open the setup dialog to connect another computer.',
- 'swarm.new': 'Open a fresh empty tab.',
+ 'swarm.new': 'Choose an existing agent or create one in a new tab.',
'swarm.reopen': 'Reopen the most recently closed harness.',
- 'agent.add': 'Browse existing harnesses and add one to this workspace.',
+ 'agent.add':
+ 'Choose an existing agent or create one in a new pane in this tab.',
'project.add': 'Choose a project folder to add to the workspace.',
'pane.layout': 'Open the workspace layout chooser.',
'pane.zoom': 'Toggle the focused pane between full size and the grid.',
diff --git a/desktop/lib/state/first_harness_launch.dart b/desktop/lib/state/first_harness_launch.dart
new file mode 100644
index 000000000..22fa2cb65
--- /dev/null
+++ b/desktop/lib/state/first_harness_launch.dart
@@ -0,0 +1,37 @@
+import '../core/local_key_value_store.dart';
+
+/// Remembers that the initial launch prompt was offered or superseded by real
+/// work. Escape is a decision too; reconnecting must never reopen the prompt.
+class FirstHarnessLaunch {
+ FirstHarnessLaunch({this.storage});
+ final LocalKeyValueStore? storage;
+ static const storageKey = 'first_harness_launch_v1';
+ bool loaded = false;
+ bool handled = false;
+ Future<void>? _loading;
+ Future<void> _saving = Future.value();
+
+ Future<void> load() => _loading ??= _load();
+ Future<void> _load() async {
+ try {
+ handled = await storage?.read(storageKey) == 'handled' || handled;
+ } catch (_) {
+ // Unavailable preferences never prevent entering the workspace.
+ }
+ loaded = true;
+ }
+
+ void handle() {
+ if (handled) return;
+ handled = true;
+ _saving = _saving.then((_) async {
+ try {
+ await storage?.write(storageKey, 'handled');
+ } catch (_) {
+ // The decision still holds for this window.
+ }
+ });
+ }
+
+ Future<void> flush() => _saving;
+}
diff --git a/desktop/lib/state/harness_placement.dart b/desktop/lib/state/harness_placement.dart
new file mode 100644
index 000000000..d87da8734
--- /dev/null
+++ b/desktop/lib/state/harness_placement.dart
@@ -0,0 +1,11 @@
+/// A requested destination, not an allocated tab or pane. Resolving it waits
+/// until an existing harness is chosen or a new harness is successfully made.
+enum HarnessPlacement {
+ currentTab,
+ newTab;
+
+ String get title => this == newTab ? 'New Tab' : 'New Pane';
+ String get action => this == newTab ? 'Open in new tab' : 'Add to this tab';
+ String get createAction =>
+ this == newTab ? 'Create in new tab' : 'Create in this tab';
+}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
new file mode 100644
index 000000000..9c3c52438
--- /dev/null
+++ b/desktop/lib/state/new_harness.dart
@@ -0,0 +1,2068 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:isolate';
+
+import 'package:collection/collection.dart' show compareNatural;
+import 'package:flutter/foundation.dart';
+import 'package:path/path.dart' as p;
+
+import '../analytics/analytics.dart';
+import '../core/codex_profiles.dart';
+import '../core/dsh_catalog.dart';
+import '../core/first_task.dart';
+import '../core/fuzzy_match.dart';
+import '../core/permission_modes.dart';
+import '../core/project_folder.dart';
+import '../core/repository_clone.dart';
+import '../core/test_run.dart';
+import '../widgets/engine_identity.dart';
+import 'app_state.dart';
+import 'harness_placement.dart';
+import 'pane_arrangement.dart';
+
+/// Whether New Harness opens as a line in the box, or as the full form.
+///
+/// The app, including Store Open/Try, uses the box. Advanced options can still
+/// open the form with the same draft. Legacy form tests leave this off; dock
+/// journeys enable it explicitly.
+bool newHarnessOpensInBox = !kUnderTest;
+
+/// A launch command with inherited arguments. Arrows select a launch argument;
+/// a focused prompt edits one argument at a time. Enter
+/// accepts a choice, Tab completes text, and Escape returns to the menu.
+enum NewHarnessField {
+ launch,
+ task,
+ agent,
+ machine,
+ projectMenu,
+ project,
+ projectName,
+ projectRepository,
+ mode,
+ profile,
+}
+
+/// What Project holds: a folder that exists, a project to make, or a
+/// GitHub repository to clone.
+@immutable
+class NewHarnessProject {
+ /// A new project, named by the person or (null) after the agent and the time.
+ const NewHarnessProject.fresh([this.name])
+ : folder = null,
+ repository = null,
+ generated = null;
+ NewHarnessProject.generated(ProjectFolderRequest request)
+ : name = request.name,
+ generated = request,
+ folder = null,
+ repository = null;
+ const NewHarnessProject.folder(String this.folder)
+ : name = null,
+ repository = null,
+ generated = null;
+ const NewHarnessProject.clone(GitHubRepository this.repository)
+ : name = null,
+ folder = null,
+ generated = null;
+ final String? name;
+ final String? folder;
+ final GitHubRepository? repository;
+ final ProjectFolderRequest? generated;
+ bool get isNew => folder == null;
+
+ @override
+ bool operator ==(Object other) =>
+ other is NewHarnessProject &&
+ other.name == name &&
+ other.generated?.generatedAt == generated?.generatedAt &&
+ other.generated?.generatedLabel == generated?.generatedLabel &&
+ other.folder == folder &&
+ other.repository?.url == repository?.url;
+ @override
+ int get hashCode => Object.hash(
+ name,
+ folder,
+ repository?.url,
+ generated?.generatedAt,
+ generated?.generatedLabel,
+ );
+}
+
+/// A creation buffer shared by the prompt and advanced options. It includes
+/// the receipt of an unresolved request, so going back cannot start a duplicate.
+@immutable
+class NewHarnessDraft {
+ const NewHarnessDraft({
+ required this.machineId,
+ required this.engine,
+ required this.project,
+ required this.task,
+ required this.permissionMode,
+ this.profile,
+ this.profileChosen = false,
+ this.attempt,
+ this.error,
+ this.dismissalWarningShown = false,
+ this.projectsByMachine = const {},
+ });
+
+ final String machineId, engine, task, permissionMode;
+ final NewHarnessProject project;
+ final LocalCodexProfile? profile;
+ final bool profileChosen;
+ final AgentCreationAttempt? attempt;
+ final String? error;
+ // The visible "Escape again" message must keep the same meaning if the
+ // unresolved prompt is dismissed and then restored.
+ final bool dismissalWarningShown;
+ final Map<String, NewHarnessProject> projectsByMachine;
+
+ ProjectFolderRequest? get projectFolderRequest =>
+ project.folder != null || isTerminalEngine(engine)
+ ? null
+ : project.repository != null
+ ? ProjectFolderRequest.remote(project.repository!)
+ : project.generated ??
+ ProjectFolderRequest.newProject(name: project.name);
+}
+
+@immutable
+class NewHarnessOption {
+ const NewHarnessOption({
+ required this.id,
+ required this.title,
+ this.detail = '',
+ this.engine,
+ this.project,
+ this.profile,
+ this.machineId,
+ this.enabled = true,
+ this.synthetic = false,
+ this.risky = false,
+ this.why,
+ });
+
+ /// A row the box adds rather than finds — "New project", "Use this folder".
+ /// It is never a match, so it is in neither half of the `2 of 14`.
+ final bool synthetic;
+
+ /// A permission mode that disables the engine's safety checks.
+ final bool risky;
+
+ /// Why the row cannot be chosen, said when somebody tries.
+ final String? why;
+
+ /// An engine or harness id, a machine id, or a project token.
+ final String id;
+ final String title, detail;
+
+ /// Whose mark the row wears, on the agent field.
+ final String? engine;
+
+ /// What choosing the row sets, on the project field.
+ final NewHarnessProject? project;
+
+ /// A profile folder on [machineId], never on an implicitly different host.
+ final LocalCodexProfile? profile;
+
+ /// A recent project chooses its machine and folder together.
+ final String? machineId;
+ final bool enabled;
+}
+
+enum NewHarnessOutcome { created, failed }
+
+class NewHarnessController extends ChangeNotifier {
+ NewHarnessController(
+ this.app, {
+ required String machineId,
+ String? engine,
+ String? folder,
+ String? projectName,
+ bool autoProject = false,
+ DateTime Function()? now,
+ String? task,
+ NewHarnessDraft? draft,
+ this.swarmId,
+ this.split,
+ this.placement,
+ this.offersStore = false,
+ this.firstRun = false,
+ String? home,
+ }) : _machineId = draft?.machineId ?? machineId,
+ _autoProject = autoProject || draft?.project.generated != null,
+ _now = now ?? DateTime.now,
+ _home = home ?? Platform.environment['HOME'] {
+ final remembered = app.agentPreference.value;
+ engine = draft?.engine ?? engine;
+ _engine = _known(engine)
+ ? engine!
+ : _known(remembered)
+ ? remembered!
+ : allEngines.first.id;
+ _project = projectName != null
+ ? NewHarnessProject.fresh(projectName)
+ : folder != null
+ ? NewHarnessProject.folder(folder)
+ : _autoProject
+ ? _generatedProject()
+ : const NewHarnessProject.fresh();
+ if (task != null) this.task = task;
+ if (draft != null) {
+ _projectsByMachine.addAll(draft.projectsByMachine);
+ _project = draft.project;
+ this.task = draft.task;
+ _mode = draft.permissionMode;
+ _profile = draft.profile;
+ _profileChosen = draft.profileChosen;
+ _attempt = draft.attempt;
+ error = draft.error;
+ _warnedAboutClosing = draft.dismissalWarningShown;
+ }
+ if ((projectName != null || _autoProject) &&
+ !checking &&
+ _project.folder == null &&
+ _project.repository == null &&
+ (_project.name?.isEmpty ?? true)) {
+ _project = projectName != null
+ ? NewHarnessProject.fresh(projectName)
+ : _generatedProject();
+ }
+ // A missing destination is the only required question. A carried task is
+ // shown in the launch summary and remains editable, including after Escape.
+ field = needsProject && !checking
+ ? NewHarnessField.projectMenu
+ : NewHarnessField.launch;
+ query = field == NewHarnessField.task ? this.task : '';
+ if (!takesTask && this.task.trim().isNotEmpty && !checking) {
+ error =
+ '$agentLabel cannot start on a first message, so '
+ '“${_short(this.task)}” will not be sent. Choose another agent to send it.';
+ }
+ app.addListener(_onApp);
+ _refresh();
+ unawaited(
+ app.projectHistory.load().then((_) {
+ if (!_disposed && !listEquals(_seen, _signature())) _refresh();
+ }),
+ );
+ // What the machine has is asked when the box opens, as the form does: an
+ // engine installed in a terminal a minute ago is otherwise still "missing".
+ if (firstRun) {
+ unawaited(_detectInitialAgent(allowSelection: engine == null));
+ } else {
+ unawaited(app.probeEngines(_machineId, force: true));
+ }
+ unawaited(app.probeDsh(_machineId, force: true));
+ unawaited(_ensureHome(_machineId));
+ unawaited(_refreshGeneratedProject());
+ }
+
+ final AppNotifier app;
+ final String? swarmId;
+ final PaneSplitRequest? split;
+ final HarnessPlacement? placement;
+ final bool firstRun;
+ final bool _autoProject;
+ final DateTime Function() _now;
+ bool detectingAgent = false;
+ bool _agentEdited = false;
+ final String? _home;
+
+ late String _engine;
+ String _machineId;
+ late NewHarnessProject _project;
+ final _projectsByMachine = <String, NewHarnessProject>{};
+ final _homes = <String, String>{};
+ final _homeRequests = <String, Future<String?>>{};
+ int _machineRevision = 0;
+ String get engine => _engine;
+ String get machineId => _machineId;
+ NewHarnessProject get project => _project;
+ LocalCodexProfile? _profile;
+ bool _profileChosen = false;
+ String? get profileLabel =>
+ _base == 'codex' && (_profileChosen || _profile != null)
+ ? _profile?.label ?? 'Default'
+ : null;
+
+ NewHarnessDraft get draft => NewHarnessDraft(
+ machineId: _machineId,
+ engine: _engine,
+ project: _project,
+ task: task,
+ permissionMode: _mode,
+ profile: _profile,
+ profileChosen: _profileChosen,
+ attempt: _attempt,
+ error: error,
+ dismissalWarningShown: _warnedAboutClosing,
+ projectsByMachine: Map.unmodifiable({
+ ..._projectsByMachine,
+ _machineId: _project,
+ }),
+ );
+
+ /// The same preparation intent is used by the prompt and advanced options.
+ ProjectFolderRequest? get projectFolderRequest =>
+ _project.folder != null || isTerminal
+ ? null
+ : _project.repository != null
+ ? ProjectFolderRequest.remote(_project.repository!)
+ : _project.generated ??
+ ProjectFolderRequest.newProject(name: _project.name);
+
+ NewHarnessField field = NewHarnessField.agent;
+ final bool offersStore;
+ String query = '';
+
+ /// The harness's first message, sent exactly as written as it starts. Empty
+ /// starts it with nothing sent. Kept while the other answers are changed.
+ String task = '';
+
+ /// The permission mode picked, by id; an engine without it uses its default.
+ String _mode = kDefaultPermissionMode;
+
+ /// The engine a choice launches: a store harness runs ON one of them.
+ String _baseOf(String engine) => isHarnessId(engine)
+ ? _machine?.dsh[engine]?.engine ?? knownHarnessBase[engine] ?? 'claude'
+ : engine;
+ String get _base => _baseOf(_engine);
+
+ // Browsing previews an engine without changing the launch draft. Keep that
+ // engine while its settings are open in a child picker.
+ String? _agentPreview;
+ String get _settingsEngine => _agentPreview ?? _engine;
+ String get agentSettingsLabel => labelOf(_settingsEngine);
+ LocalCodexProfile? get _settingsProfile =>
+ _settingsEngine == _engine ? _profile : null;
+ List<PermissionMode> get _settingsModes =>
+ permissionModesOf(_baseOf(_settingsEngine));
+ String get _settingsMode => _settingsModes.any((mode) => mode.id == _mode)
+ ? _mode
+ : kDefaultPermissionMode;
+ bool get takesTask => takesFirstTask(_base);
+ String get taskAvailability => takesTask
+ ? 'Add a task (optional)'
+ : 'Enter a task in $agentLabel after launch';
+ bool get taskTooLong => task.trim().length > kFirstTaskMaxLength;
+ List<PermissionMode> get _modes =>
+ isTerminal ? const [] : permissionModesOf(_base);
+ bool get hasModes => _modes.isNotEmpty;
+ String get mode =>
+ _modes.any((mode) => mode.id == _mode) ? _mode : kDefaultPermissionMode;
+ String get modeLabel =>
+ _modes.where((m) => m.id == mode).firstOrNull?.label ?? mode;
+ bool get riskyMode => _modes.any((m) => m.id == mode && m.risky);
+ bool get hasProfile => _baseOf(_settingsEngine) == 'codex';
+ bool get supportsProfiles =>
+ hasProfile && _machine?.engines['codex']?.supportsCodexHome == true;
+ String? get profileHelp => supportsProfiles
+ ? null
+ : _machine?.engines.loaded == true
+ ? 'Update Harness CLI on $machineLabel to choose a Codex profile.'
+ : 'Checking Codex profile support on $machineLabel…';
+
+ /// Settings are offered separately so browsing never inserts list rows.
+ List<NewHarnessOption> agentSettingsFor(String engine) {
+ final modes = permissionModesOf(_baseOf(engine));
+ final mode =
+ modes.where((mode) => mode.id == _mode).firstOrNull ??
+ modes.where((mode) => mode.id == kDefaultPermissionMode).firstOrNull;
+ return [
+ if (mode != null)
+ NewHarnessOption(
+ id: permissionsId,
+ title: 'Permissions',
+ detail: mode.label,
+ synthetic: true,
+ ),
+ if (_baseOf(engine) == 'codex')
+ NewHarnessOption(
+ id: profileId,
+ title: 'Codex Profile',
+ detail: engine == _engine ? profileLabel ?? 'Default' : 'Default',
+ synthetic: true,
+ ),
+ ];
+ }
+
+ void openAgentSetting(String engine, String setting) {
+ if (locked ||
+ field != NewHarnessField.agent ||
+ !options.any((row) => row.engine == engine) ||
+ !agentSettingsFor(engine).any((row) => row.id == setting)) {
+ return;
+ }
+ _agentPreview = engine;
+ focusField(
+ setting == profileId ? NewHarnessField.profile : NewHarnessField.mode,
+ );
+ }
+
+ /// The arguments exposed by the launch menu. Machine sets the context;
+ /// permissions and profiles belong to the selected agent's picker.
+ List<NewHarnessField> get fields => [
+ NewHarnessField.agent,
+ NewHarnessField.machine,
+ NewHarnessField.projectMenu,
+ if (takesTask) NewHarnessField.task,
+ ];
+ bool _supportsField(NewHarnessField value) =>
+ fields.contains(value) ||
+ value == NewHarnessField.launch ||
+ value == NewHarnessField.project ||
+ value == NewHarnessField.projectName ||
+ value == NewHarnessField.projectRepository ||
+ value == NewHarnessField.machine ||
+ (value == NewHarnessField.mode && _settingsModes.isNotEmpty) ||
+ (value == NewHarnessField.profile && hasProfile);
+
+ NewHarnessField get nextMainField => field == NewHarnessField.machine
+ ? NewHarnessField.projectMenu
+ : fields[(fields.indexOf(field) + 1) % fields.length];
+ int cursor = 0;
+ List<NewHarnessOption> options = const [];
+
+ /// How many things the field has before what was typed narrowed them, and
+ /// how many are left: the `2 of 14` beside the input. Rows the box adds
+ /// itself are in neither number — "1 of 0" was the count lying.
+ int total = 0;
+ int matchCount = 0;
+
+ /// A folder's listing has been asked for and has not come back: the list is
+ /// not empty, it is not here yet, and the two must not read the same.
+ bool get listing => _listing != null;
+ bool busy = false;
+ String? status;
+ String? error;
+ bool _disposed = false;
+
+ /// Folder listings for path completion, by the folder that was listed.
+ final _listings = <String, List<String>>{};
+ String? _listing;
+
+ bool _known(String? id) =>
+ id != null &&
+ (isTerminalEngine(id) ||
+ isHarnessId(id) ||
+ allEngines.any((identity) => identity.id == id));
+
+ MachineState? get _machine => app.stateOf(_machineId);
+ bool get isTerminal => isTerminalEngine(_engine);
+ bool get needsProject =>
+ !isTerminal &&
+ _project.folder == null &&
+ _project.repository == null &&
+ projectFolderSlug(_project.name ?? '') == null;
+
+ // ---- what the line says -------------------------------------------------
+
+ String get createLabel => 'Start';
+
+ Future<void> _detectInitialAgent({required bool allowSelection}) async {
+ detectingAgent = true;
+ final machineId = _machineId;
+ await Future.wait([
+ app.agentPreference.load(),
+ app.probeEngines(machineId, force: true),
+ ]);
+ if (_disposed) return;
+ detectingAgent = false;
+ if (allowSelection && !_agentEdited && machineId == _machineId) {
+ final installed = [
+ for (final identity in allEngines)
+ if (_machine?.engines[identity.id]?.installed == true) identity.id,
+ ];
+ final preferred = app.agentPreference.value;
+ final chosen = installed.contains(preferred)
+ ? preferred
+ : installed.firstOrNull ?? (_known(preferred) ? preferred : null);
+ if (chosen != null) _selectEngine(chosen);
+ }
+ _refresh();
+ }
+
+ String get agentLabel => labelOf(_engine);
+ String labelOf(String id) =>
+ _machine?.dsh[id]?.name ??
+ (id == 'claude' ? 'Claude Code' : engineIdentity(id).label);
+
+ String get machineLabel => _machineLabel(_machineId);
+ String _machineLabel(String id) =>
+ app.stateOf(id)?.machine.displayName ?? 'No machine';
+
+ String get projectLabel {
+ final project = _project;
+ if (project.folder case final folder?) return tildePath(folder);
+ if (project.repository case final repo?) return '~/harnesses/${repo.name}';
+ if (isTerminal) return '~';
+ final name = project.name == null ? null : projectFolderSlug(project.name!);
+ return name == null ? '~/harnesses' : '~/harnesses/$name';
+ }
+
+ String get projectLocation => needsProject
+ ? 'Choose a project on $machineLabel'
+ : '$machineLabel:$projectLabel';
+
+ String location(String path, [String? machineId]) {
+ final id = machineId ?? _machineId;
+ return '${_machineLabel(id)}:${tildePath(path, id)}';
+ }
+
+ String? _homeOf(String id) =>
+ app.stateOf(id)?.isLocalMachine == true ? _home : _homes[id];
+
+ String tildePath(String path, [String? machineId]) {
+ final home = _homeOf(machineId ?? _machineId);
+ if (home == null) return path;
+ return path == home
+ ? '~'
+ : path.startsWith('$home/')
+ ? '~${path.substring(home.length)}'
+ : path;
+ }
+
+ String get hint => switch (field) {
+ NewHarnessField.launch => '',
+ NewHarnessField.projectMenu => 'Find a project by name or path',
+ NewHarnessField.task => 'What should this agent work on? (optional)',
+ NewHarnessField.agent => 'Choose an agent',
+ NewHarnessField.machine => 'Choose a machine',
+ NewHarnessField.project => 'Enter a folder path, or press Enter to browse',
+ NewHarnessField.projectName => 'Type a project name',
+ NewHarnessField.projectRepository => 'Paste a GitHub repository URL',
+ NewHarnessField.mode => 'How much it may do without asking',
+ NewHarnessField.profile => 'Find a Codex profile',
+ };
+
+ // ---- moving along the line ----------------------------------------------
+
+ ({NewHarnessField field, String query, String? agentPreview}) _machineOrigin =
+ (field: NewHarnessField.launch, query: '', agentPreview: null);
+
+ void focusField(NewHarnessField next) {
+ if (locked || field == next || !_supportsField(next)) return;
+ // Discovery may finish while somebody edits. Never change their choice
+ // or the rows they are navigating underneath their fingers.
+ if (next == NewHarnessField.agent || next == NewHarnessField.machine) {
+ _agentEdited = true;
+ }
+ if (next == NewHarnessField.machine) {
+ _machineOrigin = (
+ field: field,
+ query: query,
+ agentPreview: _agentPreview,
+ );
+ }
+ if (next == NewHarnessField.mode || next == NewHarnessField.profile) {
+ _agentSettingsOrigin = (
+ field: field == NewHarnessField.agent
+ ? NewHarnessField.agent
+ : NewHarnessField.launch,
+ query: field == NewHarnessField.agent ? query : '',
+ );
+ } else {
+ _agentPreview = null;
+ }
+ if (field == NewHarnessField.projectMenu) _projectFilter = query;
+ if (next == NewHarnessField.projectMenu &&
+ field == NewHarnessField.launch) {
+ _projectFilter = '';
+ }
+ field = next;
+ _editingSuggestedProject =
+ next == NewHarnessField.projectName && _project.generated != null;
+ _cycle = null;
+ _steered = false;
+ // Keep the task and a Project filter when returning from a child prompt.
+ // A fresh visit from the launch menu starts with all recent projects.
+ query = next == NewHarnessField.task
+ ? task
+ : next == NewHarnessField.projectName
+ ? _project.name ?? ''
+ : next == NewHarnessField.projectMenu
+ ? _projectFilter
+ : '';
+ error = null;
+ _refresh();
+ }
+
+ void nextField([int step = 1]) {
+ if (field == NewHarnessField.machine) {
+ _returnToProject();
+ return;
+ }
+ final line = fields;
+ final at = line.indexOf(field);
+ focusField(line[((at < 0 ? 0 : at) + step) % line.length]);
+ }
+
+ void setQuery(String value) {
+ if (locked || field == NewHarnessField.launch || query == value) {
+ return;
+ }
+ if (field == NewHarnessField.projectName) _editingSuggestedProject = false;
+ if (field == NewHarnessField.task) {
+ task = query = value;
+ error = taskTooLong
+ ? 'A first message can be $kFirstTaskMaxLength characters; '
+ 'this is ${value.trim().length}.'
+ : null;
+ notifyListeners();
+ return;
+ }
+ // A completion menu's `/`: with a folder highlighted, typing a slash takes
+ // that folder and goes into it, rather than the half-typed stem before it.
+ if (field == NewHarnessField.project &&
+ _isPath(query) &&
+ value == '$query/' &&
+ !query.endsWith('/')) {
+ final folder = selected?.project?.folder;
+ final slash = query.lastIndexOf('/');
+ if (folder != null &&
+ slash >= 0 &&
+ selected!.detail.startsWith('Use ') == false) {
+ value = '${query.substring(0, slash + 1)}${selected!.title}/';
+ }
+ }
+ // Typing ends a Tab walk: the list goes back to following what is typed.
+ _cycle = null;
+ query = value;
+ error = null;
+ _refresh(resetCursor: true);
+ // A filter's top row is the person's: they typed what put it there.
+ _steered = value.trim().isNotEmpty;
+ }
+
+ /// Only an explicitly highlighted result may override a launch argument
+ /// when using the quick-start shortcut from a picker.
+ bool _steered = false;
+
+ /// The arrows end a Tab walk: the line goes back to what was typed and the
+ /// highlight is the arrows' again. Left set, the walk outranked them — the
+ /// next app tick or folder listing yanked the highlight back to its row.
+ void _endCycle() {
+ final cycle = _cycle;
+ if (cycle == null) return;
+ _cycle = null;
+ query = '${cycle.typedParent}${cycle.stem}';
+ }
+
+ /// Escape during a Tab walk gives back what was typed, as vim's wildmenu
+ /// does, before it closes anything. Whether there was a walk to end.
+ bool endCompletion() {
+ if (_cycle == null || locked) return false;
+ _endCycle();
+ _refresh();
+ return true;
+ }
+
+ void move(int delta) {
+ if (options.isEmpty || locked) return;
+ _endCycle();
+ cursor = (cursor + delta) % options.length;
+ _steered = true;
+ if (field == NewHarnessField.agent) {
+ _refresh();
+ return;
+ }
+ notifyListeners();
+ }
+
+ NewHarnessOption? get selected =>
+ cursor < 0 || cursor >= options.length ? null : options[cursor];
+
+ /// The answers cannot change: a create is running, or one whose reply was
+ /// lost has still to be checked on.
+ bool get locked => busy || checking || linkingProfile;
+
+ /// Lists always choose. The launch menu and optional task prompt start.
+ bool get returnCreates =>
+ checking ||
+ field == NewHarnessField.launch ||
+ field == NewHarnessField.task;
+
+ /// Whether [option] is the answer the line already gives — the row that
+ /// wears the ✓, as the current folder and branch do in an editor's pickers.
+ bool isCurrent(NewHarnessOption option) => switch (field) {
+ NewHarnessField.launch || NewHarnessField.task => false,
+ NewHarnessField.agent => option.id == _engine,
+ NewHarnessField.machine => option.id == _machineId,
+ NewHarnessField.project ||
+ NewHarnessField.projectMenu ||
+ NewHarnessField.projectName ||
+ NewHarnessField.projectRepository =>
+ option.project != null &&
+ (option.machineId ?? _machineId) == _machineId &&
+ option.project == _project,
+ NewHarnessField.mode => option.id == _settingsMode,
+ NewHarnessField.profile =>
+ option.id ==
+ (_settingsProfile == null
+ ? defaultProfileId
+ : 'profile:${_settingsProfile!.path}'),
+ };
+ bool _isCurrent(NewHarnessOption option) => isCurrent(option);
+
+ /// The project row that opens the system's folder chooser: the way in for
+ /// anyone who would rather point at a folder than type its path.
+ static const browseId = 'project:browse';
+ static const changeMachineId = 'project:machine';
+ static const newProjectId = 'project:name';
+ static const existingProjectId = 'project:existing';
+ static const repositoryId = 'project:repository';
+ static const storeId = 'agent:store';
+ static const permissionsId = 'agent:permissions';
+ static const profileId = 'agent:profile';
+ static const defaultProfileId = 'profile:default';
+ static const refreshProfilesId = 'profile:refresh';
+ static const linkProfileId = 'profile:link';
+ static const _store = NewHarnessOption(
+ id: storeId,
+ synthetic: true,
+ title: 'Browse more harnesses…',
+ detail: 'Harness Store',
+ );
+
+ // For anyone who would rather point at a folder than type its path. It stays
+ // under whatever is typed: the way out must not vanish on the first key.
+ NewHarnessOption get _browse =>
+ NewHarnessOption(id: browseId, synthetic: true, title: 'Open Folder');
+
+ NewHarnessOption get _changeMachine => NewHarnessOption(
+ id: changeMachineId,
+ synthetic: true,
+ title: 'Change Machine',
+ detail: machineLabel,
+ );
+
+ List<NewHarnessOption> _projectMenu() => [
+ const NewHarnessOption(
+ id: repositoryId,
+ synthetic: true,
+ title: 'Clone GitHub Repository',
+ detail: 'Paste a GitHub repository URL',
+ ),
+ const NewHarnessOption(
+ id: existingProjectId,
+ synthetic: true,
+ title: 'Open Folder',
+ detail: 'Enter a path or browse folders',
+ ),
+ const NewHarnessOption(
+ id: newProjectId,
+ synthetic: true,
+ title: 'New Project',
+ detail: 'Name a new folder',
+ ),
+ ..._ranked(_recentProjects()),
+ ];
+
+ /// Takes the highlighted row as this field's answer and moves along.
+ void accept([NewHarnessOption? row]) {
+ final option = row ?? selected;
+ if (locked || option?.id == storeId) return;
+ if (option?.id == permissionsId) {
+ focusField(NewHarnessField.mode);
+ return;
+ }
+ if (option?.id == profileId) {
+ focusField(NewHarnessField.profile);
+ return;
+ }
+ if (option?.id == refreshProfilesId) {
+ unawaited(refreshProfiles());
+ return;
+ }
+ if (option?.id == linkProfileId) return;
+ if (option?.id == changeMachineId) {
+ focusField(NewHarnessField.machine);
+ return;
+ }
+ if (option?.id == newProjectId) {
+ focusField(NewHarnessField.projectName);
+ return;
+ }
+ if (option?.id == existingProjectId) {
+ focusField(NewHarnessField.project);
+ return;
+ }
+ if (option?.id == repositoryId) {
+ focusField(NewHarnessField.projectRepository);
+ return;
+ }
+ if (option?.id == browseId) return;
+ if (option == null) {
+ // Return is never silent: nothing matched, so say so and how to go on.
+ error = field == NewHarnessField.projectName && query.trim().isEmpty
+ ? 'Type a project name.'
+ : field == NewHarnessField.projectRepository
+ ? 'Enter a GitHub URL or a short name like openai/codex.'
+ : listing
+ ? 'Still reading that folder…'
+ : field == NewHarnessField.project && _isPath(query)
+ ? 'No folder matches “${query.trim()}”.'
+ : 'Nothing matches “${query.trim()}”. Edit it, or press Escape to go back.';
+ notifyListeners();
+ return;
+ }
+ if (!option.enabled) {
+ // A key that silently does nothing is the worst answer: say why.
+ error = option.why ?? '${option.title} cannot be chosen.';
+ notifyListeners();
+ return;
+ }
+ if (field == NewHarnessField.profile && option.machineId != _machineId) {
+ warn('Choose a Codex profile on $machineLabel. The machine has changed.');
+ return;
+ }
+ if ((field == NewHarnessField.projectMenu ||
+ field == NewHarnessField.project ||
+ field == NewHarnessField.projectName ||
+ field == NewHarnessField.projectRepository) &&
+ option.machineId != null &&
+ option.machineId != _machineId) {
+ warn('Choose a project on $machineLabel. The machine has changed.');
+ return;
+ }
+ final from = field;
+ final previousMachine = _machineId;
+ _apply(option);
+ _cycle = null;
+ if (from == NewHarnessField.machine) {
+ _returnFromMachine(changed: previousMachine != _machineId);
+ return;
+ }
+ if (from == NewHarnessField.mode || from == NewHarnessField.profile) {
+ _returnFromAgentSettings(accepted: true);
+ return;
+ }
+ _agentPreview = null;
+ field = needsProject ? NewHarnessField.projectMenu : NewHarnessField.launch;
+ query = '';
+ _refresh(resetCursor: true);
+ }
+
+ /// The folder the system chooser (or the remote browser) came back with.
+ void setFolder(String folder) {
+ if (locked) return;
+ _project = NewHarnessProject.folder(folder);
+ field = NewHarnessField.launch;
+ _cycle = null;
+ query = field == NewHarnessField.task ? task : '';
+ error = null;
+ _refresh(resetCursor: true);
+ }
+
+ /// ⌘↵: make it now — WITH the row under the highlight. Creating with the
+ /// old answer while a different one was lit threw away the one thing the
+ /// person had just done.
+ Future<NewHarnessOutcome> createNow() {
+ if (!locked &&
+ (field == NewHarnessField.projectMenu ||
+ field == NewHarnessField.machine ||
+ field == NewHarnessField.mode ||
+ field == NewHarnessField.profile ||
+ selected?.id == permissionsId ||
+ selected?.id == profileId ||
+ selected?.id == changeMachineId ||
+ selected?.id == newProjectId)) {
+ accept();
+ return Future.value(NewHarnessOutcome.failed);
+ }
+ if (!locked && !returnCreates && selected == null) {
+ accept();
+ return Future.value(NewHarnessOutcome.failed);
+ }
+ if (!locked && selected?.id == browseId) {
+ return Future.value(_fail('Choose a folder to continue.'));
+ }
+ if (selected?.id == storeId && !locked) {
+ return Future.value(_fail('Choose a harness from the Store first.'));
+ }
+ // Only a row the person went to: see [_steered].
+ final option = _steered ? selected : null;
+ if (!checking && !busy && option != null && !option.enabled) {
+ // Never make it with the OLD answer while a different one is lit.
+ if (!returnCreates) {
+ return Future.value(
+ _fail(option.why ?? '${option.title} cannot be chosen.'),
+ );
+ }
+ }
+ if (!checking && !busy && option != null && option.enabled) {
+ if (!returnCreates) {
+ _apply(option);
+ _cycle = null;
+ query = '';
+ _refresh(resetCursor: true);
+ }
+ }
+ return create();
+ }
+
+ void _apply(NewHarnessOption option) {
+ switch (field) {
+ case NewHarnessField.agent:
+ _selectEngine(option.id);
+ case NewHarnessField.machine:
+ _selectMachine(option.id);
+ case NewHarnessField.project:
+ case NewHarnessField.projectMenu:
+ case NewHarnessField.projectName:
+ case NewHarnessField.projectRepository:
+ if (option.machineId case final id?) _selectMachine(id);
+ _project = option.project ?? _project;
+ case NewHarnessField.mode:
+ _selectEngine(_settingsEngine);
+ _mode = option.id;
+ case NewHarnessField.profile:
+ _selectEngine(_settingsEngine);
+ _profile = option.profile;
+ _profileChosen = true;
+ case NewHarnessField.task:
+ case NewHarnessField.launch:
+ break;
+ }
+ }
+
+ void _selectEngine(String engine) {
+ final changed = engine != _engine;
+ if (_engine != engine) {
+ _profile = null;
+ _profileChosen = false;
+ _resetProfiles();
+ }
+ _engine = engine;
+ if (changed &&
+ _project.generated != null &&
+ field != NewHarnessField.projectName) {
+ _project = _generatedProject();
+ unawaited(_refreshGeneratedProject());
+ }
+ _dropAccepted = false;
+ if (!takesTask && task.trim().isNotEmpty) {
+ error =
+ '${labelOf(engine)} cannot start on a first message, so '
+ '“${_short(task)}” will not be sent. Type it once it is open.';
+ }
+ }
+
+ void _selectMachine(String id) {
+ if (_machineId == id) return;
+ _projectsByMachine[_machineId] = _project;
+ _machineId = id;
+ _projectFilter = '';
+ _project =
+ _projectsByMachine[id] ??
+ (_autoProject ? _generatedProject() : const NewHarnessProject.fresh());
+ _profile = null;
+ _profileChosen = false;
+ _agentPreview = null;
+ _resetProfiles();
+ _machineRevision++;
+ _listDebounce?.cancel();
+ _listings.clear();
+ _listing = null;
+ _pathKey = null;
+ unawaited(app.probeEngines(id, force: true));
+ unawaited(app.probeDsh(id, force: true));
+ unawaited(_ensureHome(id));
+ unawaited(_refreshGeneratedProject());
+ }
+
+ NewHarnessProject _generatedProject() => NewHarnessProject.generated(
+ ProjectFolderRequest.generated(
+ label: _machine?.dsh[_engine]?.name ?? engineIdentity(_engine).label,
+ at: _now(),
+ ),
+ );
+
+ /// Offer an unused name without creating anything. Start still reserves the
+ /// folder atomically, including when two previews saw the same free name.
+ Future<void> _refreshGeneratedProject() async {
+ final project = _project;
+ final request = project.generated;
+ if (request == null) return;
+ final id = _machineId;
+ final revision = _machineRevision;
+ try {
+ final home = await _ensureHome(id);
+ if (home == null) return;
+ final root = p.join(home, 'harnesses');
+ final List<String> names;
+ if (app.stateOf(id)?.isLocalMachine == true) {
+ names = await Isolate.run(
+ () =>
+ Directory(root)
+ .listSync(followLinks: false)
+ .map((entry) => p.basename(entry.path))
+ .toList(),
+ );
+ } else {
+ final answer = await app.listRemoteFolder(id, root);
+ final entries = answer['entries'];
+ if (entries is! List) return;
+ names = [
+ for (final entry in entries)
+ if (entry is Map && entry['name'] is String)
+ entry['name'] as String,
+ ];
+ }
+ if (_disposed ||
+ locked ||
+ id != _machineId ||
+ revision != _machineRevision ||
+ field == NewHarnessField.projectName ||
+ !identical(project, _project)) {
+ return;
+ }
+ final name = request.availableGeneratedName(names);
+ if (name == project.name) return;
+ _project = NewHarnessProject.generated(request.withGeneratedName(name));
+ _refresh();
+ } catch (_) {
+ // Missing or unreadable listings are not permission to reuse a folder.
+ // The exclusive reservation at Start remains authoritative.
+ }
+ }
+
+ ({NewHarnessField field, String query}) _agentSettingsOrigin = (
+ field: NewHarnessField.launch,
+ query: '',
+ );
+
+ void _returnFromAgentSettings({bool accepted = false}) {
+ final engine = _settingsEngine;
+ field = _agentSettingsOrigin.field;
+ query = _agentSettingsOrigin.query;
+ if (accepted && field == NewHarnessField.launch && needsProject) {
+ field = NewHarnessField.projectMenu;
+ query = '';
+ }
+ _cycle = null;
+ error = null;
+ _refresh(resetCursor: true, agentSelection: engine);
+ }
+
+ List<LocalCodexProfile> _profiles = const [];
+ String? _profilesMachine;
+ int _profileRevision = 0;
+ int _profileRequest = 0;
+ bool loadingProfiles = false;
+ bool linkingProfile = false;
+
+ void _resetProfiles() {
+ _profiles = const [];
+ _profilesMachine = null;
+ _profileRevision++;
+ _profileRequest++;
+ loadingProfiles = linkingProfile = false;
+ }
+
+ Future<void> refreshProfiles() async {
+ if (_disposed || locked || loadingProfiles || !supportsProfiles) return;
+ final machine = _machineId;
+ final revision = _profileRevision;
+ final request = ++_profileRequest;
+ bool current() =>
+ !_disposed &&
+ revision == _profileRevision &&
+ request == _profileRequest;
+ _profilesMachine = machine;
+ loadingProfiles = true;
+ error = null;
+ _refresh();
+ try {
+ final result = await app.listCodexProfiles(
+ machine,
+ observedPaths: {
+ for (final agent in _machine?.agents ?? const [])
+ if (agent.engine == 'codex' && agent.codexHome != null)
+ agent.codexHome!,
+ },
+ );
+ if (!current()) return;
+ if (result['error'] != null) throw StateError('Profiles unavailable');
+ _profiles = [
+ for (final raw in result['profiles'] as List? ?? const [])
+ LocalCodexProfile.fromJson(Map<String, dynamic>.from(raw as Map)),
+ ];
+ } catch (_) {
+ if (current() && field == NewHarnessField.profile) {
+ error =
+ 'Could not load Codex profiles on $machineLabel. Choose Refresh profiles to retry.';
+ }
+ } finally {
+ if (current()) {
+ loadingProfiles = false;
+ _refresh();
+ }
+ }
+ }
+
+ Future<void> linkProfile(String path) async {
+ if (_disposed ||
+ locked ||
+ !supportsProfiles ||
+ field != NewHarnessField.profile) {
+ return;
+ }
+ final revision = _profileRevision;
+ bool current() => !_disposed && revision == _profileRevision;
+ linkingProfile = true;
+ error = null;
+ _refresh();
+ try {
+ final result = await app.linkCodexProfile(_machineId, path);
+ if (!current()) return;
+ if (result['error'] != null || result['profile'] is! Map) {
+ throw StateError('Profile unavailable');
+ }
+ _selectEngine(_settingsEngine);
+ _profile = LocalCodexProfile.fromJson(
+ Map<String, dynamic>.from(result['profile'] as Map),
+ );
+ _profileChosen = true;
+ _profiles = [..._profiles, _profile!];
+ linkingProfile = false;
+ _returnFromAgentSettings(accepted: true);
+ } catch (_) {
+ if (current()) {
+ error =
+ 'Could not link this Codex profile folder on $machineLabel. Try another folder.';
+ }
+ } finally {
+ if (current()) {
+ linkingProfile = false;
+ _refresh();
+ }
+ }
+ }
+
+ List<NewHarnessOption> _profileOptions() {
+ final choices = <String, LocalCodexProfile>{
+ if (supportsProfiles) ...{
+ for (final profile in [..._profiles, ?_settingsProfile])
+ profile.path: profile,
+ },
+ };
+ return [
+ if (supportsProfiles) ...[
+ const NewHarnessOption(
+ id: linkProfileId,
+ title: 'Link profile folder…',
+ synthetic: true,
+ ),
+ NewHarnessOption(
+ id: refreshProfilesId,
+ title: loadingProfiles ? 'Loading profiles…' : 'Refresh profiles',
+ synthetic: true,
+ enabled: !loadingProfiles,
+ ),
+ ],
+ ..._ranked([
+ NewHarnessOption(
+ id: defaultProfileId,
+ title: 'Default profile',
+ detail: 'Use Codex’s default account on $machineLabel',
+ machineId: _machineId,
+ ),
+ for (final profile in choices.values)
+ NewHarnessOption(
+ id: 'profile:${profile.path}',
+ title: profile.label,
+ detail: profile.path,
+ profile: profile,
+ machineId: _machineId,
+ ),
+ ]),
+ ];
+ }
+
+ String _projectFilter = '';
+ bool _editingSuggestedProject = false;
+
+ void _returnToProject() {
+ field = NewHarnessField.projectMenu;
+ query = _projectFilter;
+ _cycle = null;
+ error = null;
+ _refresh(resetCursor: true);
+ }
+
+ void _returnFromMachine({bool changed = false}) {
+ field = _machineOrigin.field;
+ _agentPreview = _machineOrigin.agentPreview;
+ // A path filter belongs to its machine; a task, name, or URL can travel.
+ query =
+ changed &&
+ (field == NewHarnessField.project ||
+ field == NewHarnessField.projectMenu)
+ ? ''
+ : _machineOrigin.query;
+ _cycle = null;
+ error = null;
+ _refresh(resetCursor: true, agentSelection: _agentPreview);
+ }
+
+ /// Escape closes a nested machine chooser before it closes the agent draft.
+ bool backToProject() {
+ if (locked ||
+ (field != NewHarnessField.machine &&
+ field != NewHarnessField.project &&
+ field != NewHarnessField.projectName &&
+ field != NewHarnessField.projectRepository)) {
+ return false;
+ }
+ _returnToProject();
+ return true;
+ }
+
+ /// Escape leaves the focused prompt before dismissing the launch command.
+ /// Uncommitted filters are discarded; the task and accepted arguments stay.
+ bool back() {
+ if (locked) return false;
+ if (field == NewHarnessField.machine) {
+ _returnFromMachine();
+ return true;
+ }
+ if (field == NewHarnessField.mode || field == NewHarnessField.profile) {
+ _returnFromAgentSettings();
+ return true;
+ }
+ if (endCompletion() || backToProject()) return true;
+ if (field == NewHarnessField.launch) return false;
+ focusField(NewHarnessField.launch);
+ return true;
+ }
+
+ static String _short(String text) {
+ final one = text.trim().replaceAll(RegExp(r'\s+'), ' ');
+ return one.length <= 40 ? one : '${one.substring(0, 39)}…';
+ }
+
+ /// Tab is walking a completion menu: the stem that was typed, and the
+ /// candidate the line currently holds. Typing anything ends it.
+ ({String typedParent, String stem, String name})? _cycle;
+
+ /// Tab completes the current argument without accepting it or changing
+ /// prompts. Paths retain common-prefix expansion and reversible cycling.
+ String? complete([int step = 1]) {
+ if (locked) return null;
+ if (!isPathQuery) {
+ if (field == NewHarnessField.task ||
+ field == NewHarnessField.launch ||
+ field == NewHarnessField.projectName ||
+ field == NewHarnessField.projectRepository) {
+ return null;
+ }
+ final option = selected;
+ if (option != null && !option.synthetic) {
+ setQuery(option.title);
+ _steered = true;
+ }
+ return query;
+ }
+ final slash = query.lastIndexOf('/');
+ final typedParent =
+ _cycle?.typedParent ?? (slash < 0 ? '' : query.substring(0, slash + 1));
+ final stem =
+ _cycle?.stem ?? (slash < 0 ? query : query.substring(slash + 1));
+ // The folders under what was typed; "Use this folder" is not a candidate.
+ final names = [
+ for (final option in options)
+ if (!option.synthetic) option.title,
+ ];
+ if (names.isEmpty) return query;
+ if (_cycle case final cycle?) {
+ final at = names.indexOf(cycle.name);
+ final next = names[(at + step) % names.length];
+ return _showCandidate(typedParent, stem, next);
+ }
+ var common = names.first;
+ for (final name in names.skip(1)) {
+ var i = 0;
+ while (i < common.length &&
+ i < name.length &&
+ common[i].toLowerCase() == name[i].toLowerCase()) {
+ i++;
+ }
+ common = common.substring(0, i);
+ }
+ if (names.length == 1) {
+ final text = '$typedParent${names.single}/';
+ setQuery(text);
+ return text;
+ }
+ if (common.length > stem.length) {
+ final text = '$typedParent$common';
+ setQuery(text);
+ return text;
+ }
+ return _showCandidate(
+ typedParent,
+ stem,
+ step < 0 ? names.last : names.first,
+ );
+ }
+
+ String _showCandidate(String typedParent, String stem, String name) {
+ _cycle = (typedParent: typedParent, stem: stem, name: name);
+ query = '$typedParent$name';
+ error = null;
+ _refresh();
+ _steered = true;
+ return query;
+ }
+
+ // ---- the lists ----------------------------------------------------------
+
+ /// What of the app this box shows, and nothing else. The app notifies on
+ /// every turn heartbeat and every terminal byte; none of that is on this
+ /// screen, and rebuilding each list — and the panel with it — for each was
+ /// work done many times a second for nothing. Same idea as the search
+ /// catalog's presentation key.
+ List<Object?>? _seen;
+ List<Object?> _signature() {
+ final machine = _machine;
+ return [
+ for (final state in app.machineStates.values) ...[
+ state.machine.machineId,
+ state.machine.displayName,
+ state.machine.isShared,
+ state.isLocalMachine,
+ state.needsLink,
+ state.nodeOnline,
+ ],
+ machine?.engines.loaded,
+ for (final identity in allEngines)
+ machine?.engines[identity.id]?.installed,
+ machine?.engines['codex']?.supportsCodexHome,
+ machine?.dsh.loaded,
+ machine?.dsh.error,
+ for (final entry in machine?.dsh.entries ?? const <DshEntry>[]) ...[
+ entry.id,
+ entry.name,
+ entry.installed,
+ ],
+ ...app.agentPreference.recent,
+ null,
+ // Projects can arrive after the box opens, including metadata recovered
+ // by the local CLI. Terminal output alone must not reorder this list.
+ ..._recentProjectFolders(),
+ null,
+ for (final id in app.machineStates.keys) ...[
+ id,
+ ...app.projectHistory.recent(id),
+ null,
+ ],
+ ];
+ }
+
+ Timer? _appTick;
+ void _onApp() {
+ if (_disposed || _appTick != null) return;
+ // Coalesced: the app notifies on every terminal byte batch, and building
+ // even a small signature for each is work nobody sees. Ten looks a second
+ // is more often than any of this changes.
+ _appTick = Timer(const Duration(milliseconds: 100), () {
+ _appTick = null;
+ if (_disposed) return;
+ if (listEquals(_seen, _signature())) return;
+ _refresh();
+ });
+ }
+
+ void _refresh({bool resetCursor = false, String? agentSelection}) {
+ if (_disposed) return;
+ _seen = _signature();
+ final current = resetCursor ? null : selected?.id;
+ // An agent picked from another field may have no task or no modes.
+ if (!_supportsField(field)) {
+ field = fields.first;
+ query = field == NewHarnessField.task ? task : '';
+ }
+ if (field == NewHarnessField.agent) {
+ _refreshAgents(agentSelection ?? current, resetCursor: resetCursor);
+ return;
+ }
+ options = switch (field) {
+ NewHarnessField.launch ||
+ NewHarnessField.task ||
+ NewHarnessField.agent => const [],
+ NewHarnessField.machine => _machineOptions(),
+ NewHarnessField.projectMenu => _projectMenu(),
+ NewHarnessField.project ||
+ NewHarnessField.projectName => _projectOptions(),
+ NewHarnessField.projectRepository => _repositoryOptions(),
+ NewHarnessField.mode => _ranked([
+ for (final mode in _settingsModes)
+ NewHarnessOption(
+ id: mode.id,
+ title: mode.label,
+ detail: mode.detail,
+ risky: mode.risky,
+ ),
+ ]),
+ NewHarnessField.profile => _profileOptions(),
+ };
+ // A path list is capped; its count is of every match, not of the rows.
+ matchCount =
+ _pathMatched ?? options.where((option) => !option.synthetic).length;
+ _pathMatched = null;
+ final kept = current == null
+ ? -1
+ : options.indexWhere((option) => option.id == current);
+ final now = options.indexWhere(_isCurrent);
+ final pathChoice = isPathQuery
+ ? options.indexWhere((option) => option.project?.folder != null)
+ : -1;
+ final cycling = _cycle == null
+ ? -1
+ : options.indexWhere(
+ (option) => !option.synthetic && option.title == _cycle!.name,
+ );
+ cursor = cycling >= 0
+ ? cycling
+ : kept >= 0
+ ? kept
+ : field == NewHarnessField.projectMenu
+ ? (options.length > 3 ? 3 : 1)
+ : query.isEmpty && now >= 0
+ ? now
+ : field == NewHarnessField.profile
+ ? options.indexWhere((row) => !row.synthetic).clamp(0, options.length)
+ : pathChoice >= 0
+ ? pathChoice
+ : 0;
+ // A row we put the highlight on is not one the person chose.
+ if (resetCursor || (cycling < 0 && kept < 0)) _steered = false;
+ notifyListeners();
+ if (field == NewHarnessField.profile &&
+ supportsProfiles &&
+ _profilesMachine != _machineId) {
+ unawaited(refreshProfiles());
+ }
+ }
+
+ /// A page of the list, for PgUp/PgDn: [rows] is how many fit on screen.
+ void page(int direction, int rows) {
+ if (options.isEmpty || locked) return;
+ _endCycle();
+ cursor = (cursor + direction * rows.clamp(1, options.length)).clamp(
+ 0,
+ options.length - 1,
+ );
+ _steered = true;
+ if (field == NewHarnessField.agent) {
+ _refresh();
+ return;
+ }
+ notifyListeners();
+ }
+
+ void _refreshAgents(String? current, {required bool resetCursor}) {
+ final agents = _agentOptions();
+ final target =
+ agents.where((row) => row.id == current).firstOrNull ??
+ (query.isEmpty
+ ? agents.where((row) => row.id == _engine).firstOrNull
+ : null) ??
+ agents.firstOrNull;
+ _agentPreview = target?.id;
+ options = [...agents, if (offersStore) _store];
+ matchCount = agents.length;
+ final kept = options.indexWhere((row) => row.id == current);
+ cursor = kept >= 0
+ ? kept
+ : target == null
+ ? (options.isEmpty ? -1 : 0)
+ : options.indexWhere(
+ (row) => row.engine == _agentPreview && row.engine != null,
+ );
+ if (resetCursor || kept < 0) _steered = false;
+ notifyListeners();
+ }
+
+ List<NewHarnessOption> _ranked(List<NewHarnessOption> all) {
+ total = all.length;
+ String normalize(String text) {
+ final lower = text.toLowerCase();
+ if (field != NewHarnessField.project &&
+ field != NewHarnessField.projectMenu) {
+ return lower;
+ }
+ final normalized = lower.replaceAll(RegExp(r'[\s._-]+'), ' ').trim();
+ return normalized.isEmpty ? lower : normalized;
+ }
+
+ final needle = normalize(query.trim());
+ if (needle.isEmpty) return all;
+ final scored = <(int, int, NewHarnessOption)>[];
+ for (var i = 0; i < all.length; i++) {
+ final option = all[i];
+ final name = normalize(option.title);
+ final spread = subsequenceSpread(name, needle);
+ final detail = subsequenceSpread(normalize(option.detail), needle);
+ // The start of the name, then the start of a word in it, then anywhere
+ // in it, then scattered through it, then the description. `co` is
+ // Codex and Claude Code before it is MuJoCo.
+ final score = name.startsWith(needle)
+ ? 0
+ : name.split(RegExp(r'[\s/._-]+')).any((w) => w.startsWith(needle))
+ ? 100
+ : name.contains(needle)
+ ? 200
+ : spread != null
+ ? 300 + spread
+ // A description is long; two letters scattered through one match
+ // nearly everything. It counts from three letters on.
+ : detail == null || needle.length < 3
+ ? null
+ : 1000 + detail;
+ if (score != null) scored.add((score, i, option));
+ }
+ scored.sort((a, b) {
+ final by = a.$1.compareTo(b.$1);
+ return by != 0 ? by : a.$2.compareTo(b.$2);
+ });
+ return [for (final entry in scored) entry.$3];
+ }
+
+ List<NewHarnessOption> _agentOptions() {
+ final machine = _machine;
+ final harnesses = machine != null && machine.dsh.loaded
+ ? [
+ for (final entry in machine.dsh.entries)
+ if (!entry.isViewerPackage) entry.id,
+ ]
+ : [for (final identity in knownHarnesses) identity.id];
+ final ids = <String>{
+ // Keep the inherited choice beside the prompt, followed by recent choices.
+ _engine,
+ ...app.agentPreference.recent.where(_known),
+ for (final identity in allEngines) identity.id,
+ ...harnesses,
+ kTerminalEngine,
+ };
+ return _ranked([
+ for (final id in ids)
+ NewHarnessOption(
+ id: id,
+ title: labelOf(id),
+ engine: id,
+ detail: [
+ if (isTerminalEngine(id))
+ 'A shell, no agent'
+ else if (isHarnessId(id))
+ machine?.dsh[id]?.tagline ??
+ engineIdentity(id).tagline ??
+ machine?.dsh[id]?.category ??
+ engineIdentity(id).category
+ // Every plain engine is "Code"; a column saying so eight times is
+ // noise. Only what sets a row apart is said.
+ else
+ null,
+ if (isHarnessId(id) && machine?.dsh[id]?.installed == false)
+ 'installs first',
+ ].whereType<String>().where((part) => part.isNotEmpty).join(' · '),
+ ),
+ ]);
+ }
+
+ List<NewHarnessOption> _machineOptions() => _ranked([
+ for (final machine in app.machineStates.values)
+ if (!machine.machine.isShared)
+ NewHarnessOption(
+ id: machine.machine.machineId,
+ title: machine.machine.displayName,
+ detail: [
+ machine.isLocalMachine ? 'This computer' : 'Remote',
+ if (machine.needsLink)
+ 'link required'
+ else if (machine.nodeOnline == false)
+ 'offline',
+ ].join(' · '),
+ enabled: !machine.needsLink && machine.nodeOnline != false,
+ why: machine.needsLink
+ ? '${machine.machine.displayName} is not linked to this '
+ 'computer yet. Link it from the Machines menu.'
+ : '${machine.machine.displayName} is offline.',
+ ),
+ ]);
+
+ /// Whether what is typed in the project field is a path being completed.
+ bool get isPathQuery => field == NewHarnessField.project && _isPath(query);
+
+ /// A notice in the box's bottom line that is not a failed create.
+ void warn(String message) {
+ error = message;
+ notifyListeners();
+ }
+
+ bool _isPath(String text) =>
+ text.startsWith('/') ||
+ text.startsWith('~') ||
+ text.startsWith('./') ||
+ text.startsWith('../') ||
+ text == '.' ||
+ text == '..';
+
+ String _expand(String text) {
+ final home = _homeOf(_machineId);
+ if (home != null) {
+ if (text == '~') return home;
+ // `~/` keeps its slash: joined with nothing it came back as the home
+ // folder itself, which then read as "the folder `me` under /home" — the
+ // list showed one row, your own home, and Tab completed to `~/me/`.
+ if (text == '~/') return '$home/';
+ if (text.startsWith('~/')) return p.join(home, text.substring(2));
+ }
+ // `./x` and `../x` are relative to the project the line already names —
+ // the box's only "here" — and to home when it names none.
+ if (text.startsWith('.')) {
+ final here = _project.folder ?? home;
+ if (here != null) {
+ final trailing = text.endsWith('/') ? '/' : '';
+ return '${p.normalize(p.join(here, text))}$trailing';
+ }
+ }
+ return text;
+ }
+
+ Iterable<String> _recentProjectFolders() sync* {
+ final machine = _machine;
+ final seen = <String>{};
+ for (final folder in [
+ ?_project.folder,
+ ...app.projectHistory.recent(_machineId),
+ // Match the full form: explicit choices first, then known agent folders
+ // on this machine. Older projects need not be picked again to appear.
+ if (machine != null)
+ for (final agent in machine.agents.reversed)
+ ?machine.projectOf(agent)?.cwd,
+ ]) {
+ if (!p.isAbsolute(folder) ||
+ folder.length > 4096 ||
+ RegExp(r'[\x00-\x1f\x7f]').hasMatch(folder)) {
+ continue;
+ }
+ if (seen.add(p.normalize(folder))) yield folder;
+ }
+ }
+
+ List<NewHarnessOption> _recentProjects() => [
+ for (final folder in _recentProjectFolders())
+ NewHarnessOption(
+ id: 'project:$_machineId:$folder',
+ title: p.basename(folder),
+ detail: location(folder),
+ project: NewHarnessProject.folder(folder),
+ machineId: _machineId,
+ enabled: _machine?.needsLink != true && _machine?.nodeOnline != false,
+ why: _machine?.needsLink == true
+ ? '$machineLabel needs linking. Open Machines to link it.'
+ : '$machineLabel is offline.',
+ ),
+ ];
+
+ List<NewHarnessOption> _projectOptions() {
+ final typed = query.trim();
+ if (field == NewHarnessField.project) {
+ if (_isPath(typed)) return _pathOptions(typed);
+ // Recent projects live in the project menu. This prompt only opens a
+ // folder by path or browser, so it cannot look like a second history.
+ total = 0;
+ return [_browse];
+ }
+ final slug = typed.contains('/') ? null : projectFolderSlug(typed);
+ final keepSuggestion = _editingSuggestedProject && typed == _project.name;
+ // Resolve the owning machine's home before offering an existing name.
+ // The daemon still reserves a fresh name atomically on submission.
+ final root = _expand('~/harnesses');
+ if (slug != null && p.isAbsolute(root) && !_listings.containsKey(root)) {
+ _requestListing(root);
+ }
+ final existingName = _listings[root]
+ ?.where((name) => name == slug)
+ .firstOrNull;
+ final existingFolder = existingName == null || keepSuggestion
+ ? null
+ : p.join(root, existingName);
+ return [
+ if (typed.isNotEmpty)
+ NewHarnessOption(
+ id: 'project:new',
+ synthetic: true,
+ title: slug == null
+ ? 'Enter a project name'
+ : '${existingFolder == null ? 'Create' : 'Open existing'} $slug',
+ detail: slug == null
+ ? 'Use letters or numbers, like payments'
+ : location('~/harnesses/$slug'),
+ project: existingFolder != null
+ ? NewHarnessProject.folder(existingFolder)
+ : keepSuggestion
+ ? _project
+ : slug == null
+ ? null
+ : NewHarnessProject.fresh(typed),
+ machineId: _machineId,
+ enabled: slug != null,
+ why: 'Use a project name with letters or numbers. Choose Existing for a folder path.',
+ ),
+ ];
+ }
+
+ List<NewHarnessOption> _repositoryOptions() {
+ final repository = GitHubRepository.parse(query.trim());
+ return [
+ if (repository != null)
+ NewHarnessOption(
+ id: 'project:clone',
+ synthetic: true,
+ title: 'Clone ${repository.name}',
+ detail: location('~/harnesses/${repository.name}'),
+ project: NewHarnessProject.clone(repository),
+ machineId: _machineId,
+ ),
+ ];
+ }
+
+ /// The most folders one listing offers. `node_modules` has five thousand; a
+ /// list nobody scrolls that far costs a row object each, every keystroke.
+ /// Typing narrows it, and the count still says how many there really are.
+ static const maxPathRows = 200;
+
+ /// The last path list built, and what it was built from: a keystroke that
+ /// changes neither the folder nor the stem (or a tick that changes nothing)
+ /// gets the same list back instead of thousands of new rows.
+ (String, String, List<String>)? _pathKey;
+ List<NewHarnessOption> _pathRows = const [];
+ int _pathTotal = 0;
+ int _pathHits = 0;
+ int? _pathMatched;
+
+ /// zsh's path completion: the folders under what has been typed so far.
+ List<NewHarnessOption> _pathOptions(String typed) {
+ final full = _expand(typed);
+ if (!p.isAbsolute(full)) {
+ total = 0;
+ return [_browse, _changeMachine];
+ }
+ final slash = full.lastIndexOf('/');
+ final parent = slash <= 0 ? '/' : full.substring(0, slash);
+ // While Tab is cycling the candidates, the line holds one of them but the
+ // list stays the list of the stem that was typed — a completion menu.
+ final stem = (_cycle?.stem ?? full.substring(slash + 1)).toLowerCase();
+ final names = _listings[parent];
+ if (names == null) {
+ _requestListing(parent);
+ total = 0;
+ return const [];
+ }
+ final key = (parent, stem, names);
+ if (_pathKey != null &&
+ _pathKey!.$1 == parent &&
+ _pathKey!.$2 == stem &&
+ identical(_pathKey!.$3, names)) {
+ total = _pathTotal;
+ _pathMatched = _pathHits;
+ return _pathRows;
+ }
+ // Dot-folders are offered only once a dot is typed, as `ls` hides them; the
+ // count is of what is on offer.
+ final dots = stem.startsWith('.');
+ var offered = 0;
+ final rows = <NewHarnessOption>[
+ _browse,
+ if (stem.isEmpty && parent != '/')
+ NewHarnessOption(
+ id: 'project:$parent',
+ title: p.basename(parent),
+ detail: 'Use ${location(parent)}',
+ project: NewHarnessProject.folder(parent),
+ synthetic: true,
+ ),
+ ];
+ var matched = 0;
+ for (final name in names) {
+ if (!dots && name.startsWith('.')) continue;
+ offered++;
+ if (!name.toLowerCase().startsWith(stem)) continue;
+ if (++matched > maxPathRows) continue;
+ final folder = p.join(parent, name);
+ rows.add(
+ NewHarnessOption(
+ id: 'project:$folder',
+ title: name,
+ detail: location(folder),
+ project: NewHarnessProject.folder(folder),
+ ),
+ );
+ }
+ rows.add(_changeMachine);
+ _pathKey = key;
+ _pathRows = rows;
+ total = _pathTotal = offered;
+ _pathMatched = _pathHits = matched;
+ return rows;
+ }
+
+ Timer? _listDebounce;
+ static const _maxListings = 16;
+
+ /// ~ always means the home of the selected machine's account. The browser
+ /// protocol resolves an omitted path to that home; no local path is guessed.
+ Future<String?> _ensureHome(String id) {
+ if (app.stateOf(id)?.isLocalMachine == true) return Future.value(_home);
+ return _homeRequests.putIfAbsent(id, () async {
+ try {
+ final answer = await app.listRemoteFolder(id, null);
+ final home = answer['path'];
+ if (_disposed || home is! String || !p.isAbsolute(home)) return null;
+ _homes[id] = home;
+ if (id == _machineId) _refresh();
+ return home;
+ } catch (_) {
+ // Display the full path until this machine can resolve its home.
+ return null;
+ }
+ });
+ }
+
+ /// Ask for [folder]'s listing. A local folder is read at once, off this
+ /// isolate; another machine's is asked for only once the typing pauses — each
+ /// keystroke through `~/code/au` would otherwise be a round trip whose answer
+ /// nobody is waiting for any more.
+ void _requestListing(String folder) {
+ if (_listing == folder) return;
+ _listing = folder;
+ _listDebounce?.cancel();
+ if (_machine?.isLocalMachine == true) {
+ unawaited(_list(folder));
+ } else {
+ _listDebounce = Timer(
+ const Duration(milliseconds: 80),
+ () => unawaited(_list(folder)),
+ );
+ }
+ }
+
+ Future<void> _list(String folder) async {
+ final machineId = _machineId;
+ final revision = _machineRevision;
+ var names = <String>[];
+ try {
+ if (_machine?.isLocalMachine == true) {
+ // Five thousand entries streamed through the UI isolate's event loop
+ // is five thousand events between two frames; read them elsewhere.
+ names = await Isolate.run(() {
+ final found = <String>[];
+ for (final entry in Directory(folder).listSync(followLinks: true)) {
+ if (entry is Directory) found.add(p.basename(entry.path));
+ }
+ return found;
+ });
+ } else {
+ final answer = await app.listRemoteFolder(_machineId, folder);
+ final entries = answer['entries'];
+ if (entries is List) {
+ names = [
+ for (final entry in entries)
+ if (entry is Map &&
+ entry['isDir'] == true &&
+ entry['name'] is String)
+ entry['name'] as String,
+ ];
+ }
+ }
+ } catch (_) {
+ // A folder that cannot be read lists nothing, as a shell's Tab does.
+ }
+ if (_disposed || machineId != _machineId || revision != _machineRevision) {
+ return;
+ }
+ names.sort((a, b) => compareNatural(a.toLowerCase(), b.toLowerCase()));
+ _listings.remove(folder);
+ _listings[folder] = names;
+ // Recently listed folders stay; a long walk does not keep every one.
+ while (_listings.length > _maxListings) {
+ _listings.remove(_listings.keys.first);
+ }
+ // An answer for a folder the line has already left is kept, not shown.
+ final current = _listing == folder;
+ if (current) _listing = null;
+ if (current &&
+ (field == NewHarnessField.project ||
+ field == NewHarnessField.projectName)) {
+ _refresh();
+ }
+ }
+
+ // ---- making it ----------------------------------------------------------
+
+ /// One attempt per harness, kept across a lost reply: a create whose answer
+ /// never came back may have worked, and asking again must ask the machine
+ /// what happened to THAT request rather than start a second harness.
+ AgentCreationAttempt? _attempt;
+
+ /// The person has been told a typed task will not be sent, and pressed again.
+ bool _dropAccepted = false;
+
+ /// A reply was lost; Return now checks on it instead of creating again.
+ bool get checking => _attempt?.awaitingConfirmation == true;
+
+ bool _warnedAboutClosing = false;
+
+ /// Every dismissal path observes the same in-flight receipt and completion.
+ /// A second explicit dismissal acknowledges an unresolved creation.
+ bool requestDismiss() {
+ if (linkingProfile) {
+ warn('Linking the profile. Escape closes once it is done.');
+ return false;
+ }
+ if (busy) {
+ warn('Still working on it. Escape closes once it is done.');
+ return false;
+ }
+ if (checking && !_warnedAboutClosing) {
+ _warnedAboutClosing = true;
+ warn(
+ 'The harness may already exist. Return checks on it; Escape again '
+ 'closes without knowing.',
+ );
+ return false;
+ }
+ return !endCompletion();
+ }
+
+ Future<NewHarnessOutcome> create() async {
+ if (busy || linkingProfile || detectingAgent) {
+ return NewHarnessOutcome.failed;
+ }
+ if (needsProject && !checking) {
+ focusField(NewHarnessField.projectMenu);
+ return _fail('Choose a project, or create a new one.');
+ }
+ // Shortened by the person, never cut by us: a machine refuses one longer.
+ if (takesTask && taskTooLong && !checking) {
+ return _fail(
+ 'A first message can be $kFirstTaskMaxLength characters; '
+ 'this is ${task.trim().length}.',
+ );
+ }
+ // A task typed for an agent that cannot take one is said BEFORE the
+ // harness is made, on every path — ⌘↵ from the agent field went straight
+ // past the notice that choosing the agent shows. The second press means it.
+ if (!takesTask && task.trim().isNotEmpty && !checking && !_dropAccepted) {
+ _dropAccepted = true;
+ return _fail(
+ '$agentLabel cannot start on a first message, so “${_short(task)}” '
+ 'will not be sent. Press again to make it anyway.',
+ );
+ }
+ final machine = _machine;
+ if (machine == null) {
+ error = 'Choose a machine.';
+ notifyListeners();
+ return NewHarnessOutcome.failed;
+ }
+ final choice = _engine;
+ final harness = isHarnessId(choice) ? choice : null;
+ final terminal = isTerminalEngine(choice);
+ final base = harness == null
+ ? choice
+ : machine.dsh[choice]?.engine ?? knownHarnessBase[choice] ?? 'claude';
+ // The daemon's launch installs a missing engine inside its new terminal.
+ // A cached availability probe must not block that first launch.
+ final recheck = checking;
+ if (!recheck) {
+ _attempt = AgentCreationAttempt();
+ _warnedAboutClosing = false;
+ }
+ final attempt = _attempt!;
+ busy = true;
+ error = null;
+ status = recheck ? 'Checking on the harness…' : 'Starting harness…';
+ notifyListeners();
+ if (harness != null && !recheck) {
+ await app.probeDsh(_machineId, force: true);
+ if (_disposed) return NewHarnessOutcome.failed;
+ if (!machine.dsh.loaded && machine.dsh.error != null) {
+ return _fail(
+ 'Update Harness CLI on ${machine.machine.displayName} to create a '
+ '${labelOf(harness)} harness.',
+ );
+ }
+ if (machine.dsh[harness]?.installed == false) {
+ status = 'Installing ${labelOf(harness)}… this can take a few minutes';
+ notifyListeners();
+ final failure = await app.installDsh(_machineId, harness);
+ if (_disposed) return NewHarnessOutcome.failed;
+ if (failure != null) return _fail(failure);
+ status = 'Starting harness…';
+ notifyListeners();
+ }
+ }
+ final permissionMode = hasModes ? mode : null;
+ final bypass =
+ permissionMode != null && permissionModeApproves(permissionMode);
+ final folder = _project.folder;
+ final firstMessage = task.trim();
+ final failure = await app.createAgent(
+ _machineId,
+ engine: base,
+ folder: terminal ? folder : folder ?? '',
+ projectFolder: projectFolderRequest,
+ swarmId: swarmId,
+ split: split,
+ placement: placement,
+ bypassPermission: bypass,
+ permissionMode: permissionMode,
+ codexHome: base == 'codex' ? _profile?.path : null,
+ dsh: harness,
+ // Sent exactly as written; an agent that cannot take one is never sent it.
+ prompt: takesTask && firstMessage.isNotEmpty ? firstMessage : null,
+ attempt: attempt,
+ );
+ if (_disposed) return NewHarnessOutcome.failed;
+ if (failure != null) {
+ // A folder already made for this attempt is the project now: a retry
+ // goes into it rather than making a second one beside it.
+ if (!checking && attempt.preparedFolder != null) {
+ _project = NewHarnessProject.folder(attempt.preparedFolder!);
+ }
+ return _fail(failure);
+ }
+ analytics.agentCreated(
+ engine: choice,
+ bypassPermission: bypass,
+ permissionMode: permissionMode,
+ );
+ unawaited(app.agentPreference.remember(choice));
+ busy = false;
+ status = null;
+ return NewHarnessOutcome.created;
+ }
+
+ NewHarnessOutcome _fail(String message) {
+ busy = false;
+ status = null;
+ error = message;
+ notifyListeners();
+ return NewHarnessOutcome.failed;
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _appTick?.cancel();
+ _listDebounce?.cancel();
+ app.removeListener(_onApp);
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dart
index dc799bbb3..2fe6706e5 100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@ -1,5 +1,6 @@
import 'dart:ui' show Size;
+import '../core/models.dart' show isAutomaticHarnessName;
import 'pane_preset.dart';
import 'pane_arrangement.dart';
import 'terminal_pane.dart';
@@ -8,8 +9,13 @@ import 'terminal_pane.dart';
/// Shared agents reuse the same pane/session across swarms, so the daemon has
/// exactly one controller and switching tabs cannot take over our own stream.
class Swarm {
- Swarm({required this.id, String name = defaultName, this.kind = 'harness'})
- : name = normalizeName(name);
+ Swarm({
+ required this.id,
+ String name = defaultName,
+ this.kind = 'harness',
+ bool? nameIsCustom,
+ }) : name = nameIsCustom == true ? name : normalizeName(name),
+ nameIsCustom = nameIsCustom ?? (normalizeName(name) != defaultName);
/// What the tab holds: `harness` — panes of agents (the default); `store` —
/// the Harness Store, no panes. A store tab is a tab like any other —
@@ -25,23 +31,26 @@ class Swarm {
String? orchestratorId, orchestratorMachineId;
static const storeName = 'Harness Store';
- static const defaultName = 'New Tab';
+ static const defaultName = 'Untitled Tab';
// 'New Harness' was the default until 2026-09-15 and 'New Agent' for a day
// after; a layout saved then still carries one, and it must read as the same
// fresh tab.
static String normalizeName(String name) =>
const {
- 'New swarm',
- 'New tab',
- 'New Tab',
- 'New Harness',
- 'New Agent',
- }.contains(name)
+ 'New swarm',
+ 'New tab',
+ 'New Tab',
+ 'New Harness',
+ 'New Agent',
+ }.contains(name) ||
+ isAutomaticHarnessName(name)
? defaultName
: name;
final String id;
String name;
+ bool nameIsCustom;
+ String? titleMachineId, titleAgentId;
final List<TerminalPane> panes = [];
final Map<int, PanePreset> presets = {};
final Map<String, PaneArrangement> paneSizes = {};
@@ -108,6 +117,9 @@ class Swarm {
return {
'id': id,
'name': name,
+ if (nameIsCustom) 'nameIsCustom': true,
+ if (titleMachineId != null) 'titleMachineId': titleMachineId,
+ if (titleAgentId != null) 'titleAgentId': titleAgentId,
if (kind != 'harness') 'kind': kind,
if (isOrchestrator) 'orchestratorId': orchestratorId,
if (isOrchestrator) 'orchestratorMachineId': orchestratorMachineId,
@@ -180,6 +192,9 @@ class ClosedSwarm extends ClosedWork {
this.engine,
}) : id = swarm.id,
name = swarm.name,
+ nameIsCustom = swarm.nameIsCustom,
+ titleMachineId = swarm.titleMachineId,
+ titleAgentId = swarm.titleAgentId,
kind = swarm.kind,
orchestratorId = swarm.orchestratorId,
orchestratorMachineId = swarm.orchestratorMachineId,
@@ -204,6 +219,8 @@ class ClosedSwarm extends ClosedWork {
final String id;
final String name;
+ final bool nameIsCustom;
+ final String? titleMachineId, titleAgentId;
/// So a closed store tab reopens as the store, not as an empty harness tab.
final String kind;
diff --git a/desktop/lib/state/swarm_catalog.dart b/desktop/lib/state/swarm_catalog.dart
index 694562a08..435c2f085 100644
--- a/desktop/lib/state/swarm_catalog.dart
+++ b/desktop/lib/state/swarm_catalog.dart
@@ -1,5 +1,6 @@
import 'dart:convert';
+import 'package:collection/collection.dart' show compareNatural;
import 'package:flutter/foundation.dart';
import '../core/local_key_value_store.dart';
@@ -13,7 +14,7 @@ class SwarmAgentRef {
String get machineId => machine.machine.machineId;
AgentProject? get project => machine.projectOf(agent);
String get searchText => [
- agent.name,
+ agent.displayName,
agent.engine,
machine.machine.displayName,
project?.name,
@@ -118,8 +119,9 @@ List<SwarmProjectGroup> swarmProjects(
}
}
}
- return groups.values.toList()
- ..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase()));
+ return groups.values.toList()..sort(
+ (a, b) => compareNatural(a.name.toLowerCase(), b.name.toLowerCase()),
+ );
}
class SwarmProjectStore extends ChangeNotifier {
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index 7e3c415a0..1fe61c063 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -1,9 +1,17 @@
+import '../shared/theme/prompt_style.dart';
+
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:collection/collection.dart' show compareNatural;
import 'package:flutter/foundation.dart' show listEquals, setEquals;
import '../core/fuzzy_match.dart';
+import '../core/local_key_value_store.dart';
import '../core/models.dart';
import '../widgets/engine_identity.dart';
import 'app_state.dart';
+import 'harness_placement.dart';
import 'pane_arrangement.dart';
import 'session_preview.dart';
import 'swarm.dart';
@@ -19,6 +27,85 @@ String agentLocationId(String swarmId, int paneId) =>
/// Session-local history contains identities only, never terminal buffers or
/// controllers. Repeated discovery/output notifications do not reorder it.
class SwarmNavigationHistory {
+ SwarmNavigationHistory({this.storage});
+
+ /// Where the recently used harnesses are kept between launches, or null to
+ /// keep them for this session only (tests).
+ ///
+ /// A quick-open earns its keep in the first three rows, before anything is
+ /// typed. Session-only memory meant every launch opened the box on an
+ /// alphabetical list: the harness from an hour ago was no nearer than one
+ /// from last month. Only harnesses are kept — their ids outlive a restart,
+ /// and a tab's does not have to.
+ final LocalKeyValueStore? storage;
+ static const _storageKey = 'swarm_recent_v1';
+ static const _commandsKey = 'swarm_recent_commands_v1';
+
+ /// The commands run from the palette, most recent first. A palette that
+ /// opens A–Z makes you type three letters for the command you ran a minute
+ /// ago; an editor's opens on it.
+ final _commands = <String>[];
+ List<String> get recentCommands => List.unmodifiable(_commands);
+ void rememberCommand(String id) {
+ _commands.remove(id);
+ _commands.insert(0, id);
+ if (_commands.length > _kept) _commands.removeLast();
+ _save();
+ }
+
+ static const _kept = 32;
+ Timer? _saving;
+ bool _disposed = false;
+
+ /// Fold what the last session remembered in BEHIND what this one has already
+ /// visited: a load that lands late must not reorder the present.
+ Future<void> load() async {
+ try {
+ final raw = await storage?.read(_storageKey);
+ if (raw == null || _disposed) return;
+ final ids = jsonDecode(raw);
+ if (ids is! List) return;
+ for (final id in ids.take(_kept)) {
+ if (id is String && id.startsWith('agent:') && !_recent.contains(id)) {
+ _recent.add(id);
+ }
+ }
+ _revision++;
+ final commands = await storage?.read(_commandsKey);
+ final ran = commands == null ? null : jsonDecode(commands);
+ if (ran is List && !_disposed) {
+ for (final id in ran.take(_kept)) {
+ if (id is String && !_commands.contains(id)) _commands.add(id);
+ }
+ }
+ } catch (_) {
+ // A damaged list is an empty one; the next visit writes a good one.
+ }
+ }
+
+ void _save() {
+ if (storage == null || _disposed) return;
+ // Focus moves in bursts; one write after it settles is enough.
+ _saving?.cancel();
+ _saving = Timer(const Duration(milliseconds: 600), () {
+ final ids = [
+ for (final id in _recent)
+ if (id.startsWith('agent:')) id,
+ ].take(_kept).toList();
+ unawaited(
+ storage!.write(_storageKey, jsonEncode(ids)).catchError((_) {}),
+ );
+ unawaited(
+ storage!.write(_commandsKey, jsonEncode(_commands)).catchError((_) {}),
+ );
+ });
+ }
+
+ void dispose() {
+ _disposed = true;
+ _saving?.cancel();
+ }
+
static const capacity = 64;
final _recent = <String>[];
final _recentLocations = <String>[];
@@ -100,6 +187,7 @@ class SwarmNavigationHistory {
_recent.remove(id);
_recent.insert(0, id);
if (_recent.length > capacity) _recent.removeLast();
+ _save();
}
/// Native menus are ready before opening. Ordinary terminal output reuses
@@ -158,6 +246,8 @@ class SwarmDestination {
required this.title,
required this.detail,
this.detailBranchOffset,
+ this.terminalDetail,
+ this.promptContext,
required this.swarmId,
required this.current,
this.machineId,
@@ -166,6 +256,7 @@ class SwarmDestination {
this.engine,
this.closedId,
this.commandId,
+ this.pickerQuery,
this.shortcut,
this.paneId,
this.swarmName = '',
@@ -173,6 +264,8 @@ class SwarmDestination {
this.previewKey,
this.members = const {},
this.isStore = false,
+ this.isCreate = false,
+ this.task,
Iterable<String?> searchFields = const [],
int titleFields = 1,
}) : fields = [
@@ -190,10 +283,19 @@ class SwarmDestination {
/// The branch's start in the readable metadata, for its decorative glyph.
final int? detailBranchOffset;
+
+ /// Plain-text identity for results without a provider mark. Put the agent
+ /// and machine before paths and branches, which are more likely to truncate.
+ final String? terminalDetail;
+ final PromptContext? promptContext;
final String? swarmId, machineId, agentId, engine;
final String? closedId;
final String? commandId, shortcut;
+ /// A Quick Access help row changes the query in place, keeping the picker,
+ /// its destination tab, and keyboard focus rather than running a command.
+ final String? pickerQuery;
+
/// An exact navigation location. Never fall back to a different swarm.
final int? paneId;
final String swarmName;
@@ -205,29 +307,49 @@ class SwarmDestination {
/// The Harness Store's tab, open or recently closed. It holds no agents, so
/// without this it would be drawn as an empty group; it wears the app icon.
final bool isStore;
+
+ /// The box's last row: make what was typed instead of finding it, the way a
+ /// browser's address bar offers to search for what is not a page.
+ final bool isCreate;
+
+ /// What the create row would start the new harness on: what was typed.
+ final String? task;
final bool current;
final List<String> fields;
bool get isProject => projectId != null;
bool get isMachine => agentId == null && machineId != null && !isProject;
bool get isGroup => isProject || isMachine;
- bool get isSwarm => agentId == null && !isGroup && !isCommand;
+ bool get isSwarm =>
+ agentId == null &&
+ !isGroup &&
+ !isCommand &&
+ !isCreate &&
+ pickerQuery == null;
bool get hasView => swarmId != null;
}
enum SwarmSearchAction { open, addHere }
-({String text, int? branchOffset}) _harnessDetail(
+({String text, String terminalText, int? branchOffset}) _harnessDetail(
String? type,
AgentProject? project,
String machine,
- bool offline,
-) {
+ bool offline, {
+ required String agentLabel,
+}) {
final prefix = [
type,
project?.name,
].whereType<String>().where((part) => part.isNotEmpty).join(' · ');
final branch = project?.branch;
return (
+ terminalText: [
+ agentLabel,
+ machine,
+ if (offline) 'Offline',
+ project?.name,
+ branch,
+ ].whereType<String>().where((part) => part.isNotEmpty).join(' · '),
text: [
prefix,
branch,
@@ -244,6 +366,12 @@ String? _harnessType(MachineState? machine, String? engine) =>
(engine == null ? null : machine?.dsh[engine]?.category) ??
engineIdentity(engine).category;
+String _harnessLabel(MachineState? machine, String? engine, String? name) =>
+ engineIdentity(
+ engine,
+ displayName: (engine == null ? null : machine?.dsh[engine]?.name) ?? name,
+ ).label;
+
class SwarmSearchSelection {
const SwarmSearchSelection(
this.destination, [
@@ -452,17 +580,27 @@ class SwarmLocationCatalog {
final project = agent == null ? null : machine?.projectOf(agent);
final machineLabel = machine?.machine.displayName ?? pane.machineId;
final engine = agent?.identityEngine ?? pane.session?.engineId;
+ final label = _harnessLabel(machine, engine, agent?.identityDisplayName);
final detail = _harnessDetail(
_harnessType(machine, engine),
project,
machineLabel,
machine?.nodeOnline == false,
+ agentLabel: label,
);
return SwarmDestination(
id: agentLocationId(swarm.id, pane.id),
- title: agent?.name ?? pane.session?.agentName ?? pane.agentId!,
+ title: agent?.displayName ?? pane.session?.agentName ?? pane.agentId!,
detail: detail.text,
detailBranchOffset: detail.branchOffset,
+ terminalDetail: detail.terminalText,
+ promptContext: PromptContext(
+ harness: label,
+ machine: machineLabel,
+ project: project?.name,
+ branch: project?.branch,
+ leading: machine?.nodeOnline == false ? 'Offline' : null,
+ ),
swarmId: swarm.id,
swarmName: swarm.name,
paneId: pane.id,
@@ -474,7 +612,14 @@ class SwarmLocationCatalog {
current: swarm.id == app.activeSwarmId && pane.id == app.focusedPaneId,
// The agent's own title first, ranked like the name: "board fab check"
// finds the agent whose work that is, not whichever recap mentions fab.
- searchFields: [agent?.title, detail.text, project?.cwd, engine, swarm.name],
+ searchFields: [
+ agent?.title,
+ detail.text,
+ project?.cwd,
+ engine,
+ label,
+ swarm.name,
+ ],
titleFields: agent?.title == null ? 1 : 2,
);
}
@@ -516,8 +661,57 @@ Future<bool> activateSwarmSearchSelection(
required String destinationSwarmId,
List<SavedSwarmProject> projects = const [],
PaneSplitRequest? split,
+ HarnessPlacement? placement,
}) async {
final destination = selection.destination;
+ if (placement != null) {
+ final machineId = destination.machineId;
+ final agentId = destination.agentId;
+ if (machineId == null || agentId == null || destination.isCommand) {
+ return false;
+ }
+ final agent = app
+ .stateOf(machineId)
+ ?.agents
+ .where((agent) => agent.id == agentId)
+ .firstOrNull;
+ final hasView = app.allPanes.any(
+ (pane) => pane.machineId == machineId && pane.agentId == agentId,
+ );
+ if (agent == null || (!agent.terminalAvailable && !hasView)) return false;
+ var target = app.swarms
+ .where((tab) => tab.id == destinationSwarmId)
+ .firstOrNull;
+ if (placement == HarnessPlacement.currentTab) {
+ if (target == null || target.isStore || target.isOrchestrator) {
+ return false;
+ }
+ final existing = target.panes.any(
+ (pane) => pane.machineId == machineId && pane.agentId == agentId,
+ );
+ if (!existing && target.panes.length >= AppNotifier.maxPanes) {
+ return false;
+ }
+ } else {
+ // Validation precedes allocation, and allocation precedes the first
+ // network wait. A stale row cannot leave an empty tab behind.
+ app.newSwarm();
+ target = app.activeSwarm;
+ }
+ await app.assignAgentToPane(
+ null,
+ machineId,
+ agentId,
+ swarmId: target.id,
+ autoTile: true,
+ );
+ if (app.activeSwarmId == target.id) {
+ app.revealAgentView(machineId, agentId, preferredSwarmId: target.id);
+ }
+ return target.panes.any(
+ (pane) => pane.machineId == machineId && pane.agentId == agentId,
+ );
+ }
if (selection.agents.isNotEmpty) {
final target = app.swarms
.where((swarm) => swarm.id == destinationSwarmId)
@@ -846,6 +1040,9 @@ List<SwarmDestination> swarmDestinations(
: null,
machineLabel: _swarmMachineLabel(app, machines),
detail: [
+ // Project and machine rows name their kind; a tab beside them
+ // without one read as some fourth, unnamed thing.
+ if (!swarm.isStore) 'Tab',
_countLabel(members.length, 'harness'),
if (projects.isNotEmpty) _countLabel(projects.length, 'project'),
if (machines.isNotEmpty) _countLabel(machines.length, 'machine'),
@@ -890,11 +1087,13 @@ List<SwarmDestination> swarmDestinations(
final machineName = machine?.machine.displayName ?? machineId;
final engine = row?.$2.identityEngine ?? pane?.session?.engineId;
final type = _harnessType(machine, engine);
+ final label = _harnessLabel(machine, engine, row?.$2.identityDisplayName);
final detail = _harnessDetail(
type,
project,
machineName,
machine?.nodeOnline == false,
+ agentLabel: label,
);
result.add(
SwarmDestination(
@@ -902,6 +1101,14 @@ List<SwarmDestination> swarmDestinations(
title: row?.$2.name ?? pane?.session?.agentName ?? agentId,
detail: detail.text,
detailBranchOffset: detail.branchOffset,
+ terminalDetail: detail.terminalText,
+ promptContext: PromptContext(
+ harness: label,
+ machine: machineName,
+ project: project?.name,
+ branch: project?.branch,
+ leading: machine?.nodeOnline == false ? 'Offline' : null,
+ ),
swarmId: owner?.id,
machineId: machineId,
machineLabel: machineName,
@@ -921,6 +1128,7 @@ List<SwarmDestination> swarmDestinations(
project?.branch,
project?.cwd,
engine,
+ label,
...memberships.map((s) => s.name),
],
titleFields: row?.$2.title == null ? 1 : 2,
@@ -1028,7 +1236,7 @@ List<SwarmDestination> rankSwarmDestinations(
);
}
if (order == 0) {
- order = a.entry.fields.first.compareTo(b.entry.fields.first);
+ order = compareNatural(a.entry.fields.first, b.entry.fields.first);
}
return order == 0 ? a.entry.id.compareTo(b.entry.id) : order;
});
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 62a520054..1fc1a8169 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -1,10 +1,19 @@
import 'package:flutter/foundation.dart';
import 'app_state.dart';
+import 'harness_placement.dart';
import 'pane_arrangement.dart';
import 'swarm_catalog.dart';
import 'swarm_navigation.dart';
+/// What the box finds, said in the box: it searches four kinds of thing, and
+/// "Find a harness" named one of them.
+const kSwarmSearchHint =
+ 'Search agents > commands # projects @ machines ? help';
+const kHarnessPickerHint = 'Find a harness…';
+
+const kSwarmCreateRowId = 'create:harness';
+
/// Search text and selection retained while the start-page picker is dismissed.
/// Membership and availability are revalidated against a fresh catalog on return.
class SwarmSearchDraft {
@@ -22,13 +31,20 @@ class SwarmSearchController extends ChangeNotifier {
this.projects,
this.history,
this.commands,
+ this.recentCommands,
+ this.modes,
this.adding = false,
this.navigating = false,
this.commandsOnly = false,
- this.split,
+ this.offersCreate = false,
+ this.resultsFromBottom = false,
+ this._placement,
+ this._split,
+ bool previewInitiallyVisible = true,
SwarmSearchCatalog? catalog,
SwarmLocationCatalog? locations,
- }) : _cache = catalog ?? SwarmSearchCatalog(),
+ }) : _previewVisible = previewInitiallyVisible,
+ _cache = catalog ?? SwarmSearchCatalog(),
_locations = locations ?? SwarmLocationCatalog(),
targetId = app.activeSwarmId,
targetName = app.activeSwarm.name {
@@ -46,20 +62,113 @@ class SwarmSearchController extends ChangeNotifier {
/// Availability is read from workspace state and rechecked at activation.
/// Commands never enter the ordinary agent/swarm catalog or History.
final List<SwarmDestination> Function()? commands;
+
+ /// Command ids run lately, most recent first: with nothing typed the
+ /// palette opens on these, in this order, ahead of the rest.
+ final List<String> Function()? recentCommands;
+
+ /// The rows `?` lists: the box's other modes, as commands with their keys.
+ final List<SwarmDestination> Function()? modes;
final bool adding;
final bool navigating;
final bool commandsOnly;
- final PaneSplitRequest? split;
- bool get allowsCommands => split == null && history == null;
+
+ /// Whether the list ends in a row that makes a harness instead of finding
+ /// one. What was typed becomes the new harness's first task.
+ final bool offersCreate;
+
+ /// Docked pickers keep their best match next to the input at the bottom.
+ /// Catalog ranking stays unchanged; rendering and spatial movement invert.
+ final bool resultsFromBottom;
+ HarnessPlacement? _placement;
+ HarnessPlacement? get placement => _placement;
+ PaneSplitRequest? _split;
+ PaneSplitRequest? get split => _split;
+ bool get allowsCommands => history == null && !navigating;
bool get isCommandMode =>
allowsCommands && (commandsOnly || query.trimLeft().startsWith('>'));
- bool get hasPreview => !isCommandMode && history == null && selected != null;
+
+ /// `?` — what this one box can do, each with the key that goes there
+ /// directly. An editor's quick-open answers `?` the same way: five shortcuts
+ /// that open five things read as five features, and they are one.
+ bool get isHelpMode =>
+ modes != null &&
+ allowsCommands &&
+ !commandsOnly &&
+ !navigating &&
+ query.trimLeft().startsWith('?');
+ String get helpQuery => query.trimLeft().replaceFirst(_helpPrefix, '');
+ bool get isProjectMode =>
+ allowsCommands && !commandsOnly && query.trimLeft().startsWith('#');
+ static final _quickAccessPrefix = RegExp(r'^[>@#?]');
+ bool get isMachineMode =>
+ allowsCommands && !commandsOnly && query.trimLeft().startsWith('@');
+ bool get isGroupMode => isProjectMode || isMachineMode;
+ ({String id, String name, String query})? _groupScope;
+ bool get canGoBack => _groupScope != null;
+ String get matchQuery => isCommandMode
+ ? commandQuery
+ : isHelpMode
+ ? helpQuery
+ : isGroupMode
+ ? query.trimLeft().substring(1).trimLeft()
+ : query;
+ String get title => isCommandMode
+ ? 'Commands'
+ : isHelpMode
+ ? 'Quick access'
+ : isProjectMode
+ ? 'Projects'
+ : isMachineMode
+ ? 'Machines'
+ : _groupScope != null
+ ? 'Agents · ${_groupScope!.name}'
+ : placement?.title ?? 'Search';
+
+ bool _previewVisible;
+ bool get previewVisible => _previewVisible;
+ bool get supportsPreview => !isCommandMode && !isHelpMode && history == null;
+ bool get canPreview =>
+ supportsPreview &&
+ selected != null &&
+ // With nothing found the only row is "New harness: …"; a preview beside
+ // it could only say the same words again, over 400px of empty panel.
+ rows.any((row) => !row.isCreate);
+
+ bool get hasPreview =>
+ _previewVisible &&
+ canPreview &&
+ (!resultsFromBottom || selected?.isCreate != true);
+
+ void togglePreview() {
+ if (!supportsPreview) return;
+ _previewVisible = !_previewVisible;
+ notifyListeners();
+ }
+
+ /// How many things could match, and how many do: fzf's `4/7`. The count is
+ /// the quickest answer to "did that narrow it, or is it just not here?".
+ int total = 0;
+
+ /// Counted once per filter, not once per read: the count and the hints both
+ /// rebuild on every arrow key.
+ int matchCount = 0;
+
+ // Compiled once: both run in `_filter` and in two builds per keystroke.
+ static final _helpPrefix = RegExp(r'^\?\s*');
+ static final _commandPrefix = RegExp(r'^>\s*');
// Paging the preview must not rebuild the result list or its text editor.
final _previewPage = ValueNotifier<int>(0);
ValueListenable<int> get previewPage => _previewPage;
- void pagePreview(int pages) {
- if (hasPreview) _previewPage.value += pages;
+ final _resultPage = ValueNotifier<int>(0);
+ ValueListenable<int> get resultPage => _resultPage;
+ void page(int pages) {
+ if (hasPreview) {
+ _previewPage.value += pages;
+ } else {
+ _resultPage.value += pages;
+ }
}
final String targetId, targetName;
@@ -87,7 +196,27 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
+ /// Cmd-T and Cmd-P change where Enter opens the result, while the query,
+ /// highlighted result and project/machine scope remain the person's choices.
+ bool changePlacement(HarnessPlacement placement) {
+ if (!adding ||
+ navigating ||
+ history != null ||
+ targetId != app.activeSwarmId) {
+ return false;
+ }
+ if (_placement != placement || _split != null) {
+ _placement = placement;
+ _split = null;
+ // Capacity and "already here" are destination-dependent even when the
+ // catalog itself has not changed.
+ _refresh(force: true);
+ }
+ return true;
+ }
+
int get capacity {
+ if (placement == HarnessPlacement.newTab) return AppNotifier.maxPanes;
final target = app.swarms
.where((swarm) => swarm.id == targetId)
.firstOrNull;
@@ -99,29 +228,97 @@ class SwarmSearchController extends ChangeNotifier {
SwarmDestination? get selected => rows.isEmpty ? null : rows[cursor];
String get hint => isCommandMode
? 'Search commands…'
+ : isHelpMode
+ ? 'Choose a mode or search help…'
+ : _groupScope != null
+ ? 'Search agents in ${_groupScope!.name}…'
+ : isProjectMode
+ ? 'Search projects…'
+ : isMachineMode
+ ? 'Search machines…'
: history != null
? 'Search history…'
- : 'Find a harness';
+ : placement != null
+ ? kHarnessPickerHint
+ : kSwarmSearchHint;
+
+ /// What the create row would start the harness on: what was typed, as its
+ /// first message. An editor's palette offers `New agent: "fix the login
+ /// test"` the same way — in the AI age the thing you type when nothing
+ /// matches is more often a job than a name. (Naming the project is a field
+ /// of New Harness itself.)
+ String? get createTask {
+ final typed = query.trim();
+ if (typed.isEmpty ||
+ isCommandMode ||
+ isHelpMode ||
+ _groupScope != null ||
+ isGroupMode) {
+ return null;
+ }
+ return typed;
+ }
+
+ bool get _showsCreateRow =>
+ offersCreate &&
+ adding &&
+ history == null &&
+ !navigating &&
+ !isCommandMode &&
+ !isHelpMode &&
+ _groupScope == null &&
+ !isGroupMode &&
+ canCreate;
+
+ SwarmDestination? _createRow;
+ SwarmDestination _createRowFor(String? name) {
+ const title = 'New Harness';
+ // The same object while the words are the same: live preview text
+ // re-filters constantly and compares rows by identity.
+ if (_createRow?.task == name && _createRow != null) return _createRow!;
+ return _createRow = SwarmDestination(
+ id: kSwarmCreateRowId,
+ title: title,
+ detail: name ?? 'use current defaults',
+ swarmId: null,
+ current: false,
+ isCreate: true,
+ task: name,
+ );
+ }
bool get canCreate =>
history == null &&
- app.swarms.any(
- (swarm) =>
- swarm.id == targetId && swarm.panes.length < AppNotifier.maxPanes,
- ) &&
+ (placement == HarnessPlacement.newTab ||
+ app.swarms.any(
+ (swarm) =>
+ swarm.id == targetId &&
+ !swarm.isStore &&
+ !swarm.isOrchestrator &&
+ swarm.panes.length < AppNotifier.maxPanes,
+ )) &&
(split == null || app.isPaneSplitCurrent(split!));
- String get commandQuery =>
- query.trimLeft().replaceFirst(RegExp(r'^>\s*'), '');
+ String get commandQuery => query.trimLeft().replaceFirst(_commandPrefix, '');
- String get primaryAction => switch (split?.axis) {
- PaneResizeAxis.x => 'Split right',
- PaneResizeAxis.y => 'Split down',
- null => 'Open Harness',
- };
+ String get primaryAction =>
+ placement?.action ??
+ switch (split?.axis) {
+ PaneResizeAxis.x => 'Split right',
+ PaneResizeAxis.y => 'Split down',
+ null => 'Open Harness',
+ };
- String actionLabel(SwarmDestination? row) => row?.isCommand == true
- ? action(row!)
+ String actionLabel(SwarmDestination? row) => row?.isCreate == true
+ ? 'New Harness'
+ : row?.pickerQuery != null
+ ? 'Open'
+ : isGroupMode && row?.isGroup == true
+ ? 'Choose ${isProjectMode ? 'project' : 'machine'}'
+ : placement != null && row != null && alreadyHere(row)
+ ? 'Focus pane'
+ : row?.isCommand == true
+ ? (isHelpMode ? 'Open' : action(row!))
: adding
? row != null &&
row.agentId == null &&
@@ -138,24 +335,38 @@ class SwarmSearchController extends ChangeNotifier {
? 'The layout changed. Split the pane again.'
: selected != null && alreadyHere(selected!)
? 'This harness is already open here.'
+ // A tab, project or machine with nothing left to add is not "no room".
+ : selected != null &&
+ selected!.agentId == null &&
+ selected!.members.isNotEmpty &&
+ _missingIds(selected!).isEmpty
+ ? 'Everything in it is already open here.'
: 'No room for another harness.';
- void _refresh() {
+ void _refresh({bool force = false}) {
final next = navigating
? _locations.read(app, projects?.projects ?? const [])
: history == null
? _cache.read(app, projects?.projects ?? const [], recent: recent)
: [...history!.menuDestinations(app), ...closedWorkDestinations(app)];
final splitCurrent = split == null || app.isPaneSplitCurrent(split!);
- if (identical(next, _catalog) &&
- !isCommandMode &&
- splitCurrent == _splitCurrent) {
- return;
+ if (!force && identical(next, _catalog) && splitCurrent == _splitCurrent) {
+ if (!isCommandMode) return;
+ // Which commands are available follows the workspace, so command mode
+ // cannot skip the look — but most ticks change none of them, and those
+ // must not re-rank, re-sort and rebuild the list.
+ final available = {
+ for (final command in commands?.call() ?? const <SwarmDestination>[])
+ command.id,
+ };
+ if (setEquals(available, _commandIds)) return;
}
_catalog = next;
_splitCurrent = splitCurrent;
_presentIds = {
- for (final swarm in app.swarms.where((s) => s.id == targetId))
+ for (final swarm in app.swarms.where(
+ (s) => placement != HarnessPlacement.newTab && s.id == targetId,
+ ))
for (final pane in swarm.panes)
if (pane.agentId != null)
agentDestinationId(pane.machineId, pane.agentId!),
@@ -171,7 +382,12 @@ class SwarmSearchController extends ChangeNotifier {
}
void _previewChanged() {
- if (query.trim().isEmpty || isCommandMode || history != null) return;
+ if (matchQuery.trim().isEmpty ||
+ isCommandMode ||
+ isHelpMode ||
+ history != null) {
+ return;
+ }
final previous = rows;
final previousSelection = selected?.id;
_filter(keepOrder: true);
@@ -184,31 +400,73 @@ class SwarmSearchController extends ChangeNotifier {
void _filter({bool keepOrder = false}) {
final previous = rows;
+ if (isHelpMode) {
+ // The modes keep the order they are taught in; what follows `?` only
+ // narrows them, the way a quick-open's own `?` does.
+ final all = modes?.call() ?? const <SwarmDestination>[];
+ final needle = helpQuery.toLowerCase();
+ _commandIds = {for (final mode in all) mode.id};
+ total = all.length;
+ rows = [
+ for (final mode in all)
+ if (needle.isEmpty ||
+ mode.fields.any((field) => field.contains(needle)) ||
+ mode.detail.toLowerCase().contains(needle))
+ mode,
+ ];
+ cursor = rows.isEmpty ? 0 : cursor.clamp(0, rows.length - 1);
+ _selectedId = selected?.id;
+ matchCount = rows.length;
+ return;
+ }
final availableCommands = isCommandMode
? commands?.call() ?? const <SwarmDestination>[]
: const <SwarmDestination>[];
_commandIds = {for (final command in availableCommands) command.id};
+ final scopedMembers = _groupScope == null
+ ? null
+ : _catalog
+ .where((row) => row.id == _groupScope!.id)
+ .firstOrNull
+ ?.members ??
+ <String>{};
+ final candidates = isCommandMode
+ ? availableCommands
+ : isProjectMode
+ ? _catalog.where((row) => row.isProject).toList()
+ : isMachineMode
+ ? _catalog.where((row) => row.isMachine).toList()
+ : placement != null || _groupScope != null
+ ? _catalog
+ .where(
+ (row) =>
+ row.agentId != null &&
+ (scopedMembers == null || scopedMembers.contains(row.id)),
+ )
+ .toList()
+ : navigating || !adding
+ ? _catalog
+ : _catalog
+ .where(
+ (row) =>
+ (split == null || row.agentId != null) &&
+ (_hasMissing(row) ||
+ (query.isNotEmpty && row.agentId != null)),
+ )
+ .toList();
+ total = candidates.length;
rows = isCommandMode
- ? rankSwarmDestinations(availableCommands, commandQuery)
+ ? _recentFirst(rankSwarmDestinations(availableCommands, commandQuery))
: navigating
? rankSwarmLocations(
_catalog,
- query,
+ matchQuery,
recent: recent,
previews: app.sessionPreviews,
)
: rankSwarmDestinations(
- adding
- ? _catalog
- .where(
- (row) =>
- (split == null || row.agentId != null) &&
- (_hasMissing(row) ||
- (query.isNotEmpty && row.agentId != null)),
- )
- .toList()
- : _catalog,
- query,
+ candidates,
+ matchQuery,
recent: recent,
previews: history == null ? app.sessionPreviews : null,
);
@@ -219,6 +477,29 @@ class SwarmSearchController extends ChangeNotifier {
...remaining.values,
];
}
+ // Keep the match order within each group, but put rows Return can open
+ // first. An already-added exact match must not bury the usable matches.
+ // Location navigation retains its parent/child structure.
+ if (!navigating && !isCommandMode) {
+ final available = <SwarmDestination>[];
+ final unavailable = <SwarmDestination>[];
+ for (final row in rows) {
+ (canSubmit(row) ? available : unavailable).add(row);
+ }
+ rows = [...available, ...unavailable];
+ }
+ // Creation has a stable place beside the prompt. Filtering changes the
+ // matches above it, never the position of the action itself.
+ if (offersCreate) {
+ final create = _showsCreateRow ? _createRowFor(createTask) : null;
+ final found = [
+ for (final row in rows)
+ if (!row.isCreate) row,
+ ];
+ rows = resultsFromBottom || placement != null || query.trim().isEmpty
+ ? [?create, ...found]
+ : [...found, ?create];
+ }
// The parent stays above its children visually, but Enter after a query
// still targets the best match, including an agent nested under that parent.
final preferred =
@@ -236,12 +517,45 @@ class SwarmSearchController extends ChangeNotifier {
? 0
: index >= 0
? index
+ // The box opens on the most recent harness, not on the create row above
+ // it: Return on a fresh box goes back to work, it does not make more.
+ : preferred == null &&
+ rows.length > 1 &&
+ rows.first.isCreate &&
+ (placement == null || query.trim().isNotEmpty)
+ ? 1
: cursor.clamp(0, rows.length - 1);
+ // Nor on a row Return cannot take: "Already added", dimmed, with its
+ // reason stranded at the bottom. Only when the position is ours to pick —
+ // a row somebody arrowed to stays theirs.
+ if (preferred == null && rows.isNotEmpty && !canSubmit(rows[cursor])) {
+ final first = rows.indexWhere(canSubmit);
+ if (first >= 0) cursor = first;
+ }
_selectedId = selected?.id;
+ matchCount = rows.where((row) => !row.isCreate).length;
+ }
+
+ /// With nothing typed, the commands run lately lead, newest first; the rest
+ /// keep their order. Once something is typed, the match decides.
+ List<SwarmDestination> _recentFirst(List<SwarmDestination> ranked) {
+ final recent = recentCommands?.call() ?? const <String>[];
+ if (commandQuery.trim().isNotEmpty || recent.isEmpty) return ranked;
+ final byId = {
+ for (final row in ranked)
+ if (row.commandId != null) row.commandId!: row,
+ };
+ final first = [for (final id in recent) ?byId[id]];
+ return [
+ ...first,
+ for (final row in ranked)
+ if (!first.contains(row)) row,
+ ];
}
void setQuery(String value) {
if (query == value) return;
+ if (_quickAccessPrefix.hasMatch(value.trimLeft())) _groupScope = null;
query = value;
cursor = 0;
_selectedId = null;
@@ -249,6 +563,14 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
+ bool back() {
+ final scope = _groupScope;
+ if (scope == null) return false;
+ _groupScope = null;
+ setQuery(scope.query);
+ return true;
+ }
+
void move(int delta) {
if (rows.isEmpty) return;
cursor = (cursor + delta) % rows.length;
@@ -256,11 +578,44 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
+ /// Positive means down on screen, including in a bottom-up dock. At a dock
+ /// edge, keep the selection still instead of jumping to the opposite end.
+ void moveVisually(int direction) {
+ if (!resultsFromBottom) {
+ move(direction);
+ return;
+ }
+ if (rows.isEmpty) return;
+ final next = (cursor - direction).clamp(0, rows.length - 1);
+ if (next != cursor) move(next - cursor);
+ }
+
SwarmSearchSelection? submit([SwarmDestination? row]) {
final destination = row ?? selected;
if (destination == null || !canSubmit(destination)) return null;
+ if (isGroupMode && destination.isGroup) {
+ final group = _catalog
+ .where((row) => row.id == destination.id && row.isGroup)
+ .firstOrNull;
+ if (group != null) {
+ _groupScope = (id: group.id, name: group.title, query: query);
+ setQuery('');
+ }
+ return null;
+ }
+ if (destination.pickerQuery case final next?) {
+ if (modes?.call().any(
+ (mode) => mode.id == destination.id && mode.pickerQuery == next,
+ ) ??
+ false) {
+ setQuery(next);
+ }
+ return null;
+ }
if (destination.isCommand &&
- !(commands?.call().any((command) => command.id == destination.id) ??
+ !((isHelpMode ? modes : commands)?.call().any(
+ (command) => command.id == destination.id,
+ ) ??
false)) {
return null;
}
@@ -270,14 +625,21 @@ class SwarmSearchController extends ChangeNotifier {
);
}
- bool canSubmit(SwarmDestination? row) =>
- row != null &&
- (!adding || row.isCommand || canAdd(row)) &&
- (!row.isCommand || (isCommandMode && _commandIds.contains(row.id))) &&
- (adding ||
- !row.isGroup ||
- canOpenSwarmGroup(app, row, destinationSwarmId: targetId)) &&
- (row.closedId == null || app.canReopenClosed(row.closedId!));
+ bool canSubmit(SwarmDestination? row) => row?.pickerQuery != null
+ ? isHelpMode && _commandIds.contains(row!.id)
+ : isGroupMode && row?.isGroup == true
+ ? _catalog.any((group) => group.id == row!.id && group.isGroup)
+ : row != null && row.isCreate
+ ? canCreate
+ : row != null &&
+ (!adding || row.isCommand || canAdd(row)) &&
+ (!row.isCommand ||
+ ((isCommandMode || isHelpMode) &&
+ _commandIds.contains(row.id))) &&
+ (adding ||
+ !row.isGroup ||
+ canOpenSwarmGroup(app, row, destinationSwarmId: targetId)) &&
+ (row.closedId == null || app.canReopenClosed(row.closedId!));
Set<String> _missingIds(SwarmDestination row) {
final members = row.agentId == null ? row.members : {row.id};
@@ -297,17 +659,22 @@ class SwarmSearchController extends ChangeNotifier {
row != null &&
!row.isCommand &&
row.closedId == null &&
- _missingIds(row).isNotEmpty &&
- (split == null || row.agentId != null) &&
- (split == null || app.isPaneSplitCurrent(split!)) &&
- app.swarms.any(
- (swarm) =>
- swarm.id == targetId &&
- swarm.panes.length + _missingIds(row).length <=
- AppNotifier.maxPanes,
- );
-
- SwarmSearchSelection? addHere() => adding
+ (placement == null || row.agentId != null) &&
+ (placement != null && alreadyHere(row) ||
+ _missingIds(row).isNotEmpty &&
+ (split == null || row.agentId != null) &&
+ (split == null || app.isPaneSplitCurrent(split!)) &&
+ (placement == HarnessPlacement.newTab ||
+ app.swarms.any(
+ (swarm) =>
+ swarm.id == targetId &&
+ !swarm.isStore &&
+ !swarm.isOrchestrator &&
+ swarm.panes.length + _missingIds(row).length <=
+ AppNotifier.maxPanes,
+ )));
+
+ SwarmSearchSelection? addHere() => adding || isGroupMode || isHelpMode
? submit()
: canAdd(selected)
? SwarmSearchSelection(selected!, SwarmSearchAction.addHere)
@@ -317,6 +684,8 @@ class SwarmSearchController extends ChangeNotifier {
? 'Run command'
: row.closedId != null
? 'Reopen'
+ : row.isSwarm && !row.isStore && row.members.length != 1
+ ? 'Go to Tab'
: 'Open Harness';
@override
@@ -325,6 +694,7 @@ class SwarmSearchController extends ChangeNotifier {
projects?.removeListener(_refresh);
app.sessionPreviews.removeListener(_previewChanged);
_previewPage.dispose();
+ _resultPage.dispose();
super.dispose();
}
}
diff --git a/desktop/lib/state/workspace_learning.dart b/desktop/lib/state/workspace_learning.dart
new file mode 100644
index 000000000..f42adfa19
--- /dev/null
+++ b/desktop/lib/state/workspace_learning.dart
@@ -0,0 +1,109 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/foundation.dart';
+
+import '../core/local_key_value_store.dart';
+
+enum WorkspaceLesson { agent, pane, zoom, commands }
+
+/// Progress belongs to this person's desktop, never to an agent or project.
+/// Merely opening a chooser does not complete the agent/pane lessons.
+class WorkspaceLearning extends ChangeNotifier {
+ WorkspaceLearning({this.storage});
+ final LocalKeyValueStore? storage;
+ static const storageKey = 'workspace_quick_start_v1';
+ final _completed = <WorkspaceLesson>{};
+ bool active = false;
+ bool dismissed = false;
+ bool loaded = false;
+ bool _disposed = false;
+ int _revision = 0;
+ Future<void> _saving = Future.value();
+
+ Set<WorkspaceLesson> get completed => Set.unmodifiable(_completed);
+ bool get finished => _completed.length == WorkspaceLesson.values.length;
+ bool get offer => loaded && !active && !dismissed && !finished;
+ WorkspaceLesson? get next => WorkspaceLesson.values
+ .where((step) => !_completed.contains(step))
+ .firstOrNull;
+
+ Future<void> load() async {
+ final revision = _revision;
+ try {
+ final raw = await storage?.read(storageKey);
+ if (_disposed || revision != _revision) return;
+ final data = raw == null ? null : jsonDecode(raw);
+ if (data is Map) {
+ active = data['active'] == true;
+ dismissed = data['dismissed'] == true;
+ final done = data['completed'];
+ if (done is List) {
+ _completed.addAll(
+ WorkspaceLesson.values.where((s) => done.contains(s.name)),
+ );
+ }
+ }
+ } catch (_) {
+ // A missing/corrupt preference must never block the workspace.
+ } finally {
+ if (!_disposed) {
+ loaded = true;
+ notifyListeners();
+ }
+ }
+ }
+
+ void start() {
+ if (finished) _completed.clear();
+ active = true;
+ dismissed = false;
+ _changed();
+ }
+
+ void pause() {
+ active = false;
+ dismissed = true;
+ _changed();
+ }
+
+ void observe({required int agents, required bool zoomed}) {
+ if (!active || finished) return;
+ final before = _completed.length;
+ if (agents > 0) _completed.add(WorkspaceLesson.agent);
+ if (agents > 1) _completed.add(WorkspaceLesson.pane);
+ if (agents > 1 && zoomed) _completed.add(WorkspaceLesson.zoom);
+ if (before != _completed.length) _changed();
+ }
+
+ void commandSearchOpened() {
+ if (!active || next != WorkspaceLesson.commands) return;
+ _completed.add(WorkspaceLesson.commands);
+ _changed();
+ }
+
+ void _changed() {
+ _revision++;
+ final data = jsonEncode({
+ 'active': active,
+ 'dismissed': dismissed,
+ 'completed': _completed.map((s) => s.name).toList(),
+ });
+ _saving = _saving.then((_) async {
+ try {
+ await storage?.write(storageKey, data);
+ } catch (_) {
+ // Learning remains available if a preference cannot be saved.
+ }
+ });
+ notifyListeners();
+ }
+
+ Future<void> flush() => _saving;
+
+ @override
+ void dispose() {
+ _disposed = true;
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/store/store_editorial.dart b/desktop/lib/store/store_editorial.dart
index 5577a4559..f77903420 100644
--- a/desktop/lib/store/store_editorial.dart
+++ b/desktop/lib/store/store_editorial.dart
@@ -9,7 +9,11 @@ String storeCategoryFor(DshEntry entry) {
if (const {'autonomous/autonomous-grid', 'local/ollama'}.contains(entry.id)) {
return 'Local AI';
}
- final domain = entry.category?.trim().toLowerCase();
+ // Published Home Assistant packages also use the older Automation domain.
+ final domain = switch (entry.category?.trim().toLowerCase()) {
+ 'automation' => 'home automation',
+ final domain => domain,
+ };
for (final category in storeCategoryDomains.entries) {
if (category.key.toLowerCase() == domain ||
category.value.any((value) => value.toLowerCase() == domain)) {
diff --git a/desktop/lib/store/store_mark.dart b/desktop/lib/store/store_mark.dart
index 93acf87f8..2f801b3e3 100644
--- a/desktop/lib/store/store_mark.dart
+++ b/desktop/lib/store/store_mark.dart
@@ -1,10 +1,10 @@
import 'package:flutter/widgets.dart';
-/// The Harness Store wears the app icon — the mark the Dock shows — wherever
-/// its tab is drawn. The native tab strip and History menu are sent this path
+/// Six disciplines meeting at one center: the Harness Store's polymath mark.
+/// The native tab strip and History menu are sent this path
/// and open the same file (`SwarmHistoryIcons` in
/// macos/Runner/SwarmTitlebar.swift, which must name it or it draws an initial).
-const String kStoreMarkAsset = 'assets/app_icon.png';
+const String kStoreMarkAsset = 'assets/store/polymath.png';
/// [kStoreMarkAsset] at a mark's size: the Flutter tab strip, and the store's
/// row in History. The 256px source is filtered down, so it stays crisp at 2x.
diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dart
index 3d40dfb03..713a10d5e 100644
--- a/desktop/lib/store/store_screen.dart
+++ b/desktop/lib/store/store_screen.dart
@@ -17,6 +17,7 @@ import '../shortcuts/keymap.dart';
import '../state/app_state.dart';
import '../widgets/engine_identity.dart';
import '../widgets/new_agent_dialog.dart';
+import '../widgets/open_harness_intent.dart';
import 'store_category.dart';
import 'store_controller.dart';
import 'store_discover.dart';
@@ -892,8 +893,8 @@ bool _canGetOnMachine(MachineState machine, DshEntry entry) {
machine.dsh.runs[entry.id]?.inProgress != true;
}
-/// Open a Store harness on [machineId] the way the Store's Open button does: a
-/// draft tab of its own, then New Agent with the harness already chosen.
+/// Open the workspace's New Harness dock with this product and machine chosen.
+/// A successful start opens a new tab; reviewing or cancelling allocates none.
///
/// Public because it is the ONE way a harness is opened from anywhere — the
/// Store page, and the model picker's "Open Grid" — so the two cannot drift
@@ -905,6 +906,12 @@ Future<void> openStoreAgent(
String machineId, {
String? prompt,
}) async {
+ final intent = OpenHarnessIntent(harnessId, machineId, task: prompt);
+ if (Actions.maybeFind<OpenHarnessIntent>(context) != null) {
+ final opening = Actions.maybeInvoke(context, intent);
+ if (opening is Future) await opening;
+ return;
+ }
final navigator = Navigator.of(context);
final origin = notifier.activeSwarmId;
notifier.newSwarm(draft: true);
@@ -1032,10 +1039,8 @@ class _ProductPageState extends State<_ProductPage> {
if (failure != null) _say(failure);
}
- /// Open (or Get) from the store: the harness needs a tab of its own, since
- /// a pane never lands in the store tab. A draft tab is opened for it and
- /// abandoned — back to the store — if the dialog is dismissed. [prompt] is
- /// an example's, and becomes the new harness's first message.
+ /// Open from the Store with this product and machine. An example's [prompt]
+ /// becomes the editable task in the same dock before the person presses Start.
Future<void> _open(String machineId, {String? prompt}) async {
if (widget.notifier.localMachineState?.machine.machineId != machineId) {
return;
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index 9d136c9a5..c611f7559 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -804,7 +804,9 @@ class TerminalSession extends ChangeNotifier {
Terminal _newTerminal({bool bindCallbacks = true}) {
final result = Terminal(
maxLines: 10000,
- platform: TerminalTargetPlatform.macos,
+ platform: defaultTargetPlatform == TargetPlatform.linux
+ ? TerminalTargetPlatform.linux
+ : TerminalTargetPlatform.macos,
// ⌥⏎ has to become a Meta-prefixed Return before it reaches the pty, or the engine's prompt
// reads it as the submit it is byte-identical to. See [MetaEnterInputHandler].
inputHandler: harnessInputHandler,
diff --git a/desktop/lib/terminal/terminal_theme_store.dart b/desktop/lib/terminal/terminal_theme_store.dart
index b11b8988e..31dbde597 100644
--- a/desktop/lib/terminal/terminal_theme_store.dart
+++ b/desktop/lib/terminal/terminal_theme_store.dart
@@ -69,10 +69,8 @@ class TerminalThemeStore extends ValueNotifier<TerminalThemeChoice> {
/// Read the saved choice, if there is one. Failure — or a scheme name from a
/// build that had one this one does not — is silent and lands on the default.
/// An unreadable state file is not a reason to refuse to start.
- /// `readMany`, not a plain `read`, for a single key: it is the batch path
- /// [TerminalFontStore] and [AppearancePrefsStore] take, so on a shared file
- /// store this preference arrives in the same snapshot as theirs rather than
- /// as a second pass over a file that may have been rewritten in between.
+ /// Uses the same batch-read API as [TerminalFontStore] and
+ /// [AppearancePrefsStore]. Each load observes its own current snapshot.
Future<void> load() async {
try {
final saved = await _storage.readMany([_key]);
diff --git a/desktop/lib/update/desktop_updater.dart b/desktop/lib/update/desktop_updater.dart
index 852d9452e..6fa3b69ee 100644
--- a/desktop/lib/update/desktop_updater.dart
+++ b/desktop/lib/update/desktop_updater.dart
@@ -58,6 +58,26 @@ class UpdateInfo {
});
}
+enum DesktopUpdateCheckStatus { upToDate, available, disabled, failed }
+
+/// A failed or disabled check cannot establish that the installed app is current.
+class DesktopUpdateCheck {
+ final DesktopUpdateCheckStatus status;
+ final UpdateInfo? update;
+
+ const DesktopUpdateCheck.upToDate()
+ : status = DesktopUpdateCheckStatus.upToDate,
+ update = null;
+ const DesktopUpdateCheck.available(UpdateInfo this.update)
+ : status = DesktopUpdateCheckStatus.available;
+ const DesktopUpdateCheck.disabled()
+ : status = DesktopUpdateCheckStatus.disabled,
+ update = null;
+ const DesktopUpdateCheck.failed()
+ : status = DesktopUpdateCheckStatus.failed,
+ update = null;
+}
+
/// A downloaded, sha256-verified build sitting in a temp directory, not yet swapped into place.
class StagedUpdate {
final String version;
@@ -148,6 +168,11 @@ class DesktopUpdater {
final bool _enabled;
final bool _isLinux;
final String _architecture;
+ final _checksInFlight = <String?, Future<DesktopUpdateCheck>>{};
+
+ static const checkInterval = Duration(hours: 6);
+
+ bool get canCheck => _enabled && _releaseMode;
DesktopUpdater({
this._enabled = true,
@@ -191,26 +216,41 @@ class DesktopUpdater {
return const [_otaKeyMacOSArm64, _otaKeyMacOS];
}
- /// Fetches the manifest and returns the newer entry, or null if this app is already current (or
- /// the manifest/network is unavailable — treated the same as "nothing to do", never surfaced as an
- /// error; this runs unattended in the background).
- ///
- /// A debug or profile build never reports an update — self-installing (swapping the running .app
- /// bundle for a downloaded release build and relaunching, see [applyStaged]) makes no sense for a
- /// local dev build and would silently clobber it mid-session.
- Future<UpdateInfo?> checkOnce({String? currentVersion}) async {
- if (!_enabled || !_releaseMode) return null;
+ /// Unattended callers only need an offer. Interactive callers use [check]
+ /// so an unreachable service is not presented as "up to date".
+ Future<UpdateInfo?> checkOnce({String? currentVersion}) async =>
+ (await check(currentVersion: currentVersion)).update;
+
+ /// Manual and background callers share an in-flight manifest request.
+ /// Debug/profile and explicitly disabled builds never offer a release that
+ /// could replace the local development build.
+ Future<DesktopUpdateCheck> check({String? currentVersion}) =>
+ _checksInFlight.putIfAbsent(currentVersion, () async {
+ try {
+ return await _check(currentVersion: currentVersion);
+ } finally {
+ _checksInFlight.remove(currentVersion);
+ }
+ });
+
+ Future<DesktopUpdateCheck> _check({String? currentVersion}) async {
+ if (!canCheck) return const DesktopUpdateCheck.disabled();
try {
final running = currentVersion ?? await runningAppVersion();
+ if (_parseSemverCore(running) == null) {
+ return const DesktopUpdateCheck.failed();
+ }
final response = await _dio.get<Map<String, dynamic>>(
_metadataUrlForInstance,
);
final newest = _newestEntry(response.data);
- if (newest == null || !semverGt(newest.version, running)) return null;
- return newest;
+ if (newest == null) return const DesktopUpdateCheck.failed();
+ return semverGt(newest.version, running)
+ ? DesktopUpdateCheck.available(newest)
+ : const DesktopUpdateCheck.upToDate();
} catch (error) {
- debugPrint('DesktopUpdater.checkOnce: $error');
- return null;
+ debugPrint('DesktopUpdater.check: $error');
+ return const DesktopUpdateCheck.failed();
}
}
@@ -238,6 +278,7 @@ class DesktopUpdater {
final sha256 = entry['sha256'];
final size = entry['size'];
if (version is! String ||
+ _parseSemverCore(version) == null ||
url is! String ||
sha256 is! String ||
size is! int) {
@@ -250,23 +291,33 @@ class DesktopUpdater {
/// build is found (re-finding the same version on a later tick is harmless; the caller is expected
/// to no-op if it's already showing that version). Cancel the returned [Timer] to stop.
Timer startChecking({
- Duration interval = const Duration(minutes: 1),
- required void Function(UpdateInfo info) onUpdateAvailable,
+ Duration interval = checkInterval,
+ void Function(UpdateInfo info)? onUpdateAvailable,
+ void Function(DesktopUpdateCheck result)? onCheckCompleted,
// Forwarded to checkOnce() on every tick — tests pass this to avoid checkOnce()'s default
// runningAppVersion() call, which (via PackageInfo.fromPlatform()) needs a platform method
// channel real production code gets for free but a plain `test()` doesn't.
String? currentVersion,
}) {
- void tick() {
- unawaited(
- checkOnce(currentVersion: currentVersion).then((info) {
- if (info != null) onUpdateAvailable(info);
- }),
- );
+ var checking = false;
+ late final Timer timer;
+ Future<void> tick() async {
+ if (checking || !timer.isActive) return;
+ checking = true;
+ try {
+ final result = await check(currentVersion: currentVersion);
+ if (!timer.isActive) return;
+ onCheckCompleted?.call(result);
+ final info = result.update;
+ if (info != null) onUpdateAvailable?.call(info);
+ } finally {
+ checking = false;
+ }
}
- tick();
- return Timer.periodic(interval, (_) => tick());
+ timer = Timer.periodic(interval, (_) => unawaited(tick()));
+ unawaited(tick());
+ return timer;
}
/// Downloads [info] and verifies its sha256 BEFORE trusting the bytes. On macOS, unpacks the zip
diff --git a/desktop/lib/update/manual_update_check.dart b/desktop/lib/update/manual_update_check.dart
index 70f5ce7cc..6e7f71010 100644
--- a/desktop/lib/update/manual_update_check.dart
+++ b/desktop/lib/update/manual_update_check.dart
@@ -3,10 +3,12 @@ import 'desktop_updater.dart';
/// Result of a user-initiated check. A manually checked version remains
/// installable even when the user skipped its background notification earlier.
class ManualUpdateCheck {
- final UpdateInfo? update;
+ final DesktopUpdateCheck check;
final bool isSkipped;
- const ManualUpdateCheck({this.update, this.isSkipped = false});
+ const ManualUpdateCheck({required this.check, this.isSkipped = false});
- bool get isUpToDate => update == null;
+ UpdateInfo? get update => check.update;
+ DesktopUpdateCheckStatus get status => check.status;
+ bool get isUpToDate => status == DesktopUpdateCheckStatus.upToDate;
}
diff --git a/desktop/lib/usage/ledger/claude_ledger_scanner.dart b/desktop/lib/usage/ledger/claude_ledger_scanner.dart
index 3217c2c03..a36b02fc8 100644
--- a/desktop/lib/usage/ledger/claude_ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/claude_ledger_scanner.dart
@@ -11,6 +11,7 @@ import 'dart:io';
import 'ledger_scanner.dart';
import 'ledger_types.dart';
+import 'jsonl_ledger_scan.dart';
class ClaudeLedgerScanner implements LedgerScanner {
ClaudeLedgerScanner({String? home, this.environment})
@@ -39,56 +40,25 @@ class ClaudeLedgerScanner implements LedgerScanner {
'No home directory to read Claude transcripts from',
);
}
- final files = await listJsonlFiles(roots);
- if (files.isEmpty) {
- return const LedgerScanResult.unavailable(
- 'No Claude Code transcripts on this computer',
- );
- }
-
- final sources = <ScannedSource>[];
- for (final file in files) {
- final FileStat stat;
- try {
- stat = await file.stat();
- } on FileSystemException {
- continue;
- }
- final cached = previous[file.path];
- if (cached != null && cached.matches(stat)) {
- sources.add(cached);
- continue;
- }
- sources.add(
- ScannedSource(
- path: file.path,
- mtimeMs: stat.modified.millisecondsSinceEpoch,
- size: stat.size,
- entries: await _parse(file),
- ),
- );
- }
- return LedgerScanResult(sources: sources);
+ return scanJsonlUsage(
+ provider: provider,
+ roots: roots,
+ previous: previous,
+ missingMessage: 'No Claude Code transcripts on this computer',
+ parse: _parse,
+ );
}
- Future<List<LedgerEntry>> _parse(File file) async {
+ Future<List<LedgerEntry>> _parse(File file, int length) async {
// The session id the transcript is named after, for the rows that omit it.
final fallbackSessionId = file.uri.pathSegments.last.replaceAll(
'.jsonl',
'',
);
final turns = <ClaudeTurn>[];
- try {
- final lines = file
- .openRead()
- .transform(utf8.decoder)
- .transform(const LineSplitter());
- await for (final line in lines) {
- final turn = parseClaudeLine(line, fallbackSessionId);
- if (turn != null) turns.add(turn);
- }
- } on FileSystemException {
- return const [];
+ await for (final line in readJsonlLines(file, length)) {
+ final turn = parseClaudeLine(line, fallbackSessionId);
+ if (turn != null) turns.add(turn);
}
return _dedupe(turns);
}
diff --git a/desktop/lib/usage/ledger/codex_ledger_scanner.dart b/desktop/lib/usage/ledger/codex_ledger_scanner.dart
index 36617a7ec..3222d91d5 100644
--- a/desktop/lib/usage/ledger/codex_ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/codex_ledger_scanner.dart
@@ -16,6 +16,7 @@ import 'dart:io';
import 'ledger_scanner.dart';
import 'ledger_types.dart';
+import 'jsonl_ledger_scan.dart';
class CodexLedgerScanner implements LedgerScanner {
CodexLedgerScanner({String? home, Map<String, String>? environment})
@@ -49,54 +50,23 @@ class CodexLedgerScanner implements LedgerScanner {
'No home directory to read Codex sessions from',
);
}
- final files = await listJsonlFiles(roots);
- if (files.isEmpty) {
- return const LedgerScanResult.unavailable(
- 'No Codex sessions on this computer',
- );
- }
-
- final sources = <ScannedSource>[];
- for (final file in files) {
- final FileStat stat;
- try {
- stat = await file.stat();
- } on FileSystemException {
- continue;
- }
- final cached = previous[file.path];
- if (cached != null && cached.matches(stat)) {
- sources.add(cached);
- continue;
- }
- sources.add(
- ScannedSource(
- path: file.path,
- mtimeMs: stat.modified.millisecondsSinceEpoch,
- size: stat.size,
- entries: await _parse(file),
- ),
- );
- }
- return LedgerScanResult(sources: sources);
+ return scanJsonlUsage(
+ provider: provider,
+ roots: roots,
+ previous: previous,
+ missingMessage: 'No Codex sessions on this computer',
+ parse: _parse,
+ );
}
- Future<List<LedgerEntry>> _parse(File file) async {
+ Future<List<LedgerEntry>> _parse(File file, int length) async {
final context = CodexParseContext(
sessionId: file.uri.pathSegments.last.replaceAll('.jsonl', ''),
);
final entries = <LedgerEntry>[];
- try {
- final lines = file
- .openRead()
- .transform(utf8.decoder)
- .transform(const LineSplitter());
- await for (final line in lines) {
- final entry = parseCodexLine(line, context);
- if (entry != null) entries.add(entry);
- }
- } on FileSystemException {
- return const [];
+ await for (final line in readJsonlLines(file, length)) {
+ final entry = parseCodexLine(line, context);
+ if (entry != null) entries.add(entry);
}
return entries;
}
diff --git a/desktop/lib/usage/ledger/jsonl_ledger_scan.dart b/desktop/lib/usage/ledger/jsonl_ledger_scan.dart
new file mode 100644
index 000000000..ded00adc5
--- /dev/null
+++ b/desktop/lib/usage/ledger/jsonl_ledger_scan.dart
@@ -0,0 +1,159 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'ledger_scanner.dart';
+import 'ledger_types.dart';
+
+/// Shared file lifecycle; each provider retains its own usage parser.
+Future<LedgerScanResult> scanJsonlUsage({
+ required LedgerProvider provider,
+ required List<String> roots,
+ required Map<String, ScannedSource> previous,
+ required String missingMessage,
+ required Future<List<LedgerEntry>> Function(File file, int length) parse,
+}) async {
+ final failures = <String>[];
+ final files = <String, File>{};
+ for (final root in roots) {
+ try {
+ await for (final entity in Directory(
+ root,
+ ).list(recursive: true, followLinks: false)) {
+ if (entity is File && entity.path.endsWith('.jsonl')) {
+ files[entity.path] = entity;
+ }
+ }
+ } on FileSystemException catch (error) {
+ // Unused/older roots normally do not exist. Other listing failures must
+ // not look like a provider that simply has no logs on this machine.
+ if (error.osError?.errorCode != 2 &&
+ !(Platform.isWindows && error.osError?.errorCode == 3)) {
+ failures.add(error.osError?.message ?? error.message);
+ }
+ }
+ }
+
+ final sources = <ScannedSource>[];
+ final paths = files.keys.toList()..sort();
+ for (final path in paths) {
+ final file = files[path]!;
+ try {
+ final stat = await file.stat();
+ if (stat.type != FileSystemEntityType.file) {
+ failures.add(
+ 'A transcript changed while scanning. Refresh to read it again.',
+ );
+ continue;
+ }
+ final cached = previous[path];
+ if (cached != null && cached.matches(stat)) {
+ sources.add(cached);
+ continue;
+ }
+ final entries = await parse(file, stat.size);
+ sources.add(
+ ScannedSource(
+ path: path,
+ mtimeMs: stat.modified.millisecondsSinceEpoch,
+ size: stat.size,
+ entries: entries,
+ ),
+ );
+ } on FileSystemException catch (error) {
+ failures.add(error.osError?.message ?? error.message);
+ } on FormatException {
+ failures.add('A transcript contains unreadable text.');
+ }
+ }
+
+ if (failures.isEmpty && files.isEmpty) {
+ return LedgerScanResult.unavailable(missingMessage);
+ }
+ return LedgerScanResult(
+ sources: sources,
+ status: failures.isEmpty
+ ? LedgerStatus.ok
+ : sources.isEmpty
+ ? LedgerStatus.failed
+ : LedgerStatus.partial,
+ message: failures.isEmpty
+ ? null
+ : sources.isEmpty
+ ? 'Could not read ${provider.label} usage: ${failures.first}'
+ : 'Some ${provider.label} usage could not be read. '
+ 'Figures are incomplete. ${failures.first}',
+ );
+}
+
+/// Read only the bytes that existed when scanning started. Holding back the
+/// final four bytes keeps an unfinished UTF-8 character in the final record
+/// from discarding earlier complete records while an agent appends to its log.
+/// Corrupt completed lines still fail the source. A valid last line needs no LF.
+Stream<String> readJsonlLines(File file, int length) {
+ var pending = Uint8List(0);
+ final completeBytes = StreamTransformer<List<int>, List<int>>.fromHandlers(
+ handleData: (chunk, sink) {
+ if (chunk.length >= 4) {
+ if (pending.isNotEmpty) sink.add(pending);
+ if (chunk.length > 4) sink.add(_slice(chunk, 0, chunk.length - 4));
+ pending = Uint8List.fromList(
+ _slice(chunk, chunk.length - 4, chunk.length),
+ );
+ } else {
+ final combined = Uint8List(pending.length + chunk.length)
+ ..setRange(0, pending.length, pending)
+ ..setRange(pending.length, pending.length + chunk.length, chunk);
+ final keepFrom = combined.length > 4 ? combined.length - 4 : 0;
+ if (keepFrom > 0) {
+ sink.add(Uint8List.sublistView(combined, 0, keepFrom));
+ }
+ pending = Uint8List.sublistView(combined, keepFrom);
+ }
+ },
+ handleDone: (sink) {
+ final end = pending.length - _unfinishedUtf8Length(pending);
+ if (end > 0) sink.add(Uint8List.sublistView(pending, 0, end));
+ sink.close();
+ },
+ );
+ return file
+ .openRead(0, length)
+ .transform(completeBytes)
+ .transform(utf8.decoder)
+ .transform(const LineSplitter());
+}
+
+List<int> _slice(List<int> bytes, int start, int end) => bytes is Uint8List
+ ? Uint8List.sublistView(bytes, start, end)
+ : bytes.sublist(start, end);
+
+int _unfinishedUtf8Length(Uint8List bytes) {
+ var start = bytes.length - 1;
+ while (start >= 0 && (bytes[start] & 0xc0) == 0x80) {
+ start--;
+ }
+ if (start < 0) return 0;
+ final lead = bytes[start];
+ final expected = switch (lead) {
+ >= 0xc2 && <= 0xdf => 2,
+ >= 0xe0 && <= 0xef => 3,
+ >= 0xf0 && <= 0xf4 => 4,
+ _ => 0,
+ };
+ final available = bytes.length - start;
+ if (expected == 0 || available >= expected) return 0;
+ if (available > 1) {
+ final next = bytes[start + 1];
+ if ((lead == 0xe0 && next < 0xa0) ||
+ (lead == 0xed && next >= 0xa0) ||
+ (lead == 0xf0 && next < 0x90) ||
+ (lead == 0xf4 && next >= 0x90)) {
+ return 0;
+ }
+ }
+ // Earlier bytes still pass through the strict decoder, including when they
+ // precede an unfinished character. Only a valid incomplete suffix is omitted.
+ return available;
+}
diff --git a/desktop/lib/usage/ledger/ledger_scanner.dart b/desktop/lib/usage/ledger/ledger_scanner.dart
index c72f5cd8c..7c03d1a51 100644
--- a/desktop/lib/usage/ledger/ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/ledger_scanner.dart
@@ -15,10 +15,9 @@ import 'ledger_types.dart';
/// One file or database a scan read, and what came out of it.
///
-/// [mtimeMs] and [size] together are the fingerprint. Cheap to take, and between
-/// them they catch every edit an agent CLI actually makes — these are
-/// append-only logs, so a write moves both. A hash would be exact and would cost
-/// a full read of the very file the fingerprint exists to avoid reading.
+/// [mtimeMs] and [size] together fingerprint the append-mostly JSONL logs.
+/// SQLite sources keep these as metadata only: committed changes can live in a
+/// separate, reused WAL file, so their scanner queries SQLite on each scan.
class ScannedSource {
const ScannedSource({
required this.path,
@@ -101,39 +100,11 @@ abstract class LedgerScanner {
/// Read what changed since [previous], keyed by source path.
///
- /// An implementation is expected to reuse a [ScannedSource] whose fingerprint
- /// still matches rather than re-parsing it.
+ /// JSONL implementations reuse a [ScannedSource] whose fingerprint still
+ /// matches. SQLite always queries a new committed snapshot.
Future<LedgerScanResult> scan(Map<String, ScannedSource> previous);
}
-/// Every `.jsonl` under [roots], deepest first, with unreadable roots skipped.
-///
-/// Skipped rather than reported: a missing `~/.codex` means that CLI was never
-/// run here, which is the ordinary case for two of the three providers on any
-/// given machine and not worth a sentence on screen.
-Future<List<File>> listJsonlFiles(Iterable<String> roots) async {
- final seen = <String>{};
- final files = <File>[];
- for (final root in roots) {
- final directory = Directory(root);
- if (!await directory.exists()) continue;
- try {
- await for (final entity in directory.list(
- recursive: true,
- followLinks: false,
- )) {
- if (entity is! File || !entity.path.endsWith('.jsonl')) continue;
- if (seen.add(entity.path)) files.add(entity);
- }
- } on FileSystemException {
- // A single unreadable subtree must not hide the roots beside it.
- continue;
- }
- }
- files.sort((a, b) => a.path.compareTo(b.path));
- return files;
-}
-
/// The current user's home, or null when the environment names none.
///
/// Null rather than a throw: every caller here is a scanner, and a scanner with
diff --git a/desktop/lib/usage/ledger/ledger_types.dart b/desktop/lib/usage/ledger/ledger_types.dart
index f975a6c6a..dce1e3826 100644
--- a/desktop/lib/usage/ledger/ledger_types.dart
+++ b/desktop/lib/usage/ledger/ledger_types.dart
@@ -285,7 +285,9 @@ class LedgerDay {
/// `UsageStatus.signedOut` is kept apart from `UsageStatus.failed` — a machine
/// with no OpenCode installed will never be fixed by retrying, and offering a
/// Retry there fails identically forever.
-enum LedgerStatus { disabled, scanning, ok, unavailable, failed }
+/// [partial] keeps readable figures with a visible warning when another source
+/// could not be read. It never represents a complete total or fresh cache.
+enum LedgerStatus { disabled, scanning, ok, partial, unavailable, failed }
/// Where one provider's scan stands.
class LedgerScanState {
@@ -305,13 +307,17 @@ class LedgerScanState {
/// switching it off must not be mistaken for it having nothing to say.
final bool enabled;
- /// When the last successful scan finished. Null until one has.
+ /// When the last complete or partial scan finished. Null until one has.
final DateTime? lastScanAt;
- /// Why there are no figures — set for [LedgerStatus.unavailable] and
- /// [LedgerStatus.failed], null otherwise.
+ /// Why figures are missing or incomplete — set for unavailable, failed, and
+ /// partial scans, null otherwise.
final String? message;
+ bool get hasIncompleteFigures =>
+ status == LedgerStatus.partial ||
+ (status == LedgerStatus.scanning && message != null);
+
LedgerScanState copyWith({
LedgerStatus? status,
bool? enabled,
diff --git a/desktop/lib/usage/ledger/model_pricing.dart b/desktop/lib/usage/ledger/model_pricing.dart
index c4eff944b..8fdde8cee 100644
--- a/desktop/lib/usage/ledger/model_pricing.dart
+++ b/desktop/lib/usage/ledger/model_pricing.dart
@@ -15,6 +15,26 @@ library;
import '../../usage/ledger/ledger_types.dart';
+// A history repeats the same model thousands of times. Resolve its naming
+// variants once, while keeping token-dependent tier arithmetic per entry.
+// Bound both count and key length because model names originate in log files.
+final _claudeModelNames = <String, String?>{};
+final _codexModelNames = <String, String?>{};
+
+String? _rememberModelName(
+ String? model,
+ Map<String, String?> cache,
+ String? Function(String) resolve,
+) {
+ if (model == null) return null;
+ if (model.length > 512) return resolve(model);
+ if (cache.containsKey(model)) return cache[model];
+ final result = resolve(model);
+ if (cache.length >= 128) cache.remove(cache.keys.first);
+ cache[model] = result;
+ return result;
+}
+
/// USD per million tokens, per bucket.
///
/// The `above` fields are the long-context tier: past [thresholdTokens] in a
@@ -231,8 +251,10 @@ bool _isLegacyBaseOpus4(String model) {
}
/// The pricing key a Claude model id maps to, or null when none does.
-String? normalizeClaudeModel(String? model) {
- if (model == null) return null;
+String? normalizeClaudeModel(String? model) =>
+ _rememberModelName(model, _claudeModelNames, _normalizeClaudeModel);
+
+String? _normalizeClaudeModel(String model) {
final lower = model.toLowerCase().trim().replaceFirst(
RegExp(r'^anthropic[/:]'),
'',
@@ -438,8 +460,10 @@ String _stripDashTiers(String model) {
}
/// The pricing key a Codex model id maps to, or null when none does.
-String? normalizeCodexModel(String? model) {
- if (model == null) return null;
+String? normalizeCodexModel(String? model) =>
+ _rememberModelName(model, _codexModelNames, _normalizeCodexModel);
+
+String? _normalizeCodexModel(String model) {
final stripped = _stripParenthesizedTier(model.toLowerCase().trim());
if (stripped == null || stripped.isEmpty) return null;
final normalized = _stripDashTiers(stripped);
diff --git a/desktop/lib/usage/ledger/opencode_ledger_scanner.dart b/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
index 380423a3c..92e17d6a3 100644
--- a/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
+++ b/desktop/lib/usage/ledger/opencode_ledger_scanner.dart
@@ -16,12 +16,17 @@ library;
import 'dart:convert';
import 'dart:io';
+import 'dart:isolate';
import 'package:sqlite3/sqlite3.dart';
import 'ledger_scanner.dart';
import 'ledger_types.dart';
+class _UnsupportedUsageFormat implements Exception {
+ const _UnsupportedUsageFormat();
+}
+
class OpenCodeLedgerScanner implements LedgerScanner {
OpenCodeLedgerScanner({
String? dataDirectory,
@@ -43,14 +48,25 @@ class OpenCodeLedgerScanner implements LedgerScanner {
}
@override
- Future<LedgerScanResult> scan(Map<String, ScannedSource> previous) async {
- final directory = _dataDirectory;
+ Future<LedgerScanResult> scan(Map<String, ScannedSource> previous) =>
+ Isolate.run(() => _scanDirectory(_dataDirectory));
+
+ static Future<LedgerScanResult> _scanDirectory(String? directory) async {
if (directory == null) {
return const LedgerScanResult.unavailable(
'No home directory to read the OpenCode database from',
);
}
- final databases = await _listDatabases(directory);
+ final List<File> databases;
+ try {
+ databases = await _listDatabases(directory);
+ } on FileSystemException catch (error) {
+ return LedgerScanResult(
+ status: LedgerStatus.failed,
+ message:
+ 'Could not read OpenCode usage: ${error.osError?.message ?? error.message}',
+ );
+ }
if (databases.isEmpty) {
return const LedgerScanResult.unavailable(
'No OpenCode database on this computer',
@@ -58,42 +74,50 @@ class OpenCodeLedgerScanner implements LedgerScanner {
}
final sources = <ScannedSource>[];
+ final failures = <String>[];
for (final file in databases) {
- final FileStat stat;
- try {
- stat = await file.stat();
- } on FileSystemException {
- continue;
- }
- final cached = previous[file.path];
- if (cached != null && cached.matches(stat)) {
- sources.add(cached);
- continue;
- }
- final List<LedgerEntry> entries;
try {
- entries = _read(file.path);
- } on SqliteException catch (error) {
- // One unreadable database must not hide the others, but a machine whose
- // only database is locked or corrupt has to say so rather than report an
- // empty ledger as though nothing had been spent.
- if (databases.length == 1) {
- return LedgerScanResult.unavailable(
- 'Could not read the OpenCode database: ${error.message}',
- );
+ final stat = await file.stat();
+ if (stat.type != FileSystemEntityType.file) {
+ failures.add('A database is no longer available.');
+ continue;
}
- continue;
+ // The main database can keep its size and mtime while commits change
+ // only its WAL. WAL files can also be reused. Query SQLite's committed
+ // snapshot on every requested scan instead of trusting file metadata.
+ // This aggregate query runs off the UI isolate; the store still avoids
+ // rescanning on every visit through its five-minute snapshot lifetime.
+ final entries = _read(file.path);
+ sources.add(
+ ScannedSource(
+ path: file.path,
+ mtimeMs: stat.modified.millisecondsSinceEpoch,
+ size: stat.size,
+ entries: entries,
+ ),
+ );
+ } on SqliteException catch (error) {
+ failures.add(error.message);
+ } on FileSystemException catch (error) {
+ failures.add(error.osError?.message ?? error.message);
+ } on _UnsupportedUsageFormat {
+ failures.add('This OpenCode usage format is not supported yet.');
}
- sources.add(
- ScannedSource(
- path: file.path,
- mtimeMs: stat.modified.millisecondsSinceEpoch,
- size: stat.size,
- entries: entries,
- ),
- );
}
- return LedgerScanResult(sources: sources);
+ return LedgerScanResult(
+ sources: sources,
+ status: failures.isEmpty
+ ? LedgerStatus.ok
+ : sources.isEmpty
+ ? LedgerStatus.failed
+ : LedgerStatus.partial,
+ message: failures.isEmpty
+ ? null
+ : sources.isEmpty
+ ? 'Could not read OpenCode usage: ${failures.first}'
+ : 'Could not read ${failures.length} of ${databases.length} OpenCode databases. '
+ 'Figures are incomplete. ${failures.first}',
+ );
}
/// `opencode.db` and its siblings, canonical one first.
@@ -101,9 +125,8 @@ class OpenCodeLedgerScanner implements LedgerScanner {
/// The canonical database is the live one and must claim a duplicated session
/// ahead of a stale copy beside it; remaining ties go in path order so
/// ownership is the same on every rescan.
- Future<List<File>> _listDatabases(String directory) async {
+ static Future<List<File>> _listDatabases(String directory) async {
final dir = Directory(directory);
- if (!await dir.exists()) return const [];
final pattern = RegExp(r'^opencode(?:-[A-Za-z0-9_.-]+)?\.db$');
final files = <File>[];
try {
@@ -111,8 +134,9 @@ class OpenCodeLedgerScanner implements LedgerScanner {
if (entity is! File) continue;
if (pattern.hasMatch(entity.uri.pathSegments.last)) files.add(entity);
}
- } on FileSystemException {
- return const [];
+ } on FileSystemException catch (error) {
+ if (error.osError?.errorCode == 2) return const [];
+ rethrow;
}
files.sort((a, b) {
final aRank = a.uri.pathSegments.last == 'opencode.db' ? 0 : 1;
@@ -123,24 +147,29 @@ class OpenCodeLedgerScanner implements LedgerScanner {
return files;
}
- List<LedgerEntry> _read(String path) {
+ static List<LedgerEntry> _read(String path) {
// Read-only, so a scan can never write to a database the CLI owns — and
// opening a live WAL database this way is fine, which is the case that
// matters since OpenCode may be running while this scan happens.
final db = sqlite3.open(path, mode: OpenMode.readOnly);
try {
- if (!_hasTable(db, 'session')) return const [];
+ if (!_hasTable(db, 'session')) throw const _UnsupportedUsageFormat();
final columns = _columns(db, 'session');
// Newer OpenCode keeps per-session totals. One aggregate row per session
// is both cheaper and more accurate than re-adding every message blob.
const required = [
+ 'id',
+ 'directory',
+ 'time_created',
'cost',
'tokens_input',
'tokens_output',
'tokens_reasoning',
'tokens_cache_read',
];
- if (!required.every(columns.contains)) return const [];
+ if (!required.every(columns.contains)) {
+ throw const _UnsupportedUsageFormat();
+ }
final hasCacheWrite = columns.contains('tokens_cache_write');
final hasModel = columns.contains('model');
@@ -150,7 +179,8 @@ class OpenCodeLedgerScanner implements LedgerScanner {
'${hasCacheWrite ? ', tokens_cache_write' : ''}'
'${hasModel ? ', model' : ''} '
'FROM session '
- 'WHERE tokens_input + tokens_output + tokens_reasoning + tokens_cache_read > 0 '
+ 'WHERE tokens_input > 0 OR tokens_output > 0 OR tokens_reasoning > 0 OR tokens_cache_read > 0 '
+ '${hasCacheWrite ? 'OR tokens_cache_write > 0 ' : ''}'
'ORDER BY time_created, id',
);
@@ -163,7 +193,7 @@ class OpenCodeLedgerScanner implements LedgerScanner {
}
}
- LedgerEntry? _entry(
+ static LedgerEntry? _entry(
Row row, {
required bool hasCacheWrite,
required bool hasModel,
diff --git a/desktop/lib/usage/ledger/usage_ledger_controller.dart b/desktop/lib/usage/ledger/usage_ledger_controller.dart
index de7f4c19f..930f8de90 100644
--- a/desktop/lib/usage/ledger/usage_ledger_controller.dart
+++ b/desktop/lib/usage/ledger/usage_ledger_controller.dart
@@ -57,11 +57,15 @@ class UsageLedgerController extends ChangeNotifier {
final List<UsageLedgerStore> stores;
bool _loaded = false;
+ bool _disposed = false;
+ Future<void>? _loading;
+ final _overviews = <UsageRange, ({DateTime? cutoff, UsageOverview value})>{};
/// Whether [load] has finished. Before it has, the panel knows nothing — not
/// even which providers are switched on — and draws its skeleton rather than
/// an empty state that would be a claim.
bool get loaded => _loaded;
+ bool get loading => _loading != null && !_loaded;
UsageLedgerStore storeFor(LedgerProvider provider) =>
stores.firstWhere((store) => store.provider == provider);
@@ -71,16 +75,22 @@ class UsageLedgerController extends ChangeNotifier {
/// The reads run together because one store's disk has nothing to say about
/// another's, and three sequential `~/.harness` reads is three chances to make
/// the panel wait.
- Future<void> load() async {
+ Future<void> load() => _loading ??= _load();
+
+ Future<void> _load() async {
+ if (_disposed) return;
await Future.wait([for (final store in stores) store.load()]);
+ if (_disposed) return;
_loaded = true;
- notifyListeners();
- await refresh();
+ final rescanning = refresh();
+ if (!_disposed) notifyListeners();
+ await rescanning;
}
/// Rescan every enabled provider. A disabled one returns immediately.
- Future<void> refresh({bool force = false}) =>
- Future.wait([for (final store in stores) store.refresh(force: force)]);
+ Future<void> refresh({bool force = false}) => _disposed
+ ? Future.value()
+ : Future.wait([for (final store in stores) store.refresh(force: force)]);
/// True while any provider is mid-scan — what the refresh button spins on.
bool get isScanning =>
@@ -95,13 +105,23 @@ class UsageLedgerController extends ChangeNotifier {
/// The range is applied here rather than at scan time, so changing it redraws
/// from what is already in memory instead of re-walking the disk — the scan is
/// the expensive half and it does not depend on the window being looked at.
- UsageOverview overviewFor(UsageRange range, {DateTime? now}) => buildOverview(
- ledgers: [
- for (final store in stores) clipLedger(store.ledger, range, now: now),
- ],
- enabledCount: stores.where((store) => store.state.enabled).length,
- lastScanAt: _lastScanAt,
- );
+ UsageOverview overviewFor(UsageRange range, {DateTime? now}) {
+ final at = now ?? DateTime.now();
+ final cutoff = range.cutoff(now: at);
+ final cached = _overviews[range];
+ if (cached != null && cached.cutoff == cutoff) return cached.value;
+ final value = buildOverview(
+ ledgers: [
+ for (final store in stores) clipLedger(store.ledger, range, now: at),
+ ],
+ enabledCount: stores.where((store) => store.state.enabled).length,
+ lastScanAt: _lastScanAt,
+ );
+ // At most one result per range; midnight changes the cutoff even when no
+ // provider has emitted new data. Stats/UI rebuilds can reuse these totals.
+ _overviews[range] = (cutoff: cutoff, value: value);
+ return value;
+ }
/// The most recent scan across the providers.
///
@@ -119,10 +139,14 @@ class UsageLedgerController extends ChangeNotifier {
return latest;
}
- void _onStoreChanged() => notifyListeners();
+ void _onStoreChanged() {
+ _overviews.clear();
+ if (!_disposed) notifyListeners();
+ }
@override
void dispose() {
+ _disposed = true;
for (final store in stores) {
store.removeListener(_onStoreChanged);
store.dispose();
diff --git a/desktop/lib/usage/ledger/usage_ledger_store.dart b/desktop/lib/usage/ledger/usage_ledger_store.dart
index 02ccdd847..be47285b4 100644
--- a/desktop/lib/usage/ledger/usage_ledger_store.dart
+++ b/desktop/lib/usage/ledger/usage_ledger_store.dart
@@ -12,6 +12,7 @@
/// [enabled] defaults false and [refresh] returns without looking when it is.
library;
+import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
@@ -43,7 +44,9 @@ const kLedgerStaleAfter = Duration(minutes: 5);
/// corrected it, because those fingerprints go on matching forever — only a
/// version bump discards the stale rows. `usage_ledger_test.dart` pins the
/// serialised key set so the next field cannot be added quietly.
-const _kCacheVersion = 2;
+// Version 2 could cache failed JSONL reads as empty successful files, whose
+// unchanged size/mtime then hid their usage even after access was restored.
+const _kCacheVersion = 3;
class UsageLedgerStore extends ChangeNotifier {
UsageLedgerStore({
@@ -71,8 +74,36 @@ class UsageLedgerStore extends ChangeNotifier {
Map<String, ScannedSource> _sources = const {};
Future<void>? _inFlight;
+ int? _scanRevision;
+ Future<void>? _loading;
+ int _revision = 0;
+ bool _hasExplicitChoice = false;
bool _disposed = false;
+ // Reopening Settings creates new stores. Those stores must wait for an Off
+ // already being persisted by the previous screen before restoring a cache.
+ // The shared settings instance identifies the same user's persistence;
+ // providers still write independently of one another.
+ static final _writes = Expando<Map<LedgerProvider, Future<void>>>();
+ Map<LedgerProvider, Future<void>> get _writeQueue =>
+ _writes[_settings] ??= {};
+ Future<void> get _persisted => _writeQueue[provider] ?? Future.value();
+
+ bool _current(int revision) => !_disposed && revision == _revision;
+
+ Future<void> _persist(Future<void> Function() operation) {
+ final next = _persisted.then((_) async {
+ try {
+ await operation();
+ } on Object {
+ // Persistence is best effort. An in-session toggle still takes effect,
+ // and one failed write must not prevent a following cache clear.
+ }
+ });
+ _writeQueue[provider] = next;
+ return next;
+ }
+
LedgerScanState get state => _state;
ProviderLedger get ledger => _ledger;
@@ -83,45 +114,58 @@ class UsageLedgerStore extends ChangeNotifier {
/// Never throws: a cache that cannot be read is a cache that is not there, and
/// a panel that failed to open because last week's snapshot was truncated
/// would be a worse bug than a rescan.
- Future<void> load() async {
- _state = LedgerScanState(provider: provider);
- _ledger = ProviderLedger(provider: provider);
+ Future<void> load() => _loading ??= _load(_revision);
+
+ Future<void> _load(int revision) async {
+ if (_disposed || _hasExplicitChoice) return;
try {
+ await _persisted;
+ if (!_current(revision)) return;
final enabled = await _settings.read(_enabledKey) == 'true';
- _state = _state.copyWith(enabled: enabled);
- if (enabled) await _loadCache();
+ if (!_current(revision)) return;
+ final cache = enabled ? await _readCache().onError((_, _) => null) : null;
+ if (!_current(revision)) return;
+ _sources = cache?.sources ?? const {};
+ _ledger = buildProviderLedger(provider, _sources.values);
+ _state = LedgerScanState(
+ provider: provider,
+ enabled: enabled,
+ status: cache == null ? LedgerStatus.disabled : LedgerStatus.ok,
+ lastScanAt: cache?.scannedAt,
+ );
} on Object {
- // Fall through to the empty state this method already installed.
+ // An unreadable preference/cache leaves the initial empty state.
}
- _notify();
+ if (_current(revision)) _notify();
}
- Future<void> _loadCache() async {
+ Future<({Map<String, ScannedSource> sources, DateTime? scannedAt})?>
+ _readCache() async {
final contents = await _snapshots.read();
- if (contents == null) return;
+ if (contents == null) return null;
final Object? decoded;
try {
decoded = jsonDecode(contents);
} on Object {
- return;
+ return null;
+ }
+ if (decoded is! Map<String, Object?> ||
+ decoded['version'] != _kCacheVersion ||
+ decoded['provider'] != provider.name) {
+ return null;
}
- if (decoded is! Map<String, Object?>) return;
- if (decoded['version'] != _kCacheVersion) return;
final sources = decoded['sources'];
- if (sources is! List) return;
+ if (sources is! List) return null;
final restored = <String, ScannedSource>{};
for (final raw in sources) {
if (raw is! Map<String, Object?>) continue;
final source = ScannedSource.fromJson(provider, raw);
if (source != null) restored[source.path] = source;
}
- _sources = restored;
- _ledger = buildProviderLedger(provider, _sources.values);
- final scannedAt = DateTime.tryParse('${decoded['lastScanAt']}');
- _state = _state.copyWith(
- status: _ledger.hasData ? LedgerStatus.ok : _state.status,
- lastScanAt: scannedAt,
+ return (
+ sources: restored,
+ scannedAt: DateTime.tryParse('${decoded['lastScanAt']}'),
);
}
@@ -130,29 +174,31 @@ class UsageLedgerStore extends ChangeNotifier {
/// Switching off drops the snapshot from memory AND from disk. Keeping it
/// would mean a provider the user turned off still had its transcripts
/// summarised in a file on their machine, which is not what "off" reads as.
- Future<void> setEnabled(bool enabled) async {
- if (_state.enabled == enabled) return;
- _state = _state.copyWith(
+ Future<void> setEnabled(bool enabled) {
+ if (_disposed) return Future.value();
+ if (_hasExplicitChoice && _state.enabled == enabled) {
+ return enabled ? refresh() : _persisted;
+ }
+ _hasExplicitChoice = true;
+ final revision = ++_revision;
+ _state = LedgerScanState(
+ provider: provider,
enabled: enabled,
status: enabled ? LedgerStatus.scanning : LedgerStatus.disabled,
- clearMessage: true,
);
- _notify();
- try {
- await _settings.write(_enabledKey, '$enabled');
- } on Object {
- // A switch that could not be persisted still holds for this session; the
- // alternative is refusing an action the user can see took effect.
- }
+ var saved = _persist(() => _settings.write(_enabledKey, '$enabled'));
if (!enabled) {
_sources = const {};
_ledger = ProviderLedger(provider: provider);
- _state = _state.copyWith(status: LedgerStatus.disabled, lastScanAt: null);
- await _snapshots.clear();
- _notify();
- return;
+ saved = _persist(_snapshots.clear);
}
- await refresh(force: true);
+ // Queue persistence before notifying: a listener can make the next choice
+ // synchronously, and the writes must retain that same order.
+ _notify();
+ return Future.wait([
+ saved,
+ if (enabled && _current(revision)) refresh(force: true),
+ ]);
}
/// Rescan if the last result has gone stale, or [force] regardless.
@@ -160,66 +206,127 @@ class UsageLedgerStore extends ChangeNotifier {
/// Concurrent calls share one scan rather than queueing a second walk of the
/// same disk.
Future<void> refresh({bool force = false}) {
- if (!_state.enabled) return Future.value();
+ if (_disposed || !_state.enabled) return Future.value();
+ final revision = _revision;
+ if (_inFlight case final pending?) {
+ if (_scanRevision == revision &&
+ (_state.status == LedgerStatus.scanning ||
+ (!force && _state.status == LedgerStatus.ok))) {
+ return pending;
+ }
+ // Off/On invalidates the old result, but cannot cancel a scanner's disk
+ // operation. Finish that read before starting the newly requested one.
+ // A Retry after a visible failure also waits for the old cache clear,
+ // then starts a fresh read instead of joining the finished failure.
+ return pending.then((_) async {
+ if (_current(revision) && _state.enabled) await refresh(force: force);
+ });
+ }
final lastScanAt = _state.lastScanAt;
if (!force &&
+ _state.status == LedgerStatus.ok &&
lastScanAt != null &&
DateTime.now().difference(lastScanAt) < kLedgerStaleAfter) {
return Future.value();
}
- return _inFlight ??= _run().whenComplete(() => _inFlight = null);
+ final done = Completer<void>();
+ _inFlight = done.future;
+ _scanRevision = revision;
+ // Install the shared future before _run notifies synchronous listeners.
+ unawaited(
+ _run(revision).then(
+ (_) {
+ _inFlight = null;
+ _scanRevision = null;
+ done.complete();
+ },
+ onError: (Object error, StackTrace stack) {
+ _inFlight = null;
+ _scanRevision = null;
+ done.completeError(error, stack);
+ },
+ ),
+ );
+ return done.future;
}
- Future<void> _run() async {
- _state = _state.copyWith(status: LedgerStatus.scanning, clearMessage: true);
+ Future<void> _run(int revision) async {
+ _state = _state.copyWith(
+ status: LedgerStatus.scanning,
+ clearMessage: _state.status != LedgerStatus.partial,
+ );
_notify();
+ if (!_current(revision) || !_state.enabled) return;
LedgerScanResult result;
try {
result = await scanner.scan(_sources);
} on Object catch (error) {
- _state = _state.copyWith(
- status: LedgerStatus.failed,
- message: 'Could not read ${provider.label} usage: $error',
+ await _failed(
+ revision,
+ LedgerStatus.failed,
+ 'Could not read ${provider.label} usage: $error',
);
- _notify();
return;
}
- if (_disposed) return;
+ if (!_current(revision) || !_state.enabled) return;
- if (result.status != LedgerStatus.ok) {
+ if (result.status != LedgerStatus.ok &&
+ result.status != LedgerStatus.partial) {
// The sources are dropped with the result: a provider that has become
// unavailable must not keep showing the totals from when it was not.
- _sources = const {};
- _ledger = ProviderLedger(provider: provider);
- _state = _state.copyWith(
- status: result.status,
- message: result.message,
- clearMessage: result.message == null,
- );
- _notify();
+ await _failed(revision, result.status, result.message);
return;
}
_sources = {for (final source in result.sources) source.path: source};
_ledger = buildProviderLedger(provider, _sources.values);
_state = _state.copyWith(
- status: LedgerStatus.ok,
+ status: result.status,
lastScanAt: DateTime.now(),
- clearMessage: true,
+ message: result.message,
+ clearMessage: result.status == LedgerStatus.ok,
);
+ if (result.status == LedgerStatus.partial) {
+ // Keep readable figures in this view, but never restore an incomplete
+ // snapshot as a fresh complete result when Settings is reopened.
+ final cleared = _persist(_snapshots.clear);
+ _notify();
+ await cleared;
+ return;
+ }
_notify();
- await _writeCache();
+ await _persist(() async {
+ if (!_current(revision) || !_state.enabled) return;
+ await _snapshots.write(
+ jsonEncode({
+ 'version': _kCacheVersion,
+ 'provider': provider.name,
+ 'lastScanAt': _state.lastScanAt?.toIso8601String(),
+ 'sources': [for (final source in _sources.values) source.toJson()],
+ }),
+ );
+ });
}
- Future<void> _writeCache() => _snapshots.write(
- jsonEncode({
- 'version': _kCacheVersion,
- 'provider': provider.name,
- 'lastScanAt': _state.lastScanAt?.toIso8601String(),
- 'sources': [for (final source in _sources.values) source.toJson()],
- }),
- );
+ Future<void> _failed(
+ int revision,
+ LedgerStatus status,
+ String? message,
+ ) async {
+ if (!_current(revision) || !_state.enabled) return;
+ _sources = const {};
+ _ledger = ProviderLedger(provider: provider);
+ _state = LedgerScanState(
+ provider: provider,
+ enabled: true,
+ status: status,
+ message: message,
+ );
+ final cleared = _persist(_snapshots.clear);
+ _notify();
+ await cleared;
+ }
void _notify() {
if (!_disposed) notifyListeners();
diff --git a/desktop/lib/usage/usage_accounts.dart b/desktop/lib/usage/usage_accounts.dart
index db63a25a6..790a79264 100644
--- a/desktop/lib/usage/usage_accounts.dart
+++ b/desktop/lib/usage/usage_accounts.dart
@@ -111,8 +111,7 @@ ProviderUsage? _readingFor(
UsageProvider provider,
) => _firstWhereOrNull(readings, (reading) => reading.provider == provider);
-/// A plain loop rather than `firstWhereOrNull`: `package:collection` is not a
-/// dependency of this project, and a three-line lookup is not worth adding one.
+/// The first matching reading, or null when this provider has no reading.
T? _firstWhereOrNull<T>(Iterable<T> items, bool Function(T) test) {
for (final item in items) {
if (test(item)) return item;
diff --git a/desktop/lib/viewer/direct_auth.dart b/desktop/lib/viewer/direct_auth.dart
index 8f7a9b69e..88a96c218 100644
--- a/desktop/lib/viewer/direct_auth.dart
+++ b/desktop/lib/viewer/direct_auth.dart
@@ -11,31 +11,86 @@ class DirectAuth implements AccessTokenSource {
final AuthSession session;
final DirectAuthApi api;
Future<String>? _refreshing;
+ Future<void> _writes = Future<void>.value();
+ int _revision = 0;
static const _refreshSkew = Duration(seconds: 60);
- Future<bool> hasSession() async =>
- ((await session.accessToken()) ?? '').isNotEmpty;
+ Future<bool> hasSession() async {
+ final revision = _revision;
+ await _writes;
+ final token = await session.accessToken();
+ _requireCurrent(revision);
+ return (token ?? '').isNotEmpty;
+ }
- Future<void> signIn(IssuedTokens tokens) => session.saveLogin(
- token: tokens.token,
- refreshToken: tokens.refreshToken,
- autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,
- expiresIn: tokens.expiresIn,
- );
+ Future<void> signIn(IssuedTokens tokens, {bool Function()? stillCurrent}) {
+ final revision = ++_revision;
+ _refreshing = null;
+ return _write(revision, () async {
+ if (stillCurrent?.call() == false) throw _changed;
+ await session.saveLogin(
+ token: tokens.token,
+ refreshToken: tokens.refreshToken,
+ autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,
+ expiresIn: tokens.expiresIn,
+ );
+ // Cancel can land during a disk write. These writes are serialized, so
+ // clearing this incomplete login cannot erase a newer queued login.
+ if (stillCurrent?.call() == false) {
+ await session.clear();
+ throw _changed;
+ }
+ });
+ }
+
+ Future<void> signOut() {
+ final revision = ++_revision;
+ _refreshing = null;
+ return _write(revision, session.clear);
+ }
- Future<void> signOut() => session.clear();
+ // A stale request is no longer allowed to decide that the CURRENT account
+ // is signed out. Its caller may discard or retry it without losing a login.
+ static const _changed = DirectAuthException('Sign-in changed. Try again.');
+
+ void _requireCurrent(int revision) {
+ if (revision != _revision) throw _changed;
+ }
+
+ Future<void> _write(int revision, Future<void> Function() action) {
+ final result = _writes.then((_) async {
+ _requireCurrent(revision);
+ await action();
+ _requireCurrent(revision);
+ });
+ // Keep the queue usable after an I/O failure or a cancelled operation.
+ _writes = result.then<void>((_) {}, onError: (Object _) {});
+ return result;
+ }
@override
Future<String> accessToken({bool force = false, String? failedToken}) async {
+ final revision = _revision;
+ await _writes;
final current = await session.accessToken();
+ _requireCurrent(revision);
if (current == null || current.isEmpty) {
throw const DirectAuthException('Not signed in.', signedOut: true);
}
// Someone else already refreshed past the token that failed — use theirs.
if (failedToken != null && failedToken != current) return current;
- if (!force && !await _isStale()) return current;
- return _refreshing ??= _refresh().whenComplete(() => _refreshing = null);
+ if (!force) {
+ final stale = await _isStale();
+ _requireCurrent(revision);
+ if (!stale) return current;
+ }
+ if (_refreshing case final pending?) return pending;
+ late final Future<String> refreshing;
+ refreshing = _refresh(revision).whenComplete(() {
+ if (identical(_refreshing, refreshing)) _refreshing = null;
+ });
+ return _refreshing = refreshing;
}
Future<bool> _isStale() async {
@@ -44,10 +99,11 @@ class DirectAuth implements AccessTokenSource {
expiresAt.isBefore(DateTime.now().toUtc().add(_refreshSkew));
}
- Future<String> _refresh() async {
+ Future<String> _refresh(int revision) async {
final refreshToken = await session.refreshToken();
+ _requireCurrent(revision);
if (refreshToken == null || refreshToken.isEmpty) {
- await session.clear();
+ await signOut();
throw const DirectAuthException(
'Your sign-in expired. Sign in again.',
signedOut: true,
@@ -55,16 +111,25 @@ class DirectAuth implements AccessTokenSource {
}
try {
final autonomousEnv = await session.autonomousEnv();
- final tokens = await api.refresh(refreshToken, autonomousEnv: autonomousEnv);
- await session.saveRefresh(
- token: tokens.token,
- refreshToken: tokens.refreshToken,
+ _requireCurrent(revision);
+ final tokens = await api.refresh(
+ refreshToken,
autonomousEnv: autonomousEnv,
- expiresIn: tokens.expiresIn,
+ );
+ _requireCurrent(revision);
+ await _write(
+ revision,
+ () => session.saveRefresh(
+ token: tokens.token,
+ refreshToken: tokens.refreshToken,
+ autonomousEnv: autonomousEnv,
+ expiresIn: tokens.expiresIn,
+ ),
);
return tokens.token;
} on DirectAuthException catch (error) {
- if (error.signedOut) await session.clear();
+ _requireCurrent(revision);
+ if (error.signedOut) await signOut();
rethrow;
}
}
diff --git a/desktop/lib/viewer/direct_login.dart b/desktop/lib/viewer/direct_login.dart
index 902bbcc44..077f0f7e3 100644
--- a/desktop/lib/viewer/direct_login.dart
+++ b/desktop/lib/viewer/direct_login.dart
@@ -16,6 +16,7 @@ class DirectLogin implements SignInClient {
final DirectAuth auth;
_LoopbackCallback? _pending;
+ int _loginRevision = 0;
static const _callbackTimeout = Duration(minutes: 5);
@@ -27,47 +28,74 @@ class DirectLogin implements SignInClient {
Future<void> login({
required void Function(String url) onAuthorizeUrl,
}) async {
+ cancel();
+ final revision = _loginRevision;
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
- final callback = _pending = _LoopbackCallback(server);
+ _LoopbackCallback? callback;
try {
+ _requireCurrent(revision);
+ callback = _pending = _LoopbackCallback(server);
final start = await auth.api.authorizeNative(
'http://127.0.0.1:${server.port}/callback',
);
+ _requireCurrent(revision);
onAuthorizeUrl(start.authorizeUrl);
+ _requireCurrent(revision);
final redirect = await callback.result.timeout(
_callbackTimeout,
onTimeout: () => throw const DirectAuthException('Sign-in timed out.'),
);
- await auth.signIn(
- await auth.api.exchange(
- code: redirect.code,
- state: redirect.state,
- tx: start.tx,
- ),
+ _requireCurrent(revision);
+ if (redirect == null) throw callback.error!;
+ final tokens = await auth.api.exchange(
+ code: redirect.code,
+ state: redirect.state,
+ tx: start.tx,
);
+ _requireCurrent(revision);
+ await auth.signIn(tokens, stillCurrent: () => revision == _loginRevision);
+ _requireCurrent(revision);
} finally {
- _pending = null;
+ if (identical(_pending, callback)) _pending = null;
await server.close(force: true);
}
}
@override
- void cancel() => _pending?.cancel();
+ void cancel() {
+ ++_loginRevision;
+ final callback = _pending;
+ _pending = null;
+ callback?.cancel();
+ }
+
+ void _requireCurrent(int revision) {
+ if (revision != _loginRevision) {
+ throw const DirectAuthException('Sign-in was cancelled.');
+ }
+ }
@override
- Future<void> logout() => auth.signOut();
+ Future<void> logout() {
+ cancel();
+ return auth.signOut();
+ }
}
/// The loopback end of the redirect: the first `/callback` carrying `code` and `state` completes
/// it and an `error` fails it; anything else the browser asks for (a favicon) is turned away.
class _LoopbackCallback {
- _LoopbackCallback(HttpServer server) {
- server.listen(_onRequest);
+ _LoopbackCallback(this._server) {
+ _server.listen(_onRequest);
}
- final _completer = Completer<({String code, String state})>();
+ final HttpServer _server;
+ // Cancellation can precede the authorization response and its listener.
+ // Keep the outcome as data until login awaits it, without an unhandled error.
+ final _completer = Completer<({String code, String state})?>();
+ DirectAuthException? error;
- Future<({String code, String state})> get result => _completer.future;
+ Future<({String code, String state})?> get result => _completer.future;
Future<void> _onRequest(HttpRequest request) async {
final response = request.response;
@@ -82,21 +110,29 @@ class _LoopbackCallback {
response
..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest
..headers.contentType = ContentType.html
- ..write(_page(signedIn ? 'Signed in to OpenHarness' : 'OpenHarness sign-in failed'));
+ ..write(
+ _page(
+ signedIn ? 'Signed in to OpenHarness' : 'OpenHarness sign-in failed',
+ ),
+ );
await response.close();
if (_completer.isCompleted) return;
if (signedIn) {
_completer.complete((code: code, state: state));
} else {
- _completer.completeError(
- DirectAuthException('Sign-in failed: ${error ?? 'no code returned'}'),
+ this.error = DirectAuthException(
+ 'Sign-in failed: ${error ?? 'no code returned'}',
);
+ _completer.complete(null);
}
}
void cancel() {
- if (_completer.isCompleted) return;
- _completer.completeError(const DirectAuthException('Sign-in was cancelled.'));
+ if (!_completer.isCompleted) {
+ error = const DirectAuthException('Sign-in was cancelled.');
+ _completer.complete(null);
+ }
+ unawaited(_server.close(force: true));
}
}
diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dart
index de1fab464..0477b1632 100644
--- a/desktop/lib/widgets/agent_picker.dart
+++ b/desktop/lib/widgets/agent_picker.dart
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
+import 'box_chrome.dart';
import 'search_result_text.dart';
import 'swarm_search_input.dart';
import 'swarm_switcher.dart' show SwarmSearchActionLabel, swarmSearchRowHeight;
@@ -72,6 +73,7 @@ class AgentPicker extends StatefulWidget {
this.focusNode,
this.height = 64,
this.width,
+ this.terminalStyle = false,
});
final String value;
@@ -104,6 +106,7 @@ class AgentPicker extends StatefulWidget {
/// LayoutBuilder builds its children during layout, after the rest of the
/// dialog, and Flutter orders Tab by when a focus node attached.
final double? width;
+ final bool terminalStyle;
/// What the search input says before anything is typed.
static const hint = 'Choose an agent for what you’d like to make';
@@ -123,11 +126,13 @@ class AgentPicker extends StatefulWidget {
class _AgentPickerState extends State<AgentPicker> {
final _portal = OverlayPortalController();
- final _link = LayerLink();
final _query = TextEditingController();
final _inputFocus = FocusNode(debugLabel: 'Agent search input');
final _ownBarFocus = FocusNode(debugLabel: 'Agent search');
final _scroll = ScrollController();
+ final _previewScroll = ScrollController();
+ final _pointer = BoxPointerGate();
+ bool _previewVisible = false;
/// The search input and everything in the panel are one tap region. On a
/// desktop, a mouse press outside a text field's region unfocuses it, and
@@ -138,16 +143,16 @@ class _AgentPickerState extends State<AgentPicker> {
int _cursor = 0;
- /// The bar's box when the panel opened: where the panel goes, and how much
- /// of the window is left under it.
- Rect _anchor = Rect.zero;
- Size _overlaySize = Size.zero;
-
bool get _open => _portal.isShowing;
String get _needle => _query.text.trim().toLowerCase();
/// The type in the bar and the panel's input, grown with the bar.
- double get _fontSize => widget.height >= 88 ? 20 : 17;
+ double get _fontSize => widget.terminalStyle
+ ? 13
+ : widget.height >= 88
+ ? 20
+ : 17;
+ double get _radius => widget.terminalStyle ? 2 : AgentPicker.radius;
@override
void initState() {
@@ -173,6 +178,7 @@ class _AgentPickerState extends State<AgentPicker> {
_inputFocus.dispose();
_ownBarFocus.dispose();
_scroll.dispose();
+ _previewScroll.dispose();
super.dispose();
}
@@ -247,13 +253,6 @@ class _AgentPickerState extends State<AgentPicker> {
List<AgentChoice> get _rows => _needle.isEmpty ? _recent : _matches;
void _show({String initial = ''}) {
- final box = context.findRenderObject() as RenderBox?;
- final overlay =
- Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?;
- if (box != null && box.hasSize && overlay != null && overlay.hasSize) {
- _anchor = box.localToGlobal(Offset.zero, ancestor: overlay) & box.size;
- _overlaySize = overlay.size;
- }
_query.value = TextEditingValue(
text: initial,
selection: TextSelection.collapsed(offset: initial.length),
@@ -316,8 +315,9 @@ class _AgentPickerState extends State<AgentPicker> {
});
}
- static double _rowHeight(TextScaler scaler) =>
- swarmSearchRowHeight(scaler, commands: false);
+ double _rowHeight(TextScaler scaler) => widget.terminalStyle
+ ? math.max(46, scaler.scale(13) * 1.35 + scaler.scale(12) * 1.35 + 12)
+ : swarmSearchRowHeight(scaler, commands: false);
/// The closed bar opens on the keys that start a search: Return, Space,
/// an arrow, or the first letter of what you are looking for.
@@ -358,11 +358,13 @@ class _AgentPickerState extends State<AgentPicker> {
choice?.label ?? 'Choose an agent',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: _fontSize,
- fontWeight: FontWeight.w500,
- color: choice == null ? Colors.white60 : Colors.white,
- ),
+ style: widget.terminalStyle
+ ? boxMonoStyle()
+ : TextStyle(
+ fontSize: _fontSize,
+ fontWeight: FontWeight.w500,
+ color: choice == null ? Colors.white60 : Colors.white,
+ ),
),
);
@@ -378,55 +380,65 @@ class _AgentPickerState extends State<AgentPicker> {
? AgentPicker.hint
: 'Agent: ${choice.label}. Search agents',
excludeSemantics: true,
- child: CompositedTransformTarget(
- link: _link,
- child: Material(
- key: const Key('new-agent-agent-field'),
- color: grid.AppPalette.swarmSearchSurface,
- surfaceTintColor: Colors.transparent,
- elevation: 2,
- shadowColor: Colors.black38,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AgentPicker.radius),
- side: BorderSide(
- color: focused && !_open
- ? grid.AppPalette.swarmAccent.withValues(alpha: .7)
- : Colors.white.withValues(alpha: .10),
- width: focused && !_open ? 1.5 : 1,
- ),
+ child: Material(
+ key: const Key('new-agent-agent-field'),
+ color: grid.AppPalette.swarmSearchSurface,
+ surfaceTintColor: Colors.transparent,
+ elevation: 2,
+ shadowColor: Colors.black38,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(_radius),
+ side: BorderSide(
+ color: focused && !_open
+ ? grid.AppPalette.swarmAccent.withValues(alpha: .7)
+ : Colors.white.withValues(alpha: .10),
+ width: focused && !_open ? 1.5 : 1,
),
- clipBehavior: Clip.antiAlias,
- child: InkWell(
- canRequestFocus: false,
- mouseCursor: SystemMouseCursors.click,
- hoverColor: Colors.white.withValues(alpha: .03),
- onTap: () {
- _barFocus.requestFocus();
- _show();
- },
- child: ConstrainedBox(
- constraints: BoxConstraints(minHeight: widget.height),
- child: Row(
- children: [
- SizedBox(
- width: _fontSize >= 20 ? 64 : 52,
- child: Icon(
- Icons.search,
- size: _fontSize + 4,
- color: Colors.white60,
- ),
- ),
- Expanded(child: _chosen(choice)),
- const Padding(
- padding: EdgeInsets.only(left: 12, right: 22),
- child: Icon(
- Icons.keyboard_arrow_down,
- size: 22,
- color: Colors.white60,
- ),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ canRequestFocus: false,
+ mouseCursor: SystemMouseCursors.click,
+ hoverColor: Colors.white.withValues(alpha: .03),
+ onTap: () {
+ _barFocus.requestFocus();
+ _show();
+ },
+ child: ConstrainedBox(
+ constraints: BoxConstraints(minHeight: widget.height),
+ child: Row(
+ children: [
+ SizedBox(
+ width: widget.terminalStyle
+ ? 32
+ : _fontSize >= 20
+ ? 64
+ : 52,
+ child: widget.terminalStyle
+ ? Center(
+ child: Text(
+ '>',
+ style: boxMonoStyle(
+ color: grid.AppPalette.swarmAccent,
+ ),
+ ),
+ )
+ : Icon(
+ Icons.search,
+ size: _fontSize + 4,
+ color: Colors.white60,
+ ),
+ ),
+ Expanded(child: _chosen(choice)),
+ const Padding(
+ padding: EdgeInsets.only(left: 12, right: 22),
+ child: Icon(
+ Icons.keyboard_arrow_down,
+ size: 22,
+ color: Colors.white60,
),
- ],
- ),
+ ),
+ ],
),
),
),
@@ -446,9 +458,20 @@ class _AgentPickerState extends State<AgentPicker> {
composing: _composing,
actions: {
'picker.accept': () => run(_accept),
+ 'picker.add_here': () => run(_accept),
'picker.next': () => run(() => _move(1)),
'picker.previous': () => run(() => _move(-1)),
'picker.cancel': () => run(_close),
+ if (widget.terminalStyle)
+ 'picker.toggle_preview': () => run(_togglePreview),
+ 'picker.preview_page_down': () => run(() => _page(1)),
+ 'picker.preview_page_up': () => run(() => _page(-1)),
+ // Tab is a picker command now (the box completes paths with it); a
+ // matched key is consumed, so here it must still move the focus.
+ 'picker.complete': () =>
+ run(() => FocusManager.instance.primaryFocus?.nextFocus()),
+ 'picker.complete_back': () =>
+ run(() => FocusManager.instance.primaryFocus?.previousFocus()),
},
child: Actions(
// The panel lives in an overlay, where EditableText's Escape would
@@ -456,7 +479,21 @@ class _AgentPickerState extends State<AgentPicker> {
actions: {
DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
},
- child: child,
+ // The host gets first use of configured bindings. Any unbound
+ // modified Enter still belongs to this picker, not to the form's
+ // creation shortcut underneath it (including during composition).
+ child: CallbackShortcuts(
+ bindings: {
+ for (final key in [
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.numpadEnter,
+ ]) ...{
+ SingleActivator(key, meta: true): () {},
+ SingleActivator(key, control: true): () {},
+ },
+ },
+ child: child,
+ ),
),
);
}
@@ -465,6 +502,13 @@ class _AgentPickerState extends State<AgentPicker> {
const SingleActivator(LogicalKeyboardKey.enter): () => run(_accept),
const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>
run(_accept),
+ for (final key in [
+ LogicalKeyboardKey.enter,
+ LogicalKeyboardKey.numpadEnter,
+ ]) ...{
+ SingleActivator(key, meta: true): () => run(_accept),
+ SingleActivator(key, control: true): () => run(_accept),
+ },
const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
run(() => _move(1)),
const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
@@ -478,54 +522,93 @@ class _AgentPickerState extends State<AgentPicker> {
const SingleActivator(LogicalKeyboardKey.keyK, control: true): () =>
run(() => _move(-1)),
const SingleActivator(LogicalKeyboardKey.escape): () => run(_close),
+ const SingleActivator(LogicalKeyboardKey.keyC, control: true): () =>
+ run(_close),
+ if (widget.terminalStyle)
+ const SingleActivator(LogicalKeyboardKey.slash, control: true): () =>
+ run(_togglePreview),
+ const SingleActivator(LogicalKeyboardKey.pageDown): () =>
+ run(() => _page(1)),
+ const SingleActivator(LogicalKeyboardKey.pageUp): () =>
+ run(() => _page(-1)),
},
child: child,
);
}
- Widget _panel(BuildContext context) {
+ void _togglePreview() => setState(() => _previewVisible = !_previewVisible);
+
+ void _queryChanged(String _) {
+ setState(() => _cursor = 0);
+ if (_scroll.hasClients) _scroll.jumpTo(0);
+ }
+
+ void _page(int direction) {
+ if (_previewScroll.hasClients) {
+ final position = _previewScroll.position;
+ _previewScroll.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .9).clamp(
+ 0.0,
+ position.maxScrollExtent,
+ ),
+ );
+ } else if (_scroll.hasClients) {
+ final rows =
+ (_scroll.position.viewportDimension /
+ _rowHeight(MediaQuery.textScalerOf(context)))
+ .floor();
+ _move(direction * math.max(1, rows));
+ }
+ }
+
+ Widget _panel(BuildContext context, {required double width}) {
final scaler = MediaQuery.textScalerOf(context);
final rows = _rows;
final cursor = rows.isEmpty ? 0 : _cursor.clamp(0, rows.length - 1);
final rowHeight = _rowHeight(scaler);
- final width = _anchor.width;
final empty = rows.isEmpty;
final lines = empty ? 1 : rows.length;
- final room = math.max(
- rowHeight * 3 + 16,
- _overlaySize.height - _anchor.top - _anchor.height - 32,
- );
- final listHeight = math.min(room, lines.clamp(4, 8) * rowHeight + 16);
- final sideBySide = width >= 760;
+ final listHeight =
+ lines.clamp(widget.terminalStyle && !_previewVisible ? 1 : 4, 8) *
+ rowHeight +
+ 16;
final highlighted = empty ? null : rows[cursor];
- final results = SizedBox(
- height: listHeight,
- child: ExcludeFocus(
- child: ListView.builder(
- key: const ValueKey('new-agent-agent-list'),
- controller: _scroll,
- padding: const EdgeInsets.all(8),
- itemExtent: rowHeight,
- itemCount: lines,
- itemBuilder: (context, index) => empty
- ? Padding(
- key: const Key('new-agent-agent-search-empty'),
- padding: const EdgeInsets.symmetric(horizontal: 12),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Text(
- 'No agents match “${_query.text.trim()}”.',
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 14,
- color: Colors.white60,
- ),
- ),
+ final showPreview =
+ highlighted != null &&
+ (widget.terminalStyle ? _previewVisible : width >= 760);
+ final sideBySide = showPreview && width >= 760;
+ final preview = showPreview
+ ? _AgentPreview(
+ key: const ValueKey('new-agent-agent-preview'),
+ choice: highlighted,
+ status: widget.statusOf?.call(highlighted.id),
+ current: highlighted.id == widget.value,
+ controller: _previewScroll,
+ terminalStyle: widget.terminalStyle,
+ )
+ : null;
+ final results = ExcludeFocus(
+ child: ListView.builder(
+ key: const ValueKey('new-agent-agent-list'),
+ controller: _scroll,
+ padding: const EdgeInsets.all(8),
+ itemExtent: rowHeight,
+ itemCount: lines,
+ itemBuilder: (context, index) => empty
+ ? Padding(
+ key: const Key('new-agent-agent-search-empty'),
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Text(
+ 'No agents match “${_query.text.trim()}”.',
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 14, color: Colors.white60),
),
- )
- : _row(rows[index], index, cursor, rowHeight, width),
- ),
+ ),
+ )
+ : _row(rows[index], index, cursor, rowHeight, width),
),
);
return SizedBox(
@@ -541,64 +624,105 @@ class _AgentPickerState extends State<AgentPicker> {
elevation: 4,
shadowColor: Colors.black26,
shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(AgentPicker.radius),
+ borderRadius: BorderRadius.circular(_radius),
side: BorderSide(color: Colors.white.withValues(alpha: .10)),
),
clipBehavior: Clip.antiAlias,
- child: _keys(
- context,
- Column(
- mainAxisSize: MainAxisSize.min,
- children: [
- Semantics(
- label: 'Search agents',
- child: SwarmSearchInput(
- inputKey: const Key('new-agent-agent-search'),
- controller: _query,
- focusNode: _inputFocus,
- groupId: _tapGroup,
- search: null,
- onClose: _close,
- onChanged: (_) {
- setState(() => _cursor = 0);
- if (_scroll.hasClients) _scroll.jumpTo(0);
- },
- autofocus: false,
- showClose: true,
- hintText: AgentPicker.hint,
- rounded: true,
- prominent: true,
- height: widget.height,
- fontSize: _fontSize,
+ child: DefaultTextStyle.merge(
+ style: widget.terminalStyle ? boxMonoStyle() : const TextStyle(),
+ child: _keys(
+ context,
+ Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Semantics(
+ label: 'Search agents',
+ child: ReadlineKeys(
+ controller: _query,
+ onChanged: _queryChanged,
+ child: SwarmSearchInput(
+ inputKey: const Key('new-agent-agent-search'),
+ controller: _query,
+ focusNode: _inputFocus,
+ groupId: _tapGroup,
+ search: null,
+ onClose: _close,
+ onChanged: _queryChanged,
+ autofocus: false,
+ showClose: !widget.terminalStyle,
+ hintText: AgentPicker.hint,
+ rounded: !widget.terminalStyle,
+ prominent: !widget.terminalStyle,
+ prompt: widget.terminalStyle ? '>' : null,
+ height: widget.height,
+ fontSize: _fontSize,
+ ),
+ ),
),
- ),
- Padding(
- padding: const EdgeInsets.only(bottom: 8),
- child: sideBySide && highlighted != null
- ? SizedBox(
- height: listHeight,
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Expanded(flex: 5, child: results),
- const SizedBox(width: 8),
- Expanded(
- flex: 5,
- child: _AgentPreview(
- key: const ValueKey(
- 'new-agent-agent-preview',
- ),
- choice: highlighted,
- status: widget.statusOf?.call(highlighted.id),
- current: highlighted.id == widget.value,
- ),
- ),
- ],
+ Flexible(
+ child: Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: SizedBox(
+ height: listHeight,
+ child: sideBySide
+ ? Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(flex: 5, child: results),
+ const SizedBox(width: 8),
+ Expanded(flex: 5, child: preview!),
+ ],
+ )
+ : showPreview
+ ? Column(
+ children: [
+ Expanded(flex: 11, child: results),
+ Expanded(flex: 9, child: preview!),
+ ],
+ )
+ : results,
+ ),
+ ),
+ ),
+ if (widget.terminalStyle)
+ ExcludeFocus(
+ child: BoxHintStrip(
+ hints: [
+ BoxHint(
+ effectiveCommandHint(
+ context,
+ 'picker.accept',
+ contextKind: KeymapContext.picker,
+ ) ??
+ '',
+ 'choose',
+ onTap: _accept,
),
- )
- : results,
- ),
- ],
+ BoxHint(
+ effectiveCommandHint(
+ context,
+ 'picker.toggle_preview',
+ contextKind: KeymapContext.picker,
+ ) ??
+ '',
+ 'preview',
+ onTap: _togglePreview,
+ ),
+ BoxHint(
+ effectiveCommandHint(
+ context,
+ 'picker.cancel',
+ contextKind: KeymapContext.picker,
+ ) ??
+ '',
+ 'back',
+ onTap: _close,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
),
),
),
@@ -629,8 +753,10 @@ class _AgentPickerState extends State<AgentPicker> {
(panelWidth >= 760 ? panelWidth / 2 : panelWidth) <
380 * scaler.scale(14) / 14;
return MouseRegion(
- onEnter: (_) {
- if (_cursor != index) setState(() => _cursor = index);
+ onHover: (event) {
+ if (_pointer.moved(event) && _cursor != index) {
+ setState(() => _cursor = index);
+ }
},
child: ListTile(
key: ValueKey('new-agent-agent-row-${choice.id}'),
@@ -641,9 +767,21 @@ class _AgentPickerState extends State<AgentPicker> {
selectedColor: Colors.white,
hoverColor: Colors.transparent,
selectedTileColor: Colors.white.withValues(alpha: .055),
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(widget.terminalStyle ? 0 : 12),
+ ),
contentPadding: const EdgeInsets.symmetric(horizontal: 12),
- leading: SizedBox(width: 24, child: Center(child: choice.mark(22))),
+ leading: SizedBox(
+ width: 24,
+ child: Center(
+ child: widget.terminalStyle
+ ? Text(
+ highlighted ? '>' : ' ',
+ style: boxMonoStyle(color: grid.AppPalette.swarmAccent),
+ )
+ : choice.mark(22),
+ ),
+ ),
// "MuJoCo by Google DeepMind": the name first and bright, whose it is
// after it and quiet.
title: Row(
@@ -654,11 +792,13 @@ class _AgentPickerState extends State<AgentPicker> {
child: SearchResultText(
choice.label,
matches: matches(choice.label, title: true),
- style: const TextStyle(
- fontSize: 14,
- fontWeight: FontWeight.w600,
- color: Colors.white,
- ),
+ style: widget.terminalStyle
+ ? boxMonoStyle()
+ : const TextStyle(
+ fontSize: 14,
+ fontWeight: FontWeight.w600,
+ color: Colors.white,
+ ),
),
),
if (choice.creator case final creator?) ...[
@@ -669,7 +809,9 @@ class _AgentPickerState extends State<AgentPicker> {
key: ValueKey('new-agent-agent-row-by-${choice.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 13, color: Colors.white54),
+ style: widget.terminalStyle
+ ? boxMonoStyle(size: 12, color: kBoxFaint)
+ : const TextStyle(fontSize: 13, color: Colors.white54),
),
),
],
@@ -680,9 +822,13 @@ class _AgentPickerState extends State<AgentPicker> {
: SearchResultText(
choice.detail!,
matches: matches(choice.detail, title: false),
- style: const TextStyle(fontSize: 12, color: Colors.white60),
+ style: widget.terminalStyle
+ ? boxMonoStyle(size: 12, color: Colors.white60)
+ : const TextStyle(fontSize: 12, color: Colors.white60),
),
- trailing: highlighted
+ trailing: widget.terminalStyle && highlighted
+ ? Text('↵', style: boxMonoStyle(color: kBoxFaint))
+ : highlighted
? ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 170 * scaler.scale(11) / 11,
@@ -708,30 +854,52 @@ class _AgentPickerState extends State<AgentPicker> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- return OverlayPortal(
+ return OverlayPortal.overlayChildLayoutBuilder(
controller: _portal,
- overlayChildBuilder: (context) => Stack(
- children: [
- // A click anywhere the panel does not cover closes it, and lands on
- // nothing else: the sections under the panel are not the target.
- Positioned.fill(
- child: GestureDetector(
- key: const Key('new-agent-agent-barrier'),
- behavior: HitTestBehavior.opaque,
- onTap: _close,
+ overlayChildBuilder: (context, info) {
+ // Read the current geometry during layout. A snapshot taken on open
+ // leaves the panel outside the window after a resize or text scaling.
+ final anchor = MatrixUtils.transformRect(
+ info.childPaintTransform,
+ Offset.zero & info.childSize,
+ );
+ final width = math.min(
+ anchor.width,
+ math.max(0.0, info.overlaySize.width - 16),
+ );
+ final left = math.max(
+ 8.0,
+ math.min(anchor.left, info.overlaySize.width - width - 8),
+ );
+ final top = math.max(
+ 8.0,
+ math.min(anchor.top, info.overlaySize.height - 180),
+ );
+ return Stack(
+ children: [
+ // A click anywhere the panel does not cover closes it, and lands on
+ // nothing else: the sections under the panel are not the target.
+ Positioned.fill(
+ child: GestureDetector(
+ key: const Key('new-agent-agent-barrier'),
+ behavior: HitTestBehavior.opaque,
+ onTap: _close,
+ ),
),
- ),
- Positioned(
- left: 0,
- top: 0,
- child: CompositedTransformFollower(
- link: _link,
- showWhenUnlinked: false,
- child: _panel(context),
+ Positioned(
+ left: left,
+ top: top,
+ width: width,
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ maxHeight: math.max(0, info.overlaySize.height - top - 16),
+ ),
+ child: _panel(context, width: width),
+ ),
),
- ),
- ],
- ),
+ ],
+ );
+ },
child: _bar(context),
);
}
@@ -745,11 +913,15 @@ class _AgentPreview extends StatelessWidget {
required this.choice,
required this.status,
required this.current,
+ this.controller,
+ this.terminalStyle = false,
});
final AgentChoice choice;
final String? status;
final bool current;
+ final ScrollController? controller;
+ final bool terminalStyle;
static const _muted = TextStyle(
fontSize: 12,
@@ -770,33 +942,42 @@ class _AgentPreview extends StatelessWidget {
container: true,
label: 'Agent preview',
child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(16, 20, 24, 20),
+ controller: controller,
+ padding: terminalStyle
+ ? const EdgeInsets.all(12)
+ : const EdgeInsets.fromLTRB(16, 20, 24, 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
- choice.mark(28),
- const SizedBox(width: 12),
+ if (!terminalStyle) ...[
+ choice.mark(28),
+ const SizedBox(width: 12),
+ ],
Expanded(
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: choice.label,
- style: const TextStyle(
- fontSize: 20,
- fontWeight: FontWeight.w600,
- color: Colors.white,
- ),
+ style: terminalStyle
+ ? boxMonoStyle()
+ : const TextStyle(
+ fontSize: 20,
+ fontWeight: FontWeight.w600,
+ color: Colors.white,
+ ),
),
if (choice.creator case final creator?)
TextSpan(
text: ' by $creator',
- style: const TextStyle(
- fontSize: 14,
- color: Colors.white54,
- ),
+ style: terminalStyle
+ ? boxMonoStyle(size: 12, color: kBoxFaint)
+ : const TextStyle(
+ fontSize: 14,
+ color: Colors.white54,
+ ),
),
],
),
@@ -810,47 +991,63 @@ class _AgentPreview extends StatelessWidget {
const SizedBox(height: 8),
Text(
detail,
- style: const TextStyle(
- fontSize: 14,
- height: 1.4,
- color: Colors.white70,
- ),
+ style: terminalStyle
+ ? boxMonoStyle(size: 12, color: Colors.white70)
+ : const TextStyle(
+ fontSize: 14,
+ height: 1.4,
+ color: Colors.white70,
+ ),
),
],
if (chips.isNotEmpty) ...[
const SizedBox(height: 12),
- Wrap(
- spacing: 8,
- runSpacing: 8,
- children: [
- for (final chip in chips)
- DecoratedBox(
- decoration: BoxDecoration(
- color: Colors.white.withValues(alpha: .06),
- borderRadius: BorderRadius.circular(999),
- ),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: 10,
- vertical: 4,
+ if (terminalStyle)
+ Text(
+ chips.join(' · '),
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ )
+ else
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final chip in chips)
+ DecoratedBox(
+ decoration: BoxDecoration(
+ color: Colors.white.withValues(alpha: .06),
+ borderRadius: BorderRadius.circular(999),
),
- child: Text(
- chip,
- style: const TextStyle(
- fontSize: 12,
- color: Colors.white70,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 4,
+ ),
+ child: Text(
+ chip,
+ style: const TextStyle(
+ fontSize: 12,
+ color: Colors.white70,
+ ),
),
),
),
- ),
- ],
- ),
+ ],
+ ),
],
if (description != null && description.trim().isNotEmpty) ...[
- const SizedBox(height: 24),
- const Text('About', style: _muted),
+ SizedBox(height: terminalStyle ? 16 : 24),
+ Text(
+ 'About',
+ style: terminalStyle
+ ? boxMonoStyle(size: 12, color: kBoxFaint)
+ : _muted,
+ ),
const SizedBox(height: 6),
- Text(description.trim(), style: _body),
+ Text(
+ description.trim(),
+ style: terminalStyle ? boxMonoStyle() : _body,
+ ),
],
],
),
diff --git a/desktop/lib/widgets/box_chrome.dart b/desktop/lib/widgets/box_chrome.dart
new file mode 100644
index 000000000..2e51658fa
--- /dev/null
+++ b/desktop/lib/widgets/box_chrome.dart
@@ -0,0 +1,483 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/semantics.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../terminal/terminal_font_store.dart';
+
+const double kTerminalCornerRadius = 3;
+const double kWorkspaceInset = 6;
+
+/// The selected tab joins the workspace with the same small radius used at
+/// its top corners. The bottom curves turn outward, like a browser tab.
+class TerminalTabBorder extends ShapeBorder {
+ const TerminalTabBorder({this.radius = kTerminalCornerRadius});
+ final double radius;
+
+ @override
+ EdgeInsetsGeometry get dimensions => EdgeInsets.zero;
+
+ @override
+ ShapeBorder scale(double t) => TerminalTabBorder(radius: radius * t);
+
+ @override
+ Path getOuterPath(Rect rect, {TextDirection? textDirection}) {
+ final r = radius.clamp(0.0, rect.shortestSide / 4);
+ final c = r * .5522847498;
+ final left = rect.left + r, right = rect.right - r;
+ final top = rect.top, bottom = rect.bottom;
+ return Path()
+ ..moveTo(rect.left, bottom)
+ ..cubicTo(rect.left + c, bottom, left, bottom - r + c, left, bottom - r)
+ ..lineTo(left, top + r)
+ ..cubicTo(left, top + r - c, left + r - c, top, left + r, top)
+ ..lineTo(right - r, top)
+ ..cubicTo(right - r + c, top, right, top + r - c, right, top + r)
+ ..lineTo(right, bottom - r)
+ ..cubicTo(
+ right,
+ bottom - r + c,
+ rect.right - c,
+ bottom,
+ rect.right,
+ bottom,
+ )
+ ..close();
+ }
+
+ @override
+ Path getInnerPath(Rect rect, {TextDirection? textDirection}) =>
+ getOuterPath(rect, textDirection: textDirection);
+
+ @override
+ void paint(Canvas canvas, Rect rect, {TextDirection? textDirection}) {}
+}
+
+/// A temporary command area attached to the workspace's bottom edge. Its
+/// overlay never changes the dimensions or scroll position of live terminals.
+class CommandDock extends StatelessWidget {
+ const CommandDock({
+ super.key,
+ required this.child,
+ this.topClearance = 0,
+ this.expanded = false,
+ });
+ final Widget child;
+ final double topClearance;
+ final bool expanded;
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) {
+ final available =
+ (constraints.maxHeight - topClearance - 2 * kWorkspaceInset).clamp(
+ 0.0,
+ double.infinity,
+ );
+ final scale = MediaQuery.textScalerOf(context).scale(13) / 13;
+ // A shallow dock at ordinary sizes, with room for readable defaults and
+ // key hints when accessibility text or a narrow window needs more rows.
+ final minimum = constraints.maxWidth < 800 * scale ? 320.0 : 280.0;
+ final maxHeight =
+ (expanded
+ ? 520.0 * scale
+ : (available * .4).clamp(minimum * scale, 400.0 * scale))
+ .clamp(0.0, available);
+ return Align(
+ alignment: Alignment.bottomCenter,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(
+ kWorkspaceInset,
+ 0,
+ kWorkspaceInset,
+ kWorkspaceInset,
+ ),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minWidth: (constraints.maxWidth - 2 * kWorkspaceInset).clamp(
+ 0.0,
+ double.infinity,
+ ),
+ maxHeight: maxHeight,
+ ),
+ child: FocusScope(child: child),
+ ),
+ ),
+ );
+ },
+ );
+}
+
+/// Shared typography and frame for prompts that sit over the terminals.
+TextStyle boxMonoStyle({double size = 13, Color? color, FontWeight? weight}) =>
+ TextStyle(
+ fontFamily: terminalFontStore.value.fontFamily,
+ fontFamilyFallback: terminalFontStore.value.fontFamilyFallback,
+ fontSize: size,
+ height: 1.35,
+ color: color ?? Colors.white,
+ fontWeight: weight ?? FontWeight.w400,
+ );
+
+class TerminalBox extends StatelessWidget {
+ const TerminalBox({super.key, required this.child, this.docked = false});
+ final Widget child;
+ final bool docked;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => Material(
+ elevation: 0,
+ color: grid.AppPalette.swarmField,
+ surfaceTintColor: Colors.transparent,
+ shape: docked
+ ? Border(top: BorderSide(color: Colors.white.withValues(alpha: .24)))
+ : RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),
+ side: BorderSide(color: Colors.white.withValues(alpha: .24)),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: DefaultTextStyle.merge(style: boxMonoStyle(), child: child),
+ ),
+ );
+}
+
+/// A compact text row that grows with the user's accessibility text size.
+double boxRowHeight(TextScaler scale) =>
+ (scale.scale(13) * 1.35 + 8).clamp(26, double.infinity);
+
+/// Small print on the box's surface. 54% white is the floor that still reads
+/// (about 5.5:1 on the surface); 38% at 11px did not pass AA.
+const kBoxFaint = Colors.white54;
+const kBoxFaintStyle = TextStyle(fontSize: 11, color: kBoxFaint);
+
+/// Keep the user's actual binding, printed like a terminal's local key guide.
+String boxKeyLabel(String hint) => hint
+ .replaceAll('⌃', 'ctrl-')
+ .replaceAll('⌥', 'alt-')
+ .replaceAll('⇧', 'shift-')
+ .replaceAll('⌘', 'cmd-')
+ .replaceAll('↵', 'enter')
+ .replaceAll('⇥', 'tab')
+ .replaceAll('Esc', 'esc');
+
+/// The highlighted row: a bar at its left edge, fzf's `▌`, with a fill you can
+/// see. A 5% wash on its own was about 1.15:1 — the keyboard's whole position
+/// on screen, nearly invisible.
+class BoxRowHighlight extends StatelessWidget {
+ const BoxRowHighlight({
+ super.key,
+ required this.highlighted,
+ required this.accent,
+ required this.child,
+ this.terminal = false,
+ });
+ final bool highlighted;
+ final Color accent;
+ final Widget child;
+ final bool terminal;
+
+ // A Material, not a coloured box: a ListTile paints its ink on the nearest
+ // Material, and a plain fill between the two hides it (Flutter asserts so).
+ @override
+ Widget build(BuildContext context) => Material(
+ color: highlighted
+ ? Colors.white.withValues(alpha: .10)
+ : Colors.transparent,
+ borderRadius: BorderRadius.circular(terminal ? 0 : 6),
+ // No clip: nothing in a row overflows it, and an antialiased rounded clip
+ // per row was paid again on every arrow key.
+ child: Stack(
+ children: [
+ child,
+ if (highlighted && !terminal)
+ Positioned(
+ left: 0,
+ top: 7,
+ bottom: 7,
+ child: Container(
+ width: 3,
+ decoration: BoxDecoration(
+ color: accent,
+ borderRadius: BorderRadius.circular(2),
+ ),
+ ),
+ ),
+ ],
+ ),
+ );
+}
+
+/// One entry of the bottom line: the key, what it does, and — because a key
+/// nobody told you about is a key you never press, and not everybody has the
+/// keys yet — a click that does the same thing.
+@immutable
+class BoxHint {
+ const BoxHint(this.keys, this.label, {this.onTap, this.reserveLabel});
+ final String keys, label;
+ final VoidCallback? onTap;
+
+ /// Keep a changing action from wrapping the guide and shifting its prompt.
+ final String? reserveLabel;
+}
+
+/// The box's bottom line. Errors keep the available keys underneath them, so
+/// recovery stays discoverable. An in-flight request shows only its status.
+class BoxHintStrip extends StatelessWidget {
+ const BoxHintStrip({
+ super.key,
+ required this.hints,
+ this.message,
+ this.isError = false,
+ this.busy = false,
+ });
+ final List<BoxHint> hints;
+ final String? message;
+ final bool isError, busy;
+
+ double _reservedWidth(BuildContext context, BoxHint hint) {
+ if (hint.reserveLabel == null) return 0;
+ final measure = TextPainter(
+ text: TextSpan(
+ text: '${boxKeyLabel(hint.keys)} ${hint.reserveLabel}',
+ style: DefaultTextStyle.of(context).style.merge(kBoxFaintStyle),
+ ),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ )..layout();
+ final width = measure.width;
+ measure.dispose();
+ return width;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ Widget? notice;
+ if (message case final message?) {
+ notice = Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 7),
+ child: Semantics(
+ liveRegion: true,
+ child: Row(
+ children: [
+ if (busy) ...[
+ const SizedBox.square(
+ dimension: 11,
+ child: CircularProgressIndicator(strokeWidth: 1.5),
+ ),
+ const SizedBox(width: 8),
+ ],
+ Expanded(
+ child: SelectableText(
+ message,
+ maxLines: 3,
+ minLines: 1,
+ style: boxMonoStyle(
+ size: 12,
+ color: isError ? Colors.orangeAccent : Colors.white70,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+ // Every available key stays in view. A horizontal scroll hid Escape and
+ // advanced options exactly when larger text made them most useful.
+ final guide = Wrap(
+ children: [
+ for (final hint in hints)
+ Padding(
+ padding: const EdgeInsets.only(right: 6),
+ child: Semantics(
+ button: hint.onTap != null,
+ label: '${hint.label}, ${hint.keys}',
+ excludeSemantics: true,
+ child: InkWell(
+ borderRadius: BorderRadius.circular(5),
+ onTap: hint.onTap,
+ child: Padding(
+ // 11px text + 2×7 = a target a hand can hit (≥24px).
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 7,
+ ),
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minWidth: _reservedWidth(context, hint),
+ ),
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: boxKeyLabel(hint.keys),
+ style: const TextStyle(color: Colors.white70),
+ ),
+ TextSpan(text: ' ${hint.label}'),
+ ],
+ ),
+ style: kBoxFaintStyle,
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ return Container(
+ constraints: const BoxConstraints(minHeight: 32),
+ alignment: Alignment.centerLeft,
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ decoration: BoxDecoration(
+ border: Border(
+ top: BorderSide(color: Colors.white.withValues(alpha: .08)),
+ ),
+ ),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [?notice, if (!busy || notice == null) guide],
+ ),
+ );
+ }
+}
+
+/// Says the highlighted row or current message to a screen reader. Focus stays in the input while
+/// the arrows move a highlight the reader never visits, so without this the
+/// list is silent. Coalesced: holding an arrow announces where it stopped.
+class BoxAnnouncer {
+ String? _last;
+ // Clearing the message lets the same error be announced on a later attempt.
+ void row(BuildContext context, String? text) {
+ if (text == _last) return;
+ _last = text;
+ if (text == null) return;
+ SemanticsService.sendAnnouncement(
+ View.of(context),
+ text,
+ Directionality.of(context),
+ );
+ }
+}
+
+/// A row follows the pointer only when the pointer MOVED. `onEnter` also fires
+/// when rows appear or scroll under a parked pointer — the box opening, the
+/// list revealing the keyboard's selection — and that stole the highlight from
+/// the keyboard with nobody touching the mouse.
+class BoxPointerGate {
+ Offset? _last;
+ bool moved(PointerEvent event) {
+ final was = _last;
+ _last = event.position;
+ return was != null && (was - event.position).distanceSquared > 1;
+ }
+}
+
+/// readline in the box's line. macOS gives a text field ⌃A ⌃E ⌃F ⌃B and ⌥←/→;
+/// the kill keys were nobody's, and they are the ones a shell's fingers reach
+/// for: ⌃W (word — stopping at `/`, as a path wants), ⌃U (to this line's start),
+/// ⌃H and ⌃D (a character each way), ⌃Y (put the last kill back).
+class ReadlineKeys extends StatefulWidget {
+ const ReadlineKeys({
+ super.key,
+ required this.controller,
+ required this.onChanged,
+ required this.child,
+ this.enabled = true,
+ });
+ final TextEditingController controller;
+ final ValueChanged<String> onChanged;
+ final Widget child;
+ final bool enabled;
+
+ @override
+ State<ReadlineKeys> createState() => _ReadlineKeysState();
+}
+
+class _ReadlineKeysState extends State<ReadlineKeys> {
+ String _killed = '';
+
+ bool get _composing {
+ final composing = widget.controller.value.composing;
+ return composing.isValid && !composing.isCollapsed;
+ }
+
+ void _edit(int start, int end, {String insert = '', bool kill = false}) {
+ final value = widget.controller.value;
+ if (!widget.enabled ||
+ _composing ||
+ start < 0 ||
+ end > value.text.length ||
+ start > end) {
+ return;
+ }
+ if (start == end && insert.isEmpty) return;
+ if (kill) _killed = value.text.substring(start, end);
+ final text = value.text.replaceRange(start, end, insert);
+ widget.controller.value = TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: start + insert.length),
+ );
+ widget.onChanged(text);
+ }
+
+ (int, int) get _span {
+ final value = widget.controller.value;
+ final selection = value.selection;
+ if (!selection.isValid) return (value.text.length, value.text.length);
+ return (selection.start, selection.end);
+ }
+
+ void _killWord() {
+ final (start, end) = _span;
+ if (start != end) return _edit(start, end, kill: true);
+ final text = widget.controller.text;
+ var at = start;
+ bool boundary(int i) => text[i] == '/' || text[i].trim().isEmpty;
+ while (at > 0 && boundary(at - 1)) {
+ at--;
+ }
+ while (at > 0 && !boundary(at - 1)) {
+ at--;
+ }
+ _edit(at, start, kill: true);
+ }
+
+ void _killLine() {
+ final (start, end) = _span;
+ if (start != end) return _edit(start, end, kill: true);
+ if (start == 0) return;
+ final lineStart = widget.controller.text.lastIndexOf('\n', start - 1) + 1;
+ _edit(lineStart, start, kill: true);
+ }
+
+ void _deleteCharacter({required bool backwards}) {
+ final (start, end) = _span;
+ if (start != end) return _edit(start, end);
+ // Editing offsets are UTF-16 code units. Step over a whole visible
+ // character, including combining accents, emoji modifiers and joiners.
+ final range = CharacterBoundary(widget.controller.text)
+ .getTextBoundaryAt(backwards ? start - 1 : start);
+ if (range.isValid) _edit(range.start, range.end);
+ }
+
+ @override
+ Widget build(BuildContext context) => CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.keyW, control: true): _killWord,
+ const SingleActivator(LogicalKeyboardKey.keyU, control: true): _killLine,
+ const SingleActivator(LogicalKeyboardKey.keyH, control: true): () =>
+ _deleteCharacter(backwards: true),
+ const SingleActivator(LogicalKeyboardKey.keyD, control: true): () =>
+ _deleteCharacter(backwards: false),
+ const SingleActivator(LogicalKeyboardKey.keyY, control: true): () {
+ final (start, end) = _span;
+ if (_killed.isNotEmpty) _edit(start, end, insert: _killed);
+ },
+ },
+ child: widget.child,
+ );
+}
diff --git a/desktop/lib/widgets/codex_profile_field.dart b/desktop/lib/widgets/codex_profile_field.dart
index 4ccac7461..cccd62f9f 100644
--- a/desktop/lib/widgets/codex_profile_field.dart
+++ b/desktop/lib/widgets/codex_profile_field.dart
@@ -24,6 +24,8 @@ class CodexProfileField extends StatefulWidget {
required this.onChanged,
this.onBusyChanged,
this.observedPaths = const {},
+ this.textStyle,
+ this.valueChosen = false,
});
final AppNotifier notifier;
@@ -33,6 +35,8 @@ class CodexProfileField extends StatefulWidget {
final ValueChanged<LocalCodexProfile?> onChanged;
final ValueChanged<bool>? onBusyChanged;
final Set<String> observedPaths;
+ final TextStyle? textStyle;
+ final bool valueChosen;
@override
State<CodexProfileField> createState() => _CodexProfileFieldState();
@@ -42,7 +46,7 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
List<LocalCodexProfile> _profiles = const [];
bool _loading = true;
bool _linking = false;
- bool _hasChosenProfile = false;
+ late bool _hasChosenProfile = widget.valueChosen;
String? _error;
int _loadGeneration = 0;
int _machineRevision = 0;
@@ -61,7 +65,7 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
oldWidget.notifier != widget.notifier) {
_machineRevision++;
_profiles = [];
- _hasChosenProfile = false;
+ _hasChosenProfile = widget.valueChosen;
_linking = false;
_load();
} else if (!setEquals(oldWidget.observedPaths, widget.observedPaths)) {
@@ -186,6 +190,10 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
if (widget.value != null) widget.value!.path: widget.value!,
};
const refreshValue = '__refresh_profiles__';
+ final height = math.max(
+ 34.0,
+ MediaQuery.textScalerOf(context).scale(13) * 1.35 + 14,
+ );
return Wrap(
spacing: 8,
runSpacing: 6,
@@ -195,10 +203,12 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
width:
252 *
math.min(1.4, MediaQuery.textScalerOf(context).scale(13) / 13),
- height: 34,
+ height: height,
child: AppSelectField<String>(
key: const Key('new-agent-codex-profile-field'),
- height: 34,
+ height: height,
+ textStyle: widget.textStyle,
+ radius: widget.textStyle == null ? null : 2,
value: widget.value?.path ?? '',
options: [
const SelectOption(value: '', label: 'Default profile'),
@@ -228,10 +238,12 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
'Codex profile: ${widget.value?.label ?? (_loading ? 'Loading…' : 'Default')}',
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 13,
- color: grid.AppPalette.textPrimary,
- ),
+ style:
+ widget.textStyle ??
+ TextStyle(
+ fontSize: 13,
+ color: grid.AppPalette.textPrimary,
+ ),
),
),
const SizedBox(width: 8),
@@ -250,11 +262,13 @@ class _CodexProfileFieldState extends State<CodexProfileField> {
foregroundColor: grid.AppPalette.textSecondary,
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 6),
minimumSize: const Size(0, 32),
- textStyle: TextStyle(
- fontFamily: grid.AppFont.sans,
- fontFamilyFallback: grid.AppFont.sansFallback,
- fontSize: 13,
- ),
+ textStyle:
+ widget.textStyle ??
+ TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontFamilyFallback: grid.AppFont.sansFallback,
+ fontSize: 13,
+ ),
),
child: Text(_linking ? 'Adding…' : 'Add'),
),
diff --git a/desktop/lib/widgets/delete_agent_dialog.dart b/desktop/lib/widgets/delete_agent_dialog.dart
index 1f40c9037..0e271c994 100644
--- a/desktop/lib/widgets/delete_agent_dialog.dart
+++ b/desktop/lib/widgets/delete_agent_dialog.dart
@@ -1,16 +1,16 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
import 'engine_identity.dart';
+import 'terminal_prompt.dart';
-/// Shared Stop Agent confirmation. The legacy agent_delete request stops the
-/// engine and removes its active entry, preserving files and saved history.
-///
-/// [engine] tells the dialog what it is ending: a terminal (`kTerminalEngine`)
-/// is a shell, and closing one ends whatever was running in it — said in
-/// those words, since "agent" and "conversation history" mean nothing to it.
+/// Stopping ends the running process; closing a pane only removes its view.
+/// Requests remain with the model if this prompt is dismissed.
Future<void> confirmDeleteAgent(
BuildContext context,
AppNotifier notifier,
@@ -18,42 +18,224 @@ Future<void> confirmDeleteAgent(
String agentId,
String name, {
String? engine,
-}) async {
- final terminal = isTerminalEngine(engine);
- final verb = terminal ? 'Stop Terminal' : 'Stop Harness';
- final confirmed = await showAppDialog<bool>(
- context: context,
- builder: (dialogContext) => AlertDialog(
- title: Text(verb),
- content: SizedBox(
- width: 360,
- child: Text(
- terminal
- ? 'Stop “$name”? This closes the shell and ends anything still '
- 'running in it. Files are kept.'
- : 'Stop “$name”? This ends the running agent and removes it from your '
- 'active agents. Project files and saved conversation history are kept.',
- style: TextStyle(fontFamily: grid.AppFont.sans, fontSize: 13.5),
- ),
+ AppKeymap? keymap,
+}) => showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (_) => _StopAgentPrompt(
+ notifier: notifier,
+ machineId: machineId,
+ agentId: agentId,
+ name: name,
+ terminal: isTerminalEngine(engine),
+ ),
+);
+
+class _StopAgentPrompt extends StatefulWidget {
+ const _StopAgentPrompt({
+ required this.notifier,
+ required this.machineId,
+ required this.agentId,
+ required this.name,
+ required this.terminal,
+ });
+ final AppNotifier notifier;
+ final String machineId, agentId, name;
+ final bool terminal;
+ @override
+ State<_StopAgentPrompt> createState() => _StopAgentPromptState();
+}
+
+class _StopAgentPromptState extends State<_StopAgentPrompt> {
+ final _cancel = FocusNode(debugLabel: 'Cancel stop');
+ final _promptFocus = FocusNode(debugLabel: 'Pending stop');
+ final _body = ScrollController();
+ final _announcer = BoxAnnouncer();
+ late final Future<String?> Function() _requestStop;
+ bool _stopping = false;
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ _requestStop = widget.notifier.prepareAgentStop(
+ widget.machineId,
+ widget.agentId,
+ );
+ if (widget.notifier.pendingAgentStop(widget.machineId, widget.agentId)
+ case final pending?) {
+ _stopping = true;
+ unawaited(_finish(pending));
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _stopping) _promptFocus.requestFocus();
+ });
+ } else {
+ _focusCancel();
+ }
+ }
+
+ void _focusCancel() => WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _cancel.requestFocus();
+ }
+ });
+
+ @override
+ void dispose() {
+ _cancel.dispose();
+ _promptFocus.dispose();
+ _body.dispose();
+ super.dispose();
+ }
+
+ void _close() => Navigator.pop(context);
+
+ void _page(int direction) {
+ if (!_body.hasClients) return;
+ final position = _body.position;
+ _body.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .8).clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(dialogContext).pop(false),
- child: const Text('Cancel'),
- ),
- FilledButton(
- style: FilledButton.styleFrom(
- backgroundColor: grid.AppPalette.dangerFill,
- ),
- onPressed: () => Navigator.of(dialogContext).pop(true),
- child: Text(verb),
+ );
+ }
+
+ void _stop() {
+ if (_stopping) return;
+ // The Stop button is removed while pending; keep Escape and custom keys
+ // in the prompt instead of letting focus fall back to the terminal.
+ _promptFocus.requestFocus();
+ setState(() {
+ _stopping = true;
+ _error = null;
+ });
+ unawaited(_finish(_requestStop()));
+ }
+
+ Future<void> _finish(Future<String?> request) async {
+ String? error;
+ try {
+ error = await request;
+ } catch (_) {
+ error = 'Could not stop the agent. Try again.';
+ }
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.pop(context);
+ return;
+ }
+ setState(() {
+ _stopping = false;
+ _error = error;
+ });
+ _announcer.row(context, error);
+ _focusCancel();
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => TerminalPromptKeys(
+ focusNode: _promptFocus,
+ cancel: _close,
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: TerminalPrompt(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ controller: _body,
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ widget.terminal ? 'Stop Terminal' : 'Stop Agent',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ widget.name,
+ style: boxMonoStyle(weight: FontWeight.w600),
+ ),
+ if (widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
+ case final machine?) ...[
+ const SizedBox(height: 4),
+ Text(
+ machine,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ const SizedBox(height: 10),
+ Text(
+ widget.terminal
+ ? 'End this shell and anything running in it? Files are kept.'
+ : 'End the running agent? Project files and saved conversation history are kept.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Its panes close across tabs. Close Pane keeps it running.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ if (_stopping) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Stopping continues if you close this prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ if (!_stopping)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 10),
+ child: Wrap(
+ spacing: 12,
+ children: [
+ terminalPromptButton('Cancel', _close, focusNode: _cancel),
+ terminalPromptButton(
+ 'Stop',
+ _stop,
+ danger: true,
+ key: const Key('agent-stop-confirm'),
+ ),
+ ],
+ ),
+ ),
+ BoxHintStrip(
+ message: _error ?? (_stopping ? 'Stopping…' : null),
+ isError: _error != null,
+ hints: [
+ if (!_stopping)
+ BoxHint(
+ terminalPromptHint(context, 'picker.accept', 'enter'),
+ 'select',
+ ),
+ if (!_stopping)
+ BoxHint(
+ terminalPromptHint(context, 'picker.complete', 'tab'),
+ 'controls',
+ ),
+ BoxHint(
+ terminalPromptHint(context, 'picker.cancel', 'esc'),
+ 'close',
+ onTap: _close,
+ ),
+ ],
+ ),
+ ],
),
- ],
+ ),
),
);
- if (confirmed != true || !context.mounted) return;
- final error = await notifier.deleteAgent(machineId, agentId);
- if (error != null && context.mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error)));
- }
}
diff --git a/desktop/lib/widgets/engine_identity.dart b/desktop/lib/widgets/engine_identity.dart
index 5669fac2f..984e7e838 100644
--- a/desktop/lib/widgets/engine_identity.dart
+++ b/desktop/lib/widgets/engine_identity.dart
@@ -698,7 +698,7 @@ const _harnesses = <String, EngineIdentity>{
id: 'autonomous/home-assistant',
label: "Home Assistant",
category: "Automation",
- tagline: "Open-source home automation that puts local control first",
+ tagline: "Home automation ideas → tested YAML, native traces and a real handoff",
creator: "OpenHarness contributors",
color: Color(0xffb88159),
asset: 'assets/engine-icons/home-assistant.png',
diff --git a/desktop/lib/widgets/environment_preflight_screen.dart b/desktop/lib/widgets/environment_preflight_screen.dart
index 1875871d8..026c01ccd 100644
--- a/desktop/lib/widgets/environment_preflight_screen.dart
+++ b/desktop/lib/widgets/environment_preflight_screen.dart
@@ -19,6 +19,7 @@ class EnvironmentPreflightScreen extends StatelessWidget {
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
final ready = readiness.isReady;
+ final reduceMotion = MediaQuery.disableAnimationsOf(context);
return Scaffold(
backgroundColor: grid.AppPalette.panelBg,
@@ -38,15 +39,23 @@ class EnvironmentPreflightScreen extends StatelessWidget {
borderRadius: BorderRadius.circular(14),
boxShadow: grid.AppCard.shadow,
),
- child: AnimatedSwitcher(
- duration: const Duration(milliseconds: 180),
- child: ready
- ? const _ReadyContent(
- key: ValueKey('environment-ready'),
- )
- : const _CheckingContent(
- key: ValueKey('environment-checking'),
- ),
+ child: Semantics(
+ key: const Key('environment-status'),
+ container: true,
+ liveRegion: true,
+ label: 'OpenHarness setup status',
+ child: AnimatedSwitcher(
+ duration: reduceMotion
+ ? Duration.zero
+ : const Duration(milliseconds: 180),
+ child: ready
+ ? const _ReadyContent(
+ key: ValueKey('environment-ready'),
+ )
+ : const _CheckingContent(
+ key: ValueKey('environment-checking'),
+ ),
+ ),
),
),
),
@@ -65,10 +74,16 @@ class _CheckingContent extends StatelessWidget {
Widget build(BuildContext context) => Column(
mainAxisSize: MainAxisSize.min,
children: [
- const SizedBox(
+ SizedBox(
width: 34,
height: 34,
- child: CircularProgressIndicator(strokeWidth: 2.5),
+ child: MediaQuery.disableAnimationsOf(context)
+ ? Icon(
+ Icons.hourglass_empty_rounded,
+ size: 34,
+ color: Theme.of(context).colorScheme.primary,
+ )
+ : const CircularProgressIndicator(strokeWidth: 2.5),
),
const SizedBox(height: 24),
Text(
diff --git a/desktop/lib/widgets/environment_setup_screen.dart b/desktop/lib/widgets/environment_setup_screen.dart
index 4a7e8f271..01d1f1ede 100644
--- a/desktop/lib/widgets/environment_setup_screen.dart
+++ b/desktop/lib/widgets/environment_setup_screen.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
@@ -22,6 +23,9 @@ class EnvironmentSetupScreen extends StatefulWidget {
class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
String? _copied;
+ String? _copyError;
+ var _copyRevision = 0;
+ Timer? _copyTimer;
final _scroll = ScrollController();
final _primaryFocus = FocusNode(debugLabel: 'Setup action');
final _bodyFocus = FocusNode(
@@ -35,6 +39,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
@override
void dispose() {
+ _copyTimer?.cancel();
_scroll.dispose();
_primaryFocus.dispose();
_bodyFocus.dispose();
@@ -43,12 +48,28 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
}
Future<void> _copy(String value) async {
- await Clipboard.setData(ClipboardData(text: value));
- if (!mounted) return;
- setState(() => _copied = value);
- Future<void>.delayed(const Duration(milliseconds: 1400), () {
- if (mounted && _copied == value) setState(() => _copied = null);
- });
+ final revision = ++_copyRevision;
+ _copyTimer?.cancel();
+ try {
+ await Clipboard.setData(ClipboardData(text: value));
+ if (!mounted || revision != _copyRevision) return;
+ setState(() {
+ _copied = value;
+ _copyError = null;
+ });
+ _copyTimer = Timer(const Duration(milliseconds: 1400), () {
+ if (mounted && revision == _copyRevision) {
+ setState(() => _copied = null);
+ }
+ });
+ } catch (_) {
+ if (!mounted || revision != _copyRevision) return;
+ setState(() {
+ _copied = null;
+ _copyError =
+ 'Could not copy. Select the text to copy it, or try again.';
+ });
+ }
}
@override
@@ -183,8 +204,8 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
count == 0
? 'Your tools are ready. Verify them to continue.'
: count == 1
- ? 'Install this tool, then sign in to start your first agent.'
- : 'Install these $countLabel, then sign in to start your first agent.',
+ ? 'Install this tool, then sign in to start your first harness.'
+ : 'Install these $countLabel, then sign in to start your first harness.',
),
Row(
children: [
@@ -365,6 +386,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
leading: CircleAvatar(
radius: 14,
backgroundColor: AppColors.hover,
+ foregroundColor: AppColors.text,
child: Text(
'${index + 1}',
style: const TextStyle(fontSize: 11),
@@ -554,7 +576,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
: widget.notifier.startEnvironmentSetup;
case EnvironmentSetupPhase.failed:
label = 'Retry';
- action = manual
+ action = manual || !widget.notifier.environmentInstallRequested
? widget.notifier.retryEnvironmentSetup
: widget.notifier.startEnvironmentSetup;
case EnvironmentSetupPhase.ready:
@@ -607,9 +629,15 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {
),
],
);
- final next = Text(
- 'Next: sign in and start a harness.',
- style: TextStyle(color: AppColors.textSoft, fontSize: 11),
+ final next = Semantics(
+ liveRegion: _copyError != null,
+ child: Text(
+ _copyError ?? 'Next: sign in and start a harness.',
+ style: TextStyle(
+ color: _copyError == null ? AppColors.textSoft : AppColors.danger,
+ fontSize: 11,
+ ),
+ ),
);
return Container(
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
diff --git a/desktop/lib/widgets/fork_agent_dialog.dart b/desktop/lib/widgets/fork_agent_dialog.dart
index 9d2ccdbd4..3e101ee5f 100644
--- a/desktop/lib/widgets/fork_agent_dialog.dart
+++ b/desktop/lib/widgets/fork_agent_dialog.dart
@@ -1,23 +1,18 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'terminal_prompt.dart';
-/// The default name for a fork of [name] — the owner's spelling.
String forkNameFor(String name) =>
'${name.trim().isEmpty ? 'Agent' : name.trim()} - fork';
-/// The engines that can fork a session outright. Fork is only OFFERED for an
-/// agent that can fork at all ([Agent.canFork]); among those, this sets the
-/// words the dialog opens with, so a person is told before the round trip
-/// whether the fork will carry the whole context or a handoff.
-const _nativeForkEngines = {'claude', 'codex'};
-
-/// Fork a harness: open the dialog, then a second agent with the first one's
-/// history, placed beside it and focused. Errors land as a snackbar; a fork
-/// that could only hand off (no native fork on that engine) says so once.
+/// The model retains the draft, receipt and destination across dismissal.
Future<void> forkHarness(
BuildContext context,
AppNotifier notifier,
@@ -25,34 +20,24 @@ Future<void> forkHarness(
String agentId,
String name, {
String? engine,
+ AppKeymap? keymap,
}) async {
- if (notifier.agentIsProcessing(machineId, agentId)) {
- ScaffoldMessenger.of(context).showSnackBar(
- const SnackBar(
- content: Text(
- 'This harness is in the middle of a turn. Wait for it to finish, then fork.',
- ),
- ),
- );
- return;
- }
- final choice = await showForkAgentDialogForTest(
+ final result = await showTerminalPrompt<ForkAgentResult>(
context,
- name,
- engine: engine,
+ keymap: keymap,
+ builder: (_) => _ForkAgentPrompt(
+ notifier: notifier,
+ machineId: machineId,
+ agentId: agentId,
+ sourceName: name,
+ engine: engine,
+ ),
);
- if (choice == null || !context.mounted) return;
- final result = await notifier.forkAgent(
- machineId,
- agentId,
- name: choice.name,
- prompt: choice.task,
- );
- if (!context.mounted) return;
+ if (result == null || !context.mounted) return;
final message =
- result.error ??
+ result.notice ??
(result.level == 'handoff'
- ? 'Forked with a handoff: this engine cannot copy a session, so the fork opened with a summary of what “$name” had done.'
+ ? 'Fork opened with a handoff summary of the source conversation.'
: null);
if (message != null) {
ScaffoldMessenger.of(context)
@@ -60,190 +45,406 @@ Future<void> forkHarness(
}
}
-/// The dialog alone — name and first task, or null on cancel. Public for the
-/// widget test; [forkHarness] is what the app calls.
-@visibleForTesting
-Future<({String name, String task})?> showForkAgentDialogForTest(
- BuildContext context,
- String sourceName, {
- String? engine,
-}) => showAppDialog<({String name, String task})>(
- context: context,
- transitionDuration: Duration.zero,
- veilBlur: 0,
- veilTint: const Color(0x99000000),
- builder: (_) => _ForkAgentDialog(sourceName: sourceName, engine: engine),
-);
-
-class _ForkAgentDialog extends StatefulWidget {
- const _ForkAgentDialog({required this.sourceName, this.engine});
- final String sourceName;
+class _ForkAgentPrompt extends StatefulWidget {
+ const _ForkAgentPrompt({
+ required this.notifier,
+ required this.machineId,
+ required this.agentId,
+ required this.sourceName,
+ this.engine,
+ });
+ final AppNotifier notifier;
+ final String machineId, agentId, sourceName;
final String? engine;
@override
- State<_ForkAgentDialog> createState() => _ForkAgentDialogState();
+ State<_ForkAgentPrompt> createState() => _ForkAgentPromptState();
}
-class _ForkAgentDialogState extends State<_ForkAgentDialog> {
- late final _name = TextEditingController(
- text: forkNameFor(widget.sourceName),
- );
+class _ForkAgentPromptState extends State<_ForkAgentPrompt> {
+ late AgentForkAttempt _attempt;
+ final _name = TextEditingController();
final _task = TextEditingController();
final _nameFocus = FocusNode(debugLabel: 'Fork name');
- final _taskFocus = FocusNode(debugLabel: 'Fork first task');
+ final _taskFocus = FocusNode(debugLabel: 'Fork task');
+ final _body = ScrollController();
+ final _announcer = BoxAnnouncer();
+ bool _busy = false;
+ String? _error;
+ bool get _locked => _busy || _attempt.awaitingConfirmation;
+ bool get _composing => [_name, _task].any(
+ (controller) =>
+ controller.value.composing.isValid &&
+ !controller.value.composing.isCollapsed,
+ );
@override
void initState() {
super.initState();
+ _attempt = widget.notifier.forkAttempt(
+ widget.machineId,
+ widget.agentId,
+ name: forkNameFor(widget.sourceName),
+ );
+ _name.text = _attempt.name;
+ _task.text = _attempt.prompt;
+ _error = _attempt.result?.error;
+ _nameFocus.addListener(_focusChanged);
+ _taskFocus.addListener(_focusChanged);
+ if (_attempt.pending case final pending?) {
+ _busy = true;
+ unawaited(_finish(pending));
+ }
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && ModalRoute.isCurrentOf(context) != false) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
_taskFocus.requestFocus();
}
});
}
+ void _focusChanged() {
+ if (mounted) setState(() {});
+ }
+
@override
void dispose() {
+ _nameFocus.removeListener(_focusChanged);
+ _taskFocus.removeListener(_focusChanged);
_nameFocus.dispose();
_taskFocus.dispose();
_name.dispose();
_task.dispose();
+ _body.dispose();
super.dispose();
}
- void _fork() {
- final name = _name.text.trim();
- if (name.isEmpty) return;
- Navigator.pop(context, (name: name, task: _task.text.trim()));
+ void _changed(String _) {
+ if (_locked) return;
+ _attempt.name = _name.text;
+ _attempt.prompt = _task.text;
+ _attempt.result = null;
+ setState(() => _error = null);
}
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final accent = grid.AppPalette.accentOnSurface;
- final border = OutlineInputBorder(
- borderRadius: BorderRadius.circular(10),
- borderSide: BorderSide.none,
+ void _close() {
+ if (!_composing) Navigator.pop(context);
+ }
+
+ void _accept() {
+ if (_composing) return;
+ if (_nameFocus.hasFocus) {
+ _taskFocus.requestFocus();
+ return;
+ }
+ if (_taskFocus.hasFocus) {
+ _submit();
+ return;
+ }
+ activatePromptControl();
+ }
+
+ void _submit() {
+ if (_busy || _composing) return;
+ if (!_attempt.awaitingConfirmation && _name.text.trim().isEmpty) {
+ setState(() => _error = 'Name cannot be empty');
+ _nameFocus.requestFocus();
+ return;
+ }
+ if (!_attempt.awaitingConfirmation && _name.text.characters.length > 80) {
+ setState(() => _error = 'Use at most 80 characters for the name.');
+ _nameFocus.requestFocus();
+ return;
+ }
+ _taskFocus.requestFocus();
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ unawaited(
+ _finish(
+ widget.notifier.forkAgent(
+ widget.machineId,
+ widget.agentId,
+ attempt: _attempt,
+ ),
+ ),
);
- InputDecoration decoration(String hint) => InputDecoration(
- filled: true,
- fillColor: grid.AppSurface.recess,
- isDense: true,
- hintText: hint,
- hintStyle: TextStyle(fontSize: 14, color: grid.AppPalette.textSecondary),
- contentPadding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
- border: border,
- enabledBorder: border,
- focusedBorder: border.copyWith(borderSide: BorderSide(color: accent)),
- counterText: '',
+ }
+
+ Future<void> _finish(Future<ForkAgentResult> request) async {
+ ForkAgentResult result;
+ try {
+ result = await request;
+ } catch (_) {
+ result = const ForkAgentResult(
+ error:
+ 'Could not confirm the fork. Check agents before starting another.',
+ );
+ }
+ if (!mounted) return;
+ if (result.error == null) {
+ Navigator.pop(context, result);
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error = result.error;
+ });
+ _taskFocus.requestFocus();
+ _announcer.row(context, result.error!);
+ }
+
+ void _startAnother() {
+ if (!widget.notifier.discardForkAttempt(
+ widget.machineId,
+ widget.agentId,
+ _attempt,
+ )) {
+ return;
+ }
+ _attempt = widget.notifier.forkAttempt(
+ widget.machineId,
+ widget.agentId,
+ name: _name.text,
+ prompt: _task.text,
);
- final native =
- widget.engine == null || _nativeForkEngines.contains(widget.engine);
- final what = native
- ? 'The fork starts with everything “${widget.sourceName}” knows, in the same folder. Both keep running on their own.'
- : 'This engine cannot copy a session: the fork opens with a summary of what “${widget.sourceName}” has done, in the same folder.';
- Widget label(String text) => Padding(
- padding: const EdgeInsets.only(bottom: 6),
- child: Text(
- text,
- style: TextStyle(
- fontSize: 12,
- fontWeight: FontWeight.w600,
- color: grid.AppPalette.textSecondary,
- ),
+ setState(
+ () => _error =
+ 'The previous fork may already exist. Confirm to start another.',
+ );
+ _taskFocus.requestFocus();
+ }
+
+ void _newline() {
+ if (_locked || _composing || !_taskFocus.hasFocus) return;
+ final value = _task.value;
+ if (!value.selection.isValid) return;
+ _task.value = TextEditingValue(
+ text: value.text.replaceRange(
+ value.selection.start,
+ value.selection.end,
+ '\n',
+ ),
+ selection: TextSelection.collapsed(offset: value.selection.start + 1),
+ );
+ _changed(_task.text);
+ }
+
+ void _page(int direction) {
+ if (!_body.hasClients) return;
+ final position = _body.position;
+ _body.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .8).clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
),
);
- return ListenableBuilder(
- listenable: _name,
- builder: (context, _) => AlertDialog(
- title: const Text('Fork Harness'),
- titleTextStyle: Theme.of(context).textTheme.titleMedium,
- content: SizedBox(
- width: 400,
+ }
+
+ void _vertical(int direction) {
+ final input = _nameFocus.hasFocus ? _nameFocus : _taskFocus;
+ if (input.hasFocus && input.context != null) {
+ Actions.maybeInvoke(
+ input.context!,
+ ExtendSelectionVerticallyToAdjacentLineIntent(
+ forward: direction > 0,
+ collapseSelection: true,
+ ),
+ );
+ } else if (direction > 0) {
+ FocusManager.instance.primaryFocus?.nextFocus();
+ } else {
+ FocusManager.instance.primaryFocus?.previousFocus();
+ }
+ }
+
+ Widget _input(
+ String label,
+ TextEditingController controller,
+ FocusNode focus, {
+ bool task = false,
+ }) => Semantics(
+ label: task ? 'Fork first task, optional' : 'Fork name',
+ child: ReadlineKeys(
+ controller: controller,
+ enabled: !_locked,
+ onChanged: _changed,
+ child: TextField(
+ key: ValueKey(task ? 'fork-task' : 'fork-name'),
+ controller: controller,
+ focusNode: focus,
+ readOnly: _locked,
+ style: boxMonoStyle(),
+ textAlignVertical: TextAlignVertical.center,
+ minLines: 1,
+ maxLines: task ? 6 : 1,
+ textInputAction: task ? TextInputAction.done : TextInputAction.next,
+ decoration: InputDecoration(
+ hintText: task ? 'first task (optional)' : 'name',
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ isDense: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ contentPadding: EdgeInsets.zero,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ '$label >',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
+ ),
+ ),
+ prefixIconConstraints: const BoxConstraints(minHeight: 38),
+ ),
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) {
+ if (task) {
+ _submit();
+ } else {
+ _taskFocus.requestFocus();
+ }
+ },
+ ),
+ ),
+ );
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => TerminalPromptKeys(
+ composing: () => _composing,
+ inputFocus: _nameFocus.hasFocus ? _nameFocus : _taskFocus,
+ cancel: _close,
+ accept: _accept,
+ submit: _submit,
+ next: () => _vertical(1),
+ previous: () => _vertical(-1),
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: CallbackShortcuts(
+ bindings: {
+ const SingleActivator(LogicalKeyboardKey.enter, alt: true): _newline,
+ if (KeymapTheme.of(context) == null)
+ const SingleActivator(LogicalKeyboardKey.enter, meta: true):
+ _submit,
+ },
+ child: TerminalPrompt(
+ width: 760,
child: Column(
mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Text(
- what,
- style: TextStyle(
- fontFamily: grid.AppFont.sans,
- fontSize: 13,
- height: 1.4,
- color: grid.AppPalette.textSecondary,
- ),
- ),
- const SizedBox(height: 16),
- label('Name'),
- TextField(
- key: const ValueKey('fork-name'),
- controller: _name,
- focusNode: _nameFocus,
- maxLength: 80,
- cursorColor: accent,
- textInputAction: TextInputAction.next,
- style: TextStyle(
- fontSize: 14,
- color: grid.AppPalette.textPrimary,
+ Flexible(
+ child: SingleChildScrollView(
+ controller: _body,
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Fork Agent',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 10),
+ Text(
+ 'from ${_attempt.source?.name ?? widget.sourceName}',
+ style: boxMonoStyle(),
+ ),
+ if (widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
+ case final machine?)
+ Text(
+ [
+ machine,
+ if (_attempt.source?.project?.cwd case final cwd?
+ when cwd.isNotEmpty)
+ cwd,
+ ].join(' '),
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ const SizedBox(height: 6),
+ Text(
+ widget.engine == 'opencode'
+ ? 'Starts from a handoff summary, in the same project folder.'
+ : 'Continues the conversation in the same project folder.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ const SizedBox(height: 8),
+ _input('name', _name, _nameFocus),
+ _input('task', _task, _taskFocus, task: true),
+ if (_error case final error?) ...[
+ const SizedBox(height: 8),
+ Text(
+ error,
+ style: boxMonoStyle(
+ size: 12,
+ color: Colors.orangeAccent,
+ ),
+ ),
+ ],
+ if (_busy)
+ Text(
+ 'Forking continues if you close this prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
),
- decoration: decoration(''),
- onSubmitted: (_) => _taskFocus.requestFocus(),
),
- const SizedBox(height: 14),
- label('First task (optional)'),
- // Return adds a line; ⌘Return forks — the New Harness field's
- // own contract, so the two forms answer the keyboard alike.
- CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.enter, meta: true):
- _fork,
- },
- child: TextField(
- key: const ValueKey('fork-task'),
- controller: _task,
- focusNode: _taskFocus,
- minLines: 2,
- maxLines: 6,
- maxLength: 2000,
- cursorColor: accent,
- style: TextStyle(
- fontSize: 14,
- height: 1.4,
- color: grid.AppPalette.textPrimary,
- ),
- decoration: decoration(
- 'What should the fork work on? Sent as its first message, exactly as written.',
+ if (_attempt.awaitingConfirmation && !_busy)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: terminalPromptButton(
+ 'Start another fork',
+ _startAnother,
+ key: const Key('fork-start-another'),
+ ),
),
),
+ BoxHintStrip(
+ message: _busy
+ ? 'Waiting for fork…'
+ : (_attempt.awaitingConfirmation
+ ? 'Fork may already exist.'
+ : null),
+ isError: !_busy && _attempt.awaitingConfirmation,
+ hints: [
+ if (!_busy)
+ BoxHint(
+ terminalPromptHint(context, 'picker.accept', 'enter'),
+ _attempt.awaitingConfirmation
+ ? 'check status'
+ : (_nameFocus.hasFocus ? 'edit task' : 'fork'),
+ onTap: _nameFocus.hasFocus
+ ? _taskFocus.requestFocus
+ : _submit,
+ ),
+ if (!_locked)
+ BoxHint(
+ terminalPromptHint(context, 'picker.complete', 'tab'),
+ 'fields',
+ ),
+ if (!_locked) const BoxHint('alt-enter', 'newline'),
+ BoxHint(
+ terminalPromptHint(context, 'picker.cancel', 'esc'),
+ 'close',
+ onTap: _close,
+ ),
+ ],
),
],
),
),
- actions: [
- OutlinedButton(
- onPressed: () => Navigator.pop(context),
- style: OutlinedButton.styleFrom(
- foregroundColor: grid.AppPalette.textSecondary,
- minimumSize: const Size(88, 38),
- padding: const EdgeInsets.symmetric(horizontal: 18),
- side: const BorderSide(color: Colors.white24),
- shape: const StadiumBorder(),
- ),
- child: const Text('Cancel'),
- ),
- FilledButton(
- key: const ValueKey('fork-submit'),
- onPressed: _name.text.trim().isEmpty ? null : _fork,
- style: FilledButton.styleFrom(
- backgroundColor: grid.AppPalette.swarmAccent,
- foregroundColor: grid.AppPalette.swarmTabBar,
- minimumSize: const Size(88, 38),
- padding: const EdgeInsets.symmetric(horizontal: 18),
- shape: const StadiumBorder(),
- ),
- child: const Text('Fork'),
- ),
- ],
),
- );
- }
+ ),
+ );
}
diff --git a/desktop/lib/widgets/grid_model_picker.dart b/desktop/lib/widgets/grid_model_picker.dart
index 8cecc1a71..7b508d00f 100644
--- a/desktop/lib/widgets/grid_model_picker.dart
+++ b/desktop/lib/widgets/grid_model_picker.dart
@@ -74,6 +74,7 @@ class GridModelPicker extends StatefulWidget {
/// The agent's engine, for the subscription row's icon and label.
final String? engineLabel;
+ final bool compact;
const GridModelPicker({
super.key,
@@ -85,6 +86,7 @@ class GridModelPicker extends StatefulWidget {
this.currentModel,
this.webSearch,
this.engineLabel,
+ this.compact = false,
});
@override
@@ -401,6 +403,28 @@ class _GridModelPickerState extends State<GridModelPicker> {
@override
Widget build(BuildContext context) {
final sentence = _webSearchSentence;
+ if (widget.compact) {
+ return IconButton(
+ tooltip: sentence == null
+ ? 'Where this agent runs'
+ : 'Where this agent runs\n$sentence',
+ onPressed: _open,
+ icon: _loading
+ ? const SizedBox(
+ width: 14,
+ height: 14,
+ child: CircularProgressIndicator(strokeWidth: 1.5),
+ )
+ : const Icon(Icons.tune, size: 16),
+ style: IconButton.styleFrom(
+ foregroundColor: AppColors.mutedStrong,
+ fixedSize: const Size(28, 28),
+ minimumSize: const Size(28, 28),
+ padding: EdgeInsets.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ );
+ }
return Tooltip(
// The same sentence the menu shows, one line under the control's own — so a person can learn
// the agent has no web search without opening the menu at all.
@@ -483,7 +507,6 @@ class _ManagerInvitationState extends State<_ManagerInvitation> {
@override
Widget build(BuildContext context) {
- final rule = Expanded(child: Container(height: 1, color: AppColors.border));
return Padding(
// Wider than a row's inset on purpose: this block is not one of them.
padding: const EdgeInsets.fromLTRB(
@@ -496,20 +519,22 @@ class _ManagerInvitationState extends State<_ManagerInvitation> {
mainAxisSize: MainAxisSize.min,
children: [
Row(
+ mainAxisAlignment: MainAxisAlignment.center,
children: [
- rule,
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 10),
+ Container(width: 12, height: 1, color: AppColors.border),
+ const SizedBox(width: 8),
+ Flexible(
child: Text(
'Manage the models on your machines',
+ textAlign: TextAlign.center,
style: TextStyle(
fontSize: 10.5,
- letterSpacing: .2,
color: AppColors.mutedStrong,
),
),
),
- rule,
+ const SizedBox(width: 8),
+ Container(width: 12, height: 1, color: AppColors.border),
],
),
const SizedBox(height: 9),
@@ -517,7 +542,7 @@ class _ManagerInvitationState extends State<_ManagerInvitation> {
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
- child: GestureDetector(
+ child: InkWell(
onTap: widget.onPressed,
child: Container(
// Full width, so it reads as the section's one action rather than as a wider row.
diff --git a/desktop/lib/widgets/harness_command_bar.dart b/desktop/lib/widgets/harness_command_bar.dart
index eea84a732..3686f73ee 100644
--- a/desktop/lib/widgets/harness_command_bar.dart
+++ b/desktop/lib/widgets/harness_command_bar.dart
@@ -180,7 +180,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
itemBuilder: (_) => const [
PopupMenuItem(
value: 'new',
- child: Text('New harness'),
+ child: Text('New Harness'),
),
PopupMenuItem(
value: 'store',
@@ -485,7 +485,7 @@ class _HarnessCommandBarState extends State<HarnessCommandBar> {
),
TextButton(
onPressed: widget.onNew,
- child: const Text('New harness'),
+ child: const Text('New Harness'),
),
],
),
diff --git a/desktop/lib/widgets/harness_customize_pane.dart b/desktop/lib/widgets/harness_customize_pane.dart
index b97462024..60d6ce212 100644
--- a/desktop/lib/widgets/harness_customize_pane.dart
+++ b/desktop/lib/widgets/harness_customize_pane.dart
@@ -9,6 +9,8 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/theme/appearance_prefs_store.dart';
import '../shared/theme/harness_background.dart';
import 'swarm_wallpaper.dart';
+import 'box_chrome.dart';
+import 'prompt_customize.dart';
/// Page-local customization. Appearance and Terminal use their existing stores
/// and controls, so moving them here keeps the user's saved choices intact.
@@ -28,7 +30,7 @@ class HarnessCustomizePane extends StatelessWidget {
child: CallbackShortcuts(
bindings: {const SingleActivator(LogicalKeyboardKey.escape): onClose},
child: DefaultTabController(
- length: 3,
+ length: 4,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -39,8 +41,11 @@ class HarnessCustomizePane extends StatelessWidget {
Expanded(
child: Text(
'Customize OpenHarness',
- style: Theme.of(context).textTheme.titleMedium
- ?.copyWith(fontWeight: FontWeight.w600),
+ style: boxMonoStyle(
+ size: 14,
+ color: grid.AppPalette.textPrimary,
+ weight: FontWeight.w600,
+ ),
),
),
IconButton(
@@ -60,7 +65,9 @@ class HarnessCustomizePane extends StatelessWidget {
unselectedLabelColor: grid.AppPalette.textSecondary,
indicatorColor: grid.AppPalette.swarmAccent,
dividerColor: grid.AppPalette.divider,
+ labelStyle: boxMonoStyle(size: 12),
tabs: const [
+ Tab(key: ValueKey('customize-prompt'), text: 'Prompt'),
Tab(
key: ValueKey('customize-background'),
text: 'Wallpaper',
@@ -75,6 +82,7 @@ class HarnessCustomizePane extends StatelessWidget {
Expanded(
child: TabBarView(
children: [
+ PromptCustomize(store: store ?? appearancePrefsStore),
_Backgrounds(store: store ?? appearancePrefsStore),
const AppearanceSection(),
const TerminalSection(),
diff --git a/desktop/lib/widgets/harness_join_guide_screen.dart b/desktop/lib/widgets/harness_join_guide_screen.dart
index 8ea660241..85b89a21b 100644
--- a/desktop/lib/widgets/harness_join_guide_screen.dart
+++ b/desktop/lib/widgets/harness_join_guide_screen.dart
@@ -42,7 +42,7 @@ class _HarnessJoinGuideScreenState extends State<HarnessJoinGuideScreen> {
@override
Widget build(BuildContext context) {
final isLocal = widget.machineState.isLocalMachine;
- return Center(
+ final content = Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 460),
child: Container(
@@ -117,5 +117,19 @@ class _HarnessJoinGuideScreenState extends State<HarnessJoinGuideScreen> {
),
),
);
+ // The compact tab bar can expose this card near its size breakpoint.
+ // Keep its instructions and Retry reachable when text needs more height.
+ return LayoutBuilder(
+ builder: (context, constraints) => SingleChildScrollView(
+ child: ConstrainedBox(
+ constraints: BoxConstraints(
+ minHeight: constraints.maxHeight.isFinite
+ ? constraints.maxHeight
+ : 0,
+ ),
+ child: content,
+ ),
+ ),
+ );
}
}
diff --git a/desktop/lib/widgets/harness_start_page.dart b/desktop/lib/widgets/harness_start_page.dart
index f131ddb97..4e932263b 100644
--- a/desktop/lib/widgets/harness_start_page.dart
+++ b/desktop/lib/widgets/harness_start_page.dart
@@ -6,7 +6,7 @@ import '../shared/theme/appearance_prefs_store.dart';
import '../shared/theme/harness_background.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
-import 'harness_entry_actions.dart';
+import 'box_chrome.dart';
import 'harness_customize_pane.dart';
import 'swarm_search_input.dart';
import 'swarm_switcher.dart';
@@ -19,12 +19,25 @@ class HarnessStartPage extends StatefulWidget {
required this.focusNode,
required this.createSearch,
required this.onNew,
+ this.onNewTab,
+ this.onNewPane,
+ this.onCommands,
+ this.onQuickStart,
+ this.onPractice,
+ this.onNewWithTask,
required this.onChoose,
this.onStore,
});
final FocusNode focusNode;
final SwarmSearchController Function() createSearch;
final VoidCallback onNew;
+ final VoidCallback? onNewTab, onNewPane;
+ final VoidCallback? onCommands;
+ final VoidCallback? onQuickStart, onPractice;
+
+ /// New Harness with what was typed in the search as its first message: the
+ /// button and ⌘N must not throw away what the create row would have kept.
+ final ValueChanged<String>? onNewWithTask;
final ValueChanged<SwarmSearchSelection> onChoose;
/// Open the Harness Store. Null hides its card (a build without one).
@@ -87,8 +100,13 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
}
void _new() {
+ final task = _search?.createTask;
_close();
- widget.onNew();
+ if (task != null && widget.onNewWithTask != null) {
+ widget.onNewWithTask!(task);
+ } else {
+ widget.onNew();
+ }
}
Widget _searchPanel() => TextFieldTapRegion(
@@ -112,12 +130,18 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
onClose: _close,
onOpen: _open,
onNewAgent: _new,
+ onCommands: widget.onCommands == null
+ ? null
+ : () {
+ _close();
+ widget.onCommands!();
+ },
onRefocus: _focus.requestFocus,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Semantics(
- label: 'Find a harness',
+ label: kHarnessPickerHint,
child: SwarmSearchInput(
inputKey: const ValueKey('harness-start-search'),
controller: _query,
@@ -130,9 +154,13 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
groupId: _searchGroup,
autofocus: true,
showClose: _showResults,
- hintText: 'Find a harness',
+ hintText: kHarnessPickerHint,
rounded: true,
prominent: true,
+ // The same `4 of 31` the box shows: this is the same box.
+ trailing: _search == null
+ ? null
+ : SwarmSearchCount(search: _search!),
),
),
if (_showResults) ...[
@@ -140,13 +168,44 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
child: Padding(
padding: const EdgeInsets.only(bottom: 12),
child: SizedBox(
- height: 480,
- child: SwarmSearchResults(
- key: const ValueKey('harness-start-results'),
- search: _search!,
- sideBySideMinWidth: 700,
- onChoose: _choose,
- onRefocus: _focus.requestFocus,
+ // The results keep their 480; the hint line is extra.
+ height: 480 + 32,
+ child: LayoutBuilder(
+ builder: (context, box) => Column(
+ children: [
+ Expanded(
+ child: SwarmSearchResults(
+ key: const ValueKey('harness-start-results'),
+ search: _search!,
+ sideBySideMinWidth: 700,
+ onChoose: _choose,
+ onRefocus: _focus.requestFocus,
+ ),
+ ),
+ // The same bottom line ⌘P has: this is the first box a
+ // new person sees, and the one that most needs to say
+ // what the keys are. On a window too short for both,
+ // the results keep the room.
+ if (box.maxHeight >= 500)
+ SwarmSearchHints(
+ search: _search!,
+ onSubmit: () {
+ final choice = _search!.submit();
+ if (choice != null) _choose(choice);
+ },
+ onQuery: (text) {
+ _query.value = TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(
+ offset: text.length,
+ ),
+ );
+ _search!.setQuery(text);
+ _focus.requestFocus();
+ },
+ ),
+ ],
+ ),
),
),
),
@@ -394,11 +453,52 @@ class _HarnessStartPageState extends State<HarnessStartPage> {
Flexible(child: _searchPanel()),
if (!_showResults) ...[
const SizedBox(height: 20),
- HarnessEntryActions(
- onOpen: _open,
- onNew: _new,
- openKey: const ValueKey('harness-start-open'),
- newKey: const ValueKey('harness-start-new'),
+ Wrap(
+ spacing: 12,
+ runSpacing: 12,
+ children: [
+ OutlinedButton.icon(
+ key: const ValueKey(
+ 'harness-start-new-tab',
+ ),
+ onPressed: widget.onNewTab ?? _open,
+ icon: const Icon(Icons.add, size: 18),
+ label: const Text('New Tab'),
+ ),
+ OutlinedButton.icon(
+ key: const ValueKey(
+ 'harness-start-new-pane',
+ ),
+ onPressed: widget.onNewPane ?? _open,
+ icon: const Icon(
+ Icons.add_box_outlined,
+ size: 18,
+ ),
+ label: const Text('New Pane'),
+ ),
+ if (widget.onQuickStart != null)
+ TextButton(
+ key: const ValueKey(
+ 'harness-start-quick-start',
+ ),
+ onPressed: widget.onQuickStart,
+ child: Text(
+ 'Quick start · 4 steps',
+ style: boxMonoStyle(size: 12),
+ ),
+ ),
+ if (widget.onPractice != null)
+ TextButton(
+ key: const ValueKey(
+ 'harness-start-practice',
+ ),
+ onPressed: widget.onPractice,
+ child: Text(
+ 'Keyboard practice',
+ style: boxMonoStyle(size: 12),
+ ),
+ ),
+ ],
),
],
],
diff --git a/desktop/lib/widgets/layout_palette.dart b/desktop/lib/widgets/layout_palette.dart
index 8dfff1d58..67648d1cb 100644
--- a/desktop/lib/widgets/layout_palette.dart
+++ b/desktop/lib/widgets/layout_palette.dart
@@ -9,7 +9,7 @@ import '../shortcuts/keymap.dart';
import '../state/pane_preset.dart';
import '../theme/app_theme.dart';
-/// ⌘S — pick the shape of the grid.
+/// ⇧⌘L — pick the shape of the grid.
///
/// Shapes are DRAWN, not listed. "Two over one" and "one over two" are the same
/// four words in a different order, and nobody reads a layout name twice; the
@@ -17,15 +17,15 @@ import '../theme/app_theme.dart';
///
/// Every card describes a distinct concrete arrangement. Automatic defaults
/// resolve to the matching card, instead of adding a duplicate picture.
-/// Set while the palette is up, so a second ⌘S can be answered rather than
+/// Set while the palette is up, so a second ⇧⌘L can be answered rather than
/// stacking a route.
///
/// It used to be a bool and a bare return. That stopped the palette fading the
/// window to black under a held key — each press laid another dialog and another
-/// 30% barrier over the last — but it left ⌘S meaning "open" once and nothing
+/// 30% barrier over the last — but it left ⇧⌘L meaning "open" once and nothing
/// ever after, which is the one thing a person holding a key does not expect.
///
-/// THE SAME KEY WALKS THE STRIP. ⌘S opens it, ⌘S again steps to the next shape,
+/// THE SAME KEY WALKS THE STRIP. ⇧⌘L opens it, ⇧⌘L again steps to the next shape,
/// Enter takes it. That is how every cycling chord on this OS behaves, and it
/// means the shape can be chosen without the hand leaving the chord it arrived
/// on.
@@ -107,7 +107,7 @@ class _LayoutPaletteState extends State<_LayoutPalette> {
/// `autofocus: true` alone was not enough: it only takes the focus when the
/// enclosing scope has none to give, and by the time this is laid out the
/// route that opened it has already settled focus somewhere. The symptom was
- /// precise — ⌘S opened the palette and cycled it, because that chord is a
+ /// precise — ⇧⌘L opened the palette and cycled it, because that chord is a
/// global binding, while the arrow keys did nothing at all, because those are
/// read HERE and nothing here was listening.
final FocusNode _keys = FocusNode(debugLabel: 'layout-palette');
@@ -123,7 +123,7 @@ class _LayoutPaletteState extends State<_LayoutPalette> {
});
// Registered here rather than by the opener, so the hook cannot outlive the
// widget it steps: a stale callback would move a cursor on a palette that
- // is no longer on screen, and the next ⌘S would find the strip already
+ // is no longer on screen, and the next ⇧⌘L would find the strip already
// walked.
_layoutPaletteAdvance = _advance;
}
diff --git a/desktop/lib/widgets/link_another_machine_dialog.dart b/desktop/lib/widgets/link_another_machine_dialog.dart
index bb59eea0b..c1105ddd2 100644
--- a/desktop/lib/widgets/link_another_machine_dialog.dart
+++ b/desktop/lib/widgets/link_another_machine_dialog.dart
@@ -1,1080 +1,841 @@
import 'dart:async';
-import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:url_launcher/url_launcher.dart';
-import '../core/test_run.dart';
-import '../shared/theme/app_theme.dart' as grid;
+import '../core/fuzzy_match.dart';
import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_commands.dart' show describeKeyBinding;
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
import 'link_machine_dialog.dart';
import 'link_machine_screen.dart';
-/// The one-liner a server runs to get the CLI. The same script the app's own
-/// first-run setup drives (`environment_provisioner.dart`), without the
-/// `--desktop` half: a server has no app to set up around it.
+/// Commands run on the OTHER machine. Copying never executes them locally.
const String kLinkServerInstallCommand =
'curl -fsSL https://cdn.autonomous.ai/harness/cli/install.sh | bash';
const String kLinkServerLoginCommand = 'harness login';
const String kLinkServerStartCommand =
'harness start && harness remote-password set';
-
-/// Where the app is downloaded from, for the other computer.
final Uri kHarnessDownloadUrl = Uri.parse('https://www.autonomous.ai/harness');
-/// Link another machine — reach its agents from here.
-///
-/// The old dialog said "on the other machine, sign in to Harness and start
-/// the daemon" and printed two commands. It never said WHICH machine, HOW
-/// Harness gets onto it, or that a third step — the remote password — is what
-/// actually makes the link; people read it as one obscure instruction.
-///
-/// This one leads with the question that decides every step after it: is the
-/// other machine a computer with a screen, or a server reached over SSH? Then
-/// it shows the steps for that answer only — install, sign in as THIS
-/// account, set a remote password — each something the person does, in order,
-/// with a copy button wherever there is a command. The list at the bottom is
-/// live: the moment the other machine signs in it appears, and the row itself
-/// carries the last step (Enter password → [showLinkMachineScreenDialog]).
Future<void> showLinkAnotherMachineDialog(
BuildContext context,
- AppNotifier notifier,
-) {
+ AppNotifier notifier, {
+ AppKeymap? keymap,
+}) {
+ final activeKeymap = keymap ?? KeymapTheme.of(context, listen: false);
return showAppDialog<void>(
context: context,
- builder: (_) => _LinkAnotherMachineDialog(notifier: notifier),
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ veilTint: Colors.transparent,
+ builder: (_) {
+ final dialog = _LinkAnotherMachineDialog(notifier: notifier);
+ return activeKeymap == null
+ ? dialog
+ : KeymapProvider(keymap: activeKeymap, child: dialog);
+ },
);
}
-enum _Where { computer, server }
+enum _Guide { desktop, server }
+
+class _LinkEntry {
+ const _LinkEntry(this.id, this.name, this.detail, {this.machine});
+ final String id, name, detail;
+ final MachineState? machine;
+ bool get enabled => machine == null || machine!.needsLink;
+}
class _LinkAnotherMachineDialog extends StatefulWidget {
const _LinkAnotherMachineDialog({required this.notifier});
-
final AppNotifier notifier;
-
@override
State<_LinkAnotherMachineDialog> createState() =>
_LinkAnotherMachineDialogState();
}
class _LinkAnotherMachineDialogState extends State<_LinkAnotherMachineDialog> {
- AppNotifier get notifier => widget.notifier;
+ AppNotifier get app => widget.notifier;
+ final _query = TextEditingController();
+ final _inputFocus = FocusNode(debugLabel: 'Find a machine to link');
+ final _guideFocus = FocusNode(debugLabel: 'Machine setup first action');
+ final _announcer = BoxAnnouncer();
+ final _rowKeys = <String, GlobalKey>{};
+ _Guide? _guide;
+ String? _selectedId;
+ String? _message;
+ bool _error = false;
+ bool _refreshing = false;
+ bool _nested = false;
+ int _copyRevision = 0;
+ Timer? _messageTimer;
+
+ bool get _composing =>
+ _query.value.composing.isValid && !_query.value.composing.isCollapsed;
+ bool get _mac => Theme.of(context).platform == TargetPlatform.macOS;
+
+ String _hint(String command, String fallback) {
+ final map = KeymapTheme.of(context);
+ if (map == null) return fallback;
+ final bindings = map
+ .bindings(command, context: KeymapContext.picker)
+ .toList();
+ final preferred =
+ bindings.where((binding) => binding.custom).firstOrNull ??
+ (command == 'picker.refresh' && !_mac
+ ? bindings
+ .where(
+ (binding) =>
+ binding.keys.length == 1 && binding.keys.first.control,
+ )
+ .firstOrNull
+ : null) ??
+ bindings.firstOrNull;
+ return preferred == null ? 'click' : describeKeyBinding(preferred);
+ }
- _Where _where = _Where.computer;
+ void _accept() {
+ if (_nested || _composing) return;
+ if (_guide == null && _inputFocus.hasFocus) {
+ unawaited(_open(_selected));
+ } else if (FocusManager.instance.primaryFocus?.context case final target?) {
+ Actions.maybeInvoke(target, const ActivateIntent());
+ }
+ }
- /// The remote machines on the list when the dialog opened. A machine not in
- /// this set is the one the person is linking right now: its arrival is what
- /// collapses the steps and puts the row in front of them.
- late final Set<String> _known = _remoteIds();
+ Widget _keys(Widget child) {
+ if (KeymapTheme.of(context) == null) return child;
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: () => _composing,
+ actions: {
+ 'picker.accept': _accept,
+ 'picker.add_here': _accept,
+ 'picker.next': () => _guide == null && _inputFocus.hasFocus
+ ? _move(1)
+ : FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.previous': () => _guide == null && _inputFocus.hasFocus
+ ? _move(-1)
+ : FocusManager.instance.primaryFocus?.previousFocus(),
+ 'picker.cancel': _back,
+ 'picker.refresh': () => unawaited(_refresh()),
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ },
+ // A deliberately unbound Escape must not dismiss via the route's
+ // fallback shortcut. Configured cancel keys own this prompt.
+ child: Actions(
+ actions: {
+ DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
+ },
+ child: child,
+ ),
+ );
+ }
- /// Steps hidden behind "Show the steps again" once a machine has appeared.
- bool _stepsCollapsed = false;
+ List<MachineState> get _remotes =>
+ app.machineStates.values.where((state) => !state.isLocalMachine).toList()
+ ..sort((a, b) {
+ if (a.needsLink != b.needsLink) return a.needsLink ? -1 : 1;
+ return a.machine.displayName.toLowerCase().compareTo(
+ b.machine.displayName.toLowerCase(),
+ );
+ });
+
+ List<_LinkEntry> get _entries {
+ final rows = [
+ for (final state in _remotes)
+ _LinkEntry(
+ 'machine:${state.machine.machineId}',
+ state.machine.displayName,
+ '${state.nodeOnline == false
+ ? 'offline'
+ : state.nodeOnline == true
+ ? 'online'
+ : 'checking'}'
+ ' · ${state.needsLink ? 'enter remote password' : 'already linked'}',
+ machine: state,
+ ),
+ const _LinkEntry(
+ 'desktop',
+ 'Set up a desktop',
+ 'macOS or Linux · install the app',
+ ),
+ const _LinkEntry(
+ 'server',
+ 'Set up a server over SSH',
+ 'install the CLI on the other machine',
+ ),
+ const _LinkEntry(
+ 'password',
+ 'This computer’s password',
+ 'let another machine connect here',
+ ),
+ ];
+ final query = _query.text.trim().toLowerCase();
+ if (query.isEmpty) return rows;
+ final words = query.split(RegExp(r'\s+'));
+ final ranked = <(int, int, _LinkEntry)>[];
+ for (final (index, entry) in rows.indexed) {
+ final text = '${entry.name} ${entry.detail}'.toLowerCase();
+ var score = 0;
+ var matches = true;
+ for (final word in words) {
+ final literal = text.indexOf(word);
+ if (literal >= 0) {
+ score += literal;
+ } else {
+ final spread = subsequenceSpread(text, word);
+ if (spread == null) {
+ matches = false;
+ break;
+ }
+ score += 1000 + spread;
+ }
+ }
+ if (matches) ranked.add((score, index, entry));
+ }
+ ranked.sort((a, b) {
+ final score = a.$1.compareTo(b.$1);
+ return score == 0 ? a.$2.compareTo(b.$2) : score;
+ });
+ return ranked.map((rank) => rank.$3).toList();
+ }
+
+ _LinkEntry? get _selected {
+ final rows = _entries;
+ return rows.where((row) => row.id == _selectedId).firstOrNull ??
+ rows.firstOrNull;
+ }
- /// The command most recently copied, for the button to say so.
- String? _copied;
- Timer? _copiedTimer;
+ @override
+ void initState() {
+ super.initState();
+ _selectedId = _entries.where((entry) => entry.enabled).firstOrNull?.id;
+ _focusInput();
+ }
@override
void dispose() {
- _copiedTimer?.cancel();
+ _messageTimer?.cancel();
+ _query.dispose();
+ _inputFocus.dispose();
+ _guideFocus.dispose();
super.dispose();
}
- Set<String> _remoteIds() => {
- for (final state in notifier.machineStates.values)
- if (!state.isLocalMachine) state.machine.machineId,
- };
+ void _focusInput() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _inputFocus.requestFocus();
+ _reveal();
+ }
+ });
+ }
+
+ void _reveal() {
+ final row = _selected;
+ if (row == null || _guide != null) return;
+ final rowContext = _rowKeys[row.id]?.currentContext;
+ if (rowContext != null) Scrollable.ensureVisible(rowContext, alignment: .5);
+ }
+
+ void _changed(String _) {
+ setState(
+ () => _selectedId =
+ (_query.text.trim().isEmpty
+ ? _entries.where((entry) => entry.enabled)
+ : _entries)
+ .firstOrNull
+ ?.id,
+ );
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _reveal();
+ });
+ }
- List<MachineState> _remotes() =>
- notifier.machineStates.values.where((m) => !m.isLocalMachine).toList();
+ void _move(int step) {
+ final rows = _entries;
+ if (rows.isEmpty) return;
+ final at = rows.indexWhere((row) => row.id == _selected?.id);
+ final next = (at + step).clamp(0, rows.length - 1);
+ setState(() => _selectedId = rows[next].id);
+ _announcer.row(context, '${rows[next].name}, ${rows[next].detail}');
+ _reveal();
+ }
- MachineState? _arrived() {
- for (final state in _remotes()) {
- if (!_known.contains(state.machine.machineId)) return state;
+ void _say(String message, {bool error = false, bool transient = false}) {
+ if (!mounted) return;
+ _messageTimer?.cancel();
+ setState(() {
+ _message = message;
+ _error = error;
+ });
+ _announcer.row(context, message);
+ if (transient) {
+ _messageTimer = Timer(const Duration(seconds: 3), () {
+ if (mounted) setState(() => _message = null);
+ });
}
- return null;
}
- Future<void> _copy(String text) async {
+ Future<void> _copy(String text, {bool command = true}) async {
+ final revision = ++_copyRevision;
try {
await Clipboard.setData(ClipboardData(text: text));
+ if (mounted && revision == _copyRevision) {
+ _say(
+ command
+ ? 'Copied. Run on the other machine.'
+ : 'Download link copied.',
+ transient: true,
+ );
+ }
} catch (_) {
- return; // no clipboard here; the text is on screen to select
+ if (mounted && revision == _copyRevision) {
+ _say(
+ 'Could not copy. Select the text to copy it, or try again.',
+ error: true,
+ );
+ }
}
- if (!mounted) return;
- _copiedTimer?.cancel();
- setState(() => _copied = text);
- _copiedTimer = Timer(const Duration(milliseconds: 1600), () {
- if (mounted) setState(() => _copied = null);
- });
}
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- return ListenableBuilder(
- listenable: notifier,
- builder: (context, _) {
- final arrived = _arrived();
- // A machine just signed in: the steps have done their job, and the
- // row that finishes the link takes their room. Only ever collapses
- // on its own — the person reopens them with the link below.
- if (arrived != null && !_stepsCollapsed && !_reopenedSteps) {
- _stepsCollapsed = true;
- }
- final remotes = _remotes();
- final email = notifier.currentUser?.email;
- return Dialog(
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 560),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Padding(
- padding: const EdgeInsets.fromLTRB(22, 20, 22, 0),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- 'Link another machine',
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 16,
- fontWeight: grid.AppFont.semibold,
- ),
- ),
- const SizedBox(height: 4),
- Text(
- _stepsCollapsed
- ? 'Reach its agents from here, end-to-end encrypted.'
- : 'Reach its agents from here, end-to-end encrypted. '
- 'Where does it live?',
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 12.5,
- ),
- ),
- ],
- ),
- ),
- Flexible(
- child: SingleChildScrollView(
- padding: const EdgeInsets.fromLTRB(22, 16, 22, 18),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (_stepsCollapsed) ...[
- _ArrivedSummary(machine: arrived),
- ] else ...[
- _WhereChooser(
- where: _where,
- onChanged: (w) => setState(() => _where = w),
- ),
- const SizedBox(height: 16),
- if (_where == _Where.computer)
- _ComputerSteps(email: email)
- else
- _ServerSteps(
- email: email,
- copied: _copied,
- onCopy: _copy,
- ),
- ],
- const SizedBox(height: 16),
- if (remotes.isEmpty)
- const _WaitingStrip()
- else
- _MachineList(
- machines: remotes,
- arrivedId: arrived?.machine.machineId,
- onEnterPassword: (id) =>
- showLinkMachineScreenDialog(
- context,
- notifier,
- id,
- ),
- ),
- if (_stepsCollapsed) ...[
- const SizedBox(height: 12),
- _NotSeeingIt(
- email: email,
- onShowSteps: () => setState(() {
- _stepsCollapsed = false;
- _reopenedSteps = true;
- }),
- ),
- ],
- ],
- ),
- ),
- ),
- _Footer(
- linked: remotes.where((m) => !m.needsLink).length,
- showCopyAll: !_stepsCollapsed && _where == _Where.server,
- copiedAll: _copied == _allServerCommands,
- onCopyAll: () => _copy(_allServerCommands),
- onRefresh: _stepsCollapsed ? notifier.refreshMachines : null,
- onThisMachine: () =>
- unawaited(showLinkMachineDialog(context, notifier)),
- onClose: () => Navigator.of(context).pop(),
- ),
- ],
- ),
- ),
- );
- },
- );
+ Future<void> _refresh() async {
+ if (_refreshing || app.machinesRefreshing) return;
+ setState(() => _refreshing = true);
+ try {
+ await app.retryMachines();
+ if (!mounted) return;
+ final error = app.machineListError ?? app.lastError;
+ if (error != null) {
+ _say(error, error: true);
+ } else {
+ _say('Machine list refreshed.', transient: true);
+ }
+ } catch (_) {
+ _say('Could not refresh machines. Try again.', error: true);
+ } finally {
+ if (mounted) setState(() => _refreshing = false);
+ }
}
- /// Once the person asked for the steps back, an arrival must not fold them
- /// away again under their eyes.
- bool _reopenedSteps = false;
-
- static const String _allServerCommands =
- '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand';
-}
-
-// ── the fork ────────────────────────────────────────────────────────────────
+ Future<void> _download() async {
+ try {
+ if (await launchUrl(
+ kHarnessDownloadUrl,
+ mode: LaunchMode.externalApplication,
+ )) {
+ return;
+ }
+ } catch (_) {
+ // Keep recovery in the guide if the platform has no browser handler.
+ }
+ _say(
+ 'Could not open the browser. Copy the download link instead.',
+ error: true,
+ );
+ }
-class _WhereChooser extends StatelessWidget {
- const _WhereChooser({required this.where, required this.onChanged});
+ void _back() {
+ if (_guide == null) {
+ Navigator.of(context).pop();
+ } else {
+ setState(() => _guide = null);
+ _focusInput();
+ }
+ }
- final _Where where;
- final ValueChanged<_Where> onChanged;
+ void _openGuide(_Guide guide) {
+ setState(() => _guide = guide);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _guideFocus.requestFocus();
+ }
+ });
+ }
- @override
- Widget build(BuildContext context) {
- return Row(
- children: [
- Expanded(
- child: _WhereCard(
- icon: LucideIcons.monitor300,
- title: 'A computer with a screen',
- detail: 'Mac or Linux desktop. Install the OpenHarness app there.',
- selected: where == _Where.computer,
- onTap: () => onChanged(_Where.computer),
- ),
- ),
- const SizedBox(width: 8),
- Expanded(
- child: _WhereCard(
- icon: LucideIcons.server300,
- title: 'A server over SSH',
- detail: 'Headless box. Install the CLI with one command.',
- selected: where == _Where.server,
- onTap: () => onChanged(_Where.server),
- ),
- ),
- ],
- );
+ Future<void> _open(_LinkEntry? entry) async {
+ if (entry == null || !entry.enabled || _nested || _composing) return;
+ setState(() => _selectedId = entry.id);
+ if (entry.id == 'desktop' || entry.id == 'server') {
+ _openGuide(entry.id == 'desktop' ? _Guide.desktop : _Guide.server);
+ return;
+ }
+ setState(() => _nested = true);
+ final previous = FocusManager.instance.primaryFocus;
+ try {
+ if (entry.machine case final state?) {
+ final id = state.machine.machineId;
+ if (app.stateOf(id)?.needsLink != true) return;
+ await showLinkMachineScreenDialog(context, app, id);
+ if (mounted && app.stateOf(id)?.needsLink == false) {
+ _say('${state.machine.displayName} is linked.', transient: true);
+ }
+ } else {
+ await showLinkMachineDialog(context, app);
+ }
+ } finally {
+ if (mounted) setState(() => _nested = false);
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ if (_guide == null) {
+ _focusInput();
+ } else if (previous?.context != null && previous!.canRequestFocus) {
+ previous.requestFocus();
+ } else {
+ _guideFocus.requestFocus();
+ }
+ }
+ }
}
-}
-class _WhereCard extends StatelessWidget {
- const _WhereCard({
- required this.icon,
- required this.title,
- required this.detail,
- required this.selected,
- required this.onTap,
- });
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ if (_nested) return KeyEventResult.ignored;
+ final keys = HardwareKeyboard.instance;
+ final key = event.logicalKey;
+ final plain =
+ !keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed;
+ final ctrl =
+ keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed;
+ final refresh =
+ key == LogicalKeyboardKey.keyR &&
+ (_mac
+ ? keys.isMetaPressed && !keys.isControlPressed
+ : keys.isControlPressed && !keys.isMetaPressed) &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed;
+ final escape = plain && key == LogicalKeyboardKey.escape;
+ final enter =
+ plain &&
+ (key == LogicalKeyboardKey.enter ||
+ key == LogicalKeyboardKey.numpadEnter);
+ final down =
+ (plain && key == LogicalKeyboardKey.arrowDown) ||
+ (ctrl &&
+ (key == LogicalKeyboardKey.keyN || key == LogicalKeyboardKey.keyJ));
+ final up =
+ (plain && key == LogicalKeyboardKey.arrowUp) ||
+ (ctrl &&
+ (key == LogicalKeyboardKey.keyP || key == LogicalKeyboardKey.keyK));
+ if (_composing && (escape || enter || up || down || refresh)) {
+ return KeyEventResult.skipRemainingHandlers;
+ }
+ if (KeymapTheme.of(context, listen: false) != null) {
+ // The host already had first use of configured keys. Don't turn an
+ // unbound physical Enter into EditableText's native submit action.
+ return enter && _inputFocus.hasFocus
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ if (escape) {
+ _back();
+ } else if (refresh) {
+ unawaited(_refresh());
+ } else if (_guide == null && _inputFocus.hasFocus && (up || down)) {
+ _move(down ? 1 : -1);
+ } else if (_guide == null && _inputFocus.hasFocus && enter) {
+ unawaited(_open(_selected));
+ } else {
+ return KeyEventResult.ignored;
+ }
+ return KeyEventResult.handled;
+ }
- final IconData icon;
- final String title;
- final String detail;
- final bool selected;
- final VoidCallback onTap;
+ Widget _button(
+ String label,
+ VoidCallback action, {
+ FocusNode? focus,
+ Key? key,
+ }) => TextButton(
+ key: key,
+ focusNode: focus,
+ onPressed: action,
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white70,
+ textStyle: boxMonoStyle(size: 12),
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 5),
+ minimumSize: const Size(0, 28),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(2)),
+ ),
+ child: Text(label),
+ );
- @override
- Widget build(BuildContext context) {
- final accent = grid.AppPalette.accentOnSurface;
+ Widget _machineRow(_LinkEntry entry, {bool picker = false}) {
+ final selected = picker && entry.id == _selected?.id;
return Semantics(
- button: true,
selected: selected,
+ button: entry.enabled,
+ enabled: entry.enabled,
child: InkWell(
- onTap: onTap,
- borderRadius: BorderRadius.circular(10),
- child: AnimatedContainer(
- duration: const Duration(milliseconds: 120),
- padding: const EdgeInsets.fromLTRB(12, 11, 12, 11),
- decoration: BoxDecoration(
- color: selected
- ? accent.withValues(alpha: 0.08)
- : grid.AppCard.inset,
- borderRadius: BorderRadius.circular(10),
- border: Border.all(
- color: selected ? accent : grid.AppPalette.divider,
- width: selected ? 1.5 : 1,
- ),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- width: 30,
- height: 30,
- decoration: BoxDecoration(
- color: selected
- ? accent.withValues(alpha: 0.16)
- : grid.AppSurface.recess,
- borderRadius: BorderRadius.circular(8),
- ),
- alignment: Alignment.center,
- child: Icon(
- icon,
- size: 16,
- color: selected ? accent : grid.AppPalette.textSecondary,
+ key: picker
+ ? _rowKeys.putIfAbsent(entry.id, GlobalKey.new)
+ : ValueKey('link-row-${entry.machine?.machine.machineId}'),
+ canRequestFocus: !picker,
+ onTap: entry.enabled ? () => unawaited(_open(entry)) : null,
+ child: BoxRowHighlight(
+ highlighted: selected,
+ accent: Colors.white70,
+ terminal: true,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 20,
+ child: Text(
+ selected ? '>' : ' ',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
),
- ),
- const SizedBox(width: 10),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- title,
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 13,
- fontWeight: grid.AppFont.semibold,
- height: 1.3,
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ entry.name,
+ style: boxMonoStyle(
+ weight: selected ? FontWeight.w600 : null,
+ ),
),
- ),
- const SizedBox(height: 2),
- Text(
- detail,
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 11.5,
- height: 1.35,
+ Text(
+ entry.detail,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
),
- ),
- ],
+ ],
+ ),
),
- ),
- ],
+ ],
+ ),
),
),
),
);
}
-}
-
-// ── the steps ───────────────────────────────────────────────────────────────
-
-class _ComputerSteps extends StatelessWidget {
- const _ComputerSteps({required this.email});
- final String? email;
-
- @override
- Widget build(BuildContext context) {
- final who = email ?? 'the same account';
+ Widget _guideBody() {
+ final server = _guide == _Guide.server;
+ final email = app.currentUser?.email ?? 'the same account as this computer';
+ final remotes = _remotes.where((state) => state.needsLink).toList();
return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- _Step(
- number: 1,
- title: 'Install OpenHarness on that computer',
- detail: TextSpan(
- children: [
- const TextSpan(text: 'Download from '),
- _linkSpan(context, 'autonomous.ai/harness', kHarnessDownloadUrl),
- const TextSpan(text: ' — macOS and Linux.'),
- ],
- ),
+ Text(
+ 'On the other ${server ? 'machine, over SSH' : 'computer'}:',
+ style: boxMonoStyle(weight: FontWeight.w600),
),
- _Step(
- number: 2,
- title: 'Sign in with the same account',
- detail: TextSpan(
- children: [
- const TextSpan(text: 'You are '),
- _strongSpan(who),
- const TextSpan(
- text:
- ' here. The other computer must sign in as the same '
- 'person — that is what puts it on your list.',
- ),
- ],
+ const SizedBox(height: 12),
+ if (server) ...[
+ _command(
+ '1. Install the CLI (skip if installed)',
+ kLinkServerInstallCommand,
+ first: true,
),
- ),
- _Step(
- number: 3,
- title: 'Set a remote password there',
- detail: TextSpan(
- children: [
- const TextSpan(
- text: 'In that app: account menu (bottom of the rail) → ',
- ),
- _strongSpan('Remote into another machine…'),
- const TextSpan(text: ' → '),
- _strongSpan('Set password'),
- const TextSpan(
- text:
- '. You will type it here, once, when the machine appears '
- 'below.',
- ),
- ],
+ _command('2. Sign in as $email', kLinkServerLoginCommand),
+ Text(
+ 'Open the printed sign-in link in a browser on any device.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
),
- ),
- ],
- );
- }
-}
-
-class _ServerSteps extends StatelessWidget {
- const _ServerSteps({
- required this.email,
- required this.copied,
- required this.onCopy,
- });
-
- final String? email;
- final String? copied;
- final ValueChanged<String> onCopy;
-
- @override
- Widget build(BuildContext context) {
- final who = email ?? 'the same account';
- return Column(
- children: [
- _Step(
- number: 1,
- title: 'Install the Harness CLI',
- detail: TextSpan(
- children: [
- const TextSpan(
- text: 'Run this on the server. Installs Node, tmux and ',
- ),
- _codeSpan('harness'),
- const TextSpan(text: ' under '),
- _codeSpan('~/.harness'),
- const TextSpan(text: '; nothing system-wide.'),
- ],
+ _command(
+ '3. Start Harness and set a remote password',
+ kLinkServerStartCommand,
),
- command: kLinkServerInstallCommand,
- copied: copied == kLinkServerInstallCommand,
- onCopy: () => onCopy(kLinkServerInstallCommand),
- ),
- _Step(
- number: 2,
- title: 'Sign in as $who',
- detail: TextSpan(
- children: [
- const TextSpan(text: 'Prints a link — open it in a browser on '),
- _strongSpan('any'),
- const TextSpan(
- text: ' device, sign in, and the server picks it up.',
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Copy all three commands',
+ () => unawaited(
+ _copy(
+ '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand',
+ ),
),
- ],
+ key: const Key('link-copy-all'),
+ ),
),
- command: kLinkServerLoginCommand,
- copied: copied == kLinkServerLoginCommand,
- onCopy: () => onCopy(kLinkServerLoginCommand),
- ),
- _Step(
- number: 3,
- title: 'Start it, and set a remote password',
- detail: const TextSpan(
- text:
- 'The password is what this computer will type, once, to open '
- 'the encrypted link. Choose any; it stays on the server.',
+ ] else ...[
+ Text(
+ '1. Install OpenHarness for macOS or Linux.',
+ style: boxMonoStyle(size: 12),
),
- command: kLinkServerStartCommand,
- copied: copied == kLinkServerStartCommand,
- onCopy: () => onCopy(kLinkServerStartCommand),
- ),
- ],
- );
- }
-}
-
-TextSpan _strongSpan(String text) => TextSpan(
- text: text,
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontWeight: grid.AppFont.medium,
- ),
-);
-
-TextSpan _codeSpan(String text) => TextSpan(
- text: text,
- style: TextStyle(
- fontFamily: grid.AppFont.mono,
- fontFamilyFallback: grid.AppFont.monoFallback,
- fontSize: 11.5,
- color: grid.AppPalette.textSecondary,
- ),
-);
-
-TextSpan _linkSpan(BuildContext context, String text, Uri url) => TextSpan(
- text: text,
- style: TextStyle(
- color: grid.AppPalette.accentOnSurface,
- decoration: TextDecoration.underline,
- decorationColor: grid.AppPalette.accentOnSurface.withValues(alpha: 0.4),
- ),
- recognizer: TapGestureRecognizer()
- ..onTap = () =>
- unawaited(launchUrl(url, mode: LaunchMode.externalApplication)),
-);
-
-/// One numbered step: a title, a line under it, and — for a server — the
-/// command with its own copy button.
-class _Step extends StatelessWidget {
- const _Step({
- required this.number,
- required this.title,
- required this.detail,
- this.command,
- this.copied = false,
- this.onCopy,
- this.done = false,
- });
-
- final int number;
- final String title;
- final InlineSpan detail;
- final String? command;
- final bool copied;
- final VoidCallback? onCopy;
- final bool done;
-
- @override
- Widget build(BuildContext context) {
- return Container(
- padding: EdgeInsets.fromLTRB(0, number == 1 ? 2 : 10, 0, 10),
- decoration: number == 1
- ? null
- : BoxDecoration(
- border: Border(top: BorderSide(color: grid.AppCard.insetHair)),
- ),
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- _StepNumber(number: number, done: done),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- title,
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 13,
- fontWeight: grid.AppFont.medium,
- ),
- ),
- const SizedBox(height: 2),
- Text.rich(
- detail,
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 12,
- height: 1.45,
- ),
- ),
- if (command != null) ...[
- const SizedBox(height: 8),
- _CommandLine(
- command: command!,
- copied: copied,
- onCopy: onCopy,
- ),
- ],
- ],
- ),
+ const SizedBox(height: 4),
+ SelectableText(
+ kHarnessDownloadUrl.toString(),
+ style: boxMonoStyle(size: 12, color: Colors.white70),
),
- ],
- ),
- );
- }
-}
-
-class _StepNumber extends StatelessWidget {
- const _StepNumber({required this.number, required this.done});
-
- final int number;
- final bool done;
-
- @override
- Widget build(BuildContext context) {
- final ok = grid.AppPalette.online;
- return Container(
- width: 22,
- height: 22,
- margin: const EdgeInsets.only(top: 1),
- decoration: BoxDecoration(
- color: done ? ok.withValues(alpha: 0.15) : grid.AppSurface.recess,
- shape: BoxShape.circle,
- ),
- alignment: Alignment.center,
- child: done
- ? Icon(LucideIcons.check300, size: 13, color: ok)
- : Text(
- '$number',
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontSize: 11.5,
- fontWeight: grid.AppFont.semibold,
- ),
- ),
- );
- }
-}
-
-/// A command the person copies. The whole line is selectable too, for the
-/// person who would rather drag than click.
-class _CommandLine extends StatelessWidget {
- const _CommandLine({
- required this.command,
- required this.copied,
- required this.onCopy,
- });
-
- final String command;
- final bool copied;
- final VoidCallback? onCopy;
-
- @override
- Widget build(BuildContext context) {
- return Container(
- padding: const EdgeInsets.fromLTRB(12, 8, 8, 8),
- decoration: BoxDecoration(
- color: grid.AppCard.inset,
- borderRadius: BorderRadius.circular(8),
- border: Border.all(color: grid.AppCard.insetHair),
- ),
- child: Row(
- children: [
- Expanded(
- child: SelectableText.rich(
- TextSpan(
- children: [
- TextSpan(
- text: r'$ ',
- style: TextStyle(color: grid.AppPalette.textFaint),
- ),
- TextSpan(text: command),
- ],
+ Wrap(
+ spacing: 8,
+ children: [
+ _button(
+ 'Download OpenHarness',
+ () => unawaited(_download()),
+ focus: _guideFocus,
),
- style: TextStyle(
- fontFamily: grid.AppFont.mono,
- fontFamilyFallback: grid.AppFont.monoFallback,
- fontSize: 12,
- height: 1.5,
- color: grid.AppPalette.textPrimary,
+ _button(
+ 'Copy download link',
+ () => unawaited(
+ _copy(kHarnessDownloadUrl.toString(), command: false),
+ ),
),
- ),
+ ],
),
- const SizedBox(width: 8),
- _SmallButton(
- label: copied ? 'Copied' : 'Copy',
- icon: copied ? LucideIcons.check300 : LucideIcons.copy300,
- onPressed: onCopy,
+ const SizedBox(height: 10),
+ Text('2. Sign in as $email.', style: boxMonoStyle(size: 12)),
+ const SizedBox(height: 10),
+ Text(
+ '3. Open commands → Link machine → This computer’s password.',
+ style: boxMonoStyle(size: 12),
),
- ],
- ),
- );
- }
-}
-
-// ── the list ────────────────────────────────────────────────────────────────
-
-class _WaitingStrip extends StatelessWidget {
- const _WaitingStrip();
-
- @override
- Widget build(BuildContext context) {
- return Container(
- padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(10),
- border: Border.all(color: grid.AppPalette.divider),
- ),
- child: Row(
- children: [
- // Still under test: a spinner that never stops is a pumpAndSettle
- // that never settles, the same reason the install panel's clock
- // holds still there.
- SizedBox(
- width: 14,
- height: 14,
- child: kUnderTest
- ? DecoratedBox(
- decoration: BoxDecoration(
- shape: BoxShape.circle,
- border: Border.all(
- color: grid.AppPalette.accentOnSurface,
- width: 2,
- ),
- ),
- )
- : CircularProgressIndicator(
- strokeWidth: 2,
- color: grid.AppPalette.accentOnSurface,
- ),
+ const SizedBox(height: 4),
+ Text(
+ 'Set a remote password there, then enter it here.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- 'Waiting for a new machine to sign in… it appears here on its own.',
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 12.5,
- ),
+ ],
+ const SizedBox(height: 16),
+ Text(
+ remotes.isEmpty
+ ? 'After sign-in, the machine appears here. Refresh to check now.'
+ : 'Available to link',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ for (final state in remotes)
+ _machineRow(
+ _LinkEntry(
+ 'machine:${state.machine.machineId}',
+ state.machine.displayName,
+ 'Enter remote password',
+ machine: state,
),
),
- ],
- ),
- );
- }
-}
-
-class _ArrivedSummary extends StatelessWidget {
- const _ArrivedSummary({required this.machine});
-
- final MachineState? machine;
-
- @override
- Widget build(BuildContext context) {
- final name = machine?.machine.displayName ?? 'A machine';
- return _Step(
- number: 1,
- done: true,
- title: '$name signed in just now',
- detail: const TextSpan(
- text:
- 'Set a remote password on it if you have not, then enter it here.',
- ),
+ ],
);
}
-}
-
-class _MachineList extends StatelessWidget {
- const _MachineList({
- required this.machines,
- required this.arrivedId,
- required this.onEnterPassword,
- });
-
- final List<MachineState> machines;
- final String? arrivedId;
- final ValueChanged<String> onEnterPassword;
- @override
- Widget build(BuildContext context) {
- // The one just linked first, then unlinked, then the rest as listed.
- final rows = [...machines]
- ..sort((a, b) {
- int rank(MachineState m) => m.machine.machineId == arrivedId
- ? 0
- : m.needsLink
- ? 1
- : 2;
- return rank(a).compareTo(rank(b));
- });
- return ClipRRect(
- borderRadius: BorderRadius.circular(10),
- child: Container(
- decoration: BoxDecoration(
- border: Border.all(color: grid.AppCard.insetHair),
- borderRadius: BorderRadius.circular(10),
- ),
+ Widget _command(String title, String command, {bool first = false}) =>
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8, top: 8),
child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- for (var i = 0; i < rows.length; i++)
- _MachineRow(
- machine: rows[i],
- first: i == 0,
- onEnterPassword: () =>
- onEnterPassword(rows[i].machine.machineId),
+ Text(title, style: boxMonoStyle(size: 12)),
+ const SizedBox(height: 4),
+ SelectableText(
+ command,
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Copy command',
+ () => unawaited(_copy(command)),
+ focus: first ? _guideFocus : null,
+ key: ValueKey('copy-$command'),
),
+ ),
],
),
- ),
- );
- }
-}
-
-class _MachineRow extends StatelessWidget {
- const _MachineRow({
- required this.machine,
- required this.first,
- required this.onEnterPassword,
- });
-
- final MachineState machine;
- final bool first;
- final VoidCallback onEnterPassword;
+ );
@override
- Widget build(BuildContext context) {
- final online = machine.nodeOnline;
- final presence = online == true
- ? 'Online'
- : online == false
- ? 'Offline'
- : 'Connecting…';
- final needsLink = machine.needsLink;
- // The row is the target as well as the button: the old list opened the
- // password screen from a tap on the name, and hands still go there.
- return InkWell(
- key: ValueKey('link-row-${machine.machine.machineId}'),
- onTap: needsLink ? onEnterPassword : null,
- child: Container(
- padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
- decoration: BoxDecoration(
- color: grid.AppCard.inset,
- border: first
- ? null
- : Border(top: BorderSide(color: grid.AppCard.insetHair)),
- ),
- child: Row(
- children: [
- Container(
- width: 28,
- height: 28,
- decoration: BoxDecoration(
- color: grid.AppSurface.recess,
- borderRadius: BorderRadius.circular(7),
- ),
- alignment: Alignment.center,
- child: Icon(
- LucideIcons.server300,
- size: 15,
- color: grid.AppPalette.textSecondary,
- ),
- ),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- machine.machine.displayName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 13,
- fontWeight: grid.AppFont.medium,
- ),
- ),
- const SizedBox(height: 2),
- Row(
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([app, terminalFontStore]),
+ builder: (context, _) {
+ final rows = _entries;
+ final selected = _selected;
+ final message = _message ?? app.machineListError;
+ return Offstage(
+ offstage: _nested,
+ child: Dialog(
+ alignment: Alignment.topCenter,
+ insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
+ elevation: 0,
+ backgroundColor: Colors.transparent,
+ child: _keys(
+ Focus(
+ onKeyEvent: _key,
+ child: SizedBox(
+ width: 760,
+ child: TerminalBox(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Container(
- width: 7,
- height: 7,
- decoration: BoxDecoration(
- color: online == true
- ? grid.AppPalette.online
- : grid.AppPalette.textFaint,
- shape: BoxShape.circle,
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Text(
+ 'Link another machine${_guide == null
+ ? ''
+ : _guide == _Guide.server
+ ? ' / SSH'
+ : ' / desktop'}',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (_guide == null)
+ Text(
+ '${rows.length}/${_remotes.length + 3}',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
),
),
- const SizedBox(width: 6),
- Flexible(
- child: Text.rich(
- TextSpan(
- children: [
- TextSpan(text: '$presence · '),
- TextSpan(
- text: needsLink ? 'Not linked yet' : 'Linked',
- style: TextStyle(
- color: needsLink
- ? grid.AppPalette.warn
- : grid.AppPalette.online,
- fontSize: 11,
+ if (_guide == null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: ReadlineKeys(
+ controller: _query,
+ onChanged: _changed,
+ child: TextField(
+ key: const Key('link-machine-search'),
+ controller: _query,
+ focusNode: _inputFocus,
+ autofocus: true,
+ style: boxMonoStyle(),
+ textAlignVertical: TextAlignVertical.center,
+ decoration: InputDecoration(
+ hintText: 'find a machine / desktop / SSH',
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ isDense: true,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ 'machine >',
+ style: boxMonoStyle(
+ color: Colors.white70,
+ ),
+ ),
+ ),
+ ),
+ prefixIconConstraints: const BoxConstraints(
+ minHeight: 36,
),
+ contentPadding: EdgeInsets.zero,
),
- ],
- ),
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 11.5,
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) => unawaited(_open(_selected)),
+ ),
),
),
+ Flexible(
+ child: SingleChildScrollView(
+ key: ValueKey(_guide),
+ padding: const EdgeInsets.fromLTRB(8, 6, 8, 10),
+ child: _guide != null
+ ? Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ ),
+ child: _guideBody(),
+ )
+ : Column(
+ crossAxisAlignment:
+ CrossAxisAlignment.stretch,
+ children: [
+ if (rows.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(8),
+ child: Text(
+ 'No matching machines. Clear the search to see setup options.',
+ style: boxMonoStyle(
+ size: 12,
+ color: kBoxFaint,
+ ),
+ ),
+ ),
+ for (final entry in rows)
+ _machineRow(entry, picker: true),
+ if (selected != null && !selected.enabled)
+ Padding(
+ padding: const EdgeInsets.all(8),
+ child: Text(
+ 'Already linked. Open its agents from New Tab or New Pane.',
+ style: boxMonoStyle(
+ size: 11,
+ color: kBoxFaint,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ BoxHintStrip(
+ message: _refreshing || app.machinesRefreshing
+ ? 'Refreshing machines…'
+ : message,
+ isError:
+ !_refreshing &&
+ !app.machinesRefreshing &&
+ (_error ||
+ (_message == null &&
+ app.machineListError != null)),
+ hints: [
+ if (_guide == null)
+ BoxHint(
+ '${_hint('picker.previous', '↑')}/${_hint('picker.next', '↓')}',
+ 'select',
+ ),
+ if (_guide == null && selected?.enabled == true)
+ BoxHint(
+ _hint('picker.accept', 'enter'),
+ 'open',
+ onTap: () => unawaited(_open(selected)),
+ ),
+ if (_guide != null)
+ BoxHint(
+ _hint('picker.complete', 'tab'),
+ 'controls',
+ ),
+ BoxHint(
+ _hint('picker.refresh', _mac ? 'cmd-r' : 'ctrl-r'),
+ 'refresh',
+ onTap: () => unawaited(_refresh()),
+ ),
+ BoxHint(
+ _hint('picker.cancel', 'esc'),
+ _guide == null ? 'close' : 'back',
+ onTap: _back,
+ ),
+ ],
),
],
),
- ],
- ),
- ),
- if (needsLink) ...[
- const SizedBox(width: 12),
- FilledButton(
- key: ValueKey('link-enter-${machine.machine.machineId}'),
- onPressed: onEnterPassword,
- style: FilledButton.styleFrom(
- visualDensity: VisualDensity.compact,
- textStyle: const TextStyle(fontSize: 11.5),
),
- child: const Text('Enter password'),
),
- ],
- ],
- ),
- ),
- );
- }
-}
-
-class _NotSeeingIt extends StatelessWidget {
- const _NotSeeingIt({required this.email, required this.onShowSteps});
-
- final String? email;
- final VoidCallback onShowSteps;
-
- @override
- Widget build(BuildContext context) {
- return Text.rich(
- TextSpan(
- children: [
- const TextSpan(text: 'Not seeing it? It signs in as '),
- _strongSpan(email ?? 'the same account'),
- const TextSpan(text: ' and needs '),
- _codeSpan('harness start'),
- const TextSpan(text: ' running. '),
- TextSpan(
- text: 'Show the steps again',
- style: TextStyle(
- color: grid.AppPalette.accentOnSurface,
- decoration: TextDecoration.underline,
- decorationColor: grid.AppPalette.accentOnSurface.withValues(
- alpha: 0.4,
- ),
- ),
- recognizer: TapGestureRecognizer()..onTap = onShowSteps,
- ),
- ],
- ),
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 12,
- height: 1.45,
- ),
- );
- }
-}
-
-// ── the footer ──────────────────────────────────────────────────────────────
-
-class _Footer extends StatelessWidget {
- const _Footer({
- required this.linked,
- required this.showCopyAll,
- required this.copiedAll,
- required this.onCopyAll,
- required this.onRefresh,
- required this.onThisMachine,
- required this.onClose,
- });
-
- final int linked;
- final bool showCopyAll;
- final bool copiedAll;
- final VoidCallback onCopyAll;
- final VoidCallback? onRefresh;
- final VoidCallback onThisMachine;
- final VoidCallback onClose;
-
- @override
- Widget build(BuildContext context) {
- return Container(
- padding: const EdgeInsets.fromLTRB(22, 12, 22, 16),
- decoration: BoxDecoration(
- border: Border(top: BorderSide(color: grid.AppCard.insetHair)),
- ),
- child: Row(
- children: [
- Expanded(
- child: Align(
- alignment: Alignment.centerLeft,
- child: showCopyAll
- ? _SmallButton(
- label: copiedAll
- ? 'Copied all three'
- : 'Copy all three commands',
- icon: copiedAll
- ? LucideIcons.check300
- : LucideIcons.copy300,
- tinted: true,
- onPressed: onCopyAll,
- )
- : onRefresh != null
- ? TextButton(
- onPressed: onRefresh,
- child: const Text('Refresh'),
- )
- : linked > 0
- ? Text(
- '$linked machine${linked == 1 ? '' : 's'} already linked',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: grid.AppPalette.textFaint,
- fontSize: 11.5,
- ),
- )
- : const SizedBox.shrink(),
),
),
- const SizedBox(width: 8),
- TextButton(
- onPressed: onThisMachine,
- style: TextButton.styleFrom(
- foregroundColor: grid.AppPalette.textSecondary,
- ),
- child: const Text('This computer’s password'),
- ),
- const SizedBox(width: 4),
- OutlinedButton(onPressed: onClose, child: const Text('Close')),
- ],
- ),
- );
- }
-}
-
-class _SmallButton extends StatelessWidget {
- const _SmallButton({
- required this.label,
- required this.icon,
- required this.onPressed,
- this.tinted = false,
- });
-
- final String label;
- final IconData icon;
- final VoidCallback? onPressed;
- final bool tinted;
-
- @override
- Widget build(BuildContext context) {
- final accent = grid.AppPalette.accentOnSurface;
- return OutlinedButton.icon(
- onPressed: onPressed,
- style: OutlinedButton.styleFrom(
- visualDensity: VisualDensity.compact,
- padding: const EdgeInsets.symmetric(horizontal: 10),
- textStyle: const TextStyle(fontSize: 11.5),
- foregroundColor: tinted ? accent : grid.AppPalette.textPrimary,
- backgroundColor: tinted ? accent.withValues(alpha: 0.14) : null,
- side: BorderSide(
- color: tinted ? Colors.transparent : grid.AppPalette.divider,
),
- ),
- icon: Icon(icon, size: 13),
- label: Text(label),
- );
- }
+ );
+ },
+ );
}
diff --git a/desktop/lib/widgets/link_machine_dialog.dart b/desktop/lib/widgets/link_machine_dialog.dart
index c08cf5eb7..b47683bb4 100644
--- a/desktop/lib/widgets/link_machine_dialog.dart
+++ b/desktop/lib/widgets/link_machine_dialog.dart
@@ -1,698 +1,818 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../auth/cli_link.dart';
import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_commands.dart' show describeKeyBinding;
import '../state/app_state.dart';
-import '../shared/widgets/skeleton.dart';
-import '../theme/app_theme.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
-/// Sets (or manages) THIS machine's remote password, so another machine can later connect to it
-/// with `harness link connect` — no code to copy/paste. To link a specific machine FROM here
-/// instead, select it in the sidebar (see `machine_rail.dart`'s `selectMachineForSetup`), not
-/// duplicated here — that flow lives in `link_machine_screen.dart`.
+/// This computer's incoming password and, separately, its outgoing links.
Future<void> showLinkMachineDialog(BuildContext context, AppNotifier notifier) {
+ final keymap = KeymapTheme.of(context, listen: false);
return showAppDialog<void>(
context: context,
- builder: (context) => _LinkMachineDialog(notifier: notifier),
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ veilTint: Colors.transparent,
+ builder: (_) {
+ final dialog = _LinkMachineDialog(notifier: notifier);
+ return keymap == null
+ ? dialog
+ : KeymapProvider(keymap: keymap, child: dialog);
+ },
);
}
-class _LinkMachineDialog extends StatefulWidget {
- final AppNotifier notifier;
+enum _Page { password, clear, links, unlink }
+class _LinkMachineDialog extends StatefulWidget {
const _LinkMachineDialog({required this.notifier});
-
+ final AppNotifier notifier;
@override
State<_LinkMachineDialog> createState() => _LinkMachineDialogState();
}
class _LinkMachineDialogState extends State<_LinkMachineDialog> {
- bool _statusLoading = true;
+ AppNotifier get app => widget.notifier;
+ final _password = TextEditingController();
+ final _confirm = TextEditingController();
+ final _passwordFocus = FocusNode(debugLabel: 'New remote password');
+ final _confirmFocus = FocusNode(debugLabel: 'Confirm remote password');
+ final _actionFocus = FocusNode(debugLabel: 'Password prompt action');
+ final _announcer = BoxAnnouncer();
+ _Page _page = _Page.password;
RemotePasswordStatus? _status;
- String? _statusError;
-
- // Set/change form state.
- bool _editing = false;
- final _passwordController = TextEditingController();
- final _confirmController = TextEditingController();
- bool _obscure = true;
- bool _submitting = false;
- String? _formError;
-
- bool _clearing = false;
+ LinkedMachine? _unlinkTarget;
+ bool _loading = true, _editing = false, _obscure = true;
+ bool _busy = false, _clearing = false;
+ String? _message;
+ bool _error = false;
+
+ bool get _composing =>
+ _page == _Page.password &&
+ _editing &&
+ [_password, _confirm].any(
+ (controller) =>
+ controller.value.composing.isValid &&
+ !controller.value.composing.isCollapsed,
+ );
+ bool get _mac => Theme.of(context).platform == TargetPlatform.macOS;
@override
void initState() {
super.initState();
- unawaited(widget.notifier.refreshLinkedMachines());
- unawaited(_loadStatus());
+ if (app.pendingRemotePasswordChange case final pending?) {
+ _loading = false;
+ _busy = true;
+ _clearing = app.clearingRemotePassword;
+ unawaited(_finishChange(pending));
+ } else {
+ unawaited(_loadStatus());
+ }
}
@override
void dispose() {
- _passwordController.dispose();
- _confirmController.dispose();
+ _password.dispose();
+ _confirm.dispose();
+ _passwordFocus.dispose();
+ _confirmFocus.dispose();
+ _actionFocus.dispose();
super.dispose();
}
+ void _focus([FocusNode? node]) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || ModalRoute.of(context)?.isCurrent == false) return;
+ (node ??
+ (_page == _Page.password && _editing && !_busy
+ ? _passwordFocus
+ : _actionFocus))
+ .requestFocus();
+ });
+ }
+
+ void _say(String? message, {bool error = false}) {
+ setState(() {
+ _message = message;
+ _error = error;
+ });
+ _announcer.row(context, message);
+ }
+
Future<void> _loadStatus() async {
+ if (_busy) return;
setState(() {
- _statusLoading = true;
- _statusError = null;
+ _loading = true;
+ _message = null;
+ _error = false;
});
- final status = await widget.notifier.remotePasswordStatus();
+ final status = await app.remotePasswordStatus();
if (!mounted) return;
setState(() {
- _statusLoading = false;
- if (status.error != null) {
- _statusError = status.error;
- } else {
+ _loading = false;
+ if (status.error == null) {
_status = status;
_editing = !status.hasPassword;
}
});
+ if (status.error != null) _say(status.error, error: true);
+ _focus();
+ }
+
+ void _edit() {
+ if (_busy) return;
+ setState(() {
+ _editing = true;
+ _message = null;
+ _obscure = true;
+ });
+ _focus(_passwordFocus);
}
- Future<void> _submit() async {
- final password = _passwordController.text;
- final confirm = _confirmController.text;
- if (password.isEmpty) {
- setState(() => _formError = 'Enter a password');
+ void _edited(String _) {
+ if (_message != null) _say(null);
+ }
+
+ void _nextField() {
+ if (_busy || _composing) return;
+ if (_password.text.isEmpty) {
+ _say('Enter a password', error: true);
+ } else {
+ _confirmFocus.requestFocus();
+ }
+ }
+
+ void _submit() {
+ if (_busy ||
+ _loading ||
+ _composing ||
+ _page != _Page.password ||
+ !_editing) {
+ return;
+ }
+ if (_password.text.isEmpty) {
+ _say('Enter a password', error: true);
+ _passwordFocus.requestFocus();
return;
}
- if (password != confirm) {
- setState(() => _formError = 'Passwords do not match');
+ if (_password.text != _confirm.text) {
+ _say('Passwords do not match', error: true);
+ _confirmFocus.requestFocus();
+ return;
+ }
+ // The CLI reads one line from stdin. Never silently accept a truncated
+ // paste that would set a different password from the one shown here.
+ if (_password.text.contains(RegExp(r'[\r\n]'))) {
+ _say('Use a password on one line', error: true);
+ _passwordFocus.requestFocus();
return;
}
setState(() {
- _submitting = true;
- _formError = null;
+ _busy = true;
+ _clearing = false;
+ _message = null;
});
- final result = await widget.notifier.setRemotePassword(password);
+ final request = app.setRemotePassword(_password.text);
+ unawaited(
+ _finishChange(
+ request.then(
+ (result) => RemotePasswordStatus(
+ error: result.error,
+ hasPassword: result.error == null,
+ fingerprint: result.fingerprint,
+ setAt: result.error == null ? DateTime.now() : null,
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _finishChange(Future<RemotePasswordStatus> request) async {
+ final result = await request;
if (!mounted) return;
+ final cleared = _clearing;
setState(() {
- _submitting = false;
- if (result.error != null) {
- _formError = result.error;
- } else {
- _editing = false;
- _status = RemotePasswordStatus(
- hasPassword: true,
- fingerprint: result.fingerprint,
- setAt: DateTime.now(),
- );
- _passwordController.clear();
- _confirmController.clear();
+ _busy = false;
+ _page = _Page.password;
+ if (result.error == null) {
+ _status = result;
+ _editing = !result.hasPassword;
+ _password.clear();
+ _confirm.clear();
+ _obscure = true;
+ }
+ });
+ _say(
+ result.error ?? (cleared ? 'Password cleared.' : 'Password set.'),
+ error: result.error != null,
+ );
+ // A reopened failed operation has no local status or password buffer.
+ // Read status before offering a retry; never show "not set" on failure.
+ if (result.error != null && _status == null) {
+ final status = await app.remotePasswordStatus();
+ if (!mounted) return;
+ if (status.error == null) {
+ setState(() {
+ _status = status;
+ _editing = !status.hasPassword;
+ });
}
+ }
+ _focus(result.error != null && _editing ? _confirmFocus : null);
+ }
+
+ void _askClear() {
+ if (_busy) return;
+ setState(() {
+ _page = _Page.clear;
+ _message = null;
});
+ _focus(); // Cancel owns Enter until the user chooses Clear.
}
- Future<void> _confirmClear() async {
- final confirmed = await showAppDialog<bool>(
- context: context,
- builder: (dialogContext) => AlertDialog(
- title: const Text('Clear remote password'),
- content: SizedBox(
- width: 360,
- child: Text(
- 'Clear the remote password for this machine? Anyone using it to connect will lose '
- "remote access until you set a new one. This can't be undone.",
- style: TextStyle(fontFamily: AppFonts.sans, fontSize: 13.5),
- ),
+ void _clear() {
+ if (_busy) return;
+ setState(() {
+ _busy = true;
+ _clearing = true;
+ _message = null;
+ });
+ unawaited(
+ _finishChange(
+ app.clearRemotePassword().then(
+ (error) => RemotePasswordStatus(error: error),
),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(dialogContext).pop(false),
- child: const Text('Cancel'),
- ),
- FilledButton(
- key: const Key('remote-password-clear-confirm-button'),
- style: FilledButton.styleFrom(backgroundColor: AppColors.danger),
- onPressed: () => Navigator.of(dialogContext).pop(true),
- child: const Text('Clear'),
- ),
- ],
),
);
- if (confirmed != true || !mounted) return;
- setState(() => _clearing = true);
- final error = await widget.notifier.clearRemotePassword();
+ }
+
+ void _links() {
+ if (_busy) return;
+ setState(() {
+ _page = _Page.links;
+ _message = null;
+ });
+ unawaited(app.refreshLinkedMachines());
+ _focus();
+ }
+
+ void _askUnlink(LinkedMachine machine) {
+ setState(() {
+ _page = _Page.unlink;
+ _unlinkTarget = machine;
+ _message = null;
+ });
+ _focus();
+ }
+
+ Future<void> _unlink() async {
+ final machine = _unlinkTarget;
+ if (_busy || machine == null) return;
+ setState(() {
+ _busy = true;
+ _message = null;
+ });
+ final error = await app.unlinkMachine(machine.machineId);
if (!mounted) return;
setState(() {
- _clearing = false;
- if (error != null) {
- _statusError = error;
+ _busy = false;
+ if (error == null) _page = _Page.links;
+ });
+ final refreshError = app.linkedMachinesError;
+ _say(
+ error ??
+ '${_name(machine)} unlinked.${refreshError == null ? '' : ' $refreshError'}',
+ error: error != null || refreshError != null,
+ );
+ _focus();
+ }
+
+ String _name(LinkedMachine machine) =>
+ app.stateOf(machine.machineId)?.machine.displayName ?? machine.machineId;
+
+ void _back() {
+ if (_composing) return;
+ if (_busy ||
+ _page == _Page.password && !_editing ||
+ _page == _Page.password && _status?.hasPassword != true) {
+ Navigator.of(context).pop();
+ return;
+ }
+ setState(() {
+ _message = null;
+ if (_page == _Page.unlink) {
+ _page = _Page.links;
+ } else if (_page != _Page.password) {
+ _page = _Page.password;
} else {
- _status = const RemotePasswordStatus(hasPassword: false);
- _editing = true;
+ _editing = false;
+ _password.clear();
+ _confirm.clear();
+ _obscure = true;
}
});
+ _focus();
}
- @override
- Widget build(BuildContext context) {
- return AlertDialog(
- title: const Text('Link another machine'),
- content: SizedBox(
- width: 460,
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- "Set a remote password here so another machine can connect to this one. To link "
- "a specific machine from here instead, select it in the sidebar — you'll get a "
- "\"Link this machine\" guide to enter the password there.",
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11.2,
- color: AppColors.mutedStrong,
- height: 1.4,
- ),
- ),
- const SizedBox(height: 16),
- _ActionCard(
- icon: Icons.password,
- title: 'Let another machine control this one',
- steps: const [
- 'Set a remote password for this machine below.',
- "On the OTHER machine, select this machine in the sidebar (it'll show "
- "'link required') and enter the same password there.",
- ],
- error: _formError ?? _statusError,
- child: _buildPasswordSection(),
- ),
- const SizedBox(height: 18),
- Text(
- 'MACHINES YOU CAN REMOTE INTO',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11,
- fontWeight: FontWeight.w600,
- letterSpacing: 0.6,
- color: AppColors.mutedStrong,
- ),
- ),
- const SizedBox(height: 8),
- ListenableBuilder(
- listenable: widget.notifier,
- builder: (context, _) {
- if (widget.notifier.linkedMachinesLoading &&
- widget.notifier.linkedMachines.isEmpty) {
- return const _LinkedMachinesSkeleton(
- key: Key('linked-machines-skeleton'),
- );
- }
- final machines = widget.notifier.linkedMachines;
- if (machines.isEmpty) {
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 12),
- child: Text(
- 'No machines linked yet.',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 12,
- color: AppColors.muted,
- ),
- ),
- );
- }
- return Column(
- children: [
- for (final machine in machines)
- _LinkedMachineRow(
- machine: machine,
- displayName: widget.notifier
- .stateOf(machine.machineId)
- ?.machine
- .displayName,
- onUnlink: () async {
- await widget.notifier.unlinkMachine(
- machine.machineId,
- );
- },
- ),
- ],
- );
- },
- ),
- ],
- ),
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('Close'),
- ),
- ],
- );
+ void _accept() {
+ if (_composing) return;
+ if (_page == _Page.password && _editing && _passwordFocus.hasFocus) {
+ _nextField();
+ } else if (_page == _Page.password && _editing && _confirmFocus.hasFocus) {
+ _submit();
+ } else if (FocusManager.instance.primaryFocus?.context case final target?) {
+ Actions.maybeInvoke(target, const ActivateIntent());
+ }
}
- Widget _buildPasswordSection() {
- if (_statusLoading) {
- return const Padding(
- padding: EdgeInsets.symmetric(vertical: 8),
- child: SizedBox(
- width: 16,
- height: 16,
- child: CircularProgressIndicator(strokeWidth: 2),
- ),
- );
- }
- final status = _status;
- if (!_editing && status != null && status.hasPassword) {
- return _RemotePasswordSummary(
- status: status,
- clearing: _clearing,
- onChange: () => setState(() {
- _editing = true;
- _formError = null;
- }),
- onClear: _confirmClear,
- );
+ void _refresh() {
+ if (_busy || _loading) return;
+ if (_page == _Page.links) {
+ if (app.linkedMachinesLoading) return;
+ _say(null);
+ unawaited(app.refreshLinkedMachines());
+ } else if (_page == _Page.password && !_editing) {
+ unawaited(_loadStatus());
}
- return _RemotePasswordForm(
- passwordController: _passwordController,
- confirmController: _confirmController,
- obscure: _obscure,
- onToggleObscure: () => setState(() => _obscure = !_obscure),
- submitting: _submitting,
- onSubmit: _submit,
- onCancel: (status != null && status.hasPassword)
- ? () => setState(() {
- _editing = false;
- _formError = null;
- _passwordController.clear();
- _confirmController.clear();
- })
- : null,
- );
}
-}
-class _ActionCard extends StatelessWidget {
- final IconData icon;
- final String title;
- final List<String> steps;
- final Widget child;
- final String? error;
-
- const _ActionCard({
- required this.icon,
- required this.title,
- required this.steps,
- required this.child,
- this.error,
- });
+ String _hint(String command, String fallback) {
+ final map = KeymapTheme.of(context);
+ if (map == null) return fallback;
+ final bindings = map
+ .bindings(command, context: KeymapContext.picker)
+ .toList();
+ final binding =
+ bindings.where((b) => b.custom).firstOrNull ??
+ (command == 'picker.refresh' && !_mac
+ ? bindings
+ .where((b) => b.keys.length == 1 && b.keys.first.control)
+ .firstOrNull
+ : null) ??
+ bindings.firstOrNull;
+ return binding == null ? 'click' : describeKeyBinding(binding);
+ }
- @override
- Widget build(BuildContext context) {
- return Container(
- width: double.infinity,
- padding: const EdgeInsets.all(14),
- decoration: BoxDecoration(
- color: AppColors.hover,
- border: Border.all(color: AppColors.border),
- borderRadius: BorderRadius.circular(8),
- ),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(icon, size: 18, color: AppColors.accent),
- const SizedBox(height: 8),
- Text(
- title,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 13,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
- ),
- ),
- const SizedBox(height: 10),
- for (var i = 0; i < steps.length; i++) ...[
- if (i > 0) const SizedBox(height: 8),
- _ActionStep(number: i + 1, text: steps[i]),
- ],
- const SizedBox(height: 12),
- child,
- if (error != null) ...[
- const SizedBox(height: 8),
- Text(
- error!,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11,
- color: AppColors.danger,
- ),
- ),
- ],
- ],
+ Widget _keys(Widget child) {
+ if (KeymapTheme.of(context) == null) return child;
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: () => _composing,
+ actions: {
+ 'picker.accept': _accept,
+ 'picker.add_here': _accept,
+ 'picker.cancel': _back,
+ 'picker.refresh': _refresh,
+ 'picker.next': () => FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.previous': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ },
+ child: Actions(
+ actions: {
+ DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
+ },
+ child: child,
),
);
}
-}
-/// Same "numbered badge + text" language as `link_machine_screen.dart`'s `_StepTitle` — sized
-/// identically (20px badge, 12px w600 text) now that this dialog is single-column and no longer
-/// needs to be squeezed into a ~250px card, so the two linking surfaces read as one design.
-class _ActionStep extends StatelessWidget {
- final int number;
- final String text;
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final keyboard = HardwareKeyboard.instance;
+ final enter =
+ event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter;
+ final escape = event.logicalKey == LogicalKeyboardKey.escape;
+ if (_composing && (enter || escape)) {
+ return KeyEventResult.skipRemainingHandlers;
+ }
+ if (KeymapTheme.of(context, listen: false) != null) {
+ // Do not let TextField's native submit bypass an unbound accept key.
+ return enter &&
+ _page == _Page.password &&
+ _editing &&
+ (_passwordFocus.hasFocus || _confirmFocus.hasFocus)
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ if (keyboard.isAltPressed || keyboard.isShiftPressed) {
+ return KeyEventResult.ignored;
+ }
+ if (keyboard.isMetaPressed || keyboard.isControlPressed) {
+ if (event.logicalKey == LogicalKeyboardKey.keyR &&
+ (_mac ? keyboard.isMetaPressed : keyboard.isControlPressed)) {
+ _refresh();
+ return KeyEventResult.handled;
+ }
+ if (keyboard.isControlPressed &&
+ event.logicalKey == LogicalKeyboardKey.keyC) {
+ _back();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+ if (escape) {
+ _back();
+ return KeyEventResult.handled;
+ }
+ if (enter &&
+ _page == _Page.password &&
+ _editing &&
+ (_passwordFocus.hasFocus || _confirmFocus.hasFocus)) {
+ // A held Enter cannot advance and then submit on a key repeat.
+ if (event is KeyDownEvent) _accept();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
- const _ActionStep({required this.number, required this.text});
+ Widget _button(
+ String label,
+ VoidCallback? action, {
+ Key? key,
+ bool first = false,
+ bool danger = false,
+ }) => TextButton(
+ key: key,
+ focusNode: first ? _actionFocus : null,
+ onPressed: action,
+ style: TextButton.styleFrom(
+ foregroundColor: danger ? Colors.orangeAccent : Colors.white70,
+ textStyle: boxMonoStyle(size: 12),
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ minimumSize: const Size(0, 30),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ child: Text(label),
+ );
- @override
- Widget build(BuildContext context) {
- return Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- width: 20,
- height: 20,
- alignment: Alignment.center,
- decoration: BoxDecoration(
- color: AppColors.accent,
- shape: BoxShape.circle,
- ),
- child: Text(
- '$number',
- style: TextStyle(
- color: AppColors.background,
- fontSize: 11,
- fontWeight: FontWeight.w700,
- ),
- ),
+ Widget _field({required bool confirm}) {
+ final controller = confirm ? _confirm : _password;
+ return ReadlineKeys(
+ controller: controller,
+ enabled: !_busy,
+ onChanged: _edited,
+ child: TextField(
+ key: Key(
+ confirm ? 'remote-password-confirm-field' : 'remote-password-field',
),
- const SizedBox(width: 8),
- Expanded(
- child: Text(
- text,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 12,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
+ controller: controller,
+ focusNode: confirm ? _confirmFocus : _passwordFocus,
+ readOnly: _busy,
+ obscureText: _obscure,
+ enableSuggestions: false,
+ autocorrect: false,
+ style: boxMonoStyle(),
+ textAlignVertical: TextAlignVertical.center,
+ textInputAction: confirm ? TextInputAction.done : TextInputAction.next,
+ decoration: InputDecoration(
+ hintText: confirm ? 'Repeat password' : 'New remote password',
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ isDense: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ confirm ? ' again >' : 'password >',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
),
),
+ prefixIconConstraints: const BoxConstraints(minHeight: 38),
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 28,
+ minHeight: 28,
+ ),
+ suffixIcon: confirm
+ ? null
+ : IconButton(
+ tooltip: _obscure ? 'Show password' : 'Hide password',
+ icon: Icon(
+ _obscure
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined,
+ size: 16,
+ ),
+ onPressed: _busy
+ ? null
+ : () => setState(() => _obscure = !_obscure),
+ ),
+ contentPadding: EdgeInsets.zero,
),
- ],
+ onEditingComplete: () {},
+ onSubmitted: (_) => confirm ? _submit() : _nextField(),
+ onChanged: _edited,
+ ),
);
}
-}
-
-/// Two obscured fields (new + confirm) plus a "Set" button — used both for setting a password
-/// the first time and, via [onCancel], for changing an existing one.
-class _RemotePasswordForm extends StatelessWidget {
- final TextEditingController passwordController;
- final TextEditingController confirmController;
- final bool obscure;
- final VoidCallback onToggleObscure;
- final bool submitting;
- final VoidCallback onSubmit;
- final VoidCallback? onCancel;
-
- const _RemotePasswordForm({
- required this.passwordController,
- required this.confirmController,
- required this.obscure,
- required this.onToggleObscure,
- required this.submitting,
- required this.onSubmit,
- this.onCancel,
- });
- @override
- Widget build(BuildContext context) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- TextField(
- key: const Key('remote-password-field'),
- controller: passwordController,
- obscureText: obscure,
- style: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),
- decoration: InputDecoration(
- hintText: 'New remote password',
- hintStyle: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),
- prefixIcon: const Icon(Icons.password, size: 17),
- suffixIcon: IconButton(
- icon: Icon(
- obscure ? Icons.visibility : Icons.visibility_off,
- size: 17,
- ),
- onPressed: onToggleObscure,
+ List<Widget> _passwordBody() {
+ if (_loading) {
+ return [
+ Text('Reading password status…', style: boxMonoStyle(color: kBoxFaint)),
+ ];
+ }
+ if (_status == null) {
+ return [
+ Text(
+ _busy
+ ? 'This operation continues if you close the prompt.'
+ : 'Password status is unavailable.',
+ style: boxMonoStyle(color: kBoxFaint),
+ ),
+ if (!_busy)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Retry',
+ () => unawaited(_loadStatus()),
+ first: true,
),
),
+ ];
+ }
+ return [
+ if (_editing) ...[
+ Text(
+ 'Use this password on the other machine to link to this computer.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
),
+ const SizedBox(height: 12),
+ _field(confirm: false),
+ _field(confirm: true),
const SizedBox(height: 8),
- TextField(
- key: const Key('remote-password-confirm-field'),
- controller: confirmController,
- obscureText: obscure,
- style: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),
- decoration: InputDecoration(
- hintText: 'Confirm password',
- hintStyle: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),
- prefixIcon: const Icon(Icons.password, size: 17),
- ),
- onSubmitted: (_) => onSubmit(),
- ),
- const SizedBox(height: 10),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
+ Wrap(
+ spacing: 10,
children: [
- if (onCancel != null) ...[
- TextButton(
- onPressed: submitting ? null : onCancel,
- child: const Text('Cancel'),
- ),
- const SizedBox(width: 8),
- ],
- FilledButton(
+ _button(
+ _status!.hasPassword ? 'Change password' : 'Set password',
+ _busy ? null : _submit,
key: const Key('remote-password-set-button'),
- onPressed: submitting ? null : onSubmit,
- child: submitting
- ? const SizedBox(
- width: 14,
- height: 14,
- child: CircularProgressIndicator(strokeWidth: 2),
- )
- : const Text('Set'),
),
+ if (_status!.hasPassword) _button('Cancel', _busy ? null : _back),
],
),
- ],
- );
- }
-}
-
-/// Shown once a remote password is already set: the fingerprint to verify on the connecting
-/// side, when it was set, and the "Change"/"Clear" actions.
-class _RemotePasswordSummary extends StatelessWidget {
- final RemotePasswordStatus status;
- final bool clearing;
- final VoidCallback onChange;
- final VoidCallback onClear;
-
- const _RemotePasswordSummary({
- required this.status,
- required this.clearing,
- required this.onChange,
- required this.onClear,
- });
-
- @override
- Widget build(BuildContext context) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Row(
- children: [
- Icon(Icons.check_circle, size: 15, color: AppColors.success),
- const SizedBox(width: 6),
- Text(
- 'Remote password is set',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 12.5,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
- ),
- ),
- ],
+ ] else ...[
+ Text(
+ 'Remote password is set',
+ style: boxMonoStyle(weight: FontWeight.w600),
),
- if (status.fingerprint != null) ...[
- const SizedBox(height: 8),
- Text(
- "This machine's fingerprint — verify it matches on the other side:",
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 10.5,
- color: AppColors.mutedStrong,
- ),
- ),
- const SizedBox(height: 3),
+ const SizedBox(height: 8),
+ Text(
+ 'On the other machine: Link machine → select this computer → enter its password.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ if (_status!.fingerprint case final fingerprint?) ...[
+ const SizedBox(height: 12),
+ Text('fingerprint', style: boxMonoStyle(size: 11, color: kBoxFaint)),
SelectableText(
- status.fingerprint!,
- style: TextStyle(
- fontFamily: AppFonts.mono,
- fontSize: 12,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
- ),
+ fingerprint,
+ style: boxMonoStyle(size: 12, color: Colors.white70),
),
],
- if (status.setAt != null) ...[
- const SizedBox(height: 4),
+ if (_status!.setAt case final date?)
Text(
- 'Set on ${_formatDate(status.setAt!)}.',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 10.5,
- color: AppColors.muted,
- ),
+ 'set ${date.toLocal().toIso8601String().substring(0, 16).replaceFirst('T', ' ')}',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
),
- ],
const SizedBox(height: 10),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
+ Wrap(
+ spacing: 10,
children: [
- TextButton(
- key: const Key('remote-password-clear-button'),
- onPressed: clearing ? null : onClear,
- child: const Text('Clear'),
- ),
- const SizedBox(width: 8),
- FilledButton(
+ _button(
+ 'Change password',
+ _busy ? null : _edit,
key: const Key('remote-password-change-button'),
- onPressed: clearing ? null : onChange,
- child: const Text('Change'),
+ first: true,
+ ),
+ _button(
+ 'Clear password…',
+ _busy ? null : _askClear,
+ key: const Key('remote-password-clear-button'),
),
],
),
],
- );
- }
-
- String _formatDate(DateTime date) {
- final local = date.toLocal();
- String two(int n) => n.toString().padLeft(2, '0');
- return '${local.year}-${two(local.month)}-${two(local.day)}';
+ if (_busy) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'This operation continues if you close the prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button(
+ 'Links from this computer…',
+ _busy ? null : _links,
+ key: const Key('remote-password-links-button'),
+ ),
+ ),
+ ];
}
-}
-/// Two [_LinkedMachineRow]s before `harness link list` has answered: a name,
-/// a mono line for the fingerprint, and the room the Unlink button takes.
-///
-/// Two, because this sits in a dialog and most accounts link one or two
-/// machines; a skeleton taller than the answer jumps up when it lands.
-class _LinkedMachinesSkeleton extends StatelessWidget {
- const _LinkedMachinesSkeleton({super.key});
-
- static const _names = [128.0, 96.0];
-
- @override
- Widget build(BuildContext context) => SkeletonList(
- rows: 2,
- fadeDepth: skeletonFadeLight,
- semanticsLabel: 'Loading linked machines',
- itemBuilder: (context, i) => Padding(
- padding: const EdgeInsets.symmetric(vertical: 6),
- child: Row(
+ List<Widget> _linksBody() => [
+ Text(
+ 'Machines this computer can connect to.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: _button('Refresh links', _refresh, first: true),
+ ),
+ if (app.linkedMachinesLoading && app.linkedMachines.isEmpty)
+ Text('Loading linked machines…', style: boxMonoStyle(color: kBoxFaint))
+ else if (app.linkedMachines.isEmpty && app.linkedMachinesError == null)
+ Text('No machines linked yet.', style: boxMonoStyle(color: kBoxFaint)),
+ for (final machine in app.linkedMachines)
+ Padding(
+ padding: const EdgeInsets.only(top: 12, bottom: 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(_name(machine), style: boxMonoStyle()),
+ SelectableText(
+ machine.fingerprint,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ Text(
+ 'linked ${machine.linkedAt}',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ _button(
+ app.unlinkingMachine(machine.machineId)
+ ? 'Unlinking…'
+ : 'Unlink…',
+ app.unlinkingMachine(machine.machineId)
+ ? null
+ : () => _askUnlink(machine),
+ key: ValueKey('unlink-${machine.machineId}'),
+ ),
+ ],
+ ),
+ ),
+ ];
+
+ List<Widget> _confirmationBody() {
+ final clear = _page == _Page.clear;
+ return [
+ Text(
+ clear
+ ? 'Prevent new links using this password? Existing links and sessions stay connected.'
+ : 'Remove this computer’s saved link to ${_name(_unlinkTarget!)}? A new connection will need that machine’s password.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ const SizedBox(height: 14),
+ Wrap(
+ spacing: 12,
children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- SkeletonText(
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 12.5,
- fontWeight: FontWeight.w600,
- ),
- width: _names[i],
- ),
- SkeletonText(
- style: TextStyle(fontFamily: AppFonts.mono, fontSize: 10.5),
- widthFactor: 0.72,
- ),
- ],
+ _button('Cancel', _busy ? null : _back, first: true),
+ _button(
+ clear ? 'Clear password' : 'Unlink',
+ _busy
+ ? null
+ : clear
+ ? _clear
+ : () => unawaited(_unlink()),
+ danger: true,
+ key: Key(
+ clear
+ ? 'remote-password-clear-confirm-button'
+ : 'remote-password-unlink-confirm-button',
),
),
- // A TextButton's box: Material's 40px minimum, the label's width.
- const Skeleton(width: 58, height: 40, radius: 8),
],
),
- ),
- );
-}
-
-class _LinkedMachineRow extends StatelessWidget {
- final LinkedMachine machine;
- final String? displayName;
- final Future<void> Function() onUnlink;
-
- const _LinkedMachineRow({
- required this.machine,
- required this.displayName,
- required this.onUnlink,
- });
+ ];
+ }
@override
- Widget build(BuildContext context) {
- return Padding(
- padding: const EdgeInsets.symmetric(vertical: 6),
- child: Row(
- children: [
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Text(
- displayName ?? machine.machineId,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 12.5,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([
+ app,
+ terminalFontStore,
+ _passwordFocus,
+ _confirmFocus,
+ ]),
+ builder: (context, _) => Dialog(
+ alignment: Alignment.topCenter,
+ insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
+ elevation: 0,
+ backgroundColor: Colors.transparent,
+ child: _keys(
+ Focus(
+ autofocus: true,
+ onKeyEvent: _key,
+ child: SizedBox(
+ width: 660,
+ child: TerminalBox(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(switch (_page) {
+ _Page.password => 'This computer’s password',
+ _Page.clear => 'Clear remote password',
+ _Page.links => 'Links from this computer',
+ _Page.unlink => 'Unlink machine',
+ }, style: boxMonoStyle(size: 12, color: kBoxFaint)),
+ const SizedBox(height: 14),
+ ...switch (_page) {
+ _Page.password => _passwordBody(),
+ _Page.links => _linksBody(),
+ _Page.clear || _Page.unlink => _confirmationBody(),
+ },
+ ],
+ ),
+ ),
),
- ),
- Text(
- '${machine.fingerprint} · linked ${machine.linkedAt}',
- style: TextStyle(
- fontFamily: AppFonts.mono,
- fontSize: 10.5,
- color: AppColors.mutedStrong,
+ BoxHintStrip(
+ message: _busy
+ ? (_page == _Page.unlink
+ ? 'Unlinking machine…'
+ : _clearing
+ ? 'Clearing password…'
+ : 'Setting password…')
+ : _message ??
+ (_page == _Page.links
+ ? app.linkedMachinesLoading
+ ? 'Loading linked machines…'
+ : app.linkedMachinesError
+ : null),
+ isError:
+ !_busy &&
+ (_error ||
+ _page == _Page.links &&
+ app.linkedMachinesError != null),
+ hints: [
+ if (!_busy && !_loading)
+ BoxHint(
+ _hint('picker.accept', 'enter'),
+ _page == _Page.password &&
+ _editing &&
+ _passwordFocus.hasFocus
+ ? 'confirm password'
+ : _page == _Page.password &&
+ _editing &&
+ _confirmFocus.hasFocus
+ ? 'set password'
+ : 'select',
+ ),
+ if (!_busy && !_loading)
+ BoxHint(_hint('picker.complete', 'tab'), 'controls'),
+ if (!_busy &&
+ !_loading &&
+ (_page == _Page.links ||
+ _page == _Page.password && !_editing))
+ BoxHint(
+ _hint('picker.refresh', _mac ? 'cmd-r' : 'ctrl-r'),
+ 'refresh',
+ onTap: _refresh,
+ ),
+ BoxHint(
+ _hint('picker.cancel', 'esc'),
+ _busy ||
+ _page == _Page.password &&
+ (!_editing || _status?.hasPassword != true)
+ ? 'close'
+ : 'back',
+ onTap: _back,
+ ),
+ ],
),
- ),
- ],
+ ],
+ ),
),
),
- TextButton(
- key: Key('unlink-${machine.machineId}'),
- onPressed: () => unawaited(onUnlink()),
- child: const Text('Unlink'),
- ),
- ],
+ ),
),
- );
- }
+ ),
+ );
}
diff --git a/desktop/lib/widgets/link_machine_screen.dart b/desktop/lib/widgets/link_machine_screen.dart
index 3e2bbd770..176a4e0cf 100644
--- a/desktop/lib/widgets/link_machine_screen.dart
+++ b/desktop/lib/widgets/link_machine_screen.dart
@@ -1,8 +1,12 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
-import '../theme/app_theme.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
/// Opens [LinkMachineScreen] as a modal popup for [machineId], closing itself automatically once
/// linking succeeds or the prompt is dismissed (including a barrier tap/Escape, which counts as an
@@ -25,10 +29,14 @@ Future<void> showLinkMachineScreenDialog(
notifier.revisitLinkPrompt(machineId);
await showAppDialog<void>(
context: context,
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ veilTint: Colors.transparent,
builder: (context) => Dialog(
+ alignment: Alignment.topCenter,
backgroundColor: Colors.transparent,
elevation: 0,
- insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
+ insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
child: ListenableBuilder(
listenable: notifier,
builder: (context, _) {
@@ -38,12 +46,19 @@ Future<void> showLinkMachineScreenDialog(
state.needsLink &&
!notifier.isLinkPromptDismissed(machineId);
if (!stillNeeded) {
+ final route = ModalRoute.of(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (Navigator.of(context).canPop()) Navigator.of(context).pop();
+ if (context.mounted && route?.isCurrent == true) {
+ Navigator.of(context).pop();
+ }
});
return const SizedBox.shrink();
}
- return LinkMachineScreen(notifier: notifier, machineState: state);
+ return LinkMachineScreen(
+ notifier: notifier,
+ machineState: state,
+ onClose: () => Navigator.of(context).pop(),
+ );
},
),
),
@@ -63,10 +78,12 @@ Future<void> showLinkMachineScreenDialog(
class LinkMachineScreen extends StatefulWidget {
final AppNotifier notifier;
final MachineState machineState;
+ final VoidCallback? onClose;
const LinkMachineScreen({
super.key,
required this.notifier,
required this.machineState,
+ this.onClose,
});
@override
@@ -75,201 +92,280 @@ class LinkMachineScreen extends StatefulWidget {
class _LinkMachineScreenState extends State<LinkMachineScreen> {
final _passwordController = TextEditingController();
+ final _passwordFocus = FocusNode(debugLabel: 'Remote password');
+ final _announcer = BoxAnnouncer();
bool _obscure = true;
bool _submitting = false;
bool _showTroubleshootingDetails = false;
String? _error;
- String? _stage;
+
+ String get _machineId => widget.machineState.machine.machineId;
+ bool get _composing =>
+ _passwordController.value.composing.isValid &&
+ !_passwordController.value.composing.isCollapsed;
+
+ @override
+ void initState() {
+ super.initState();
+ final pending = widget.notifier.pendingMachineLink(_machineId);
+ if (pending != null) {
+ _submitting = true;
+ unawaited(_finish(pending));
+ }
+ // The dialog's fallback focus can win autofocus during route insertion.
+ // Claim the input once mounted, as the search and creation prompts do.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _passwordFocus.requestFocus();
+ }
+ });
+ }
@override
void dispose() {
_passwordController.dispose();
+ _passwordFocus.dispose();
super.dispose();
}
- Future<void> _submit() async {
- setState(() {
- _submitting = true;
- _error = null;
- _stage = null;
- });
- final error = await widget.notifier.connectWithPassword(
- widget.machineState.machine.machineId,
- _passwordController.text,
- onProgress: (stage) {
- if (mounted) setState(() => _stage = stage);
- },
- );
+ Future<void> _finish(Future<String?> request) async {
+ final error = await request;
if (!mounted) return;
setState(() {
_submitting = false;
_error = error;
- _stage = null;
});
- if (error == null) _passwordController.clear();
+ if (error == null) {
+ _passwordController.clear();
+ } else {
+ _passwordFocus.requestFocus();
+ _announcer.row(context, error);
+ }
}
- @override
- Widget build(BuildContext context) {
- final machineId = widget.machineState.machine.machineId;
- final machineName = widget.machineState.machine.displayName;
-
- return Container(
- width: 460,
- padding: const EdgeInsets.all(24),
- decoration: BoxDecoration(
- border: Border.all(color: AppColors.border),
- borderRadius: BorderRadius.circular(14),
- color: AppColors.surface,
+ void _submit() {
+ if (_submitting || _composing) return;
+ if (_passwordController.text.isEmpty) {
+ setState(() => _error = 'Enter the remote password first');
+ _passwordFocus.requestFocus();
+ _announcer.row(context, _error);
+ return;
+ }
+ setState(() {
+ _submitting = true;
+ _error = null;
+ });
+ unawaited(
+ _finish(
+ widget.notifier.connectWithPassword(
+ _machineId,
+ _passwordController.text,
+ ),
),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Icon(Icons.link, size: 32, color: AppColors.accent),
- const SizedBox(height: 6),
- Text(
- 'Link this machine',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 13.5,
- fontWeight: FontWeight.w600,
- color: AppColors.text,
- ),
- ),
- const SizedBox(height: 6),
- Text(
- "This computer isn't linked to $machineName yet. Enter the remote password set "
- 'on that machine to connect.',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11.2,
- color: AppColors.mutedStrong,
- ),
- ),
- const SizedBox(height: 14),
- TextField(
- key: const Key('remote-password-connect-field'),
- controller: _passwordController,
- obscureText: _obscure,
- style: TextStyle(
- fontFamily: AppFonts.mono,
- fontSize: 12.5,
- color: AppColors.textSoft,
- ),
- decoration: InputDecoration(
- hintText: 'Remote password for $machineName',
- hintStyle: TextStyle(fontFamily: AppFonts.mono, fontSize: 12.5),
- prefixIcon: const Icon(Icons.password, size: 17),
- suffixIcon: IconButton(
- icon: Icon(
- _obscure ? Icons.visibility : Icons.visibility_off,
- size: 17,
- ),
- onPressed: () => setState(() => _obscure = !_obscure),
- ),
- ),
- onSubmitted: (_) => _submit(),
- ),
- if (_error != null) ...[
- const SizedBox(height: 6),
- Text(
- _error!,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11.2,
- color: AppColors.danger,
- ),
- ),
- ],
- const SizedBox(height: 10),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- if (_submitting && _stage != null) ...[
- Text(
- _stage!,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontFamilyFallback: AppFonts.sansFallback,
- fontSize: 11.2,
- color: AppColors.mutedStrong,
+ );
+ }
+
+ void _close() {
+ widget.notifier.dismissLinkPrompt(_machineId);
+ widget.onClose?.call();
+ }
+
+ void _edited(String _) {
+ if (_error != null) setState(() => _error = null);
+ }
+
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final keyboard = HardwareKeyboard.instance;
+ if (keyboard.isAltPressed ||
+ keyboard.isMetaPressed ||
+ keyboard.isControlPressed ||
+ keyboard.isShiftPressed) {
+ return KeyEventResult.ignored;
+ }
+ final enter =
+ event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter;
+ final escape = event.logicalKey == LogicalKeyboardKey.escape;
+ if (!enter && !escape) return KeyEventResult.ignored;
+ if (_composing) return KeyEventResult.skipRemainingHandlers;
+ if (escape) {
+ _close();
+ return KeyEventResult.handled;
+ }
+ if (_passwordFocus.hasFocus) {
+ _submit();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ String get _progress =>
+ switch (widget.notifier.machineLinkStage(_machineId)) {
+ 'deriving_key' => 'Checking password…',
+ 'exchanging' || 'verifying' => 'Verifying the link…',
+ _ => 'Connecting…',
+ };
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([widget.notifier, terminalFontStore]),
+ builder: (context, _) {
+ final machineName = widget.machineState.machine.displayName;
+ return Focus(
+ onKeyEvent: _key,
+ child: SizedBox(
+ width: 620,
+ child: TerminalBox(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Link this machine',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ machineName,
+ style: boxMonoStyle(weight: FontWeight.w600),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'Enter the remote password set on this machine.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ const SizedBox(height: 14),
+ ReadlineKeys(
+ controller: _passwordController,
+ enabled: !_submitting,
+ onChanged: _edited,
+ child: TextField(
+ key: const Key('remote-password-connect-field'),
+ controller: _passwordController,
+ focusNode: _passwordFocus,
+ autofocus: true,
+ readOnly: _submitting,
+ obscureText: _obscure,
+ enableSuggestions: false,
+ autocorrect: false,
+ textInputAction: TextInputAction.done,
+ textAlignVertical: TextAlignVertical.center,
+ style: boxMonoStyle(),
+ decoration: InputDecoration(
+ hintText: 'Remote password for $machineName',
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ isDense: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ 'password >',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
+ ),
+ ),
+ prefixIconConstraints: const BoxConstraints(
+ minHeight: 36,
+ ),
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 28,
+ minHeight: 28,
+ ),
+ suffixIcon: IconButton(
+ tooltip: _obscure
+ ? 'Show password'
+ : 'Hide password',
+ icon: Icon(
+ _obscure
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined,
+ size: 16,
+ ),
+ onPressed: _submitting
+ ? null
+ : () =>
+ setState(() => _obscure = !_obscure),
+ ),
+ contentPadding: EdgeInsets.zero,
+ ),
+ // Native Done must keep the prompt's key scope alive
+ // while connecting, so Escape still closes it.
+ onEditingComplete: () {},
+ onSubmitted: (_) => _submit(),
+ onChanged: _edited,
+ ),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ _submitting
+ ? 'Connecting continues if you close this prompt.'
+ : 'Your previous agent will reconnect automatically after linking.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ const SizedBox(height: 8),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton(
+ key: const Key('link-troubleshooting-details'),
+ style: TextButton.styleFrom(
+ textStyle: boxMonoStyle(size: 11),
+ foregroundColor: Colors.white70,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 4,
+ ),
+ minimumSize: const Size(0, 28),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ onPressed: () => setState(
+ () => _showTroubleshootingDetails =
+ !_showTroubleshootingDetails,
+ ),
+ child: Text(
+ _showTroubleshootingDetails
+ ? 'Hide details'
+ : 'Troubleshooting details',
+ ),
+ ),
+ ),
+ if (_showTroubleshootingDetails)
+ SelectableText(
+ 'Machine ID: $_machineId',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
),
),
- const SizedBox(width: 10),
- ],
- FilledButton(
- key: const Key('remote-password-connect-button'),
- onPressed: _submitting ? null : _submit,
- child: _submitting
- ? const SizedBox(
- width: 14,
- height: 14,
- child: CircularProgressIndicator(strokeWidth: 2),
- )
- : const Text('Link machine'),
- ),
- ],
- ),
- const SizedBox(height: 8),
- Text(
- 'Your previous agent will reconnect automatically after linking.',
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontSize: 11.2,
- color: AppColors.mutedStrong,
- ),
- ),
- const SizedBox(height: 4),
- TextButton.icon(
- key: const Key('link-troubleshooting-details'),
- onPressed: () => setState(
- () => _showTroubleshootingDetails = !_showTroubleshootingDetails,
- ),
- icon: Icon(
- _showTroubleshootingDetails
- ? Icons.expand_less
- : Icons.expand_more,
- size: 16,
- ),
- label: const Text('Troubleshooting details'),
- ),
- if (_showTroubleshootingDetails)
- Padding(
- padding: const EdgeInsets.only(left: 12),
- child: SelectableText(
- 'Machine ID: $machineId',
- style: TextStyle(
- fontFamily: AppFonts.mono,
- fontSize: 11.2,
- color: AppColors.muted,
+ BoxHintStrip(
+ message: _error ?? (_submitting ? _progress : null),
+ isError: _error != null,
+ hints: [
+ if (!_submitting)
+ BoxHint('enter', 'link machine', onTap: _submit),
+ BoxHint('tab', 'controls'),
+ BoxHint('esc', 'close', onTap: _close),
+ ],
),
- ),
- ),
- // An explicit way out, in addition to the barrier tap/Escape that
- // showLinkMachineScreenDialog already treats as an implicit dismiss. Closing does
- // not pretend the machine is linked: it still cannot be read and the rail still
- // says so. It only stops the popup from insisting, and choosing that machine again
- // brings it straight back. Bottom-right text button, matching every other dialog in
- // the app (see link_machine_dialog.dart's 'Close').
- const SizedBox(height: 6),
- Align(
- alignment: Alignment.centerRight,
- child: TextButton(
- style: TextButton.styleFrom(
- minimumSize: Size.zero,
- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- onPressed: () => widget.notifier.dismissLinkPrompt(machineId),
- child: const Text('Close'),
+ ],
),
),
- ],
- ),
- );
- }
+ ),
+ );
+ },
+ );
}
diff --git a/desktop/lib/widgets/machine_actions.dart b/desktop/lib/widgets/machine_actions.dart
index 9b6e21a8e..6c3f5501b 100644
--- a/desktop/lib/widgets/machine_actions.dart
+++ b/desktop/lib/widgets/machine_actions.dart
@@ -1,48 +1,180 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'terminal_prompt.dart';
-/// Shared "Delete machine" confirmation, used by the sidebar rail's context
-/// menu and the native Machines menu. Delete disconnects the machine's agents
-/// and drops the link (see [AppNotifier.deleteMachine]); it cannot be undone.
+/// Account deletion, shared by the manager and native/legacy machine menus.
+/// A pending request stays with the model if its confirmation is closed.
Future<void> confirmDeleteMachine(
BuildContext context,
AppNotifier notifier, {
required String machineId,
required String displayName,
-}) async {
- final confirmed = await showAppDialog<bool>(
- context: context,
- builder: (dialogContext) => AlertDialog(
- title: const Text('Delete machine'),
- content: SizedBox(
- width: 360,
- child: Text(
- 'Delete "$displayName"? All its agents will be disconnected and '
- "it'll need to be linked again. This can't be undone.",
- style: TextStyle(fontFamily: grid.AppFont.sans, fontSize: 13.5),
+ AppKeymap? keymap,
+}) => showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (_) => _DeleteMachinePrompt(
+ notifier: notifier,
+ machineId: machineId,
+ displayName: displayName,
+ ),
+);
+
+class _DeleteMachinePrompt extends StatefulWidget {
+ const _DeleteMachinePrompt({
+ required this.notifier,
+ required this.machineId,
+ required this.displayName,
+ });
+ final AppNotifier notifier;
+ final String machineId, displayName;
+ @override
+ State<_DeleteMachinePrompt> createState() => _DeleteMachinePromptState();
+}
+
+class _DeleteMachinePromptState extends State<_DeleteMachinePrompt> {
+ final _cancel = FocusNode(debugLabel: 'Cancel machine deletion');
+ final _announcer = BoxAnnouncer();
+ bool _deleting = false;
+ String? _error;
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.notifier.pendingMachineDelete(widget.machineId)
+ case final pending?) {
+ _deleting = true;
+ unawaited(_finish(pending));
+ } else {
+ _focusCancel();
+ }
+ }
+
+ void _focusCancel() => WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _cancel.requestFocus();
+ }
+ });
+
+ @override
+ void dispose() {
+ _cancel.dispose();
+ super.dispose();
+ }
+
+ void _close() => Navigator.pop(context);
+
+ void _delete() {
+ if (_deleting) return;
+ setState(() {
+ _deleting = true;
+ _error = null;
+ });
+ unawaited(_finish(widget.notifier.deleteMachine(widget.machineId)));
+ }
+
+ Future<void> _finish(Future<String?> request) async {
+ final error = await request;
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.pop(context);
+ return;
+ }
+ setState(() {
+ _deleting = false;
+ _error = error;
+ });
+ _announcer.row(context, error);
+ _focusCancel();
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => TerminalPromptKeys(
+ cancel: _close,
+ child: TerminalPrompt(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'Delete machine',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ widget.displayName,
+ style: boxMonoStyle(weight: FontWeight.w600),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Delete this machine from your account and close its panes in this window?',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ const SizedBox(height: 12),
+ if (!_deleting)
+ Wrap(
+ spacing: 12,
+ children: [
+ terminalPromptButton(
+ 'Cancel',
+ _close,
+ focusNode: _cancel,
+ ),
+ terminalPromptButton(
+ 'Delete',
+ _delete,
+ danger: true,
+ key: const Key('machine-delete-confirm'),
+ ),
+ ],
+ )
+ else
+ Text(
+ 'Deletion continues if you close this prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
+ ),
+ ),
+ BoxHintStrip(
+ message: _error ?? (_deleting ? 'Deleting machine…' : null),
+ isError: _error != null,
+ hints: [
+ if (!_deleting)
+ BoxHint(
+ terminalPromptHint(context, 'picker.accept', 'enter'),
+ 'select',
+ ),
+ if (!_deleting)
+ BoxHint(
+ terminalPromptHint(context, 'picker.complete', 'tab'),
+ 'controls',
+ ),
+ BoxHint(
+ terminalPromptHint(context, 'picker.cancel', 'esc'),
+ 'close',
+ onTap: _close,
+ ),
+ ],
+ ),
+ ],
),
),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(dialogContext).pop(false),
- child: const Text('Cancel'),
- ),
- FilledButton(
- style: FilledButton.styleFrom(
- backgroundColor: grid.AppPalette.dangerFill,
- ),
- onPressed: () => Navigator.of(dialogContext).pop(true),
- child: const Text('Delete'),
- ),
- ],
),
);
- if (confirmed != true || !context.mounted) return;
- final error = await notifier.deleteMachine(machineId);
- if (error != null && context.mounted) {
- ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(error)));
- }
}
diff --git a/desktop/lib/widgets/machine_rail.dart b/desktop/lib/widgets/machine_rail.dart
index 7a5b5965a..a93eb5648 100644
--- a/desktop/lib/widgets/machine_rail.dart
+++ b/desktop/lib/widgets/machine_rail.dart
@@ -1022,7 +1022,7 @@ class _AgentRowState extends State<_AgentRow> {
notifier,
state.machine.machineId,
agent.id,
- agent.name,
+ agent.displayName,
);
/// The row's way into the shared confirmation — see delete_agent_dialog.dart.
@@ -1031,7 +1031,7 @@ class _AgentRowState extends State<_AgentRow> {
notifier,
state.machine.machineId,
agent.id,
- agent.name,
+ agent.displayName,
engine: agent.engine,
);
@@ -1043,7 +1043,7 @@ class _AgentRowState extends State<_AgentRow> {
notifier,
state.machine.machineId,
agent.id,
- agent.name,
+ agent.displayName,
engine: agent.engine,
);
@@ -1112,7 +1112,7 @@ class _AgentRowState extends State<_AgentRow> {
agentId: agent.id,
),
child: SidebarItem(
- label: agent.name,
+ label: agent.displayName,
selected: selected,
enabled: enabled,
dimmed: !visuallyEnabled,
@@ -1227,7 +1227,9 @@ class _AgentRowState extends State<_AgentRow> {
const AppMenuDivider(),
AppMenuItem(
icon: LucideIcons.refreshCw300,
- label: 'Restart Harness',
+ label: isTerminalEngine(agent.engine)
+ ? 'Restart Terminal'
+ : 'Restart Agent',
onPressed: () {
_agentMenu.close();
_restartAgent();
@@ -1236,7 +1238,7 @@ class _AgentRowState extends State<_AgentRow> {
if (agent.canFork)
AppMenuItem(
icon: LucideIcons.gitFork300,
- label: 'Fork Harness',
+ label: 'Fork Agent',
onPressed: () {
_agentMenu.close();
_forkAgent();
@@ -1245,7 +1247,7 @@ class _AgentRowState extends State<_AgentRow> {
const AppMenuDivider(),
AppMenuItem(
icon: Icons.stop_rounded,
- label: 'Stop Harness',
+ label: 'Stop Agent',
danger: true,
onPressed: () {
_agentMenu.close();
@@ -1275,7 +1277,7 @@ class _AgentRowState extends State<_AgentRow> {
data: AgentDragRef(
machineId: machineId,
agentId: agent.id,
- name: agent.name,
+ name: agent.displayName,
),
// Horizontal only, and the rail is a scrolling list — that is the whole
// reason. An unrestricted Draggable competes with the list's own vertical
@@ -1287,11 +1289,14 @@ class _AgentRowState extends State<_AgentRow> {
onDragStarted: () => agentDrag.value = AgentDragRef(
machineId: machineId,
agentId: agent.id,
- name: agent.name,
+ name: agent.displayName,
),
onDragEnd: (_) => agentDrag.value = null,
onDraggableCanceled: (_, _) => agentDrag.value = null,
- feedback: _DragChip(name: agent.name, engine: agent.identityEngine),
+ feedback: _DragChip(
+ name: agent.displayName,
+ engine: agent.identityEngine,
+ ),
// The row stays put and dims. Removing it would reflow the list under the
// pointer mid-drag, moving every other row out from under the place the
// hand had already aimed at.
@@ -1651,7 +1656,7 @@ class _AgentLoadError extends StatelessWidget {
}
}
-/// "New Harness…", drawn as the row it would create.
+/// "New Harness", drawn as the row it would create.
///
/// The rail is a LIST, and every framed control put in it has read as a foreign object — there is
/// nothing else in this column with a border or a fill of its own. So this is not a button placed in a
@@ -1692,7 +1697,7 @@ class _NewAgentRow extends StatelessWidget {
// one. A different indent here would bend the trunk at the last branch.
padding: const EdgeInsets.only(left: 28),
child: SidebarItem(
- label: 'New Harness…',
+ label: 'New Harness',
// Dimmed rather than a colour of its own: this row is a placeholder until it is reached for, and
// the hover state SidebarItem already owns is what says it is live.
dimmed: true,
diff --git a/desktop/lib/widgets/machines_manager.dart b/desktop/lib/widgets/machines_manager.dart
index 05fafa36d..f42eeaaaf 100644
--- a/desktop/lib/widgets/machines_manager.dart
+++ b/desktop/lib/widgets/machines_manager.dart
@@ -1,225 +1,631 @@
+import 'dart:async';
+
+import 'package:collection/collection.dart' show compareNatural;
import 'package:flutter/material.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../core/fuzzy_match.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'link_machine_dialog.dart';
+import 'link_machine_screen.dart';
+import 'machine_actions.dart';
import 'swarm_dialogs.dart';
+import 'terminal_prompt.dart';
+import 'terminal_name_prompt.dart';
-Future<void> showMachinesManager(BuildContext context, AppNotifier notifier) =>
- showAppDialog<void>(
- context: context,
- builder: (_) => _MachinesManager(notifier: notifier),
- );
+Future<void> showMachinesManager(
+ BuildContext context,
+ AppNotifier notifier, {
+ AppKeymap? keymap,
+}) => showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (_) => _MachinesManager(notifier: notifier),
+);
+
+class _Entry {
+ const _Entry(
+ this.id,
+ this.title,
+ this.detail, {
+ this.machine,
+ this.danger = false,
+ });
+ final String id, title, detail;
+ final MachineState? machine;
+ final bool danger;
+}
class _MachinesManager extends StatefulWidget {
const _MachinesManager({required this.notifier});
final AppNotifier notifier;
-
@override
State<_MachinesManager> createState() => _MachinesManagerState();
}
class _MachinesManagerState extends State<_MachinesManager> {
- bool _refreshing = false;
+ AppNotifier get app => widget.notifier;
+ final _machineQuery = TextEditingController();
+ final _actionQuery = TextEditingController();
+ final _input = FocusNode(debugLabel: 'Find a machine or action');
+ final _rows = <String, GlobalKey>{};
+ final _pointer = BoxPointerGate();
+ final _announcer = BoxAnnouncer();
+ String? _machineId, _machineTitle, _selectedMachine, _selectedAction;
+ String? _message;
+ bool _error = false, _refreshing = false, _nested = false;
- Future<void> _refresh() async {
- if (_refreshing) return;
- setState(() => _refreshing = true);
- try {
- await widget.notifier.retryMachines();
- } finally {
- if (mounted) setState(() => _refreshing = false);
- }
- }
+ TextEditingController get _query =>
+ _machineId == null ? _machineQuery : _actionQuery;
+ MachineState? get _machine =>
+ _machineId == null ? null : app.stateOf(_machineId!);
+ bool get _composing =>
+ _query.value.composing.isValid && !_query.value.composing.isCollapsed;
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- return ListenableBuilder(
- listenable: widget.notifier,
- builder: (context, _) {
- final machines = widget.notifier.machineStates.values.toList();
- return AlertDialog(
- title: const Text('Machines Manager'),
- content: SizedBox(
- width: 600,
- child: ConstrainedBox(
- constraints: BoxConstraints(
- maxHeight: MediaQuery.sizeOf(context).height * 0.55,
- ),
- child: SingleChildScrollView(
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (machines.isEmpty)
- Padding(
- padding: const EdgeInsets.symmetric(vertical: 24),
- child: Text(
- widget.notifier.machinesLoading
- ? 'Loading machines…'
- : 'No machines linked yet.',
- ),
- ),
- for (var i = 0; i < machines.length; i++) ...[
- if (i > 0) const Divider(height: 1),
- ListTile(
- key: ValueKey(
- 'managed-machine-${machines[i].machine.machineId}',
- ),
- contentPadding: const EdgeInsets.symmetric(vertical: 8),
- leading: Icon(
- machines[i].isLocalMachine
- ? Icons.laptop_mac_outlined
- : Icons.desktop_windows_outlined,
- size: 22,
- color: grid.AppPalette.textSecondary,
- ),
- title: Text(machines[i].machine.displayName),
- subtitle: Text(
- [
- if (machines[i].isLocalMachine) 'This computer',
- // Presence and link state are independent segments,
- // the same split the Machines menu and rail use: an
- // unlinked machine whose node is up reads
- // "Online · Link required" rather than the link
- // state hiding that the computer is reachable.
- // "Connecting…" only when presence is genuinely
- // unknown and there is no link prompt to show.
- if (machines[i].nodeOnline == true)
- 'Online'
- else if (machines[i].nodeOnline == false)
- 'Offline'
- else if (!machines[i].needsLink)
- 'Connecting…',
- if (machines[i].needsLink) 'Link required',
- ].join(' · '),
- ),
- trailing: machines[i].machine.isShared
- ? const Text('View only')
- : TextButton(
- onPressed: () => showMachineRenameDialog(
- context,
- widget.notifier,
- machines[i].machine.machineId,
- machines[i].machine.displayName,
- ),
- child: const Text('Rename'),
- ),
- ),
- ],
- ],
- ),
- ),
- ),
+ String _status(MachineState machine) => [
+ if (machine.isLocalMachine) 'this computer',
+ if (machine.nodeOnline == true)
+ 'online'
+ else if (machine.nodeOnline == false)
+ 'offline'
+ else
+ 'checking',
+ if (machine.needsLink) 'link required',
+ if (machine.machine.isShared) 'view only',
+ if (machine.agentLoadStatus == AgentLoadStatus.loaded ||
+ machine.agents.isNotEmpty)
+ '${machine.agents.length} ${machine.agents.length == 1 ? 'agent' : 'agents'}',
+ ].join(' · ');
+
+ List<_Entry> get _allEntries {
+ if (_machineId != null) {
+ final machine = _machine;
+ if (machine == null || machine.machine.isShared) return [];
+ return [
+ if (machine.needsLink && !machine.isLocalMachine)
+ const _Entry(
+ 'link',
+ 'Link this machine',
+ 'Enter its remote password',
),
- actions: [
- TextButton(
- onPressed: _refreshing ? null : _refresh,
- child: Text(_refreshing ? 'Refreshing…' : 'Refresh'),
- ),
- TextButton.icon(
- onPressed: () => showSwarmLinkDialog(context, widget.notifier),
- icon: const Icon(Icons.add, size: 18),
- label: const Text('Link Machine'),
- ),
- FilledButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Done'),
- ),
- ],
+ _Entry(
+ 'rename',
+ 'Rename',
+ app.pendingMachineRename(_machineId!) != null
+ ? 'Saving name…'
+ : 'Change the name in your account',
+ ),
+ if (machine.isLocalMachine)
+ const _Entry(
+ 'password',
+ 'This computer’s password',
+ 'Let another machine connect here',
+ ),
+ if (!machine.isLocalMachine)
+ _Entry(
+ 'delete',
+ 'Delete machine…',
+ app.pendingMachineDelete(_machineId!) != null
+ ? 'Deleting machine…'
+ : 'Remove from your account and close its panes here',
+ danger: true,
+ ),
+ ];
+ }
+ final machines = app.machineStates.values.toList()
+ ..sort((a, b) {
+ if (a.isLocalMachine != b.isLocalMachine) {
+ return a.isLocalMachine ? -1 : 1;
+ }
+ return compareNatural(
+ a.machine.displayName.toLowerCase(),
+ b.machine.displayName.toLowerCase(),
);
- },
+ });
+ return [
+ for (final machine in machines)
+ _Entry(
+ machine.machine.machineId,
+ machine.machine.displayName,
+ _status(machine),
+ machine: machine,
+ ),
+ const _Entry(
+ 'action:link',
+ 'Link Machine',
+ 'Set up or link another computer',
+ ),
+ ];
+ }
+
+ List<_Entry> get _entries {
+ final rows = _allEntries;
+ final query = _query.text.trim().toLowerCase();
+ if (query.isEmpty) return rows;
+ final words = query.split(RegExp(r'\s+'));
+ final ranked = <(int, int, _Entry)>[];
+ for (final (index, entry) in rows.indexed) {
+ final text =
+ '${entry.title} ${entry.detail} ${entry.machine?.machine.hostname ?? ''} ${entry.machine?.machine.machineId ?? ''}'
+ .toLowerCase();
+ var score = 0;
+ var matches = true;
+ for (final word in words) {
+ final literal = text.indexOf(word);
+ if (literal >= 0) {
+ score += literal;
+ continue;
+ }
+ final spread = subsequenceSpread(text, word);
+ if (spread == null) {
+ matches = false;
+ break;
+ }
+ score += 1000 + spread;
+ }
+ if (matches) ranked.add((score, index, entry));
+ }
+ ranked.sort(
+ (a, b) => a.$1 == b.$1 ? a.$2.compareTo(b.$2) : a.$1.compareTo(b.$1),
);
+ return ranked.map((rank) => rank.$3).toList();
}
-}
-Future<void> showMachineRenameDialog(
- BuildContext context,
- AppNotifier notifier,
- String machineId,
- String currentName,
-) => showAppDialog<void>(
- context: context,
- builder: (_) => _RenameMachineDialog(
- notifier: notifier,
- machineId: machineId,
- currentName: currentName,
- ),
-);
+ _Entry? get _selected {
+ final id = _machineId == null ? _selectedMachine : _selectedAction;
+ return _entries.where((row) => row.id == id).firstOrNull ??
+ _entries.firstOrNull;
+ }
-class _RenameMachineDialog extends StatefulWidget {
- const _RenameMachineDialog({
- required this.notifier,
- required this.machineId,
- required this.currentName,
+ void _select(String? id) => setState(() {
+ if (_machineId == null) {
+ _selectedMachine = id;
+ } else {
+ _selectedAction = id;
+ }
});
- final AppNotifier notifier;
- final String machineId;
- final String currentName;
@override
- State<_RenameMachineDialog> createState() => _RenameMachineDialogState();
-}
-
-class _RenameMachineDialogState extends State<_RenameMachineDialog> {
- late final _text = TextEditingController(text: widget.currentName)
- ..selection = TextSelection(
- baseOffset: 0,
- extentOffset: widget.currentName.length,
- );
- bool _saving = false;
- String? _error;
+ void initState() {
+ super.initState();
+ _selectedMachine = _entries.firstOrNull?.id;
+ _focus();
+ }
@override
void dispose() {
- _text.dispose();
+ _machineQuery.dispose();
+ _actionQuery.dispose();
+ _input.dispose();
super.dispose();
}
- Future<void> _save() async {
- if (_saving) return;
- setState(() {
- _saving = true;
- _error = null;
+ void _focus() {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || ModalRoute.of(context)?.isCurrent == false) return;
+ _input.requestFocus();
+ _reveal();
});
- final error = await widget.notifier.renameMachine(
- widget.machineId,
- _text.text,
- );
+ }
+
+ void _reveal() {
+ final context = _rows[_selected?.id]?.currentContext;
+ if (context != null) Scrollable.ensureVisible(context, alignment: .5);
+ }
+
+ void _changed(String _) {
+ _select(_entries.firstOrNull?.id);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _reveal();
+ });
+ }
+
+ void _move(int step) {
+ if (!_input.hasFocus) {
+ if (step > 0) {
+ FocusManager.instance.primaryFocus?.nextFocus();
+ } else {
+ FocusManager.instance.primaryFocus?.previousFocus();
+ }
+ return;
+ }
+ final rows = _entries;
+ if (rows.isEmpty) return;
+ final index = rows.indexWhere((row) => row.id == _selected?.id);
+ final selected = rows[(index + step).clamp(0, rows.length - 1)];
+ _select(selected.id);
+ _announcer.row(context, '${selected.title}, ${selected.detail}');
+ _reveal();
+ }
+
+ void _say(String? message, {bool error = false}) {
if (!mounted) return;
- if (error == null) {
- Navigator.pop(context);
+ setState(() {
+ _message = message;
+ _error = error;
+ });
+ _announcer.row(context, message);
+ }
+
+ Future<void> _refresh() async {
+ if (_refreshing || app.machinesRefreshing) return;
+ setState(() {
+ _refreshing = true;
+ _message = null;
+ });
+ try {
+ await app.retryMachines();
+ if (mounted) {
+ final error = app.machineListError ?? app.lastError;
+ _say(error, error: error != null);
+ }
+ } catch (_) {
+ _say('Could not refresh machines. Try again.', error: true);
+ } finally {
+ if (mounted) setState(() => _refreshing = false);
+ }
+ }
+
+ void _back() {
+ if (_nested || _composing) return;
+ if (_machineId == null) {
+ Navigator.of(context).pop();
+ return;
+ }
+ setState(() {
+ _machineId = null;
+ _message = null;
+ });
+ _focus();
+ }
+
+ void _accept() {
+ if (_nested || _composing) return;
+ if (_input.hasFocus) {
+ unawaited(_open(_selected));
} else {
+ activatePromptControl();
+ }
+ }
+
+ Future<void> _open(_Entry? entry) async {
+ if (entry == null || _nested || _composing) return;
+ if (entry.machine case final machine?) {
setState(() {
- _saving = false;
- _error = error;
+ _selectedMachine = entry.id;
+ _machineId = entry.id;
+ _machineTitle = machine.machine.displayName;
+ _actionQuery.clear();
+ _selectedAction = null;
+ _message = null;
});
+ _focus();
+ return;
+ }
+ final id = _machineId;
+ final machine = _machine;
+ if (entry.id != 'action:link' && machine == null) return;
+ setState(() => _nested = true);
+ try {
+ switch (entry.id) {
+ case 'action:link':
+ await showSwarmLinkDialog(context, app);
+ case 'rename':
+ await showMachineRenameDialog(
+ context,
+ app,
+ id!,
+ machine!.machine.displayName,
+ );
+ case 'delete':
+ await confirmDeleteMachine(
+ context,
+ app,
+ machineId: id!,
+ displayName: machine!.machine.displayName,
+ );
+ if (mounted && app.stateOf(id) == null) {
+ setState(() {
+ _machineId = null;
+ _message = '${machine.machine.displayName} deleted.';
+ _error = false;
+ });
+ }
+ case 'password':
+ await showLinkMachineDialog(context, app);
+ case 'link':
+ await showLinkMachineScreenDialog(context, app, id!);
+ if (mounted && app.stateOf(id)?.needsLink == false) {
+ _say('${machine!.machine.displayName} linked.');
+ }
+ }
+ } finally {
+ if (mounted) {
+ setState(() => _nested = false);
+ _focus();
+ }
}
}
- @override
- Widget build(BuildContext context) => AlertDialog(
- title: const Text('Rename Machine'),
- content: SizedBox(
- width: 360,
- child: TextField(
- controller: _text,
- autofocus: true,
- readOnly: _saving,
- decoration: InputDecoration(labelText: 'Name', errorText: _error),
- onSubmitted: (_) => _save(),
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Cancel'),
+ String _hint(String command, String fallback) =>
+ terminalPromptHint(context, command, fallback);
+
+ Widget _row(_Entry entry) {
+ final selected = _selected?.id == entry.id;
+ return KeyedSubtree(
+ key: ValueKey(
+ entry.machine == null
+ ? 'machine-action-${entry.id}'
+ : 'managed-machine-${entry.id}',
),
- FilledButton(
- onPressed: _saving ? null : _save,
- child: Text(_saving ? 'Saving…' : 'Save'),
+ child: MouseRegion(
+ onHover: (event) {
+ if (_pointer.moved(event)) _select(entry.id);
+ },
+ child: Semantics(
+ button: true,
+ selected: selected,
+ child: InkWell(
+ key: _rows.putIfAbsent(entry.id, GlobalKey.new),
+ canRequestFocus: false,
+ onTap: () => unawaited(_open(entry)),
+ child: BoxRowHighlight(
+ highlighted: selected,
+ accent: Colors.white70,
+ terminal: true,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 20,
+ child: Text(selected ? '>' : ' ', style: boxMonoStyle()),
+ ),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ entry.title,
+ style: boxMonoStyle(
+ color: entry.danger
+ ? Colors.orangeAccent
+ : Colors.white,
+ weight: selected ? FontWeight.w600 : null,
+ ),
+ ),
+ Text(
+ entry.detail,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
),
- ],
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([app, terminalFontStore]),
+ builder: (context, _) {
+ final rows = _entries;
+ final machine = _machine;
+ final empty = _machineId != null && machine == null
+ ? 'This machine is no longer available.'
+ : machine?.machine.isShared == true
+ ? 'Shared machines are view-only. Their owner manages machine settings.'
+ : app.machinesLoading
+ ? 'Loading machines…'
+ : 'No matching ${_machineId == null ? 'machines' : 'actions'}.';
+ return Offstage(
+ offstage: _nested,
+ child: TerminalPromptKeys(
+ inputFocus: _input,
+ composing: () => _composing,
+ cancel: _back,
+ accept: _accept,
+ next: () => _move(1),
+ previous: () => _move(-1),
+ pageDown: () => _move(8),
+ pageUp: () => _move(-8),
+ refresh: () => unawaited(_refresh()),
+ child: TerminalPrompt(
+ width: 760,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Expanded(
+ child: Text(
+ _machineId == null
+ ? 'Machines Manager'
+ : machine?.machine.displayName ??
+ _machineTitle ??
+ 'Machine',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ Text(
+ '${rows.length}/${_allEntries.length}',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14),
+ child: ReadlineKeys(
+ controller: _query,
+ onChanged: _changed,
+ child: TextField(
+ key: const Key('machines-manager-search'),
+ controller: _query,
+ focusNode: _input,
+ style: boxMonoStyle(),
+ textAlignVertical: TextAlignVertical.center,
+ textInputAction: TextInputAction.done,
+ decoration: InputDecoration(
+ hintText: _machineId == null
+ ? 'find a machine / link another'
+ : 'find an action',
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ isDense: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ _machineId == null ? 'machine >' : 'action >',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
+ ),
+ ),
+ prefixIconConstraints: const BoxConstraints(
+ minHeight: 38,
+ ),
+ contentPadding: EdgeInsets.zero,
+ ),
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) => _accept(),
+ ),
+ ),
+ ),
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(6, 8, 6, 8),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (machine != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
+ child: SelectableText(
+ [
+ _status(machine),
+ if (machine.machine.ownerName case final owner?)
+ 'shared by $owner',
+ ?machine.machine.hostname,
+ machine.machine.machineId,
+ ].join(' · '),
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ),
+ if (_machineId == null &&
+ app.machineStates.isEmpty &&
+ _machineQuery.text.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(12),
+ child: Text(
+ app.machinesLoading
+ ? 'Loading machines…'
+ : app.machineListError != null
+ ? 'Machine list unavailable.'
+ : 'No machines available yet.',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (rows.isEmpty)
+ Padding(
+ padding: const EdgeInsets.all(12),
+ child: Text(
+ empty,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ )
+ else
+ ...rows.map(_row),
+ ],
+ ),
+ ),
+ ),
+ BoxHintStrip(
+ message: _refreshing || app.machinesRefreshing
+ ? 'Refreshing machines…'
+ : _message ?? app.machineListError,
+ isError:
+ !_refreshing &&
+ !app.machinesRefreshing &&
+ (_error ||
+ _message == null && app.machineListError != null),
+ hints: [
+ if (rows.isNotEmpty)
+ BoxHint(
+ '${_hint('picker.previous', '↑')}/${_hint('picker.next', '↓')}',
+ 'select',
+ ),
+ if (rows.isNotEmpty)
+ BoxHint(
+ _hint('picker.accept', 'enter'),
+ _machineId == null && _selected?.machine != null
+ ? 'actions'
+ : 'open',
+ onTap: () => unawaited(_open(_selected)),
+ ),
+ BoxHint(
+ _hint(
+ 'picker.refresh',
+ Theme.of(context).platform == TargetPlatform.macOS
+ ? 'cmd-r'
+ : 'ctrl-r',
+ ),
+ 'refresh',
+ onTap: () => unawaited(_refresh()),
+ ),
+ BoxHint(
+ _hint('picker.cancel', 'esc'),
+ _machineId == null ? 'close' : 'back',
+ onTap: _back,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ },
+ );
+}
+
+Future<void> showMachineRenameDialog(
+ BuildContext context,
+ AppNotifier notifier,
+ String machineId,
+ String currentName,
+) async {
+ await showTerminalPrompt<String>(
+ context,
+ builder: (_) => TerminalNamePrompt(
+ title: 'Rename Machine',
+ name: notifier.pendingMachineName(machineId) ?? currentName,
+ fieldKey: const Key('machine-rename-input'),
+ fieldLabel: 'Machine name',
+ pending: notifier.pendingMachineRename(machineId),
+ save: (name) => notifier.renameMachine(machineId, name),
+ ),
);
}
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index 8ba82c9cc..2273cfe54 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -20,11 +20,15 @@ import '../shared/widgets/app_icon_button.dart';
import '../shared/widgets/app_choice_picker.dart';
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../state/harness_placement.dart';
+import '../state/new_harness.dart';
import '../store/store_editorial.dart';
import 'engine_identity.dart';
import 'codex_profile_field.dart';
import 'agent_picker.dart';
+import 'box_chrome.dart';
import 'remote_folder_picker.dart';
import 'new_agent_project_picker.dart';
import 'new_harness_help.dart';
@@ -49,8 +53,15 @@ Future<NewAgentDialogResult?> showNewAgentDialog(
String machineId, {
required String source,
String? initialFolder,
+ ProjectFolderRequest? initialProjectFolder,
+ String? initialPermissionMode,
+ bool initiallyAdvanced = false,
+ NewHarnessDraft? initialDraft,
+ ValueChanged<NewHarnessDraft>? onBack,
+ AppKeymap? keymap,
String? swarmId,
PaneSplitRequest? split,
+ HarnessPlacement? placement,
Future<void>? initialEngineProbe,
bool offerFindExisting = false,
bool offerBackToSearch = false,
@@ -62,6 +73,14 @@ Future<NewAgentDialogResult?> showNewAgentDialog(
/// The harness's first message, sent as it starts — the store's "Try this prompt".
String? initialPrompt,
}) {
+ if (initialDraft != null) {
+ machineId = initialDraft.machineId;
+ initialEngine = initialDraft.engine;
+ initialFolder = initialDraft.project.folder;
+ initialProjectFolder = initialDraft.projectFolderRequest;
+ initialPermissionMode = initialDraft.permissionMode;
+ initialPrompt = initialDraft.task;
+ }
// Reported here rather than at each call site: the doors are four and
// growing, and one that forgets to track is a hole in the funnel that only
// shows up as a number quietly being too small.
@@ -75,22 +94,36 @@ Future<NewAgentDialogResult?> showNewAgentDialog(
'';
}
analytics.newAgentOpened(source: source);
+ // This dialog uses a separate route. Carry the live picker bindings with
+ // it; showGeneralDialog does not capture inherited themes for us.
+ final activeKeymap = keymap ?? KeymapTheme.of(context, listen: false);
return showAppDialog<NewAgentDialogResult>(
context: context,
transitionDuration: Duration.zero,
veilBlur: 0,
- builder: (context) => _NewAgentDialog(
- notifier: notifier,
- initialEngine: initialEngine,
- initialPrompt: initialPrompt,
- machineId: machineId,
- initialFolder: initialFolder,
- swarmId: swarmId ?? notifier.activeSwarmId,
- split: split,
- initialEngineProbe: initialEngineProbe,
- offerFindExisting: offerFindExisting,
- offerBackToSearch: offerBackToSearch,
- ),
+ builder: (context) {
+ final dialog = _NewAgentDialog(
+ notifier: notifier,
+ initialEngine: initialEngine,
+ initialPrompt: initialPrompt,
+ machineId: machineId,
+ initialFolder: initialFolder,
+ initialProjectFolder: initialProjectFolder,
+ initialPermissionMode: initialPermissionMode,
+ initiallyAdvanced: initiallyAdvanced,
+ initialDraft: initialDraft,
+ onBack: onBack,
+ swarmId: swarmId ?? notifier.activeSwarmId,
+ split: split,
+ placement: placement,
+ initialEngineProbe: initialEngineProbe,
+ offerFindExisting: offerFindExisting,
+ offerBackToSearch: offerBackToSearch,
+ );
+ return activeKeymap == null
+ ? dialog
+ : KeymapProvider(keymap: activeKeymap, child: dialog);
+ },
);
}
@@ -98,8 +131,14 @@ class _NewAgentDialog extends StatefulWidget {
final AppNotifier notifier;
final String machineId;
final String? initialFolder;
+ final ProjectFolderRequest? initialProjectFolder;
+ final String? initialPermissionMode;
+ final bool initiallyAdvanced;
+ final NewHarnessDraft? initialDraft;
+ final ValueChanged<NewHarnessDraft>? onBack;
final String swarmId;
final PaneSplitRequest? split;
+ final HarnessPlacement? placement;
final Future<void>? initialEngineProbe;
final bool offerFindExisting;
final bool offerBackToSearch;
@@ -108,8 +147,14 @@ class _NewAgentDialog extends StatefulWidget {
required this.notifier,
required this.machineId,
this.initialFolder,
+ this.initialProjectFolder,
+ this.initialPermissionMode,
+ this.initiallyAdvanced = false,
+ this.initialDraft,
+ this.onBack,
required this.swarmId,
this.split,
+ this.placement,
this.initialEngineProbe,
required this.offerFindExisting,
required this.offerBackToSearch,
@@ -133,7 +178,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// starts the harness with nothing sent. The Store's "Try this prompt" fills
/// it, and the person can change it before creating.
late final _task = TextEditingController(
- text: widget.initialPrompt?.trim() ?? '',
+ text: widget.initialDraft?.task ?? widget.initialPrompt?.trim() ?? '',
);
String? get _firstPrompt {
final task = _task.text.trim();
@@ -160,14 +205,22 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
final _folderFocus = FocusNode(debugLabel: 'Working folder');
final _agentSearchFocus = FocusNode(debugLabel: 'Agent search');
final _actionFocus = FocusNode(debugLabel: 'Create or check agent');
- GitHubRepository? _repository;
+ late GitHubRepository? _repository = widget.initialProjectFolder?.repository;
+ late String? _projectName = widget.initialProjectFolder?.name;
+ late ProjectFolderRequest? _generatedProject =
+ widget.initialProjectFolder?.isGenerated == true
+ ? widget.initialProjectFolder
+ : null;
final _choicesScroll = ScrollController();
final _projectChoices = PageStorageBucket();
- late _FolderSource _folderSource = widget.initialFolder == null
+ late _FolderSource _folderSource =
+ widget.initialProjectFolder?.repository != null
+ ? _FolderSource.remote
+ : widget.initialFolder == null
? _FolderSource.newProject
: _FolderSource.local;
String? _preparedFolder;
- AgentCreationAttempt? _creation;
+ late AgentCreationAttempt? _creation = widget.initialDraft?.attempt;
bool _checkingCreation = false;
bool get _confirmationPending => _creation?.awaitingConfirmation == true;
bool get _choicesLocked => _submitting || _confirmationPending;
@@ -176,13 +229,15 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
late String _machineId = widget.machineId;
int _machineRevision = 0;
late String? _folder = widget.initialFolder;
- LocalCodexProfile? _codexProfile;
+ late LocalCodexProfile? _codexProfile = widget.initialDraft?.profile;
+ late bool _codexProfileChosen = widget.initialDraft?.profileChosen ?? false;
bool _codexProfilesBusy = true;
/// Auto-approve unless the person picks otherwise: a new harness works without stopping to ask
/// for each command — Claude Code's manual mode was what every harness opened in before. Kept
/// across engine changes; an engine without the picked mode uses its default instead.
- String _permissionMode = kDefaultPermissionMode;
+ late String _permissionMode =
+ widget.initialPermissionMode ?? kDefaultPermissionMode;
/// The mode [engine] launches in: the picked one when it has it.
String _permissionModeFor(String engine) {
@@ -192,10 +247,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
: kDefaultPermissionMode;
}
- /// Whether the fold is open. Closed on every open of the dialog, deliberately:
- /// it is shut for the case it exists to serve, and a drawer that remembers
- /// being open is a drawer that is open for somebody who never asked.
- bool _advancedOpen = false;
+ /// Direct creation starts compact. More options from the task prompt opens
+ /// the advanced controls immediately, keeping the chosen mode visible.
+ late bool _advancedOpen = widget.initiallyAdvanced;
bool _submitting = false;
/// A harness install is running ahead of the create. Its progress line is
@@ -379,6 +433,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
if (_engine != remembered) {
_engine = remembered!;
_codexProfile = null;
+ _codexProfileChosen = false;
_codexProfilesBusy = true;
}
});
@@ -417,6 +472,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
setState(() {
_engine = preferred;
_codexProfile = null;
+ _codexProfileChosen = false;
_codexProfilesBusy = true;
});
}
@@ -450,7 +506,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
}
bool _picking = false;
- String? _error;
+ late String? _error = widget.initialDraft?.error;
/// Whether the machine this agent will run on is the computer the app is
/// running on, which is what decides where the folder is picked.
@@ -580,6 +636,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
projectFolder: project,
swarmId: widget.swarmId,
split: widget.split,
+ placement: widget.placement,
bypassPermission: bypassPermission,
permissionMode: permissionMode,
// Keep the explicit choice even if machine discovery changes mid-submit.
@@ -619,7 +676,8 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
}
ProjectFolderRequest? get _projectFolder => switch (_folderSource) {
- _FolderSource.newProject => const ProjectFolderRequest.newProject(),
+ _FolderSource.newProject =>
+ _generatedProject ?? ProjectFolderRequest.newProject(name: _projectName),
_FolderSource.local => null,
_FolderSource.remote => switch (_repository) {
final repository? => ProjectFolderRequest.remote(repository),
@@ -629,6 +687,30 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
void _toggleAdvanced() => setState(() => _advancedOpen = !_advancedOpen);
+ NewHarnessDraft get _draft {
+ final folder =
+ _preparedFolder ??
+ (_folderSource == _FolderSource.local ? _folder : null);
+ return NewHarnessDraft(
+ machineId: _machineId,
+ engine: _engine,
+ project: folder != null
+ ? NewHarnessProject.folder(folder)
+ : _folderSource == _FolderSource.remote && _repository != null
+ ? NewHarnessProject.clone(_repository!)
+ : _generatedProject != null
+ ? NewHarnessProject.generated(_generatedProject!)
+ : NewHarnessProject.fresh(_projectName),
+ task: _task.text,
+ permissionMode: _permissionMode,
+ profile: _codexProfile,
+ profileChosen: _codexProfileChosen,
+ attempt: _creation,
+ error: _error,
+ projectsByMachine: widget.initialDraft?.projectsByMachine ?? const {},
+ );
+ }
+
@override
Widget build(BuildContext context) {
// Reads colour tokens, and lives in an Overlay — a top-down rebuild never
@@ -637,10 +719,13 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
grid.AppTheme.watch(context);
return ListenableBuilder(
listenable: widget.notifier,
- builder: (context, _) => PopScope(
+ builder: (context, _) => PopScope<NewAgentDialogResult>(
// The launch request cannot be cancelled after it is sent. Keep its
// outcome visible instead of allowing an accidental second launch.
canPop: !_submitting,
+ onPopInvokedWithResult: (didPop, result) {
+ if (didPop && result == null) widget.onBack?.call(_draft);
+ },
child: _buildDialog(context),
),
);
@@ -648,14 +733,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// The dialog's title: what it makes, and where a split puts it. The
/// primary button says "New Harness" alone.
- String get _title => switch (widget.split?.axis) {
- PaneResizeAxis.x => 'New Harness to the right',
- PaneResizeAxis.y => 'New Harness below',
- null => 'New Harness',
- };
+ String get _title =>
+ widget.placement?.createAction ??
+ switch (widget.split?.axis) {
+ PaneResizeAxis.x => 'New Harness to the right',
+ PaneResizeAxis.y => 'New Harness below',
+ null => 'New Harness',
+ };
Widget _buildDialog(BuildContext context) {
- final edgePadding = MediaQuery.sizeOf(context).width < 700 ? 24.0 : 36.0;
+ const edgePadding = 14.0;
final compactHeight = MediaQuery.sizeOf(context).height < 800;
final canCreate =
(_preparedFolder != null ||
@@ -677,37 +764,24 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
},
},
child: AlertDialog(
+ alignment: Alignment.topCenter,
+ insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
constraints: BoxConstraints.tightFor(
width: _dialogWidth + edgePadding * 2,
),
backgroundColor: grid.AppPalette.swarmField,
surfaceTintColor: Colors.transparent,
- shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(28)),
- title: Text(_title),
- titleTextStyle: Theme.of(context).textTheme.headlineSmall?.copyWith(
- fontSize: 28,
- height: 1.2,
- fontWeight: grid.AppFont.semibold,
- color: grid.AppPalette.textPrimary,
- ),
- titlePadding: EdgeInsets.fromLTRB(
- edgePadding,
- compactHeight ? 24 : 32,
- edgePadding,
- 0,
- ),
- contentPadding: EdgeInsets.fromLTRB(
- edgePadding,
- compactHeight ? 24 : 32,
- edgePadding,
- 40,
- ),
- actionsPadding: EdgeInsets.fromLTRB(
- edgePadding,
- 0,
- edgePadding,
- compactHeight ? 24 : 28,
+ elevation: 4,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(3),
+ side: BorderSide(color: Colors.white.withValues(alpha: .24)),
),
+ title: Text(_title),
+ titleTextStyle: boxMonoStyle(size: 12, color: kBoxFaint),
+ contentTextStyle: boxMonoStyle(),
+ titlePadding: EdgeInsets.fromLTRB(edgePadding, 12, edgePadding, 0),
+ contentPadding: EdgeInsets.fromLTRB(edgePadding, 16, edgePadding, 16),
+ actionsPadding: EdgeInsets.fromLTRB(edgePadding, 0, edgePadding, 10),
actionsOverflowButtonSpacing: 8,
content: SizedBox(
width: _dialogWidth,
@@ -753,7 +827,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- SizedBox(height: compactHeight ? 24 : 32),
+ const SizedBox(height: 16),
_sectionHeader(
'First task',
_takesTask
@@ -840,7 +914,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
style: TextButton.styleFrom(
foregroundColor: grid.AppPalette.textSecondary,
),
- child: const Text('Close'),
+ child: Text(widget.onBack == null ? 'Close' : 'Back'),
),
if (widget.offerFindExisting &&
_confirmationPending &&
@@ -859,24 +933,21 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
focusNode: _actionFocus,
onPressed: canCreate ? _submit : null,
style: FilledButton.styleFrom(
- // Taller and larger type, in proportion with the
- // tile-tall rows above it; no wider at rest, so the
- // settings beside it keep their one line at 900.
- minimumSize: const Size(192, 64),
+ minimumSize: const Size(0, 32),
maximumSize: const Size(420, double.infinity),
padding: const EdgeInsets.symmetric(
- horizontal: 32,
- vertical: 18,
+ horizontal: 12,
+ vertical: 8,
),
- backgroundColor: grid.AppPalette.accent,
+ backgroundColor: Colors.white.withValues(alpha: .08),
foregroundColor: Colors.white,
- textStyle: TextStyle(
- fontFamily: grid.AppFont.sans,
- fontFamilyFallback: grid.AppFont.sansFallback,
- fontSize: 18,
- fontWeight: FontWeight.w600,
+ textStyle: boxMonoStyle(),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(2),
+ side: BorderSide(
+ color: Colors.white.withValues(alpha: .24),
+ ),
),
- shape: const StadiumBorder(),
disabledForegroundColor: _submitting
? grid.AppPalette.textPrimary
: null,
@@ -913,7 +984,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
? 'Installing ${_labelOf(_engine)}…'
: _engineIsTerminal
? 'Opening terminal…'
- : 'Creating harness…',
+ : 'Starting harness…',
),
),
],
@@ -935,7 +1006,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
constraints.maxWidth < 740 * math.min(1.4, scale);
// Keep the controls mounted when the footer wraps or hides.
// In particular, an explicit Default profile must stay chosen.
- return Flex(
+ final controls = Flex(
direction: stacked ? Axis.vertical : Axis.horizontal,
mainAxisSize: stacked ? MainAxisSize.min : MainAxisSize.max,
crossAxisAlignment: stacked
@@ -950,6 +1021,35 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Align(alignment: Alignment.centerRight, child: actions),
],
);
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ controls,
+ const SizedBox(height: 8),
+ DefaultTextStyle(
+ style: boxMonoStyle(),
+ child: BoxHintStrip(
+ hints: [
+ BoxHint(
+ Theme.of(context).platform == TargetPlatform.macOS
+ ? 'cmd-enter'
+ : 'ctrl-enter',
+ _confirmationPending ? 'check status' : 'create',
+ onTap: canCreate ? _submit : null,
+ ),
+ const BoxHint('tab / shift-tab', 'fields'),
+ BoxHint(
+ 'esc',
+ widget.onBack == null ? 'close' : 'back',
+ onTap: _submitting
+ ? null
+ : () => Navigator.of(context).maybePop(),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
},
),
),
@@ -966,7 +1066,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
HarnessHelpTopic? helpTopic, {
required bool compactHeight,
}) => Padding(
- padding: EdgeInsets.only(bottom: compactHeight ? 12 : 16),
+ padding: const EdgeInsets.only(bottom: 6),
child: OverflowBar(
alignment: MainAxisAlignment.spaceBetween,
overflowAlignment: OverflowBarAlignment.end,
@@ -988,15 +1088,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
TextSpan(text: ' $prompt'),
],
),
- style: TextStyle(
- fontSize: 20,
- height: 1.35,
- fontWeight: grid.AppFont.regular,
- color: grid.AppPalette.textSecondary,
- ),
+ style: boxMonoStyle(size: 12, color: grid.AppPalette.textSecondary),
),
),
- if (helpTopic != null) HarnessHelpLink(topic: helpTopic),
+ if (helpTopic != null)
+ HarnessHelpLink(topic: helpTopic, textStyle: boxMonoStyle(size: 12)),
],
),
);
@@ -1005,41 +1101,18 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// but never on its width — so the task field, laid out outside the tiles'
/// LayoutBuilder, can be the same height as they are.
static double _tileHeight(TextScaler scaler, {required bool compactHeight}) {
- final labelLine =
- scaler.scale(AppChoiceTileContent.labelSize) *
- AppChoiceTileContent.lineHeight;
- final detailLine =
- scaler.scale(AppChoiceTileContent.detailSize) *
- AppChoiceTileContent.lineHeight;
- return math.max(
- compactHeight ? 96 : 100,
- math.max(labelLine * 2 + detailLine, labelLine + detailLine * 2) + 38,
- );
+ return math.max(32, scaler.scale(13) * 1.35 + 14);
}
Widget _choices() => LayoutBuilder(
builder: (context, constraints) {
final scaler = MediaQuery.textScalerOf(context);
final compactHeight = MediaQuery.sizeOf(context).height < 800;
- final sectionGap = compactHeight ? 24.0 : 32.0;
- final minimumTileWidth = 172 * math.min(1.3, scaler.scale(16) / 16);
- final columns =
- constraints.maxWidth >= minimumTileWidth * 4 + AppChoiceTile.gap * 3
- ? 4
- : constraints.maxWidth >= minimumTileWidth * 2 + AppChoiceTile.gap
- ? 2
- : 1;
- // Three lines of text, and the 38 the tile spends on its own padding and
- // the gap between them. Three because the name and the detail under it
- // each want two and the tile can afford one second line between them:
- // sized for whichever of those two shapes is taller, so either can
- // happen without the column overflowing its box. The detail is the one
- // that usually takes it — "Documents · Typst GmbH" does not fit on one
- // line at this width, and on one it arrived as "Documents · Typst Gm…".
- // Which line is spent where is decided per tile, against the name it
- // actually holds: AppChoiceTileContent.linesFor.
+ const sectionGap = 16.0;
+ // Single-line choices keep names and machine/project context readable.
+ // Their shared full width also makes keyboard focus easy to follow.
final tileSize = Size(
- (constraints.maxWidth - AppChoiceTile.gap * (columns - 1)) / columns,
+ constraints.maxWidth,
_tileHeight(scaler, compactHeight: compactHeight),
);
return Column(
@@ -1056,6 +1129,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
compactHeight: compactHeight,
),
AgentPicker(
+ terminalStyle: true,
key: const Key('new-agent-agent-picker'),
focusNode: _agentSearchFocus,
// A tile's height, so the bar is in proportion with the rows of
@@ -1124,7 +1198,20 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_engineChosenByUser = true;
if (_engine != value) {
_engine = value;
+ if (_generatedProject != null) {
+ _generatedProject = ProjectFolderRequest.generated(
+ label:
+ widget.notifier
+ .stateOf(_machineId)
+ ?.dsh[value]
+ ?.name ??
+ engineIdentity(value).label,
+ at: DateTime.now(),
+ );
+ _projectName = _generatedProject!.name;
+ }
_codexProfile = null;
+ _codexProfileChosen = false;
_codexProfilesBusy = true;
// A terminal cannot clone: a Git project chosen for an
// agent goes back to the default, as the project picker
@@ -1151,9 +1238,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Expanded(
child: Text(
'Couldn’t check whether ${_labelOf(_baseEngine(_engine))} is installed. '
- 'You can still try creating the harness.',
- style: Theme.of(context).textTheme.bodySmall
- ?.copyWith(color: grid.AppPalette.textSecondary),
+ 'You can still try starting the harness.',
+ style: boxMonoStyle(
+ size: 12,
+ color: grid.AppPalette.textSecondary,
+ ),
),
),
const SizedBox(width: 12),
@@ -1185,6 +1274,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
PageStorage(
bucket: _projectChoices,
child: NewAgentProjectPicker(
+ terminalStyle: true,
// Keyed on the kind too: a terminal's tiles differ (Home, no
// Git), and switching remounts the picker with them.
key: ValueKey(
@@ -1194,6 +1284,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
notifier: widget.notifier,
machineId: _machineId,
initialFolder: _folder,
+ initialProject: _repository != null
+ ? ProjectFolderRequest.remote(_repository!)
+ : _projectName != null
+ ? _generatedProject ??
+ ProjectFolderRequest.newProject(name: _projectName)
+ : null,
focusNode: _folderFocus,
tileSize: tileSize,
locked: _choicesLocked,
@@ -1201,12 +1297,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
// home when none is named, never in one prepared or cloned.
terminal: _engineIsTerminal,
onBrowse: _browse,
- onSelected: (folder, repository) {
+ onSelected: (folder, project) {
if (_choicesLocked) return;
setState(() {
_folder = folder;
- _repository = repository;
- _folderSource = repository != null
+ _repository = project?.repository;
+ _projectName = project?.name;
+ _generatedProject = project?.isGenerated == true
+ ? project
+ : null;
+ _folderSource = _repository != null
? _FolderSource.remote
: folder != null
? _FolderSource.local
@@ -1228,6 +1328,8 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
children: [
if (_availability('codex')?.supportsCodexHome == true)
CodexProfileField(
+ textStyle: boxMonoStyle(),
+ valueChosen: _codexProfileChosen,
notifier: widget.notifier,
machineId: _machineId,
machineIsThisComputer: _machineIsThisComputer,
@@ -1239,7 +1341,10 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
},
onChanged: (profile) {
if (!_choicesLocked) {
- setState(() => _codexProfile = profile);
+ setState(() {
+ _codexProfile = profile;
+ _codexProfileChosen = true;
+ });
}
},
onBusyChanged: (busy) {
@@ -1268,9 +1373,9 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
Widget _taskField({required double minHeight}) => ListenableBuilder(
listenable: _task,
builder: (context, _) {
- final radius = BorderRadius.circular(grid.AppControl.radius);
- final line = MediaQuery.textScalerOf(context).scale(16) * 1.45;
- final padding = ((minHeight - line) / 2).clamp(12.0, double.infinity);
+ final radius = BorderRadius.circular(2);
+ final line = MediaQuery.textScalerOf(context).scale(13) * 1.35;
+ final padding = ((minHeight - line) / 2).clamp(6.0, double.infinity);
final tooLong = _taskTooLong;
final errorBorder = OutlineInputBorder(
borderRadius: radius,
@@ -1289,19 +1394,11 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
maxLines: 6,
keyboardType: TextInputType.multiline,
textInputAction: TextInputAction.newline,
- style: TextStyle(
- fontSize: 16,
- height: 1.45,
- color: grid.AppPalette.textPrimary,
- ),
+ style: boxMonoStyle(),
decoration: InputDecoration(
hintText: 'Tell your agent what to do first.',
// Readable, not faint: the hint says what the field is for.
- hintStyle: TextStyle(
- fontSize: 16,
- height: 1.45,
- color: grid.AppPalette.textSecondary,
- ),
+ hintStyle: boxMonoStyle(color: kBoxFaint),
// One line, so an empty box is exactly a tile tall at any width.
hintMaxLines: 1,
errorText: tooLong
@@ -1363,15 +1460,16 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
label: 'Advanced settings',
button: true,
toggled: _advancedOpen,
- child: IconButton(
+ child: TextButton(
key: const Key('new-agent-advanced'),
onPressed: _choicesLocked ? null : _toggleAdvanced,
- icon: const Icon(LucideIcons.settings, size: 16),
- color: grid.AppPalette.textFaint,
- style: IconButton.styleFrom(
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.textSecondary,
+ textStyle: boxMonoStyle(size: 12),
minimumSize: const Size(28, 28),
padding: const EdgeInsets.all(6),
),
+ child: Text(_advancedOpen ? '[-] options' : '[+] options'),
),
),
if (permissionModesOf(_baseEngine(_engine)) case final modes
@@ -1384,11 +1482,19 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
/// How far the agent may go without asking. The field shows the mode; the menu says what each
/// one does, since "Accept edits" and "Plan first" mean little on their own.
Widget _permissionModeField(List<PermissionMode> modes) => SizedBox(
- width: 156 * math.min(1.4, MediaQuery.textScalerOf(context).scale(13) / 13),
- height: 34,
+ width: 156 * math.min(1.8, MediaQuery.textScalerOf(context).scale(13) / 13),
+ height: math.max(
+ 34,
+ MediaQuery.textScalerOf(context).scale(13) * 1.35 + 14,
+ ),
child: AppSelectField<String>(
key: const Key('new-agent-permission-mode'),
- height: 34,
+ textStyle: boxMonoStyle(),
+ radius: 2,
+ height: math.max(
+ 34,
+ MediaQuery.textScalerOf(context).scale(13) * 1.35 + 14,
+ ),
menuWidth: 340,
value: _permissionModeFor(_baseEngine(_engine)),
options: [
@@ -1453,6 +1559,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
}
Widget _machineOptions(Size tileSize) => AppChoicePicker<String>(
+ terminalStyle: true,
key: const Key('new-agent-machine-field'),
value: _machineId,
moreKey: const Key('new-agent-machine-more'),
@@ -1495,9 +1602,12 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
_machineId = id;
_folder = null;
_repository = null;
+ _projectName = null;
+ _generatedProject = null;
_folderSource = _FolderSource.newProject;
_preparedFolder = null;
_codexProfile = null;
+ _codexProfileChosen = false;
_codexProfilesBusy = true;
_error = null;
});
@@ -1557,7 +1667,7 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {
}
/// The project picker shares Open Agent’s generous reading space.
-const double _dialogWidth = 1080;
+const double _dialogWidth = 812;
/// Blocks inside one card: the command, the facts, the reason.
const double _gapBlock = 12;
diff --git a/desktop/lib/widgets/new_agent_project_picker.dart b/desktop/lib/widgets/new_agent_project_picker.dart
index 8997fb952..535ef721b 100644
--- a/desktop/lib/widgets/new_agent_project_picker.dart
+++ b/desktop/lib/widgets/new_agent_project_picker.dart
@@ -6,6 +6,7 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:path/path.dart' as p;
import '../core/models.dart';
+import '../core/project_folder.dart';
import '../core/repository_clone.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_choice_picker.dart';
@@ -24,20 +25,24 @@ class NewAgentProjectPicker extends StatefulWidget {
required this.onBrowse,
this.terminal = false,
this.initialFolder,
+ this.initialProject,
this.locked = false,
+ this.terminalStyle = false,
});
final AppNotifier notifier;
final String machineId;
final String? initialFolder;
+ final ProjectFolderRequest? initialProject;
final FocusNode focusNode;
final Size tileSize;
final bool locked;
+ final bool terminalStyle;
/// The choice is for a terminal, not an agent: the first tile is the home
/// folder (a shell opens there, nothing is prepared), and there is no Git
/// tile — a terminal does not clone.
final bool terminal;
- final void Function(String? folder, GitHubRepository? repository) onSelected;
+ final void Function(String? folder, ProjectFolderRequest? project) onSelected;
final Future<String?> Function() onBrowse;
@override
@@ -50,14 +55,18 @@ typedef _ProjectChoice = ({
_ProjectSource source,
String? folder,
GitHubRepository? repository,
+ String? name,
});
class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
- late _ProjectSource _source = widget.initialFolder == null
+ late _ProjectSource _source = widget.initialProject?.repository != null
+ ? _ProjectSource.git
+ : widget.initialFolder == null
? _ProjectSource.newProject
: _ProjectSource.local;
late String? _folder = widget.initialFolder;
- GitHubRepository? _repository;
+ late GitHubRepository? _repository = widget.initialProject?.repository;
+ late String? _name = widget.initialProject?.name;
bool _chosen = false, _browsing = false;
final _localFocus = FocusNode();
@@ -90,7 +99,13 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
Future<void> _restore() async {
final history = widget.notifier.projectHistory;
await history.load();
- if (!mounted || widget.locked || _chosen || widget.initialFolder != null) {
+ if (!mounted || widget.locked || _chosen) {
+ return;
+ }
+ if (widget.initialFolder != null || widget.initialProject != null) {
+ // A handed-off choice is just as explicit as one made in these tiles.
+ // Keep it in this dialog's per-machine history before switching away.
+ _rememberChoice();
return;
}
// The dialog owns this bucket. Choices survive machine switches, never a
@@ -101,9 +116,10 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
setState(() {
_folder = choice.folder;
_repository = choice.repository;
+ _name = choice.name;
_source = choice.source;
});
- widget.onSelected(choice.folder, choice.repository);
+ widget.onSelected(choice.folder, _preparation);
} else {
setState(() {});
}
@@ -111,10 +127,18 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
void _rememberChoice() => PageStorage.maybeOf(context)?.writeState(
context,
- (source: _source, folder: _folder, repository: _repository),
+ (source: _source, folder: _folder, repository: _repository, name: _name),
identifier: ('project-choice', widget.machineId),
);
+ ProjectFolderRequest? get _preparation => switch (_source) {
+ _ProjectSource.newProject =>
+ widget.terminal ? null : ProjectFolderRequest.newProject(name: _name),
+ _ProjectSource.git =>
+ _repository == null ? null : ProjectFolderRequest.remote(_repository!),
+ _ => null,
+ };
+
List<SelectOption<String>> get _recent {
final machine = widget.notifier.stateOf(widget.machineId);
final projects = <String, String>{};
@@ -156,7 +180,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
_repository = repository;
});
_rememberChoice();
- widget.onSelected(folder, repository);
+ widget.onSelected(folder, _preparation);
if (repository == null) {
unawaited(
widget.notifier.projectHistory.select(widget.machineId, folder),
@@ -209,13 +233,17 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
children: [
Wrap(
spacing: AppChoiceTile.gap,
- runSpacing: AppChoiceTile.gap,
+ runSpacing: widget.terminalStyle ? 2 : AppChoiceTile.gap,
children: [
AppChoiceTile(
+ terminalStyle: widget.terminalStyle,
key: const Key('new-agent-folder-newProject'),
size: widget.tileSize,
focusNode: widget.focusNode,
label: widget.terminal ? 'Home' : 'New project',
+ detail: widget.terminal || _name == null
+ ? null
+ : projectFolderSlug(_name!),
leading: Icon(
widget.terminal ? LucideIcons.house : LucideIcons.folderPlus,
size: 22,
@@ -226,6 +254,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
: () => _select(_ProjectSource.newProject),
),
AppChoiceTile(
+ terminalStyle: widget.terminalStyle,
key: const Key('new-agent-project-browse'),
size: widget.tileSize,
focusNode: _localFocus,
@@ -239,6 +268,7 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
),
if (!widget.terminal)
AppChoiceTile(
+ terminalStyle: widget.terminalStyle,
key: const Key('new-agent-project-git'),
size: widget.tileSize,
label: 'Git',
@@ -252,6 +282,10 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
inMutuallyExclusiveGroup: true,
child: AppSelectField<String>(
key: const Key('new-agent-project-recent'),
+ textStyle: widget.terminalStyle
+ ? DefaultTextStyle.of(context).style
+ : null,
+ radius: widget.terminalStyle ? 2 : null,
value: selectedRecent ? _folder ?? '' : '',
options: recent,
width: widget.tileSize.width,
@@ -262,20 +296,27 @@ class _NewAgentProjectPickerState extends State<NewAgentProjectPicker> {
menuWidth: widget.tileSize.width * 2,
menuAlignedToEnd: true,
height: widget.tileSize.height,
- padding: AppChoiceTile.padding,
+ padding: widget.terminalStyle
+ ? AppChoiceTile.terminalPadding
+ : AppChoiceTile.padding,
selected: selectedRecent,
fillColor: selectedRecent
? grid.AppPalette.swarmAccent.withValues(alpha: .16)
+ : widget.terminalStyle
+ ? Colors.transparent
: grid.AppSurface.recess,
emptyLabel: 'No recent projects',
onChanged: (path) =>
_select(_ProjectSource.recent, folder: path),
trigger: AppChoiceTileContent(
+ terminalStyle: widget.terminalStyle,
label: 'Recent',
detail: selectedRecent && _folder != null
? p.basename(_folder!)
: null,
- leading: const Icon(LucideIcons.history, size: 22),
+ leading: widget.terminalStyle
+ ? Text(selectedRecent ? '>' : ' ')
+ : const Icon(LucideIcons.history, size: 22),
trailing: const Icon(Icons.keyboard_arrow_down, size: 18),
),
),
diff --git a/desktop/lib/widgets/new_harness_box.dart b/desktop/lib/widgets/new_harness_box.dart
new file mode 100644
index 000000000..e51b41148
--- /dev/null
+++ b/desktop/lib/widgets/new_harness_box.dart
@@ -0,0 +1,1575 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../core/permission_modes.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../state/new_harness.dart';
+import 'box_chrome.dart';
+import 'pane_menu.dart';
+import 'terminal_prompt.dart';
+
+enum _LaunchChoice { agent, machine, project, task, create }
+
+/// A launch menu and focused completion prompts with shared arrow navigation.
+/// Create is selected initially; arrows and Enter edit a displayed default.
+class NewHarnessBox extends StatefulWidget {
+ const NewHarnessBox({
+ super.key,
+ required this.controller,
+ required this.onClose,
+ required this.onCreated,
+ required this.onNeedsForm,
+ this.onBrowse,
+ this.onStore,
+ this.onLinkProfile,
+ this.docked = false,
+ });
+ final NewHarnessController controller;
+ final bool docked;
+
+ /// Open the system's folder chooser (or another machine's browser) and hand
+ /// the folder to the controller. Null hides nothing: the row then does nothing.
+ final VoidCallback? onBrowse;
+ final VoidCallback? onStore;
+ final VoidCallback? onLinkProfile;
+ final VoidCallback onClose;
+ final VoidCallback onCreated;
+
+ /// Open the full creation form for advanced options.
+ final VoidCallback onNeedsForm;
+
+ @override
+ State<NewHarnessBox> createState() => _NewHarnessBoxState();
+}
+
+class _NewHarnessBoxState extends State<NewHarnessBox> {
+ final _text = TextEditingController();
+ final _focus = FocusNode(debugLabel: 'New harness argument');
+ final _launchFocus = FocusNode(debugLabel: 'New harness launch');
+ bool get _launching => box.field == NewHarnessField.launch;
+ bool get _projectMenu => box.field == NewHarnessField.projectMenu;
+ bool get _agentPicker => box.field == NewHarnessField.agent;
+ bool get _machinePicker => box.field == NewHarnessField.machine;
+ bool get _profilePicker => box.field == NewHarnessField.profile;
+ bool get _reverseResults =>
+ widget.docked || _projectMenu || _agentPicker || _profilePicker;
+ int get _pinnedCount => _profilePicker && box.supportsProfiles ? 2 : 0;
+ bool get _hasInput => !_launching;
+ _LaunchChoice _launchChoice = _LaunchChoice.create;
+ String get _agentSummary => box.detectingAgent
+ ? 'Detecting installed agents…'
+ : [
+ box.agentLabel,
+ if (box.hasModes && box.mode != kDefaultPermissionMode) box.modeLabel,
+ if (box.profileLabel case final profile?) 'profile $profile',
+ ].join(' · ');
+ List<_LaunchChoice> get _launchChoices => [
+ _LaunchChoice.agent,
+ _LaunchChoice.machine,
+ _LaunchChoice.project,
+ _LaunchChoice.task,
+ _LaunchChoice.create,
+ ];
+ String get _launchCreateLabel => box.checking
+ ? 'Check status'
+ : box.needsProject
+ ? 'Choose project'
+ : box.createLabel;
+
+ void _selectLaunchChoice(_LaunchChoice choice) {
+ if (box.locked || _launchChoice == choice) return;
+ setState(() => _launchChoice = choice);
+ _announce();
+ }
+
+ void _activateLaunchChoice(_LaunchChoice choice) {
+ if (box.busy || (box.locked && choice != _LaunchChoice.create)) return;
+ switch (choice) {
+ case _LaunchChoice.agent:
+ box.focusField(NewHarnessField.agent);
+ case _LaunchChoice.machine:
+ box.focusField(NewHarnessField.machine);
+ case _LaunchChoice.project:
+ box.focusField(NewHarnessField.projectMenu);
+ case _LaunchChoice.task:
+ _editTask();
+ case _LaunchChoice.create:
+ unawaited(_finish(box.create()));
+ }
+ _requestFocus();
+ }
+
+ void _requestFocus() => (_hasInput ? _focus : _launchFocus).requestFocus();
+ final _scroll = ScrollController();
+ final _announcer = BoxAnnouncer();
+ final _pointer = BoxPointerGate();
+ double _rowHeight = 38;
+ double _compactRowHeight = 28;
+ int _revealed = -1;
+ String? _revealedQuery;
+ NewHarnessField? _announcedField;
+ bool _announcementScheduled = false;
+ bool _altHeld = false;
+ String? _hoveredAgent;
+ VoidCallback? _closeSettingsMenu;
+ NewHarnessController get box => widget.controller;
+
+ @override
+ void initState() {
+ super.initState();
+ // A task carried in — a draft kept from the last Escape, or what was typed
+ // in the search — is in the field from the first frame, caret at its end.
+ _text.value = TextEditingValue(
+ text: box.query,
+ selection: TextSelection.collapsed(offset: box.query.length),
+ );
+ box.addListener(_changed);
+ HardwareKeyboard.instance.addHandler(_watchAlt);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ _requestFocus();
+ _changed();
+ });
+ }
+
+ @override
+ void dispose() {
+ _closeSettingsMenu?.call();
+ HardwareKeyboard.instance.removeHandler(_watchAlt);
+ box.removeListener(_changed);
+ _text.dispose();
+ _focus.dispose();
+ _launchFocus.dispose();
+ _scroll.dispose();
+ super.dispose();
+ }
+
+ /// ⌥ held shows the digit each of the first nine rows answers to, the way the
+ /// tab strip shows ⌘1–⌘9 while ⌘ is held. Never consumes the key.
+ bool _watchAlt(KeyEvent event) {
+ // Only where a digit picks a row: on the task ⌥ is word motion and
+ // composed characters, and a panel rebuild for each would be for nothing.
+ final held =
+ HardwareKeyboard.instance.isAltPressed &&
+ box.field != NewHarnessField.task &&
+ box.options.isNotEmpty;
+ if (held != _altHeld && mounted) setState(() => _altHeld = held);
+ return false;
+ }
+
+ /// The keys this box prints, resolved when the keymap changes — not six
+ /// linear scans of the picker bindings on every keystroke.
+ Map<String, String> _pickerKeys = const {}, _projectKeys = const {};
+ Map<String, String> get _keys => _projectMenu ? _projectKeys : _pickerKeys;
+ static const _printed = {
+ 'picker.previous': '↑',
+ 'picker.next': '↓',
+ 'picker.accept': '↵',
+ 'picker.add_here': '⌘↵',
+ 'picker.complete': '⇥',
+ 'picker.complete_back': '⇧⇥',
+ 'picker.more_options': '⌘.',
+ 'picker.cancel': 'esc',
+ 'creation.project_browse': 'ctrl-o',
+ };
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ Map<String, String> hints(KeymapContext scope) => {
+ for (final entry in _printed.entries)
+ entry.key: terminalPromptHint(
+ context,
+ entry.key,
+ entry.value,
+ contextKind: scope,
+ ),
+ };
+ _pickerKeys = hints(KeymapContext.picker);
+ _projectKeys = hints(KeymapContext.project);
+ }
+
+ /// Only rebuild when the arguments, results, or visible status change.
+ Object? _shown;
+ NewHarnessField? _focusedField;
+ Object _visible() => (
+ box.field,
+ box.options,
+ box.cursor,
+ box.busy,
+ box.detectingAgent,
+ box.checking,
+ box.listing,
+ box.status,
+ box.error,
+ box.task,
+ box.query.trim().isEmpty,
+ box.matchCount,
+ box.total,
+ (
+ box.agentLabel,
+ box.machineLabel,
+ box.projectLocation,
+ box.modeLabel,
+ box.profileLabel,
+ ),
+ );
+
+ void _changed() {
+ if (!mounted) return;
+ final editingName =
+ _focusedField != box.field && box.field == NewHarnessField.projectName;
+ if (_text.text != box.query) {
+ _text.value = TextEditingValue(
+ text: box.query,
+ selection: editingName
+ ? TextSelection(baseOffset: 0, extentOffset: box.query.length)
+ : TextSelection.collapsed(offset: box.query.length),
+ );
+ }
+ if (_focusedField != box.field) {
+ _focusedField = box.field;
+ if (_launching) _launchChoice = _LaunchChoice.create;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _requestFocus();
+ });
+ }
+ if (box.locked || !_launchChoices.contains(_launchChoice)) {
+ _launchChoice = _LaunchChoice.create;
+ }
+ final visible = _visible();
+ if (visible != _shown) {
+ _shown = visible;
+ setState(() {});
+ _announce();
+ }
+ }
+
+ void _announce() {
+ if (!_announcementScheduled) {
+ _announcementScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _announcementScheduled = false;
+ if (!mounted) return;
+ final fieldChanged = _announcedField != box.field;
+ if (_revealed != box.cursor ||
+ fieldChanged ||
+ _revealedQuery != box.query) {
+ _reveal();
+ }
+ _revealed = box.cursor;
+ _revealedQuery = box.query;
+ _announcedField = box.field;
+ final row = box.selected;
+ // macOS does not announce liveRegion changes. Send the visible
+ // message explicitly, ahead of the row, without moving the list.
+ // Read at frame end so one update announces only its final state.
+ _announcer.row(
+ context,
+ box.error ??
+ box.status ??
+ (_launching
+ ? _launchChoice == _LaunchChoice.create
+ ? _summaryText()
+ : '${_launchChoice.name}. Enter to edit.'
+ : box.field == NewHarnessField.task
+ // No row to read here: read what Return will do instead.
+ ? _summaryText()
+ : row == null
+ ? null
+ : '${fieldChanged ? '${_fieldName(box.field)}. ' : ''}'
+ '${row.title}${row.detail.isEmpty ? '' : ', ${row.detail}'}'
+ '${box.isCurrent(row) ? ', current' : ''}'
+ '${row.enabled ? '' : ', unavailable'}'),
+ );
+ });
+ }
+ }
+
+ void _reveal() {
+ if (!_scroll.hasClients || box.options.isEmpty) return;
+ final start = _projectMenu ? 3 : _pinnedCount;
+ if (box.cursor < start) return;
+ final first = box.cursor;
+ final top = box.options
+ .skip(start)
+ .take(first - start)
+ .fold(0.0, (height, row) => height + _heightOf(row));
+ final height = box.options
+ .skip(first)
+ .take(box.cursor - first + 1)
+ .fold(0.0, (height, row) => height + _heightOf(row));
+ final position = _scroll.position;
+ final target =
+ (top < position.pixels
+ ? top
+ : top + height > position.pixels + position.viewportDimension
+ ? top + height - position.viewportDimension
+ : position.pixels)
+ .clamp(0.0, position.maxScrollExtent);
+ if (target != position.pixels) _scroll.jumpTo(target);
+ }
+
+ double _heightOf(NewHarnessOption row) => _projectMenu
+ ? _compactRowHeight
+ : (box.field == NewHarnessField.project ||
+ box.field == NewHarnessField.projectName) &&
+ row.detail.isEmpty
+ ? _compactRowHeight
+ : _rowHeight;
+
+ static String _fieldName(NewHarnessField field) => switch (field) {
+ NewHarnessField.launch => 'New Harness',
+ NewHarnessField.projectMenu => 'Project',
+ NewHarnessField.projectName => 'Project name',
+ NewHarnessField.projectRepository => 'GitHub repository',
+ NewHarnessField.task => 'Task',
+ NewHarnessField.mode => 'Permissions',
+ NewHarnessField.profile => 'Codex profile',
+ NewHarnessField.agent => 'Agent',
+ NewHarnessField.machine => 'Machine',
+ NewHarnessField.project => 'Project',
+ };
+
+ bool get _composing =>
+ _hasInput &&
+ _text.value.composing.isValid &&
+ !_text.value.composing.isCollapsed;
+
+ Future<void> _finish(Future<NewHarnessOutcome> work) async {
+ switch (await work) {
+ case NewHarnessOutcome.created:
+ widget.onCreated();
+ case NewHarnessOutcome.failed:
+ if (mounted) _requestFocus();
+ }
+ }
+
+ void _moreOptions() {
+ if (!box.locked && !_composing) widget.onNeedsForm();
+ }
+
+ Future<void> _agentSettings(
+ BuildContext anchor,
+ NewHarnessOption agent,
+ ) async {
+ final engine = agent.engine;
+ if (engine == null || box.locked) return;
+ final settings = box.agentSettingsFor(engine);
+ if (settings.isEmpty) return;
+ _closeSettingsMenu?.call();
+ final machine = box.machineId;
+ final overlay = Overlay.of(anchor).context.findRenderObject()! as RenderBox;
+ final button = anchor.findRenderObject()! as RenderBox;
+ final position = button.localToGlobal(Offset.zero, ancestor: overlay);
+ final setting = await showPaneMenu<String>(
+ context: context,
+ position: RelativeRect.fromRect(
+ position & button.size,
+ Offset.zero & overlay.size,
+ ),
+ minWidth: 270,
+ maxWidth: 350,
+ onOpen: (_, close) => _closeSettingsMenu = close,
+ onClose: () => _closeSettingsMenu = null,
+ children: (close) => [
+ paneMenuHeader(agent.title),
+ for (final setting in settings)
+ paneMenuItem(
+ onTap: () => close(setting.id),
+ child: PaneMenuRow(
+ key: ValueKey(setting.id),
+ selected: false,
+ title: setting.title,
+ detail: setting.detail,
+ ),
+ ),
+ ],
+ );
+ if (!mounted || machine != box.machineId || setting == null) return;
+ box.openAgentSetting(engine, setting);
+ _requestFocus();
+ }
+
+ void _editTask() {
+ if (box.locked) return;
+ if (box.takesTask) {
+ box.focusField(NewHarnessField.task);
+ } else {
+ box.warn(
+ 'Starting ${box.agentLabel} with a task is not supported yet. Enter it in the agent after launch.',
+ );
+ }
+ }
+
+ void _projectAction(String id) {
+ if (box.locked) return;
+ box.accept(box.options.firstWhere((row) => row.id == id));
+ _requestFocus();
+ }
+
+ void _pickRecent(int number) {
+ final recents = box.options.where((row) => !row.synthetic).toList();
+ if (box.locked || number > recents.length) return;
+ box.accept(recents[number - 1]);
+ _requestFocus();
+ }
+
+ void _enter() {
+ if (_composing || box.busy) return;
+ if (_launching && !box.locked) {
+ _activateLaunchChoice(_launchChoice);
+ return;
+ }
+ if (box.selected?.id == NewHarnessController.linkProfileId && !box.locked) {
+ widget.onLinkProfile?.call();
+ return;
+ }
+ if (box.selected?.id == NewHarnessController.storeId && !box.locked) {
+ widget.onStore?.call();
+ return;
+ }
+ if (box.returnCreates) {
+ unawaited(_finish(box.create()));
+ } else if (box.selected?.id == NewHarnessController.browseId) {
+ widget.onBrowse?.call();
+ } else {
+ box.accept();
+ }
+ _requestFocus();
+ }
+
+ void _createNow() {
+ if (_composing || box.busy) return;
+ if (box.selected?.id == NewHarnessController.linkProfileId && !box.locked) {
+ widget.onLinkProfile?.call();
+ return;
+ }
+ if (box.selected?.id == NewHarnessController.storeId && !box.locked) {
+ widget.onStore?.call();
+ return;
+ }
+ if (box.selected?.id == NewHarnessController.browseId && !box.locked) {
+ widget.onBrowse?.call();
+ return;
+ }
+ unawaited(_finish(box.createNow()));
+ }
+
+ /// Closing mid-create would throw away the attempt that exists to recover a
+ /// lost reply, and leave a harness nobody is watching arrive.
+ ///
+ /// The same goes, once, for a create whose reply was lost: the first Escape
+ /// says what is at stake, the second means it.
+ void _cancel() {
+ if (_composing) return;
+ if (box.back()) return;
+ if (box.requestDismiss()) widget.onClose();
+ }
+
+ /// Down, Up and the page keys: the highlight in a list, the caret in the
+ /// task. The keymap consumes a key it matches whether or not anything
+ /// handles it, so on the task — six lines with nothing to highlight — the
+ /// arrows did nothing at all. There they are handed to the text field.
+ void _vertical(int direction, {bool page = false}) {
+ if (_launching) {
+ final choices = _launchChoices;
+ _selectLaunchChoice(
+ page
+ ? (direction < 0 ? choices.first : choices.last)
+ : choices[(choices.indexOf(_launchChoice) + direction) %
+ choices.length],
+ );
+ return;
+ }
+ if (box.field != NewHarnessField.task) {
+ if (_reverseResults) {
+ box.page(-direction, page ? _rowsPerPage : 1);
+ } else {
+ page ? box.page(direction, _rowsPerPage) : box.move(direction);
+ }
+ return;
+ }
+ final context = _focus.context;
+ if (context == null) return;
+ Actions.maybeInvoke(
+ context,
+ page
+ ? ExtendSelectionVerticallyToAdjacentPageIntent(
+ forward: direction > 0,
+ collapseSelection: true,
+ )
+ : ExtendSelectionVerticallyToAdjacentLineIntent(
+ forward: direction > 0,
+ collapseSelection: true,
+ ),
+ );
+ }
+
+ void _tab(int step) {
+ if (_composing || box.busy) return;
+ box.complete(step);
+ _requestFocus();
+ }
+
+ int get _rowsPerPage {
+ if (!_scroll.hasClients) return 8;
+ final height = _projectMenu ? _compactRowHeight : _rowHeight;
+ return (_scroll.position.viewportDimension / height).floor().clamp(1, 50);
+ }
+
+ void _pick(int index) {
+ if (index >= box.options.length || box.locked) return;
+ if (box.options[index].id == NewHarnessController.linkProfileId) {
+ widget.onLinkProfile?.call();
+ return;
+ }
+ if (box.options[index].id == NewHarnessController.browseId) {
+ widget.onBrowse?.call();
+ return;
+ }
+ if (box.options[index].id == NewHarnessController.storeId) {
+ widget.onStore?.call();
+ return;
+ }
+ box.accept(box.options[index]);
+ _requestFocus();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final scale = MediaQuery.textScalerOf(context);
+ _compactRowHeight = boxRowHeight(scale);
+ _rowHeight =
+ (box.field == NewHarnessField.project ||
+ box.field == NewHarnessField.projectName ||
+ box.field == NewHarnessField.projectRepository ||
+ _projectMenu)
+ ? scale.scale(13) * 1.35 + scale.scale(12) * 1.35 + 10
+ : boxRowHeight(scale);
+ final input = Semantics(
+ label: '${_fieldName(box.field)}. ${box.hint}',
+ child: ReadlineKeys(
+ enabled: !box.locked,
+ controller: _text,
+ onChanged: box.setQuery,
+ child: _input(),
+ ),
+ );
+ final keys = <String, VoidCallback>{
+ 'picker.accept': _enter,
+ 'picker.add_here': _createNow,
+ 'picker.next': () => _vertical(1),
+ 'picker.previous': () => _vertical(-1),
+ // No preview here to page, so the page keys page the list.
+ 'picker.preview_page_down': () => _vertical(1, page: true),
+ 'picker.preview_page_up': () => _vertical(-1, page: true),
+ 'picker.cancel': _cancel,
+ 'picker.complete': () => _tab(1),
+ 'picker.complete_back': () => _tab(-1),
+ 'picker.more_options': _moreOptions,
+ if (_launching && !box.locked) ...{
+ 'creation.agent': () => box.focusField(NewHarnessField.agent),
+ 'creation.project': () => box.focusField(NewHarnessField.projectMenu),
+ 'creation.task': _editTask,
+ 'creation.options': _moreOptions,
+ },
+ if (_launching && !box.locked)
+ 'creation.project_machine': () =>
+ box.focusField(NewHarnessField.machine),
+ if (_projectMenu && !box.locked) ...{
+ 'creation.project_new': () =>
+ _projectAction(NewHarnessController.newProjectId),
+ 'creation.project_existing': () =>
+ _projectAction(NewHarnessController.existingProjectId),
+ 'creation.project_repository': () =>
+ _projectAction(NewHarnessController.repositoryId),
+ for (var recent = 1; recent <= 9; recent++)
+ 'creation.project_recent_$recent': () => _pickRecent(recent),
+ },
+ if (box.field == NewHarnessField.project && !box.locked)
+ 'creation.project_browse': () => widget.onBrowse?.call(),
+ // Only where there are rows: on the task ⌥-digits are characters, and a
+ // picker key nothing handles now falls through to the field.
+ if (box.field != NewHarnessField.task && !_projectMenu)
+ for (var row = 1; row <= 9; row++)
+ 'picker.pick_$row': () => _pick(row - 1),
+ };
+ final panel = Semantics(
+ scopesRoute: true,
+ namesRoute: true,
+ explicitChildNodes: true,
+ label: box.checking
+ ? 'Check agent creation'
+ : box.placement == null
+ ? 'New Harness'
+ : box.createLabel,
+ child: TerminalBox(
+ key: const ValueKey('new-harness-box'),
+ docked: widget.docked,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ _line(),
+ if (!_launching &&
+ _reverseResults &&
+ box.field != NewHarnessField.task)
+ Flexible(child: RepaintBoundary(child: _options())),
+ // A long first task scrolls inside its editor after using the
+ // available room; it never pushes the key guide out of the box.
+ if (_hasInput)
+ Flexible(
+ // Field changes move the result list above this editor in a
+ // dock. Keep its text-input connection and focus while it moves.
+ key: const ValueKey('new-harness-editor-slot'),
+ flex: box.field == NewHarnessField.task ? 1 : 0,
+ child: input,
+ ),
+ // The rows churn on every keystroke; the shadow and the clip
+ // around them should not be redrawn for it.
+ if (!_launching &&
+ !_reverseResults &&
+ box.field != NewHarnessField.task)
+ Flexible(child: RepaintBoundary(child: _options())),
+ _footer(context),
+ ],
+ ),
+ ),
+ );
+ final extra = CallbackShortcuts(
+ bindings: {
+ // ⌥↵ is the pane's own chord for "break the line"; it is not a command.
+ const SingleActivator(LogicalKeyboardKey.enter, alt: true): _newline,
+ if (KeymapTheme.of(context) == null) ...{
+ if (box.field == NewHarnessField.project && !box.locked)
+ const SingleActivator(LogicalKeyboardKey.keyO, control: true): () =>
+ widget.onBrowse?.call(),
+ const SingleActivator(LogicalKeyboardKey.tab): () => _tab(1),
+ const SingleActivator(LogicalKeyboardKey.tab, shift: true): () =>
+ _tab(-1),
+ const SingleActivator(LogicalKeyboardKey.period, meta: true):
+ _moreOptions,
+ // Only where there are rows: on the task ⌥-digits are characters.
+ if (box.field != NewHarnessField.task && !_projectMenu)
+ for (var digit = 0; digit < 9; digit++)
+ SingleActivator(_digits[digit], alt: true): () => _pick(digit),
+ const SingleActivator(LogicalKeyboardKey.enter): _enter,
+ const SingleActivator(LogicalKeyboardKey.numpadEnter): _enter,
+ const SingleActivator(LogicalKeyboardKey.enter, meta: true):
+ _createNow,
+ const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
+ _vertical(1),
+ const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
+ _vertical(-1),
+ const SingleActivator(LogicalKeyboardKey.keyN, control: true): () =>
+ _vertical(1),
+ const SingleActivator(LogicalKeyboardKey.keyP, control: true): () =>
+ _vertical(-1),
+ const SingleActivator(LogicalKeyboardKey.pageDown): () =>
+ _vertical(1, page: true),
+ const SingleActivator(LogicalKeyboardKey.pageUp): () =>
+ _vertical(-1, page: true),
+ const SingleActivator(LogicalKeyboardKey.escape): _cancel,
+ const SingleActivator(LogicalKeyboardKey.keyC, control: true): () {
+ if (!_composing) _cancel();
+ },
+ },
+ },
+ child: Focus(focusNode: _launchFocus, child: panel),
+ );
+ if (KeymapTheme.of(context) == null) return extra;
+ return KeymapRegion(
+ contextKind: _projectMenu ? KeymapContext.project : KeymapContext.picker,
+ composing: () => _composing,
+ actions: keys,
+ child: Actions(
+ actions: {
+ DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
+ },
+ child: extra,
+ ),
+ );
+ }
+
+ static const _digits = [
+ LogicalKeyboardKey.digit1,
+ LogicalKeyboardKey.digit2,
+ LogicalKeyboardKey.digit3,
+ LogicalKeyboardKey.digit4,
+ LogicalKeyboardKey.digit5,
+ LogicalKeyboardKey.digit6,
+ LogicalKeyboardKey.digit7,
+ LogicalKeyboardKey.digit8,
+ LogicalKeyboardKey.digit9,
+ ];
+
+ /// One field for every answer. On the task it grows to hold a real message —
+ /// a first message can be two thousand characters, and a single 46px line
+ /// showed forty of them — and ⌥↵ breaks the line, as it does in the panes.
+ Widget _input() {
+ final onTask = box.field == NewHarnessField.task;
+ return TextField(
+ key: const ValueKey('new-harness-input'),
+ controller: _text,
+ focusNode: _focus,
+ onChanged: box.setQuery,
+ readOnly: box.locked,
+ minLines: 1,
+ maxLines: onTask ? 6 : 1,
+ keyboardType: onTask ? TextInputType.multiline : TextInputType.text,
+ textInputAction: TextInputAction.none,
+ style: boxMonoStyle(),
+ cursorColor: grid.AppPalette.swarmAccent,
+ decoration: InputDecoration(
+ hintText: box.hint,
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ hintMaxLines: 1,
+ // This is text on the first input line, not a vertically centered icon.
+ // InputDecorator aligns a prefix to both the hint and editor baseline.
+ floatingLabelBehavior: FloatingLabelBehavior.always,
+ prefix: Text(
+ '${switch (box.field) {
+ NewHarnessField.projectName => 'Name',
+ NewHarnessField.projectRepository => 'Repo',
+ NewHarnessField.project => 'Folder',
+ NewHarnessField.projectMenu => 'Project',
+ NewHarnessField.mode => 'Permissions',
+ _ => _fieldName(box.field),
+ }.padRight(8)} ',
+ style: boxMonoStyle(size: 12, color: grid.AppPalette.swarmAccent),
+ ),
+ suffixIconConstraints: const BoxConstraints(minHeight: 38),
+ suffixIcon: !onTask && box.query.trim().isNotEmpty && box.matchCount > 0
+ ? Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(right: 4),
+ child: Text(
+ '${box.matchCount}/${box.total}',
+ key: const ValueKey('new-harness-count'),
+ style: kBoxFaintStyle.copyWith(
+ fontFeatures: const [FontFeature.tabularFigures()],
+ ),
+ ),
+ ),
+ ],
+ ),
+ )
+ : null,
+ // The box supplies the background; a filled M3 input adds another
+ // horizontal inset that would move this label off the context column.
+ filled: false,
+ hoverColor: Colors.transparent,
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 14,
+ vertical: 10,
+ ),
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ ),
+ );
+ }
+
+ /// ⌥↵ on the task: a new line in the message, not a harness.
+ void _newline() {
+ if (box.field != NewHarnessField.task || box.busy || _composing) return;
+ final value = _text.value;
+ final selection = value.selection.isValid
+ ? value.selection
+ : TextSelection.collapsed(offset: value.text.length);
+ final text = value.text.replaceRange(selection.start, selection.end, '\n');
+ _text.value = TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: selection.start + 1),
+ );
+ box.setQuery(text);
+ }
+
+ /// A compact command context, with names for every editable default.
+ Widget _line() => _projectMenu
+ ? Padding(
+ padding: const EdgeInsets.fromLTRB(14, 8, 14, 4),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Projects on ${box.machineLabel}',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ TextButton(
+ key: const ValueKey('new-harness-change-machine'),
+ onPressed: box.locked
+ ? null
+ : () => box.focusField(NewHarnessField.machine),
+ child: Text(
+ 'Change Machine',
+ style: boxMonoStyle(
+ size: 12,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ ),
+ ),
+ ],
+ ),
+ )
+ : Padding(
+ padding: const EdgeInsets.fromLTRB(6, 8, 6, 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8),
+ child: Text(
+ box.checking
+ ? 'pending harness'
+ : _agentPicker
+ ? 'Choose an agent'
+ : _machinePicker
+ ? 'Choose a machine'
+ : _profilePicker
+ ? 'Codex profile on ${box.machineLabel}'
+ : box.field == NewHarnessField.mode
+ ? 'Permissions for ${box.agentSettingsLabel}'
+ : 'New Harness${box.placement == null ? '' : ' / ${box.placement!.title}'}',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (!_agentPicker && !_machinePicker) ...[
+ const SizedBox(height: 8),
+ _segment(
+ NewHarnessField.agent,
+ _launching
+ ? _agentSummary
+ : box.field == NewHarnessField.mode || _profilePicker
+ ? box.agentSettingsLabel
+ : box.agentLabel,
+ ),
+ _segment(NewHarnessField.machine, box.machineLabel),
+ _segment(NewHarnessField.project, switch (box.field) {
+ NewHarnessField.project => 'Open Folder',
+ NewHarnessField.projectName => 'New Project',
+ NewHarnessField.projectRepository => 'GitHub Repository',
+ _ => box.needsProject ? 'Choose a project' : box.projectLabel,
+ }),
+ ],
+ if (_launching)
+ _default(
+ 'task',
+ box.task.trim().isEmpty
+ ? box.taskAvailability
+ : box.task.trim().replaceAll(RegExp(r'\s+'), ' '),
+ muted: !box.takesTask,
+ onTap: _editTask,
+ ),
+ if (_launching) ...[
+ const SizedBox(height: 8),
+ _default(
+ 'create',
+ _launchCreateLabel,
+ action: true,
+ onTap: () => _activateLaunchChoice(_LaunchChoice.create),
+ ),
+ ],
+ ],
+ ),
+ );
+
+ Widget _segment(NewHarnessField field, String label) => _default(
+ field.name,
+ label,
+ active:
+ box.field == field ||
+ (field == NewHarnessField.project &&
+ (_projectMenu ||
+ box.field == NewHarnessField.projectName ||
+ box.field == NewHarnessField.projectRepository)),
+ risky: _launching && field == NewHarnessField.agent && box.riskyMode,
+ onTap: () {
+ box.focusField(
+ field == NewHarnessField.project ? NewHarnessField.projectMenu : field,
+ );
+ _requestFocus();
+ },
+ );
+
+ Widget _default(
+ String name,
+ String label, {
+ required VoidCallback onTap,
+ bool active = false,
+ bool risky = false,
+ bool muted = false,
+ bool action = false,
+ }) {
+ final choice = _launching
+ ? _LaunchChoice.values.where((item) => item.name == name).firstOrNull
+ : null;
+ final highlighted = choice != null && choice == _launchChoice;
+ final disabled = name == 'create'
+ ? box.busy || box.detectingAgent
+ : box.locked;
+ final fieldLabel = '${name[0].toUpperCase()}${name.substring(1)}';
+ return MouseRegion(
+ onHover: (event) {
+ if (choice != null && _pointer.moved(event)) {
+ _selectLaunchChoice(choice);
+ }
+ },
+ child: Semantics(
+ button: true,
+ enabled: !disabled,
+ selected: highlighted || active,
+ label: action ? label : '$fieldLabel, $label',
+ excludeSemantics: true,
+ child: BoxRowHighlight(
+ terminal: true,
+ highlighted: highlighted,
+ accent: grid.AppPalette.swarmAccent,
+ child: Tooltip(
+ message: label,
+ child: InkWell(
+ key: ValueKey('new-harness-field-$name'),
+ onTap: disabled ? null : onTap,
+ canRequestFocus: false,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ child: Row(
+ children: [
+ if (!action)
+ Text(
+ '${fieldLabel.padRight(8)} ',
+ style: boxMonoStyle(
+ size: 12,
+ color: active
+ ? grid.AppPalette.swarmAccent
+ : kBoxFaint,
+ ),
+ ),
+ Flexible(
+ child: Text(
+ label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ size: 12,
+ color: risky
+ ? grid.AppPalette.warn
+ : muted || disabled
+ ? kBoxFaint
+ : Colors.white,
+ weight: active || action
+ ? FontWeight.w600
+ : FontWeight.w400,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// On the task there is nothing to pick: say, in one sentence, what Return
+ /// will do — every answer on the line read back in words — so the person
+ /// can check it at a glance and never has to trust what they cannot see.
+ String _summaryText() => box.needsProject
+ ? 'Choose a project before starting ${box.agentLabel}.'
+ : 'Return starts ${box.agentLabel} on ${box.machineLabel} in '
+ '${box.projectLabel}'
+ '${box.hasModes ? ', ${box.modeLabel.toLowerCase()}' : ''}'
+ '${box.profileLabel == null ? '' : ', profile ${box.profileLabel}'}'
+ '${box.task.trim().isEmpty ? '' : ', and sends what you typed as its first message'}.';
+
+ Widget _projectChoices() {
+ final recents = box.options.skip(3).toList();
+ Widget row(int index) {
+ final option = box.options[index];
+ final highlighted = box.cursor == index;
+ final folder = option.project?.folder;
+ final title = Text(
+ option.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(color: option.enabled ? Colors.white : kBoxFaint),
+ );
+ return MouseRegion(
+ onHover: (event) {
+ if (_pointer.moved(event) && !highlighted) {
+ box.move(index - box.cursor);
+ }
+ },
+ child: Semantics(
+ button: true,
+ selected: highlighted,
+ label: '${option.title}, ${option.detail}',
+ child: BoxRowHighlight(
+ terminal: true,
+ highlighted: highlighted,
+ accent: grid.AppPalette.swarmAccent,
+ child: Tooltip(
+ message: option.detail,
+ child: InkWell(
+ key: ValueKey(option.id),
+ canRequestFocus: false,
+ onTap: box.locked ? null : () => _pick(index),
+ child: SizedBox(
+ height: _compactRowHeight,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: LayoutBuilder(
+ builder: (context, constraints) => Row(
+ children: [
+ if (folder == null)
+ Expanded(child: title)
+ else
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: constraints.maxWidth * .4,
+ ),
+ child: title,
+ ),
+ if (folder != null) ...[
+ const SizedBox(width: 12),
+ Expanded(
+ child: Text(
+ box.tildePath(folder),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ ],
+ if (box.isCurrent(option))
+ const Padding(
+ padding: EdgeInsets.only(left: 8),
+ child: Icon(
+ LucideIcons.check,
+ size: 13,
+ color: kBoxFaint,
+ ),
+ ),
+ if (highlighted)
+ Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: Text(
+ _keys['picker.accept'] ?? '↵',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(12, 10, 12, 6),
+ child: Text(
+ box.query.trim().isNotEmpty
+ ? recents.isEmpty
+ ? 'No projects match “${box.query.trim()}”'
+ : 'matches · ${recents.length}/${box.total}'
+ : recents.isEmpty
+ ? 'No recent projects'
+ : 'recent · ${recents.length}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ if (recents.isNotEmpty)
+ Flexible(
+ child: SizedBox(
+ height: recents.length.clamp(0, 9) * _compactRowHeight,
+ child: NotificationListener<ScrollMetricsNotification>(
+ onNotification: (_) {
+ // Keep the chosen project visible after resizing or
+ // changing text size, even when its cursor hasn't moved.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _projectMenu) _reveal();
+ });
+ return false;
+ },
+ child: ListView.builder(
+ key: const ValueKey('new-harness-recent-projects'),
+ controller: _scroll,
+ reverse: true,
+ itemCount: recents.length,
+ itemExtent: _compactRowHeight,
+ itemBuilder: (_, index) => row(index + 3),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(height: 8),
+ for (var i = 2; i >= 0; i--) row(i),
+ ],
+ ),
+ );
+ }
+
+ Widget _options() {
+ if (_launching || box.field == NewHarnessField.task) {
+ return const SizedBox.shrink();
+ }
+ if (_projectMenu) return _projectChoices();
+ if (box.field == NewHarnessField.projectRepository && box.options.isEmpty) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ heightFactor: 1,
+ child: Text(
+ box.query.trim().isEmpty
+ ? 'Clone to ${box.machineLabel}:~/harnesses/<repository>'
+ : 'Paste a GitHub repository URL, or try openai/codex',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ );
+ }
+ if (box.field == NewHarnessField.projectName && box.query.trim().isEmpty) {
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ heightFactor: 1,
+ child: Text(
+ "${box.machineLabel}:~/harnesses/<name>",
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ );
+ }
+ if (box.options.isEmpty) {
+ final path = box.field == NewHarnessField.project && box.isPathQuery;
+ return Center(
+ heightFactor: 1,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
+ child: Text(
+ box.listing
+ ? 'Reading the folder…'
+ : _agentPicker
+ ? 'No agents match “${box.query.trim()}”.'
+ : path
+ ? 'No folders here'
+ // Typing a project's name into the agent field is the first
+ // thing a new person does; say where they are and the way out.
+ : 'Nothing matches “${box.query.trim()}” in '
+ '${_fieldName(box.field)}. Escape goes back.',
+ textAlign: TextAlign.center,
+ style: const TextStyle(fontSize: 13, color: kBoxFaint),
+ ),
+ ),
+ );
+ }
+ if (_agentPicker && box.matchCount == 0) {
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
+ child: Text(
+ 'No agents match “${box.query.trim()}”.',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ ),
+ Flexible(child: _optionList()),
+ ],
+ );
+ }
+ if (_pinnedCount == 0) return _optionList();
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(child: _optionList(start: _pinnedCount)),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 4),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var i = _pinnedCount - 1; i >= 0; i--)
+ SizedBox(
+ height: _heightOf(box.options[i]),
+ child: _optionRow(i),
+ ),
+ ],
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _optionList({int start = 0}) {
+ if (start == box.options.length) return const SizedBox.shrink();
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final height = box.options
+ .skip(start)
+ .take(widget.docked ? 6 : 8)
+ .fold(12.0, (height, row) => height + _heightOf(row));
+ return Align(
+ alignment: Alignment.topCenter,
+ heightFactor: 1,
+ child: SizedBox(
+ height: height.clamp(0, constraints.maxHeight),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: ListView.builder(
+ key: const ValueKey('new-harness-options'),
+ controller: _scroll,
+ reverse: _reverseResults,
+ padding: const EdgeInsets.symmetric(horizontal: 6),
+ itemExtentBuilder: (index, _) =>
+ _heightOf(box.options[index + start]),
+ itemCount: box.options.length - start,
+ itemBuilder: (_, index) => _optionRow(index + start),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+ }
+
+ Widget _optionRow(int index) {
+ final accent = grid.AppPalette.swarmAccent;
+ final option = box.options[index];
+ final highlighted = index == box.cursor;
+ final hasSettings =
+ _agentPicker &&
+ option.engine != null &&
+ box.agentSettingsFor(option.engine!).isNotEmpty;
+ final folder = option.project?.folder;
+ final walkable =
+ folder != null &&
+ !option.synthetic &&
+ box.field == NewHarnessField.project &&
+ box.isPathQuery;
+ return MouseRegion(
+ onEnter: hasSettings
+ ? (_) => setState(() => _hoveredAgent = option.id)
+ : null,
+ onExit: hasSettings
+ ? (_) => setState(() {
+ if (_hoveredAgent == option.id) _hoveredAgent = null;
+ })
+ : null,
+ // The pointer moving onto a row, never a row moving under it.
+ onHover: (event) {
+ if (_pointer.moved(event) && box.cursor != index) {
+ box.move(index - box.cursor);
+ }
+ },
+ child: BoxRowHighlight(
+ terminal: true,
+ highlighted: highlighted,
+ accent: accent,
+ child: ListTile(
+ key: ValueKey(option.id),
+ dense: true,
+ visualDensity: VisualDensity.compact,
+ minVerticalPadding: 0,
+ minTileHeight: _heightOf(option),
+ enabled: !box.busy,
+ hoverColor: Colors.transparent,
+ shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+ contentPadding: const EdgeInsets.only(left: 8, right: 6),
+ title:
+ (box.field == NewHarnessField.project ||
+ box.field == NewHarnessField.projectName ||
+ box.field == NewHarnessField.projectRepository ||
+ _projectMenu)
+ ? Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ option.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ color: option.enabled ? Colors.white : kBoxFaint,
+ ),
+ ),
+ if (option.detail.isNotEmpty)
+ Text(
+ option.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ],
+ )
+ : Row(
+ children: [
+ Flexible(
+ flex: 3,
+ child: Text(
+ option.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ color: option.risky
+ ? grid.AppPalette.warn
+ : option.enabled
+ ? Colors.white
+ : Colors.white54,
+ ),
+ ),
+ ),
+ if (option.detail.isNotEmpty) ...[
+ const SizedBox(width: 10),
+ Flexible(
+ flex: 5,
+ child: Text(
+ option.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ size: 12,
+ color: option.risky
+ ? grid.AppPalette.warn
+ : kBoxFaint,
+ ),
+ ),
+ ),
+ ],
+ ],
+ ),
+ trailing: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // The answer the line already gives wears the check, as the
+ // current folder and branch do in an editor's pickers.
+ if (box.isCurrent(option))
+ const Padding(
+ padding: EdgeInsets.only(right: 10),
+ child: Icon(LucideIcons.check, size: 15, color: kBoxFaint),
+ ),
+ if (_altHeld && index < 9)
+ Padding(
+ padding: const EdgeInsets.only(right: 8),
+ child: Text('⌥${index + 1}', style: kBoxFaintStyle),
+ ),
+ if (walkable)
+ // The mouse's Tab: go into the folder rather than take it.
+ IconButton(
+ tooltip: 'Open ${option.title}',
+ visualDensity: VisualDensity.compact,
+ iconSize: 16,
+ color: Colors.white54,
+ icon: const Icon(LucideIcons.chevronRight),
+ onPressed: box.busy
+ ? null
+ : () {
+ box.setQuery('${box.tildePath(folder)}/');
+ _requestFocus();
+ },
+ ),
+ if (highlighted && option.enabled)
+ Text(
+ _keys['picker.accept'] ?? '↵',
+ key: const ValueKey('new-harness-row-action'),
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ if (_agentPicker)
+ SizedBox(
+ width: 28,
+ height: 28,
+ child: hasSettings
+ ? Builder(
+ builder: (anchor) => _AgentSettingsButton(
+ key: ValueKey('new-harness-settings-${option.id}'),
+ label: 'Settings for ${option.title}',
+ visible: _hoveredAgent == option.id,
+ onPressed: box.locked
+ ? null
+ : () => _agentSettings(anchor, option),
+ ),
+ )
+ : null,
+ ),
+ ],
+ ),
+ onTap: () => _pick(index),
+ ),
+ ),
+ );
+ }
+
+ /// Errors retain the available recovery keys. A pending receipt permits a
+ /// status check or dismissal; it cannot edit choices or change forms.
+ Widget _footer(BuildContext context) {
+ String key(String command, String fallback) => _keys[command] ?? fallback;
+ return BoxHintStrip(
+ key: const ValueKey('new-harness-footer'),
+ message:
+ box.error ??
+ (_profilePicker
+ ? box.profileHelp ??
+ (box.linkingProfile ? 'Linking profile…' : null)
+ : null) ??
+ box.status,
+ isError: box.error != null,
+ busy: box.busy || box.linkingProfile,
+ hints: [
+ if (box.field != NewHarnessField.task && !box.checking)
+ BoxHint(
+ '${key('picker.previous', '↑')}/${key('picker.next', '↓')}',
+ 'select',
+ ),
+ BoxHint(
+ key('picker.accept', '↵'),
+ box.checking
+ ? 'check status'
+ : _projectMenu
+ ? switch (box.selected?.id) {
+ NewHarnessController.newProjectId => 'new project',
+ NewHarnessController.existingProjectId => 'open folder',
+ NewHarnessController.repositoryId => 'clone repository',
+ _ => 'use project',
+ }
+ : _launching && _launchChoice != _LaunchChoice.create
+ ? 'edit ${_launchChoice.name}'
+ : _launching && box.needsProject
+ ? 'choose project'
+ : box.returnCreates
+ ? box.createLabel.toLowerCase()
+ : box.selected?.id == NewHarnessController.storeId
+ ? 'open store'
+ : box.selected?.id == NewHarnessController.permissionsId
+ ? 'edit permissions'
+ : box.selected?.id == NewHarnessController.profileId
+ ? 'choose profile'
+ : box.selected?.id == NewHarnessController.linkProfileId
+ ? 'link profile folder'
+ : box.selected?.id == NewHarnessController.refreshProfilesId
+ ? 'refresh profiles'
+ : _profilePicker
+ ? 'use profile'
+ : box.field == NewHarnessField.mode
+ ? 'use permissions'
+ : box.selected?.id == NewHarnessController.browseId
+ ? 'open folder'
+ : box.selected?.id == NewHarnessController.changeMachineId
+ ? 'change machine'
+ : box.selected?.id == NewHarnessController.newProjectId
+ ? 'name project'
+ : box.field == NewHarnessField.projectRepository
+ ? 'use repository'
+ : box.field == NewHarnessField.project ||
+ box.field == NewHarnessField.projectName
+ ? 'use project'
+ : 'choose',
+ onTap: box.detectingAgent && box.returnCreates ? null : _enter,
+ ),
+ if (_launching &&
+ !box.checking &&
+ _launchChoice != _LaunchChoice.create)
+ BoxHint(
+ key('picker.add_here', '⌘↵'),
+ box.createLabel.toLowerCase(),
+ onTap: _createNow,
+ ),
+ if (!box.checking &&
+ !_launching &&
+ !_projectMenu &&
+ box.field != NewHarnessField.task &&
+ box.field != NewHarnessField.projectName &&
+ box.field != NewHarnessField.projectRepository)
+ BoxHint(
+ key('picker.complete', '⇥'),
+ box.isPathQuery ? 'complete path' : 'complete',
+ onTap: () => _tab(1),
+ ),
+ if (!box.checking && box.field == NewHarnessField.project)
+ BoxHint(
+ key('creation.project_browse', 'ctrl-o'),
+ 'browse folders',
+ onTap: widget.onBrowse,
+ ),
+ BoxHint(
+ key('picker.cancel', 'esc'),
+ _launching || box.checking ? 'close' : 'back',
+ onTap: _cancel,
+ ),
+ ],
+ );
+ }
+}
+
+/// Reserve the same hit target even when the icon is quiet, so rows never move.
+class _AgentSettingsButton extends StatefulWidget {
+ const _AgentSettingsButton({
+ super.key,
+ required this.label,
+ required this.visible,
+ required this.onPressed,
+ });
+ final String label;
+ final bool visible;
+ final VoidCallback? onPressed;
+
+ @override
+ State<_AgentSettingsButton> createState() => _AgentSettingsButtonState();
+}
+
+class _AgentSettingsButtonState extends State<_AgentSettingsButton> {
+ bool _focused = false;
+
+ @override
+ Widget build(BuildContext context) => Focus(
+ onFocusChange: (focused) => setState(() => _focused = focused),
+ child: Opacity(
+ opacity: widget.visible || _focused ? 1 : 0,
+ alwaysIncludeSemantics: true,
+ child: IconButton(
+ tooltip: widget.label,
+ onPressed: widget.onPressed,
+ icon: const Icon(LucideIcons.settings, size: 14, color: kBoxFaint),
+ style: IconButton.styleFrom(
+ padding: EdgeInsets.zero,
+ minimumSize: const Size(28, 28),
+ maximumSize: const Size(28, 28),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/new_harness_help.dart b/desktop/lib/widgets/new_harness_help.dart
index 6ce14ee1f..9f30b7a95 100644
--- a/desktop/lib/widgets/new_harness_help.dart
+++ b/desktop/lib/widgets/new_harness_help.dart
@@ -10,9 +10,10 @@ enum HarnessHelpTopic { agent, machine, project }
/// Optional guidance beside the choices it explains. A separate route keeps
/// the form, its scroll position and its keyboard shortcuts underneath it.
class HarnessHelpLink extends StatefulWidget {
- const HarnessHelpLink({super.key, required this.topic});
+ const HarnessHelpLink({super.key, required this.topic, this.textStyle});
final HarnessHelpTopic topic;
+ final TextStyle? textStyle;
@override
State<HarnessHelpLink> createState() => _HarnessHelpLinkState();
@@ -52,13 +53,15 @@ class _HarnessHelpLinkState extends State<HarnessHelpLink> {
foregroundColor: AppPalette.textSecondary,
minimumSize: const Size(0, 32),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
- textStyle: TextStyle(
- fontFamily: AppFont.sans,
- fontFamilyFallback: AppFont.sansFallback,
- fontSize: 14,
- fontWeight: FontWeight.w400,
- height: 1.4,
- ),
+ textStyle:
+ widget.textStyle ??
+ TextStyle(
+ fontFamily: AppFont.sans,
+ fontFamilyFallback: AppFont.sansFallback,
+ fontSize: 14,
+ fontWeight: FontWeight.w400,
+ height: 1.4,
+ ),
side: BorderSide.none,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
diff --git a/desktop/lib/widgets/open_harness_intent.dart b/desktop/lib/widgets/open_harness_intent.dart
new file mode 100644
index 000000000..e5ee239ae
--- /dev/null
+++ b/desktop/lib/widgets/open_harness_intent.dart
@@ -0,0 +1,8 @@
+import 'package:flutter/widgets.dart';
+
+/// Store and pane menus use the workspace's creation flow with their context.
+class OpenHarnessIntent extends Intent {
+ const OpenHarnessIntent(this.engine, this.machineId, {this.task});
+ final String engine, machineId;
+ final String? task;
+}
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index c73f4be09..5a33d23b4 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -10,7 +10,7 @@ import 'window_chrome.dart';
import '../clipboard/image_bytes.dart';
import '../core/dsh_catalog.dart' show DshEntry;
-import '../core/models.dart' show Agent;
+import '../core/models.dart' show Agent, kUntitledPane;
import '../clipboard/native_clipboard.dart';
import '../shared/theme/app_theme.dart' as grid;
// `hide TerminalKey`: this file's own shortcut-label class, unused here, collides with xterm's
@@ -33,6 +33,7 @@ import 'restart_agent_action.dart';
import 'terminal_panel.dart';
import 'web_pane_panel.dart';
import 'pane_resize_handle.dart';
+import 'box_chrome.dart';
import 'pane_split_edges.dart';
/// Terminal views arranged by the chosen preset. Swarms keep each view under
@@ -568,18 +569,44 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
right: 24,
child: IgnorePointer(
child: Center(
- child: Container(
+ child: TerminalBox(
key: const ValueKey('pane-resize-hint'),
- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
- decoration: BoxDecoration(
- color: AppColors.surface,
- border: Border.all(color: AppColors.borderStrong),
- borderRadius: BorderRadius.circular(10),
- ),
- child: Text(
- 'Arrow keys resize · Shift for larger steps · Tab next divider · Esc done',
- style: TextStyle(fontSize: 13, color: AppColors.textSoft),
- textAlign: TextAlign.center,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ child: Wrap(
+ spacing: 18,
+ runSpacing: 6,
+ children: [
+ Text(
+ 'resize >',
+ style: boxMonoStyle(
+ size: 12,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ ),
+ for (final (key, action) in const [
+ ('arrows', 'resize'),
+ ('shift', 'larger steps'),
+ ('tab', 'next divider'),
+ ('esc', 'done'),
+ ])
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '$key ',
+ style: const TextStyle(color: Colors.white70),
+ ),
+ TextSpan(text: action),
+ ],
+ ),
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ],
+ ),
),
),
),
@@ -1081,7 +1108,7 @@ class _Gap extends StatelessWidget {
/// How round a card's corners are — a pane, and the rail beside it. Public for the same reason
/// [kPaneGap] is: the rail is a card now, and two places typing 10 is how they drift apart.
-const double kPaneRadius = 10;
+const double kPaneRadius = kTerminalCornerRadius;
/// How round a pane's corners are — the shared card radius, so a terminal does not read as a different
/// KIND of surface from the rail beside it.
@@ -1133,28 +1160,39 @@ class _PaneCell extends StatelessWidget {
onPointerDown: (_) => notifier.focusPane(pane.id),
child: ValueListenableBuilder<PaneDragRef?>(
valueListenable: paneDragging,
- builder: (context, inFlight, child) => PaneSplitEdges(
- enabled:
- swarmMode &&
- visible &&
- agentId != null &&
- (onSplit != null || onNewSplit != null) &&
- notifier.zoomedPaneId == null &&
- notifier.canAddPane &&
- dragging == null &&
- inFlight == null,
- canSplitRight:
- notifier.preparePaneSplit(PaneResizeAxis.x, paneId: pane.id) !=
- null,
- canSplitDown:
- notifier.preparePaneSplit(PaneResizeAxis.y, paneId: pane.id) !=
- null,
- onSplit: onSplit == null ? null : (axis) => onSplit!(pane.id, axis),
- onNewSplit: onNewSplit == null
- ? null
- : (axis) => onNewSplit!(pane.id, axis),
- child: child!,
- ),
+ builder: (context, inFlight, child) =>
+ onSplit == null && onNewSplit == null
+ ? child!
+ : PaneSplitEdges(
+ enabled:
+ swarmMode &&
+ visible &&
+ agentId != null &&
+ (onSplit != null || onNewSplit != null) &&
+ notifier.zoomedPaneId == null &&
+ notifier.canAddPane &&
+ dragging == null &&
+ inFlight == null,
+ canSplitRight:
+ notifier.preparePaneSplit(
+ PaneResizeAxis.x,
+ paneId: pane.id,
+ ) !=
+ null,
+ canSplitDown:
+ notifier.preparePaneSplit(
+ PaneResizeAxis.y,
+ paneId: pane.id,
+ ) !=
+ null,
+ onSplit: onSplit == null
+ ? null
+ : (axis) => onSplit!(pane.id, axis),
+ onNewSplit: onNewSplit == null
+ ? null
+ : (axis) => onNewSplit!(pane.id, axis),
+ child: child!,
+ ),
child: Container(
decoration: BoxDecoration(
// UNCHANGED, and deliberately: the terminal renders its own background
@@ -1318,7 +1356,7 @@ class _PaneContent extends StatelessWidget {
final agent = machine?.agents
.where((agent) => agent.id == wantedAgentId)
.firstOrNull;
- final agentName = agent?.name;
+ final agentName = agent?.displayName;
final needsLink =
machine != null &&
machine.isRemote &&
@@ -1351,7 +1389,9 @@ class _PaneContent extends StatelessWidget {
notice = (
label: 'Unavailable',
icon: Icons.cloud_off,
- detail: 'Waiting for this machine. Retained output is read only.',
+ detail: notifier.machineInventoryLoaded
+ ? 'This machine isn’t available. Retained output is read only.'
+ : 'Waiting for this machine. Retained output is read only.',
);
} else if (needsLink) {
notice = (
@@ -1422,7 +1462,7 @@ class _PaneContent extends StatelessWidget {
notifier,
pane.machineId,
agent.id,
- agent.name,
+ agent.displayName,
engine: agent.engine,
),
// The same confirmation the rail's row menu opens. Only for an
@@ -1435,7 +1475,7 @@ class _PaneContent extends StatelessWidget {
notifier,
pane.machineId,
agent.id,
- agent.name,
+ agent.displayName,
engine: agent.engine,
),
zoomed: notifier.zoomedPaneId == pane.id,
@@ -1459,24 +1499,27 @@ class _PaneContent extends StatelessWidget {
// A never-attached view has no output to preserve: keep its setup guidance.
if (machine == null) {
- // "Waiting" is only honest while there is still something to wait FOR. When the machine list
- // itself could not be read, this machine is not slow — it is unknown, and a spinner that never
- // ends is the wrong answer. Keyed off `machineListError`, not `lastError`: that slot is shared
- // with agent-launch failures and is cleared by `dismissError`.
+ // Waiting ends once the inventory has answered, even when it has no row
+ // for this saved pane. Keep Retry mounted during refresh so keyboard focus
+ // survives. Repeated activation joins the same retry in AppNotifier.
final listFailed = notifier.machineListError != null;
final retrying = notifier.machinesRefreshing;
+ final waiting = !listFailed && !notifier.machineInventoryLoaded;
+ final stale = notifier.machinesAreStale;
return _PaneStatus(
- title: wantedAgentId ?? pane.machineId,
- icon: listFailed ? Icons.cloud_off : Icons.hourglass_empty,
+ title: wantedAgentId == null ? 'Machine' : kUntitledPane,
+ icon: listFailed || stale ? Icons.cloud_off : Icons.link_off,
message: listFailed
- ? 'Could not reach the Harness backend, so this machine is unknown right now.'
- : 'Waiting for this machine to answer…',
+ ? 'Could not load machines. Retry to reconnect.'
+ : waiting
+ ? 'Waiting for this machine to answer…'
+ : stale
+ ? 'Could not confirm this machine’s status. Retry to reconnect.'
+ : 'This machine isn’t available. Check that it’s still linked to your account.',
onClose: single && !swarmMode ? null : close,
- busy: !listFailed || retrying,
- // The automatic recovery is already retrying in the background; this is for someone who does not
- // want to wait for the next tick. `retryMachines` coalesces, so pressing it during a run joins it.
- actionLabel: listFailed && !retrying ? 'RETRY' : null,
- onAction: listFailed ? notifier.retryMachines : null,
+ busy: waiting || retrying,
+ actionLabel: waiting ? null : 'Retry',
+ onAction: waiting ? null : notifier.retryMachines,
);
}
if (needsLink) {
@@ -1982,14 +2025,19 @@ class _PaneStatus extends StatelessWidget {
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
- if (busy)
- const SizedBox(
- width: 18,
- height: 18,
- child: CircularProgressIndicator(strokeWidth: 2),
- )
- else
- Icon(icon, size: 26, color: AppColors.mutedStrong),
+ SizedBox(
+ width: 26,
+ height: 26,
+ child: busy
+ ? const Center(
+ child: SizedBox(
+ width: 18,
+ height: 18,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ ),
+ )
+ : Icon(icon, size: 26, color: AppColors.mutedStrong),
+ ),
const SizedBox(height: 10),
Text(
message,
diff --git a/desktop/lib/widgets/pane_header_actions.dart b/desktop/lib/widgets/pane_header_actions.dart
index 745b1fc02..aeaecc9a6 100644
--- a/desktop/lib/widgets/pane_header_actions.dart
+++ b/desktop/lib/widgets/pane_header_actions.dart
@@ -3,6 +3,10 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../theme/app_theme.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/app_keymap.dart';
+import 'box_chrome.dart';
+import 'transient_menus.dart';
/// Direct pane controls, in a stable order even when an action is unavailable.
class PaneHeaderActions extends StatelessWidget {
@@ -23,13 +27,15 @@ class PaneHeaderActions extends StatelessWidget {
this.details,
this.modelPicker,
this.terminal = false,
+ this.compact = false,
});
final bool zoomed, composerVisible;
/// The pane is a shell, not a harness: Restart and Stop say so, because
- /// "Stop Harness" over a terminal reads as a button for something else.
+ /// "Stop Agent" over a terminal reads as a button for something else.
final bool terminal;
+ final bool compact;
final VoidCallback? onShare;
final VoidCallback? onZoom,
onRestart,
@@ -75,7 +81,9 @@ class PaneHeaderActions extends StatelessWidget {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
shape: WidgetStatePropertyAll(
- RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),
+ ),
),
foregroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) {
@@ -103,7 +111,7 @@ class PaneHeaderActions extends StatelessWidget {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
- if (onShare != null) ...[
+ if (!compact && onShare != null) ...[
action('Share harness', Icons.person_add_alt_1_outlined, onShare),
const SizedBox(width: 2),
],
@@ -111,48 +119,80 @@ class PaneHeaderActions extends StatelessWidget {
modelPicker!,
const SizedBox(width: 4),
],
- if (onToggleViewer != null) ...[
- _ViewerToggle(
- key: const ValueKey('pane-viewer-toggle'),
- on: viewerVisible,
- color: viewerColor ?? AppColors.text,
- onPressed: onToggleViewer,
+ if (compact)
+ _CompactPaneActions(
+ items: [
+ (label: 'Zoom Pane', callback: onZoom),
+ if (onToggleViewer != null)
+ (
+ label: viewerVisible ? 'Hide viewer' : 'Show viewer',
+ callback: onToggleViewer,
+ ),
+ if (onToggleComposer != null)
+ (
+ label: composerVisible
+ ? 'Hide message composer'
+ : 'Show message composer',
+ callback: onToggleComposer,
+ ),
+ if (onShare != null)
+ (label: 'Share harness', callback: onShare),
+ (
+ label: terminal ? 'Restart Terminal' : 'Restart Agent',
+ callback: onRestart,
+ ),
+ if (onFork != null) (label: 'Fork Agent', callback: onFork),
+ (label: 'Close Pane', callback: onClose),
+ (
+ label: terminal ? 'Stop Terminal' : 'Stop Agent',
+ callback: onDelete,
+ ),
+ ],
+ )
+ else ...[
+ if (onToggleViewer != null) ...[
+ _ViewerToggle(
+ key: const ValueKey('pane-viewer-toggle'),
+ on: viewerVisible,
+ color: viewerColor ?? AppColors.text,
+ onPressed: onToggleViewer,
+ ),
+ const SizedBox(width: 2),
+ ],
+ if (onToggleComposer != null) ...[
+ action(
+ composerVisible
+ ? 'Hide message composer'
+ : 'Show message composer',
+ LucideIcons.keyboard,
+ onToggleComposer,
+ ),
+ const SizedBox(width: 2),
+ ],
+ action(
+ 'Zoom Pane',
+ zoomed ? LucideIcons.minimize : LucideIcons.maximize,
+ onZoom,
),
const SizedBox(width: 2),
- ],
- if (onToggleComposer != null) ...[
action(
- composerVisible
- ? 'Hide message composer'
- : 'Show message composer',
- LucideIcons.keyboard,
- onToggleComposer,
+ terminal ? 'Restart Terminal' : 'Restart Agent',
+ LucideIcons.refreshCw,
+ onRestart,
),
const SizedBox(width: 2),
- ],
- action(
- 'Zoom Pane',
- zoomed ? LucideIcons.minimize : LucideIcons.maximize,
- onZoom,
- ),
- const SizedBox(width: 2),
- action(
- terminal ? 'Restart Terminal' : 'Restart Harness',
- LucideIcons.refreshCw,
- onRestart,
- ),
- const SizedBox(width: 2),
- if (onFork != null) ...[
- action('Fork Harness', LucideIcons.gitFork, onFork),
+ if (onFork != null) ...[
+ action('Fork Agent', LucideIcons.gitFork, onFork),
+ const SizedBox(width: 2),
+ ],
+ action(
+ terminal ? 'Stop Terminal' : 'Stop Agent',
+ Icons.stop_rounded,
+ onDelete,
+ ),
const SizedBox(width: 2),
+ action('Close Pane', LucideIcons.x, onClose),
],
- action(
- terminal ? 'Stop Terminal' : 'Stop Harness',
- Icons.stop_rounded,
- onDelete,
- ),
- const SizedBox(width: 2),
- action('Close Pane', LucideIcons.x, onClose),
],
),
),
@@ -178,6 +218,99 @@ class PaneHeaderActions extends StatelessWidget {
}
}
+/// A small pane keeps the same actions in a keyboard-navigable menu, leaving
+/// room for its title. Native titlebar actions dismiss this menu too.
+class _CompactPaneActions extends StatefulWidget {
+ const _CompactPaneActions({required this.items});
+ final List<({String label, VoidCallback? callback})> items;
+
+ @override
+ State<_CompactPaneActions> createState() => _CompactPaneActionsState();
+}
+
+class _CompactPaneActionsState extends State<_CompactPaneActions> {
+ final _controller = MenuController();
+ final _triggerFocus = FocusNode(debugLabel: 'Pane actions');
+ final _firstFocus = FocusNode(debugLabel: 'First pane action');
+ VoidCallback? _unregister;
+
+ @override
+ void dispose() {
+ _unregister?.call();
+ _triggerFocus.dispose();
+ _firstFocus.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final enabled = widget.items
+ .where((item) => item.callback != null)
+ .toList();
+ return MenuAnchor(
+ controller: _controller,
+ childFocusNode: _triggerFocus,
+ onOpen: () {
+ _unregister = registerTransientMenu(_controller.close);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _controller.isOpen) _firstFocus.requestFocus();
+ });
+ },
+ onClose: () {
+ _unregister?.call();
+ _unregister = null;
+ },
+ style: grid.AppMenu.style(maxHeight: double.infinity).copyWith(
+ shape: WidgetStatePropertyAll(
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(3),
+ side: BorderSide(color: AppColors.border),
+ ),
+ ),
+ padding: const WidgetStatePropertyAll(EdgeInsets.all(4)),
+ ),
+ menuChildren: [
+ for (var i = 0; i < enabled.length; i++)
+ KeymapRegion(
+ contextKind: KeymapContext.picker,
+ child: MenuItemButton(
+ focusNode: i == 0 ? _firstFocus : null,
+ onPressed: enabled[i].callback,
+ style: ButtonStyle(
+ textStyle: WidgetStatePropertyAll(boxMonoStyle(size: 12)),
+ foregroundColor: WidgetStatePropertyAll(AppColors.text),
+ minimumSize: const WidgetStatePropertyAll(Size(180, 30)),
+ shape: const WidgetStatePropertyAll(RoundedRectangleBorder()),
+ ),
+ child: Text(enabled[i].label),
+ ),
+ ),
+ ],
+ builder: (context, controller, _) => IconButton(
+ focusNode: _triggerFocus,
+ tooltip: 'Pane actions',
+ onPressed: enabled.isEmpty
+ ? null
+ : () {
+ if (controller.isOpen) {
+ controller.close();
+ } else {
+ controller.open();
+ }
+ },
+ icon: const Icon(Icons.more_horiz, size: 16),
+ style: IconButton.styleFrom(
+ foregroundColor: AppColors.mutedStrong,
+ fixedSize: const Size(28, 28),
+ minimumSize: const Size(28, 28),
+ padding: EdgeInsets.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ ),
+ );
+ }
+}
+
/// Only header controls depend on this hover state, so the terminal and title
/// are retained as the pointer crosses the bar. Keyboard focus reveals them too.
class PaneHeaderHover extends StatefulWidget {
@@ -268,7 +401,9 @@ class _ViewerToggle extends StatelessWidget {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
shape: WidgetStatePropertyAll(
- RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
+ RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(kTerminalCornerRadius),
+ ),
),
overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),
),
diff --git a/desktop/lib/widgets/pane_menu.dart b/desktop/lib/widgets/pane_menu.dart
index 90ab60aac..2ec6359d6 100644
--- a/desktop/lib/widgets/pane_menu.dart
+++ b/desktop/lib/widgets/pane_menu.dart
@@ -1,6 +1,12 @@
import 'dart:async';
+import 'dart:math' as math;
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import 'box_chrome.dart';
import '../theme/app_theme.dart';
import 'engine_identity.dart';
@@ -33,6 +39,7 @@ Future<T?> showPaneMenu<T>({
}) {
final overlayState = Overlay.of(context);
final completer = Completer<T?>();
+ final previousFocus = FocusManager.instance.primaryFocus;
late final OverlayEntry entry;
late final void Function() deregister;
var closed = false;
@@ -43,6 +50,7 @@ Future<T?> showPaneMenu<T>({
closed = true;
deregister();
entry.remove();
+ if (previousFocus?.context?.mounted == true) previousFocus!.requestFocus();
onClose?.call();
if (!completer.isCompleted) completer.complete(choice);
}
@@ -62,32 +70,20 @@ Future<T?> showPaneMenu<T>({
child: const SizedBox.expand(),
),
),
- Positioned(
- // Right-aligned to the control, which sits at the right end of a pane header — anchoring
- // the left edge would push a wide menu off-screen.
- right: position.right,
- top: position.top,
- child: ConstrainedBox(
- // Wide enough that a status can sit right-aligned against a model id without the two
- // meeting, and for a full GGUF-style model id beside its node without either cut.
- constraints: BoxConstraints(minWidth: minWidth, maxWidth: maxWidth),
- // ⚠️ IntrinsicWidth, or the menu is ALWAYS [maxWidth] wide. `Positioned` hands down
- // unbounded width, the ConstrainedBox turns that into "up to maxWidth", and a
- // stretching Column takes all of it — so a two-line menu wore the width of the longest
- // model id it could ever hold. This measures the rows and the clamp then applies to
- // what they actually need.
+ CustomSingleChildLayout(
+ delegate: _PaneMenuPosition(position, minWidth, maxWidth),
+ child: _PaneMenuFocus(
+ close: () => close(null),
child: IntrinsicWidth(
- child: Material(
- color: AppColors.surface,
- elevation: 8,
- borderRadius: BorderRadius.circular(8),
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.symmetric(vertical: 6),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: children(close),
+ child: TerminalBox(
+ child: SingleChildScrollView(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: 6),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: children(close),
+ ),
),
),
),
@@ -102,6 +98,100 @@ Future<T?> showPaneMenu<T>({
return completer.future;
}
+/// Position against the actual overlay, including panes beside the left edge
+/// and short windows. Long model catalogs scroll inside the available height.
+class _PaneMenuPosition extends SingleChildLayoutDelegate {
+ const _PaneMenuPosition(this.position, this.minWidth, this.maxWidth);
+ final RelativeRect position;
+ final double minWidth, maxWidth;
+
+ @override
+ BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
+ final width = math.max(0.0, constraints.maxWidth - 16);
+ return BoxConstraints(
+ minWidth: math.min(minWidth, width),
+ maxWidth: math.min(maxWidth, width),
+ maxHeight: math.max(0, constraints.maxHeight - 16),
+ );
+ }
+
+ @override
+ Offset getPositionForChild(Size size, Size childSize) => Offset(
+ (size.width - position.right - childSize.width).clamp(
+ 8,
+ math.max(8, size.width - childSize.width - 8),
+ ),
+ position.top.clamp(8, math.max(8, size.height - childSize.height - 8)),
+ );
+
+ @override
+ bool shouldRelayout(_PaneMenuPosition oldDelegate) =>
+ position != oldDelegate.position ||
+ minWidth != oldDelegate.minWidth ||
+ maxWidth != oldDelegate.maxWidth;
+}
+
+class _PaneMenuFocus extends StatefulWidget {
+ const _PaneMenuFocus({required this.close, required this.child});
+ final VoidCallback close;
+ final Widget child;
+
+ @override
+ State<_PaneMenuFocus> createState() => _PaneMenuFocusState();
+}
+
+class _PaneMenuFocusState extends State<_PaneMenuFocus> {
+ final _scope = FocusScopeNode(debugLabel: 'Pane model menu');
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _scope.nextFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _scope.dispose();
+ super.dispose();
+ }
+
+ KeyEventResult _key(FocusNode node, KeyEvent event) {
+ if (event is KeyUpEvent) return KeyEventResult.ignored;
+ final keyboard = HardwareKeyboard.instance;
+ if (keyboard.isMetaPressed ||
+ keyboard.isAltPressed ||
+ keyboard.isControlPressed) {
+ return KeyEventResult.ignored;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.escape) {
+ widget.close();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowDown) {
+ _scope.nextFocus();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.arrowUp) {
+ _scope.previousFocus();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ @override
+ Widget build(BuildContext context) => KeymapRegion(
+ contextKind: KeymapContext.picker,
+ child: FocusScope(
+ node: _scope,
+ autofocus: true,
+ onKeyEvent: _key,
+ child: FocusTraversalGroup(child: widget.child),
+ ),
+ );
+}
+
/// One selectable row of a pane menu.
///
/// The hover is the SAME rectangle as the selected fill — inset by [kPaneMenuInset] and rounded
diff --git a/desktop/lib/widgets/prompt_context.dart b/desktop/lib/widgets/prompt_context.dart
new file mode 100644
index 000000000..653a15ad0
--- /dev/null
+++ b/desktop/lib/widgets/prompt_context.dart
@@ -0,0 +1,184 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/appearance_prefs_store.dart';
+import '../shared/theme/prompt_style.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'search_result_text.dart';
+
+/// The same compact identity line in the picker, pane header and live preview.
+/// Symbols use our bundled icon font; Powerline separators are drawn shapes.
+/// Changing the terminal font therefore never requires a patched Nerd Font.
+class PromptContextView extends StatelessWidget {
+ const PromptContextView({
+ super.key,
+ required this.contextData,
+ this.prefs,
+ this.store,
+ this.size = 12,
+ this.matches = const [],
+ });
+
+ final PromptContext contextData;
+ final PromptPrefs? prefs;
+ final AppearancePrefsStore? store;
+ final double size;
+ final Iterable<SearchFieldMatch> matches;
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return ListenableBuilder(
+ listenable: Listenable.merge([
+ store ?? appearancePrefsStore,
+ terminalFontStore,
+ ]),
+ builder: (context, _) =>
+ _line(prefs ?? (store ?? appearancePrefsStore).value.prompt),
+ );
+ }
+
+ Widget _line(PromptPrefs prefs) {
+ final data = contextData;
+ final segments =
+ <
+ ({
+ String label,
+ String value,
+ String ascii,
+ IconData? icon,
+ Color color,
+ })
+ >[
+ if (data.harness?.isNotEmpty == true)
+ (
+ label: 'Harness',
+ value: data.harness!,
+ ascii: kHarnessPromptMarker,
+ icon: null,
+ color: Colors.white60,
+ ),
+ if (data.leading?.isNotEmpty == true)
+ (
+ label: '',
+ value: data.leading!,
+ ascii: '',
+ icon: null,
+ color: Colors.white60,
+ ),
+ if (prefs.machine && data.machine?.isNotEmpty == true)
+ (
+ label: 'Machine',
+ value: data.machine!,
+ ascii: '@',
+ icon: LucideIcons.monitor300,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ if (prefs.project && data.project?.isNotEmpty == true)
+ (
+ label: 'Project',
+ value: data.project!,
+ ascii: '/',
+ icon: LucideIcons.folder300,
+ color: grid.AppPalette.teal,
+ ),
+ if (prefs.branch && data.branch?.isNotEmpty == true)
+ (
+ label: 'Branch',
+ value: data.branch!,
+ ascii: 'git:',
+ icon: LucideIcons.gitBranch300,
+ color: grid.AppPalette.online,
+ ),
+ ];
+ if (segments.isEmpty) return const SizedBox.shrink();
+ final powerline = prefs.style == PromptStyle.powerline;
+ return Semantics(
+ label: segments
+ .map(
+ (part) =>
+ '${part.label.isEmpty ? '' : '${part.label}: '}${part.value}',
+ )
+ .join(', '),
+ child: ExcludeSemantics(
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var index = 0; index < segments.length; index++) ...[
+ if (index > 0 && !powerline) const SizedBox(width: 12),
+ Flexible(
+ child: Builder(
+ builder: (context) {
+ final part = segments[index];
+ final tone = prefs.color ? part.color : Colors.white60;
+ Widget segment = Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (part.ascii.isNotEmpty) ...[
+ if (prefs.style == PromptStyle.plain ||
+ part.icon == null)
+ Text(
+ part.ascii,
+ style: boxMonoStyle(size: size, color: tone),
+ )
+ else
+ Icon(part.icon, size: size, color: tone),
+ const SizedBox(width: 4),
+ ],
+ Flexible(
+ child: SearchResultText(
+ part.value,
+ matches: matches,
+ style: boxMonoStyle(size: size, color: tone),
+ ),
+ ),
+ ],
+ );
+ if (powerline) {
+ segment = ClipPath(
+ clipper: _PromptChevron(first: index == 0),
+ child: ColoredBox(
+ color: tone.withValues(alpha: .14),
+ child: Padding(
+ padding: EdgeInsets.fromLTRB(
+ index == 0 ? 6 : 12,
+ 2,
+ 12,
+ 2,
+ ),
+ child: segment,
+ ),
+ ),
+ );
+ }
+ return segment;
+ },
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+class _PromptChevron extends CustomClipper<Path> {
+ const _PromptChevron({required this.first});
+ final bool first;
+
+ @override
+ Path getClip(Size size) => Path()
+ ..moveTo(0, 0)
+ ..lineTo(size.width - 8, 0)
+ ..lineTo(size.width, size.height / 2)
+ ..lineTo(size.width - 8, size.height)
+ ..lineTo(0, size.height)
+ ..lineTo(first ? 0 : 8, size.height / 2)
+ ..close();
+
+ @override
+ bool shouldReclip(_PromptChevron oldClipper) => first != oldClipper.first;
+}
diff --git a/desktop/lib/widgets/prompt_customize.dart b/desktop/lib/widgets/prompt_customize.dart
new file mode 100644
index 000000000..b98b0a0d1
--- /dev/null
+++ b/desktop/lib/widgets/prompt_customize.dart
@@ -0,0 +1,186 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/theme/appearance_prefs_store.dart';
+import '../shared/theme/prompt_style.dart';
+import 'box_chrome.dart';
+import 'prompt_context.dart';
+
+class PromptCustomize extends StatelessWidget {
+ const PromptCustomize({super.key, required this.store});
+ final AppearancePrefsStore store;
+
+ @override
+ Widget build(BuildContext context) => ValueListenableBuilder<AppearancePrefs>(
+ valueListenable: store,
+ builder: (context, appearance, _) {
+ final prefs = appearance.prompt;
+ void choose(PromptPrefs next) => unawaited(store.setPrompt(next));
+ Widget toggle(
+ String name,
+ String label,
+ bool value,
+ ValueChanged<bool> onChanged,
+ ) => TextButton(
+ key: ValueKey('prompt-$name'),
+ style: TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ foregroundColor: grid.AppPalette.textPrimary,
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.all(
+ Radius.circular(kTerminalCornerRadius),
+ ),
+ ),
+ ),
+ onPressed: () => onChanged(!value),
+ child: Semantics(
+ checked: value,
+ label: label,
+ child: ExcludeSemantics(
+ child: Text(
+ '${value ? '[x]' : '[ ]'} $label',
+ style: boxMonoStyle(color: grid.AppPalette.textPrimary),
+ ),
+ ),
+ ),
+ );
+ return SingleChildScrollView(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ 'prompt style',
+ style: boxMonoStyle(color: grid.AppPalette.textSecondary),
+ ),
+ const SizedBox(height: 8),
+ for (final style in PromptStyle.values)
+ TextButton(
+ key: ValueKey('prompt-style-${style.name}'),
+ onPressed: () => choose(prefs.copyWith(style: style)),
+ style: TextButton.styleFrom(
+ alignment: Alignment.centerLeft,
+ backgroundColor: prefs.style == style
+ ? grid.AppSurface.selectedFill
+ : null,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 10,
+ ),
+ shape: const RoundedRectangleBorder(
+ borderRadius: BorderRadius.all(
+ Radius.circular(kTerminalCornerRadius),
+ ),
+ ),
+ ),
+ child: Semantics(
+ selected: prefs.style == style,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '${prefs.style == style ? '>' : ' '} ${style.label}',
+ style: boxMonoStyle(color: grid.AppPalette.textPrimary),
+ ),
+ Padding(
+ padding: const EdgeInsets.only(left: 16, top: 3),
+ child: Text(
+ style.description,
+ style: boxMonoStyle(
+ size: 11,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ 'preview',
+ style: boxMonoStyle(
+ size: 11,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ const SizedBox(height: 6),
+ TerminalBox(
+ child: Padding(
+ padding: const EdgeInsets.all(12),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ PromptContextView(
+ key: const ValueKey('prompt-preview'),
+ store: store,
+ contextData: const PromptContext(
+ harness: 'Codex',
+ machine: 'devbox',
+ project: 'openharness',
+ branch: 'main',
+ ),
+ ),
+ const SizedBox(height: 12),
+ Text('> fix the login flow', style: boxMonoStyle()),
+ ],
+ ),
+ ),
+ ),
+ const SizedBox(height: 16),
+ Text(
+ 'context',
+ style: boxMonoStyle(
+ size: 11,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ toggle(
+ 'machine',
+ 'Machine',
+ prefs.machine,
+ (value) => choose(prefs.copyWith(machine: value)),
+ ),
+ toggle(
+ 'project',
+ 'Project',
+ prefs.project,
+ (value) => choose(prefs.copyWith(project: value)),
+ ),
+ toggle(
+ 'branch',
+ 'Branch',
+ prefs.branch,
+ (value) => choose(prefs.copyWith(branch: value)),
+ ),
+ toggle(
+ 'color',
+ 'Color',
+ prefs.color,
+ (value) => choose(prefs.copyWith(color: value)),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ 'Applies to agent search and pane headers. Changes are saved as you choose.',
+ style: boxMonoStyle(
+ size: 11,
+ color: grid.AppPalette.textSecondary,
+ ),
+ ),
+ const SizedBox(height: 12),
+ TextButton(
+ key: const ValueKey('prompt-reset'),
+ onPressed: () => choose(const PromptPrefs()),
+ child: Text(
+ 'Reset prompt style',
+ style: boxMonoStyle(color: grid.AppPalette.textSecondary),
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+}
diff --git a/desktop/lib/widgets/rename_agent_dialog.dart b/desktop/lib/widgets/rename_agent_dialog.dart
index ae313bef5..04d020661 100644
--- a/desktop/lib/widgets/rename_agent_dialog.dart
+++ b/desktop/lib/widgets/rename_agent_dialog.dart
@@ -1,152 +1,31 @@
import 'package:flutter/material.dart';
-import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import 'terminal_name_prompt.dart';
+import 'terminal_prompt.dart';
-/// The one "Edit name" dialog, opened from every place a name is shown.
-///
-/// Pulled out of the rail so the pane header could use it too: two copies would
-/// have been two sets of error handling for one rename, and the second is the
-/// one that quietly stops matching.
-///
-/// Keyboard-complete on purpose — autofocus, Enter submits, Escape closes —
-/// because the way in is a double click but the way through should never need
-/// the mouse again.
+/// Shared by command search and every agent title. The editor owns its input
+/// until unmount; the model owns a pending rename after the route closes.
Future<void> showAgentRenameDialog(
BuildContext context,
AppNotifier notifier,
String machineId,
String agentId,
- String currentName,
-) => showAppDialog<void>(
- context: context,
- builder: (_) => _RenameAgentDialog(
- notifier: notifier,
- machineId: machineId,
- agentId: agentId,
- currentName: currentName,
- ),
-);
-
-/// ⚠️ A widget that OWNS its controller, not a `StatefulBuilder` over one made
-/// beside `showDialog`.
-///
-/// That is what this file used to be, and it crashed the app on Escape: the
-/// controller was disposed the moment `showDialog`'s future resolved, which is
-/// when the route STARTS animating out — the dialog is still on screen and
-/// still rebuilding for the length of that transition, and the first rebuild
-/// after the dispose threw "A TextEditingController was used after being
-/// disposed" and took the window to a red screen.
-///
-/// A `State` disposes on unmount instead, which happens after the transition
-/// has finished and the route is gone, so there is nothing left to rebuild.
-class _RenameAgentDialog extends StatefulWidget {
- const _RenameAgentDialog({
- required this.notifier,
- required this.machineId,
- required this.agentId,
- required this.currentName,
- });
-
- final AppNotifier notifier;
- final String machineId;
- final String agentId;
- final String currentName;
-
- @override
- State<_RenameAgentDialog> createState() => _RenameAgentDialogState();
-}
-
-class _RenameAgentDialogState extends State<_RenameAgentDialog> {
- late final _controller = TextEditingController(text: widget.currentName);
- final _focus = FocusNode(debugLabel: 'rename-agent-name');
-
- /// The CLI's refusal, shown under the field. Null until one arrives.
- String? _error;
-
- @override
- void initState() {
- super.initState();
- // Typing replaces the name, the way a rename works everywhere else on
- // the Mac. Claimed after the first frame, and once more a beat later:
- // the terminal under the dialog autofocuses on its own rebuilds, and
- // `autofocus: true` on the field lost that race (owner, 2026-09-15).
- void claim() {
- if (!mounted) return;
- _focus.requestFocus();
- _controller.selection = TextSelection(
- baseOffset: 0,
- extentOffset: _controller.text.length,
- );
- }
-
- WidgetsBinding.instance.addPostFrameCallback((_) {
- claim();
- Future<void>.delayed(const Duration(milliseconds: 120), claim);
- });
- }
-
- @override
- void dispose() {
- _focus.dispose();
- _controller.dispose();
- super.dispose();
- }
-
- Future<void> _submit() async {
- final result = await widget.notifier.renameAgent(
- widget.machineId,
- widget.agentId,
- _controller.text,
- );
- if (!mounted) return;
- if (result == null) {
- Navigator.of(context).pop();
- return;
- }
- setState(() => _error = result);
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- return AlertDialog(
- title: const Text('Rename Harness'),
- content: SizedBox(
- width: 360,
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- TextField(
- controller: _controller,
- focusNode: _focus,
- autofocus: true,
- style: grid.kFieldTextStyle,
- onSubmitted: (_) => _submit(),
- ),
- if (_error case final error?) ...[
- const SizedBox(height: 10),
- Text(
- error,
- style: TextStyle(
- color: grid.AppPalette.dangerFill,
- fontFamily: grid.AppFont.sans,
- fontSize: 11.2,
- ),
- ),
- ],
- ],
- ),
- ),
- actions: [
- TextButton(
- onPressed: () => Navigator.of(context).pop(),
- child: const Text('Cancel'),
- ),
- FilledButton(onPressed: _submit, child: const Text('Save')),
- ],
- );
- }
+ String currentName, {
+ AppKeymap? keymap,
+}) async {
+ await showTerminalPrompt<String>(
+ context,
+ keymap: keymap,
+ builder: (_) => TerminalNamePrompt(
+ title: 'Rename Agent',
+ detail: notifier.stateOf(machineId)?.machine.displayName,
+ name: notifier.pendingAgentName(machineId, agentId) ?? currentName,
+ fieldKey: const Key('agent-rename-input'),
+ fieldLabel: 'Agent name',
+ pending: notifier.pendingAgentRename(machineId, agentId),
+ save: (name) => notifier.renameAgent(machineId, agentId, name),
+ ),
+ );
}
diff --git a/desktop/lib/widgets/restart_agent_action.dart b/desktop/lib/widgets/restart_agent_action.dart
index 336d59f68..67a166fec 100644
--- a/desktop/lib/widgets/restart_agent_action.dart
+++ b/desktop/lib/widgets/restart_agent_action.dart
@@ -1,23 +1,335 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/app_state.dart';
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'engine_identity.dart';
+import 'terminal_prompt.dart';
-/// Relaunches the same harness through the existing CLI restart action.
+/// Restart is an immediate action. Its progress and recovery remain accessible
+/// through the same prompt, even after Escape returns to the terminal.
Future<void> restartHarness(
BuildContext context,
AppNotifier notifier,
String machineId,
- String agentId,
-) async {
- final result = await notifier.restartAgent(machineId, agentId);
- if (!context.mounted) return;
- final message =
- result.error ??
- (result.resumed
- ? null
- : 'Restarted with a new session — the previous one could not be resumed.');
- if (message != null) {
- ScaffoldMessenger.of(context)
- .showSnackBar(SnackBar(content: Text(message)));
+ String agentId, {
+ AppKeymap? keymap,
+}) => showTerminalPrompt<void>(
+ context,
+ keymap: keymap,
+ builder: (_) => _RestartAgentPrompt(
+ notifier: notifier,
+ machineId: machineId,
+ agentId: agentId,
+ ),
+);
+
+class _RestartAgentPrompt extends StatefulWidget {
+ const _RestartAgentPrompt({
+ required this.notifier,
+ required this.machineId,
+ required this.agentId,
+ });
+ final AppNotifier notifier;
+ final String machineId, agentId;
+ @override
+ State<_RestartAgentPrompt> createState() => _RestartAgentPromptState();
+}
+
+class _RestartAgentPromptState extends State<_RestartAgentPrompt> {
+ late AgentRestartAttempt _attempt;
+ final _focus = FocusNode(debugLabel: 'Restart status');
+ final _cancel = FocusNode(debugLabel: 'Cancel another restart');
+ final _body = ScrollController();
+ final _announcer = BoxAnnouncer();
+ bool _busy = false, _confirmAgain = false, _fresh = false;
+ String? _error;
+ bool get _closeOnly => _fresh || _attempt.result?.retryable == false;
+ bool get _terminal => isTerminalEngine(_attempt.agent?.engine);
+
+ @override
+ void initState() {
+ super.initState();
+ _attempt = widget.notifier.restartAttempt(widget.machineId, widget.agentId);
+ _error = _attempt.result?.error;
+ if (_attempt.pending case final pending?) {
+ _busy = true;
+ unawaited(_finish(pending));
+ } else if (_attempt.result == null) {
+ _busy = true;
+ unawaited(
+ _finish(
+ widget.notifier.restartAgent(
+ widget.machineId,
+ widget.agentId,
+ attempt: _attempt,
+ ),
+ ),
+ );
+ }
+ _focusStatus();
+ }
+
+ void _focusStatus() => WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _focus.requestFocus();
+ }
+ });
+
+ @override
+ void dispose() {
+ _focus.dispose();
+ _cancel.dispose();
+ _body.dispose();
+ super.dispose();
+ }
+
+ void _close() => Navigator.pop(context);
+
+ void _accept() {
+ if (_confirmAgain || !_focus.hasPrimaryFocus) {
+ activatePromptControl();
+ return;
+ }
+ if (_busy) return;
+ if (_closeOnly) {
+ _close();
+ } else {
+ _retry();
+ }
+ }
+
+ void _retry() {
+ if (_busy) return;
+ _focus.requestFocus();
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ unawaited(
+ _finish(
+ widget.notifier.restartAgent(
+ widget.machineId,
+ widget.agentId,
+ attempt: _attempt,
+ ),
+ ),
+ );
+ }
+
+ Future<void> _finish(Future<RestartAgentResult> request) async {
+ RestartAgentResult result;
+ try {
+ result = await request;
+ } catch (_) {
+ result = const RestartAgentResult(
+ error: 'Could not confirm the restart. Check the terminal before restarting again.',
+ );
+ }
+ if (!mounted) return;
+ if (result.error == null && (result.resumed || _terminal)) {
+ Navigator.pop(context);
+ return;
+ }
+ setState(() {
+ _busy = false;
+ _error = result.error;
+ _fresh = result.error == null && !result.resumed;
+ });
+ _announcer.row(context, _error ?? 'Restarted with a new conversation.');
+ _focusStatus();
+ }
+
+ void _askAgain() {
+ setState(() => _confirmAgain = true);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _cancel.requestFocus();
+ });
+ }
+
+ void _cancelAgain() {
+ setState(() => _confirmAgain = false);
+ _focusStatus();
+ }
+
+ void _restartAgain() {
+ if (!widget.notifier.discardRestartAttempt(
+ widget.machineId,
+ widget.agentId,
+ _attempt,
+ )) {
+ return;
+ }
+ _attempt = widget.notifier.restartAttempt(widget.machineId, widget.agentId);
+ setState(() => _confirmAgain = false);
+ _retry();
}
+
+ void _page(int direction) {
+ if (!_body.hasClients) return;
+ final position = _body.position;
+ _body.jumpTo(
+ (position.pixels + direction * position.viewportDimension * .8).clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
+ ),
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => TerminalPromptKeys(
+ focusNode: _focus,
+ inputFocus: _focus,
+ accept: _accept,
+ cancel: _confirmAgain ? _cancelAgain : _close,
+ pageDown: () => _page(1),
+ pageUp: () => _page(-1),
+ child: TerminalPrompt(
+ child: Column(
+ key: const ValueKey('agent-restart-prompt'),
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: ExcludeFocus(
+ child: SingleChildScrollView(
+ controller: _body,
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ _terminal ? 'Restart Terminal' : 'Restart Agent',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ _attempt.agent?.name ?? widget.agentId,
+ style: boxMonoStyle(weight: FontWeight.w600),
+ ),
+ if (widget.notifier
+ .stateOf(widget.machineId)
+ ?.machine
+ .displayName
+ case final machine?)
+ Text(
+ machine,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ if (!_confirmAgain) ...[
+ const SizedBox(height: 10),
+ Text(
+ _terminal ? 'Starts a fresh shell in the same pane.' : 'Relaunches the agent in the same pane and tries to resume its conversation.',
+ style: boxMonoStyle(size: 12, color: Colors.white70),
+ ),
+ if (_busy) ...[
+ const SizedBox(height: 8),
+ Text(
+ 'Restart continues if you close this prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(
+ error,
+ style: boxMonoStyle(
+ size: 12,
+ color: Colors.orangeAccent,
+ ),
+ ),
+ ],
+ if (_fresh) ...[
+ const SizedBox(height: 12),
+ Text(
+ 'Started a new conversation. The previous session could not be resumed.',
+ style: boxMonoStyle(
+ size: 12,
+ color: Colors.orangeAccent,
+ ),
+ ),
+ ],
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ if (_confirmAgain) ...[
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
+ child: Wrap(
+ spacing: 12,
+ children: [
+ terminalPromptButton(
+ 'Cancel',
+ _cancelAgain,
+ focusNode: _cancel,
+ ),
+ terminalPromptButton(
+ 'Restart',
+ _restartAgain,
+ key: const Key('restart-again-confirm'),
+ ),
+ ],
+ ),
+ ),
+ ] else if (_attempt.awaitingConfirmation && !_busy && !_closeOnly)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(14, 0, 14, 8),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: terminalPromptButton(
+ 'Restart again…',
+ _askAgain,
+ key: const Key('restart-again'),
+ ),
+ ),
+ ),
+ BoxHintStrip(
+ message: _busy
+ ? 'Restarting…'
+ : (_confirmAgain
+ ? 'May have already restarted.'
+ : (_attempt.awaitingConfirmation && !_closeOnly
+ ? 'Restart not confirmed.'
+ : null)),
+ isError: !_busy && _attempt.awaitingConfirmation,
+ hints: [
+ if (!_busy)
+ BoxHint(
+ terminalPromptHint(context, 'picker.accept', 'enter'),
+ _confirmAgain
+ ? 'select'
+ : (_closeOnly
+ ? 'close'
+ : (_attempt.awaitingConfirmation && !_closeOnly
+ ? 'check status'
+ : 'retry')),
+ onTap: _confirmAgain
+ ? null
+ : (_closeOnly ? _close : _retry),
+ ),
+ if (_confirmAgain)
+ BoxHint(
+ terminalPromptHint(context, 'picker.complete', 'tab'),
+ 'controls',
+ ),
+ BoxHint(
+ terminalPromptHint(context, 'picker.cancel', 'esc'),
+ _confirmAgain ? 'back' : 'close',
+ onTap: _confirmAgain ? _cancelAgain : _close,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
}
diff --git a/desktop/lib/widgets/shortcuts_sheet.dart b/desktop/lib/widgets/shortcuts_sheet.dart
index 3ea5b1c1f..23d0e87fd 100644
--- a/desktop/lib/widgets/shortcuts_sheet.dart
+++ b/desktop/lib/widgets/shortcuts_sheet.dart
@@ -5,6 +5,7 @@ import '../shared/widgets/app_dialog.dart';
import '../shortcuts/shortcuts_list.dart';
import '../shortcuts/keymap.dart';
import '../shortcuts/keymap_settings.dart';
+import '../shortcuts/keyboard_practice.dart';
/// The ⌘/ sheet — [ShortcutsList] in a dialog.
///
@@ -63,6 +64,10 @@ class _ShortcutsSheetState extends State<_ShortcutsSheet> {
onContextChanged: (value) =>
setState(() => _contextKind = value),
),
+ TextButton(
+ onPressed: () => showKeyboardPractice(context),
+ child: const Text('Practice these shortcuts'),
+ ),
ShortcutsList(contextKind: _contextKind),
],
),
diff --git a/desktop/lib/widgets/swarm_dialogs.dart b/desktop/lib/widgets/swarm_dialogs.dart
index bf8b90852..19c8a0ca3 100644
--- a/desktop/lib/widgets/swarm_dialogs.dart
+++ b/desktop/lib/widgets/swarm_dialogs.dart
@@ -3,145 +3,32 @@ import 'dart:async';
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
-import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_dialog.dart';
import '../shared/widgets/app_select_field.dart';
import '../state/app_state.dart';
+import '../shortcuts/app_keymap.dart';
import '../state/swarm_catalog.dart';
import 'link_another_machine_dialog.dart';
import 'remote_folder_picker.dart';
import 'clone_repository_dialog.dart';
+import 'terminal_name_prompt.dart';
+import 'terminal_prompt.dart';
-Future<String?> showSwarmRenameDialog(BuildContext context, String name) =>
- showAppDialog<String>(
- context: context,
- transitionDuration: Duration.zero,
- veilBlur: 0,
- veilTint: const Color(0x99000000),
- builder: (_) => _RenameSwarmDialog(name: name),
- );
-
-class _RenameSwarmDialog extends StatefulWidget {
- const _RenameSwarmDialog({required this.name});
- final String name;
- @override
- State<_RenameSwarmDialog> createState() => _RenameSwarmDialogState();
-}
-
-class _RenameSwarmDialogState extends State<_RenameSwarmDialog> {
- late final _text = TextEditingController(
- text: widget.name,
- )..selection = TextSelection(baseOffset: 0, extentOffset: widget.name.length);
- final _focus = FocusNode(debugLabel: 'Rename Tab name');
-
- @override
- void initState() {
- super.initState();
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted && ModalRoute.isCurrentOf(context) != false) {
- _focus.requestFocus();
- }
- });
- }
-
- @override
- void dispose() {
- _focus.dispose();
- _text.dispose();
- super.dispose();
- }
-
- void _save() {
- final name = _text.text.trim();
- if (name.isNotEmpty) Navigator.pop(context, name);
- }
-
- @override
- Widget build(BuildContext context) {
- grid.AppTheme.watch(context);
- final accent = grid.AppPalette.accentOnSurface;
- final border = OutlineInputBorder(
- borderRadius: BorderRadius.circular(10),
- borderSide: BorderSide.none,
- );
- return ListenableBuilder(
- listenable: _text,
- builder: (context, _) => AlertDialog(
- title: const Text('Rename Tab'),
- titleTextStyle: Theme.of(context).textTheme.titleMedium,
- content: SizedBox(
- width: 360,
- child: Semantics(
- label: 'Harness name',
- child: TextSelectionTheme(
- data: TextSelectionTheme.of(context)
- .copyWith(selectionColor: accent.withValues(alpha: .3)),
- child: TextField(
- controller: _text,
- focusNode: _focus,
- autofocus: true,
- maxLength: 80,
- cursorColor: accent,
- textInputAction: TextInputAction.done,
- style: TextStyle(
- fontSize: 15,
- color: grid.AppPalette.textPrimary,
- ),
- decoration: InputDecoration(
- filled: true,
- fillColor: grid.AppSurface.recess,
- isDense: true,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 14,
- vertical: 14,
- ),
- border: border,
- enabledBorder: border,
- focusedBorder: border.copyWith(
- borderSide: BorderSide(color: accent),
- ),
- counterText: '',
- suffixText: _text.text.characters.length >= 70
- ? '${_text.text.characters.length}/80'
- : null,
- suffixStyle: TextStyle(
- fontSize: 11,
- color: grid.AppPalette.textSecondary,
- ),
- ),
- onSubmitted: (_) => _save(),
- ),
- ),
- ),
- ),
- actions: [
- OutlinedButton(
- onPressed: () => Navigator.pop(context),
- style: OutlinedButton.styleFrom(
- foregroundColor: grid.AppPalette.textSecondary,
- minimumSize: const Size(88, 38),
- padding: const EdgeInsets.symmetric(horizontal: 18),
- side: const BorderSide(color: Colors.white24),
- shape: const StadiumBorder(),
- ),
- child: const Text('Cancel'),
- ),
- FilledButton(
- onPressed: _text.text.trim().isEmpty ? null : _save,
- style: FilledButton.styleFrom(
- backgroundColor: grid.AppPalette.swarmAccent,
- foregroundColor: grid.AppPalette.swarmTabBar,
- minimumSize: const Size(88, 38),
- padding: const EdgeInsets.symmetric(horizontal: 18),
- shape: const StadiumBorder(),
- ),
- child: const Text('Rename'),
- ),
- ],
- ),
- );
- }
-}
+Future<String?> showSwarmRenameDialog(
+ BuildContext context,
+ String name, {
+ AppKeymap? keymap,
+}) => showTerminalPrompt<String>(
+ context,
+ keymap: keymap,
+ builder: (_) => TerminalNamePrompt(
+ title: 'Rename Tab',
+ name: name,
+ fieldKey: const Key('tab-rename-input'),
+ fieldLabel: 'Tab name',
+ maxLength: 80,
+ ),
+);
Future<SavedSwarmProject?> showSwarmProjectDialog(
BuildContext context,
@@ -315,5 +202,8 @@ class _ProjectDialogState extends State<_ProjectDialog> {
/// Link another machine. The dialog itself lives in
/// `link_another_machine_dialog.dart`; this name is what every caller — the
/// Machines menu, ⌘ commands, the machines manager — has always used.
-Future<void> showSwarmLinkDialog(BuildContext context, AppNotifier notifier) =>
- showLinkAnotherMachineDialog(context, notifier);
+Future<void> showSwarmLinkDialog(
+ BuildContext context,
+ AppNotifier notifier, {
+ AppKeymap? keymap,
+}) => showLinkAnotherMachineDialog(context, notifier, keymap: keymap);
diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dart
index 72be89c07..fe75e5413 100644
--- a/desktop/lib/widgets/swarm_search_input.dart
+++ b/desktop/lib/widgets/swarm_search_input.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../state/swarm_search.dart';
+import 'box_chrome.dart';
/// The shared input for the start page, Open Agent and split searches.
/// Flutter owns the caret and result navigation; native chrome only opens it.
@@ -27,6 +28,8 @@ class SwarmSearchInput extends StatelessWidget {
this.trailing,
this.height,
this.fontSize = 16,
+ this.prompt,
+ this.terminal = false,
});
final Key inputKey;
@@ -52,6 +55,11 @@ class SwarmSearchInput extends StatelessWidget {
/// The typed text and the hint; the search glyph grows with it.
final double fontSize;
+ final String? prompt;
+
+ /// Plain monospace input in a TerminalBox, without a decorative search glyph.
+ /// Mode prefixes belong to the editable buffer.
+ final bool terminal;
@override
Widget build(BuildContext context) => ListenableBuilder(
@@ -63,6 +71,7 @@ class SwarmSearchInput extends StatelessWidget {
Widget _buildInput(BuildContext context) {
final open = search != null;
+ final terminalStyle = terminal || prompt != null;
final border = OutlineInputBorder(
borderRadius: BorderRadius.vertical(
top: Radius.circular(rounded ? (prominent ? 32 : 28) : 12),
@@ -88,22 +97,46 @@ class SwarmSearchInput extends StatelessWidget {
onTapAlwaysCalled: true,
onTapOutside: onTapOutside == null ? null : (_) => onTapOutside!(),
onChanged: onChanged,
- style: TextStyle(fontSize: fontSize, color: Colors.white),
+ style: terminalStyle
+ ? boxMonoStyle(size: fontSize)
+ : TextStyle(fontSize: fontSize, color: Colors.white),
cursorColor: grid.AppPalette.swarmAccent,
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
- hintText: search?.isCommandMode == true
+ hintText:
+ search?.isCommandMode == true ||
+ search?.isHelpMode == true ||
+ search?.isGroupMode == true
? search!.hint
- : hintText ?? search?.hint ?? 'Find a harness',
- hintStyle: TextStyle(fontSize: fontSize, color: Colors.white60),
+ : hintText ?? search?.hint ?? kSwarmSearchHint,
+ hintStyle: terminalStyle
+ ? boxMonoStyle(size: fontSize, color: kBoxFaint)
+ : TextStyle(fontSize: fontSize, color: Colors.white60),
hintMaxLines: 1,
- prefixIcon: Icon(
- Icons.search,
- size: fontSize + 4,
- color: Colors.white60,
- ),
+ prefixIcon: prompt != null
+ ? Padding(
+ padding: const EdgeInsets.only(left: 14, right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ prompt!,
+ style: boxMonoStyle(
+ size: fontSize,
+ color: grid.AppPalette.swarmAccent,
+ ),
+ ),
+ ),
+ )
+ : terminal
+ ? null
+ : Icon(Icons.search, size: fontSize + 4, color: Colors.white60),
prefixIconConstraints: BoxConstraints(
- minWidth: fontSize >= 20 ? 64 : 52,
+ minWidth: prompt != null
+ ? 36
+ : fontSize >= 20
+ ? 64
+ : 52,
minHeight: height ?? (prominent ? 64 : 56),
),
suffixIcon: showClose || trailing != null
@@ -129,8 +162,14 @@ class SwarmSearchInput extends StatelessWidget {
),
)
: null,
- filled: true,
- fillColor: fillColor ?? grid.AppPalette.swarmSearchSurface,
+ // TerminalBox owns the dock surface. An unfilled field also avoids
+ // Material's extra inset, keeping the input aligned with result text.
+ filled: !terminal,
+ fillColor:
+ fillColor ??
+ (terminalStyle
+ ? grid.AppPalette.swarmField
+ : grid.AppPalette.swarmSearchSurface),
hoverColor: Colors.transparent,
contentPadding: EdgeInsets.symmetric(
horizontal: 18,
@@ -139,9 +178,9 @@ class SwarmSearchInput extends StatelessWidget {
: ((height! - fontSize * 1.2) / 2).clamp(0, double.infinity),
),
isDense: true,
- border: border,
- enabledBorder: border,
- focusedBorder: border,
+ border: terminalStyle ? InputBorder.none : border,
+ enabledBorder: terminalStyle ? InputBorder.none : border,
+ focusedBorder: terminalStyle ? InputBorder.none : border,
),
);
}
diff --git a/desktop/lib/widgets/swarm_search_preview.dart b/desktop/lib/widgets/swarm_search_preview.dart
index 909a7b7f8..1d6983e0d 100644
--- a/desktop/lib/widgets/swarm_search_preview.dart
+++ b/desktop/lib/widgets/swarm_search_preview.dart
@@ -5,9 +5,11 @@ import 'package:flutter/rendering.dart' show ScrollCacheExtent;
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../core/models.dart';
+import '../shared/theme/prompt_style.dart';
import '../state/app_state.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
+import 'box_chrome.dart';
import 'engine_identity.dart';
typedef _PreviewAgent = ({MachineState machine, Agent agent});
@@ -46,9 +48,11 @@ class SwarmSearchPreview extends StatefulWidget {
super.key,
required this.search,
this.compactHeader = false,
+ this.terminal = false,
});
final SwarmSearchController search;
final bool compactHeader;
+ final bool terminal;
@override
State<SwarmSearchPreview> createState() => _SwarmSearchPreviewState();
@@ -172,7 +176,13 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
? ListView.builder(
key: ValueKey('preview-content:${row.id}'),
controller: _scroll,
- padding: EdgeInsets.all(widget.compactHeader ? 16 : 24),
+ padding: EdgeInsets.all(
+ widget.terminal
+ ? 12
+ : widget.compactHeader
+ ? 16
+ : 24,
+ ),
scrollCacheExtent: const ScrollCacheExtent.pixels(120),
itemCount: agents.length + 1,
itemBuilder: (context, index) => index == 0
@@ -183,14 +193,17 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
children: [
Text(
row.title,
+ // The list leads the eye; this confirms it.
style: const TextStyle(
- fontSize: 20,
+ fontSize: 15,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 6),
Text(row.detail, style: _muted),
- if (agents.isEmpty)
+ // Nothing exists yet behind the create row, so
+ // there is no session to be missing text from.
+ if (agents.isEmpty && !row.isCreate)
const Padding(
padding: EdgeInsets.only(top: 24),
child: Text(
@@ -210,6 +223,7 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
app: app,
item: agents[index - 1],
compact: true,
+ terminal: widget.terminal,
),
if (index < agents.length)
const SizedBox(height: 20),
@@ -220,11 +234,18 @@ class _SwarmSearchPreviewState extends State<SwarmSearchPreview> {
: SingleChildScrollView(
key: ValueKey('preview-content:${row.id}'),
controller: _scroll,
- padding: EdgeInsets.all(widget.compactHeader ? 16 : 24),
+ padding: EdgeInsets.all(
+ widget.terminal
+ ? 12
+ : widget.compactHeader
+ ? 16
+ : 24,
+ ),
child: _AgentPreview(
app: app,
item: agents.single,
dense: widget.compactHeader,
+ terminal: widget.terminal,
),
),
),
@@ -242,14 +263,22 @@ class _AgentPreview extends StatelessWidget {
required this.item,
this.compact = false,
this.dense = false,
+ this.terminal = false,
});
final AppNotifier app;
final _PreviewAgent item;
final bool compact;
final bool dense;
+ final bool terminal;
@override
Widget build(BuildContext context) {
+ final muted = terminal ? boxMonoStyle(size: 11, color: kBoxFaint) : _muted;
+ final body = terminal
+ ? boxMonoStyle(size: 12, color: const Color(0xffe1e1e4))
+ : _body;
+ Widget section(String label, String text, {int? maxLines}) =>
+ _Section(label, text, maxLines: maxLines, terminal: terminal);
final (:machine, :agent) = item;
final record = app.sessionPreviews.read(
app.previewKey(machine.machine.machineId, agent),
@@ -268,7 +297,7 @@ class _AgentPreview extends StatelessWidget {
? 'Working'
: 'Idle';
final color = offline
- ? Colors.white38
+ ? Colors.white54
: waiting != null
? const Color(0xffe9bf79)
: working
@@ -294,35 +323,55 @@ class _AgentPreview extends StatelessWidget {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Row(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Padding(
- padding: const EdgeInsets.only(top: 2),
- child: EngineMark(
- engine: agent.identityEngine,
- displayName: agent.identityDisplayName,
- size: compact ? 18 : 22,
- ),
+ if (terminal) ...[
+ Text(agent.displayName, style: boxMonoStyle(weight: FontWeight.w600)),
+ const SizedBox(height: 4),
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '$state ',
+ style: TextStyle(color: color),
+ ),
+ TextSpan(
+ text:
+ '$kHarnessPromptMarker ${agentIdentity(agent).label} · ${machine.machine.name}',
+ ),
+ ],
),
- const SizedBox(width: 10),
- Expanded(
- child: Text(
- agent.name,
- style: TextStyle(
- fontSize: compact || dense ? 15 : 20,
- fontWeight: FontWeight.w600,
- height: 1.25,
+ style: muted,
+ ),
+ ] else
+ Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(top: 2),
+ child: EngineMark(
+ engine: agent.identityEngine,
+ displayName: agent.identityDisplayName,
+ size: compact ? 18 : 22,
),
),
- ),
- if (dense) ...[
const SizedBox(width: 10),
- Text(state, style: TextStyle(fontSize: 11, color: color)),
+ Expanded(
+ child: Text(
+ agent.displayName,
+ style: TextStyle(
+ // The list leads the eye; the preview confirms it.
+ fontSize: 15,
+ fontWeight: FontWeight.w600,
+ height: 1.25,
+ ),
+ ),
+ ),
+ if (dense) ...[
+ const SizedBox(width: 10),
+ Text(state, style: TextStyle(fontSize: 11, color: color)),
+ ],
],
- ],
- ),
- if (!dense) ...[
+ ),
+ if (!dense && !terminal) ...[
const SizedBox(height: 10),
Wrap(
spacing: 8,
@@ -357,7 +406,7 @@ class _AgentPreview extends StatelessWidget {
agentIdentity(agent).label,
machine.machine.name,
].join(' · '),
- style: _muted,
+ style: muted,
),
],
),
@@ -368,26 +417,32 @@ class _AgentPreview extends StatelessWidget {
_displayText(excerpt ?? 'No recent session text available.'),
maxLines: 4,
overflow: TextOverflow.ellipsis,
- style: excerpt == null ? _muted : _body,
+ style: excerpt == null ? muted : body,
),
if (project?.name != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
[project!.name, project.branch].whereType<String>().join(' · '),
- style: _muted,
+ style: muted,
),
),
] else ...[
- SizedBox(height: dense ? 16 : 26),
+ SizedBox(
+ height: terminal
+ ? 8
+ : dense
+ ? 16
+ : 26,
+ ),
if (waiting != null) ...[
Container(
width: double.infinity,
- padding: const EdgeInsets.all(16),
+ padding: EdgeInsets.all(terminal ? 8 : 16),
decoration: BoxDecoration(
color: color.withValues(alpha: .06),
border: Border.all(color: color.withValues(alpha: .24)),
- borderRadius: BorderRadius.circular(12),
+ borderRadius: BorderRadius.circular(terminal ? 0 : 12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -401,27 +456,27 @@ class _AgentPreview extends StatelessWidget {
),
),
const SizedBox(height: 8),
- Text(_displayText(waiting.prompt), style: _body),
+ Text(_displayText(waiting.prompt), style: body),
if (waiting.options.isNotEmpty) ...[
const SizedBox(height: 12),
- Text(waiting.options.take(6).join(' · '), style: _muted),
+ Text(waiting.options.take(6).join(' · '), style: muted),
],
],
),
),
- const SizedBox(height: 24),
+ SizedBox(height: terminal ? 14 : 24),
],
if (working) ...[
- if (request != null) _Section(requestLabel, request),
+ if (request != null) section(requestLabel, request),
if (record?.earlierRequest case final earlier?)
- _Section('Earlier request', earlier),
- if (activity != null) _Section('Latest activity', activity),
- if (record?.activity case final tool?) _Section('Using tool', tool),
+ section('Earlier request', earlier),
+ if (activity != null) section('Latest activity', activity),
+ if (record?.activity case final tool?) section('Using tool', tool),
if (activity == null && response != null)
- _Section('Previous response', response),
+ section('Previous response', response),
] else ...[
if (response != null)
- _Section(
+ section(
record?.interrupted == true
? 'Last response · interrupted'
: 'Latest response',
@@ -438,32 +493,32 @@ class _AgentPreview extends StatelessWidget {
children: [
Text(
'Earlier in this session',
- style: _muted.copyWith(fontWeight: FontWeight.w500),
+ style: muted.copyWith(fontWeight: FontWeight.w500),
),
for (final text in record!.earlierResponses)
Padding(
- padding: const EdgeInsets.only(top: 10),
+ padding: EdgeInsets.only(top: terminal ? 6 : 10),
child: Text(
_displayText(text),
maxLines: 4,
overflow: TextOverflow.ellipsis,
- style: _body,
+ style: body,
),
),
],
),
),
- if (request != null) _Section('Recent request', request),
+ if (request != null) section('Recent request', request),
if (record?.earlierRequest case final earlier?)
- _Section('Earlier request', earlier),
+ section('Earlier request', earlier),
],
if (record?.hasContent != true && waiting == null)
- const Padding(
- padding: EdgeInsets.only(bottom: 24),
- child: Text('No recent session text available.', style: _muted),
+ Padding(
+ padding: const EdgeInsets.only(bottom: 24),
+ child: Text('No recent session text available.', style: muted),
),
const SizedBox(height: 8),
- if (project?.cwd case final cwd?) Text(cwd, style: _muted),
+ if (project?.cwd case final cwd?) Text(cwd, style: muted),
if (project?.branch case final branch?)
Padding(
padding: const EdgeInsets.only(top: 4),
@@ -475,7 +530,7 @@ class _AgentPreview extends StatelessWidget {
color: Colors.white54,
),
const SizedBox(width: 6),
- Expanded(child: Text(branch, style: _muted)),
+ Expanded(child: Text(branch, style: muted)),
],
),
),
@@ -484,7 +539,7 @@ class _AgentPreview extends StatelessWidget {
padding: const EdgeInsets.only(top: 8),
child: Text(
'${offline || record?.unavailable == true ? 'Saved text · ' : ''}Received ${TimeOfDay.fromDateTime(at).format(context)}',
- style: _muted,
+ style: muted,
),
),
],
@@ -494,20 +549,26 @@ class _AgentPreview extends StatelessWidget {
}
class _Section extends StatelessWidget {
- const _Section(this.label, this.text, {this.maxLines});
+ const _Section(this.label, this.text, {this.maxLines, this.terminal = false});
final String label, text;
final int? maxLines;
+ final bool terminal;
@override
Widget build(BuildContext context) => Padding(
- padding: const EdgeInsets.only(bottom: 24),
+ padding: EdgeInsets.only(bottom: terminal ? 8 : 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- Text(label, style: _muted.copyWith(fontWeight: FontWeight.w500)),
- const SizedBox(height: 7),
+ Text(
+ label,
+ style: terminal
+ ? boxMonoStyle(size: 11, color: kBoxFaint)
+ : _muted.copyWith(fontWeight: FontWeight.w500),
+ ),
+ SizedBox(height: terminal ? 4 : 7),
Text(
_displayText(text),
- style: _body,
+ style: terminal ? boxMonoStyle(size: 12) : _body,
maxLines: maxLines,
overflow: maxLines == null ? null : TextOverflow.ellipsis,
),
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 40efed091..0abb98278 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -6,6 +6,9 @@ import 'package:flutter/services.dart';
import '../shortcuts/app_keymap.dart';
import '../shortcuts/keymap.dart';
+import 'box_chrome.dart';
+import 'prompt_context.dart';
+import '../terminal/terminal_font_store.dart';
import 'search_result_text.dart';
import '../shared/theme/app_theme.dart' as grid;
@@ -118,6 +121,7 @@ class SwarmSearchKeys extends StatelessWidget {
required this.onClose,
this.onOpen,
this.onNewAgent,
+ this.onCommands,
this.onRefocus,
required this.child,
});
@@ -130,6 +134,7 @@ class SwarmSearchKeys extends StatelessWidget {
/// The first navigation/accept key reveals them without choosing unseen work.
final VoidCallback? onOpen;
final VoidCallback? onNewAgent;
+ final VoidCallback? onCommands;
final VoidCallback? onRefocus;
final Widget child;
@@ -142,19 +147,30 @@ class SwarmSearchKeys extends StatelessWidget {
if (!composing()) action();
}
+ void dismiss() {
+ if (search?.back() == true) {
+ onRefocus?.call();
+ } else {
+ onClose();
+ }
+ }
+
void choose(bool add) => run(() {
if (search == null) {
onOpen?.call();
return;
}
+ final switchingMode =
+ !add && (search.selected?.pickerQuery != null || search.isGroupMode);
final choice = add ? search.addHere() : search.submit();
if (choice != null) onChoose(choice);
+ if (switchingMode) onRefocus?.call();
});
void move(int delta) => run(() {
if (search == null) {
onOpen?.call();
} else {
- search.move(delta);
+ search.moveVisually(delta);
onRefocus?.call();
}
});
@@ -170,12 +186,31 @@ class SwarmSearchKeys extends StatelessWidget {
'picker.next': () => move(1),
'picker.previous': () => move(-1),
if (search != null) ...{
- 'picker.preview_page_up': () => run(() => search.pagePreview(-1)),
- 'picker.preview_page_down': () =>
- run(() => search.pagePreview(1)),
+ 'picker.toggle_preview': () => run(search.togglePreview),
+ 'picker.preview_page_up': () => run(() => search.page(-1)),
+ 'picker.preview_page_down': () => run(() => search.page(1)),
},
- 'picker.cancel': onClose,
- if (search == null || search.allowsCommands)
+ 'picker.cancel': dismiss,
+ // Tab is a picker command now (New Harness completes paths with
+ // it); a matched key is consumed, so here it still walks the focus.
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ if (search != null)
+ for (var row = 1; row <= 9; row++)
+ 'picker.pick_$row': () => run(() {
+ if (row > search.rows.length) return;
+ final destination = search.rows[row - 1];
+ final switchingMode =
+ destination.pickerQuery != null || search.isGroupMode;
+ final choice = search.submit(destination);
+ if (choice != null) onChoose(choice);
+ if (switchingMode) onRefocus?.call();
+ }),
+ if (onCommands != null)
+ 'navigation.commands': () => run(onCommands!)
+ else if (search == null || search.allowsCommands)
'navigation.commands': () {
editing.value = const TextEditingValue(
text: '> ',
@@ -239,10 +274,15 @@ class SwarmSearchKeys extends StatelessWidget {
move(1),
const SingleActivator(LogicalKeyboardKey.arrowUp): () => move(-1),
if (search != null) ...{
+ const SingleActivator(
+ LogicalKeyboardKey.slash,
+ control: true,
+ ): () =>
+ run(search.togglePreview),
const SingleActivator(LogicalKeyboardKey.pageUp): () =>
- run(() => search.pagePreview(-1)),
+ run(() => search.page(-1)),
const SingleActivator(LogicalKeyboardKey.pageDown): () =>
- run(() => search.pagePreview(1)),
+ run(() => search.page(1)),
},
const SingleActivator(
LogicalKeyboardKey.keyN,
@@ -265,6 +305,11 @@ class SwarmSearchKeys extends StatelessWidget {
): () =>
move(-1),
const SingleActivator(LogicalKeyboardKey.escape): () =>
+ run(dismiss),
+ const SingleActivator(
+ LogicalKeyboardKey.keyC,
+ control: true,
+ ): () =>
run(onClose),
const SingleActivator(
LogicalKeyboardKey.keyG,
@@ -277,10 +322,19 @@ class SwarmSearchKeys extends StatelessWidget {
}
}
-double swarmSearchRowHeight(TextScaler scale, {required bool commands}) =>
- commands
- ? (scale.scale(14) + 20).clamp(40, double.infinity)
- : (scale.scale(14) + scale.scale(12) + 30).clamp(56, double.infinity);
+/// One line a row, commands and results alike: the name, then what it is, the
+/// way an editor's quick-open lists things. Narrow terminal results put their
+/// metadata below the title so both identity and task remain readable.
+double swarmSearchRowHeight(
+ TextScaler scale, {
+ required bool commands,
+ bool terminal = false,
+ bool stacked = false,
+}) => terminal
+ ? stacked
+ ? scale.scale(13) * 1.35 + scale.scale(12) * 1.35 + 8
+ : boxRowHeight(scale)
+ : (scale.scale(14) * 1.2 + 14).clamp(34, double.infinity);
double swarmSearchResultsHeight(
SwarmSearchController search,
@@ -298,11 +352,18 @@ class SwarmSearchResults extends StatefulWidget {
required this.onChoose,
required this.onRefocus,
this.sideBySideMinWidth = 800,
+ this.fitRows = false,
+ this.terminal = false,
});
final SwarmSearchController search;
final ValueChanged<SwarmSearchSelection> onChoose;
final VoidCallback onRefocus;
final double sideBySideMinWidth;
+
+ /// Let the overlay shrink to whole rows after its editor and hints have
+ /// taken their actual heights, including larger text and warning messages.
+ final bool fitRows;
+ final bool terminal;
@override
State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
}
@@ -310,22 +371,97 @@ class SwarmSearchResults extends StatefulWidget {
class _SwarmSearchResultsState extends State<SwarmSearchResults> {
// Keep a small set of recently built rows, not the whole search catalog.
// A new highlight only changes two rows; their neighbors keep their widgets.
+ // Query highlights listen within the text, leaving these controls intact.
final _rowWidgets = <String, ({Object presentation, Widget child})>{};
+ final _pointer = BoxPointerGate();
+ final _announcer = BoxAnnouncer();
+ String? _announced;
final _scroll = ScrollController();
+ final _resultsKey = GlobalKey();
double _rowHeight = 56;
bool _revealScheduled = false;
+ bool _createPinned = false;
+ int _lastPage = 0;
(Size, double)? _geometry;
SwarmSearchController get search => widget.search;
+
+ double _fittedHeight(
+ BoxConstraints constraints, {
+ required bool sideBySide,
+ required bool unavailable,
+ }) {
+ final stacked = search.hasPreview && !sideBySide;
+ if (stacked && search.resultsFromBottom) return constraints.maxHeight;
+ final available = stacked
+ ? (constraints.maxHeight - 8) * 5 / 11
+ : constraints.maxHeight;
+ final chrome = 16.0 + (unavailable ? 48 : 0);
+ final capacity = ((available - chrome) / _rowHeight).floor();
+ // A window too short for one row can only scroll a partial row.
+ if (capacity < 1) return constraints.maxHeight;
+ final maxRows = search.resultsFromBottom
+ ? 6
+ : widget.terminal
+ ? 9
+ : 12;
+ final count = search.hasPreview
+ ? capacity.clamp(1, maxRows)
+ : search.rows.length.clamp(1, capacity.clamp(1, maxRows));
+ final listHeight = chrome + count * _rowHeight;
+ return stacked ? 8 + listHeight * 11 / 5 : listHeight;
+ }
+
@override
void initState() {
super.initState();
search.addListener(_changed);
+ terminalFontStore.addListener(_fontChanged);
+ _lastPage = search.resultPage.value;
+ search.resultPage.addListener(_pageResults);
+ }
+
+ void _pageResults() {
+ final pages = search.resultPage.value - _lastPage;
+ _lastPage = search.resultPage.value;
+ if (!_scroll.hasClients || search.rows.isEmpty) return;
+ final count = (_scroll.position.viewportDimension / _rowHeight)
+ .floor()
+ .clamp(1, 50);
+ final direction = search.resultsFromBottom ? -pages : pages;
+ final next = (search.cursor + direction * count).clamp(
+ 0,
+ search.rows.length - 1,
+ );
+ search.move(next - search.cursor);
+ widget.onRefocus();
+ }
+
+ void _fontChanged() {
+ _rowWidgets.clear();
+ setState(() {});
}
void _changed() {
setState(() {});
_scrollToSelection();
_revealSelection();
+ // Focus stays in the input while the arrows move a highlight the screen
+ // reader never visits; say the row it landed on.
+ final row = search.selected;
+ if (row != null && row.id != _announced) {
+ _announced = row.id;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ final detail = widget.terminal
+ ? row.terminalDetail ?? row.detail
+ : row.detail;
+ _announcer.row(
+ context,
+ '${row.title}${detail.isEmpty ? '' : ', $detail'}, '
+ '${search.actionLabel(row)}',
+ );
+ });
+ }
}
void _revealSelection() {
@@ -337,13 +473,18 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
});
}
+ bool get _pinsCreate =>
+ search.resultsFromBottom && search.rows.firstOrNull?.isCreate == true;
+
void _scrollToSelection() {
if (!_scroll.hasClients || search.rows.isEmpty) return;
- final top = 8 + search.cursor * _rowHeight;
- final bottom = top + _rowHeight + 8;
+ final index = search.cursor - (_createPinned ? 1 : 0);
+ if (index < 0) return;
+ final top = index * _rowHeight;
+ final bottom = top + _rowHeight;
final position = _scroll.position;
- final offset = top - 8 < position.pixels
- ? top - 8
+ final offset = top < position.pixels
+ ? top
: bottom > position.pixels + position.viewportDimension
? bottom - position.viewportDimension
: position.pixels;
@@ -372,6 +513,8 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
void dispose() {
search.removeListener(_changed);
+ terminalFontStore.removeListener(_fontChanged);
+ search.resultPage.removeListener(_pageResults);
_scroll.dispose();
super.dispose();
}
@@ -379,26 +522,224 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
Widget build(BuildContext context) {
final scale = MediaQuery.textScalerOf(context);
- _rowHeight = swarmSearchRowHeight(scale, commands: search.isCommandMode);
+ final acceptKey = effectiveCommandHint(
+ context,
+ 'picker.accept',
+ contextKind: KeymapContext.picker,
+ );
final selected = search.selected;
final unavailable =
(selected != null && !search.canSubmit(selected)) ||
- search.adding && !search.canCreate;
- final terms = swarmQueryTerms(
- search.isCommandMode ? search.commandQuery : search.query,
- );
+ search.adding &&
+ !search.canCreate &&
+ !search.isCommandMode &&
+ !search.isHelpMode;
return LayoutBuilder(
builder: (context, constraints) {
final sideBySide = constraints.maxWidth >= widget.sideBySideMinWidth;
+ final resultWidth = search.hasPreview && sideBySide
+ ? (constraints.maxWidth - 1) * .6
+ : constraints.maxWidth;
+ final stacked =
+ widget.terminal &&
+ !search.isCommandMode &&
+ !search.isHelpMode &&
+ resultWidth < 700 * scale.scale(13) / 13;
+ _rowHeight = swarmSearchRowHeight(
+ scale,
+ commands: search.isCommandMode,
+ terminal: widget.terminal,
+ stacked: stacked,
+ );
+ final height = widget.fitRows
+ ? _fittedHeight(
+ constraints,
+ sideBySide: sideBySide,
+ unavailable: unavailable,
+ )
+ : constraints.maxHeight;
final compactAction =
(sideBySide ? constraints.maxWidth / 2 : constraints.maxWidth) <
380 * scale.scale(14) / 14;
- final geometry = (constraints.biggest, _rowHeight);
+ final geometry = (Size(constraints.maxWidth, height), _rowHeight);
if (_geometry != geometry) {
_geometry = geometry;
_revealSelection();
}
+ // The create action is outside the scrolling matches. Its location
+ // does not change when a query, preview, or selection changes.
+ final pinCreate = _createPinned =
+ _pinsCreate && constraints.maxHeight >= _rowHeight + 16;
+ Widget buildRow(BuildContext context, int index) {
+ final row = search.rows[index];
+ final highlighted = index == search.cursor;
+ final canSubmit = search.canSubmit(row);
+ final alreadyHere = search.alreadyHere(row);
+ final presentation = (
+ row,
+ highlighted,
+ canSubmit,
+ alreadyHere,
+ highlighted ? (search.canAccept, search.actionLabel(row)) : null,
+ _rowHeight,
+ compactAction,
+ scale.scale(11),
+ grid.AppTheme.palette.value,
+ acceptKey,
+ widget.terminal,
+ stacked,
+ );
+ final previous = _rowWidgets.remove(row.id);
+ if (previous?.presentation == presentation) {
+ _rowWidgets[row.id] = previous!;
+ return FocusTraversalOrder(
+ order: NumericFocusOrder(index.toDouble()),
+ child: previous.child,
+ );
+ }
+ final tile = ListTile(
+ key: ValueKey(row.id),
+ minTileHeight: _rowHeight,
+ enabled: canSubmit,
+ onFocusChange: (focused) {
+ if (focused) _focusResult(row.id);
+ },
+ selected: highlighted,
+ selectedColor: Colors.white,
+ hoverColor: Colors.transparent,
+ // BoxRowHighlight draws the selection, the same
+ // in both modes of the box.
+ selectedTileColor: Colors.transparent,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(widget.terminal ? 0 : 6),
+ ),
+ dense: true,
+ visualDensity: VisualDensity.compact,
+ minVerticalPadding: 0,
+ horizontalTitleGap: 10,
+ minLeadingWidth: 20,
+ contentPadding: const EdgeInsets.symmetric(horizontal: 10),
+ // The dock uses its full-row highlight for
+ // selection; prefixes only appear in the input.
+ leading: widget.terminal
+ ? null
+ : Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ // Every command wore the same ⌘: a column
+ // of identical marks says nothing. Its
+ // own key, at the right, says something.
+ row.isCommand || row.pickerQuery != null
+ ? const SizedBox(width: 2)
+ : row.isCreate
+ ? const Icon(
+ LucideIcons.plus300,
+ size: 18,
+ color: Colors.white70,
+ )
+ : row.isStore
+ ? StoreMark(size: 20, enabled: canSubmit)
+ : row.agentId != null ||
+ (row.isSwarm && row.members.length == 1)
+ ? EngineMark(
+ engine: row.engine,
+ size: 20,
+ enabled: canSubmit,
+ )
+ : row.isProject
+ ? const Icon(
+ LucideIcons.folderOpen,
+ size: 18,
+ color: Colors.white60,
+ )
+ : row.isMachine
+ ? const Icon(
+ LucideIcons.monitor300,
+ size: 18,
+ color: Colors.white60,
+ )
+ : const SwarmIcon(size: 20, color: Colors.white60),
+ ],
+ ),
+ title: _SearchRowContent(
+ search: search,
+ row: row,
+ terminal: widget.terminal,
+ stacked: stacked,
+ ),
+ trailing: widget.terminal
+ ? (highlighted
+ ? Text(
+ acceptKey ?? '',
+ key: const ValueKey('swarm-row-action'),
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ )
+ : row.shortcut == null
+ ? null
+ : Text(
+ row.shortcut!,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ))
+ : alreadyHere && search.placement == null
+ ? const Text(
+ 'Already added',
+ style: TextStyle(fontSize: 11, color: Colors.white54),
+ )
+ : highlighted
+ ? ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: 170 * scale.scale(11) / 11,
+ ),
+ child: TextButton(
+ key: const ValueKey('swarm-row-action'),
+ onPressed: search.canAccept ? _submit : null,
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white,
+ ),
+ child: SwarmSearchActionLabel(
+ search.actionLabel(row),
+ compact: compactAction,
+ ),
+ ),
+ )
+ : row.shortcut == null
+ ? null
+ : Text(
+ row.shortcut!,
+ style: const TextStyle(fontSize: 12, color: Colors.white60),
+ ),
+ onTap: canSubmit ? () => _submit(row) : null,
+ );
+ _rowWidgets[row.id] = (
+ presentation: presentation,
+ child: MouseRegion(
+ // The pointer moving onto a row, never a row
+ // arriving under a parked pointer: that took the
+ // highlight from the keyboard untouched.
+ onHover: (event) {
+ if (_pointer.moved(event)) {
+ _focusResult(row.id);
+ }
+ },
+ child: BoxRowHighlight(
+ terminal: widget.terminal,
+ highlighted: highlighted,
+ accent: grid.AppPalette.swarmAccent,
+ child: tile,
+ ),
+ ),
+ );
+ if (_rowWidgets.length > 48) {
+ _rowWidgets.remove(_rowWidgets.keys.first);
+ }
+ return FocusTraversalOrder(
+ order: NumericFocusOrder(index.toDouble()),
+ child: _rowWidgets[row.id]!.child,
+ );
+ }
+
final results = Semantics(
+ key: _resultsKey,
container: true,
label: 'Search results',
child: Column(
@@ -409,8 +750,14 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
child: Text(
search.isCommandMode
? 'No matching commands'
+ : search.isHelpMode
+ ? 'No matching modes or help'
+ : search.isProjectMode
+ ? 'No matching projects'
+ : search.isMachineMode
+ ? 'No matching machines'
: search.adding && search.query.isEmpty
- ? 'Create a new harness to start fresh.'
+ ? 'This tab is full (${AppNotifier.maxPanes} panes). Open a new tab to add more.'
: search.adding
? 'No matching harnesses'
: 'No matching results',
@@ -420,156 +767,32 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
),
),
)
- : ListView.builder(
- key: const ValueKey('swarm-search-result-list'),
- padding: const EdgeInsets.all(8),
- controller: _scroll,
- itemCount: search.rows.length,
- itemExtent: _rowHeight,
- itemBuilder: (context, index) {
- final row = search.rows[index];
- final highlighted = index == search.cursor;
- final canSubmit = search.canSubmit(row);
- final alreadyHere = search.alreadyHere(row);
- final presentation = (
- row,
- search.query,
- highlighted,
- canSubmit,
- alreadyHere,
- highlighted
- ? (search.canAccept, search.actionLabel(row))
- : null,
- _rowHeight,
- compactAction,
- scale.scale(11),
- grid.AppTheme.palette.value,
- );
- final previous = _rowWidgets.remove(row.id);
- if (previous?.presentation == presentation) {
- _rowWidgets[row.id] = previous!;
- return previous.child;
- }
- final matches = searchResultMatches(row, terms);
- final tile = ListTile(
- key: ValueKey(row.id),
- minTileHeight: _rowHeight,
- enabled: canSubmit,
- onFocusChange: (focused) {
- if (focused) _focusResult(row.id);
- },
- selected: highlighted,
- selectedColor: Colors.white,
- hoverColor: Colors.transparent,
- selectedTileColor: Colors.white.withValues(
- alpha: .055,
- ),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(12),
- ),
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- leading: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- row.isCommand
- ? const Icon(
- Icons.keyboard_command_key,
- size: 20,
- color: Colors.white60,
- )
- : row.isStore
- ? StoreMark(size: 22, enabled: canSubmit)
- : row.agentId != null ||
- (row.isSwarm &&
- row.members.length == 1)
- ? EngineMark(
- engine: row.engine,
- size: 22,
- enabled: canSubmit,
- )
- : const SwarmIcon(
- size: 22,
- color: Colors.white60,
- ),
- ],
- ),
- title: SearchResultText(
- row.title,
- matches: matches.where((match) => match.title),
- style: const TextStyle(fontSize: 14),
- ),
- subtitle: row.isCommand
- ? null
- : SearchResultText(
- row.detail,
- iconOffset: row.detailBranchOffset ?? 0,
- inlineIcon: row.detailBranchOffset == null
- ? null
- : const Icon(
- LucideIcons.gitBranch300,
- size: 12,
- color: Colors.white60,
- ),
- matches: matches.where(
- (match) => !match.title,
- ),
- style: const TextStyle(
- fontSize: 12,
- color: Colors.white60,
- ),
- ),
- trailing: alreadyHere
- ? const Text(
- 'Already added',
- style: TextStyle(
- fontSize: 11,
- color: Colors.white38,
- ),
- )
- : highlighted
- ? ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: 170 * scale.scale(11) / 11,
- ),
- child: TextButton(
- key: const ValueKey('swarm-row-action'),
- onPressed: search.canAccept
- ? _submit
- : null,
- style: TextButton.styleFrom(
- foregroundColor: Colors.white,
- ),
- child: SwarmSearchActionLabel(
- search.actionLabel(row),
- compact: compactAction,
- ),
- ),
- )
- : row.shortcut == null
- ? null
- : Text(
- row.shortcut!,
- style: const TextStyle(
- fontSize: 12,
- color: Colors.white60,
- ),
- ),
- onTap: canSubmit ? () => _submit(row) : null,
- );
- _rowWidgets[row.id] = (
- presentation: presentation,
- child: MouseRegion(
- onEnter: (_) => _focusResult(row.id),
- child: tile,
+ : Padding(
+ padding: EdgeInsets.only(
+ top: 8,
+ bottom: pinCreate ? 0 : 8,
+ ),
+ child: FocusTraversalOrder(
+ order: const NumericFocusOrder(1),
+ child: FocusTraversalGroup(
+ policy: OrderedTraversalPolicy(),
+ child: ListView.builder(
+ key: const ValueKey('swarm-search-result-list'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ ),
+ controller: _scroll,
+ reverse: search.resultsFromBottom,
+ itemCount:
+ search.rows.length - (pinCreate ? 1 : 0),
+ itemExtent: _rowHeight,
+ itemBuilder: (context, index) => buildRow(
+ context,
+ index + (pinCreate ? 1 : 0),
+ ),
),
- );
- if (_rowWidgets.length > 48) {
- _rowWidgets.remove(_rowWidgets.keys.first);
- }
- return _rowWidgets[row.id]!.child;
- },
+ ),
+ ),
),
),
if (unavailable) ...[
@@ -609,6 +832,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
key: const ValueKey('swarm-search-preview'),
search: search,
compactHeader: constraints.maxWidth < 800,
+ terminal: widget.terminal,
)
: null;
final content = preview == null
@@ -617,9 +841,33 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
? Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- Expanded(flex: 5, child: results),
- const SizedBox(width: 8),
- Expanded(flex: 5, child: preview),
+ // The list is what is being read; the preview confirms it.
+ Expanded(flex: 6, child: results),
+ if (widget.terminal)
+ VerticalDivider(
+ width: 1,
+ thickness: 1,
+ color: Colors.white.withValues(alpha: .16),
+ )
+ else
+ const SizedBox(width: 8),
+ Expanded(flex: 4, child: preview),
+ ],
+ )
+ : search.resultsFromBottom
+ ? Column(
+ children: [
+ Expanded(child: preview),
+ const SizedBox(height: 8),
+ SizedBox(
+ // Reserve whole rows next to the prompt; preview gets the
+ // remaining space above, never between query and matches.
+ height: _bottomListHeight(
+ height - (pinCreate ? _rowHeight + 8 : 0),
+ unavailable,
+ ),
+ child: results,
+ ),
],
)
: Column(
@@ -629,7 +877,28 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
Expanded(flex: 6, child: preview),
],
);
- if (KeymapTheme.of(context) == null) return content;
+ final withAction = pinCreate
+ ? Column(
+ children: [
+ Expanded(child: content),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(8, 0, 8, 8),
+ child: SizedBox(
+ height: _rowHeight,
+ child: buildRow(context, 0),
+ ),
+ ),
+ ],
+ )
+ : content;
+ final sized = widget.fitRows
+ ? SizedBox(height: height, child: withAction)
+ : withAction;
+ final fitted = FocusTraversalGroup(
+ policy: OrderedTraversalPolicy(),
+ child: sized,
+ );
+ if (KeymapTheme.of(context) == null) return fitted;
// The early keymap handler owns these keys across the whole picker.
// If unbound, do not fall through to ListTile's default activation or
// directional focus traversal and silently perform the removed action.
@@ -640,13 +909,129 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
SingleActivator(LogicalKeyboardKey.arrowDown): DoNothingIntent(),
SingleActivator(LogicalKeyboardKey.arrowUp): DoNothingIntent(),
},
- child: content,
+ child: fitted,
);
},
);
}
+
+ double _bottomListHeight(double height, bool unavailable) {
+ final available = (height - 8).clamp(0.0, double.infinity);
+ final chrome = 16.0 + (unavailable ? 48 : 0);
+ final rows = ((available * .6 - chrome) / _rowHeight).floor().clamp(1, 6);
+ return (chrome + rows * _rowHeight).clamp(0.0, available);
+ }
}
+// Typing changes the match text even when the row, its controls, and its focus
+// state stay the same. Listen here so the cached ListTile can keep that state.
+class _SearchRowContent extends StatefulWidget {
+ const _SearchRowContent({
+ required this.search,
+ required this.row,
+ required this.terminal,
+ required this.stacked,
+ });
+
+ final SwarmSearchController search;
+ final SwarmDestination row;
+ final bool terminal;
+ final bool stacked;
+
+ @override
+ State<_SearchRowContent> createState() => _SearchRowContentState();
+}
+
+class _SearchRowContentState extends State<_SearchRowContent> {
+ late (String, bool) _query;
+
+ (String, bool) get _currentQuery =>
+ (widget.search.matchQuery, widget.search.isHelpMode);
+
+ @override
+ void initState() {
+ super.initState();
+ _query = _currentQuery;
+ widget.search.addListener(_changed);
+ }
+
+ @override
+ void didUpdateWidget(_SearchRowContent oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.search != widget.search) {
+ oldWidget.search.removeListener(_changed);
+ widget.search.addListener(_changed);
+ }
+ _query = _currentQuery;
+ }
+
+ void _changed() {
+ final query = _currentQuery;
+ if (_query != query) setState(() => _query = query);
+ }
+
+ @override
+ void dispose() {
+ widget.search.removeListener(_changed);
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final row = widget.row;
+ final matches = searchResultMatches(row, swarmQueryTerms(_query.$1));
+ final title = SearchResultText(
+ row.title,
+ matches: matches.where((match) => match.title),
+ style: widget.terminal ? boxMonoStyle() : const TextStyle(fontSize: 14),
+ );
+ final detailText = widget.terminal
+ ? row.terminalDetail ?? row.detail
+ : row.detail;
+ final detail = widget.terminal && row.promptContext != null
+ ? PromptContextView(
+ contextData: row.promptContext!,
+ matches: matches.where((match) => !match.title),
+ )
+ : (!row.isCommand || _query.$2) && detailText.isNotEmpty
+ ? SearchResultText(
+ detailText,
+ iconOffset: row.detailBranchOffset ?? 0,
+ inlineIcon: widget.terminal || row.detailBranchOffset == null
+ ? null
+ : const Icon(
+ LucideIcons.gitBranch300,
+ size: 12,
+ color: Colors.white60,
+ ),
+ matches: matches.where((match) => !match.title),
+ style: widget.terminal
+ ? boxMonoStyle(size: 12, color: kBoxFaint)
+ : const TextStyle(fontSize: 12, color: Colors.white54),
+ )
+ : null;
+ return widget.stacked
+ ? Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [title, ?detail],
+ )
+ : Row(
+ children: [
+ Flexible(flex: 3, child: title),
+ if (detail != null) ...[
+ const SizedBox(width: 10),
+ Flexible(flex: 4, child: detail),
+ ],
+ ],
+ );
+ }
+}
+
+// Compiled once: this runs in the build of the highlighted row, every arrow key.
+final _returnChord = RegExp(r'^[⌃⌥⇧⌘]*↵$');
+
class SwarmSearchActionLabel extends StatelessWidget {
const SwarmSearchActionLabel(
this.label, {
@@ -681,7 +1066,7 @@ class SwarmSearchActionLabel extends StatelessWidget {
),
if (hint != null) ...[
if (!compact) const SizedBox(width: 8),
- if (RegExp(r'^[⌃⌥⇧⌘]*↵$').hasMatch(hint)) ...[
+ if (_returnChord.hasMatch(hint)) ...[
if (hint.length > 1)
Text(
hint.substring(0, hint.length - 1),
@@ -704,3 +1089,157 @@ class SwarmSearchActionLabel extends StatelessWidget {
);
}
}
+
+/// The box's bottom line: what the keys do here. Read off the live keymap, so
+/// a remapped key shows as the key it now is, and only the actions this
+/// opening of the box can take. A key nobody told you about is a key you never
+/// press; a line in the corner of the eye teaches it without a manual.
+///
+/// Every entry is also a button: [onSubmit], [onAddHere], [onClose] and
+/// [onQuery] are what the keys do, handed in so a click does the same.
+class SwarmSearchHints extends StatelessWidget {
+ const SwarmSearchHints({
+ super.key,
+ required this.search,
+ this.onSubmit,
+ this.onAddHere,
+ this.onClose,
+ this.onQuery,
+ });
+ final SwarmSearchController search;
+ final VoidCallback? onSubmit, onAddHere, onClose;
+
+ /// Put this text in the input: `>` commands, `#` projects, `@` machines, `?` help.
+ final ValueChanged<String>? onQuery;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: search,
+ builder: (context, _) {
+ String? key(
+ String command, [
+ KeymapContext kind = KeymapContext.picker,
+ ]) => effectiveCommandHint(context, command, contextKind: kind);
+ final selected = search.selected;
+ final action = search.actionLabel(selected);
+ // `>` and `?` only mean something at the start of an ordinary search: a
+ // hint for a key that does nothing here is worse than no hint.
+ final prefixes =
+ search.allowsCommands && !search.isCommandMode && !search.isHelpMode;
+ return BoxHintStrip(
+ key: const ValueKey('swarm-search-hints'),
+ hints: [
+ if (search.resultsFromBottom)
+ if ((key('picker.previous'), key('picker.next')) case (
+ final String previous,
+ final String next,
+ ))
+ BoxHint('$previous/$next', 'select'),
+ if (key('picker.accept') case final accept?)
+ BoxHint(
+ accept,
+ selected?.isCreate == true
+ ? 'new harness'
+ // The dock title already names the destination. Keep this
+ // hint short so filtering does not wrap the footer and move
+ // the input above it on narrow windows.
+ : search.placement != null && action == search.primaryAction
+ ? 'open'
+ : action.toLowerCase(),
+ onTap: onSubmit,
+ reserveLabel: search.resultsFromBottom ? 'focus pane' : null,
+ ),
+ if (!search.adding && search.canAdd(selected))
+ if (key('picker.add_here') case final add?)
+ BoxHint(add, 'add here', onTap: onAddHere),
+ if (search.supportsPreview)
+ if (key('picker.toggle_preview') case final toggle?)
+ BoxHint(
+ toggle,
+ search.previewVisible ? 'preview on' : 'preview off',
+ onTap: search.togglePreview,
+ reserveLabel: search.resultsFromBottom ? 'preview off' : null,
+ ),
+ if (prefixes) ...[
+ if (search.commands != null)
+ BoxHint(
+ '>',
+ 'commands',
+ onTap: onQuery == null ? null : () => onQuery!('> '),
+ ),
+ BoxHint(
+ '@',
+ 'machines',
+ onTap: onQuery == null ? null : () => onQuery!('@ '),
+ ),
+ BoxHint(
+ '#',
+ 'projects',
+ onTap: onQuery == null ? null : () => onQuery!('# '),
+ ),
+ ],
+ if (prefixes && search.modes != null && !search.commandsOnly)
+ BoxHint(
+ '?',
+ 'help',
+ onTap: onQuery == null ? null : () => onQuery!('?'),
+ ),
+ if (key('picker.cancel') case final cancel?)
+ BoxHint(
+ cancel,
+ search.canGoBack ? 'back' : 'close',
+ onTap: () {
+ if (search.back()) {
+ onQuery?.call(search.query);
+ } else {
+ onClose?.call();
+ }
+ },
+ ),
+ ],
+ );
+ },
+ );
+}
+
+/// fzf's `4/7`, in the input: how many of what could match do. It answers, at
+/// a glance and without reading the list, whether the query narrowed anything
+/// or the thing is simply not here. Shown only while filtering, so an empty
+/// box stays empty.
+class SwarmSearchCount extends StatelessWidget {
+ const SwarmSearchCount({
+ super.key,
+ required this.search,
+ this.terminal = false,
+ });
+ final SwarmSearchController search;
+ final bool terminal;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: search,
+ builder: (context, _) {
+ final typed = search.matchQuery;
+ // "0 of 71" beside a row that offers to make the thing reads as a bug.
+ if (!terminal && (typed.trim().isEmpty || search.matchCount == 0)) {
+ return const SizedBox.shrink();
+ }
+ return Padding(
+ padding: const EdgeInsets.only(right: 4),
+ child: Text(
+ terminal
+ ? '${search.matchCount}/${search.total}'
+ : '${search.matchCount} of ${search.total}',
+ key: const ValueKey('swarm-search-count'),
+ style: terminal
+ ? boxMonoStyle(size: 11, color: kBoxFaint)
+ : const TextStyle(
+ fontSize: 11,
+ color: Colors.white54,
+ fontFeatures: [FontFeature.tabularFigures()],
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/desktop/lib/widgets/terminal_find_bar.dart b/desktop/lib/widgets/terminal_find_bar.dart
index c155dbde3..7131205ab 100644
--- a/desktop/lib/widgets/terminal_find_bar.dart
+++ b/desktop/lib/widgets/terminal_find_bar.dart
@@ -1,7 +1,10 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import '../terminal/terminal_font_store.dart';
import '../terminal/terminal_search.dart';
+import 'box_chrome.dart';
+import 'pane_menu.dart';
class TerminalFindBar extends StatefulWidget {
const TerminalFindBar({
@@ -39,6 +42,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
);
// Keys can arrive before the widget receives the newly opened search.
TerminalSearch? _activeSearch;
+ VoidCallback? _closeMenu;
@override
void initState() {
@@ -70,6 +74,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
void releaseSearchFocus() {
_activeSearch = null;
_setActive(false);
+ _closeMenu?.call();
}
void _onFocus() {
@@ -105,6 +110,9 @@ class TerminalFindBarState extends State<TerminalFindBar> {
event.logicalKey == LogicalKeyboardKey.escape &&
!keyboard.isShiftPressed;
if (!enter && !escape) return KeyEventResult.ignored;
+ // Enter on a keyboard-focused control activates that control. It steps
+ // through matches only while the query editor owns focus.
+ if (enter && !_focus.hasFocus) return KeyEventResult.ignored;
final composing = _text.value.composing;
if (composing.isValid && !composing.isCollapsed) {
// Let the platform commit/cancel composition without a later shortcut
@@ -121,6 +129,7 @@ class TerminalFindBarState extends State<TerminalFindBar> {
@override
void dispose() {
+ _closeMenu?.call();
_focus.removeListener(_onFocus);
_focus.dispose();
_scope.dispose();
@@ -128,16 +137,77 @@ class TerminalFindBarState extends State<TerminalFindBar> {
super.dispose();
}
+ void _toggleCase() {
+ widget.onQuery(
+ _text.text,
+ !(_activeSearch?.caseSensitive ?? widget.initialCaseSensitive),
+ );
+ _focus.requestFocus();
+ }
+
+ Future<void> _openOptions(BuildContext context) async {
+ final anchor = context.findRenderObject()! as RenderBox;
+ final overlay =
+ Overlay.of(context).context.findRenderObject()! as RenderBox;
+ final rect =
+ anchor.localToGlobal(Offset.zero, ancestor: overlay) & anchor.size;
+ final choice = await showPaneMenu<VoidCallback>(
+ context: context,
+ position: RelativeRect.fromRect(
+ Rect.fromLTWH(rect.left, rect.bottom + 4, rect.width, 0),
+ Offset.zero & overlay.size,
+ ),
+ minWidth: 230,
+ maxWidth: 360,
+ onOpen: (_, close) => _closeMenu = close,
+ onClose: () => _closeMenu = null,
+ children: (close) {
+ Widget option(String label, String hint, VoidCallback action) =>
+ paneMenuItem(
+ onTap: () => close(action),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ vertical: 8,
+ ),
+ child: Row(
+ children: [
+ Expanded(child: Text(label, style: boxMonoStyle(size: 12))),
+ const SizedBox(width: 16),
+ Text(hint, style: boxMonoStyle(size: 11, color: kBoxFaint)),
+ ],
+ ),
+ ),
+ );
+ return [
+ option(
+ 'Match case',
+ _activeSearch?.caseSensitive == true ? 'on' : 'off',
+ _toggleCase,
+ ),
+ if ((_activeSearch?.count ?? 0) > 0) ...[
+ option('Next match', 'enter', () => widget.onStep(1)),
+ option('Previous match', 'shift-enter', () => widget.onStep(-1)),
+ ],
+ ];
+ },
+ );
+ if (choice != null && mounted && _activeSearch != null) {
+ choice();
+ _focus.requestFocus();
+ }
+ }
+
@override
- Widget build(BuildContext context) => FocusScope(
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => _buildBar(context),
+ );
+
+ Widget _buildBar(BuildContext context) => FocusScope(
node: _scope,
onKeyEvent: _onKeyEvent,
- child: Material(
- color: const Color(0xff272727),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
- side: const BorderSide(color: Colors.white24),
- ),
+ child: TerminalBox(
child: Padding(
padding: const EdgeInsets.only(left: 10, right: 4, top: 2, bottom: 2),
child: ListenableBuilder(
@@ -146,32 +216,35 @@ class TerminalFindBarState extends State<TerminalFindBar> {
// editor. Keep its widget stable while the search index refreshes.
child: Expanded(
key: const ValueKey('terminal-find-editor'),
- child: TextField(
+ child: ReadlineKeys(
controller: _text,
- focusNode: _focus,
- autofocus: widget.search != null,
- textAlignVertical: TextAlignVertical.center,
- style: const TextStyle(
- fontSize: 13,
- height: 1,
- color: Colors.white,
- ),
- decoration: const InputDecoration(
- hintText: 'Find in terminal…',
- hintStyle: TextStyle(color: Colors.white54),
- isDense: true,
- isCollapsed: true,
- constraints: BoxConstraints(),
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- filled: false,
- contentPadding: EdgeInsets.zero,
- ),
onChanged: (value) => widget.onQuery(
value,
_activeSearch?.caseSensitive ?? widget.initialCaseSensitive,
),
+ child: TextField(
+ controller: _text,
+ focusNode: _focus,
+ autofocus: widget.search != null,
+ textAlignVertical: TextAlignVertical.center,
+ style: boxMonoStyle().copyWith(height: 1),
+ decoration: const InputDecoration(
+ hintText: 'Find in terminal…',
+ hintStyle: TextStyle(color: Colors.white54),
+ isDense: true,
+ isCollapsed: true,
+ constraints: BoxConstraints(),
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ filled: false,
+ contentPadding: EdgeInsets.zero,
+ ),
+ onChanged: (value) => widget.onQuery(
+ value,
+ _activeSearch?.caseSensitive ?? widget.initialCaseSensitive,
+ ),
+ ),
),
),
builder: (context, editor) {
@@ -211,98 +284,118 @@ class TerminalFindBarState extends State<TerminalFindBar> {
icon: icon,
),
);
- return Row(
- children: [
- if (widget.readOnly) ...[
- const Tooltip(
- message: 'This terminal is read only',
- child: Icon(
- Icons.lock_outline,
- size: 14,
- color: Colors.white54,
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ // Keep room to edit at narrow pane widths and larger text sizes.
+ // The same actions remain available in a small keyboard menu.
+ final compact =
+ constraints.maxWidth <
+ 200 + MediaQuery.textScalerOf(context).scale(120);
+ return Row(
+ children: [
+ if (widget.readOnly) ...[
+ const Tooltip(
+ message: 'This terminal is read only',
+ child: Icon(
+ Icons.lock_outline,
+ size: 14,
+ color: Colors.white54,
+ ),
+ ),
+ const SizedBox(width: 6),
+ ],
+ Padding(
+ padding: const EdgeInsets.only(right: 6),
+ child: ExcludeSemantics(
+ child: Text(
+ '/',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
+ ),
),
- ),
- const SizedBox(width: 6),
- ],
- editor!,
- const SizedBox(width: 6),
- Semantics(
- liveRegion: true,
- label: searching && !hasSnapshot
- ? 'Searching terminal'
- : query.isEmpty
- ? 'Find in terminal'
- : count == 0
- ? 'No matches'
- : 'Match $selected of $count',
- child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 56),
- child: ExcludeSemantics(
- child: Text(
- status,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontSize: 11,
- height: 1,
- color: count == 0 && query.isNotEmpty && !searching
- ? const Color(0xffffb4a9)
- : Colors.white54,
+ editor!,
+ const SizedBox(width: 6),
+ Semantics(
+ liveRegion: true,
+ label: searching && !hasSnapshot
+ ? 'Searching terminal'
+ : query.isEmpty
+ ? 'Find in terminal'
+ : count == 0
+ ? 'No matches'
+ : 'Match $selected of $count',
+ child: ConstrainedBox(
+ constraints: const BoxConstraints(maxWidth: 56),
+ child: ExcludeSemantics(
+ child: Text(
+ status,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ size: 11,
+ color:
+ count == 0 && query.isNotEmpty && !searching
+ ? const Color(0xffffb4a9)
+ : Colors.white54,
+ ).copyWith(height: 1),
+ ),
),
),
),
- ),
- ),
- const SizedBox(width: 4),
- button(
- 'Match case',
- Text(
- 'Aa',
- style: TextStyle(
- fontSize: 12,
- height: 1,
- color: sensitive ? Colors.white : Colors.white54,
- fontWeight: sensitive
- ? FontWeight.w700
- : FontWeight.normal,
+ const SizedBox(width: 4),
+ if (compact)
+ Builder(
+ builder: (context) => button(
+ 'Find options',
+ const Icon(Icons.more_horiz),
+ () => _openOptions(context),
+ ),
+ )
+ else ...[
+ button(
+ 'Match case',
+ Text(
+ 'Aa',
+ style: boxMonoStyle(
+ size: 12,
+ color: sensitive ? Colors.white : Colors.white54,
+ weight: sensitive
+ ? FontWeight.w700
+ : FontWeight.normal,
+ ).copyWith(height: 1),
+ ),
+ _toggleCase,
+ selected: sensitive,
+ ),
+ button(
+ 'Previous match (Shift-Enter)',
+ const Icon(Icons.keyboard_arrow_up),
+ count > 0
+ ? () {
+ widget.onStep(-1);
+ _focus.requestFocus();
+ }
+ : null,
+ ),
+ button(
+ 'Next match (Enter)',
+ const Icon(Icons.keyboard_arrow_down),
+ count > 0
+ ? () {
+ widget.onStep(1);
+ _focus.requestFocus();
+ }
+ : null,
+ ),
+ ],
+ button(
+ 'Close find (Esc)',
+ const Icon(Icons.close),
+ widget.onClose,
),
- ),
- () {
- widget.onQuery(
- _text.text,
- !(_activeSearch?.caseSensitive ??
- widget.initialCaseSensitive),
- );
- _focus.requestFocus();
- },
- selected: sensitive,
- ),
- button(
- 'Previous match (⇧⌘G)',
- const Icon(Icons.keyboard_arrow_up),
- count > 0
- ? () {
- widget.onStep(-1);
- _focus.requestFocus();
- }
- : null,
- ),
- button(
- 'Next match (⌘G)',
- const Icon(Icons.keyboard_arrow_down),
- count > 0
- ? () {
- widget.onStep(1);
- _focus.requestFocus();
- }
- : null,
- ),
- button(
- 'Close find (Esc)',
- const Icon(Icons.close),
- widget.onClose,
- ),
- ],
+ ],
+ );
+ },
);
},
),
diff --git a/desktop/lib/widgets/terminal_name_prompt.dart b/desktop/lib/widgets/terminal_name_prompt.dart
new file mode 100644
index 000000000..7902cf5df
--- /dev/null
+++ b/desktop/lib/widgets/terminal_name_prompt.dart
@@ -0,0 +1,243 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../terminal/terminal_font_store.dart';
+import 'box_chrome.dart';
+import 'terminal_prompt.dart';
+
+/// One rename editor for tabs, agents, and machines. A remote save may outlive
+/// the route; its owner supplies that same future when the prompt is reopened.
+class TerminalNamePrompt extends StatefulWidget {
+ const TerminalNamePrompt({
+ super.key,
+ required this.title,
+ required this.name,
+ required this.fieldKey,
+ required this.fieldLabel,
+ this.detail,
+ this.maxLength,
+ this.save,
+ this.pending,
+ });
+ final String title, name, fieldLabel;
+ final Key fieldKey;
+ final String? detail;
+ final int? maxLength;
+ final Future<String?> Function(String name)? save;
+ final Future<String?>? pending;
+
+ @override
+ State<TerminalNamePrompt> createState() => _TerminalNamePromptState();
+}
+
+class _TerminalNamePromptState extends State<TerminalNamePrompt> {
+ late final _text = TextEditingController(
+ text: widget.name,
+ )..selection = TextSelection(baseOffset: 0, extentOffset: widget.name.length);
+ final _input = FocusNode(debugLabel: 'Rename input');
+ final _announcer = BoxAnnouncer();
+ bool _saving = false;
+ String? _error;
+ bool get _composing =>
+ _text.value.composing.isValid && !_text.value.composing.isCollapsed;
+
+ @override
+ void initState() {
+ super.initState();
+ if (widget.pending case final pending?) {
+ _saving = true;
+ unawaited(_finish(pending, widget.name));
+ }
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && ModalRoute.of(context)?.isCurrent != false) {
+ _input.requestFocus();
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ _input.dispose();
+ super.dispose();
+ }
+
+ void _close() {
+ if (!_composing) Navigator.pop(context);
+ }
+
+ void _changed(String _) => setState(() => _error = null);
+
+ void _failed(String error) {
+ setState(() {
+ _saving = false;
+ _error = error;
+ });
+ _input.requestFocus();
+ _announcer.row(context, error);
+ }
+
+ void _accept() {
+ if (_input.hasFocus) {
+ _save();
+ } else {
+ activatePromptControl();
+ }
+ }
+
+ void _save() {
+ if (_saving || _composing) return;
+ final name = _text.text.trim();
+ if (name.isEmpty) return _failed('Name cannot be empty');
+ if (widget.maxLength case final limit?) {
+ if (name.characters.length > limit) {
+ return _failed('Use at most $limit characters.');
+ }
+ }
+ final save = widget.save;
+ if (save == null) {
+ Navigator.pop(context, name);
+ return;
+ }
+ setState(() {
+ _saving = true;
+ _error = null;
+ });
+ unawaited(_finish(Future.sync(() => save(name)), name));
+ }
+
+ Future<void> _finish(Future<String?> request, String name) async {
+ String? error;
+ try {
+ error = await request;
+ } catch (_) {
+ error = 'Could not save the name. Try again.';
+ }
+ if (!mounted) return;
+ if (error == null) {
+ Navigator.pop(context, name);
+ } else {
+ _failed(error);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: terminalFontStore,
+ builder: (context, _) => TerminalPromptKeys(
+ inputFocus: _input,
+ composing: () => _composing,
+ cancel: _close,
+ accept: _accept,
+ child: TerminalPrompt(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Flexible(
+ child: SingleChildScrollView(
+ padding: const EdgeInsets.fromLTRB(14, 12, 14, 10),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ widget.title,
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ if (widget.detail case final detail?) ...[
+ const SizedBox(height: 6),
+ Text(
+ detail,
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ const SizedBox(height: 10),
+ ReadlineKeys(
+ controller: _text,
+ enabled: !_saving,
+ onChanged: _changed,
+ child: Semantics(
+ label: widget.fieldLabel,
+ child: TextField(
+ key: widget.fieldKey,
+ controller: _text,
+ focusNode: _input,
+ readOnly: _saving,
+ maxLength: widget.maxLength,
+ style: boxMonoStyle(),
+ textAlignVertical: TextAlignVertical.center,
+ textInputAction: TextInputAction.done,
+ decoration: InputDecoration(
+ hintText: widget.fieldLabel,
+ hintStyle: boxMonoStyle(color: kBoxFaint),
+ counterText: '',
+ suffixText:
+ widget.maxLength != null &&
+ _text.text.characters.length >=
+ widget.maxLength! - 10
+ ? '${_text.text.characters.length}/${widget.maxLength}'
+ : null,
+ suffixStyle: boxMonoStyle(
+ size: 11,
+ color: kBoxFaint,
+ ),
+ isDense: true,
+ filled: false,
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ prefixIcon: Padding(
+ padding: const EdgeInsets.only(right: 10),
+ child: Center(
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(
+ 'name >',
+ style: boxMonoStyle(color: Colors.white70),
+ ),
+ ),
+ ),
+ prefixIconConstraints: const BoxConstraints(
+ minHeight: 38,
+ ),
+ contentPadding: EdgeInsets.zero,
+ ),
+ onChanged: _changed,
+ onEditingComplete: () {},
+ onSubmitted: (_) => _save(),
+ ),
+ ),
+ ),
+ if (_saving)
+ Text(
+ 'Saving continues if you close this prompt.',
+ style: boxMonoStyle(size: 11, color: kBoxFaint),
+ ),
+ ],
+ ),
+ ),
+ ),
+ BoxHintStrip(
+ message: _error ?? (_saving ? 'Saving name…' : null),
+ isError: _error != null,
+ hints: [
+ if (!_saving)
+ BoxHint(
+ terminalPromptHint(context, 'picker.accept', 'enter'),
+ 'save',
+ onTap: _save,
+ ),
+ BoxHint(
+ terminalPromptHint(context, 'picker.cancel', 'esc'),
+ 'close',
+ onTap: _close,
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 2065d60aa..b6adf2610 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -1,3 +1,5 @@
+import '../shared/theme/prompt_style.dart';
+import 'prompt_context.dart';
import '../sharing/share_harness_dialog.dart';
import 'dart:async';
@@ -33,6 +35,7 @@ import '../terminal/terminal_viewport.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../theme/app_theme.dart';
import 'engine_identity.dart';
+import 'box_chrome.dart';
import 'grid_model_picker.dart';
import 'pane_header_actions.dart';
@@ -959,54 +962,82 @@ class _TerminalPanelState extends State<TerminalPanel>
/// reserved for a genuinely REMOTE pane, whose engine reads a DIFFERENT
/// clipboard than this one — see `MachineState.isLocalMachine`.
Future<void> _paste() async {
- if (widget.readOnly || !widget.session.acceptsInput) return;
- final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;
+ final target = widget.session;
+ final streamId = target.streamId;
+ bool stillOwnsPaste() =>
+ mounted &&
+ identical(widget.session, target) &&
+ !widget.readOnly &&
+ target.acceptsInput &&
+ target.streamId == streamId;
+ if (!stillOwnsPaste()) return;
+
+ ClipboardData? data;
+ try {
+ data = await Clipboard.getData(Clipboard.kTextPlain);
+ } on PlatformException {
+ if (mounted && stillOwnsPaste()) {
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ const SnackBar(
+ content: Text('Could not read the clipboard. Try Paste again.'),
+ ),
+ );
+ }
+ return;
+ }
+ // Reading the clipboard crosses a platform boundary. The pane may have
+ // changed agents, become read only, closed, or reconnected in that time.
+ if (!stillOwnsPaste()) return;
+ final text = data?.text;
if (text != null && text.isNotEmpty) {
- // A binary TerminalBinaryKind.paste frame rides the same AEAD channel as every other terminal
- // byte, so this works identically for a local or a relayed machine — see pasteText's doc. Only
- // the CLI's own version gates it: an older daemon never advertises the capability.
- final machine = widget.notifier.stateOf(widget.session.machineId);
+ final machine = widget.notifier.stateOf(target.machineId);
+ _controller.clearSelection();
if (machine != null && machine.terminalPasteRawAvailable) {
- await widget.session.pasteText(text);
+ await target.pasteText(text);
} else {
- widget.session.terminal.paste(text);
+ target.terminal.paste(text);
}
return;
}
- final machine = widget.notifier.stateOf(widget.session.machineId);
+ // An empty clipboard has no input for a shell. Ctrl-V there means
+ // quoted-insert, so the agent image-paste fallback would change its mode.
+ if (isTerminalEngine(target.engineId)) return;
+ final machine = widget.notifier.stateOf(target.machineId);
if (machine != null &&
!machine.isLocalMachine &&
machine.terminalImagePasteAvailable) {
final imageBytes = await NativeClipboard.readImagePng();
+ if (!stillOwnsPaste()) return;
if (imageBytes != null &&
imageBytes.isNotEmpty &&
imageBytes.length <= terminalLocalImagePasteMaxPayloadBytes) {
- await widget.session.pasteImage(imageBytes);
+ await target.pasteImage(imageBytes);
return;
}
}
- widget.session.terminal.keyInput(TerminalKey.keyV, ctrl: true);
+ target.terminal.keyInput(TerminalKey.keyV, ctrl: true);
}
- /// ⌘V (Ctrl+V off Apple) — taken from xterm so the fallthrough above applies.
- ///
- /// xterm binds paste itself, but only ever to its text-only action. `onKeyEvent`
- /// is the one hook that runs BEFORE its shortcut map (terminal_view.dart), so
- /// this is where the binding has to be replaced rather than added.
+ /// Take the platform's exact paste chord before xterm's text-only action,
+ /// so agent image paste follows the same path. Linux reserves Ctrl-V for
+ /// the terminal program and uses Ctrl-Shift-V for its clipboard.
KeyEventResult _onTerminalKey(FocusNode node, KeyEvent event) {
- if (event is! KeyDownEvent) return KeyEventResult.ignored;
- if (event.logicalKey != LogicalKeyboardKey.keyV) {
+ if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyV) {
return KeyEventResult.ignored;
}
final keyboard = HardwareKeyboard.instance;
- if (keyboard.isShiftPressed) {
- return KeyEventResult.ignored; // ⇧⌘V is a different verb
- }
-
+ if (keyboard.isAltPressed) return KeyEventResult.ignored;
final apple =
defaultTargetPlatform == TargetPlatform.macOS ||
defaultTargetPlatform == TargetPlatform.iOS;
- final pasting = apple ? keyboard.isMetaPressed : keyboard.isControlPressed;
+ final pasting = apple
+ ? keyboard.isMetaPressed &&
+ !keyboard.isControlPressed &&
+ !keyboard.isShiftPressed
+ : keyboard.isControlPressed &&
+ !keyboard.isMetaPressed &&
+ keyboard.isShiftPressed ==
+ (defaultTargetPlatform == TargetPlatform.linux);
if (!pasting) return KeyEventResult.ignored;
unawaited(_paste());
return KeyEventResult.handled;
@@ -1214,8 +1245,7 @@ class _TerminalPanelState extends State<TerminalPanel>
session.agentName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 13,
+ style: boxMonoStyle(
color: Colors.white70,
),
),
@@ -1388,6 +1418,7 @@ class _TerminalPanelState extends State<TerminalPanel>
theme: Theme.of(context),
brightness: grid.AppTheme.brightness.value,
fontFamily: AppFonts.sans,
+ terminalFont: terminalFontStore.value,
notifier: widget.notifier,
session: session,
name: session.agentName,
@@ -1571,7 +1602,11 @@ class _TerminalHeader extends StatelessWidget {
final showModelPicker =
status == null && !readOnly && modelPickerSupports(session.engineId);
final pickerWidth = showModelPicker ? 72.0 : 0.0;
- final actionsWidth = (remoteComposer == null ? 118.0 : 148.0) + pickerWidth;
+ final actionsWidth =
+ (remoteComposer == null ? 148.0 : 178.0) +
+ pickerWidth +
+ (onFork == null ? 0 : 30) +
+ (agent?.viewerUrl == null && agent?.viewerError == null ? 0 : 30);
final folder =
project?.cwd
.split(RegExp(r'[/\\]'))
@@ -1581,285 +1616,265 @@ class _TerminalHeader extends StatelessWidget {
// A fork says so first: "forked from X" is the one fact about this pane
// that the folder and the branch — shared with its source — cannot tell.
final forkedFrom = agent?.forkedFrom;
- final details = [
- if (forkedFrom != null) 'forked from ${forkedFrom.name}',
- if (folder?.isNotEmpty == true) folder!,
- if (project?.branch?.trim().isNotEmpty == true) project!.branch!,
- machineName,
- ];
- final forkIndex = forkedFrom != null ? 0 : null;
- final branchIndex = project?.branch?.trim().isNotEmpty == true
- ? (forkedFrom != null ? 1 : 0) + (folder?.isNotEmpty == true ? 1 : 0)
- : null;
final strip = PaneHeaderHover(
child: SizedBox(
height: compact ? 38 : 46,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: _stripPadding),
child: LayoutBuilder(
- builder: (context, constraints) => Row(
- children: [
- if (agent != null)
- EngineMark.forAgent(agent, size: 17)
- else
- EngineMark(engine: session.engineId, size: 17),
- // Icon and name, the same as every other pane (owner,
- // 2026-09-15): a harness agent is its harness here, and the
- // engine it runs on is the dialog's and the tooltip's to say.
- const SizedBox(width: 10),
- Expanded(
- child: Row(
- children: [
- Flexible(
- child: Tooltip(
- message: identityDetail,
- waitDuration: const Duration(milliseconds: 700),
- child: GestureDetector(
- behavior: HitTestBehavior.opaque,
- onDoubleTap: () => unawaited(
- showAgentRenameDialog(
- context,
- notifier,
- session.machineId,
- session.agentId,
- session.agentName,
+ builder: (context, constraints) {
+ final scale = MediaQuery.textScalerOf(context).scale(13) / 13;
+ final narrow = constraints.maxWidth < 560 * math.max(1, scale);
+ final rightWidth = narrow
+ ? math.max(
+ showModelPicker ? 60.0 : 28.0,
+ constraints.maxWidth * .36,
+ )
+ : math.max(actionsWidth, constraints.maxWidth * .55);
+ return Row(
+ children: [
+ if (agent != null)
+ EngineMark.forAgent(agent, size: 17)
+ else
+ EngineMark(engine: session.engineId, size: 17),
+ // Icon and name, the same as every other pane (owner,
+ // 2026-09-15): a harness agent is its harness here, and the
+ // engine it runs on is the dialog's and the tooltip's to say.
+ const SizedBox(width: 10),
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ child: Tooltip(
+ message: identityDetail,
+ waitDuration: const Duration(milliseconds: 700),
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onDoubleTap: () => unawaited(
+ showAgentRenameDialog(
+ context,
+ notifier,
+ session.machineId,
+ session.agentId,
+ session.agentName,
+ ),
),
- ),
- child: Text(
- session.agentName,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- color: AppColors.text,
- fontFamily: AppFonts.sans,
- fontSize: 13,
- fontWeight: FontWeight.w600,
+ child: Text(
+ session.agentName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ color: AppColors.text,
+ size: 12,
+ weight: FontWeight.w600,
+ ),
),
),
),
),
- ),
- const SizedBox(width: 8),
- if (status != null)
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: math.max(
- 0,
- math.min(
- constraints.maxWidth * .22,
- constraints.maxWidth - actionsWidth - 110,
+ if (status != null || !compact)
+ const SizedBox(width: 8),
+ if (status != null && narrow)
+ Tooltip(
+ message: '${status.label}: ${status.detail}',
+ child: IconButton(
+ tooltip: status.label,
+ onPressed: canReconnect
+ ? () => notifier.selectAgent(
+ session.machineId,
+ session.agentId,
+ )
+ : null,
+ icon: Icon(status.icon, size: 14),
+ style: IconButton.styleFrom(
+ foregroundColor: color,
+ disabledForegroundColor: color,
+ fixedSize: const Size(28, 28),
+ minimumSize: const Size(28, 28),
+ padding: EdgeInsets.zero,
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
- ),
- child: Align(
- alignment: Alignment.centerLeft,
- child: Tooltip(
- message: status.detail,
- child: TextButton(
- onPressed: canReconnect
- ? () => notifier.selectAgent(
- session.machineId,
- session.agentId,
- )
- : null,
- style: TextButton.styleFrom(
- foregroundColor: color,
- disabledForegroundColor: AppColors.textSoft,
- minimumSize: Size.zero,
- tapTargetSize:
- MaterialTapTargetSize.shrinkWrap,
- padding: const EdgeInsets.symmetric(
- horizontal: 6,
- vertical: 4,
- ),
+ )
+ else if (status != null)
+ ConstrainedBox(
+ constraints: BoxConstraints(
+ maxWidth: math.max(
+ 0,
+ math.min(
+ constraints.maxWidth * .22,
+ constraints.maxWidth - actionsWidth - 110,
),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- Icon(status.icon, size: 14),
- const SizedBox(width: 6),
- Flexible(
- child: Text(
- status.label,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 11),
- ),
+ ),
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Tooltip(
+ message: status.detail,
+ child: TextButton(
+ onPressed: canReconnect
+ ? () => notifier.selectAgent(
+ session.machineId,
+ session.agentId,
+ )
+ : null,
+ style: TextButton.styleFrom(
+ foregroundColor: color,
+ disabledForegroundColor: AppColors.textSoft,
+ minimumSize: Size.zero,
+ tapTargetSize:
+ MaterialTapTargetSize.shrinkWrap,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 6,
+ vertical: 4,
),
- ],
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Icon(status.icon, size: 14),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ status.label,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11),
+ ),
+ ),
+ ],
+ ),
),
),
),
+ )
+ else if (!compact)
+ Padding(
+ padding: const EdgeInsets.all(4),
+ child: Icon(Icons.circle, size: 8, color: color),
),
- )
- else if (!compact)
- Padding(
- padding: const EdgeInsets.all(4),
- child: Icon(Icons.circle, size: 8, color: color),
- ),
- ],
- ),
- ),
- const SizedBox(width: 8),
- // Which of the three paths carries this pane's bytes. Absent for a local machine's own
- // terminal, which has no such distinction and so gets no badge.
- //
- // The wire word and the word a person reads differ for the middle state, deliberately:
- // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to
- // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original
- // meaning — the backend WebSocket — so an older CLI is never mislabelled.
- if (!compact && session.linkMode != null)
- Padding(
- padding: const EdgeInsets.symmetric(horizontal: 2),
- child: _LinkModeMark(mode: session.linkMode!),
- ),
- ConstrainedBox(
- constraints: BoxConstraints(
- maxWidth: math.max(
- actionsWidth,
- constraints.maxWidth * .55,
+ ],
),
),
- child: PaneHeaderActions(
- // Where this agent runs, with the controls rather than beside the name — the
- // header has room for one of the two, and this is the half you only read while
- // reaching for it. Absent while a notice is showing: a header asking to
- // reconnect is not the moment to offer a menu.
- modelPicker: showModelPicker
- ? GridModelPicker(
- notifier: notifier,
- machineId: session.machineId,
- currentModel: agent?.gridModel,
- webSearch: agent?.gridWebSearch,
- engineLabel: session.engineId,
- onSelected: (model) => unawaited(
- notifier.retargetAgentToGridModel(
- session.machineId,
- session.agentId,
- model.id,
- gridName: model.grid,
- ),
- ),
- onUseOwnLogin: () => unawaited(
- notifier.clearAgentGrid(
- session.machineId,
- session.agentId,
- ),
- ),
- // The pane's own context, because the door opens New Agent — and
- // the pane's own MACHINE, because a picker on a remote agent's pane
- // is asking about the models that computer can serve, not this one's.
- onRunLocalModel: () => unawaited(
- notifier.runLocalModel(
- context,
- machineId: session.machineId,
+ const SizedBox(width: 8),
+ // Which of the three paths carries this pane's bytes. Absent for a local machine's own
+ // terminal, which has no such distinction and so gets no badge.
+ //
+ // The wire word and the word a person reads differ for the middle state, deliberately:
+ // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to
+ // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original
+ // meaning — the backend WebSocket — so an older CLI is never mislabelled.
+ if (!compact && !narrow && session.linkMode != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 2),
+ child: _LinkModeMark(mode: session.linkMode!),
+ ),
+ ConstrainedBox(
+ constraints: BoxConstraints(maxWidth: rightWidth),
+ child: PaneHeaderActions(
+ compact: narrow,
+ // Where this agent runs, with the controls rather than beside the name — the
+ // header has room for one of the two, and this is the half you only read while
+ // reaching for it. Absent while a notice is showing: a header asking to
+ // reconnect is not the moment to offer a menu.
+ modelPicker: showModelPicker
+ ? GridModelPicker(
+ compact: narrow,
+ notifier: notifier,
+ machineId: session.machineId,
+ currentModel: agent?.gridModel,
+ webSearch: agent?.gridWebSearch,
+ engineLabel: session.engineId,
+ onSelected: (model) => unawaited(
+ notifier.retargetAgentToGridModel(
+ session.machineId,
+ session.agentId,
+ model.id,
+ gridName: model.grid,
+ ),
),
- ),
- )
- : null,
- onShare:
- readOnly ||
- notifier
- .stateOf(session.machineId)
- ?.machine
- .isShared ==
- true
- ? null
- : () => showShareHarnessDialog(
- context,
- notifier,
- session.machineId,
- session.agentId,
- session.agentName,
- ),
- zoomed: zoomed,
- onZoom: onToggleZoom,
- onRestart: onRestart,
- onFork: onFork,
- onDelete: onDelete,
- onClose: onClose,
- terminal: isTerminalEngine(session.engineId),
- onToggleComposer: remoteComposer,
- composerVisible: composerVisible,
- // A harness agent's viewer, shown or hidden from the
- // pane it belongs to.
- onToggleViewer:
- agent?.viewerUrl == null && agent?.viewerError == null
- ? null
- : () => notifier.toggleViewerPane(
- session.machineId,
- agent!.id,
- ),
- viewerVisible:
- agent != null &&
- notifier.viewerPaneShown(session.machineId, agent.id),
- viewerColor: agent == null
- ? null
- : agentIdentity(agent).color,
- details: Tooltip(
- message: [
- if (forkedFrom != null)
- 'Forked from ${forkedFrom.name}',
- if (project != null) project.cwd,
- if (project?.branch?.isNotEmpty == true)
- 'Branch: ${project!.branch}',
- machineName,
- ].join('\n'),
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- for (var i = 0; i < details.length; i++) ...[
- if (i > 0)
- Text(
- ' • ',
- style: TextStyle(
- fontSize: 10,
- color: AppColors.mutedStrong,
+ onUseOwnLogin: () => unawaited(
+ notifier.clearAgentGrid(
+ session.machineId,
+ session.agentId,
),
),
- Flexible(
- child: Row(
- mainAxisSize: MainAxisSize.min,
- children: [
- if (i == branchIndex) ...[
- Icon(
- LucideIcons.gitBranch300,
- size: 12,
- color: AppColors.mutedStrong,
- ),
- const SizedBox(width: 4),
- ],
- if (i == forkIndex) ...[
- Icon(
- LucideIcons.gitFork300,
- size: 12,
- color: AppColors.mutedStrong,
- ),
- const SizedBox(width: 4),
- ],
- Flexible(
- child: Text(
- details[i],
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: TextStyle(
- fontFamily: AppFonts.sans,
- fontSize: 12,
- color: AppColors.mutedStrong,
- ),
- ),
- ),
- ],
+ // The pane's own context, because the door opens New Agent — and
+ // the pane's own MACHINE, because a picker on a remote agent's pane
+ // is asking about the models that computer can serve, not this one's.
+ onRunLocalModel: () => unawaited(
+ notifier.runLocalModel(
+ context,
+ machineId: session.machineId,
+ ),
),
+ )
+ : null,
+ onShare:
+ readOnly ||
+ notifier
+ .stateOf(session.machineId)
+ ?.machine
+ .isShared ==
+ true
+ ? null
+ : () => showShareHarnessDialog(
+ context,
+ notifier,
+ session.machineId,
+ session.agentId,
+ session.agentName,
),
- ],
- ],
+ zoomed: zoomed,
+ onZoom: onToggleZoom,
+ onRestart: onRestart,
+ onFork: onFork,
+ onDelete: onDelete,
+ onClose: onClose,
+ terminal: isTerminalEngine(session.engineId),
+ onToggleComposer: remoteComposer,
+ composerVisible: composerVisible,
+ // A harness agent's viewer, shown or hidden from the
+ // pane it belongs to.
+ onToggleViewer:
+ agent?.viewerUrl == null && agent?.viewerError == null
+ ? null
+ : () => notifier.toggleViewerPane(
+ session.machineId,
+ agent!.id,
+ ),
+ viewerVisible:
+ agent != null &&
+ notifier.viewerPaneShown(session.machineId, agent.id),
+ viewerColor: agent == null
+ ? null
+ : agentIdentity(agent).color,
+ details: Tooltip(
+ message: [
+ if (forkedFrom != null)
+ 'Forked from ${forkedFrom.name}',
+ if (project != null) project.cwd,
+ if (project?.branch?.isNotEmpty == true)
+ 'Branch: ${project!.branch}',
+ machineName,
+ ].join('\n'),
+ child: PromptContextView(
+ size: narrow ? 11 : 12,
+ contextData: PromptContext(
+ machine: machineName,
+ project: narrow ? null : folder,
+ branch: narrow ? null : project?.branch,
+ leading: !narrow && forkedFrom != null
+ ? 'forked from ${forkedFrom.name}'
+ : null,
+ ),
+ ),
),
),
),
- ),
- ],
- ),
+ ],
+ );
+ },
),
),
),
diff --git a/desktop/lib/widgets/terminal_prompt.dart b/desktop/lib/widgets/terminal_prompt.dart
new file mode 100644
index 000000000..2aa7de7c0
--- /dev/null
+++ b/desktop/lib/widgets/terminal_prompt.dart
@@ -0,0 +1,250 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_commands.dart' show describeKeyBinding;
+import 'box_chrome.dart';
+
+/// Dialog routes preserve the workspace's live keymap and use the shared dark
+/// backdrop. Callers hide a parent prompt while a nested route is open.
+Future<T?> showTerminalPrompt<T>(
+ BuildContext context, {
+ required WidgetBuilder builder,
+ AppKeymap? keymap,
+}) {
+ final active = keymap ?? KeymapTheme.of(context, listen: false);
+ return showAppDialog<T>(
+ context: context,
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ builder: (context) => active == null
+ ? builder(context)
+ : KeymapProvider(
+ keymap: active,
+ child: Builder(builder: builder),
+ ),
+ );
+}
+
+String terminalPromptHint(
+ BuildContext context,
+ String command,
+ String fallback, {
+ KeymapContext contextKind = KeymapContext.picker,
+}) {
+ final map = KeymapTheme.of(context);
+ if (map == null) return fallback;
+ final bindings = map.bindings(command, context: contextKind).toList();
+ final binding =
+ bindings.where((binding) => binding.custom).firstOrNull ??
+ (command == 'picker.refresh' &&
+ Theme.of(context).platform != TargetPlatform.macOS
+ ? bindings
+ .where(
+ (binding) =>
+ binding.keys.length == 1 && binding.keys.first.control,
+ )
+ .firstOrNull
+ : null) ??
+ bindings.firstOrNull;
+ return binding == null ? 'click' : describeKeyBinding(binding);
+}
+
+void activatePromptControl() {
+ if (FocusManager.instance.primaryFocus?.context case final context?) {
+ Actions.maybeInvoke(context, const ActivateIntent());
+ }
+}
+
+/// Picker keys belong to the focused prompt, including custom bindings. Plain
+/// input remains text; Enter on a focused button activates that button.
+class TerminalPromptKeys extends StatelessWidget {
+ const TerminalPromptKeys({
+ super.key,
+ required this.child,
+ required this.cancel,
+ this.accept,
+ this.submit,
+ this.next,
+ this.previous,
+ this.pageDown,
+ this.pageUp,
+ this.refresh,
+ this.composing,
+ this.inputFocus,
+ this.focusNode,
+ });
+ final Widget child;
+ final VoidCallback cancel;
+ final VoidCallback? accept, submit, next, previous, pageDown, pageUp, refresh;
+ final bool Function()? composing;
+ final FocusNode? inputFocus;
+ final FocusNode? focusNode;
+
+ void _accept() => (accept ?? activatePromptControl)();
+ void _next() =>
+ (next ?? () => FocusManager.instance.primaryFocus?.nextFocus())();
+ void _previous() =>
+ (previous ?? () => FocusManager.instance.primaryFocus?.previousFocus())();
+
+ KeyEventResult _key(BuildContext context, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final enter =
+ event.logicalKey == LogicalKeyboardKey.enter ||
+ event.logicalKey == LogicalKeyboardKey.numpadEnter;
+ final escape = event.logicalKey == LogicalKeyboardKey.escape;
+ if (composing?.call() == true) {
+ return enter || escape
+ ? KeyEventResult.skipRemainingHandlers
+ : KeyEventResult.ignored;
+ }
+ if (KeymapTheme.of(context, listen: false) != null) {
+ // The TextField must not submit through its native fallback when Enter
+ // was deliberately unbound. Buttons keep their normal activation keys.
+ return enter && inputFocus?.hasFocus == true
+ ? KeyEventResult.handled
+ : KeyEventResult.ignored;
+ }
+ final keys = HardwareKeyboard.instance;
+ if (keys.isAltPressed || keys.isShiftPressed) return KeyEventResult.ignored;
+ if (keys.isControlPressed && !keys.isMetaPressed) {
+ if ([
+ LogicalKeyboardKey.keyC,
+ LogicalKeyboardKey.keyG,
+ LogicalKeyboardKey.bracketLeft,
+ ].contains(event.logicalKey)) {
+ if (composing?.call() == true) {
+ return KeyEventResult.skipRemainingHandlers;
+ }
+ cancel();
+ return KeyEventResult.handled;
+ }
+ if ([
+ LogicalKeyboardKey.keyN,
+ LogicalKeyboardKey.keyJ,
+ ].contains(event.logicalKey)) {
+ _next();
+ return KeyEventResult.handled;
+ }
+ if ([
+ LogicalKeyboardKey.keyP,
+ LogicalKeyboardKey.keyK,
+ ].contains(event.logicalKey)) {
+ _previous();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.keyM) {
+ if (composing?.call() != true && event is KeyDownEvent) _accept();
+ return KeyEventResult.handled;
+ }
+ }
+ if (keys.isMetaPressed || keys.isControlPressed) {
+ final refreshModifier = Theme.of(context).platform == TargetPlatform.macOS
+ ? keys.isMetaPressed
+ : keys.isControlPressed;
+ if (refresh != null &&
+ refreshModifier &&
+ event.logicalKey == LogicalKeyboardKey.keyR) {
+ refresh!();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+ if (escape) {
+ cancel();
+ return KeyEventResult.handled;
+ }
+ if (enter && inputFocus?.hasFocus == true) {
+ if (event is KeyDownEvent) _accept();
+ return KeyEventResult.handled;
+ }
+ final action = switch (event.logicalKey) {
+ LogicalKeyboardKey.arrowDown => next,
+ LogicalKeyboardKey.arrowUp => previous,
+ LogicalKeyboardKey.pageDown => pageDown,
+ LogicalKeyboardKey.pageUp => pageUp,
+ _ => null,
+ };
+ if (action != null) {
+ action();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final focused = Focus(
+ focusNode: focusNode,
+ autofocus: true,
+ onKeyEvent: (_, event) => _key(context, event),
+ child: child,
+ );
+ if (KeymapTheme.of(context) == null) return focused;
+ return KeymapRegion(
+ contextKind: KeymapContext.picker,
+ composing: composing,
+ actions: {
+ 'picker.accept': _accept,
+ 'picker.add_here': submit ?? _accept,
+ 'picker.cancel': cancel,
+ 'picker.next': _next,
+ 'picker.previous': _previous,
+ 'picker.complete': () =>
+ FocusManager.instance.primaryFocus?.nextFocus(),
+ 'picker.complete_back': () =>
+ FocusManager.instance.primaryFocus?.previousFocus(),
+ 'picker.preview_page_down': ?pageDown,
+ 'picker.preview_page_up': ?pageUp,
+ 'picker.refresh': ?refresh,
+ },
+ child: Actions(
+ actions: {
+ DismissIntent: CallbackAction<DismissIntent>(onInvoke: (_) => null),
+ },
+ child: focused,
+ ),
+ );
+ }
+}
+
+class TerminalPrompt extends StatelessWidget {
+ const TerminalPrompt({super.key, required this.child, this.width = 660});
+ final Widget child;
+ final double width;
+ @override
+ Widget build(BuildContext context) => Dialog(
+ alignment: Alignment.topCenter,
+ insetPadding: const EdgeInsets.fromLTRB(16, 56, 16, 18),
+ elevation: 0,
+ backgroundColor: Colors.transparent,
+ child: SizedBox(
+ width: width,
+ child: TerminalBox(child: child),
+ ),
+ );
+}
+
+Widget terminalPromptButton(
+ String label,
+ VoidCallback? onPressed, {
+ Key? key,
+ FocusNode? focusNode,
+ bool danger = false,
+}) => TextButton(
+ key: key,
+ focusNode: focusNode,
+ onPressed: onPressed,
+ style: TextButton.styleFrom(
+ foregroundColor: danger ? Colors.orangeAccent : Colors.white70,
+ textStyle: boxMonoStyle(size: 12),
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
+ minimumSize: const Size(0, 30),
+ tapTargetSize: MaterialTapTargetSize.shrinkWrap,
+ ),
+ child: Text(label),
+);
diff --git a/desktop/lib/widgets/update_notice.dart b/desktop/lib/widgets/update_notice.dart
index a8a7d44f1..44dde40be 100644
--- a/desktop/lib/widgets/update_notice.dart
+++ b/desktop/lib/widgets/update_notice.dart
@@ -157,8 +157,9 @@ class UpdateNotice extends StatelessWidget {
key: const Key('retry-update-button'),
label: 'Try again',
kind: _ActionKind.ghost,
- onPressed: () =>
- unawaited(notifier.installAvailableUpdate()),
+ onPressed: () => unawaited(
+ notifier.installAvailableUpdate(update: update),
+ ),
),
] else ...[
_NoticeAction(
@@ -166,7 +167,8 @@ class UpdateNotice extends StatelessWidget {
label: 'Skip this version',
onPressed: installing
? null
- : notifier.skipAvailableUpdate,
+ : () =>
+ notifier.skipAvailableUpdate(update: update),
),
const SizedBox(width: 6),
_NoticeAction(
@@ -175,8 +177,9 @@ class UpdateNotice extends StatelessWidget {
kind: _ActionKind.primary,
onPressed: installing
? null
- : () =>
- unawaited(notifier.installAvailableUpdate()),
+ : () => unawaited(
+ notifier.installAvailableUpdate(update: update),
+ ),
),
],
],
@@ -242,6 +245,8 @@ class _NoticeAction extends StatelessWidget {
: BorderSide.none,
),
textStyle: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontFamilyFallback: grid.AppFont.sansFallback,
fontSize: 12,
fontWeight: primary ? grid.AppFont.semibold : grid.AppFont.regular,
),
@@ -251,88 +256,156 @@ class _NoticeAction extends StatelessWidget {
}
}
-/// Opens the result of a manual check from the Harness menu. It never downloads
+final _manualChecks = Expando<Future<void>>('manual desktop update checks');
+
+/// The native menu and About share one check and one result dialog per window.
+/// Invoking the other entry while a check is pending cannot stack two dialogs.
+Future<void> checkForUpdatesAndShowResult(
+ BuildContext context,
+ AppNotifier notifier,
+) {
+ final navigator = Navigator.of(context, rootNavigator: true);
+ final pending = _manualChecks[navigator];
+ if (pending != null) return pending;
+ // Schedule after assigning ownership, before notifying check-state listeners.
+ final operation = Future<void>(() async {
+ final result = await notifier.checkForUpdates();
+ if (context.mounted) {
+ await showUpdateCheckDialog(context, notifier, result);
+ }
+ }).whenComplete(() => _manualChecks[navigator] = null);
+ _manualChecks[navigator] = operation;
+ return operation;
+}
+
+/// Opens the result of a manual check. It never downloads
/// a release until the user chooses the primary action.
Future<void> showUpdateCheckDialog(
BuildContext context,
AppNotifier notifier,
ManualUpdateCheck result,
) {
- final update = result.update;
- if (update == null) {
- return showAppDialog<void>(
- context: context,
- builder: (context) => const _UpdateDialog(
- icon: LucideIcons.circleCheck300,
- tone: _DialogTone.ok,
- title: 'You’re up to date',
- body: 'This copy of OpenHarness already has the latest version.',
- ),
- );
- }
return showAppDialog<void>(
context: context,
- barrierDismissible: false,
builder: (dialogContext) {
+ var current = result;
+ var checking = false;
var installing = false;
return StatefulBuilder(
- builder: (context, setState) => _UpdateDialog(
- icon: LucideIcons.arrowDownToLine300,
- title: installing
- ? 'Installing OpenHarness ${update.version}…'
- : 'OpenHarness ${update.version} is available',
- body: installing
- ? 'Don’t quit OpenHarness. It will restart on its own.'
- : result.isSkipped
- ? 'You skipped this version earlier. You can still install it.'
- : 'Download and install it now? OpenHarness will restart when it '
- 'finishes.',
- busy: installing,
- update: installing ? null : update,
- actions: installing
- ? const []
- : [
- _DialogAction(
- key: const Key('close-update-dialog-button'),
- label: 'Close',
- onPressed: () async {
- Navigator.of(dialogContext).pop();
- },
- ),
- _DialogAction(
- label: result.isSkipped
- ? 'Not now'
- : 'Skip ${update.version}',
- onPressed: () async {
- if (!result.isSkipped) {
- await notifier.skipAvailableUpdate();
- }
- if (dialogContext.mounted) {
- Navigator.of(dialogContext).pop();
- }
- },
- ),
- _DialogAction(
- label: 'Update',
- primary: true,
- onPressed: () async {
- setState(() => installing = true);
- final installed = await notifier.installAvailableUpdate();
- // A successful install never returns — the process is
- // replaced. Reaching here means it failed, and the banner
- // behind this dialog is already showing why.
- if (!dialogContext.mounted || installed) return;
- Navigator.of(dialogContext).pop();
- },
- ),
- ],
- ),
+ builder: (context, setState) {
+ if (checking) {
+ return const _UpdateDialog(
+ icon: LucideIcons.refreshCw300,
+ title: 'Checking for updates…',
+ body: 'Looking for a newer version of OpenHarness.',
+ busy: true,
+ );
+ }
+ if (current.status == DesktopUpdateCheckStatus.failed) {
+ return _UpdateDialog(
+ icon: LucideIcons.triangleAlert300,
+ tone: _DialogTone.warning,
+ title: 'Couldn’t check for updates',
+ body:
+ 'OpenHarness couldn’t read the latest version. '
+ 'Check your connection and try again.',
+ actions: [
+ _DialogAction(
+ label: 'Close',
+ onPressed: () async => Navigator.of(dialogContext).pop(),
+ ),
+ _DialogAction(
+ label: 'Retry',
+ primary: true,
+ onPressed: () async {
+ setState(() => checking = true);
+ final next = await notifier.checkForUpdates();
+ if (!context.mounted) return;
+ setState(() {
+ current = next;
+ checking = false;
+ });
+ },
+ ),
+ ],
+ );
+ }
+ if (current.status == DesktopUpdateCheckStatus.disabled) {
+ return const _UpdateDialog(
+ icon: LucideIcons.info300,
+ title: 'Updates are off for this build',
+ body: 'This build does not check for or install desktop updates.',
+ );
+ }
+ final update = current.update;
+ if (update == null) {
+ return const _UpdateDialog(
+ icon: LucideIcons.circleCheck300,
+ tone: _DialogTone.ok,
+ title: 'You’re up to date',
+ body: 'This copy of OpenHarness already has the latest version.',
+ );
+ }
+ return PopScope(
+ canPop: !installing,
+ child: _UpdateDialog(
+ icon: LucideIcons.arrowDownToLine300,
+ title: installing
+ ? 'Installing OpenHarness ${update.version}…'
+ : 'OpenHarness ${update.version} is available',
+ body: installing
+ ? 'Don’t quit OpenHarness. It will restart on its own.'
+ : current.isSkipped
+ ? 'You skipped this version earlier. You can still install it.'
+ : 'Download and install it now? OpenHarness will restart when it '
+ 'finishes.',
+ busy: installing,
+ update: installing ? null : update,
+ actions: installing
+ ? const []
+ : [
+ _DialogAction(
+ key: const Key('close-update-dialog-button'),
+ label: 'Close',
+ onPressed: () async {
+ Navigator.of(dialogContext).pop();
+ },
+ ),
+ if (!current.isSkipped)
+ _DialogAction(
+ label: 'Skip ${update.version}',
+ onPressed: () async {
+ await notifier.skipAvailableUpdate(update: update);
+ if (dialogContext.mounted) {
+ Navigator.of(dialogContext).pop();
+ }
+ },
+ ),
+ _DialogAction(
+ label: 'Update',
+ primary: true,
+ onPressed: () async {
+ setState(() => installing = true);
+ final installed = await notifier
+ .installAvailableUpdate(update: update);
+ // A successful install never returns — the process is
+ // replaced. Reaching here means it failed, and the banner
+ // behind this dialog is already showing why.
+ if (!context.mounted || installed) return;
+ setState(() => installing = false);
+ Navigator.of(dialogContext).pop();
+ },
+ ),
+ ],
+ ),
+ );
+ },
);
},
);
}
-enum _DialogTone { accent, ok }
+enum _DialogTone { accent, ok, warning }
class _DialogAction {
final Key? key;
@@ -370,9 +443,11 @@ class _UpdateDialog extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
- final mark = tone == _DialogTone.ok
- ? grid.AppPalette.online
- : grid.AppPalette.accentOnSurface;
+ final mark = switch (tone) {
+ _DialogTone.ok => grid.AppPalette.online,
+ _DialogTone.warning => grid.AppPalette.warn,
+ _DialogTone.accent => grid.AppPalette.accentOnSurface,
+ };
return Dialog(
// No backgroundColor, no shape: `dialogTheme` supplies both, at
@@ -380,98 +455,108 @@ class _UpdateDialog extends StatelessWidget {
// carry is gone with them — §1 allows exactly one border in the app and
// it belongs to the menu panel, not to a dialog.
child: ConstrainedBox(
- constraints: const BoxConstraints(maxWidth: 372),
- child: Padding(
- padding: const EdgeInsets.fromLTRB(18, 18, 18, 14),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- Container(
- width: 34,
- height: 34,
- decoration: BoxDecoration(
- color: mark.withValues(alpha: 0.13),
- borderRadius: BorderRadius.circular(grid.AppCard.insetRadius),
+ constraints: BoxConstraints(
+ maxWidth: 372 * MediaQuery.textScalerOf(context).scale(12.5) / 12.5,
+ ),
+ child: SingleChildScrollView(
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(18, 18, 18, 14),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Container(
+ width: 34,
+ height: 34,
+ decoration: BoxDecoration(
+ color: mark.withValues(alpha: 0.13),
+ borderRadius: BorderRadius.circular(
+ grid.AppCard.insetRadius,
+ ),
+ ),
+ alignment: Alignment.center,
+ child: busy
+ ? SizedBox(
+ width: 17,
+ height: 17,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ color: mark,
+ ),
+ )
+ : Icon(icon, size: 18, color: mark),
),
- alignment: Alignment.center,
- child: busy
- ? SizedBox(
- width: 17,
- height: 17,
- child: CircularProgressIndicator(
- strokeWidth: 2,
- color: mark,
- ),
- )
- : Icon(icon, size: 18, color: mark),
- ),
- const SizedBox(height: 12),
- Text(
- title,
- style: TextStyle(
- color: grid.AppPalette.textPrimary,
- fontSize: 15,
- fontWeight: grid.AppFont.semibold,
+ const SizedBox(height: 12),
+ Text(
+ title,
+ style: TextStyle(
+ color: grid.AppPalette.textPrimary,
+ fontSize: 15,
+ fontWeight: grid.AppFont.semibold,
+ ),
),
- ),
- const SizedBox(height: 5),
- Text(
- body,
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontSize: 12.5,
- height: 1.5,
+ const SizedBox(height: 5),
+ Text(
+ body,
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 12.5,
+ height: 1.5,
+ ),
),
- ),
- if (update != null) ...[
- const SizedBox(height: 12),
- Divider(height: 1, color: grid.AppGlass.hair),
- const SizedBox(height: 10),
- _Fact(label: 'Installed', value: _InstalledVersion()),
- const SizedBox(height: 6),
- _Fact(label: 'New version', value: Text(update!.version)),
- if (update!.size > 0) ...[
+ if (update != null) ...[
+ const SizedBox(height: 12),
+ Divider(height: 1, color: grid.AppGlass.hair),
+ const SizedBox(height: 10),
+ _Fact(label: 'Installed', value: _InstalledVersion()),
const SizedBox(height: 6),
- _Fact(
- label: 'Download',
- value: Text(formatDownloadSize(update!.size)),
+ _Fact(label: 'New version', value: Text(update!.version)),
+ if (update!.size > 0) ...[
+ const SizedBox(height: 6),
+ _Fact(
+ label: 'Download',
+ value: Text(formatDownloadSize(update!.size)),
+ ),
+ ],
+ ],
+ if (actions.isNotEmpty) ...[
+ const SizedBox(height: 15),
+ Align(
+ alignment: Alignment.centerRight,
+ child: Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final action in actions) ...[
+ _NoticeAction(
+ key: action.key,
+ label: action.label,
+ kind: action.primary
+ ? _ActionKind.primary
+ : _ActionKind.quiet,
+ onPressed: () => unawaited(action.onPressed()),
+ ),
+ ],
+ ],
+ ),
),
],
- ],
- if (actions.isNotEmpty) ...[
- const SizedBox(height: 15),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- for (final action in actions) ...[
- if (action != actions.first) const SizedBox(width: 8),
+ if (actions.isEmpty && !busy) ...[
+ const SizedBox(height: 15),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.end,
+ children: [
_NoticeAction(
- key: action.key,
- label: action.label,
- kind: action.primary
- ? _ActionKind.primary
- : _ActionKind.quiet,
- onPressed: () => unawaited(action.onPressed()),
+ label: 'Close',
+ kind: _ActionKind.ghost,
+ onPressed: () => Navigator.of(context).pop(),
),
],
- ],
- ),
- ],
- if (actions.isEmpty && !busy) ...[
- const SizedBox(height: 15),
- Row(
- mainAxisAlignment: MainAxisAlignment.end,
- children: [
- _NoticeAction(
- label: 'Close',
- kind: _ActionKind.ghost,
- onPressed: () => Navigator.of(context).pop(),
- ),
- ],
- ),
+ ),
+ ],
],
- ],
+ ),
),
),
),
@@ -493,20 +578,22 @@ class _Fact extends StatelessWidget {
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
- width: 96,
+ width: 96 * MediaQuery.textScalerOf(context).scale(11.5) / 11.5,
child: Text(
label,
style: TextStyle(color: grid.AppPalette.textFaint, fontSize: 11.5),
),
),
- DefaultTextStyle(
- style: TextStyle(
- color: grid.AppPalette.textSecondary,
- fontSize: 11.5,
- fontFamily: grid.AppFont.mono,
- fontFamilyFallback: grid.AppFont.monoFallback,
+ Expanded(
+ child: DefaultTextStyle(
+ style: TextStyle(
+ color: grid.AppPalette.textSecondary,
+ fontSize: 11.5,
+ fontFamily: grid.AppFont.mono,
+ fontFamilyFallback: grid.AppFont.monoFallback,
+ ),
+ child: value,
),
- child: value,
),
],
);
diff --git a/desktop/lib/widgets/welcome_project_example.dart b/desktop/lib/widgets/welcome_project_example.dart
new file mode 100644
index 000000000..1957e8b53
--- /dev/null
+++ b/desktop/lib/widgets/welcome_project_example.dart
@@ -0,0 +1,244 @@
+import 'dart:math' as math;
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import 'box_chrome.dart';
+
+/// Illustrative project outputs for the welcome guide, not live workspaces.
+enum WelcomeProjectExample { code, gripper, circuit }
+
+class WelcomeProjectOutput extends StatelessWidget {
+ const WelcomeProjectOutput({
+ super.key,
+ required this.example,
+ required this.ink,
+ required this.faint,
+ });
+
+ final WelcomeProjectExample example;
+ final Color ink, faint;
+
+ @override
+ Widget build(BuildContext context) {
+ if (example != WelcomeProjectExample.code) {
+ return SizedBox.expand(
+ child: CustomPaint(painter: _RobotComponent(example)),
+ );
+ }
+ final syntax = grid.AppPalette.teal;
+ return FittedBox(
+ fit: BoxFit.scaleDown,
+ alignment: Alignment.topLeft,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text('controller.ts', style: boxMonoStyle(size: 10, color: faint)),
+ const SizedBox(height: 10),
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: 'const ',
+ style: TextStyle(color: syntax),
+ ),
+ const TextSpan(text: 'arm = new RobotArm();\n\n'),
+ for (final command in [
+ 'arm.moveTo(pickup);',
+ 'arm.gripper.close();',
+ 'arm.moveTo(dropoff);',
+ 'arm.gripper.open();',
+ ]) ...[
+ TextSpan(
+ text: 'await ',
+ style: TextStyle(color: syntax),
+ ),
+ TextSpan(text: '$command\n'),
+ ],
+ ],
+ ),
+ softWrap: false,
+ style: boxMonoStyle(size: 12, color: ink),
+ ),
+ ],
+ ),
+ );
+ }
+}
+
+class _RobotComponent extends CustomPainter {
+ const _RobotComponent(this.example);
+ final WelcomeProjectExample example;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final scale = math.min(size.width / 200, size.height / 140);
+ canvas.save();
+ canvas.translate(
+ (size.width - 200 * scale) / 2,
+ (size.height - 140 * scale) / 2,
+ );
+ canvas.scale(scale);
+ switch (example) {
+ case WelcomeProjectExample.gripper:
+ _gripper(canvas);
+ case WelcomeProjectExample.circuit:
+ _circuit(canvas);
+ case WelcomeProjectExample.code:
+ break;
+ }
+ canvas.restore();
+ }
+
+ void _gripper(Canvas canvas) {
+ const steel = Color(0xffa4b1c0);
+ const jaw = Color(0xffd5a55c);
+ Offset project(double x, double y, double z) =>
+ Offset(114 + (x - y) * 1.1, 66 + (x + y) * .45 - z);
+ void face(List<Offset> points, Color color) {
+ final path = Path()..addPolygon(points, true);
+ canvas.drawPath(path, Paint()..color = color);
+ canvas.drawPath(
+ path,
+ Paint()
+ ..color = const Color(0xff192127)
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = .9,
+ );
+ }
+
+ void block(double x, double y, double w, double d, double h, Color color) {
+ face([
+ project(x, y + d, 0),
+ project(x + w, y + d, 0),
+ project(x + w, y + d, h),
+ project(x, y + d, h),
+ ], Color.lerp(color, Colors.black, .28)!);
+ face([
+ project(x + w, y, 0),
+ project(x + w, y + d, 0),
+ project(x + w, y + d, h),
+ project(x + w, y, h),
+ ], Color.lerp(color, Colors.black, .48)!);
+ face([
+ project(x, y, h),
+ project(x + w, y, h),
+ project(x + w, y + d, h),
+ project(x, y + d, h),
+ ], color);
+ }
+
+ canvas.drawOval(
+ const Rect.fromLTWH(33, 106, 137, 15),
+ Paint()..color = Colors.black.withValues(alpha: .20),
+ );
+ block(-32, -25, 64, 34, 18, steel);
+ block(-23, -20, 46, 21, 23, const Color(0xff798c9e));
+ block(19, 9, 12, 43, 13, steel);
+ block(8, 43, 23, 12, 17, jaw);
+ block(-31, 9, 12, 43, 13, steel);
+ block(-31, 43, 23, 12, 17, jaw);
+ for (final x in [-26.0, 26.0]) {
+ for (final y in [-19.0, 3.0]) {
+ canvas.drawOval(
+ Rect.fromCenter(center: project(x, y, 18), width: 5, height: 2.8),
+ Paint()..color = const Color(0xff303941),
+ );
+ }
+ }
+ final track = Paint()
+ ..color = const Color(0xff45545f)
+ ..strokeWidth = 1;
+ for (var i = 0; i < 4; i++) {
+ canvas.drawLine(
+ project(-12 + i * 8, -16, 23),
+ project(-12 + i * 8, -3, 23),
+ track,
+ );
+ }
+ }
+
+ void _circuit(Canvas canvas) {
+ final board = RRect.fromRectAndRadius(
+ const Rect.fromLTWH(17, 24, 165, 92),
+ const Radius.circular(6),
+ );
+ canvas.drawRRect(
+ board.shift(const Offset(0, 4)),
+ Paint()..color = const Color(0xff082e27),
+ );
+ canvas.drawRRect(board, Paint()..color = const Color(0xff164f42));
+ canvas.drawRRect(
+ board,
+ Paint()
+ ..color = const Color(0xff458f76)
+ ..style = PaintingStyle.stroke
+ ..strokeWidth = 1,
+ );
+ final trace = Paint()
+ ..color = const Color(0xff62b994)
+ ..strokeWidth = 1.2
+ ..style = PaintingStyle.stroke;
+ for (var i = 0; i < 4; i++) {
+ final y = 53.0 + i * 7;
+ canvas.drawPath(
+ Path()
+ ..moveTo(34, y)
+ ..lineTo(49 + i * 3, y)
+ ..lineTo(49 + i * 3, 46 + i * 7)
+ ..lineTo(72, 46 + i * 7),
+ trace,
+ );
+ canvas.drawPath(
+ Path()
+ ..moveTo(108, 46 + i * 7)
+ ..lineTo(121 + i * 4, 46 + i * 7)
+ ..lineTo(121 + i * 4, 91 - i * 7)
+ ..lineTo(163, 91 - i * 7),
+ trace,
+ );
+ }
+ final gold = Paint()..color = const Color(0xffd4b36e);
+ final dark = Paint()..color = const Color(0xff182421);
+ for (var i = 0; i < 6; i++) {
+ final y = 40.0 + i * 6;
+ canvas.drawRect(Rect.fromLTWH(67, y, 7, 2.4), gold);
+ canvas.drawRect(Rect.fromLTWH(107, y, 7, 2.4), gold);
+ }
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ const Rect.fromLTWH(73, 35, 35, 43),
+ const Radius.circular(2),
+ ),
+ dark,
+ );
+ canvas.drawCircle(
+ const Offset(79, 41),
+ 1.5,
+ Paint()..color = const Color(0xff73817a),
+ );
+ for (final x in [26.0, 163.0]) {
+ canvas.drawRect(Rect.fromLTWH(x - 2, 43, 11, 49), dark);
+ for (var i = 0; i < 5; i++) {
+ canvas.drawRect(Rect.fromLTWH(x, 46 + i * 9, 7, 4), gold);
+ }
+ }
+ for (final point in [
+ const Offset(27, 33),
+ const Offset(172, 33),
+ const Offset(27, 106),
+ const Offset(172, 106),
+ ]) {
+ canvas.drawCircle(point, 3.5, gold);
+ canvas.drawCircle(point, 1.9, dark);
+ }
+ for (var i = 0; i < 3; i++) {
+ canvas.drawRect(Rect.fromLTWH(80 + i * 18, 94, 12, 5), gold);
+ canvas.drawRect(Rect.fromLTWH(82 + i * 18, 94, 8, 5), dark);
+ }
+ }
+
+ @override
+ bool shouldRepaint(_RobotComponent old) => old.example != example;
+}
diff --git a/desktop/lib/widgets/workspace_quick_start.dart b/desktop/lib/widgets/workspace_quick_start.dart
new file mode 100644
index 000000000..ce1c359a3
--- /dev/null
+++ b/desktop/lib/widgets/workspace_quick_start.dart
@@ -0,0 +1,79 @@
+import 'package:flutter/material.dart';
+
+import '../shortcuts/app_keymap.dart';
+import '../state/workspace_learning.dart';
+import 'box_chrome.dart';
+
+/// A temporary guide beside real work. It never requests terminal focus.
+class WorkspaceQuickStart extends StatelessWidget {
+ const WorkspaceQuickStart({
+ super.key,
+ required this.learning,
+ required this.onCommand,
+ required this.onPractice,
+ });
+ final WorkspaceLearning learning;
+ final ValueChanged<String> onCommand;
+ final VoidCallback onPractice;
+
+ @override
+ Widget build(BuildContext context) {
+ final next = learning.next;
+ final (command, label) = switch (next) {
+ WorkspaceLesson.agent => ('swarm.new', 'Open your first agent'),
+ WorkspaceLesson.pane => ('agent.add', 'Add a second agent to this tab'),
+ WorkspaceLesson.zoom => ('pane.zoom', 'Zoom the focused pane'),
+ WorkspaceLesson.commands => (
+ 'navigation.commands',
+ 'Find an action by name',
+ ),
+ null => (
+ 'keyboard.practice',
+ 'Workspace ready. Keep learning at your own pace.',
+ ),
+ };
+ final keys = KeymapTheme.of(context)?.hint(command);
+ final hint = keys == null ? null : boxKeyLabel(keys);
+ return TerminalBox(
+ docked: true,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 4),
+ child: Wrap(
+ spacing: 14,
+ runSpacing: 2,
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: [
+ Text(
+ next == null
+ ? 'quick start [done]'
+ : 'quick start ${next.index + 1}/4',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ Semantics(
+ liveRegion: true,
+ child: Text(label, style: boxMonoStyle(size: 12)),
+ ),
+ TextButton(
+ key: const ValueKey('quick-start-action'),
+ onPressed: next == null ? onPractice : () => onCommand(command),
+ child: Text(
+ next == null
+ ? 'Keyboard practice'
+ : '${hint == null ? '' : '$hint '}${next == WorkspaceLesson.commands ? 'Search commands' : 'Try it'}',
+ style: boxMonoStyle(size: 12),
+ ),
+ ),
+ TextButton(
+ key: const ValueKey('quick-start-pause'),
+ onPressed: learning.pause,
+ child: Text(
+ next == null ? 'Done' : 'Pause guide',
+ style: boxMonoStyle(size: 12, color: kBoxFaint),
+ ),
+ ),
+ ],
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/workspace_start_guide.dart b/desktop/lib/widgets/workspace_start_guide.dart
new file mode 100644
index 000000000..cf5269e12
--- /dev/null
+++ b/desktop/lib/widgets/workspace_start_guide.dart
@@ -0,0 +1,396 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shortcuts/app_keymap.dart';
+import '../shortcuts/keymap.dart';
+import '../shortcuts/keymap_commands.dart';
+import 'box_chrome.dart';
+import 'welcome_project_example.dart';
+
+/// A quiet, live keyboard map for an empty workspace. The drawing illustrates
+/// tabs and panes. Only the full shortcuts link is interactive.
+class WorkspaceStartGuide extends StatelessWidget {
+ const WorkspaceStartGuide({super.key, required this.onShortcuts});
+
+ final VoidCallback onShortcuts;
+
+ String _hint(BuildContext context, String command) =>
+ KeymapTheme.of(context)?.hint(command) ??
+ (KeymapTheme.of(context) == null
+ ? harnessDefaultKeymap
+ .bindingsFor(KeymapContext.workspace)
+ .where((binding) => binding.command == command)
+ .map(describeKeyBinding)
+ .firstOrNull
+ : null) ??
+ '';
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final ink = grid.AppTheme.palette.value.foreground;
+ final faint = ink.withValues(alpha: .62);
+ final accent = grid.AppPalette.swarmAccent;
+ final stroke = faint.withValues(alpha: .30);
+ return Material(
+ color: grid.AppPalette.swarmWelcome,
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final scale = MediaQuery.textScalerOf(context).scale(13) / 13;
+ final compact = constraints.maxWidth < 680 * scale;
+ final short = constraints.maxHeight < 420 * scale;
+ Widget callout(String command, String label, String explanation) =>
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text.rich(
+ TextSpan(
+ children: [
+ if (_hint(context, command).isNotEmpty)
+ TextSpan(
+ text: '${_hint(context, command)} ',
+ style: TextStyle(color: accent),
+ ),
+ TextSpan(text: label),
+ ],
+ ),
+ style: boxMonoStyle(size: 13, color: ink),
+ ),
+ const SizedBox(height: 4),
+ Text(
+ explanation,
+ style: boxMonoStyle(size: 12, color: faint),
+ ),
+ ],
+ ),
+ );
+ final diagram = Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Padding(
+ padding: const EdgeInsets.only(bottom: 40),
+ child: Text(
+ 'Follow your curiosity. Build across disciplines.',
+ textAlign: TextAlign.center,
+ style: boxMonoStyle(
+ size: 20,
+ color: ink,
+ weight: FontWeight.w600,
+ ),
+ ),
+ ),
+ Row(
+ mainAxisAlignment: MainAxisAlignment.spaceBetween,
+ children: [
+ Flexible(
+ child: callout(
+ 'swarm.new',
+ 'New Tab',
+ 'Group multiple harnesses in one tab.',
+ ),
+ ),
+ Flexible(
+ child: callout(
+ 'app.store',
+ 'Harness Store',
+ 'Code, 3D design, circuits, video, and more.',
+ ),
+ ),
+ ],
+ ),
+ SizedBox(
+ height: 14,
+ width: double.infinity,
+ child: CustomPaint(painter: _GuideArrows(stroke, top: true)),
+ ),
+ ExcludeSemantics(
+ child: Container(
+ decoration: BoxDecoration(border: Border.all(color: stroke)),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Container(
+ decoration: BoxDecoration(
+ border: Border(bottom: BorderSide(color: stroke)),
+ ),
+ padding: const EdgeInsets.symmetric(
+ horizontal: 16,
+ vertical: 8,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Row(
+ children: [
+ Flexible(
+ child: Text(
+ 'robot arm',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(
+ size: 12,
+ color: faint,
+ ),
+ ),
+ ),
+ if (!compact) ...[
+ const SizedBox(width: 32),
+ Text(
+ 'launch video',
+ style: boxMonoStyle(
+ size: 12,
+ color: faint,
+ ),
+ ),
+ ],
+ const SizedBox(width: 20),
+ Text(
+ '+',
+ style: boxMonoStyle(size: 14, color: faint),
+ ),
+ ],
+ ),
+ ),
+ Text(
+ compact ? 'Store' : 'Harness Store',
+ style: boxMonoStyle(size: 12, color: faint),
+ ),
+ ],
+ ),
+ ),
+ SizedBox(
+ height: (constraints.maxHeight - 254 * scale).clamp(
+ (short ? 220 : 280) * scale,
+ 340 * scale,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: _DrawnPane(
+ name: 'Claude Code',
+ example: WelcomeProjectExample.code,
+ task: 'Write the robot arm control code',
+ showLocation: !short,
+ ink: ink,
+ faint: faint,
+ accent: accent,
+ ),
+ ),
+ VerticalDivider(
+ width: 1,
+ thickness: 1,
+ color: stroke,
+ ),
+ Expanded(
+ child: Column(
+ children: [
+ Expanded(
+ child: _DrawnPane(
+ name: 'Blender',
+ example: WelcomeProjectExample.gripper,
+ task: 'Design a printable robot gripper',
+ showLocation: !short,
+ ink: ink,
+ faint: faint,
+ accent: accent,
+ ),
+ ),
+ Divider(
+ height: 1,
+ thickness: 1,
+ color: stroke,
+ ),
+ Expanded(
+ child: _DrawnPane(
+ name: 'KiCad',
+ example: WelcomeProjectExample.circuit,
+ task: 'Design the motor controller board',
+ showLocation: !short,
+ ink: ink,
+ faint: faint,
+ accent: accent,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ SizedBox(
+ height: 14,
+ width: double.infinity,
+ child: CustomPaint(painter: _GuideArrows(stroke)),
+ ),
+ Row(
+ children: [
+ Expanded(
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton(
+ key: const ValueKey('workspace-all-shortcuts'),
+ onPressed: onShortcuts,
+ style: TextButton.styleFrom(foregroundColor: faint),
+ child: Text(
+ '${_hint(context, 'keyboard.help')} All Keyboard Shortcuts'
+ .trimLeft(),
+ style: boxMonoStyle(size: 11, color: faint),
+ ),
+ ),
+ ),
+ ),
+ Expanded(
+ child: Align(
+ alignment: Alignment.center,
+ child: callout(
+ 'agent.add',
+ 'New Pane',
+ 'Add a harness beside your work.',
+ ),
+ ),
+ ),
+ ],
+ ),
+ ],
+ );
+ final horizontalPadding = compact ? 16.0 : 24.0;
+ return Padding(
+ padding: EdgeInsets.symmetric(
+ horizontal: horizontalPadding,
+ vertical: 12,
+ ),
+ child: Center(
+ // The dock owns its actual height. Scale the entire original
+ // diagram together, including the tagline and all its arrows.
+ child: FittedBox(
+ fit: BoxFit.scaleDown,
+ child: SizedBox(
+ key: const ValueKey('workspace-welcome-diagram'),
+ width: (constraints.maxWidth - horizontalPadding * 2).clamp(
+ 0.0,
+ 1000.0,
+ ),
+ child: diagram,
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ }
+}
+
+class _DrawnPane extends StatelessWidget {
+ const _DrawnPane({
+ required this.name,
+ required this.example,
+ required this.task,
+ required this.ink,
+ required this.faint,
+ required this.accent,
+ this.showLocation = true,
+ });
+ final String name, task;
+ final WelcomeProjectExample example;
+ final Color ink, faint, accent;
+ final bool showLocation;
+ @override
+ Widget build(BuildContext context) {
+ final copy = Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ name,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 14, color: ink),
+ ),
+ if (showLocation) ...[
+ const SizedBox(height: 6),
+ Text(
+ 'This Mac:~/work/robot-arm',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 11, color: faint),
+ ),
+ ],
+ const SizedBox(height: 10),
+ Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: '› ',
+ style: TextStyle(color: accent),
+ ),
+ TextSpan(text: '$task ▏'),
+ ],
+ ),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: boxMonoStyle(size: 12, color: ink),
+ ),
+ ],
+ );
+ final output = WelcomeProjectOutput(
+ example: example,
+ ink: ink,
+ faint: faint,
+ );
+ return Padding(
+ padding: const EdgeInsets.all(12),
+ child: example == WelcomeProjectExample.code
+ ? Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ copy,
+ const SizedBox(height: 16),
+ Expanded(child: output),
+ ],
+ )
+ : Row(
+ children: [
+ Expanded(flex: 3, child: copy),
+ const SizedBox(width: 12),
+ Expanded(flex: 2, child: output),
+ ],
+ ),
+ );
+ }
+}
+
+class _GuideArrows extends CustomPainter {
+ const _GuideArrows(this.color, {this.top = false});
+ final Color color;
+ final bool top;
+ @override
+ void paint(Canvas canvas, Size size) {
+ final pen = Paint()
+ ..color = color
+ ..strokeWidth = 1;
+ void arrow(double x, {required bool down}) {
+ final tip = Offset(x, down ? size.height - 2 : 2);
+ canvas.drawLine(Offset(x, down ? 0 : size.height), tip, pen);
+ for (final side in [-1, 1]) {
+ canvas.drawLine(tip, tip + Offset(4.0 * side, down ? -5 : 5), pen);
+ }
+ }
+
+ if (top) {
+ arrow(56, down: true);
+ arrow(size.width - 56, down: true);
+ } else {
+ arrow(size.width * .75, down: false);
+ }
+ }
+
+ @override
+ bool shouldRepaint(_GuideArrows old) => old.color != color || old.top != top;
+}
diff --git a/desktop/lib/ws/ws_pool.dart b/desktop/lib/ws/ws_pool.dart
index 30b97e695..f1ee6b991 100644
--- a/desktop/lib/ws/ws_pool.dart
+++ b/desktop/lib/ws/ws_pool.dart
@@ -58,8 +58,13 @@ class WsPool {
!current.isClosed) {
return current;
}
+ // Stop accepting callbacks before close yields. Its final disconnected
+ // event must not mark a replacement connection offline.
+ _conns.remove(machineId);
if (current != null) unawaited(current.close());
- final conn = WsConn(
+ late final WsConn conn;
+ bool ownsMachine() => identical(_conns[machineId], conn);
+ conn = WsConn(
wsBaseUrl: wsBaseUrl,
autonomousEnv: autonomousEnv,
relayCodecs: transportKind == WsTransportKind.cloudE2ee
@@ -70,12 +75,20 @@ class WsPool {
: null,
machineId: machineId,
accessTokenProvider: accessTokenProvider,
- onAuthFailure: onAuthFailure,
+ onAuthFailure: (message) {
+ if (ownsMachine()) onAuthFailure(message);
+ },
onLocalFailure: onLocalFailure == null
? null
- : (code, reason) => onLocalFailure!(machineId, code, reason),
- onEvent: (event) => onEvent(machineId, event),
- onStatus: (status) => onStatus(machineId, status),
+ : (code, reason) {
+ if (ownsMachine()) onLocalFailure!(machineId, code, reason);
+ },
+ onEvent: (event) {
+ if (ownsMachine()) return onEvent(machineId, event);
+ },
+ onStatus: (status) {
+ if (ownsMachine()) onStatus(machineId, status);
+ },
transportKind: transportKind,
localWsUri: localWsUri,
localApiKey: localApiKey,
@@ -98,8 +111,7 @@ class WsPool {
Future<void> closeAll() async {
final all = _conns.values.toList();
_conns.clear();
- for (final conn in all) {
- await conn.close();
- }
+ // A failed close must not leave the other transports connected.
+ await Future.wait(all.map((conn) => conn.close()));
}
}
diff --git a/desktop/macos/Runner/HarnessKeymap.swift b/desktop/macos/Runner/HarnessKeymap.swift
index 7791abadc..9a0d003f9 100644
--- a/desktop/macos/Runner/HarnessKeymap.swift
+++ b/desktop/macos/Runner/HarnessKeymap.swift
@@ -126,13 +126,14 @@ private final class HarnessKeyNode {
/// Reject a malformed snapshot as a whole, leaving the caller's last good map.
/// Defaults and overrides are already resolved in Dart, including unbinding.
final class HarnessNativeKeymap {
+ static let contexts: Set<String> = ["workspace", "terminal", "picker", "project"]
private var roots: [String: HarnessKeyNode] = [:]
private(set) var bindings: [String: [HarnessNativeBinding]] = [:]
init?(_ payload: [String: Any]) {
guard payload["version"] as? Int == 1,
let contexts = payload["contexts"] as? [String: Any],
- Set(contexts.keys) == Set(["workspace", "terminal", "picker"]) else { return nil }
+ Set(contexts.keys) == Self.contexts else { return nil }
for (context, raw) in contexts {
guard let rows = raw as? [[String: Any]], rows.count <= 640 else { return nil }
let root = HarnessKeyNode()
diff --git a/desktop/macos/Runner/MainFlutterWindow.swift b/desktop/macos/Runner/MainFlutterWindow.swift
index da4e5c964..786f788e1 100644
--- a/desktop/macos/Runner/MainFlutterWindow.swift
+++ b/desktop/macos/Runner/MainFlutterWindow.swift
@@ -148,6 +148,10 @@ class MainFlutterWindow: NSWindow {
at: 0
)
helpMenu.insertItem(NSMenuItem.separator(), at: 1)
+ helpMenu.insertItem(menuItem(title: "Quick Start", action: #selector(quickStart(_:)),
+ symbol: "terminal", tag: 7310), at: 0)
+ helpMenu.insertItem(menuItem(title: "Keyboard Practice", action: #selector(keyboardPractice(_:)),
+ symbol: "keyboard", tag: 7311), at: 1)
}
/// The Safari/Chrome/Terminal.app "Font" convention, in the SAME menu and the SAME order those
@@ -189,17 +193,14 @@ class MainFlutterWindow: NSWindow {
// key equivalent it is handled by the responder chain first, so it works
// wherever the focus happens to be.
//
- // ⌘S, matching the Dart binding. It was still "l" here after that binding moved, and this side is
- // the one that wins: AppKit takes the key equivalent before Flutter ever sees the event, so ⌘L went
- // on opening the layout palette and ⌘S did nothing inside a terminal — the exact silent conflict
- // the shortcut table's own comment warns about.
+ // Cmd-Shift-L matches the workspace keymap; Cmd-S opens the Store.
viewMenu.insertItem(
menuItem(
title: "Layout…",
action: #selector(showLayout(_:)),
symbol: "square.grid.2x2",
tag: layoutMenuItemTag,
- keyEquivalent: "s"
+ keyEquivalent: "l"
),
at: at
)
@@ -259,8 +260,10 @@ class MainFlutterWindow: NSWindow {
)
item.target = self
item.tag = tag
- if tag == shortcutsMenuItemTag || tag == layoutMenuItemTag {
- let command = tag == shortcutsMenuItemTag ? "showShortcuts" : "layout"
+ if tag == layoutMenuItemTag { item.keyEquivalentModifierMask = [.command, .shift] }
+ let keymapActions = [shortcutsMenuItemTag: "showShortcuts", layoutMenuItemTag: "layout",
+ 7310: "quickStart", 7311: "keyboardPractice"]
+ if let command = keymapActions[tag] {
item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + command)
}
// Every other row in this menu carries a glyph, so one without reads as
@@ -314,6 +317,14 @@ class MainFlutterWindow: NSWindow {
menuChannel?.invokeMethod("showShortcuts", arguments: nil)
}
+ @objc private func quickStart(_ sender: Any?) {
+ swarmTitlebar?.startQuickStart()
+ }
+
+ @objc private func keyboardPractice(_ sender: Any?) {
+ menuChannel?.invokeMethod("keyboardPractice", arguments: nil)
+ }
+
@objc private func increaseTerminalFontSize(_ sender: Any?) {
menuChannel?.invokeMethod("increaseTerminalFontSize", arguments: nil)
}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index f3c1c76ce..eace5ca77 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -8,7 +8,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private weak var window: NSWindow?
private let channel: FlutterMethodChannel
private let accessory = NSTitlebarAccessoryViewController()
- private let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 52))
+ private let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))
private var observers: [NSObjectProtocol] = []
private var configured = false
private var actionsEnabled = false
@@ -78,7 +78,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
result(nil)
case "keymapContext":
if let context = (call.arguments as? [String: Any])?["context"] as? String,
- ["workspace", "terminal", "picker"].contains(context) {
+ HarnessNativeKeymap.contexts.contains(context) {
self.flutterKeyContext = context
self.syncMenuKeys()
}
@@ -100,7 +100,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["select", "close", "new", "rename", "commands", "notifications", "addAgent", "newAgent", "newTerminal", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
+ guard ["select", "close", "new", "rename", "commands", "notifications", "store", "addAgent", "newAgent", "newTerminal", "runLocalModel", "splitRight", "splitDown", "zoomPane", "pinPane", "machineDestination", "machineAgent", "manageMachines", "machineList"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -116,6 +116,11 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
}
+ func startQuickStart() {
+ guard actionsEnabled else { return }
+ sendTabAction("keymapCommand", arguments: ["command": "keyboard.quick_start"])
+ }
+
private func focusContent(in window: NSWindow) {
guard let content = window.contentViewController?.view else { return }
// Keep a text field/Flutter input that already took focus while Dart was
@@ -136,6 +141,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private func setKeymap(_ map: HarnessNativeKeymap) {
keymap = map
+ // Mouse controls teach the effective shortcuts, including user remaps.
+ strip.newButton.toolTip = "New Tab " + (map.hint(for: "swarm.new", context: "workspace") ?? "")
+ strip.storeButton.toolTip = "Harness Store " + (map.hint(for: "app.store", context: "workspace") ?? "")
if let main = NSApp.mainMenu, let window {
let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)
if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }
@@ -171,13 +179,13 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
window.styleMask.remove(.fullSizeContentView)
window.backgroundColor = strip.palette.tabBar
// AppKit fixes a right accessory's height to the title bar. A taller view
- // alone is clipped. A unified toolbar gives the native traffic lights and
- // the tab strip one spacious row, without a second toolbar row.
+ // alone is clipped. The compact unified toolbar keeps the traffic lights
+ // and tabs in one 40pt row; unified adds 12pt of empty vertical space.
let toolbar = NSToolbar(identifier: "harness.swarm.titlebar")
toolbar.displayMode = .iconOnly
toolbar.allowsUserCustomization = false
window.toolbar = toolbar
- window.toolbarStyle = .unified
+ window.toolbarStyle = .unifiedCompact
window.titlebarSeparatorStyle = .none
accessory.layoutAttribute = .right
accessory.view = strip
@@ -222,7 +230,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
item.representedObject = action
item.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + action)
let symbols = [
- "new": "plus.square", "newAgent": "plus", "addAgent": "arrow.up.right", "newTerminal": "terminal",
+ "new": "plus.square", "newAgent": "plus", "addAgent": "plus", "newTerminal": "terminal",
"renameActive": "pencil", "closeActive": "xmark",
"splitRight": "rectangle.split.2x1", "splitDown": "rectangle.split.1x2",
"zoomPane": "viewfinder", "closePane": "xmark",
@@ -241,17 +249,14 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
if let file = main.item(withTitle: "File") { main.removeItem(file) }
let file = NSMenu(title: "File")
add(file, "New Tab", "t", "new")
- add(file, "New Harness…", "n", "newAgent")
+ add(file, "New Pane…", "p", "addAgent")
// ⌘⇧T, as in a terminal app. It used to be Reopen Last Closed (History menu), which keeps its
// row and loses its default chord — the Dart keymap (`swarm.reopen`) is where both are decided,
// and applyMenuKeys rewrites every equivalent here from it.
add(file, "New Terminal", "t", "newTerminal", [.command, .shift])
- add(file, "Open Harness…", "o", "addAgent")
add(file, "Rename Tab…", "r", "renameActive", [.command, .shift])
add(file, "Close Tab", "w", "closeActive")
file.addItem(.separator())
- add(file, "Split Right…", "r", "splitRight")
- add(file, "Split Down…", "d", "splitDown")
add(file, "Zoom Pane", "", "zoomPane")
add(file, "Close Pane", "w", "closePane", [.command, .shift])
install(file, at: 1)
@@ -619,7 +624,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
command("Back", "[", "historyBack")
command("Forward", "]", "historyForward")
// No default chord: ⌘⇧T is New Terminal now. A person can give this one in keybindings.jsonc.
- let reopen = NSMenuItem(title: "Reopen Last Closed", action: #selector(menuAction(_:)), keyEquivalent: "")
+ let reopen = NSMenuItem(title: "Reopen Closed Tab or Pane", action: #selector(menuAction(_:)), keyEquivalent: "")
reopen.target = self
reopen.representedObject = "reopen"
reopen.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "reopen")
@@ -668,7 +673,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
historyMenu.addItem(item)
}
if entries.isEmpty {
- let item = NSMenuItem(title: closed ? "No Recently Closed Harnesses" : "No Recent Visits", action: nil, keyEquivalent: "")
+ let item = NSMenuItem(title: closed ? "No Recently Closed Tabs or Panes" : "No Recent Visits", action: nil, keyEquivalent: "")
item.isEnabled = false
historyMenu.addItem(item)
}
@@ -1179,11 +1184,11 @@ private struct SwarmHistoryEntry: Equatable {
/// or reopening assets on every history/focus update.
private final class SwarmHistoryIcons {
/// The Flutter assets this opens: engine and harness artwork, and the app
- /// icon the Harness Store's tab wears (`kStoreMarkAsset` in
+ /// polymath mark the Harness Store wears (`kStoreMarkAsset` in
/// lib/store/store_mark.dart). Any other path draws the engine's initial,
/// which is how the store tab once read "S".
static func opens(_ asset: String) -> Bool {
- !asset.contains("..") && (asset == "assets/app_icon.png"
+ !asset.contains("..") && (asset == "assets/app_icon.png" || asset == "assets/store/polymath.png"
|| asset.hasPrefix("assets/engine-icons/") && asset.hasSuffix(".png"))
}
@@ -1294,7 +1299,7 @@ private struct SwarmNativePalette: Equatable {
/// Match the quiet rounded hover well used by the app's pane controls.
private class SwarmIconButton: NSButton {
- private var hovered = false
+ private(set) var hovered = false
private(set) var hasKeyboardFocus = false
var showsHoverFill: Bool { true }
override var acceptsFirstResponder: Bool { isEnabled }
@@ -1339,6 +1344,40 @@ private class SwarmIconButton: NSButton {
}
}
+/// A quiet filled pill, with the Store's colorful mark as its focal point.
+/// Drawing the content keeps the same spacing across AppKit button styles.
+private final class SwarmStoreButton: SwarmIconButton {
+ var palette = SwarmNativePalette() { didSet { needsDisplay = true } }
+ var preferredWidth: CGFloat {
+ ceil((title as NSString).size(withAttributes: [
+ .font: font ?? NSFont.monospacedSystemFont(ofSize: 12, weight: .medium),
+ ]).width) + 48
+ }
+
+ override func draw(_ dirtyRect: NSRect) {
+ let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
+ xRadius: bounds.height / 2, yRadius: bounds.height / 2)
+ palette.workspace.setFill()
+ shape.fill()
+ let alpha: CGFloat = !isEnabled ? 0.04 : isHighlighted ? 0.24 : hovered ? 0.18 : 0.10
+ palette.accent.withAlphaComponent(alpha).setFill()
+ shape.fill()
+ palette.accent.withAlphaComponent(hasKeyboardFocus && isEnabled ? 0.85 : 0.12).setStroke()
+ shape.lineWidth = hasKeyboardFocus && isEnabled ? 1.5 : 1
+ shape.stroke()
+ image?.draw(in: NSRect(x: 12, y: (bounds.height - 16) / 2, width: 16, height: 16),
+ from: .zero, operation: .sourceOver, fraction: isEnabled ? 1 : 0.45,
+ respectFlipped: true, hints: [.interpolation: NSImageInterpolation.high])
+ let attributes: [NSAttributedString.Key: Any] = [
+ .font: font ?? NSFont.monospacedSystemFont(ofSize: 12, weight: .medium),
+ .foregroundColor: palette.accent.withAlphaComponent(isEnabled ? 1 : 0.45),
+ ]
+ let text = title as NSString
+ let height = text.size(withAttributes: attributes).height
+ text.draw(at: NSPoint(x: 36, y: (bounds.height - height) / 2), withAttributes: attributes)
+ }
+}
+
private final class SwarmNotificationButton: SwarmIconButton {
var hasAttention = false { didSet { needsDisplay = true } }
override func draw(_ dirtyRect: NSRect) {
@@ -1350,67 +1389,6 @@ private final class SwarmNotificationButton: SwarmIconButton {
}
}
-/// Keep titlebar actions on the app's palette. AppKit's rounded bezel chooses
-/// its own label color in active/inactive windows, ignoring contentTintColor.
-private final class SwarmActionButton: NSButton {
- var fillColor = NSColor.clear { didSet { needsDisplay = true } }
- var borderColor: NSColor? { didSet { needsDisplay = true } }
- var labelColor = NSColor.labelColor { didSet { needsDisplay = true } }
- private var hovered = false
- override var isEnabled: Bool {
- didSet {
- needsDisplay = true
- window?.invalidateCursorRects(for: self)
- }
- }
- override var mouseDownCanMoveWindow: Bool { false }
-
- override func resetCursorRects() {
- super.resetCursorRects()
- if isEnabled { addCursorRect(bounds, cursor: .pointingHand) }
- }
-
- override func updateTrackingAreas() {
- super.updateTrackingAreas()
- trackingAreas.forEach(removeTrackingArea)
- addTrackingArea(NSTrackingArea(rect: .zero,
- options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self))
- }
- override func mouseEntered(with event: NSEvent) { hovered = true; needsDisplay = true }
- override func mouseExited(with event: NSEvent) { hovered = false; needsDisplay = true }
-
- override func draw(_ dirtyRect: NSRect) {
- // A workspace modal dims the canvas, not this native chrome. Keep the
- // normal appearance while isEnabled still prevents actions behind it.
- let emphasis: CGFloat = isHighlighted ? 0.16 : 0.08
- let hoverFill = fillColor.alphaComponent == 0
- ? labelColor.withAlphaComponent(emphasis)
- : fillColor.blended(withFraction: emphasis, of: labelColor) ?? fillColor
- let fill = isEnabled && (hovered || isHighlighted) ? hoverFill : fillColor
- fill.setFill()
- NSBezierPath(roundedRect: bounds, xRadius: bounds.height / 2, yRadius: bounds.height / 2).fill()
- if let borderColor {
- borderColor.setStroke()
- let border = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5),
- xRadius: (bounds.height - 1) / 2, yRadius: (bounds.height - 1) / 2)
- border.lineWidth = 1
- border.stroke()
- }
- let label = NSAttributedString(string: title, attributes: [
- .font: font ?? NSFont.systemFont(ofSize: 12, weight: .medium),
- .foregroundColor: labelColor,
- ])
- let size = label.size()
- let iconWidth: CGFloat = image == nil ? 0 : 20
- let left = (bounds.width - size.width - iconWidth) / 2
- image?.withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [labelColor]))?
- .draw(in: NSRect(x: left, y: (bounds.height - 14) / 2, width: 14, height: 14))
- label.draw(at: NSPoint(x: left + iconWidth, y: (bounds.height - size.height) / 2))
- }
-}
-
-/// The strip's scroller. A mouse wheel turns vertically, the strip runs sideways: turn the one into the
-/// other while there are more tabs than fit, as Safari and Chrome do over their tab bars.
private final class SwarmStripScrollView: NSScrollView {
override func scrollWheel(with event: NSEvent) {
let dx = event.scrollingDeltaX, dy = event.scrollingDeltaY
@@ -1434,8 +1412,7 @@ private final class SwarmTabStrip: NSView {
private let document = NSView()
fileprivate let newButton = SwarmIconButton()
fileprivate let notificationButton = SwarmNotificationButton()
- fileprivate let openButton = SwarmActionButton()
- fileprivate let createButton = SwarmActionButton()
+ fileprivate let storeButton = SwarmStoreButton(title: "Harness Store", target: nil, action: nil)
private var tabs: [SwarmTabButton] = []
private let icons = SwarmHistoryIcons()
private var activeId = ""
@@ -1485,23 +1462,18 @@ private final class SwarmTabStrip: NSView {
newButton.isEnabled = false
button(notificationButton, "bell", "Notifications", #selector(openNotifications))
notificationButton.isEnabled = false
- func textButton(_ button: NSButton, _ label: String, _ action: Selector) {
- button.title = label
- button.font = .systemFont(ofSize: 12, weight: .medium)
- button.isBordered = false
- button.setButtonType(.momentaryChange)
- button.target = self
- button.action = action
- button.setAccessibilityLabel(label)
- button.isEnabled = false
- addSubview(button)
- }
- textButton(createButton, "New Harness", #selector(createAgent))
- textButton(openButton, "Open Harness", #selector(openHarness))
- createButton.image = NSImage(systemSymbolName: "plus", accessibilityDescription: nil)
- openButton.image = NSImage(systemSymbolName: "arrow.up.right", accessibilityDescription: nil)
- updateActionColors()
- setAccessibilityChildren([notificationButton, scroll, newButton, createButton, openButton])
+ newButton.toolTip = "New Tab ⌘T"
+ storeButton.isBordered = false
+ storeButton.palette = palette
+ storeButton.image = icons.image(engine: "store", asset: "assets/store/polymath.png")
+ storeButton.font = NSFont.monospacedSystemFont(ofSize: 12, weight: .medium)
+ storeButton.target = self
+ storeButton.action = #selector(openStore)
+ storeButton.isEnabled = false
+ storeButton.toolTip = "Harness Store ⌘S"
+ storeButton.setAccessibilityLabel("Harness Store")
+ addSubview(storeButton)
+ setAccessibilityChildren([notificationButton, scroll, newButton, storeButton])
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -1512,18 +1484,11 @@ private final class SwarmTabStrip: NSView {
palette = nextPalette
notificationButton.contentTintColor = palette.accent
newButton.contentTintColor = palette.accent
- updateActionColors()
+ storeButton.palette = palette
for tab in tabs { tab.palette = palette }
needsDisplay = true
}
- private func updateActionColors() {
- createButton.fillColor = palette.accent
- createButton.labelColor = palette.tabBar
- openButton.fillColor = .clear
- openButton.labelColor = palette.accent
- openButton.borderColor = palette.accent.withAlphaComponent(0.3)
- }
deinit {
if let flagsMonitor { NSEvent.removeMonitor(flagsMonitor) }
@@ -1546,6 +1511,12 @@ private final class SwarmTabStrip: NSView {
// Workspace teardown clears its controls without changing appearance.
if let palette = state["palette"] as? [String: Any] { updatePalette(palette) }
actionsEnabled = state["enabled"] as? Bool == true
+ let families = [state["fontFamily"] as? String].compactMap { $0 }
+ + (state["fontFallbacks"] as? [String] ?? [])
+ storeButton.font = families.first == ".AppleSystemUIFontMonospaced"
+ ? NSFont.monospacedSystemFont(ofSize: 12, weight: .medium)
+ : families.compactMap { NSFont(name: $0, size: 12) }.first
+ ?? NSFont.monospacedSystemFont(ofSize: 12, weight: .medium)
let rows = state["tabs"] as? [[String: Any]] ?? []
let nextActiveId = state["activeId"] as? String ?? ""
revealActiveAfterLayout = revealActiveAfterLayout || nextActiveId != activeId
@@ -1559,6 +1530,12 @@ private final class SwarmTabStrip: NSView {
guard let id = row["id"] as? String else { return nil }
let tab = previous[id] ?? SwarmTabButton(id: id)
tab.palette = palette
+ let families = [state["fontFamily"] as? String].compactMap { $0 }
+ + (state["fontFallbacks"] as? [String] ?? [])
+ tab.labelFont = families.first == ".AppleSystemUIFontMonospaced"
+ ? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
+ : families.compactMap { NSFont(name: $0, size: 13) }.first
+ ?? NSFont.monospacedSystemFont(ofSize: 13, weight: .regular)
tab.name = row["name"] as? String ?? "New Tab"
let count = row["agentCount"] as? Int ?? 0
// The Harness Store tab holds no agents; without its own mark it would wear New Tab's plus.
@@ -1589,8 +1566,7 @@ private final class SwarmTabStrip: NSView {
document.setAccessibilityChildren(tabs)
newButton.isEnabled = actionsEnabled
notificationButton.isEnabled = actionsEnabled
- openButton.isEnabled = actionsEnabled
- createButton.isEnabled = actionsEnabled
+ storeButton.isEnabled = actionsEnabled
let attention = state["attention"] as? Int ?? 0
notificationButton.hasAttention = attention > 0
notificationButton.setAccessibilityLabel(attention > 0 ? "\(attention) agents need input" : "Notifications")
@@ -1617,15 +1593,14 @@ private final class SwarmTabStrip: NSView {
let previousDocumentSize = document.frame.size
let leading: CGFloat = 36
let spacious = bounds.width >= 480
- let openWidth: CGFloat = spacious ? 122 : 108
let trailing: CGFloat = spacious ? 12 : 8
- let actionsWidth = openWidth * 2 + 10 + trailing
- newButton.isHidden = bounds.width < 420
+ let storeWidth = storeButton.preferredWidth
+ newButton.isHidden = false
// A reserve after the "+" that tabs never grow into — Chrome's gap. It is
// where a full strip can still be dragged and double-clicked to zoom
// (owner, 2026-09-15); tabs shrink and then scroll instead of taking it.
let grip: CGFloat = spacious ? 84 : 44
- let available = max(32, bounds.width - leading - actionsWidth - (newButton.isHidden ? 0 : 36) - grip)
+ let available = max(32, bounds.width - leading - trailing - (newButton.isHidden ? 0 : 36) - grip - storeWidth - 8)
// As in Chrome, tabs keep shrinking until they are only their mark, so thirty tabs still sit in
// one strip with nothing hidden; only past that does the strip scroll (the wheel scrolls it).
let width = min(220, max(min(SwarmTabButton.minimumWidth, available), available / CGFloat(max(1, tabs.count))))
@@ -1633,15 +1608,13 @@ private final class SwarmTabStrip: NSView {
scroll.frame = NSRect(x: leading, y: 0, width: occupied, height: bounds.height)
document.frame = NSRect(x: 0, y: 0, width: max(occupied, CGFloat(tabs.count) * width), height: bounds.height)
for (index, tab) in tabs.enumerated() {
- tab.frame = NSRect(x: CGFloat(index) * width, y: 0, width: width, height: bounds.height - 6)
+ tab.frame = NSRect(x: CGFloat(index) * width, y: 0, width: width, height: bounds.height - 4)
tab.contentCenterY = bounds.midY
}
let buttonY = (bounds.height - 28) / 2
notificationButton.frame = NSRect(x: 0, y: buttonY, width: 28, height: 28)
newButton.frame = NSRect(x: leading + occupied + 4, y: buttonY, width: 28, height: 28)
- let actionY = (bounds.height - 34) / 2
- openButton.frame = NSRect(x: bounds.width - trailing - openWidth, y: actionY, width: openWidth, height: 34)
- createButton.frame = NSRect(x: openButton.frame.minX - 10 - openWidth, y: actionY, width: openWidth, height: 34)
+ storeButton.frame = NSRect(x: bounds.width - trailing - storeWidth, y: buttonY, width: storeWidth, height: 28)
let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
@@ -1650,8 +1623,7 @@ private final class SwarmTabStrip: NSView {
tabOrderChanged = false
}
override func draw(_ dirtyRect: NSRect) {
- // The selected tab meets this edge; its bottom corners are shoulders,
- // rather than the rounded bottom of a separate pill.
+ // A fine rule joins the flat tabs to the workspace.
palette.workspace.setFill()
NSRect(x: 0, y: 0, width: bounds.width, height: 1).fill()
@@ -1683,11 +1655,8 @@ private final class SwarmTabStrip: NSView {
@objc private func openNotifications() {
if actionsEnabled { emit?("notifications", nil) }
}
- @objc private func openHarness() {
- if actionsEnabled { emit?("addAgent", nil) }
- }
- @objc private func createAgent() {
- if actionsEnabled { emit?("newAgent", nil) }
+ @objc private func openStore() {
+ if actionsEnabled { emit?("store", nil) }
}
private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {
@@ -1732,6 +1701,9 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
get { iconView.image }
set { iconView.image = newValue }
}
+ var labelFont = NSFont.monospacedSystemFont(ofSize: 13, weight: .regular) {
+ didSet { if oldValue != labelFont { invalidateLabel() } }
+ }
private var cachedLabel: NSAttributedString?
var actionsEnabled = true {
didSet {
@@ -1825,30 +1797,43 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
let paragraph = NSMutableParagraphStyle()
paragraph.lineBreakMode = .byTruncatingTail
let label = NSAttributedString(string: name,
- attributes: [.font: NSFont.systemFont(ofSize: 13, weight: selected ? .medium : .regular),
+ attributes: [.font: selected ? NSFontManager.shared.convert(labelFont, toHaveTrait: .boldFontMask) : labelFont,
.foregroundColor: selected ? NSColor.white : NSColor(white: 0.76, alpha: 1), .paragraphStyle: paragraph])
cachedLabel = label
return label
}
override func draw(_ dirtyRect: NSRect) {
if selected {
- let w = bounds.width, h = bounds.height
- let shape = NSBezierPath()
- shape.move(to: NSPoint(x: 0, y: 0))
- shape.curve(to: NSPoint(x: 8, y: 8), controlPoint1: NSPoint(x: 4.4, y: 0), controlPoint2: NSPoint(x: 8, y: 3.6))
- shape.line(to: NSPoint(x: 8, y: h - 10))
- shape.curve(to: NSPoint(x: 18, y: h), controlPoint1: NSPoint(x: 8, y: h - 4.5), controlPoint2: NSPoint(x: 12.5, y: h))
- shape.line(to: NSPoint(x: w - 18, y: h))
- shape.curve(to: NSPoint(x: w - 8, y: h - 10), controlPoint1: NSPoint(x: w - 12.5, y: h), controlPoint2: NSPoint(x: w - 8, y: h - 4.5))
- shape.line(to: NSPoint(x: w - 8, y: 8))
- shape.curve(to: NSPoint(x: w, y: 0), controlPoint1: NSPoint(x: w - 8, y: 3.6), controlPoint2: NSPoint(x: w - 4.4, y: 0))
- shape.close()
palette.workspace.setFill()
- shape.fill()
+ // Match TerminalTabBorder: small top corners and outward bottom joins,
+ // all at the same radius. AppKit's origin is at the bottom left.
+ let r = min(CGFloat(3), min(bounds.width, bounds.height) / 4)
+ let c = r * 0.5522847498
+ let left = bounds.minX + r, right = bounds.maxX - r
+ let top = bounds.maxY, bottom = bounds.minY
+ let path = NSBezierPath()
+ path.move(to: NSPoint(x: bounds.minX, y: bottom))
+ path.curve(to: NSPoint(x: left, y: bottom + r),
+ controlPoint1: NSPoint(x: bounds.minX + c, y: bottom),
+ controlPoint2: NSPoint(x: left, y: bottom + r - c))
+ path.line(to: NSPoint(x: left, y: top - r))
+ path.curve(to: NSPoint(x: left + r, y: top),
+ controlPoint1: NSPoint(x: left, y: top - r + c),
+ controlPoint2: NSPoint(x: left + r - c, y: top))
+ path.line(to: NSPoint(x: right - r, y: top))
+ path.curve(to: NSPoint(x: right, y: top - r),
+ controlPoint1: NSPoint(x: right - r + c, y: top),
+ controlPoint2: NSPoint(x: right, y: top - r + c))
+ path.line(to: NSPoint(x: right, y: bottom + r))
+ path.curve(to: NSPoint(x: bounds.maxX, y: bottom),
+ controlPoint1: NSPoint(x: right, y: bottom + r - c),
+ controlPoint2: NSPoint(x: bounds.maxX - c, y: bottom))
+ path.close()
+ path.fill()
} else if hovered && actionsEnabled {
NSColor(white: 1, alpha: 0.05).setFill()
let hoverRect = NSRect(x: 8, y: contentCenterY - 14, width: bounds.width - 16, height: 28)
- NSBezierPath(roundedRect: hoverRect, xRadius: 12, yRadius: 12).fill()
+ NSBezierPath(roundedRect: hoverRect, xRadius: 3, yRadius: 3).fill()
}
if showsDivider && !hovered {
NSColor(white: 1, alpha: 0.16).setFill()
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index fe506434f..def02c47b 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -42,7 +42,7 @@ packages:
source: hosted
version: "1.1.3"
collection:
- dependency: transitive
+ dependency: "direct main"
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index aff4faad8..3fd34a9ee 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -30,6 +30,8 @@ environment:
dependencies:
flutter:
sdk: flutter
+ # Natural ordering for numbered agents, projects, and completion candidates.
+ collection: ^1.19.1
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
diff --git a/desktop/test/about_section_test.dart b/desktop/test/about_section_test.dart
index 04a77282a..4dfdf2d33 100644
--- a/desktop/test/about_section_test.dart
+++ b/desktop/test/about_section_test.dart
@@ -34,7 +34,7 @@ void main() {
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
- desktopUpdater: DesktopUpdater(enabled: true),
+ desktopUpdater: DesktopUpdater(enabled: true, releaseMode: true),
);
addTearDown(notifier.dispose);
tester.view.physicalSize = const Size(900 * 2, 700 * 2);
@@ -65,28 +65,30 @@ void main() {
size: 48600000,
);
- testWidgets('names the app, its version, and says nothing is waiting', (
- tester,
- ) async {
- await pumpAbout(tester);
-
- expect(find.text('OpenHarness'), findsOneWidget);
- expect(find.text('1.0.0'), findsOneWidget);
- expect(find.text('Up to date'), findsOneWidget);
- // Secondary actions, never a filled one — the pane is read, not operated.
- // Two of them since the merge with main: the update check, and the dial
- // flash, which on Linux and Windows has no native menu item to live in.
- expect(
- find.byKey(const Key('settings-check-updates-button')),
- findsOneWidget,
- );
- expect(
- find.byKey(const Key('settings-flash-firmware-button')),
- findsOneWidget,
- );
- expect(find.byType(OutlinedButton), findsNWidgets(2));
- expect(find.byType(FilledButton), findsNothing);
- });
+ testWidgets(
+ 'names the app and version without claiming an untested update status',
+ (tester) async {
+ await pumpAbout(tester);
+
+ expect(find.text('OpenHarness'), findsOneWidget);
+ expect(find.text('1.0.0'), findsOneWidget);
+ expect(find.text('Not checked'), findsOneWidget);
+ expect(find.text('Up to date'), findsNothing);
+ // Secondary actions, never a filled one — the pane is read, not operated.
+ // Two of them since the merge with main: the update check, and the dial
+ // flash, which on Linux and Windows has no native menu item to live in.
+ expect(
+ find.byKey(const Key('settings-check-updates-button')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const Key('settings-flash-firmware-button')),
+ findsOneWidget,
+ );
+ expect(find.byType(OutlinedButton), findsNWidgets(2));
+ expect(find.byType(FilledButton), findsNothing);
+ },
+ );
testWidgets('the pill names the waiting version', (tester) async {
final notifier = await pumpAbout(tester);
diff --git a/desktop/test/advanced_agent_keyboard_test.dart b/desktop/test/advanced_agent_keyboard_test.dart
new file mode 100644
index 000000000..a3dd73a1a
--- /dev/null
+++ b/desktop/test/advanced_agent_keyboard_test.dart
@@ -0,0 +1,269 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/agent_picker.dart';
+import 'package:harness/widgets/new_agent_dialog.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'support/agent_picker.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final launches = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ for (final engine in ['claude', 'codex', 'opencode'])
+ {'engine': engine, 'installed': true},
+ ],
+ };
+ }
+ if (type == 'agent_create') {
+ launches.add(payload);
+ return {'error': 'Recorded without creating an agent'};
+ }
+ return {};
+ }
+}
+
+Future<_Connection> _open(WidgetTester tester, {MemoryKeymap? keymap}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.reset);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ app.machineStates['m']!.nodeOnline = true;
+ addTearDown(app.dispose);
+ Widget opener() => Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'm',
+ source: 'test',
+ initialEngine: 'codex',
+ initialFolder: '/work/project',
+ ),
+ child: const Text('Open'),
+ ),
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ home: keymap == null
+ ? opener()
+ : KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ enabled: () => false,
+ actions: const {},
+ child: opener(),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ await openAgentSearch(tester);
+ return connection;
+}
+
+void main() {
+ for (final mapped in [false, true]) {
+ testWidgets(
+ 'modified Enter chooses the visible agent without launching the form (keymap: $mapped)',
+ (tester) async {
+ final map = mapped ? MemoryKeymap() : null;
+ if (map != null) addTearDown(map.dispose);
+ final connection = await _open(tester, keymap: map);
+ await tester.enterText(agentSearch, 'opencode');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await tester.pumpAndSettle();
+ expect(connection.launches, isEmpty);
+ expect(agentSearch, findsNothing);
+ expect(
+ tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ 'opencode',
+ );
+ expect(find.byType(AlertDialog), findsOneWidget);
+ // On macOS Ctrl-Enter also belongs to the open picker, even though
+ // the form accepts it as an alternative creation shortcut.
+ await openAgentSearch(tester);
+ await tester.enterText(agentSearch, 'claude');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter, ctrl: true);
+ await tester.pumpAndSettle();
+ expect(connection.launches, isEmpty);
+ if (agentSearch.evaluate().isEmpty) await openAgentSearch(tester);
+ final editor = tester.widget<TextField>(agentSearch);
+ final chosen = tester
+ .widget<AgentPicker>(find.byType(AgentPicker))
+ .value;
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'co',
+ selection: TextSelection.collapsed(offset: 2),
+ composing: TextRange(start: 0, end: 2),
+ ),
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter, ctrl: true);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(agentSearch, findsOneWidget);
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
+ expect(connection.launches, isEmpty);
+ expect(
+ tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ chosen,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+ }
+
+ testWidgets('advanced search uses live remapped keys and hints', (
+ tester,
+ ) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply('''{"bindings":[
+ {"keys":"ctrl+slash","command":null,"when":"picker"},
+ {"keys":"f6","command":"picker.toggle_preview","when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"}
+ ]}''');
+ final connection = await _open(tester, keymap: map);
+ await tester.enterText(agentSearch, 'opencode');
+ await tester.pump();
+ final preview = find.byKey(const ValueKey('new-agent-agent-preview'));
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsNothing);
+ await key(tester, LogicalKeyboardKey.f6);
+ expect(preview, findsOneWidget);
+ expect(
+ find.textContaining(RegExp('f6 preview', caseSensitive: false)),
+ findsOneWidget,
+ );
+ final editor = tester.widget<TextField>(agentSearch);
+ expect(editor.controller!.text, 'opencode');
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
+
+ map.apply('''{"bindings":[
+ {"keys":"ctrl+slash","command":null,"when":"picker"},
+ {"keys":"f7","command":"picker.toggle_preview","when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(
+ find.textContaining(RegExp('f7 preview', caseSensitive: false)),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.f7);
+ expect(preview, findsNothing);
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(agentSearch, findsNothing);
+ expect(connection.launches, isEmpty);
+ expect(
+ tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ 'opencode',
+ );
+ map.apply('''{"bindings":[
+ {"keys":"cmd+enter","command":null,"when":"picker"}
+ ]}''');
+ await openAgentSearch(tester);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(agentSearch, findsOneWidget);
+ expect(connection.launches, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('the workspace carries picker bindings into advanced options', (
+ tester,
+ ) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ await tester.pumpAndSettle();
+ await openAgentSearch(tester);
+ await tester.enterText(agentSearch, 'opencode');
+ await tester.pump();
+ // Ctrl-M is a configured picker alias, absent from the fallback shortcuts.
+ await key(tester, LogicalKeyboardKey.keyM, ctrl: true);
+ expect(agentSearch, findsNothing);
+ expect(
+ tester.widget<AgentPicker>(find.byType(AgentPicker)).value,
+ 'opencode',
+ );
+ expect(connection.launches, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('an open agent picker follows resizing and enlarged text', (
+ tester,
+ ) async {
+ await _open(tester);
+ await tester.enterText(agentSearch, 'code');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ final editor = tester.widget<TextField>(agentSearch);
+ final value = editor.controller!.value;
+ for (final (size, scale) in [
+ (const Size(600, 800), 1.7),
+ (const Size(700, 420), 1.0),
+ (const Size(1280, 800), 1.0),
+ ]) {
+ tester.view.physicalSize = size;
+ tester.platformDispatcher.textScaleFactorTestValue = scale;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pumpAndSettle();
+ final panel = tester.getRect(
+ find.byKey(const Key('new-agent-agent-panel')),
+ );
+ final bar = tester.getRect(agentBar);
+ expect(panel.left, greaterThanOrEqualTo(0));
+ expect(panel.right, lessThanOrEqualTo(size.width));
+ expect(panel.bottom, lessThanOrEqualTo(size.height));
+ expect(panel.width, closeTo(bar.width, 1));
+ expect(editor.controller!.value, value);
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ }
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/agent_creation_recovery_test.dart b/desktop/test/agent_creation_recovery_test.dart
index 2f55e43fb..75fdf5186 100644
--- a/desktop/test/agent_creation_recovery_test.dart
+++ b/desktop/test/agent_creation_recovery_test.dart
@@ -90,7 +90,7 @@ Future<void> _timeOut(
}
void main() {
- for (final entry in ['header', 'shortcut', 'search shortcut', 'start page']) {
+ for (final entry in ['new pane', 'shortcut', 'search shortcut', 'new tab']) {
for (final dismissal in ['outside', 'escape']) {
testWidgets('$entry creation dismisses once on $dismissal', (
tester,
@@ -104,15 +104,15 @@ void main() {
final keymap = AppKeymap();
await runtime.mount(tester, app, keymap);
switch (entry) {
- case 'header':
- await tester.tap(
- find.byKey(const ValueKey('swarm-new-agent-button')),
- );
- case 'start page':
+ case 'new pane':
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ case 'new tab':
await chord(tester, LogicalKeyboardKey.keyT);
- await tester.tap(find.byKey(const ValueKey('harness-start-new')));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
case 'search shortcut':
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
'Agent 12',
@@ -133,17 +133,8 @@ void main() {
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(find.byType(SwarmSearchResults), findsNothing);
- if (entry == 'start page') {
- expect(app.swarms, hasLength(2));
- expect(app.activeSwarmId, isNot(original));
- final field = tester.widget<TextField>(
- find.byKey(const ValueKey('harness-start-search')),
- );
- expect(field.focusNode!.hasFocus, isFalse);
- // The unused page remains usable and closes without a history entry.
- await chord(tester, LogicalKeyboardKey.keyW);
- }
expect(app.focusedPane, same(pane));
+ expect(app.activeSwarmId, original);
expect(app.swarms, hasLength(1));
expect(app.closedHistory, isEmpty);
expect(connection.calls, isEmpty);
@@ -225,7 +216,7 @@ void main() {
await mount(tester, app);
final field = find.byKey(const ValueKey('swarm-search-input'));
if (entry == 'Open') {
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
} else {
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
await tester.enterText(field, '> $entry');
@@ -342,7 +333,7 @@ void main() {
expect(app.activeSwarmId, current);
if (change == 'closed' || change == 'stale split') {
expect(app.allPanes.any((p) => p.agentId == 'created'), isFalse);
- expect(app.lastError, contains('Open Harness'));
+ expect(app.lastError, contains('New Pane'));
} else {
expect(original.panes.first, same(originalPane));
expect(original.panes.last.agentId, 'created');
@@ -369,7 +360,7 @@ void main() {
final input = <TerminalBinaryFrame>[];
final pane = app.adoptSessionForTest(terminal('a0', input));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pumpAndSettle();
await browseNewAgentProject(tester);
@@ -395,7 +386,7 @@ void main() {
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
await tester.pump();
expect(input.single.bytes, [27, 91, 66]);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
expect(find.byType(SwarmSearchResults), findsOneWidget);
expect(find.byKey(const ValueKey('create-agent-submit')), findsNothing);
expect(connection.calls, hasLength(1));
@@ -615,7 +606,7 @@ void main() {
app.stateOf('m')!.agents.any((agent) => agent.id == 'created'),
isTrue,
);
- expect(app.lastError, contains('Open Harness'));
+ expect(app.lastError, contains('New Pane'));
});
testWidgets(
diff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dart
index 61c12e368..a8f8599ef 100644
--- a/desktop/test/agent_events_test.dart
+++ b/desktop/test/agent_events_test.dart
@@ -15,6 +15,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
@@ -71,6 +72,7 @@ class FakeCreateAgentNotifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async => null;
}
diff --git a/desktop/test/agent_fork_state_test.dart b/desktop/test/agent_fork_state_test.dart
new file mode 100644
index 000000000..29642bee7
--- /dev/null
+++ b/desktop/test/agent_fork_state_test.dart
@@ -0,0 +1,262 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/fork_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+import 'swarm_screen_test.dart' show terminal;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late ForkConnection connection;
+ late AppNotifier app;
+ bool disposed = false;
+ setUp(() {
+ connection = ForkConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ disposed = false;
+ });
+ tearDown(() {
+ if (!disposed) app.dispose();
+ });
+ String getId() => connection.forks.last['creationId'] as String;
+
+ test('one fork request joins across views and a completed intent cannot fork twice', () async {
+ app.adoptSessionForTest(terminal('a0', []));
+ final attempt = app.forkAttempt(
+ 'm',
+ 'a0',
+ name: 'Separate idea',
+ prompt: ' keep\n whitespace ',
+ );
+ final first = app.forkAgent('m', 'a0', attempt: attempt);
+ expect(app.forkAgent('m', 'a0', attempt: attempt), same(first));
+ expect(
+ (await app.forkAgent('m', 'a0', name: 'Different')).error,
+ contains('original fork'),
+ );
+ expect(connection.forks, hasLength(1));
+ expect(connection.forks.single['prompt'], ' keep\n whitespace ');
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ final result = await first;
+ expect(result.error, isNull);
+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'forked']);
+ expect(app.focusedPane!.agentId, 'forked');
+ expect(await app.forkAgent('m', 'a0', attempt: attempt), same(result));
+ expect(connection.forks, hasLength(1));
+ });
+
+ test(
+ 'lost receipts only check status and preserve the returned handoff level',
+ () async {
+ final attempt = app.forkAttempt('m', 'a0', name: 'Separate idea');
+ final first = app.forkAgent('m', 'a0', attempt: attempt);
+ final id = getId();
+ connection.forkReplies.single.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ expect((await first).error, contains('not confirmed'));
+ expect(attempt.awaitingConfirmation, isTrue);
+ expect(app.forkAttempt('m', 'a0'), same(attempt));
+ var check = app.forkAgent('m', 'a0', attempt: attempt);
+ connection.checkReplies.last.complete({
+ 'creationId': id,
+ 'state': 'pending',
+ });
+ expect((await check).error, contains('still starting'));
+ check = app.forkAgent('m', 'a0', attempt: attempt);
+ connection.checkReplies.last.complete(forkReceipt(id, level: 'handoff'));
+ expect((await check).level, 'handoff');
+ expect(connection.forks, hasLength(1));
+ expect(connection.checks, [
+ {'creationId': id},
+ {'creationId': id},
+ ]);
+ },
+ );
+
+ for (final state in [
+ 'missing',
+ 'unconfirmed',
+ 'wrong receipt',
+ 'malformed',
+ ]) {
+ test('$state never allows an implicit second fork', () async {
+ final attempt = app.forkAttempt('m', 'a0', name: 'Separate idea');
+ var request = app.forkAgent('m', 'a0', attempt: attempt);
+ connection.forkReplies.single.complete(switch (state) {
+ 'wrong receipt' => forkReceipt('not-this-intent'),
+ 'malformed' => {'creationId': getId(), 'state': 'created', 'agent': {}},
+ _ => {'creationId': getId(), 'state': state},
+ });
+ expect((await request).error, isNotNull);
+ expect(attempt.locked, isTrue);
+ request = app.forkAgent('m', 'a0', attempt: attempt);
+ connection.checkReplies.last.complete({'error': 'UNKNOWN_TYPE'});
+ expect((await request).error, isNotNull);
+ expect(connection.forks, hasLength(1));
+ expect(app.discardForkAttempt('m', 'a0', attempt), isTrue);
+ final fresh = app.forkAttempt('m', 'a0', name: 'Another');
+ request = app.forkAgent('m', 'a0', attempt: fresh);
+ connection.forkReplies.last.complete(
+ forkReceipt(getId(), agentId: 'another'),
+ );
+ expect((await request).error, isNull);
+ expect(connection.forks, hasLength(2));
+ });
+ }
+
+ test(
+ 'a confirmed refusal unlocks the draft and retry has a new receipt',
+ () async {
+ final attempt = app.forkAttempt(
+ 'm',
+ 'a0',
+ name: 'Separate idea',
+ prompt: 'retry me',
+ );
+ var request = app.forkAgent('m', 'a0', attempt: attempt);
+ final id = getId();
+ connection.forkReplies.single.complete({
+ 'creationId': id,
+ 'state': 'failed',
+ 'failure': {'code': 'BUSY', 'detail': 'Try later'},
+ });
+ expect((await request).error, 'Try later');
+ expect(attempt.locked, isFalse);
+ expect(attempt.prompt, 'retry me');
+ request = app.forkAgent('m', 'a0', attempt: attempt);
+ expect(getId(), isNot(id));
+ connection.forkReplies.last.complete(forkReceipt(getId()));
+ expect((await request).error, isNull);
+ },
+ );
+
+ for (final change in ['switch', 'close', 'focus', 'full']) {
+ test('a delayed fork respects its original tab after $change', () async {
+ app.adoptSessionForTest(terminal('a0', []));
+ final source = app.activeSwarm;
+ final request = app.forkAgent('m', 'a0');
+ if (change == 'close') await app.closeSwarm(source.id);
+ if (change == 'switch') {
+ app.newSwarm(name: 'Other work');
+ app.adoptSessionForTest(terminal('a1', []));
+ }
+ if (change == 'focus') app.adoptSessionForTest(terminal('a1', []));
+ if (change == 'full') {
+ for (var i = 1; i < AppNotifier.maxPanes; i++) {
+ app.adoptSessionForTest(terminal('a$i', []));
+ }
+ }
+ final active = app.activeSwarmId;
+ final focused = app.focusedPane;
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ final result = await request;
+ expect(result.error, isNull);
+ expect(app.activeSwarmId, active);
+ expect(app.focusedPane, same(focused));
+ if (change == 'switch' || change == 'focus') {
+ expect(source.panes.any((pane) => pane.agentId == 'forked'), isTrue);
+ } else {
+ expect(app.allPanes.any((pane) => pane.agentId == 'forked'), isFalse);
+ expect(result.notice, contains('Fork created'));
+ }
+ });
+ }
+
+ for (final change in ['machine', 'session', 'removed', 'dispose']) {
+ test('a draft cannot start after its source changes by $change', () async {
+ final attempt = app.forkAttempt('m', 'a0', name: 'Separate idea');
+ if (change == 'machine') {
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine);
+ }
+ if (change == 'session') {
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Replacement',
+ engine: 'codex',
+ sessionId: 'new',
+ ),
+ ];
+ }
+ if (change == 'removed') {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0'},
+ });
+ }
+ if (change == 'dispose') {
+ app.dispose();
+ disposed = true;
+ }
+ expect(
+ (await app.forkAgent('m', 'a0', attempt: attempt)).error,
+ isNotNull,
+ );
+ expect(connection.forks, isEmpty);
+ });
+ }
+
+ test('late fork reply cannot update a replacement machine', () async {
+ final request = app.forkAgent('m', 'a0');
+ final replacement = MachineState(app.stateOf('m')!.machine);
+ app.machineStates['m'] = replacement;
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ expect((await request).error, contains('machine changed'));
+ expect(replacement.agents, isEmpty);
+ expect(app.allPanes, isEmpty);
+ });
+
+ for (final change in ['removed', 'recreated', 'renamed']) {
+ test('a late fork receipt cannot undo a $change child', () async {
+ final request = app.forkAgent('m', 'a0');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_created',
+ 'payload': {'agent': forkReceipt(null)['agent']},
+ });
+ if (change == 'renamed') {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'payload': {'agentId': 'forked', 'name': 'Fresh name'},
+ });
+ } else {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'forked'},
+ });
+ if (change == 'recreated') {
+ app
+ .stateOf('m')!
+ .agents
+ .add(
+ const Agent(
+ id: 'forked',
+ name: 'Replacement fork',
+ sessionId: 'new',
+ engine: 'codex',
+ ),
+ );
+ }
+ }
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ final result = await request;
+ expect(result.error, isNull);
+ final child = app
+ .stateOf('m')!
+ .agents
+ .where((agent) => agent.id == 'forked')
+ .firstOrNull;
+ expect(child?.name, switch (change) {
+ 'renamed' => 'Fresh name',
+ 'recreated' => 'Replacement fork',
+ _ => null,
+ });
+ if (change != 'renamed') {
+ expect(result.notice, contains('has since stopped'));
+ expect(app.allPanes, isEmpty);
+ }
+ });
+ }
+}
diff --git a/desktop/test/agent_rename_state_test.dart b/desktop/test/agent_rename_state_test.dart
new file mode 100644
index 000000000..8c499ab98
--- /dev/null
+++ b/desktop/test/agent_rename_state_test.dart
@@ -0,0 +1,202 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/rename_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+import 'swarm_screen_test.dart' show terminal;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late RenameConnection connection;
+ late AppNotifier app;
+ var disposed = false;
+ setUp(() {
+ connection = RenameConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ disposed = false;
+ });
+ tearDown(() {
+ if (!disposed) app.dispose();
+ });
+ String name([String id = 'a0']) =>
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == id).name;
+
+ test('identical renames join; separate agents rename independently and all views update', () async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ app.newSwarm();
+ app.activeSwarm.panes.add(pane);
+ final second = app.adoptSessionForTest(terminal('a0', []));
+ final request = app.renameAgent('m', 'a0', ' Fix parser ');
+ expect(
+ identical(request, app.renameAgent('m', 'a0', 'Fix parser')),
+ isTrue,
+ );
+ expect(app.pendingAgentRename('m', 'a0'), same(request));
+ expect(app.pendingAgentName('m', 'a0'), 'Fix parser');
+ expect(
+ await app.renameAgent('m', 'a0', 'Competing'),
+ contains('already in progress'),
+ );
+ final another = app.renameAgent('m', 'a1', 'Docs');
+ expect(connection.renames, [
+ {'agentId': 'a0', 'name': 'Fix parser'},
+ {'agentId': 'a1', 'name': 'Docs'},
+ ]);
+ connection.replies.first.complete({
+ 'agent': {'id': 'a0', 'name': 'Fix parser · canonical'},
+ });
+ connection.replies.last.complete({});
+ expect(await request, isNull);
+ expect(await another, isNull);
+ expect(name(), 'Fix parser · canonical');
+ expect(name('a1'), 'Docs');
+ expect(pane.session!.agentName, name());
+ expect(second.session!.agentName, name());
+ expect(app.pendingAgentRename('m', 'a0'), isNull);
+ expect(await app.renameAgent('m', 'a0', name()), isNull);
+ expect(connection.renames, hasLength(2));
+ });
+
+ test(
+ 'blank, missing, and shared agents cannot send rename requests',
+ () async {
+ expect(
+ await app.renameAgent('missing', 'a0', 'Name'),
+ 'Machine not found',
+ );
+ expect(await app.renameAgent('m', 'a0', ' '), 'Name cannot be empty');
+ expect(await app.renameAgent('m', 'gone', 'Name'), 'Agent not found');
+ final shared = MachineState(
+ const Machine(
+ machineId: 'shared',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ ),
+ )..agents = app.stateOf('m')!.agents;
+ app.machineStates['shared'] = shared;
+ expect(
+ await app.renameAgent('shared', 'a0', 'Name'),
+ contains('view-only'),
+ );
+ expect(connection.renames, isEmpty);
+ },
+ );
+
+ for (final change in ['machine', 'session', 'dispose']) {
+ test('a late rename cannot mutate a changed $change', () async {
+ final request = app.renameAgent('m', 'a0', 'Late name');
+ switch (change) {
+ case 'machine':
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..agents = [
+ const Agent(id: 'a0', name: 'Replacement', status: 'idle'),
+ ];
+ case 'session':
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ sessionId: 'replacement-session',
+ name: 'Replacement',
+ ),
+ ];
+ case 'dispose':
+ app.dispose();
+ disposed = true;
+ }
+ connection.replies.single.complete({});
+ expect(await request, contains('agent changed'));
+ if (!disposed) expect(name(), 'Replacement');
+ expect(app.pendingAgentRename('m', 'a0'), isNull);
+ });
+ }
+
+ test('deleting then reusing an id invalidates its old rename', () async {
+ final request = app.renameAgent('m', 'a0', 'Old request');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0'},
+ });
+ app.stateOf('m')!.agents.add(const Agent(id: 'a0', name: 'Recreated'));
+ connection.replies.single.complete({});
+ expect(await request, contains('agent changed'));
+ expect(name(), 'Recreated');
+ });
+
+ test(
+ 'refusals, exceptions, and timeouts release busy state for retry',
+ () async {
+ var request = app.renameAgent('m', 'a0', 'Retry');
+ connection.replies.last.complete({
+ 'error': 'REFUSED',
+ 'detail': 'Agent is read only',
+ });
+ expect(await request, 'Rename failed: Agent is read only');
+ expect(name(), 'Agent 0');
+ request = app.renameAgent('m', 'a0', 'Retry');
+ connection.replies.last.completeError(StateError('fixture detail'));
+ expect(await request, 'Could not rename the agent. Try again.');
+ request = app.renameAgent('m', 'a0', 'Retry');
+ connection.replies.last.completeError(
+ const WsRequestTimeout('agent_update'),
+ );
+ expect(await request, contains('Could not confirm'));
+ expect(app.pendingAgentRename('m', 'a0'), isNull);
+ request = app.renameAgent('m', 'a0', 'Retry');
+ connection.replies.last.complete({});
+ expect(await request, isNull);
+ expect(name(), 'Retry');
+ },
+ );
+
+ test('a later rename event wins over an older request receipt', () async {
+ final request = app.renameAgent('m', 'a0', 'Requested');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'payload': {'agentId': 'a0', 'name': 'From another client'},
+ });
+ connection.replies.single.complete({
+ 'agent': {'name': 'Requested'},
+ });
+ expect(await request, contains('From another client'));
+ expect(name(), 'From another client');
+ final retry = app.renameAgent('m', 'a0', 'Requested');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'payload': {'agentId': 'a0', 'name': 'Requested'},
+ });
+ connection.replies.last.complete({});
+ expect(await retry, isNull);
+ });
+
+ test('old inventory preserves a confirmed rename; a new inventory updates open titles', () async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ connection.inventory = Completer<Map<String, dynamic>>();
+ final oldRead = app.reloadMachineData('m');
+ await Future<void>.delayed(Duration.zero);
+ final request = app.renameAgent('m', 'a0', 'Saved name');
+ connection.replies.single.complete({});
+ expect(await request, isNull);
+ connection.inventory!.complete({
+ 'agents': [
+ {'id': 'a0', 'name': 'Agent 0', 'engine': 'codex'},
+ ],
+ });
+ await oldRead;
+ expect(name(), 'Saved name');
+ expect(pane.session!.agentName, 'Saved name');
+ connection.inventory = Completer<Map<String, dynamic>>();
+ final freshRead = app.reloadMachineData('m');
+ connection.inventory!.complete({
+ 'agents': [
+ {'id': 'a0', 'name': 'New inventory', 'engine': 'codex'},
+ ],
+ });
+ await freshRead;
+ expect(name(), 'New inventory');
+ expect(pane.session!.agentName, 'New inventory');
+ });
+}
diff --git a/desktop/test/agent_restart_state_test.dart b/desktop/test/agent_restart_state_test.dart
new file mode 100644
index 000000000..f735e220c
--- /dev/null
+++ b/desktop/test/agent_restart_state_test.dart
@@ -0,0 +1,258 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/restart_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late RestartConnection connection;
+ late AppNotifier app;
+ bool disposed = false;
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ disposed = false;
+ });
+ tearDown(() {
+ if (!disposed) app.dispose();
+ });
+ String id() => connection.requests.last['creationId'] as String;
+
+ test(
+ 'restart joins across views and preserves tabs, focus and sessions',
+ () async {
+ final source = app.adoptSessionForTest(terminal('a0', []));
+ final session = source.session;
+ app.newSwarm(name: 'Other work');
+ final other = app.adoptSessionForTest(terminal('a1', []));
+ final target = app.activeSwarm;
+ final attempt = app.restartAttempt('m', 'a0');
+ final first = app.restartAgent('m', 'a0', attempt: attempt);
+ expect(app.restartAgent('m', 'a0'), same(first));
+ connection.restartReplies.single.complete(restartReceipt(id()));
+ expect((await first).error, isNull);
+ expect(
+ await app.restartAgent('m', 'a0', attempt: attempt),
+ same(attempt.result),
+ );
+ expect(connection.requests, hasLength(1));
+ expect(app.activeSwarm, same(target));
+ expect(app.focusedPane, same(other));
+ expect(source.session, same(session));
+ expect(app.allPanes, hasLength(2));
+ },
+ );
+
+ test('lost response checks the original receipt and retains fresh-session outcome', () async {
+ final attempt = app.restartAttempt('m', 'a0');
+ var request = app.restartAgent('m', 'a0', attempt: attempt);
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ expect((await request).error, contains('not confirmed'));
+ expect(app.restartAttempt('m', 'a0'), same(attempt));
+ request = app.restartAgent('m', 'a0');
+ connection.checkReplies.last.complete({
+ 'creationId': id(),
+ 'state': 'pending',
+ });
+ expect((await request).error, contains('still restarting'));
+ request = app.restartAgent('m', 'a0');
+ connection.checkReplies.last.complete(restartReceipt(id(), resumed: false));
+ expect((await request).resumed, isFalse);
+ expect(connection.requests, hasLength(1));
+ expect(connection.checks, [
+ {'creationId': id()},
+ {'creationId': id()},
+ ]);
+ });
+
+ for (final state in [
+ 'missing',
+ 'unconfirmed',
+ 'wrong receipt',
+ 'malformed',
+ 'wrong agent',
+ ]) {
+ test('$state cannot implicitly repeat the restart', () async {
+ final attempt = app.restartAttempt('m', 'a0');
+ final request = app.restartAgent('m', 'a0');
+ final previous = id();
+ connection.restartReplies.single.complete(switch (state) {
+ 'wrong receipt' => restartReceipt('another-intent'),
+ 'malformed' => {'creationId': id(), 'state': 'created', 'agent': {}},
+ 'wrong agent' => restartReceipt(id(), agentId: 'a1'),
+ _ => {'creationId': id(), 'state': state},
+ });
+ expect((await request).error, isNotNull);
+ final check = app.restartAgent('m', 'a0');
+ connection.checkReplies.single.complete({'error': 'UNKNOWN_TYPE'});
+ expect((await check).error, isNotNull);
+ expect(connection.requests, hasLength(1));
+ expect(app.discardRestartAttempt('m', 'a0', attempt), isTrue);
+ final fresh = app.restartAgent('m', 'a0');
+ expect(id(), isNot(previous));
+ connection.restartReplies.last.complete(restartReceipt(id()));
+ expect((await fresh).error, isNull);
+ });
+ }
+
+ test('a confirmed refusal allows a new receipt on retry', () async {
+ final first = app.restartAgent('m', 'a0');
+ final previous = id();
+ connection.restartReplies.single.complete({
+ 'creationId': previous,
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'AGENT_BUSY',
+ 'detail': 'Wait for the other operation.',
+ },
+ });
+ expect((await first).error, 'Wait for the other operation.');
+ final retry = app.restartAgent('m', 'a0');
+ expect(id(), isNot(previous));
+ connection.restartReplies.last.complete(restartReceipt(id()));
+ expect((await retry).error, isNull);
+ });
+
+ for (final change in [
+ 'machine',
+ 'removed',
+ 'recreated',
+ 'dispose',
+ 'stop pending',
+ 'stop refused',
+ ]) {
+ test('late restart cannot undo $change', () async {
+ final first = app.restartAgent('m', 'a0');
+ Future<String?>? stop;
+ switch (change) {
+ case 'machine':
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..agents = [const Agent(id: 'a0', name: 'Replacement')];
+ case 'removed':
+ case 'recreated':
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0'},
+ });
+ if (change == 'recreated') {
+ app
+ .stateOf('m')!
+ .agents
+ .add(const Agent(id: 'a0', name: 'Replacement'));
+ }
+ case 'dispose':
+ app.dispose();
+ disposed = true;
+ case 'stop pending':
+ case 'stop refused':
+ stop = app.deleteAgent('m', 'a0');
+ if (change == 'stop refused') {
+ connection.stopReplies.single.complete({'error': 'REFUSED'});
+ await stop;
+ }
+ }
+ connection.restartReplies.single.complete(
+ restartReceipt(id(), name: 'Stale'),
+ );
+ expect((await first).error, contains('changed'));
+ expect((await first).retryable, isFalse);
+ if (!disposed) {
+ expect(app.stateOf('m')!.agents.any((a) => a.name == 'Stale'), isFalse);
+ }
+ if (change == 'stop pending') {
+ connection.stopReplies.single.complete({'deleted': true});
+ await stop;
+ }
+ });
+ }
+
+ test('a changed source before dispatch sends nothing; reopening uses the current source', () async {
+ final old = app.restartAttempt('m', 'a0');
+ app.stateOf('m')!.agents[0] = const Agent(
+ id: 'a0',
+ name: 'New session',
+ sessionId: 'new',
+ );
+ expect(
+ (await app.restartAgent('m', 'a0', attempt: old)).error,
+ contains('changed'),
+ );
+ expect(connection.requests, isEmpty);
+ expect(app.restartAttempt('m', 'a0'), isNot(same(old)));
+ });
+
+ test(
+ 'newer name and session observations outrank an old restart receipt',
+ () async {
+ final first = app.restartAgent('m', 'a0');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'payload': {'agentId': 'a0', 'name': 'A better name'},
+ });
+ connection.restartReplies.single.complete(
+ restartReceipt(id(), sessionId: 'fresh', resumed: false),
+ );
+ await first;
+ expect(
+ app.stateOf('m')!.agents.firstWhere((a) => a.id == 'a0').name,
+ 'A better name',
+ );
+ final second = app.restartAgent('m', 'a0');
+ app.stateOf('m')!.agents[0] = const Agent(
+ id: 'a0',
+ name: 'Latest',
+ sessionId: 'later',
+ );
+ connection.restartReplies.last.complete(
+ restartReceipt(id(), sessionId: 'old'),
+ );
+ await second;
+ expect(app.stateOf('m')!.agents[0].sessionId, 'later');
+ expect(app.stateOf('m')!.agents[0].name, 'Latest');
+ },
+ );
+
+ test(
+ 'inventory begun before restart cannot undo its fresh session',
+ () async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ final read = app.reloadMachineData('m');
+ await Future<void>.delayed(Duration.zero);
+ final restart = app.restartAgent('m', 'a0');
+ connection.restartReplies.single.complete(
+ restartReceipt(id(), sessionId: 'fresh'),
+ );
+ await restart;
+ connection.inventory!.complete({
+ 'agents': [
+ {'id': 'a0', 'name': 'Old', 'sessionId': 'old'},
+ ],
+ });
+ await read;
+ expect(app.stateOf('m')!.agents.single.sessionId, 'fresh');
+ },
+ );
+
+ test('missing and shared agents cannot restart', () async {
+ expect(
+ (await app.restartAgent('missing', 'a0')).error,
+ 'Machine not found',
+ );
+ expect((await app.restartAgent('m', 'missing')).error, contains('changed'));
+ app.stateOf('m')!.machine = const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ expect((await app.restartAgent('m', 'a0')).error, contains('view-only'));
+ expect(connection.requests, isEmpty);
+ });
+}
diff --git a/desktop/test/agent_stop_state_test.dart b/desktop/test/agent_stop_state_test.dart
new file mode 100644
index 000000000..8d756f118
--- /dev/null
+++ b/desktop/test/agent_stop_state_test.dart
@@ -0,0 +1,208 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/stop_connection.dart';
+import 'swarm_state_test.dart' show createApp;
+import 'swarm_screen_test.dart' show terminal;
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late StopConnection connection;
+ late AppNotifier app;
+ var disposed = false;
+ setUp(() {
+ connection = StopConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ disposed = false;
+ });
+ tearDown(() {
+ if (!disposed) app.dispose();
+ });
+
+ for (final change in ['machine', 'session', 'removed', 'recreated']) {
+ test(
+ 'confirmation cannot stop a target changed by $change before accepting',
+ () async {
+ final confirm = app.prepareAgentStop('m', 'a0');
+ if (change == 'machine') {
+ app.machineStates['m'] = MachineState(app.stateOf('m')!.machine)
+ ..agents = [const Agent(id: 'a0', name: 'Other machine')];
+ } else if (change == 'session') {
+ app.stateOf('m')!.agents = [
+ const Agent(id: 'a0', name: 'Restarted', sessionId: 'replacement'),
+ ];
+ } else {
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0'},
+ });
+ if (change == 'recreated') {
+ app
+ .stateOf('m')!
+ .agents
+ .add(const Agent(id: 'a0', name: 'Recreated'));
+ }
+ }
+ expect(await confirm(), contains('The agent changed'));
+ expect(connection.stops, isEmpty);
+ },
+ );
+ }
+
+ test(
+ 'confirmation still applies after an ordinary name or inventory update',
+ () async {
+ final confirm = app.prepareAgentStop('m', 'a0');
+ app.stateOf('m')!.agents = [
+ const Agent(id: 'a0', name: 'Renamed by another view', engine: 'codex'),
+ ];
+ final request = confirm();
+ expect(connection.stops, ['a0']);
+ connection.stopReplies.single.complete({'deleted': true});
+ expect(await request, isNull);
+ },
+ );
+
+ test('stop joins across views, blocks conflicting actions and removes only its panes', () async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final first = app.activeSwarm;
+ app.newSwarm();
+ app.activeSwarm.panes.add(pane);
+ final other = app.adoptSessionForTest(terminal('a1', []));
+ final stopping = app.deleteAgent('m', 'a0');
+ expect(app.deleteAgent('m', 'a0'), same(stopping));
+ expect(app.pendingAgentStop('m', 'a0'), same(stopping));
+ expect(await app.renameAgent('m', 'a0', 'New'), contains('stopping'));
+ expect((await app.restartAgent('m', 'a0')).error, contains('stopping'));
+ expect(connection.renames, isEmpty);
+ expect(connection.restarts, 0);
+ connection.stopReplies.single.complete({'deleted': true});
+ expect(await stopping, isNull);
+ expect(connection.stops, ['a0']);
+ expect(first.panes, isEmpty);
+ expect(app.allPanes, [other]);
+ expect(pane.session, isNull);
+ expect(app.stateOf('m')!.agents.any((a) => a.id == 'a0'), isFalse);
+ });
+
+ for (final change in ['machine', 'session', 'dispose']) {
+ test('late stop cannot remove a changed $change', () async {
+ final stop = app.deleteAgent('m', 'a0');
+ if (change == 'dispose') {
+ app.dispose();
+ disposed = true;
+ } else {
+ final state = change == 'machine'
+ ? MachineState(app.stateOf('m')!.machine)
+ : app.stateOf('m')!;
+ state.agents = [
+ Agent(
+ id: 'a0',
+ sessionId: change == 'session' ? 'new' : null,
+ name: 'Replacement',
+ ),
+ ];
+ app.machineStates['m'] = state;
+ }
+ connection.stopReplies.single.complete({'deleted': true});
+ expect(await stop, contains('agent changed'));
+ if (!disposed) {
+ expect(app.stateOf('m')!.agents.single.name, 'Replacement');
+ }
+ });
+ }
+
+ test(
+ 'a delete event confirms early, and an old receipt cannot stop a reused id',
+ () async {
+ final stop = app.deleteAgent('m', 'a0');
+ await app.handleEventForTest('m', {
+ 'type': 'agent_deleted',
+ 'payload': {'agentId': 'a0'},
+ });
+ expect(await stop, isNull);
+ expect(app.pendingAgentStop('m', 'a0'), isNull);
+ app.stateOf('m')!.agents.add(const Agent(id: 'a0', name: 'Recreated'));
+ final newStop = app.deleteAgent('m', 'a0');
+ expect(newStop, isNot(same(stop)));
+ connection.stopReplies.first.completeError(
+ const WsRequestTimeout('agent_delete'),
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(app.stateOf('m')!.agents.last.name, 'Recreated');
+ expect(app.pendingAgentStop('m', 'a0'), same(newStop));
+ connection.stopReplies.last.complete({
+ 'error': 'REFUSED',
+ 'detail': 'Still working',
+ });
+ expect(await newStop, 'Stop failed: Still working');
+ expect(app.stateOf('m')!.agents.last.name, 'Recreated');
+ },
+ );
+
+ test(
+ 'refusal, timeout and exception keep the agent and allow retry',
+ () async {
+ for (final failure in [
+ {'error': 'REFUSED', 'detail': 'Try after reconnecting'},
+ const WsRequestTimeout('agent_delete'),
+ StateError('fixture detail'),
+ ]) {
+ final stop = app.deleteAgent('m', 'a0');
+ if (failure is Map<String, dynamic>) {
+ connection.stopReplies.last.complete(failure);
+ } else {
+ connection.stopReplies.last.completeError(failure);
+ }
+ expect(await stop, isNotNull);
+ expect(app.pendingAgentStop('m', 'a0'), isNull);
+ expect(app.stateOf('m')!.agents.any((a) => a.id == 'a0'), isTrue);
+ }
+ final stop = app.deleteAgent('m', 'a0');
+ connection.stopReplies.last.complete({'deleted': true});
+ expect(await stop, isNull);
+ },
+ );
+
+ test('missing and shared targets cannot send a stop', () async {
+ expect(await app.deleteAgent('unknown', 'a0'), 'Machine not found');
+ expect(await app.deleteAgent('m', 'unknown'), contains('no longer listed'));
+ app.stateOf('m')!.machine = const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ expect(await app.deleteAgent('m', 'a0'), contains('view-only'));
+ expect(connection.stops, isEmpty);
+ });
+
+ for (final recreated in [false, true]) {
+ test('old inventory cannot undo a stop (recreated: $recreated)', () async {
+ connection.inventory = Completer<Map<String, dynamic>>();
+ final read = app.reloadMachineData('m');
+ await Future<void>.delayed(Duration.zero);
+ final stop = app.deleteAgent('m', 'a0');
+ connection.stopReplies.single.complete({'deleted': true});
+ expect(await stop, isNull);
+ if (recreated) {
+ app.stateOf('m')!.agents.add(const Agent(id: 'a0', name: 'Recreated'));
+ }
+ connection.inventory!.complete({
+ 'agents': [
+ {'id': 'a0', 'name': 'Old name', 'engine': 'codex'},
+ ],
+ });
+ await read;
+ final current = app
+ .stateOf('m')!
+ .agents
+ .where((a) => a.id == 'a0')
+ .firstOrNull;
+ expect(current?.name, recreated ? 'Recreated' : isNull);
+ });
+ }
+}
diff --git a/desktop/test/benchmarks/swarm_benchmark.dart b/desktop/test/benchmarks/swarm_benchmark.dart
index 82724d8d4..04ba7ad73 100644
--- a/desktop/test/benchmarks/swarm_benchmark.dart
+++ b/desktop/test/benchmarks/swarm_benchmark.dart
@@ -1,6 +1,9 @@
// Run explicitly: flutter test test/benchmarks/swarm_benchmark.dart --reporter expanded
// These are headless CPU measurements, not network or display latency claims.
+// Optional dock CPU samples: set HARNESS_DOCK_CPU_PROFILE to a temporary file
+// prefix and pass --enable-vmservice --name 'command dock widget benchmark'.
import 'dart:convert';
+import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -18,6 +21,8 @@ import 'package:harness/widgets/terminal_panel.dart';
import '../swarm_screen_test.dart' show mount;
import '../swarm_state_test.dart' show createApp;
+import '../keymap_host_test.dart' show key;
+import '../support/cpu_profile.dart';
Map<String, num> distribution(List<int> microseconds) {
microseconds.sort();
@@ -45,6 +50,122 @@ Map<String, num> measure(void Function() operation, {void Function()? setup}) {
}
void main() {
+ for (final agentCount in [2000, 10000]) {
+ testWidgets('command dock widget benchmark with $agentCount harnesses', (
+ tester,
+ ) async {
+ var usedTransport = false;
+ final app = createApp(
+ connectionForTest: (_) {
+ usedTransport = true;
+ throw StateError('The offline benchmark must not contact a machine');
+ },
+ );
+ app.machineStates['m']!.agents = [
+ for (var i = 0; i < agentCount; i++)
+ Agent(
+ id: 'a$i',
+ name: 'Harness Task $i',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'Project ${i % 50}',
+ cwd: '/work/project-${i % 50}',
+ branch: 'main',
+ ),
+ ),
+ ];
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a0',
+ agentName: 'Harness Task 0',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )..status = TerminalSessionStatus.controlling,
+ );
+ await mount(tester, app);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ final profilePath = Platform.environment['HARNESS_DOCK_CPU_PROFILE'];
+ final profile = profilePath == null
+ ? null
+ : await tester.runAsync(BenchmarkCpuProfile.start);
+ if (profile != null) {
+ addTearDown(() => tester.runAsync(profile.close));
+ }
+ Future<Map<String, num>> timed(
+ Future<void> Function() operation, {
+ Future<void> Function()? setup,
+ }) async {
+ for (var i = 0; i < 8; i++) {
+ await setup?.call();
+ await operation();
+ }
+ final samples = <int>[];
+ for (var i = 0; i < 50; i++) {
+ await setup?.call();
+ final watch = Stopwatch()..start();
+ await operation();
+ samples.add(watch.elapsedMicroseconds);
+ }
+ return distribution(samples);
+ }
+
+ Future<void> type(String query) async {
+ await tester.enterText(field, query);
+ await tester.pump();
+ }
+
+ final reopen = await timed(
+ () async {
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pump();
+ expect(field, findsOneWidget);
+ },
+ setup: () async {
+ if (field.evaluate().isNotEmpty) {
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ },
+ );
+ final query = await timed(() => type('harness'), setup: () => type(''));
+ final queryGrowth = await timed(
+ () => type('harness'),
+ setup: () => type('harnes'),
+ );
+ final narrow = await timed(
+ () => type('harness 12'),
+ setup: () => type('harness'),
+ );
+ await type('harness');
+ final move = await timed(() async {
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ await tester.pump();
+ });
+ final retarget = await timed(() async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pump();
+ });
+ expect(tester.widget<TextField>(field).controller!.text, 'harness');
+ expect(usedTransport, isFalse);
+ expect(tester.takeException(), isNull);
+ debugPrint(
+ 'SWARM_BENCH ${jsonEncode({'kind': 'headless_debug_widget_elapsed', 'operation': 'command_dock', 'agents': agentCount, 'reopen': reopen, 'broadQuery': query, 'queryGrowth': queryGrowth, 'narrowQuery': narrow, 'arrow': move, 'cmdPThenCmdT': retarget})}',
+ );
+ if (profile != null) {
+ await tester.runAsync(
+ () => profile.save('$profilePath-$agentCount.json'),
+ );
+ }
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+ }
+
for (final sampleText in ['abcd', '界 ']) {
test(
'terminal output CPU benchmark for ${sampleText == 'abcd' ? 'ASCII' : 'Unicode'}',
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index 230a4e082..0a6edb08c 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -94,6 +94,7 @@ class _ReadyEnvironmentProvisioner extends EnvironmentProvisioner {
for (final step in EnvironmentStep.values)
step: EnvironmentStepStatus.ready,
},
+ phase: EnvironmentSetupPhase.ready,
);
onProgress(ready);
return ready;
@@ -319,6 +320,7 @@ void main() {
for (final step in EnvironmentStep.values)
step: EnvironmentStepStatus.ready,
},
+ phase: EnvironmentSetupPhase.ready,
);
final storage = _FakeKeyValueStore();
final provisioner = _ScriptedEnvironmentProvisioner([stuck, ready]);
@@ -837,7 +839,7 @@ void main() {
),
);
await tester.pumpAndSettle();
- expect(find.text('New Harness'), findsWidgets);
+ expect(find.text('New Pane'), findsWidgets);
expect(
tester
.widget<TextField>(
@@ -847,15 +849,20 @@ void main() {
.hasFocus,
isTrue,
);
- expect(find.byKey(const ValueKey('harness-start-open')), findsOneWidget);
- await tester.tap(find.byKey(const ValueKey('harness-start-new')));
+ expect(
+ find.byKey(const ValueKey('harness-start-new-tab')),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const ValueKey('harness-start-new-pane')));
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
// With no machine to open an agent on, the start page's New goes to
- // linking one — the fork between a computer and a server, first.
+ // linking one, with the desktop and server setup choices in its picker.
expect(find.text('Link another machine'), findsOneWidget);
- expect(find.text('A computer with a screen'), findsOneWidget);
- expect(find.text('A server over SSH'), findsOneWidget);
- await tester.tap(find.text('Close'));
+ expect(find.text('Set up a desktop'), findsOneWidget);
+ expect(find.text('Set up a server over SSH'), findsOneWidget);
+ await tester.tap(find.text('esc close'));
await tester.pumpAndSettle();
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
@@ -926,11 +933,13 @@ void main() {
tester.element(find.byType(Placeholder)),
app,
const ManualUpdateCheck(
- update: UpdateInfo(
- version: '1.2.3',
- url: 'https://example.test/Harness-macos.zip',
- sha256: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
- size: 1,
+ check: DesktopUpdateCheck.available(
+ UpdateInfo(
+ version: '1.2.3',
+ url: 'https://example.test/Harness-macos.zip',
+ sha256: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
+ size: 1,
+ ),
),
isSkipped: true,
),
@@ -991,6 +1000,11 @@ void main() {
);
await tester.pump();
+ expect(find.text('Harness is offline'), findsOneWidget);
+ expect(app.panes.single.agentId, 'offline-agent');
+ await tester.binding.setSurfaceSize(const Size(800, 560));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pump();
expect(
find.text('Harness is not running on this computer.'),
findsOneWidget,
@@ -1048,10 +1062,7 @@ void main() {
expect(find.text('Link this machine'), findsOneWidget);
expect(
- find.text(
- "This computer isn't linked to remote-mac yet. Enter the remote password set "
- 'on that machine to connect.',
- ),
+ find.text('Enter the remote password set on this machine.'),
findsOneWidget,
);
expect(find.text('Harness is offline'), findsNothing);
@@ -1115,10 +1126,7 @@ void main() {
expect(find.text('Link this machine'), findsOneWidget);
expect(
- find.text(
- "This computer isn't linked to link-mac yet. Enter the remote password set "
- 'on that machine to connect.',
- ),
+ find.text('Enter the remote password set on this machine.'),
findsOneWidget,
);
app.dispose();
diff --git a/desktop/test/box_flows_test.dart b/desktop/test/box_flows_test.dart
new file mode 100644
index 000000000..6313202de
--- /dev/null
+++ b/desktop/test/box_flows_test.dart
@@ -0,0 +1,462 @@
+import 'support/launch_menu.dart';
+
+import 'dart:async';
+
+import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+
+import 'support/mixed_agents.dart';
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _CancelFolder extends FileSelectorPlatform {
+ final answer = Completer<String?>();
+ @override
+ Future<String?> getDirectoryPath({
+ String? initialDirectory,
+ String? confirmButtonText,
+ }) => answer.future;
+}
+
+/// The box, driven through the whole screen the way a person drives it: the
+/// flows where work could be lost or a key could quietly do nothing.
+void main() {
+ final line = find.byKey(const ValueKey('new-harness-input'));
+ final box = find.byKey(const ValueKey('new-harness-box'));
+
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
+
+ Future<void> open(WidgetTester tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ await app.addAgentToSwarm('m', 'a0');
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ }
+
+ NewHarnessController creation(WidgetTester tester) =>
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+
+ Future<void> editTask(WidgetTester tester) async {
+ creation(tester).focusField(NewHarnessField.task);
+ await tester.pump();
+ }
+
+ Future<void> close(WidgetTester tester) async {
+ for (var i = 0; box.evaluate().isNotEmpty && i < 4; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ expect(box, findsNothing);
+ }
+
+ testWidgets('edited defaults survive Escape before a task is typed', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final creation = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ creation.focusField(NewHarnessField.agent);
+ await tester.pump();
+ await tester.enterText(line, 'OpenCode');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ creation.setFolder('/work/selected-before-task');
+ await tester.pump();
+ expect(creation.task, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final restored = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(restored.task, isEmpty);
+ expect(restored.engine, 'opencode');
+ expect(restored.project.folder, '/work/selected-before-task');
+ expect(restored.field, NewHarnessField.launch);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('cancelling a folder browser returns to project input', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ addTearDown(app.dispose);
+ final previous = FileSelectorPlatform.instance;
+ final picker = _CancelFolder();
+ FileSelectorPlatform.instance = picker;
+ addTearDown(() => FileSelectorPlatform.instance = previous);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final creation = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ creation.focusField(NewHarnessField.project);
+ creation.move(
+ creation.options.indexWhere(
+ (row) => row.id == NewHarnessController.browseId,
+ ) -
+ creation.cursor,
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ FocusManager.instance.primaryFocus?.unfocus();
+ await tester.pump();
+ picker.answer.complete(null);
+ await tester.pumpAndSettle();
+ expect(creation.field, NewHarnessField.project);
+ expect(tester.widget<TextField>(line).focusNode!.hasFocus, isTrue);
+ await tester.enterText(line, 'payments processing');
+ await tester.pump();
+ expect(creation.query, 'payments processing');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('Escape keeps what was typed for the next ⌘N', (tester) async {
+ await open(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ await editTask(tester);
+ await tester.enterText(line, 'fix the flaky login test');
+ await tester.pump();
+ await close(tester);
+ // Up to two thousand characters, and Escape is the most-pressed key here.
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ expect(creation(tester).task, 'fix the flaky login test');
+ await editTask(tester);
+ expect(
+ tester.widget<TextField>(line).controller!.text,
+ 'fix the flaky login test',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('the arrows move the caret in a task of several lines', (
+ tester,
+ ) async {
+ await open(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ await editTask(tester);
+ await tester.enterText(line, 'first line\nsecond line');
+ await tester.pump();
+ final field = tester.widget<TextField>(line);
+ expect(field.maxLines, greaterThan(1));
+ field.controller!.selection = const TextSelection.collapsed(offset: 22);
+ await tester.pump();
+ // Matched keys are consumed by the keymap whether or not anything handles
+ // them, so on the task the arrows have to be handed to the text field.
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await tester.pump();
+ expect(field.controller!.selection.baseOffset, lessThan(11));
+ // Still the task, and nothing was made.
+ expect(box, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('⌥↵ breaks the line in the task; it does not make the harness', (
+ tester,
+ ) async {
+ await open(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ await editTask(tester);
+ await tester.enterText(line, 'one');
+ await tester.pump();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ await tester.pump();
+ expect(tester.widget<TextField>(line).controller!.text, 'one\n');
+ expect(box, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('⌘N from the empty workspace picker keeps what was typed there', (
+ tester,
+ ) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ final start = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.tap(start);
+ await tester.pump();
+ await tester.enterText(start, 'write the docs');
+ await tester.pump();
+ // ⌘N used to throw this away; only the create row kept it. (The page's
+ // own New Harness button is hidden while its results are showing.)
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(box, findsOneWidget);
+ expect(creation(tester).task, 'write the docs');
+ expect(creation(tester).field, NewHarnessField.launch);
+ expect(creation(tester).project.generated, isNotNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('Tab completes an agent and Enter accepts it', (tester) async {
+ await open(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final controller = creation(tester);
+ final previous = controller.engine;
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ await tester.enterText(line, 'open');
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(controller.query, 'OpenCode');
+ expect(controller.engine, previous);
+ expect(controller.field, NewHarnessField.agent);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(controller.field, NewHarnessField.launch);
+ expect(controller.engine, 'opencode');
+ await close(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a draft comes back once, not under every later ⌘N', (
+ tester,
+ ) async {
+ await open(tester);
+ Future<String> reopen() async {
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ await editTask(tester);
+ return tester.widget<TextField>(line).controller!.text;
+ }
+
+ expect(await reopen(), isEmpty);
+ await tester.enterText(line, 'for the auth project');
+ await tester.pump();
+ await close(tester);
+ expect(await reopen(), 'for the auth project');
+ // Cleared by hand and dismissed: it is gone, not resurrected.
+ await tester.enterText(line, '');
+ await tester.pump();
+ await close(tester);
+ expect(await reopen(), isEmpty);
+ await close(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'drafts stay with their source project and retain edited defaults',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ final auth = app.adoptSessionForTest(terminal('a0', []));
+ final docs = app.adoptSessionForTest(terminal('a2', []));
+ app.focusPane(auth.id);
+ await mount(tester, app);
+
+ Future<NewHarnessController> resume() async {
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await editTask(tester);
+ return tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ }
+
+ Future<void> cancel() async {
+ await close(tester);
+ }
+
+ var creation = await resume();
+ await tester.enterText(
+ line,
+ ' Investigate the redirect\nDo not change code ',
+ );
+ await tester.pump();
+ creation.focusField(NewHarnessField.mode);
+ creation.accept(
+ const NewHarnessOption(id: 'readOnly', title: 'Read only'),
+ );
+ creation.focusField(NewHarnessField.machine);
+ creation.accept(
+ const NewHarnessOption(id: 'studio', title: 'iMac · Office'),
+ );
+ creation.setFolder('/work/isolated-auth');
+ creation.focusField(NewHarnessField.task);
+ await tester.pump();
+ await cancel();
+
+ // Starting in another project must never put the auth task one Return
+ // away from running there. That project keeps its own in-progress task.
+ app.focusPane(docs.id);
+ creation = await resume();
+ expect(creation.task, isEmpty);
+ expect(creation.machineId, 'm');
+ expect(creation.project.folder, '/work/release-notes');
+ await tester.enterText(line, 'Explain the release notes');
+ await tester.pump();
+ await cancel();
+
+ app.focusPane(auth.id);
+ creation = await resume();
+ expect(creation.task, ' Investigate the redirect\nDo not change code ');
+ expect(creation.engine, 'codex');
+ expect(creation.machineId, 'studio');
+ expect(creation.project.folder, '/work/isolated-auth');
+ expect(creation.mode, 'readOnly');
+ await cancel();
+
+ app.focusPane(docs.id);
+ creation = await resume();
+ expect(creation.task, 'Explain the release notes');
+ expect(creation.machineId, 'm');
+ expect(creation.project.folder, '/work/release-notes');
+ await cancel();
+ await tester.pump(const Duration(milliseconds: 60));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final otherMachine in [false, true]) {
+ testWidgets(
+ 'same-project drafts are isolated across ${otherMachine ? 'machines' : 'agents'}',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ final sourceAgent = app.machineStates['m']!.agents.first;
+ final machineId = otherMachine ? 'studio' : 'm';
+ final agentId = otherMachine ? sourceAgent.id : 'a1';
+ app.machineStates[machineId]!.agents = [
+ if (!otherMachine) sourceAgent,
+ Agent(
+ id: agentId,
+ name: 'Another feature',
+ engine: sourceAgent.engine,
+ terminalAvailable: true,
+ project: sourceAgent.project,
+ ),
+ ];
+ final source = app.adoptSessionForTest(terminal(sourceAgent.id, []));
+ final other = app.adoptSessionForTest(
+ TerminalSession(
+ machineId: machineId,
+ agentId: agentId,
+ agentName: 'Another feature',
+ engineId: 'codex',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'other-feature',
+ );
+ app.focusPane(source.id);
+ await mount(tester, app);
+ Future<NewHarnessController> resume() async {
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await editTask(tester);
+ return tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ }
+
+ Future<void> cancel() async {
+ await close(tester);
+ }
+
+ var creation = await resume();
+ await tester.enterText(line, 'Inspect authentication');
+ await tester.pump();
+ creation.focusField(NewHarnessField.mode);
+ creation.accept(
+ const NewHarnessOption(id: 'readOnly', title: 'Read only'),
+ );
+ await cancel();
+ app.focusPane(other.id);
+ creation = await resume();
+ expect(creation.task, isEmpty);
+ expect(creation.machineId, machineId);
+ await tester.enterText(line, 'Update feature documentation');
+ await tester.pump();
+ await cancel();
+
+ app.focusPane(source.id);
+ creation = await resume();
+ expect(creation.task, 'Inspect authentication');
+ expect(creation.mode, 'readOnly');
+ await cancel();
+ // Explicit text in search starts the requested task using the source's
+ // defaults, without touching another context's draft.
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Implement a new redirect',
+ );
+ await tester.pump();
+ creation = await resume();
+ expect(creation.task, 'Implement a new redirect');
+ expect(creation.mode, 'auto');
+ expect(creation.machineId, 'm');
+ expect(creation.project.folder, sourceAgent.project!.cwd);
+ await cancel();
+ app.focusPane(other.id);
+ expect((await resume()).task, 'Update feature documentation');
+ await cancel();
+ await tester.pump(const Duration(milliseconds: 60));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'a list field chooses with Return and comes back to the launch menu',
+ (tester) async {
+ await open(tester);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ // The key guide keeps the same action while filtering choices.
+ expect(find.textContaining('choose', findRichText: true), findsOneWidget);
+ await tester.enterText(line, 'open');
+ await tester.pump();
+ expect(find.textContaining('choose', findRichText: true), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box, findsOneWidget);
+ expect(creation(tester).field, NewHarnessField.launch);
+ expect(find.text('OpenCode'), findsWidgets);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/box_polish_test.dart b/desktop/test/box_polish_test.dart
new file mode 100644
index 000000000..725e000d6
--- /dev/null
+++ b/desktop/test/box_polish_test.dart
@@ -0,0 +1,399 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/box_chrome.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'keymap_host_test.dart' show key;
+
+class _PendingConnection extends WsConn {
+ _PendingConnection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final creation = Completer<Map<String, dynamic>>();
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => switch (type) {
+ 'engines_probe' => {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ ],
+ },
+ 'dsh_list' => {'dsh': []},
+ 'agent_create' => creation.future,
+ _ => {},
+ };
+}
+
+void main() {
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
+
+ testWidgets(
+ 'dock stays aligned across search, creation, resizing and preview without changing pane geometry',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ for (final size in [const Size(1280, 800), const Size(600, 540)]) {
+ tester.view.physicalSize = size;
+ await tester.pump();
+ final before = tester.getRect(find.byKey(pane.cellKey));
+ await chord(tester, LogicalKeyboardKey.keyP);
+ void aligned(Finder panel) {
+ final rect = tester.getRect(panel);
+ expect(rect.left, before.left);
+ expect(rect.right, before.right);
+ expect(rect.bottom, before.bottom);
+ expect(tester.getRect(find.byKey(pane.cellKey)), before);
+ expect(tester.takeException(), isNull);
+ }
+
+ final search = find.byKey(const ValueKey('swarm-search-results'));
+ aligned(search);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final y = tester.getRect(input).bottom;
+ await tester.enterText(input, 'Agent 1');
+ await tester.pump();
+ aligned(search);
+ expect(tester.getRect(input).bottom, y);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ aligned(search);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final create = find.byKey(const ValueKey('new-harness-box'));
+ aligned(create);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ aligned(create);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('all key hints stay visible as the prompt grows and wraps', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a69', []));
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyP);
+
+ void checkGuide() {
+ final guide = find.byType(BoxHintStrip);
+ final bounds = tester.getRect(guide);
+ final hints = find.descendant(of: guide, matching: find.byType(InkWell));
+ expect(hints, findsWidgets);
+ for (final hint in hints.evaluate()) {
+ final rect = tester.getRect(find.byWidget(hint.widget));
+ expect(bounds.contains(rect.topLeft), isTrue);
+ expect(
+ bounds.contains(rect.bottomRight - const Offset(.1, .1)),
+ isTrue,
+ );
+ }
+ expect(bounds.bottom, lessThan(800));
+ expect(tester.takeException(), isNull);
+ }
+
+ checkGuide();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ checkGuide();
+ final panel = find.byKey(const ValueKey('new-harness-box'));
+ final creation = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ creation.focusField(NewHarnessField.task);
+ await tester.pump();
+ final originalHeight = tester.getSize(panel).height;
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-input')),
+ 'Fix the login flow\nKeep the session alive\nAdd regression coverage',
+ );
+ await tester.pump();
+ expect(tester.getSize(panel).height, greaterThan(originalHeight));
+ checkGuide();
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ checkGuide();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'preview toggles without losing the query and Ctrl-C returns to the terminal',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a69', frames));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ final preview = find.byKey(const ValueKey('swarm-search-preview'));
+ await tester.enterText(field, 'Agent 1');
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final editor = tester.widget<TextField>(field);
+ final value = editor.controller!.value;
+ final selected = search.selected;
+ expect(preview, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsNothing);
+ expect(editor.controller!.value, value);
+ expect(search.selected, same(selected));
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsOneWidget);
+ expect(search.selected, same(selected));
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsNothing);
+ expect(search.selected, same(selected));
+ // Without a preview, page keys navigate the result list, retaining input.
+ final beforePage = search.cursor;
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(search.cursor, greaterThan(beforePage));
+ expect(editor.controller!.value, value);
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(search.cursor, beforePage);
+ await key(tester, LogicalKeyboardKey.keyC, ctrl: true);
+ expect(field, findsNothing);
+ expect(frames, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyC, ctrl: true);
+ expect(frames.single.bytes, [3]);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test('openable matches precede already-added exact matches', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ for (final (id, name) in [
+ ('a0', 'Auth'),
+ ('a1', 'Auth service'),
+ ('a2', 'Fix auth'),
+ ])
+ Agent(id: id, name: name, engine: 'codex', terminalAvailable: true),
+ ];
+ app.adoptSessionForTest(terminal('a0', []));
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ );
+ addTearDown(search.dispose);
+ search.setQuery('auth');
+ expect(search.rows.map((row) => row.agentId), ['a1', 'a2', 'a0', null]);
+ expect(search.selected?.agentId, 'a1');
+ expect(search.submit()?.destination.agentId, 'a1');
+ expect(search.matchCount, 3);
+
+ // An explicitly highlighted unavailable row stays selected on app updates.
+ search.move(2);
+ app.dismissError();
+ expect(search.selected?.agentId, 'a0');
+ expect(search.submit(), isNull);
+ });
+
+ testWidgets('held Tab completes without committing or changing the project', (
+ tester,
+ ) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final controller = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ controller.setFolder('/work/repo');
+ controller.focusField(NewHarnessField.agent);
+ await tester.pump();
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-input')),
+ 'open',
+ );
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(controller.engine, 'codex');
+ expect(controller.query, 'OpenCode');
+ for (var i = 0; i < 12; i++) {
+ await tester.sendKeyRepeatEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.tab);
+ expect(controller.engine, 'codex');
+ expect(controller.query, 'OpenCode');
+ expect(controller.machineId, 'm');
+ expect(controller.project.folder, '/work/repo');
+ expect(app.allPanes, hasLength(1));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'box errors are announced, including the same error after editing',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ // Agent choices now offer the Store even when no agent matches. Use
+ // the machine field to exercise an empty-choice error and announcement.
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ final controller = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ controller.focusField(NewHarnessField.machine);
+ await tester.pump();
+ for (var i = 0; i < 2; i++) {
+ await tester.enterText(input, 'zzqq');
+ await tester.pump();
+ tester.takeAnnouncements();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(controller.error, contains('Nothing matches'));
+ expect(
+ tester.takeAnnouncements(),
+ contains(isAccessibilityAnnouncement(controller.error!)),
+ );
+ await tester.enterText(input, 'zzqqx');
+ await tester.pump();
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('creation status and a lost reply are announced', (tester) async {
+ final connection = _PendingConnection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ final controller = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ controller.setFolder('/work/repo');
+ await tester.pump();
+ tester.takeAnnouncements();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(controller.busy, isTrue);
+ expect(
+ tester.takeAnnouncements(),
+ contains(isAccessibilityAnnouncement('Starting harness…')),
+ );
+ connection.creation.completeError(const WsRequestTimeout('agent_create'));
+ await tester.pump();
+ expect(controller.checking, isTrue);
+ expect(
+ tester.takeAnnouncements(),
+ contains(isAccessibilityAnnouncement(controller.error!)),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(
+ tester.takeAnnouncements(),
+ contains(isAccessibilityAnnouncement(controller.error!)),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final (width, scale) in [(1280.0, 1.0), (760.0, 1.0), (600.0, 1.7)]) {
+ testWidgets(
+ 'search ends on a whole row at width $width and text scale $scale',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('a69', []));
+ await mount(tester, app);
+ tester.view.physicalSize = Size(width, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = scale;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyP);
+ final list = find.byKey(const ValueKey('swarm-search-result-list'));
+ final row = find
+ .descendant(of: list, matching: find.byType(ListTile))
+ .first;
+ final padding = tester.widget<ListView>(list).padding! as EdgeInsets;
+ final visibleRows =
+ (tester.getSize(list).height - padding.vertical) /
+ tester.getSize(row).height;
+ expect(visibleRows, closeTo(visibleRows.roundToDouble(), .001));
+
+ // Creation stays outside the scrolling results, directly above input.
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'zzqq',
+ );
+ await tester.pump();
+ final onlyRow = find.descendant(
+ of: list,
+ matching: find.byType(ListTile),
+ );
+ expect(onlyRow, findsNothing);
+ final create = find.widgetWithText(ListTile, 'New Harness');
+ expect(create, findsOneWidget);
+ expect(
+ tester.getRect(create).bottom,
+ lessThanOrEqualTo(
+ tester
+ .getRect(find.byKey(const ValueKey('swarm-search-input')))
+ .top,
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/box_render_preview_test.dart b/desktop/test/box_render_preview_test.dart
new file mode 100644
index 000000000..bf47c0946
--- /dev/null
+++ b/desktop/test/box_render_preview_test.dart
@@ -0,0 +1,1078 @@
+import 'support/launch_menu.dart';
+
+import 'package:harness/shared/theme/appearance_prefs_store.dart';
+import 'package:harness/shared/theme/prompt_style.dart';
+
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/auth/peer_link_client.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_preset.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/engine_identity.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'swarm_search_preview_test.dart' show seedPreviews;
+import 'keymap_host_test.dart' show key;
+import 'support/agent_picker.dart' show chooseAgent;
+import 'support/mixed_agents.dart';
+import 'support/password_cli.dart';
+import 'support/machine_api.dart';
+import 'support/rename_connection.dart';
+import 'support/stop_connection.dart';
+import 'support/fork_connection.dart';
+import 'support/restart_connection.dart';
+import 'terminal_find_test.dart' show findField, finishFind, output;
+
+class _PreviewLink implements PeerLinkClient {
+ final result = Completer<CliLinkConnectResult>();
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) {
+ onProgress?.call('verifying');
+ return result.future;
+ }
+
+ @override
+ Future<CliLinkListResult> list() async => const CliLinkListResult(
+ machines: [
+ LinkedMachine(
+ machineId: 'studio',
+ fingerprint: 'AA24·B561·0B81·EF21',
+ linkedAt: '2026-09-19 12:00',
+ ),
+ ],
+ );
+ @override
+ Future<String?> unlink(String machineId) async => null;
+}
+
+class _PreviewConnection extends WsConn {
+ _PreviewConnection({this.pendingCreation = false})
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final bool pendingCreation;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => switch (type) {
+ 'engines_probe' => {
+ 'engines': [
+ for (final engine in allEngines)
+ {
+ 'engine': engine.id,
+ 'installed': true,
+ if (engine.id == 'codex') 'supportsCodexHome': true,
+ },
+ ],
+ },
+ 'codex_profiles_list' => {
+ 'profiles': [
+ {'path': '/home/developer/.codex-work', 'label': 'Work'},
+ ],
+ },
+ 'dsh_list' => {'dsh': []},
+ 'agent_create' =>
+ pendingCreation
+ ? throw const WsRequestTimeout('agent_create')
+ : throw StateError('Rendering must never create an agent'),
+ _ => {},
+ };
+}
+
+/// PICTURES OF THE BOX, WITHOUT A SCREEN.
+///
+/// A widget test draws text in Ahem — solid blocks — so nobody can judge how a
+/// surface LOOKS from one. This loads the real fonts and writes each state of
+/// the box as a PNG, so the look can be reviewed on a machine whose display is
+/// asleep or locked, in CI, or by a reviewer who cannot run the app.
+///
+/// Off unless asked for, because it depends on this Mac's system font:
+///
+/// BOX_RENDER_DIR=/tmp/box flutter test --update-goldens \\
+/// test/box_render_preview_test.dart
+Future<void> _loadFonts() async {
+ Future<void> load(String family, List<String> files) async {
+ final loader = FontLoader(family);
+ var any = false;
+ for (final path in files) {
+ final file = File(path);
+ if (!file.existsSync()) continue;
+ any = true;
+ final bytes = file.readAsBytesSync();
+ loader.addFont(Future.value(ByteData.view(bytes.buffer)));
+ }
+ if (any) await loader.load();
+ }
+
+ final flutterRoot = Platform.environment['FLUTTER_ROOT'] ?? '';
+ final materialFonts = '$flutterRoot/bin/cache/artifacts/material_fonts';
+ const system = '/System/Library/Fonts/SFNS.ttf';
+ // Whatever the theme asks for, draw it in the system face.
+ for (final family in ['Roboto', '.AppleSystemUIFont', '.SF NS', 'Inter']) {
+ await load(family, [system, '$materialFonts/Roboto-Regular.ttf']);
+ }
+ for (final family in [
+ '.AppleSystemUIFontMonospaced',
+ 'Menlo',
+ 'DejaVu Sans Mono',
+ 'monospace',
+ ]) {
+ await load(family, ['/System/Library/Fonts/Menlo.ttc']);
+ }
+ await load('MaterialIcons', ['$materialFonts/MaterialIcons-Regular.otf']);
+ final home = Platform.environment['HOME'] ?? '';
+ final lucideRoot = Directory('$home/.pub-cache/hosted/pub.dev')
+ .listSync()
+ .whereType<Directory>()
+ .where((dir) => dir.path.contains('/lucide_icons_flutter-'))
+ .map((dir) => dir.path)
+ .fold<String?>(
+ null,
+ (best, path) => best == null || path.compareTo(best) > 0 ? path : best,
+ );
+ if (lucideRoot != null) {
+ await load('packages/lucide_icons_flutter/Lucide', [
+ '$lucideRoot/assets/lucide.ttf',
+ ]);
+ for (final weight in [100, 200, 300, 400, 500, 600]) {
+ await load('packages/lucide_icons_flutter/Lucide$weight', [
+ '$lucideRoot/assets/build_font/LucideVariable-w$weight.ttf',
+ ]);
+ }
+ }
+}
+
+void main() {
+ final dir = Platform.environment['BOX_RENDER_DIR'];
+
+ testWidgets(
+ 'renders the box to PNGs',
+ skip: dir == null,
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ (tester) async {
+ await tester.runAsync(_loadFonts);
+ // Tests draw shadows as solid black slabs; a picture wants the real thing.
+ debugDisableShadows = false;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+
+ final app = createApp(connectionForTest: (_) => _PreviewConnection());
+ app.machineStates['m']!.nodeOnline = true;
+ for (final id in ['a0', 'a1']) {
+ app.adoptSessionForTest(terminal(id, []));
+ await app.addAgentToSwarm('m', id);
+ }
+ await mount(tester, app);
+
+ Future<void> shot(String name) async {
+ await tester.pump(const Duration(milliseconds: 50));
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$dir/$name.png')),
+ );
+ }
+
+ Future<void> type(Finder input, String text) async {
+ await tester.enterText(input, text);
+ await tester.pump();
+ }
+
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await shot('01-new-pane-empty');
+ await type(search, 'age');
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
+ await shot('02-new-pane-typed');
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await shot('03-new-tab-empty');
+ await type(search, 'Agent 12');
+ await shot('04-new-tab-typed');
+ await type(search, 'zzqq');
+ await shot('05-new-tab-create-only');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+
+ final line = find.byKey(const ValueKey('new-harness-input'));
+ final contextPicker = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ contextPicker.setFolder('/work/payments');
+ await app.projectHistory.select('m', '/work/payments');
+ app.machineStates['m']!.localProjects = {
+ for (final (index, name) in [
+ 'product-video',
+ 'website',
+ 'research',
+ ].indexed)
+ 'a${index + 2}': AgentProject(name: name, cwd: '/work/$name'),
+ };
+ await shot('06-launch-menu');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await shot('06-launch-agent-selected');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await shot('06-launch-project-selected');
+ tester.view.physicalSize = const Size(600, 680);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await tester.pumpAndSettle();
+ await shot('06-launch-large-text');
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await openLaunchRow(tester, 'task');
+ await tester.pump();
+ await type(line, '');
+ await shot('07-new-tab-task-empty');
+ await type(line, 'Plan the launch\nInclude the product demo');
+ await shot('07-new-tab-task-multiline');
+ await type(line, 'fix the flaky login test');
+ await shot('07-new-tab-task-typed');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ await shot('08-new-agent');
+ await type(line, 'Claude Code');
+ await key(tester, LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'agent');
+ final previewAgent = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ for (
+ var step = 0;
+ previewAgent.selected?.id != 'codex' && step < 30;
+ step++
+ ) {
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ }
+ expect(previewAgent.selected?.id, 'codex');
+ expect(previewAgent.engine, 'claude');
+ await shot('08-codex-highlighted-from-claude');
+ await type(line, 'co');
+ await shot('09-new-agent-filtered');
+ await openAgentSetting(
+ tester,
+ 'codex',
+ NewHarnessController.permissionsId,
+ );
+ await shot('09-agent-permissions');
+ await type(line, 'ask');
+ await key(tester, LogicalKeyboardKey.enter);
+ await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
+ await tester.pump(const Duration(milliseconds: 200));
+ await shot('09-codex-profiles');
+ await type(line, 'Work');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await shot('09-configured-agent');
+ await openLaunchRow(tester, 'project');
+ await tester.pump();
+ await shot('10-new-project');
+ for (final name in [
+ 'payments',
+ 'website',
+ 'research',
+ 'robotics',
+ 'music',
+ 'documents',
+ 'analytics',
+ 'launch',
+ 'support',
+ 'design',
+ 'prototype',
+ 'experiments',
+ ]) {
+ await app.projectHistory.select(contextPicker.machineId, '/work/$name');
+ }
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ await shot('10-project-many-recents');
+ await key(tester, LogicalKeyboardKey.pageUp);
+ await key(tester, LogicalKeyboardKey.pageUp);
+ await shot('10-project-older-recents');
+ tester.view.physicalSize = const Size(600, 680);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await tester.pumpAndSettle();
+ await shot('10-project-recents-large-text');
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await type(line, 'pay');
+ await shot('10-project-filtered');
+ await type(line, 'no-matching-project');
+ await shot('10-project-no-matches');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('10-existing-project');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('10-github-empty');
+ await type(line, 'https://github.com/acme/payments');
+ await shot('10-github-repository');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ contextPicker.accept(
+ contextPicker.options.firstWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ),
+ );
+ await tester.pump();
+ await shot('11-project-name-empty');
+ await type(line, 'payments processing');
+ await shot('11-new-project-named');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('11-project-selected');
+ await openLaunchRow(tester, 'machine');
+ await tester.pump();
+ await shot('12-project-machine');
+ for (var i = 0; i < 1; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ contextPicker.focusField(NewHarnessField.task);
+ contextPicker.setQuery('');
+ contextPicker.focusField(NewHarnessField.agent);
+ contextPicker.accept(const NewHarnessOption(id: 'pi', title: 'Pi'));
+ await tester.pump();
+ await shot('12-pi-task-availability');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byKey(const ValueKey('new-harness-box')), findsNothing);
+
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await shot('13-command-open');
+ await type(search, '> spl');
+ await shot('13-command-palette');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+
+ await seedPreviews(app);
+ final previousAppearance = appearancePrefsStore.value;
+ addTearDown(() => appearancePrefsStore.value = previousAppearance);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ for (final style in PromptStyle.values) {
+ appearancePrefsStore.value = previousAppearance.copyWith(
+ prompt: PromptPrefs(style: style),
+ );
+ await shot('14-prompt-${style.name}');
+ }
+ tester.view.physicalSize = const Size(600, 540);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('14-prompt-powerline-narrow');
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ appearancePrefsStore.value = previousAppearance;
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await type(search, 'Checkout');
+ await shot('14-search-preview');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final largeBox = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ largeBox.setFolder('/work/payments');
+ await shot('15-create-large-text');
+ await openLaunchRow(tester, 'task');
+ await tester.pump();
+ await shot('15-task-large-text');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await openLaunchRow(tester, 'project');
+ await tester.pump();
+ await shot('15-project-menu-large-text');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ await shot('16-agent-large-text');
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final create = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ create.focusField(NewHarnessField.projectName);
+ create.setQuery('Super terminal');
+ create.accept();
+ create.focusField(NewHarnessField.mode);
+ create.setQuery('Plan first');
+ create.accept();
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pump(const Duration(milliseconds: 200));
+ await shot('17-advanced-keeps-context');
+ await tester.tap(find.byKey(const Key('new-agent-agent-field')));
+ await tester.pump();
+ await shot('18-advanced-agent-search');
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ await shot('19-advanced-agent-preview');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('20-advanced-large-text');
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await tester.pump();
+ await chooseAgent(tester, 'codex');
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('new-agent-task')),
+ 'Review the keyboard flow\nKeep the patch small',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ await shot('21-returned-draft');
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('22-returned-draft-large-text');
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('new-agent-agent-field')));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('23-agent-search-resized-large-text');
+ tester.view.physicalSize = const Size(700, 420);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await shot('24-agent-search-resized-short');
+
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+
+ final catalogApp = createApp();
+ seedMixedAgents(catalogApp);
+ catalogApp.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, catalogApp);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ await shot('25-mixed-catalog');
+ await type(search, '?');
+ await shot('25-quick-access-help');
+ await type(search, '> zoom');
+ await shot('25-quick-access-commands');
+ await type(search, '# openharness');
+ await shot('25-quick-access-projects');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('25-quick-access-project-agents');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await type(search, '@ Office');
+ await shot('25-quick-access-machines');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('25-quick-access-machine-agents');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await type(search, 'login');
+ await shot('26-matching-same-task');
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ await shot('27-mixed-catalog-preview');
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('28-mixed-catalog-large-text');
+ await tester.pumpWidget(const SizedBox());
+ catalogApp.dispose();
+
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final pendingApp = createApp(
+ connectionForTest: (_) => _PreviewConnection(pendingCreation: true),
+ );
+ pendingApp.machineStates['m']!.nodeOnline = true;
+ pendingApp.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, pendingApp);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('29-pending-creation');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('30-resumed-pending-large-text');
+ await tester.pumpWidget(const SizedBox());
+ pendingApp.dispose();
+
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final workspaceApp = createApp();
+ seedMixedAgents(workspaceApp);
+ for (var i = 0; i < 4; i++) {
+ final session = terminal('a$i', []);
+ session.agentName = workspaceApp.machineStates['m']!.agents[i].name;
+ workspaceApp.adoptSessionForTest(session);
+ }
+ workspaceApp.setPreset(4, PanePreset.quad);
+ workspaceApp.renameSwarm(workspaceApp.activeSwarmId, 'Feature work');
+ await mount(tester, workspaceApp);
+ await tester.pump(const Duration(milliseconds: 100));
+ for (var i = 0; i < workspaceApp.panes.length; i++) {
+ final session = workspaceApp.panes[i].session!;
+ // This render fixture exercises the workspace frame; no PTY is run.
+ session.terminal.write('\x1b[36m❯\x1b[0m ');
+ }
+
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await type(search, '> resize panes');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await shot('31-keyboard-resize');
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('32-keyboard-resize-large-text');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ tester
+ .widget<IconButton>(
+ find.widgetWithIcon(IconButton, Icons.more_horiz).first,
+ )
+ .focusNode!
+ .requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('35-pane-actions-narrow');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ Focus.of(tester.element(find.byIcon(Icons.tune).first)).requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('36-model-menu-narrow');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ for (var i = 4; i < 16; i++) {
+ workspaceApp.machineStates['m']!.agents = [
+ ...workspaceApp.machineStates['m']!.agents,
+ Agent(
+ id: 'a$i',
+ name: 'Feature ${i - 2}',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ workspaceApp.newSwarm(name: 'Feature ${i - 2}');
+ workspaceApp.adoptSessionForTest(
+ terminal('a$i', [])..agentName = 'Feature ${i - 2}',
+ );
+ }
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.digit9);
+ await shot('33-many-tabs-keyboard');
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('34-many-tabs-narrow');
+ await tester.pumpWidget(const SizedBox());
+ workspaceApp.dispose();
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final findApp = createApp();
+ seedMixedAgents(findApp);
+ final readingSession = terminal('a0', [])
+ ..agentName = 'Fix login redirect';
+ findApp.adoptSessionForTest(readingSession);
+ await mount(tester, findApp);
+ await output(
+ readingSession,
+ 0,
+ 'Reviewing the redirect handler\r\n'
+ 'checkpoint: original query survives authentication\r\n'
+ 'checkpoint: sessions stay attached\r\n'
+ 'ready> ',
+ keyframe: true,
+ );
+ await chord(tester, LogicalKeyboardKey.keyF);
+ await tester.enterText(findField, 'checkpoint');
+ await finishFind(tester);
+ await shot('37-output-find');
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('38-output-find-large-text');
+ await tester.tap(find.byTooltip('Find options'));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ await shot('39-output-find-options');
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ findApp.dispose();
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final links = _PreviewLink();
+ final passwordCli = PasswordCli();
+ final linkApp = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ peerLinks: links,
+ cliLink: passwordCli,
+ )..hasNavigationRail = false;
+ seedMixedAgents(linkApp);
+ linkApp.adoptSessionForTest(terminal('a0', []));
+ linkApp.machineStates['studio']!.needsLink = true;
+ linkApp.selectedMachineId = 'studio';
+ await mount(tester, linkApp);
+ await tester.pumpAndSettle();
+ await shot('40-link-machine');
+ await tester.enterText(
+ find.byKey(const Key('remote-password-connect-field')),
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('41-link-pending');
+ links.result.complete(
+ const CliLinkConnectResult(
+ error: 'Incorrect password. Enter the password set on iMac · Office.',
+ ),
+ );
+ await tester.pumpAndSettle();
+ await shot('42-link-error');
+ tester.view.physicalSize = const Size(600, 420);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('43-link-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ linkApp.machineStates['m']!.localOnly = true;
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> link machine',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('44-machine-chooser');
+ final machineSearch = find.byKey(const Key('link-machine-search'));
+ await tester.enterText(machineSearch, 'ssh');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('45-machine-ssh-guide');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.enterText(machineSearch, 'desktop');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('46-machine-desktop-guide');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.enterText(machineSearch, 'zzzz');
+ await shot('47-machine-no-match');
+ await tester.enterText(machineSearch, 'ssh');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(600, 420);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('48-machine-guide-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> link machine',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.enterText(machineSearch, 'password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('49-own-password-prompt');
+ passwordCli.setReply = Completer<RemotePasswordSetResult>();
+ await tester.enterText(
+ find.byKey(const Key('remote-password-field')),
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.enterText(
+ find.byKey(const Key('remote-password-confirm-field')),
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('50-own-password-pending');
+ passwordCli.setReply!.complete(
+ const RemotePasswordSetResult(
+ error: 'Could not reach the local service. Try again.',
+ ),
+ );
+ await tester.pumpAndSettle();
+ await shot('51-own-password-error');
+ passwordCli.setReply = null;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('52-own-password-set');
+ await tester.tap(find.byKey(const Key('remote-password-clear-button')));
+ await tester.pumpAndSettle();
+ await shot('53-own-password-clear');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('remote-password-links-button')));
+ await tester.pumpAndSettle();
+ await shot('54-outgoing-links');
+ await tester.tap(find.byKey(const Key('unlink-studio')));
+ await tester.pumpAndSettle();
+ await shot('55-unlink-machine');
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('remote-password-change-button')));
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('56-own-password-small-large-text');
+ await tester.pumpWidget(const SizedBox());
+ linkApp.dispose();
+
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final machineApi = MachineApi();
+ final managerApp = createApp()..api = machineApi;
+ seedMixedAgents(managerApp);
+ managerApp.machineStates['m']!.localOnly = true;
+ managerApp.adoptSessionForTest(terminal('a0', []));
+ const shared = Machine(
+ machineId: 'shared-fixture',
+ name: 'Shared render server',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ ownerName: 'Morgan',
+ );
+ managerApp.machineStates['shared-fixture'] = MachineState(shared)
+ ..nodeOnline = true;
+ managerApp.machines.add(shared);
+ await mount(tester, managerApp);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> machines manager',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final managerSearch = find.byKey(const Key('machines-manager-search'));
+ await shot('57-machines-manager');
+ await tester.enterText(managerSearch, 'office');
+ await shot('58-machines-filtered');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('59-machine-actions');
+ await tester.enterText(managerSearch, 'rename');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final renameInput = find.byKey(const Key('machine-rename-input'));
+ await shot('60-machine-rename');
+ machineApi.renameReply = Completer<String?>();
+ await tester.enterText(renameInput, 'Office builder');
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('61-machine-rename-pending');
+ machineApi.renameReply!.completeError(
+ ApiException('Could not reach your account. Try again.'),
+ );
+ await tester.pumpAndSettle();
+ await shot('62-machine-rename-error');
+ machineApi.renameReply = null;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.enterText(managerSearch, 'delete');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('63-machine-delete');
+ machineApi.deleteFailure = ApiException(
+ 'Could not reach your account. Try again.',
+ );
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('64-machine-delete-error');
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.enterText(managerSearch, 'shared');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('65-shared-machine');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.enterText(managerSearch, 'office');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('66-machine-actions-small-large-text');
+ await tester.enterText(managerSearch, 'rename');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('67-machine-rename-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ managerApp.machineStates.remove('studio');
+ managerApp.machines.removeWhere(
+ (machine) => machine.machineId == 'studio',
+ );
+ managerApp.notifyListeners();
+ await shot('68-machine-unavailable-small-large-text');
+ await tester.pumpWidget(const SizedBox());
+ managerApp.dispose();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final renameConnection = RenameConnection();
+ final renameApp = createApp(connectionForTest: (_) => renameConnection);
+ seedMixedAgents(renameApp);
+ renameApp.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, renameApp);
+ Future<void> renameCommand(String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $query',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ await renameCommand('rename tab');
+ await shot('69-tab-rename');
+ await tester.enterText(find.byKey(const Key('tab-rename-input')), '');
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('70-tab-rename-validation');
+ await key(tester, LogicalKeyboardKey.escape);
+ await renameCommand('rename agent');
+ final agentRename = find.byKey(const Key('agent-rename-input'));
+ await shot('71-agent-rename');
+ await tester.enterText(agentRename, 'Resolve parser edge cases');
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('72-agent-rename-pending');
+ renameConnection.replies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ await shot('73-agent-rename-error');
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('74-agent-rename-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ await renameCommand('rename tab');
+ await shot('75-tab-rename-small-large-text');
+ await tester.pumpWidget(const SizedBox());
+ renameApp.dispose();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final stopConnection = StopConnection();
+ final stopApp = createApp(connectionForTest: (_) => stopConnection);
+ seedMixedAgents(stopApp);
+ stopApp.adoptSessionForTest(terminal('a0', []));
+ stopApp.adoptSessionForTest(terminal('a1', []));
+ await mount(tester, stopApp);
+ await renameCommand('stop');
+ await shot('76-agent-stop');
+ await key(tester, LogicalKeyboardKey.tab);
+ await shot('77-agent-stop-confirm');
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('78-agent-stop-pending');
+ await key(tester, LogicalKeyboardKey.escape);
+ await renameCommand('stop');
+ await shot('79-agent-stop-reopened');
+ stopConnection.stopReplies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ await shot('80-agent-stop-error');
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('81-agent-stop-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ stopApp.stateOf('m')!.agents = [
+ const Agent(id: 'a1', name: 'Build shell', engine: 'terminal'),
+ ];
+ stopApp.notifyListeners();
+ await renameCommand('stop');
+ await shot('82-terminal-stop-small-large-text');
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await shot('83-terminal-stop-details-small-large-text');
+ await tester.pumpWidget(const SizedBox());
+ stopApp.dispose();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ final forkConnection = ForkConnection();
+ final forkApp = createApp(connectionForTest: (_) => forkConnection);
+ seedMixedAgents(forkApp);
+ forkApp.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, forkApp);
+ await renameCommand('fork');
+ await shot('84-fork-agent');
+ final task = find.byKey(const ValueKey('fork-task'));
+ await tester.enterText(
+ task,
+ 'Try a smaller parser change\nKeep the public API stable.',
+ );
+ await shot('85-fork-task');
+ await key(tester, LogicalKeyboardKey.enter);
+ await shot('86-fork-pending');
+ await key(tester, LogicalKeyboardKey.escape);
+ await renameCommand('fork');
+ await shot('87-fork-reopened');
+ forkConnection.forkReplies.single.complete({
+ 'creationId': forkConnection.forks.last['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'BUSY',
+ 'detail': 'Wait for the turn to finish, then fork.',
+ },
+ });
+ await tester.pumpAndSettle();
+ await shot('88-fork-error');
+ await key(tester, LogicalKeyboardKey.enter);
+ forkConnection.forkReplies.last.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ await tester.pumpAndSettle();
+ await shot('89-fork-unconfirmed');
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('90-fork-small-large-text');
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await shot('91-fork-details-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ forkApp.discardForkAttempt('m', 'a0', forkApp.forkAttempt('m', 'a0'));
+ forkApp.stateOf('m')!.agents = [
+ const Agent(id: 'a0', name: 'Fix login redirect', engine: 'opencode'),
+ ];
+ forkApp.notifyListeners();
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await renameCommand('fork');
+ await shot('92-fork-handoff');
+ await tester.pumpWidget(const SizedBox());
+ forkApp.dispose();
+ final restartConnection = RestartConnection();
+ final restartApp = createApp(connectionForTest: (_) => restartConnection);
+ seedMixedAgents(restartApp);
+ restartApp.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, restartApp);
+ await renameCommand('restart');
+ await shot('93-restart-pending');
+ await key(tester, LogicalKeyboardKey.escape);
+ await renameCommand('restart');
+ await shot('94-restart-reopened');
+ restartConnection.restartReplies.single.complete({
+ 'creationId': restartConnection.requests.last['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'AGENT_BUSY',
+ 'detail': 'Another operation is changing this agent. Wait for it to finish, then retry.',
+ },
+ });
+ await tester.pumpAndSettle();
+ await shot('95-restart-error');
+ await key(tester, LogicalKeyboardKey.enter);
+ restartConnection.restartReplies.last.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ await shot('96-restart-unconfirmed');
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await shot('97-restart-again');
+ tester.view.physicalSize = const Size(480, 360);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ await shot('98-restart-again-small-large-text');
+ await key(tester, LogicalKeyboardKey.escape);
+ await shot('99-restart-small-large-text');
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await shot('100-restart-details-small-large-text');
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await key(tester, LogicalKeyboardKey.enter);
+ restartConnection.checkReplies.single.complete(
+ restartReceipt(
+ restartConnection.requests.last['creationId'] as String,
+ resumed: false,
+ ),
+ );
+ await tester.pumpAndSettle();
+ await shot('101-restart-fresh-conversation');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ restartApp.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Build shell',
+ engine: 'terminal',
+ terminalAvailable: true,
+ ),
+ ];
+ restartApp.notifyListeners();
+ await renameCommand('restart');
+ await shot('102-restart-terminal');
+ await tester.pumpWidget(const SizedBox());
+ restartApp.dispose();
+ debugDisableShadows = true;
+ },
+ );
+}
diff --git a/desktop/test/cli_login_test.dart b/desktop/test/cli_login_test.dart
index d23fe99c8..d8f6d12d1 100644
--- a/desktop/test/cli_login_test.dart
+++ b/desktop/test/cli_login_test.dart
@@ -24,10 +24,10 @@ class _Process implements Process {
var kills = 0;
void emit(Map<String, dynamic> event) =>
output.add(utf8.encode('${jsonEncode(event)}\n'));
- void finish() {
+ void finish([int exitCode = 0]) {
unawaited(output.close());
unawaited(errors.close());
- if (!ended.isCompleted) ended.complete(0);
+ if (!ended.isCompleted) ended.complete(exitCode);
}
@override
@@ -50,7 +50,72 @@ class _Process implements Process {
IOSink get stdin => throw UnimplementedError();
}
+class _LogoutRunner extends HarnessCliRunner {
+ _LogoutRunner(this.process)
+ : super(runTimeout: const Duration(milliseconds: 30));
+ final _Process process;
+ final arguments = <List<String>>[];
+ @override
+ Future<Process> start(List<String> command) async {
+ arguments.add(command);
+ return process;
+ }
+
+ @override
+ Future<ProcessResult> run(List<String> command) async {
+ // The original fire-and-forget run path reports this as success.
+ return ProcessResult(1, 1, '', 'Fixture failure');
+ }
+}
+
+class _TimeoutProcess extends _Process {
+ @override
+ bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {
+ final killed = super.kill(signal);
+ finish(1);
+ return killed;
+ }
+}
+
void main() {
+ test('logout reports a nonzero CLI exit as a failure', () async {
+ final process = _Process()..finish(1);
+ final runner = _LogoutRunner(process);
+ await expectLater(CliLogin(runner: runner).logout(), throwsStateError);
+ });
+
+ test(
+ 'logout drains output and finishes before permitting another command',
+ () async {
+ final process = _Process();
+ final runner = _LogoutRunner(process);
+ var finished = false;
+ final pending = CliLogin(runner: runner)
+ .logout()
+ .then((_) => finished = true);
+ await Future<void>.delayed(Duration.zero);
+ expect(finished, isFalse);
+ process.emit({'fixture': 'output'});
+ process.errors.add(utf8.encode('fixture diagnostic'));
+ process.finish();
+ await pending;
+ expect(runner.arguments, [
+ ['logout'],
+ ]);
+ },
+ );
+
+ test(
+ 'a timed-out logout stops its process before returning failure',
+ () async {
+ final process = _TimeoutProcess();
+ final runner = _LogoutRunner(process);
+ await expectLater(CliLogin(runner: runner).logout(), throwsStateError);
+ expect(process.kills, 1);
+ expect(process.ended.isCompleted, isTrue);
+ },
+ );
+
test(
'cancel while the CLI starts ignores its late URL and stops that process',
() async {
diff --git a/desktop/test/command_dock_interaction_test.dart b/desktop/test/command_dock_interaction_test.dart
new file mode 100644
index 000000000..e54c06754
--- /dev/null
+++ b/desktop/test/command_dock_interaction_test.dart
@@ -0,0 +1,652 @@
+import 'support/launch_menu.dart';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/box_chrome.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'swarm_screen_test.dart' show terminal;
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
+
+ testWidgets(
+ 'launch arrows edit the highlighted field without starting an agent',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ final original = (box.engine, box.machineId, box.project);
+ final paneCount = app.activeSwarm.panes.length;
+ void highlighted(String name) {
+ final row = find.byKey(ValueKey('new-harness-field-$name'));
+ expect(row.hitTestable(), findsOneWidget);
+ final highlight = tester.widget<BoxRowHighlight>(
+ find.ancestor(of: row, matching: find.byType(BoxRowHighlight)),
+ );
+ expect(highlight.highlighted, isTrue);
+ expect(box.field, NewHarnessField.launch);
+ }
+
+ highlighted('create');
+ for (final letter in [
+ LogicalKeyboardKey.keyA,
+ LogicalKeyboardKey.keyM,
+ LogicalKeyboardKey.keyP,
+ LogicalKeyboardKey.keyT,
+ LogicalKeyboardKey.keyO,
+ LogicalKeyboardKey.keyG,
+ ]) {
+ await key(tester, letter);
+ highlighted('create');
+ }
+ // Down wraps from the bottom action into the arguments in visual order.
+ for (final (steps, name, field) in [
+ (1, 'agent', NewHarnessField.agent),
+ (2, 'machine', NewHarnessField.machine),
+ (3, 'project', NewHarnessField.projectMenu),
+ (4, 'task', NewHarnessField.task),
+ ]) {
+ for (var i = 0; i < steps; i++) {
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ }
+ highlighted(name);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, field);
+ await key(tester, LogicalKeyboardKey.escape);
+ highlighted('create');
+ }
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ highlighted('task');
+ expect(
+ find.byKey(const ValueKey('new-harness-field-options')),
+ findsNothing,
+ );
+ await openLaunchRow(tester, 'agent');
+ await openAgentSetting(
+ tester,
+ box.selected!.engine!,
+ NewHarnessController.permissionsId,
+ );
+ expect(box.field, NewHarnessField.mode);
+ expect(find.byKey(const Key('new-agent-task')), findsNothing);
+ await tester.enterText(
+ find.byKey(const ValueKey('new-harness-input')),
+ 'ask',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.agent);
+ expect(box.mode, 'ask');
+ await key(tester, LogicalKeyboardKey.escape);
+ highlighted('create');
+ expect(find.textContaining('Ask first'), findsOneWidget);
+ expect((box.engine, box.machineId, box.project), original);
+ expect(app.activeSwarm.panes, hasLength(paneCount));
+ expect(frames, isEmpty);
+
+ // Navigation obeys the same live picker remaps as the child lists.
+ map.apply('''{"bindings":[
+ {"keys":"down","command":null,"when":"picker"},
+ {"keys":"ctrl+j","command":"picker.next","when":"picker"}
+ ]}''');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ highlighted('create');
+ await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
+ highlighted('agent');
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ highlighted('create');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Machine returns to its source menu and project search stays on that machine',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.projectHistory.select('studio', '/work/remote-project');
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ final original = box.project;
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ await openLaunchRow(tester, 'task');
+ await tester.enterText(input, 'Inspect the project');
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'machine');
+ await tester.enterText(input, 'Office');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.launch);
+ expect(box.machineId, 'm');
+ expect(box.project, original);
+ await openLaunchRow(tester, 'machine');
+ await tester.enterText(input, 'Office');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.launch);
+ expect(box.machineId, 'studio');
+ expect(box.needsProject, isTrue);
+ await openLaunchRow(tester, 'project');
+ final remoteRow = box.options.singleWhere(
+ (row) => row.project?.folder == '/work/remote-project',
+ );
+ expect(find.text('remote-project').hitTestable(), findsOneWidget);
+ await tester.enterText(input, 'remote-project');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.launch);
+ expect(box.project.folder, '/work/remote-project');
+ await openLaunchRow(tester, 'machine');
+ await tester.enterText(input, 'M2');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.project, original);
+ expect(box.task, 'Inspect the project');
+ await openLaunchRow(tester, 'project');
+ box.accept(remoteRow);
+ expect(box.error, contains('machine has changed'));
+ expect(box.machineId, 'm');
+ map.apply('''{"bindings":[
+ {"keys":"m","command":null,"when":"picker"},
+ {"keys":"u","command":"creation.project_machine","when":"picker"},
+ {"keys":"ctrl+r","command":"creation.project_recent_1","when":"project"}
+ ]}''');
+ await tester.pump();
+ await tester.enterText(input, 'robotics');
+ await key(tester, LogicalKeyboardKey.keyR, ctrl: true);
+ expect(box.field, NewHarnessField.launch);
+ expect(box.project.folder, '/work/robotics');
+ await key(tester, LogicalKeyboardKey.keyM);
+ expect(box.field, NewHarnessField.launch);
+ await key(tester, LogicalKeyboardKey.keyU);
+ expect(box.field, NewHarnessField.machine);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'project');
+ await tester.enterText(input, 'robotics');
+ await key(tester, LogicalKeyboardKey.keyU);
+ expect(box.field, NewHarnessField.projectMenu);
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-change-machine')),
+ );
+ await tester.pump();
+ expect(box.field, NewHarnessField.machine);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.query, 'robotics');
+ expect(frames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Project keeps its actions visible and scopes each prompt to its intent',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ for (var i = 0; i < 40; i++) {
+ await app.projectHistory.select('m', '/work/project-$i');
+ }
+ await app.projectHistory.select('studio', '/work/office-only');
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ final original = box.project;
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ await openLaunchRow(tester, 'project');
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ for (final label in [
+ 'New Project',
+ 'Open Folder',
+ 'Clone GitHub Repository',
+ ]) {
+ expect(find.text(label).hitTestable(), findsOneWidget);
+ }
+ expect(
+ find.byKey(const ValueKey('new-harness-change-machine')).hitTestable(),
+ findsOneWidget,
+ );
+ expect(box.options.where((row) => !row.synthetic), hasLength(43));
+ expect(box.selected!.project, original);
+ for (final shortcut in ['1', '9', 'n', 'o', 'g']) {
+ expect(find.text(shortcut), findsNothing);
+ }
+ final openRow = find.byKey(
+ const ValueKey(NewHarnessController.existingProjectId),
+ );
+ final newRow = find.byKey(
+ const ValueKey(NewHarnessController.newProjectId),
+ );
+ final openBounds = tester.getRect(openRow);
+ expect(tester.getRect(newRow).bottom, lessThanOrEqualTo(openBounds.top));
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected!.id, NewHarnessController.newProjectId);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected!.id, NewHarnessController.existingProjectId);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected!.id, NewHarnessController.repositoryId);
+ final cloneRow = find.byKey(
+ const ValueKey(NewHarnessController.repositoryId),
+ );
+ expect(
+ tester.getRect(openRow).bottom,
+ lessThanOrEqualTo(tester.getRect(cloneRow).top),
+ );
+ expect(
+ tester.getRect(cloneRow).bottom,
+ lessThanOrEqualTo(tester.getRect(input).top),
+ );
+ // Older recents scroll; project actions remain anchored beside the footer.
+ for (var i = 0; i < 5; i++) {
+ await key(tester, LogicalKeyboardKey.pageUp);
+ }
+ await tester.pump();
+ expect(box.cursor, greaterThan(12));
+ expect(
+ find.byKey(ValueKey(box.selected!.id)).hitTestable(),
+ findsOneWidget,
+ );
+ expect(tester.getRect(openRow), openBounds);
+ final previousSize = tester.view.physicalSize;
+ final selectedProject = box.selected!.id;
+ tester.view.physicalSize = const Size(600, 680);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pumpAndSettle();
+ expect(box.selected!.id, selectedProject);
+ expect(
+ find.byKey(ValueKey(selectedProject)).hitTestable(),
+ findsOneWidget,
+ );
+ expect(openRow.hitTestable(), findsOneWidget);
+ tester.view.physicalSize = previousSize;
+ tester.platformDispatcher.clearTextScaleFactorTestValue();
+ await tester.pumpAndSettle();
+ // Letters and digits belong to the search, not hidden action shortcuts.
+ for (final ordinary in [
+ LogicalKeyboardKey.keyN,
+ LogicalKeyboardKey.keyO,
+ LogicalKeyboardKey.keyG,
+ LogicalKeyboardKey.keyM,
+ LogicalKeyboardKey.digit1,
+ LogicalKeyboardKey.digit9,
+ ]) {
+ await key(tester, ordinary);
+ expect(box.field, NewHarnessField.projectMenu);
+ }
+ await tester.enterText(input, 'nogm19');
+ await tester.pump();
+ expect(box.query, 'nogm19');
+ expect(box.options, hasLength(3));
+ expect(find.text('No projects match “nogm19”'), findsOneWidget);
+ for (final label in [
+ 'New Project',
+ 'Open Folder',
+ 'Clone GitHub Repository',
+ ]) {
+ expect(find.text(label).hitTestable(), findsOneWidget);
+ }
+ await tester.enterText(input, 'project-9');
+ await tester.pump();
+ expect(box.selected!.project!.folder, '/work/project-9');
+ expect(
+ find.byKey(ValueKey(box.selected!.id)).hitTestable(),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.project.folder, '/work/project-9');
+ expect(box.field, NewHarnessField.launch);
+ box.setFolder(original.folder!);
+ await openLaunchRow(tester, 'project');
+ expect(box.query, isEmpty);
+ await tester.enterText(input, 'office-only');
+ await tester.pump();
+ expect(box.options.where((row) => !row.synthetic), isEmpty);
+ expect(box.selected!.id, NewHarnessController.existingProjectId);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.project);
+ expect(box.options.single.id, NewHarnessController.browseId);
+ await tester.enterText(input, 'new project');
+ await tester.pump();
+ expect(box.options.any((row) => row.id == 'project:new'), isFalse);
+ expect(box.project, original);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.query, 'office-only');
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected!.id, NewHarnessController.repositoryId);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.projectRepository);
+ await tester.enterText(input, 'https://example.com/owner/repo');
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(box.error, contains('GitHub URL'));
+ expect(box.project, original);
+ await tester.enterText(input, 'acme/payments');
+ await key(tester, LogicalKeyboardKey.keyM);
+ expect(box.field, NewHarnessField.projectRepository);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ box.project.repository!.url,
+ 'https://github.com/acme/payments.git',
+ );
+ expect(box.field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'machine');
+ await tester.enterText(input, 'Office');
+ await key(tester, LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'project');
+ expect(box.machineId, 'studio');
+ expect(
+ box.options
+ .where((row) => row.project != null)
+ .every((row) => row.machineId == 'studio'),
+ isTrue,
+ );
+ await tester.enterText(input, 'office-only');
+ await tester.pump();
+ expect(box.selected!.project!.folder, '/work/office-only');
+ // Explicit custom bindings remain available without reserving search text.
+ map.apply(
+ '{"bindings":[{"keys":"ctrl+r","command":"creation.project_new","when":"project"}]}',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyR, ctrl: true);
+ expect(box.field, NewHarnessField.projectName);
+ await tester.enterText(input, 'payments processing');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.project.name, 'payments processing');
+ expect(
+ box.projectLocation,
+ 'iMac · Office:~/harnesses/payments-processing',
+ );
+ // The full form remains available through its compatibility shortcut.
+ await key(tester, LogicalKeyboardKey.period, cmd: true);
+ expect(find.byKey(const Key('new-agent-task')), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(frames, isEmpty);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('Pi keeps a task row and explains its launch limitation', (
+ tester,
+ ) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'Pi');
+ box.accept(box.options.firstWhere((row) => row.id == 'pi'));
+ await tester.pump();
+ expect(
+ find.byKey(const ValueKey('new-harness-field-task')),
+ findsOneWidget,
+ );
+ expect(find.text('Enter a task in Pi after launch'), findsOneWidget);
+ await openLaunchRow(tester, 'task');
+ expect(box.error, contains('not supported yet'));
+ expect(box.field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'Codex');
+ await key(tester, LogicalKeyboardKey.enter);
+ await openLaunchRow(tester, 'task');
+ expect(box.field, NewHarnessField.task);
+ await tester.enterText(input, 'Make a product video');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.task, 'Make a product video');
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'launch keys are remappable and remain text in an argument prompt',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply(
+ '{"bindings":[{"keys":"a","command":null,"when":"picker"},{"keys":"e","command":"creation.agent","when":"picker"}]}',
+ );
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.field, NewHarnessField.launch);
+ await key(tester, LogicalKeyboardKey.keyA);
+ expect(box.field, NewHarnessField.launch);
+ await key(tester, LogicalKeyboardKey.keyE);
+ expect(box.field, NewHarnessField.agent);
+ // The menu action must not steal letters while editing or searching.
+ await key(tester, LogicalKeyboardKey.keyP);
+ await key(tester, LogicalKeyboardKey.keyT);
+ await key(tester, LogicalKeyboardKey.keyO);
+ await key(tester, LogicalKeyboardKey.keyE);
+ expect(box.field, NewHarnessField.agent);
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ await tester.enterText(input, 'OpenCode');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.engine, 'opencode');
+ expect(box.field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'task');
+ await tester.enterText(input, 'a project to open');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.task, 'a project to open');
+ expect(box.field, NewHarnessField.launch);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(frames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final size in [const Size(1280, 800), const Size(600, 700)]) {
+ testWidgets(
+ 'dock pins creation beside its input while matches filter at $size',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a69', frames));
+ app.renameSwarm(app.activeSwarmId, 'Feature work');
+ await configured.mount(tester, app, map);
+ tester.view.physicalSize = size;
+ await tester.pump();
+ final paneBounds = tester.getRect(find.byKey(pane.cellKey));
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final preview = find.byKey(const ValueKey('swarm-search-preview'));
+ expect(find.text('· Feature work'), findsOneWidget);
+ // The create row already explains itself; only real agents need preview.
+ expect(preview, findsNothing);
+ await tester.enterText(input, 'Agent 1');
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final best = search.selected!;
+ expect(best.agentId, 'a1');
+ final bestRow = find.byKey(ValueKey(best.id));
+ final queryBounds = tester.getRect(input);
+ final matchBounds = tester.getRect(bestRow);
+ final createRow = find.byKey(const ValueKey('create:harness'));
+ final createBounds = tester.getRect(createRow);
+ expect(queryBounds.top - createBounds.bottom, inInclusiveRange(0, 12));
+ expect(matchBounds.bottom, lessThanOrEqualTo(createBounds.top));
+ expect(search.rows.first.isCreate, isTrue);
+ expect(search.rows.first.task, 'Agent 1');
+ expect(preview, findsOneWidget);
+ if (size.width < 800) {
+ expect(
+ tester.getRect(preview).bottom,
+ lessThan(tester.getRect(bestRow).top),
+ );
+ } else {
+ expect(tester.getRect(preview).left, greaterThan(matchBounds.right));
+ expect(
+ tester
+ .getSize(find.byKey(const ValueKey('swarm-search-results')))
+ .height,
+ lessThan(size.height * .4),
+ );
+ }
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsNothing);
+ expect(search.selected, same(best));
+ expect(tester.getRect(input), queryBounds);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ expect(preview, findsOneWidget);
+ expect(tester.getRect(input), queryBounds);
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(search.cursor, 2);
+ final selectedRow = find.byKey(ValueKey(search.selected!.id));
+ expect(selectedRow.hitTestable(), findsOneWidget);
+ if (bestRow.evaluate().isNotEmpty) {
+ expect(
+ tester.getRect(selectedRow).center.dy,
+ lessThan(tester.getRect(bestRow).center.dy),
+ );
+ }
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(search.selected, same(best));
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(search.selected!.isCreate, isTrue);
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(
+ search.selected!.isCreate,
+ isTrue,
+ reason: 'Do not wrap at the edge',
+ );
+ await key(tester, LogicalKeyboardKey.keyK, ctrl: true);
+ expect(search.selected, same(best));
+ await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
+ expect(search.selected!.isCreate, isTrue);
+ expect(tester.getRect(createRow), createBounds);
+ await tester.drag(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ const Offset(0, 180),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.getRect(createRow), createBounds);
+ await tester.enterText(input, '');
+ await tester.pump();
+ expect(tester.getRect(createRow), createBounds);
+ await key(tester, LogicalKeyboardKey.tab);
+ expect(
+ FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<ListTile>()
+ ?.key,
+ const ValueKey('create:harness'),
+ reason: 'Tab reaches the pinned action next to the query first',
+ );
+ expect(tester.getRect(find.byKey(pane.cellKey)), paneBounds);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(frames.single.bytes, [27, 91, 68]);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'creation choices follow spatial keys while task arrows edit text',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ box.setFolder("/work/project");
+ box.focusField(NewHarnessField.task);
+ await tester.pump();
+ await tester.enterText(input, 'First line\nSecond line');
+ await tester.pump();
+ expect(box.task, 'First line\nSecond line');
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(box.task, 'First line\nSecond line');
+ final editor = tester.widget<TextField>(input);
+ expect(editor.controller!.selection.baseOffset, lessThan(11));
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'agent');
+ expect(box.task, 'First line\nSecond line');
+ await tester.enterText(input, 'c');
+ await tester.pump();
+ expect(box.options.length, greaterThan(1));
+ expect(box.cursor, 0);
+ final first = box.selected!;
+ final order = box.options.map((row) => row.id).toList();
+ final firstBounds = tester.getRect(find.byKey(ValueKey(first.id)));
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(box.cursor, 1);
+ expect(box.options.map((row) => row.id), order);
+ expect(tester.getRect(find.byKey(ValueKey(first.id))), firstBounds);
+ expect(find.text('Permissions'), findsNothing);
+ expect(find.text('Codex Profile'), findsNothing);
+ expect(
+ tester.getRect(find.byKey(ValueKey(box.selected!.id))).center.dy,
+ lessThan(firstBounds.center.dy),
+ );
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(box.selected!.id, first.id);
+ expect(tester.getRect(find.byKey(ValueKey(first.id))), firstBounds);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.launch);
+ expect(box.task, 'First line\nSecond line');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/daemon_readiness_test.dart b/desktop/test/daemon_readiness_test.dart
index 5073cbe37..5b8007793 100644
--- a/desktop/test/daemon_readiness_test.dart
+++ b/desktop/test/daemon_readiness_test.dart
@@ -103,8 +103,9 @@ class _Notifier extends AppNotifier {
}
@override
- Future<void> refreshMachines() async {
+ Future<bool> refreshMachines() async {
refreshes++;
+ return true;
}
}
diff --git a/desktop/test/entry_surfaces_render_test.dart b/desktop/test/entry_surfaces_render_test.dart
index 4b6450d0f..94e5a0ee5 100644
--- a/desktop/test/entry_surfaces_render_test.dart
+++ b/desktop/test/entry_surfaces_render_test.dart
@@ -197,7 +197,7 @@ void main() {
}
}
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pumpAndSettle();
await capture('open');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
diff --git a/desktop/test/environment_preflight_screen_test.dart b/desktop/test/environment_preflight_screen_test.dart
new file mode 100644
index 000000000..a18da7a63
--- /dev/null
+++ b/desktop/test/environment_preflight_screen_test.dart
@@ -0,0 +1,76 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/widgets/environment_preflight_screen.dart';
+
+Widget host(EnvironmentReadiness readiness, {bool reduceMotion = false}) =>
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion),
+ child: child!,
+ ),
+ home: EnvironmentPreflightScreen(readiness: readiness),
+ );
+
+void main() {
+ testWidgets('the initial computer check respects Reduce Motion', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ host(EnvironmentReadiness.initial(), reduceMotion: true),
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.byIcon(Icons.hourglass_empty_rounded), findsOneWidget);
+ expect(tester.binding.hasScheduledFrame, isFalse);
+ });
+
+ testWidgets('computer readiness has an accessible changing status', (
+ tester,
+ ) async {
+ final semantics = tester.ensureSemantics();
+ try {
+ await tester.pumpWidget(
+ host(EnvironmentReadiness.initial(), reduceMotion: true),
+ );
+ final status = find.byKey(const Key('environment-status'));
+ expect(status, findsOneWidget);
+ expect(
+ tester
+ .getSemantics(status)
+ .getSemanticsData()
+ .flagsCollection
+ .isLiveRegion,
+ isTrue,
+ );
+ expect(find.text('Checking this computer'), findsOneWidget);
+ await tester.pumpWidget(
+ host(
+ EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ ),
+ reduceMotion: true,
+ ),
+ );
+ await tester.pump();
+ expect(find.text('Environment ready'), findsOneWidget);
+ expect(find.text('Checking this computer'), findsNothing);
+ expect(
+ tester
+ .getSemantics(status)
+ .getSemanticsData()
+ .flagsCollection
+ .isLiveRegion,
+ isTrue,
+ );
+ } finally {
+ semantics.dispose();
+ }
+ });
+}
diff --git a/desktop/test/environment_probe_lifecycle_test.dart b/desktop/test/environment_probe_lifecycle_test.dart
new file mode 100644
index 000000000..8d3097cbb
--- /dev/null
+++ b/desktop/test/environment_probe_lifecycle_test.dart
@@ -0,0 +1,283 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+
+class _ProbeProcess implements Process {
+ final output = StreamController<List<int>>();
+ final errors = StreamController<List<int>>();
+ final ended = Completer<int>();
+ final signals = <ProcessSignal>[];
+ @override
+ final stdin = IOSink(StreamController<List<int>>.broadcast().sink);
+
+ _ProbeProcess();
+
+ _ProbeProcess.finished(List<int> bytes) {
+ output.add(bytes);
+ finish();
+ }
+
+ void finish() {
+ unawaited(output.close());
+ unawaited(errors.close());
+ if (!ended.isCompleted) ended.complete(0);
+ }
+
+ @override
+ Stream<List<int>> get stdout => output.stream;
+ @override
+ Stream<List<int>> get stderr => errors.stream;
+ @override
+ Future<int> get exitCode => ended.future;
+ @override
+ int get pid => 42;
+ @override
+ bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {
+ signals.add(signal);
+ return true;
+ }
+}
+
+void main() {
+ late Directory scratch;
+ late String node;
+ final children = <_ProbeProcess>[];
+ setUp(() async {
+ scratch = await Directory.systemTemp.createTemp('harness-probe-test-');
+ node = '${scratch.path}/runtime/node/bin/node';
+ await File(node).parent.create(recursive: true);
+ await File(node).writeAsString('test fixture');
+ await File('${scratch.path}/runtime/current-node').writeAsString(node);
+ final cli = File('${scratch.path}/cli/cli.js');
+ await cli.parent.create(recursive: true);
+ await cli.writeAsString('test fixture');
+ });
+ tearDown(() async {
+ for (final child in children) {
+ child.finish();
+ await child.stdin.close();
+ }
+ children.clear();
+ await scratch.delete(recursive: true);
+ });
+
+ _ProbeProcess healthy(List<String> arguments) {
+ final value = arguments.contains('--version') ? 'v20.18.0' : 'ready';
+ final child = _ProbeProcess.finished(utf8.encode(value));
+ children.add(child);
+ return child;
+ }
+
+ EnvironmentProvisioner provisioner(ProcessStarter start) =>
+ EnvironmentProvisioner(
+ harnessHome: scratch,
+ isMacOS: true,
+ isLinux: false,
+ probeTimeout: const Duration(milliseconds: 20),
+ start: start,
+ // Never execute a real tool, even on the old Process.run path.
+ run: (_, _, {environment}) => Completer<ProcessResult>().future,
+ openTerminal: (_) async => fail('A check must not open an installer'),
+ );
+
+ Future<EnvironmentReadiness?> check(
+ EnvironmentProvisioner setup, {
+ void Function(EnvironmentReadiness)? onProgress,
+ }) => setup
+ .ensureReady(onProgress: onProgress ?? (_) {}, install: false)
+ .then<EnvironmentReadiness?>((value) => value)
+ .timeout(const Duration(milliseconds: 300), onTimeout: () => null);
+
+ for (final stalled in ['shell', 'tmux', 'node', 'cli']) {
+ test('$stalled timeout is a failed check, and Retry can recover', () async {
+ final waiting = _ProbeProcess();
+ children.add(waiting);
+ var shouldHang = true;
+ final calls = <String>[];
+ final setup = provisioner((executable, arguments, {environment}) async {
+ final command = '$executable ${arguments.join(' ')}';
+ calls.add(command);
+ final isTarget = switch (stalled) {
+ 'shell' => command.contains('test -w'),
+ 'tmux' => command.contains('command -v tmux'),
+ 'node' => arguments.contains('--version'),
+ _ => arguments.contains('version'),
+ };
+ return shouldHang && isTarget ? waiting : healthy(arguments);
+ });
+ final updates = <EnvironmentReadiness>[];
+ final result = await check(setup, onProgress: updates.add);
+ expect(result, isNotNull, reason: 'Checking must stop waiting');
+ expect(result!.phase, EnvironmentSetupPhase.failed);
+ expect(result.isReady, isFalse);
+ expect(result.failure?.title, 'Checking this computer took too long');
+ expect(
+ result.failure?.command,
+ isNull,
+ reason: 'Do not suggest installing',
+ );
+ expect(waiting.signals, [ProcessSignal.sigkill]);
+ expect(waiting.output.hasListener, isFalse);
+ expect(waiting.errors.hasListener, isFalse);
+ expect(calls.any((call) => call.contains('install.sh')), isFalse);
+ final lastUpdate = updates.last;
+ waiting.finish();
+ await Future<void>.delayed(Duration.zero);
+ expect(identical(updates.last, lastUpdate), isTrue);
+
+ shouldHang = false;
+ final retry = await check(setup);
+ expect(retry?.phase, EnvironmentSetupPhase.ready);
+ expect(retry?.isReady, isTrue);
+ });
+ }
+
+ test(
+ 'a process that starts after timeout is stopped without updating UI',
+ () async {
+ final starting = Completer<Process>();
+ final setup = provisioner((_, _, {environment}) => starting.future);
+ final updates = <EnvironmentReadiness>[];
+ final result = await check(setup, onProgress: updates.add);
+ expect(result?.phase, EnvironmentSetupPhase.failed);
+ final count = updates.length;
+ final late = _ProbeProcess();
+ children.add(late);
+ starting.complete(late);
+ await Future<void>.delayed(Duration.zero);
+ expect(late.signals, [ProcessSignal.sigkill]);
+ expect(late.output.hasListener, isFalse);
+ expect(late.errors.hasListener, isFalse);
+ expect(updates, hasLength(count));
+ },
+ );
+
+ test('inherited open pipes cannot hold a finished check forever', () async {
+ final child = _ProbeProcess()..ended.complete(0);
+ children.add(child);
+ final setup = provisioner((_, _, {environment}) async => child);
+ final result = await check(setup);
+ expect(result?.phase, EnvironmentSetupPhase.failed);
+ expect(
+ child.signals,
+ isEmpty,
+ reason: 'Never signal an already exited PID',
+ );
+ expect(child.output.hasListener, isFalse);
+ expect(child.errors.hasListener, isFalse);
+ });
+
+ test(
+ 'partial UTF-8 in tool output does not prevent a successful check',
+ () async {
+ final setup = provisioner((_, arguments, {environment}) async {
+ final text = arguments.contains('--version') ? 'v20.18.0\n' : 'ready\n';
+ final child = _ProbeProcess.finished([...utf8.encode(text), 0xff]);
+ children.add(child);
+ return child;
+ });
+ expect((await check(setup))?.isReady, isTrue);
+ expect(children.every((child) => child.signals.isEmpty), isTrue);
+ },
+ );
+
+ test(
+ 'an unreadable output pipe stops the owned check and offers retry',
+ () async {
+ final child = _ProbeProcess()
+ ..errors.addError(StateError('Pipe unavailable'));
+ children.add(child);
+ final setup = provisioner((_, _, {environment}) async => child);
+ final result = await check(setup);
+ expect(result?.phase, EnvironmentSetupPhase.failed);
+ expect(result?.failure?.title, 'Could not check this computer');
+ expect(child.signals, [ProcessSignal.sigkill]);
+ expect(child.output.hasListener, isFalse);
+ expect(child.errors.hasListener, isFalse);
+ },
+ );
+
+ test('an injected run-only check also has a bounded wait', () async {
+ final setup = EnvironmentProvisioner(
+ harnessHome: scratch,
+ isMacOS: true,
+ isLinux: false,
+ probeTimeout: const Duration(milliseconds: 20),
+ run: (_, _, {environment}) => Completer<ProcessResult>().future,
+ );
+ expect((await check(setup))?.phase, EnvironmentSetupPhase.failed);
+ });
+
+ test(
+ 'retrying a previous verification never reports ready before checking',
+ () async {
+ final child = _ProbeProcess();
+ children.add(child);
+ final setup = provisioner((_, _, {environment}) async => child);
+ final updates = <EnvironmentReadiness>[];
+ final previous = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.failed,
+ failure: const EnvironmentFailure(
+ title: 'Verification failed',
+ detail: 'Retry to check again.',
+ ),
+ );
+ final result = await setup.ensureReady(
+ resumeFrom: previous,
+ onProgress: updates.add,
+ install: false,
+ );
+ expect(result.phase, EnvironmentSetupPhase.failed);
+ expect(updates.where((value) => value.isReady), isEmpty);
+ },
+ );
+
+ test('Windows verification also returns a recoverable timeout', () async {
+ final child = _ProbeProcess();
+ children.add(child);
+ final setup = EnvironmentProvisioner(
+ harnessHome: scratch,
+ isMacOS: false,
+ isLinux: false,
+ isWindows: true,
+ probeTimeout: const Duration(milliseconds: 20),
+ start: (_, _, {environment}) async => child,
+ run: (_, _, {environment}) => Completer<ProcessResult>().future,
+ );
+ final result = await check(setup);
+ expect(result?.phase, EnvironmentSetupPhase.failed);
+ expect(result?.failure?.step, EnvironmentStep.harness);
+ expect(child.signals, [ProcessSignal.sigkill]);
+ });
+
+ test('a timed-out native subprocess exits before another check', () async {
+ Process? child;
+ var exited = false;
+ addTearDown(() {
+ if (!exited) child?.kill(ProcessSignal.sigkill);
+ });
+ final started = Completer<Process>();
+ final setup = provisioner((_, _, {environment}) async {
+ final process = await Process.start('/bin/sleep', ['10']);
+ child = process;
+ unawaited(process.exitCode.then((_) => exited = true));
+ started.complete(process);
+ return process;
+ });
+ final result = await check(setup);
+ expect(result?.phase, EnvironmentSetupPhase.failed);
+ final process = await started.future.timeout(const Duration(seconds: 2));
+ expect(
+ await process.exitCode.timeout(const Duration(seconds: 2)),
+ isNot(0),
+ );
+ expect(exited, isTrue);
+ }, skip: Platform.isWindows);
+}
diff --git a/desktop/test/environment_provisioner_test.dart b/desktop/test/environment_provisioner_test.dart
index 26f4d9338..14ec252a7 100644
--- a/desktop/test/environment_provisioner_test.dart
+++ b/desktop/test/environment_provisioner_test.dart
@@ -1,3 +1,4 @@
+import 'dart:convert';
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
@@ -637,6 +638,111 @@ void main() {
expect(calls.any((line) => line.contains('command -v wl-copy')), isFalse);
});
+ for (final source in ['log', 'result', 'empty result']) {
+ test(
+ 'a Terminal recheck tolerates ${source == 'empty result' ? 'a partially written empty result' : 'invalid UTF-8 in its $source'}',
+ () async {
+ await createManagedHarness();
+ var launches = 0;
+ final provisioner = EnvironmentProvisioner(
+ harnessHome: scratch,
+ isMacOS: false,
+ isLinux: true,
+ platformEnvironment: const {'DISPLAY': ':0'},
+ openTerminal: (_) async => launches++,
+ run: runner(tmuxPresent: () => true, xclipPresent: () => false),
+ );
+ final waiting = await provisioner.ensureReady(
+ onProgress: (_) {},
+ install: true,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ final path = source == 'log'
+ ? waiting.terminalLogPath!
+ : waiting.terminalResultPath!;
+ await File(path).writeAsBytes(
+ source == 'empty result'
+ ? []
+ : [
+ ...utf8.encode('A partial installer write\n'),
+ 0xff,
+ 0xc3,
+ ...utf8.encode('\nRecent package output\n'),
+ ],
+ );
+ final rechecked = await provisioner.ensureReady(
+ onProgress: (_) {},
+ resumeFrom: waiting,
+ install: false,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ expect(rechecked.phase, EnvironmentSetupPhase.waitingForTerminal);
+ expect(rechecked.isReady, isFalse);
+ expect(launches, 1);
+ if (source == 'log') {
+ expect(
+ rechecked.output.join('\n'),
+ contains('Recent package output'),
+ );
+ }
+ },
+ );
+ }
+
+ test(
+ 'Terminal rechecks show recent output without loading the whole log',
+ () async {
+ await createManagedHarness();
+ final provisioner = EnvironmentProvisioner(
+ harnessHome: scratch,
+ isMacOS: false,
+ isLinux: true,
+ platformEnvironment: const {'DISPLAY': ':0'},
+ openTerminal: (_) async {},
+ run: runner(tmuxPresent: () => true, xclipPresent: () => false),
+ );
+ final waiting = await provisioner.ensureReady(
+ onProgress: (_) {},
+ install: true,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ final log = File(waiting.terminalLogPath!);
+ await log.writeAsString(
+ 'OLDEST_PACKAGE_OUTPUT\n'
+ '${List.filled(60000, 'Package diagnostic line\n').join()}'
+ 'LATEST_PACKAGE_OUTPUT\n',
+ );
+ final fullLength = await log.length();
+ final rechecked = await provisioner.ensureReady(
+ onProgress: (_) {},
+ resumeFrom: waiting,
+ install: false,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ final diagnostics = rechecked.output.join('\n');
+ expect(diagnostics.length, lessThan(80 * 1024));
+ expect(diagnostics, contains('LATEST_PACKAGE_OUTPUT'));
+ expect(diagnostics, isNot(contains('OLDEST_PACKAGE_OUTPUT')));
+ expect(diagnostics, contains(log.path));
+ expect(await log.length(), fullLength);
+ expect(rechecked.phase, EnvironmentSetupPhase.waitingForTerminal);
+
+ // Some installers rewrite progress on one long line. Keep its useful tail
+ // even if the only newline is the final byte, and replace the older view.
+ await log.writeAsString('${'x' * (128 * 1024)}LONG_LINE_END\n');
+ final next = await provisioner.ensureReady(
+ onProgress: (_) {},
+ resumeFrom: rechecked,
+ install: false,
+ mode: EnvironmentSetupMode.automatic,
+ );
+ final nextDiagnostics = next.output.join('\n');
+ expect(nextDiagnostics.length, lessThan(80 * 1024));
+ expect(nextDiagnostics, contains('LONG_LINE_END'));
+ expect(nextDiagnostics, isNot(contains('LATEST_PACKAGE_OUTPUT')));
+ },
+ );
+
test('a running Linux Terminal setup is not opened a second time', () async {
await createManagedHarness();
var launches = 0;
diff --git a/desktop/test/environment_recheck_timer_test.dart b/desktop/test/environment_recheck_timer_test.dart
index 64b634a1e..cf9fcb53d 100644
--- a/desktop/test/environment_recheck_timer_test.dart
+++ b/desktop/test/environment_recheck_timer_test.dart
@@ -53,6 +53,67 @@ class _ScriptedProvisioner extends EnvironmentProvisioner {
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
+ test('a failed verification cannot retain an earlier ready result', () {
+ final failed = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.failed,
+ failure: const EnvironmentFailure(
+ title: 'Checking this computer took too long',
+ detail: 'A required tool did not respond.',
+ ),
+ );
+ expect(failed.isReady, isFalse);
+ });
+
+ testWidgets('failed automatic rechecks stop before another install', (
+ tester,
+ ) async {
+ final review = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.failed,
+ },
+ phase: EnvironmentSetupPhase.review,
+ );
+ final waiting = review.copyWith(
+ phase: EnvironmentSetupPhase.waitingForTerminal,
+ mode: EnvironmentSetupMode.automatic,
+ terminalSetup: EnvironmentTerminalSetup.linuxHost,
+ );
+ final failed = review.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ mode: EnvironmentSetupMode.automatic,
+ steps: {
+ EnvironmentStep.tmux: EnvironmentStepStatus.ready,
+ EnvironmentStep.clipboard: EnvironmentStepStatus.ready,
+ EnvironmentStep.harness: EnvironmentStepStatus.failed,
+ },
+ failure: const EnvironmentFailure(
+ title: 'Harness did not respond',
+ detail: 'Retry to check again.',
+ ),
+ );
+ final provisioner = _ScriptedProvisioner([review, waiting, failed]);
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLogin: _FakeCliLogin(),
+ environmentProvisioner: provisioner,
+ );
+ await app.bootstrap();
+ await app.startEnvironmentSetup();
+ await app.recheckEnvironmentStep(EnvironmentStep.tmux);
+ expect(provisioner.installCalls, [false, true, false]);
+ expect(app.status, AppStatus.preparingEnvironment);
+ expect(app.environmentReadiness.phase, EnvironmentSetupPhase.failed);
+ expect(app.environmentRecheckPending, isFalse);
+ app.dispose();
+ });
+
testWidgets('automatic Terminal setup rechecks after five seconds', (
tester,
) async {
diff --git a/desktop/test/environment_setup_screen_test.dart b/desktop/test/environment_setup_screen_test.dart
index fb2494bfd..248efac1f 100644
--- a/desktop/test/environment_setup_screen_test.dart
+++ b/desktop/test/environment_setup_screen_test.dart
@@ -11,7 +11,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/environment_setup_screen.dart';
-const _review = EnvironmentReadiness(
+const setupReview = EnvironmentReadiness(
steps: {
EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
EnvironmentStep.tmux: EnvironmentStepStatus.failed,
@@ -22,14 +22,14 @@ const _review = EnvironmentReadiness(
plan: [EnvironmentPlanItem.tmuxManaged, EnvironmentPlanItem.harnessCli],
);
-class _Login extends CliLogin {
+class SetupLogin extends CliLogin {
@override
Future<CliAuthStatus> checkStatus() async =>
const CliAuthStatus(loggedIn: false);
}
-class _Attempt {
- _Attempt(this.install, this.progress);
+class SetupAttempt {
+ SetupAttempt(this.install, this.progress);
final bool install;
final void Function(EnvironmentReadiness) progress;
final result = Completer<EnvironmentReadiness>();
@@ -39,9 +39,9 @@ class _Attempt {
}
}
-class _Provisioner extends EnvironmentProvisioner {
- _Provisioner() : super(isMacOS: true);
- final attempts = <_Attempt>[];
+class SetupProvisioner extends EnvironmentProvisioner {
+ SetupProvisioner() : super(isMacOS: true);
+ final attempts = <SetupAttempt>[];
@override
Future<EnvironmentReadiness> ensureReady({
required void Function(EnvironmentReadiness) onProgress,
@@ -49,10 +49,10 @@ class _Provisioner extends EnvironmentProvisioner {
bool install = true,
EnvironmentSetupMode? mode,
}) {
- final attempt = _Attempt(install, onProgress);
+ final attempt = SetupAttempt(install, onProgress);
attempts.add(attempt);
onProgress(
- (resumeFrom ?? _review).copyWith(
+ (resumeFrom ?? setupReview).copyWith(
phase: install
? EnvironmentSetupPhase.installing
: EnvironmentSetupPhase.preflight,
@@ -93,22 +93,48 @@ Future<void> _mount(
await tester.pump();
}
-AppNotifier _app(_Provisioner provisioner) =>
+AppNotifier _app(SetupProvisioner provisioner) =>
AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
- cliLogin: _Login(),
+ cliLogin: SetupLogin(),
environmentProvisioner: provisioner,
)
..status = AppStatus.preparingEnvironment
- ..environmentReadiness = _review;
+ ..environmentReadiness = setupReview;
void main() {
+ testWidgets('Retry after a launch check failure only checks the computer', (
+ tester,
+ ) async {
+ final provisioner = SetupProvisioner();
+ final app = _app(provisioner)
+ ..environmentReadiness = setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ mode: EnvironmentSetupMode.automatic,
+ failure: const EnvironmentFailure(
+ title: 'Checking this computer took too long',
+ detail: 'A required tool did not respond.',
+ ),
+ );
+ await _mount(tester, app);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(provisioner.attempts, hasLength(1));
+ expect(provisioner.attempts.single.install, isFalse);
+ provisioner.attempts.single.finish(setupReview);
+ await tester.pump();
+ expect(find.text('Install 2 tools').hitTestable(), findsOneWidget);
+ expect(provisioner.attempts, hasLength(1));
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
testWidgets('manual setup keeps keyboard focus and never starts an install', (
tester,
) async {
- final provisioner = _Provisioner();
+ final provisioner = SetupProvisioner();
final app = _app(provisioner);
await _mount(tester, app);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
@@ -131,9 +157,9 @@ void main() {
testWidgets('Retry after manual setup failure remains a read-only check', (
tester,
) async {
- final provisioner = _Provisioner();
+ final provisioner = SetupProvisioner();
final app = _app(provisioner)
- ..environmentReadiness = _review.copyWith(
+ ..environmentReadiness = setupReview.copyWith(
phase: EnvironmentSetupPhase.failed,
mode: EnvironmentSetupMode.manual,
);
@@ -143,7 +169,7 @@ void main() {
expect(provisioner.attempts, hasLength(1));
expect(provisioner.attempts.single.install, isFalse);
provisioner.attempts.single.finish(
- _review.copyWith(mode: EnvironmentSetupMode.manual),
+ setupReview.copyWith(mode: EnvironmentSetupMode.manual),
);
await tester.pump();
await tester.pump();
@@ -156,10 +182,10 @@ void main() {
testWidgets('setup details can expand and copy without hiding Retry', (
tester,
) async {
- final provisioner = _Provisioner();
+ final provisioner = SetupProvisioner();
final diagnostics = List.generate(40, (i) => 'Installer output line $i');
final app = _app(provisioner)
- ..environmentReadiness = _review.copyWith(
+ ..environmentReadiness = setupReview.copyWith(
phase: EnvironmentSetupPhase.failed,
failure: const EnvironmentFailure(
title: 'Could not install Harness',
@@ -200,17 +226,118 @@ void main() {
app.dispose();
});
+ testWidgets('copy failure keeps setup recovery visible and can be retried', (
+ tester,
+ ) async {
+ final provisioner = SetupProvisioner();
+ final app = _app(provisioner)
+ ..environmentReadiness = setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ output: const ['A diagnostic to copy'],
+ );
+ addTearDown(app.dispose);
+ var rejectClipboard = true;
+ String? copied;
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ if (rejectClipboard) {
+ throw PlatformException(code: 'clipboard_unavailable');
+ }
+ copied = (call.arguments as Map)['text'] as String;
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ await _mount(tester, app, textScale: 2);
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.pump();
+ expect(
+ find
+ .text('Could not copy. Select the text to copy it, or try again.')
+ .hitTestable(),
+ findsOneWidget,
+ );
+ expect(find.text('Retry').hitTestable(), findsOneWidget);
+ expect(find.text('Copied'), findsNothing);
+ expect(tester.takeException(), isNull);
+ expect(provisioner.attempts, isEmpty);
+ rejectClipboard = false;
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.pump();
+ expect(copied, 'A diagnostic to copy');
+ expect(find.text('Copied'), findsOneWidget);
+ expect(find.textContaining('Could not copy.'), findsNothing);
+ await tester.pump(const Duration(milliseconds: 1500));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('an older clipboard failure cannot replace a newer copy result', (
+ tester,
+ ) async {
+ final app = _app(SetupProvisioner())
+ ..environmentReadiness = setupReview.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ output: const ['Diagnostics'],
+ );
+ addTearDown(app.dispose);
+ final writes = <Completer<void>>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ final write = Completer<void>();
+ writes.add(write);
+ await write.future;
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ await _mount(tester, app);
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ expect(writes, hasLength(2));
+ writes.last.complete();
+ await tester.pump();
+ expect(find.text('Copied'), findsOneWidget);
+ writes.first.completeError(
+ PlatformException(code: 'clipboard_unavailable'),
+ );
+ await tester.pump();
+ expect(find.text('Copied'), findsOneWidget);
+ expect(find.textContaining('Could not copy.'), findsNothing);
+ expect(tester.takeException(), isNull);
+ await tester.pump(const Duration(milliseconds: 1500));
+ await tester.pumpWidget(const SizedBox());
+ });
+
for (final scale in [1.0, 2.0]) {
testWidgets('setup actions stay visible at minimum size with $scale text', (
tester,
) async {
- final provisioner = _Provisioner();
+ final provisioner = SetupProvisioner();
final app = _app(provisioner);
addTearDown(app.dispose);
await _mount(tester, app, textScale: scale);
expect(find.text('Install 2 tools').hitTestable(), findsOneWidget);
expect(provisioner.attempts, isEmpty);
- app.environmentReadiness = _review.copyWith(
+ app.environmentReadiness = setupReview.copyWith(
phase: EnvironmentSetupPhase.failed,
failure: const EnvironmentFailure(
title: 'Could not install Harness',
@@ -229,7 +356,7 @@ void main() {
testWidgets('Enter installs and retries once before reaching sign-in', (
tester,
) async {
- final provisioner = _Provisioner();
+ final provisioner = SetupProvisioner();
final app = _app(provisioner);
await _mount(tester, app);
expect(provisioner.attempts, isEmpty);
@@ -241,7 +368,7 @@ void main() {
await tester.pump();
expect(provisioner.attempts, hasLength(1));
provisioner.attempts.single.finish(
- _review.copyWith(
+ setupReview.copyWith(
phase: EnvironmentSetupPhase.failed,
failure: const EnvironmentFailure(
title: 'Could not install Harness',
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 17c3cae4d..8de012353 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/shared/widgets/app_choice_picker.dart';
import 'package:harness/widgets/agent_picker.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/state/swarm_catalog.dart';
@@ -25,7 +26,7 @@ import 'swarm_interactions_test.dart' show chord;
import 'keymap_host_test.dart' show MemoryKeymap;
import 'keymap_runtime_test.dart' as runtime;
-final _newHarness = find.byKey(const ValueKey('harness-start-new'));
+final _newHarness = find.byKey(const ValueKey('harness-start-new-pane'));
final _localProject = find.byKey(const Key('new-agent-project-browse'));
final _newProject = find.byKey(const Key('new-agent-folder-newProject'));
@@ -88,6 +89,7 @@ class _FirstUseApp extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add((
machine: machineId,
@@ -257,7 +259,7 @@ void main() {
await mount(tester, app, projects: projects);
expect(_startInput, findsOneWidget);
expect(_newHarness, findsOneWidget);
- expect(find.byKey(const ValueKey('harness-start-open')), findsOneWidget);
+ expect(find.byKey(const ValueKey('harness-start-new-tab')), findsOneWidget);
expect(tester.widget<TextField>(_startInput).focusNode!.hasFocus, isTrue);
expect(find.byType(ListTile), findsNothing);
expect(find.byType(AlertDialog), findsNothing);
@@ -295,6 +297,8 @@ void main() {
await tester.pump();
await tester.tap(_newHarness);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
expect(picker.opened, 0);
expect(find.byType(AlertDialog), findsOneWidget);
expect(app.probes, 1);
@@ -352,6 +356,8 @@ void main() {
expect(find.text('Machines'), findsNothing);
await tester.tap(_newHarness);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
expect(picker.opened, 0);
await _browseLocal(tester);
await tester.pump();
@@ -410,7 +416,7 @@ void main() {
await tester.tapAt(const Offset(8, 100));
await tester.pump();
expect(find.byType(AlertDialog), findsOneWidget);
- expect(find.text('Creating harness…'), findsOneWidget);
+ expect(find.text('Starting harness…'), findsOneWidget);
expect(app.launches, hasLength(1));
expect(app.panes, isEmpty);
expect(tester.widget<AppChoiceTile>(_localProject).onPressed, isNull);
@@ -504,20 +510,20 @@ void main() {
await tester.pump();
await opening;
} else {
- final addButton = find.byKey(
- const ValueKey('swarm-new-agent-button'),
+ expect(
+ find.byKey(const ValueKey('swarm-new-pane-button')),
+ findsNothing,
);
- final bell = find.byKey(const ValueKey('swarm-notifications-button'));
expect(
- tester.getRect(bell).right,
- lessThan(tester.getRect(addButton).left),
+ find.byKey(const ValueKey('swarm-notifications-button')),
+ findsOneWidget,
);
expect(
find.byKey(const ValueKey('swarm-new-harness-button')),
findsNothing,
);
expect(find.byType(FloatingActionButton), findsNothing);
- await tester.tap(addButton);
+ await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
}
await tester.pump();
@@ -691,7 +697,7 @@ void main() {
addTearDown(() => FileSelectorPlatform.instance = oldPicker);
await mount(tester, app);
- expect(find.text('New Harness'), findsWidgets);
+ expect(find.text('New Pane'), findsWidgets);
expect(find.text('Machines'), findsNothing);
expect(find.text('Projects'), findsNothing);
expect(app.launches, isEmpty);
@@ -699,6 +705,8 @@ void main() {
expect(tester.widget<TextField>(_startInput).focusNode!.hasFocus, isTrue);
await tester.tap(_newHarness);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
final engine = tester.widget<AgentPicker>(find.byType(AgentPicker));
expect(engine.value, 'codex');
expect(find.byKey(const Key('new-agent-machine-field')), findsOneWidget);
@@ -725,12 +733,7 @@ void main() {
await tester.pump();
expect(app.launches, [
- (
- machine: 'm',
- engine: 'codex',
- folder: '/work/my-project',
- bypass: true,
- ),
+ (machine: 'm', engine: 'codex', folder: '/work/my-project', bypass: true),
]);
expect(find.byType(TerminalView), findsOneWidget);
expect(find.text('Your first workspace'), findsNothing);
@@ -803,6 +806,8 @@ void main() {
await tester.tap(_newHarness);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
expect(find.byType(AlertDialog), findsOneWidget);
await _browseLocal(tester);
await tester.pump();
@@ -846,6 +851,8 @@ void main() {
await mount(tester, app);
await tester.tap(_newHarness);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
await _browseLocal(tester);
await tester.pump();
expect(picker.opened, 1);
diff --git a/desktop/test/fork_agent_test.dart b/desktop/test/fork_agent_test.dart
index 33b7c055d..fdd60ec68 100644
--- a/desktop/test/fork_agent_test.dart
+++ b/desktop/test/fork_agent_test.dart
@@ -104,6 +104,7 @@ void main() {
'agentId': 'a0',
'name': 'Agent 0 - fork',
'prompt': 'ship it',
+ 'creationId': isA<String>(),
});
// Beside the source, in the tab that was open, focused, and known to the machine.
@@ -160,17 +161,28 @@ void main() {
expect(app.focusedPane?.agentId, 'a0-fork');
});
- testWidgets(
- 'the dialog opens named "X - fork", takes a task, and ⌘Return forks',
- (tester) async {
- ({String name, String task})? picked;
- await tester.pumpWidget(
- MaterialApp(
- home: Builder(
+ testWidgets('the prompt opens with a name and submits the exact first task', (
+ tester,
+ ) async {
+ final connection = _Connection();
+ connection.answer = (type, payload) async => {
+ 'agent': _agentJson('forked'),
+ 'level': 'native',
+ };
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.stateOf('m')!.nodeOnline = true;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
builder: (context) => TextButton(
onPressed: () async {
- picked = await showForkAgentDialogForTest(
+ await forkHarness(
context,
+ app,
+ 'm',
+ 'a0',
'Kinh Te',
engine: 'claude',
);
@@ -179,24 +191,28 @@ void main() {
),
),
),
- );
- await tester.tap(find.text('open'));
- await tester.pumpAndSettle();
- expect(find.text('Fork Harness'), findsOneWidget);
- expect(find.textContaining('everything “Kinh Te” knows'), findsOneWidget);
- final name = tester.widget<TextField>(
- find.byKey(const ValueKey('fork-name')),
- );
- expect(name.controller!.text, 'Kinh Te - fork');
- await tester.enterText(
- find.byKey(const ValueKey('fork-task')),
- 'ship it',
- );
- await tester.tap(find.byKey(const ValueKey('fork-submit')));
- await tester.pumpAndSettle();
- expect(picked, (name: 'Kinh Te - fork', task: 'ship it'));
- },
- );
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(find.text('Fork Agent'), findsOneWidget);
+ expect(find.textContaining('same project folder'), findsOneWidget);
+ final name = tester.widget<TextField>(
+ find.byKey(const ValueKey('fork-name')),
+ );
+ expect(name.controller!.text, 'Kinh Te - fork');
+ await tester.enterText(find.byKey(const ValueKey('fork-task')), 'ship it');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(
+ connection.calls.firstWhere((call) => call.$1 == 'agent_fork').$2,
+ containsPair('prompt', 'ship it'),
+ );
+ expect(
+ app.stateOf('m')!.agents.any((agent) => agent.id == 'forked'),
+ isTrue,
+ );
+ });
test('Fork is offered only where the daemon (or the engine) can fork', () {
expect(
diff --git a/desktop/test/fork_keyboard_test.dart b/desktop/test/fork_keyboard_test.dart
new file mode 100644
index 000000000..707d8c353
--- /dev/null
+++ b/desktop/test/fork_keyboard_test.dart
@@ -0,0 +1,326 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'support/fork_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+final _task = find.byKey(const ValueKey('fork-task'));
+final _name = find.byKey(const ValueKey('fork-name'));
+TextField field(WidgetTester tester, Finder finder) =>
+ tester.widget<TextField>(finder);
+
+// The fixture has no new PTY transport. Verify receipt/UI completion without
+// waiting for the new pane's intentionally ongoing attachment animation.
+Future<void> pumpForkReceipt(WidgetTester tester) async {
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 120));
+}
+
+void main() {
+ late ForkConnection connection;
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late SwarmProjectStore projects;
+ setUp(() {
+ connection = ForkConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.nodeOnline = true;
+ map = MemoryKeymap();
+ projects = SwarmProjectStore();
+ });
+ tearDown(() {
+ app.dispose();
+ map.dispose();
+ projects.dispose();
+ });
+ Future<void> mount(
+ WidgetTester tester, {
+ Size size = const Size(1280, 800),
+ double scale = 1,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ projectStore: projects,
+ nativeTabs: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> open(
+ WidgetTester tester, {
+ LogicalKeyboardKey accept = LogicalKeyboardKey.enter,
+ }) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> fork',
+ );
+ await key(tester, accept);
+ await tester.pumpAndSettle();
+ }
+
+ String getId() => connection.forks.last['creationId'] as String;
+
+ testWidgets(
+ 'fork keeps its draft, task focus, pending request and inline retry',
+ (tester) async {
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ await mount(tester);
+ await open(tester);
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ expect(field(tester, _name).controller!.text, 'Agent 0 - fork');
+ tester.testTextInput.enterText(' keep\n indentation ');
+ await key(tester, LogicalKeyboardKey.escape);
+ await open(tester);
+ expect(field(tester, _task).controller!.text, ' keep\n indentation ');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(connection.forks.single['prompt'], ' keep\n indentation ');
+ expect(field(tester, _task).readOnly, isTrue);
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.forks, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await open(tester);
+ expect(find.text('Waiting for fork…'), findsOneWidget);
+ expect(connection.forks, hasLength(1));
+ connection.forkReplies.single.complete({
+ 'creationId': getId(),
+ 'state': 'failed',
+ 'failure': {'code': 'BUSY', 'detail': 'Wait for the turn to finish.'},
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Wait for the turn to finish.'), findsOneWidget);
+ expect(field(tester, _task).readOnly, isFalse);
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.forkReplies.last.complete(forkReceipt(getId()));
+ await pumpForkReceipt(tester);
+ expect(_task, findsNothing);
+ expect(app.focusedPane!.agentId, 'forked');
+ expect(input, isEmpty);
+ app.focusPane(app.panes.first.id, reveal: true);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'lost fork reply locks its draft and Enter checks the same receipt',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ tester.testTextInput.enterText('another approach');
+ await key(tester, LogicalKeyboardKey.enter);
+ final id = getId();
+ connection.forkReplies.single.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('enter check status'), findsOneWidget);
+ expect(field(tester, _task).readOnly, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await open(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.checks, [
+ {'creationId': id},
+ ]);
+ expect(connection.forks, hasLength(1));
+ connection.checkReplies.single.complete(
+ forkReceipt(id, level: 'handoff'),
+ );
+ await pumpForkReceipt(tester);
+ expect(_task, findsNothing);
+ expect(find.textContaining('handoff summary'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('a new fork after uncertainty is a separate explicit action', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ await key(tester, LogicalKeyboardKey.enter);
+ final oldId = getId();
+ connection.forkReplies.single.complete({
+ 'creationId': oldId,
+ 'state': 'unconfirmed',
+ });
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('fork-start-another')));
+ await tester.pumpAndSettle();
+ expect(connection.forks, hasLength(1));
+ expect(field(tester, _task).readOnly, isFalse);
+ expect(
+ find.textContaining('previous fork may already exist'),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(getId(), isNot(oldId));
+ connection.forkReplies.last.complete(forkReceipt(getId()));
+ await pumpForkReceipt(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'fork respects custom keys, composition, line editing and disabled defaults',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ map.apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f6","command":"picker.complete","when":"picker"},
+ {"keys":"f10","command":"picker.add_here","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await mount(tester);
+ await open(tester, accept: LogicalKeyboardKey.f8);
+ tester.testTextInput.enterText('Fix parser edge');
+ final editor = field(tester, _task).controller!;
+ editor.value = editor.value.copyWith(
+ composing: const TextRange(start: 0, end: 3),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.f10);
+ expect(editor.text, 'Fix parser edge');
+ expect(connection.forks, isEmpty);
+ editor.clearComposing();
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(connection.forks, isEmpty);
+ expect(_task, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
+ expect(editor.text, 'Fix parser ');
+ await key(tester, LogicalKeyboardKey.enter, alt: true);
+ expect(editor.text, 'Fix parser \n');
+ await key(tester, LogicalKeyboardKey.f10);
+ expect(connection.forks.single['prompt'], 'Fix parser \n');
+ map.apply(
+ '''{"bindings":[{"keys":"f4","command":"picker.cancel","when":"picker"}]}''',
+ );
+ await tester.pump();
+ expect(find.text('F4 close'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(_task, findsNothing);
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ await pumpForkReceipt(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('name validation and native Next retain editing ownership', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ await tester.enterText(_name, '');
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(field(tester, _name).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Separate idea');
+ await tester.testTextInput.receiveAction(TextInputAction.next);
+ await tester.pump();
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('first');
+ await key(tester, LogicalKeyboardKey.enter, alt: true);
+ expect(field(tester, _task).controller!.text, 'first\n');
+ await key(tester, LogicalKeyboardKey.keyP, ctrl: true);
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ expect(field(tester, _task).controller!.selection.baseOffset, lessThan(6));
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ expect(field(tester, _task).controller!.selection.baseOffset, 6);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.forks.single['name'], 'Separate idea');
+ connection.forkReplies.single.complete(forkReceipt(getId()));
+ await pumpForkReceipt(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('fork prompt works at enlarged text and retains pending Escape', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, size: const Size(480, 360), scale: 1.7);
+ await open(tester);
+ expect(field(tester, _task).focusNode!.hasPrimaryFocus, isTrue);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.forkReplies.single.completeError(
+ const WsRequestTimeout('agent_fork'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(find.text('Fork may already exist.').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_task, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final shared in [true, false]) {
+ testWidgets(
+ 'fork is absent for ${shared ? 'shared' : 'unsupported'} agents',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ if (shared) {
+ app.stateOf('m')!.machine = const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ } else {
+ app.stateOf('m')!.agents = [
+ const Agent(id: 'a0', name: 'Shell', engine: 'terminal'),
+ ];
+ }
+ await mount(tester);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> fork',
+ );
+ expect(find.byKey(const ValueKey('command:agent.fork')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/generated_project_launch_test.dart b/desktop/test/generated_project_launch_test.dart
new file mode 100644
index 000000000..255177f82
--- /dev/null
+++ b/desktop/test/generated_project_launch_test.dart
@@ -0,0 +1,323 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:path/path.dart' as p;
+
+class _Connection extends WsConn {
+ _Connection(String id)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: id,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final creates = <Map<String, dynamic>>[];
+ final checks = <String>[];
+ int collisions = 0;
+ bool loseReply = false;
+ bool collisionAsFailure = false;
+ bool wrongCollisionReceipt = false;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ {'engine': 'codex', 'installed': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ }
+ if (type == 'dsh_list') return {'dsh': []};
+ if (type == 'fs_list_dir') {
+ return {'path': payload['path'] ?? '/fixture/$machineId', 'entries': []};
+ }
+ if (type == 'agent_create') {
+ creates.add(Map.of(payload));
+ if (collisions-- > 0) {
+ if (collisionAsFailure) {
+ throw const WsRequestFailure(
+ responseType: 'agent_create_result',
+ code: 'PROJECT_EXISTS',
+ detail: 'That folder already exists.',
+ );
+ }
+ return {
+ 'creationId': wrongCollisionReceipt
+ ? 'another-request'
+ : payload['creationId'],
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'PROJECT_EXISTS',
+ 'detail': 'That folder already exists.',
+ },
+ };
+ }
+ if (loseReply) {
+ loseReply = false;
+ throw const WsRequestTimeout('agent_create');
+ }
+ } else if (type == 'agent_create_status') {
+ checks.add(payload['creationId'] as String);
+ } else {
+ return {};
+ }
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'made-${creates.length}',
+ 'name': 'A new harness',
+ 'engine': 'codex',
+ },
+ };
+ }
+}
+
+class _App extends AppNotifier {
+ _App(this.root, Map<String, _Connection> connections)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ connectionForTest: (id) => connections[id]!,
+ ) {
+ machines = [
+ for (final id in connections.keys)
+ Machine(machineId: id, name: id, authMode: MachineAuthMode.remote),
+ ];
+ for (final machine in machines) {
+ machineStates[machine.machineId] = MachineState(machine)
+ ..localOnly = machine.machineId == 'local'
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ }
+ status = AppStatus.authenticated;
+ }
+ final String root;
+ @override
+ Future<String> prepareLocalProjectFolder(
+ ProjectFolderRequest request, {
+ String label = 'harness',
+ }) => request.prepareLocal(projectHome: root, label: label);
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ final at = DateTime(2026, 9, 20, 17, 22, 19);
+ late Directory home;
+ late _App app;
+ late Map<String, _Connection> connections;
+ setUp(() async {
+ home = await Directory.systemTemp.createTemp('harness-generated-project-');
+ connections = {
+ for (final id in ['local', 'remote']) id: _Connection(id),
+ };
+ app = _App(p.join(home.path, 'harnesses'), connections);
+ });
+ tearDown(() async {
+ app.dispose();
+ for (final connection in connections.values) {
+ await connection.close();
+ }
+ await home.delete(recursive: true);
+ });
+
+ NewHarnessController box([String machine = 'local']) => NewHarnessController(
+ app,
+ machineId: machine,
+ engine: 'codex',
+ autoProject: true,
+ now: () => at,
+ home: home.path,
+ placement: HarnessPlacement.newTab,
+ );
+
+ test('the suggested folder is shown, survives a delay, and is the folder used by Start', () async {
+ var clock = at;
+ final draft = NewHarnessController(
+ app,
+ machineId: 'local',
+ engine: 'codex',
+ autoProject: true,
+ now: () => clock,
+ home: home.path,
+ placement: HarnessPlacement.newTab,
+ );
+ addTearDown(draft.dispose);
+ expect(draft.field, NewHarnessField.launch);
+ expect(draft.projectLabel, '~/harnesses/codex-2026-09-20-17-22');
+ expect(draft.needsProject, isFalse);
+ clock = at.add(const Duration(minutes: 15));
+ expect(await draft.create(), NewHarnessOutcome.created);
+ final folder = connections['local']!.creates.single['cwd'] as String;
+ expect(p.basename(folder), 'codex-2026-09-20-17-22');
+ expect(await Directory(folder).exists(), isTrue);
+ });
+
+ test('two starts reserve unique folders and preserve an existing folder and its files', () async {
+ final existing = Directory(p.join(app.root, 'codex-2026-09-20-17-22'));
+ await existing.create(recursive: true);
+ final keep = File(p.join(existing.path, 'keep.txt'));
+ await keep.writeAsString('untouched');
+ final a = box(), b = box();
+ addTearDown(a.dispose);
+ addTearDown(b.dispose);
+ expect(await Future.wait([a.create(), b.create()]), [
+ NewHarnessOutcome.created,
+ NewHarnessOutcome.created,
+ ]);
+ expect(
+ connections['local']!.creates
+ .map((c) => p.basename(c['cwd'] as String))
+ .toSet(),
+ {'codex-2026-09-20-17-22-19', 'codex-2026-09-20-17-22-19-2'},
+ );
+ expect(await keep.readAsString(), 'untouched');
+ });
+
+ test(
+ 'the suggested name is prefilled; editing it makes it an explicit choice',
+ () async {
+ final draft = box();
+ addTearDown(draft.dispose);
+ draft.focusField(NewHarnessField.projectName);
+ expect(draft.query, 'codex-2026-09-20-17-22');
+ draft.accept();
+ expect(draft.projectFolderRequest!.isGenerated, isTrue);
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('my new tool');
+ draft.accept();
+ expect(draft.projectFolderRequest!.isGenerated, isFalse);
+ expect(draft.projectLabel, '~/harnesses/my-new-tool');
+ draft.focusField(NewHarnessField.agent);
+ draft.setQuery('Claude');
+ draft.accept();
+ expect(draft.projectLabel, '~/harnesses/my-new-tool');
+ expect(await draft.create(), NewHarnessOutcome.created);
+ expect(
+ p.basename(connections['local']!.creates.single['cwd'] as String),
+ 'my-new-tool',
+ );
+ },
+ );
+
+ test('switching machines carries a fresh suggestion and restores each machine’s draft', () async {
+ final draft = box();
+ addTearDown(draft.dispose);
+ final original = draft.project;
+ draft.focusField(NewHarnessField.machine);
+ draft.setQuery('remote');
+ draft.accept();
+ expect(draft.machineId, 'remote');
+ expect(draft.projectFolderRequest!.isGenerated, isTrue);
+ expect(draft.project.folder, isNull);
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('remote-work');
+ draft.accept();
+ draft.focusField(NewHarnessField.machine);
+ draft.setQuery('local');
+ draft.accept();
+ expect(draft.project, original);
+ draft.focusField(NewHarnessField.machine);
+ draft.setQuery('remote');
+ draft.accept();
+ expect(draft.project.name, 'remote-work');
+ expect(draft.projectFolderRequest!.isGenerated, isFalse);
+ });
+
+ test('remote collisions advance only an automatic name and use distinct receipts', () async {
+ connections['remote']!.collisions = 2;
+ final draft = box('remote');
+ addTearDown(draft.dispose);
+ expect(await draft.create(), NewHarnessOutcome.created);
+ final calls = connections['remote']!.creates;
+ expect(calls.map((c) => c['projectName']), [
+ 'codex-2026-09-20-17-22',
+ 'codex-2026-09-20-17-22-19',
+ 'codex-2026-09-20-17-22-19-2',
+ ]);
+ expect(calls.map((c) => c['creationId']).toSet(), hasLength(3));
+ });
+
+ test('a lost reply after collision checks that exact attempt without another start', () async {
+ connections['remote']!
+ ..collisions = 1
+ ..loseReply = true;
+ final draft = box('remote');
+ addTearDown(draft.dispose);
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(draft.checking, isTrue);
+ expect(connections['remote']!.creates, hasLength(2));
+ expect(await draft.create(), NewHarnessOutcome.created);
+ expect(connections['remote']!.creates, hasLength(2));
+ expect(connections['remote']!.checks, [
+ connections['remote']!.creates.last['creationId'],
+ ]);
+ });
+
+ test(
+ 'a collision belonging to another receipt cannot trigger a new start',
+ () async {
+ connections['remote']!
+ ..collisions = 1
+ ..wrongCollisionReceipt = true;
+ final draft = box('remote');
+ addTearDown(draft.dispose);
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(draft.checking, isTrue);
+ expect(connections['remote']!.creates, hasLength(1));
+ },
+ );
+
+ test('a typed collision refusal leaves a custom name editable', () async {
+ connections['remote']!
+ ..collisions = 1
+ ..collisionAsFailure = true;
+ final draft = box('remote');
+ addTearDown(draft.dispose);
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('payments');
+ draft.accept();
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(draft.checking, isFalse);
+ expect(draft.error, contains('already exists'));
+ expect(connections['remote']!.creates, hasLength(1));
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('design-system');
+ draft.accept();
+ expect(await draft.create(), NewHarnessOutcome.created);
+ expect(connections['remote']!.creates.last['projectName'], 'design-system');
+ });
+
+ test(
+ 'a user-chosen name is never silently numbered after a remote conflict',
+ () async {
+ connections['remote']!.collisions = 1;
+ final draft = box('remote');
+ addTearDown(draft.dispose);
+ draft.focusField(NewHarnessField.projectName);
+ draft.setQuery('payments');
+ draft.accept();
+ expect(await draft.create(), NewHarnessOutcome.failed);
+ expect(draft.error, contains('already exists'));
+ expect(connections['remote']!.creates, hasLength(1));
+ expect(draft.project.name, 'payments');
+ },
+ );
+}
diff --git a/desktop/test/grid_model_picker_test.dart b/desktop/test/grid_model_picker_test.dart
index e20f59191..45697f0aa 100644
--- a/desktop/test/grid_model_picker_test.dart
+++ b/desktop/test/grid_model_picker_test.dart
@@ -1,6 +1,9 @@
// The pane header's model picker: two sections, the way back always offered, and a tick that says
// where the agent actually is.
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:harness/widgets/box_chrome.dart';
+import 'package:harness/widgets/transient_menus.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
@@ -152,6 +155,72 @@ void main() {
expect(find.textContaining('usage'), findsOneWidget);
});
+ testWidgets('compact model menu stays on screen and is keyboard navigable', (
+ tester,
+ ) async {
+ tester.view.physicalSize = const Size(380, 300);
+ tester.view.devicePixelRatio = 1;
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.view.reset);
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ var ownLogin = 0;
+ var manage = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: GridModelPicker(
+ notifier: notifier,
+ machineId: 'local',
+ compact: true,
+ currentModel: 'fixture-model',
+ engineLabel: 'claude',
+ onUseOwnLogin: () => ownLogin++,
+ onRunLocalModel: () => manage++,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final trigger = Focus.of(tester.element(find.byIcon(Icons.tune)));
+ trigger.requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Subscription'), findsOneWidget);
+ final bounds = tester.getRect(find.byType(TerminalBox));
+ expect(bounds.left, greaterThanOrEqualTo(8));
+ expect(bounds.right, lessThanOrEqualTo(372));
+ expect(bounds.bottom, lessThanOrEqualTo(292));
+ expect(tester.takeException(), isNull);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(ownLogin, 1);
+ expect(trigger.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(manage, 1);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Subscription'), findsNothing);
+ expect(trigger.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ dismissTransientMenus();
+ await tester.pumpAndSettle();
+ expect(find.text('Subscription'), findsNothing);
+ expect(ownLogin, 1);
+ expect(manage, 1);
+ });
+
// THREE situations, two sentences and one silence, one test each — a single test cannot cover
// them, because re-pumping the same widget reuses the State and the picker answers from the memo
// it already has. Only the middle one is about the ACCOUNT, and folding the first two together is
diff --git a/desktop/test/harness_command_bar_test.dart b/desktop/test/harness_command_bar_test.dart
index fbb5e19da..eb7d1a047 100644
--- a/desktop/test/harness_command_bar_test.dart
+++ b/desktop/test/harness_command_bar_test.dart
@@ -9,12 +9,16 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/command_bar.dart';
+import 'package:harness/state/new_harness.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/widgets/harness_command_bar.dart';
+import 'package:harness/widgets/new_harness_box.dart';
import 'package:xterm/xterm.dart';
import 'support/real_fonts.dart';
+import 'support/mixed_agents.dart';
import 'swarm_state_test.dart' show createApp, MemoryStore;
import 'swarm_screen_test.dart' show terminal;
import 'swarm_interactions_test.dart' show chord;
@@ -356,7 +360,10 @@ void main() {
tester.testTextInput.enterText('Open a fresh tab');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();
- expect(app.activeSwarmId, isNot(previousTab));
+ expect(app.activeSwarmId, previousTab);
+ final picker = find.byKey(const ValueKey('swarm-search-input'));
+ expect(picker, findsOneWidget);
+ expect(tester.widget<TextField>(picker).focusNode!.hasFocus, isTrue);
expect(input, findsNothing);
// The exact app command opens the tab even without a provider decision.
expect(calls, 1);
@@ -364,6 +371,83 @@ void main() {
},
);
+ testWidgets(
+ 'JEV hands a task to the new prompt on the chosen machine without a foreign folder',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ seedMixedAgents(app);
+ app.machineStates['m']!.localOnly = true;
+ final session = TerminalSession(
+ machineId: 'studio',
+ agentId: 'focus',
+ agentName: 'Remote task',
+ engineId: 'opencode',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ )..status = TerminalSessionStatus.controlling;
+ app.adoptSessionForTest(session);
+ final projects = SwarmProjectStore(storage: MemoryStore());
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ projects.dispose();
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: false,
+ projectStore: projects,
+ commandResolver: (_, _) async => {
+ 'selectedId': 'create:m:studio/arm',
+ 'autoExecute': false,
+ },
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await chord(tester, LogicalKeyboardKey.keyJ, shift: true);
+ await tester.enterText(input, 'Plan the arm calibration');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(input, findsNothing);
+ final prompt = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(prompt.machineId, 'm');
+ expect(prompt.engine, 'studio/arm');
+ expect(prompt.project.folder, isNull);
+ expect(prompt.task, 'Plan the arm calibration');
+ expect(prompt.field, NewHarnessField.projectMenu);
+ expect(find.byKey(const ValueKey('new-harness-input')), findsOneWidget);
+ await tester.tap(
+ find.byKey(const ValueKey(NewHarnessController.newProjectId)),
+ );
+ await tester.pump();
+ expect(prompt.field, NewHarnessField.projectName);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('new-harness-input')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ // Opening the experimental prompt saves this draft and removes its dock.
+ await chord(tester, LogicalKeyboardKey.keyJ, shift: true);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(input, findsOneWidget);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(app.allPanes, hasLength(1));
+ expect(tester.takeException(), isNull);
+ },
+ );
+
testWidgets(
'disabling JEV leaves the normal start page and shortcut behavior intact',
(tester) async {
diff --git a/desktop/test/harness_customize_test.dart b/desktop/test/harness_customize_test.dart
index acbb0d5d2..4cd82881a 100644
--- a/desktop/test/harness_customize_test.dart
+++ b/desktop/test/harness_customize_test.dart
@@ -1,3 +1,5 @@
+import 'package:harness/terminal/terminal_binary.dart';
+
import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;
@@ -15,6 +17,12 @@ import 'package:harness/shared/theme/harness_background.dart';
import 'package:harness/widgets/harness_customize_pane.dart';
import 'support/real_fonts.dart';
+
+import 'package:harness/shared/theme/prompt_style.dart';
+import 'package:harness/widgets/prompt_context.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
class _Storage implements LocalKeyValueStore {
@@ -60,6 +68,128 @@ void main() {
.load();
});
+ test('rapid prompt edits persist together and malformed prompt leaves appearance intact', () async {
+ final storage = _Storage()..gate = Completer<void>();
+ final store = AppearancePrefsStore(storage: storage);
+ addTearDown(store.dispose);
+ final saving = store.setPrompt(const PromptPrefs(style: PromptStyle.plain));
+ store.setPrompt(store.value.prompt.copyWith(branch: false));
+ store.setPrompt(
+ store.value.prompt.copyWith(style: PromptStyle.powerline, color: false),
+ );
+ storage.gate!.complete();
+ await saving;
+ final reopened = AppearancePrefsStore(storage: storage);
+ addTearDown(reopened.dispose);
+ await reopened.load();
+ expect(
+ reopened.value.prompt,
+ const PromptPrefs(
+ style: PromptStyle.powerline,
+ branch: false,
+ color: false,
+ ),
+ );
+ await store.setPalette(HarnessPalette.forest);
+ storage.values['workspace_prompt_v1'] = '{broken';
+ await reopened.load();
+ expect(reopened.value.prompt, const PromptPrefs());
+ expect(reopened.value.palette, HarnessPalette.forest);
+ await store.reset();
+ await reopened.load();
+ expect(reopened.value, const AppearancePrefs());
+ });
+
+ testWidgets(
+ 'prompt choices preview, accept keyboard input and survive reopening',
+ (tester) async {
+ final storage = _Storage();
+ final store = AppearancePrefsStore(storage: storage);
+ addTearDown(store.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SizedBox(
+ width: 440,
+ child: HarnessCustomizePane(store: store, onClose: () {}),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> focus(String key) async {
+ final label = find
+ .descendant(
+ of: find.byKey(ValueKey(key)),
+ matching: find.byType(Text),
+ )
+ .first;
+ for (
+ var i = 0;
+ i < 20 && !Focus.of(tester.element(label)).hasFocus;
+ i++
+ ) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ expect(Focus.of(tester.element(label)).hasFocus, isTrue);
+ }
+
+ await focus('prompt-style-powerline');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(store.value.prompt.style, PromptStyle.powerline);
+ await focus('prompt-branch');
+ await tester.sendKeyEvent(LogicalKeyboardKey.space);
+ await tester.pumpAndSettle();
+ expect(store.value.prompt.branch, isFalse);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('prompt-preview')),
+ matching: find.text('main'),
+ ),
+ findsNothing,
+ );
+ final reopened = AppearancePrefsStore(storage: storage);
+ addTearDown(reopened.dispose);
+ await reopened.load();
+ expect(reopened.value.prompt, store.value.prompt);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'command search opens customization and Escape returns typing to the terminal',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final input = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', input));
+ await mount(tester, app);
+ final before = tester.getRect(find.byKey(pane.cellKey));
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> customize',
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessCustomizePane), findsOneWidget);
+ expect(find.byType(PromptContextView), findsWidgets);
+ expect(tester.getRect(find.byKey(pane.cellKey)), before);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(HarnessCustomizePane), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump();
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
test(
'background persists without replacing palette or type choices',
() async {
@@ -109,6 +239,8 @@ void main() {
),
);
await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('customize-background')));
+ await tester.pumpAndSettle();
final choice = find.byKey(const ValueKey('background-lake'));
await tester.ensureVisible(choice);
await tester.tap(choice);
@@ -192,6 +324,20 @@ void main() {
expect(find.byKey(const ValueKey('harness-start-results')), findsNothing);
expect(tester.widget<TextField>(start).controller!.text, 'Keep my query');
expect(tester.takeException(), isNull);
+ for (final style in PromptStyle.values) {
+ appearancePrefsStore.value = appearancePrefsStore.value.copyWith(
+ prompt: PromptPrefs(style: style),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await _capture(
+ tester,
+ boundary,
+ '${width.toInt()}-prompt-${style.name}',
+ );
+ }
+ await tester.tap(find.byKey(const ValueKey('customize-background')));
+ await tester.pumpAndSettle();
await _capture(tester, boundary, '${width.toInt()}-background');
await tester.tap(find.byKey(const ValueKey('customize-appearance')));
diff --git a/desktop/test/harness_file_store_test.dart b/desktop/test/harness_file_store_test.dart
index e57a98a05..55731d291 100644
--- a/desktop/test/harness_file_store_test.dart
+++ b/desktop/test/harness_file_store_test.dart
@@ -197,4 +197,56 @@ void main() {
}
}
}, skip: Platform.isWindows);
+
+ test(
+ 'reads repair directory and lock permissions changed between calls',
+ () async {
+ final store = HarnessFileStore(directory: dataDirectory);
+ await store.write('preference', 'kept');
+ final lock = File(
+ '${dataDirectory.path}/${HarnessFileStore.lockFileName}',
+ );
+
+ for (final reader in [
+ store,
+ HarnessFileStore(directory: dataDirectory),
+ ]) {
+ expect(
+ (await Process.run('/bin/chmod', [
+ '755',
+ dataDirectory.path,
+ ])).exitCode,
+ 0,
+ );
+ expect(
+ (await Process.run('/bin/chmod', ['664', lock.path])).exitCode,
+ 0,
+ );
+ expect(await reader.readMany(['preference']), {'preference': 'kept'});
+ expect((await dataDirectory.stat()).mode & 0xfff, 0x1c0);
+ expect((await lock.stat()).mode & 0xfff, 0x180);
+ expect((await store.stateFile.stat()).mode & 0xfff, 0x180);
+ }
+ },
+ skip: Platform.isWindows,
+ );
+
+ test(
+ 'a replacement directory at the same path is made private again',
+ () async {
+ final store = HarnessFileStore(directory: dataDirectory);
+ await store.write('preference', 'old');
+ await dataDirectory.delete(recursive: true);
+ await dataDirectory.create();
+ expect(
+ (await Process.run('/bin/chmod', ['755', dataDirectory.path])).exitCode,
+ 0,
+ );
+ await store.write('preference', 'new');
+ expect(await store.read('preference'), 'new');
+ expect((await dataDirectory.stat()).mode & 0xfff, 0x1c0);
+ expect((await store.stateFile.stat()).mode & 0xfff, 0x180);
+ },
+ skip: Platform.isWindows,
+ );
}
diff --git a/desktop/test/harness_picker_entry_test.dart b/desktop/test/harness_picker_entry_test.dart
index 00dab676e..6d9116780 100644
--- a/desktop/test/harness_picker_entry_test.dart
+++ b/desktop/test/harness_picker_entry_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/state/swarm_search.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shortcuts/app_keymap.dart';
import 'package:harness/terminal/terminal_binary.dart';
@@ -70,19 +71,19 @@ void main() {
);
await tester.pump(const Duration(milliseconds: 100));
final field = find.byKey(const ValueKey('swarm-search-input'));
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
expect(field, findsOneWidget);
expect(find.byType(SwarmSearchResults), findsOneWidget);
expect(
find.byKey(const ValueKey('swarm-search-preview')),
- findsOneWidget,
+ findsNothing,
);
expect(find.byKey(const ValueKey('harness-picker-open')), findsNothing);
expect(
tester.widget<TextField>(field).decoration!.hintText,
- 'Find a harness',
+ kHarnessPickerHint,
);
- expect(find.text('Find a harness'), findsOneWidget);
+ expect(find.text(kHarnessPickerHint), findsOneWidget);
expect(find.byKey(const ValueKey('create-agent-submit')), findsNothing);
final before = tester.getRect(field);
final controller = tester.widget<TextField>(field).controller;
diff --git a/desktop/test/harness_placement_test.dart b/desktop/test/harness_placement_test.dart
new file mode 100644
index 000000000..ef5871ac4
--- /dev/null
+++ b/desktop/test/harness_placement_test.dart
@@ -0,0 +1,976 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/codex_profiles.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_preset.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/codex_profile_field.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _Connection extends WsConn {
+ _Connection({this.profiles = const []})
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final List<Map<String, dynamic>> profiles;
+ final requests =
+ <
+ ({
+ String type,
+ Map<String, dynamic> payload,
+ Completer<Map<String, dynamic>> reply,
+ })
+ >[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'engines_probe') {
+ return Future.value({
+ 'engines': [
+ {
+ 'engine': 'codex',
+ 'installed': true,
+ 'supportsCodexHome': profiles.isNotEmpty,
+ },
+ ],
+ });
+ }
+ if (type == 'codex_profiles_list') {
+ return Future.value({'profiles': profiles});
+ }
+ if (type == 'fs_list_dir') {
+ return Future.value({
+ 'path': payload['path'],
+ 'entries': [
+ if (payload['path'] == '/work')
+ {'name': 'space project', 'isDir': true},
+ ],
+ });
+ }
+ if (type != 'agent_create' && type != 'agent_create_status') {
+ return Future.value({});
+ }
+ final reply = Completer<Map<String, dynamic>>();
+ requests.add((type: type, payload: payload, reply: reply));
+ return reply.future;
+ }
+
+ void created() {
+ final request = requests.last;
+ request.reply.complete({
+ 'creationId': request.payload['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'made', 'name': 'Made', 'engine': 'codex'},
+ });
+ }
+}
+
+SwarmSearchController picker(AppNotifier app, HarnessPlacement placement) =>
+ SwarmSearchController(
+ app,
+ [],
+ adding: true,
+ offersCreate: true,
+ placement: placement,
+ );
+
+void main() {
+ for (final field in [NewHarnessField.agent, NewHarnessField.machine]) {
+ test(
+ 'changing ${field.name} clears the profile before the next launch',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['remote'] = MachineState(
+ const Machine(
+ machineId: 'remote',
+ name: 'Remote',
+ authMode: MachineAuthMode.remote,
+ ),
+ )..nodeOnline = true;
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ draft: const NewHarnessDraft(
+ machineId: 'm',
+ engine: 'codex',
+ project: NewHarnessProject.folder('/work/project'),
+ task: 'Check the project',
+ permissionMode: 'readOnly',
+ profile: LocalCodexProfile('/work/.codex-work', 'Work'),
+ profileChosen: true,
+ ),
+ );
+ addTearDown(box.dispose);
+ expect(box.profileLabel, 'Work');
+ box.focusField(field);
+ box.accept(
+ NewHarnessOption(
+ id: field == NewHarnessField.agent ? 'opencode' : 'remote',
+ title: 'Other',
+ ),
+ );
+ if (field == NewHarnessField.agent) {
+ box.focusField(field);
+ box.accept(const NewHarnessOption(id: 'codex', title: 'Codex'));
+ }
+ expect(box.profileLabel, isNull);
+ expect(box.draft.profile, isNull);
+ if (field == NewHarnessField.machine) {
+ expect(box.needsProject, isTrue);
+ box.setFolder('/work/remote-project');
+ }
+ await Future<void>.delayed(Duration.zero);
+ final result = box.create();
+ await Future<void>.delayed(Duration.zero);
+ expect(
+ connection.requests.single.payload.containsKey('codexHome'),
+ isFalse,
+ );
+ connection.created();
+ expect(await result, NewHarnessOutcome.created);
+ },
+ );
+ }
+
+ for (final (dismiss, profile) in [
+ ('escape', 'Work'),
+ ('outside', 'Default'),
+ ('footer', 'Work'),
+ ]) {
+ testWidgets(
+ 'advanced $dismiss returns the edited draft and $profile profile to the prompt',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection(
+ profiles: [
+ {'path': '/work/.codex-work', 'label': 'Work'},
+ ],
+ );
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('new-agent-task')),
+ ' Review before changing anything\nKeep the patch small ',
+ );
+ await tester.tap(find.byKey(const Key('new-agent-permission-mode')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Read only'));
+ await tester.pumpAndSettle();
+ if (profile == 'Default') {
+ await tester.tap(
+ find.byKey(const Key('new-agent-codex-profile-field')),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Default profile'));
+ await tester.pumpAndSettle();
+ }
+ final git = find.byKey(const Key('new-agent-project-git'));
+ await tester.ensureVisible(git);
+ await tester.tap(git);
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const Key('new-agent-git-url')),
+ 'acme/terminal-tools',
+ );
+ await chord(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ switch (dismiss) {
+ case 'escape':
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ case 'outside':
+ await tester.tapAt(const Offset(4, 650));
+ case 'footer':
+ await tester.tap(find.textContaining('esc back'));
+ }
+ await tester.pumpAndSettle();
+ expect(find.byType(AlertDialog), findsNothing);
+ var box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(
+ box.task,
+ ' Review before changing anything\nKeep the patch small ',
+ );
+ expect(
+ box.project.repository?.url,
+ 'https://github.com/acme/terminal-tools.git',
+ );
+ expect(box.mode, 'readOnly');
+ expect(box.profileLabel, profile);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('new-harness-field-agent')),
+ matching: find.textContaining('Read only · profile $profile'),
+ ),
+ findsOneWidget,
+ );
+ expect(box.field, NewHarnessField.launch);
+ expect(
+ FocusManager.instance.primaryFocus!.debugLabel,
+ 'New harness launch',
+ );
+ expect(connection.requests, isEmpty);
+ expect(app.swarms, [original]);
+
+ // Returning to advanced options preserves an explicit Default choice,
+ // even when discovery finds one profile and would normally select it.
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<CodexProfileField>(find.byType(CodexProfileField))
+ .value
+ ?.label,
+ profile == 'Default' ? null : 'Work',
+ );
+ expect(find.text('terminal-tools'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.profileLabel, profile);
+ // A second Escape leaves creation entirely. Reopening from the same
+ // source must retain the clone, permissions, task, and profile while
+ // honoring the newly requested destination.
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ final inPane = dismiss == 'outside';
+ await chord(
+ tester,
+ inPane ? LogicalKeyboardKey.keyP : LogicalKeyboardKey.keyT,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.profileLabel, profile);
+ expect(
+ box.placement,
+ inPane ? HarnessPlacement.currentTab : HarnessPlacement.newTab,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final request = connection.requests.single;
+ expect(request.payload['permissionMode'], 'readOnly');
+ expect(
+ request.payload['repositoryUrl'],
+ 'https://github.com/acme/terminal-tools.git',
+ );
+ expect(
+ request.payload['prompt'],
+ 'Review before changing anything\nKeep the patch small',
+ );
+ expect(
+ request.payload['codexHome'],
+ profile == 'Default' ? null : '/work/.codex-work',
+ );
+ connection.created();
+ await tester.pumpAndSettle();
+ if (inPane) {
+ expect(app.swarms, [original]);
+ expect(original.panes, hasLength(2));
+ } else {
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ }
+ app.selectSwarm(original.id);
+ app.focusPane(original.panes.first.id);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .task,
+ isEmpty,
+ reason:
+ 'Successful creation consumes the draft in its source context',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'back from an unresolved advanced creation retains its receipt and locks the task',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .focusField(NewHarnessField.task);
+ await tester.pump();
+ await tester.enterText(input, 'Keep this first task');
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ await chord(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ final request = connection.requests.single;
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.tapAt(const Offset(4, 650));
+ await tester.pump();
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ request.reply.completeError(const WsRequestTimeout('agent_create'));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.checking, isTrue);
+ expect(box.field, NewHarnessField.launch);
+ expect(input, findsNothing);
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyW);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyU);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pump();
+ expect(box.task, 'Keep this first task');
+ expect(app.swarms, [original]);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(connection.requests, hasLength(2));
+ expect(connection.requests.last.type, 'agent_create_status');
+ expect(
+ connection.requests.last.payload['creationId'],
+ request.payload['creationId'],
+ );
+ connection.created();
+ await tester.pumpAndSettle();
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final (projectQuery, detail, preparation) in [
+ (
+ 'Keyboard tools',
+ 'Keyboard-tools',
+ {'projectSource': 'new', 'projectName': 'Keyboard-tools'},
+ ),
+ (
+ 'acme/super-terminal',
+ 'super-terminal',
+ {
+ 'projectSource': 'remote',
+ 'repositoryUrl': 'https://github.com/acme/super-terminal.git',
+ },
+ ),
+ ('/work/space project', 'space project', {'cwd': '/work/space project'}),
+ ]) {
+ testWidgets(
+ 'advanced options retain the task, read-only mode, and $projectQuery',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .focusField(NewHarnessField.task);
+ await tester.pump();
+ await tester.enterText(
+ input,
+ 'Review the project before changing anything',
+ );
+ await tester.tap(
+ find.byKey(const ValueKey('new-harness-field-project')),
+ );
+ await tester.pump();
+ await tester.tap(
+ find.byKey(
+ ValueKey(
+ projectQuery.startsWith('/')
+ ? NewHarnessController.existingProjectId
+ : projectQuery.contains('/')
+ ? NewHarnessController.repositoryId
+ : NewHarnessController.newProjectId,
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.enterText(input, projectQuery);
+ await tester.pump(const Duration(milliseconds: 250));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('new-agent-permission-mode')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Read only'));
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.mode, 'readOnly');
+ await chord(tester, LogicalKeyboardKey.period);
+ await tester.pumpAndSettle();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.text(detail), findsOneWidget);
+ final mode = find.byKey(const Key('new-agent-permission-mode'));
+ expect(
+ find.descendant(of: mode, matching: find.text('Read only')),
+ findsOneWidget,
+ );
+ expect(app.swarms, [original]);
+ final create = find.byKey(const ValueKey('create-agent-submit'));
+ await tester.ensureVisible(create);
+ await tester.tap(create);
+ await tester.pump();
+ final request = connection.requests.single;
+ for (final field in preparation.entries) {
+ expect(request.payload[field.key], field.value);
+ }
+ expect(request.payload['permissionMode'], 'readOnly');
+ expect(request.payload['bypassPermission'], false);
+ expect(
+ request.payload['prompt'],
+ 'Review the project before changing anything',
+ );
+ connection.created();
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump();
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ await chord(tester, LogicalKeyboardKey.keyN);
+ expect(
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .task,
+ isEmpty,
+ reason: 'A task created through advanced options must not reappear as a draft',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ test('placement picker pins creation, searches only harnesses and focuses matches', () {
+ final app = createApp();
+ final search = picker(app, HarnessPlacement.currentTab);
+ addTearDown(search.dispose);
+ addTearDown(app.dispose);
+ expect(search.selected!.isCreate, isTrue);
+ expect(
+ search.rows.every((row) => row.isCreate || row.agentId != null),
+ isTrue,
+ );
+ search.setQuery('Agent 12');
+ expect(search.rows.first.isCreate, isTrue);
+ expect(search.selected!.agentId, 'a12');
+ for (final query in ['> commands', '# projects', '@ machines']) {
+ search.setQuery(query);
+ expect(search.isCommandMode, query.startsWith('>'));
+ expect(search.isHelpMode, isFalse);
+ expect(search.createTask, isNull);
+ expect(search.rows.any((row) => row.isCreate), isFalse);
+ }
+ search.setQuery('');
+ expect(search.selected!.isCreate, isTrue);
+ });
+
+ test('new tab can open from a full tab; current tab can still focus an existing pane', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ for (var i = 0; i < AppNotifier.maxPanes; i++) {
+ await app.addAgentToSwarm('m', 'a$i');
+ }
+ final pane = picker(app, HarnessPlacement.currentTab);
+ final tab = picker(app, HarnessPlacement.newTab);
+ addTearDown(pane.dispose);
+ addTearDown(tab.dispose);
+ expect(pane.canCreate, isFalse);
+ pane.setQuery('Agent 0');
+ expect(pane.canAccept, isTrue);
+ expect(pane.actionLabel(pane.selected), 'Focus pane');
+ expect(tab.canCreate, isTrue);
+ expect(tab.selected!.isCreate, isTrue);
+ expect(tab.capacity, AppNotifier.maxPanes);
+ tab.setQuery('Agent 0');
+ final selected = tab.selected!.id;
+ expect(tab.changePlacement(HarnessPlacement.currentTab), isTrue);
+ expect(tab.query, 'Agent 0');
+ expect(tab.selected!.id, selected);
+ expect(tab.capacity, 0);
+ expect(tab.canCreate, isFalse);
+ expect(tab.canAccept, isTrue);
+ expect(tab.actionLabel(tab.selected), 'Focus pane');
+ expect(tab.changePlacement(HarnessPlacement.newTab), isTrue);
+ expect(tab.selected!.id, selected);
+ expect(tab.capacity, AppNotifier.maxPanes);
+ expect(tab.canCreate, isTrue);
+ expect(tab.actionLabel(tab.selected), 'Open in new tab');
+ });
+
+ test(
+ 'new tab shares the running view; new pane focuses it without a duplicate',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final original = app.activeSwarm;
+ await app.addAgentToSwarm('m', 'a0');
+ final firstPane = original.panes.single;
+ final search = picker(app, HarnessPlacement.newTab)..setQuery('Agent 0');
+ final choice = search.submit()!;
+ search.dispose();
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ choice,
+ destinationSwarmId: original.id,
+ placement: HarnessPlacement.newTab,
+ ),
+ isTrue,
+ );
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Agent 0');
+ expect(app.activeSwarm.toJson()['name'], 'Agent 0');
+ expect(original.panes.single, same(firstPane));
+ expect(app.panes.single, same(firstPane));
+ final target = app.activeSwarmId;
+ app.renameSwarm(target, 'Feature work');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ choice,
+ destinationSwarmId: target,
+ placement: HarnessPlacement.currentTab,
+ ),
+ isTrue,
+ );
+ expect(app.panes, hasLength(1));
+ expect(app.activeSwarm.name, 'Feature work');
+ await app.closePane(firstPane.id);
+ expect(original.panes.single, same(firstPane));
+ },
+ );
+
+ test('a stale new-tab selection does not allocate a tab', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.activeSwarm;
+ final search = picker(app, HarnessPlacement.newTab)..setQuery('Agent 12');
+ final choice = search.submit()!;
+ search.dispose();
+ app.machineStates['m']!.agents.removeWhere((agent) => agent.id == 'a12');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ choice,
+ destinationSwarmId: original.id,
+ placement: HarnessPlacement.newTab,
+ ),
+ isFalse,
+ );
+ expect(app.swarms, [original]);
+ });
+
+ test('harnesses on different machines auto tile in one tab', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ const remote = Machine(
+ machineId: 'remote',
+ name: 'Build host',
+ authMode: MachineAuthMode.remote,
+ );
+ app.machineStates['remote'] = MachineState(remote)
+ ..nodeOnline = false
+ ..agents = [
+ Agent(
+ id: 'a0',
+ name: 'Remote feature',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ app.activeSwarm.presets[2] = PanePreset.rows;
+ final search = picker(app, HarnessPlacement.currentTab)
+ ..setQuery('Build host');
+ final choice = search.submit()!;
+ search.dispose();
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ choice,
+ destinationSwarmId: app.activeSwarmId,
+ placement: HarnessPlacement.currentTab,
+ ),
+ isTrue,
+ );
+ expect(app.panes.map((pane) => pane.machineId), ['m', 'remote']);
+ expect(app.presetFor(2), PanePreset.defaultFor(2));
+ });
+
+ test(
+ 'new tab waits for a confirmed creation and recovery allocates once',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.activeSwarm;
+ final attempt = AgentCreationAttempt();
+ Future<String?> create() => app.createAgent(
+ 'm',
+ engine: 'codex',
+ folder: '/work',
+ swarmId: original.id,
+ placement: HarnessPlacement.newTab,
+ attempt: attempt,
+ );
+ final first = create();
+ expect(app.swarms, [original]);
+ connection.requests.single.reply.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ expect(await first, contains('Check status'));
+ expect(app.swarms, [original]);
+ final recovery = create();
+ expect(connection.requests.last.type, 'agent_create_status');
+ connection.created();
+ expect(await recovery, isNull);
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ expect(app.panes.single.agentId, 'made');
+ expect(await create(), isNull);
+ expect(app.swarms, hasLength(2));
+ expect(connection.requests, hasLength(2));
+ },
+ );
+
+ test(
+ 'explicit pane placement also keeps domain harnesses in this tab',
+ () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.activeSwarm;
+ final creating = app.createAgent(
+ 'm',
+ engine: 'codex',
+ folder: '/work',
+ dsh: 'blender',
+ swarmId: original.id,
+ placement: HarnessPlacement.currentTab,
+ );
+ connection.created();
+ expect(await creating, isNull);
+ expect(app.swarms, [original]);
+ expect(app.panes.map((pane) => pane.agentId), ['a0', 'made']);
+ },
+ );
+
+ test('a failed new-tab creation leaves the original layout intact', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.activeSwarm;
+ final creating = app.createAgent(
+ 'm',
+ engine: 'codex',
+ folder: '/missing',
+ placement: HarnessPlacement.newTab,
+ );
+ final request = connection.requests.single;
+ request.reply.complete({
+ 'creationId': request.payload['creationId'],
+ 'state': 'failed',
+ 'failure': {'code': 'CWD_NOT_FOUND'},
+ });
+ expect(await creating, contains('folder is unavailable'));
+ expect(app.swarms, [original]);
+ expect(original.panes.single.agentId, 'a0');
+ });
+
+ testWidgets(
+ 'new-tab creation keeps the task and pending receipt through picker shortcuts',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, 'fix the login regression');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.task, 'fix the login regression');
+ expect(box.placement, HarnessPlacement.newTab);
+ box.setFolder('/work/project');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.busy, isTrue);
+ expect(
+ connection.requests.single.payload['prompt'],
+ 'fix the login regression',
+ );
+
+ Future<void> keepsPendingBox() async {
+ expect(box.field, NewHarnessField.launch);
+ expect(box.locked, isTrue);
+ final task = box.task;
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyW);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyU);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pump();
+ expect(box.task, task);
+ for (final key in [
+ LogicalKeyboardKey.keyP,
+ LogicalKeyboardKey.keyT,
+ LogicalKeyboardKey.period,
+ ]) {
+ await chord(tester, key);
+ await tester.pump();
+ expect(search, findsNothing);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller,
+ same(box),
+ );
+ expect(app.swarms, [original]);
+ }
+ await tester.tapAt(const Offset(12, 650));
+ await tester.pump();
+ expect(
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller,
+ same(box),
+ reason:
+ 'Clicking outside must preserve an active or unresolved creation',
+ );
+ }
+
+ await keepsPendingBox();
+ connection.requests.single.reply.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ await tester.pump();
+ expect(box.busy, isFalse);
+ expect(box.checking, isTrue);
+ await keepsPendingBox();
+ expect(connection.requests, hasLength(1));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(connection.requests.last.type, 'agent_create_status');
+ connection.created();
+ await tester.pump();
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ expect(app.panes.single.agentId, 'made');
+ expect(original.panes.single.agentId, 'a0');
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 100));
+ },
+ );
+
+ testWidgets(
+ 'a dismissed pending creation resumes its receipt even without a task',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyT);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .setFolder('/work/project');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final request = connection.requests.single;
+ expect(request.payload.containsKey('prompt'), isFalse);
+ request.reply.completeError(const WsRequestTimeout('agent_create'));
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.task, isEmpty);
+ expect(box.checking, isTrue);
+ expect(find.text('pending harness'), findsOneWidget);
+ expect(
+ find.textContaining('check status', findRichText: true),
+ findsOneWidget,
+ );
+ // The restored "Escape again" warning keeps its meaning; it must not
+ // require another invisible acknowledgement before closing.
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(connection.requests, hasLength(2));
+ expect(connection.requests.last.type, 'agent_create_status');
+ expect(
+ connection.requests.last.payload['creationId'],
+ request.payload['creationId'],
+ );
+ connection.created();
+ await tester.pumpAndSettle();
+ // A submitted request keeps its original destination; this was a status
+ // check, not another launch with the new chooser's placement.
+ expect(app.swarms, hasLength(2));
+ expect(app.activeSwarm.name, 'Made');
+ expect(original.panes.single.agentId, 'a0');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final placement in HarnessPlacement.values) {
+ testWidgets(
+ '${placement.title} cancels without altering layout and carries inherited creation context',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents[0] = Agent(
+ id: 'a0',
+ name: 'Feature',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: const AgentProject(name: 'Project', cwd: '/work/project'),
+ );
+ app.adoptSessionForTest(terminal('a0', []));
+ await app.addAgentToSwarm('m', 'a0');
+ final original = app.activeSwarm;
+ await mount(tester, app);
+ final key = placement == HarnessPlacement.newTab
+ ? LogicalKeyboardKey.keyT
+ : LogicalKeyboardKey.keyP;
+ await chord(tester, key);
+ await tester.pump();
+ expect(app.swarms, [original]);
+ expect(find.text(placement.title), findsWidgets);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(app.swarms, [original]);
+ await chord(tester, key);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.placement, placement);
+ expect(box.engine, 'codex');
+ expect(box.machineId, 'm');
+ expect(box.project.folder, '/work/project');
+ expect(app.swarms, [original]);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(app.activeSwarm, same(original));
+ expect(app.closedHistory, isEmpty);
+ // The creation box was opened from a search editor that is now gone.
+ // Returning focus to that detached editor would disable shortcuts.
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ expect(
+ find.byKey(const ValueKey('swarm-search-input')),
+ findsOneWidget,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/harness_store_entry_test.dart b/desktop/test/harness_store_entry_test.dart
new file mode 100644
index 000000000..d9bce598b
--- /dev/null
+++ b/desktop/test/harness_store_entry_test.dart
@@ -0,0 +1,202 @@
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
+
+import 'package:harness/store/store_screen.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ for (final native in [false, true]) {
+ testWidgets(
+ 'Store entry reuses its tab and preserves work (native=$native)',
+ (tester) async {
+ final app = createApp();
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', frames));
+ final work = app.activeSwarm;
+ await configured.mount(tester, app, map, native: native);
+ final view = find.byWidgetPredicate(
+ (widget) =>
+ widget is TerminalView &&
+ widget.terminal == pane.session!.terminal,
+ );
+ final terminalState = tester.state(view);
+ Future<void> openStore() async {
+ if (native) {
+ await configured.native(tester, 'store');
+ } else {
+ final button = find.byKey(const ValueKey('swarm-store-button'));
+ expect(tester.getRect(button).bottom, lessThanOrEqualTo(40));
+ await tester.tap(button);
+ }
+ await tester.pump();
+ }
+
+ await openStore();
+ final store = app.activeSwarm;
+ expect(store.isStore, isTrue);
+ expect(work.panes.single, same(pane));
+ expect(app.swarms, hasLength(2));
+ app.selectSwarm(work.id);
+ await tester.pump();
+ await openStore();
+ expect(app.activeSwarm, same(store));
+ expect(app.swarms, hasLength(2));
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ expect(app.activeSwarm, same(work));
+ expect(tester.state(view), same(terminalState));
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(frames.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('Store is searchable by install and browse and can be remapped', (
+ tester,
+ ) async {
+ final app = createApp();
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ final work = app.activeSwarm;
+ await configured.mount(tester, app, map);
+ for (final query in [
+ 'store',
+ 'install',
+ 'browse harnesses',
+ 'extensions',
+ ]) {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $query',
+ );
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(search.selected?.commandId, 'app.store', reason: query);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(app.swarms, hasLength(2));
+ expect(find.byType(SwarmSearchResults), findsNothing);
+ }
+ app.selectSwarm(work.id);
+ map.apply('{"bindings":[{"keys":"cmd+shift+m","command":"app.store"}]}');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyM, cmd: true, shift: true);
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final prompt in [null, 'Model a reading nook']) {
+ testWidgets(
+ 'Store ${prompt == null ? 'Open' : 'Try'} uses the dock with its harness and task',
+ (tester) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ seedMixedAgents(app);
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ app.openStore();
+ final store = app.activeSwarm;
+ final count = app.swarms.length;
+ await configured.mount(tester, app, map);
+ await openStoreAgent(
+ tester.element(find.byType(StoreTab)),
+ app,
+ 'studio/arm',
+ 'm',
+ prompt: prompt,
+ );
+ await tester.pump();
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.engine, 'studio/arm');
+ expect(box.task, prompt ?? '');
+ expect(box.projectLabel, startsWith('~/harnesses/robot-studio-'));
+ expect(box.projectFolderRequest!.isGenerated, isTrue);
+ expect(box.placement, HarnessPlacement.newTab);
+ expect(box.field, NewHarnessField.launch);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(app.activeSwarm, same(store));
+ expect(app.swarms, hasLength(count));
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(app.activeSwarm, same(store));
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('browsing from agent choices retains the task and defaults', (
+ tester,
+ ) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final work = app.activeSwarm;
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ box.setFolder('/work/project');
+ await tester.pump();
+ await openLaunchRow(tester, 'task');
+ await tester.enterText(input, 'Finish the login feature');
+ await tester.pump();
+ final draft = box.draft;
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'a harness not in this catalog');
+ await tester.pump();
+ expect(box.selected?.id, NewHarnessController.storeId);
+ expect(find.text('Browse more harnesses…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.activeSwarm.isStore, isTrue);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(work.panes.single, same(pane));
+ app.selectSwarm(work.id);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final resumed = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(resumed.task, draft.task);
+ expect(resumed.engine, draft.engine);
+ expect(resumed.machineId, draft.machineId);
+ expect(resumed.project, draft.project);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/harness_titles_test.dart b/desktop/test/harness_titles_test.dart
new file mode 100644
index 000000000..0559fef43
--- /dev/null
+++ b/desktop/test/harness_titles_test.dart
@@ -0,0 +1,98 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'swarm_state_test.dart' show createApp, MemoryStore;
+
+const automaticName = 'Codex harness 9-20 9:15';
+
+Future<void> sessionTitle(
+ AppNotifier app,
+ String title, {
+ String name = automaticName,
+}) => app.handleEventForTest('m', {
+ 'type': 'agent_synced',
+ 'payload': {
+ 'agent': {
+ 'id': 'a0',
+ 'name': name,
+ 'title': title,
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ },
+ },
+});
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ test(
+ 'pane placeholders are display-only and explicit names beat session titles',
+ () {
+ const agent = Agent(id: 'a0', name: automaticName, engine: 'codex');
+ expect(agent.name, automaticName);
+ expect(agent.displayName, 'Untitled Pane');
+ expect(
+ const Agent(
+ id: 'a0',
+ name: automaticName,
+ title: 'Review API changes',
+ ).displayName,
+ 'Review API changes',
+ );
+ expect(
+ const Agent(
+ id: 'a0',
+ name: 'My release',
+ title: 'Review API changes',
+ ).displayName,
+ 'My release',
+ );
+ },
+ );
+
+ test('tab follows its first harness until an explicit rename, including after restore', () async {
+ final store = MemoryStore();
+ final app = createApp(store: store);
+ app.machineStates['m']!.agents = const [
+ Agent(
+ id: 'a0',
+ name: automaticName,
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ await app.addAgentToSwarm('m', 'a0');
+ expect(app.activeSwarm.name, 'Untitled Tab');
+ expect(app.activeSwarm.nameIsCustom, isFalse);
+ await sessionTitle(app, 'Review API changes');
+ expect(app.activeSwarm.name, 'Review API changes');
+ await app.flushPaneLayout();
+ app.dispose();
+
+ final restored = createApp(store: store);
+ await restored.restorePaneLayoutForTest();
+ expect(restored.activeSwarm.nameIsCustom, isFalse);
+ await sessionTitle(restored, 'Fix API retries');
+ expect(restored.activeSwarm.name, 'Fix API retries');
+ restored.renameSwarm(restored.activeSwarmId, 'Release workspace');
+ await sessionTitle(restored, 'Add regression tests');
+ expect(restored.activeSwarm.name, 'Release workspace');
+ expect(
+ restored.stateOf('m')!.agents.first.displayName,
+ 'Add regression tests',
+ );
+ await restored.closeSwarm(restored.activeSwarmId);
+ restored.reopenClosedSwarm();
+ expect(restored.activeSwarm.nameIsCustom, isTrue);
+ await restored.flushPaneLayout();
+ restored.dispose();
+
+ final reopened = createApp(store: store);
+ addTearDown(reopened.dispose);
+ await reopened.restorePaneLayoutForTest();
+ await sessionTitle(reopened, 'An engine title', name: 'My custom pane');
+ expect(reopened.activeSwarm.name, 'Release workspace');
+ expect(reopened.stateOf('m')!.agents.first.displayName, 'My custom pane');
+ });
+}
diff --git a/desktop/test/keyboard_practice_test.dart b/desktop/test/keyboard_practice_test.dart
new file mode 100644
index 000000000..3cecb6042
--- /dev/null
+++ b/desktop/test/keyboard_practice_test.dart
@@ -0,0 +1,408 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keyboard_practice.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
+import 'package:harness/state/workspace_learning.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/workspace_quick_start.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'workspace_learning_test.dart' show LearningMemoryStore;
+import 'support/real_fonts.dart';
+
+void main() {
+ final filter = find.byKey(const ValueKey('practice-filter'));
+
+ Future<void> openLesson(WidgetTester tester, String query) async {
+ await tester.enterText(filter, query);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+
+ Future<void> command(WidgetTester tester, String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $query',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> capture(
+ WidgetTester tester,
+ GlobalKey boundary,
+ String name,
+ ) async {
+ final path = Platform.environment['HARNESS_LEARNING_CAPTURE_DIR'];
+ if (path == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()
+ as RenderRepaintBoundary)
+ .toImage();
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ Directory(path).createSync(recursive: true);
+ File('$path/$name.png').writeAsBytesSync(data!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ test(
+ 'the practice catalog covers all stable app bindings and local overrides',
+ () {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply(
+ '''{"bindings":[{"keys":"ctrl+x ctrl+t","command":"swarm.new","when":"terminal"}]}''',
+ );
+ final lessons = keyboardLessons(map);
+ for (final context in KeymapContext.values) {
+ for (final binding in map.current.bindingsFor(context)) {
+ if (binding.command == 'navigation.command_bar' ||
+ binding.command == 'app.debug' ||
+ harnessCommandById[binding.command]?.hidden == true) {
+ continue;
+ }
+ expect(
+ lessons.any(
+ (l) =>
+ l.command == binding.command &&
+ l.bindings.any((b) => b.sequence == binding.sequence),
+ ),
+ isTrue,
+ reason: '${context.name}: ${binding.command} ${binding.sequence}',
+ );
+ }
+ }
+ expect(
+ lessons.any((l) => l.command == 'agent.stop' && l.bindings.isEmpty),
+ isTrue,
+ );
+ expect(
+ lessons.any((l) => l.command == 'navigation.command_bar'),
+ isFalse,
+ );
+ },
+ );
+
+ testWidgets(
+ 'practice captures workspace and destructive actions, then restores terminal input',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ final original = app.activeSwarm;
+ final panes = original.panes.toList();
+ await configured.mount(tester, app, map);
+ await command(tester, 'Keyboard practice');
+ expect(filter, findsOneWidget);
+ await openLesson(tester, 'New Tab');
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ expect(find.textContaining('That is Close Tab'), findsOneWidget);
+ expect(app.swarms, [original]);
+ expect(original.panes, panes);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(find.text('[x] New Tab'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLesson(tester, 'Stop Agent');
+ await tester.enterText(
+ find.byKey(const ValueKey('practice-command')),
+ 'Stop Agent',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('[x] Stop Agent'), findsOneWidget);
+ expect(app.swarms, [original]);
+ expect(original.panes, panes);
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(KeyboardPractice), findsNothing);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 200));
+ },
+ );
+
+ testWidgets('practice follows remaps, sequences and live unbindings', (
+ tester,
+ ) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply(
+ '''{"bindings":[{"keys":"cmd+t","command":null},{"keys":"ctrl+x ctrl+t","command":"swarm.new"}]}''',
+ );
+ await tester.pumpWidget(MaterialApp(home: KeyboardPractice(keymap: map)));
+ await openLesson(tester, 'New Tab');
+ expect(find.text('Press ctrl-X ctrl-T'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ expect(find.text('[x] New Tab'), findsNothing);
+ await key(tester, LogicalKeyboardKey.keyX, ctrl: true);
+ await key(tester, LogicalKeyboardKey.keyT, ctrl: true);
+ expect(find.text('[x] New Tab'), findsOneWidget);
+ map.apply('''{"bindings":[{"keys":"cmd+t","command":null}]}''');
+ await tester.pump();
+ expect(find.byKey(const ValueKey('practice-command')), findsOneWidget);
+ await tester.enterText(
+ find.byKey(const ValueKey('practice-command')),
+ 'New Tab',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('[x] New Tab'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('Escape can be practiced before it returns to the lesson list', (
+ tester,
+ ) async {
+ await tester.pumpWidget(const MaterialApp(home: KeyboardPractice()));
+ await openLesson(tester, 'Close search');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('[x] Close search'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(filter, findsOneWidget);
+ await openLesson(tester, 'Erase the previous word');
+ await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
+ expect(find.text('[x] Erase the previous word'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'practice retains progress completed during a slow preference read',
+ (tester) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final earlier = keyboardLessons(map)
+ .firstWhere((l) => l.command == 'pane.zoom');
+ final storage = LearningMemoryStore()..pending = Completer<String?>();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeyboardPractice(keymap: map, storage: storage),
+ ),
+ );
+ await openLesson(tester, 'New Tab');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ storage.pending!.complete(jsonEncode([earlier.id]));
+ await tester.pumpAndSettle();
+ final saved = jsonDecode(storage.values.values.single) as List;
+ expect(saved, contains(earlier.id));
+ expect(
+ saved.whereType<String>().any((id) => id.contains('swarm.new')),
+ isTrue,
+ );
+ expect(
+ find.text('2/${keyboardLessons(map).length} practiced'),
+ findsOneWidget,
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'practice buttons activate from the keyboard in both lesson contexts',
+ (tester) async {
+ await tester.pumpWidget(const MaterialApp(home: KeyboardPractice()));
+ for (final query in ['New Tab', 'Next result']) {
+ await openLesson(tester, query);
+ final buttonText = find.descendant(
+ of: find.byKey(const ValueKey('practice-back')),
+ matching: find.byType(Text),
+ );
+ Focus.of(tester.element(buttonText)).requestFocus();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(filter, findsOneWidget);
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'quick start advances on real pane changes without capturing typing',
+ (tester) async {
+ final app = createApp();
+ final learning = WorkspaceLearning();
+ final map = MemoryKeymap();
+ addTearDown(app.dispose);
+ addTearDown(learning.dispose);
+ addTearDown(map.dispose);
+ tester.view.physicalSize = const Size(1280, 800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ nativeTabs: false,
+ learning: learning,
+ ),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(
+ find.byKey(const ValueKey('harness-start-quick-start')),
+ findsOneWidget,
+ );
+ await command(tester, 'Quick start');
+ expect(find.byType(WorkspaceQuickStart), findsOneWidget);
+ expect(learning.next, WorkspaceLesson.agent);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(
+ learning.next,
+ WorkspaceLesson.agent,
+ reason: 'Cancelling an empty chooser is not opening an agent',
+ );
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', []));
+ app.renameSwarm(app.activeSwarmId, 'First agent');
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(learning.next, WorkspaceLesson.pane);
+ app.adoptSessionForTest(terminal('a1', input));
+ app.renameSwarm(app.activeSwarmId, 'Two agents');
+ await tester.pump(const Duration(milliseconds: 120));
+ expect(learning.next, WorkspaceLesson.zoom);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(learning.next, WorkspaceLesson.commands);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ expect(learning.finished, isTrue);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('swarm-search-input')))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await command(tester, 'Pause quick start');
+ expect(find.byType(WorkspaceQuickStart), findsNothing);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ expect(input.last.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 200));
+ },
+ );
+
+ for (final (size, scale) in [
+ (const Size(1000, 800), 1.0),
+ (const Size(480, 420), 1.7),
+ ]) {
+ testWidgets('practice stays readable at $size and $scale text', (
+ tester,
+ ) async {
+ await tester.runAsync(loadRealFonts);
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final boundary = GlobalKey();
+ final storage = LearningMemoryStore();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: boundary,
+ child: KeyboardPractice(storage: storage),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ Future<void> snap(String name) =>
+ capture(tester, boundary, '$name-${size.width.toInt()}');
+
+ await snap('practice-list');
+ await openLesson(tester, 'New Tab');
+ await snap('practice-key');
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await snap('practice-result');
+ if (size.width < 500) {
+ final details = tester.widget<SingleChildScrollView>(
+ find.byType(SingleChildScrollView),
+ );
+ final scrolling = details.controller!;
+ expect(scrolling.position.maxScrollExtent, greaterThan(0));
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(scrolling.offset, greaterThan(0));
+ await snap('practice-read');
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(scrolling.offset, 0);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ await key(tester, LogicalKeyboardKey.escape);
+ await openLesson(tester, 'New Pane');
+ expect(scrolling.offset, 0);
+ }
+ expect(storage.values.values.any((v) => v.contains('swarm.new')), isTrue);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+
+ testWidgets(
+ 'quick start wraps beside a narrow workspace with enlarged text',
+ (tester) async {
+ await tester.runAsync(loadRealFonts);
+ final app = createApp();
+ final learning = WorkspaceLearning()..start();
+ final boundary = GlobalKey();
+ addTearDown(app.dispose);
+ addTearDown(learning.dispose);
+ tester.view.physicalSize = const Size(480, 600);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(1.7)),
+ child: child!,
+ ),
+ home: RepaintBoundary(
+ key: boundary,
+ child: SwarmScreen(
+ notifier: app,
+ nativeTabs: false,
+ learning: learning,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(tester, boundary, 'quick-start-480');
+ expect(find.byKey(const ValueKey('quick-start-action')), findsOneWidget);
+ expect(find.byKey(const ValueKey('quick-start-pause')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/keymap_dispatch_test.dart b/desktop/test/keymap_dispatch_test.dart
index 7ec0d9ff0..e42e10831 100644
--- a/desktop/test/keymap_dispatch_test.dart
+++ b/desktop/test/keymap_dispatch_test.dart
@@ -43,6 +43,31 @@ void main() {
modifier: modifier,
);
+ test('a picker key nothing can run is left to the text field', () {
+ final picker = KeymapDispatch(
+ ResolvedKeymap([
+ binding('alt+1', 'picker.pick_1'),
+ ], const KeymapConfig.empty()),
+ );
+ KeymapDispatchResult press(KeymapContext context, {required bool can}) =>
+ picker.dispatch(
+ stroke: KeyStroke.parse('alt+1'),
+ physicalKey: 'Digit1',
+ phase: KeymapKeyPhase.down,
+ context: context,
+ owner: owner,
+ canExecute: (_) => can,
+ );
+ // In a list it picks a row. On the task field there are no rows, and
+ // swallowing it took ¡ ™ £ out of a message somebody was writing.
+ for (final context in [KeymapContext.picker, KeymapContext.project]) {
+ expect(press(context, can: true).command, 'picker.pick_1');
+ final unavailable = press(context, can: false);
+ expect(unavailable.handled, isFalse);
+ expect(unavailable.command, isNull);
+ }
+ });
+
test('ordinary terminal and native editing keys are untouched', () {
for (final key in [
'h',
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index f0fa91428..f3f69568e 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -59,7 +59,7 @@ void main() {
('cmd+9', 'swarm.select_9'),
('cmd+t', 'swarm.new'),
('cmd+n', 'agent.new'),
- ('cmd+o', 'agent.add'),
+ ('cmd+p', 'agent.add'),
('cmd+h', 'pane.focus_left'),
('cmd+j', 'pane.focus_below'),
('cmd+k', 'pane.focus_above'),
@@ -71,10 +71,9 @@ void main() {
('cmd+enter', 'pane.zoom'),
('cmd+shift+p', 'navigation.commands'),
('cmd+shift+j', 'navigation.command_bar'),
- ('cmd+s', 'pane.layout'),
+ ('cmd+s', 'app.store'),
+ ('cmd+shift+l', 'pane.layout'),
('cmd+b', 'task.route'),
- ('cmd+r', 'pane.split_right'),
- ('cmd+d', 'pane.split_down'),
('cmd+shift+w', 'pane.close'),
('cmd+w', 'swarm.close'),
('ctrl+tab', 'swarm.next'),
@@ -94,12 +93,7 @@ void main() {
final id = command(stroke.toString());
expect(harnessCommandById[id]?.action, shortcut.action);
}
- for (final retired in [
- 'cmd+shift+n',
- 'cmd+shift+h',
- 'cmd+shift+k',
- 'cmd+shift+l',
- ]) {
+ for (final retired in ['cmd+shift+n', 'cmd+shift+h', 'cmd+shift+k']) {
expect(command(retired), isNull, reason: retired);
}
expect(command('cmd+alt+left'), isNull);
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
index 8e2e5f04a..e48a18efa 100644
--- a/desktop/test/keymap_runtime_test.dart
+++ b/desktop/test/keymap_runtime_test.dart
@@ -80,7 +80,7 @@ void main() {
final map = MemoryKeymap();
if (remapped) {
map.apply('''{"bindings":[
- {"keys":"cmd+s","command":null},
+ {"keys":"cmd+shift+l","command":null},
{"keys":"cmd+y","command":"pane.layout"}
]}''');
}
@@ -111,15 +111,20 @@ void main() {
final before = app.presetFor(2);
final shortcut = remapped
? LogicalKeyboardKey.keyY
- : LogicalKeyboardKey.keyS;
- await key(tester, shortcut, cmd: true);
+ : LogicalKeyboardKey.keyL;
+ await key(tester, shortcut, cmd: true, shift: !remapped);
await tester.pumpAndSettle();
- if (remapped) await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ if (remapped)
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true, shift: true);
// Fast repeated chords can arrive before the next rendered frame.
await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ if (!remapped)
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyEvent(shortcut);
await tester.sendKeyEvent(shortcut);
await tester.sendKeyEvent(shortcut);
+ if (!remapped)
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
await tester.pump();
expect(find.byType(Dialog), findsOneWidget);
@@ -157,7 +162,7 @@ void main() {
app.adoptSessionForTest(terminal('a1', []));
await mount(tester, app, map);
final before = app.presetFor(2);
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true, shift: true);
await tester.pumpAndSettle();
for (final modifier in ['cmd', 'ctrl', 'alt', 'shift']) {
await key(
@@ -178,7 +183,7 @@ void main() {
map.dispose();
});
- testWidgets('Command-T opens New Tab and Command-S opens Layout', (
+ testWidgets('Command-T opens New Tab and Command-Shift-L opens Layout', (
tester,
) async {
final app = createApp();
@@ -188,24 +193,23 @@ void main() {
final focused = app.adoptSessionForTest(terminal('a1', input));
final original = app.activeSwarm;
await mount(tester, app, map);
- await key(tester, LogicalKeyboardKey.keyS, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true, shift: true);
await tester.pumpAndSettle();
expect(find.text('Layout · 2 panes'), findsOneWidget);
expect(app.focusedPane, same(focused));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- expect(app.swarms, hasLength(2));
- expect(app.activeSwarm, isNot(same(original)));
- expect(app.activeSwarm.panes, isEmpty);
+ expect(app.swarms, hasLength(1));
+ expect(app.activeSwarm, same(original));
expect(
tester
- .widget<TextField>(find.byKey(const ValueKey('harness-start-search')))
+ .widget<TextField>(find.byKey(const ValueKey('swarm-search-input')))
.focusNode!
.hasPrimaryFocus,
isTrue,
);
- expect(find.byType(SwarmSearchResults), findsNothing);
+ expect(find.byType(SwarmSearchResults), findsOneWidget);
expect(original.panes.last, same(focused));
expect(input, isEmpty);
await tester.pumpWidget(const SizedBox());
@@ -381,7 +385,7 @@ void main() {
if (inline) {
await tester.tap(input);
} else {
- await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
}
await tester.enterText(input, 'Agent');
await tester.pump();
@@ -392,7 +396,10 @@ void main() {
await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.cursor, initial);
await key(tester, LogicalKeyboardKey.keyJ, ctrl: true);
- expect(search.cursor, (initial - 1) % search.rows.length);
+ expect(
+ search.cursor,
+ inline ? (initial - 1) % search.rows.length : initial + 1,
+ );
await tester.enterText(input, 'Agent 0');
await tester.pump();
expect(
@@ -450,14 +457,22 @@ void main() {
await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
expect(search.cursor, (cursor + 1) % search.rows.length);
await key(tester, LogicalKeyboardKey.keyD, cmd: true);
- expect(search.isCommandMode, isTrue);
- expect(tester.widget<TextField>(field).controller!.text, '> ');
+ final commands = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(commands.isCommandMode, isTrue);
+ expect(
+ tester
+ .widget<TextField>(find.byKey(const ValueKey('swarm-search-input')))
+ .controller!
+ .text,
+ '> ',
+ );
await key(tester, LogicalKeyboardKey.escape);
expect(field, findsOneWidget);
expect(find.byType(SwarmSearchResults), findsNothing);
- expect(tester.widget<TextField>(field).controller!.text, '> ');
- expect(tester.widget<TextField>(field).focusNode!.hasFocus, isFalse);
- await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ expect(tester.widget<TextField>(field).controller!.text, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
final modal = find.byKey(const ValueKey('swarm-search-input'));
expect(tester.widget<TextField>(modal).focusNode!.hasFocus, isTrue);
expect(tester.widget<TextField>(modal).controller!.text, isEmpty);
@@ -487,9 +502,6 @@ void main() {
final map = MemoryKeymap();
final app = createApp();
await mount(tester, app, map, native: true);
- final newPage = native(tester, 'new');
- await tester.pump();
- await newPage;
calls.clear();
final field = find.byKey(const ValueKey('harness-start-search'));
await tester.tap(field);
@@ -553,22 +565,22 @@ void main() {
isEmpty,
reason: 'Native chrome never mirrors the Flutter query',
);
- expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
- expect(tester.widget<TextField>(field).controller!.text, '> ');
+ final commandField = find.byKey(const ValueKey('swarm-search-input'));
+ expect(commandField, findsOneWidget);
+ expect(tester.widget<TextField>(commandField).controller!.text, '> ');
expect(
- tester.widget<TextField>(field).focusNode!.hasPrimaryFocus,
+ tester.widget<TextField>(commandField).focusNode!.hasPrimaryFocus,
isTrue,
);
expect(
- tester.widget<TextField>(field).decoration!.hintText,
+ tester.widget<TextField>(commandField).decoration!.hintText,
'Search commands…',
);
await key(tester, LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byType(SwarmSearchResults), findsNothing);
expect(field, findsOneWidget);
- expect(tester.widget<TextField>(field).controller!.text, '> ');
- expect(tester.widget<TextField>(field).focusNode!.hasFocus, isFalse);
+ expect(tester.widget<TextField>(field).controller!.text, 'Agent');
await tester.pumpWidget(const SizedBox());
app.dispose();
map.dispose();
@@ -665,7 +677,7 @@ void main() {
if (inline) {
await tester.tap(field);
} else {
- await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
}
await tester.enterText(field, 'Agent');
await tester.pump();
@@ -675,7 +687,10 @@ void main() {
final secondRow = search.rows.firstWhere((row) => row.agentId == 'a1');
await tabToResult(tester, id: secondRow.id);
expect(search.selected, same(secondRow));
- final next = search.rows[(search.cursor + 1) % search.rows.length];
+ final next =
+ search.rows[inline
+ ? (search.cursor + 1) % search.rows.length
+ : (search.cursor - 1).clamp(0, search.rows.length - 1)];
await key(tester, LogicalKeyboardKey.arrowDown);
expect(search.selected, same(secondRow));
await key(tester, LogicalKeyboardKey.keyG, ctrl: true);
@@ -733,7 +748,8 @@ void main() {
tester.testTextInput.updateEditingValue(TextEditingValue.empty);
await tester.pump();
await key(tester, LogicalKeyboardKey.keyT, cmd: true);
- expect(app.swarms, hasLength(2));
+ expect(app.swarms, hasLength(1));
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);
await tester.pumpWidget(const SizedBox());
app.dispose();
map.dispose();
@@ -783,7 +799,7 @@ void main() {
);
await native(tester, 'keymapCommand', {'command': 'swarm.new'});
await tester.pump();
- final field = find.byKey(const ValueKey('harness-start-search'));
+ final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.tap(field);
await tester.enterText(field, 'Agent 0');
await tester.pump();
diff --git a/desktop/test/keymap_store_test.dart b/desktop/test/keymap_store_test.dart
index f5cc07105..8f1f45fdd 100644
--- a/desktop/test/keymap_store_test.dart
+++ b/desktop/test/keymap_store_test.dart
@@ -44,6 +44,29 @@ class _ControlledFile extends Fake implements File {
}
}
+class _PausedResolutionFile extends Fake implements File {
+ _PausedResolutionFile(this.delegate);
+ final File delegate;
+ Completer<void>? resolutionGate;
+ final resolutionPaused = Completer<void>();
+
+ @override
+ File get absolute => delegate.absolute;
+ @override
+ Stream<List<int>> openRead([int? start, int? end]) =>
+ delegate.openRead(start, end);
+ @override
+ Future<String> resolveSymbolicLinks() async {
+ final gate = resolutionGate;
+ if (gate != null) {
+ if (!resolutionPaused.isCompleted) resolutionPaused.complete();
+ await gate.future;
+ resolutionGate = null;
+ }
+ return delegate.resolveSymbolicLinks();
+ }
+}
+
void main() {
late Directory directory;
setUp(() async {
@@ -206,4 +229,66 @@ void main() {
'/users/dev/.config/harness/keybindings.jsonc',
);
});
+
+ test(
+ 'an immediate save to a newly selected symlink target is not lost',
+ () async {
+ final first = File('${directory.path}/repo1/keys.jsonc');
+ final second = File('${directory.path}/repo2/keys.jsonc');
+ await first.parent.create();
+ await second.parent.create();
+ await first.writeAsString(config('swarm.new'));
+ await second.writeAsString(config('pane.focus_left'));
+ final replacement = File('${second.path}.save');
+ await replacement.writeAsString(config('swarm.new'));
+ final link = Link('${directory.path}/app/keybindings.jsonc');
+ await Directory('${directory.path}/app').create();
+ await link.create(first.path);
+ final watchedFile = _PausedResolutionFile(File(link.path));
+ final store = storeFor(watchedFile, watch: true);
+ addTearDown(store.dispose);
+ await store.start();
+ var replaced = false;
+ final replacementDelivered = Completer<void>();
+ final replacementPaths = {
+ second.path,
+ await second.resolveSymbolicLinks(),
+ };
+ final witness = second.parent.watch().listen((event) {
+ if (replaced &&
+ (replacementPaths.contains(event.path) ||
+ event is FileSystemMoveEvent &&
+ replacementPaths.contains(event.destination)) &&
+ !replacementDelivered.isCompleted) {
+ replacementDelivered.complete();
+ }
+ });
+ addTearDown(witness.cancel);
+ final gate = Completer<void>();
+ store.addListener(() {
+ if (!replaced && selected(store) == 'pane.focus_left') {
+ // The editor saves again as soon as the new target's map is visible.
+ // Hold the next watch refresh until the filesystem delivered this
+ // replacement. A slow target discovery must not lose an editor save.
+ watchedFile.resolutionGate = gate;
+ replacement.renameSync(second.path);
+ replaced = true;
+ }
+ });
+ await link.update(second.path);
+ try {
+ await Future.wait([
+ watchedFile.resolutionPaused.future,
+ replacementDelivered.future,
+ ]).timeout(const Duration(seconds: 5));
+ } finally {
+ gate.complete();
+ }
+ await eventually(() => replaced && selected(store) == 'swarm.new');
+ expect(store.error, isNull);
+ },
+ skip: Platform.isWindows
+ ? 'Creating Windows symlinks requires host permission'
+ : false,
+ );
}
diff --git a/desktop/test/keymap_test.dart b/desktop/test/keymap_test.dart
index 13c1199a1..a219b0b90 100644
--- a/desktop/test/keymap_test.dart
+++ b/desktop/test/keymap_test.dart
@@ -1,5 +1,6 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_commands.dart';
const commands = {'swarm.new', 'pane.focus_left', 'picker.next'};
KeyBinding bind(
@@ -18,6 +19,79 @@ KeymapMatch match(
]) => map.match(context, keys.split(' ').map(KeyStroke.parse));
void main() {
+ test('Launch and Project actions have no default text shortcuts', () {
+ final commands = {
+ 'creation.agent',
+ 'creation.project',
+ 'creation.task',
+ 'creation.project_machine',
+ 'creation.options',
+ 'creation.project_new',
+ 'creation.project_existing',
+ 'creation.project_repository',
+ for (var i = 1; i <= 9; i++) 'creation.project_recent_$i',
+ };
+ expect(
+ harnessDefaultKeymap
+ .bindingsFor(KeymapContext.project)
+ .where((binding) => commands.contains(binding.command)),
+ isEmpty,
+ );
+ expect(
+ match(harnessDefaultKeymap, 'up', KeymapContext.project).command,
+ 'picker.previous',
+ );
+ expect(
+ match(harnessDefaultKeymap, 'down', KeymapContext.project).command,
+ 'picker.next',
+ );
+ expect(
+ match(harnessDefaultKeymap, 'enter', KeymapContext.project).command,
+ 'picker.accept',
+ );
+ });
+
+ test(
+ 'project bindings override picker defaults and inherit custom navigation',
+ () {
+ final defaults = [
+ bind('o', 'creation.options', KeymapContext.picker),
+ bind('o', 'creation.project_existing', KeymapContext.project),
+ bind('ctrl+n', 'picker.next', KeymapContext.picker),
+ ];
+ final original = ResolvedKeymap(defaults, const KeymapConfig.empty());
+ expect(
+ match(original, 'o', KeymapContext.picker).command,
+ 'creation.options',
+ );
+ expect(
+ match(original, 'o', KeymapContext.project).command,
+ 'creation.project_existing',
+ );
+ final custom = ResolvedKeymap(
+ defaults,
+ KeymapConfig([
+ bind('o', null, KeymapContext.project),
+ bind('f', 'creation.project_existing', KeymapContext.project),
+ bind('ctrl+n', null, KeymapContext.picker),
+ bind('j', 'picker.next', KeymapContext.picker),
+ ]),
+ );
+ expect(
+ match(custom, 'o', KeymapContext.picker).command,
+ 'creation.options',
+ );
+ expect(match(custom, 'o', KeymapContext.project).matched, isFalse);
+ expect(match(custom, 'f', KeymapContext.picker).matched, isFalse);
+ expect(
+ match(custom, 'f', KeymapContext.project).command,
+ 'creation.project_existing',
+ );
+ expect(match(custom, 'ctrl+n', KeymapContext.project).matched, isFalse);
+ expect(match(custom, 'j', KeymapContext.project).command, 'picker.next');
+ },
+ );
+
test('retired Navigate and preview bindings preserve other shortcuts', () {
final config = KeymapConfig.parse('''{"bindings":[
{"keys":"cmd+i","command":"picker.preview","when":"picker"},
diff --git a/desktop/test/link_another_machine_test.dart b/desktop/test/link_another_machine_test.dart
new file mode 100644
index 000000000..afd6a1be5
--- /dev/null
+++ b/desktop/test/link_another_machine_test.dart
@@ -0,0 +1,414 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/auth/peer_link_client.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/widgets/link_another_machine_dialog.dart';
+import 'package:harness/widgets/link_machine_screen.dart';
+import 'package:harness/widgets/machines_manager.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+
+class _Links implements PeerLinkClient {
+ final requests = <String>[];
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async {
+ requests.add(machineId);
+ return CliLinkConnectResult(linkedMachineId: machineId);
+ }
+
+ @override
+ Future<CliLinkListResult> list() async => const CliLinkListResult();
+ @override
+ Future<String?> unlink(String machineId) async => null;
+}
+
+class _App extends AppNotifier {
+ _App(this.links)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ peerLinks: links,
+ );
+ final _Links links;
+ int refreshes = 0;
+ Completer<void>? refresh;
+ String? error;
+ @override
+ String? get machineListError => error;
+ @override
+ Future<void> retryMachines() {
+ refreshes++;
+ return refresh?.future ?? Future.value();
+ }
+
+ void add(String id, String name, {bool linked = false, bool local = false}) {
+ final machine = Machine(
+ machineId: id,
+ name: name,
+ authMode: MachineAuthMode.remote,
+ );
+ machineStates[id] = MachineState(machine)
+ ..localOnly = local
+ ..nodeOnline = true
+ ..needsLink = !linked;
+ machines = machineStates.values.map((state) => state.machine).toList();
+ notifyListeners();
+ }
+}
+
+const _search = Key('link-machine-search');
+final _input = find.byKey(_search);
+
+Future<void> _mount(
+ WidgetTester tester,
+ _App app, {
+ double scale = 1,
+ AppKeymap? keymap,
+ bool manager = false,
+}) async {
+ final opener = Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => manager
+ ? showMachinesManager(context, app)
+ : showLinkAnotherMachineDialog(context, app),
+ child: const Text('open setup'),
+ ),
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: keymap == null
+ ? opener
+ : KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ actions: const {},
+ enabled: () => false,
+ child: opener,
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open setup'));
+ await tester.pumpAndSettle();
+ if (manager) {
+ await tester.tap(find.text('Link Machine'));
+ await tester.pumpAndSettle();
+ }
+}
+
+void main() {
+ late _App app;
+ late List<String> clipboard;
+ var failCopy = false;
+ setUp(() {
+ app = _App(_Links());
+ clipboard = [];
+ failCopy = false;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ if (call.method == 'Clipboard.setData') {
+ if (failCopy) {
+ throw PlatformException(code: 'clipboard unavailable');
+ }
+ clipboard.add((call.arguments as Map)['text'] as String);
+ }
+ return null;
+ });
+ });
+ tearDown(() {
+ app.dispose();
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, null);
+ });
+
+ testWidgets(
+ 'filter, link, and return to the same machine query by keyboard',
+ (tester) async {
+ app.add('build', 'build-box');
+ app.add('studio', 'studio');
+ app.add('local', 'my laptop', local: true);
+ await _mount(tester, app);
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ expect(find.text('my laptop'), findsNothing);
+ tester.testTextInput.enterText('bdbx');
+ await tester.pump();
+ expect(find.text('build-box'), findsOneWidget);
+ expect(find.text('studio'), findsNothing);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final password = find.byKey(const Key('remote-password-connect-field'));
+ expect(tester.widget<TextField>(password).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.byType(LinkMachineScreen), findsNothing);
+ expect(app.links.requests, ['build']);
+ expect(tester.widget<TextField>(_input).controller!.text, 'bdbx');
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ expect(find.text('build-box is linked.'), findsOneWidget);
+ expect(
+ find.text('Already linked. Open its agents from New Tab or New Pane.'),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_input, findsNothing);
+ },
+ );
+
+ testWidgets('SSH guide copies exact commands and Escape restores the query', (
+ tester,
+ ) async {
+ await _mount(tester, app);
+ tester.testTextInput.enterText('ssh');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('On the other machine, over SSH:'), findsOneWidget);
+ final copyInstall = find.byKey(
+ const ValueKey('copy-$kLinkServerInstallCommand'),
+ );
+ expect(tester.widget<TextButton>(copyInstall).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(clipboard, [kLinkServerInstallCommand]);
+ await tester.tap(find.byKey(const Key('link-copy-all')));
+ await tester.pumpAndSettle();
+ expect(
+ clipboard.last,
+ '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand',
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(_input).controller!.text, 'ssh');
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ });
+
+ testWidgets(
+ 'background arrivals preserve the highlighted action and open guide',
+ (tester) async {
+ await _mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ await key(tester, LogicalKeyboardKey.keyP, ctrl: true);
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ app.add('new', 'new-server');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Link another machine / SSH'), findsOneWidget);
+ app.add('next', 'second-server');
+ await tester.pump();
+ expect(find.text(kLinkServerInstallCommand), findsOneWidget);
+ expect(find.text('second-server'), findsOneWidget);
+ expect(
+ tester
+ .widget<TextButton>(
+ find.byKey(const ValueKey('copy-$kLinkServerInstallCommand')),
+ )
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Link another machine / SSH'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'refresh coalesces, preserves filtering, and reports recovery',
+ (tester) async {
+ app.add('build', 'build-box');
+ app.refresh = Completer<void>();
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ await _mount(tester, app, keymap: map);
+ tester.testTextInput.enterText('build');
+ final mac =
+ Theme.of(tester.element(_input)).platform == TargetPlatform.macOS;
+ await key(tester, LogicalKeyboardKey.keyR, cmd: mac, ctrl: !mac);
+ await key(tester, LogicalKeyboardKey.keyR, cmd: mac, ctrl: !mac);
+ expect(app.refreshes, 1);
+ expect(find.text('Refreshing machines…'), findsOneWidget);
+ app.error = 'Machine list is offline';
+ app.refresh!.complete();
+ await tester.pumpAndSettle();
+ expect(find.text(app.error!), findsOneWidget);
+ expect(tester.widget<TextField>(_input).controller!.text, 'build');
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ app.error = null;
+ app.refresh = null;
+ await key(tester, LogicalKeyboardKey.keyR, cmd: mac, ctrl: !mac);
+ await tester.pumpAndSettle();
+ expect(app.refreshes, 2);
+ expect(find.text('Machine list refreshed.'), findsOneWidget);
+ },
+ variant: TargetPlatformVariant({
+ TargetPlatform.macOS,
+ TargetPlatform.linux,
+ }),
+ );
+
+ for (final manager in [false, true]) {
+ testWidgets(
+ 'picker keys stay live across dialog routes (manager: $manager)',
+ (tester) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ map.apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"ctrl+n","command":null,"when":"picker"},
+ {"keys":"cmd+r","command":null,"when":"picker"},
+ {"keys":"f6","command":"picker.next","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f9","command":"picker.refresh","when":"picker"}
+ ]}''');
+ await _mount(tester, app, keymap: map, manager: manager);
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_input, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ await key(tester, LogicalKeyboardKey.f6);
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(find.text('Link another machine / SSH'), findsOneWidget);
+ // The configured accept key also activates a focused guide control.
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(clipboard, [kLinkServerInstallCommand]);
+ await key(tester, LogicalKeyboardKey.keyR, cmd: true);
+ expect(app.refreshes, 0);
+ await key(tester, LogicalKeyboardKey.f9);
+ await tester.pumpAndSettle();
+ expect(app.refreshes, 1);
+ await key(tester, LogicalKeyboardKey.f7);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ map.apply('''{"bindings":[
+ {"keys":"f4","command":"picker.cancel","when":"picker"},
+ {"keys":"f10","command":"picker.accept","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(
+ find.textContaining(RegExp('f10 open', caseSensitive: false)),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(_input, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f10);
+ await tester.pumpAndSettle();
+ expect(find.text('Link another machine / SSH'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f4);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(_input, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('composition owns Enter and Escape in machine search', (
+ tester,
+ ) async {
+ await _mount(tester, app);
+ tester.testTextInput.enterText('ssh');
+ await tester.pump();
+ final controller = tester.widget<TextField>(_input).controller!;
+ controller.value = controller.value.copyWith(
+ composing: const TextRange(start: 0, end: 3),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_input, findsOneWidget);
+ expect(find.text('Link another machine / SSH'), findsNothing);
+ controller.value = controller.value.copyWith(composing: TextRange.empty);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Link another machine / SSH'), findsOneWidget);
+ });
+
+ testWidgets('clipboard errors leave the focused command available to retry', (
+ tester,
+ ) async {
+ await _mount(tester, app);
+ tester.testTextInput.enterText('ssh');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ failCopy = true;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Could not copy. Select the text to copy it, or try again.'),
+ findsOneWidget,
+ );
+ failCopy = false;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(clipboard, [kLinkServerInstallCommand]);
+ expect(find.text('Copied. Run on the other machine.'), findsOneWidget);
+ });
+
+ testWidgets('short windows with enlarged text keep setup and back reachable', (
+ tester,
+ ) async {
+ tester.view.physicalSize = const Size(600, 420);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await _mount(tester, app, scale: 1.7);
+ tester.testTextInput.enterText('ssh');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(find.text('esc back').hitTestable(), findsOneWidget);
+ // Tab traversal scrolls the controls into view; no mouse is needed to copy.
+ for (var i = 0; i < 10; i++) {
+ final all = tester.widget<TextButton>(
+ find.byKey(const Key('link-copy-all')),
+ );
+ final focus = Focus.of(
+ tester.element(find.text('Copy all three commands')),
+ );
+ if (focus.hasFocus) {
+ expect(all.onPressed, isNotNull);
+ break;
+ }
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ clipboard.last,
+ '$kLinkServerInstallCommand\n$kLinkServerLoginCommand\n$kLinkServerStartCommand',
+ );
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
+ });
+}
diff --git a/desktop/test/link_machine_dialog_widget_test.dart b/desktop/test/link_machine_dialog_widget_test.dart
index 5a37e1c74..582cc2f95 100644
--- a/desktop/test/link_machine_dialog_widget_test.dart
+++ b/desktop/test/link_machine_dialog_widget_test.dart
@@ -1,4 +1,8 @@
+import 'dart:async';
+import 'dart:convert';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_link.dart';
@@ -6,117 +10,124 @@ import 'package:harness/core/config.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/link_machine_dialog.dart';
-class _FakeCliLink implements CliLink {
- final RemotePasswordStatus statusResult;
- final RemotePasswordSetResult setResult;
- final String? clearError;
- _FakeCliLink({
- this.statusResult = const RemotePasswordStatus(hasPassword: false),
- this.setResult = const RemotePasswordSetResult(),
- this.clearError,
- });
-
- @override
- Future<RemotePasswordSetResult> setRemotePassword(String password) async =>
- setResult;
-
- @override
- Future<RemotePasswordStatus> remotePasswordStatus() async => statusResult;
-
- @override
- Future<String?> clearRemotePassword() async => clearError;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/widgets/link_another_machine_dialog.dart';
- @override
- Future<CliLinkConnectResult> connect(
- String machineId,
- String password, {
- void Function(String stage)? onProgress,
- String? displayName,
- }) async => const CliLinkConnectResult();
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'support/password_cli.dart';
- @override
- Future<CliLinkListResult> list() async => const CliLinkListResult();
+const passwordKey = Key('remote-password-field');
+const confirmKey = Key('remote-password-confirm-field');
- @override
- Future<String?> unlink(String machineId) async => null;
-}
-
-Future<void> _pumpDialog(WidgetTester tester, AppNotifier notifier) async {
- // The password form (two fields + actions) is taller than the old single-button generate
- // flow — give the test surface enough room that every control renders on-screen and can
- // actually be hit-tested, rather than relying on scrolling it into view.
- tester.view.physicalSize = const Size(900 * 2, 1000 * 2);
- tester.view.devicePixelRatio = 2;
+Future<void> _pumpDialog(
+ WidgetTester tester,
+ AppNotifier notifier, {
+ Size size = const Size(900, 700),
+ double scale = 1,
+ AppKeymap? keymap,
+ bool nested = false,
+}) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
+ final opener = Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => nested
+ ? showLinkAnotherMachineDialog(context, notifier)
+ : showLinkMachineDialog(context, notifier),
+ child: const Text('open'),
+ ),
+ ),
+ );
await tester.pumpWidget(
MaterialApp(
- home: Scaffold(
- body: Builder(
- builder: (context) => ElevatedButton(
- onPressed: () => showLinkMachineDialog(context, notifier),
- child: const Text('open'),
- ),
- ),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
),
+ home: keymap == null
+ ? opener
+ : KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ actions: const {},
+ enabled: () => false,
+ child: opener,
+ ),
+ ),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
+ if (nested) {
+ await tester.enterText(
+ find.byKey(const Key('link-machine-search')),
+ 'password',
+ );
+ await tester.tap(find.text('This computer’s password').first);
+ await tester.pumpAndSettle();
+ }
+}
+
+TextField field(WidgetTester tester, Key key) =>
+ tester.widget<TextField>(find.byKey(key));
+Future<void> enterPassword(WidgetTester tester) async {
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
}
void main() {
- AppNotifier notifier({_FakeCliLink? cliLink}) => AppNotifier(
+ AppNotifier notifier({PasswordCli? cliLink}) => AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
- cliLink: cliLink ?? _FakeCliLink(),
+ cliLink: cliLink ?? PasswordCli(),
);
- testWidgets(
- 'shows the password form when no password is set yet, pointing at the sidebar',
- (tester) async {
- final appNotifier = notifier();
- await _pumpDialog(tester, appNotifier);
+ testWidgets('shows the terminal password form when no password is set', (
+ tester,
+ ) async {
+ final appNotifier = notifier();
+ await _pumpDialog(tester, appNotifier);
- expect(find.text('Link another machine'), findsOneWidget);
- expect(find.text('Let another machine control this one'), findsOneWidget);
- expect(
- find.text('Set a remote password for this machine below.'),
- findsOneWidget,
- );
- expect(find.byKey(const Key('remote-password-field')), findsOneWidget);
- expect(
- find.byKey(const Key('remote-password-confirm-field')),
- findsOneWidget,
- );
- expect(
- find.byKey(const Key('remote-password-set-button')),
- findsOneWidget,
- );
+ expect(find.text('This computer’s password'), findsOneWidget);
+ expect(
+ find.text(
+ 'Use this password on the other machine to link to this computer.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.byKey(const Key('remote-password-field')), findsOneWidget);
+ expect(
+ find.byKey(const Key('remote-password-confirm-field')),
+ findsOneWidget,
+ );
+ expect(find.byKey(const Key('remote-password-set-button')), findsOneWidget);
- // The paste-to-link card moved to LinkMachineScreen — it must not be duplicated here.
- expect(
- find.byKey(const Key('remote-password-connect-field')),
- findsNothing,
- );
- expect(
- find.byKey(const Key('remote-password-connect-button')),
- findsNothing,
- );
- appNotifier.dispose();
- },
- );
+ // The paste-to-link card moved to LinkMachineScreen — it must not be duplicated here.
+ expect(
+ find.byKey(const Key('remote-password-connect-field')),
+ findsNothing,
+ );
+ expect(
+ find.byKey(const Key('remote-password-connect-button')),
+ findsNothing,
+ );
+ appNotifier.dispose();
+ });
testWidgets(
'setting a password shows the fingerprint summary and Change/Clear',
(tester) async {
- final appNotifier = notifier(
- cliLink: _FakeCliLink(
- setResult: const RemotePasswordSetResult(
- fingerprint: '1535·C035·9474·FE9D',
- ),
- ),
- );
+ final appNotifier = notifier(cliLink: PasswordCli());
await _pumpDialog(tester, appNotifier);
await tester.enterText(
@@ -172,12 +183,11 @@ void main() {
tester,
) async {
final appNotifier = notifier(
- cliLink: _FakeCliLink(
- statusResult: const RemotePasswordStatus(
+ cliLink: PasswordCli()
+ ..status = const RemotePasswordStatus(
hasPassword: true,
fingerprint: 'AAAA·BBBB·CCCC·DDDD',
),
- ),
);
await _pumpDialog(tester, appNotifier);
@@ -191,13 +201,12 @@ void main() {
'clearing asks for confirmation and shows the CLI error on failure',
(tester) async {
final appNotifier = notifier(
- cliLink: _FakeCliLink(
- statusResult: const RemotePasswordStatus(
+ cliLink: PasswordCli()
+ ..status = const RemotePasswordStatus(
hasPassword: true,
fingerprint: 'AAAA·BBBB·CCCC·DDDD',
- ),
- clearError: 'Could not run the Harness CLI: not found',
- ),
+ )
+ ..clearError = 'Could not run the Harness CLI: not found',
);
await _pumpDialog(tester, appNotifier);
@@ -220,4 +229,286 @@ void main() {
appNotifier.dispose();
},
);
+
+ testWidgets(
+ 'Enter advances and submits once; reopening joins the pending change',
+ (tester) async {
+ final cli = PasswordCli()
+ ..setReply = Completer<RemotePasswordSetResult>();
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ await enterPassword(tester);
+ expect(cli.passwords, ['fixture password']);
+ expect(field(tester, passwordKey).readOnly, isTrue);
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.passwords, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(find.text('Setting password…'), findsOneWidget);
+ expect(find.byKey(passwordKey), findsNothing);
+ expect(cli.reads, 1);
+ cli.setReply!.complete(cli.setResult);
+ await tester.pumpAndSettle();
+ expect(find.text('Remote password is set'), findsOneWidget);
+ expect(find.text('1535·C035·9474·FE9D'), findsOneWidget);
+ expect(app.pendingRemotePasswordChange, isNull);
+ },
+ );
+
+ testWidgets(
+ 'unknown password status stays distinct from unset and retries by keyboard',
+ (tester) async {
+ final cli = PasswordCli()
+ ..statusFailure = StateError('fixture secret must not be printed');
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ expect(find.byKey(passwordKey), findsNothing);
+ expect(
+ find.text('Could not read this computer’s password status. Try again.'),
+ findsOneWidget,
+ );
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Retry'))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ cli.statusFailure = null;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ expect(cli.reads, 2);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'mismatch and CLI errors keep the input and restore retry focus',
+ (tester) async {
+ final cli = PasswordCli()..setFailure = StateError('fixture secret');
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ tester.testTextInput.enterText('different');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(cli.passwords, isEmpty);
+ expect(find.text('Passwords do not match'), findsOneWidget);
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Could not set the password. Try again.'),
+ findsOneWidget,
+ );
+ expect(field(tester, passwordKey).controller!.text, 'fixture password');
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ expect(field(tester, confirmKey).readOnly, isFalse);
+ cli.setFailure = null;
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, hasLength(2));
+ expect(find.text('Password set.'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'composition owns Enter and Escape; native Next and Done retain key focus',
+ (tester) async {
+ final cli = PasswordCli();
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ final input = field(tester, passwordKey);
+ input.controller!.value = const TextEditingValue(
+ text: 'password',
+ selection: TextSelection.collapsed(offset: 8),
+ composing: TextRange(start: 0, end: 8),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(input.focusNode!.hasFocus, isTrue);
+ expect(cli.passwords, isEmpty);
+ input.controller!.clearComposing();
+ await tester.testTextInput.receiveAction(TextInputAction.next);
+ await tester.pump();
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('password');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['password']);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('This computer’s password'), findsNothing);
+ },
+ );
+
+ testWidgets('clear defaults to Cancel and survives closing while pending', (
+ tester,
+ ) async {
+ final cli = PasswordCli()
+ ..status = const RemotePasswordStatus(hasPassword: true)
+ ..clearReply = Completer<String?>();
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ await tester.tap(find.byKey(const Key('remote-password-clear-button')));
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'Prevent new links using this password? Existing links and sessions stay connected.',
+ ),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.clears, 0);
+ expect(find.text('Remote password is set'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('remote-password-clear-button')));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.clears, 1);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ expect(find.text('Clearing password…'), findsOneWidget);
+ cli.clearReply!.complete(null);
+ await tester.pumpAndSettle();
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ expect(find.text('Password cleared.'), findsOneWidget);
+ });
+
+ testWidgets(
+ 'links remain separate; unlink failure is visible and keyboard retryable',
+ (tester) async {
+ final cli = PasswordCli()
+ ..links = CliLinkListResult(
+ machines: [
+ LinkedMachine(
+ machineId: 'build-box',
+ fingerprint: 'AAAA·BBBB',
+ linkedAt: '2026-09-19 12:00',
+ ),
+ ],
+ )
+ ..unlinkError = 'Machine is busy. Try again.';
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app);
+ expect(find.text('build-box'), findsNothing);
+ expect(cli.lists, 0);
+ await tester.tap(find.byKey(const Key('remote-password-links-button')));
+ await tester.pumpAndSettle();
+ expect(find.text('Links from this computer'), findsOneWidget);
+ await tester.tap(find.byKey(const Key('unlink-build-box')));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Machine is busy. Try again.'), findsOneWidget);
+ expect(app.linkedMachines, hasLength(1));
+ cli.unlinkError = null;
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.unlinks, ['build-box', 'build-box']);
+ expect(find.text('No machines linked yet.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ },
+ );
+
+ testWidgets(
+ 'short window and enlarged text keep both password prompts and Escape usable',
+ (tester) async {
+ final cli = PasswordCli();
+ final app = notifier(cliLink: cli);
+ addTearDown(app.dispose);
+ await _pumpDialog(tester, app, size: const Size(480, 360), scale: 1.7);
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ await enterPassword(tester);
+ expect(cli.passwords, ['fixture password']);
+ expect(tester.takeException(), isNull);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'nested password prompt follows live keymap and keeps parent query',
+ (tester) async {
+ final cli = PasswordCli();
+ final app = notifier(cliLink: cli);
+ final map = MemoryKeymap()
+ ..apply(
+ jsonEncode({
+ 'bindings': [
+ {'keys': 'enter', 'command': null, 'when': 'picker'},
+ {'keys': 'escape', 'command': null, 'when': 'picker'},
+ {'keys': 'f8', 'command': 'picker.accept', 'when': 'picker'},
+ {'keys': 'f7', 'command': 'picker.cancel', 'when': 'picker'},
+ ],
+ }),
+ );
+ addTearDown(app.dispose);
+ addTearDown(map.dispose);
+ await _pumpDialog(tester, app, keymap: map, nested: true);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ expect(
+ find.textContaining(
+ RegExp('f8 confirm password', caseSensitive: false),
+ ),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(field(tester, confirmKey).focusNode!.hasFocus, isTrue);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(cli.passwords, ['fixture password']);
+ // The summary owns Enter now; a detached field must not resubmit.
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(field(tester, passwordKey).focusNode!.hasFocus, isTrue);
+ expect(field(tester, passwordKey).controller!.text, isEmpty);
+ expect(cli.passwords, hasLength(1));
+ await key(tester, LogicalKeyboardKey.f7);
+ await tester.pumpAndSettle();
+ map.apply(
+ jsonEncode({
+ 'bindings': [
+ {'keys': 'f4', 'command': 'picker.cancel', 'when': 'picker'},
+ ],
+ }),
+ );
+ await tester.pump();
+ expect(
+ find.textContaining(RegExp('f4 close', caseSensitive: false)),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ final search = tester.widget<TextField>(
+ find.byKey(const Key('link-machine-search')),
+ );
+ expect(search.controller!.text, 'password');
+ expect(search.focusNode!.hasFocus, isTrue);
+ },
+ );
}
diff --git a/desktop/test/link_machine_widget_test.dart b/desktop/test/link_machine_widget_test.dart
index 444bbb4d5..9b1ad8c78 100644
--- a/desktop/test/link_machine_widget_test.dart
+++ b/desktop/test/link_machine_widget_test.dart
@@ -1,4 +1,7 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/cli_link.dart';
@@ -7,6 +10,8 @@ import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/widgets/link_machine_screen.dart';
+import 'keymap_host_test.dart' show key;
+
class _FakeCliLink implements CliLink {
final Future<CliLinkConnectResult> Function(String machineId, String password)
onConnect;
@@ -18,7 +23,10 @@ class _FakeCliLink implements CliLink {
String password, {
void Function(String stage)? onProgress,
String? displayName,
- }) => onConnect(machineId, password);
+ }) {
+ onProgress?.call('exchanging');
+ return onConnect(machineId, password);
+ }
@override
Future<RemotePasswordSetResult> setRemotePassword(String password) async =>
@@ -61,6 +69,272 @@ void main() {
return notifier;
}
+ test(
+ 'pending handshakes coalesce by machine and ignore a disposed session',
+ () async {
+ final pending = Completer<CliLinkConnectResult>();
+ var calls = 0;
+ final notifier = notifierFor(
+ _FakeCliLink((_, _) {
+ calls++;
+ return pending.future;
+ }),
+ );
+ final first = notifier.connectWithPassword(
+ machine.machineId,
+ 'test password',
+ );
+ final second = notifier.connectWithPassword(
+ machine.machineId,
+ 'another password',
+ );
+ expect(second, same(first));
+ expect(calls, 1);
+ expect(notifier.machineLinkStage(machine.machineId), 'exchanging');
+ notifier.dispose();
+ pending.complete(
+ CliLinkConnectResult(linkedMachineId: machine.machineId),
+ );
+ expect(await first, 'This connection request is no longer active.');
+ expect(notifier.machineStates[machine.machineId]!.needsLink, isTrue);
+ },
+ );
+
+ testWidgets('link prompt accepts typing immediately and submits only once', (
+ tester,
+ ) async {
+ final pending = Completer<CliLinkConnectResult>();
+ final passwords = <String>[];
+ final notifier = notifierFor(
+ _FakeCliLink((_, password) {
+ passwords.add(password);
+ return pending.future;
+ }),
+ );
+ addTearDown(notifier.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: LinkMachineScreen(
+ notifier: notifier,
+ machineState: notifier.machineStates[machine.machineId]!,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final field = find.byKey(const Key('remote-password-connect-field'));
+ expect(tester.widget<TextField>(field).focusNode?.hasFocus, isTrue);
+ tester.testTextInput.enterText('test remote password');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ expect(passwords, ['test remote password']);
+ await tester.pump();
+ expect(tester.widget<TextField>(field).readOnly, isTrue);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ pending.complete(const CliLinkConnectResult(error: 'Incorrect password'));
+ await tester.pumpAndSettle();
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(tester.widget<TextField>(field).readOnly, isFalse);
+ expect(
+ tester.widget<TextField>(field).controller!.text,
+ 'test remote password',
+ );
+ expect(find.text('Incorrect password'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a failed link process unlocks the prompt for keyboard retry', (
+ tester,
+ ) async {
+ var calls = 0;
+ final notifier = notifierFor(
+ _FakeCliLink((machineId, _) async {
+ if (++calls == 1) throw StateError('CLI process failed');
+ return CliLinkConnectResult(linkedMachineId: machineId);
+ }),
+ );
+ addTearDown(notifier.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: LinkMachineScreen(
+ notifier: notifier,
+ machineState: notifier.machineStates[machine.machineId]!,
+ ),
+ ),
+ ),
+ );
+ final field = find.byKey(const Key('remote-password-connect-field'));
+ await tester.enterText(field, 'fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ find.text('Could not link this machine. Try again.'),
+ findsOneWidget,
+ );
+ expect(notifier.pendingMachineLink(machine.machineId), isNull);
+ expect(tester.widget<TextField>(field).readOnly, isFalse);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.keyU, ctrl: true);
+ expect(tester.widget<TextField>(field).controller!.text, isEmpty);
+ expect(find.text('Could not link this machine. Try again.'), findsNothing);
+ await key(tester, LogicalKeyboardKey.keyY, ctrl: true);
+ expect(
+ tester.widget<TextField>(field).controller!.text,
+ 'fixture password',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(calls, 2);
+ expect(notifier.machineStates[machine.machineId]!.needsLink, isFalse);
+ expect(tester.widget<TextField>(field).controller!.text, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ test(
+ 'links to different machines progress and finish independently',
+ () async {
+ const other = Machine(
+ machineId: 'remote-2',
+ authMode: MachineAuthMode.remote,
+ name: 'remote-server',
+ );
+ final replies = <String, Completer<CliLinkConnectResult>>{};
+ final notifier = notifierFor(
+ _FakeCliLink((id, _) => (replies[id] = Completer()).future),
+ );
+ addTearDown(notifier.dispose);
+ notifier.machineStates[other.machineId] = MachineState(other)
+ ..needsLink = true;
+ final first = notifier.connectWithPassword(machine.machineId, 'first');
+ final second = notifier.connectWithPassword(other.machineId, 'second');
+ expect(replies.keys, containsAll([machine.machineId, other.machineId]));
+ replies[other.machineId]!.complete(
+ const CliLinkConnectResult(error: 'Incorrect password'),
+ );
+ expect(await second, 'Incorrect password');
+ expect(notifier.pendingMachineLink(other.machineId), isNull);
+ expect(notifier.machineStates[other.machineId]!.needsLink, isTrue);
+ expect(notifier.pendingMachineLink(machine.machineId), same(first));
+ replies[machine.machineId]!.complete(
+ CliLinkConnectResult(linkedMachineId: machine.machineId),
+ );
+ expect(await first, isNull);
+ expect(notifier.pendingMachineLink(machine.machineId), isNull);
+ expect(notifier.machineStates[machine.machineId]!.needsLink, isFalse);
+ },
+ );
+
+ testWidgets('link prompt leaves Enter and Escape with active composition', (
+ tester,
+ ) async {
+ var calls = 0;
+ final notifier = notifierFor(
+ _FakeCliLink((_, _) async {
+ calls++;
+ return const CliLinkConnectResult(error: 'Not submitted');
+ }),
+ );
+ addTearDown(notifier.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showLinkMachineScreenDialog(
+ context,
+ notifier,
+ machine.machineId,
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ final field = find.byKey(const Key('remote-password-connect-field'));
+ expect(
+ tester.widget<TextField>(field).focusNode!.hasFocus,
+ isTrue,
+ reason: FocusManager.instance.primaryFocus?.toString(),
+ );
+ await tester.enterText(field, '日本語');
+ final controller = tester.widget<TextField>(field).controller!;
+ controller.value = controller.value.copyWith(
+ composing: const TextRange(start: 0, end: 3),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(calls, 0);
+ expect(field, findsOneWidget);
+ expect(notifier.isLinkPromptDismissed(machine.machineId), isFalse);
+ controller.value = controller.value.copyWith(composing: TextRange.empty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(field, findsNothing);
+ expect(notifier.isLinkPromptDismissed(machine.machineId), isTrue);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'closing and reopening joins the pending link without another request',
+ (tester) async {
+ final pending = Completer<CliLinkConnectResult>();
+ var calls = 0;
+ final notifier = notifierFor(
+ _FakeCliLink((_, _) {
+ calls++;
+ return pending.future;
+ }),
+ );
+ addTearDown(notifier.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showLinkMachineScreenDialog(
+ context,
+ notifier,
+ machine.machineId,
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ final field = find.byKey(const Key('remote-password-connect-field'));
+ await tester.enterText(field, 'test password');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.tap(find.text('open'));
+ await tester.pump();
+ await tester.pump();
+ expect(tester.widget<TextField>(field).readOnly, isTrue);
+ expect(calls, 1);
+ pending.complete(
+ const CliLinkConnectResult(error: 'Try another password'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Try another password'), findsOneWidget);
+ expect(tester.widget<TextField>(field).readOnly, isFalse);
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(calls, 1);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets('shows a clear password prompt for the target machine', (
tester,
) async {
@@ -80,10 +354,7 @@ void main() {
expect(find.text('Link this machine'), findsOneWidget);
expect(
- find.text(
- "This computer isn't linked to remote-mac yet. Enter the remote password set "
- 'on that machine to connect.',
- ),
+ find.text('Enter the remote password set on this machine.'),
findsOneWidget,
);
expect(
@@ -91,7 +362,7 @@ void main() {
findsOneWidget,
);
expect(find.text('Remote password for remote-mac'), findsOneWidget);
- expect(find.text('Link machine'), findsOneWidget);
+ expect(find.text('enter link machine'), findsOneWidget);
expect(
find.text(
'Your previous agent will reconnect automatically after linking.',
@@ -104,9 +375,8 @@ void main() {
await tester.pump();
expect(find.text('Machine ID: remote-1'), findsOneWidget);
- // Close sits bottom-right as a text button, matching every other dialog in the app —
- // not a floating top-right × icon.
- expect(find.text('Close'), findsOneWidget);
+ // The close key guide remains clickable as well as keyboard accessible.
+ expect(find.text('esc close'), findsOneWidget);
notifier.dispose();
});
@@ -126,7 +396,7 @@ void main() {
);
expect(notifier.isLinkPromptDismissed(machine.machineId), isFalse);
- await tester.tap(find.text('Close'));
+ await tester.tap(find.text('esc close'));
await tester.pump();
expect(notifier.isLinkPromptDismissed(machine.machineId), isTrue);
notifier.dispose();
@@ -157,7 +427,7 @@ void main() {
find.byKey(const Key('remote-password-connect-field')),
'correct horse battery staple',
);
- await tester.tap(find.byKey(const Key('remote-password-connect-button')));
+ await tester.tap(find.text('enter link machine'));
await tester.pumpAndSettle();
expect(connectedPassword, 'correct horse battery staple');
@@ -189,7 +459,7 @@ void main() {
find.byKey(const Key('remote-password-connect-field')),
'wrong-password',
);
- await tester.tap(find.byKey(const Key('remote-password-connect-button')));
+ await tester.tap(find.text('enter link machine'));
await tester.pumpAndSettle();
expect(find.text('Incorrect password'), findsOneWidget);
diff --git a/desktop/test/machine_edits_test.dart b/desktop/test/machine_edits_test.dart
new file mode 100644
index 000000000..3174db1a8
--- /dev/null
+++ b/desktop/test/machine_edits_test.dart
@@ -0,0 +1,291 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'support/machine_api.dart';
+import 'swarm_state_test.dart' show createApp;
+import 'swarm_screen_test.dart' show terminal;
+
+class _InventoryApi extends MachineApi {
+ final replies = <Completer<List<Machine>>>[];
+ bool stale = false;
+ @override
+ Future<List<Machine>> machines() {
+ final reply = Completer<List<Machine>>();
+ replies.add(reply);
+ return reply.future.then((list) {
+ lastMachinesStale = stale;
+ return list;
+ });
+ }
+}
+
+class _InventoryConnection extends WsConn {
+ _InventoryConnection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'remote',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ @override
+ Future<void> waitUntilReady({required Duration timeout}) async {}
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => const {'agents': []};
+}
+
+class _NoDiscovery extends LocalCliDiscovery {
+ _NoDiscovery() : super(config: AppConfig.dev);
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late AppNotifier app;
+ late MachineApi api;
+ setUp(() {
+ api = MachineApi();
+ app = createApp()..api = api;
+ });
+ tearDown(() => app.dispose());
+
+ test(
+ 'rename joins an identical request and rejects competing account edits',
+ () async {
+ api.renameReply = Completer<String?>();
+ final rename = app.renameMachine('m', ' Workstation ');
+ expect(identical(rename, app.renameMachine('m', 'Workstation')), isTrue);
+ expect(identical(rename, app.pendingMachineRename('m')), isTrue);
+ expect(app.pendingMachineName('m'), 'Workstation');
+ expect(
+ await app.renameMachine('m', 'Different'),
+ contains('already in progress'),
+ );
+ expect(await app.deleteMachine('m'), contains('already in progress'));
+ expect(api.renames, [('m', 'Workstation')]);
+ api.renameReply!.complete('Workstation · Office');
+ expect(await rename, isNull);
+ expect(app.stateOf('m')!.machine.displayName, 'Workstation · Office');
+ expect(app.machines.single.displayName, 'Workstation · Office');
+ expect(app.pendingMachineRename('m'), isNull);
+ await app.renameMachine('m', 'Workstation · Office');
+ expect(api.renames, hasLength(1));
+ },
+ );
+
+ test(
+ 'a late rename cannot change a replaced machine with the same id',
+ () async {
+ api.renameReply = Completer<String?>();
+ final rename = app.renameMachine('m', 'Old request');
+ final replacement = MachineState(
+ const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Replacement',
+ ),
+ );
+ app.machineStates['m'] = replacement;
+ app.machines = [replacement.machine];
+ api.renameReply!.complete('Old request');
+ expect(await rename, contains('machine changed'));
+ expect(replacement.machine.displayName, 'Replacement');
+ expect(app.machines.single.displayName, 'Replacement');
+ expect(app.pendingMachineRename('m'), isNull);
+ },
+ );
+
+ test(
+ 'late delete cannot remove a replacement machine or its panes',
+ () async {
+ api.deleteReply = Completer<void>();
+ final deleted = app.deleteMachine('m');
+ final replacement = MachineState(
+ const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Replacement',
+ ),
+ );
+ app.machineStates['m'] = replacement;
+ app.machines = [replacement.machine];
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ api.deleteReply!.complete();
+ expect(await deleted, contains('machine changed'));
+ expect(app.stateOf('m'), same(replacement));
+ expect(app.allPanes, contains(pane));
+ },
+ );
+
+ test('delete joins its request and removes only that machine’s views across tabs', () async {
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final original = app.activeSwarm;
+ app.newSwarm();
+ final second = app.activeSwarm;
+ second.panes.add(pane);
+ const remote = Machine(
+ machineId: 'other',
+ authMode: MachineAuthMode.remote,
+ name: 'Other',
+ );
+ app.machineStates['other'] = MachineState(remote);
+ app.machines.add(remote);
+ api.deleteReply = Completer<void>();
+ final deleting = app.deleteMachine('m');
+ expect(identical(deleting, app.deleteMachine('m')), isTrue);
+ expect(app.pendingMachineDelete('m'), same(deleting));
+ expect(
+ await app.renameMachine('m', 'New'),
+ contains('already in progress'),
+ );
+ api.deleteReply!.complete();
+ expect(await deleting, isNull);
+ expect(api.deletes, ['m']);
+ expect(app.stateOf('m'), isNull);
+ expect(app.stateOf('other'), isNotNull);
+ expect(original.panes, isNot(contains(pane)));
+ expect(second.panes, isNot(contains(pane)));
+ expect(pane.session, isNull);
+ expect(app.pendingMachineDelete('m'), isNull);
+ });
+
+ test(
+ 'local deletion and all shared-machine edits fail before making a request',
+ () async {
+ app.stateOf('m')!.localOnly = true;
+ expect(await app.deleteMachine('m'), contains('cannot be deleted'));
+ const shared = Machine(
+ machineId: 'shared',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ app.machineStates['shared'] = MachineState(shared);
+ expect(await app.renameMachine('shared', 'New'), contains('view-only'));
+ expect(await app.deleteMachine('shared'), contains('view-only'));
+ expect(api.renames, isEmpty);
+ expect(api.deletes, isEmpty);
+ },
+ );
+
+ test('API and unexpected failures leave current state intact and release busy state', () async {
+ final name = app.stateOf('m')!.machine.displayName;
+ api.renameFailure = ApiException('Connection unavailable');
+ expect(
+ await app.renameMachine('m', 'New'),
+ 'Rename failed: Connection unavailable',
+ );
+ expect(app.pendingMachineRename('m'), isNull);
+ expect(app.stateOf('m')!.machine.displayName, name);
+ api.deleteFailure = StateError('fixture internal detail');
+ expect(
+ await app.deleteMachine('m'),
+ 'Could not delete the machine. Try again.',
+ );
+ expect(app.pendingMachineDelete('m'), isNull);
+ expect(app.stateOf('m'), isNotNull);
+ api.deleteFailure = null;
+ expect(await app.deleteMachine('m'), isNull);
+ });
+
+ test(
+ 'disposal during rename or deletion never notifies a disposed model',
+ () async {
+ for (final deleting in [false, true]) {
+ final model = createApp()..api = api;
+ api.renameReply = Completer<String?>();
+ api.deleteReply = Completer<void>();
+ final request = deleting
+ ? model.deleteMachine('m')
+ : model.renameMachine('m', 'New');
+ model.dispose();
+ if (deleting) {
+ api.deleteReply!.complete();
+ } else {
+ api.renameReply!.complete();
+ }
+ expect(await request, isNotNull);
+ }
+ },
+ );
+
+ for (final deleting in [false, true]) {
+ test(
+ 'old inventory and offline cache cannot undo an account edit (delete: $deleting)',
+ () async {
+ final api = _InventoryApi();
+ final connection = _InventoryConnection();
+ final model = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ localCliDiscovery: _NoDiscovery(),
+ connectionForTest: (_) => connection,
+ )..api = api;
+ addTearDown(model.dispose);
+ const machine = Machine(
+ machineId: 'remote',
+ authMode: MachineAuthMode.remote,
+ name: 'Before',
+ status: 'offline',
+ );
+ model.machines = [machine];
+ model.machineStates['remote'] = MachineState(machine)
+ ..nodeOnline = false;
+ final oldRead = model.refreshMachines();
+ await Future<void>.delayed(Duration.zero);
+ expect(api.replies, hasLength(1));
+ if (deleting) {
+ await model.deleteMachine('remote');
+ } else {
+ await model.renameMachine('remote', 'After');
+ }
+ api.replies.first.complete([machine]);
+ await oldRead;
+ expect(
+ model.stateOf('remote')?.machine.name,
+ deleting ? isNull : 'After',
+ );
+ api.stale = true;
+ final cachedRead = model.refreshMachines();
+ await Future<void>.delayed(Duration.zero);
+ api.replies.last.complete([machine]);
+ await cachedRead;
+ expect(
+ model.stateOf('remote')?.machine.name,
+ deleting ? isNull : 'After',
+ );
+ // A later live result can legitimately rename or re-register a machine.
+ api.stale = false;
+ final freshRead = model.refreshMachines();
+ await Future<void>.delayed(Duration.zero);
+ api.replies.last.complete([machine.copyWith(name: 'Fresh inventory')]);
+ await freshRead;
+ expect(model.stateOf('remote')!.machine.name, 'Fresh inventory');
+ api.stale = true;
+ final anotherCachedRead = model.refreshMachines();
+ await Future<void>.delayed(Duration.zero);
+ api.replies.last.complete([machine]);
+ await anotherCachedRead;
+ expect(model.stateOf('remote')!.machine.name, 'Fresh inventory');
+ },
+ );
+ }
+}
diff --git a/desktop/test/machine_inventory_api_test.dart b/desktop/test/machine_inventory_api_test.dart
new file mode 100644
index 000000000..05f5eb0f8
--- /dev/null
+++ b/desktop/test/machine_inventory_api_test.dart
@@ -0,0 +1,144 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+
+import 'swarm_state_test.dart' show MemoryStore;
+
+class _Requests {
+ final machines = <HttpRequest>[];
+ final shares = <HttpRequest>[];
+ void receive(HttpRequest request) {
+ if (request.uri.path == '/api/machines') {
+ machines.add(request);
+ } else if (request.uri.path == '/api/harness-shares') {
+ shares.add(request);
+ } else {
+ request.response.statusCode = 404;
+ unawaited(request.response.close());
+ }
+ }
+}
+
+Future<void> _until(bool Function() ready) async {
+ for (var i = 0; i < 200 && !ready(); i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 2));
+ }
+ expect(ready(), isTrue);
+}
+
+Future<void> _reply(
+ HttpRequest request,
+ String name, {
+ bool stale = false,
+ bool fails = false,
+}) async {
+ request.response
+ ..statusCode = fails ? 503 : 200
+ ..headers.contentType = ContentType.json
+ ..write(
+ jsonEncode(
+ fails
+ ? {
+ 'success': false,
+ 'error': {'message': 'Fixture unavailable'},
+ }
+ : {
+ 'success': true,
+ 'data': {
+ 'stale': stale,
+ 'machines': [
+ {'machineId': name, 'name': name, 'authMode': 'remote'},
+ ],
+ },
+ },
+ ),
+ );
+ await request.response.close();
+}
+
+void main() {
+ late HttpServer server;
+ late StreamSubscription<HttpRequest> subscription;
+ late _Requests requests;
+ late ApiClient api;
+ setUp(() async {
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ requests = _Requests();
+ subscription = server.listen(requests.receive);
+ api = ApiClient(
+ config: AppConfig(
+ localCliBaseUrl: 'http://127.0.0.1:${server.port}',
+ apiBaseUrl: 'http://unused.invalid',
+ ),
+ session: AuthSession(storage: MemoryStore()),
+ );
+ });
+ tearDown(() async {
+ await subscription.cancel();
+ await server.close(force: true);
+ });
+
+ test('overlapping inventories keep their own freshness and the latest sharing cache', () async {
+ final old = api.machines();
+ await _until(() => requests.machines.length == 1);
+ await _reply(requests.machines.first, 'owned-old');
+ await _until(() => requests.shares.length == 1);
+ final current = api.machines();
+ await _until(() => requests.machines.length == 2);
+ await _reply(requests.machines.last, 'owned-current', stale: true);
+ await _until(() => requests.shares.length == 2);
+ await _reply(requests.shares.last, 'shared-current');
+ final latest = await current as MachineInventory;
+ await _reply(requests.shares.first, 'shared-old');
+ final previous = await old as MachineInventory;
+ expect(previous.isStale, isFalse);
+ expect(latest.isStale, isTrue);
+ expect(api.lastMachinesStale, isTrue);
+ final fallback = api.machines();
+ await _until(() => requests.machines.length == 3);
+ await _reply(requests.machines.last, 'owned-next');
+ await _until(() => requests.shares.length == 3);
+ await _reply(requests.shares.last, 'unused', fails: true);
+ final snapshot = await fallback as MachineInventory;
+ expect(snapshot.map((m) => m.machineId), ['owned-next', 'shared-current']);
+ expect(snapshot.isStale, isTrue);
+ });
+
+ test('account reset stops an old request before it fetches sharing for the new account', () async {
+ final old = api.machines();
+ final rejected = expectLater(old, throwsStateError);
+ await _until(() => requests.machines.isNotEmpty);
+ api.resetAccountCache();
+ await _reply(requests.machines.single, 'old-owned');
+ await rejected;
+ expect(requests.shares, isEmpty);
+ expect(api.lastMachinesStale, isFalse);
+ });
+
+ test(
+ 'old sharing response cannot refill cache after an account reset',
+ () async {
+ final old = api.machines();
+ final rejected = expectLater(old, throwsStateError);
+ await _until(() => requests.machines.length == 1);
+ await _reply(requests.machines.first, 'old-owned');
+ await _until(() => requests.shares.length == 1);
+ api.resetAccountCache();
+ await _reply(requests.shares.first, 'old-shared');
+ await rejected;
+ final current = api.machines();
+ await _until(() => requests.machines.length == 2);
+ await _reply(requests.machines.last, 'new-owned');
+ await _until(() => requests.shares.length == 2);
+ await _reply(requests.shares.last, 'unused', fails: true);
+ final snapshot = await current as MachineInventory;
+ expect(snapshot.map((m) => m.machineId), ['new-owned']);
+ expect(snapshot.isStale, isTrue);
+ },
+ );
+}
diff --git a/desktop/test/machine_loading_test.dart b/desktop/test/machine_loading_test.dart
index 545107adf..2a611dc13 100644
--- a/desktop/test/machine_loading_test.dart
+++ b/desktop/test/machine_loading_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/terminal/terminal_session.dart';
import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/ws/ws_conn.dart';
@@ -38,8 +39,8 @@ const _capabilities = {
'available': true,
};
-class _Connection extends WsConn {
- _Connection()
+class DiscoveryConnection extends WsConn {
+ DiscoveryConnection()
: super(
wsBaseUrl: 'ws://fixture.invalid',
autonomousEnv: 'test',
@@ -57,6 +58,7 @@ class _Connection extends WsConn {
bool refuseTheme = false;
final timeouts = <String, Duration>{};
final sent = <String>[];
+ final frames = <({String type, Map<String, dynamic> payload})>[];
Completer<void>? readiness;
@override
@@ -97,6 +99,7 @@ class _Connection extends WsConn {
Map<String, dynamic> payload,
) async {
sent.add(type);
+ frames.add((type: type, payload: Map.of(payload)));
return true;
}
}
@@ -107,10 +110,12 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late AppNotifier app;
late MachineState machine;
- late _Connection connection;
+ late DiscoveryConnection connection;
+ late bool disposed;
setUp(() {
- connection = _Connection();
+ disposed = false;
+ connection = DiscoveryConnection();
app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
@@ -120,7 +125,9 @@ void main() {
app.machines = [_machine];
app.machineStates['m'] = machine;
});
- tearDown(() => app.dispose());
+ tearDown(() {
+ if (!disposed) app.dispose();
+ });
test('agent inventory and capabilities are requested together', () async {
final load = app.reloadMachineData('m');
@@ -271,6 +278,166 @@ void main() {
expect(app.panes, isEmpty);
});
+ for (final oldFails in [false, true]) {
+ test(
+ 'reconnect replaces pending capability discovery (old failure=$oldFails)',
+ () async {
+ final old = app.reloadMachineData('m');
+ await _tick();
+ connection.agents.single.complete(_agents);
+ await _tick();
+ app.onMachineConnectedForTest('m');
+ await _tick();
+ expect(connection.agents, hasLength(2));
+ expect(connection.capabilities, hasLength(2));
+ connection.agents.last.complete(_agents);
+ connection.capabilities.last.complete({
+ ..._capabilities,
+ 'features': {'imagePaste': true},
+ });
+ await machine.agentsLoadInFlight;
+ if (oldFails) {
+ connection.capabilities.first.completeError(StateError('old daemon'));
+ } else {
+ connection.capabilities.first.complete({'available': false});
+ }
+ await old;
+ expect(machine.terminalCapabilityAvailable, isTrue);
+ expect(machine.terminalImagePasteAvailable, isTrue);
+ expect(machine.terminalCapabilityError, isNull);
+ expect(machine.agentsLoadError, isNull);
+ },
+ );
+ }
+
+ test(
+ 'an old inventory timeout cannot mark a reconnected machine offline',
+ () async {
+ final old = app.reloadMachineData('m');
+ await _tick();
+ app.onMachineConnectedForTest('m');
+ await _tick();
+ connection.agents.first.completeError(
+ const WsRequestTimeout('agents_list'),
+ );
+ connection.capabilities.first.complete(_capabilities);
+ await old;
+ await _tick();
+ expect(machine.nodeOnline, isTrue);
+ expect(machine.agentsLoadError, isNull);
+ expect(
+ machine.agentsRefreshing ||
+ machine.agentLoadStatus == AgentLoadStatus.loading,
+ isTrue,
+ );
+ },
+ );
+
+ test('an offline transition invalidates a pending agent inventory', () async {
+ final old = app.reloadMachineData('m');
+ await _tick();
+ await app.handleEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': false},
+ });
+ connection.agents.first.complete(_agents);
+ connection.capabilities.first.complete(_capabilities);
+ await old;
+ expect(machine.nodeOnline, isFalse);
+ expect(machine.agents, isEmpty);
+ expect(machine.terminalCapabilityAvailable, isFalse);
+ expect(machine.agentsRefreshing, isFalse);
+ });
+
+ testWidgets(
+ 'an old background inventory cannot overwrite reconnect discovery',
+ (tester) async {
+ try {
+ app.onMachineConnectedForTest('m');
+ await tester.pump();
+ connection.agents.single.complete(_agents);
+ connection.capabilities.single.complete(_capabilities);
+ await tester.pump();
+ await tester.pump(AppNotifier.agentSyncInterval);
+ expect(connection.agents, hasLength(2));
+ final oldPoll = connection.agents.last;
+ app.onMachineConnectedForTest('m');
+ await tester.pump();
+ connection.agents.last.complete({
+ 'agents': [
+ {'id': 'new-agent', 'name': 'New agent', 'engine': 'codex'},
+ ],
+ });
+ connection.capabilities.last.complete(_capabilities);
+ await tester.pump();
+ expect(machine.agents.single.id, 'new-agent');
+ oldPoll.complete(_agents);
+ await tester.pump();
+ expect(machine.agents.single.id, 'new-agent');
+ } finally {
+ app.dispose();
+ disposed = true;
+ }
+ },
+ );
+
+ test(
+ 'a replacement connection releases its old terminal stream immediately',
+ () async {
+ final session =
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Fixture',
+ engineId: 'codex',
+ send: connection.sendTerminalFrame,
+ sendBinary: (_) async => true,
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'old-stream';
+ session.terminal.write('Keep this output');
+ final renderer = session.terminal;
+ final pane = app.adoptSessionForTest(session);
+ app.onMachineConnectedForTest('m');
+ await _tick();
+ expect(pane.session, same(session));
+ expect(session.terminal, same(renderer));
+ expect(session.terminal.buffer.getText(), contains('Keep this output'));
+ expect(session.streamId, isNull);
+ expect(session.status, TerminalSessionStatus.error);
+ },
+ );
+
+ test(
+ 'a second reconnect does not wait for the first pending recovery',
+ () async {
+ machine.nodeOnline = false;
+ machine.pendingOfflineAgentId = 'a';
+ Future<void> online(bool value) => app.handleEventForTest('m', {
+ 'type': 'node_status',
+ 'payload': {'online': value},
+ });
+ await online(true);
+ await _tick();
+ expect(connection.agents, hasLength(1));
+ await online(false);
+ await online(true);
+ await _tick();
+ expect(connection.agents, hasLength(2));
+ expect(connection.capabilities, hasLength(2));
+ connection.agents.last.complete(_agents);
+ connection.capabilities.last.complete(_capabilities);
+ await _tick();
+ expect(machine.pendingOfflineAgentId, isNull);
+ connection.agents.first.complete({'agents': []});
+ connection.capabilities.first.complete({'available': false});
+ await _tick();
+ expect(machine.agents.single.id, 'a');
+ expect(machine.terminalCapabilityAvailable, isTrue);
+ expect(machine.pendingOfflineAgentId, isNull);
+ },
+ );
+
group('pane colours reach the daemon', () {
tearDown(() {
grid.AppTheme.palette.value = HarnessPalette.graphite;
diff --git a/desktop/test/machine_tree_widget_test.dart b/desktop/test/machine_tree_widget_test.dart
index 66b1ab71f..9a10c52f0 100644
--- a/desktop/test/machine_tree_widget_test.dart
+++ b/desktop/test/machine_tree_widget_test.dart
@@ -24,8 +24,9 @@ class ReloadTrackingNotifier extends AppNotifier {
Future<void> ensureCliDaemonReady() async {}
@override
- Future<void> refreshMachines() async {
+ Future<bool> refreshMachines() async {
machineRefreshes++;
+ return true;
}
@override
@@ -174,11 +175,10 @@ void main() {
);
await tester.pump();
- expect(find.text('New Harness…'), findsOneWidget);
+ expect(find.text('New Harness'), findsOneWidget);
expect(find.text('no running agents'), findsNothing);
- // The old button read "New agent" flat, and it is the ellipsis that promises a dialog rather than an
- // agent appearing on the spot.
- expect(find.text('New Harness'), findsNothing);
+ // Keep one quiet list action rather than the old prominent button.
+ expect(find.widgetWithText(TextButton, 'New Harness'), findsNothing);
});
testWidgets('a machine that HAS agents is offered the same row, last', (
@@ -198,9 +198,9 @@ void main() {
await tester.pump();
expect(find.text('backend-api'), findsOneWidget);
- expect(find.text('New Harness…'), findsOneWidget);
+ expect(find.text('New Harness'), findsOneWidget);
// …and LAST, because a row that would create the next agent has to stand where the next agent would.
- final rowY = tester.getTopLeft(find.text('New Harness…')).dy;
+ final rowY = tester.getTopLeft(find.text('New Harness')).dy;
for (final name in ['backend-api', 'future-worker', 'herdr-session']) {
expect(
tester.getTopLeft(find.text(name)).dy,
diff --git a/desktop/test/machines_manager_keyboard_test.dart b/desktop/test/machines_manager_keyboard_test.dart
new file mode 100644
index 000000000..3e3a05981
--- /dev/null
+++ b/desktop/test/machines_manager_keyboard_test.dart
@@ -0,0 +1,423 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keymap_host.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/machines_manager.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'support/machine_api.dart';
+import 'support/password_cli.dart';
+
+class _App extends AppNotifier {
+ _App()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: PasswordCli(),
+ ) {
+ api = edits;
+ }
+ final edits = MachineApi();
+ int refreshes = 0;
+ Completer<void>? refresh;
+ String? refreshError;
+ @override
+ String? get machineListError => refreshError;
+ @override
+ Future<void> retryMachines() {
+ refreshes++;
+ return refresh?.future ?? Future.value();
+ }
+
+ void add(
+ String id,
+ String name, {
+ bool local = false,
+ bool? online = true,
+ bool needsLink = false,
+ bool shared = false,
+ }) {
+ final machine = Machine(
+ machineId: id,
+ authMode: MachineAuthMode.remote,
+ name: name,
+ hostname: '$id.local',
+ isShared: shared,
+ ownerName: shared ? 'Fixture Owner' : null,
+ );
+ machineStates[id] = MachineState(machine)
+ ..localOnly = local
+ ..nodeOnline = online
+ ..needsLink = needsLink;
+ machines = machineStates.values.map((state) => state.machine).toList();
+ notifyListeners();
+ }
+
+ void forget(String id) {
+ machineStates.remove(id);
+ machines.removeWhere((machine) => machine.machineId == id);
+ notifyListeners();
+ }
+}
+
+final _search = find.byKey(const Key('machines-manager-search'));
+final _rename = find.byKey(const Key('machine-rename-input'));
+TextField _field(WidgetTester tester, Finder finder) =>
+ tester.widget<TextField>(finder);
+
+Future<void> _mount(
+ WidgetTester tester,
+ _App app, {
+ AppKeymap? keymap,
+ Size size = const Size(1000, 700),
+ double scale = 1,
+}) async {
+ tester.view.physicalSize = size;
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final opener = Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showMachinesManager(context, app),
+ child: const Text('open'),
+ ),
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: keymap == null
+ ? opener
+ : KeymapProvider(
+ keymap: keymap,
+ child: KeymapHost(
+ keymap: keymap,
+ enabled: () => false,
+ actions: const {},
+ child: opener,
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+}
+
+Future<void> _typeOpen(WidgetTester tester, String query) async {
+ tester.testTextInput.enterText(query);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ late _App app;
+ setUp(() => app = _App());
+ tearDown(() => app.dispose());
+
+ testWidgets(
+ 'search finds hostnames, retains query across actions and keeps stable selection',
+ (tester) async {
+ app.add('work', 'Workstation', local: true);
+ app.add('build-10', 'Build 10');
+ app.add('build-2', 'Build 2', online: false, needsLink: true);
+ await _mount(tester, app);
+ expect(_field(tester, _search).focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.keyN, ctrl: true);
+ app.add('build-1', 'Build 1');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Build 2'), findsOneWidget);
+ expect(find.textContaining('offline · link required'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ tester.testTextInput.enterText('build-10.local');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Build 10'), findsOneWidget);
+ expect(find.text('Rename'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_field(tester, _search).controller!.text, 'build-10.local');
+ expect(_field(tester, _search).focusNode!.hasFocus, isTrue);
+ },
+ );
+
+ testWidgets(
+ 'rename focuses selected text, handles errors and rejoins a pending save',
+ (tester) async {
+ app.add('work', 'Workstation');
+ await _mount(tester, app);
+ await _typeOpen(tester, 'work');
+ await _typeOpen(tester, 'rename');
+ expect(_field(tester, _rename).focusNode!.hasFocus, isTrue);
+ expect(
+ _field(tester, _rename).controller!.selection,
+ const TextSelection(baseOffset: 0, extentOffset: 11),
+ );
+ expect(_search, findsNothing); // One visible prompt.
+ tester.testTextInput.enterText(' ');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(app.edits.renames, isEmpty);
+ app.edits.renameFailure = ApiException('Connection unavailable');
+ tester.testTextInput.enterText('Office');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Connection unavailable'), findsOneWidget);
+ expect(_field(tester, _rename).focusNode!.hasFocus, isTrue);
+ app.edits.renameFailure = null;
+ app.edits.renameReply = Completer<String?>();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_field(tester, _rename).readOnly, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.edits.renames, hasLength(2));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_field(tester, _search).controller!.text, 'rename');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_field(tester, _rename).controller!.text, 'Office');
+ expect(_field(tester, _rename).readOnly, isTrue);
+ expect(app.edits.renames, hasLength(2));
+ app.edits.renameReply!.complete('Office');
+ await tester.pumpAndSettle();
+ expect(find.text('Office'), findsOneWidget);
+ expect(_field(tester, _search).controller!.text, 'rename');
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_field(tester, _search).controller!.text, 'work');
+ },
+ );
+
+ testWidgets(
+ 'delete starts on Cancel, reports failure, and resumes one pending request',
+ (tester) async {
+ app.add('work', 'Workstation');
+ await _mount(tester, app);
+ await _typeOpen(tester, 'work');
+ await _typeOpen(tester, 'delete');
+ expect(find.text('Delete machine'), findsOneWidget);
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Cancel'))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.edits.deletes, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ app.edits.deleteFailure = ApiException('Account unavailable');
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Delete failed: Account unavailable'), findsOneWidget);
+ expect(app.stateOf('work'), isNotNull);
+ app.edits.deleteFailure = null;
+ app.edits.deleteReply = Completer<void>();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Deleting machine…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Deleting machine…'), findsOneWidget);
+ expect(app.edits.deletes, ['work', 'work']);
+ app.edits.deleteReply!.complete();
+ await tester.pumpAndSettle();
+ expect(app.stateOf('work'), isNull);
+ expect(find.text('Machines Manager'), findsOneWidget);
+ expect(find.text('Workstation deleted.'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'refresh keeps query and active machine while errors are recoverable',
+ (tester) async {
+ app.add('work', 'Workstation');
+ await _mount(tester, app);
+ tester.testTextInput.enterText('work');
+ app.refresh = Completer<void>();
+ final ctrl =
+ Theme.of(tester.element(_search)).platform != TargetPlatform.macOS;
+ await key(tester, LogicalKeyboardKey.keyR, ctrl: ctrl, cmd: !ctrl);
+ await key(tester, LogicalKeyboardKey.keyR, ctrl: ctrl, cmd: !ctrl);
+ expect(app.refreshes, 1);
+ expect(_field(tester, _search).controller!.text, 'work');
+ expect(_field(tester, _search).focusNode!.hasFocus, isTrue);
+ app.refreshError = 'Connection unavailable';
+ app.refresh!.complete();
+ await tester.pumpAndSettle();
+ expect(find.text('Connection unavailable'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ app.refresh = null;
+ app.refreshError = null;
+ await key(tester, LogicalKeyboardKey.keyR, ctrl: ctrl, cmd: !ctrl);
+ await tester.pumpAndSettle();
+ expect(find.text('Connection unavailable'), findsNothing);
+ app.forget('work');
+ await tester.pump();
+ expect(find.text('This machine is no longer available.'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.edits.deletes, isEmpty);
+ expect(app.edits.renames, isEmpty);
+ },
+ variant: TargetPlatformVariant({
+ TargetPlatform.macOS,
+ TargetPlatform.linux,
+ }),
+ );
+
+ testWidgets(
+ 'local and shared machine actions expose their actual capabilities',
+ (tester) async {
+ app.add('work', 'Workstation', local: true);
+ app.add('shared', 'Shared builder', shared: true);
+ await _mount(tester, app);
+ await _typeOpen(tester, 'work');
+ expect(find.text('This computer’s password'), findsOneWidget);
+ expect(find.text('Delete machine…'), findsNothing);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await _typeOpen(tester, 'shared');
+ expect(find.textContaining('view-only. Their owner'), findsOneWidget);
+ expect(find.text('Rename'), findsNothing);
+ expect(find.text('Delete machine…'), findsNothing);
+ expect(app.edits.renames, isEmpty);
+ },
+ );
+
+ testWidgets('link entry returns to the same action query and machine', (
+ tester,
+ ) async {
+ app.add('build', 'Build box', needsLink: true);
+ await _mount(tester, app);
+ await _typeOpen(tester, 'build');
+ await _typeOpen(tester, 'link');
+ final password = find.byKey(const Key('remote-password-connect-field'));
+ expect(_field(tester, password).focusNode!.hasFocus, isTrue);
+ expect(_search, findsNothing);
+ tester.testTextInput.enterText('fixture password');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(app.stateOf('build')!.needsLink, isFalse);
+ expect(_field(tester, _search).controller!.text, 'link');
+ expect(find.text('Build box'), findsOneWidget);
+ expect(find.text('Build box linked.'), findsOneWidget);
+ expect(_field(tester, _search).focusNode!.hasFocus, isTrue);
+ });
+
+ testWidgets(
+ 'custom keys own nested prompts and composition keeps Enter and Escape',
+ (tester) async {
+ app.add('work', 'Workstation');
+ final map = MemoryKeymap()
+ ..apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"}
+ ]}''');
+ addTearDown(map.dispose);
+ await _mount(tester, app, keymap: map);
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Machines Manager'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.f8);
+ await tester.pumpAndSettle();
+ expect(_rename, findsOneWidget);
+ final text = _field(tester, _rename).controller!;
+ text.value = const TextEditingValue(
+ text: 'Office',
+ selection: TextSelection.collapsed(offset: 6),
+ composing: TextRange(start: 0, end: 6),
+ );
+ await key(tester, LogicalKeyboardKey.f8);
+ await key(tester, LogicalKeyboardKey.f7);
+ expect(_rename, findsOneWidget);
+ expect(app.edits.renames, isEmpty);
+ text.clearComposing();
+ map.apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"f10","command":"picker.accept","when":"picker"},
+ {"keys":"f4","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(
+ find.textContaining(RegExp('f10 save', caseSensitive: false)),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.edits.renames, isEmpty);
+ await key(tester, LogicalKeyboardKey.f10);
+ await tester.pumpAndSettle();
+ expect(app.edits.renames, [('work', 'Office')]);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(find.text('Machines Manager'), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'short windows and long machine names keep search and back in view',
+ (tester) async {
+ app.add(
+ 'long-machine-id-0123456789',
+ 'A very long machine name used for remote feature builds',
+ online: false,
+ );
+ for (var i = 1; i < 22; i++) {
+ app.add('build-$i', 'Build $i');
+ }
+ await _mount(tester, app, size: const Size(480, 360), scale: 1.7);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(tester.takeException(), isNull);
+ tester.testTextInput.enterText('long-machine');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_search.hitTestable(), findsOneWidget);
+ expect(find.text('esc back').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await _typeOpen(tester, 'rename');
+ expect(_rename.hitTestable(), findsOneWidget);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'the footer action activates without recursively dispatching itself',
+ (tester) async {
+ app.add('work', 'Workstation');
+ await _mount(tester, app, keymap: MemoryKeymap());
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Rename'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
+ );
+}
diff --git a/desktop/test/machines_manager_test.dart b/desktop/test/machines_manager_test.dart
index 5b2ea0616..5d40dec6d 100644
--- a/desktop/test/machines_manager_test.dart
+++ b/desktop/test/machines_manager_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/terminal/terminal_binary.dart';
import 'package:xterm/xterm.dart';
import 'keymap_runtime_test.dart' show native;
+import 'keymap_host_test.dart' show key;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
@@ -61,6 +62,8 @@ void main() {
await tester.pumpAndSettle();
await opened;
expect(find.text('Machines Manager'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
await tester.tap(find.text('Rename'));
await tester.pumpAndSettle();
expect(find.text('Rename Machine'), findsOneWidget);
@@ -72,17 +75,19 @@ void main() {
expect(api.calls, isEmpty);
await tester.enterText(field, ' Office Mac ');
if (fail) api.error = 'Connection unavailable';
- await tester.tap(find.text('Save'));
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(api.calls, [('m', 'Office Mac')]);
if (fail) {
expect(find.textContaining('Connection unavailable'), findsOneWidget);
expect(app.stateOf('m')!.machine.displayName, isNot('Office Mac'));
api.error = null;
- await tester.tap(find.text('Save'));
+ await key(tester, LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
}
expect(find.text('Rename Machine'), findsNothing);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
expect(
find.descendant(
of: find.byKey(const ValueKey('managed-machine-m')),
@@ -92,7 +97,7 @@ void main() {
);
expect(app.machines.single.displayName, 'Office Mac');
expect((updates.last['machines'] as List).single['name'], 'Office Mac');
- await tester.tap(find.text('Done'));
+ await key(tester, LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
expect(find.text('Machines Manager'), findsNothing);
expect(
diff --git a/desktop/test/machines_menu_test.dart b/desktop/test/machines_menu_test.dart
index 37dba2ad7..bd80a9d55 100644
--- a/desktop/test/machines_menu_test.dart
+++ b/desktop/test/machines_menu_test.dart
@@ -320,7 +320,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 300));
await reply.future;
expect(find.text('Delete machine'), findsOneWidget);
- expect(find.widgetWithText(FilledButton, 'Delete'), findsOneWidget);
+ expect(find.byKey(const Key('machine-delete-confirm')), findsOneWidget);
// Cancelling leaves the machine in place.
await tester.tap(find.text('Cancel'));
@@ -370,7 +370,7 @@ void main() {
expect(find.text('Delete machine'), findsOneWidget);
// Confirming drops the machine from the client and the API.
- await tester.tap(find.widgetWithText(FilledButton, 'Delete'));
+ await tester.tap(find.byKey(const Key('machine-delete-confirm')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(api.deleted, ['m']);
diff --git a/desktop/test/manual_update_check_test.dart b/desktop/test/manual_update_check_test.dart
new file mode 100644
index 000000000..4e88b0b02
--- /dev/null
+++ b/desktop/test/manual_update_check_test.dart
@@ -0,0 +1,499 @@
+import 'dart:async';
+
+import 'package:dio/dio.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/settings/sections/about_section.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/update/desktop_updater.dart';
+import 'package:harness/update/manual_update_check.dart';
+import 'package:harness/viewer/viewer_services.dart';
+import 'package:harness/widgets/update_notice.dart';
+
+// Every request stops in this interceptor. No socket, download, or user file
+// is involved; a held response lets two entry points ask at the same time.
+class _Manifest {
+ final requests = <(RequestOptions, RequestInterceptorHandler)>[];
+ late final dio = Dio()
+ ..interceptors.add(
+ InterceptorsWrapper(
+ onRequest: (options, handler) {
+ requests.add((options, handler));
+ },
+ ),
+ );
+
+ DesktopUpdater updater({bool enabled = true, bool releaseMode = true}) =>
+ DesktopUpdater(
+ enabled: enabled,
+ dio: dio,
+ releaseMode: releaseMode,
+ isLinux: false,
+ architecture: 'x64',
+ metadataUrl: 'https://updates.example.test/metadata.json',
+ );
+
+ Future<void> waitForRequest(WidgetTester tester) async {
+ for (var i = 0; i < 20 && requests.isEmpty; i++) {
+ await tester.pump(const Duration(milliseconds: 1));
+ }
+ expect(requests, isNotEmpty);
+ }
+
+ void answer({String version = '1.0.4', Map<String, dynamic>? data}) {
+ final (options, handler) = requests.removeAt(0);
+ handler.resolve(
+ Response(
+ requestOptions: options,
+ data:
+ data ??
+ <String, dynamic>{
+ 'desktop-macos': {
+ 'version': version,
+ 'url': 'https://updates.example.test/Harness.zip',
+ 'sha256': 'a' * 64,
+ 'size': 1024,
+ },
+ },
+ ),
+ );
+ }
+
+ void fail() {
+ final (options, handler) = requests.removeAt(0);
+ handler.reject(
+ DioException(
+ requestOptions: options,
+ type: DioExceptionType.connectionError,
+ ),
+ );
+ }
+}
+
+class _Installer extends DesktopUpdater {
+ _Installer() : super(enabled: false);
+ final staged = Completer<StagedUpdate?>();
+ UpdateInfo? requested;
+
+ @override
+ Future<StagedUpdate?> downloadAndStage(UpdateInfo info) {
+ requested = info;
+ return staged.future;
+ }
+}
+
+const _reviewedUpdate = UpdateInfo(
+ version: '1.0.4',
+ url: 'https://updates.example.test/1.0.4.zip',
+ sha256: 'unused',
+ size: 1024,
+);
+const _laterUpdate = UpdateInfo(
+ version: '1.0.5',
+ url: 'https://updates.example.test/1.0.5.zip',
+ sha256: 'unused',
+ size: 1024,
+);
+
+void main() {
+ setUp(() {
+ PackageInfo.setMockInitialValues(
+ appName: 'Harness',
+ packageName: 'ai.autonomous.harness',
+ version: '1.0.0',
+ buildNumber: '1',
+ buildSignature: '',
+ );
+ });
+
+ AppNotifier appFor(_Manifest manifest) {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: manifest.updater(),
+ );
+ addTearDown(app.dispose);
+ return app;
+ }
+
+ testWidgets('viewer builds never contact the desktop update service', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final session = AuthSession();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ viewer: ViewerServices(config: AppConfig.dev, session: session),
+ desktopUpdater: manifest.updater(),
+ );
+ addTearDown(app.dispose);
+ expect(app.updateChecksEnabled, isFalse);
+ expect(
+ (await app.checkForUpdates()).status,
+ DesktopUpdateCheckStatus.disabled,
+ );
+ expect(manifest.requests, isEmpty);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(body: AboutSection(notifier: app)),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Updates off'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('two manual checks wait for the same answer', (tester) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ final first = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ var secondFinished = false;
+ final second = app.checkForUpdates().then((result) {
+ secondFinished = true;
+ return result;
+ });
+ await tester.pump();
+ final answeredEarly = secondFinished;
+ expect(manifest.requests, hasLength(1));
+ manifest.answer();
+ await tester.pump();
+ expect(
+ answeredEarly,
+ isFalse,
+ reason: 'A second entry point must not report a stale answer.',
+ );
+ expect((await first).update?.version, '1.0.4');
+ expect((await second).update?.version, '1.0.4');
+ });
+
+ testWidgets('an unreachable update service is not up to date', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ final check = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.fail();
+ await tester.pump();
+ final result = await check;
+ expect(result.isUpToDate, isFalse);
+ });
+
+ testWidgets('the manual result explains a failed check', (tester) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.dark),
+ home: const Scaffold(body: Placeholder()),
+ ),
+ );
+ final check = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.fail();
+ await tester.pump();
+ final result = await check;
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ result,
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Couldn’t check for updates'), findsOneWidget);
+ expect(find.text('You’re up to date'), findsNothing);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await dialog;
+ });
+
+ testWidgets(
+ 'About can retry a failed check and report the recovered result',
+ (tester) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(body: AboutSection(notifier: app)),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Not checked'), findsOneWidget);
+ expect(find.text('Up to date'), findsNothing);
+ final button = find.byKey(const Key('settings-check-updates-button'));
+ await tester.tap(button);
+ await manifest.waitForRequest(tester);
+ final menuCheck = checkForUpdatesAndShowResult(
+ tester.element(find.byType(AboutSection)),
+ app,
+ );
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(manifest.requests, hasLength(1));
+ expect(app.isCheckingForUpdate, isTrue);
+ manifest.fail();
+ await tester.pumpAndSettle();
+ expect(find.text('Check failed'), findsOneWidget);
+ expect(find.text('Couldn’t check for updates'), findsOneWidget);
+ expect(find.byType(Dialog), findsOneWidget);
+ await tester.tap(find.text('Retry'));
+ await manifest.waitForRequest(tester);
+ expect(find.text('Checking for updates…'), findsOneWidget);
+ manifest.answer(version: '1.0.0');
+ await tester.pumpAndSettle();
+ expect(find.text('You’re up to date'), findsOneWidget);
+ expect(find.text('Up to date'), findsOneWidget);
+ expect(app.isCheckingForUpdate, isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await menuCheck;
+ expect(find.byType(Dialog), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets('closing a retry leaves no late dialog behind', (tester) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ const ManualUpdateCheck(check: DesktopUpdateCheck.failed()),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Retry'));
+ await manifest.waitForRequest(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ await dialog;
+ manifest.answer();
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ expect(app.availableUpdate?.version, '1.0.4');
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('manual and background checks share the request', (tester) async {
+ final manifest = _Manifest();
+ final updater = manifest.updater();
+ final observed = <DesktopUpdateCheck>[];
+ final timer = updater.startChecking(onCheckCompleted: observed.add);
+ addTearDown(timer.cancel);
+ await manifest.waitForRequest(tester);
+ final manual = updater.check();
+ await tester.pump(const Duration(milliseconds: 1));
+ expect(manifest.requests, hasLength(1));
+ manifest.answer();
+ await tester.pump();
+ expect((await manual).update?.version, '1.0.4');
+ expect(observed.single.update?.version, '1.0.4');
+ timer.cancel();
+ });
+
+ testWidgets(
+ 'background checks wait six hours, avoid overlap, and stop after cancellation',
+ (tester) async {
+ final manifest = _Manifest();
+ final observed = <DesktopUpdateCheck>[];
+ final timer = manifest.updater().startChecking(
+ onCheckCompleted: observed.add,
+ );
+ addTearDown(timer.cancel);
+ await manifest.waitForRequest(tester);
+ manifest.answer(version: '1.0.0');
+ await tester.pump();
+ expect(observed, hasLength(1));
+ await tester.pump(const Duration(hours: 5, minutes: 59));
+ expect(manifest.requests, isEmpty);
+ await tester.pump(const Duration(minutes: 1));
+ await manifest.waitForRequest(tester);
+ await tester.pump(const Duration(hours: 12));
+ expect(manifest.requests, hasLength(1));
+ expect(observed, hasLength(1));
+ timer.cancel();
+ manifest.answer();
+ await tester.pump();
+ expect(
+ observed,
+ hasLength(1),
+ reason: 'Cancelled pollers cannot publish late replies.',
+ );
+ },
+ );
+
+ for (final disabled in [true, false]) {
+ testWidgets(
+ '${disabled ? 'Disabled' : 'Development'} builds do not claim to be current',
+ (tester) async {
+ final manifest = _Manifest();
+ final result = await manifest
+ .updater(enabled: !disabled, releaseMode: disabled)
+ .check(currentVersion: '1.0.0');
+ expect(result.status, DesktopUpdateCheckStatus.disabled);
+ expect(manifest.requests, isEmpty);
+ expect(ManualUpdateCheck(check: result).isUpToDate, isFalse);
+ },
+ );
+ }
+
+ for (final invalid in ['missing platform', 'invalid version']) {
+ testWidgets('a manifest with $invalid is not an all-clear', (tester) async {
+ final manifest = _Manifest();
+ final check = manifest.updater().check(currentVersion: '1.0.0');
+ await manifest.waitForRequest(tester);
+ manifest.answer(
+ data: invalid == 'missing platform' ? {} : null,
+ version: 'not-a-version',
+ );
+ await tester.pump();
+ expect((await check).status, DesktopUpdateCheckStatus.failed);
+ });
+ }
+
+ testWidgets('manual checks can offer a skipped version again', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ final first = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.answer();
+ await tester.pump();
+ expect((await first).isSkipped, isFalse);
+ await app.skipAvailableUpdate();
+ expect(app.availableUpdate, isNull);
+ final again = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.answer();
+ await tester.pump();
+ expect((await again).isSkipped, isTrue);
+ expect(app.availableUpdate?.version, '1.0.4');
+ });
+
+ testWidgets('a failed recheck keeps the known offer and install error', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ final first = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.answer();
+ await tester.pump();
+ await first;
+ app.updateError = 'Could not download this version.';
+ final next = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.fail();
+ await tester.pump();
+ expect((await next).status, DesktopUpdateCheckStatus.failed);
+ expect(app.availableUpdate?.version, '1.0.4');
+ expect(app.updateError, 'Could not download this version.');
+ });
+
+ testWidgets('a valid current manifest clears a withdrawn offer', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final app = appFor(manifest);
+ final first = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.answer();
+ await tester.pump();
+ await first;
+ final next = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ manifest.answer(version: '1.0.0');
+ await tester.pump();
+ expect((await next).isUpToDate, isTrue);
+ expect(app.availableUpdate, isNull);
+ });
+
+ testWidgets('a disposed app ignores an in-flight update result', (
+ tester,
+ ) async {
+ final manifest = _Manifest();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: manifest.updater(),
+ );
+ final check = app.checkForUpdates();
+ await manifest.waitForRequest(tester);
+ app.dispose();
+ manifest.answer();
+ await tester.pump();
+ await check;
+ expect(app.availableUpdate, isNull);
+ expect(app.lastUpdateCheck, isNull);
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets(
+ 'Update uses the reviewed version and stays open during installation',
+ (tester) async {
+ final installer = _Installer();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ desktopUpdater: installer,
+ )..availableUpdate = _reviewedUpdate;
+ addTearDown(app.dispose);
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ const ManualUpdateCheck(
+ check: DesktopUpdateCheck.available(_reviewedUpdate),
+ ),
+ );
+ await tester.pumpAndSettle();
+ // A newer background result must not change what the visible action does.
+ app.availableUpdate = _laterUpdate;
+ await tester.tap(find.text('Update'));
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 200));
+ final stayedOpen = find.byType(Dialog).evaluate().length == 1;
+ installer.staged.complete(null);
+ await tester.pumpAndSettle();
+ await dialog;
+ expect(stayedOpen, isTrue);
+ expect(installer.requested?.version, '1.0.4');
+ expect(app.updateError, contains('1.0.4'));
+ expect(app.availableUpdate?.version, '1.0.4');
+ expect(find.byType(Dialog), findsNothing);
+ },
+ );
+
+ testWidgets('Skip uses the reviewed version without hiding a newer offer', (
+ tester,
+ ) async {
+ final app = appFor(_Manifest())..availableUpdate = _reviewedUpdate;
+ await tester.pumpWidget(const MaterialApp(home: Placeholder()));
+ final dialog = showUpdateCheckDialog(
+ tester.element(find.byType(Placeholder)),
+ app,
+ const ManualUpdateCheck(
+ check: DesktopUpdateCheck.available(_reviewedUpdate),
+ ),
+ );
+ await tester.pumpAndSettle();
+ app.availableUpdate = _laterUpdate;
+ await tester.tap(find.text('Skip 1.0.4'));
+ await tester.pumpAndSettle();
+ await dialog;
+ expect(app.availableUpdate?.version, '1.0.5');
+ });
+}
diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dart
index f2f7b5085..a7a5df2cc 100644
--- a/desktop/test/models_menu_test.dart
+++ b/desktop/test/models_menu_test.dart
@@ -12,21 +12,26 @@ import 'package:harness/core/config.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
import 'package:harness/state/swarm_catalog.dart';
import 'package:harness/usage/models_menu_controller.dart';
import 'package:harness/usage/usage_accounts.dart';
import 'package:harness/usage/usage_controller.dart';
import 'package:harness/usage/usage_source.dart';
import 'package:harness/usage/usage_window.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
+import 'keymap_host_test.dart' show key;
/// Stands in for the machine behind the Open Grid door: the probes New Agent
/// makes answer at once, and the harness list says whether Grid is installed
/// there. Nothing is created — the door's job ends when New Agent is open on
/// the right machine with Grid chosen, or the Store is open on Grid's page.
class _GridApp extends AppNotifier {
- _GridApp({required this.grid})
+ _GridApp({required this.grid, this.harness = AppNotifier.gridHarness})
: super(
config: AppConfig.dev,
authSession: AuthSession(),
@@ -38,6 +43,7 @@ class _GridApp extends AppNotifier {
/// Per machine: true = Grid installed, false = listed but not installed,
/// absent = the machine never heard of it.
final Map<String, bool> grid;
+ final String harness;
@override
Future<void> probeEngines(String machineId, {bool force = false}) async {}
@@ -48,8 +54,10 @@ class _GridApp extends AppNotifier {
machineStates[machineId]!.dsh.replace([
if (installed != null)
DshEntry(
- id: AppNotifier.gridHarness,
- name: 'Grid',
+ id: harness,
+ name: harness == AppNotifier.machinesHarness
+ ? 'Machine Monitor'
+ : 'Grid',
engine: 'codex',
description: 'Talk to your fleet.',
installed: installed,
@@ -68,8 +76,9 @@ class _GridApp extends AppNotifier {
_GridApp _gridApp({
required Map<String, bool> grid,
bool secondMachine = false,
+ String harness = AppNotifier.gridHarness,
}) {
- final app = _GridApp(grid: grid);
+ final app = _GridApp(grid: grid, harness: harness);
const machine = Machine(
machineId: 'm',
authMode: MachineAuthMode.remote,
@@ -343,6 +352,7 @@ void main() {
WidgetTester tester,
_GridApp app, {
String? machineId,
+ String command = 'runLocalModel',
}) async {
tester.view.physicalSize = const Size(1200, 900);
tester.view.devicePixelRatio = 1;
@@ -367,7 +377,7 @@ void main() {
channel.name,
const StandardMethodCodec().encodeMethodCall(
MethodCall(
- 'runLocalModel',
+ command,
machineId == null ? null : {'machineId': machineId},
),
),
@@ -376,6 +386,61 @@ void main() {
await tester.pumpAndSettle();
}
+ for (final (command, harness, stem, machineId) in [
+ ('runLocalModel', AppNotifier.gridHarness, 'grid', null),
+ ('runLocalModel', AppNotifier.gridHarness, 'grid', 'other'),
+ ('manageMachines', AppNotifier.machinesHarness, 'machine-monitor', null),
+ ]) {
+ testWidgets('native $command opens the product dock on $machineId', (
+ tester,
+ ) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = _gridApp(
+ grid: {'m': true, 'other': true},
+ secondMachine: true,
+ harness: harness,
+ );
+ addTearDown(app.dispose);
+ app.adoptSessionForTest(terminal('source', []));
+ final source = app.activeSwarm;
+ await openGridDoor(tester, app, machineId: machineId, command: command);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.engine, harness);
+ expect(box.machineId, machineId ?? 'm');
+ expect(box.projectLabel, startsWith('~/harnesses/$stem-'));
+ expect(box.placement, HarnessPlacement.newTab);
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(app.swarms, [source]);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.swarms, [source]);
+ if (command == 'manageMachines') {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> machine monitor',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller
+ .engine,
+ harness,
+ );
+ expect(app.swarms, [source]);
+ await key(tester, LogicalKeyboardKey.escape);
+ }
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 60));
+ });
+ }
+
testWidgets('native runLocalModel opens New Agent with Grid chosen', (
tester,
) async {
diff --git a/desktop/test/new_agent_choices_layout_test.dart b/desktop/test/new_agent_choices_layout_test.dart
index 117846959..00e3014b1 100644
--- a/desktop/test/new_agent_choices_layout_test.dart
+++ b/desktop/test/new_agent_choices_layout_test.dart
@@ -12,6 +12,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
import 'package:harness/shared/widgets/app_choice_picker.dart';
@@ -72,6 +73,7 @@ class _ChoicesApp extends AppNotifier {
String? name,
String? agent,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
createCalls++;
return null;
@@ -246,7 +248,8 @@ void main() {
}
expectUniformTiles();
- // The agent box, the tiles and the first-task box are one height.
+ // Choices are compact rows; the task can reserve room for its cursor
+ // and clear control without returning to a large card-sized field.
final tileHeight = tester
.getSize(find.byType(AppChoiceTile).first)
.height;
@@ -264,9 +267,12 @@ void main() {
),
)
.height,
- closeTo(tileHeight, 1),
+ inInclusiveRange(tileHeight - 1, tileHeight + 16),
+ );
+ expect(
+ tester.getSize(taskBox).height,
+ inInclusiveRange(tileHeight - 1, tileHeight + 16),
);
- expect(tester.getSize(taskBox).height, closeTo(tileHeight, 1));
expect(
find.text('First task. What should your agent work on? (Optional)'),
findsOneWidget,
@@ -303,6 +309,24 @@ void main() {
tester.getRect(find.byKey(const Key('new-agent-agent-panel'))).bottom,
lessThanOrEqualTo(size.height),
);
+ // Both lines must fit inside the row's selection background. A compact
+ // single-line extent allowed descriptions to paint into the next row.
+ final rows = find.descendant(
+ of: find.byKey(const Key('new-agent-agent-list')),
+ matching: find.byType(ListTile),
+ );
+ for (final row in rows.evaluate()) {
+ final finder = find.byWidget(row.widget);
+ final bounds = tester.getRect(finder);
+ for (final text
+ in find
+ .descendant(of: finder, matching: find.byType(RichText))
+ .evaluate()) {
+ final rect = tester.getRect(find.byWidget(text.widget));
+ expect(rect.top, greaterThanOrEqualTo(bounds.top - .1));
+ expect(rect.bottom, lessThanOrEqualTo(bounds.bottom + .1));
+ }
+ }
await capture('search-open');
await tester.enterText(agentSearch, 'openc');
await tester.pumpAndSettle();
diff --git a/desktop/test/new_agent_codex_profile_test.dart b/desktop/test/new_agent_codex_profile_test.dart
index 6672b47f8..be27a686a 100644
--- a/desktop/test/new_agent_codex_profile_test.dart
+++ b/desktop/test/new_agent_codex_profile_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/state/pane_layout_store.dart';
@@ -138,6 +139,7 @@ class _Notifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
calls.add({'engine': engine, 'codexHome': codexHome, 'folder': folder});
return null;
diff --git a/desktop/test/new_agent_dsh_test.dart b/desktop/test/new_agent_dsh_test.dart
index f70b3291e..b594c78f0 100644
--- a/desktop/test/new_agent_dsh_test.dart
+++ b/desktop/test/new_agent_dsh_test.dart
@@ -14,6 +14,7 @@ import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/agent_picker.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
@@ -111,6 +112,7 @@ class _Notifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add({
'machine': machineId,
diff --git a/desktop/test/new_agent_engine_check_test.dart b/desktop/test/new_agent_engine_check_test.dart
index cf9329b27..d21bb8718 100644
--- a/desktop/test/new_agent_engine_check_test.dart
+++ b/desktop/test/new_agent_engine_check_test.dart
@@ -20,6 +20,7 @@ import 'package:harness/core/config.dart';
import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/shared/widgets/app_choice_picker.dart';
@@ -96,7 +97,7 @@ void main() {
// be attempted and troubleshooting stays in the optional details.
expect(find.textContaining('Couldn’t check whether'), findsOneWidget);
expect(
- find.textContaining('You can still try creating the harness.'),
+ find.textContaining('You can still try starting the harness.'),
findsOneWidget,
);
expect(find.textContaining('uses an older Harness CLI'), findsNothing);
@@ -311,6 +312,7 @@ class _RetryNotifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add({
'machine': machineId,
diff --git a/desktop/test/new_agent_permission_mode_test.dart b/desktop/test/new_agent_permission_mode_test.dart
index 219bc9f49..071c9b279 100644
--- a/desktop/test/new_agent_permission_mode_test.dart
+++ b/desktop/test/new_agent_permission_mode_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/core/permission_modes.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
@@ -61,6 +62,7 @@ class _Notifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add({
'engine': engine,
@@ -146,19 +148,21 @@ void main() {
await tester.pump();
}
- testWidgets('Auto-approve is the default', (tester) async {
- final app = await open(tester);
- expect(
- find.descendant(of: field, matching: find.text('Auto-approve')),
- findsOneWidget,
- );
- await create(tester);
- expect(app.launches.single, {
- 'engine': 'claude',
- 'mode': 'auto',
- 'bypass': true,
+ for (final engine in ['claude', 'codex']) {
+ testWidgets('Auto-approve is the default for $engine', (tester) async {
+ final app = await open(tester, engine: engine);
+ expect(
+ find.descendant(of: field, matching: find.text('Auto-approve')),
+ findsOneWidget,
+ );
+ await create(tester);
+ expect(app.launches.single, {
+ 'engine': engine,
+ 'mode': 'auto',
+ 'bypass': true,
+ });
});
- });
+ }
testWidgets('the menu says what each Claude Code mode does', (tester) async {
await open(tester);
@@ -246,10 +250,14 @@ void main() {
});
});
- test('every engine with modes starts on Auto-approve and can ask', () {
+ test('every engine with modes offers Auto-approve and Ask first', () {
for (final MapEntry(key: engine, value: modes)
in kEnginePermissionModes.entries) {
- expect(modes.first.id, kDefaultPermissionMode, reason: engine);
+ expect(
+ modes.map((mode) => mode.id),
+ contains(kDefaultPermissionMode),
+ reason: engine,
+ );
expect(modes.map((mode) => mode.id), contains('ask'), reason: engine);
expect(
modes.map((mode) => mode.id).toSet(),
diff --git a/desktop/test/new_agent_project_picker_test.dart b/desktop/test/new_agent_project_picker_test.dart
index 0772cadd2..4c2522b4d 100644
--- a/desktop/test/new_agent_project_picker_test.dart
+++ b/desktop/test/new_agent_project_picker_test.dart
@@ -7,7 +7,9 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
+import 'package:harness/core/repository_clone.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
import 'package:harness/shared/widgets/app_choice_picker.dart';
@@ -74,6 +76,7 @@ class _App extends AppNotifier {
String? name,
String? agent,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
calls.add({
'machine': machineId,
@@ -87,7 +90,12 @@ class _App extends AppNotifier {
void main() {
late _App app;
- Future<void> mount(WidgetTester tester, {String? rememberedProject}) async {
+ Future<void> mount(
+ WidgetTester tester, {
+ String? rememberedProject,
+ String? initialFolder,
+ ProjectFolderRequest? initialProject,
+ }) async {
tester.view.devicePixelRatio = 1;
tester.view.physicalSize = const Size(1280, 1000);
addTearDown(tester.view.reset);
@@ -105,8 +113,14 @@ void main() {
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
- onPressed: () =>
- showNewAgentDialog(context, app, 'local', source: 'test'),
+ onPressed: () => showNewAgentDialog(
+ context,
+ app,
+ 'local',
+ source: 'test',
+ initialFolder: initialFolder,
+ initialProjectFolder: initialProject,
+ ),
child: const Text('Open'),
),
),
@@ -133,6 +147,41 @@ void main() {
await tester.pumpAndSettle();
}
+ for (final (folder, project, label) in [
+ ('/local/context', null, 'context'),
+ (
+ null,
+ const ProjectFolderRequest.newProject(name: 'Careful work'),
+ 'Careful-work',
+ ),
+ (
+ null,
+ ProjectFolderRequest.remote(GitHubRepository.parse('owner/context')!),
+ 'context',
+ ),
+ ]) {
+ testWidgets(
+ 'an inherited project survives switching machines: ${folder ?? project?.payload}',
+ (tester) async {
+ await mount(tester, initialFolder: folder, initialProject: project);
+ expect(find.text(label), findsOneWidget);
+ await tester.tap(
+ find.byKey(const ValueKey('new-agent-machine-remote')),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text(label), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('new-agent-machine-local')));
+ await tester.pumpAndSettle();
+ expect(find.text(label), findsOneWidget);
+ await tester.tap(find.byKey(const Key('create-agent-submit')));
+ await tester.pumpAndSettle();
+ expect(app.calls.single['machine'], 'local');
+ expect(app.calls.single['folder'], folder ?? '');
+ expect(app.calls.single['project'], project?.payload);
+ },
+ );
+ }
+
testWidgets('every new dialog starts with New and leaves history in Recent', (
tester,
) async {
diff --git a/desktop/test/new_agent_rows_and_task_test.dart b/desktop/test/new_agent_rows_and_task_test.dart
index 5c38ba319..07040c5f0 100644
--- a/desktop/test/new_agent_rows_and_task_test.dart
+++ b/desktop/test/new_agent_rows_and_task_test.dart
@@ -16,6 +16,7 @@ import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/shared/widgets/app_icon_button.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
import 'package:harness/widgets/search_result_text.dart';
@@ -127,6 +128,7 @@ class _App extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
prompts.add(prompt);
return pendingCreate?.future ?? 'Test launch refused.';
@@ -267,9 +269,9 @@ void main() {
by: 'by YosysHQ',
line: 'Framework for Verilog RTL synthesis',
));
- await _search(tester, 'godogen');
+ await _search(tester, 'earth');
expect(
- find.byKey(const ValueKey('new-agent-agent-row-autonomous/godogen')),
+ find.byKey(const ValueKey('new-agent-agent-row-someone/earth')),
findsNothing,
reason: 'a harness this build has no face for waits for the machine',
);
@@ -290,15 +292,16 @@ void main() {
'someone/maps',
]);
- // The Store's shelf: Simulation is on Science.
- await _search(tester, 'science');
+ // The Store's Simulation shelf includes physics and robotics.
+ await _search(tester, 'simulation');
expect(agentRows(tester), contains('autonomous/mujoco'));
+ expect(agentRows(tester), contains('someone/earth'));
// The domain itself, where no line under a name says it.
await _search(tester, 'documents');
expect(agentRows(tester), ['autonomous/typst']);
- // An unknown domain is on the Store's Other shelf.
+ // A package with no domain is on the Store's Other shelf.
await _search(tester, 'other');
- expect(agentRows(tester), contains('someone/earth'));
+ expect(agentRows(tester), contains('someone/maps'));
// An author the row draws.
await _search(tester, 'gmbh');
expect(agentRows(tester), ['autonomous/typst']);
@@ -309,7 +312,16 @@ void main() {
await _search(tester, 'deepmind');
expect(agentRows(tester), ['autonomous/mujoco']);
final preview = find.byKey(const ValueKey('new-agent-agent-preview'));
+ expect(preview, findsNothing);
+ final input = tester.widget<TextField>(agentSearch);
+ final value = input.controller!.value;
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.slash);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pumpAndSettle();
expect(preview, findsOneWidget);
+ expect(input.controller!.value, value);
+ expect(input.focusNode!.hasPrimaryFocus, isTrue);
expect(
find.descendant(
of: preview,
diff --git a/desktop/test/new_agent_terminal_test.dart b/desktop/test/new_agent_terminal_test.dart
index c870c2707..a17181421 100644
--- a/desktop/test/new_agent_terminal_test.dart
+++ b/desktop/test/new_agent_terminal_test.dart
@@ -2,10 +2,10 @@
// no task or permission mode, a Home tile in place of New project and no Git —
// and a create that names the terminal engine with no folder at all (the daemon
// opens it at home) or with the folder that was picked.
-import 'dart:async';
import 'package:file_selector_platform_interface/file_selector_platform_interface.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
@@ -13,6 +13,7 @@ import 'package:harness/core/engine_availability.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/widgets/agent_picker.dart';
import 'package:harness/widgets/engine_identity.dart';
@@ -69,6 +70,7 @@ class _Notifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add({
'machine': machineId,
@@ -161,6 +163,10 @@ void main() {
);
await tester.enterText(agentSearch, 'Terminal');
await tester.pumpAndSettle();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.slash);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
+ await tester.pumpAndSettle();
// The preview of the top match says the shell is simply there.
expect(find.text('Your shell on harness-remote-box'), findsOneWidget);
expect(find.textContaining('Installs on'), findsNothing);
diff --git a/desktop/test/new_harness_agent_settings_test.dart b/desktop/test/new_harness_agent_settings_test.dart
new file mode 100644
index 000000000..6c60a88fc
--- /dev/null
+++ b/desktop/test/new_harness_agent_settings_test.dart
@@ -0,0 +1,372 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'support/launch_menu.dart';
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _Profiles extends WsConn {
+ _Profiles(String machine)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: machine,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final creates = <Map<String, dynamic>>[];
+ final links = <String>[];
+ int lists = 0;
+ bool failProfiles = false;
+ bool supportsProfiles = true;
+ Completer<Map<String, dynamic>>? pendingProfiles;
+ Completer<Map<String, dynamic>>? pendingLink;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ switch (type) {
+ case 'engines_probe':
+ return {
+ 'engines': [
+ {
+ 'engine': 'codex',
+ 'installed': true,
+ 'supportsCodexHome': supportsProfiles,
+ },
+ {'engine': 'claude', 'installed': true},
+ ],
+ };
+ case 'dsh_list':
+ return {'dsh': []};
+ case 'fs_list_dir':
+ return {'path': '/home/$machineId', 'entries': []};
+ case 'codex_profiles_list':
+ lists++;
+ if (pendingProfiles != null) return pendingProfiles!.future;
+ return failProfiles
+ ? {'error': 'UNREACHABLE'}
+ : {
+ 'profiles': [
+ {'path': '/profiles/$machineId/work', 'label': 'Work'},
+ {
+ 'path': '/profiles/$machineId/personal',
+ 'label': 'Personal',
+ },
+ ],
+ };
+ case 'codex_profile_link':
+ links.add(payload['path'] as String);
+ return pendingLink?.future ??
+ Future.value({
+ 'profile': {'path': payload['path'], 'label': 'Linked'},
+ });
+ case 'agent_create':
+ creates.add(Map.of(payload));
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'made',
+ 'name': 'Made',
+ 'engine': payload['engine'],
+ 'terminalAvailable': true,
+ },
+ };
+ default:
+ return {};
+ }
+ }
+}
+
+void main() {
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
+ final input = find.byKey(const ValueKey('new-harness-input'));
+
+ void setting(NewHarnessController box, String id) {
+ if (id == NewHarnessController.permissionsId ||
+ id == NewHarnessController.profileId) {
+ box.openAgentSetting(box.selected!.engine!, id);
+ } else {
+ box.accept(box.options.singleWhere((row) => row.id == id));
+ }
+ }
+
+ testWidgets(
+ 'agent settings use pickers and launch with the chosen profile and permissions',
+ (tester) async {
+ final connection = _Profiles('m');
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ app.adoptSessionForTest(terminal('a0', []));
+ await configured.mount(tester, app, map);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(
+ find.byKey(const ValueKey('new-harness-field-options')),
+ findsNothing,
+ );
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'Claude Code');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.engine, 'claude');
+ await openLaunchRow(tester, 'agent');
+ for (final name in ['agent', 'machine', 'project']) {
+ expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);
+ }
+ expect(find.text('Codex profile…'), findsNothing);
+ // Move from a saved Claude selection to Codex without accepting it.
+ for (var step = 0; box.selected?.id != 'codex' && step < 30; step++) {
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ }
+ expect(box.selected?.id, 'codex');
+ expect(box.engine, 'claude');
+ expect(find.text('Permissions'), findsNothing);
+ expect(find.text('Codex Profile'), findsNothing);
+ await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
+ expect(box.field, NewHarnessField.profile);
+ expect(box.agentSettingsLabel, 'Codex');
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-machine')));
+ await tester.pump();
+ expect(box.field, NewHarnessField.machine);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.profile);
+ expect(box.agentSettingsLabel, 'Codex');
+ expect(box.engine, 'claude');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.selected?.id, 'codex');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.engine, 'claude', reason: 'Escape keeps the saved agent');
+ expect(box.draft.profile, isNull);
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'zzzz');
+ await tester.pump();
+ expect(find.text('No agents match “zzzz”.'), findsOneWidget);
+ expect(box.selected?.id, NewHarnessController.storeId);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.engine, 'claude');
+ await openLaunchRow(tester, 'agent');
+ await tester.enterText(input, 'Codex');
+ await tester.pump();
+ await openAgentSetting(
+ tester,
+ 'codex',
+ NewHarnessController.permissionsId,
+ );
+ expect(box.field, NewHarnessField.mode);
+ await tester.enterText(input, 'read only');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.agent);
+ expect(box.mode, 'readOnly');
+ await openAgentSetting(tester, 'codex', NewHarnessController.profileId);
+ expect(box.field, NewHarnessField.profile);
+ expect(connection.lists, greaterThanOrEqualTo(1));
+ expect(
+ box.draft.profile,
+ isNull,
+ reason: 'Discovery never changes the account',
+ );
+ await tester.enterText(input, 'Work');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box.field, NewHarnessField.agent);
+ expect(box.draft.profile!.path, '/profiles/m/work');
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.field, NewHarnessField.launch);
+ expect(find.text('Codex · Read only · profile Work'), findsOneWidget);
+ await openLaunchRow(tester, 'machine');
+ expect(find.text('Choose a machine').first, findsOneWidget);
+ for (final name in ['agent', 'machine', 'project']) {
+ expect(find.byKey(ValueKey('new-harness-field-$name')), findsNothing);
+ }
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(box.machineId, 'm');
+ expect(box.draft.profile!.path, '/profiles/m/work');
+ expect(connection.creates, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.creates.single['codexHome'], '/profiles/m/work');
+ expect(connection.creates.single['permissionMode'], 'readOnly');
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 200));
+ },
+ );
+
+ testWidgets('profile discovery ignores replies from the previous machine', (
+ tester,
+ ) async {
+ final local = _Profiles('m')..pendingProfiles = Completer();
+ final remote = _Profiles('studio');
+ final app = createApp(
+ connectionForTest: (id) => id == 'm' ? local : remote,
+ );
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/local',
+ );
+ addTearDown(box.dispose);
+ await tester.pump(const Duration(milliseconds: 200));
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('codex');
+ setting(box, NewHarnessController.profileId);
+ await tester.pump();
+ expect(box.loadingProfiles, isTrue);
+ box.back();
+ expect(box.query, 'codex');
+ box.back();
+ box.focusField(NewHarnessField.machine);
+ box.setQuery('Office');
+ box.accept();
+ await tester.pump(const Duration(milliseconds: 200));
+ box.focusField(NewHarnessField.agent);
+ setting(box, NewHarnessController.profileId);
+ await tester.pump();
+ expect(
+ box.options
+ .where((row) => row.profile != null)
+ .every((row) => row.machineId == 'studio'),
+ isTrue,
+ );
+ final stale = local.pendingProfiles!;
+ local.pendingProfiles = null;
+ stale.complete({
+ 'profiles': [
+ {'path': '/profiles/m/private', 'label': 'Private'},
+ ],
+ });
+ await tester.pump();
+ expect(box.machineId, 'studio');
+ expect(box.options.any((row) => row.title == 'Private'), isFalse);
+ expect(box.draft.profile, isNull);
+ box.setQuery('Work');
+ box.accept();
+ expect(box.draft.profile!.path, '/profiles/studio/work');
+ box.back();
+ box.focusField(NewHarnessField.machine);
+ box.setQuery('M2');
+ box.accept();
+ expect(box.draft.profile, isNull);
+ expect(box.project.folder, '/work/local');
+ await tester.pump(const Duration(milliseconds: 200));
+ });
+
+ testWidgets(
+ 'profiles can retry, link a folder, and restore default without creating',
+ (tester) async {
+ final connection = _Profiles('m')..failProfiles = true;
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/local',
+ );
+ addTearDown(box.dispose);
+ await tester.pump(const Duration(milliseconds: 200));
+ box.focusField(NewHarnessField.agent);
+ setting(box, NewHarnessController.profileId);
+ await tester.pump();
+ expect(box.error, contains('Refresh profiles'));
+ connection.failProfiles = false;
+ setting(box, NewHarnessController.refreshProfilesId);
+ await tester.pump();
+ expect(box.error, isNull);
+ expect(connection.lists, 2);
+ connection.pendingLink = Completer();
+ final link = box.linkProfile('/profiles/m/linked');
+ expect(box.linkingProfile, isTrue);
+ expect(box.requestDismiss(), isFalse);
+ expect(await box.createNow(), NewHarnessOutcome.failed);
+ expect(connection.creates, isEmpty);
+ connection.pendingLink!.complete({
+ 'profile': {'path': '/profiles/m/linked', 'label': 'Linked'},
+ });
+ await link;
+ expect(connection.links, ['/profiles/m/linked']);
+ expect(box.field, NewHarnessField.agent);
+ expect(box.draft.profile!.path, '/profiles/m/linked');
+ box.setQuery('Claude');
+ expect(box.agentSettingsFor('claude'), hasLength(1));
+ expect(box.engine, 'codex');
+ box.back();
+ expect(box.draft.profile!.path, '/profiles/m/linked');
+ box.focusField(NewHarnessField.agent);
+ setting(box, NewHarnessController.profileId);
+ setting(box, NewHarnessController.defaultProfileId);
+ expect(box.draft.profile, isNull);
+ expect(box.draft.profileChosen, isTrue);
+ box.setQuery('claude');
+ box.accept();
+ box.focusField(NewHarnessField.agent);
+ expect(
+ box.options.any((row) => row.id == NewHarnessController.profileId),
+ isFalse,
+ );
+ box.setQuery('Terminal');
+ box.accept();
+ box.focusField(NewHarnessField.agent);
+ expect(box.agentSettingsFor('terminal'), isEmpty);
+ expect(connection.creates, isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'an older machine offers the default profile and explains support',
+ (tester) async {
+ final connection = _Profiles('m')..supportsProfiles = false;
+ final app = createApp(connectionForTest: (_) => connection);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/local',
+ );
+ addTearDown(box.dispose);
+ await tester.pump(const Duration(milliseconds: 200));
+ box.focusField(NewHarnessField.agent);
+ setting(box, NewHarnessController.profileId);
+ expect(box.profileHelp, contains('Update Harness CLI on M2'));
+ expect(box.options.single.id, NewHarnessController.defaultProfileId);
+ expect(connection.lists, 0);
+ // A later capability response refreshes the open picker automatically.
+ app.machineStates['m']!.engines.replace(const [
+ EngineAvailability(
+ engine: 'codex',
+ installed: true,
+ supportsCodexHome: true,
+ ),
+ ]);
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(connection.lists, 1);
+ expect(box.profileHelp, isNull);
+ },
+ );
+}
diff --git a/desktop/test/new_harness_box_test.dart b/desktop/test/new_harness_box_test.dart
new file mode 100644
index 000000000..9cd50a3be
--- /dev/null
+++ b/desktop/test/new_harness_box_test.dart
@@ -0,0 +1,773 @@
+import 'support/launch_menu.dart';
+
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/core/repository_clone.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/ws/ws_conn.dart';
+import 'package:path/path.dart' as p;
+
+import 'support/mixed_agents.dart';
+import 'swarm_interactions_test.dart' show chord;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+class _MemoryStore implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _Request {
+ _Request(this.type, this.payload);
+ final String type;
+ final Map<String, dynamic> payload;
+}
+
+class _Connection extends WsConn {
+ _Connection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+ final calls = <_Request>[];
+
+ /// The first create's reply is lost, as a dropped connection loses it.
+ bool loseFirstReply = false;
+ String? createFailure;
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'dsh_list') return {'dsh': []};
+ if (type == 'fs_list_dir') return {};
+ calls.add(_Request(type, Map.of(payload)));
+ if (type == 'agent_create' && createFailure != null) {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': {'code': 'INSTALL_FAILED', 'detail': createFailure},
+ };
+ }
+ if (type == 'agent_create' && loseFirstReply) {
+ loseFirstReply = false;
+ throw const WsRequestTimeout('agent_create');
+ }
+ if (type == 'agent_create' || type == 'agent_create_status') {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': {'id': 'made', 'name': 'Made', 'engine': payload['engine']},
+ };
+ }
+ return {};
+ }
+}
+
+/// The rows of a list without the ever-present way out by mouse.
+Iterable<String> found(NewHarnessController box) => box.options
+ .where(
+ (option) =>
+ option.id != NewHarnessController.browseId &&
+ option.id != NewHarnessController.changeMachineId,
+ )
+ .map((option) => option.title);
+
+void main() {
+ test('a named new project gets that folder, and never a changed name', () async {
+ final root = await Directory.systemTemp.createTemp('harness-named-test-');
+ addTearDown(() => root.delete(recursive: true));
+ const request = ProjectFolderRequest.newProject(name: 'My Game! v2');
+ expect(request.folderName, 'My-Game-v2');
+ expect(request.payload, {
+ 'projectSource': 'new',
+ 'projectName': 'My-Game-v2',
+ });
+ final folder = await request.prepareLocal(projectHome: root.path);
+ expect(p.basename(folder), 'My-Game-v2');
+ expect(Directory(folder).existsSync(), isTrue);
+ // Asking again is refused rather than answered with "My-Game-v2-2".
+ await expectLater(
+ request.prepareLocal(projectHome: root.path),
+ throwsA(
+ isA<RepositoryCloneException>().having(
+ (error) => error.message,
+ 'message',
+ contains('already exists'),
+ ),
+ ),
+ );
+ // A name with nothing usable in it is no name: the clock names the folder.
+ expect(projectFolderSlug(' ../.. '), isNull);
+ expect(projectFolderSlug('~/x'), 'x');
+ expect(const ProjectFolderRequest.newProject(name: '///').payload, {
+ 'projectSource': 'new',
+ });
+ });
+
+ test('the line starts as another of the pane you were in', () {
+ final app = createApp();
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/auth',
+ home: '/work',
+ );
+ addTearDown(box.dispose);
+ expect(box.engine, 'codex');
+ expect(box.machineId, 'm');
+ expect(box.project, const NewHarnessProject.folder('/work/auth'));
+ // The inherited arguments are ready to launch immediately.
+ expect(box.field, NewHarnessField.launch);
+ expect(box.options, isEmpty);
+ expect(box.returnCreates, isTrue);
+ box.focusField(NewHarnessField.task);
+ box.setQuery('fix the flaky login test');
+ expect(box.task, 'fix the flaky login test');
+ expect(box.returnCreates, isTrue);
+ // Tab steps out to who; the task is kept, and is back on the way round.
+ box.nextField();
+ expect(box.field, NewHarnessField.agent);
+ expect(box.query, isEmpty);
+ // The highlight opens on the line's own answer, which wears the ✓. In a
+ // list Return chooses — one verb per field — and ⌘↵ makes it from here.
+ expect(box.selected?.id, 'codex');
+ expect(box.isCurrent(box.selected!), isTrue);
+ expect(box.returnCreates, isFalse);
+ box.nextField(-1);
+ expect(box.field, NewHarnessField.task);
+ expect(box.query, 'fix the flaky login test');
+ });
+
+ test('the main loop follows Agent, Project, Task and modes remain available to advanced drafts', () {
+ final app = createApp();
+ final box = NewHarnessController(app, machineId: 'm', engine: 'claude');
+ addTearDown(box.dispose);
+ expect(box.fields, [
+ NewHarnessField.agent,
+ NewHarnessField.machine,
+ NewHarnessField.projectMenu,
+ NewHarnessField.task,
+ ]);
+ box.focusField(NewHarnessField.mode);
+ expect(box.options.where(box.isCurrent).single.id, 'auto');
+ box.setQuery('plan');
+ box.accept();
+ expect(box.mode, 'plan');
+ // A destination is still required before this command can launch.
+ expect(box.field, NewHarnessField.projectMenu);
+ // A terminal is a shell: nothing to tell it, nothing to permit.
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('terminal');
+ box.accept();
+ expect(box.isTerminal, isTrue);
+ expect(box.fields, [
+ NewHarnessField.agent,
+ NewHarnessField.machine,
+ NewHarnessField.projectMenu,
+ ]);
+ });
+
+ test('the project field offers a clone, and a way in without typing', () {
+ final app = createApp();
+ final box = NewHarnessController(app, machineId: 'm', engine: 'claude');
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.project);
+ expect(
+ box.options.any((row) => row.id == NewHarnessController.browseId),
+ isTrue,
+ );
+ expect(box.options.any((row) => row.id == 'project:new'), isFalse);
+ box.focusField(NewHarnessField.projectRepository);
+ box.setQuery('acme/rocket');
+ // Repository input is dedicated to cloning, never creating a blank folder.
+ expect(box.options.any((row) => row.id == 'project:new'), isFalse);
+ expect(box.options.first.title, 'Clone rocket');
+ box.accept(box.options.first);
+ expect(box.project.repository?.name, 'rocket');
+ expect(box.projectLabel, '~/harnesses/rocket');
+ // The system chooser's answer lands as the folder.
+ box.setFolder('/work/picked');
+ expect(box.project, const NewHarnessProject.folder('/work/picked'));
+ });
+
+ test('typing filters the field, Return takes the row and moves along', () {
+ final app = createApp();
+ final box = NewHarnessController(app, machineId: 'm', engine: 'codex');
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('clau');
+ expect(box.selected!.id, 'claude');
+ expect(box.returnCreates, isFalse);
+ box.accept();
+ expect(box.engine, 'claude');
+ // With no destination yet, ask for the missing project.
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.returnCreates, isFalse);
+ box.focusField(NewHarnessField.projectName);
+ expect(box.query, isEmpty);
+ // A plain word names a new project; it is the first thing offered when
+ // no folder matches it.
+ box.setQuery('my game');
+ expect(box.options.first.title, 'Create my-game');
+ box.accept();
+ expect(box.project, const NewHarnessProject.fresh('my game'));
+ expect(box.projectLabel, '~/harnesses/my-game');
+ expect(box.field, NewHarnessField.launch);
+ });
+
+ test('Tab completes a machine without committing it, including repeats', () {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final box = NewHarnessController(
+ app,
+ machineId: 'elsewhere',
+ engine: 'codex',
+ folder: '/work/repo',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.machine);
+ for (var i = 0; i < 12; i++) {
+ box.complete();
+ expect(box.machineId, 'elsewhere');
+ expect(box.project.folder, '/work/repo');
+ expect(box.field, NewHarnessField.machine);
+ }
+ box.accept();
+ expect(box.machineId, 'm');
+ expect(box.field, NewHarnessField.launch);
+ expect(box.needsProject, isTrue);
+ });
+
+ test(
+ 'Escape gives a Tab walk its typed stem back before it closes',
+ () async {
+ final root = await Directory.systemTemp.createTemp('box-walk');
+ addTearDown(() => root.delete(recursive: true));
+ for (final name in ['alpha', 'beta']) {
+ await Directory('${root.path}/$name').create();
+ }
+ final app = createApp();
+ app.machineStates['m']!.localOnly = true;
+ final box = NewHarnessController(app, machineId: 'm', home: root.path);
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.project);
+ box.setQuery('~/');
+ // The listing is read off the disk, then the field refreshes itself.
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(box.endCompletion(), isFalse);
+ // A bare `~/` is what is IN home, not home's own row in its parent.
+ expect(
+ [
+ for (final option in box.options)
+ if (!option.synthetic) option.title,
+ ],
+ ['alpha', 'beta'],
+ );
+ expect(box.complete(), '~/alpha');
+ expect(box.endCompletion(), isTrue);
+ expect(box.query, '~/');
+ expect(box.endCompletion(), isFalse);
+ },
+ );
+
+ test('a typed path completes like a shell', () async {
+ final root = await Directory.systemTemp.createTemp('harness-path-test-');
+ addTearDown(() => root.delete(recursive: true));
+ await Directory(p.join(root.path, 'auth', 'api')).create(recursive: true);
+ await Directory(p.join(root.path, 'authz')).create();
+ await Directory(p.join(root.path, 'billing')).create();
+ await Directory(p.join(root.path, '.hidden')).create();
+ final app = createApp();
+ app.machineStates['m']!.localOnly = true;
+ final box = NewHarnessController(app, machineId: 'm', home: root.path);
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.project);
+ box.setQuery('~/au');
+ // The listing is read off the disk, then the field refreshes itself.
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(found(box), ['auth', 'authz']);
+ expect((box.matchCount, box.total), (2, 3));
+ // zsh's Tab: first as much as every candidate agrees on…
+ expect(box.complete(), '~/auth');
+ expect(found(box), ['auth', 'authz']);
+ // …then, with nothing more to agree on, Tab walks a completion menu: each
+ // candidate goes INTO the line while the list stays the stem's list…
+ expect(box.complete(), '~/auth');
+ expect(box.selected!.title, 'auth');
+ expect(box.complete(), '~/authz');
+ expect(box.selected!.title, 'authz');
+ expect(found(box), ['auth', 'authz']);
+ // …⇧⇥ walks it backwards…
+ expect(box.complete(-1), '~/auth');
+ expect(box.selected!.title, 'auth');
+ // …and a slash goes into the one in the line, as a completion menu's does.
+ box.setQuery('~/auth/');
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(found(box), ['auth', 'api']);
+ // One folder left: Tab goes into it.
+ box.setQuery('~/auth/a');
+ expect(box.complete(), '~/auth/api/');
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ box.setQuery('~/auth/');
+ box.accept(box.options.firstWhere((option) => option.title == 'api'));
+ expect(
+ box.project,
+ NewHarnessProject.folder(p.join(root.path, 'auth', 'api')),
+ );
+ expect(box.projectLabel, '~/auth/api');
+ });
+
+ test('Return sends one create, with the project name when there is one', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'claude',
+ projectName: 'my game',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.task);
+ box.setQuery(' write the README ');
+ box.focusField(NewHarnessField.mode);
+ box.setQuery('plan');
+ box.accept();
+ expect(await box.create(), NewHarnessOutcome.created);
+ final create = connection.calls.singleWhere(
+ (call) => call.type == 'agent_create',
+ );
+ // What was typed is the first message, exactly; the mode is the one picked.
+ expect(create.payload['prompt'], 'write the README');
+ expect(create.payload['permissionMode'], 'plan');
+ expect(create.payload['bypassPermission'], isFalse);
+ expect(create.payload['engine'], 'claude');
+ expect(create.payload['projectSource'], 'new');
+ expect(create.payload['projectName'], 'my-game');
+ expect(create.payload.containsKey('cwd'), isFalse);
+ });
+
+ for (final engine in [
+ 'claude',
+ 'codex',
+ 'amp',
+ 'muse',
+ 'devin',
+ 'commandcode',
+ ]) {
+ test('a missing $engine goes directly to the daemon launch', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.engines.replace([
+ EngineAvailability(engine: engine, installed: false),
+ ]);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: engine,
+ folder: '/work',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.agent);
+ final option = box.options.singleWhere((option) => option.id == engine);
+ expect(option.enabled, isTrue);
+ expect(option.detail, isNot(contains('not installed')));
+ box.accept(option);
+ expect(await box.create(), NewHarnessOutcome.created);
+ final create = connection.calls.singleWhere(
+ (call) => call.type == 'agent_create',
+ );
+ expect(create.payload['engine'], engine);
+ });
+ }
+
+ test('a failed first launch shows the daemon error', () async {
+ final connection = _Connection()
+ ..createFailure = 'Automatic installation failed.';
+ final app = createApp(connectionForTest: (_) => connection);
+ addTearDown(app.dispose);
+ app.machineStates['m']!.engines.replace([
+ const EngineAvailability(engine: 'amp', installed: false),
+ ]);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'amp',
+ folder: '/work',
+ );
+ addTearDown(box.dispose);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Automatic installation failed.'));
+ expect(
+ connection.calls.where((call) => call.type == 'agent_create'),
+ hasLength(1),
+ );
+ });
+
+ test(
+ 'a lost reply is checked on, never answered with a second harness',
+ () async {
+ final connection = _Connection()..loseFirstReply = true;
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work',
+ );
+ addTearDown(box.dispose);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isTrue);
+ expect(box.error, isNotNull);
+ // The answers are frozen: what may already exist cannot be re-aimed.
+ box.setQuery('codex');
+ expect(box.query, isEmpty);
+ expect(box.returnCreates, isTrue);
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(connection.calls.map((call) => call.type), [
+ 'agent_create',
+ 'agent_create_status',
+ ]);
+ },
+ );
+
+ testWidgets('⌘N opens the box over live panes, and Escape closes it', (
+ tester,
+ ) async {
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = false);
+ final app = createApp();
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ await app.addAgentToSwarm('m', 'a0');
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyN);
+ await tester.pump();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(find.byKey(const ValueKey('new-harness-box')), findsOneWidget);
+ // Attached to the workspace's bottom edge, without dimming or resizing it.
+ final dock = tester.getRect(find.byKey(const ValueKey('new-harness-box')));
+ expect(dock.left, 6);
+ expect(dock.right, tester.view.physicalSize.width - 6);
+ expect(dock.bottom, tester.view.physicalSize.height - 6);
+ expect(find.byKey(const ValueKey('new-harness-input')), findsNothing);
+ expect(
+ FocusManager.instance.primaryFocus!.debugLabel,
+ 'New harness launch',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byKey(const ValueKey('new-harness-box')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ test('a typed task is never dropped without being said, on any path', () async {
+ final connection = _Connection();
+ final app = createApp(connectionForTest: (_) => connection);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work',
+ task: 'fix the login test',
+ );
+ addTearDown(box.dispose);
+ // ⌘↵ from the agent list, a shell highlighted: it used to go straight past
+ // the notice and make the terminal with the task silently gone.
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('terminal');
+ expect(await box.createNow(), NewHarnessOutcome.failed);
+ expect(box.error, contains('will not be sent'));
+ expect(connection.calls.where((c) => c.type == 'agent_create'), isEmpty);
+ // The second press means it.
+ expect(await box.create(), NewHarnessOutcome.created);
+ expect(
+ connection.calls.singleWhere((c) => c.type == 'agent_create').payload,
+ isNot(contains('prompt')),
+ );
+ // Opening on an agent that cannot take the seeded task says so at once.
+ final shell = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'terminal',
+ task: 'do the thing',
+ );
+ addTearDown(shell.dispose);
+ expect(shell.error, contains('will not be sent'));
+ });
+
+ test('Return and ⌘↵ are never silent, and a dropped task is said', () async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = false;
+ final box = NewHarnessController(app, machineId: 'm', engine: 'claude');
+ addTearDown(box.dispose);
+ // Nothing matches: Return says so instead of doing nothing.
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('zzzz');
+ expect(box.matchCount, 0);
+ expect(box.selected, isNull);
+ box.accept();
+ expect(box.error, contains('Nothing matches'));
+ expect(await box.createNow(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Nothing matches'));
+ expect(box.engine, 'claude');
+ // An offline machine: Return says why, and ⌘↵ will not quietly make the
+ // harness with the OLD answer while this one is lit.
+ box.focusField(NewHarnessField.machine);
+ box.setQuery('test');
+ expect(box.selected!.enabled, isFalse);
+ box.accept();
+ expect(box.error, contains('offline'));
+ expect(await box.createNow(), NewHarnessOutcome.failed);
+ expect(box.error, contains('offline'));
+ // A task typed for an agent that cannot take one is not dropped in silence.
+ box.focusField(NewHarnessField.task);
+ box.setQuery('fix the login test');
+ box.focusField(NewHarnessField.agent);
+ box.setQuery('terminal');
+ box.accept();
+ expect(box.error, contains('will not be sent'));
+ });
+
+ test('the arrows end a Tab walk', () async {
+ final root = await Directory.systemTemp.createTemp('harness-cycle-test-');
+ addTearDown(() => root.delete(recursive: true));
+ for (final name in ['auth', 'authz', 'authn']) {
+ await Directory(p.join(root.path, name)).create();
+ }
+ final app = createApp();
+ app.machineStates['m']!.localOnly = true;
+ final box = NewHarnessController(app, machineId: 'm', home: root.path);
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.project);
+ box.setQuery('~/auth');
+ await Future<void>.delayed(const Duration(milliseconds: 100));
+ expect(box.complete(), '~/auth');
+ expect(box.complete(), '~/authn');
+ // Down leaves the walk: the line is what was typed again, and the
+ // highlight stays where the arrow put it through the next refresh.
+ box.move(1);
+ expect(box.query, '~/auth');
+ final moved = box.selected!.title;
+ app.renameSwarm(app.activeSwarmId, 'a tick');
+ expect(box.selected!.title, moved);
+ });
+
+ test(
+ 'the palette opens on what was run last, until something is typed',
+ () async {
+ final store = _MemoryStore();
+ final history = SwarmNavigationHistory(storage: store);
+ addTearDown(history.dispose);
+ history.rememberCommand('pane.zoom');
+ history.rememberCommand('app.settings');
+ SwarmDestination command(String id, String title) => SwarmDestination(
+ id: 'command:$id',
+ title: title,
+ detail: '',
+ swarmId: null,
+ current: false,
+ commandId: id,
+ searchFields: [id],
+ );
+ final app = createApp();
+ final search = SwarmSearchController(
+ app,
+ const [],
+ commandsOnly: true,
+ commands: () => [
+ command('agent.new', 'New Harness'),
+ command('app.settings', 'Customize Harness'),
+ command('pane.zoom', 'Zoom pane'),
+ ],
+ recentCommands: () => history.recentCommands,
+ );
+ addTearDown(search.dispose);
+ expect(search.rows.map((row) => row.commandId), [
+ 'app.settings',
+ 'pane.zoom',
+ 'agent.new',
+ ]);
+ // Typing hands the order back to the match.
+ search.setQuery('new');
+ expect(search.rows.first.commandId, 'agent.new');
+ // And it outlives a restart.
+ await Future<void>.delayed(const Duration(milliseconds: 700));
+ final next = SwarmNavigationHistory(storage: store);
+ addTearDown(next.dispose);
+ await next.load();
+ expect(next.recentCommands, ['app.settings', 'pane.zoom']);
+ },
+ );
+
+ test(
+ 'recent harnesses outlive a restart, and never reorder the present',
+ () async {
+ final store = _MemoryStore();
+ await store.write(
+ 'swarm_recent_v1',
+ '["agent:m\\u0000old","swarm:tab-7","agent:m\\u0000older",42]',
+ );
+ final history = SwarmNavigationHistory(storage: store);
+ addTearDown(history.dispose);
+ await history.load();
+ // Harnesses only: a tab's id need not survive a launch, and junk is dropped.
+ expect(history.recent, ['agent:m\u0000old', 'agent:m\u0000older']);
+ // A second load adds nothing twice.
+ await history.load();
+ expect(history.recent, hasLength(2));
+ },
+ );
+
+ test('? lists what the box can do, and the count says how much matches', () {
+ final app = createApp();
+ SwarmDestination mode(String id, String title) => SwarmDestination(
+ id: 'command:$id',
+ title: title,
+ detail: 'where it goes',
+ swarmId: null,
+ current: false,
+ commandId: id,
+ searchFields: [id],
+ );
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ modes: () => [
+ mode('navigation.commands', '> Commands'),
+ mode('agent.new', 'New Harness'),
+ ],
+ );
+ addTearDown(search.dispose);
+ search.setQuery('?');
+ expect(search.isHelpMode, isTrue);
+ // In the order they are taught, with no create row and no preview.
+ expect(search.rows.map((row) => row.title), ['> Commands', 'New Harness']);
+ expect(search.hasPreview, isFalse);
+ expect(search.canAccept, isTrue);
+ expect(search.actionLabel(search.selected), 'Open');
+ expect(search.submit()?.destination.commandId, 'navigation.commands');
+ // What follows `?` narrows them.
+ search.setQuery('? new');
+ expect(search.rows.single.commandId, 'agent.new');
+ expect((search.matchCount, search.total), (1, 2));
+ // Leaving `?` is leaving the mode.
+ search.setQuery('zzz');
+ expect(search.isHelpMode, isFalse);
+ expect(search.matchCount, 0);
+ });
+
+ test('the box ends in a row that makes what was typed', () {
+ final app = createApp();
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ );
+ addTearDown(search.dispose);
+ // Nothing typed: it leads, where the mouse can always find it — but the
+ // box never opens WITH it selected when there is a harness to go back to.
+ expect(search.rows.first.isCreate, isTrue);
+ expect(search.rows.first.title, 'New Harness');
+ expect(search.rows.length == 1 || !search.selected!.isCreate, isTrue);
+ search.setQuery('zzz no such thing');
+ expect(search.rows.single.isCreate, isTrue);
+ // What was typed is what the new harness starts on, as an editor's
+ // `New agent: "…"` row does.
+ expect(search.rows.single.title, 'New Harness');
+ expect(search.rows.single.detail, 'zzz no such thing');
+ expect(search.createTask, 'zzz no such thing');
+ expect(search.canAccept, isTrue);
+ expect(search.actionLabel(search.selected), 'New Harness');
+ // Commands never offer it.
+ search.setQuery('> split');
+ expect(search.rows.any((row) => row.isCreate), isFalse);
+ });
+
+ testWidgets('the box is driven from the keyboard', (tester) async {
+ final app = createApp();
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/auth',
+ );
+ var closed = 0;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 720,
+ height: 420,
+ child: NewHarnessBox(
+ controller: box,
+ onClose: () => closed++,
+ onCreated: () {},
+ onNeedsForm: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ expect(box.field, NewHarnessField.launch);
+ expect(input, findsNothing);
+ await openLaunchRow(tester, 'agent');
+ await tester.pump();
+ expect(box.field, NewHarnessField.agent);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ await tester.enterText(input, 'clau');
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(box.query, 'Claude Code');
+ expect(box.engine, 'codex');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.engine, 'claude');
+ expect(box.field, NewHarnessField.launch);
+ await openLaunchRow(tester, 'task');
+ await tester.pump();
+ await tester.enterText(input, 'a project to test');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(box.field, NewHarnessField.launch);
+ expect(box.task, 'a project to test');
+ expect(closed, 0);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ expect(closed, 1);
+ await tester.pumpWidget(const SizedBox());
+ box.dispose();
+ app.dispose();
+ });
+}
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
new file mode 100644
index 000000000..f47ebbd21
--- /dev/null
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -0,0 +1,568 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/store/store_screen.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/swarm_search_input.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+const _products = [
+ {
+ 'id': 'autonomous/workshop',
+ 'name': 'Autonomous Workshop',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+ {
+ 'id': 'autonomous/blender',
+ 'name': 'Blender',
+ 'engine': 'claude',
+ 'installed': true,
+ },
+];
+
+class _Connection extends WsConn {
+ _Connection(String id)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: id,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final starts = <Map<String, dynamic>>[];
+ final replies = <Completer<Map<String, dynamic>>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') {
+ return {
+ 'engines': [
+ for (final engine in ['codex', 'claude'])
+ {'engine': engine, 'installed': true},
+ ],
+ };
+ }
+ if (type == 'dsh_list') return {'dsh': _products};
+ if (type == 'fs_list_dir') {
+ return {'path': payload['path'] ?? '/home/$machineId', 'entries': []};
+ }
+ if (type == 'agent_create') {
+ starts.add(Map.of(payload));
+ final reply = Completer<Map<String, dynamic>>();
+ replies.add(reply);
+ return reply.future;
+ }
+ return {};
+ }
+
+ void created() => replies.last.complete({
+ 'creationId': starts.last['creationId'],
+ 'state': 'created',
+ 'agent': {
+ 'id': 'created-${starts.length}',
+ 'name': 'Created harness',
+ 'engine': starts.last['engine'],
+ 'dsh': starts.last['dsh'],
+ 'project': {
+ 'cwd':
+ starts.last['cwd'] ??
+ '/home/$machineId/harnesses/${starts.last['projectName']}',
+ },
+ },
+ });
+}
+
+void main() {
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late Map<String, _Connection> connections;
+ final input = find.byKey(const ValueKey('new-harness-input'));
+ NewHarnessController box(WidgetTester tester) =>
+ tester.widget<NewHarnessBox>(find.byType(NewHarnessBox)).controller;
+
+ setUp(() {
+ newHarnessOpensInBox = true;
+ connections = {
+ for (final id in ['m', 'studio', 'build']) id: _Connection(id),
+ };
+ app = createApp(connectionForTest: (id) => connections[id]!);
+ seedMixedAgents(app);
+ for (final machine in app.machineStates.values) {
+ machine.dsh.replace(_products.map((json) => DshEntry.fromJson(json)!));
+ }
+ map = MemoryKeymap();
+ });
+ tearDown(() {
+ map.dispose();
+ app.dispose();
+ newHarnessOpensInBox = false;
+ });
+
+ Future<void> mount(WidgetTester tester, {bool store = true}) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ if (store) app.openStore();
+ await configured.mount(tester, app, map);
+ }
+
+ Future<void> product(
+ WidgetTester tester,
+ String id, {
+ String machine = 'm',
+ String? task,
+ }) async {
+ await openStoreAgent(
+ tester.element(
+ find
+ .descendant(
+ of: find.byType(SwarmScreen),
+ matching: find.byType(Scaffold),
+ )
+ .first,
+ ),
+ app,
+ id,
+ machine,
+ prompt: task,
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 150));
+ }
+
+ Future<void> dismiss(WidgetTester tester) async {
+ for (
+ var i = 0;
+ i < 4 && find.byType(NewHarnessBox).evaluate().isNotEmpty;
+ i++
+ ) {
+ await key(tester, LogicalKeyboardKey.escape);
+ }
+ expect(find.byType(NewHarnessBox), findsNothing);
+ }
+
+ Future<void> nameProject(WidgetTester tester, String name) async {
+ box(tester).focusField(NewHarnessField.projectName);
+ await tester.pump();
+ await tester.enterText(input, name);
+ await key(tester, LogicalKeyboardKey.enter);
+ }
+
+ for (final closeFirst in [false, true]) {
+ for (final task in [null, 'Model a reading nook']) {
+ testWidgets(
+ 'switching Store products ${closeFirst ? 'after Escape' : 'with the dock open'} respects ${task == null ? 'Open' : 'Try'}',
+ (tester) async {
+ await mount(tester);
+ await product(tester, 'autonomous/workshop');
+ expect(
+ box(tester).projectLabel,
+ startsWith('~/harnesses/autonomous-workshop-'),
+ );
+ await nameProject(tester, 'workshop-design');
+ box(tester).task = 'Workshop task';
+ if (closeFirst) await dismiss(tester);
+ await product(tester, 'autonomous/blender', task: task);
+ expect(box(tester).engine, 'autonomous/blender');
+ expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
+ expect(box(tester).project.generated, isNotNull);
+ expect(box(tester).task, task ?? '');
+ expect(box(tester).placement, HarnessPlacement.newTab);
+ await dismiss(tester);
+ await product(tester, 'autonomous/workshop');
+ expect(box(tester).engine, 'autonomous/workshop');
+ expect(box(tester).projectLabel, '~/harnesses/workshop-design');
+ expect(box(tester).task, 'Workshop task');
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
+
+ testWidgets(
+ 'Store machine choices have separate drafts and override edited defaults',
+ (tester) async {
+ await mount(tester);
+ await product(tester, 'autonomous/blender');
+ await nameProject(tester, 'local-scene');
+ await product(tester, 'autonomous/blender', machine: 'studio');
+ expect(box(tester).machineId, 'studio');
+ expect(box(tester).project.generated, isNotNull);
+ await nameProject(tester, 'remote-scene');
+ await product(tester, 'autonomous/blender');
+ expect(box(tester).machineId, 'm');
+ expect(box(tester).project.name, 'local-scene');
+ box(tester).focusField(NewHarnessField.machine);
+ box(tester).accept(const NewHarnessOption(id: 'studio', title: 'Studio'));
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender');
+ expect(
+ box(tester).machineId,
+ 'm',
+ reason: 'The Store explicitly requested this machine',
+ );
+ expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender', machine: 'studio');
+ expect(box(tester).project.name, 'remote-scene');
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'product entry from a pane does not inherit workspace projects or search tasks',
+ (tester) async {
+ await mount(tester, store: false);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Review the API',
+ );
+ await product(tester, 'autonomous/blender');
+ expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
+ expect(box(tester).task, isEmpty);
+ expect(box(tester).placement, HarnessPlacement.newTab);
+ await dismiss(tester);
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).project.folder, '/work/openharness');
+ expect(box(tester).task, isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final task in [null, 'Model a reading nook']) {
+ testWidgets(
+ 'Store ${task == null ? 'Open' : 'Try'} starts the displayed product, project and machine after a product switch',
+ (tester) async {
+ await mount(tester);
+ final store = app.activeSwarm;
+ await product(tester, 'autonomous/workshop');
+ await product(
+ tester,
+ 'autonomous/blender',
+ machine: 'studio',
+ task: task,
+ );
+ final displayed = box(tester).projectFolderRequest!.folderName;
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connections['m']!.starts, isEmpty);
+ final connection = connections['studio']!;
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['engine'], 'claude');
+ expect(connection.starts.single['dsh'], 'autonomous/blender');
+ expect(connection.starts.single['projectName'], displayed);
+ expect(displayed, startsWith('blender-'));
+ expect(connection.starts.single['prompt'], task);
+ expect(app.activeSwarm, same(store));
+ connection.created();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(app.activeSwarm.isStore, isFalse);
+ expect(app.focusedPane?.machineId, 'studio');
+ expect(app.focusedPane?.agentId, 'created-1');
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('Store Open overrides an agent changed inside its saved draft', (
+ tester,
+ ) async {
+ await mount(tester);
+ await product(tester, 'autonomous/blender');
+ box(tester).focusField(NewHarnessField.agent);
+ box(tester).accept(const NewHarnessOption(id: 'codex', title: 'Codex'));
+ expect(box(tester).engine, 'codex');
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender');
+ expect(box(tester).engine, 'autonomous/blender');
+ expect(box(tester).projectLabel, startsWith('~/harnesses/blender-'));
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'an in-flight or uncertain Store start cannot be replaced or retried as a new task',
+ (tester) async {
+ await mount(tester);
+ await product(tester, 'autonomous/workshop', task: 'Original task');
+ final original = box(tester);
+ final starting = original.create();
+ await tester.pump();
+ expect(connections['m']!.starts, hasLength(1));
+ await product(tester, 'autonomous/blender');
+ expect(box(tester), same(original));
+ expect(original.error, contains('Finish the current action'));
+ connections['m']!.replies.single.completeError(
+ const WsRequestTimeout('agent_create'),
+ );
+ expect(await starting, NewHarnessOutcome.failed);
+ await tester.pump();
+ await product(tester, 'autonomous/blender');
+ expect(box(tester), same(original));
+ expect(original.checking, isTrue);
+ expect(original.error, contains('Check the pending start'));
+ await dismiss(tester);
+ await product(tester, 'autonomous/blender');
+ expect(box(tester).engine, 'autonomous/blender');
+ await dismiss(tester);
+ await product(tester, 'autonomous/workshop', task: 'A different example');
+ expect(box(tester).checking, isTrue);
+ expect(box(tester).task, 'Original task');
+ expect(connections['m']!.starts, hasLength(1));
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final newTab in [true, false]) {
+ testWidgets(
+ 'switching to Cmd-${newTab ? 'T' : 'P'} keeps the highlighted existing harness',
+ (tester) async {
+ await mount(tester, store: false);
+ final origin = app.activeSwarm;
+ await key(
+ tester,
+ newTab ? LogicalKeyboardKey.keyP : LogicalKeyboardKey.keyT,
+ cmd: true,
+ );
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, 'login');
+ final picker = tester
+ .widget<SwarmSearchInput>(find.byType(SwarmSearchInput))
+ .search!;
+ for (
+ var i = 0;
+ i < picker.rows.length && picker.selected?.agentId != 'a1';
+ i++
+ ) {
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ }
+ expect(picker.selected?.agentId, 'a1');
+ await key(
+ tester,
+ newTab ? LogicalKeyboardKey.keyT : LogicalKeyboardKey.keyP,
+ cmd: true,
+ );
+ final updated = tester
+ .widget<SwarmSearchInput>(find.byType(SwarmSearchInput))
+ .search!;
+ expect(updated.query, 'login');
+ expect(updated.selected?.agentId, 'a1');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.focusedPane?.agentId, 'a1');
+ expect(app.activeSwarm == origin, !newTab);
+ expect(app.swarms.length, newTab ? 2 : 1);
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ for (final switchDestination in [false, true]) {
+ testWidgets(
+ 'Cmd-${newTab ? 'T' : 'P'} ${switchDestination ? 'switches destination' : 'repeats'} without losing the search task',
+ (tester) async {
+ await mount(tester, store: false);
+ final origin = app.activeSwarm;
+ final shortcut = newTab
+ ? LogicalKeyboardKey.keyT
+ : LogicalKeyboardKey.keyP;
+ final nextTab = switchDestination ? !newTab : newTab;
+ await key(tester, shortcut, cmd: true);
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, 'Check the keyboard workflow');
+ final editor = tester.widget<SwarmSearchInput>(
+ find.byType(SwarmSearchInput),
+ );
+ editor.controller.selection = const TextSelection(
+ baseOffset: 6,
+ extentOffset: 18,
+ );
+ await key(
+ tester,
+ nextTab ? LogicalKeyboardKey.keyT : LogicalKeyboardKey.keyP,
+ cmd: true,
+ );
+ final updated = tester.widget<SwarmSearchInput>(
+ find.byType(SwarmSearchInput),
+ );
+ expect(updated.controller.text, 'Check the keyboard workflow');
+ expect(
+ updated.controller.selection,
+ const TextSelection(baseOffset: 6, extentOffset: 18),
+ );
+ expect(updated.focusNode.hasFocus, isTrue);
+ expect(find.text(nextTab ? 'New Tab' : 'New Pane'), findsOneWidget);
+ expect(app.swarms, [origin]);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box(tester).task, 'Check the keyboard workflow');
+ expect(
+ box(tester).placement,
+ nextTab ? HarnessPlacement.newTab : HarnessPlacement.currentTab,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(
+ connections['m']!.starts.single['prompt'],
+ 'Check the keyboard workflow',
+ );
+ connections['m']!.created();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(app.swarms.length, nextTab ? 2 : 1);
+ expect(app.focusedPane?.agentId, 'created-1');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'Cmd-${newTab ? 'T' : 'P'} keeps drafts separate when the focused source pane changes',
+ (tester) async {
+ await mount(tester, store: false);
+ final first = app.focusedPane!;
+ final other = app.adoptSessionForTest(terminal('a2', []));
+ app.focusPane(first.id);
+ await tester.pump();
+ final shortcut = newTab
+ ? LogicalKeyboardKey.keyT
+ : LogicalKeyboardKey.keyP;
+ await key(tester, shortcut, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ await nameProject(tester, 'keyboard-review');
+ box(tester).focusField(NewHarnessField.task);
+ await tester.pump();
+ await tester.enterText(input, 'Review this project');
+ await dismiss(tester);
+ app.focusPane(other.id);
+ await tester.pump();
+ await key(tester, shortcut, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box(tester).engine, 'autonomous/typst');
+ expect(box(tester).project.folder, '/work/release-notes');
+ expect(box(tester).task, isEmpty);
+ await dismiss(tester);
+ app.focusPane(first.id);
+ await tester.pump();
+ await key(tester, shortcut, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(box(tester).engine, 'codex');
+ expect(box(tester).project.name, 'keyboard-review');
+ expect(box(tester).task, 'Review this project');
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await dismiss(tester);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(milliseconds: 60));
+ },
+ );
+
+ testWidgets(
+ 'Cmd-${newTab ? 'T' : 'P'} inherits its source and resumes edits into the requested destination',
+ (tester) async {
+ await mount(tester, store: false);
+ final origin = app.activeSwarm;
+ final shortcut = newTab
+ ? LogicalKeyboardKey.keyT
+ : LogicalKeyboardKey.keyP;
+ await key(tester, shortcut, cmd: true);
+ await key(tester, LogicalKeyboardKey.enter);
+ var draft = box(tester);
+ expect(draft.engine, 'codex');
+ expect(draft.machineId, 'm');
+ expect(draft.project.folder, '/work/openharness');
+ expect(app.swarms, [origin]);
+ draft.focusField(NewHarnessField.task);
+ await tester.pump();
+ await tester.enterText(input, 'Check keyboard focus');
+ await key(tester, LogicalKeyboardKey.escape);
+ await nameProject(tester, 'keyboard-review');
+ await dismiss(tester);
+ await key(
+ tester,
+ newTab ? LogicalKeyboardKey.keyP : LogicalKeyboardKey.keyT,
+ cmd: true,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ draft = box(tester);
+ expect(draft.task, 'Check keyboard focus');
+ expect(draft.project.name, 'keyboard-review');
+ expect(
+ draft.placement,
+ newTab ? HarnessPlacement.currentTab : HarnessPlacement.newTab,
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ final connection = connections['m']!;
+ expect(connection.starts, hasLength(1));
+ expect(connection.starts.single['engine'], 'codex');
+ expect(connection.starts.single['projectName'], 'keyboard-review');
+ expect(connection.starts.single['prompt'], 'Check keyboard focus');
+ expect(connection.starts.single['dsh'], isNull);
+ connection.created();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.swarms.length, newTab ? 1 : 2);
+ expect(app.activeSwarm.panes.last.agentId, 'created-1');
+ expect(app.focusedPane?.agentId, 'created-1');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets(
+ 'switching the picker keeps its project scope and Escape goes back',
+ (tester) async {
+ await mount(tester, store: false);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ final search = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(search, '# openharness');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.enterText(search, 'login');
+ final before = tester
+ .widget<SwarmSearchInput>(find.byType(SwarmSearchInput))
+ .search!;
+ expect(before.canGoBack, isTrue);
+ final selected = before.selected?.id;
+ final results = before.rows.map((row) => row.id).toList();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final picker = tester
+ .widget<SwarmSearchInput>(find.byType(SwarmSearchInput))
+ .search!;
+ expect(picker.query, 'login');
+ expect(picker.canGoBack, isTrue);
+ expect(picker.rows.any((row) => row.isCreate), isFalse);
+ expect(picker.selected?.id, selected);
+ expect(picker.rows.map((row) => row.id), results);
+ expect(find.text('Agents · openharness'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(picker.query, '# openharness');
+ expect(picker.canGoBack, isFalse);
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/new_harness_project_context_test.dart b/desktop/test/new_harness_project_context_test.dart
new file mode 100644
index 000000000..5ab1f5d83
--- /dev/null
+++ b/desktop/test/new_harness_project_context_test.dart
@@ -0,0 +1,675 @@
+import 'support/launch_menu.dart';
+
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_history.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/mixed_agents.dart';
+import 'swarm_state_test.dart' show createApp, MemoryStore;
+
+class _Folders extends WsConn {
+ _Folders(String id)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: id,
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final paths = <String?>[];
+ Completer<Map<String, dynamic>>? pendingHome;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ if (type == 'engines_probe') return {'engines': []};
+ if (type == 'dsh_list') return {'dsh': []};
+ if (type != 'fs_list_dir') throw StateError('Unexpected request: $type');
+ final path = payload['path'] as String?;
+ paths.add(path);
+ if (path == null && pendingHome != null) return pendingHome!.future;
+ return {
+ 'path': path ?? '/home/$machineId',
+ 'entries': [
+ if (path == '/home/$machineId/harnesses')
+ {'name': 'payments-processing', 'isDir': true},
+ if (path == '/home/$machineId/work')
+ {'name': 'payments', 'isDir': true},
+ ],
+ };
+ }
+}
+
+void main() {
+ final input = find.byKey(const ValueKey('new-harness-input'));
+
+ Future<void> mount(WidgetTester tester, NewHarnessController box) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData.dark(),
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 760,
+ height: 420,
+ child: NewHarnessBox(
+ docked: true,
+ controller: box,
+ onClose: () {},
+ onCreated: () =>
+ fail('Reviewing a project must not create an agent'),
+ onNeedsForm: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ void chooseMachine(NewHarnessController box) {
+ box.focusField(NewHarnessField.projectMenu);
+ box.focusField(NewHarnessField.machine);
+ }
+
+ testWidgets(
+ 'the proposed project name is selected for immediate replacement',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ autoProject: true,
+ now: () => DateTime(2026, 9, 20, 17, 22, 19),
+ );
+ addTearDown(box.dispose);
+ await mount(tester, box);
+ await openLaunchRow(tester, 'project');
+ box.accept(
+ box.options.firstWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ),
+ );
+ await tester.pump();
+ final controller = tester.widget<TextField>(input).controller!;
+ expect(controller.text, 'codex-2026-09-20-17-22');
+ expect(
+ controller.selection,
+ TextSelection(baseOffset: 0, extentOffset: controller.text.length),
+ );
+ await tester.enterText(input, 'design-system');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.projectLabel, '~/harnesses/design-system');
+ expect(box.project.generated, isNull);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'saved project history loads on first opening without replacing the draft',
+ (tester) async {
+ final store = MemoryStore();
+ await ProjectHistory(store).select('m', '/work/last-session');
+ final app = createApp(store: store);
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/current',
+ task: 'Keep this task',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ await mount(tester, box);
+ expect(
+ box.options
+ .where((row) => !row.synthetic)
+ .map((row) => row.project?.folder)
+ .take(2),
+ ['/work/current', '/work/last-session'],
+ );
+ expect(box.project.folder, '/work/current');
+ expect(box.task, 'Keep this task');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test('recent projects include existing agents before any picker history', () {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final machine = app.machineStates['m']!;
+ machine.agents = [
+ ...machine.agents,
+ const Agent(id: 'local-metadata', name: 'Local project'),
+ const Agent(id: 'duplicate', name: 'Same folder'),
+ const Agent(id: 'worktree', name: 'Another checkout'),
+ const Agent(id: 'missing-path', name: 'Unknown folder'),
+ ];
+ machine.localProjects = const {
+ 'local-metadata': AgentProject(name: 'website', cwd: '/work/website'),
+ 'duplicate': AgentProject(name: 'same', cwd: '/work/openharness/'),
+ 'worktree': AgentProject(
+ name: 'openharness',
+ cwd: '/work/openharness/.worktrees/design',
+ root: '/work/openharness',
+ ),
+ 'missing-path': AgentProject(name: 'unknown', cwd: ''),
+ };
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/openharness',
+ );
+ addTearDown(box.dispose);
+ expect(app.projectHistory.recent('m'), isEmpty);
+ box.focusField(NewHarnessField.projectMenu);
+ final recent = box.options.where((row) => !row.synthetic).toList();
+ expect(recent.map((row) => row.project?.folder), [
+ '/work/openharness',
+ '/work/openharness/.worktrees/design',
+ '/work/website',
+ '/work/robotics',
+ '/work/release-notes',
+ ]);
+ expect(recent.every((row) => row.machineId == 'm'), isTrue);
+ box.focusField(NewHarnessField.project);
+ // All recents live in the menu; the folder prompt does not repeat them.
+ box.setQuery('release');
+ expect(box.options.single.id, NewHarnessController.browseId);
+ chooseMachine(box);
+ box.setQuery('Office');
+ box.accept();
+ expect(
+ box.options
+ .where((row) => !row.synthetic)
+ .map((row) => row.project?.folder),
+ ['/work/helmet', '/work/openharness/.worktrees/keyboard'],
+ );
+ });
+
+ testWidgets(
+ 'late project discovery refreshes an open menu without losing selection',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.projectHistory.select('m', '/work/chosen');
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/openharness',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ await mount(tester, box);
+ await tester.pump(const Duration(milliseconds: 200));
+ final selected = box.selected?.id;
+ final machine = app.machineStates['m']!;
+ machine.agents = [
+ ...machine.agents,
+ const Agent(id: 'late', name: 'Late'),
+ ];
+ machine.localProjects = const {
+ 'late': AgentProject(name: 'product-video', cwd: '/work/product-video'),
+ };
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(
+ box.options
+ .where((row) => !row.synthetic)
+ .map((row) => row.project?.folder),
+ [
+ '/work/openharness',
+ '/work/chosen',
+ '/work/product-video',
+ '/work/robotics',
+ '/work/release-notes',
+ ],
+ );
+ expect(find.text('product-video'), findsOneWidget);
+ expect(box.selected?.id, selected);
+ var changes = 0;
+ box.addListener(() => changes++);
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(changes, 0);
+ await tester.enterText(input, 'product video');
+ await tester.pump();
+ expect(box.selected!.project!.folder, '/work/product-video');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.project.folder, '/work/product-video');
+ expect(box.field, NewHarnessField.launch);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test(
+ 'Project filters names and paths and restores the query after a child',
+ () async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.projectHistory.select('m', '/work/team/payments-processing');
+ await app.projectHistory.select('m', '/work/notes-19');
+ await app.projectHistory.select('studio', '/work/remote-payments');
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/current',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ final total = box.total;
+ for (final query in [
+ 'PAYMENTS PROCESSING',
+ 'payments_processing',
+ '/work/team/payments',
+ ]) {
+ box.setQuery(query);
+ expect(box.selected!.project!.folder, '/work/team/payments-processing');
+ expect(box.matchCount, 1);
+ expect(box.total, total);
+ expect(box.options.where((row) => row.synthetic), hasLength(3));
+ }
+ box.setQuery('19');
+ expect(box.selected!.project!.folder, '/work/notes-19');
+ box.setQuery('no-matching-project');
+ expect(box.matchCount, 0);
+ expect(box.selected!.id, NewHarnessController.existingProjectId);
+ box.accept();
+ expect(box.field, NewHarnessField.project);
+ box.setQuery('/some/other/path');
+ box.back();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.query, 'no-matching-project');
+ expect(box.project.folder, '/work/current');
+ box.focusField(NewHarnessField.machine);
+ box.setQuery('Office');
+ box.accept();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.query, isEmpty);
+ box.setQuery('payments');
+ expect(box.selected!.project!.folder, '/work/remote-payments');
+ expect(
+ box.options
+ .where((row) => !row.synthetic)
+ .every((row) => row.machineId == 'studio'),
+ isTrue,
+ );
+ },
+ );
+
+ testWidgets(
+ 'missing project asks once, names it explicitly, and returns to launch',
+ (tester) async {
+ final app = createApp(connectionForTest: (id) => _Folders(id));
+ seedMixedAgents(app);
+ final box = NewHarnessController(app, machineId: 'm', engine: 'codex');
+ addTearDown(app.dispose);
+ addTearDown(box.dispose);
+ await mount(tester, box);
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.needsProject, isTrue);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('Choose a project'));
+ box.accept(
+ box.options.firstWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ),
+ );
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectName);
+ expect(find.text('M2:~/harnesses/<name>'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.error, 'Type a project name.');
+ await tester.enterText(input, 'payments processing');
+ await tester.pump();
+ expect(find.text('Create payments-processing'), findsOneWidget);
+ expect(find.text('M2:~/harnesses/payments-processing'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.field, NewHarnessField.launch);
+ expect(box.project.name, 'payments processing');
+ expect(
+ box.projectFolderRequest!.payload['projectName'],
+ 'payments-processing',
+ );
+ expect(box.needsProject, isFalse);
+ // Clearing the prefilled name cannot launch in the old project.
+ await openLaunchRow(tester, 'project');
+ await tester.pump();
+ box.accept(
+ box.options.firstWhere(
+ (row) => row.id == NewHarnessController.newProjectId,
+ ),
+ );
+ await tester.pump();
+ expect(box.query, 'payments processing');
+ await tester.enterText(input, '');
+ await tester.pump();
+ expect(await box.createNow(), NewHarnessOutcome.failed);
+ expect(box.error, 'Type a project name.');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectMenu);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(box.field, NewHarnessField.launch);
+ expect(box.project.name, 'payments processing');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test(
+ 'recent projects are chosen directly and invalid names cannot create',
+ () async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ await app.projectHistory.select('studio', '/work/payments-processing');
+ final box = NewHarnessController(
+ app,
+ machineId: 'studio',
+ engine: 'codex',
+ );
+ addTearDown(box.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ final recent = box.options.singleWhere(
+ (row) => row.project?.folder == '/work/payments-processing',
+ );
+ expect(recent.title, 'payments-processing');
+ box.accept(recent);
+ expect(box.machineId, 'studio');
+ expect(box.project.folder, '/work/payments-processing');
+ box.focusField(NewHarnessField.projectName);
+ box.setQuery('---');
+ final fresh = box.options.singleWhere((row) => row.id == 'project:new');
+ expect(fresh.enabled, isFalse);
+ box.accept(fresh);
+ expect(box.field, NewHarnessField.projectName);
+ expect(box.project.folder, '/work/payments-processing');
+ expect(box.error, contains('letters or numbers'));
+ },
+ );
+
+ testWidgets(
+ 'launch rows open focused prompts and Enter returns to the launch summary',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'claude',
+ folder: '/work/payments',
+ task: 'Review the retry path',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, box);
+ final agent = find.byKey(const ValueKey('new-harness-field-agent'));
+ final project = find.byKey(const ValueKey('new-harness-field-project'));
+ expect(tester.getRect(agent).top, lessThan(tester.getRect(project).top));
+ expect(input, findsNothing);
+ expect(find.text('/work/payments'), findsOneWidget);
+ expect(find.text('M2'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('new-harness-field-machine')),
+ findsOneWidget,
+ );
+ expect(
+ find.byKey(const ValueKey('new-harness-field-mode')),
+ findsNothing,
+ );
+ expect(find.text('Auto-approve'), findsNothing);
+ for (final (name, field) in [
+ ('agent', NewHarnessField.agent),
+ ('machine', NewHarnessField.machine),
+ ('project', NewHarnessField.projectMenu),
+ ('task', NewHarnessField.task),
+ ]) {
+ await openLaunchRow(tester, name);
+ await tester.pump();
+ expect(box.field, field);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(box.field, NewHarnessField.launch);
+ }
+ await openLaunchRow(tester, 'project');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ await tester.enterText(input, 'payments processing');
+ await tester.pump();
+ expect(find.text('Create payments-processing'), findsOneWidget);
+ expect(find.text('M2:~/harnesses/payments-processing'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.field, NewHarnessField.launch);
+ expect(box.task, 'Review the retry path');
+ expect(
+ box.projectFolderRequest!.payload['projectName'],
+ 'payments-processing',
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'machine is nested in Project and switching back restores its folder',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/payments',
+ task: 'Keep this task',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, box);
+ box.focusField(NewHarnessField.project);
+ box.setQuery('payments processing');
+ chooseMachine(box);
+ await tester.pump();
+ expect(box.field, NewHarnessField.machine);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.query, isEmpty);
+ chooseMachine(box);
+ box.setQuery('Office');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(box.field, NewHarnessField.projectMenu);
+ expect(box.machineId, 'studio');
+ expect(box.project.folder, isNull);
+ expect(box.query, isEmpty);
+ expect(box.task, 'Keep this task');
+ box.setFolder('/work/remote-payments');
+ expect(box.field, NewHarnessField.launch);
+ box.focusField(NewHarnessField.project);
+ chooseMachine(box);
+ box.setQuery('M2');
+ box.accept();
+ expect(box.machineId, 'm');
+ expect(box.project.folder, '/work/payments');
+ // This cache travels with the draft through Escape and More options.
+ final restored = NewHarnessController(
+ app,
+ machineId: 'm',
+ draft: box.draft,
+ );
+ addTearDown(restored.dispose);
+ restored.focusField(NewHarnessField.machine);
+ restored.setQuery('Office');
+ restored.accept();
+ expect(restored.project.folder, '/work/remote-payments');
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test(
+ 'project choices belong only to the selected machine, including stale rows',
+ () async {
+ final app = createApp();
+ seedMixedAgents(app);
+ await app.projectHistory.select('m', '/work/payments');
+ await app.projectHistory.select('studio', '/work/payments');
+ await app.projectHistory.select('build', '/work/payments');
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/work/payments',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ box.focusField(NewHarnessField.projectMenu);
+ final recents = box.options
+ .where((row) => row.project?.folder == '/work/payments')
+ .toList();
+ expect(recents, hasLength(1));
+ expect(recents.single.machineId, 'm');
+ chooseMachine(box);
+ box.setQuery('build');
+ box.accept();
+ expect(box.field, NewHarnessField.machine);
+ expect(box.error, contains('offline'));
+ box.setQuery('Office');
+ box.accept();
+ expect(box.machineId, 'studio');
+ expect(box.field, NewHarnessField.projectMenu);
+ final remote = box.options.singleWhere(
+ (row) => row.project?.folder == '/work/payments',
+ );
+ expect(remote.machineId, 'studio');
+ expect(remote.detail, 'iMac · Office:/work/payments');
+ box.accept(recents.single);
+ expect(box.machineId, 'studio');
+ expect(box.error, contains('machine has changed'));
+ box.accept(remote);
+ expect(box.project.folder, '/work/payments');
+ expect(box.field, NewHarnessField.launch);
+ },
+ );
+
+ testWidgets(
+ 'remote home resolves tilde completion and an existing named project',
+ (tester) async {
+ final connections = <String, _Folders>{};
+ final app = createApp(
+ connectionForTest: (id) =>
+ connections.putIfAbsent(id, () => _Folders(id)),
+ );
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'studio',
+ engine: 'claude',
+ folder: '/home/studio/work/payments',
+ home: '/local-only-home',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, box);
+ expect(box.projectLocation, 'iMac · Office:~/work/payments');
+ box.focusField(NewHarnessField.project);
+ box.setQuery('~/work/pa');
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump();
+ expect(box.options.first.id, NewHarnessController.browseId);
+ expect(box.selected!.project!.folder, '/home/studio/work/payments');
+ expect(box.complete(), '~/work/payments/');
+ box.focusField(NewHarnessField.projectName);
+ box.setQuery('payments processing');
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.pump();
+ final row = box.options.firstWhere((row) => row.id == 'project:new');
+ expect(row.title, 'Open existing payments-processing');
+ expect(row.detail, 'iMac · Office:~/harnesses/payments-processing');
+ box.accept(row);
+ expect(box.project.folder, '/home/studio/harnesses/payments-processing');
+ expect(box.projectFolderRequest, isNull);
+ expect(connections['studio']!.paths, contains('/home/studio/work'));
+ expect(
+ connections['studio']!.paths.any(
+ (path) => path?.startsWith('/local-only-home') == true,
+ ),
+ isFalse,
+ );
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'a late home answer does not move a project to the previous machine',
+ (tester) async {
+ final local = _Folders('m')
+ ..pendingHome = Completer<Map<String, dynamic>>();
+ final remote = _Folders('studio');
+ final app = createApp(
+ connectionForTest: (id) => id == 'm' ? local : remote,
+ );
+ seedMixedAgents(app);
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: 'codex',
+ folder: '/home/m/payments',
+ );
+ addTearDown(box.dispose);
+ addTearDown(app.dispose);
+ await mount(tester, box);
+ box.focusField(NewHarnessField.machine);
+ box.setQuery('Office');
+ box.accept();
+ box.setFolder('/home/studio/payments');
+ await tester.pump();
+ local.pendingHome!.complete({'path': '/home/m', 'entries': []});
+ await tester.pump();
+ expect(box.machineId, 'studio');
+ expect(box.projectLocation, 'iMac · Office:~/payments');
+ expect(box.field, NewHarnessField.launch);
+ await tester.pump(const Duration(milliseconds: 200));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+}
diff --git a/desktop/test/orchestrator_test.dart b/desktop/test/orchestrator_test.dart
index 581c517c2..ba0521c6a 100644
--- a/desktop/test/orchestrator_test.dart
+++ b/desktop/test/orchestrator_test.dart
@@ -119,15 +119,17 @@ void main() {
);
}
- test('Cmd-P is two keys and leaves Cmd-B and Shift-Cmd-P distinct', () {
- final shortcut = kAppShortcuts
- .singleWhere((s) => s.action == ShortcutAction.orchestrate)
+ test('Cmd-P opens a pane and the orchestrator remains a palette command', () {
+ final shortcut = appShortcuts()
+ .singleWhere((s) => s.action == ShortcutAction.addAgent)
.activator;
expect(shortcut.trigger, LogicalKeyboardKey.keyP);
expect(shortcut.meta, isTrue);
expect(shortcut.shift, isFalse);
- expect(shortcut.control, isFalse);
- expect(shortcut.alt, isFalse);
+ expect(
+ kAppShortcuts.where((s) => s.action == ShortcutAction.orchestrate),
+ isEmpty,
+ );
expect(
kAppShortcuts
.singleWhere((s) => s.action == ShortcutAction.routeTask)
diff --git a/desktop/test/pane_machine_unknown_test.dart b/desktop/test/pane_machine_unknown_test.dart
index c7062d24b..78554d51b 100644
--- a/desktop/test/pane_machine_unknown_test.dart
+++ b/desktop/test/pane_machine_unknown_test.dart
@@ -4,8 +4,12 @@
// machine LIST itself could not be read, the machine is not slow — it is unknown, and a spinner that
// never ends tells the user nothing and offers them nothing. This is the difference between those two.
import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/api/api_client.dart';
import 'package:harness/auth/auth_session.dart';
@@ -14,11 +18,19 @@ import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/widgets/pane_grid.dart';
import 'package:harness/ws/local_cli_discovery.dart';
+import 'support/real_fonts.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
class _Api extends ApiClient {
- _Api() : super(config: AppConfig.dev, session: AuthSession());
+ _Api()
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
final lists = <Completer<List<Machine>>>[];
@override
@@ -55,7 +67,7 @@ class _App extends AppNotifier {
_App(_Api api)
: super(
config: AppConfig.dev,
- authSession: AuthSession(),
+ authSession: AuthSession(storage: MemoryStore()),
cliLogin: _Cli(),
localCliDiscovery: _Discovery(),
configStore: null,
@@ -67,6 +79,10 @@ class _App extends AppNotifier {
}
const _waiting = 'Waiting for this machine to answer…';
+const _unavailable =
+ 'This machine isn’t available. Check that it’s still linked to your account.';
+const _unconfirmed =
+ 'Could not confirm this machine’s status. Retry to reconnect.';
/// Run the refresh chain until it has actually asked for the list.
///
@@ -84,9 +100,33 @@ Future<void> _untilRequested(WidgetTester tester, _Api api, int count) async {
);
}
-Future<void> _pump(WidgetTester tester, AppNotifier app) async {
+Future<void> _pump(
+ WidgetTester tester,
+ AppNotifier app, {
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ GlobalKey? boundary,
+}) async {
+ grid.AppTheme.brightness.value = brightness;
await tester.pumpWidget(
- MaterialApp(home: PaneGrid(notifier: app, swarmMode: false)),
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => PaneGrid(notifier: app, swarmMode: false),
+ ),
+ ),
+ ),
+ ),
);
await tester.pump();
}
@@ -95,8 +135,17 @@ void main() {
late _Api api;
late _App app;
late bool disposed;
+ late Brightness previousBrightness;
+
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
setUp(() {
+ previousBrightness = grid.AppTheme.brightness.value;
api = _Api();
app = _App(api);
disposed = false;
@@ -107,6 +156,7 @@ void main() {
tearDown(() {
if (!disposed) app.dispose();
+ grid.AppTheme.brightness.value = previousBrightness;
});
// A failed load leaves the automatic recovery timer armed (by design — it is what gets the list back).
@@ -122,49 +172,193 @@ void main() {
) async {
await _pump(tester, app);
expect(find.text(_waiting), findsOneWidget);
- expect(find.text('RETRY'), findsNothing);
+ expect(find.text('Retry'), findsNothing);
end();
});
- testWidgets('says the machine is unknown, and offers a retry, once the list fails', (
+ testWidgets(
+ 'says the machine is unknown, and offers a retry, once the list fails',
+ (tester) async {
+ final retry = app.retryMachines();
+ await _untilRequested(tester, api, 1);
+ api.lists.single.completeError(
+ ApiException('Could not reach the Harness backend', status: 502),
+ );
+ await retry;
+ await _pump(tester, app);
+
+ expect(find.text(_waiting), findsNothing);
+ expect(
+ find.text('Could not load machines. Retry to reconnect.'),
+ findsOneWidget,
+ );
+ expect(find.byIcon(Icons.cloud_off), findsOneWidget);
+
+ // And the button reaches the same reload the error strip's RETRY does.
+ expect(api.lists, hasLength(1));
+ await tester.tap(find.text('Retry'));
+ await _untilRequested(tester, api, 2);
+ end();
+ },
+ );
+
+ testWidgets('explains when a recovered list does not contain the machine', (
tester,
) async {
- final retry = app.retryMachines();
+ final failed = app.retryMachines();
await _untilRequested(tester, api, 1);
- api.lists.single.completeError(
- ApiException('Could not reach the Harness backend', status: 502),
- );
- await retry;
+ api.lists.single.completeError(ApiException('boom', status: 502));
+ await failed;
await _pump(tester, app);
-
- expect(find.text(_waiting), findsNothing);
- expect(find.textContaining('this machine is unknown'), findsOneWidget);
expect(find.byIcon(Icons.cloud_off), findsOneWidget);
- // And the button reaches the same reload the error strip's RETRY does.
- expect(api.lists, hasLength(1));
- await tester.tap(find.text('RETRY'));
+ final ok = app.retryMachines();
await _untilRequested(tester, api, 2);
+ api.lists.last.complete(const []);
+ await ok;
+ await _pump(tester, app);
+
+ // A completed list with no matching machine cannot promise an answer.
+ expect(find.text(_unavailable), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.text('Retry'), findsOneWidget);
+ expect(find.text(kUntitledPane), findsOneWidget);
+ expect(find.text('a0'), findsNothing);
end();
});
- testWidgets('goes back to waiting once the list loads again', (tester) async {
- final failed = app.retryMachines();
+ testWidgets('a fresh empty inventory ends the indefinite waiting state', (
+ tester,
+ ) async {
+ final refresh = app.refreshMachines();
await _untilRequested(tester, api, 1);
- api.lists.single.completeError(ApiException('boom', status: 502));
- await failed;
await _pump(tester, app);
- expect(find.byIcon(Icons.cloud_off), findsOneWidget);
+ expect(find.text(_waiting), findsOneWidget);
+ api.lists.single.complete(const []);
+ await refresh;
+ await tester.pump();
- final ok = app.retryMachines();
+ expect(find.text(_unavailable), findsOneWidget);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.text('Retry'), findsOneWidget);
+ end();
+ });
+
+ testWidgets(
+ 'a cached empty inventory does not claim the machine is missing',
+ (tester) async {
+ final refresh = app.refreshMachines();
+ await _untilRequested(tester, api, 1);
+ api.lists.single.complete(MachineInventory([], isStale: true));
+ await refresh;
+ await _pump(tester, app);
+
+ expect(find.text(_unconfirmed), findsOneWidget);
+ expect(find.text(_unavailable), findsNothing);
+ expect(find.byType(CircularProgressIndicator), findsNothing);
+ expect(find.text('Retry'), findsOneWidget);
+ end();
+ },
+ );
+
+ testWidgets('Retry keeps keyboard focus during and after a refresh', (
+ tester,
+ ) async {
+ final refresh = app.refreshMachines();
+ await _untilRequested(tester, api, 1);
+ api.lists.single.complete(const []);
+ await refresh;
+ await _pump(tester, app);
+ final resting = tester.getRect(find.widgetWithText(TextButton, 'Retry'));
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await _untilRequested(tester, api, 2);
+ expect(find.text('Retry'), findsOneWidget);
+ expect(find.text(_unavailable), findsOneWidget);
+ expect(tester.getRect(find.widgetWithText(TextButton, 'Retry')), resting);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(api.lists, hasLength(2), reason: 'a pending retry is coalesced');
+
api.lists.last.complete(const []);
- await ok;
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await _untilRequested(tester, api, 3);
+ expect(find.text('Retry'), findsOneWidget);
+ end();
+ });
+
+ testWidgets('an account change clears the completed inventory state', (
+ tester,
+ ) async {
+ final refresh = app.refreshMachines();
+ await _untilRequested(tester, api, 1);
+ api.lists.single.complete(const []);
+ await refresh;
+ await app.logout();
+ app.status = AppStatus.authenticated;
+ app.panes.add(TerminalPane(id: 1, machineId: 'm', agentId: 'a0'));
await _pump(tester, app);
- // The list is readable again; this machine is merely absent from it.
expect(find.text(_waiting), findsOneWidget);
- expect(find.text('RETRY'), findsNothing);
+ expect(find.text('Retry'), findsNothing);
end();
});
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.8]) {
+ for (final state in ['missing', 'cached', 'failed']) {
+ testWidgets('small pane recovery $state in $brightness at $scale', (
+ tester,
+ ) async {
+ tester.view.physicalSize = const Size(440, 240);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final retry = app.retryMachines();
+ await _untilRequested(tester, api, 1);
+ if (state == 'failed') {
+ api.lists.single.completeError(
+ ApiException('fixture outage', status: 502),
+ );
+ } else {
+ api.lists.single.complete(
+ MachineInventory([], isStale: state == 'cached'),
+ );
+ }
+ await retry;
+ final boundary = GlobalKey();
+ await _pump(
+ tester,
+ app,
+ brightness: brightness,
+ scale: scale,
+ boundary: boundary,
+ );
+ expect(tester.takeException(), isNull);
+ final action = find.widgetWithText(TextButton, 'Retry');
+ expect(action, findsOneWidget);
+ expect(tester.getRect(action).bottom, lessThanOrEqualTo(240));
+ final output = Platform.environment['HARNESS_PANE_CAPTURE_DIR'];
+ if (output != null) {
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File('$output/$state-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ end();
+ });
+ }
+ }
+ }
}
diff --git a/desktop/test/pane_restart_test.dart b/desktop/test/pane_restart_test.dart
index e8f9c4f43..eea6cdb68 100644
--- a/desktop/test/pane_restart_test.dart
+++ b/desktop/test/pane_restart_test.dart
@@ -37,10 +37,10 @@ void main() {
({'resumed': true}, null),
(
{'resumed': false},
- 'Restarted with a new session — the previous one could not be resumed.',
+ 'Started a new conversation. The previous session could not be resumed.',
),
(
- {'error': 'RESTART_FAILED', 'detail': 'The engine could not restart.'},
+ {'error': 'AGENT_BUSY', 'detail': 'The engine could not restart.'},
'The engine could not restart.',
),
]) {
@@ -62,10 +62,10 @@ void main() {
await tester.tap(
find.descendant(
of: controls,
- matching: find.byTooltip('Restart Harness'),
+ matching: find.byTooltip('Restart Agent'),
),
);
- await tester.pump();
+ await tester.pumpAndSettle();
// Each pane header's model picker also asks for grid_models_list as it mounts; the restart is
// the one request that is not that.
final sent = connection.calls
@@ -73,7 +73,7 @@ void main() {
.toList();
expect(sent, hasLength(1));
expect(sent.single.$1, 'agent_restart');
- expect(sent.single.$2, {'agentId': 'a0'});
+ expect(sent.single.$2, {'agentId': 'a0', 'creationId': isA<String>()});
expect(app.panes, [first, second]);
expect(first.session, same(session));
expect(find.byType(AlertDialog), findsNothing);
@@ -90,7 +90,7 @@ void main() {
of: controls,
matching: find.byWidgetPredicate(
(widget) =>
- widget is IconButton && widget.tooltip == 'Restart Harness',
+ widget is IconButton && widget.tooltip == 'Restart Agent',
),
),
);
diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dart
index bf6c991ef..14723dc86 100644
--- a/desktop/test/profile_startup_test.dart
+++ b/desktop/test/profile_startup_test.dart
@@ -388,6 +388,75 @@ void main() {
);
}
+ test(
+ 'newer machine inventory cannot be replaced by an older reply',
+ () async {
+ app.status = AppStatus.authenticated;
+ final old = app.refreshMachines();
+ await _tick();
+ final current = app.refreshMachines();
+ await _tick();
+ expect(api.lists, hasLength(2));
+ api.lists.last.complete([_machine.copyWith(name: 'Current computer')]);
+ expect(await current, isTrue);
+ api.lists.first.complete([_machine.copyWith(name: 'Old computer')]);
+ expect(await old, isFalse);
+ expect(app.machines.single.displayName, 'Current computer');
+ expect(
+ app.machineStates['fixture']!.machine.displayName,
+ 'Current computer',
+ );
+ },
+ );
+
+ for (final failure in [false, true]) {
+ test(
+ 'superseded inventory ${failure ? 'failure' : 'success'} leaves the current loading state alone',
+ () async {
+ app.status = AppStatus.authenticated;
+ final old = app.refreshMachines();
+ await _tick();
+ final current = app.refreshMachines();
+ await _tick();
+ if (failure) {
+ api.lists.first.completeError(
+ ApiException('Old failure', status: 403),
+ );
+ } else {
+ api.lists.first.complete([_machine]);
+ }
+ expect(await old, isFalse);
+ expect(app.machinesLoading, isTrue);
+ expect(app.machines, isEmpty);
+ api.lists.last.complete([_machine]);
+ expect(await current, isTrue);
+ expect(app.machinesLoading, isFalse);
+ expect(app.machines, [_machine]);
+ },
+ );
+ }
+
+ test(
+ 'older inventory success cannot dismiss the latest retry error',
+ () async {
+ app.status = AppStatus.authenticated;
+ final old = app.refreshMachines();
+ await _tick();
+ final current = app.retryMachines();
+ await _tick();
+ api.profiles.single.complete(null);
+ api.lists.last.completeError(
+ ApiException('Current inventory failure', status: 403),
+ );
+ await current;
+ api.lists.first.complete([_machine]);
+ await old;
+ expect(app.lastError, contains('Current inventory failure'));
+ expect(app.machines, isEmpty);
+ expect(app.machinesLoading, isFalse);
+ },
+ );
+
test('a late profile response cannot restore a signed-out account', () async {
final start = app.login();
await Future<void>.delayed(Duration.zero);
@@ -405,6 +474,23 @@ void main() {
expect(connection.requests, isEmpty);
});
+ test(
+ 'a late machine response cannot restore signed-out cache status',
+ () async {
+ app.status = AppStatus.authenticated;
+ final pending = app.refreshMachines();
+ await _tick();
+ expect(api.lists, hasLength(1));
+ await app.logout();
+ api.lastMachinesStale = true;
+ api.lists.single.complete([_machine]);
+ await pending;
+ expect(app.machinesAreStale, isFalse);
+ expect(app.machines, isEmpty);
+ expect(app.machineStates, isEmpty);
+ },
+ );
+
test(
'a late profile publishes account details without reloading agents',
() async {
diff --git a/desktop/test/project_folder_test.dart b/desktop/test/project_folder_test.dart
index 19434c271..0fdc23041 100644
--- a/desktop/test/project_folder_test.dart
+++ b/desktop/test/project_folder_test.dart
@@ -57,6 +57,22 @@ void main() {
);
expect(projectFolderName('***', at), 'harness-2026-12-25-00-00');
});
+ test('long suggested names preserve the timestamp through remote name limits and collisions', () {
+ final request = ProjectFolderRequest.generated(
+ label: 'A very long descriptive name for a custom harness from the store',
+ at: DateTime(2026, 9, 20, 17, 22, 19),
+ );
+ final names = <String>[];
+ for (var i = 0; i < 105; i++) {
+ final name = request.availableGeneratedName(names);
+ expect(name.length, lessThanOrEqualTo(64));
+ expect(name, contains('-2026-09-20-17-22'));
+ expect(request.withGeneratedName(name).payload['projectName'], name);
+ names.add(name);
+ }
+ expect(names.toSet(), hasLength(105));
+ expect(names.last, endsWith('-2026-09-20-17-22-19-104'));
+ });
test(
'remote repository uses the existing safe clone on this computer',
() async {
diff --git a/desktop/test/prompt_editing_test.dart b/desktop/test/prompt_editing_test.dart
new file mode 100644
index 000000000..fc6505fdc
--- /dev/null
+++ b/desktop/test/prompt_editing_test.dart
@@ -0,0 +1,126 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/widgets/box_chrome.dart';
+
+import 'keymap_host_test.dart' show key;
+
+void main() {
+ Future<TextEditingController> editor(
+ WidgetTester tester, {
+ bool enabled = true,
+ }) async {
+ final controller = TextEditingController();
+ addTearDown(controller.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ReadlineKeys(
+ enabled: enabled,
+ controller: controller,
+ onChanged: (_) {},
+ child: TextField(
+ autofocus: true,
+ controller: controller,
+ maxLines: 5,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ return controller;
+ }
+
+ for (final backwards in [true, false]) {
+ testWidgets(
+ 'Ctrl-${backwards ? 'H' : 'D'} deletes one visible character',
+ variant: TargetPlatformVariant({
+ TargetPlatform.macOS,
+ TargetPlatform.linux,
+ }),
+ (tester) async {
+ final controller = await editor(tester);
+ for (final character in ['🐙', '👩🏽‍💻', 'e\u0301', '🇻🇳']) {
+ controller.value = TextEditingValue(
+ text: 'a${character}b',
+ selection: TextSelection.collapsed(
+ offset: backwards ? 1 + character.length : 1,
+ ),
+ );
+ await key(
+ tester,
+ backwards ? LogicalKeyboardKey.keyH : LogicalKeyboardKey.keyD,
+ ctrl: true,
+ );
+ expect(controller.text, 'ab', reason: character);
+ expect(
+ controller.selection,
+ const TextSelection.collapsed(offset: 1),
+ );
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('kill word respects lines and path segments, and can be yanked', (
+ tester,
+ ) async {
+ final controller = await editor(tester);
+ await tester.enterText(find.byType(TextField), 'first line\nsecond');
+ await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
+ expect(controller.text, 'first line\n');
+ await key(tester, LogicalKeyboardKey.keyY, ctrl: true);
+ expect(controller.text, 'first line\nsecond');
+ await tester.enterText(find.byType(TextField), '/work/emoji-🐙/source\t');
+ await key(tester, LogicalKeyboardKey.keyW, ctrl: true);
+ expect(controller.text, '/work/emoji-🐙/');
+ await key(tester, LogicalKeyboardKey.keyY, ctrl: true);
+ expect(controller.text, '/work/emoji-🐙/source\t');
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('kill line keeps preceding task lines and restores with Ctrl-Y', (
+ tester,
+ ) async {
+ final controller = await editor(tester);
+ controller.value = const TextEditingValue(
+ text: 'first line\nedit here\nlast line',
+ selection: TextSelection.collapsed(offset: 15),
+ );
+ await key(tester, LogicalKeyboardKey.keyU, ctrl: true);
+ expect(controller.text, 'first line\n here\nlast line');
+ await key(tester, LogicalKeyboardKey.keyY, ctrl: true);
+ expect(controller.text, 'first line\nedit here\nlast line');
+ expect(controller.selection, const TextSelection.collapsed(offset: 15));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('editing keys preserve composition and a locked prompt', (
+ tester,
+ ) async {
+ for (final enabled in [true, false]) {
+ final controller = await editor(tester, enabled: enabled);
+ final value = TextEditingValue(
+ text: '日本語 🐙',
+ selection: const TextSelection.collapsed(offset: 2),
+ composing: enabled
+ ? const TextRange(start: 0, end: 3)
+ : TextRange.empty,
+ );
+ controller.value = value;
+ for (final letter in [
+ LogicalKeyboardKey.keyH,
+ LogicalKeyboardKey.keyD,
+ LogicalKeyboardKey.keyW,
+ LogicalKeyboardKey.keyU,
+ LogicalKeyboardKey.keyY,
+ ]) {
+ await key(tester, letter, ctrl: true);
+ expect(controller.value, value);
+ }
+ await tester.pumpWidget(const SizedBox());
+ }
+ });
+}
diff --git a/desktop/test/quick_access_test.dart b/desktop/test/quick_access_test.dart
new file mode 100644
index 000000000..5347c7c8e
--- /dev/null
+++ b/desktop/test/quick_access_test.dart
@@ -0,0 +1,196 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/state/swarm_search.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' as configured;
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ for (final placement in HarnessPlacement.values) {
+ test('prefixes switch lists and retain $placement', () {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final command = SwarmDestination(
+ id: 'command:app.store',
+ title: 'Harness Store',
+ detail: '',
+ swarmId: null,
+ current: false,
+ commandId: 'app.store',
+ );
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ placement: placement,
+ commands: () => [command],
+ );
+ addTearDown(search.dispose);
+ final target = search.targetId;
+ expect(
+ search.rows
+ .where((row) => !row.isCreate)
+ .every((row) => row.agentId != null),
+ isTrue,
+ );
+ search.setQuery('> store');
+ expect(search.rows.single.commandId, 'app.store');
+ expect(search.createTask, isNull);
+ search.setQuery('@ Office');
+ expect(search.rows.single.isMachine, isTrue);
+ expect(search.rows.single.machineId, 'studio');
+ search.setQuery('# openharness');
+ expect(search.rows.single.isProject, isTrue);
+ search.setQuery('');
+ expect(search.rows.any((row) => row.isCreate), isTrue);
+ expect(
+ search.rows
+ .where((row) => !row.isCreate)
+ .every((row) => row.agentId != null),
+ isTrue,
+ );
+ expect(search.placement, placement);
+ expect(search.targetId, target);
+ });
+ }
+
+ test('project and machine selections narrow to individual agents and revalidate discovery', () {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final search = SwarmSearchController(
+ app,
+ const [],
+ adding: true,
+ offersCreate: true,
+ placement: HarnessPlacement.newTab,
+ );
+ addTearDown(search.dispose);
+ search.setQuery('# openharness');
+ expect(search.submit(), isNull);
+ expect(search.query, isEmpty);
+ expect(search.canGoBack, isTrue);
+ expect(
+ search.rows.map((row) => row.agentId),
+ unorderedEquals(['a0', 'a1', 'focus', 'login']),
+ );
+ search.setQuery('keyboard');
+ expect(search.rows.single.agentId, 'focus');
+ expect(search.submit()?.destination.agentId, 'focus');
+ expect(search.back(), isTrue);
+ expect(search.query, '# openharness');
+ search.setQuery('@ Office');
+ final stale = search.selected!;
+ expect(search.submit(), isNull);
+ expect(
+ search.rows.map((row) => row.agentId),
+ unorderedEquals(['focus', 'helmet']),
+ );
+ expect(search.rows.every((row) => row.machineId == 'studio'), isTrue);
+ app.machineStates['studio']!.agents = [];
+ app.notifyListeners();
+ expect(
+ search.rows,
+ isEmpty,
+ reason: 'A missing group must never fall back to all agents',
+ );
+ app.machineStates.remove('studio');
+ app.notifyListeners();
+ search.back();
+ expect(search.submit(stale), isNull);
+ search.setQuery('');
+ expect(search.canGoBack, isFalse);
+ expect(search.rows.any((row) => row.agentId == 'a0'), isTrue);
+ });
+
+ for (final entry in [LogicalKeyboardKey.keyP, LogicalKeyboardKey.keyT]) {
+ testWidgets(
+ 'Quick Access stays in the same picker from ${entry.keyLabel}',
+ (tester) async {
+ final app = createApp();
+ seedMixedAgents(app);
+ addTearDown(app.dispose);
+ final frames = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', frames));
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ await configured.mount(tester, app, map);
+ final tabs = app.swarms.length;
+ await key(tester, entry, cmd: true);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final field = tester.widget<TextField>(input);
+ final search = tester
+ .widget<SwarmSearchResults>(
+ find.descendant(
+ of: find.byKey(const ValueKey('swarm-search-results')),
+ matching: find.byType(SwarmSearchResults),
+ ),
+ )
+ .search;
+ final placement = search.placement;
+ Future<void> type(String text) async {
+ await tester.enterText(input, text);
+ await tester.pump();
+ }
+
+ await type('? #');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search.isProjectMode, isTrue);
+ expect(
+ tester.widget<TextField>(input).controller,
+ same(field.controller),
+ );
+ expect(field.focusNode!.hasFocus, isTrue);
+ await type('# openharness');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search.canGoBack, isTrue);
+ expect(search.rows.every((row) => row.agentId != null), isTrue);
+ expect(app.swarms, hasLength(tabs));
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(field.controller!.text, '# openharness');
+ await type('? @');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(field.controller!.text, '@ ');
+ await type('@ Office');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(search.rows.every((row) => row.machineId == 'studio'), isTrue);
+ expect(field.focusNode!.hasFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(field.controller!.text, '@ Office');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ expect(field.controller!.text, '> ');
+ expect(search.isCommandMode, isTrue);
+ expect(search.canGoBack, isFalse);
+ // Backspace leaves command mode without closing/reopening the dock.
+ await key(tester, LogicalKeyboardKey.backspace);
+ await key(tester, LogicalKeyboardKey.backspace);
+ expect(search.isCommandMode, isFalse);
+ expect(
+ search.rows
+ .where((row) => !row.isCreate)
+ .every((row) => row.agentId != null),
+ isTrue,
+ );
+ expect(search.placement, placement);
+ expect(
+ tester.widget<TextField>(input).controller,
+ same(field.controller),
+ );
+ expect(frames, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(input, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+}
diff --git a/desktop/test/remote_folder_picker_test.dart b/desktop/test/remote_folder_picker_test.dart
index 507505471..c388f218e 100644
--- a/desktop/test/remote_folder_picker_test.dart
+++ b/desktop/test/remote_folder_picker_test.dart
@@ -7,6 +7,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
@@ -57,6 +58,7 @@ class _Folders extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
launches.add((machine: machineId, engine: engine, folder: folder!));
return null;
diff --git a/desktop/test/remote_password_state_test.dart b/desktop/test/remote_password_state_test.dart
new file mode 100644
index 000000000..9c0f6dd25
--- /dev/null
+++ b/desktop/test/remote_password_state_test.dart
@@ -0,0 +1,153 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_link.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/state/app_state.dart';
+
+import 'support/password_cli.dart';
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ late PasswordCli cli;
+ late AppNotifier app;
+ setUp(() {
+ cli = PasswordCli();
+ app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ );
+ });
+ tearDown(() => app.dispose());
+
+ test(
+ 'a pending change rejects competing mutations while status joins it',
+ () async {
+ cli.setReply = Completer<RemotePasswordSetResult>();
+ final first = app.setRemotePassword('fixture password');
+ final pending = app.pendingRemotePasswordChange!;
+ final status = app.remotePasswordStatus();
+ expect(await app.clearRemotePassword(), contains('already in progress'));
+ expect(
+ (await app.setRemotePassword('another fixture')).error,
+ contains('already in progress'),
+ );
+ expect(cli.passwords, ['fixture password']);
+ expect(cli.clears, 0);
+ expect(cli.reads, 0);
+ cli.setReply!.complete(cli.setResult);
+ expect((await first).error, isNull);
+ expect((await pending).hasPassword, isTrue);
+ expect((await status).fingerprint, '1535·C035·9474·FE9D');
+ expect(app.pendingRemotePasswordChange, isNull);
+ },
+ );
+
+ test(
+ 'a stale status read cannot overwrite a completed password change',
+ () async {
+ final slow = Completer<RemotePasswordStatus>();
+ cli.statusReply = slow;
+ final reading = app.remotePasswordStatus();
+ cli.statusReply = null;
+ await app.setRemotePassword('fixture password');
+ slow.complete(const RemotePasswordStatus());
+ final result = await reading;
+ expect(result.hasPassword, isTrue);
+ expect(result.fingerprint, '1535·C035·9474·FE9D');
+ expect(cli.reads, 2);
+ },
+ );
+
+ test(
+ 'unexpected change failure releases the operation and can be retried',
+ () async {
+ cli.clearFailure = StateError('fixture secret');
+ expect(
+ await app.clearRemotePassword(),
+ 'Could not clear the password. Try again.',
+ );
+ expect(app.pendingRemotePasswordChange, isNull);
+ cli.clearFailure = null;
+ expect(await app.clearRemotePassword(), isNull);
+ expect(cli.clears, 2);
+ },
+ );
+
+ test(
+ 'pending changes complete safely after their notifier is disposed',
+ () async {
+ final disposed = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ cliLink: cli,
+ );
+ cli.setReply = Completer<RemotePasswordSetResult>();
+ final request = disposed.setRemotePassword('fixture password');
+ disposed.dispose();
+ cli.setReply!.complete(cli.setResult);
+ expect((await request).error, contains('no longer active'));
+ expect(disposed.pendingRemotePasswordChange, isNull);
+ },
+ );
+
+ test(
+ 'linked machine refresh joins its request and keeps known rows on failure',
+ () async {
+ final machine = LinkedMachine(
+ machineId: 'build',
+ fingerprint: 'fixture',
+ linkedAt: '2026-09-19 12:00',
+ );
+ cli.links = CliLinkListResult(machines: [machine]);
+ await app.refreshLinkedMachines();
+ cli.listReply = Completer<CliLinkListResult>();
+ final first = app.refreshLinkedMachines();
+ final second = app.refreshLinkedMachines();
+ expect(identical(first, second), isTrue);
+ expect(cli.lists, 2);
+ cli.listReply!.complete(
+ const CliLinkListResult(error: 'Cannot load links'),
+ );
+ await first;
+ expect(app.linkedMachines, [machine]);
+ expect(app.linkedMachinesError, 'Cannot load links');
+ expect(app.linkedMachinesLoading, isFalse);
+ cli.listReply = null;
+ cli.listFailure = StateError('fixture');
+ await app.refreshLinkedMachines();
+ expect(app.linkedMachines, [machine]);
+ expect(
+ app.linkedMachinesError,
+ 'Could not load linked machines. Try again.',
+ );
+ expect(app.linkedMachinesLoading, isFalse);
+ },
+ );
+
+ test('unlink joins its request and does not restore removed rows on refresh failure', () async {
+ final machine = LinkedMachine(
+ machineId: 'build',
+ fingerprint: 'fixture',
+ linkedAt: '2026-09-19 12:00',
+ );
+ cli.links = CliLinkListResult(machines: [machine]);
+ await app.refreshLinkedMachines();
+ cli.unlinkReply = Completer<String?>();
+ final first = app.unlinkMachine('build');
+ final second = app.unlinkMachine('build');
+ expect(identical(first, second), isTrue);
+ expect(app.unlinkingMachine('build'), isTrue);
+ cli.listFailure = StateError('fixture');
+ cli.unlinkReply!.complete(null);
+ expect(await first, isNull);
+ expect(app.unlinkingMachine('build'), isFalse);
+ expect(cli.unlinks, ['build']);
+ expect(app.linkedMachines, isEmpty);
+ expect(app.linkedMachinesError, isNotNull);
+ });
+}
diff --git a/desktop/test/rename_agent_dialog_test.dart b/desktop/test/rename_agent_dialog_test.dart
index 03378df09..5a12416aa 100644
--- a/desktop/test/rename_agent_dialog_test.dart
+++ b/desktop/test/rename_agent_dialog_test.dart
@@ -52,14 +52,14 @@ void main() {
);
await tester.tap(find.text('rename'));
await tester.pumpAndSettle();
- expect(find.text('Rename Harness'), findsOneWidget);
+ expect(find.text('Rename Agent'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
// Pumped through the WHOLE exit transition, which is the window the bug
// lived in: one pump would settle before the rebuild that threw.
await tester.pumpAndSettle();
- expect(find.text('Rename Harness'), findsNothing);
+ expect(find.text('Rename Agent'), findsNothing);
expect(
tester.takeException(),
isNull,
diff --git a/desktop/test/rename_keyboard_test.dart b/desktop/test/rename_keyboard_test.dart
new file mode 100644
index 000000000..0aafca1f4
--- /dev/null
+++ b/desktop/test/rename_keyboard_test.dart
@@ -0,0 +1,291 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/rename_agent_dialog.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'keymap_runtime_test.dart' show native;
+import 'support/rename_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+final _agent = find.byKey(const Key('agent-rename-input'));
+final _tab = find.byKey(const Key('tab-rename-input'));
+final _search = find.byKey(const ValueKey('swarm-search-input'));
+TextField field(WidgetTester tester, Finder finder) =>
+ tester.widget<TextField>(finder);
+
+Future<void> command(WidgetTester tester, String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(_search, '> $query');
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+}
+
+void main() {
+ late RenameConnection connection;
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late SwarmProjectStore projects;
+ setUp(() {
+ connection = RenameConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.nodeOnline = true;
+ map = MemoryKeymap();
+ projects = SwarmProjectStore();
+ });
+ tearDown(() {
+ app.dispose();
+ map.dispose();
+ projects.dispose();
+ });
+
+ Future<void> mount(
+ WidgetTester tester, {
+ bool nativeTabs = false,
+ Size size = const Size(1280, 800),
+ double scale = 1,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ projectStore: projects,
+ nativeTabs: nativeTabs,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'command rename targets the focused agent, retries and rejoins without leaking input',
+ (tester) async {
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a0', input));
+ final pane = app.adoptSessionForTest(terminal('a1', input));
+ await mount(tester);
+ await command(tester, 'rename agent');
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ expect(
+ field(tester, _agent).controller!.selection,
+ const TextSelection(baseOffset: 0, extentOffset: 7),
+ );
+ tester.testTextInput.enterText('Fix parser');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(connection.renames.single, {
+ 'agentId': 'a1',
+ 'name': 'Fix parser',
+ });
+ expect(field(tester, _agent).readOnly, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ await command(tester, 'rename agent');
+ expect(field(tester, _agent).controller!.text, 'Fix parser');
+ expect(field(tester, _agent).readOnly, isTrue);
+ expect(connection.renames, hasLength(1));
+ connection.replies.single.complete({
+ 'error': 'REFUSED',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Rename failed: Reconnect and retry.'), findsOneWidget);
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.replies.last.complete({
+ 'agent': {'name': 'Fix parser · saved'},
+ });
+ await tester.pumpAndSettle();
+ expect(_agent, findsNothing);
+ expect(pane.session!.agentName, 'Fix parser · saved');
+ expect(app.focusedPane, same(pane));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.streamId, 'stream-a1');
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'live custom rename keys, disabled defaults and composition keep ownership',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ map.apply('''{"bindings":[
+ {"keys":"f2","command":"agent.rename","when":"terminal"},
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await mount(tester);
+ await key(tester, LogicalKeyboardKey.f2);
+ await tester.pumpAndSettle();
+ expect(find.text('F8 save'), findsOneWidget);
+ tester.testTextInput.enterText('Updated');
+ final editor = field(tester, _agent).controller!;
+ editor.value = editor.value.copyWith(
+ composing: const TextRange(start: 0, end: 7),
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(editor.value.composing, const TextRange(start: 0, end: 7));
+ expect(_agent, findsOneWidget);
+ expect(connection.renames, isEmpty);
+ editor.clearComposing();
+ await key(tester, LogicalKeyboardKey.enter);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(connection.renames, isEmpty);
+ expect(_agent, findsOneWidget);
+ map.apply('''{"bindings":[
+ {"keys":"f10","command":"picker.accept","when":"picker"},
+ {"keys":"f4","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(find.text('F10 save'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f10);
+ connection.replies.single.complete({});
+ await tester.pumpAndSettle();
+ await command(tester, 'rename tab');
+ expect(field(tester, _tab).focusNode!.hasPrimaryFocus, isTrue);
+ expect(find.text('F10 save'), findsOneWidget);
+ tester.testTextInput.enterText('Named tab');
+ await key(tester, LogicalKeyboardKey.f10);
+ expect(app.activeSwarm.name, 'Named tab');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'native Rename Tab acknowledges visible input before waiting for its value',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, nativeTabs: true);
+ final opened = native(tester, 'renameActive');
+ await tester.pumpAndSettle();
+ await opened;
+ expect(field(tester, _tab).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Native rename');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarm.name, 'Native rename');
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('agent rename is unavailable without an owned listed agent', (
+ tester,
+ ) async {
+ await mount(tester);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(_search, '> rename agent');
+ expect(find.byKey(const ValueKey('command:agent.rename')), findsNothing);
+ await key(tester, LogicalKeyboardKey.escape);
+ app.adoptSessionForTest(terminal('a0', []));
+ final state = app.stateOf('m')!;
+ state.machine = const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ app.notifyListeners();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(_search, '> rename agent');
+ expect(find.byKey(const ValueKey('command:agent.rename')), findsNothing);
+ expect(connection.renames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('a prompt never reselects text after the user starts typing', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () =>
+ showAgentRenameDialog(context, app, 'm', 'a0', 'Agent 0'),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pump();
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('First keystrokes');
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(field(tester, _agent).controller!.selection.isCollapsed, isTrue);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'large-text rename retains input and retry keys in a short window',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, size: const Size(480, 360), scale: 1.7);
+ await command(tester, 'rename agent');
+ tester.testTextInput.enterText('');
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(_agent.hitTestable(), findsOneWidget);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('double-click rename retains typing through terminal updates', (
+ tester,
+ ) async {
+ final input = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', input));
+ await mount(tester);
+ final title = find.text('Session a0');
+ await tester.tap(title);
+ await tester.pump(const Duration(milliseconds: 40));
+ await tester.tap(title);
+ await tester.pump();
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.enterText('Typed immediately');
+ pane.session!.terminal.write('Background output\r\n');
+ app.notifyListeners();
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(field(tester, _agent).controller!.selection.isCollapsed, isTrue);
+ expect(field(tester, _agent).focusNode!.hasPrimaryFocus, isTrue);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.replies.single.complete({});
+ await tester.pumpAndSettle();
+ expect(pane.session!.agentName, 'Typed immediately');
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/restart_keyboard_test.dart b/desktop/test/restart_keyboard_test.dart
new file mode 100644
index 000000000..ed3d180b5
--- /dev/null
+++ b/desktop/test/restart_keyboard_test.dart
@@ -0,0 +1,274 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'support/restart_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+final _prompt = find.byKey(const ValueKey('agent-restart-prompt'));
+
+void main() {
+ late RestartConnection connection;
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late SwarmProjectStore projects;
+ setUp(() {
+ connection = RestartConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.nodeOnline = true;
+ map = MemoryKeymap();
+ projects = SwarmProjectStore();
+ });
+ tearDown(() {
+ app.dispose();
+ map.dispose();
+ projects.dispose();
+ });
+ String id() => connection.requests.last['creationId'] as String;
+ Future<void> mount(
+ WidgetTester tester, {
+ Size size = const Size(1280, 800),
+ double scale = 1,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ nativeTabs: false,
+ projectStore: projects,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> open(
+ WidgetTester tester, {
+ LogicalKeyboardKey accept = LogicalKeyboardKey.enter,
+ }) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> restart',
+ );
+ await key(tester, accept);
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'restart starts immediately, rejoins pending work, retries inline and restores terminal input',
+ (tester) async {
+ final input = <TerminalBinaryFrame>[];
+ final pane = app.adoptSessionForTest(terminal('a0', input));
+ final original = pane.session;
+ await mount(tester);
+ await open(tester);
+ expect(find.text('Restarting…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.requests, hasLength(1));
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await open(tester);
+ expect(connection.requests, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await open(tester);
+ expect(connection.requests, hasLength(1));
+ connection.restartReplies.single.complete({
+ 'creationId': id(),
+ 'state': 'failed',
+ 'failure': {
+ 'code': 'AGENT_BUSY',
+ 'detail': 'Wait for the other operation.',
+ },
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Wait for the other operation.'), findsOneWidget);
+ expect(find.text('enter retry'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.requests, hasLength(2));
+ connection.restartReplies.last.complete(restartReceipt(id()));
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ expect(pane.session, same(original));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('lost restart checks status and explains a fresh conversation', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.escape);
+ await open(tester);
+ expect(find.text('enter check status'), findsOneWidget);
+ expect(connection.requests, hasLength(1));
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.checkReplies.single.complete(
+ restartReceipt(id(), resumed: false),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ find.text(
+ 'Started a new conversation. The previous session could not be resumed.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('enter close'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.requests, hasLength(1));
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'restarting again after uncertainty requires a separate keyboard confirmation',
+ (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ final previous = id();
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ Future<void> ask() async {
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('May have already restarted.'), findsOneWidget);
+ }
+
+ await ask();
+ await key(tester, LogicalKeyboardKey.enter); // Cancel has initial focus.
+ await tester.pumpAndSettle();
+ expect(connection.requests, hasLength(1));
+ await ask();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.requests, hasLength(2));
+ expect(id(), isNot(previous));
+ connection.restartReplies.last.complete(restartReceipt(id()));
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Restart Terminal starts a fresh shell without a conversation warning',
+ (tester) async {
+ app.stateOf('m')!.agents[0] = const Agent(
+ id: 'a0',
+ name: 'Shell',
+ engine: 'terminal',
+ terminalAvailable: true,
+ );
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ expect(find.text('Restart Terminal'), findsOneWidget);
+ connection.restartReplies.single.complete(
+ restartReceipt(id(), resumed: false),
+ );
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ expect(find.textContaining('previous session'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('status prompt obeys live custom keys and disabled defaults', (
+ tester,
+ ) async {
+ map.apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"}
+ ]}''');
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester, accept: LogicalKeyboardKey.f8);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(_prompt, findsOneWidget);
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.checks, isEmpty);
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(connection.checks, hasLength(1));
+ map.apply('''{"bindings":[
+ {"keys":"f4","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(find.text('F4 close'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ connection.checkReplies.single.complete(restartReceipt(id()));
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('enlarged short window keeps uncertainty and Escape visible', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, size: const Size(480, 360), scale: 1.7);
+ await open(tester);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ connection.restartReplies.single.completeError(
+ const WsRequestTimeout('agent_restart'),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Restart not confirmed.').hitTestable(), findsOneWidget);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('esc back').hitTestable(), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(_prompt, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dart
index 2cdb874ec..2e3e4738f 100644
--- a/desktop/test/search_workspace_test.dart
+++ b/desktop/test/search_workspace_test.dart
@@ -44,13 +44,13 @@ void main() {
(w) => w is ListTile && w.selected,
);
final first = tester.widget<ListTile>(selected).key;
- await key(tester, LogicalKeyboardKey.arrowDown);
- expect(tester.widget<ListTile>(selected).key, isNot(first));
await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(tester.widget<ListTile>(selected).key, isNot(first));
+ await key(tester, LogicalKeyboardKey.arrowDown);
expect(tester.widget<ListTile>(selected).key, first);
- await tester.enterText(field, 'new');
+ await tester.enterText(field, '> new');
await key(tester, LogicalKeyboardKey.keyA, cmd: true);
- expect(controller.selection.textInside(controller.text), 'new');
+ expect(controller.selection.textInside(controller.text), '> new');
await key(tester, LogicalKeyboardKey.backspace);
expect(controller.text, isEmpty);
expect(
@@ -58,7 +58,7 @@ void main() {
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search
.rows
- .every((row) => row.isCommand),
+ .every((row) => row.isCreate || row.agentId != null),
isTrue,
);
expect(focus.hasFocus, isTrue);
@@ -68,7 +68,7 @@ void main() {
);
await key(tester, LogicalKeyboardKey.escape);
expect(field, findsNothing);
- await key(tester, LogicalKeyboardKey.keyO, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
await tester.enterText(field, 'Agent 0');
await tester.pump();
expect(
diff --git a/desktop/test/settings_review_render_test.dart b/desktop/test/settings_review_render_test.dart
new file mode 100644
index 000000000..865315631
--- /dev/null
+++ b/desktop/test/settings_review_render_test.dart
@@ -0,0 +1,251 @@
+// Optional pictures: HARNESS_SETTINGS_CAPTURE_DIR=/private/tmp/settings-review
+// flutter test --no-pub test/settings_review_render_test.dart
+// Uses the real screen with synthetic account data. It never starts a CLI,
+// loads user usage logs, edits preferences, or invokes a settings action.
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:package_info_plus/package_info_plus.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/settings/settings_nav.dart';
+import 'package:harness/settings/settings_screen.dart';
+import 'package:harness/settings/settings_section.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/update/desktop_updater.dart';
+import 'package:harness/update/manual_update_check.dart';
+import 'package:harness/widgets/shortcuts_sheet.dart';
+import 'package:harness/widgets/update_notice.dart';
+
+import 'support/real_fonts.dart';
+
+void main() {
+ setUpAll(() async {
+ // Real Apple faces include the modifier glyphs. The metric-compatible
+ // Arial used by the shared layout helper does not contain Command/Shift.
+ if (Platform.isMacOS) {
+ for (final (family, path) in [
+ ('.AppleSystemUIFont', '/System/Library/Fonts/SFNS.ttf'),
+ ('SF Pro Text', '/System/Library/Fonts/SFNS.ttf'),
+ ('Roboto', '/System/Library/Fonts/SFNS.ttf'),
+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Menlo', '/System/Library/Fonts/SFNSMono.ttf'),
+ ('Helvetica Neue', '/System/Library/Fonts/Apple Symbols.ttf'),
+ ]) {
+ final bytes = ByteData.sublistView(await File(path).readAsBytes());
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ } else {
+ await loadRealFonts();
+ }
+ for (final (family, path) in [
+ ('MaterialIcons', 'fonts/MaterialIcons-Regular.otf'),
+ (
+ 'packages/lucide_icons_flutter/Lucide',
+ 'packages/lucide_icons_flutter/assets/lucide.ttf',
+ ),
+ (
+ 'packages/lucide_icons_flutter/Lucide300',
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ ),
+ ]) {
+ await (FontLoader(family)..addFont(rootBundle.load(path))).load();
+ }
+ PackageInfo.setMockInitialValues(
+ appName: 'Harness',
+ packageName: 'ai.autonomous.harness',
+ version: '1.0.0',
+ buildNumber: '1',
+ buildSignature: '',
+ );
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.8]) {
+ for (final section in settingsGroupsFor(
+ debugSurface: false,
+ ).expand((group) => group.sections)) {
+ testWidgets(
+ '${section.name} at minimum window, ${brightness.name}, $scale text',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 560);
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final shadows = debugDisableShadows;
+ debugDisableShadows = false;
+ addTearDown(() => debugDisableShadows = shadows);
+ final app =
+ AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ )
+ ..currentUser = const CurrentUserProfile(
+ name: 'Morgan Rivera',
+ email: '[email protected]',
+ );
+ final boundary = GlobalKey();
+ Future<void> capture(String name) async {
+ final output =
+ Platform.environment['HARNESS_SETTINGS_CAPTURE_DIR'];
+ if (output == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File('$output/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ addTearDown(() async {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: grid.BrightnessScope(child: child!),
+ ),
+ home: SettingsScreen(notifier: app),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final search = find.byKey(const Key('settings-search-field'));
+ expect(
+ tester.widget<TextField>(search).focusNode!.hasFocus,
+ isTrue,
+ );
+ await tester.enterText(search, section.label);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ section,
+ );
+ if (section == SettingsSection.about) {
+ await tester.runAsync(() async {
+ await precacheImage(
+ const AssetImage('assets/app_icon.png'),
+ boundary.currentContext!,
+ );
+ });
+ await tester.pumpAndSettle();
+ }
+ final name = '${section.name}-${brightness.name}-$scale';
+ await capture(name);
+ debugDisableShadows = shadows;
+ if (section == SettingsSection.usage) {
+ final label = tester.renderObject<RenderParagraph>(
+ find.text('Last 30 days'),
+ );
+ expect(
+ label.getMaxIntrinsicWidth(double.infinity),
+ lessThanOrEqualTo(label.size.width + 0.1),
+ reason: 'The current Usage range must be readable at a glance.',
+ );
+ await tester.ensureVisible(find.text('Last 30 days'));
+ await tester.pumpAndSettle();
+ debugDisableShadows = false;
+ await capture('$name-range');
+ debugDisableShadows = shadows;
+ }
+ if (section == SettingsSection.about) {
+ await tester.ensureVisible(
+ find.byKey(const Key('settings-flash-firmware-button')),
+ );
+ await tester.pumpAndSettle();
+ debugDisableShadows = false;
+ await capture('$name-actions');
+ debugDisableShadows = shadows;
+ const available = DesktopUpdateCheck.available(
+ UpdateInfo(
+ version: '1.0.4',
+ url: 'https://updates.example.test/Harness.zip',
+ sha256: 'unused',
+ size: 48000000,
+ ),
+ );
+ for (final result in const [
+ ManualUpdateCheck(check: DesktopUpdateCheck.upToDate()),
+ ManualUpdateCheck(check: DesktopUpdateCheck.failed()),
+ ManualUpdateCheck(check: DesktopUpdateCheck.disabled()),
+ ManualUpdateCheck(check: available),
+ ManualUpdateCheck(check: available, isSkipped: true),
+ ]) {
+ unawaited(
+ showUpdateCheckDialog(
+ tester.element(find.byType(SettingsScreen)),
+ app,
+ result,
+ ),
+ );
+ await tester.pumpAndSettle();
+ debugDisableShadows = false;
+ await capture(
+ '$name-update-${result.status.name}'
+ '${result.isSkipped ? '-skipped' : ''}',
+ );
+ debugDisableShadows = shadows;
+ expect(
+ tester.takeException(),
+ isNull,
+ reason: result.status.name,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ }
+ }
+ if (section == SettingsSection.shortcuts) {
+ final label = tester.renderObject<RenderParagraph>(
+ find.text('Workspace'),
+ );
+ expect(
+ label.getMaxIntrinsicWidth(double.infinity),
+ lessThanOrEqualTo(label.size.width + 0.1),
+ reason:
+ 'The shortcut context must be readable without opening it.',
+ );
+ unawaited(
+ showShortcutsSheet(tester.element(find.byType(SettingsScreen))),
+ );
+ await tester.pumpAndSettle();
+ debugDisableShadows = false;
+ await capture('$name-sheet');
+ debugDisableShadows = shadows;
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ }
+ expect(tester.takeException(), isNull);
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+ }
+ }
+ }
+}
diff --git a/desktop/test/settings_screen_test.dart b/desktop/test/settings_screen_test.dart
index 9d1826f31..616240d4a 100644
--- a/desktop/test/settings_screen_test.dart
+++ b/desktop/test/settings_screen_test.dart
@@ -9,13 +9,19 @@
import 'dart:async';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/settings/settings_screen.dart';
+import 'package:harness/settings/settings_nav.dart';
+import 'package:harness/settings/settings_section.dart';
+import 'package:harness/settings/sections/shortcuts_section.dart';
+import 'package:harness/shared/widgets/app_select_field.dart';
import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/shortcuts/keymap.dart';
import 'package:harness/state/app_state.dart';
void main() {
@@ -138,4 +144,186 @@ void main() {
expect(find.text('Appearance'), findsNothing);
expect(find.byType(Placeholder), findsOneWidget);
});
+
+ testWidgets(
+ 'Settings opens ready to type, Enter selects a match and Escape returns',
+ (tester) async {
+ await openSettings(tester);
+ final field = find.byKey(const Key('settings-search-field'));
+ expect(
+ tester.widget<TextField>(field).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ final initial = tester
+ .widget<SettingsNav>(find.byType(SettingsNav))
+ .section;
+ await tester.enterText(field, 'keyboard');
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ initial,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ SettingsSection.shortcuts,
+ );
+ expect(
+ tester.widget<TextField>(field).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsNothing);
+ expect(find.byType(Placeholder), findsOneWidget);
+ },
+ );
+
+ testWidgets(
+ 'an empty or unmatched settings query does not change the section',
+ (tester) async {
+ await openSettings(tester);
+ final field = find.byKey(const Key('settings-search-field'));
+ final initial = tester
+ .widget<SettingsNav>(find.byType(SettingsNav))
+ .section;
+ for (final text in ['', 'nothing-matches-this']) {
+ await tester.enterText(field, text);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ initial,
+ );
+ expect(
+ tester.widget<TextField>(field).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ expect(
+ tester.widget<TextField>(field).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ },
+ );
+
+ testWidgets('Down enters the matching section row and Enter opens it', (
+ tester,
+ ) async {
+ await openSettings(tester);
+ final field = find.byKey(const Key('settings-search-field'));
+ await tester.enterText(field, 'about');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(tester.widget<TextField>(field).focusNode!.hasPrimaryFocus, isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ SettingsSection.about,
+ );
+ });
+
+ testWidgets(
+ 'shortcut help can be paged and its context changed by keyboard',
+ (tester) async {
+ await openSettings(tester);
+ await tester.enterText(
+ find.byKey(const Key('settings-search-field')),
+ 'keyboard',
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ // Search -> matching section -> shortcut context. No pointer is needed
+ // to leave the search and reach the section's first control.
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(
+ FocusManager.instance.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<AppSelectField<KeymapContext>>(),
+ isNotNull,
+ );
+ final scroll = tester.state<ScrollableState>(
+ find
+ .descendant(
+ of: find.byType(ShortcutsSection),
+ matching: find.byType(Scrollable),
+ )
+ .first,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageDown);
+ await tester.pumpAndSettle();
+ expect(scroll.position.pixels, greaterThan(0));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<AppSelectField<KeymapContext>>(
+ find.byType(AppSelectField<KeymapContext>),
+ )
+ .value,
+ KeymapContext.picker,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets('Escape belongs to composition before it can leave Settings', (
+ tester,
+ ) async {
+ await openSettings(tester);
+ final field = find.byKey(const Key('settings-search-field'));
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'keyboard',
+ selection: TextSelection.collapsed(offset: 8),
+ composing: TextRange(start: 0, end: 8),
+ ),
+ );
+ await tester.pump();
+ final section = tester
+ .widget<SettingsNav>(find.byType(SettingsNav))
+ .section;
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ expect(
+ tester.widget<SettingsNav>(find.byType(SettingsNav)).section,
+ section,
+ );
+ expect(tester.widget<TextField>(field).focusNode!.hasPrimaryFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsOneWidget);
+ expect(tester.widget<TextField>(field).focusNode!.hasPrimaryFocus, isTrue);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'keyboard',
+ selection: TextSelection.collapsed(offset: 8),
+ ),
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(SettingsScreen), findsNothing);
+ });
}
diff --git a/desktop/test/setup_review_render_test.dart b/desktop/test/setup_review_render_test.dart
new file mode 100644
index 000000000..27fc5a911
--- /dev/null
+++ b/desktop/test/setup_review_render_test.dart
@@ -0,0 +1,196 @@
+// Optional PNGs: HARNESS_SETUP_CAPTURE_DIR=/private/tmp/setup-review
+// flutter test test/setup_review_render_test.dart
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/bootstrap/environment_provisioner.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/widgets/environment_preflight_screen.dart';
+import 'package:harness/widgets/environment_setup_screen.dart';
+
+import 'support/real_fonts.dart';
+
+class _NoInstall extends EnvironmentProvisioner {
+ @override
+ Future<EnvironmentReadiness> ensureReady({
+ required void Function(EnvironmentReadiness) onProgress,
+ EnvironmentReadiness? resumeFrom,
+ bool install = true,
+ EnvironmentSetupMode? mode,
+ }) => throw StateError('The render fixture must not run an installer');
+}
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets('setup at minimum window, ${brightness.name}, $scale text', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 560);
+ addTearDown(tester.view.reset);
+ final previousBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ (call) async {
+ if (call.method == 'Clipboard.setData') {
+ throw PlatformException(code: 'clipboard_unavailable');
+ }
+ return null;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ SystemChannels.platform,
+ null,
+ ),
+ );
+ const review = EnvironmentReadiness(
+ steps: {
+ EnvironmentStep.clipboard: EnvironmentStepStatus.notApplicable,
+ EnvironmentStep.tmux: EnvironmentStepStatus.failed,
+ EnvironmentStep.harness: EnvironmentStepStatus.failed,
+ },
+ phase: EnvironmentSetupPhase.review,
+ plan: [
+ EnvironmentPlanItem.tmuxManaged,
+ EnvironmentPlanItem.harnessCli,
+ ],
+ );
+ final app =
+ AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ environmentProvisioner: _NoInstall(),
+ )
+ ..status = AppStatus.preparingEnvironment
+ ..environmentReadiness = EnvironmentReadiness.initial();
+ addTearDown(app.dispose);
+ final boundary = GlobalKey();
+ Future<void> capture(String name) async {
+ expect(tester.takeException(), isNull);
+ final output = Platform.environment['HARNESS_SETUP_CAPTURE_DIR'];
+ if (output == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final picture = await render.toImage(pixelRatio: 1);
+ try {
+ final bytes = await picture.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File('$output/$name-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ } finally {
+ picture.dispose();
+ }
+ });
+ }
+
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ disableAnimations: true,
+ textScaler: TextScaler.linear(scale),
+ ),
+ child: child!,
+ ),
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => switch (app.environmentReadiness.phase) {
+ EnvironmentSetupPhase.preflight ||
+ EnvironmentSetupPhase.ready => EnvironmentPreflightScreen(
+ readiness: app.environmentReadiness,
+ ),
+ _ => EnvironmentSetupScreen(notifier: app),
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(
+ find.text('Checking this computer').hitTestable(),
+ findsOneWidget,
+ );
+ await capture('checking');
+ app.environmentReadiness = EnvironmentReadiness(
+ steps: {
+ for (final step in EnvironmentStep.values)
+ step: EnvironmentStepStatus.ready,
+ },
+ phase: EnvironmentSetupPhase.ready,
+ );
+ app.notifyListeners();
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Environment ready').hitTestable(), findsOneWidget);
+ await capture('ready');
+ app.environmentReadiness = review;
+ app.notifyListeners();
+ await tester.pump();
+ expect(find.text('Install 2 tools').hitTestable(), findsOneWidget);
+ await capture('review');
+ app.selectEnvironmentSetupMode(EnvironmentSetupMode.manual);
+ await tester.pump();
+ expect(find.text('Check again').hitTestable(), findsOneWidget);
+ await capture('manual');
+ app.environmentReadiness = review.copyWith(
+ mode: EnvironmentSetupMode.automatic,
+ phase: EnvironmentSetupPhase.waitingForTerminal,
+ );
+ app.notifyListeners();
+ await tester.pump();
+ expect(find.text('Recheck now').hitTestable(), findsOneWidget);
+ await capture('waiting');
+ app.environmentReadiness = review.copyWith(
+ phase: EnvironmentSetupPhase.failed,
+ failure: const EnvironmentFailure(
+ title: 'Setup could not finish',
+ detail: 'Check your connection, then retry setup.',
+ ),
+ output: const ['Recent package output', 'Connection interrupted'],
+ );
+ app.notifyListeners();
+ await tester.pump();
+ expect(find.text('Retry').hitTestable(), findsOneWidget);
+ await capture('failed');
+ await tester.ensureVisible(find.text('Copy diagnostics'));
+ await tester.tap(find.text('Copy diagnostics'));
+ await tester.pump();
+ expect(
+ find
+ .text('Could not copy. Select the text to copy it, or try again.')
+ .hitTestable(),
+ findsOneWidget,
+ );
+ expect(find.text('Retry').hitTestable(), findsOneWidget);
+ await capture('copy-error');
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
+ }
+}
diff --git a/desktop/test/shared_harness_panel_test.dart b/desktop/test/shared_harness_panel_test.dart
index 424783c88..4a35f2be9 100644
--- a/desktop/test/shared_harness_panel_test.dart
+++ b/desktop/test/shared_harness_panel_test.dart
@@ -205,8 +205,15 @@ void main() {
await settleNetwork(() => find.text('Live').evaluate().isNotEmpty);
expect(requests.first['payload'], containsPair('shareId', 'grant'));
expect(find.text('View only'), findsOneWidget);
+ // Receiving the request on the server does not mean its reply has
+ // reached the UI yet. Wait for the response we are about to inspect.
await settleNetwork(
- () => requests.any((r) => r['type'] == 'observer_viewer'),
+ () =>
+ requests.any((r) => r['type'] == 'observer_viewer') &&
+ find
+ .textContaining('The viewer will appear', skipOffstage: false)
+ .evaluate()
+ .isNotEmpty,
);
// Narrow: the terminal is in front and the viewer waits behind its tab —
// until the first frame lands, which brings it forward by itself (below).
diff --git a/desktop/test/shortcuts_deck_test.dart b/desktop/test/shortcuts_deck_test.dart
index cc156c74c..afeff6115 100644
--- a/desktop/test/shortcuts_deck_test.dart
+++ b/desktop/test/shortcuts_deck_test.dart
@@ -180,4 +180,74 @@ void main() {
reason: 'a chord outgrew the narrowest card — it must wrap, not overflow',
);
});
+
+ testWidgets('enlarged text reduces columns before labels become cramped', (
+ tester,
+ ) async {
+ tester.view.physicalSize = const Size(1400, 900);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.light),
+ home: MediaQuery(
+ data: const MediaQueryData(textScaler: TextScaler.linear(1.8)),
+ child: const Scaffold(
+ body: SingleChildScrollView(
+ child: SizedBox(width: 900, child: ShortcutsDeck()),
+ ),
+ ),
+ ),
+ ),
+ );
+ final workspace = tester.getTopLeft(find.text('WORKSPACE'));
+ final panes = tester.getTopLeft(find.text('PANES'));
+ expect(panes.dx, workspace.dx);
+ expect(panes.dy, greaterThan(workspace.dy));
+ expect(tester.takeException(), isNull);
+ });
+
+ for (final label in ['W', 'Ctrl K, then Ctrl Shift R']) {
+ testWidgets('enlarged keycap keeps the full glyphs for $label', (
+ tester,
+ ) async {
+ const probe = Key('natural-key-label');
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: buildAppTheme(brightness: Brightness.light),
+ home: MediaQuery(
+ data: const MediaQueryData(textScaler: TextScaler.linear(2.5)),
+ child: Scaffold(
+ body: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(width: 260, child: KeyCap(label)),
+ SizedBox(
+ width: 248,
+ child: Text(
+ label,
+ key: probe,
+ style: const TextStyle(fontSize: 11.5, height: 1),
+ ),
+ ),
+ const KeyCap('⇥'),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ expect(
+ tester.getSize(find.byType(KeyCap).first).height,
+ greaterThan(tester.getSize(find.byKey(probe)).height),
+ reason: 'The cap needs room for its full label and vertical padding.',
+ );
+ expect(
+ tester.getSize(find.byIcon(Icons.keyboard_tab)).height,
+ greaterThan(14),
+ reason: 'The Tab symbol should enlarge along with the letter keys.',
+ );
+ expect(tester.takeException(), isNull);
+ });
+ }
}
diff --git a/desktop/test/shortcuts_test.dart b/desktop/test/shortcuts_test.dart
index 5c6653f5d..3c1b7e749 100644
--- a/desktop/test/shortcuts_test.dart
+++ b/desktop/test/shortcuts_test.dart
@@ -262,10 +262,10 @@ void main() {
expect(chordsFor(ShortcutAction.zoomPane), contains('⌘⏎'));
expect(chordsFor(ShortcutAction.lastPane), contains('⌘;'));
expect(chordsFor(ShortcutAction.newSwarm), ['⌘T']);
- expect(chordsFor(ShortcutAction.showLayout), ['⌘S']);
- expect(chordsFor(ShortcutAction.orchestrate), ['⌘P']);
+ expect(chordsFor(ShortcutAction.showLayout), ['⇧⌘L']);
+ expect(chordsFor(ShortcutAction.orchestrate), isEmpty);
expect(chordsFor(ShortcutAction.routeTask), ['⌘B']);
- expect(chordsFor(ShortcutAction.addAgent), ['⌘O']);
+ expect(chordsFor(ShortcutAction.addAgent), ['⌘P']);
expect(chordsFor(ShortcutAction.newAgent), ['⌘N']);
expect(chordsFor(ShortcutAction.showAttention), ['⇧⌘I']);
expect(chordsFor(ShortcutAction.findTerminal), ['⌘F']);
@@ -297,7 +297,7 @@ void main() {
['⌘', '→'],
]);
- final next = rows.firstWhere((row) => row.label == 'Next Harness');
+ final next = rows.firstWhere((row) => row.label == 'Next Tab');
expect(next.chords, [
['⇧', '⌘', ']'],
['⌃', '⇥'],
@@ -318,9 +318,7 @@ void main() {
test('the digits are one row, at the end of their own group', () {
final rows = shortcutRows();
- final digits = rows.indexWhere(
- (row) => row.label == 'Select harnesses 1–9',
- );
+ final digits = rows.indexWhere((row) => row.label == 'Select tabs 1–9');
expect(digits, isNot(-1));
expect(rows[digits].chords, [
['⌘', '1 – 9'],
diff --git a/desktop/test/signin_recovery_test.dart b/desktop/test/signin_recovery_test.dart
index da25fc1e0..5ecc8b6ad 100644
--- a/desktop/test/signin_recovery_test.dart
+++ b/desktop/test/signin_recovery_test.dart
@@ -65,6 +65,65 @@ const _platform = SystemChannels.platform;
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
+ for (final hasUrl in [false, true]) {
+ testWidgets(
+ 'Escape cancels sign-in ${hasUrl ? 'after' : 'before'} the browser link and restores Enter',
+ (tester) async {
+ final cli = _Cli();
+ final app = _app(cli);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ _browser,
+ (_) async => true,
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ _browser,
+ null,
+ ),
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => LoginScreen(notifier: app),
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(cli.attempts, hasLength(1));
+ if (hasUrl) {
+ cli.attempts.single.authorize('https://auth.example/fixture');
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text('Waiting for your browser'), findsOneWidget);
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.signingIn, isFalse);
+ expect(cli.cancellations, 1);
+ expect(app.pendingAuthorizeUrl, isNull);
+ expect(app.lastError, isNull);
+ expect(find.text('Sign in'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ expect(cli.cancellations, 1);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(cli.attempts, hasLength(2));
+ cli.attempts.first.done.complete();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(app.signingIn, isTrue);
+ expect(app.daemonChecks, 0);
+ app.cancelLogin();
+ cli.attempts.last.done.complete();
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+
testWidgets(
'keyboard sign-in can reopen and copy its link without restarting login',
(tester) async {
diff --git a/desktop/test/signout_recovery_test.dart b/desktop/test/signout_recovery_test.dart
new file mode 100644
index 000000000..54a5337c5
--- /dev/null
+++ b/desktop/test/signout_recovery_test.dart
@@ -0,0 +1,240 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/screens/login_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/terminal/terminal_session.dart';
+
+import 'support/real_fonts.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+
+class SignOutFixture extends CliLogin {
+ final attempts = <Completer<void>>[];
+ var logins = 0;
+ @override
+ Future<void> logout() {
+ final result = Completer<void>();
+ attempts.add(result);
+ return result.future;
+ }
+
+ @override
+ Future<void> login({required void Function(String) onAuthorizeUrl}) async {
+ logins++;
+ throw StateError('Fixture login stopped before any external work.');
+ }
+}
+
+Widget signOutHost(
+ AppNotifier app, {
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+}) {
+ grid.AppTheme.brightness.value = brightness;
+ return MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(
+ context,
+ ).copyWith(disableAnimations: true, textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: grid.BrightnessScope(
+ child: ListenableBuilder(
+ listenable: app,
+ builder: (_, _) => LoginScreen(notifier: app),
+ ),
+ ),
+ );
+}
+
+AppNotifier signOutApp(SignOutFixture cli, {bool local = false}) => AppNotifier(
+ config: AppConfig.dev,
+ configStore: null,
+ authSession: AuthSession(storage: MemoryStore()),
+ cliLogin: cli,
+ localManualFixture: local
+ ? const LocalManualFixture(
+ apiBaseUrl: 'http://127.0.0.1:1',
+ apiKey: 'fixture',
+ machineId: 'fixture',
+ machineName: 'Fixture',
+ setupToken: 'fixture',
+ )
+ : null,
+)..status = AppStatus.authenticated;
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+ test(
+ 'sign-out waits for credentials, coalesces clicks, and gates sign-in',
+ () async {
+ final cli = SignOutFixture();
+ final app = signOutApp(cli);
+ addTearDown(app.dispose);
+ var done = false;
+ final first = app.logout().then((_) => done = true);
+ final second = app.logout();
+ await Future<void>.delayed(Duration.zero);
+ expect(cli.attempts, hasLength(1));
+ expect(done, isFalse);
+ await app.login();
+ expect(cli.logins, 0);
+ cli.attempts.single.complete();
+ await first;
+ await second;
+ expect(app.status, AppStatus.unauthenticated);
+ await app.login();
+ expect(cli.logins, 1);
+ },
+ );
+
+ test(
+ 'disconnecting a development fixture never signs out the real CLI',
+ () async {
+ final cli = SignOutFixture();
+ final app = signOutApp(cli, local: true);
+ addTearDown(app.dispose);
+ await app.logout();
+ expect(cli.attempts, isEmpty);
+ expect(app.status, AppStatus.unauthenticated);
+ },
+ );
+
+ test('one failed terminal close cannot interrupt sign-out', () async {
+ final cli = SignOutFixture();
+ final app = signOutApp(cli);
+ addTearDown(app.dispose);
+ final closed = <String>[];
+ for (final id in ['broken', 'healthy']) {
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'fixture',
+ agentId: id,
+ agentName: id,
+ engineId: 'codex',
+ send: (type, _) async {
+ if (type == 'terminal_close') {
+ closed.add(id);
+ if (id == 'broken') throw StateError('disconnected fixture');
+ }
+ return true;
+ },
+ sendBinary: (_) async => true,
+ )..streamId = id,
+ );
+ }
+ final pending = app.logout();
+ cli.attempts.single.complete();
+ await pending;
+ expect(closed, ['broken', 'healthy']);
+ expect(app.allPanes, isEmpty);
+ expect(app.signingOut, isFalse);
+ expect(app.signOutError, isNull);
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.8]) {
+ testWidgets(
+ 'sign-out failure recovers using only the keyboard in $brightness at $scale',
+ (tester) async {
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final cli = SignOutFixture();
+ final app = signOutApp(cli);
+ addTearDown(app.dispose);
+ final boundary = GlobalKey();
+ Future<void> capture(String stage) async {
+ final directory = Platform.environment['HARNESS_AUTH_CAPTURE_DIR'];
+ if (directory == null) return;
+ await tester.runAsync(
+ () => precacheImage(
+ const AssetImage('assets/app_icon.png'),
+ boundary.currentContext!,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$stage-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ final pending = app.logout();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: signOutHost(app, brightness: brightness, scale: scale),
+ ),
+ );
+ await tester.pump();
+ expect(find.text('Signing out…'), findsOneWidget);
+ expect(find.text('Sign in'), findsNothing);
+ expect(find.text('Cancel'), findsNothing);
+ await capture('pending');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ expect(cli.logins, 0);
+ cli.attempts.single.completeError(
+ StateError('fixture-private-details'),
+ );
+ await tester.pump();
+ await pending;
+ await tester.pump();
+ expect(find.text('Retry sign out'), findsOneWidget);
+ expect(find.textContaining('could not be cleared'), findsOneWidget);
+ for (final content in [
+ find.text('Retry sign out'),
+ find.textContaining('could not be cleared'),
+ ]) {
+ expect(tester.getRect(content).bottom, lessThanOrEqualTo(544));
+ expect(tester.getRect(content).top, greaterThanOrEqualTo(16));
+ }
+ expect(find.textContaining('fixture-private-details'), findsNothing);
+ await capture('failed');
+ await app.login();
+ expect(cli.logins, 0);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(cli.attempts, hasLength(2));
+ expect(find.text('Signing out…'), findsOneWidget);
+ cli.attempts.last.complete();
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('Sign in'), findsOneWidget);
+ await capture('ready');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(cli.logins, 1);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/startup_test.dart b/desktop/test/startup_test.dart
index 73b30f107..902f8780a 100644
--- a/desktop/test/startup_test.dart
+++ b/desktop/test/startup_test.dart
@@ -167,6 +167,7 @@ void main() {
'app_ui_font_size',
'app_color_palette',
'harness_start_background',
+ 'workspace_prompt_v1',
},
]);
expect(counters.requested, isTrue);
diff --git a/desktop/test/stop_keyboard_test.dart b/desktop/test/stop_keyboard_test.dart
new file mode 100644
index 000000000..2dd535a6c
--- /dev/null
+++ b/desktop/test/stop_keyboard_test.dart
@@ -0,0 +1,267 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+
+import 'keymap_host_test.dart' show key, MemoryKeymap;
+import 'support/stop_connection.dart';
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ late StopConnection connection;
+ late AppNotifier app;
+ late MemoryKeymap map;
+ late SwarmProjectStore projects;
+ setUp(() {
+ connection = StopConnection();
+ app = createApp(connectionForTest: (_) => connection);
+ app.stateOf('m')!.nodeOnline = true;
+ map = MemoryKeymap();
+ projects = SwarmProjectStore();
+ });
+ tearDown(() {
+ app.dispose();
+ map.dispose();
+ projects.dispose();
+ });
+
+ Future<void> mount(
+ WidgetTester tester, {
+ Size size = const Size(1280, 800),
+ double scale = 1,
+ }) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.reset);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: KeymapProvider(
+ keymap: map,
+ child: SwarmScreen(
+ notifier: app,
+ projectStore: projects,
+ nativeTabs: false,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> open(
+ WidgetTester tester, {
+ LogicalKeyboardKey accept = LogicalKeyboardKey.enter,
+ }) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> stop',
+ );
+ await key(tester, accept);
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets(
+ 'Stop uses safe confirmation, inline retry and one pending request across reopen',
+ (tester) async {
+ final input = <TerminalBinaryFrame>[];
+ final retained = app.adoptSessionForTest(terminal('a0', input));
+ app.adoptSessionForTest(terminal('a1', input));
+ await mount(tester);
+ await open(tester);
+ expect(find.text('Stop Agent'), findsOneWidget);
+ expect(
+ find.textContaining('Close Pane keeps it running.'),
+ findsOneWidget,
+ );
+ // The default action must leave the agent running.
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ expect(connection.stops, isEmpty);
+ await open(tester);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(connection.stops, ['a1']);
+ expect(find.text('Stopping…'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.stops, hasLength(1));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ await open(tester);
+ expect(find.text('Stopping…'), findsOneWidget);
+ expect(connection.stops, hasLength(1));
+ connection.stopReplies.single.complete({
+ 'error': 'OFFLINE',
+ 'detail': 'Reconnect and retry.',
+ });
+ await tester.pumpAndSettle();
+ expect(find.text('Stop failed: Reconnect and retry.'), findsOneWidget);
+ await key(
+ tester,
+ LogicalKeyboardKey.enter,
+ ); // Retry still starts on Cancel.
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ expect(connection.stops, hasLength(1));
+ await open(tester);
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ connection.stopReplies.last.complete({'deleted': true});
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ expect(app.allPanes, [retained]);
+ expect(app.focusedPane, same(retained));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input.single.streamId, 'stream-a0');
+ expect(input.single.bytes, [27, 91, 68]);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('stop honors live accept, traversal and cancel remapping', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ map.apply('''{"bindings":[
+ {"keys":"enter","command":null,"when":"picker"},
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f8","command":"picker.accept","when":"picker"},
+ {"keys":"f6","command":"picker.complete","when":"picker"},
+ {"keys":"f7","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await mount(tester);
+ await open(tester, accept: LogicalKeyboardKey.f8);
+ expect(find.text('F8 select'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Stop Agent'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f6);
+ await key(tester, LogicalKeyboardKey.f8);
+ expect(connection.stops, ['a0']);
+ map.apply('''{"bindings":[
+ {"keys":"escape","command":null,"when":"picker"},
+ {"keys":"f4","command":"picker.cancel","when":"picker"}
+ ]}''');
+ await tester.pump();
+ expect(find.text('F4 close'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Stop Agent'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.f4);
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ connection.stopReplies.single.complete({'error': 'REFUSED'});
+ await tester.pumpAndSettle();
+ expect(app.stateOf('m')!.agents.any((agent) => agent.id == 'a0'), isTrue);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'terminal stopping names the shell and remains usable at enlarged text',
+ (tester) async {
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Build shell',
+ engine: 'terminal',
+ terminalAvailable: true,
+ ),
+ ];
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, size: const Size(480, 360), scale: 1.7);
+ await open(tester);
+ expect(find.text('Stop Terminal'), findsOneWidget);
+ expect(find.textContaining('End this shell'), findsOneWidget);
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ expect(find.text('esc close').hitTestable(), findsOneWidget);
+ final body = tester.widget<SingleChildScrollView>(
+ find.ancestor(
+ of: find.textContaining('End this shell'),
+ matching: find.byType(SingleChildScrollView),
+ ),
+ );
+ expect(body.controller!.offset, 0);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(body.controller!.offset, greaterThan(0));
+ expect(find.text('Cancel').hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(
+ find.textContaining('Close Pane keeps it running.').hitTestable(),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.pageUp);
+ await key(tester, LogicalKeyboardKey.pageUp);
+ expect(body.controller!.offset, 0);
+ expect(tester.takeException(), isNull);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(connection.stops, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('shared agents never offer the stop command', (tester) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ app.stateOf('m')!.machine = const Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ isShared: true,
+ );
+ await mount(tester);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> stop',
+ );
+ expect(find.byKey(const ValueKey('command:agent.stop')), findsNothing);
+ expect(connection.stops, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('an open confirmation cannot stop a newly replaced session', (
+ tester,
+ ) async {
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester);
+ await open(tester);
+ app.stateOf('m')!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Restarted',
+ sessionId: 'replacement',
+ engine: 'codex',
+ ),
+ ];
+ app.notifyListeners();
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(connection.stops, isEmpty);
+ expect(find.textContaining('The agent changed.'), findsOneWidget);
+ await key(
+ tester,
+ LogicalKeyboardKey.enter,
+ ); // Cancel retains focus on error.
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/store_showcase_test.dart b/desktop/test/store_showcase_test.dart
index cd5ce5352..806c5ce06 100644
--- a/desktop/test/store_showcase_test.dart
+++ b/desktop/test/store_showcase_test.dart
@@ -14,6 +14,7 @@ import 'package:harness/core/project_folder.dart';
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
+import 'package:harness/state/harness_placement.dart';
import 'package:harness/state/pane_arrangement.dart';
import 'package:harness/store/store_showcase.dart';
import 'package:harness/widgets/new_agent_dialog.dart';
@@ -87,6 +88,7 @@ class _Notifier extends AppNotifier {
String? swarmId,
PaneSplitRequest? split,
AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
}) async {
prompts.add(prompt);
return 'Test launch refused.';
diff --git a/desktop/test/support/cpu_profile.dart b/desktop/test/support/cpu_profile.dart
new file mode 100644
index 000000000..f17902729
--- /dev/null
+++ b/desktop/test/support/cpu_profile.dart
@@ -0,0 +1,134 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:developer' as developer;
+import 'dart:io';
+import 'dart:isolate';
+
+/// Optional sampling of the current synthetic benchmark, using its own VM's
+/// loopback service. No dependency on a user's running app or DevTools session.
+class BenchmarkCpuProfile {
+ BenchmarkCpuProfile._(this._client, this._socket, this._isolate);
+
+ final HttpClient _client;
+ final WebSocket _socket;
+ final String _isolate;
+ final _pending = <String, Completer<Map<String, dynamic>>>{};
+ var _id = 0;
+ var _started = 0;
+ var _closed = false;
+
+ static Future<BenchmarkCpuProfile> start() async {
+ final info = await developer.Service.controlWebServer(enable: true);
+ final uri = info.serverUri;
+ if (uri == null) {
+ throw StateError(
+ 'Run this benchmark with flutter test --enable-vmservice',
+ );
+ }
+ if (!['127.0.0.1', 'localhost', '::1'].contains(uri.host)) {
+ throw StateError(
+ 'Benchmark profiling requires its own loopback VM service',
+ );
+ }
+ final client = _ServiceHttp().createHttpClient(null);
+ final WebSocket socket;
+ try {
+ socket = await WebSocket.connect(
+ uri.replace(scheme: 'ws', path: '${uri.path}ws').toString(),
+ customClient: client,
+ ).timeout(const Duration(seconds: 10));
+ } catch (_) {
+ client.close(force: true);
+ rethrow;
+ }
+ final profile = BenchmarkCpuProfile._(
+ client,
+ socket,
+ developer.Service.getIsolateId(Isolate.current)!,
+ );
+ socket.listen(
+ (raw) {
+ final event = jsonDecode(raw as String) as Map<String, dynamic>;
+ final pending = profile._pending.remove(event['id']);
+ if (pending == null) return;
+ if (event['error'] case final error?) {
+ pending.completeError(StateError('$error'));
+ } else {
+ pending.complete(Map<String, dynamic>.from(event['result'] as Map));
+ }
+ },
+ onError: profile._failPending,
+ onDone: () => profile._failPending(StateError('VM service closed')),
+ );
+ try {
+ await profile._call('setFlag', {'name': 'profiler', 'value': 'true'});
+ await profile._call('clearCpuSamples', {'isolateId': profile._isolate});
+ profile._started =
+ (await profile._call('getVMTimelineMicros'))['timestamp'] as int;
+ return profile;
+ } catch (_) {
+ await profile.close();
+ rethrow;
+ }
+ }
+
+ void _failPending(Object error) {
+ final pending = _pending.values.toList();
+ _pending.clear();
+ for (final call in pending) {
+ call.completeError(error);
+ }
+ }
+
+ Future<Map<String, dynamic>> _call(
+ String method, [
+ Map<String, Object> params = const {},
+ ]) async {
+ if (_closed) throw StateError('Benchmark profiling has finished');
+ final id = '${_id++}';
+ final result = Completer<Map<String, dynamic>>();
+ _pending[id] = result;
+ try {
+ _socket.add(
+ jsonEncode({
+ 'jsonrpc': '2.0',
+ 'id': id,
+ 'method': method,
+ 'params': params,
+ }),
+ );
+ return await result.future.timeout(const Duration(seconds: 10));
+ } finally {
+ _pending.remove(id);
+ }
+ }
+
+ Future<void> save(String path) async {
+ try {
+ final end = (await _call('getVMTimelineMicros'))['timestamp'] as int;
+ final samples = await _call('getCpuSamples', {
+ 'isolateId': _isolate,
+ 'timeOriginMicros': _started,
+ 'timeExtentMicros': end - _started,
+ });
+ await File(path).writeAsString(jsonEncode(samples));
+ } finally {
+ await close();
+ }
+ }
+
+ Future<void> close() async {
+ if (_closed) return;
+ _closed = true;
+ _failPending(StateError('Benchmark profiling has finished'));
+ try {
+ await _socket.close();
+ } finally {
+ _client.close(force: true);
+ }
+ }
+}
+
+// Widget tests replace HTTP globally. Only the loopback VM connection above
+// uses this real client; product network requests remain under their test fakes.
+class _ServiceHttp extends HttpOverrides {}
diff --git a/desktop/test/support/fork_connection.dart b/desktop/test/support/fork_connection.dart
new file mode 100644
index 000000000..a1e8a9abb
--- /dev/null
+++ b/desktop/test/support/fork_connection.dart
@@ -0,0 +1,43 @@
+import 'dart:async';
+
+import 'rename_connection.dart';
+
+class ForkConnection extends RenameConnection {
+ final forks = <Map<String, dynamic>>[];
+ final checks = <Map<String, dynamic>>[];
+ final forkReplies = <Completer<Map<String, dynamic>>>[];
+ final checkReplies = <Completer<Map<String, dynamic>>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'agent_fork' || type == 'agent_create_status') {
+ final checking = type == 'agent_create_status';
+ (checking ? checks : forks).add(Map.of(payload));
+ final reply = Completer<Map<String, dynamic>>();
+ (checking ? checkReplies : forkReplies).add(reply);
+ return reply.future;
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
+Map<String, dynamic> forkReceipt(
+ String? id, {
+ String agentId = 'forked',
+ String level = 'native',
+}) => {
+ 'creationId': ?id,
+ if (id != null) 'state': 'created',
+ 'level': level,
+ 'agent': {
+ 'id': agentId,
+ 'name': 'Separate idea',
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ 'forkedFrom': {'agentId': 'a0', 'name': 'Agent 0'},
+ },
+};
diff --git a/desktop/test/support/launch_menu.dart b/desktop/test/support/launch_menu.dart
new file mode 100644
index 000000000..6c737af04
--- /dev/null
+++ b/desktop/test/support/launch_menu.dart
@@ -0,0 +1,50 @@
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+
+/// Open a launch row through the same navigation keys as the visible menu.
+Future<void> openLaunchRow(WidgetTester tester, String name) async {
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.field, NewHarnessField.launch);
+ final index = ['agent', 'machine', 'project', 'task'].indexOf(name);
+ expect(index, greaterThanOrEqualTo(0));
+ await tester.sendKeyEvent(LogicalKeyboardKey.pageUp);
+ await tester.pump();
+ for (var i = 0; i < index; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+}
+
+/// Settings are deliberately separate from the arrow/Enter selection path.
+Future<void> openAgentSetting(
+ WidgetTester tester,
+ String engine,
+ String setting,
+) async {
+ final row = find.byKey(ValueKey(engine));
+ await tester.ensureVisible(row);
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: tester.getCenter(row));
+ await mouse.moveTo(tester.getCenter(row));
+ await tester.pump();
+ await tester.tap(find.byKey(ValueKey('new-harness-settings-$engine')));
+ await tester.pump();
+ await tester.tap(
+ find
+ .ancestor(
+ of: find.byKey(ValueKey(setting)),
+ matching: find.byType(InkWell),
+ )
+ .first,
+ );
+ await tester.pump();
+ await mouse.removePointer();
+}
diff --git a/desktop/test/support/machine_api.dart b/desktop/test/support/machine_api.dart
new file mode 100644
index 000000000..b25b4efc5
--- /dev/null
+++ b/desktop/test/support/machine_api.dart
@@ -0,0 +1,33 @@
+import 'dart:async';
+
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+
+/// Account edits stay entirely in memory; this client never opens a socket.
+class MachineApi extends ApiClient {
+ MachineApi() : super(config: AppConfig.dev, session: AuthSession());
+ final renames = <(String, String)>[];
+ final deletes = <String>[];
+ Completer<String?>? renameReply;
+ Completer<void>? deleteReply;
+ Object? renameFailure, deleteFailure;
+ String? canonicalName;
+
+ @override
+ Future<String?> renameMachine({
+ required String machineId,
+ required String name,
+ }) async {
+ renames.add((machineId, name));
+ if (renameFailure case final error?) throw error;
+ return renameReply?.future ?? canonicalName;
+ }
+
+ @override
+ Future<void> deleteMachine({required String machineId}) async {
+ deletes.add(machineId);
+ if (deleteFailure case final error?) throw error;
+ await deleteReply?.future;
+ }
+}
diff --git a/desktop/test/support/mixed_agents.dart b/desktop/test/support/mixed_agents.dart
new file mode 100644
index 000000000..c12ea31c6
--- /dev/null
+++ b/desktop/test/support/mixed_agents.dart
@@ -0,0 +1,116 @@
+import 'package:harness/core/dsh_catalog.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+
+/// A realistic catalog, including identical tasks on different engines and
+/// machines. Nothing connects to a real daemon or creates an agent.
+void seedMixedAgents(AppNotifier app) {
+ const local = Machine(
+ machineId: 'm',
+ name: 'M2',
+ authMode: MachineAuthMode.remote,
+ );
+ const remote = Machine(
+ machineId: 'studio',
+ name: 'iMac · Office',
+ authMode: MachineAuthMode.remote,
+ );
+ const offline = Machine(
+ machineId: 'build',
+ name: 'build-box',
+ authMode: MachineAuthMode.remote,
+ );
+ const project = AgentProject(
+ name: 'openharness',
+ cwd: '/work/openharness',
+ branch: 'feature/login-redirect',
+ remote: 'github.com/team/openharness',
+ );
+ app.machines = [local, remote, offline];
+ app.machineStates['m'] = MachineState(local)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = const [
+ Agent(
+ id: 'a0',
+ name: 'Fix login redirect',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: project,
+ ),
+ Agent(
+ id: 'a1',
+ name: 'Fix login redirect',
+ engine: 'claude',
+ terminalAvailable: true,
+ project: project,
+ ),
+ Agent(
+ id: 'a2',
+ name: 'Review the release notes',
+ engine: 'codex',
+ dsh: 'autonomous/typst',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'release-notes',
+ cwd: '/work/release-notes',
+ ),
+ ),
+ Agent(
+ id: 'a3',
+ name: 'Calibrate the arm',
+ engine: 'claude',
+ dsh: 'studio/arm',
+ terminalAvailable: true,
+ project: AgentProject(name: 'robotics', cwd: '/work/robotics'),
+ ),
+ ];
+ app.machineStates['m']!.dsh.replace(const [
+ DshEntry(
+ id: 'studio/arm',
+ name: 'Robot Studio',
+ engine: 'claude',
+ category: 'Robotics',
+ installed: true,
+ ),
+ ]);
+ app.machineStates['studio'] = MachineState(remote)
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = const [
+ Agent(
+ id: 'focus',
+ name: 'Improve keyboard focus after reconnect',
+ engine: 'opencode',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: 'openharness',
+ cwd: '/work/openharness/.worktrees/keyboard',
+ branch: 'worktree/keyboard-navigation',
+ remote: 'github.com/team/openharness',
+ ),
+ ),
+ Agent(
+ id: 'helmet',
+ name: 'Aero bicycle helmet',
+ engine: 'claude',
+ dsh: 'autonomous/blender',
+ terminalAvailable: true,
+ project: AgentProject(name: 'helmet', cwd: '/work/helmet'),
+ ),
+ ];
+ app.machineStates['build'] = MachineState(offline)
+ ..nodeOnline = false
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = const [
+ Agent(
+ id: 'login',
+ name: 'Fix login redirect',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: project,
+ ),
+ ];
+}
diff --git a/desktop/test/support/password_cli.dart b/desktop/test/support/password_cli.dart
new file mode 100644
index 000000000..3c28644e0
--- /dev/null
+++ b/desktop/test/support/password_cli.dart
@@ -0,0 +1,82 @@
+import 'dart:async';
+
+import 'package:harness/auth/cli_link.dart';
+
+/// In-memory CLI for password UI/native fixtures. Never invokes a process or
+/// reads a Harness home. Every password used with this fake is fixture text.
+class PasswordCli implements CliLink {
+ RemotePasswordStatus status = const RemotePasswordStatus();
+ RemotePasswordSetResult setResult = const RemotePasswordSetResult(
+ fingerprint: '1535·C035·9474·FE9D',
+ );
+ String? clearError, unlinkError;
+ CliLinkListResult links = const CliLinkListResult();
+ final passwords = <String>[];
+ final unlinks = <String>[];
+ int reads = 0, clears = 0, lists = 0;
+ Completer<RemotePasswordStatus>? statusReply;
+ Completer<RemotePasswordSetResult>? setReply;
+ Completer<String?>? clearReply, unlinkReply;
+ Completer<CliLinkListResult>? listReply;
+ Object? statusFailure, setFailure, clearFailure, listFailure, unlinkFailure;
+
+ @override
+ Future<RemotePasswordStatus> remotePasswordStatus() async {
+ reads++;
+ if (statusFailure case final error?) throw error;
+ return statusReply?.future ?? status;
+ }
+
+ @override
+ Future<RemotePasswordSetResult> setRemotePassword(String password) async {
+ passwords.add(password);
+ if (setFailure case final error?) throw error;
+ final result = await (setReply?.future ?? Future.value(setResult));
+ if (result.error == null) {
+ status = RemotePasswordStatus(
+ hasPassword: true,
+ fingerprint: result.fingerprint,
+ );
+ }
+ return result;
+ }
+
+ @override
+ Future<String?> clearRemotePassword() async {
+ clears++;
+ if (clearFailure case final error?) throw error;
+ final error = await (clearReply?.future ?? Future.value(clearError));
+ if (error == null) status = const RemotePasswordStatus();
+ return error;
+ }
+
+ @override
+ Future<CliLinkListResult> list() async {
+ lists++;
+ if (listFailure case final error?) throw error;
+ return listReply?.future ?? links;
+ }
+
+ @override
+ Future<String?> unlink(String machineId) async {
+ unlinks.add(machineId);
+ if (unlinkFailure case final error?) throw error;
+ final error = await (unlinkReply?.future ?? Future.value(unlinkError));
+ if (error == null) {
+ links = CliLinkListResult(
+ machines: links.machines
+ .where((machine) => machine.machineId != machineId)
+ .toList(),
+ );
+ }
+ return error;
+ }
+
+ @override
+ Future<CliLinkConnectResult> connect(
+ String machineId,
+ String password, {
+ void Function(String stage)? onProgress,
+ String? displayName,
+ }) async => const CliLinkConnectResult();
+}
diff --git a/desktop/test/support/rename_connection.dart b/desktop/test/support/rename_connection.dart
new file mode 100644
index 000000000..dd75ff4db
--- /dev/null
+++ b/desktop/test/support/rename_connection.dart
@@ -0,0 +1,40 @@
+import 'dart:async';
+
+import 'package:harness/ws/ws_conn.dart';
+
+/// Explicit receipts for UI/model tests; no socket is opened.
+class RenameConnection extends WsConn {
+ RenameConnection()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final renames = <Map<String, dynamic>>[];
+ final replies = <Completer<Map<String, dynamic>>>[];
+ Completer<Map<String, dynamic>>? inventory;
+
+ @override
+ Future<void> waitUntilReady({required Duration timeout}) async {}
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'agent_update') {
+ renames.add(Map.of(payload));
+ final reply = Completer<Map<String, dynamic>>();
+ replies.add(reply);
+ return reply.future;
+ }
+ if (type == 'agents_list' && inventory != null) return inventory!.future;
+ return Future.value({});
+ }
+}
diff --git a/desktop/test/support/restart_connection.dart b/desktop/test/support/restart_connection.dart
new file mode 100644
index 000000000..8f6786868
--- /dev/null
+++ b/desktop/test/support/restart_connection.dart
@@ -0,0 +1,50 @@
+import 'dart:async';
+
+import 'stop_connection.dart';
+
+/// Controlled receipts only; never opens a connection or starts a process.
+class RestartConnection extends StopConnection {
+ final requests = <Map<String, dynamic>>[];
+ final restartReplies = <Completer<Map<String, dynamic>>>[];
+ final checks = <Map<String, dynamic>>[];
+ final checkReplies = <Completer<Map<String, dynamic>>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'agent_restart' || type == 'agent_create_status') {
+ final reply = Completer<Map<String, dynamic>>();
+ if (type == 'agent_restart') {
+ requests.add(Map.of(payload));
+ restartReplies.add(reply);
+ } else {
+ checks.add(Map.of(payload));
+ checkReplies.add(reply);
+ }
+ return reply.future;
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
+Map<String, dynamic> restartReceipt(
+ String? id, {
+ String agentId = 'a0',
+ String name = 'Restarted',
+ String? sessionId,
+ bool resumed = true,
+}) => {
+ 'creationId': ?id,
+ if (id != null) 'state': 'created',
+ 'resumed': resumed,
+ 'agent': {
+ 'id': agentId,
+ 'name': name,
+ 'sessionId': ?sessionId,
+ 'engine': 'codex',
+ 'terminal': {'available': true},
+ },
+};
diff --git a/desktop/test/support/stop_connection.dart b/desktop/test/support/stop_connection.dart
new file mode 100644
index 000000000..b4be4369c
--- /dev/null
+++ b/desktop/test/support/stop_connection.dart
@@ -0,0 +1,25 @@
+import 'dart:async';
+
+import 'rename_connection.dart';
+
+class StopConnection extends RenameConnection {
+ final stops = <String>[];
+ final stopReplies = <Completer<Map<String, dynamic>>>[];
+ int restarts = 0;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'agent_delete') {
+ stops.add(payload['agentId'] as String);
+ final reply = Completer<Map<String, dynamic>>();
+ stopReplies.add(reply);
+ return reply.future;
+ }
+ if (type == 'agent_restart') restarts++;
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
diff --git a/desktop/test/swarm_add_agent_test.dart b/desktop/test/swarm_add_agent_test.dart
index 1248a46a9..5059317e1 100644
--- a/desktop/test/swarm_add_agent_test.dart
+++ b/desktop/test/swarm_add_agent_test.dart
@@ -12,56 +12,44 @@ import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
void main() {
- testWidgets(
- 'Open Harness in the header reuses the chosen session in this workspace',
- (tester) async {
- final app = createApp();
- final input = <TerminalBinaryFrame>[];
- final shared = app.adoptSessionForTest(terminal('a0', input));
- final source = app.activeSwarm;
- app.newSwarm(name: 'Review');
- final existing = app.adoptSessionForTest(terminal('a1', input));
- final target = app.activeSwarm;
- await mount(tester, app);
- tester.view.physicalSize = const Size(880, 560);
- await tester.pump();
- final add = find.byKey(const ValueKey('swarm-open-agent-button'));
- expect(tester.getRect(add).top, lessThan(44));
- expect(find.byType(FloatingActionButton), findsNothing);
- expect(
- tester
- .getRect(find.byKey(existing.cellKey))
- .overlaps(tester.getRect(add)),
- isFalse,
- );
- await tester.tap(add);
- await tester.pump();
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- 'Agent 0',
- );
- await tester.pump();
- expect(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-row-action')),
- matching: find.text('Open Harness'),
- ),
- findsOneWidget,
- );
- expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
+ testWidgets('New Pane shortcut reuses the chosen session in this workspace', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ final shared = app.adoptSessionForTest(terminal('a0', input));
+ final source = app.activeSwarm;
+ app.newSwarm(name: 'Review');
+ final existing = app.adoptSessionForTest(terminal('a1', input));
+ final target = app.activeSwarm;
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(880, 560);
+ await tester.pump();
+ expect(find.byKey(const ValueKey('swarm-new-pane-button')), findsNothing);
+ expect(find.byType(FloatingActionButton), findsNothing);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Agent 0',
+ );
+ await tester.pump();
+ expect(
+ find.textContaining('enter open', findRichText: true),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
- expect(find.byType(AlertDialog), findsNothing);
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(app.activeSwarm, same(target));
- expect(target.panes, [existing, shared]);
- expect(source.panes, [shared]);
- expect(input, isEmpty);
- expect(tester.takeException(), isNull);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- },
- );
+ expect(find.byType(AlertDialog), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.activeSwarm, same(target));
+ expect(target.panes, [existing, shared]);
+ expect(source.panes, [shared]);
+ expect(input, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
for (final axis in PaneResizeAxis.values) {
testWidgets(
diff --git a/desktop/test/swarm_arrange_keyboard_test.dart b/desktop/test/swarm_arrange_keyboard_test.dart
new file mode 100644
index 000000000..d59ac0778
--- /dev/null
+++ b/desktop/test/swarm_arrange_keyboard_test.dart
@@ -0,0 +1,259 @@
+import 'dart:convert';
+
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/pane_preset.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/widgets/pane_resize_handle.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp, MemoryStore;
+
+void main() {
+ testWidgets(
+ 'many tabs reveal keyboard selection without undoing manual scrolling',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final input = List.generate(12, (_) => <TerminalBinaryFrame>[]);
+ final tabs = <String>[];
+ for (var i = 0; i < 12; i++) {
+ if (i > 0) app.newSwarm();
+ app.adoptSessionForTest(terminal('a$i', input[i]));
+ app.renameSwarm(app.activeSwarmId, 'Feature ${i + 1}');
+ tabs.add(app.activeSwarmId);
+ }
+ app.selectSwarm(tabs.first);
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(600, 800);
+ await tester.pump();
+ final strip = find.byType(ReorderableListView);
+ Future<void> visible() async {
+ await tester.pump();
+ final label = find.descendant(
+ of: strip,
+ matching: find.text(app.activeSwarm.name),
+ );
+ expect(label, findsOneWidget);
+ final viewport = tester.getRect(strip);
+ final bounds = tester.getRect(label);
+ expect(bounds.left, greaterThanOrEqualTo(viewport.left));
+ expect(bounds.right, lessThanOrEqualTo(viewport.right));
+ }
+
+ await key(tester, LogicalKeyboardKey.digit9, cmd: true);
+ expect(app.activeSwarmId, tabs[8]);
+ await visible();
+ for (var i = 0; i < 2; i++) {
+ await key(tester, LogicalKeyboardKey.tab, ctrl: true);
+ await visible();
+ }
+ expect(app.activeSwarmId, tabs[10]);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(input[10].single.bytes, [27, 91, 68]);
+ expect(
+ [
+ for (var i = 0; i < 12; i++)
+ if (i != 10) input[i],
+ ].every((frames) => frames.isEmpty),
+ isTrue,
+ );
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ await visible();
+ app.reorderSwarm(app.activeSwarmId, 0);
+ await tester.pump();
+ await visible();
+ tester.view.physicalSize = const Size(450, 800);
+ await tester.pump();
+ await visible();
+ tester.view.physicalSize = const Size(600, 800);
+ await tester.pump();
+ await visible();
+ await tester.sendEventToBinding(
+ PointerScrollEvent(
+ position: tester.getCenter(strip),
+ scrollDelta: const Offset(850, 0),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final scrolling = tester.state<ScrollableState>(
+ find.descendant(of: strip, matching: find.byType(Scrollable)).first,
+ );
+ final manualOffset = scrolling.position.pixels;
+ expect(manualOffset, greaterThan(400));
+ app.notifyListeners();
+ await tester.pump();
+ await tester.pump();
+ expect(
+ scrolling.position.pixels,
+ manualOffset,
+ reason: 'Agent updates must not snap a manually scrolled strip back',
+ );
+ await key(tester, LogicalKeyboardKey.tab, ctrl: true);
+ await visible();
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets('directional moves swap only neighbors and carry their pins', (
+ tester,
+ ) async {
+ final store = MemoryStore();
+ final app = createApp(store: store);
+ app.machineStates['m']!.nodeOnline = true;
+ final input = List.generate(4, (_) => <TerminalBinaryFrame>[]);
+ final panes = List.generate(
+ 4,
+ (i) => app.adoptSessionForTest(terminal('a$i', input[i])),
+ );
+ app.setPreset(4, PanePreset.quad);
+ app.focusPane(panes.first.id);
+ app.togglePinPane(panes[0].id);
+ app.togglePinPane(panes[2].id);
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(2000, 1200);
+ await tester.pump();
+ final before = [
+ for (final pane in panes) tester.getRect(find.byKey(pane.cellKey)),
+ ];
+ final retained = tester.element(
+ find.descendant(
+ of: find.byKey(panes[0].cellKey),
+ matching: find.byType(TerminalView),
+ ),
+ );
+ await key(tester, LogicalKeyboardKey.arrowDown, cmd: true, shift: true);
+ expect(app.panes, [panes[2], panes[1], panes[0], panes[3]]);
+ expect(tester.getRect(find.byKey(panes[0].cellKey)), before[2]);
+ expect(tester.getRect(find.byKey(panes[2].cellKey)), before[0]);
+ expect(tester.getRect(find.byKey(panes[1].cellKey)), before[1]);
+ expect(tester.getRect(find.byKey(panes[3].cellKey)), before[3]);
+ expect(app.pinnedSlotFor(panes[0]), 2);
+ expect(app.pinnedSlotFor(panes[2]), 0);
+ expect(app.focusedPane, same(panes[0]));
+ expect(
+ tester.element(
+ find.descendant(
+ of: find.byKey(panes[0].cellKey),
+ matching: find.byType(TerminalView),
+ ),
+ ),
+ same(retained),
+ );
+ await app.flushPaneLayout();
+ final saved = jsonDecode(store.values['swarm_layout_v1']!) as Map;
+ final savedPanes =
+ ((saved['swarms'] as List).first as Map)['panes'] as List;
+ expect(savedPanes.map((p) => p['agentId']), ['a2', 'a1', 'a0', 'a3']);
+ expect(savedPanes.map((p) => p['pinnedSlot']), [0, null, 2, null]);
+ await app.closePane(panes[3].id);
+ await tester.pump();
+ expect(app.panes, [panes[2], panes[1], panes[0]]);
+ expect(input.every((frames) => frames.isEmpty), isTrue);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 60));
+ expect(input[0].single.bytes, [27, 91, 68]);
+ expect(input.skip(1).every((frames) => frames.isEmpty), isTrue);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+
+ testWidgets(
+ 'moving a pane down a scrolling layout keeps its terminal visible',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final input = <TerminalBinaryFrame>[];
+ final panes = List.generate(
+ 4,
+ (i) => app.adoptSessionForTest(terminal('a$i', input)),
+ );
+ app.setPreset(4, PanePreset.rows);
+ app.focusPane(panes.first.id);
+ await mount(tester, app);
+ final first = find.byKey(panes.first.cellKey);
+ for (var move = 0; move < 3; move++) {
+ await key(tester, LogicalKeyboardKey.arrowDown, cmd: true, shift: true);
+ await tester.pump();
+ final bounds = tester.getRect(first);
+ expect(bounds.top, greaterThanOrEqualTo(52));
+ expect(bounds.bottom, lessThanOrEqualTo(800));
+ expect(app.focusedPane, same(panes.first));
+ }
+ await key(tester, LogicalKeyboardKey.arrowDown, cmd: true, shift: true);
+ expect(
+ app.panes.last,
+ same(panes.first),
+ reason: 'Moving stops at the edge',
+ );
+ expect(input, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
+ testWidgets('keyboard resize cycles dividers and restores terminal input', (
+ tester,
+ ) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final input = <TerminalBinaryFrame>[];
+ for (var i = 0; i < 3; i++) {
+ app.adoptSessionForTest(terminal('a$i', input));
+ }
+ app.setPreset(3, PanePreset.mainLeft);
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(2000, 1200);
+ await tester.pump();
+ Future<void> command(String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> $query',
+ );
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ }
+
+ final original = app.activeSwarm.arranged!.toJson();
+ final focus = app.focusedPane;
+ await command('resize panes');
+ final visited = <String>{};
+ for (var i = 0; i < 4; i++) {
+ final handle = FocusManager.instance.primaryFocus!.context!
+ .findAncestorWidgetOfExactType<PaneResizeHandle>();
+ expect(handle, isNotNull);
+ visited.add(handle!.divider.id);
+ final horizontal = handle.divider.axis.name == 'x';
+ final before = app.activeSwarm.arranged!.toJson();
+ await key(
+ tester,
+ horizontal
+ ? LogicalKeyboardKey.arrowRight
+ : LogicalKeyboardKey.arrowDown,
+ );
+ expect(app.activeSwarm.arranged!.toJson(), isNot(before));
+ expect(find.byKey(const ValueKey('pane-resize-hint')), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.tab);
+ }
+ expect(visited, hasLength(2));
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.byKey(const ValueKey('pane-resize-hint')), findsNothing);
+ expect(app.focusedPane, same(focus));
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(input.single.bytes, [27, 91, 65]);
+ await command('reset pane sizes');
+ expect(app.activeSwarm.arranged!.toJson(), original);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ });
+}
diff --git a/desktop/test/swarm_async_test.dart b/desktop/test/swarm_async_test.dart
index 8327b7a4d..c158f91fe 100644
--- a/desktop/test/swarm_async_test.dart
+++ b/desktop/test/swarm_async_test.dart
@@ -100,7 +100,7 @@ void main() {
(
'UNSUPPORTED',
null,
- 'Update the harness CLI on this machine to create a harness',
+ 'Update the harness CLI on this machine to start a harness',
),
// Refused at the wire before any pane exists: a definite no, never
// "check status".
@@ -112,7 +112,7 @@ void main() {
(
'INVALID_PROMPT',
'prompt must be a string',
- 'Create harness failed: prompt must be a string',
+ 'Could not start harness: prompt must be a string',
),
(
'PROMPT_UNSUPPORTED',
@@ -122,7 +122,7 @@ void main() {
(
'SPAWN_FAILED',
'The machine could not allocate an agent process.',
- 'Test host has not confirmed the new agent yet. Check status before creating another.',
+ 'Test host has not confirmed the new harness yet. Check status before starting another.',
),
]) {
test(
@@ -198,7 +198,7 @@ void main() {
connection.reply.completeError(const WsRequestTimeout('agent_create'));
expect(
await creation,
- 'Test host has not confirmed the new agent yet. Check status before creating another.',
+ 'Test host has not confirmed the new harness yet. Check status before starting another.',
);
expect(connection.calls, ['agent_create']);
expect(app.panes, isEmpty);
diff --git a/desktop/test/swarm_commands_test.dart b/desktop/test/swarm_commands_test.dart
index a41b5878d..b6787bb8e 100644
--- a/desktop/test/swarm_commands_test.dart
+++ b/desktop/test/swarm_commands_test.dart
@@ -117,7 +117,7 @@ void main() {
final app = createApp();
await mount(tester, app);
final input = find.byKey(const ValueKey('swarm-search-input'));
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
await tester.enterText(input, '> rename');
await tester.pump();
expect(
diff --git a/desktop/test/swarm_content_search_test.dart b/desktop/test/swarm_content_search_test.dart
index 182fb75dd..31a24d78f 100644
--- a/desktop/test/swarm_content_search_test.dart
+++ b/desktop/test/swarm_content_search_test.dart
@@ -72,10 +72,12 @@ void main() {
expect(search.rows, isEmpty);
app.sessionPreviews.warm([key]);
await tester.pump(const Duration(milliseconds: 80));
- expect(search.rows.single.agentId, 'a0');
+ // ⌘O's list ends in the row that makes a harness; it is not a match.
+ expect(search.rows.where((row) => !row.isCreate).single.agentId, 'a0');
expect(catalog.read(app, []), same(metadata));
search.setQuery('DESIGN HOVER');
- expect(search.rows.single.agentId, 'a0');
+ // ⌘O's list ends in the row that makes a harness; it is not a match.
+ expect(search.rows.where((row) => !row.isCreate).single.agentId, 'a0');
search.setQuery('skylark');
expect(search.rows.map((row) => row.agentId), ['a1', 'a0']);
search.setQuery(
@@ -94,7 +96,8 @@ void main() {
expect(resultChanges, 0);
expect(search.selected?.agentId, 'a0');
search.setQuery('progress 99');
- expect(search.rows.single.agentId, 'a0');
+ // ⌘O's list ends in the row that makes a harness; it is not a match.
+ expect(search.rows.where((row) => !row.isCreate).single.agentId, 'a0');
machine.agents = [
const Agent(
id: 'a0',
@@ -145,7 +148,8 @@ void main() {
'content': 'Changed topic',
});
await tester.pump(const Duration(milliseconds: 80));
- expect(search.rows.single.agentId, 'a0');
+ // ⌘O's list ends in the row that makes a harness; it is not a match.
+ expect(search.rows.where((row) => !row.isCreate).single.agentId, 'a0');
search.dispose();
app.dispose();
},
@@ -160,7 +164,7 @@ void main() {
app.adoptSessionForTest(terminal('a69', []));
app.newSwarm();
await mount(tester, app);
- if (!inline) await chord(tester, LogicalKeyboardKey.keyO);
+ if (!inline) await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(
ValueKey(inline ? 'harness-start-search' : 'swarm-search-input'),
);
@@ -169,7 +173,8 @@ void main() {
final search = tester
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search;
- expect(search.rows.single.agentId, 'a0');
+ // ⌘O's list ends in the row that makes a harness; it is not a match.
+ expect(search.rows.where((row) => !row.isCreate).single.agentId, 'a0');
expect(find.textContaining('Payment retries now reuse'), findsOneWidget);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_entry_picker_test.dart b/desktop/test/swarm_entry_picker_test.dart
index a8cd59a51..248ed8611 100644
--- a/desktop/test/swarm_entry_picker_test.dart
+++ b/desktop/test/swarm_entry_picker_test.dart
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/swarm_search.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:xterm/xterm.dart';
@@ -27,15 +28,18 @@ void main() {
}
await tester.pump();
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
- expect(tester.widget<TextField>(_startInput).controller!.text, '> ');
- expect(find.text('Run command'), findsOneWidget);
+ expect(tester.widget<TextField>(_input).controller!.text, '> ');
+ expect(
+ find.textContaining('run command', findRichText: true),
+ findsOneWidget,
+ );
expect(find.widgetWithText(ListTile, 'Agent 0'), findsNothing);
expect(
- tester.widget<TextField>(_startInput).decoration!.hintText,
+ tester.widget<TextField>(_input).decoration!.hintText,
'Search commands…',
);
- expect(_results, findsNothing);
- await tester.enterText(_startInput, '> rename');
+ expect(_results, findsOneWidget);
+ await tester.enterText(_input, '> rename');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
@@ -70,7 +74,7 @@ void main() {
findsOneWidget,
);
expect(
- find.descendant(of: selected, matching: find.text('Open Harness')),
+ find.descendant(of: selected, matching: find.text('Add to this tab')),
findsOneWidget,
);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
@@ -105,12 +109,14 @@ void main() {
expect(
tester.getRect(_startInput).bottom,
lessThan(
- tester.getRect(find.byKey(const ValueKey('harness-start-open'))).top,
+ tester
+ .getRect(find.byKey(const ValueKey('harness-start-new-pane')))
+ .top,
),
);
expect(
tester.widget<TextField>(_startInput).decoration!.hintText,
- 'Find a harness',
+ kHarnessPickerHint,
);
expect(tester.widget<TextField>(_startInput).focusNode!.hasFocus, isTrue);
expect(find.byKey(const ValueKey('harness-device-link')), findsOneWidget);
@@ -149,7 +155,9 @@ void main() {
app.renameSwarm(original, 'Background update');
await tester.pump();
expect(_results, findsNothing);
- await tester.tap(find.byKey(const ValueKey('harness-start-new')));
+ await tester.tap(find.byKey(const ValueKey('harness-start-new-pane')));
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(AlertDialog), findsOneWidget);
expect(
@@ -183,12 +191,9 @@ void main() {
await mount(tester, app, nativeTabs: native);
await chord(tester, LogicalKeyboardKey.keyT);
await tester.pump();
- final page = app.activeSwarmId;
- expect(page, isNot(original));
- expect(_results, findsNothing);
- expect(_startInput, findsOneWidget);
- await chord(tester, LogicalKeyboardKey.keyO);
+ expect(app.activeSwarmId, original);
expect(_results, findsOneWidget);
+ expect(_startInput, findsNothing);
if (dismissal == 'outside') {
await tester.tapAt(const Offset(20, 200));
} else {
@@ -196,11 +201,8 @@ void main() {
}
await tester.pump();
expect(_results, findsNothing);
- expect(_startInput, findsOneWidget);
- expect(app.activeSwarmId, page);
- await app.closeSwarm(page);
- await tester.pump();
expect(app.activeSwarmId, original);
+ expect(app.swarms, hasLength(1));
expect(app.closedHistory, isEmpty);
expect(app.focusedPane, same(pane));
await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
@@ -218,7 +220,7 @@ void main() {
(tester) async {
final app = createApp();
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(_input, 'Agent 12');
await tester.pump();
final text = tester.widget<TextField>(_input).controller!;
@@ -240,9 +242,9 @@ void main() {
expect(_startInput, findsOneWidget);
expect(tester.widget<TextField>(_startInput).focusNode!.hasFocus, isTrue);
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
- expect(tester.widget<TextField>(_startInput).controller!.text, '> ');
+ expect(tester.widget<TextField>(_input).controller!.text, '> ');
expect(
- tester.widget<TextField>(_startInput).decoration!.hintText,
+ tester.widget<TextField>(_input).decoration!.hintText,
'Search commands…',
);
await tester.pumpWidget(const SizedBox());
@@ -261,7 +263,7 @@ void main() {
app.newSwarm();
final destination = app.activeSwarmId;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(_input, 'Agent 0');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
diff --git a/desktop/test/swarm_immediate_input_test.dart b/desktop/test/swarm_immediate_input_test.dart
index f0869b9bd..49da4d5d2 100644
--- a/desktop/test/swarm_immediate_input_test.dart
+++ b/desktop/test/swarm_immediate_input_test.dart
@@ -103,12 +103,13 @@ void main() {
await tester.pump(const Duration(milliseconds: 10));
expect(secondInput, isEmpty, reason: 'The old agent owns no input');
if (action == 'new tab') {
- expect(app.panes, isEmpty);
+ expect(app.panes, [first, second]);
+ expect(app.swarms, hasLength(1));
expect(firstInput, isEmpty);
expect(
tester
.widget<TextField>(
- find.byKey(const ValueKey('harness-start-search')),
+ find.byKey(const ValueKey('swarm-search-input')),
)
.focusNode!
.hasFocus,
@@ -245,10 +246,7 @@ void main() {
await command(tester, LogicalKeyboardKey.keyR, shift: true);
await tester.pumpAndSettle();
final field = tester.widget<TextField>(
- find.descendant(
- of: find.byType(AlertDialog),
- matching: find.byType(TextField),
- ),
+ find.byKey(const Key('tab-rename-input')),
);
expect(field.focusNode!.hasFocus, isTrue);
if (change == 'waiting composer') {
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index 9279f0e97..2efb43524 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -69,102 +69,97 @@ Future<void> chord(
void main() {
for (final native in [false, true]) {
- testWidgets('New Tab actions reuse the existing page (native: $native)', (
- tester,
- ) async {
- const channel = MethodChannel('harness/swarm_tabs');
- const codec = StandardMethodCodec();
- final messenger = tester.binding.defaultBinaryMessenger;
- messenger.setMockMethodCallHandler(channel, (_) async => true);
- addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
- final app = createApp();
- app.machineStates['m']!.nodeOnline = true;
- app.adoptSessionForTest(terminal('a0', []));
- final work = app.activeSwarmId;
- app.newSwarm();
- final starter = app.activeSwarmId;
- final projects = SwarmProjectStore(storage: MemoryStore());
- await tester.pumpWidget(
- MaterialApp(
- home: SwarmScreen(
- notifier: app,
- nativeTabs: native,
- projectStore: projects,
+ testWidgets(
+ 'New Tab actions defer placement until selection (native: $native)',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ const codec = StandardMethodCodec();
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (_) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ app.adoptSessionForTest(terminal('a0', []));
+ final work = app.activeSwarmId;
+ app.newSwarm();
+ final starter = app.activeSwarmId;
+ final projects = SwarmProjectStore(storage: MemoryStore());
+ await tester.pumpWidget(
+ MaterialApp(
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: native,
+ projectStore: projects,
+ ),
),
- ),
- );
- await tester.pumpAndSettle();
-
- Future<void> newFromChrome() async {
- if (!native) {
- await tester.tap(find.byKey(const ValueKey('swarm-new-tab-button')));
- return;
- }
- var replied = false;
- messenger.handlePlatformMessage(
- channel.name,
- codec.encodeMethodCall(const MethodCall('new')),
- (_) => replied = true,
);
- for (var i = 0; i < 5 && !replied; i++) {
- await tester.pump();
- }
- expect(replied, isTrue);
- }
+ await tester.pumpAndSettle();
- for (final action in <Future<void> Function()>[
- () => chord(tester, LogicalKeyboardKey.keyT),
- newFromChrome,
- () async {
- await chord(tester, LogicalKeyboardKey.keyP, shift: true);
- await tester.enterText(
- find.byKey(const ValueKey('swarm-search-input')),
- 'New Tab',
+ Future<void> newFromChrome() async {
+ if (!native) {
+ await tester.tap(
+ find.byKey(const ValueKey('swarm-new-tab-button')),
+ );
+ return;
+ }
+ var replied = false;
+ messenger.handlePlatformMessage(
+ channel.name,
+ codec.encodeMethodCall(const MethodCall('new')),
+ (_) => replied = true,
);
+ for (var i = 0; i < 5 && !replied; i++) {
+ await tester.pump();
+ }
+ expect(replied, isTrue);
+ }
+
+ for (final action in <Future<void> Function()>[
+ () => chord(tester, LogicalKeyboardKey.keyT),
+ newFromChrome,
+ () async {
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> New Tab',
+ );
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ },
+ ]) {
+ app.selectSwarm(work);
+ await tester.pumpAndSettle();
+ await action();
+ await tester.pumpAndSettle();
+ expect(app.activeSwarmId, work);
+ expect(app.swarms, hasLength(2));
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ await tester.enterText(input, 'Agent 1');
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- },
- ]) {
- app.selectSwarm(work);
- await tester.pumpAndSettle();
- await action();
- await tester.pumpAndSettle();
- expect(app.activeSwarmId, starter);
- expect(app.swarms, hasLength(2));
- await chord(tester, LogicalKeyboardKey.keyT);
- expect(app.activeSwarmId, starter);
- expect(app.swarms, hasLength(2));
- final input = tester.widget<TextField>(
- find.byKey(const ValueKey('harness-start-search')),
- );
- expect(input.focusNode!.hasFocus, isTrue);
- expect(
- find.byKey(const ValueKey('harness-start-results')),
- findsNothing,
- );
- tester.testTextInput.enterText('Agent 1');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(input, findsNothing);
+ expect(app.activeSwarmId, work);
+ expect(app.swarms, hasLength(2));
+ }
+ await newFromChrome();
await tester.pump();
- expect(
- find.byKey(const ValueKey('harness-start-results')),
- findsOneWidget,
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Agent 0',
);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
- expect(input.focusNode!.hasFocus, isFalse);
- await newFromChrome();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(app.activeSwarmId, starter);
expect(app.swarms, hasLength(2));
- expect(input.focusNode!.hasFocus, isTrue);
- expect(
- find.byKey(const ValueKey('harness-start-results')),
- findsNothing,
- );
- }
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- projects.dispose();
- });
+ expect(app.panes.single.agentId, 'a0');
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ projects.dispose();
+ },
+ );
}
testWidgets(
@@ -172,7 +167,7 @@ void main() {
(tester) async {
final app = createApp();
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
expect(app.panes, isEmpty);
await tester.enterText(
@@ -181,7 +176,7 @@ void main() {
);
await tester.pump();
await tester.sendKeyDownEvent(LogicalKeyboardKey.control);
- await tester.sendKeyEvent(LogicalKeyboardKey.keyN);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
await tester.sendKeyUpEvent(LogicalKeyboardKey.control);
await tester.pump();
final selected = find.byWidgetPredicate(
@@ -248,13 +243,13 @@ void main() {
'Share harness',
'Show message composer',
'Zoom Pane',
- 'Restart Harness',
- 'Fork Harness',
- 'Stop Harness',
+ 'Restart Agent',
+ 'Fork Agent',
+ 'Stop Agent',
'Close Pane',
]),
);
- expect(find.byTooltip('Stop Harness').first.hitTestable(), findsNothing);
+ expect(find.byTooltip('Stop Agent').first.hitTestable(), findsNothing);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: const Offset(1, 1));
Future<void> hover() async {
@@ -281,10 +276,11 @@ void main() {
await hover();
await tester.tap(
- find.descendant(of: controls, matching: find.byTooltip('Stop Harness')),
+ find.descendant(of: controls, matching: find.byTooltip('Stop Agent')),
);
await tester.pumpAndSettle();
- expect(find.text('Stop Harness'), findsNWidgets(2));
+ expect(find.text('Stop Agent'), findsOneWidget);
+ expect(find.text('Stop'), findsOneWidget);
expect(app.panes, contains(pane));
expect(original.panes.single.session, same(session));
await tester.tap(find.text('Cancel'));
diff --git a/desktop/test/swarm_navigation_test.dart b/desktop/test/swarm_navigation_test.dart
index dda0ce368..c7dc121d8 100644
--- a/desktop/test/swarm_navigation_test.dart
+++ b/desktop/test/swarm_navigation_test.dart
@@ -7,6 +7,37 @@ import 'swarm_screen_test.dart' show terminal;
import 'swarm_state_test.dart' show createApp;
void main() {
+ test('numbered results sort naturally without overriding recency or match strength', () {
+ final rows = [
+ for (final name in ['Feature 10', 'Feature 2', 'Feature 1', 'Feature 02'])
+ SwarmDestination(
+ id: name,
+ title: name,
+ detail: '',
+ swarmId: null,
+ current: false,
+ ),
+ ];
+ expect(rankSwarmDestinations(rows, '').map((row) => row.title), [
+ 'Feature 1',
+ 'Feature 2',
+ 'Feature 02',
+ 'Feature 10',
+ ]);
+ expect(
+ rankSwarmDestinations(rows, '', recent: ['Feature 10']).first.title,
+ 'Feature 10',
+ );
+ expect(
+ rankSwarmDestinations(
+ rows,
+ 'Feature 2',
+ recent: ['Feature 10'],
+ ).first.title,
+ 'Feature 2',
+ );
+ });
+
test('search prioritizes title matches without losing better metadata matches', () {
SwarmDestination row(String id, String title, List<String?> fields) =>
SwarmDestination(
diff --git a/desktop/test/swarm_picker_activation_test.dart b/desktop/test/swarm_picker_activation_test.dart
index 393975fe8..d9e731529 100644
--- a/desktop/test/swarm_picker_activation_test.dart
+++ b/desktop/test/swarm_picker_activation_test.dart
@@ -16,7 +16,7 @@ void main() {
final input = <TerminalBinaryFrame>[];
final pane = app.adoptSessionForTest(terminal('a0', input));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
final results = find.byKey(const ValueKey('swarm-search-results'));
expect(field, findsOneWidget);
@@ -56,20 +56,15 @@ void main() {
app.newSwarm();
final target = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
- if (activate == 'click') {
- await tester.enterText(field, 'Agent 0');
- }
+ await tester.enterText(field, 'Agent 0');
await tester.pump();
expect(find.byType(Checkbox), findsNothing);
expect(app.panes, isEmpty);
expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
expect(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-row-action')),
- matching: find.text('Open Harness'),
- ),
+ find.textContaining('enter open', findRichText: true),
findsOneWidget,
);
expect(find.byKey(const ValueKey('swarm-search-accept')), findsNothing);
diff --git a/desktop/test/swarm_project_members_test.dart b/desktop/test/swarm_project_members_test.dart
index a9951b643..205f05200 100644
--- a/desktop/test/swarm_project_members_test.dart
+++ b/desktop/test/swarm_project_members_test.dart
@@ -1,3 +1,9 @@
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:flutter/services.dart';
+
+import 'swarm_interactions_test.dart' show chord;
+
+import 'package:harness/state/swarm_navigation.dart';
import 'package:flutter/material.dart';
import 'package:harness/widgets/swarm_project_agents.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -92,21 +98,29 @@ void main() {
reason:
'Editing project membership does not attach or take over terminals',
);
- await tester.tap(find.byKey(const ValueKey('swarm-open-agent-button')));
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
'Solid',
);
await tester.pump();
- await tester.tap(find.widgetWithText(ListTile, 'Solid'));
+ expect(
+ tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search
+ .rows
+ .where((row) => row.isProject),
+ isEmpty,
+ );
+ await tester.tap(
+ find.byKey(ValueKey(agentDestinationId('remote', 'chess'))),
+ );
await tester.pump(const Duration(milliseconds: 100));
expect(app.panes.map((p) => (p.machineId, p.agentId)), [
- ('m', 'a0'),
- ('m', 'a1'),
('remote', 'chess'),
]);
- expect(app.activeSwarm.name, 'Solid');
+ expect(app.panes.single.machineId, 'remote');
await tester.pumpWidget(const SizedBox());
app.dispose();
projects.dispose();
diff --git a/desktop/test/swarm_rename_dialog_test.dart b/desktop/test/swarm_rename_dialog_test.dart
index a5e936130..73066b1ad 100644
--- a/desktop/test/swarm_rename_dialog_test.dart
+++ b/desktop/test/swarm_rename_dialog_test.dart
@@ -77,20 +77,16 @@ void main() {
await tester.enterText(field, ' ');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pump();
- expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.byType(Dialog), findsOneWidget);
expect(completions, 0);
- expect(
- tester
- .widget<FilledButton>(find.widgetWithText(FilledButton, 'Rename'))
- .onPressed,
- isNull,
- );
+ expect(find.text('Name cannot be empty'), findsOneWidget);
+ expect(editor.focusNode!.hasPrimaryFocus, isTrue);
await tester.enterText(field, ' Search polish ');
await tester.testTextInput.receiveAction(TextInputAction.done);
await tester.pumpAndSettle();
expect(result, 'Search polish');
expect(completions, 1);
- expect(find.byType(AlertDialog), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
@@ -99,7 +95,7 @@ void main() {
await tester.pumpAndSettle();
expect(result, isNull);
expect(completions, 2);
- expect(find.byType(AlertDialog), findsNothing);
+ expect(find.byType(Dialog), findsNothing);
expect(tester.takeException(), isNull);
},
);
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index dcefe3468..99bb63c4d 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -1,3 +1,5 @@
+import 'package:harness/widgets/swarm_switcher.dart';
+
import 'dart:convert';
import 'dart:io';
@@ -57,10 +59,12 @@ bool nativeIconLoaderOpens(String asset) {
final start = swift.indexOf('class SwarmHistoryIcons');
expect(start, isNonNegative, reason: 'SwarmHistoryIcons moved');
final body = swift.substring(start, swift.indexOf('\n}\n', start));
- final exact = RegExp(r'asset == "([^"]+)"').allMatches(body).map((m) => m[1]!);
- final folders = RegExp(
- r'hasPrefix\("([^"]+/)"\)',
- ).allMatches(body).map((m) => m[1]!);
+ final exact = RegExp(r'asset == "([^"]+)"')
+ .allMatches(body)
+ .map((m) => m[1]!);
+ final folders = RegExp(r'hasPrefix\("([^"]+/)"\)')
+ .allMatches(body)
+ .map((m) => m[1]!);
return !asset.contains('..') &&
(exact.contains(asset) || folders.any(asset.startsWith));
}
@@ -122,43 +126,59 @@ void main() {
});
for (final native in [false, true]) {
- testWidgets('New Tab keeps opening tabs past two dozen, as Chrome does (native=$native)', (
- tester,
- ) async {
- const channel = MethodChannel('harness/swarm_tabs');
- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (_) async => true);
- addTearDown(() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null));
- final app = createApp();
- for (var i = 1; i < 30; i++) {
- app.newSwarm(name: 'Project $i');
- }
- app.selectSwarm(app.swarms.first.id);
- await app.addAgentToSwarm('m', 'a0');
- expect(app.swarms, hasLength(30));
- await mount(tester, app, nativeTabs: native);
- if (native) {
- // What Swift sends for File ▸ New Tab, ⌘T and the strip's plus. Not awaited: the handler
- // waits on a frame, which only the pumps below produce.
- tester.binding.defaultBinaryMessenger.handlePlatformMessage(
- 'harness/swarm_tabs',
- const StandardMethodCodec().encodeMethodCall(const MethodCall('new')),
- (_) {},
+ testWidgets(
+ 'New Tab keeps opening tabs past two dozen, as Chrome does (native=$native)',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (_) async => true,
);
- } else {
- await chord(tester, LogicalKeyboardKey.keyT);
- }
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 300));
- expect(app.swarms, hasLength(31));
- expect(app.activeSwarm.name, 'New Tab');
- expect(app.panes, isEmpty);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- });
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ final app = createApp();
+ for (var i = 1; i < 30; i++) {
+ app.newSwarm(name: 'Project $i');
+ }
+ app.selectSwarm(app.swarms.first.id);
+ await app.addAgentToSwarm('m', 'a0');
+ expect(app.swarms, hasLength(30));
+ await mount(tester, app, nativeTabs: native);
+ if (native) {
+ // What Swift sends for File ▸ New Tab, ⌘T and the strip's plus. Not awaited: the handler
+ // waits on a frame, which only the pumps below produce.
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ 'harness/swarm_tabs',
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('new'),
+ ),
+ (_) {},
+ );
+ } else {
+ await chord(tester, LogicalKeyboardKey.keyT);
+ }
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 300));
+ expect(app.swarms, hasLength(30));
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(input, 'Agent 1');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.swarms, hasLength(31));
+ expect(app.panes.single.agentId, 'a1');
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
}
for (final native in [false, true]) {
- testWidgets('the store tab uses the app icon (native=$native)', (
+ testWidgets('the store tab uses the Store mark (native=$native)', (
tester,
) async {
const channel = MethodChannel('harness/swarm_tabs');
@@ -218,12 +238,13 @@ void main() {
(tester) async {
const channel = MethodChannel('harness/swarm_tabs');
final updates = <Map>[];
- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
- call,
- ) async {
- if (call.method == 'update') updates.add(call.arguments as Map);
- return true;
- });
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return true;
+ },
+ );
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
@@ -262,7 +283,11 @@ void main() {
final row = (updates.last['tabs'] as List).single as Map;
expect(row['kind'], 'harness');
expect(row['agentCount'], 1);
- expect(row['engine'], 'autonomous/marp', reason: 'the harness, not the engine under it');
+ expect(
+ row['engine'],
+ 'autonomous/marp',
+ reason: 'the harness, not the engine under it',
+ );
expect(row['iconAsset'], 'assets/engine-icons/marp.png');
} else {
final mark = find.byKey(ValueKey('tab-engine:${tab.id}'));
@@ -286,7 +311,11 @@ void main() {
expect(row['iconAsset'], isNull);
} else {
expect(
- tester.widget<EngineMark>(find.byKey(ValueKey('tab-engine:${leftovers.id}'))).engine,
+ tester
+ .widget<EngineMark>(
+ find.byKey(ValueKey('tab-engine:${leftovers.id}')),
+ )
+ .engine,
isNull,
);
}
@@ -300,7 +329,11 @@ void main() {
expect(row['iconAsset'], 'assets/engine-icons/codex.png');
} else {
expect(
- tester.widget<EngineMark>(find.byKey(ValueKey('tab-engine:${leftovers.id}'))).engine,
+ tester
+ .widget<EngineMark>(
+ find.byKey(ValueKey('tab-engine:${leftovers.id}')),
+ )
+ .engine,
'codex',
);
}
@@ -311,63 +344,65 @@ void main() {
},
);
- testWidgets('the store opens past forty tabs, and is still one tab (native=$native)', (
- tester,
- ) async {
- const channel = MethodChannel('harness/swarm_tabs');
- final updates = <Map>[];
- tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (
- call,
- ) async {
- if (call.method == 'update') updates.add(call.arguments as Map);
- return true;
- });
- addTearDown(
- () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ testWidgets(
+ 'the store opens past forty tabs, and is still one tab (native=$native)',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ final updates = <Map>[];
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
channel,
- null,
- ),
- );
- final app = createApp();
- await mount(tester, app, nativeTabs: native);
- await app.addAgentToSwarm('m', 'a0');
- for (var i = 0; i < 40; i++) {
- app.newSwarm(name: 'Project $i');
- }
- app.openStore();
- await tester.pump();
- final store = app.activeSwarm;
- expect(store.isStore, isTrue);
- expect(app.swarms, hasLength(42));
- app.selectSwarm(app.swarms.first.id);
- app.openStore();
- await tester.pump();
- expect(app.activeSwarm, same(store));
- expect(app.swarms.where((swarm) => swarm.isStore), hasLength(1));
- if (native) {
- final rows = (updates.last['tabs'] as List).cast<Map>();
- expect(rows, hasLength(42));
- expect(rows.where((row) => row['kind'] == 'store'), hasLength(1));
- expect(rows.last['engine'], 'store');
- expect(updates.last['activeId'], store.id);
- } else {
- // The strip is the one horizontal list; the store is its last tab.
- final strip = find
- .byWidgetPredicate(
- (widget) =>
- widget is Scrollable &&
- widget.axisDirection == AxisDirection.right,
- )
- .first;
- // Scrolled, not dragged: a drag on a tab reorders it.
- final position = tester.state<ScrollableState>(strip).position;
- position.jumpTo(position.maxScrollExtent);
+ (call) async {
+ if (call.method == 'update') updates.add(call.arguments as Map);
+ return true;
+ },
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ final app = createApp();
+ await mount(tester, app, nativeTabs: native);
+ await app.addAgentToSwarm('m', 'a0');
+ for (var i = 0; i < 40; i++) {
+ app.newSwarm(name: 'Project $i');
+ }
+ app.openStore();
await tester.pump();
- expect(find.byKey(ValueKey('tab-store:${store.id}')), findsOneWidget);
- }
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- });
+ final store = app.activeSwarm;
+ expect(store.isStore, isTrue);
+ expect(app.swarms, hasLength(42));
+ app.selectSwarm(app.swarms.first.id);
+ app.openStore();
+ await tester.pump();
+ expect(app.activeSwarm, same(store));
+ expect(app.swarms.where((swarm) => swarm.isStore), hasLength(1));
+ if (native) {
+ final rows = (updates.last['tabs'] as List).cast<Map>();
+ expect(rows, hasLength(42));
+ expect(rows.where((row) => row['kind'] == 'store'), hasLength(1));
+ expect(rows.last['engine'], 'store');
+ expect(updates.last['activeId'], store.id);
+ } else {
+ // The strip is the one horizontal list; the store is its last tab.
+ final strip = find
+ .byWidgetPredicate(
+ (widget) =>
+ widget is Scrollable &&
+ widget.axisDirection == AxisDirection.right,
+ )
+ .first;
+ // Scrolled, not dragged: a drag on a tab reorders it.
+ final position = tester.state<ScrollableState>(strip).position;
+ position.jumpTo(position.maxScrollExtent);
+ await tester.pump();
+ expect(find.byKey(ValueKey('tab-store:${store.id}')), findsOneWidget);
+ }
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
testWidgets('tab identity follows its agent count (native=$native)', (
tester,
@@ -389,7 +424,7 @@ void main() {
final app = createApp();
final tab = app.activeSwarm;
await mount(tester, app, nativeTabs: native);
- expect(tab.name, 'New Tab');
+ expect(tab.name, 'Untitled Tab');
expect(
find.byKey(const ValueKey('harness-start-search')),
findsOneWidget,
@@ -408,7 +443,13 @@ void main() {
// A harness's viewer beside its agent is the same agent: still its mark, not a group.
tab.panes.add(
- TerminalPane(id: 900, machineId: 'm', kind: PaneKind.web, ownerAgentId: 'a0', url: 'http://127.0.0.1:1/'),
+ TerminalPane(
+ id: 900,
+ machineId: 'm',
+ kind: PaneKind.web,
+ ownerAgentId: 'a0',
+ url: 'http://127.0.0.1:1/',
+ ),
);
app.renameSwarm(tab.id, 'New Tab');
await tester.pump();
@@ -465,7 +506,7 @@ void main() {
);
await mount(tester, app);
expect(find.text('Existing project'), findsNothing);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
@@ -481,10 +522,17 @@ void main() {
findsOneWidget,
);
expect(find.byKey(ValueKey(agentDestinationId('m', 'a2'))), findsNothing);
- await tester.tap(find.widgetWithText(ListTile, 'Existing project'));
+ expect(
+ tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search
+ .rows
+ .where((row) => row.isProject),
+ isEmpty,
+ );
+ await tester.tap(find.byKey(ValueKey(agentDestinationId('m', 'a0'))));
await tester.pump(const Duration(milliseconds: 100));
- expect(app.activeSwarm.name, 'Existing project');
- expect(app.panes.map((p) => p.agentId), ['a0', 'a1']);
+ expect(app.panes.map((p) => p.agentId), ['a0']);
await tester.pumpWidget(const SizedBox());
app.dispose();
},
@@ -501,7 +549,7 @@ void main() {
);
expect(find.text('Models'), findsNothing);
expect(find.text('Machines'), findsNothing);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
@@ -513,11 +561,11 @@ void main() {
await tester.pump();
await app.addAgentToSwarm('m', 'a2');
app.toggleZoomPane();
- // The Open button appears when the first agent replaces the welcome page.
+ // New Pane overlays the workspace without resizing its terminals.
await tester.pump(const Duration(milliseconds: 200));
final zoom = app.zoomedPaneId;
final before = tester.getSize(find.byType(PaneGrid));
- await tester.tap(find.byKey(const ValueKey('swarm-open-agent-button')));
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump(const Duration(milliseconds: 300));
expect(
find.byKey(const ValueKey('swarm-search-results')),
diff --git a/desktop/test/swarm_search_identity_test.dart b/desktop/test/swarm_search_identity_test.dart
index ce26272fc..b4d597a6e 100644
--- a/desktop/test/swarm_search_identity_test.dart
+++ b/desktop/test/swarm_search_identity_test.dart
@@ -235,7 +235,7 @@ void main() {
var rows = cache.read(app, []);
expect(
rows.singleWhere((row) => row.isSwarm).detail,
- '2 harnesses · 1 project · 2 machines',
+ 'Tab · 2 harnesses · 1 project · 2 machines',
);
expect(rows.where((row) => row.agentId == 'a0'), hasLength(2));
expect(rows.singleWhere((row) => row.isSwarm).title, 'Release work');
@@ -243,7 +243,7 @@ void main() {
rows = cache.read(app, []);
expect(
rows.singleWhere((row) => row.isSwarm).detail,
- '3 harnesses · 2 projects · 2 machines',
+ 'Tab · 3 harnesses · 2 projects · 2 machines',
);
app.newSwarm();
@@ -291,11 +291,11 @@ void main() {
final cache = SwarmSearchCatalog();
expect(
cache.read(app, projects).singleWhere((row) => row.isSwarm).detail,
- '2 harnesses · 1 project · 1 machine',
+ 'Tab · 2 harnesses · 1 project · 1 machine',
);
expect(
cache.read(app, []).singleWhere((row) => row.isSwarm).detail,
- '2 harnesses · 1 machine',
+ 'Tab · 2 harnesses · 1 machine',
);
},
);
@@ -319,7 +319,7 @@ void main() {
);
testWidgets(
- 'Cmd O renders one harness result and opens it from a tab-name alias',
+ 'Cmd P renders one harness result and opens it from a tab-name alias',
(tester) async {
final app = createApp();
final machine = app.machineStates['m']!..nodeOnline = true;
@@ -343,29 +343,38 @@ void main() {
app.newSwarm();
final target = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final input = find.byKey(const ValueKey('swarm-search-input'));
expect(
tester.widget<TextField>(input).decoration!.hintText,
- 'Find a harness',
+ kHarnessPickerHint,
);
await tester.enterText(input, 'extensibility');
await tester.pump();
- expect(find.byType(ListTile), findsOneWidget);
- final result = tester.widget<ListTile>(find.byType(ListTile));
- final subtitle = result.subtitle! as SearchResultText;
- expect(subtitle.text, 'Code · autonomous-harness · main · Test host');
- expect(subtitle.iconOffset, subtitle.text.indexOf('main'));
+ // One harness, then the row that makes what was typed instead.
+ expect(find.byType(ListTile), findsNWidgets(2));
+ expect(find.byKey(const ValueKey(kSwarmCreateRowId)), findsOneWidget);
+ // Context remains visible and searchable when drawn as separate segments.
+ for (final value in [
+ 'Claude',
+ 'Test host',
+ 'autonomous-harness',
+ 'main',
+ ]) {
+ expect(
+ find.byWidgetPredicate(
+ (widget) => widget is SearchResultText && widget.text == value,
+ ),
+ findsOneWidget,
+ );
+ }
expect(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-row-action')),
- matching: find.text('Open Harness'),
- ),
+ find.textContaining('enter open', findRichText: true),
findsOneWidget,
);
await tester.enterText(input, 'Architecture review');
await tester.pump();
- expect(find.byType(ListTile), findsOneWidget);
+ expect(find.byType(ListTile), findsNWidgets(2));
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(app.activeSwarm, same(target));
diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dart
index 001a2b424..11b4b6417 100644
--- a/desktop/test/swarm_search_preview_test.dart
+++ b/desktop/test/swarm_search_preview_test.dart
@@ -99,7 +99,7 @@ void main() {
await seedPreviews(app);
app.adoptSessionForTest(terminal('a69', []));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Workspace sync');
await tester.pump();
@@ -107,7 +107,7 @@ void main() {
app.machineStates['m']!.connectionStatus = ConnectionStatus.disconnected;
app.notifyListeners();
await tester.pump();
- expect(find.text('Offline'), findsOneWidget);
+ expect(find.textContaining('Offline', findRichText: true), findsOneWidget);
expect(find.text('Needs your input'), findsNothing);
expect(
find.textContaining('Keep shared workspaces in sync'),
@@ -173,7 +173,7 @@ void main() {
if (inline) {
await tester.tap(field);
} else {
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
}
await tester.enterText(field, 'Checkout retries');
await tester.pump();
@@ -250,10 +250,9 @@ void main() {
// Switching to a group and paging before its frame uses the new
// viewport and never retains the previous session's reading position.
- await tester.enterText(field, 'Test host');
+ await tester.enterText(field, 'Additional agent 3');
await page();
- expect(search.selected!.agentId, isNull);
- expect(previewPosition().pixels, greaterThan(0));
+ expect(search.selected!.agentId, 'paging-3');
await page(up: true);
expect(previewPosition().pixels, 0);
await tester.enterText(field, 'Checkout retries');
@@ -286,7 +285,7 @@ void main() {
if (inline) {
await tester.tap(field);
} else {
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
}
await tester.enterText(field, 'Checkout retries');
await tester.pump();
@@ -341,10 +340,12 @@ void main() {
final search = tester
.widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
.search;
- expect(search.selected!.agentId, isNull);
- final waiting = tester.getTopLeft(find.text('Workspace sync').last);
- final working = tester.getTopLeft(find.text('Search experience').last);
- expect(waiting.dy, lessThan(working.dy));
+ expect(
+ search.rows.every((row) => row.isCreate || row.agentId != null),
+ isTrue,
+ );
+ await tester.enterText(field, 'Workspace sync');
+ await tester.pump();
expect(
find.text(
'Should a workspace reopen its last layout on another machine?',
@@ -368,7 +369,7 @@ void main() {
}
testWidgets(
- 'existing earlier explanations stay visible after a commit receipt',
+ 'earlier explanations remain readable by keyboard after a commit receipt',
(tester) async {
final app = createApp();
await seedPreviews(app);
@@ -381,7 +382,7 @@ void main() {
);
app.adoptSessionForTest(terminal('a69', []));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
'Checkout',
@@ -395,6 +396,11 @@ void main() {
final preview = tester.getRect(
find.byKey(const ValueKey('swarm-search-preview')),
);
+ await key(tester, LogicalKeyboardKey.pageDown);
+ expect(
+ tester.getRect(explanation).top,
+ greaterThanOrEqualTo(preview.top),
+ );
expect(tester.getRect(explanation).bottom, lessThan(preview.bottom));
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -415,7 +421,7 @@ void main() {
await mount(tester, app);
tester.view.physicalSize = size;
await tester.pump();
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
'Checkout',
@@ -429,7 +435,7 @@ void main() {
find.byKey(const ValueKey('swarm-search-result-list')),
);
if (size.width < 864) {
- expect(preview.top, greaterThanOrEqualTo(list.bottom));
+ expect(preview.bottom, lessThanOrEqualTo(list.top));
}
final directory = Platform.environment['HARNESS_PREVIEW_CAPTURE_DIR'];
if (directory != null) {
diff --git a/desktop/test/swarm_search_render_test.dart b/desktop/test/swarm_search_render_test.dart
index 430dc8ff8..6c58360c0 100644
--- a/desktop/test/swarm_search_render_test.dart
+++ b/desktop/test/swarm_search_render_test.dart
@@ -10,6 +10,7 @@ import 'package:harness/state/swarm_navigation.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/swarm_search_input.dart';
import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/widgets/search_result_text.dart';
import 'package:xterm/xterm.dart';
import 'swarm_interactions_test.dart' show chord;
@@ -58,10 +59,7 @@ void main() {
final target = app.activeSwarm;
await mount(tester, app);
final field = find.byKey(const ValueKey('swarm-search-input'));
- Future<void> open() => chord(
- tester,
- add ? LogicalKeyboardKey.keyO : LogicalKeyboardKey.keyP,
- );
+ Future<void> open() => chord(tester, LogicalKeyboardKey.keyP);
SwarmSearchKeys keys() => tester.widget<SwarmSearchKeys>(
find.ancestor(of: field, matching: find.byType(SwarmSearchKeys)),
);
@@ -104,7 +102,8 @@ void main() {
expect(search.targetId, target.id);
if (add) {
expect(search.alreadyHere(rows.single), isTrue);
- expect(search.canSubmit(rows.single), isFalse);
+ expect(search.canSubmit(rows.single), isTrue);
+ expect(search.actionLabel(rows.single), 'Focus pane');
} else {
expect(rows.map((row) => row.swarmId).toSet(), {
source.id,
@@ -144,7 +143,7 @@ void main() {
SwarmSearchInput inputWidget() => tester.widget<SwarmSearchInput>(
find.ancestor(of: field, matching: find.byType(SwarmSearchInput)),
);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.enterText(field, 'Agent 0');
await tester.pump();
final first = inputWidget().search!;
@@ -159,7 +158,7 @@ void main() {
await tester.pump();
session.terminal.write('Newest useful output.\r\n');
machine.projectReads = 0;
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
expect(tester.widget<TextField>(field).controller!.text, isEmpty);
await tester.enterText(field, 'Agent 0');
await tester.pump();
@@ -198,11 +197,7 @@ void main() {
if (element.widget is SwarmScreen) canvasBuilds++;
};
try {
- await chord(
- tester,
- add ? LogicalKeyboardKey.keyO : LogicalKeyboardKey.keyP,
- shift: !add,
- );
+ await chord(tester, LogicalKeyboardKey.keyP, shift: !add);
expect(
tester
.widget<TextField>(
@@ -242,7 +237,7 @@ void main() {
final input = <TerminalBinaryFrame>[];
app.adoptSessionForTest(terminal('a69', input));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Agent');
await tester.pump(const Duration(milliseconds: 200));
@@ -260,7 +255,7 @@ void main() {
if (element.widget is ListTile && visibleRows.contains(element)) rows++;
};
try {
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
} finally {
debugOnRebuildDirtyWidget = null;
@@ -283,6 +278,53 @@ void main() {
app.dispose();
});
+ testWidgets(
+ 'query edits update match text without rebuilding unchanged row controls',
+ (tester) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ app.adoptSessionForTest(terminal('a69', input));
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(field, 'Agent');
+ await tester.pump(const Duration(milliseconds: 200));
+ final visibleRows = find.byType(ListTile).evaluate().where((element) {
+ final key = element.widget.key;
+ return key is ValueKey<String> && key.value.startsWith('agent:');
+ }).toSet();
+ expect(visibleRows, isNotEmpty);
+ var rowBuilds = 0;
+ debugOnRebuildDirtyWidget = (element, _) {
+ if (element.widget is ListTile && visibleRows.contains(element)) {
+ rowBuilds++;
+ }
+ };
+ try {
+ await tester.enterText(field, 'Agen');
+ await tester.pump();
+ } finally {
+ debugOnRebuildDirtyWidget = null;
+ }
+ expect(
+ rowBuilds,
+ 0,
+ reason: 'Only match text changed on these same result rows',
+ );
+ final matches = tester
+ .widgetList<SearchResultText>(find.byType(SearchResultText))
+ .where((widget) => widget.text.startsWith('Agent '))
+ .expand((widget) => widget.matches.where((match) => match.title))
+ .map((match) => match.term)
+ .toSet();
+ expect(matches, {'agen'});
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(input, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
testWidgets(
'cached Add rows keep selection through palette and text changes',
(tester) async {
@@ -303,7 +345,7 @@ void main() {
),
),
);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Agent');
await tester.pump();
@@ -338,7 +380,7 @@ void main() {
final input = <TerminalBinaryFrame>[];
app.adoptSessionForTest(terminal('a69', input));
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Agent');
await tester.pump();
@@ -349,10 +391,10 @@ void main() {
app.dismissError(); // Publish the sessions assembled through the test seam.
await tester.pump();
final row = find.byKey(ValueKey(agentDestinationId('m', 'a0')));
- expect(tester.widget<ListTile>(row).enabled, isFalse);
+ expect(tester.widget<ListTile>(row).enabled, isTrue);
expect(
find.descendant(of: row, matching: find.text('Already added')),
- findsOneWidget,
+ findsNothing,
);
await app.closePane(app.panes.last.id);
await tester.pump();
@@ -375,7 +417,7 @@ void main() {
app.adoptSessionForTest(terminal('a69', input));
final target = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
final field = find.byKey(const ValueKey('swarm-search-input'));
await tester.enterText(field, 'Agent');
await tester.pump();
@@ -388,7 +430,7 @@ void main() {
)
.search!;
final previous = search.selected!.id;
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp);
await tester.pump();
expect(search.selected!.id, isNot(previous));
expect(input, isEmpty);
diff --git a/desktop/test/swarm_search_test.dart b/desktop/test/swarm_search_test.dart
index 812c93edd..61c629134 100644
--- a/desktop/test/swarm_search_test.dart
+++ b/desktop/test/swarm_search_test.dart
@@ -27,7 +27,7 @@ void main() {
await mount(tester, app);
final input = find.byKey(const ValueKey('swarm-search-input'));
expect(input, findsNothing);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
final originalController = tester.widget<TextField>(input).controller;
await tester.enterText(input, 'a query only');
@@ -74,12 +74,21 @@ void main() {
),
];
final entries = SwarmSearchCatalog().read(app, const []);
- expect(rankSwarmDestinations(entries, 'Board fab check').first.agentId, 'a6');
+ expect(
+ rankSwarmDestinations(entries, 'Board fab check').first.agentId,
+ 'a6',
+ );
expect(rankSwarmDestinations(entries, 'parts review').first.agentId, 'a6');
// a bare word that names a project outranks a title that merely contains it
expect(rankSwarmDestinations(entries, 'fab').first.isProject, isTrue);
// the whole title, exactly, is the strongest match there is
- expect(rankSwarmDestinations(entries, 'board fab check and parts review').first.agentId, 'a6');
+ expect(
+ rankSwarmDestinations(
+ entries,
+ 'board fab check and parts review',
+ ).first.agentId,
+ 'a6',
+ );
});
test('one cached catalog searches all four objects and explicit remote project members', () {
@@ -295,28 +304,29 @@ void main() {
},
);
- testWidgets('Add imports all agents from a machine into this swarm', (
- tester,
- ) async {
- final app = createApp();
- app.machineStates['m']!.agents = app.machineStates['m']!.agents
- .take(3)
- .toList();
- await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
- await tester.pump();
- await tester.enterText(jumpField, 'Test host');
- await tester.pump();
- await tester.tap(find.byKey(const ValueKey('machine:m')));
- await tester.pump();
- expect(app.activeSwarm.name, 'Test host');
- expect(app.panes.map((pane) => pane.agentId), ['a0', 'a1', 'a2']);
- expect(app.swarms.length, 1);
- expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);
- expect(find.text('Browse agents'), findsNothing);
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- });
+ testWidgets(
+ 'machine names filter harnesses without adding the whole machine',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.agents = app.machineStates['m']!.agents
+ .take(3)
+ .toList();
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyP);
+ await tester.pump();
+ await tester.enterText(jumpField, 'Test host');
+ await tester.pump();
+ expect(find.byKey(const ValueKey('machine:m')), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.panes.map((pane) => pane.agentId), ['a0']);
+ expect(app.swarms.length, 1);
+ expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);
+ expect(find.text('Browse agents'), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
testWidgets('Add keeps a shared view here and the first key reaches it', (
tester,
@@ -332,16 +342,13 @@ void main() {
app.adoptSessionForTest(terminal('a1', secondInputs));
final target = app.activeSwarm;
await mount(tester, app);
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
await tester.enterText(jumpField, 'Agent 0');
await tester.pump();
expect(find.byKey(const ValueKey('swarm-row-action')), findsOneWidget);
expect(
- find.descendant(
- of: find.byKey(const ValueKey('swarm-row-action')),
- matching: find.text('Open Harness'),
- ),
+ find.textContaining('enter open', findRichText: true),
findsOneWidget,
);
await chord(tester, LogicalKeyboardKey.enter);
@@ -378,7 +385,7 @@ void main() {
ValueKey(adding ? 'swarm-search-input' : 'harness-start-search'),
);
if (adding) {
- await chord(tester, LogicalKeyboardKey.keyO);
+ await chord(tester, LogicalKeyboardKey.keyP);
await tester.pump();
} else {
await tester.tap(field);
diff --git a/desktop/test/swarm_split_test.dart b/desktop/test/swarm_split_test.dart
index 1300bcc96..87a0df47b 100644
--- a/desktop/test/swarm_split_test.dart
+++ b/desktop/test/swarm_split_test.dart
@@ -48,7 +48,7 @@ void main() {
for (final axis in PaneResizeAxis.values) {
final direction = axis == PaneResizeAxis.x ? 'right' : 'down';
testWidgets(
- 'Command-${direction == 'right' ? 'R' : 'D'} splits the focused pane $direction',
+ 'the secondary palette command splits the focused pane $direction',
(tester) async {
final app = createApp();
final machine = app.machineStates['m']!;
@@ -68,13 +68,14 @@ void main() {
app.selectSwarm(original);
app.focusPane(first.id);
await mountWide(tester, app);
- await chord(
- tester,
- axis == PaneResizeAxis.x
- ? LogicalKeyboardKey.keyR
- : LogicalKeyboardKey.keyD,
+ await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ '> split $direction',
);
await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
final search = find.byKey(const ValueKey('swarm-search-input'));
expect(search, findsOneWidget);
await tester.enterText(search, 'New split helper');
@@ -97,191 +98,23 @@ void main() {
},
);
- testWidgets(
- 'edge Open $direction targets that pane without disturbing its neighbor',
- (tester) async {
- final app = createApp();
- final machine = app.machineStates['m']!;
- machine.nodeOnline = true;
- machine.localOnly = true;
- machine.agents[2] = const Agent(
- id: 'a2',
- name: 'Existing helper',
- engine: 'codex',
- terminalAvailable: true,
- );
- final frames = <TerminalBinaryFrame>[];
- final first = app.adoptSessionForTest(terminal('a0', frames));
- final neighbor = app.adoptSessionForTest(terminal('a1', frames));
- final original = app.activeSwarmId;
- app.newSwarm();
- final helper = app.adoptSessionForTest(terminal('a2', frames));
- app.selectSwarm(original);
- app.focusPane(neighbor.id);
- await mountWide(tester, app);
- tester.view.physicalSize = const Size(3000, 1800);
- await tester.pump();
- final target = find.byKey(first.cellKey);
- final rect = tester.getRect(target);
- final neighborRect = tester.getRect(find.byKey(neighbor.cellKey));
- final view = find.descendant(
- of: target,
- matching: find.byType(TerminalView),
- );
- final retained = tester.element(view);
- final previousFocus = FocusManager.instance.primaryFocus;
- final button = find.descendant(
- of: target,
- matching: find.byKey(ValueKey('pane-open-$direction')),
- );
- final newButton = find.descendant(
- of: target,
- matching: find.byKey(ValueKey('pane-new-$direction')),
- );
- expect(button.hitTestable(), findsNothing);
- expect(newButton.hitTestable(), findsNothing);
- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: rect.center);
- await mouse.moveTo(
- axis == PaneResizeAxis.x
- ? Offset(rect.right - 2, rect.center.dy)
- : Offset(rect.center.dx, rect.bottom - 2),
- );
- await tester.pump(const Duration(milliseconds: 120));
- expect(button.hitTestable(), findsOneWidget);
- expect(newButton.hitTestable(), findsOneWidget);
- expect(
- tester.getRect(button).overlaps(tester.getRect(newButton)),
- isFalse,
- );
- expect(app.focusedPaneId, neighbor.id);
- expect(FocusManager.instance.primaryFocus, same(previousFocus));
- expect(tester.element(view), same(retained));
- expect(tester.getRect(target), rect);
- expect(frames, isEmpty);
-
- // Moving from the border onto the inset button must keep it visible.
- await mouse.moveTo(tester.getCenter(newButton));
- await tester.pump();
- expect(newButton.hitTestable(), findsOneWidget);
- await mouse.moveTo(tester.getCenter(button));
- await tester.pump();
- expect(button.hitTestable(), findsOneWidget);
- await mouse.down(tester.getCenter(button));
- await mouse.up();
- await tester.pump();
- final search = find.byKey(const ValueKey('swarm-search-input'));
- expect(search, findsOneWidget);
- expect(
- find.byKey(const ValueKey('swarm-search-new-agent')),
- findsNothing,
- );
- expect(app.focusedPaneId, first.id);
- await tester.enterText(search, 'Existing helper');
- await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
- await tester.pump();
- expect(search, findsNothing);
- expect(app.panes, [first, helper, neighbor]);
- expect(tester.element(view), same(retained));
- expect(tester.getRect(find.byKey(neighbor.cellKey)), neighborRect);
- final splitRect = tester.getRect(target);
- final addedRect = tester.getRect(find.byKey(helper.cellKey));
- if (axis == PaneResizeAxis.x) {
- expect(addedRect.left, greaterThan(splitRect.right));
- expect(addedRect.top, splitRect.top);
- expect(addedRect.height, splitRect.height);
- } else {
- expect(addedRect.top, greaterThan(splitRect.bottom));
- expect(addedRect.left, splitRect.left);
- expect(addedRect.width, splitRect.width);
- }
- expect(frames, isEmpty);
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
- await tester.pump(const Duration(milliseconds: 10));
- expect(frames.single.streamId, helper.session!.streamId);
- expect(frames.single.bytes, [27, 91, 67]);
- await mouse.removePointer();
- await tester.pumpWidget(const SizedBox());
- app.dispose();
- },
- );
- testWidgets('edge New $direction opens creation with the hovered project', (
+ testWidgets('pane edges no longer offer New/Open $direction', (
tester,
) async {
- final connection = _Creation();
- final app = createApp(connectionForTest: (_) => connection);
- final machine = app.machineStates['m']!;
- machine.nodeOnline = true;
- machine.agents[0] = const Agent(
- id: 'a0',
- name: 'First project',
- engine: 'claude',
- project: AgentProject(name: 'first', cwd: '/work/first'),
- );
- machine.agents[1] = const Agent(
- id: 'a1',
- name: 'Neighbor',
- engine: 'claude',
- project: AgentProject(name: 'neighbor', cwd: '/work/neighbor'),
- );
- final frames = <TerminalBinaryFrame>[];
- final first = app.adoptSessionForTest(terminal('a0', frames));
- final neighbor = app.adoptSessionForTest(terminal('a1', frames));
- app.focusPane(neighbor.id);
+ final app = createApp();
+ app.adoptSessionForTest(terminal('a0', []));
await mountWide(tester, app);
- tester.view.physicalSize = const Size(3000, 1800);
- await tester.pump();
- final target = find.byKey(first.cellKey);
- final before = tester.getRect(target);
- final neighborBefore = tester.getRect(find.byKey(neighbor.cellKey));
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
- await mouse.addPointer(location: before.center);
+ final rect = tester.getRect(find.byKey(app.panes.single.cellKey));
+ await mouse.addPointer(location: rect.center);
await mouse.moveTo(
axis == PaneResizeAxis.x
- ? Offset(before.right - 2, before.center.dy)
- : Offset(before.center.dx, before.bottom - 2),
+ ? Offset(rect.right - 2, rect.center.dy)
+ : Offset(rect.center.dx, rect.bottom - 2),
);
await tester.pump(const Duration(milliseconds: 120));
- final create = find.descendant(
- of: target,
- matching: find.byKey(ValueKey('pane-new-$direction')),
- );
- await mouse.moveTo(tester.getCenter(create));
- await mouse.down(tester.getCenter(create));
- await mouse.up();
- await tester.pump();
- expect(find.byType(AlertDialog), findsOneWidget);
- expect(
- find.text(
- axis == PaneResizeAxis.x
- ? 'New Harness to the right'
- : 'New Harness below',
- ),
- findsOneWidget,
- );
- expect(
- find.descendant(
- of: find.byKey(const Key('new-agent-project-browse')),
- matching: find.text('first'),
- ),
- findsOneWidget,
- );
- expect(find.text('/work/neighbor'), findsNothing);
- expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
- expect(app.focusedPaneId, first.id);
- expect(tester.getRect(target), before);
- expect(tester.getRect(find.byKey(neighbor.cellKey)), neighborBefore);
- expect(connection.calls, isNot(contains('agent_create')));
- expect(frames, isEmpty);
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await tester.pump();
- expect(find.byType(AlertDialog), findsNothing);
- expect(app.panes, [first, neighbor]);
- await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
- await tester.pump(const Duration(milliseconds: 10));
- expect(frames.single.streamId, first.session!.streamId);
+ expect(find.byKey(ValueKey('pane-open-$direction')), findsNothing);
+ expect(find.byKey(ValueKey('pane-new-$direction')), findsNothing);
await mouse.removePointer();
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -434,7 +267,7 @@ void main() {
isTrue,
);
if (change != 'switch') {
- expect(app.lastError, contains('harness was created'));
+ expect(app.lastError, contains('harness started'));
}
expect(connection.calls, isNot(contains('agent_delete')));
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dart
index c5e6222cb..79de0684b 100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@ -60,35 +60,32 @@ AppNotifier createApp({
}
void main() {
- test(
- 'New Tab reuses the unused page from every tab, and past two dozen tabs still opens one',
- () async {
- final app = createApp();
- addTearDown(app.dispose);
- final starter = app.activeSwarm;
- for (var i = 0; i < 10; i++) {
- app.newSwarm();
- }
- expect(app.swarms, [starter]);
-
- for (var i = 1; i < 30; i++) {
- app.newSwarm(name: 'Project $i');
- }
- final project = app.activeSwarm;
- for (var i = 0; i < 10; i++) {
- app.selectSwarm(project.id);
- app.newSwarm();
- expect(app.activeSwarm, same(starter));
- expect(app.swarms, hasLength(30));
- }
+ test('New Tab reuses the unused page from every tab, and past two dozen tabs still opens one', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final starter = app.activeSwarm;
+ for (var i = 0; i < 10; i++) {
+ app.newSwarm();
+ }
+ expect(app.swarms, [starter]);
- await app.addAgentToSwarm('m', 'a0');
+ for (var i = 1; i < 30; i++) {
+ app.newSwarm(name: 'Project $i');
+ }
+ final project = app.activeSwarm;
+ for (var i = 0; i < 10; i++) {
+ app.selectSwarm(project.id);
app.newSwarm();
- expect(app.activeSwarm, isNot(same(starter)));
- expect(app.panes, isEmpty);
- expect(app.swarms, hasLength(31));
- },
- );
+ expect(app.activeSwarm, same(starter));
+ expect(app.swarms, hasLength(30));
+ }
+
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm();
+ expect(app.activeSwarm, isNot(same(starter)));
+ expect(app.panes, isEmpty);
+ expect(app.swarms, hasLength(31));
+ });
for (final activeId in ['empty-2', 'work']) {
test(
@@ -136,7 +133,7 @@ void main() {
'New Tab',
]) {
test(
- '$legacy empty tabs restore as New Tab and number the first occupied tab',
+ '$legacy legacy empty tabs restore with a placeholder and follow the first agent',
() async {
final store = MemoryStore();
final original = createApp(store: store);
@@ -147,13 +144,17 @@ void main() {
store.values.values.any((value) => value.contains(legacy)),
isTrue,
);
+ // Old saves had no custom-name marker.
+ store.values.updateAll(
+ (_, value) => value.replaceAll(',"nameIsCustom":true', ''),
+ );
original.dispose();
final restored = createApp(store: store);
addTearDown(restored.dispose);
await restored.restorePaneLayoutForTest();
- expect(restored.activeSwarm.name, 'New Tab');
+ expect(restored.activeSwarm.name, 'Untitled Tab');
await restored.addAgentToSwarm('m', 'a0');
- expect(restored.activeSwarm.name, 'harness-1');
+ expect(restored.activeSwarm.name, 'Agent 0');
},
);
}
@@ -164,13 +165,13 @@ void main() {
final app = createApp();
addTearDown(app.dispose);
await app.addAgentToSwarm('m', 'a0');
- expect(app.activeSwarm.name, 'harness-1');
+ expect(app.activeSwarm.name, 'Agent 0');
await app.addAgentToSwarm('m', 'a1');
- expect(app.activeSwarm.name, 'harness-1');
- expect(app.activeSwarm.toJson()['name'], 'harness-1');
+ expect(app.activeSwarm.name, 'Agent 0');
+ expect(app.activeSwarm.toJson()['name'], 'Agent 0');
await app.closeSwarm(app.activeSwarmId);
app.reopenClosedSwarm();
- expect(app.activeSwarm.name, 'harness-1');
+ expect(app.activeSwarm.name, 'Agent 0');
},
);
@@ -186,32 +187,36 @@ void main() {
final target = app.activeSwarm;
app.newSwarm(name: 'Elsewhere');
await app.addAgentToSwarm('m', 'a1', swarmId: target.id);
- expect(target.name, 'harness-1');
+ expect(target.name, 'Agent 1');
expect(app.activeSwarm.name, 'Elsewhere');
},
);
- test('tab numbering skips saved and recently closed names', () async {
- final store = MemoryStore();
- final app = createApp(store: store);
- await app.addAgentToSwarm('m', 'a0');
- app.newSwarm();
- await app.addAgentToSwarm('m', 'a1');
- expect(app.activeSwarm.name, 'harness-2');
- await app.closeSwarm(app.activeSwarmId);
- app.newSwarm();
- await app.addAgentToSwarm('m', 'a2');
- expect(app.activeSwarm.name, 'harness-3');
- app.renameSwarm(app.activeSwarmId, 'harness-10');
- await app.flushPaneLayout();
- app.dispose();
- final restored = createApp(store: store);
- addTearDown(restored.dispose);
- await restored.restorePaneLayoutForTest();
- restored.newSwarm();
- await restored.addAgentToSwarm('m', 'a3');
- expect(restored.activeSwarm.name, 'harness-11');
- });
+ test(
+ 'new tabs follow their harness and preserve custom names across restores',
+ () async {
+ final store = MemoryStore();
+ final app = createApp(store: store);
+ await app.addAgentToSwarm('m', 'a0');
+ app.newSwarm();
+ await app.addAgentToSwarm('m', 'a1');
+ expect(app.activeSwarm.name, 'Agent 1');
+ await app.closeSwarm(app.activeSwarmId);
+ app.newSwarm();
+ await app.addAgentToSwarm('m', 'a2');
+ expect(app.activeSwarm.name, 'Agent 2');
+ app.renameSwarm(app.activeSwarmId, 'harness-10');
+ await app.flushPaneLayout();
+ app.dispose();
+ final restored = createApp(store: store);
+ addTearDown(restored.dispose);
+ await restored.restorePaneLayoutForTest();
+ expect(restored.activeSwarm.name, 'harness-10');
+ restored.newSwarm();
+ await restored.addAgentToSwarm('m', 'a3');
+ expect(restored.activeSwarm.name, 'Agent 3');
+ },
+ );
test(
'shared memberships own one controller and close only the final stream',
diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dart
index 996f0d301..66de8d713 100644
--- a/desktop/test/swarm_switcher_test.dart
+++ b/desktop/test/swarm_switcher_test.dart
@@ -4,7 +4,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shortcuts/keymap_commands.dart';
import 'package:harness/terminal/terminal_binary.dart';
import 'package:harness/widgets/swarm_switcher.dart';
-import 'package:harness/orchestrator/orchestrator_launcher.dart';
import 'keymap_runtime_test.dart' show native;
import 'swarm_interactions_test.dart' show chord;
@@ -43,12 +42,11 @@ void main() {
isFalse,
);
await chord(tester, LogicalKeyboardKey.keyP);
- expect(find.byType(OrchestratorLauncher), findsOneWidget);
- expect(jumpField, findsNothing);
+ expect(jumpField, findsOneWidget);
expect(app.swarms, [original]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pumpAndSettle();
- expect(find.byType(OrchestratorLauncher), findsNothing);
+ expect(jumpField, findsNothing);
if (nativeTabs) {
await native(tester, 'jump');
expect(jumpField, findsNothing);
@@ -59,19 +57,16 @@ void main() {
await tester.tap(find.byKey(const ValueKey('swarm-new-tab-button')));
await tester.pump();
}
- final opened = app.activeSwarm;
- expect(opened, isNot(same(original)));
- expect(opened.name, 'New Tab');
- expect(opened.panes, isEmpty);
+ expect(app.activeSwarm, same(original));
expect(find.byType(AlertDialog), findsNothing);
- await chord(tester, LogicalKeyboardKey.keyO);
final field = find.byKey(const ValueKey('swarm-search-input'));
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
await tester.enterText(field, 'Agent 0');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- expect(app.activeSwarm, same(opened));
+ final opened = app.activeSwarm;
+ expect(opened, isNot(same(original)));
expect(opened.panes, [pane]);
expect(original.panes, [pane]);
expect(app.focusedPane, same(pane));
@@ -85,7 +80,7 @@ void main() {
);
}
- testWidgets('command search stays commands-only and can open New Harness', (
+ testWidgets('command prefix switches lists and can open New Harness', (
tester,
) async {
final app = createApp();
@@ -94,7 +89,7 @@ void main() {
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
final field = find.byKey(const ValueKey('swarm-search-input'));
- for (final query in ['', 'Agent 0', '> ', 'new']) {
+ for (final query in ['> ', '> Agent 0', '>', '> new']) {
await tester.enterText(field, query);
await tester.pump();
final search = tester
@@ -109,13 +104,32 @@ void main() {
);
expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);
}
+ await tester.enterText(field, '');
+ await tester.pump();
+ final agents = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(agents.isCommandMode, isFalse);
+ expect(
+ agents.rows
+ .where((row) => !row.isCreate)
+ .every((row) => row.agentId != null),
+ isTrue,
+ );
expect(harnessCommandById['agent.new']!.label, 'New Harness');
+ await tester.enterText(field, '> new');
+ await tester.pump();
await tester.tap(find.byKey(const ValueKey('command:swarm.new')));
await tester.pump();
- expect(app.activeSwarm.name, 'New Tab');
- expect(app.panes, isEmpty);
+ expect(app.panes, [pane]);
+ expect(app.swarms, hasLength(1));
expect(app.allPanes, contains(pane));
- expect(find.byKey(const ValueKey('harness-start-search')), findsOneWidget);
+ expect(jumpField, findsOneWidget);
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(search.isCommandMode, isFalse);
+ expect(search.selected!.isCreate, isTrue);
expect(frames, isEmpty);
await tester.pumpWidget(const SizedBox());
app.dispose();
diff --git a/desktop/test/terminal_catalog_test.dart b/desktop/test/terminal_catalog_test.dart
new file mode 100644
index 000000000..c9866a341
--- /dev/null
+++ b/desktop/test/terminal_catalog_test.dart
@@ -0,0 +1,213 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/swarm_navigation.dart';
+import 'package:harness/widgets/search_result_text.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'support/mixed_agents.dart';
+import 'swarm_screen_test.dart' show mount, terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ testWidgets(
+ 'narrow search rows retain identity and selection through preview resizing',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(input, 'login');
+ await tester.pump();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ // Existing matches grow upward from the pinned New Harness action.
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(search.selected!.isCreate, isFalse);
+ final selected = search.selected!.id;
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pump();
+ await tester.pump();
+ for (final preview in [false, true, false]) {
+ if (search.previewVisible != preview) {
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ // The new viewport schedules the selected row's scroll position
+ // after layout; render that position before inspecting the row.
+ await tester.pump();
+ }
+ final row = find.byKey(ValueKey(selected));
+ expect(
+ row,
+ findsOneWidget,
+ reason: 'Selected row must remain visible with preview=$preview',
+ );
+ final texts = find.descendant(
+ of: row,
+ matching: find.byType(SearchResultText),
+ );
+ final title = tester.getRect(texts.first);
+ final detail = tester.getRect(texts.last);
+ final bounds = tester.getRect(row);
+ expect(detail.top, greaterThanOrEqualTo(title.bottom - .01));
+ final titleParagraph = tester.renderObject<RenderParagraph>(
+ find.descendant(of: texts.first, matching: find.byType(RichText)),
+ );
+ expect(titleParagraph.didExceedMaxLines, isFalse);
+ expect(title.left, greaterThanOrEqualTo(bounds.left));
+ expect(title.right, lessThanOrEqualTo(bounds.right));
+ expect(detail.bottom, lessThanOrEqualTo(bounds.bottom));
+ final viewport = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ );
+ expect(bounds.top, greaterThanOrEqualTo(viewport.top - .01));
+ expect(bounds.bottom, lessThanOrEqualTo(viewport.bottom + .01));
+ expect(search.selected!.id, selected);
+ expect(tester.widget<TextField>(input).controller!.text, 'login');
+ expect(
+ tester.widget<TextField>(input).focusNode!.hasPrimaryFocus,
+ isTrue,
+ );
+ expect(tester.takeException(), isNull);
+ }
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'find, close, reopen and navigate tabs and panes entirely by keyboard',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ final codexInput = <TerminalBinaryFrame>[];
+ final claudeInput = <TerminalBinaryFrame>[];
+ final codex = terminal('a0', codexInput);
+ final claude = terminal('a1', claudeInput);
+ final firstPane = app.adoptSessionForTest(codex);
+ final secondPane = app.adoptSessionForTest(claude);
+ final source = app.activeSwarm;
+ app.renameSwarm(source.id, 'Review');
+ app.focusPane(firstPane.id);
+ await mount(tester, app);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+
+ Future<void> command(String query) async {
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ await tester.enterText(input, '> $query');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump(const Duration(milliseconds: 10));
+ }
+
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.enterText(input, 'login claude M2');
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.enter);
+ final sharedTab = app.activeSwarm;
+ expect(sharedTab, isNot(same(source)));
+ expect(sharedTab.name, 'Fix login redirect');
+ expect(sharedTab.panes.single.session, same(claude));
+ expect(source.panes, [firstPane, secondPane]);
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ expect(app.activeSwarm, same(source));
+ expect(secondPane.session, same(claude));
+ await command('reopen tab');
+ expect(app.activeSwarm.id, sharedTab.id);
+ expect(app.focusedPane!.session, same(claude));
+ await command('next tab');
+ expect(app.activeSwarm, same(source));
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ expect(app.focusedPane, same(secondPane));
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(app.zoomedPaneId, secondPane.id);
+ await key(tester, LogicalKeyboardKey.keyH, cmd: true);
+ expect(app.focusedPane, same(firstPane));
+ expect(app.zoomedPaneId, firstPane.id);
+ await key(tester, LogicalKeyboardKey.enter, cmd: true);
+ expect(app.zoomedPaneId, isNull);
+ await key(tester, LogicalKeyboardKey.keyL, cmd: true);
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true, shift: true);
+ expect(source.panes, [firstPane]);
+ expect(
+ app.swarms
+ .singleWhere((tab) => tab.id == sharedTab.id)
+ .panes
+ .single
+ .session,
+ same(claude),
+ );
+ await command('reopen pane');
+ expect(app.activeSwarm, same(source));
+ expect(source.panes, [firstPane, secondPane]);
+ expect(app.focusedPane!.session, same(claude));
+ expect(codexInput, isEmpty);
+ expect(claudeInput, isEmpty);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(claudeInput.single.bytes, [27, 91, 68]);
+ expect(codexInput, isEmpty);
+ // Reopening a pane changes its terminal size. Let the 50 ms resize
+ // debounce complete before the widget-test timer invariant runs.
+ await tester.pump(const Duration(milliseconds: 60));
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'same-task results identify their agent without opening a preview',
+ (tester) async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ app.adoptSessionForTest(terminal('a0', []));
+ await mount(tester, app);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await key(tester, LogicalKeyboardKey.slash, ctrl: true);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ await tester.enterText(input, 'login');
+ await tester.pump();
+ for (final (id, engine) in [('a0', 'Codex'), ('a1', 'Claude')]) {
+ final row = find.byKey(ValueKey(agentDestinationId('m', id)));
+ final visibleText = tester
+ .widgetList<SearchResultText>(
+ find.descendant(of: row, matching: find.byType(SearchResultText)),
+ )
+ .map((widget) => widget.text)
+ .join(' ');
+ expect(visibleText, contains(engine));
+ expect(visibleText, contains('M2'));
+ }
+ expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test(
+ 'a discovered agent display name is searchable alongside its domain',
+ () {
+ final app = createApp();
+ addTearDown(app.dispose);
+ seedMixedAgents(app);
+ final rows = SwarmSearchCatalog().read(app, []);
+ for (final query in ['Robot Studio', 'Robotics', 'studio/arm']) {
+ expect(
+ rankSwarmDestinations(
+ rows,
+ query,
+ ).where((row) => row.agentId == 'a3'),
+ hasLength(1),
+ reason: query,
+ );
+ }
+ },
+ );
+}
diff --git a/desktop/test/terminal_clipboard_test.dart b/desktop/test/terminal_clipboard_test.dart
new file mode 100644
index 000000000..c0ed7ed1a
--- /dev/null
+++ b/desktop/test/terminal_clipboard_test.dart
@@ -0,0 +1,489 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/shortcuts/app_shortcuts.dart' show kTerminalOwnedKeys;
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_panel.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show key;
+import 'swarm_state_test.dart' show createApp;
+
+TerminalSession liveSession(
+ String id,
+ List<TerminalBinaryFrame> frames, {
+ String engine = 'terminal',
+ List<String>? controls,
+}) =>
+ TerminalSession(
+ machineId: 'm',
+ agentId: id,
+ agentName: id,
+ engineId: engine,
+ send: (type, _) async {
+ controls?.add(type);
+ return true;
+ },
+ sendBinary: (frame) async {
+ frames.add(frame);
+ return true;
+ },
+ )
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-$id';
+
+String input(List<TerminalBinaryFrame> frames) => utf8.decode([
+ for (final frame in frames)
+ if (frame.kind == TerminalBinaryKind.input) ...frame.bytes,
+]);
+
+Future<void> mount(
+ WidgetTester tester,
+ AppNotifier app,
+ TerminalSession session, {
+ bool readOnly = false,
+}) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: true,
+ readOnly: readOnly,
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+void onPlatform(
+ TargetPlatform platform,
+ String description,
+ Future<void> Function(WidgetTester) body,
+) {
+ testWidgets(description, body, variant: TargetPlatformVariant.only(platform));
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ String? clipboard;
+ Future<Object?> Function()? readClipboard;
+ var reads = 0;
+ const imageChannel = MethodChannel('harness/clipboard_image');
+ setUp(() {
+ clipboard = 'clipboard text';
+ reads = 0;
+ readClipboard = null;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ switch (call.method) {
+ case 'Clipboard.getData':
+ reads++;
+ return readClipboard == null
+ ? (clipboard == null ? null : {'text': clipboard})
+ : readClipboard!();
+ case 'Clipboard.setData':
+ clipboard = (call.arguments as Map)['text'] as String?;
+ }
+ return null;
+ });
+ });
+ tearDown(() {
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(imageChannel, null);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, null);
+ });
+
+ for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {
+ onPlatform(
+ platform,
+ '$platform preserves shell control keys and pastes only on the clipboard chord',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalPasteRawAvailable = true;
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ await mount(tester, app, session);
+ for (final letter in [
+ LogicalKeyboardKey.keyA,
+ LogicalKeyboardKey.keyB,
+ LogicalKeyboardKey.keyC,
+ LogicalKeyboardKey.keyD,
+ LogicalKeyboardKey.keyR,
+ LogicalKeyboardKey.keyV,
+ LogicalKeyboardKey.keyZ,
+ ]) {
+ await key(tester, letter, ctrl: true);
+ }
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input(frames).codeUnits, [1, 2, 3, 4, 18, 22, 26]);
+ expect(
+ reads,
+ 0,
+ reason: 'Readline, Vim, and tmux keep their control chords',
+ );
+ frames.clear();
+ clipboard = 'first line\nsecond line\tλ';
+ await key(
+ tester,
+ LogicalKeyboardKey.keyV,
+ cmd: platform == TargetPlatform.macOS,
+ ctrl: platform == TargetPlatform.linux,
+ shift: platform == TargetPlatform.linux,
+ );
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(reads, 1);
+ expect(
+ frames.where((f) => f.kind == TerminalBinaryKind.paste),
+ hasLength(1),
+ );
+ expect(utf8.decode(frames.single.bytes), clipboard);
+ expect(frames.single.streamId, session.streamId);
+ expect(input(frames), isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ }
+
+ onPlatform(
+ TargetPlatform.macOS,
+ 'a delayed clipboard read cannot paste into a replacement agent',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalPasteRawAvailable = true;
+ final originalFrames = <TerminalBinaryFrame>[];
+ final nextFrames = <TerminalBinaryFrame>[];
+ final original = liveSession('a0', originalFrames);
+ final next = liveSession('a1', nextFrames);
+ final read = Completer<Object?>();
+ readClipboard = () => read.future;
+ await mount(tester, app, original);
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ expect(reads, 1);
+ await mount(tester, app, next);
+ read.complete({'text': 'original agent only'});
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(originalFrames, isEmpty);
+ expect(nextFrames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ original.dispose();
+ next.dispose();
+ app.dispose();
+ },
+ );
+
+ onPlatform(
+ TargetPlatform.macOS,
+ 'empty clipboard does not send quoted-insert into a shell',
+ (tester) async {
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ clipboard = '';
+ await mount(tester, app, session);
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(reads, 1);
+ expect(frames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ for (final change in ['read only', 'reconnected', 'closed pane']) {
+ onPlatform(
+ TargetPlatform.macOS,
+ 'pending paste is cancelled after $change',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalPasteRawAvailable = true;
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ final read = Completer<Object?>();
+ readClipboard = () => read.future;
+ await mount(tester, app, session);
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ if (change == 'read only') {
+ await mount(tester, app, session, readOnly: true);
+ } else if (change == 'reconnected') {
+ session.streamId = 'replacement-stream';
+ } else {
+ await tester.pumpWidget(const SizedBox());
+ }
+ read.complete({'text': 'old request'});
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(frames, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ }
+
+ for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {
+ onPlatform(
+ platform,
+ '$platform copies selected output even in a read-only pane',
+ (tester) async {
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: session.streamId!,
+ seq: 0,
+ compressed: false,
+ cols: 80,
+ rows: 24,
+ bytes: utf8.encode('hello world'),
+ ),
+ );
+ await mount(tester, app, session, readOnly: true);
+ final controller = tester
+ .widget<TerminalView>(find.byType(TerminalView))
+ .controller!;
+ controller.setSelection(
+ session.terminal.buffer.createAnchor(0, 0),
+ session.terminal.buffer.createAnchor(5, 0),
+ );
+ final apple = platform == TargetPlatform.macOS;
+ await key(
+ tester,
+ LogicalKeyboardKey.keyC,
+ cmd: apple,
+ ctrl: !apple,
+ shift: !apple,
+ );
+ expect(clipboard, 'hello');
+ await key(
+ tester,
+ LogicalKeyboardKey.keyV,
+ cmd: apple,
+ ctrl: !apple,
+ shift: !apple,
+ );
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(reads, 0, reason: 'A read-only pane cannot initiate paste');
+ expect(frames, isEmpty);
+ expect(
+ kTerminalOwnedKeys.firstWhere((item) => item.label == 'Paste').chord,
+ apple ? ['⌘', 'V'] : ['⌃', '⇧', 'V'],
+ );
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ }
+
+ onPlatform(
+ TargetPlatform.macOS,
+ 'older daemons retain bracketed paste and clear the old selection',
+ (tester) async {
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ await session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: session.streamId!,
+ seq: 0,
+ compressed: false,
+ cols: 80,
+ rows: 24,
+ bytes: utf8.encode('hello world\x1b[?2004h'),
+ ),
+ );
+ await mount(tester, app, session);
+ final controller = tester
+ .widget<TerminalView>(find.byType(TerminalView))
+ .controller!;
+ controller.setSelection(
+ session.terminal.buffer.createAnchor(0, 0),
+ session.terminal.buffer.createAnchor(5, 0),
+ );
+ clipboard = 'α = 2';
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input(frames), '\x1b[200~α = 2\x1b[201~');
+ expect(controller.selection, isNull);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+
+ onPlatform(
+ TargetPlatform.macOS,
+ 'clipboard failure stays local and allows another paste',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalPasteRawAvailable = true;
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ readClipboard = () async =>
+ throw PlatformException(code: 'fixture-read-failed');
+ await mount(tester, app, session);
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump();
+ expect(
+ find.text('Could not read the clipboard. Try Paste again.'),
+ findsOneWidget,
+ );
+ expect(frames, isEmpty);
+ expect(session.acceptsInput, isTrue);
+ readClipboard = null;
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(utf8.decode(frames.single.bytes), clipboard);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ onPlatform(
+ TargetPlatform.linux,
+ 'Linux Alt chords preserve case and punctuation while AltGr composes',
+ (tester) async {
+ final app = createApp();
+ final frames = <TerminalBinaryFrame>[];
+ final session = liveSession('a0', frames);
+ await mount(tester, app, session);
+ for (final stroke in [
+ (LogicalKeyboardKey.keyB, 'b', false),
+ (LogicalKeyboardKey.keyF, 'f', false),
+ (LogicalKeyboardKey.keyB, 'B', true),
+ (LogicalKeyboardKey.period, '.', false),
+ (LogicalKeyboardKey.digit2, '2', false),
+ ]) {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft);
+ if (stroke.$3) {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ }
+ await tester.sendKeyEvent(stroke.$1, character: stroke.$2);
+ if (stroke.$3) {
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ }
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft);
+ }
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input(frames), '\x1bb\x1bf\x1bB\x1b.\x1b2');
+ frames.clear();
+ // Events without a printable character use the session's input handler.
+ session.terminal.keyInput(TerminalKey.keyF, alt: true);
+ session.terminal.keyInput(TerminalKey.keyF, alt: true, shift: true);
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input(frames), '\x1bf\x1bF');
+ frames.clear();
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.altRight);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyQ, character: '@');
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.altRight);
+ tester.testTextInput.enterText('@');
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(input(frames), '@');
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+ onPlatform(
+ TargetPlatform.macOS,
+ 'delayed image reads cannot upload into a replacement agent',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalImagePasteAvailable = true;
+ final oldFrames = <TerminalBinaryFrame>[];
+ final nextFrames = <TerminalBinaryFrame>[];
+ final controls = <String>[];
+ final original = liveSession(
+ 'a0',
+ oldFrames,
+ engine: 'claude',
+ controls: controls,
+ );
+ final next = liveSession(
+ 'a1',
+ nextFrames,
+ engine: 'claude',
+ controls: controls,
+ );
+ final imageRead = Completer<Uint8List?>();
+ var imageReads = 0;
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(imageChannel, (call) async {
+ imageReads++;
+ return imageRead.future;
+ });
+ clipboard = null;
+ await mount(tester, app, original);
+ await key(tester, LogicalKeyboardKey.keyV, cmd: true);
+ expect(imageReads, 1);
+ await mount(tester, app, next);
+ imageRead.complete(Uint8List.fromList([137, 80, 78, 71]));
+ await tester.pump(const Duration(milliseconds: 20));
+ expect(
+ controls.where((type) => type == 'terminal_chunked_upload_begin'),
+ isEmpty,
+ );
+ expect(oldFrames, isEmpty);
+ expect(nextFrames, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ original.dispose();
+ next.dispose();
+ app.dispose();
+ },
+ );
+
+ onPlatform(
+ TargetPlatform.linux,
+ 'Linux clipboard chord preserves remote image upload',
+ (tester) async {
+ final app = createApp();
+ app.stateOf('m')!.terminalImagePasteAvailable = true;
+ final frames = <TerminalBinaryFrame>[];
+ final controls = <String>[];
+ final session = liveSession(
+ 'a0',
+ frames,
+ engine: 'claude',
+ controls: controls,
+ );
+ final png = Uint8List.fromList([137, 80, 78, 71]);
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(imageChannel, (_) async => png);
+ clipboard = null;
+ await mount(tester, app, session);
+ await key(tester, LogicalKeyboardKey.keyV, ctrl: true, shift: true);
+ expect(controls, contains('terminal_chunked_upload_begin'));
+ await session.handleFrame('terminal_chunked_upload_begin_result', {
+ 'streamId': session.streamId,
+ 'accepted': true,
+ });
+ await tester.pump();
+ expect(frames, hasLength(1));
+ expect(frames.single.kind, TerminalBinaryKind.imagePaste);
+ expect(frames.single.bytes, png);
+ await session.handleFrame('terminal_paste_image_result', {
+ 'streamId': session.streamId,
+ 'outcome': 'clipboard',
+ });
+ await tester.pump();
+ expect(session.uploadProgress, isNull);
+ await tester.pumpWidget(const SizedBox());
+ session.dispose();
+ app.dispose();
+ },
+ );
+}
diff --git a/desktop/test/terminal_find_test.dart b/desktop/test/terminal_find_test.dart
index 4ceb12927..0d13e4cc1 100644
--- a/desktop/test/terminal_find_test.dart
+++ b/desktop/test/terminal_find_test.dart
@@ -12,6 +12,7 @@ import 'package:xterm/xterm.dart';
import 'swarm_interactions_test.dart' show chord;
import 'keymap_runtime_test.dart' show native;
+import 'keymap_host_test.dart' show key;
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_state_test.dart' show createApp;
@@ -59,6 +60,94 @@ Future<void> output(
);
void main() {
+ testWidgets('Find edits Unicode with readline keys without sending input', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ await output(session, 0, 'run 🐙\r\nrun report\r\n', keyframe: true);
+ app.adoptSessionForTest(session);
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await chord(tester, LogicalKeyboardKey.keyF);
+ await tester.enterText(findField, 'run 🐙');
+ await finishFind(tester);
+ final controller = tester.widget<TextField>(findField).controller!;
+ final search = tester
+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))
+ .search!;
+ expect(search.count, 1);
+ await key(tester, LogicalKeyboardKey.keyH, ctrl: true);
+ await finishFind(tester);
+ expect(controller.text, 'run ');
+ expect(search.count, 2);
+ await key(tester, LogicalKeyboardKey.keyU, ctrl: true);
+ await finishFind(tester);
+ expect(controller.text, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyY, ctrl: true);
+ await finishFind(tester);
+ expect(controller.text, 'run ');
+ expect(search.count, 2);
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(input.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('compact Find options own keys and return to the query', (
+ tester,
+ ) async {
+ final app = createApp();
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input);
+ await output(session, 0, 'Marker\r\nmarker\r\n', keyframe: true);
+ app.adoptSessionForTest(session);
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ tester.view.physicalSize = const Size(600, 800);
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ await tester.pump();
+ await chord(tester, LogicalKeyboardKey.keyF);
+ await tester.enterText(findField, 'marker');
+ await finishFind(tester);
+ final search = tester
+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))
+ .search!;
+ expect(search.count, 2);
+ // Tab reaches the compact actions. Enter opens them and chooses their
+ // first item, rather than stepping a match or sending input underneath.
+ await key(tester, LogicalKeyboardKey.tab);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(find.text('Match case'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await finishFind(tester);
+ expect(search.caseSensitive, isTrue);
+ expect(search.count, 1);
+ expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);
+ await tester.tap(find.byTooltip('Find options'));
+ await tester.pump();
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(find.text('Match case'), findsNothing);
+ expect(findField, findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(findField, findsNothing);
+ expect(input, isEmpty);
+ expect(tester.takeException(), isNull);
+ await chord(tester, LogicalKeyboardKey.keyF);
+ await tester.tap(find.byTooltip('Find options'));
+ await tester.pump();
+ expect(find.text('Match case'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump();
+ expect(find.text('Match case'), findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
for (final nativeEntry in [false, true]) {
testWidgets(
'opening Find owns input before its first frame (native=$nativeEntry)',
@@ -489,7 +578,9 @@ void main() {
),
findsOneWidget,
);
- await tester.tap(find.byTooltip('Match case'));
+ await tester.tap(find.byTooltip('Find options'));
+ await tester.pump();
+ await tester.tap(find.text('Match case'));
await tester.pump();
expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dart
index 3ad1f7421..d9ce2da45 100644
--- a/desktop/test/terminal_panel_presentation_test.dart
+++ b/desktop/test/terminal_panel_presentation_test.dart
@@ -1,8 +1,11 @@
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
+import 'package:flutter/services.dart';
+import 'package:harness/widgets/transient_menus.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/terminal/terminal_font_store.dart';
import 'package:harness/widgets/terminal_panel.dart';
import 'package:harness/widgets/pane_header_actions.dart';
import 'package:xterm/xterm.dart';
@@ -54,8 +57,8 @@ void main() {
await tester.pump(const Duration(milliseconds: 120));
await tester.tap(find.byTooltip('Show message composer'));
await tester.tap(find.byTooltip('Zoom Pane'));
- await tester.tap(find.byTooltip('Restart Harness'));
- await tester.tap(find.byTooltip('Stop Harness'));
+ await tester.tap(find.byTooltip('Restart Agent'));
+ await tester.tap(find.byTooltip('Stop Agent'));
await tester.tap(find.byTooltip('Close Pane'));
await tester.pump();
expect(closed, [1]);
@@ -93,6 +96,14 @@ void main() {
),
findsOneWidget,
);
+ final previousFont = terminalFontStore.value;
+ addTearDown(() => terminalFontStore.value = previousFont);
+ terminalFontStore.value = const TerminalStyle(fontFamily: 'Monaco');
+ await tester.pump();
+ expect(
+ tester.widget<Text>(find.text('Renamed terminal')).style!.fontFamily,
+ 'Monaco',
+ );
await mouse.removePointer();
await tester.pumpWidget(const SizedBox());
revision.dispose();
@@ -150,18 +161,18 @@ void main() {
expect(find.text('harness'), findsOneWidget);
expect(find.text('main'), findsOneWidget);
expect(
- tester.getRect(find.text('harness')).left,
+ tester.getRect(find.text('Test host')).left,
greaterThan(titleBounds.right),
);
expect(
- tester.getRect(find.text('main')).left,
- greaterThan(tester.getRect(find.text('harness')).right),
+ tester.getRect(find.text('harness')).left,
+ greaterThan(tester.getRect(find.text('Test host')).right),
);
expect(
- tester.getRect(find.text('Test host')).left,
- greaterThan(tester.getRect(find.text('main')).right),
+ tester.getRect(find.text('main')).left,
+ greaterThan(tester.getRect(find.text('harness')).right),
);
- expect(find.byTooltip('Stop Harness').hitTestable(), findsNothing);
+ expect(find.byTooltip('Stop Agent').hitTestable(), findsNothing);
expect(
find.descendant(of: controls, matching: find.byType(IconButton)),
findsNWidgets(local ? 5 : 6),
@@ -170,7 +181,7 @@ void main() {
await mouse.addPointer(location: tester.getCenter(title));
await tester.pump(const Duration(milliseconds: 120));
expect(tester.widget<AnimatedOpacity>(details).opacity, 0);
- expect(find.byTooltip('Stop Harness').hitTestable(), findsOneWidget);
+ expect(find.byTooltip('Stop Agent').hitTestable(), findsOneWidget);
expect(find.byTooltip('Share harness').hitTestable(), findsOneWidget);
expect(tester.getRect(title), titleBounds);
expect(
@@ -180,11 +191,11 @@ void main() {
await mouse.moveTo(const Offset(300, 200));
await tester.pump(const Duration(milliseconds: 120));
expect(tester.widget<AnimatedOpacity>(details).opacity, 1);
- expect(find.byTooltip('Stop Harness').hitTestable(), findsNothing);
+ expect(find.byTooltip('Stop Agent').hitTestable(), findsNothing);
// Keyboard users can reveal and reach the same actions without a mouse.
- Focus.of(tester.element(find.byTooltip('Stop Harness'))).nextFocus();
+ Focus.of(tester.element(find.byTooltip('Stop Agent'))).nextFocus();
await tester.pump(const Duration(milliseconds: 120));
- expect(find.byTooltip('Stop Harness').hitTestable(), findsOneWidget);
+ expect(find.byTooltip('Stop Agent').hitTestable(), findsOneWidget);
await mouse.removePointer();
await tester.pumpWidget(const SizedBox());
session.dispose();
@@ -192,4 +203,122 @@ void main() {
},
);
}
+ testWidgets(
+ 'narrow headers preserve identity and keyboard actions at large text',
+ (tester) async {
+ final app = createApp();
+ final session = terminal('a0', []);
+ session.agentName = 'Review the release notes';
+ app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'a0',
+ name: 'Review the release notes',
+ engine: 'codex',
+ terminalAvailable: true,
+ viewerUrl: 'http://fixture.invalid/viewer',
+ project: AgentProject(
+ name: 'release-notes',
+ cwd: '/work/release-notes',
+ branch: 'feature/very-long-branch',
+ ),
+ ),
+ ];
+ var zooms = 0;
+ var forks = 0;
+ final revision = ValueNotifier(0);
+ tester.view.devicePixelRatio = 1;
+ tester.platformDispatcher.textScaleFactorTestValue = 1.7;
+ addTearDown(tester.view.reset);
+ addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
+ for (final width in [240.0, 280.0, 420.0]) {
+ tester.view.physicalSize = Size(width, 600);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: ValueListenableBuilder<int>(
+ valueListenable: revision,
+ builder: (_, _, _) => TerminalPanel(
+ notifier: app,
+ session: session,
+ focused: false,
+ compactHeader: true,
+ onToggleZoom: () => zooms++,
+ onFork: () => forks++,
+ onRestart: () {},
+ onClose: () {},
+ onDelete: () {},
+ onToggleComposer: () {},
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ final title = find.text(session.agentName);
+ expect(tester.getSize(title).width, greaterThan(64));
+ expect(tester.takeException(), isNull);
+ final titleBefore = tester.getRect(title);
+ final button = tester.widget<IconButton>(
+ find.widgetWithIcon(IconButton, Icons.more_horiz),
+ );
+ button.focusNode!.requestFocus();
+ await tester.pump(const Duration(milliseconds: 120));
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Zoom Pane'), findsOneWidget);
+ expect(find.text('Show viewer'), findsOneWidget);
+ expect(find.text('Fork Agent'), findsOneWidget);
+ expect(find.text('Stop Agent'), findsOneWidget);
+ expect(tester.getRect(title), titleBefore);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(zooms, [240.0, 280.0, 420.0].indexOf(width) + 1);
+ expect(find.text('Zoom Pane'), findsNothing);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ for (var i = 0; i < 5; i++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pump();
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(forks, zooms);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.text('Zoom Pane'), findsNothing);
+ expect(button.focusNode!.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ dismissTransientMenus();
+ await tester.pumpAndSettle();
+ expect(find.text('Zoom Pane'), findsNothing);
+ expect(tester.takeException(), isNull);
+ for (final status in [
+ TerminalSessionStatus.opening,
+ TerminalSessionStatus.takenOver,
+ TerminalSessionStatus.closed,
+ ]) {
+ session.status = status;
+ revision.value++;
+ await tester.pump();
+ expect(tester.getSize(title).width, greaterThan(40));
+ expect(tester.takeException(), isNull);
+ }
+ expect(find.byTooltip('Reconnect'), findsOneWidget);
+ expect(
+ tester
+ .widget<IconButton>(
+ find.widgetWithIcon(IconButton, Icons.refresh),
+ )
+ .onPressed,
+ isNotNull,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ }
+ await tester.pumpWidget(const SizedBox());
+ revision.dispose();
+ session.dispose();
+ app.dispose();
+ },
+ );
}
diff --git a/desktop/test/terminal_session_test.dart b/desktop/test/terminal_session_test.dart
index 9dee6e9e7..74836721e 100644
--- a/desktop/test/terminal_session_test.dart
+++ b/desktop/test/terminal_session_test.dart
@@ -1021,7 +1021,9 @@ void main() {
},
);
- test('resync retries three times, reopens once, then fails closed', () async {
+ testWidgets('resync retries three times, reopens once, then fails closed', (
+ tester,
+ ) async {
session.dispose();
session = TerminalSession(
machineId: 'machine-1',
@@ -1044,7 +1046,9 @@ void main() {
);
await session.handleBinary(output(2, utf8.encode('gap')));
- await Future<void>.delayed(const Duration(milliseconds: 45));
+ // Advance the retry clock deterministically; an overloaded test runner
+ // can wake a 45 ms wall-clock wait before the last 5 ms retry is armed.
+ await tester.pump(const Duration(milliseconds: 45));
expect(
sent.where((frame) => frame.type == 'terminal_resync'),
diff --git a/desktop/test/terminal_tail_lifecycle_test.dart b/desktop/test/terminal_tail_lifecycle_test.dart
index 9629bd117..3989701cc 100644
--- a/desktop/test/terminal_tail_lifecycle_test.dart
+++ b/desktop/test/terminal_tail_lifecycle_test.dart
@@ -157,7 +157,7 @@ void main() {
PanePreset.columns,
PanePreset.rows,
]) {
- await chord(tester, LogicalKeyboardKey.keyS);
+ await chord(tester, LogicalKeyboardKey.keyL, shift: true);
await tester.pump(const Duration(milliseconds: 200));
await tester.tap(find.text(preset.label));
await tester.pump();
@@ -257,7 +257,6 @@ void main() {
view.widget.scrollController!.jumpTo(100);
await tester.pump();
await chord(tester, LogicalKeyboardKey.keyT);
- await chord(tester, LogicalKeyboardKey.keyO);
await tester.enterText(
find.byKey(const ValueKey('swarm-search-input')),
'Agent 0',
diff --git a/desktop/test/usage_jsonl_benchmark_test.dart b/desktop/test/usage_jsonl_benchmark_test.dart
new file mode 100644
index 000000000..b748cac63
--- /dev/null
+++ b/desktop/test/usage_jsonl_benchmark_test.dart
@@ -0,0 +1,88 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/usage_overview.dart';
+
+import 'usage_jsonl_scanners_test.dart'
+ show jsonlRoot, jsonlRow, jsonlScanner, sourcesOf;
+
+Future<({int elapsed, int gap})> observeLoop(
+ Future<void> Function() operation,
+) async {
+ final watch = Stopwatch()..start();
+ var previous = 0;
+ var maximum = 0;
+ final timer = Timer.periodic(const Duration(milliseconds: 1), (_) {
+ final now = watch.elapsedMicroseconds;
+ final gap = now - previous;
+ if (gap > maximum) maximum = gap;
+ previous = now;
+ });
+ try {
+ await operation();
+ final elapsed = watch.elapsedMicroseconds;
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ return (elapsed: elapsed, gap: maximum);
+ } finally {
+ timer.cancel();
+ }
+}
+
+void main() {
+ for (final provider in [LedgerProvider.claude, LedgerProvider.codex]) {
+ test('${provider.label} cold, cached, and aggregation event-loop timing', () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-jsonl-timing-',
+ );
+ addTearDown(() => fixture.delete(recursive: true));
+ final file = File('${jsonlRoot(provider, fixture.path)}/fixture.jsonl');
+ await file.parent.create(recursive: true);
+ final content = StringBuffer();
+ // A large tool result plus 20,000 distinct usage events, entirely synthetic.
+ content.writeln(
+ jsonEncode({
+ 'type': 'tool_result',
+ 'text': 'assistant ${'x' * (2 * 1024 * 1024)}',
+ }),
+ );
+ for (var i = 1; i <= 20000; i++) {
+ content.writeln(jsonlRow(provider, i));
+ }
+ await file.writeAsString(content.toString());
+ final scanner = jsonlScanner(provider, fixture.path);
+ var result = const LedgerScanResult();
+ for (final mode in ['cold', 'cached', 'aggregate']) {
+ final samples = <({int elapsed, int gap})>[];
+ for (var i = 0; i < 6; i++) {
+ final reading = await observeLoop(() async {
+ if (mode == 'aggregate') {
+ expect(
+ buildProviderLedger(provider, result.sources).entries,
+ hasLength(20000),
+ );
+ } else {
+ result = await scanner.scan(
+ mode == 'cached' ? sourcesOf(result) : {},
+ );
+ expect(result.sources.single.entries, hasLength(20000));
+ }
+ });
+ if (i > 0) samples.add(reading);
+ }
+ final elapsed = samples.map((sample) => sample.elapsed).toList()
+ ..sort();
+ final gaps = samples.map((sample) => sample.gap).toList()..sort();
+ // Report only; shared-machine scheduling is not a CI timing gate.
+ // ignore: avoid_print
+ print(
+ '${provider.label} / 20000 turns / $mode / debug: median ${elapsed[2]} us; '
+ 'median maximum caller event-loop gap ${gaps[2]} us',
+ );
+ }
+ }, skip: Platform.environment['HARNESS_USAGE_BENCHMARK'] != '1');
+ }
+}
diff --git a/desktop/test/usage_jsonl_scanners_test.dart b/desktop/test/usage_jsonl_scanners_test.dart
new file mode 100644
index 000000000..2191c609b
--- /dev/null
+++ b/desktop/test/usage_jsonl_scanners_test.dart
@@ -0,0 +1,255 @@
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/ledger/claude_ledger_scanner.dart';
+import 'package:harness/usage/ledger/codex_ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/jsonl_ledger_scan.dart';
+import 'package:harness/usage/ledger/usage_overview.dart';
+
+import 'usage_ledger_test.dart' show claudeRow, codexTokenCount;
+
+LedgerScanner jsonlScanner(LedgerProvider provider, String home) =>
+ provider == LedgerProvider.claude
+ ? ClaudeLedgerScanner(home: home, environment: const {})
+ : CodexLedgerScanner(home: home, environment: const {});
+
+String jsonlRow(LedgerProvider provider, int tokens) =>
+ provider == LedgerProvider.claude
+ ? claudeRow(
+ messageId: 'turn-$tokens',
+ input: tokens,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ cacheWrite1h: 0,
+ )
+ : codexTokenCount(totalInput: tokens, totalCached: 0, totalOutput: 0);
+
+String jsonlRoot(LedgerProvider provider, String home, {bool legacy = false}) =>
+ provider == LedgerProvider.claude
+ ? '$home/.claude/${legacy ? 'transcripts' : 'projects'}'
+ : '$home/.codex/${legacy ? 'archived_sessions' : 'sessions'}';
+
+Map<String, ScannedSource> sourcesOf(LedgerScanResult result) => {
+ for (final source in result.sources) source.path: source,
+};
+
+int tokensIn(LedgerProvider provider, LedgerScanResult result) =>
+ buildProviderLedger(provider, result.sources).totals.freshInput;
+
+Future<bool> denyRead(String path) async {
+ final result = await Process.run('chmod', ['000', path]);
+ if (result.exitCode != 0) {
+ throw StateError('Could not prepare denied-read fixture');
+ }
+ try {
+ await File(path).readAsBytes();
+ markTestSkipped('This host can read files with no read permissions.');
+ return false;
+ } on FileSystemException {
+ return true;
+ }
+}
+
+void main() {
+ test(
+ 'Unicode records survive every snapshot boundary and CRLF endings',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-jsonl-boundary-',
+ );
+ addTearDown(() => fixture.delete(recursive: true));
+ const first = '{"text":"héλ中文🙂"}';
+ const second = '{"text":"€"}';
+ final firstBytes = utf8.encode(first);
+ final bytes = utf8.encode('$first\r\n$second');
+ final file = await File('${fixture.path}/fixture.jsonl')
+ .writeAsBytes(bytes);
+ for (var end = 0; end <= bytes.length; end++) {
+ final records = <Object?>[];
+ await for (final line in readJsonlLines(file, end)) {
+ try {
+ records.add(jsonDecode(line));
+ } on FormatException {
+ // An incomplete JSON record is ignored until the next scan.
+ }
+ }
+ expect(records, [
+ if (end >= firstBytes.length) {'text': 'héλ中文🙂'},
+ if (end == bytes.length) {'text': '€'},
+ ], reason: 'snapshot ends at byte $end');
+ }
+ },
+ );
+
+ test(
+ 'malformed Unicode is not mistaken for an unfinished trailing character',
+ () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-jsonl-invalid-',
+ );
+ addTearDown(() => fixture.delete(recursive: true));
+ final file = File('${fixture.path}/fixture.jsonl');
+ for (final bytes in [
+ [0xff],
+ [0x80],
+ [0xc0],
+ [0xe0, 0x80],
+ [0xed, 0xa0],
+ [0xf0, 0x80],
+ [0xf4, 0x90],
+ [0xff, 0xe2],
+ [0xe2, 10],
+ ]) {
+ await file.writeAsBytes(bytes);
+ await expectLater(
+ readJsonlLines(file, bytes.length).toList(),
+ throwsFormatException,
+ );
+ }
+ },
+ );
+
+ for (final provider in [LedgerProvider.claude, LedgerProvider.codex]) {
+ group(provider.label, () {
+ late Directory fixture;
+ late LedgerScanner scanner;
+ late Directory root;
+ setUp(() async {
+ fixture = await Directory.systemTemp.createTemp('harness-jsonl-scan-');
+ scanner = jsonlScanner(provider, fixture.path);
+ root = Directory(jsonlRoot(provider, fixture.path));
+ });
+ tearDown(() => fixture.delete(recursive: true));
+
+ Future<File> write(String name, int tokens, {bool legacy = false}) async {
+ final file = File(
+ '${jsonlRoot(provider, fixture.path, legacy: legacy)}/$name.jsonl',
+ );
+ await file.parent.create(recursive: true);
+ await file.writeAsString('${jsonlRow(provider, tokens)}\n');
+ return file;
+ }
+
+ test(
+ 'missing logs and readable logs without usage are distinct',
+ () async {
+ expect((await scanner.scan({})).status, LedgerStatus.unavailable);
+ await root.create(recursive: true);
+ await File('${root.path}/empty.jsonl')
+ .writeAsString('{"type":"user"}\n');
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.ok);
+ expect(result.sources.single.entries, isEmpty);
+ },
+ );
+
+ test('current and legacy roots both contribute', () async {
+ await write('current', 100);
+ await write('older', 200, legacy: true);
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.ok);
+ expect(tokensIn(provider, result), 300);
+ });
+
+ test(
+ 'a denied read is not cached as zero and recovers without a file edit',
+ () async {
+ final file = await write('denied', 100);
+ late LedgerScanResult denied;
+ try {
+ if (!await denyRead(file.path)) return;
+ denied = await scanner.scan({});
+ } finally {
+ await Process.run('chmod', ['600', file.path]);
+ }
+ final recovered = await scanner.scan(sourcesOf(denied));
+ expect(tokensIn(provider, recovered), 100);
+ expect(denied.status, LedgerStatus.failed);
+ expect(denied.message, isNotEmpty);
+ },
+ skip: Platform.isWindows,
+ );
+
+ test('an unreadable file is disclosed beside readable usage', () async {
+ await write('good', 100);
+ final file = await write('denied', 200);
+ try {
+ if (!await denyRead(file.path)) return;
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.partial);
+ expect(tokensIn(provider, result), 100);
+ expect(result.message, isNotEmpty);
+ } finally {
+ await Process.run('chmod', ['600', file.path]);
+ }
+ }, skip: Platform.isWindows);
+
+ test(
+ 'an unreadable root is a failure rather than a missing installation',
+ () async {
+ await root.parent.create(recursive: true);
+ await File(root.path)
+ .writeAsString('a configured root is not a directory');
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.failed);
+ expect(result.message, isNotEmpty);
+ },
+ );
+
+ test('a corrupt UTF-8 file does not hide a readable sibling', () async {
+ await write('good', 100);
+ await File('${root.path}/bad.jsonl').writeAsBytes([0xff, 10]);
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.partial);
+ expect(tokensIn(provider, result), 100);
+ expect(result.message, isNotEmpty);
+ });
+
+ test('an incomplete Unicode tail preserves earlier turns and completes on refresh', () async {
+ final file = await write('live', 100);
+ final row = jsonDecode(jsonlRow(provider, 200)) as Map<String, dynamic>;
+ row['fixtureText'] = '€';
+ final bytes = utf8.encode(jsonEncode(row));
+ final split = bytes.indexOf(0xe2) + 1;
+ await file.writeAsBytes(bytes.sublist(0, split), mode: FileMode.append);
+ final pending = await scanner.scan({});
+ expect(pending.status, LedgerStatus.ok);
+ expect(tokensIn(provider, pending), 100);
+ await file.writeAsBytes([
+ ...bytes.sublist(split),
+ 10,
+ ], mode: FileMode.append);
+ final complete = await scanner.scan(sourcesOf(pending));
+ expect(complete.status, LedgerStatus.ok);
+ expect(
+ tokensIn(provider, complete),
+ provider == LedgerProvider.claude ? 300 : 200,
+ );
+ });
+
+ test('appended and removed files update an existing snapshot', () async {
+ final file = await write('live', 100);
+ final first = await scanner.scan({});
+ final unchanged = await scanner.scan(sourcesOf(first));
+ expect(tokensIn(provider, unchanged), 100);
+ await file.writeAsString(
+ jsonlRow(provider, 200),
+ mode: FileMode.append,
+ );
+ final appended = await scanner.scan(sourcesOf(unchanged));
+ expect(
+ tokensIn(provider, appended),
+ provider == LedgerProvider.claude ? 300 : 200,
+ );
+ await file.delete();
+ final removed = await scanner.scan(sourcesOf(appended));
+ expect(removed.status, LedgerStatus.unavailable);
+ expect(removed.sources, isEmpty);
+ });
+ });
+ }
+}
diff --git a/desktop/test/usage_ledger_benchmark_test.dart b/desktop/test/usage_ledger_benchmark_test.dart
new file mode 100644
index 000000000..0ef4549f6
--- /dev/null
+++ b/desktop/test/usage_ledger_benchmark_test.dart
@@ -0,0 +1,138 @@
+// Synthetic CPU benchmark. No user logs, account data, or filesystem scans.
+// HARNESS_USAGE_BENCHMARK=1 flutter test test/usage_ledger_benchmark_test.dart
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/snapshot_store.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/usage_ledger_controller.dart';
+import 'package:harness/usage/ledger/usage_ledger_store.dart';
+import 'package:harness/usage/ledger/usage_report.dart';
+import 'package:harness/usage/ledger/opencode_ledger_scanner.dart';
+
+import 'usage_ledger_test.dart'
+ show MemorySettings, FakeScanner, sourceOf, entryOf;
+
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+
+import 'usage_scanners_test.dart' show createUsageDatabase;
+
+void main() {
+ test('OpenCode scan CPU stays off the caller event loop', () async {
+ final fixture = await Directory.systemTemp.createTemp(
+ 'harness-usage-timing-',
+ );
+ addTearDown(() => fixture.delete(recursive: true));
+ final db = createUsageDatabase('${fixture.path}/opencode.db');
+ db.execute('BEGIN');
+ final insert = db.prepare(
+ 'INSERT INTO session VALUES (?, ?, ?, 0, 100, 0, 0, 0, 0, ?)',
+ );
+ for (var i = 0; i < 30000; i++) {
+ insert.execute([
+ 'fixture-$i',
+ '/fixture',
+ 1789862400000 + i,
+ 'fixture-model',
+ ]);
+ }
+ insert.dispose();
+ db.execute('COMMIT');
+ db.dispose();
+ final scanner = OpenCodeLedgerScanner(dataDirectory: fixture.path);
+ final elapsed = <int>[];
+ final gaps = <int>[];
+ for (var run = 0; run < 6; run++) {
+ final watch = Stopwatch()..start();
+ var previousTick = 0;
+ var maximumGap = 0;
+ final ticker = Timer.periodic(const Duration(milliseconds: 1), (_) {
+ final now = watch.elapsedMicroseconds;
+ final gap = now - previousTick;
+ if (gap > maximumGap) maximumGap = gap;
+ previousTick = now;
+ });
+ try {
+ final result = await scanner.scan({});
+ final duration = watch.elapsedMicroseconds;
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ expect(result.sources.single.entries, hasLength(30000));
+ if (run > 0) {
+ elapsed.add(duration);
+ gaps.add(maximumGap);
+ }
+ } finally {
+ ticker.cancel();
+ }
+ }
+ elapsed.sort();
+ gaps.sort();
+ // Scheduling observations, not a native-frame or CI latency assertion.
+ // ignore: avoid_print
+ print(
+ 'OpenCode / 30000 sessions / debug: median scan ${elapsed[2]} us; '
+ 'median maximum caller event-loop gap ${gaps[2]} us',
+ );
+ }, skip: Platform.environment['HARNESS_USAGE_BENCHMARK'] != '1');
+
+ test('repeated overview reads of 60000 synthetic turns', () async {
+ final now = DateTime(2026, 9, 20, 12);
+ final controller = UsageLedgerController(
+ stores: [
+ for (final provider in LedgerProvider.values)
+ UsageLedgerStore(
+ scanner: FakeScanner(
+ provider,
+ LedgerScanResult(
+ sources: [
+ sourceOf(
+ '${provider.name}.jsonl',
+ List.generate(
+ 20000,
+ (i) => entryOf(
+ provider: provider,
+ dedupeKey: '${provider.name}-$i',
+ sessionId: 'session-${i ~/ 40}',
+ timestamp: now
+ .subtract(Duration(hours: i % 2160))
+ .toIso8601String(),
+ model: provider == LedgerProvider.claude
+ ? 'claude-opus-5'
+ : 'gpt-5',
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ settings: MemorySettings(),
+ snapshots: MemorySnapshotStore(),
+ ),
+ ],
+ );
+ addTearDown(controller.dispose);
+ await controller.load();
+ for (final store in controller.stores) {
+ await store.setEnabled(true);
+ }
+ for (var i = 0; i < 8; i++) {
+ controller.overviewFor(UsageRange.d30, now: now);
+ }
+ final times = <int>[];
+ for (var i = 0; i < 60; i++) {
+ final watch = Stopwatch()..start();
+ final result = controller.overviewFor(UsageRange.d30, now: now);
+ times.add(watch.elapsedMicroseconds);
+ expect(result.enabledCount, 3);
+ expect(result.totals.total, greaterThan(0));
+ }
+ times.sort();
+ // Report only: shared-machine timing is not a pass/fail latency target.
+ // ignore: avoid_print
+ print(
+ 'usage overview / 60000 turns / warm debug CPU: '
+ 'median ${times[30]} us; p95 ${times[57]} us',
+ );
+ }, skip: Platform.environment['HARNESS_USAGE_BENCHMARK'] != '1');
+}
diff --git a/desktop/test/usage_ledger_lifecycle_test.dart b/desktop/test/usage_ledger_lifecycle_test.dart
new file mode 100644
index 000000000..f286b3445
--- /dev/null
+++ b/desktop/test/usage_ledger_lifecycle_test.dart
@@ -0,0 +1,531 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/snapshot_store.dart';
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/usage_ledger_controller.dart';
+import 'package:harness/usage/ledger/usage_ledger_store.dart';
+import 'package:harness/usage/ledger/usage_report.dart';
+
+import 'usage_ledger_test.dart'
+ show MemorySettings, FakeScanner, sourceOf, entryOf;
+
+class HeldScanner implements LedgerScanner {
+ @override
+ final provider = LedgerProvider.claude;
+ final replies = <Completer<LedgerScanResult>>[];
+ final previous = <Map<String, ScannedSource>>[];
+
+ @override
+ Future<LedgerScanResult> scan(Map<String, ScannedSource> sources) {
+ previous.add(Map.of(sources));
+ final reply = Completer<LedgerScanResult>();
+ replies.add(reply);
+ return reply.future;
+ }
+}
+
+class HeldSettings extends MemorySettings {
+ Completer<String?>? reading;
+ Completer<void>? writing;
+ int reads = 0;
+ final writes = <String>[];
+
+ @override
+ Future<String?> read(String key) {
+ reads++;
+ return reading?.future ?? super.read(key);
+ }
+
+ @override
+ Future<void> write(String key, String value) async {
+ writes.add(value);
+ await writing?.future;
+ await super.write(key, value);
+ }
+}
+
+class HeldSnapshots extends MemorySnapshotStore {
+ Completer<String?>? reading;
+ Completer<void>? writing;
+ Completer<void>? clearing;
+ int writes = 0;
+ int clears = 0;
+
+ @override
+ Future<String?> read() => reading?.future ?? super.read();
+
+ @override
+ Future<void> write(String value) async {
+ writes++;
+ await writing?.future;
+ await super.write(value);
+ }
+
+ @override
+ Future<void> clear() async {
+ clears++;
+ await clearing?.future;
+ await super.clear();
+ }
+}
+
+LedgerScanResult figures([int tokens = 100]) => LedgerScanResult(
+ sources: [
+ sourceOf('fixture.jsonl', [
+ entryOf(
+ dedupeKey: 'turn',
+ totals: UsageTotals(freshInput: tokens),
+ ),
+ ]),
+ ],
+);
+
+Future<void> tick() => Future<void>.delayed(Duration.zero);
+
+void main() {
+ const enabledKey = 'usageLedger.claude.enabled';
+ late HeldSettings settings;
+ late HeldSnapshots snapshots;
+ late HeldScanner scanner;
+ late UsageLedgerStore store;
+
+ setUp(() {
+ settings = HeldSettings();
+ snapshots = HeldSnapshots();
+ scanner = HeldScanner();
+ store = UsageLedgerStore(
+ scanner: scanner,
+ settings: settings,
+ snapshots: snapshots,
+ );
+ });
+ tearDown(() => store.dispose());
+
+ test(
+ 'partial scans keep readable figures, disclose gaps, and retry immediately',
+ () async {
+ await store.load();
+ final enabling = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures(500));
+ await enabling;
+ expect(snapshots.isEmpty, isFalse);
+ final refreshing = store.refresh(force: true);
+ await tick();
+ scanner.replies.last.complete(
+ LedgerScanResult(
+ sources: figures(100).sources,
+ status: LedgerStatus.partial,
+ message: 'One source could not be read. Figures are incomplete.',
+ ),
+ );
+ await refreshing;
+ expect(store.ledger.totals.total, 100);
+ expect(store.state.hasIncompleteFigures, isTrue);
+ expect(snapshots.isEmpty, isTrue);
+ final retrying = store.refresh();
+ await tick();
+ expect(scanner.replies, hasLength(3));
+ expect(store.state.status, LedgerStatus.scanning);
+ expect(store.state.hasIncompleteFigures, isTrue);
+ scanner.replies.last.complete(figures(250));
+ await retrying;
+ expect(store.ledger.totals.total, 250);
+ expect(store.state.status, LedgerStatus.ok);
+ expect(store.state.hasIncompleteFigures, isFalse);
+ expect(store.state.message, isNull);
+ expect(snapshots.isEmpty, isFalse);
+ },
+ );
+
+ test(
+ 'reopening after a partial scan cannot restore it as complete',
+ () async {
+ await store.load();
+ final enabling = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(
+ LedgerScanResult(
+ sources: figures().sources,
+ status: LedgerStatus.partial,
+ message: 'Figures are incomplete.',
+ ),
+ );
+ await enabling;
+ final secondScanner = HeldScanner();
+ final reopened = UsageLedgerStore(
+ scanner: secondScanner,
+ settings: settings,
+ snapshots: snapshots,
+ );
+ addTearDown(reopened.dispose);
+ await reopened.load();
+ expect(reopened.state.enabled, isTrue);
+ expect(reopened.ledger.hasData, isFalse);
+ final scanning = reopened.refresh();
+ await tick();
+ expect(secondScanner.replies, hasLength(1));
+ secondScanner.replies.single.complete(figures(300));
+ await scanning;
+ expect(reopened.ledger.totals.total, 300);
+ },
+ );
+
+ test('a completed scan cannot undo Off or recreate its snapshot', () async {
+ await store.load();
+ final enabling = store.setEnabled(true);
+ await tick();
+ expect(scanner.replies, hasLength(1));
+ await store.setEnabled(false);
+ scanner.replies.single.complete(figures());
+ await enabling;
+ expect(store.state.enabled, isFalse);
+ expect(store.state.status, LedgerStatus.disabled);
+ expect(store.state.lastScanAt, isNull);
+ expect(store.ledger.hasData, isFalse);
+ expect(snapshots.isEmpty, isTrue);
+ expect(settings.values[enabledKey], 'false');
+ });
+
+ test(
+ 'Off removes figures immediately while settings persistence is delayed',
+ () async {
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await enabled;
+ final gate = settings.writing = Completer<void>();
+ final disabled = store.setEnabled(false);
+ expect(store.state.status, LedgerStatus.disabled);
+ expect(store.state.lastScanAt, isNull);
+ expect(store.ledger.hasData, isFalse);
+ gate.complete();
+ await disabled;
+ expect(snapshots.isEmpty, isTrue);
+ },
+ );
+
+ for (final oldResult in [false, true]) {
+ test(
+ 'a delayed $oldResult preference cannot overwrite a newer toggle',
+ () async {
+ final gate = settings.reading = Completer<String?>();
+ final loaded = store.load();
+ await tick();
+ final changed = store.setEnabled(!oldResult);
+ await tick();
+ gate.complete('$oldResult');
+ await loaded;
+ if (!oldResult) {
+ expect(scanner.replies, hasLength(1));
+ scanner.replies.single.complete(figures());
+ }
+ await changed;
+ expect(store.state.enabled, !oldResult);
+ expect(settings.values[enabledKey], '${!oldResult}');
+ },
+ );
+ }
+
+ test('a delayed snapshot cannot restore figures after Off', () async {
+ final prepared = UsageLedgerStore(
+ scanner: FakeScanner(LedgerProvider.claude, figures()),
+ settings: settings,
+ snapshots: snapshots,
+ );
+ await prepared.setEnabled(true);
+ final cached = snapshots.contents;
+ prepared.dispose();
+ final gate = snapshots.reading = Completer<String?>();
+ final loaded = store.load();
+ await tick();
+ await store.setEnabled(false);
+ gate.complete(cached);
+ await loaded;
+ expect(store.state.enabled, isFalse);
+ expect(store.state.lastScanAt, isNull);
+ expect(store.ledger.hasData, isFalse);
+ expect(snapshots.isEmpty, isTrue);
+ });
+
+ test(
+ 'Off then On waits for the old scan and scans again with empty sources',
+ () async {
+ final first = store.setEnabled(true);
+ await tick();
+ await store.setEnabled(false);
+ final second = store.setEnabled(true);
+ await tick();
+ expect(
+ scanner.replies,
+ hasLength(1),
+ reason: 'Disk scans must not overlap',
+ );
+ scanner.replies.first.complete(figures(900));
+ await first;
+ await tick();
+ expect(store.ledger.hasData, isFalse);
+ expect(scanner.replies, hasLength(2));
+ expect(scanner.previous.last, isEmpty);
+ scanner.replies.last.complete(figures(20));
+ await second;
+ expect(store.ledger.totals.total, 20);
+ expect(store.state.status, LedgerStatus.ok);
+ },
+ );
+
+ test('a queued cache write finishes before Off clears it', () async {
+ final gate = snapshots.writing = Completer<void>();
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await tick();
+ expect(snapshots.writes, 1);
+ final disabled = store.setEnabled(false);
+ await tick();
+ gate.complete();
+ await Future.wait([enabled, disabled]);
+ expect(snapshots.isEmpty, isTrue);
+ expect(store.ledger.hasData, isFalse);
+ });
+
+ test(
+ 'rapid toggles persist in order and cannot publish the first scan',
+ () async {
+ final gate = settings.writing = Completer<void>();
+ final on = store.setEnabled(true);
+ await tick();
+ final off = store.setEnabled(false);
+ final onAgain = store.setEnabled(true);
+ final offAgain = store.setEnabled(false);
+ gate.complete();
+ await tick();
+ for (final reply in scanner.replies) {
+ reply.complete(figures());
+ }
+ await Future.wait([on, off, onAgain, offAgain]);
+ expect(settings.writes, ['true', 'false', 'true', 'false']);
+ expect(settings.values[enabledKey], 'false');
+ expect(store.state.status, LedgerStatus.disabled);
+ expect(store.ledger.hasData, isFalse);
+ expect(snapshots.isEmpty, isTrue);
+ },
+ );
+
+ for (final throws in [false, true]) {
+ test(
+ '${throws ? 'thrown' : 'returned'} failure drops stale totals and allows immediate retry',
+ () async {
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await enabled;
+ final failed = store.refresh(force: true);
+ await tick();
+ if (throws) {
+ scanner.replies.last.completeError(
+ StateError('Fixture is unavailable'),
+ );
+ } else {
+ scanner.replies.last.complete(
+ const LedgerScanResult.unavailable('No fixture logs'),
+ );
+ }
+ await failed;
+ expect(store.state.lastScanAt, isNull);
+ expect(store.ledger.hasData, isFalse);
+ expect(snapshots.isEmpty, isTrue);
+ final retry = store.refresh();
+ await tick();
+ expect(scanner.replies, hasLength(3));
+ scanner.replies.last.complete(figures(25));
+ await retry;
+ expect(store.ledger.totals.total, 25);
+ },
+ );
+ }
+
+ test(
+ 'closing and reopening waits for an already requested Off to persist',
+ () async {
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await enabled;
+ final gate = settings.writing = Completer<void>();
+ final disabled = store.setEnabled(false);
+ // A second controller is what reopening the settings section creates.
+ final reopened = UsageLedgerStore(
+ scanner: scanner,
+ settings: settings,
+ snapshots: snapshots,
+ );
+ addTearDown(reopened.dispose);
+ final loaded = reopened.load();
+ await tick();
+ gate.complete();
+ await Future.wait([disabled, loaded]);
+ expect(reopened.state.enabled, isFalse);
+ expect(reopened.ledger.hasData, isFalse);
+ expect(snapshots.isEmpty, isTrue);
+ },
+ );
+
+ test('load is shared and does not undo current in-session choices', () async {
+ settings.reading = Completer<String?>();
+ final first = store.load();
+ final second = store.load();
+ await tick();
+ expect(settings.reads, 1);
+ settings.reading!.complete('false');
+ await Future.wait([first, second]);
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await enabled;
+ await store.load();
+ expect(settings.reads, 1);
+ expect(store.ledger.totals.total, 100);
+ });
+
+ test('a synchronous scan listener cannot start a duplicate scan', () async {
+ final enabled = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.complete(figures());
+ await enabled;
+ Future<void>? joined;
+ var requested = false;
+ store.addListener(() {
+ if (!requested && store.state.status == LedgerStatus.scanning) {
+ requested = true;
+ joined = store.refresh(force: true);
+ }
+ });
+ final refreshed = store.refresh(force: true);
+ await tick();
+ expect(scanner.replies, hasLength(2));
+ scanner.replies.last.complete(figures());
+ await refreshed;
+ await joined;
+ });
+
+ test(
+ 'Retry after a visible failure waits for cache cleanup then scans again',
+ () async {
+ final gate = snapshots.clearing = Completer<void>();
+ final first = store.setEnabled(true);
+ await tick();
+ scanner.replies.single.completeError(StateError('Fixture read failed'));
+ await tick();
+ expect(store.state.status, LedgerStatus.failed);
+ final retry = store.refresh(force: true);
+ gate.complete();
+ await first;
+ await tick();
+ expect(scanner.replies, hasLength(2));
+ scanner.replies.last.complete(figures());
+ await retry;
+ expect(store.ledger.hasData, isTrue);
+ },
+ );
+
+ for (final fail in [false, true]) {
+ test(
+ 'a late ${fail ? 'failed' : 'successful'} scan after disposal has no effects',
+ () async {
+ final probe = HeldScanner();
+ final cache = MemorySnapshotStore();
+ final owned = UsageLedgerStore(
+ scanner: probe,
+ settings: MemorySettings(),
+ snapshots: cache,
+ );
+ var notifications = 0;
+ owned.addListener(() => notifications++);
+ final enabled = owned.setEnabled(true);
+ await tick();
+ owned.dispose();
+ final count = notifications;
+ if (fail) {
+ probe.replies.single.completeError(
+ StateError('Late fixture failure'),
+ );
+ } else {
+ probe.replies.single.complete(figures());
+ }
+ await enabled;
+ await owned.refresh(force: true);
+ expect(cache.isEmpty, isTrue);
+ expect(notifications, count);
+ expect(probe.replies, hasLength(1));
+ },
+ );
+ }
+
+ test(
+ 'disposing a controller during load never scans or notifies afterward',
+ () async {
+ final delayed = HeldSettings()..reading = Completer<String?>();
+ final probe = HeldScanner();
+ final owned = UsageLedgerStore(
+ scanner: probe,
+ settings: delayed,
+ snapshots: MemorySnapshotStore(),
+ );
+ final controller = UsageLedgerController(stores: [owned]);
+ var notifications = 0;
+ controller.addListener(() => notifications++);
+ final loading = controller.load();
+ await tick();
+ controller.dispose();
+ final count = notifications;
+ delayed.reading!.complete('true');
+ await loading;
+ expect(notifications, count);
+ expect(probe.replies, isEmpty);
+ },
+ );
+
+ test(
+ 'overview ranges follow midnight, new scans, failures, and Off',
+ () async {
+ final source = FakeScanner(LedgerProvider.claude, figures());
+ final owned = UsageLedgerStore(
+ scanner: source,
+ settings: MemorySettings(),
+ snapshots: MemorySnapshotStore(),
+ );
+ final controller = UsageLedgerController(stores: [owned]);
+ addTearDown(controller.dispose);
+ await controller.load();
+ await owned.setEnabled(true);
+ expect(
+ controller
+ .overviewFor(UsageRange.d7, now: DateTime(2026, 9, 7, 23))
+ .totals
+ .total,
+ 100,
+ );
+ expect(controller.overviewFor(UsageRange.all).totals.total, 100);
+ // The application can stay open across midnight with no new scan event.
+ expect(
+ controller
+ .overviewFor(UsageRange.d7, now: DateTime(2026, 9, 8))
+ .totals
+ .total,
+ 0,
+ );
+ source.result = figures(200);
+ await owned.refresh(force: true);
+ expect(controller.overviewFor(UsageRange.all).totals.total, 200);
+ source.result = const LedgerScanResult.unavailable('No fixture');
+ await owned.refresh(force: true);
+ expect(controller.overviewFor(UsageRange.all).totals.total, 0);
+ expect(controller.overviewFor(UsageRange.all).lastScanAt, isNull);
+ await owned.setEnabled(false);
+ expect(controller.overviewFor(UsageRange.all).enabledCount, 0);
+ },
+ );
+}
diff --git a/desktop/test/usage_ledger_test.dart b/desktop/test/usage_ledger_test.dart
index 5fd16f059..034b41d8a 100644
--- a/desktop/test/usage_ledger_test.dart
+++ b/desktop/test/usage_ledger_test.dart
@@ -480,6 +480,25 @@ void main() {
});
group('aggregation', () {
+ test(
+ 'repeated model names still price each turn at its own context tier',
+ () {
+ final ledger = buildProviderLedger(LedgerProvider.claude, [
+ sourceOf('tiered.jsonl', [
+ entryOf(
+ model: 'claude-sonnet-4-5',
+ totals: const UsageTotals(freshInput: 100000),
+ ),
+ entryOf(
+ model: 'claude-sonnet-4-5',
+ totals: const UsageTotals(freshInput: 400000),
+ ),
+ ]),
+ ]);
+ expect(ledger.costUsd, closeTo(2.1, 0.000001));
+ expect(ledger.totals.freshInput, 500000);
+ },
+ );
test('drops an exchange seen in two files', () {
final ledger = buildProviderLedger(LedgerProvider.claude, [
sourceOf('a.jsonl', [entryOf(dedupeKey: 'k1')]),
@@ -578,6 +597,40 @@ void main() {
});
});
+ test(
+ 'version 2 empty-file caches are rescanned even with a fresh timestamp',
+ () async {
+ final settings = MemorySettings()
+ ..values['usageLedger.claude.enabled'] = 'true';
+ final scanner = FakeScanner(
+ LedgerProvider.claude,
+ LedgerScanResult(
+ sources: [
+ sourceOf('restored.jsonl', [entryOf()]),
+ ],
+ ),
+ );
+ final store = UsageLedgerStore(
+ scanner: scanner,
+ settings: settings,
+ snapshots: MemorySnapshotStore(
+ jsonEncode({
+ 'version': 2,
+ 'provider': 'claude',
+ 'lastScanAt': DateTime.now().toIso8601String(),
+ 'sources': [sourceOf('restored.jsonl', []).toJson()],
+ }),
+ ),
+ );
+ addTearDown(store.dispose);
+ await store.load();
+ await store.refresh();
+ expect(scanner.scans, 1);
+ expect(scanner.lastPrevious, isEmpty);
+ expect(store.ledger.hasData, isTrue);
+ },
+ );
+
group('formatting', () {
test('shortens token counts, billions included', () {
expect(formatTokens(912), '912');
diff --git a/desktop/test/usage_loading_test.dart b/desktop/test/usage_loading_test.dart
new file mode 100644
index 000000000..b5fe5f3e1
--- /dev/null
+++ b/desktop/test/usage_loading_test.dart
@@ -0,0 +1,311 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/snapshot_store.dart';
+import 'package:harness/settings/sections/usage_panels.dart';
+import 'package:harness/settings/sections/usage_detail_panels.dart';
+import 'package:harness/settings/sections/usage_section.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/widgets/app_select_field.dart';
+import 'package:harness/stats/harness_stats.dart';
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/usage_ledger_controller.dart';
+import 'package:harness/usage/ledger/usage_ledger_store.dart';
+import 'package:harness/usage/ledger/usage_report.dart';
+
+import 'support/real_fonts.dart';
+import 'usage_ledger_lifecycle_test.dart' show HeldScanner, HeldSettings;
+import 'usage_ledger_test.dart'
+ show FakeScanner, MemorySettings, sourceOf, entryOf;
+
+LedgerScanResult _figures([int tokens = 1200]) => LedgerScanResult(
+ sources: [
+ sourceOf('fixture.jsonl', [
+ entryOf(
+ timestamp: DateTime.now()
+ .subtract(const Duration(hours: 2))
+ .toIso8601String(),
+ totals: UsageTotals(freshInput: tokens),
+ dedupeKey: 'fixture-turn',
+ ),
+ ]),
+ ],
+);
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ for (final (family, path) in [
+ ('MaterialIcons', 'fonts/MaterialIcons-Regular.otf'),
+ (
+ 'packages/lucide_icons_flutter/Lucide300',
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w300.ttf',
+ ),
+ ]) {
+ await (FontLoader(family)..addFont(rootBundle.load(path))).load();
+ }
+ });
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.8]) {
+ testWidgets(
+ 'Usage waiting, retry, range, and Off — ${brightness.name}, $scale',
+ (tester) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(880, 560);
+ addTearDown(tester.view.reset);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);
+ final settings = HeldSettings()..reading = Completer<String?>();
+ final scanner = HeldScanner();
+ final snapshot = MemorySnapshotStore();
+ final store = UsageLedgerStore(
+ scanner: scanner,
+ settings: settings,
+ snapshots: snapshot,
+ );
+ final controller = UsageLedgerController(
+ stores: [
+ store,
+ for (final provider in [
+ LedgerProvider.codex,
+ LedgerProvider.opencode,
+ ])
+ UsageLedgerStore(
+ scanner: FakeScanner(provider, const LedgerScanResult()),
+ settings: MemorySettings(),
+ snapshots: MemorySnapshotStore(),
+ ),
+ ],
+ );
+ final stats = HarnessStats(store: MemorySnapshotStore());
+ addTearDown(controller.dispose);
+ addTearDown(stats.dispose);
+ final loading = controller.load();
+ final boundary = GlobalKey();
+ Future<void> capture(String stage) async {
+ final directory = Platform.environment['HARNESS_USAGE_CAPTURE_DIR'];
+ if (directory == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$stage-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ Future<void> key(LogicalKeyboardKey key) async {
+ await tester.sendKeyEvent(key);
+ await tester.pumpAndSettle();
+ }
+
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(scale),
+ disableAnimations: true,
+ ),
+ child: grid.BrightnessScope(child: child!),
+ ),
+ home: Scaffold(
+ body: UsageSection(controller: controller, stats: stats),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Reading usage settings…'), findsOneWidget);
+ expect(find.text('Enable Claude'), findsNothing);
+ expect(find.byType(ProviderUsageRow), findsNothing);
+ await capture('settings-loading');
+
+ settings.reading!.complete('true');
+ await tester.pumpAndSettle();
+ expect(scanner.replies, hasLength(1));
+ expect(find.text('Scanning local logs…'), findsOneWidget);
+ expect(find.text('0 tokens'), findsNothing);
+ expect(find.text('0 sessions'), findsNothing);
+ expect(find.textContaining('0 with data'), findsNothing);
+ await capture('overview-scanning');
+
+ final lens = find.byType(AppSelectField<LedgerProvider?>);
+ Future<void> revealLens() => tester.scrollUntilVisible(
+ lens,
+ -200,
+ scrollable: find.byType(Scrollable).first,
+ );
+ await revealLens();
+ await tester.tap(lens);
+ await tester.pumpAndSettle();
+ await key(LogicalKeyboardKey.arrowDown);
+ await key(LogicalKeyboardKey.enter);
+ expect(find.text('Scanning Claude logs…'), findsOneWidget);
+ expect(find.text('No Claude usage in this range.'), findsNothing);
+ await capture('provider-scanning');
+
+ scanner.replies.single.completeError(
+ StateError('Fixture logs are temporarily unavailable.'),
+ );
+ await tester.pumpAndSettle();
+ await loading;
+ expect(
+ find.textContaining('temporarily unavailable'),
+ findsOneWidget,
+ );
+ expect(find.text('Fresh input'), findsNothing);
+ await capture('provider-failed');
+
+ final rescan = find.byTooltip('Rescan the local logs');
+ await tester.ensureVisible(rescan);
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(scanner.replies, hasLength(2));
+ const incomplete =
+ 'Could not read 1 of 2 Claude transcripts. Figures are incomplete.';
+ scanner.replies.last.complete(
+ LedgerScanResult(
+ sources: _figures().sources,
+ status: LedgerStatus.partial,
+ message: incomplete,
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Fresh input'), findsWidgets);
+ expect(find.text(incomplete), findsOneWidget);
+ await tester.ensureVisible(find.text(incomplete));
+ await tester.pumpAndSettle();
+ await capture('provider-partial');
+ await revealLens();
+ await tester.tap(lens);
+ await tester.pumpAndSettle();
+ await key(LogicalKeyboardKey.arrowUp);
+ await key(LogicalKeyboardKey.enter);
+ expect(find.text('Incomplete'), findsOneWidget);
+ final warning = find.text(
+ 'Some usage could not be read. Totals are incomplete.',
+ );
+ expect(warning, findsOneWidget);
+ await tester.ensureVisible(warning);
+ await tester.pumpAndSettle();
+ await capture('overview-partial');
+ await revealLens();
+ await tester.tap(lens);
+ await tester.pumpAndSettle();
+ await key(LogicalKeyboardKey.arrowDown);
+ await key(LogicalKeyboardKey.enter);
+ final range = find.byType(AppSelectField<UsageRange>);
+ await tester.ensureVisible(range);
+ await tester.tap(range);
+ await tester.pumpAndSettle();
+ await key(LogicalKeyboardKey.arrowDown);
+ await key(LogicalKeyboardKey.arrowDown);
+ await key(LogicalKeyboardKey.enter);
+ expect(
+ tester.widget<AppSelectField<UsageRange>>(range).value,
+ UsageRange.all,
+ );
+ expect(
+ scanner.replies,
+ hasLength(2),
+ reason: 'Changing range must not walk the disk',
+ );
+ await tester.ensureVisible(rescan);
+ await tester.tap(rescan);
+ await tester.pumpAndSettle();
+ expect(scanner.replies, hasLength(3));
+ expect(find.text(incomplete), findsOneWidget);
+ expect(
+ find.text('Fresh input'),
+ findsWidgets,
+ reason: 'A rescan retains the previous figures',
+ );
+ await capture('provider-rescanning');
+
+ final off = find.byTooltip('Stop reading Claude');
+ await tester.ensureVisible(off);
+ await tester.tap(off);
+ await tester.pumpAndSettle();
+ expect(find.text('Enable Claude'), findsOneWidget);
+ expect(find.text('Fresh input'), findsNothing);
+ scanner.replies.last.complete(_figures(9900));
+ await tester.pumpAndSettle();
+ expect(find.text('Enable Claude'), findsOneWidget);
+ expect(store.state.enabled, isFalse);
+ expect(snapshot.isEmpty, isTrue);
+ await capture('provider-off');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
+
+ testWidgets('daily bars share a baseline and large labels remain readable', (
+ tester,
+ ) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(400, 700);
+ addTearDown(tester.view.reset);
+ final days = [
+ LedgerDay(
+ day: DateTime(2026, 9, 19),
+ totals: const UsageTotals(freshInput: 100),
+ ),
+ LedgerDay(
+ day: DateTime(2026, 9, 20),
+ totals: const UsageTotals(freshInput: 200),
+ ),
+ ];
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(2.5)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SingleChildScrollView(child: UsageDailyChart(days: days)),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Finder bar(String label) => find.descendant(
+ of: find.byTooltip(label),
+ matching: find.byWidgetPredicate(
+ (widget) =>
+ widget is Container &&
+ widget.color == usageBucketColours.freshInput,
+ ),
+ );
+ final small = tester.getRect(bar('2026-09-19\n100 tokens'));
+ final large = tester.getRect(bar('2026-09-20\n200 tokens'));
+ expect(small.bottom, closeTo(large.bottom, .01));
+ expect(small.height * 2, closeTo(large.height, .01));
+ for (final label in ['100', '200', '09-19', '09-20']) {
+ final paragraph = tester.renderObject<RenderParagraph>(find.text(label));
+ expect(paragraph.didExceedMaxLines, isFalse);
+ }
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+}
diff --git a/desktop/test/usage_scanners_test.dart b/desktop/test/usage_scanners_test.dart
new file mode 100644
index 000000000..c24f8226b
--- /dev/null
+++ b/desktop/test/usage_scanners_test.dart
@@ -0,0 +1,196 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/ledger/ledger_scanner.dart';
+import 'package:harness/usage/ledger/ledger_types.dart';
+import 'package:harness/usage/ledger/opencode_ledger_scanner.dart';
+import 'package:harness/usage/ledger/usage_overview.dart';
+import 'package:sqlite3/sqlite3.dart';
+
+Database createUsageDatabase(String path, {bool wal = false}) {
+ final db = sqlite3.open(path);
+ if (wal) {
+ db.execute('PRAGMA journal_mode=WAL');
+ db.execute('PRAGMA wal_autocheckpoint=0');
+ }
+ db.execute('''
+ CREATE TABLE session (
+ id TEXT PRIMARY KEY, directory TEXT, time_created INTEGER,
+ cost REAL, tokens_input INTEGER, tokens_output INTEGER,
+ tokens_reasoning INTEGER, tokens_cache_read INTEGER,
+ tokens_cache_write INTEGER, model TEXT
+ )
+ ''');
+ return db;
+}
+
+void addUsage(
+ Database db, {
+ String id = 'session',
+ int input = 100,
+ int cacheWrite = 0,
+}) {
+ db.execute('INSERT INTO session VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [
+ id,
+ '/fixture/project',
+ 1789862400000,
+ 0.0,
+ input,
+ 0,
+ 0,
+ 0,
+ cacheWrite,
+ 'fixture-model',
+ ]);
+}
+
+Map<String, ScannedSource> previousSources(LedgerScanResult result) => {
+ for (final source in result.sources) source.path: source,
+};
+
+void main() {
+ late Directory fixture;
+ late OpenCodeLedgerScanner scanner;
+ setUp(() async {
+ fixture = await Directory.systemTemp.createTemp('harness-usage-scanner-');
+ scanner = OpenCodeLedgerScanner(dataDirectory: fixture.path);
+ });
+ tearDown(() async => fixture.delete(recursive: true));
+
+ test(
+ 'a refresh sees committed WAL updates while OpenCode stays open',
+ () async {
+ final file = File('${fixture.path}/opencode.db');
+ final writer = createUsageDatabase(file.path, wal: true);
+ try {
+ addUsage(writer);
+ final first = await scanner.scan({});
+ expect(first.sources.single.entries.single.totals.freshInput, 100);
+ final before = await file.stat();
+ writer.execute('UPDATE session SET tokens_input=200');
+ final after = await file.stat();
+ expect(after.modified, before.modified);
+ expect(after.size, before.size);
+ final second = await scanner.scan(previousSources(first));
+ expect(second.sources.single.entries.single.totals.freshInput, 200);
+ writer.execute('BEGIN');
+ writer.execute('UPDATE session SET tokens_input=900');
+ final uncommitted = await scanner.scan(previousSources(second));
+ expect(
+ uncommitted.sources.single.entries.single.totals.freshInput,
+ 200,
+ );
+ writer.execute('ROLLBACK');
+ writer.execute('PRAGMA wal_checkpoint(TRUNCATE)');
+ writer.execute('UPDATE session SET tokens_input=300');
+ final third = await scanner.scan(previousSources(second));
+ expect(third.sources.single.entries.single.totals.freshInput, 300);
+ } finally {
+ writer.dispose();
+ }
+ },
+ );
+
+ test(
+ 'a locked database reports a read failure and recovers on refresh',
+ () async {
+ final writer = createUsageDatabase('${fixture.path}/opencode.db');
+ try {
+ addUsage(writer);
+ writer.execute('BEGIN EXCLUSIVE');
+ final locked = await scanner.scan({});
+ expect(locked.status, LedgerStatus.failed);
+ expect(locked.message, contains('locked'));
+ writer.execute('ROLLBACK');
+ final recovered = await scanner.scan(previousSources(locked));
+ expect(recovered.status, LedgerStatus.ok);
+ expect(recovered.sources.single.entries.single.totals.freshInput, 100);
+ } finally {
+ writer.dispose();
+ }
+ },
+ );
+
+ test('a corrupt database is failed, not missing or zero usage', () async {
+ await File('${fixture.path}/opencode.db')
+ .writeAsString('not a sqlite database');
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.failed);
+ expect(result.message, isNotEmpty);
+ });
+
+ test(
+ 'a missing data directory differs from a path that is not a directory',
+ () async {
+ final path = '${fixture.path}/data';
+ final configured = OpenCodeLedgerScanner(dataDirectory: path);
+ expect((await configured.scan({})).status, LedgerStatus.unavailable);
+ await File(path).writeAsString('not a directory');
+ expect((await configured.scan({})).status, LedgerStatus.failed);
+ },
+ );
+
+ test(
+ 'an unsupported usage schema does not claim a successful empty scan',
+ () async {
+ final writer = sqlite3.open('${fixture.path}/opencode.db');
+ writer.execute('CREATE TABLE session (id TEXT PRIMARY KEY)');
+ writer.dispose();
+ final result = await scanner.scan({});
+ expect(result.status, LedgerStatus.failed);
+ expect(result.message, contains('format'));
+ },
+ );
+
+ test('a broken sibling is disclosed alongside readable usage', () async {
+ final writer = createUsageDatabase('${fixture.path}/opencode.db');
+ addUsage(writer);
+ writer.dispose();
+ await File('${fixture.path}/opencode-copy.db').writeAsString('broken');
+ final result = await scanner.scan({});
+ expect(result.status.name, 'partial');
+ expect(result.message, contains('1'));
+ expect(result.sources.single.entries.single.totals.freshInput, 100);
+ });
+
+ test('cache-write-only sessions count as usage', () async {
+ final writer = createUsageDatabase('${fixture.path}/opencode.db');
+ addUsage(writer, input: 0, cacheWrite: 70);
+ writer.dispose();
+ final result = await scanner.scan({});
+ expect(result.sources.single.entries.single.totals.total, 70);
+ });
+
+ test(
+ 'the live database wins duplicate session ids over sibling copies',
+ () async {
+ for (final (name, input) in [
+ ('opencode-copy.db', 100),
+ ('opencode.db', 200),
+ ]) {
+ final writer = createUsageDatabase('${fixture.path}/$name');
+ addUsage(writer, input: input);
+ writer.dispose();
+ }
+ final result = await scanner.scan({});
+ final ledger = buildProviderLedger(
+ LedgerProvider.opencode,
+ result.sources,
+ );
+ expect(ledger.sessionCount, 1);
+ expect(ledger.totals.freshInput, 200);
+ expect(ledger.costUsd, 0.0);
+ },
+ );
+
+ test(
+ 'an empty supported database and an absent database remain distinct',
+ () async {
+ expect((await scanner.scan({})).status, LedgerStatus.unavailable);
+ createUsageDatabase('${fixture.path}/opencode.db').dispose();
+ final empty = await scanner.scan({});
+ expect(empty.status, LedgerStatus.ok);
+ expect(empty.sources.single.entries, isEmpty);
+ },
+ );
+}
diff --git a/desktop/test/usage_section_test.dart b/desktop/test/usage_section_test.dart
index eeade57c9..44dddd0b1 100644
--- a/desktop/test/usage_section_test.dart
+++ b/desktop/test/usage_section_test.dart
@@ -4,6 +4,8 @@
// A screen that renders "nothing switched on" and "nothing spent" the same is
// the screen that sends somebody looking for a bug in the scanners.
import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/settings/sections/usage_detail_panels.dart';
@@ -13,11 +15,15 @@ import 'package:harness/settings/sections/usage_section.dart';
import 'package:harness/stats/harness_stats.dart';
import 'package:harness/shared/theme/app_theme.dart';
import 'package:harness/shared/widgets/app_menu.dart';
+import 'package:harness/shared/widgets/app_select_field.dart';
import 'package:harness/usage/ledger/ledger_scanner.dart';
import 'package:harness/core/snapshot_store.dart';
import 'package:harness/usage/ledger/ledger_types.dart';
import 'package:harness/usage/ledger/usage_ledger_controller.dart';
import 'package:harness/usage/ledger/usage_ledger_store.dart';
+import 'package:harness/usage/ledger/usage_report.dart';
+
+import 'support/real_fonts.dart';
class _MemorySettings implements LocalKeyValueStore {
final values = <String, String>{};
@@ -88,6 +94,8 @@ Future<void> _pickLens(WidgetTester tester, String label) async {
}
void main() {
+ setUpAll(loadRealFonts);
+
/// A controller over fake scanners and in-memory storage — never a real
/// `~/.claude` or a real `~/.harness`, and never real disk.
UsageLedgerController controllerWith(
@@ -113,14 +121,21 @@ void main() {
WidgetTester tester,
UsageLedgerController controller, {
HarnessStats? stats,
+ Size size = const Size(1000, 900),
+ double textScale = 1,
}) async {
- tester.view.physicalSize = const Size(1000 * 2, 900 * 2);
+ tester.view.physicalSize = size * 2;
tester.view.devicePixelRatio = 2;
addTearDown(tester.view.reset);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(textScale)),
+ child: child!,
+ ),
home: Builder(
builder: (context) {
AppTheme.brightness.value = Brightness.light;
@@ -142,6 +157,63 @@ void main() {
await tester.pumpAndSettle();
}
+ testWidgets(
+ 'overview and provider ranges stay readable and keyboard operable at large text',
+ (tester) async {
+ final controller = controllerWith(const {});
+ await controller.load();
+ await controller.storeFor(LedgerProvider.claude).setEnabled(true);
+ await pumpUsage(
+ tester,
+ controller,
+ size: const Size(620, 800),
+ textScale: 1.8,
+ );
+
+ for (final provider in [null, 'Claude']) {
+ if (provider != null) {
+ await tester.scrollUntilVisible(_lensField, -250);
+ await _pickLens(tester, provider);
+ }
+ await tester.ensureVisible(_rangeField);
+ await tester.pumpAndSettle();
+ final label = tester.renderObject<RenderParagraph>(
+ find.descendant(of: _rangeField, matching: find.text('Last 30 days')),
+ );
+ expect(
+ label.getMaxIntrinsicWidth(double.infinity),
+ lessThanOrEqualTo(label.size.width + 0.1),
+ );
+ final anchor = tester.widget<InkWell>(
+ find.descendant(of: _rangeField, matching: find.byType(InkWell)),
+ );
+ anchor.focusNode!.requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<AppSelectField<UsageRange>>(_rangeField).value,
+ UsageRange.d90,
+ );
+ expect(anchor.focusNode!.hasPrimaryFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byType(AppMenuItem), findsNothing);
+ expect(
+ tester.widget<AppSelectField<UsageRange>>(_rangeField).value,
+ UsageRange.d90,
+ );
+ expect(anchor.focusNode!.hasPrimaryFocus, isTrue);
+ expect(tester.takeException(), isNull);
+ }
+ },
+ );
+
testWidgets('rests with nothing switched on, and offers the switches', (
tester,
) async {
@@ -541,6 +613,39 @@ void main() {
);
});
+ testWidgets(
+ 'an incomplete empty scan does not claim zero sessions or tokens',
+ (tester) async {
+ final controller = controllerWith({
+ LedgerProvider.claude: const LedgerScanResult(
+ status: LedgerStatus.partial,
+ message:
+ 'Some transcripts could not be read. Figures are incomplete.',
+ ),
+ });
+ await controller.load();
+ await controller.storeFor(LedgerProvider.claude).setEnabled(true);
+ await pumpUsage(tester, controller);
+ expect(find.text('Incomplete'), findsOneWidget);
+ expect(find.text('No figures available.'), findsOneWidget);
+ expect(find.text('0 sessions'), findsNothing);
+ expect(find.text('0 tokens'), findsNothing);
+ expect(find.textContaining('0 with data'), findsNothing);
+ },
+ );
+
+ testWidgets('a complete empty scan can report zero sessions', (tester) async {
+ final controller = controllerWith({
+ LedgerProvider.claude: const LedgerScanResult(),
+ });
+ await controller.load();
+ await controller.storeFor(LedgerProvider.claude).setEnabled(true);
+ await pumpUsage(tester, controller);
+ expect(find.text('0 sessions'), findsOneWidget);
+ expect(find.text('0 tokens'), findsOneWidget);
+ expect(find.text('Incomplete'), findsNothing);
+ });
+
testWidgets('an absent CLI reads as not found, never as nothing spent', (
tester,
) async {
diff --git a/desktop/test/viewer_auth_lifecycle_test.dart b/desktop/test/viewer_auth_lifecycle_test.dart
new file mode 100644
index 000000000..31488b4ad
--- /dev/null
+++ b/desktop/test/viewer_auth_lifecycle_test.dart
@@ -0,0 +1,389 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/viewer/direct_auth.dart';
+import 'package:harness/viewer/direct_auth_api.dart';
+import 'package:harness/viewer/direct_login.dart';
+
+class _Storage implements LocalKeyValueStore {
+ final values = <String, String>{};
+ Completer<void>? nextWrite;
+
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async {
+ final wait = nextWrite;
+ nextWrite = null;
+ if (wait != null) await wait.future;
+ values[key] = value;
+ }
+
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _Api extends DirectAuthApi {
+ _Api() : super(config: AppConfig.dev);
+ final refreshes = <Completer<IssuedTokens>>[];
+ final exchanges = <Completer<IssuedTokens>>[];
+ final authorizations = <Completer<({String authorizeUrl, String tx})>>[];
+ final redirects = <String>[];
+
+ @override
+ Future<IssuedTokens> refresh(
+ String refreshToken, {
+ required String autonomousEnv,
+ }) {
+ final result = Completer<IssuedTokens>();
+ refreshes.add(result);
+ return result.future;
+ }
+
+ @override
+ Future<({String authorizeUrl, String tx})> authorizeNative(String uri) {
+ redirects.add(uri);
+ final result = Completer<({String authorizeUrl, String tx})>();
+ authorizations.add(result);
+ return result.future;
+ }
+
+ @override
+ Future<IssuedTokens> exchange({
+ required String code,
+ required String state,
+ required String tx,
+ }) {
+ expect(code, 'fixture-code');
+ expect(state, 'fixture-state');
+ final result = Completer<IssuedTokens>();
+ exchanges.add(result);
+ return result.future;
+ }
+}
+
+const _old = IssuedTokens(token: 'old', refreshToken: 'old-refresh');
+const _new = IssuedTokens(token: 'new', refreshToken: 'new-refresh');
+const _renewed = IssuedTokens(
+ token: 'renewed',
+ refreshToken: 'renewed-refresh',
+);
+const _rejected = DirectAuthException('Expired.', signedOut: true);
+final _authError = isA<DirectAuthException>();
+
+Future<void> _tick() => Future<void>.delayed(Duration.zero);
+
+Future<void> _until(bool Function() ready) async {
+ for (var attempt = 0; attempt < 100 && !ready(); attempt++) {
+ await Future<void>.delayed(const Duration(milliseconds: 2));
+ }
+ expect(ready(), isTrue);
+}
+
+Future<void> _redirect(_Api api, {int index = 0}) async {
+ final client = HttpClient();
+ try {
+ final request = await client.getUrl(
+ Uri.parse(api.redirects[index]).replace(
+ queryParameters: {'code': 'fixture-code', 'state': 'fixture-state'},
+ ),
+ );
+ final response = await request.close();
+ expect(response.statusCode, HttpStatus.ok);
+ await response.drain<void>();
+ } finally {
+ client.close(force: true);
+ }
+}
+
+void main() {
+ late _Storage storage;
+ late AuthSession session;
+ late _Api api;
+ late DirectAuth auth;
+
+ setUp(() {
+ storage = _Storage();
+ session = AuthSession(storage: storage);
+ api = _Api();
+ auth = DirectAuth(session: session, api: api);
+ });
+
+ for (final fails in [false, true]) {
+ test(
+ 'old refresh ${fails ? 'failure' : 'success'} cannot replace a new account',
+ () async {
+ await auth.signIn(_old);
+ final pending = auth.accessToken(force: true);
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.refreshes.isNotEmpty);
+ await auth.signIn(_new);
+ if (fails) {
+ api.refreshes.single.completeError(_rejected);
+ } else {
+ api.refreshes.single.complete(_renewed);
+ }
+ await rejected;
+ expect(await auth.accessToken(), 'new');
+ expect(await session.refreshToken(), 'new-refresh');
+ },
+ );
+ }
+
+ test(
+ 'a refresh completed after sign-out cannot restore credentials',
+ () async {
+ await auth.signIn(_old);
+ final pending = auth.accessToken(force: true);
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.refreshes.isNotEmpty);
+ await auth.signOut();
+ api.refreshes.single.complete(_renewed);
+ await rejected;
+ expect(await auth.hasSession(), isFalse);
+ expect(storage.values, isEmpty);
+ },
+ );
+
+ test('old refresh completion cannot reset a new refresh in flight', () async {
+ await auth.signIn(_old);
+ final old = auth.accessToken(force: true);
+ final rejected = expectLater(old, throwsA(_authError));
+ await _until(() => api.refreshes.length == 1);
+ await auth.signIn(_new);
+ final current = auth.accessToken(force: true);
+ await _until(() => api.refreshes.length == 2);
+ api.refreshes.first.completeError(_rejected);
+ await rejected;
+ final joined = auth.accessToken(force: true);
+ await _tick();
+ expect(api.refreshes, hasLength(2));
+ api.refreshes.last.complete(_renewed);
+ expect(await current, 'renewed');
+ expect(await joined, 'renewed');
+ });
+
+ test(
+ 'sign-out waits behind a credential write and leaves nothing saved',
+ () async {
+ final gate = storage.nextWrite = Completer<void>();
+ final saving = auth.signIn(_old);
+ final rejected = expectLater(saving, throwsA(_authError));
+ await _until(() => storage.nextWrite == null);
+ final logout = auth.signOut();
+ gate.complete();
+ await rejected;
+ await logout;
+ expect(storage.values, isEmpty);
+ },
+ );
+
+ test('refreshes coalesce and retain unrotated refresh tokens', () async {
+ await auth.signIn(_old);
+ final first = auth.accessToken(force: true);
+ final second = auth.accessToken(force: true);
+ await _until(() => api.refreshes.isNotEmpty);
+ expect(api.refreshes, hasLength(1));
+ api.refreshes.single.complete(const IssuedTokens(token: 'renewed'));
+ expect(await first, 'renewed');
+ expect(await second, 'renewed');
+ expect(await session.refreshToken(), 'old-refresh');
+ expect(await auth.accessToken(force: true, failedToken: 'old'), 'renewed');
+ expect(api.refreshes, hasLength(1));
+ });
+
+ for (final expires in [false, true]) {
+ test(
+ '${expires ? 'expired' : 'temporary'} refresh failure handles saved credentials truthfully',
+ () async {
+ await auth.signIn(_old);
+ final pending = auth.accessToken(force: true);
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.refreshes.isNotEmpty);
+ api.refreshes.single.completeError(
+ DirectAuthException('Fixture failure.', signedOut: expires),
+ );
+ await rejected;
+ expect(await auth.hasSession(), !expires);
+ if (!expires) expect(await session.refreshToken(), 'old-refresh');
+ },
+ );
+ }
+
+ test(
+ 'cancelling while the callback server binds never opens a browser',
+ () async {
+ final login = DirectLogin(auth: auth);
+ final urls = <String>[];
+ final pending = login.login(onAuthorizeUrl: urls.add);
+ final rejected = expectLater(pending, throwsA(_authError));
+ login.cancel();
+ // Let a broken implementation complete rather than leave a five-minute wait.
+ await Future<void>.delayed(const Duration(milliseconds: 30));
+ if (api.authorizations.isNotEmpty) {
+ api.authorizations.single.complete((
+ authorizeUrl: 'https://fixture.invalid',
+ tx: 'tx',
+ ));
+ await _tick();
+ login.cancel();
+ }
+ await rejected;
+ expect(api.authorizations, isEmpty);
+ expect(urls, isEmpty);
+ expect(storage.values, isEmpty);
+ },
+ );
+
+ test('cancelled authorization cannot publish a late browser link', () async {
+ final login = DirectLogin(auth: auth);
+ final urls = <String>[];
+ final pending = login.login(onAuthorizeUrl: urls.add);
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.authorizations.isNotEmpty);
+ login.cancel();
+ api.authorizations.single.complete((
+ authorizeUrl: 'https://fixture.invalid',
+ tx: 'tx',
+ ));
+ await rejected;
+ expect(urls, isEmpty);
+ expect(storage.values, isEmpty);
+ });
+
+ for (final signOut in [false, true]) {
+ test(
+ '${signOut ? 'sign-out' : 'cancellation'} during exchange rejects its late credentials',
+ () async {
+ final login = DirectLogin(auth: auth);
+ final pending = login.login(onAuthorizeUrl: (_) {});
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.authorizations.isNotEmpty);
+ api.authorizations.single.complete((
+ authorizeUrl: 'https://fixture.invalid',
+ tx: 'tx',
+ ));
+ await _redirect(api);
+ await _until(() => api.exchanges.isNotEmpty);
+ if (signOut) {
+ await login.logout();
+ } else {
+ login.cancel();
+ }
+ api.exchanges.single.complete(_old);
+ await rejected;
+ expect(storage.values, isEmpty);
+ },
+ );
+ }
+
+ test(
+ 'cancellation during persistence removes that incomplete sign-in',
+ () async {
+ final login = DirectLogin(auth: auth);
+ final pending = login.login(onAuthorizeUrl: (_) {});
+ final rejected = expectLater(pending, throwsA(_authError));
+ await _until(() => api.authorizations.isNotEmpty);
+ api.authorizations.single.complete((
+ authorizeUrl: 'https://fixture.invalid',
+ tx: 'tx',
+ ));
+ await _redirect(api);
+ await _until(() => api.exchanges.isNotEmpty);
+ final gate = storage.nextWrite = Completer<void>();
+ api.exchanges.single.complete(_old);
+ await _until(() => storage.nextWrite == null);
+ login.cancel();
+ gate.complete();
+ await rejected;
+ expect(storage.values, isEmpty);
+ },
+ );
+
+ test('a cancelled attempt cannot remove its replacement callback', () async {
+ final login = DirectLogin(auth: auth);
+ final urls = <String>[];
+ final old = login.login(onAuthorizeUrl: urls.add);
+ final oldRejected = expectLater(old, throwsA(_authError));
+ await _until(() => api.authorizations.length == 1);
+ login.cancel();
+ final current = login.login(onAuthorizeUrl: urls.add);
+ final currentRejected = expectLater(current, throwsA(_authError));
+ await _until(() => api.authorizations.length == 2);
+ api.authorizations.first.complete((
+ authorizeUrl: 'https://fixture.invalid/old',
+ tx: 'old',
+ ));
+ await oldRejected;
+ api.authorizations.last.complete((
+ authorizeUrl: 'https://fixture.invalid/new',
+ tx: 'new',
+ ));
+ await _until(() => urls.isNotEmpty);
+ login.cancel();
+ await currentRejected;
+ expect(urls, ['https://fixture.invalid/new']);
+ expect(storage.values, isEmpty);
+ });
+
+ test('token readers wait for the whole saved session', () async {
+ final gate = storage.nextWrite = Completer<void>();
+ final saving = auth.signIn(_new);
+ await _until(() => storage.nextWrite == null);
+ var read = false;
+ final reading = auth.accessToken().then((value) {
+ read = true;
+ return value;
+ });
+ final present = auth.hasSession();
+ await _tick();
+ expect(read, isFalse);
+ gate.complete();
+ await saving;
+ expect(await reading, 'new');
+ expect(await present, isTrue);
+ expect(await session.refreshToken(), 'new-refresh');
+ });
+
+ test('cancelled persistence cannot clear a replacement sign-in', () async {
+ var current = true;
+ final gate = storage.nextWrite = Completer<void>();
+ final old = auth.signIn(_old, stillCurrent: () => current);
+ final rejected = expectLater(old, throwsA(_authError));
+ await _until(() => storage.nextWrite == null);
+ current = false;
+ final replacement = auth.signIn(_new);
+ gate.complete();
+ await rejected;
+ await replacement;
+ expect(await auth.accessToken(), 'new');
+ expect(await session.refreshToken(), 'new-refresh');
+ });
+
+ test(
+ 'a successful browser exchange saves its session and closes the listener',
+ () async {
+ final login = DirectLogin(auth: auth);
+ final urls = <String>[];
+ final pending = login.login(onAuthorizeUrl: urls.add);
+ await _until(() => api.authorizations.isNotEmpty);
+ api.authorizations.single.complete((
+ authorizeUrl: 'https://fixture.invalid',
+ tx: 'tx',
+ ));
+ await _redirect(api);
+ await _until(() => api.exchanges.isNotEmpty);
+ api.exchanges.single.complete(_new);
+ await pending;
+ expect(urls, ['https://fixture.invalid']);
+ expect(await auth.accessToken(), 'new');
+ // Cancel after completion must leave the saved session alone.
+ login.cancel();
+ expect(await auth.accessToken(), 'new');
+ },
+ );
+}
diff --git a/desktop/test/web_pane_test.dart b/desktop/test/web_pane_test.dart
index bc42ee14c..9adceb73f 100644
--- a/desktop/test/web_pane_test.dart
+++ b/desktop/test/web_pane_test.dart
@@ -3,6 +3,7 @@
// once the person closes it, and taken down with the agent.
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/app_state.dart';
@@ -327,11 +328,18 @@ void main() {
expect(find.text('http://127.0.0.1:4179/'), findsOneWidget);
// Its own close control, and no way to end an agent from it.
expect(find.byTooltip('Close viewer'), findsOneWidget);
- expect(
- find.byTooltip('Stop Harness'),
- findsOneWidget,
- reason: 'the terminal keeps its own',
+ // This split is narrow: the terminal keeps its actions in the menu.
+ final actions = tester.widget<IconButton>(
+ find.widgetWithIcon(IconButton, Icons.more_horiz),
);
+ actions.focusNode!.requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(find.text('Stop Agent'), findsOneWidget);
+ expect(find.text('Hide viewer'), findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
// The verdict is the viewer's to show — chip and strip in its header,
// nothing on the terminal's — and the terminal's header carries the
// control that hides and shows the viewer.
@@ -368,7 +376,6 @@ void main() {
expect(find.text('Build'), findsNothing);
expect(find.text('1 warning'), findsNothing, reason: 'the phase wins');
expect(find.textContaining('· Viewer'), findsNothing);
- expect(find.byTooltip('Hide viewer'), findsOneWidget);
await tester.tap(find.byTooltip('Close viewer'));
await tester.pump();
expect(_viewers(app), isEmpty);
diff --git a/desktop/test/welcome_entry_layout_test.dart b/desktop/test/welcome_entry_layout_test.dart
index 9f03f49a2..6f9ed4a12 100644
--- a/desktop/test/welcome_entry_layout_test.dart
+++ b/desktop/test/welcome_entry_layout_test.dart
@@ -6,6 +6,7 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/state/swarm_search.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'support/real_fonts.dart';
@@ -94,14 +95,14 @@ void main() {
await tester.pump();
}
final field = find.byKey(const ValueKey('harness-start-search'));
- final create = find.byKey(const ValueKey('harness-start-new'));
- final open = find.byKey(const ValueKey('harness-start-open'));
+ final create = find.byKey(const ValueKey('harness-start-new-pane'));
+ final open = find.byKey(const ValueKey('harness-start-new-tab'));
final device = find.byKey(const ValueKey('harness-device-link'));
final store = find.byKey(const ValueKey('harness-store-link'));
expect(find.text('OpenHarness'), findsNothing);
expect(
tester.widget<TextField>(field).decoration!.hintText,
- 'Find a harness',
+ kHarnessPickerHint,
);
expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
expect(find.byType(ListTile), findsNothing);
@@ -169,6 +170,8 @@ void main() {
await tester.ensureVisible(create);
expect(create.hitTestable(), findsOneWidget);
await tester.tap(create);
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(results, findsNothing);
diff --git a/desktop/test/workspace_account_lifecycle_test.dart b/desktop/test/workspace_account_lifecycle_test.dart
new file mode 100644
index 000000000..66e73b2df
--- /dev/null
+++ b/desktop/test/workspace_account_lifecycle_test.dart
@@ -0,0 +1,262 @@
+import 'dart:async';
+import 'dart:convert';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/api/api_client.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/auth/cli_login.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/pane_layout_store.dart';
+import 'package:harness/state/pane_preset.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/ws/local_cli_discovery.dart';
+
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show MemoryStore;
+
+class WorkspaceAccountLogin extends CliLogin {
+ var logins = 0;
+ @override
+ Future<void> logout() async {}
+ @override
+ Future<void> login({required void Function(String) onAuthorizeUrl}) async {
+ logins++;
+ }
+
+ @override
+ Future<CliAuthStatus> checkStatus() async =>
+ const CliAuthStatus(loggedIn: false);
+}
+
+class _Discovery extends LocalCliDiscovery {
+ _Discovery() : super(config: AppConfig.dev);
+ @override
+ Future<LocalCliProbe> ensureRunning({
+ Duration timeout = const Duration(seconds: 15),
+ Duration readyTimeout = LocalCliDiscovery.defaultReadyTimeout,
+ }) async => const LocalCliProbe.down('fixture signed out');
+ @override
+ Future<String?> computerId() async => null;
+ @override
+ Future<LocalCliEndpoint?> discover({String? expectedComputerId}) async =>
+ null;
+}
+
+class _Api extends ApiClient {
+ _Api()
+ : super(
+ config: AppConfig.dev,
+ session: AuthSession(storage: MemoryStore()),
+ );
+ var inventoryRequests = 0;
+ @override
+ Future<Map<String, dynamic>?> me() async => {
+ 'user': {'id': 'fixture-account', 'email': '[email protected]'},
+ };
+ @override
+ Future<List<Machine>> machines() async {
+ inventoryRequests++;
+ return [];
+ }
+}
+
+class WorkspaceAccountFixture extends AppNotifier {
+ WorkspaceAccountFixture(MemoryStore storage, this.cli)
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(storage: MemoryStore()),
+ cliLogin: cli,
+ localCliDiscovery: _Discovery(),
+ paneLayoutStore: PaneLayoutStore(storage: storage),
+ ) {
+ api = _Api();
+ status = AppStatus.authenticated;
+ }
+ final WorkspaceAccountLogin cli;
+ int get inventoryRequests => (api as _Api).inventoryRequests;
+ var expired = false;
+ @override
+ Future<void> ensureCliDaemonReady() async {
+ if (expired) await super.ensureCliDaemonReady();
+ }
+
+ Future<void> expire() async {
+ expired = true;
+ await ensureCliDaemonReady();
+ expired = false;
+ }
+}
+
+class _HeldStore extends MemoryStore {
+ String? blocked;
+ final reading = Completer<void>();
+ final answer = Completer<String?>();
+ @override
+ Future<String?> read(String key) {
+ if (key == blocked) {
+ blocked = null;
+ reading.complete();
+ return answer.future;
+ }
+ return super.read(key);
+ }
+}
+
+Future<void> arrangeAccountWorkspace(WorkspaceAccountFixture app) async {
+ app.renameSwarm(app.activeSwarmId, 'Research');
+ app.adoptSessionForTest(terminal('a', []));
+ final second = app.adoptSessionForTest(terminal('b', []));
+ app.togglePinPane(second.id);
+ app.setPreset(2, PanePreset.rows);
+ app.toggleZoomPane();
+ app.newSwarm(name: 'Build');
+ app.adoptSessionForTest(terminal('c', []));
+ // Adopting fixture sessions does not write layout until an actual UI action.
+ app.renameSwarm(app.activeSwarmId, 'Build');
+ await app.flushPaneLayout();
+}
+
+void main() {
+ for (final expires in [false, true]) {
+ test(
+ '${expires ? 'expiry' : 'sign-out'} restores all tabs and their arrangement on sign-in',
+ () async {
+ final storage = MemoryStore();
+ final app = WorkspaceAccountFixture(storage, WorkspaceAccountLogin());
+ addTearDown(app.dispose);
+ await arrangeAccountWorkspace(app);
+ final saved = storage.values['swarm_layout_v1'];
+ final selected = app.activeSwarmId;
+ if (expires) {
+ await app.expire();
+ } else {
+ await app.logout();
+ }
+ expect(app.status, AppStatus.unauthenticated);
+ expect(app.allPanes, isEmpty);
+ expect(app.swarms, hasLength(1));
+ expect(storage.values['swarm_layout_v1'], saved);
+ await app.login();
+ expect(app.status, AppStatus.authenticated);
+ expect(app.swarms.map((s) => s.name), ['Research', 'Build']);
+ expect(app.allPanes.map((p) => p.agentId), ['a', 'b', 'c']);
+ expect(app.activeSwarmId, selected);
+ final research = app.swarms.first;
+ expect(research.focusedPaneId, research.panes.last.id);
+ expect(research.zoomedPaneId, research.panes.last.id);
+ expect(research.presets[2], PanePreset.rows);
+ expect(research.pinnedSlots.keys, [research.panes.last.id]);
+ },
+ );
+ }
+
+ test(
+ 'runtime expiry clears machine inventory and recently closed work',
+ () async {
+ final app = WorkspaceAccountFixture(
+ MemoryStore(),
+ WorkspaceAccountLogin(),
+ );
+ addTearDown(app.dispose);
+ const machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Old machine',
+ );
+ app.machines = [machine];
+ app.machineStates['m'] = MachineState(machine);
+ app.machinesAreStale = true;
+ final pane = app.adoptSessionForTest(terminal('closed', []));
+ await app.closePane(pane.id);
+ expect(app.closedHistory, isNotEmpty);
+ await app.expire();
+ expect(app.machines, isEmpty);
+ expect(app.machineStates, isEmpty);
+ expect(app.machinesAreStale, isFalse);
+ expect(app.closedHistory, isEmpty);
+ expect(app.lastError, contains('Sign in again'));
+ },
+ );
+
+ for (final key in [
+ 'swarm_layout_v1',
+ 'terminal_pane_presets',
+ 'terminal_pane_layout',
+ ]) {
+ for (final expires in [false, true]) {
+ test(
+ 'late $key cannot restore work after ${expires ? 'expiry' : 'sign-out'}',
+ () async {
+ final storage = _HeldStore()..blocked = key;
+ final app = WorkspaceAccountFixture(storage, WorkspaceAccountLogin());
+ addTearDown(app.dispose);
+ final restoring = app.restorePaneLayoutForTest();
+ await storage.reading.future;
+ if (expires) {
+ await app.expire();
+ } else {
+ await app.logout();
+ }
+ storage.answer.complete(switch (key) {
+ 'swarm_layout_v1' => jsonEncode({
+ 'version': 1,
+ 'activeId': 'private',
+ 'swarms': [
+ {
+ 'id': 'private',
+ 'name': 'Old work',
+ 'panes': [
+ {'machineId': 'm', 'agentId': 'old'},
+ ],
+ },
+ ],
+ }),
+ 'terminal_pane_presets' => '{"2":"rows"}',
+ _ => '[{"machineId":"m","agentId":"old"}]',
+ });
+ await restoring;
+ expect(app.allPanes, isEmpty);
+ expect(app.panePresets, isEmpty);
+ expect(app.swarms.single.name, isNot('Old work'));
+ },
+ );
+ }
+ }
+
+ for (final cancel in [false, true]) {
+ test(
+ 'sign-in ${cancel ? 'can be cancelled while waiting for' : 'waits for'} expired terminal cleanup',
+ () async {
+ final cli = WorkspaceAccountLogin();
+ final app = WorkspaceAccountFixture(MemoryStore(), cli);
+ addTearDown(app.dispose);
+ final closed = Completer<bool>();
+ app.adoptSessionForTest(
+ TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Fixture',
+ engineId: 'codex',
+ send: (type, _) =>
+ type == 'terminal_close' ? closed.future : Future.value(true),
+ sendBinary: (_) async => true,
+ )..streamId = 'fixture',
+ );
+ await app.expire();
+ final login = app.login();
+ await Future<void>.delayed(Duration.zero);
+ expect(cli.logins, 0);
+ if (cancel) app.cancelLogin();
+ closed.complete(true);
+ await login;
+ expect(cli.logins, cancel ? 0 : 1);
+ expect(
+ app.status,
+ cancel ? AppStatus.unauthenticated : AppStatus.authenticated,
+ );
+ },
+ );
+ }
+}
diff --git a/desktop/test/workspace_expiry_screen_test.dart b/desktop/test/workspace_expiry_screen_test.dart
new file mode 100644
index 000000000..2cf6175d7
--- /dev/null
+++ b/desktop/test/workspace_expiry_screen_test.dart
@@ -0,0 +1,94 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'signout_recovery_test.dart' show signOutHost;
+import 'support/real_fonts.dart';
+import 'swarm_state_test.dart' show MemoryStore;
+import 'workspace_account_lifecycle_test.dart'
+ show WorkspaceAccountFixture, WorkspaceAccountLogin;
+
+void main() {
+ setUpAll(() async {
+ await loadRealFonts();
+ await (FontLoader(
+ 'MaterialIcons',
+ )..addFont(rootBundle.load('fonts/MaterialIcons-Regular.otf'))).load();
+ });
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 1.8]) {
+ testWidgets(
+ 'expired session explains the next step in $brightness at $scale',
+ (tester) async {
+ tester.view.physicalSize = const Size(880, 560);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final cli = WorkspaceAccountLogin();
+ final app = WorkspaceAccountFixture(MemoryStore(), cli);
+ var disposed = false;
+ void disposeApp() {
+ if (disposed) return;
+ disposed = true;
+ app.dispose();
+ }
+
+ addTearDown(disposeApp);
+ await app.expire();
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: signOutHost(app, brightness: brightness, scale: scale),
+ ),
+ );
+ await tester.pump();
+ expect(find.text('Sign in'), findsOneWidget);
+ expect(find.text('Could not sign in'), findsNothing);
+ expect(find.text('Try again'), findsNothing);
+ final notice = find.textContaining('You were signed out');
+ expect(notice, findsOneWidget);
+ expect(tester.getRect(notice).bottom, lessThanOrEqualTo(544));
+ expect(
+ tester.getRect(find.text('Sign in')).top,
+ greaterThanOrEqualTo(16),
+ );
+ final directory = Platform.environment['HARNESS_AUTH_CAPTURE_DIR'];
+ if (directory != null) {
+ await tester.runAsync(
+ () => precacheImage(
+ const AssetImage('assets/app_icon.png'),
+ boundary.currentContext!,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 300));
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(directory).create(recursive: true);
+ await File('$directory/expired-${brightness.name}-$scale.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(cli.logins, 1);
+ expect(app.sessionExpired, isFalse);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ disposeApp();
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/workspace_learning_test.dart b/desktop/test/workspace_learning_test.dart
new file mode 100644
index 000000000..53eacd841
--- /dev/null
+++ b/desktop/test/workspace_learning_test.dart
@@ -0,0 +1,82 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/state/workspace_learning.dart';
+
+class LearningMemoryStore implements LocalKeyValueStore {
+ final values = <String, String>{};
+ Completer<String?>? pending;
+ @override
+ Future<String?> read(String key) async =>
+ pending == null ? values[key] : pending!.future;
+ @override
+ Future<void> write(String key, String value) async {
+ values[key] = value;
+ }
+
+ @override
+ Future<void> delete(String key) async {
+ values.remove(key);
+ }
+}
+
+void main() {
+ test(
+ 'quick start follows work, resumes after restart, and stays dismissed',
+ () async {
+ final store = LearningMemoryStore();
+ final first = WorkspaceLearning(storage: store);
+ addTearDown(first.dispose);
+ await first.load();
+ expect(first.offer, isTrue);
+ first.observe(agents: 2, zoomed: true);
+ expect(first.completed, isEmpty, reason: 'The guide is opt-in');
+ first.start();
+ first.observe(agents: 0, zoomed: false);
+ first.commandSearchOpened();
+ expect(first.next, WorkspaceLesson.agent);
+ first.observe(agents: 1, zoomed: false);
+ expect(first.next, WorkspaceLesson.pane);
+ first.pause();
+ await first.flush();
+ final resumed = WorkspaceLearning(storage: store);
+ addTearDown(resumed.dispose);
+ await resumed.load();
+ expect(resumed.offer, isFalse);
+ expect(resumed.active, isFalse);
+ expect(resumed.next, WorkspaceLesson.pane);
+ resumed.start();
+ resumed.observe(agents: 2, zoomed: false);
+ expect(resumed.next, WorkspaceLesson.zoom);
+ resumed.observe(agents: 2, zoomed: true);
+ resumed.commandSearchOpened();
+ expect(resumed.finished, isTrue);
+ await resumed.flush();
+ resumed.start();
+ expect(
+ resumed.next,
+ WorkspaceLesson.agent,
+ reason: 'The whole guide is repeatable',
+ );
+ },
+ );
+
+ test(
+ 'late storage reads cannot undo an explicit start or dismissal',
+ () async {
+ final store = LearningMemoryStore()..pending = Completer<String?>();
+ final learning = WorkspaceLearning(storage: store);
+ addTearDown(learning.dispose);
+ final loaded = learning.load();
+ learning.start();
+ learning.observe(agents: 1, zoomed: false);
+ learning.pause();
+ store.pending!.complete('{"active":true,"completed":[]}');
+ await loaded;
+ expect(learning.active, isFalse);
+ expect(learning.next, WorkspaceLesson.pane);
+ await learning.flush();
+ },
+ );
+}
diff --git a/desktop/test/workspace_start_guide_test.dart b/desktop/test/workspace_start_guide_test.dart
new file mode 100644
index 000000000..892ffb18a
--- /dev/null
+++ b/desktop/test/workspace_start_guide_test.dart
@@ -0,0 +1,609 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/auth/auth_session.dart';
+import 'package:harness/core/config.dart';
+import 'package:harness/core/engine_availability.dart';
+import 'package:harness/core/local_key_value_store.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/shortcuts/keyboard_practice.dart';
+import 'package:harness/shortcuts/keymap.dart';
+import 'package:harness/shortcuts/keymap_native.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/first_harness_launch.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/pane_arrangement.dart';
+import 'package:harness/widgets/new_harness_box.dart';
+import 'package:harness/widgets/workspace_start_guide.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'swarm_screen_test.dart' show terminal;
+
+class _Memory implements LocalKeyValueStore {
+ final values = <String, String>{};
+ @override
+ Future<String?> read(String key) async => values[key];
+ @override
+ Future<void> write(String key, String value) async => values[key] = value;
+ @override
+ Future<void> delete(String key) async => values.remove(key);
+}
+
+class _FirstApp extends AppNotifier {
+ _FirstApp()
+ : super(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ ) {
+ status = AppStatus.authenticated;
+ const local = Machine(
+ machineId: 'm',
+ name: 'This Mac',
+ authMode: MachineAuthMode.remote,
+ );
+ machines = [local];
+ machineStates['m'] = MachineState(local)
+ ..localOnly = true
+ ..nodeOnline = true
+ ..agentLoadStatus = AgentLoadStatus.loaded;
+ }
+ Completer<void>? detection;
+ List<String> installed = ['codex'];
+ final launches =
+ <
+ ({
+ String engine,
+ ProjectFolderRequest? project,
+ HarnessPlacement? placement,
+ })
+ >[];
+ @override
+ Future<void> probeEngines(String machineId, {bool force = false}) async {
+ await detection?.future;
+ machineStates[machineId]!.engines.replace([
+ for (final engine in ['claude', 'codex', 'opencode'])
+ EngineAvailability(
+ engine: engine,
+ installed: installed.contains(engine),
+ ),
+ ]);
+ notifyListeners();
+ }
+
+ @override
+ Future<void> probeDsh(String machineId, {bool force = false}) async {}
+ @override
+ Future<Map<String, dynamic>> listRemoteFolder(
+ String machineId,
+ String? path,
+ ) async => {'path': path ?? '/Users/developer', 'entries': []};
+ @override
+ Future<String?> createAgent(
+ String machineId, {
+ required String engine,
+ required String? folder,
+ ProjectFolderRequest? projectFolder,
+ bool bypassPermission = true,
+ String? permissionMode,
+ String? codexHome,
+ String? dsh,
+ String? prompt,
+ String? name,
+ String? agent,
+ String? swarmId,
+ PaneSplitRequest? split,
+ AgentCreationAttempt? attempt,
+ HarnessPlacement? placement,
+ }) async {
+ launches.add((
+ engine: engine,
+ project: projectFolder,
+ placement: placement,
+ ));
+ adoptSessionForTest(terminal('first', []));
+ return null;
+ }
+}
+
+Future<void> _mount(
+ WidgetTester tester,
+ _FirstApp app,
+ FirstHarnessLaunch entry, {
+ bool nativeTabs = false,
+}) async {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = const Size(1280, 800);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ addTearDown(tester.view.resetPhysicalSize);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: SwarmScreen(
+ notifier: app,
+ nativeTabs: nativeTabs,
+ firstLaunch: entry,
+ ),
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 150));
+}
+
+void main() {
+ setUp(() => newHarnessOpensInBox = true);
+ tearDown(() => newHarnessOpensInBox = false);
+
+ test(
+ 'a decision made during preference loading survives and persists',
+ () async {
+ final storage = _Memory();
+ final first = FirstHarnessLaunch(storage: storage);
+ final loading = first.load();
+ first.handle();
+ await loading;
+ await first.flush();
+ expect(first.handled, isTrue);
+ final again = FirstHarnessLaunch(storage: storage);
+ await again.load();
+ expect(again.handled, isTrue);
+ },
+ );
+
+ testWidgets(
+ 'first entry detects the installed agent and starts once on Enter',
+ (tester) async {
+ final app = _FirstApp()..detection = Completer<void>();
+ addTearDown(app.dispose);
+ final entry = FirstHarnessLaunch();
+ await _mount(tester, app, entry);
+ final box = tester
+ .widget<NewHarnessBox>(find.byType(NewHarnessBox))
+ .controller;
+ expect(box.detectingAgent, isTrue);
+ expect(find.text('Start'), findsOneWidget);
+ expect(find.text('Detecting installed agents…'), findsOneWidget);
+ final start = find.byKey(const ValueKey('new-harness-field-create'));
+ expect(tester.widget<InkWell>(start).onTap, isNull);
+ await tester.tap(start);
+ await tester.pump();
+ expect(app.launches, isEmpty);
+ expect(box.projectLabel, startsWith('~/harnesses/claude-'));
+ expect(box.projectFolderRequest!.isGenerated, isTrue);
+ expect(app.launches, isEmpty);
+ await key(tester, LogicalKeyboardKey.enter);
+ expect(app.launches, isEmpty);
+ app.detection!.complete();
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(box.engine, 'codex');
+ expect(find.text('Start'), findsOneWidget);
+ expect(find.text('New Harness / New Tab'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(app.launches, hasLength(1));
+ expect(app.launches.single.engine, 'codex');
+ expect(app.launches.single.project!.name, startsWith('codex-'));
+ expect(app.launches.single.project!.isGenerated, isTrue);
+ expect(app.launches.single.placement, HarnessPlacement.newTab);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'Escape stays dismissed during a visit; reopening offers the starter',
+ (tester) async {
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ final storage = _Memory();
+ final entry = FirstHarnessLaunch(storage: storage);
+ await _mount(tester, app, entry);
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ await app.probeEngines('m');
+ await tester.pump(const Duration(milliseconds: 200));
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byType(WorkspaceStartGuide), findsOneWidget);
+ await entry.flush();
+ await tester.pumpWidget(const SizedBox());
+ await _mount(tester, app, FirstHarnessLaunch(storage: storage));
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(
+ find.text('⌘/ All Keyboard Shortcuts').hitTestable(),
+ findsOneWidget,
+ );
+ await key(tester, LogicalKeyboardKey.slash, cmd: true);
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets(
+ 'an empty tab with an existing harness opens search once per visit',
+ (tester) async {
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'saved',
+ engine: 'codex',
+ name: 'Existing work',
+ terminalAvailable: true,
+ ),
+ ];
+ await _mount(tester, app, FirstHarnessLaunch());
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsOneWidget);
+ expect(find.text('Existing work'), findsOneWidget);
+ expect(find.byType(WorkspaceStartGuide).hitTestable(), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.escape);
+ app.notifyListeners();
+ await tester.pump();
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ testWidgets('restored work bypasses the automatic starter', (tester) async {
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ final entry = FirstHarnessLaunch();
+ await _mount(tester, app, entry);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(app.focusedPane, same(pane));
+ expect(entry.handled, isTrue);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ for (final native in [false, true]) {
+ testWidgets(
+ 'onboarding review reuses a welcome tab and preserves live work (native=$native)',
+ (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ (_) async => true,
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ channel,
+ null,
+ ),
+ );
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = [
+ for (final id in ['a0', 'a1'])
+ Agent(
+ id: id,
+ name: 'Work $id',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ final first = app.activeSwarm;
+ app.renameSwarm(first.id, 'Work');
+ final session = terminal('a0', [])
+ ..terminal.write('Keep this output\r\n');
+ final pane = app.adoptSessionForTest(session);
+ app.newSwarm(name: 'Research');
+ final second = app.activeSwarm;
+ final other = app.adoptSessionForTest(terminal('a1', []));
+ app.selectSwarm(first.id);
+ await _mount(tester, app, FirstHarnessLaunch(), nativeTabs: native);
+ final view = find.byWidgetPredicate(
+ (widget) =>
+ widget is TerminalView && widget.terminal == session.terminal,
+ skipOffstage: false,
+ );
+ final renderer = tester.state<TerminalViewState>(view);
+ await tester.tap(view.hitTestable());
+ await tester.pump();
+
+ Future<void> review() async {
+ if (native) {
+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ const MethodCall('keymapCommand', {
+ 'command': 'app.onboarding_review',
+ }),
+ ),
+ (_) {},
+ );
+ await tester.pump();
+ } else {
+ await key(
+ tester,
+ LogicalKeyboardKey.keyO,
+ cmd: true,
+ alt: true,
+ shift: true,
+ );
+ }
+ await tester.pump(const Duration(milliseconds: 150));
+ }
+
+ await review();
+ final welcome = app.activeSwarm;
+ expect(welcome.name, 'Welcome');
+ expect(app.swarms, [first, second, welcome]);
+ expect(app.allPanes, [pane, other]);
+ expect(find.byType(WorkspaceStartGuide).hitTestable(), findsOneWidget);
+ expect(find.byType(NewHarnessBox), findsNothing);
+ expect(
+ find.byKey(const ValueKey('swarm-search-input')),
+ findsOneWidget,
+ );
+ void expectGuideAboveDock(Finder dock) {
+ final drawing = tester.getRect(
+ find.byKey(const ValueKey('workspace-welcome-diagram')).last,
+ );
+ final shortcuts = tester.getRect(
+ find.byKey(const ValueKey('workspace-all-shortcuts')).last,
+ );
+ expect(drawing.top, greaterThanOrEqualTo(0));
+ expect(drawing.bottom, lessThanOrEqualTo(tester.getTopLeft(dock).dy));
+ expect(
+ shortcuts.bottom,
+ lessThanOrEqualTo(tester.getTopLeft(dock).dy),
+ );
+ expect(tester.takeException(), isNull);
+ }
+
+ final searchDock = find.byKey(const ValueKey('swarm-search-results'));
+ expectGuideAboveDock(searchDock);
+ tester.view.physicalSize = const Size(960, 640);
+ await tester.pump();
+ expectGuideAboveDock(searchDock);
+ expect(tester.state<TerminalViewState>(view), same(renderer));
+ expect(app.launches, isEmpty);
+
+ await key(tester, LogicalKeyboardKey.keyN, cmd: true);
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ expectGuideAboveDock(find.byKey(const ValueKey('new-harness-box')));
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump();
+ await review();
+ expect(
+ find.byKey(const ValueKey('swarm-search-input')),
+ findsOneWidget,
+ );
+ expect(app.activeSwarm, same(welcome));
+ expect(app.swarms, [first, second, welcome]);
+ app.selectSwarm(first.id);
+ await tester.pump();
+ await review();
+ expect(app.activeSwarm, same(welcome));
+ expect(app.swarms, [first, second, welcome]);
+
+ await key(tester, LogicalKeyboardKey.escape);
+ await key(tester, LogicalKeyboardKey.keyW, cmd: true);
+ await tester.pump();
+ expect(app.swarms, [first, second]);
+ app.selectSwarm(first.id);
+ await tester.pump();
+ expect(app.focusedPane, same(pane));
+ expect(pane.session, same(session));
+ expect(tester.state<TerminalViewState>(view), same(renderer));
+ expect(
+ session.terminal.buffer.lines[0].getText(),
+ contains('Keep this output'),
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
+ testWidgets('reviewing Welcome with no harnesses reopens New Harness', (
+ tester,
+ ) async {
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ await _mount(tester, app, FirstHarnessLaunch());
+ await key(tester, LogicalKeyboardKey.escape);
+ for (var visit = 0; visit < 2; visit++) {
+ await key(
+ tester,
+ LogicalKeyboardKey.keyO,
+ cmd: true,
+ alt: true,
+ shift: true,
+ );
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(app.activeSwarm.name, 'Welcome');
+ expect(app.swarms.where((tab) => tab.name == 'Welcome'), hasLength(1));
+ expect(find.byType(NewHarnessBox), findsOneWidget);
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
+ expect(
+ tester
+ .getBottomRight(
+ find.byKey(const ValueKey('workspace-welcome-diagram')).last,
+ )
+ .dy,
+ lessThanOrEqualTo(
+ tester.getTopLeft(find.byKey(const ValueKey('new-harness-box'))).dy,
+ ),
+ );
+ expect(app.launches, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ await tester.pump();
+ }
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets(
+ 'onboarding review key is native-exported but absent from help and practice',
+ (tester) async {
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final contexts = nativeKeymapSnapshot(map)['contexts'] as Map;
+ for (final context in ['workspace', 'terminal']) {
+ final binding = (contexts[context] as List).cast<Map>().singleWhere(
+ (binding) => binding['command'] == 'app.onboarding_review',
+ );
+ expect(binding['keys'], ['alt+cmd+shift+o']);
+ }
+ expect(
+ keyboardLessons(map)
+ .any((lesson) => lesson.command == 'app.onboarding_review'),
+ isFalse,
+ );
+ await tester.pumpWidget(
+ MaterialApp(
+ home: KeymapProvider(
+ keymap: map,
+ child: Builder(
+ builder: (context) {
+ expect(
+ effectiveShortcutRows(
+ context,
+ KeymapContext.workspace,
+ ).any((row) => row.label == 'Review onboarding'),
+ isFalse,
+ );
+ return const SizedBox();
+ },
+ ),
+ ),
+ ),
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ test('installed saved preference wins; explicit editing wins over late discovery', () async {
+ final app = _FirstApp()..installed = ['claude', 'codex'];
+ addTearDown(app.dispose);
+ await app.agentPreference.select('codex');
+ final first = NewHarnessController(
+ app,
+ machineId: 'm',
+ firstRun: true,
+ autoProject: true,
+ );
+ await Future<void>.delayed(Duration.zero);
+ expect(first.engine, 'codex');
+ first.dispose();
+ app.detection = Completer<void>();
+ final second = NewHarnessController(
+ app,
+ machineId: 'm',
+ firstRun: true,
+ autoProject: true,
+ );
+ second.focusField(NewHarnessField.agent);
+ second.setQuery('Claude');
+ second.accept();
+ app.detection!.complete();
+ await Future<void>.delayed(Duration.zero);
+ expect(second.engine, 'claude');
+ second.dispose();
+ });
+
+ testWidgets(
+ 'the keyboard drawing follows remaps and fits narrow, scaled layouts',
+ (tester) async {
+ final map = MemoryKeymap()
+ ..apply(
+ '{"bindings":[{"keys":"cmd+t","command":null},{"keys":"cmd+y","command":"swarm.new"}]}',
+ );
+ addTearDown(map.dispose);
+ final calls = <String>[];
+ for (final brightness in Brightness.values) {
+ for (final size in [const Size(1280, 800), const Size(390, 650)]) {
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: MediaQuery(
+ data: MediaQueryData(
+ size: size,
+ textScaler: TextScaler.linear(size.width < 500 ? 1.8 : 1),
+ ),
+ child: KeymapProvider(
+ keymap: map,
+ child: WorkspaceStartGuide(
+ onShortcuts: () => calls.add('keys'),
+ ),
+ ),
+ ),
+ ),
+ );
+ expect(tester.takeException(), isNull);
+ final tab = find.text('⌘Y New Tab');
+ expect(tab, findsOneWidget);
+ await tester.tap(tab);
+ expect(
+ calls,
+ isEmpty,
+ reason: 'Annotations explain shortcuts without acting as buttons',
+ );
+ expect(find.byType(TextButton), findsOneWidget);
+ }
+ }
+ tester.view.resetPhysicalSize();
+ tester.view.resetDevicePixelRatio();
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
+ final output = Platform.environment['GUIDE_RENDER_DIR'];
+ testWidgets('render first entry guide', skip: output == null, (tester) async {
+ await tester.runAsync(() async {
+ for (final family in [
+ 'Menlo',
+ 'monospace',
+ '.AppleSystemUIFontMonospaced',
+ ]) {
+ final loader = FontLoader(family);
+ final bytes = await File('/System/Library/Fonts/Menlo.ttc')
+ .readAsBytes();
+ loader.addFont(Future.value(ByteData.view(bytes.buffer)));
+ await loader.load();
+ }
+ });
+ for (final hasHarnesses in [false, true]) {
+ final app = _FirstApp();
+ addTearDown(app.dispose);
+ if (hasHarnesses) {
+ app.machineStates['m']!.agents = [
+ for (var index = 0; index < 20; index++)
+ Agent(
+ id: 'saved-$index',
+ name: 'Existing harness $index',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ ];
+ }
+ await _mount(tester, app, FirstHarnessLaunch());
+ final name = hasHarnesses ? 'welcome-search' : 'first-harness';
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$output/$name.png')),
+ );
+ tester.view.physicalSize = const Size(960, 640);
+ await tester.pump();
+ await expectLater(
+ find.byType(MaterialApp),
+ matchesGoldenFile(Uri.file('$output/$name-compact.png')),
+ );
+ await tester.pumpWidget(const SizedBox());
+ }
+ });
+}
diff --git a/desktop/test/ws_pool_ownership_test.dart b/desktop/test/ws_pool_ownership_test.dart
new file mode 100644
index 000000000..e1bfc7eaf
--- /dev/null
+++ b/desktop/test/ws_pool_ownership_test.dart
@@ -0,0 +1,42 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/ws/ws_pool.dart';
+
+void main() {
+ for (final replacement in [false, true]) {
+ test(
+ '${replacement ? 'replaced' : 'closed'} connection cannot publish late callbacks',
+ () async {
+ final events = <String>[];
+ final pool = WsPool(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ // Never resolves: no actual network connection or credentials.
+ accessTokenProvider: (_, _) => Completer<String>().future,
+ onAuthFailure: (message) => events.add('auth:$message'),
+ onLocalFailure: (_, code, _) => events.add('local:$code'),
+ onStatus: (_, status) => events.add('status:${status.name}'),
+ onEvent: (_, event) => events.add('event:${event['type']}'),
+ );
+ addTearDown(pool.closeAll);
+ final old = pool.connFor('machine');
+ final closing = pool.closeMachine('machine');
+ final current = replacement ? pool.connFor('machine') : null;
+ events.clear();
+ await closing;
+ old.onAuthFailure('old');
+ old.onLocalFailure!(4404, 'old');
+ await old.onEvent({'type': 'old'});
+ old.onStatus(ConnectionStatus.disconnected);
+ expect(events, isEmpty);
+ if (current != null) {
+ current.onStatus(ConnectionStatus.connected);
+ await current.onEvent({'type': 'current'});
+ expect(events, ['status:connected', 'event:current']);
+ }
+ },
+ );
+ }
+}
diff --git a/desktop/third_party/xterm/README.autonomous.md b/desktop/third_party/xterm/README.autonomous.md
index 0e9ecb756..e7b1ce970 100644
--- a/desktop/third_party/xterm/README.autonomous.md
+++ b/desktop/third_party/xterm/README.autonomous.md
@@ -13,6 +13,17 @@ fix and the regression in `test/terminal_session_test.dart` passes against it.
## Local patches
+- **Linux clipboard and Meta keys leave shell editing intact**
+ (`lib/src/ui/shortcut/shortcuts.dart`, `lib/src/terminal_view.dart`,
+ `lib/src/core/input/handler.dart`). Linux uses Ctrl-Shift-C/V/A for clipboard
+ copy/paste/select-all, preserving Ctrl-A and Ctrl-V for the program in the
+ terminal. Left-Alt printable keys send an escape prefix with the actual
+ keyboard-layout character, preserving case and punctuation; AltGr and macOS
+ Option remain native text composition. The fallback letter handler respects
+ Shift and emits lowercase otherwise. Desktop creates Linux-target terminals
+ on Linux. Regressions: `test/terminal_clipboard_test.dart`, with existing IME
+ coverage in `test/terminal_view_interaction_test.dart`.
+
- **Remote grids survive viewport resizing** (`lib/src/terminal_view.dart`,
`lib/src/ui/render.dart`). `TerminalView.resizeBuffer` defaults to true;
Harness sets it to false so a smaller local pane reports its desired size
diff --git a/desktop/third_party/xterm/lib/src/core/input/handler.dart b/desktop/third_party/xterm/lib/src/core/input/handler.dart
index 6a8ed70b4..65aaad0e8 100644
--- a/desktop/third_party/xterm/lib/src/core/input/handler.dart
+++ b/desktop/third_party/xterm/lib/src/core/input/handler.dart
@@ -188,7 +188,7 @@ class AltInputHandler implements TerminalInputHandler {
@override
String? call(TerminalKeyboardEvent event) {
- if (!event.alt || event.ctrl || event.shift) {
+ if (!event.alt || event.ctrl) {
return null;
}
@@ -200,7 +200,8 @@ class AltInputHandler implements TerminalInputHandler {
if (key.index >= TerminalKey.keyA.index &&
key.index <= TerminalKey.keyZ.index) {
- final charCode = key.index - TerminalKey.keyA.index + 65;
+ final charCode =
+ key.index - TerminalKey.keyA.index + (event.shift ? 65 : 97);
final input = [0x1b, charCode];
return String.fromCharCodes(input);
}
diff --git a/desktop/third_party/xterm/lib/src/terminal_view.dart b/desktop/third_party/xterm/lib/src/terminal_view.dart
index 621e3e051..da49ac0ee 100644
--- a/desktop/third_party/xterm/lib/src/terminal_view.dart
+++ b/desktop/third_party/xterm/lib/src/terminal_view.dart
@@ -562,6 +562,20 @@ class TerminalViewState extends State<TerminalView> {
// committed text (`に`) arrives. Let TextInputClient own all text without
// Control/Command; it will call _onInsert exactly once on commit.
final isTextInput = _isPrintableText(event.character);
+ // Linux's left Alt is Meta for readline/Vim: preserve the actual case
+ // and punctuation produced by the keyboard layout. Right Alt (AltGr)
+ // and macOS Option stay with the native text input client.
+ final keyboard = HardwareKeyboard.instance;
+ final linuxMeta = defaultTargetPlatform == TargetPlatform.linux &&
+ keyboard.logicalKeysPressed.contains(LogicalKeyboardKey.altLeft) &&
+ !keyboard.logicalKeysPressed.contains(LogicalKeyboardKey.altRight) &&
+ !keyboard.isControlPressed &&
+ !keyboard.isMetaPressed;
+ if (isTextInput && linuxMeta) {
+ widget.terminal.textInput('\x1b${event.character}');
+ _scrollToBottom();
+ return KeyEventResult.handled;
+ }
if (isTextInput && !reservesTerminalKey) {
// Do not let another Flutter shortcut consume this before macOS gets a
// chance to update the native text-input client.
diff --git a/desktop/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart b/desktop/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart
index 042ee156b..8845cfe05 100644
--- a/desktop/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart
+++ b/desktop/third_party/xterm/lib/src/ui/shortcut/shortcuts.dart
@@ -6,15 +6,27 @@ Map<ShortcutActivator, Intent> get defaultTerminalShortcuts {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
- case TargetPlatform.linux:
case TargetPlatform.windows:
return _defaultShortcuts;
+ case TargetPlatform.linux:
+ return _linuxShortcuts;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return _defaultAppleShortcuts;
}
}
+// Ctrl-A/V belong to readline, Vim and other programs in the terminal.
+// Keep the Linux clipboard chords separate from those input bytes.
+final _linuxShortcuts = {
+ SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
+ CopySelectionTextIntent.copy,
+ SingleActivator(LogicalKeyboardKey.keyV, control: true, shift: true):
+ const PasteTextIntent(SelectionChangedCause.keyboard),
+ SingleActivator(LogicalKeyboardKey.keyA, control: true, shift: true):
+ const SelectAllTextIntent(SelectionChangedCause.keyboard),
+};
+
final _defaultShortcuts = {
SingleActivator(LogicalKeyboardKey.keyC, control: true, shift: true):
CopySelectionTextIntent.copy,
diff --git a/desktop/tool/keymap_native_checks.swift b/desktop/tool/keymap_native_checks.swift
index 98029c555..a63adab15 100644
--- a/desktop/tool/keymap_native_checks.swift
+++ b/desktop/tool/keymap_native_checks.swift
@@ -11,27 +11,37 @@ let source = try Data(contentsOf: URL(fileURLWithPath: CommandLine.arguments[1])
let fixture = try JSONSerialization.jsonObject(with: source) as! [String: [String: Any]]
let defaults = HarnessNativeKeymap(fixture["defaults"]!)!
let changed = HarnessNativeKeymap(fixture["changed"]!)!
+for key in ["n", "o", "g", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
+ try checkKeymap(defaults.match([stroke(key)], context: "project").binding?.command.hasPrefix("creation.project_") != true,
+ "Project search does not bind action or recent shortcuts to \(key)")
+}
+for key in ["a", "m", "p", "t", "o"] {
+ try checkKeymap(defaults.match([stroke(key)], context: "picker").binding == nil,
+ "Launch menu uses arrows/Enter instead of plain \(key)")
+}
+try checkKeymap(changed.match([stroke("down")], context: "project").binding == nil &&
+ changed.match([stroke("ctrl+j")], context: "project").binding?.command == "picker.previous",
+ "Project navigation inherits picker remaps and unbindings")
for (key, command) in [
("cmd+left", "pane.focus_left"), ("cmd+down", "pane.focus_below"),
("cmd+up", "pane.focus_above"), ("cmd+right", "pane.focus_right"),
- ("cmd+s", "pane.layout"), ("cmd+r", "pane.split_right"),
- ("cmd+d", "pane.split_down"),
+ ("cmd+s", "app.store"), ("cmd+shift+l", "pane.layout"),
("cmd+b", "task.route"), ("cmd+t", "swarm.new"),
- ("cmd+p", "project.orchestrate"),
- ("cmd+o", "agent.add"), ("cmd+n", "agent.new"),
+ ("cmd+p", "agent.add"),
+ ("cmd+n", "agent.new"),
("cmd+h", "pane.focus_left"), ("cmd+j", "pane.focus_below"),
("cmd+k", "pane.focus_above"), ("cmd+l", "pane.focus_right"),
] {
try checkKeymap(defaults.match([stroke(key)], context: "workspace").binding?.command == command,
"Preserve the current default for \(key)")
}
-try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+p")) == "project.orchestrate",
- "A focused native viewer can open the orchestrator")
+try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+p")) == nil,
+ "The pane picker chord is not mistaken for an orchestrator command")
try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+b")) == nil,
"The viewer bridge does not change single-agent routing")
try checkKeymap(defaults.viewerOrchestratorCommand(stroke("cmd+shift+p")) == nil,
"The viewer bridge does not take the command palette chord")
-for context in ["workspace", "terminal", "picker"] {
+for context in HarnessNativeKeymap.contexts {
try checkKeymap(defaults.match([stroke("cmd+shift+n")], context: context).binding == nil,
"Shift-Command-N is unbound by default in \(context)")
for number in 1...9 {
@@ -39,7 +49,7 @@ for context in ["workspace", "terminal", "picker"] {
"Command-number selects the corresponding tab from \(context)")
}
}
-for context in ["workspace", "terminal", "picker"] {
+for context in HarnessNativeKeymap.contexts {
try checkKeymap(changed.match([stroke("cmd+t")], context: context).binding == nil,
"Native context honors inherited unbinding")
let search = changed.match([stroke("cmd+o")], context: context).binding
@@ -121,7 +131,7 @@ try checkKeymap(stroke("cmd+shift+left").menuEquivalent == "\u{f702}" && stroke(
"Native menu equivalents preserve function keys")
func payload(_ rows: [[String: Any]]) -> [String: Any] {
- ["version": 1, "contexts": ["workspace": rows, "terminal": rows, "picker": rows]]
+ ["version": 1, "contexts": ["workspace": rows, "terminal": rows, "picker": rows, "project": rows]]
}
let prefix: [String: Any] = ["keys": ["cmd+k"], "command": "example", "hint": "⌘K", "repeatable": false]
let remappedOrchestrator = HarnessNativeKeymap(payload([
diff --git a/desktop/tool/render_store_mark.swift b/desktop/tool/render_store_mark.swift
new file mode 100644
index 000000000..72cf2e47b
--- /dev/null
+++ b/desktop/tool/render_store_mark.swift
@@ -0,0 +1,40 @@
+import AppKit
+
+// Original Harness Store mark: six colorful branches meet around one center.
+// A small constellation for people working across disciplines. Keep the vector
+// source here; both Flutter and AppKit display the same transparent PNG.
+// From desktop/: swift tool/render_store_mark.swift
+let pixels = 256
+let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil,
+ pixelsWide: pixels, pixelsHigh: pixels, bitsPerSample: 8, samplesPerPixel: 4,
+ hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB,
+ bytesPerRow: 0, bitsPerPixel: 0)!
+bitmap.bitmapData!.initialize(repeating: 0, count: bitmap.bytesPerRow * pixels)
+NSGraphicsContext.saveGraphicsState()
+NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap)
+let context = NSGraphicsContext.current!.cgContext
+context.scaleBy(x: CGFloat(pixels) / 24, y: CGFloat(pixels) / 24)
+context.translateBy(x: 12, y: 12)
+let colors: [UInt32] = [0x71E2CF, 0x69BBFF, 0xAC92FF, 0xEF8DD0, 0xFFAC88, 0xF4D879]
+for (index, hex) in colors.enumerated() {
+ context.saveGState()
+ context.rotate(by: CGFloat(index) * .pi / 3)
+ let branch = NSBezierPath()
+ branch.move(to: NSPoint(x: 0, y: 1.4))
+ branch.curve(to: NSPoint(x: -2.05, y: 7.1),
+ controlPoint1: NSPoint(x: -1.0, y: 3.0), controlPoint2: NSPoint(x: -2.65, y: 5.15))
+ branch.curve(to: NSPoint(x: 2.05, y: 7.1),
+ controlPoint1: NSPoint(x: -1.5, y: 10.75), controlPoint2: NSPoint(x: 1.5, y: 10.75))
+ branch.curve(to: NSPoint(x: 0, y: 1.4),
+ controlPoint1: NSPoint(x: 2.65, y: 5.15), controlPoint2: NSPoint(x: 1.0, y: 3.0))
+ branch.close()
+ NSColor(srgbRed: CGFloat((hex >> 16) & 255) / 255,
+ green: CGFloat((hex >> 8) & 255) / 255,
+ blue: CGFloat(hex & 255) / 255, alpha: 1).setFill()
+ branch.fill()
+ context.restoreGState()
+}
+NSGraphicsContext.restoreGraphicsState()
+let destination = URL(fileURLWithPath: "assets/store/polymath.png")
+try bitmap.representation(using: .png, properties: [:])!.write(to: destination)
+print("Wrote \(destination.path)")
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index 679aeb1cb..362b8eba1 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -134,8 +134,8 @@ private extension SwarmTabStrip {
let closeFrame = close.convert(close.bounds, to: nil)
let zoomFrame = zoom.convert(zoom.bounds, to: nil)
let newFrame = newButton.convert(newButton.bounds, to: nil)
- try checkTitlebar(bounds.height >= 48, "Native title bar leaves room around the pill actions")
- for button in [openButton] {
+ try checkTitlebar(bounds.height >= 40, "Native title bar leaves room around the pill actions")
+ for button in [storeButton] {
let labelWidth = (button.title as NSString).size(withAttributes: [.font: button.font!]).width
try checkTitlebar(button.frame.minY >= 6 && bounds.height - button.frame.maxY >= 6 && button.frame.width - labelWidth >= 32,
"\(button.title) has vertical breathing room and readable horizontal padding")
@@ -237,22 +237,21 @@ private extension SwarmTabStrip {
try checkTitlebar(newButton.isEnabled,
"The retired canOpenNewTab capacity flag no longer disables New Tab")
update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0"))
- try checkTitlebar(newButton.toolTip == nil && openButton.toolTip == nil,
- "Titlebar actions add no hover hints")
+ try checkTitlebar(newButton.toolTip == "New Tab ⌘T" && storeButton.toolTip == "Harness Store ⌘S",
+ "Titlebar actions expose their keyboard alternatives")
try checkTitlebar(notificationButton.frame.maxX <= scroll.frame.minX,
"The bell is before the tabs beside the traffic lights")
- try checkTitlebar((newButton.isHidden || newButton.frame.maxX <= createButton.frame.minX) && scroll.frame.maxX <= createButton.frame.minX && createButton.frame.maxX <= openButton.frame.minX,
- "New and Open Harness have distinct targets on the right")
- try checkTitlebar(openButton.title == "Open Harness" && createButton.title == "New Harness",
- "The titlebar separates New and Open Harness")
+ try checkTitlebar(scroll.frame.maxX <= newButton.frame.minX && newButton.frame.maxX <= storeButton.frame.minX,
+ "New Tab follows the tabs while the Store stays on the right")
+ try checkTitlebar(storeButton.title == "Harness Store" && storeButton.accessibilityLabel() == "Harness Store",
+ "The Store action has a visible and accessible name")
try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")
events.removeAll()
newButton.performClick(nil)
notificationButton.performClick(nil)
- createButton.performClick(nil)
- openButton.performClick(nil)
- try checkTitlebar(events == ["new", "notifications", "newAgent", "addAgent"],
- "The tab, notification, New and Open buttons dispatch once")
+ storeButton.performClick(nil)
+ try checkTitlebar(events == ["new", "notifications", "store"],
+ "The tab, notification and Store buttons dispatch once")
try checkTitlebar(notificationButton.hasAttention, "The bell represents pending agent attention")
let oldButton = newButton
var themedState = state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0")
@@ -267,18 +266,17 @@ private extension SwarmTabStrip {
original.clickBothActions()
try checkTitlebar(events == ["select", "close"], "Native selection and close dispatch once each")
- let actionPixels = [createButton.renderedPixels(), openButton.renderedPixels()]
+ let actionPixels = storeButton.renderedPixels()
events.removeAll()
update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0", enabled: false))
try original.checkEnabled(false)
- try checkTitlebar(!newButton.isEnabled && !notificationButton.isEnabled && !openButton.isEnabled && !createButton.isEnabled, "Titlebar actions disable with a modal")
- try checkTitlebar(actionPixels == [createButton.renderedPixels(), openButton.renderedPixels()],
- "New and Open Harness retain their colors behind a workspace modal")
+ try checkTitlebar(!newButton.isEnabled && !notificationButton.isEnabled && !storeButton.isEnabled, "Titlebar actions disable with a modal")
+ try checkTitlebar(actionPixels != storeButton.renderedPixels(),
+ "The Store visibly dims when a workspace modal disables it")
original.clickBothActions()
newButton.performClick(nil)
notificationButton.performClick(nil)
- createButton.performClick(nil)
- openButton.performClick(nil)
+ storeButton.performClick(nil)
try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")
try checkDragOperations()
}
@@ -489,8 +487,8 @@ private extension SwarmTitlebar {
"The main-menu dispatcher retains the actual Edit submenu and its targets")
try checkTitlebar(newSwarm.keyEquivalent == "t" && newSwarm.toolTip == nil,
"Native shortcuts display in the menu without duplicate hover hints")
- try checkTitlebar(addHarness.keyEquivalent == "o" && addHarness.keyEquivalentModifierMask == [.command],
- "The exported keymap keeps Open Harness on Command-O")
+ try checkTitlebar(addHarness.keyEquivalent == "p" && addHarness.keyEquivalentModifierMask == [.command],
+ "The exported keymap keeps New Pane on Command-P")
setKeymap(changed)
try checkTitlebar(NSApp.mainMenu === main && newSwarm.keyEquivalent == "o",
"Hot reload updates the existing menu to the remapped key")
@@ -499,12 +497,12 @@ private extension SwarmTitlebar {
// The inherited default is still first; a sequence is not falsely shown
// as a second one-stroke accelerator in AppKit's shortcut column.
let onlySequence = HarnessNativeKeymap(["version": 1, "contexts": Dictionary(uniqueKeysWithValues:
- ["workspace", "terminal", "picker"].map { ($0, [["keys": ["cmd+k", "n"], "command": "swarm.new",
+ HarnessNativeKeymap.contexts.map { ($0, [["keys": ["cmd+k", "n"], "command": "swarm.new",
"hint": "⌘K N", "repeatable": false, "menuAction": "new"]]) })])!
setKeymap(onlySequence)
try checkTitlebar(newSwarm.keyEquivalent.isEmpty && newSwarm.toolTip == nil,
"Sequences add no hover hints or misleading first-key menu shortcut")
- setKeymap(HarnessNativeKeymap(["version": 1, "contexts": ["workspace": [], "terminal": [], "picker": []]])!)
+ setKeymap(HarnessNativeKeymap(["version": 1, "contexts": ["workspace": [], "terminal": [], "picker": [], "project": []]])!)
try checkTitlebar(newSwarm.keyEquivalent.isEmpty && newSwarm.toolTip == nil,
"Unbinding clears the old native shortcut and hint")
rebuildHistoryMenu()
@@ -523,11 +521,11 @@ private extension SwarmTitlebar {
"The menu yields the remapped search shortcut to Flutter")
try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu equivalents defer before input dispatch")
setKeymap(defaults)
- try checkTitlebar(strip.newButton.toolTip == nil, "Keymap reload does not restore hover hints")
+ try checkTitlebar(strip.newButton.toolTip == "New Tab ⌘T", "Keymap reload restores the current New Tab hint")
try checkTitlebar(strip.newButton.accessibilityLabel() == "New Tab", "The plus announces New Tab")
- try checkTitlebar(main.defersToInput(event("n", 45, .command)) && main.defersToInput(event("o", 31, .command)),
- "Command-N and Command-O reach their separate New and Open actions")
- try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches the Orchestrator launcher")
+ try checkTitlebar(main.defersToInput(event("n", 45, .command)) && main.defersToInput(event("t", 17, .command)),
+ "Command-N and Command-T reach creation and New Tab")
+ try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches New Pane")
try checkTitlebar(main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P reaches command search")
flutterKeyContext = "picker"
syncMenuKeys()
@@ -549,7 +547,13 @@ private extension SwarmTitlebar {
NSApp.mainMenu = originalMenu
}
actionsEnabled = true
- setKeymap(defaults)
+ // Orchestrator has no default chord now. Exercise an explicit user binding;
+ // Cmd-P belongs to New Pane and is covered by the exported default keymap.
+ let viewerMap = HarnessNativeKeymap(["version": 1, "contexts": [
+ "workspace": [["keys": ["cmd+y"], "command": "project.orchestrate", "hint": "⌘Y", "repeatable": false]],
+ "terminal": [], "picker": [], "project": [],
+ ]])!
+ setKeymap(viewerMap)
let main = NSApp.mainMenu as! HarnessKeymapMenu
func event(_ text: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags,
@@ -565,34 +569,34 @@ private extension SwarmTitlebar {
defer { web.removeFromSuperview(); window.makeFirstResponder(window.contentInput) }
try checkTitlebar(window.makeFirstResponder(webInput), "A native viewer descendant can own test focus")
flutterKeyContext = "workspace"
- setKeymap(defaults)
+ setKeymap(viewerMap)
let beforeViewer = messenger.calls.count
- try checkTitlebar(main.performKeyEquivalent(with: event("p", 35, .command)),
- "Command-P is consumed by the focused native viewer bridge")
+ try checkTitlebar(main.performKeyEquivalent(with: event("y", 16, .command)),
+ "The custom Orchestrator shortcut is consumed by the focused native viewer bridge")
try checkTitlebar(messenger.calls.count == beforeViewer + 1 && messenger.calls.last?.method == "keymapCommand" &&
(messenger.calls.last?.arguments as? [String: String])?["command"] == "project.orchestrate",
"The native viewer dispatches exactly one Orchestrator command to Flutter")
let repeated = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: .command,
- timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: "p",
- charactersIgnoringModifiers: "p", isARepeat: true, keyCode: 35)!
+ timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: "y",
+ charactersIgnoringModifiers: "y", isARepeat: true, keyCode: 16)!
try checkTitlebar(main.performKeyEquivalent(with: repeated) && messenger.calls.count == beforeViewer + 1,
- "Holding Command-P never launches repeated projects")
+ "Holding the shortcut never launches repeated projects")
_ = main.performKeyEquivalent(with: event("b", 11, .command))
try checkTitlebar(messenger.calls.count == beforeViewer + 1, "The viewer bridge does not hijack Command-B")
actionsEnabled = false
- _ = main.performKeyEquivalent(with: event("p", 35, .command))
+ _ = main.performKeyEquivalent(with: event("y", 16, .command))
try checkTitlebar(messenger.calls.count == beforeViewer + 1, "Modal state blocks native viewer launch dispatch")
actionsEnabled = true
let remapped = HarnessNativeKeymap(["version": 1, "contexts": [
"workspace": [["keys": ["cmd+x"], "command": "project.orchestrate", "hint": "⌘X", "repeatable": false]],
- "terminal": [], "picker": [],
+ "terminal": [], "picker": [], "project": [],
]])!
setKeymap(remapped)
- _ = main.performKeyEquivalent(with: event("p", 35, .command))
+ _ = main.performKeyEquivalent(with: event("y", 16, .command))
try checkTitlebar(messenger.calls.count == beforeViewer + 1, "The old viewer shortcut stays unbound after remapping")
try checkTitlebar(main.performKeyEquivalent(with: event("x", 7, .command)) && messenger.calls.count == beforeViewer + 2,
"The viewer bridge follows the actual remapped two-key shortcut")
- setKeymap(HarnessNativeKeymap(["version": 1, "contexts": ["workspace": [], "terminal": [], "picker": []]])!)
+ setKeymap(HarnessNativeKeymap(["version": 1, "contexts": ["workspace": [], "terminal": [], "picker": [], "project": []]])!)
_ = main.performKeyEquivalent(with: event("x", 7, .command))
try checkTitlebar(messenger.calls.count == beforeViewer + 2, "Unbinding disables viewer launch dispatch")
setKeymap(defaults)
@@ -649,12 +653,12 @@ private extension SwarmTitlebar {
try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")
let agent = main.item(withTitle: "File")!.submenu!
let addHarness = agent.items.first(where: { $0.representedObject as? String == "addAgent" })!
- try checkTitlebar(addHarness.title == "Open Harness…" && addHarness.keyEquivalent == "o" && addHarness.keyEquivalentModifierMask == [.command],
- "Open Harness advertises Command-O")
- try checkTitlebar(agent.items.contains { $0.title == "New Harness…" && $0.keyEquivalent == "n" && $0.keyEquivalentModifierMask == [.command] && $0.representedObject as? String == "newAgent" },
- "New Harness has its own Command-N menu action")
+ try checkTitlebar(addHarness.title == "New Pane…" && addHarness.keyEquivalent == "p" && addHarness.keyEquivalentModifierMask == [.command],
+ "New Pane advertises Command-P")
+ try checkTitlebar(agent.items.contains { $0.title == "New Terminal" && $0.keyEquivalent == "t" && $0.keyEquivalentModifierMask == [.command, .shift] && $0.representedObject as? String == "newTerminal" },
+ "New Terminal has its Command-Shift-T menu action")
let historyMenu = main.item(withTitle: "History")!.submenu!
- try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["new", "newAgent", "addAgent", "renameActive", "closeActive", "separator", "splitRight", "splitDown", "zoomPane", "closePane"], "File groups Harness and Pane actions, without Pin or Add Project clutter")
+ try checkTitlebar(agent.items.map { $0.isSeparatorItem ? "separator" : ($0.representedObject as? String ?? "") } == ["new", "addAgent", "newTerminal", "renameActive", "closeActive", "separator", "zoomPane", "closePane"], "File groups tab, terminal and pane actions")
try checkTitlebar(agent.items.filter { !$0.isSeparatorItem }.allSatisfy { $0.image != nil && $0.toolTip == nil },
"Every File action has a native icon and no hover hint")
try checkTitlebar(agent.items.contains { $0.title == "Rename Tab…" && $0.representedObject as? String == "renameActive" }, "Rename Tab preserves its command")
@@ -684,11 +688,16 @@ private extension SwarmTitlebar {
]
_ = try messenger.receive("machinesState", arguments: ["machines": machineRows])
let machineMenu = main.item(withTitle: "Machines")!.submenu!
- let manager = machineMenu.items.first!
- try checkTitlebar(manager.title == "Open Machines Manager" && manager.representedObject as? String == "manageMachines" && machineMenu.items[1].isSeparatorItem,
- "Machines Manager leads the menu before linked computers")
- menuAction(manager)
+ let manage = machineMenu.items[0]
+ let manager = machineMenu.items[1]
+ try checkTitlebar(manage.title == "Open Machine Monitor…" && manage.representedObject as? String == "manageMachines" &&
+ manager.title == "Open Machines Manager" && manager.representedObject as? String == "machineList" && machineMenu.items[2].isSeparatorItem,
+ "The Machines harness and existing manager lead the linked computers")
+ menuAction(manage)
try checkTitlebar(messenger.calls.last?.method == "manageMachines",
+ "The Machines harness opens through the Flutter command bridge")
+ menuAction(manager)
+ try checkTitlebar(messenger.calls.last?.method == "machineList",
"Machines Manager opens through the Flutter command bridge")
let destinations = machineMenu.items.filter { $0.action == #selector(machineAction(_:)) }
try checkTitlebar(machineMenu.minimumWidth == 0 && machineMenu.size.width < 432 &&
@@ -844,7 +853,7 @@ private extension SwarmTitlebar {
let models = main.item(withTitle: "Models")!.submenu!
try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [
"Subscription", "Anthropic, aabbcc, 12% remaining", "OpenAI, Not signed in",
- "Local", "Open Grid"
+ "Local", "Want to manage local models?", "Open Grid"
], "Models carries the two sections with something behind them, ending on the row that starts a model")
try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 1,
"One native separator, between the sections — the run row is a Local row, not a section")
@@ -855,6 +864,7 @@ private extension SwarmTitlebar {
// The caption and button distinguish the manager action from the Local data rows.
// It remains enabled with nothing served and dispatches through the same guarded
// handler as Link Machine… so a modal still swallows it.
+ let managerCaption = models.items[models.items.count - 2]
let runLocal = models.items.last!
try checkTitlebar(runLocal.title == "Open Grid",
"the last item in Models is the row that runs a local model")
@@ -873,8 +883,8 @@ private extension SwarmTitlebar {
actionsEnabled = false
try checkTitlebar(!validateMenuItem(runLocal), "Open Grid cannot run behind a modal")
actionsEnabled = true
- try checkTitlebar(!runLocal.title.lowercased().contains("grid") && !runLocal.title.contains("Mac"),
- "the command names neither the plumbing nor one vendor's computer")
+ try checkTitlebar(!runLocal.title.contains("Mac"),
+ "The model manager action does not assume one vendor's computer")
// With more than one machine linked, the row has to say WHICH computer the manager opens on:
// it becomes a submenu of the machines, each child dispatching the same command with that
diff --git a/docs/cli.md b/docs/cli.md
index 31f5b0150..cf7078d80 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -54,5 +54,16 @@ Engines report in over HTTP on the same port: `POST /api/hook/session-start`, `s
`turn-start`, `turn-stop`, `tool-start`, authenticated by a per-install token the daemon writes into
the hook it installs.
-There is no `harness new` or `harness split` today. Sessions are created and arranged through the app,
-the web client, or this socket.
+`harness new` makes a session from a shell, in the words the app's box uses, over this same socket:
+
+```
+harness new claude, in the current directory
+harness new codex @mini ~/code/auth codex, on the machine called mini, in that folder
+harness new codex my-game codex, in a new project ~/harnesses/my-game
+harness new --plan --prompt "fix the flaky login test"
+```
+
+Words may come in any order: `@` marks the machine (id, name, or an unambiguous start of a word in
+it), a path looks like a path, the first other word is the agent and a second names a new project.
+`--mode auto|ask|plan|full`, `--name`, `--new [name]` and `--json` are the rest. There is still no
+`harness split`: panes are arranged in the app.
diff --git a/docs/keyboard.md b/docs/keyboard.md
index 2939dbd7d..5d4d79a27 100644
--- a/docs/keyboard.md
+++ b/docs/keyboard.md
@@ -6,25 +6,27 @@ The defaults, in the workspace:
| Keys | Action |
|---|---|
-| ⌘N | New Harness |
-| ⌘O | Open Harness — search sessions, tabs, machines, history; `>` for commands |
-| ⇧⌘P | Command palette |
+| ⌘T | New Tab — choose an existing harness or select the pinned New agent row. The tab is allocated only after selection or successful creation; Escape leaves the layout unchanged |
+| ⌘P | New Pane — the same picker, adding to the current tab and automatically tiling its panes. Search by harness name, project, machine, or session content. Selecting a harness already here focuses its pane |
+| ⌘N | New Harness directly — the box opens on the task: type what it should do and press Return, and it starts as another of the pane you were in (labeled agent, machine, project, and mode defaults stay visible above `task >`). Tab and ⇧Tab step out to those answers; each is a list you filter by typing, with a ✓ on the current one. One verb per field: in a list Return **chooses** and comes back to the task, on the task Return **makes it**, and ⌘↵ makes it from anywhere with the highlighted row. In the project field a word names a new project, `owner/repo` clones it, a path completes the way zsh's does (Tab: common prefix, then walk the candidates, ⇧Tab back; `/` goes in) and Browse… opens the folder chooser. ⌥↵ breaks the line in the task; ⌥1–⌥9 pick a row; ⌘. opens the full form. Escape keeps what you typed for the next ⌘N |
+| ⇧⌘P | Command palette — a `:` prompt with an empty input; includes the orchestrator, directional splits, and settings. Recent commands appear first; typing `usage` opens Settings ▸ Usage |
| ⌘B | Boss mode: describe a task, it picks the agent |
-| ⌘P | Orchestrator: describe a project, coordinate background harnesses and live viewers |
-| ⌘T · ⌘W · ⇧⌘T · ⇧⌘R | New tab · close tab · reopen last closed · rename tab |
+| ⌘W · ⇧⌘R | Close tab · rename tab |
+| ⇧⌘T | New terminal in the current project |
| ⌘1 … ⌘9 | Select tab by position |
| ⇧⌘] · ⇧⌘[ · ⌃Tab · ⌃⇧Tab | Next · previous tab |
| ⌘] · ⌘[ · ⌘Y | Forward · back through visited agents · full history |
| ⌘H ⌘J ⌘K ⌘L · ⌘arrows | Focus the pane left · below · above · right |
| ⇧⌘arrows | Move the focused pane |
-| ⌘R · ⌘D | Split right · split down |
| ⌘⏎ · ⌘; · ⇧⌘W | Zoom or restore · last pane · close pane |
| ⌘S | Layout palette |
| ⌘F · ⌘G · ⇧⌘G | Find in terminal · next · previous match |
| ⇧⌘I | Agents needing input |
| ⌘, · ⌘/ | Settings · keyboard shortcuts |
-In a picker: ↓ ⌃N ⌃J and ↑ ⌃P ⌃K move, ⏎ opens, ⌘⏎ adds the result as a pane here, Esc or ⌃G closes.
+In the New Tab and New Pane pickers, New agent is selected when the query is empty. Typing selects the best matching existing harness; the creation row stays pinned above it and carries the query into the first task. Projects and machines filter individual harnesses rather than opening whole groups. The destination is shown in the picker and carried into creation. A harness can have views in several tabs, with one view per tab; closing a pane only removes that view.
+
+In a picker: ↓ ⌃N ⌃J and ↑ ⌃P ⌃K move, ⏎ accepts, and Esc, ⌃C, or ⌃G closes. In the New Tab and New Pane pickers, ⌘⏎ accepts into the same requested destination. Preview starts hidden; ⌃/ toggles it and Page Up/Down scroll it without leaving the search input.
The terminal keeps ⌘C, ⌘V, ⌘A, Esc, ⌥⏎ and ⌃C for itself. `pane.pin`, `pane.focus_1…9`,
`pane.resize`, `pane.reset_sizes`, `machine.link` and a few others ship unbound and are in the palette.
@@ -34,3 +36,5 @@ JSONC: `{ "version": 1, "bindings": [{ "keys": "cmd+k cmd+l", "command": "pane.f
whole prefix; `when` is `workspace`, `terminal` or `picker`. The file is watched and reloaded on save;
a bad edit keeps the last good keymap and says what was wrong. **Keyboard shortcuts (⌘/)** lists the
effective bindings and **Open keyboard config** writes a commented template with every command id.
+
+In both modes of the box the line is a readline: ⌃A ⌃E ⌃F ⌃B and ⌥←/→ move, ⌃W kills a word (stopping at `/`), ⌃U kills to the start, ⌃H and ⌃D delete a character each way, ⌃Y puts the last kill back. ⌃N/⌃J and ⌃P/⌃K move the highlight — ⌃K is "previous", as in fzf, not kill-line — ⌃M is Return and ⌃[ or ⌃G is Escape. Every entry of the box's bottom line is also a button.