The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Keep agent startup prompts reachable during switching (#577)
Dee1557693d7c1c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 339e1ad5b..3927075e8 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -60,6 +60,8 @@ jobs:run: python3 -c 'import pty'- name: Serial lifecycle, binary transfer and descriptor cleanuprun: npx vitest run src/cable/serial.spec.ts src/cable/serial.real.spec.ts --maxWorkers=1+ - name: Agent startup through the system zsh login shell+ run: npx vitest run src/lib/engineShellStartup.spec.ts# Typecheck, the full suite, and the package updater's complete-coverage gate.typecheck-test:diff --git a/cli/package.json b/cli/package.jsonindex c5affd85f..5cffdd2e3 100644--- a/cli/package.json+++ b/cli/package.json@@ -20,7 +20,7 @@"test:sharing-e2e": "tsx scripts/share-harness-e2e.ts","test:remote-viewers": "vitest run --config vitest.viewer.config.ts","test:cursor-e2e": "RUN_CURSOR_E2E=1 vitest run src/engines/cursor/localE2e.spec.ts",- "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts --reporter=verbose",+ "test:tmux-real": "RUN_REAL_TMUX_DISCOVERY=1 vitest run src/lib/tmuxAgentDiscovery.real.spec.ts src/lib/engineShellStartup.spec.ts --reporter=verbose","test:resume": "vitest run src/lib/sessionRepair.spec.ts src/lib/captureResumeIdentity.spec.ts src/lib/resumeStoppedAgent.spec.ts src/lib/resumeAgentService.spec.ts src/lib/stoppedAgents.spec.ts src/lib/stopAgentService.spec.ts --coverage --coverage.include=src/lib/captureResumeIdentity.ts --coverage.include=src/lib/resumeStoppedAgent.ts --coverage.include=src/lib/resumeAgentService.ts --coverage.include=src/lib/stoppedAgents.ts --coverage.include=src/lib/stopAgentService.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100 --coverage.reporter=text --coverage.reporter=json --coverage.reportsDirectory=coverage/resume","test:resume-native": "tsx scripts/resume-native-e2e.ts","test:portability": "vitest run --config vitest.portability.config.ts"diff --git a/cli/src/lib/engineInstall.user.spec.ts b/cli/src/lib/engineInstall.user.spec.tsindex 42285500c..fe7e22636 100644--- a/cli/src/lib/engineInstall.user.spec.ts+++ b/cli/src/lib/engineInstall.user.spec.ts@@ -51,7 +51,8 @@ function fixture() {}writeFileSync(join(home, '.npmrc'), `prefix=${shared}\n`)const run = (node: string, install = recipe, shell = '/bin/sh') => {- const script = buildEngineLaunchArgv('codex', { installIfMissing: install }, shell, node, 'grid', null)[2]+ const argv = buildEngineLaunchArgv('codex', { installIfMissing: install }, shell, node, 'grid', null)+ const script = argv[argv.indexOf('harness-engine') - 1]return spawnSync(shell, ['-c', script, 'harness-engine', name, 'argument with spaces'], {env, encoding: 'utf8', timeout: 20_000,})diff --git a/cli/src/lib/engineLaunch.spec.ts b/cli/src/lib/engineLaunch.spec.tsindex 0b856d0c0..3397ef441 100644--- a/cli/src/lib/engineLaunch.spec.ts+++ b/cli/src/lib/engineLaunch.spec.ts@@ -68,7 +68,7 @@ describe('buildEngineLaunchArgv', () => {it('wraps zsh in its interactive login form and execs the resolved binary', () => {expect(buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, undefined, NO_TMUX)).toEqual([- '/bin/zsh', '-lic', `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`, 'harness-engine', engineBin('claude'),+ '/usr/bin/env', 'DISABLE_AUTO_UPDATE=true', '/bin/zsh', '-lic', `${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`, 'harness-engine', engineBin('claude'),])})@@ -81,7 +81,7 @@ describe('buildEngineLaunchArgv', () => {it('enters the workspace only after interactive startup has completed', () => {const argv = buildEngineLaunchArgv('claude', { cwd: '/work/project' }, '/bin/zsh', undefined, undefined, NO_TMUX)expect(argv).toEqual([- '/bin/zsh', '-lic',+ '/usr/bin/env', 'DISABLE_AUTO_UPDATE=true', '/bin/zsh', '-lic',`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}if ! cd -- "$1"; then printf '%s\\n' 'harness: the selected working directory is unavailable.' >&2; exit 1; fi\n${unreadableCwdGuard(process.platform)}shift\nharness_engine "$@"`,'harness-engine', '/work/project', engineBin('claude'),])@@ -369,10 +369,10 @@ describe('buildEngineLaunchArgv', () => {// On this branch every pane script opens with the open-files raise, the engine-in-a-shell// wrapper and the grid prelude; the Node line lands after them, and a launch without// `harnessNode` is exactly the baseline above.- expect(argv[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}${harnessNodePrelude('/opt/harness runtime/bin/node')}harness_engine "$@"`)+ expect(argv[4]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}${harnessNodePrelude('/opt/harness runtime/bin/node')}harness_engine "$@"`)expect(harnessNodePrelude('/opt/harness runtime/bin/node')).toBe('if ! command -v node >/dev/null 2>&1; then PATH="${PATH:+$PATH:}"\'/opt/harness runtime/bin\'; export PATH; fi\n')- expect(buildEngineLaunchArgv('claude', { harnessNode: false }, '/bin/zsh', undefined, undefined, NO_TMUX)[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)+ expect(buildEngineLaunchArgv('claude', { harnessNode: false }, '/bin/zsh', undefined, undefined, NO_TMUX)[4]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('claude', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)})it('the DSH prelude, run by a real shell, reaches the engine\'s PATH only when node is missing', () => {@@ -894,7 +894,7 @@ describe('buildEngineLaunchArgv — the grid the pane finds', () => {it('puts the resolved grid first on PATH and turns its update check off, before the engine', () => {const managed = '/opt/harness/runtime/grid-0.3.47-darwin-arm64/grid'- const script = buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, managed)[2]+ const script = buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, managed)[4]expect(script).toContain(`PATH='/opt/harness/runtime/grid-0.3.47-darwin-arm64'"\${PATH:+:$PATH}"\nexport PATH\n`)expect(script).toContain('GRID_NO_UPDATE_CHECK=1\nexport GRID_NO_UPDATE_CHECK\n')@@ -902,7 +902,7 @@ describe('buildEngineLaunchArgv — the grid the pane finds', () => {})it('leaves PATH alone when grid is only a name on it, but still turns the update check off', () => {- const script = buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, 'grid')[2]+ const script = buildEngineLaunchArgv('claude', {}, '/bin/zsh', undefined, 'grid')[4]expect(script).not.toContain('export PATH')expect(script).toContain('GRID_NO_UPDATE_CHECK=1')@@ -954,10 +954,10 @@ describe('buildEngineLaunchArgv with installFirst', () => {// Doing so reproduces the `command not found` this feature exists to replace, with a screenful of// installer output above it to bury the cause.const script = (install: string): string =>- buildEngineLaunchArgv('opencode', { installFirst: install }, '/bin/zsh')[2]+ buildEngineLaunchArgv('opencode', { installFirst: install }, '/bin/zsh')[4]it('leaves the plain launch alone when nothing has to be installed', () => {- expect(buildEngineLaunchArgv('opencode', {}, '/bin/zsh', undefined, undefined, NO_TMUX)[2]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('opencode', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)+ expect(buildEngineLaunchArgv('opencode', {}, '/bin/zsh', undefined, undefined, NO_TMUX)[4]).toBe(`${RAISE_OPEN_FILES_SH}${FALLBACK('opencode', '/bin/zsh')}${GRID_PRELUDE}harness_engine "$@"`)})it('keeps the engine argv positional, so the shell never re-parses a path or a flag', () => {@@ -965,9 +965,9 @@ describe('buildEngineLaunchArgv with installFirst', () => {installFirst: 'npm install -g opencode-ai',bypassPermission: true,}, '/bin/zsh')- expect(argv.slice(0, 2)).toEqual(['/bin/zsh', '-lic'])- expect(argv.slice(3)).toEqual(['harness-engine', ...buildEngineCommandArgv('opencode', { bypassPermission: true })])- expect(argv[2]).toContain('harness_engine "$@"')+ expect(argv.slice(0, 4)).toEqual(['/usr/bin/env', 'DISABLE_AUTO_UPDATE=true', '/bin/zsh', '-lic'])+ expect(argv.slice(5)).toEqual(['harness-engine', ...buildEngineCommandArgv('opencode', { bypassPermission: true })])+ expect(argv[4]).toContain('harness_engine "$@"')})it('runs the engine only when the install succeeded', async () => {@@ -1007,7 +1007,7 @@ describe('buildEngineLaunchArgv with installIfMissing', () => {executable: EngineInstallRecipe['executable'] = { names: ['harness-no-such-engine'] },): EngineInstallRecipe => ({ command, source: 'test fixture', executable })const script = (install: EngineInstallRecipe, runtimeNode?: string): string =>- buildEngineLaunchArgv('opencode', { installIfMissing: install }, '/bin/zsh', runtimeNode)[2]+ buildEngineLaunchArgv('opencode', { installIfMissing: install }, '/bin/zsh', runtimeNode)[4]it('execs an installed engine without running the installer', async () => {await expect(runPaneScript(script(recipe('false')))).resolves.toMatchObject({ code: 0, ranEngine: true })diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.tsindex 51b558a18..a4eb242f9 100644--- a/cli/src/lib/engineLaunch.ts+++ b/cli/src/lib/engineLaunch.ts@@ -410,6 +410,17 @@ export function interactiveEngineShell(shell: string | undefined = undefined): I}}+/** Automated zsh launches must set this BEFORE rc files run. Oh My Zsh otherwise waits for an+ * update answer before the engine exists, while an agent switch is still showing the old pane.+ * DISABLE_UPDATE_PROMPT would auto-update instead; DISABLE_AUTO_UPDATE skips that work entirely.+ * Keep ordinary terminal launches unchanged, and keep loading rc files for PATH/version managers. */+function engineShellArgv(shell: InteractiveEngineShell, args: readonly string[]): string[] {+ const prefix = basename(shell.path).toLowerCase() === 'zsh'+ ? ['/usr/bin/env', 'DISABLE_AUTO_UPDATE=true']+ : []+ return [...prefix, shell.path, ...shell.args, ...args]+}+/*** Full argv for a fresh tmux pane. `exec` replaces the shell with the engine,* preserving process discovery while loading the same startup files a user@@ -455,7 +466,7 @@ export function buildEngineLaunchArgv(// started the server, and an engine (Claude Code refuses outright) or an npm install under 256 is// the failure the person then reads in the pane. See openFiles.ts.const wait = opts.waitForPid ? waitForPidScript(opts.waitForPid) : ''- return [interactive.path, ...interactive.args, RAISE_OPEN_FILES_SH + prelude + cwdPrelude + wait + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command]+ return engineShellArgv(interactive, [RAISE_OPEN_FILES_SH + prelude + cwdPrelude + wait + body, 'harness-engine', ...(opts.cwd ? [opts.cwd] : []), ...command])}/** Waits in the pane for [wait]'s process to end before the engine starts: see `waitForPid`. */@@ -864,10 +875,11 @@ export async function commandAvailableInInteractiveShell(return binaryOnPath(command)|| (recipe ? engineInstallPaths(recipe).some((candidate) => binaryOnPath(candidate)) : false)}+ const [file, ...args] = engineShellArgv(interactive, [availabilityScript(recipe), 'harness-engine-probe', command])return await new Promise((resolve) => {execFile(- interactive.path,- [...interactive.args, availabilityScript(recipe), 'harness-engine-probe', command],+ file,+ args,{ timeout: 5_000 },(error) => resolve(!error),)@@ -929,10 +941,11 @@ export async function commandSupportsFlagInInteractiveShell(// ending the help. `[!…]` is POSIX and behaves the same in sh, bash and zsh (measured).`case "$help" in *"$2"[!A-Za-z0-9-]*|*"$2") exit 0 ;; *) exit ${FLAG_UNSUPPORTED_EXIT} ;; esac`,].join('\n')+ const [file, ...args] = engineShellArgv(interactive, [script, 'harness-engine-capability', command, flag])return await new Promise((resolve) => {execFile(- interactive.path,- [...interactive.args, script, 'harness-engine-capability', command, flag],+ file,+ args,{ timeout: 5_000 },(error) => {const answer: CommandFlagSupport = !errordiff --git a/cli/src/lib/engineShellStartup.spec.ts b/cli/src/lib/engineShellStartup.spec.tsnew file mode 100644index 000000000..d2d19c90a--- /dev/null+++ b/cli/src/lib/engineShellStartup.spec.ts@@ -0,0 +1,113 @@+import { execFileSync } from 'node:child_process'+import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { isolatedTmux, type IsolatedTmux } from '../testing/isolatedTmux.js'+import { resolveBinaryOnPath } from './binaryOnPath.js'+import { buildEngineCommandArgv, buildEngineLaunchArgv, commandAvailableInInteractiveShell, commandSupportsFlagInInteractiveShell } from './engineLaunch.js'++const zsh = ['/bin/zsh', '/usr/bin/zsh'].find(existsSync)+const engines = ['claude', 'opencode', 'codex'] as const+const prompt = 'Keep spaces, "quotes", $(false), `false`, & ! ^\nand newlines'+const roots: string[] = []+let server: IsolatedTmux | undefined++afterEach(async () => {+ await server?.close()+ server = undefined+ vi.unstubAllEnvs()+ for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true })+})++function fixture() {+ const dir = realpathSync(mkdtempSync(join(tmpdir(), 'harness-shell-startup-')))+ roots.push(dir)+ // The updater's one-key prompt occurs in .zshrc, BEFORE the -c launch script.+ // The negative control below proves it really blocks a terminal, without+ // loading or updating the developer's own Oh My Zsh installation.+ writeFileSync(join(dir, '.zshrc'), `+if [[ "$DISABLE_AUTO_UPDATE" != true ]]; then+ printf '[oh-my-zsh] Would you like to update? [Y/n] '+ read -r -k 1 answer+ exit 79+fi+export HARNESS_RC_LOADED=yes+`)+ writeFileSync(join(dir, '.zprofile'), 'export HARNESS_LOGIN_LOADED=yes\n')+ const binary = join(dir, "engine with 'quotes")+ const result = join(dir, 'result.json')+ writeFileSync(binary, `#!${process.execPath}+const fs = require('node:fs');+if (process.argv.includes('--help')) { console.log('--no-daemon --auto'); process.exit(0); }+fs.writeFileSync(${JSON.stringify(result)}, JSON.stringify({+ args: process.argv.slice(2), cwd: process.cwd(),+ rc: process.env.HARNESS_RC_LOADED, login: process.env.HARNESS_LOGIN_LOADED,+ tty: [process.stdin.isTTY, process.stdout.isTTY, process.stderr.isTTY],+}));+console.log('ENGINE_READY');+if (process.stdin.isTTY) {+ process.stdin.setRawMode(true);+ process.stdin.on('data', data => console.log('INPUT:' + data.toString()));+}+`, { mode: 0o755 })+ vi.stubEnv('ZDOTDIR', dir)+ vi.stubEnv('DISABLE_AUTO_UPDATE', 'false')+ return {+ dir, binary,+ result: () => JSON.parse(readFileSync(result, 'utf8')),+ command(engine: typeof engines[number], resume = false) {+ const options = { cwd: dir, firstPrompt: prompt, ...(resume ? { resumeSessionId: 'saved-session' } : {}) }+ const argv = buildEngineLaunchArgv(engine, options, zsh, undefined, 'grid', null)+ // Substitute only the executable; exercise the full production wrapper+ // and its real positional cwd, resume flags and handoff prompt.+ argv[argv.indexOf('harness-engine') + 2] = binary+ return { argv, expected: [...(engine === 'codex' ? ['--no-daemon'] : []), ...buildEngineCommandArgv(engine, options).slice(1)] }+ },+ }+}++describe.skipIf(!zsh)('agent startup in a real zsh login shell', () => {+ for (const engine of engines) for (const resume of [false, true]) {+ it(`${engine} ${resume ? 'resume' : 'fresh launch'} skips updates before rc and preserves workspace/arguments`, () => {+ const f = fixture()+ const { argv, expected } = f.command(engine, resume)+ const output = execFileSync(argv[0], argv.slice(1), { encoding: 'utf8', timeout: 5_000, stdio: ['ignore', 'pipe', 'pipe'] })+ expect(output).not.toContain('Would you like to update?')+ expect(f.result()).toMatchObject({ args: expected, cwd: f.dir, rc: 'yes', login: 'yes' })+ })+ }++ it('availability and capability probes also skip startup maintenance', async () => {+ const f = fixture()+ await expect(commandAvailableInInteractiveShell(f.binary, zsh)).resolves.toBe(true)+ await expect(commandSupportsFlagInInteractiveShell(f.binary, '--auto', zsh)).resolves.toBe('supported')+ await expect(commandSupportsFlagInInteractiveShell(f.binary, '--missing', zsh)).resolves.toBe('unsupported')+ expect(process.env.DISABLE_AUTO_UPDATE).toBe('false')+ })+})++describe.skipIf(!zsh || process.env.RUN_REAL_TMUX_DISCOVERY !== '1' || !resolveBinaryOnPath('tmux'))('startup prompts in an isolated real tmux terminal', () => {+ it.each(engines)('%s starts and accepts input even when the normal shell would wait for an update', async engine => {+ const f = fixture()+ server = await isolatedTmux()+ const pane = await server.run('new-session', '-d', '-P', '-F', '#{pane_id}', '-s', 'startup', zsh!, '-lic', 'echo SHOULD_NOT_RUN')+ const screen = () => server!.run('capture-pane', '-p', '-t', pane)+ const waitFor = async (text: string) => {+ for (let attempt = 0; attempt < 80; attempt++) {+ if ((await screen()).includes(text)) return+ await new Promise(resolve => setTimeout(resolve, 50))+ }+ throw new Error(`Missing ${text}: ${await screen()}`)+ }+ await waitFor('[oh-my-zsh] Would you like to update? [Y/n]')+ expect(await screen()).not.toContain('SHOULD_NOT_RUN')+ const { argv, expected } = f.command(engine)+ await server.run('respawn-pane', '-k', '-t', pane, ...argv)+ await waitFor('ENGINE_READY')+ expect(f.result()).toMatchObject({ args: expected, cwd: f.dir, rc: 'yes', login: 'yes', tty: [true, true, true] })+ await server.run('send-keys', '-t', pane, '-l', 'y')+ await waitFor('INPUT:y')+ expect(await screen()).not.toContain('Would you like to update?')+ }, 15_000)+})diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex 897478e79..59058450e 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -45,8 +45,11 @@ and project, then creates into the chosen split on submission. Clicking theagent opens the shared `&` Agents picker; clicking the model opens the shared Models picker for that harness;the footer does not repeat model or effort. Agent switching saves the originalsession before starting its replacement in the same project. Its pane and layout-survive peer cleanup of the stopped source. Agents that accept an initial message-receive bounded recent requests and saved answers, preserving the handoff across+survive peer cleanup of the stopped source. Show the replacement terminal as soon+as its creation is confirmed, including during startup. Setup and resume warnings+preserve keyboard input on an available terminal, with guidance above the output+so it cannot cover a prompt. Agents that accept an initial message receive bounded+recent requests and saved answers, preserving the handoff acrossretries; the saved original session keeps the full transcript. Do not show worktree implementationpaths in everyday labels. User-selected shell/Powerline status styles remainavailable, including PR state colors and the option to disable color.diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex d6df49b56..af6c44329 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -11040,8 +11040,8 @@ class AppNotifier extends ChangeNotifier {];}- /// One switch intent owns its creation receipt. All views move together only- /// after the new agent is ready and the old conversation can be saved safely.+ /// One switch intent owns its creation receipt. Save the old conversation,+ /// then move all views as soon as the replacement terminal can be attached.Future<String?> changeAgent(String machineId, String agentId, String engine) {final source = stateOf(machineId)?.agents.where((a) => a.id == agentId)@@ -11188,20 +11188,18 @@ class AppNotifier extends ChangeNotifier {if (nextId == null) {return 'The new agent has not confirmed its start yet. Choose it again to check.';}- Agent? next() => machine.agents.where((a) => a.id == nextId).firstOrNull;- for (var i = 0; i < 60 && next()?.launchState == 'starting'; i++) {- await Future<void>.delayed(const Duration(milliseconds: 250));- if (!_machineWorkCurrent(machine, change.revision)) {- return 'This switch is no longer active.';- }+ if (!_machineWorkCurrent(machine, change.revision)) {+ return 'This switch is no longer active.';}- final target = next();- if (target == null ||- target.launchState != 'ready' ||- !target.terminalAvailable) {+ final target = machine.agents.where((a) => a.id == nextId).firstOrNull;+ // A launch receipt identifies the replacement's terminal before its engine+ // is ready. Attach now: shell, installer and onboarding prompts need input+ // during startup. Waiting for readiness leaves a stopped source onscreen+ // and can deadlock the very prompt the person must answer to become ready.+ if (target == null || !target.terminalAvailable) {change.launchFailed = target?.launchState == 'failed';return target?.launchDetail ??- 'The new agent is still starting. Choose it again to check.';+ 'The new terminal is not available yet. Choose the agent again to check.';}final terminals = allPanes.where((p) => p.machineId == machineId && p.agentId == source.id)diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex fbaa02e22..676364a5f 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1551,26 +1551,25 @@ class _PaneContent extends StatelessWidget {agent?.terminalUnavailableReason ??'This harness is unavailable on ${machine.machine.displayName}. Retained output is read only.',);+ } else if (agent.launchState == 'starting') {+ notice = terminalNotice(+ label: 'Starting',+ icon: AppIcons.terminal,+ detail: 'You can answer setup prompts in this terminal while the agent starts.',+ banner: true,+ );} else if (agent.launchState == 'failed') {- // A resume the daemon could not CONFIRM is not a start that failed: the- // engine is usually still running in this pane, which is why output- // keeps arriving while the keyboard is locked. Asking again is cheap —- // the daemon re-checks a resume it never confirmed rather than- // relaunching (`resumeStoppedAgent.ts`) — so that is the button, and- // Restart is kept for the failures where something really must be- // started again.+ // Unconfirmed can mean the shell has not reached the engine at all.+ // Keep input available for setup prompts, and re-check the existing+ // resume rather than starting another conversation.final unconfirmed = agent.launchError == 'RESUME_UNCONFIRMED';notice = terminalNotice(label: unconfirmed ? 'Not confirmed' : 'Start failed',icon: unconfirmed ? AppIcons.circleHelp : AppIcons.circleAlert,detail: unconfirmed- ? 'The engine is still running here; the daemon has not confirmed '- 'which conversation it reopened.'+ ? 'Answer setup prompts below, then check again.': agent.launchDetail ??'The engine failed to start. Terminal output is preserved.',- // The one notice that needs saying out loud rather than hovering:- // the pane keeps printing while its keyboard is locked, and nothing- // about a chip explains that.banner: true,actionLabel: unconfirmed ? 'Check again' : 'Restart',onAction: unconfirmed@@ -1603,7 +1602,15 @@ class _PaneContent extends StatelessWidget {visible: visible,compactHeader: swarmMode,composerVisible: pane.composerVisible,- readOnly: notice != null,+ // Launch progress/failure describes the engine, not permission to+ // type into its terminal. Connection and control ownership still+ // gate input independently in TerminalPanel/TerminalSession.+ readOnly:+ machine == null ||+ needsLink ||+ offline ||+ agent == null ||+ !agent.terminalAvailable,notice: notice,onToggleComposer: () => notifier.toggleComposer(pane.id),onClose: single && !swarmMode ? null : close,diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 349e10ac3..9ec137277 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -69,10 +69,8 @@ typedef TerminalNotice = ({String? actionLabel,VoidCallback? onAction,- /// Whether this one also earns the band across the top of the pane, over the- /// output. The chip is the resting place for a notice; the band is for the- /// few that are CONFUSING as well as blocking — a pane still printing while- /// its keyboard is locked — where the sentence has to be read, not hovered.+ /// Whether this one also earns a band above the terminal output.+ /// Startup and failure guidance needs to be read, not hovered./// An offline machine is neither confusing nor rare, and a band on every one/// of those would cost rows in every tile.bool banner,@@ -810,11 +808,10 @@ class _TerminalPanelState extends State<TerminalPanel>/// usually a beat long — the app reattaches them itself/// (`_paneNeedsAttach`) — and a band that flashes up for those frames is/// noise, where a taken-over pane stays taken over until somebody acts.- /// Never a pane-level [TerminalPanel.notice] (offline, unlinked — nothing- /// here would help) and never a shared read-only view.+ /// Unavailable/read-only panes cannot take control. A writable startup+ /// notice must still allow it: setup prompts need a controlling client.bool get _inputBlocked =>!widget.readOnly &&- widget.notice == null &&// A watcher is the same situation seen from the other side: this window// has the output but another client has the terminal, and the band's// button is how a person here asks for it.@@ -2215,6 +2212,12 @@ class _TerminalPanelState extends State<TerminalPanel>// [PhoneHeader], and keeping this one would stack two.if (widget.showHeader) Divider(height: 1, color: AppColors.border),?_modelNote(),+ // Reserve space for launch guidance so it cannot cover the shell+ // prompt on the first line. Stream-ownership notices below remain+ // overlays over frozen output until control is restored.+ if (widget.notice case final notice?+ when notice.banner && !_inputBlocked && !_retakingControl)+ _ControlBanner.notice(notice),Expanded(// Any press into the pane's body — the terminal, the band, its// scrollbar; not the header, which is chrome — is the person@@ -2306,13 +2309,6 @@ class _TerminalPanelState extends State<TerminalPanel>// frozen output itself, where the eyes already are, and// stays through `opening` so the pane does not jump when// it is answered.- //- // It also carries a pane-level notice that has something to- // DO about itself (a failed start offering Check again or- // Restart). One strip, never two: a noticed pane is already- // excluded from `_inputBlocked` — nothing the takeover band- // offers would help a pane whose machine or launch is the- // problem — so these two conditions cannot both hold.if (_passageId != null && !_inputBlocked)Positioned(top: 0,@@ -2341,14 +2337,6 @@ class _TerminalPanelState extends State<TerminalPanel>? () => unawaited(_takeControl()): null,),- )- else if (widget.notice case final notice?- when notice.banner && notice.onAction != null)- Positioned(- top: 0,- left: 0,- right: 0,- child: _ControlBanner.notice(notice),),if (session.uploadProgress != null ||_previewProgress != null)diff --git a/desktop/test/agent_change_test.dart b/desktop/test/agent_change_test.dartindex 0d6fec13c..1168d4591 100644--- a/desktop/test/agent_change_test.dart+++ b/desktop/test/agent_change_test.dart@@ -26,6 +26,7 @@ class SwitchConnection extends MonitorConnection {Completer<void>? holdClose;Map<String, dynamic> recent = {'asks': <String>[], 'events': <Object>[]};int recentReads = 0;+ Map<String, dynamic>? launch;@overrideFuture<Map<String, dynamic>> request(@@ -64,6 +65,7 @@ class SwitchConnection extends MonitorConnection {'agent': {...agent,'engine': creations.last['engine'],+ if (launch != null) 'launch': launch,'project': {'name': 'work', 'cwd': '/projects/work'},if (creations.last['dsh'] != null)'viewerUrl': 'http://127.0.0.1:4179/',@@ -137,6 +139,66 @@ class SwitchDeskApi extends ApiClient {}void main() {+ for (final state in ['starting', 'failed']) {+ test(+ 'attaches a $state replacement immediately so startup prompts can be answered',+ () async {+ final connection = SwitchConnection()+ ..launch = {+ 'state': state,+ if (state == 'failed') 'error': 'LAUNCH_TIMEOUT',+ };+ final app = fixture(connection, sourceEngine: 'claude');+ addTearDown(app.dispose);+ await app.addAgentToSwarm('m', 'a0');+ final pane = app.panes.single;+ final tab = app.activeSwarm;+ final sizes = Map.of(tab.paneSizes);+ expect(+ await app+ .changeAgent('m', 'a0', 'opencode')+ .timeout(const Duration(seconds: 1)),+ isNull,+ );+ expect(app.panes.single, same(pane));+ expect(pane.agentId, 'local-session');+ expect(tab.paneSizes, sizes);+ expect(connection.creations, hasLength(1));+ expect(+ app+ .stateOf('m')!+ .agents+ .firstWhere((a) => a.id == pane.agentId)+ .launchState,+ state,+ );+ // Readiness arrives later; no second picker action or agent_create.+ await app.handleEventForTest('m', {+ 'type': 'agent_synced',+ 'payload': {+ 'agent': {+ 'id': 'local-session',+ 'name': 'Work',+ 'engine': 'opencode',+ 'terminal': {'available': true},+ 'launch': {'state': 'ready'},+ },+ },+ });+ expect(pane.agentId, 'local-session');+ expect(+ app+ .stateOf('m')!+ .agents+ .firstWhere((a) => a.id == pane.agentId)+ .launchState,+ 'ready',+ );+ expect(connection.events, ['save/stop', 'start']);+ },+ );+ }+for (final (source, target) in [('claude', 'opencode'),('claude', 'codex'),diff --git a/desktop/test/pane_launch_failure_test.dart b/desktop/test/pane_launch_failure_test.dartindex 3dc1033f1..149faea0d 100644--- a/desktop/test/pane_launch_failure_test.dart+++ b/desktop/test/pane_launch_failure_test.dart@@ -1,7 +1,13 @@+import 'dart:convert';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.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/pane_grid.dart';+import 'package:harness/widgets/terminal_panel.dart';+import 'package:xterm/xterm.dart';import 'swarm_screen_test.dart' show terminal;import 'swarm_state_test.dart' show createApp;@@ -11,20 +17,24 @@ import 'swarm_state_test.dart' show createApp;/// pretending the start failed.void main() {late AppNotifier app;+ late List<TerminalBinaryFrame> input;+ late TerminalSession session;setUp(() {app = createApp();app.stateOf('m')!..nodeOnline = true..terminalCapabilityAvailable = true;- app.adoptSessionForTest(terminal('a0', []));+ input = [];+ session = terminal('a0', input);+ app.adoptSessionForTest(session);});tearDown(() => app.dispose());/// Through the daemon's own push, so the window-band rule in `_upsertAgent`/// is exercised rather than stepped over.- Future<void> agentWith({required String launchError}) =>+ Future<void> agentWith({String? launchError, String state = 'failed'}) =>app.handleEventForTest('m', {'type': 'agent_synced','payload': {@@ -34,7 +44,7 @@ void main() {'engine': 'codex','terminal': {'available': true},'launch': {- 'state': 'failed',+ 'state': state,'error': launchError,'detail': 'The daemon said so.',},@@ -59,18 +69,93 @@ void main() {testWidgets('a resume the daemon could not confirm offers Check again', (tester,) async {- // The engine is usually still running in the pane — output keeps arriving- // while the keyboard is locked — so the pane says that and offers the cheap- // question, not a relaunch.await agentWith(launchError: 'RESUME_UNCONFIRMED');await pump(tester);expect(find.text('Not confirmed'), findsWidgets);- expect(find.textContaining('still running here'), findsWidgets);+ expect(find.textContaining('Answer setup prompts below'), findsWidgets);expect(find.widgetWithText(FilledButton, 'Check again'), findsOneWidget);expect(find.text('Start failed'), findsNothing);await tester.pumpWidget(const SizedBox());});+ for (final state in ['starting', 'RESUME_UNCONFIRMED', 'LAUNCH_TIMEOUT']) {+ testWidgets(+ '$state keeps setup prompts visible and accepts keyboard input',+ (tester) async {+ await agentWith(+ state: state == 'starting' ? 'starting' : 'failed',+ launchError: state,+ );+ session.terminal.write('[oh-my-zsh] Would you like to update? [Y/n] ');+ await pump(tester);+ final panel = tester.widget<TerminalPanel>(find.byType(TerminalPanel));+ expect(panel.readOnly, isFalse);+ expect(session.acceptsInput, isTrue);+ expect(+ tester.getTopLeft(find.byType(TerminalView)).dy,+ greaterThan(+ tester+ .getBottomLeft(+ find+ .textContaining(+ state == 'starting'+ ? 'You can answer setup prompts'+ : state == 'RESUME_UNCONFIRMED'+ ? 'Answer setup prompts below'+ : 'The daemon said so.',+ )+ .last,+ )+ .dy,+ ),+ );+ await tester.tap(find.byType(TerminalView));+ await tester.pump();+ expect(session.acceptsInput, isTrue, reason: '${session.status}');+ expect(+ tester.widget<TerminalView>(find.byType(TerminalView)).readOnly,+ isFalse,+ );+ expect(+ tester+ .widget<TerminalView>(find.byType(TerminalView))+ .focusNode!+ .hasFocus,+ isTrue,+ );+ tester.testTextInput.enterText('y');+ // setUp constructs the session outside the widget fake-async zone.+ // Let its ordered transport tail complete in that same zone.+ await tester.runAsync(() async {});+ await tester.pump(const Duration(milliseconds: 20));+ expect(utf8.decode(input.expand((frame) => frame.bytes).toList()), 'y');+ await agentWith(state: 'ready');+ await tester.pump();+ expect(+ tester.widget<TerminalPanel>(find.byType(TerminalPanel)).notice,+ isNull,+ );+ expect(app.panes.single.session, same(session));+ await tester.pump(const Duration(milliseconds: 400));+ await tester.pumpWidget(const SizedBox());+ },+ );+ }++ testWidgets('an offline startup still keeps its terminal read only', (+ tester,+ ) async {+ await agentWith(state: 'starting');+ app.stateOf('m')!.nodeOnline = false;+ await pump(tester);+ expect(+ tester.widget<TerminalPanel>(find.byType(TerminalPanel)).readOnly,+ isTrue,+ );+ expect(input, isEmpty);+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('a launch that really failed offers Restart, with its reason', (tester,) async {diff --git a/desktop/test/terminal_control_banner_test.dart b/desktop/test/terminal_control_banner_test.dartindex 6001d7dab..97f5a2a82 100644--- a/desktop/test/terminal_control_banner_test.dart+++ b/desktop/test/terminal_control_banner_test.dart@@ -244,6 +244,7 @@ void main() {// A pane-level notice (offline, unlinked) already explains itself.await pump(tester,+ readOnly: true,notice: terminalNotice(label: 'Offline',icon: AppIcons.cloudOff,@@ -318,6 +319,7 @@ void main() {) async {await pump(tester,+ readOnly: true,notice: terminalNotice(label: 'Offline',icon: AppIcons.cloudOff,@@ -330,31 +332,32 @@ void main() {await finish(tester);});- testWidgets('a noticed pane keeps its own band when the stream is taken', (- tester,- ) async {- await pump(- tester,- notice: terminalNotice(- label: 'Not confirmed',- icon: AppIcons.circleHelp,- detail: 'Still checking.',- banner: true,- actionLabel: 'Check again',- onAction: () {},- ),- );- takeOver();- await tester.pump();- // A noticed pane is not "blocked" in the takeover sense — `_inputBlocked`- // excludes it, because nothing the takeover band offers would help a pane- // whose machine or launch is the problem. So the strip stays the notice's,- // and there is still exactly one band.- expect(takenOverTitle, findsNothing);- expect(find.text('Not confirmed'), findsNWidgets(2));- expect(find.widgetWithText(FilledButton, 'Check again'), findsOneWidget);- await finish(tester);- });+ testWidgets(+ 'a startup notice still allows taking control to answer prompts',+ (tester) async {+ await pump(+ tester,+ notice: terminalNotice(+ label: 'Not confirmed',+ icon: AppIcons.circleHelp,+ detail: 'Still checking.',+ banner: true,+ actionLabel: 'Check again',+ onAction: () {},+ ),+ );+ takeOver();+ await tester.pump();+ // Launch status cannot hide the control action needed to answer a prompt.+ expect(takenOverTitle, findsOneWidget);+ expect(find.text('Not confirmed'), findsOneWidget);+ expect(find.widgetWithText(FilledButton, 'Check again'), findsNothing);+ await tester.tap(banner);+ await tester.pump();+ expect(opens(), ['terminal_open']);+ await finish(tester);+ },+ );testWidgets('⏎ in the terminal takes control back, once', (tester) async {await pump(tester);@@ -737,6 +740,7 @@ void main() {app.stateOf('m')!.nodeOnline = false;await pump(tester,+ readOnly: true,notice: terminalNotice(label: 'Offline',icon: AppIcons.cloudOff,