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
fix(swarm): deliver chat input while agents are busy (#1525)
0xken1536db3d0ba5ab
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjsindex 97316a4ee..37dd9f2b5 100644--- a/cli/e2e/harness/fakeEngine.mjs+++ b/cli/e2e/harness/fakeEngine.mjs@@ -702,6 +702,7 @@ export async function run(engine, config = {}, { native = false } = {}) {let turn = 0let open = null+ let interruptSlow = null// The tool `!holdtool` left running: an interrupt flushes its output, marked aborted, before the turn ends.let runningTool = null// The question dialog `!ask` draws, as the real CLIs draw theirs (the parser's fixtures,@@ -1549,7 +1550,14 @@ export async function run(engine, config = {}, { native = false } = {}) {await new Promise((resolve) => setTimeout(resolve, 1000))}}- if (directive?.[1] === 'slow') await new Promise((resolve) => setTimeout(resolve, Number(directive[2]) || 1000))+ if (directive?.[1] === 'slow') {+ await new Promise((resolve) => {+ const done = () => { clearTimeout(timer); interruptSlow = null; resolve() }+ const timer = setTimeout(done, Number(directive[2]) || 1000)+ interruptSlow = done+ })+ if (!open) return+ }await finish(`answer ${turn}: ${prompt}`)}@@ -1699,6 +1707,15 @@ export async function run(engine, config = {}, { native = false } = {}) {continue}if (pasting) { pasted += part === '\r' ? '\n' : part; continue }+ if (engine === 'claude' && part === '\x1b' && open && !suggestions(buffer)) {+ // Observed on real Claude Code 2.1.307: Esc interrupts the response,+ // then runs a queued follow-up; it does not restore it as an unsent draft.+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'text', text: '[Request interrupted by user]' }] } })+ open = null+ say('(interrupted)\r\n')+ interruptSlow?.()+ continue+ }if (part.startsWith('\x1b')) {// Esc puts the suggestions away, the draft kept; other keys move nothing here.const popup = suggestions(buffer)@@ -1739,6 +1756,7 @@ export async function run(engine, config = {}, { native = false } = {}) {else codex('event_msg', { type: 'turn_aborted', turn_id: open })open = nullsay('(interrupted)\r\n')+ interruptSlow?.()} else draw()} else if (part === '\r' || part === '\n') {const line = expand(buffer)diff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.tsindex c855348b8..2462c23e5 100644--- a/cli/e2e/superTabs.e2e.ts+++ b/cli/e2e/superTabs.e2e.ts@@ -8,6 +8,7 @@ import { afterEach, expect, it, onTestFailed } from 'vitest'import { superTabCommand } from '../src/superTabs/command.js'import { object } from '../src/superTabs/wire.js'import { retainedHarnesses } from '../src/superTabs/retention.js'+import { screenFor } from '../src/engines/screens.js'import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'import { LocalClient } from './harness/client.js'import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'@@ -172,9 +173,33 @@ it('starts either engine once, posts to its captured group and delivers shared iconst posted = await run(['post', 'feature', `${engine} ready`, `hello-${engine}`], target)expect(posted.code, JSON.stringify(posted.answer)).toBe(0)expect(posts.at(-1)).toMatchObject({ conversationId: 'feature', text: `${engine} ready` })+ await until('worker startup prompt to finish', async () => {+ const rows = await client.request('agents_list')+ return client.frames.some(frame => frame.type === 'turn_ended' && frame.agentId === started.answer.harnessId && !frame.replay)+ && rows.agents.some((a: Record<string, any>) => a.id === started.answer.harnessId && a.activity?.state === 'idle') || null+ }, 30_000, 250)+ const busyStart = client.next(frame => frame.type === 'turn_started' && frame.agentId === started.answer.harnessId && !frame.replay)+ client.send('message', { agentId: started.answer.harnessId, content: '!slow 20000' })+ await busyStart+ const busyFrom = client.frames.length, queuedAt = performance.now()pending.set(target, { id: `delivery-${engine}`, status: 'queued', claimId: null,message: { id: `message-${engine}`, conversationId: 'feature', replyTo: `question-${engine}`, author: { name: 'Fixture human' }, text: `verify-super-tab-${engine}` } })await until('native input acknowledgement', () => pending.get(target)?.status === 'delivered' || null, 60_000, 250)+ expect(client.frames.slice(busyFrom).filter(frame => frame.type === 'turn_ended' && frame.agentId === started.answer.harnessId && !frame.replay),+ 'Swarm input must be typed and acknowledged before the current turn ends').toHaveLength(0)+ console.log(`${engine}: busy Swarm input acknowledged in ${Math.round(performance.now() - queuedAt)} ms`)+ if (engine === 'claude') {+ const rows = await client.request('agents_list')+ const pane = rows.agents.find((agent: Record<string, any>) => agent.id === started.answer.harnessId).tmuxPane+ await d.tmux.run('send-keys', '-t', pane, 'Escape')+ await until('queued Swarm input to run after Esc interrupts the preceding response', () =>+ client.frames.slice(busyFrom).some(frame => frame.type === 'turn_started' && frame.agentId === started.answer.harnessId+ && !frame.replay && String(frame.payload?.userMessage).includes(`verify-super-tab-${engine}`)) || null,+ 5_000, 100)+ const afterEscape = await d.tmux.run('capture-pane', '-p', '-e', '-t', pane)+ expect(screenFor('claude').inspect(afterEscape).pane.draft, `Esc must not restore delivered Swarm input as an unsent draft:\n${afterEscape}`).toBe(false)+ expect(pending.get(target)?.status).toBe('delivered')+ }const submitted = readFileSync(join(d.root, 'submitted-prompts'), 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line) as string)expect(submitted.filter(prompt => prompt.includes(`verify-super-tab-${engine}`))).toHaveLength(1)expect(submitted.find(prompt => prompt.includes(`verify-super-tab-${engine}`))).toContain(`In reply to message question-${engine}.`)diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsindex f1ad25ca1..c9236860a 100644--- a/cli/src/core/input.spec.ts+++ b/cli/src/core/input.spec.ts@@ -81,6 +81,42 @@ const delivery = (deliveryId: string) => ({ deliveryId }) as unknown as SessionIdescribe('the session input controller\'s dependencies', () => {afterEach(() => vi.restoreAllMocks())+ it.each(['a1', 'cx'])('types Swarm input into busy %s while retaining the Agent Messages hold', async id => {+ const t = deps(), wired = sessionInputDeps(t.deps, () => lock(t.calls))+ t.setPane(id === 'a1' ? 'Working (esc to interrupt)\n' + READY_PANE : '\n\u001b[1m›\u001b[0m \n\n esc to interrupt')+ expect(await wired.beforeTeamWrite!(agents.get(id)!, 'team:service:superTabs:busy')).toBeNull()+ expect(await wired.injectTeam!(id, 'chat follow-up', 'team:service:superTabs:busy')).toBe(ok)+ expect(await wired.injectTeam!(id, 'peer message', 'team:peer')).toMatchObject({ dispatch: 'not_started', reason: 'team_waiting_idle' })+ })++ it.each([+ [null, 'team_waiting_unavailable'],+ [CLAUDE_PERMISSION, 'team_waiting_user'],+ ['Working (esc to interrupt)\n────────────\n❯ draft\n────────────', 'team_waiting_draft'],+ ['Working (esc to interrupt)\n────────────\n❯\n human second line\n────────────', 'team_waiting_draft'],+ ])('keeps unsafe busy Swarm panes untouched (%s)', async (pane, reason) => {+ const t = deps(), wired = sessionInputDeps(t.deps, () => lock(t.calls))+ t.setPane(pane)+ expect(await wired.injectTeam!('a1', 'chat follow-up', 'team:service:superTabs:held')).toMatchObject({ dispatch: 'not_started', reason })+ expect(t.deps.terminal.submitTerminalAction).not.toHaveBeenCalled()+ })++ it('still checks authority and engine support for Swarm input', async () => {+ const t = deps(), wired = sessionInputDeps(t.deps, () => lock(t.calls))+ t.deps.deliveries.canWrite = () => false+ expect(await wired.injectTeam!('a1', 'chat', 'team:service:superTabs:control')).toMatchObject({ reason: 'team_waiting_control' })+ t.setPane('Working (esc to interrupt)')+ expect(await wired.injectTeam!('cc', 'chat', 'team:service:superTabs:unsupported')).toMatchObject({ reason: 'team_waiting_idle' })+ })++ it('requires a capture even when a screen reader returns its last reading', async () => {+ const t = deps({ readScreen: async () => screenFor('claude').inspect(READY_PANE) })+ t.setPane(null)+ const wired = sessionInputDeps(t.deps, () => lock(t.calls))+ expect(await wired.injectTeam!('a1', 'chat', 'team:service:superTabs:no-capture'))+ .toMatchObject({ dispatch: 'not_started', reason: 'team_waiting_unavailable' })+ })+it('finds a session and checks its pane through what it was given', async () => {const { deps: given } = deps()const wired = sessionInputDeps(given, () => lock([]))diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsindex 26f958a73..8d2c27c93 100644--- a/cli/src/core/input.ts+++ b/cli/src/core/input.ts@@ -26,6 +26,7 @@ import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionReimport type { TerminalControl } from './terminals/control.js'import { launchBound } from './engines/sessionBinding.js'import { inputContextIn } from '../lib/nativeTurnObservations.js'+import { teamHold } from '../engines/kit/screen.js'type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }@@ -73,7 +74,7 @@ export interface InputDeps {* it so.*/export function messageWriter({ readScreen, resolve, terminal: { captureTerminal, validateTerminal, submitTerminalAction }, promptTyped }: Pick<InputDeps, 'resolve' | 'terminal' | 'promptTyped' | 'readScreen'>) {- return async (id: string, text: string, hold?: (session: RegisteredSession, screen: ScreenReading | null) => string | null, inputContext?: string): Promise<TerminalActionResult> => {+ return async (id: string, text: string, hold?: (session: RegisteredSession, screen: ScreenReading | null, capture: string | null) => string | null, inputContext?: string): Promise<TerminalActionResult> => {const session = resolve(id)if (!session) return terminalActionNotStarted('terminal agent is unavailable')// The engine first, then its screen. A check of the engine can wait, seconds, for an answer: a probe@@ -84,8 +85,8 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminalif (!await validateTerminal(session)) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)const capture = await captureTerminal(id)const screen = await readScreen(session, capture)- if (!screen) return terminalActionNotStarted(hold?.(session, null) ?? 'screen_unreadable')- const reason = hold?.(session, screen) ?? screen.messageHold+ if (!screen) return terminalActionNotStarted(hold?.(session, null, capture) ?? 'screen_unreadable')+ const reason = hold?.(session, screen, capture) ?? screen.messageHoldif (reason) return terminalActionNotStarted(reason)if (inputContext) promptTyped?.(session, capture, screen, inputContext)else promptTyped?.(session, capture, screen)@@ -121,6 +122,13 @@ export function sessionInputDeps(const { resolve, terminal, deliveries, device, clients, agentIdFor, commandcode, emit } = depsconst { captureTerminal, validateTerminal, keyTerminalAction } = terminalconst writeMessage = messageWriter(deps)+ // Swarm chat uses the native input queue, while Agent Messages still waits for idle.+ // Both paths keep the same draft and dialog checks under the pane's writer lock.+ const deliveryHold = (session: RegisteredSession, screen: ScreenReading | null, capture: string | null, deliveryId?: string): string | null => {+ if (!screen) return 'team_waiting_unavailable'+ return deliveryId?.startsWith('team:service:superTabs:') && deps.submission.policy(session.engine)?.typesWhileBusy+ ? teamHold(session.engine, capture ?? '', screen.pane, screen.question, true) : screen.teamHold+ }return {readScreen: deps.readScreen,submission: deps.submission,@@ -129,10 +137,10 @@ export function sessionInputDeps(device()?.delivery(event)deliveries.settled(event)},- beforeTeamWrite: async session => {+ beforeTeamWrite: async (session, deliveryId) => {const capture = await captureTerminal(session.agentId)const screen = await deps.readScreen(session, capture)- return screen ? screen.teamHold : 'team_waiting_unavailable'+ return deliveryHold(session, screen, capture, deliveryId)},validateRuntime: validateTerminal,// Typed into the pane as it stands, a draft or a running turn included, under the pane's write lock.@@ -140,7 +148,7 @@ export function sessionInputDeps(// An Agent Messages turn waits for a ready composer, and for its mailbox to still want it written.injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {if (!resolve(id)) return terminalActionNotStarted('team_waiting_unavailable')- return writeMessage(id, text, (session, screen) => (screen ? screen.teamHold : 'team_waiting_unavailable')+ return writeMessage(id, text, (session, screen, capture) => deliveryHold(session, screen, capture, deliveryId)?? (deliveries.canWrite(deliveryId) ? null : 'team_waiting_control'))}),sendKey: (id, key) => deviceInput().legacyWrite(id, () => keyTerminalAction(id, key)),diff --git a/cli/src/engines/kit/screen.ts b/cli/src/engines/kit/screen.tsindex bb108931b..bfda17cfa 100644--- a/cli/src/engines/kit/screen.ts+++ b/cli/src/engines/kit/screen.ts@@ -15,13 +15,13 @@ export function assembleScreen(engine: AgentEngine, capture: string, pane: PaneIconst busy = !!activity || /\bgoal\s+active\b|\bpursuing goal\b|\b[1-9]\d*\s+background\s+(?:tasks?|agents?)\b/i.test(footer)return { pane, question, messageHold, teamHold: teamHold(engine, capture, pane, question), activity, busy, stoppedGoal }}-function teamHold(engine: AgentEngine, capture: string, pane: PaneInspection, question: PaneView): string | null {+export function teamHold(engine: AgentEngine, capture: string, pane: PaneInspection, question: PaneView, allowBusy = false): string | null {if (!capture) return 'team_waiting_unavailable'if (pane.dialog || question) return 'team_waiting_user'if (pane.draft) return 'team_waiting_draft'- if (!pane.idle) return 'team_waiting_idle'+ if (!allowBusy && !pane.idle) return 'team_waiting_idle'const lines = capture.split('\n').map(stripVTControlCharacters)- if (/esc(?:ape)? to (?:interrupt|cancel|stop)/i.test(lines.slice(-15).join('\n'))) return 'team_waiting_idle'+ if (!allowBusy && /esc(?:ape)? to (?:interrupt|cancel|stop)/i.test(lines.slice(-15).join('\n'))) return 'team_waiting_idle'// These composers permit an empty first line followed by a multiline human draft.// The general profile inspector only needs the first line; team delivery needs every line.if (['claude', 'codex', 'cursor', 'hermes'].includes(engine)) {@@ -36,6 +36,7 @@ function teamHold(engine: AgentEngine, capture: string, pane: PaneInspection, quif (/[─━―]{8,}/u.test(line)) breakconst text = line.trim()if (!text || /^(?:\? for shortcuts|\d+% context|context:|ctrl\+|shift\+|tab to|plan mode|accept edits|bypass permissions)/i.test(text)) continue+ if (allowBusy && /^esc(?:ape)? to (?:interrupt|cancel|stop)\b/i.test(text)) continuereturn 'team_waiting_draft'}}diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.tsindex 3e5d32e2d..c58819ea7 100644--- a/cli/src/lib/sessionInput.spec.ts+++ b/cli/src/lib/sessionInput.spec.ts@@ -12,6 +12,7 @@ import { createSubmissions } from '../core/engines/submissions.js'import { screenFor } from '../engines/screens.js'import { submissionFor } from '../engines/submissions.js'import { submissionPolicy } from '../engines/submissionPolicies.js'+import type { SubmissionReading } from '../engines/facets/submission.js'function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {return {@@ -34,6 +35,390 @@ const codexComposer = (draft: string, footer = ' ? for shortcuts') => `\n\u001bdescribe('SessionInputController', () => {afterEach(() => vi.useRealTimers())+ it('keeps Swarm B queued through a person paste and its uncleared composer after accepting Swarm A', async () => {+ vi.useFakeTimers()+ let release!: (ok: boolean) => void+ const personWrite = new Promise<boolean>(resolve => { release = resolve })+ const typed: string[] = [], onDelivery = vi.fn()+ let draft = ''+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return text === 'person' ? personWrite : true },+ sendKey: async () => true, capture: async () => claudeBox(draft), beforeTeamWrite: async () => null,+ onDelivery, onError: vi.fn() })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'A', 'team:service:superTabs:A')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'B', 'team:service:superTabs:B')+ controller.submit('s1', 'person')+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['A', 'person'])+ draft = 'person'+ release(true)+ await vi.advanceTimersByTimeAsync(6_000)+ expect(typed).toEqual(['A', 'person'])+ draft = ''+ await vi.advanceTimersByTimeAsync(30_000)+ expect(typed).toEqual(['A', 'person', 'B'])+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'team:service:superTabs:B', state: 'delivered' }))+ controller.forget('s1')+ })++ it('serializes a person message arriving while drained Swarm B is mid-paste', async () => {+ vi.useFakeTimers()+ let release!: (ok: boolean) => void+ const swarmWrite = new Promise<boolean>(resolve => { release = resolve })+ const typed: string[] = [], onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return text === 'B' ? swarmWrite : true },+ sendKey: async () => true, capture: async () => claudeBox(''), beforeTeamWrite: async () => null,+ onDelivery, onError: vi.fn() })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'A', 'team:service:superTabs:A')+ controller.submit('s1', 'B', 'team:service:superTabs:B')+ await vi.advanceTimersByTimeAsync(3_001)+ expect(typed).toEqual(['A', 'B'])+ controller.submit('s1', 'person')+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['A', 'B'])+ release(true)+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['A', 'B', 'person'])+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'team:service:superTabs:B', state: 'delivered' }))+ controller.forget('s1')+ })++ it.each(['transcript', 'screen unavailable', 'submission unavailable'] as const)('does not fail a busy person receipt with waiting Swarm input when %s', async mode => {+ vi.useFakeTimers()+ const receipt = vi.fn(), onError = vi.fn(), typed: string[] = []+ const controller = new SessionInputController({+ readScreen: async (record, capture) => {+ if (mode === 'screen unavailable') return null+ const screen = await readInlineScreen(record, capture)+ return screen && mode === 'transcript' ? { ...screen, messageHold: 'transcript_open' } : screen+ },+ submission: { ...inlineSubmission, read: async (record, capture, prompt) => mode === 'submission unavailable' ? null : inlineSubmission.read(record, capture, prompt) },+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, capture: async () => claudeBox(''),+ sendKey: async () => true, beforeTeamWrite: async () => 'team_waiting_dialog', onError })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'person', undefined, undefined, receipt)+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'Swarm', 'team:service:superTabs:waiting')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(typed).toEqual(['person'])+ expect(receipt).not.toHaveBeenCalled()+ expect(onError).not.toHaveBeenCalled()+ controller.onTurnStarted('s1', 'person')+ expect(receipt).toHaveBeenCalledExactlyOnceWith('started')+ controller.forget('s1')+ })++ it.each(['claude', 'codex'] as const)('bounds busy %s person-draft observations while Swarm waits', async engine => {+ vi.useFakeTimers()+ const capture = vi.fn(async () => engine === 'claude' ? claudeBox('person') : codexComposer('person'))+ const onError = vi.fn(), sendKey = vi.fn(async () => true)+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(engine), validateRuntime: async () => true, inject: async () => true,+ capture, sendKey, beforeTeamWrite: async () => 'team_waiting_draft', onError })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'person')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'Swarm', 'team:service:superTabs:waiting')+ await vi.advanceTimersByTimeAsync(60_000)+ expect(capture.mock.calls.length).toBeGreaterThan(0)+ expect(capture.mock.calls.length).toBeLessThanOrEqual(6)+ expect(sendKey).not.toHaveBeenCalled()+ expect(onError).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('ignores an older busy person observation after an identical new person write', async () => {+ vi.useFakeTimers()+ let resolveOld!: (reading: SubmissionReading) => void+ const oldReading = new Promise<SubmissionReading>(resolve => { resolveOld = resolve })+ const typed: string[] = [], firstReceipt = vi.fn(), secondReceipt = vi.fn()+ let reads = 0, draft = ''+ const controller = new SessionInputController({ readScreen: readInlineScreen,+ submission: { ...inlineSubmission, read: async (record, capture, prompt) => ++reads === 1 ? oldReading : inlineSubmission.read(record, capture, prompt) },+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, capture: async () => claudeBox(draft),+ sendKey: async () => true, beforeTeamWrite: async () => null, onError: vi.fn() })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'continue', undefined, undefined, firstReceipt)+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'Swarm', 'team:service:superTabs:waiting')+ await vi.advanceTimersByTimeAsync(3_001)+ expect(reads).toBe(1)+ controller.submit('s1', 'continue', undefined, undefined, secondReceipt)+ await vi.advanceTimersByTimeAsync(1)+ draft = 'continue'+ resolveOld({ composer: true, draft: false, nativeDraft: 'clear' })+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['continue', 'continue'])+ expect(secondReceipt).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('settles accepted Swarm input before a person writes during its composer check', async () => {+ vi.useFakeTimers()+ const onDelivery = vi.fn(), onError = vi.fn(), typed: string[] = []+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, sendKey: async () => true,+ capture: async () => claudeBox(''), beforeTeamWrite: async () => null, onDelivery, onError })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:accepted')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'person follow-up')+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['Swarm follow-up', 'person follow-up'])+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'team:service:superTabs:accepted', state: 'delivered' }))+ expect(onDelivery).not.toHaveBeenCalledWith(expect.objectContaining({ state: 'unknown' }))+ controller.forget('s1')+ })++ it('settles Swarm acceptance when a permission prompt covers the composer after Enter', async () => {+ vi.useFakeTimers()+ const onDelivery = vi.fn(), onError = vi.fn(), sendKey = vi.fn(async () => true)+ const permission = readFileSync(new URL('./__fixtures__/permission-claude.txt', import.meta.url), 'utf8').replaceAll('❯', ' ')+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async () => true, sendKey, capture: async () => permission,+ beforeTeamWrite: async () => null, onDelivery, onError })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:permission-after-enter')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'delivered' }))+ expect(onDelivery).not.toHaveBeenCalledWith(expect.objectContaining({ state: 'unknown' }))+ expect(sendKey).not.toHaveBeenCalled()+ expect(onError).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('keeps two Swarm receipts in FIFO behind an in-flight person write', async () => {+ vi.useFakeTimers()+ let release!: (ok: boolean) => void+ const personWrite = new Promise<boolean>(resolve => { release = resolve })+ const typed: string[] = [], onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return text === 'person' ? personWrite : true },+ sendKey: async () => true, capture: async () => claudeBox(''), beforeTeamWrite: async () => null,+ onDelivery, onError: vi.fn() })+ controller.submit('s1', 'person')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'first', 'team:service:superTabs:first')+ controller.submit('s1', 'second', 'team:service:superTabs:second')+ release(true)+ await vi.advanceTimersByTimeAsync(1)+ controller.onTurnStarted('s1', 'person')+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['person', 'first'])+ await vi.advanceTimersByTimeAsync(10_000)+ expect(typed).toEqual(['person', 'first', 'second'])+ for (const id of ['first', 'second']) {+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.deliveryId === `team:service:superTabs:${id}` && event.state === 'delivered')).toHaveLength(1)+ }+ controller.forget('s1')+ })++ it.each([[false, 1], [true, 1], [true, 10_000]] as const)('drains Swarm input after a person follow-up leaves the composer without a turn start (busy=%s, delay=%s)', async (busy, delay) => {+ vi.useFakeTimers()+ const typed: string[] = [], onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, sendKey: async () => true,+ capture: async () => claudeBox(''), beforeTeamWrite: async () => null, onDelivery, onError: vi.fn() })+ controller.setTurnOpen('s1', busy)+ controller.submit('s1', 'person follow-up')+ await vi.advanceTimersByTimeAsync(delay)+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:after-person')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(typed).toEqual(['person follow-up', 'Swarm follow-up'])+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'team:service:superTabs:after-person', state: 'delivered' }))+ controller.forget('s1')+ })++ it('still types person input when the extra pending-Swarm acceptance capture fails', async () => {+ vi.useFakeTimers()+ const typed: string[] = []+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, sendKey: async () => true,+ capture: async () => { throw new Error('capture unavailable') }, beforeTeamWrite: async () => null,+ onDelivery: vi.fn(), onError: vi.fn() })+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:before-person')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'person follow-up')+ await vi.advanceTimersByTimeAsync(1)+ expect(typed).toEqual(['Swarm follow-up', 'person follow-up'])+ controller.forget('s1')+ })++ it('ignores an old Swarm capture returning unavailable after a person owns the next composer check', async () => {+ vi.useFakeTimers()+ let resolveOld!: (value: string | null) => void+ const oldCapture = new Promise<string | null>(resolve => { resolveOld = resolve })+ let captures = 0+ const onError = vi.fn(), personReceipt = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true, inject: async () => true,+ sendKey: async () => true, beforeTeamWrite: async () => null, onDelivery: vi.fn(), onError,+ capture: async () => ++captures < 6 ? codexComposer('Swarm follow-up') : captures === 6 ? oldCapture : codexComposer('') })+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:old-check')+ await vi.advanceTimersByTimeAsync(9_001)+ expect(captures).toBe(6)+ controller.submit('s1', 'person follow-up', undefined, undefined, personReceipt)+ await vi.advanceTimersByTimeAsync(7_501)+ resolveOld(null)+ await vi.advanceTimersByTimeAsync(1)+ expect(personReceipt).not.toHaveBeenCalledWith('ambiguous')+ expect(onError).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it('does not retry person Enter or type Swarm input over a busy person draft', async () => {+ vi.useFakeTimers()+ const typed: string[] = [], sendKey = vi.fn(async () => true)+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { typed.push(text); return true }, sendKey,+ capture: async () => claudeBox('person draft'), beforeTeamWrite: async () => 'team_waiting_draft',+ onDelivery: vi.fn(), onError: vi.fn() })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'person draft')+ await vi.advanceTimersByTimeAsync(1)+ controller.submit('s1', 'Swarm follow-up', 'team:service:superTabs:after-draft')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(typed).toEqual(['person draft'])+ expect(sendKey).not.toHaveBeenCalled()+ controller.forget('s1')+ })++ it.each(['claude', 'codex'] as const)('delivers ordered Swarm follow-ups during a busy %s turn without waiting for another start', async engine => {+ vi.useFakeTimers()+ const inject = vi.fn(async (_id: string, _text: string) => true), onDelivery = vi.fn(), sendKey = vi.fn(async () => true), onError = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(engine), validateRuntime: async () => true, inject, sendKey, onDelivery, onError,+ beforeTeamWrite: async () => null,+ capture: async () => engine === 'claude' ? claudeBox('') : codexComposer(''),+ })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'first follow-up', 'team:service:superTabs:first')+ controller.submit('s1', 'second follow-up', 'team:service:superTabs:second')+ await vi.advanceTimersByTimeAsync(1)+ expect(inject).toHaveBeenCalledWith('h1', 'first follow-up')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(inject.mock.calls.map(call => call[1])).toEqual(['first follow-up', 'second follow-up'])+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.state === 'delivered'))+ .toEqual(expect.arrayContaining([+ expect.objectContaining({ deliveryId: 'team:service:superTabs:first' }),+ expect.objectContaining({ deliveryId: 'team:service:superTabs:second' }),+ ]))+ controller.onTurnEnded('s1')+ controller.forget('s1')+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.state === 'unknown')).toEqual([])+ expect(sendKey).not.toHaveBeenCalled()+ expect(onError).not.toHaveBeenCalled()+ })++ it('holds Swarm input for person control, then types during the same running turn', async () => {+ vi.useFakeTimers()+ const inject = vi.fn(async () => true)+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true, inject, sendKey: async () => true,+ onError: vi.fn(), beforeTeamWrite: async () => null, capture: async () => codexComposer('') })+ controller.setTurnOpen('s1', true)+ const release = controller.acquireControl('s1', { forAnswer: true })!+ controller.submit('s1', 'held chat', 'team:service:superTabs:locked')+ await vi.advanceTimersByTimeAsync(1)+ expect(inject).not.toHaveBeenCalled()+ release()+ await vi.advanceTimersByTimeAsync(2_000)+ expect(inject).toHaveBeenCalledWith('h1', 'held chat')+ controller.forget('s1')+ })++ it.each(['prior queued start', 'matching start'] as const)('keeps follow-ups ordered across a %s', async scenario => {+ vi.useFakeTimers()+ const injected: string[] = [], onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true,+ inject: async (_id, content) => { injected.push(content); return true }, sendKey: async () => true,+ onError: vi.fn(), onDelivery, beforeTeamWrite: async () => null, capture: async () => codexComposer('') })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'first', 'team:service:superTabs:first')+ controller.submit('s1', 'second', 'team:service:superTabs:second')+ await vi.advanceTimersByTimeAsync(scenario === 'prior queued start' ? 1_501 : 1)+ controller.onTurnStarted('s1', 'first')+ await vi.advanceTimersByTimeAsync(1)+ expect(injected).toEqual(['first', 'second'])+ controller.submit('s1', 'third', 'team:service:superTabs:third')+ await vi.advanceTimersByTimeAsync(10_000)+ expect(injected).toEqual(['first', 'second', 'third'])+ controller.onTurnEnded('s1')+ controller.forget('s1')+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.state === 'unknown')).toEqual([])+ })++ it('recognizes a wrapped Swarm turn through the engine reader and drains its next follow-up', async () => {+ vi.useFakeTimers()+ const injected: string[] = [], onDelivery = vi.fn()+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session('claude'), validateRuntime: async () => true,+ inject: async (_id, text) => { injected.push(text); return true }, sendKey: async () => true,+ beforeTeamWrite: async () => null, capture: async () => claudeBox(''), onDelivery, onError: vi.fn() })+ controller.submit('s1', 'first', 'team:service:superTabs:first')+ controller.submit('s1', 'second', 'team:service:superTabs:second')+ await vi.advanceTimersByTimeAsync(1)+ controller.onTurnStarted('s1', '<pasted_content id="04e3">\nfirst\n</pasted_content id="04e3">')+ await vi.advanceTimersByTimeAsync(1)+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'team:service:superTabs:first', state: 'started' }))+ expect(injected).toEqual(['first', 'second'])+ await vi.advanceTimersByTimeAsync(10_000)+ controller.forget('s1')+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.state === 'unknown')).toEqual([])+ })++ it.each(['team:peer', 'team:service:superTabs:unsupported'])('retains idle scheduling for %s', async id => {+ vi.useFakeTimers()+ const inject = vi.fn(async () => true)+ const engine = id.endsWith('unsupported') ? 'commandcode' : 'codex'+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(engine), validateRuntime: async () => true, inject, sendKey: async () => true,+ onError: vi.fn(), beforeTeamWrite: async () => null })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'held chat', id)+ await vi.advanceTimersByTimeAsync(1)+ expect(inject).not.toHaveBeenCalled()+ controller.onTurnEnded('s1')+ await vi.advanceTimersByTimeAsync(1)+ expect(inject).toHaveBeenCalledOnce()+ controller.forget('s1')+ })++ it.each(['draft', 'unreadable', 'ambiguous', 'no composer'] as const)('does not confirm Swarm queue acceptance from %s evidence', async evidence => {+ vi.useFakeTimers()+ const onDelivery = vi.fn(), sendKey = vi.fn(async () => true)+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,+ getSession: () => session(), validateRuntime: async () => true,+ inject: async () => evidence === 'ambiguous' ? { state: 'unknown', dispatch: 'possibly_executed', reason: 'lost reply' } : true,+ sendKey, onError: vi.fn(), onDelivery, beforeTeamWrite: async () => null,+ capture: async () => evidence === 'unreadable' ? null : evidence === 'no composer' ? 'Working…' : codexComposer(evidence === 'draft' ? 'follow-up' : ''),+ })+ controller.setTurnOpen('s1', true)+ controller.submit('s1', 'follow-up', 'team:service:superTabs:uncertain')+ await vi.advanceTimersByTimeAsync(1)+ controller.onTurnEnded('s1')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'unknown' }))+ expect(onDelivery.mock.calls.map(([event]) => event).filter(event => event.state === 'delivered')).toEqual([])+ expect(sendKey).not.toHaveBeenCalled()+ controller.forget('s1')+ })+it('retains each composed message context while waiting for the pane lock and the preceding turn', async () => {vi.useFakeTimers()const inject = vi.fn(async () => true)diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.tsindex 842f14986..84a0d38a0 100644--- a/cli/src/lib/sessionInput.ts+++ b/cli/src/lib/sessionInput.ts@@ -118,6 +118,8 @@ interface InputState {awaitingContent: string | null/** The receipt of the person's message typed last, until it is settled ([settle]). */awaitingReceipt?: MessageReceipt+ /** Identical follow-ups still own different asynchronous composer observations. */+ personWriteVersion?: numbercontrolLocked: booleansettling: booleanqueue: QueuedInput[]@@ -134,7 +136,7 @@ export interface SessionInputDeps {* the paste, and a turn's prompt as recorded. Every verdict and every Enter stays here. */submission: SubmissionReader/** A team-only preflight at the actual write boundary. A reason proves no paste occurred. */- beforeTeamWrite?: (session: RegisteredSession) => Promise<string | null>+ beforeTeamWrite?: (session: RegisteredSession, deliveryId?: string) => Promise<string | null>onDelivery?: (event: SessionInputDelivery) => voidgetSession: (sessionId: string) => RegisteredSession | undefinedvalidateRuntime: (session: RegisteredSession) => Promise<boolean>@@ -191,6 +193,15 @@ export class SessionInputController {return this.deps.submission.policy(engine)?.typesWhileBusy === true}+ private swarmTypesWhileBusy(engine: string, deliveryId?: string): boolean {+ return !!deliveryId?.startsWith('team:service:superTabs:') && this.typesWhileBusy(engine)+ }++ private checksWhileBusy(session: RegisteredSession, state: InputState): boolean {+ return this.swarmTypesWhileBusy(session.engine, state.deliveryId)+ || (!state.deliveryId && this.swarmTypesWhileBusy(session.engine, state.queue[0]?.deliveryId))+ }+/** Controller dependencies take the stable agent id, never a backend route. */private controlSession(id: string): RegisteredSession | undefined {return this.deps.getSession(id)@@ -305,10 +316,14 @@ export class SessionInputController {const state = this.state(sessionId)this.dropExpired(sessionId, state)if (state.controlLocked- || (deliveryId && (state.deliveryId || state.dispatching || state.turnOpen || state.awaitingFingerprint || state.settling))+ || (this.swarmTypesWhileBusy(session.engine, deliveryId) && (state.writes || state.queue.length > 0))+ || (deliveryId && (state.deliveryId || state.dispatching || state.awaitingFingerprint+ || (!this.swarmTypesWhileBusy(session.engine, deliveryId) && (state.turnOpen || state.settling))))|| (!this.typesWhileBusy(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)this.enqueue(sessionId, state, content, deliveryId, inputContext, said)+ if (this.swarmTypesWhileBusy(session.engine, deliveryId) && state.turnOpen+ && !state.deliveryId && state.awaitingFingerprint && !state.timer) this.armSubmitCheck(sessionId, session, state)return}this.delivery(sessionId, deliveryId, 'queued')@@ -320,9 +335,18 @@ export class SessionInputController {// agent as it is by then, which a restart in between may have changed.// With nothing in flight the write starts at once, so a cancel or a control request that follows// the submit sees it, as before.- const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext, said)+ this.scheduleWrite(sessionId, session, content, deliveryId, inputContext, said)+ }++ private scheduleWrite(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {+ const state = this.state(sessionId)+ const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext, receipt)const running = state.writes ? state.writes.then(write, write) : write()- const settled: Promise<void> = running.catch(() => {}).then(() => { if (state.writes === settled) state.writes = undefined })+ const settled: Promise<void> = running.catch(() => {}).then(() => {+ if (state.writes !== settled) return+ state.writes = undefined+ if (this.states.get(sessionId) === state && state.queue[0]?.deliveryId?.startsWith('team:service:superTabs:')) this.drainOne(sessionId, state)+ })state.writes = settled}@@ -366,6 +390,20 @@ export class SessionInputController {// an envelope of its own), and is settled once it has; every other engine's record is compared whole.const observedFingerprint = fingerprint(userMessage)const engineReads = !!session && !!this.deps.submission.policy(session.engine)+ if (session && this.swarmTypesWhileBusy(session.engine, state.deliveryId) && state.deliveryFingerprint+ && state.deliveryFingerprint !== observedFingerprint && !state.writing) {+ // The native queue can start an earlier follow-up after the next has been pasted.+ // Only a matching echo settles this delivery; another start must leave its check armed.+ state.turnOpen = true+ const expected = state.deliveryFingerprint, deliveryId = state.deliveryId+ void this.echoes(session, userMessage, expected).then(matched => {+ if (matched && this.states.get(sessionId) === state && state.deliveryId === deliveryId+ && state.deliveryFingerprint === expected && state.awaitingContent !== null) {+ this.onTurnStarted(sessionId, state.awaitingContent)+ }+ })+ return+ }if (state.deliveryId && state.writing) state.observedStart = userMessageelse if (state.deliveryId && state.deliveryFingerprint) {const expected = state.deliveryFingerprint@@ -409,6 +447,7 @@ export class SessionInputController {if (state.timer) clearTimeout(state.timer)state.timer = null}+ this.drainOne(sessionId, state)}/**@@ -442,6 +481,13 @@ export class SessionInputController {onTurnEnded(sessionId: string): void {const state = this.state(sessionId)+ const current = this.controlSession(sessionId)+ if (current && this.swarmTypesWhileBusy(current.engine, state.deliveryId) && state.awaitingFingerprint) {+ // Ending the preceding turn says nothing about a follow-up already in the native queue.+ state.turnOpen = false+ this.armSubmitCheck(sessionId, current, state)+ return+ }if (!state.dispatching) this.finishDelivery(sessionId, state, 'unknown', 'turn_ended_without_start')// Typed while a turn ran, the engine holds it as that turn's follow-up; otherwise no turn was seen for it.this.settle(state, state.turnOpen ? 'taken' : 'turn_ended')@@ -524,6 +570,7 @@ export class SessionInputController {/** Preserve the established injection path for every caller that opts out of receipts. */private async injectLegacy(sessionId: string, session: RegisteredSession, content: string, inputContext?: string, receipt?: MessageReceipt): Promise<void> {const state = this.state(sessionId)+ state.personWriteVersion = (state.personWriteVersion ?? 0) + 1if (!(await this.deps.validateRuntime(session))) {console.warn(`[inject] ${sid(sessionId)} abort · engine=${session.engine} · process not running`)receipt?.('runtime_gone')@@ -593,6 +640,9 @@ export class SessionInputController {private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): Promise<void> {const state = this.state(sessionId)if (!deliveryId) {+ // A later person write replaces the shared composer-check fields. Read the Swarm+ // acceptance first so its receipt is not lost merely because the person types sooner.+ if (this.swarmTypesWhileBusy(session.engine, state.deliveryId)) await this.settleSwarmAcceptance(sessionId, session, state)// A local submission keeps its original scheduling. Overlap removes our ability// to attribute a later terminal turn to the lamp; it must not block local input.this.finishDelivery(sessionId, state, 'unknown', 'prompt_mismatch')@@ -616,7 +666,7 @@ export class SessionInputController {}if (state.cancelled || this.states.get(sessionId) !== state) returnif (deliveryId.startsWith('team:')) {- const held = this.deps.beforeTeamWrite ? await this.deps.beforeTeamWrite(session) : 'team_waiting_unavailable'+ const held = this.deps.beforeTeamWrite ? await this.deps.beforeTeamWrite(session, deliveryId) : 'team_waiting_unavailable'if (state.cancelled || this.states.get(sessionId) !== state) returnif (held) { this.finishDelivery(sessionId, state, 'rejected', held); return }}@@ -681,7 +731,7 @@ export class SessionInputController {state.observes = 0state.ambiguousDispatch = typeof delivery !== 'boolean' && delivery.dispatch === 'possibly_executed'state.dispatching = false- this.delivery(sessionId, state.deliveryId, 'delivered')+ if (!this.swarmTypesWhileBusy(session.engine, state.deliveryId)) this.delivery(sessionId, state.deliveryId, 'delivered')if (state.observedStart !== undefined) {const observed = state.observedStartstate.observedStart = undefined@@ -703,7 +753,7 @@ export class SessionInputController {if (state.timer) clearTimeout(state.timer)state.timer = setTimeout(() => {state.timer = null- if (!state.awaitingFingerprint || state.turnOpen) return+ if (!state.awaitingFingerprint || (state.turnOpen && !this.checksWhileBusy(session, state))) returnconst retry = this.retrySubmit(sessionId, session, state)if (state.deliveryId) void retry.catch(() => this.failAmbiguousSubmission(sessionId, state))else void retry@@ -733,6 +783,18 @@ export class SessionInputController {}private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {+ if (state.turnOpen && !state.deliveryId) {+ await this.observeBusyPerson(sessionId, session, state)+ return+ }+ if (this.swarmTypesWhileBusy(session.engine, state.deliveryId)) {+ // Use the same native composer reading as person input. A cleared composer confirms+ // queue acceptance without waiting for a new turn; automatic traffic never retries Enter.+ if (await this.settleSwarmAcceptance(sessionId, session, state)) return+ if (++state.observes <= SUBMIT_MAX_OBSERVES) this.armSubmitCheck(sessionId, session, state)+ else this.failAmbiguousSubmission(sessionId, state)+ return+ }if (state.deliveryId?.startsWith('team:')) {// Team traffic is automatic. A missing transcript start is not permission to press Enter// again: the message may already be in the engine's queue. Inbox/reply correlation can@@ -860,6 +922,58 @@ export class SessionInputController {this.armSubmitCheck(sessionId, session, state)}+ /** A queued Swarm item may follow a person input already accepted by the busy engine. Observe only+ * enough to release it: a hidden composer or unavailable reader must leave the person's receipt for+ * its real turn event, as before, rather than run the idle retry/error path. */+ private async observeBusyPerson(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {+ const expected = state.awaitingFingerprint, version = state.personWriteVersion+ if (!expected || state.observes >= SUBMIT_MAX_OBSERVES) return+ const current = () => this.states.get(sessionId) === state && state.awaitingFingerprint === expected && state.personWriteVersion === version+ && !state.deliveryId && state.turnOpen && this.swarmTypesWhileBusy(session.engine, state.queue[0]?.deliveryId)+ if (!current()) return+ state.observes+++ const capture = await this.deps.capture?.(session.agentId).catch(() => null)+ if (!current() || !capture) return+ const screen = await this.deps.readScreen(this.readingSession(session), capture).catch(() => null)+ if (!current() || !screen || screen.messageHold) return+ const reading = await this.deps.submission.read(this.readingSession(session), capture, state.awaitingContent ?? '').catch(() => null)+ if (!current() || !reading) return+ if (reading.composer && !reading.draft && !state.ambiguousDispatch) {+ state.awaitingFingerprint = null+ state.awaitingContent = null+ state.observes = 0+ this.settle(state, 'taken')+ this.drainOne(sessionId, state)+ } else if (state.observes < SUBMIT_MAX_OBSERVES) this.armSubmitCheck(sessionId, session, state)+ }++ /** Settle only this pasted Swarm prompt, before its composer state can be replaced by another writer. */+ private async settleSwarmAcceptance(sessionId: string, session: RegisteredSession, state: InputState): Promise<boolean> {+ const expected = state.awaitingFingerprint, deliveryId = state.deliveryId+ if (!expected || state.ambiguousDispatch) return false+ const capture = await this.deps.capture?.(session.agentId).catch(() => null)+ if (this.states.get(sessionId) !== state || state.awaitingFingerprint !== expected || state.deliveryId !== deliveryId) return true+ if (!capture) return false+ const record = this.readingSession(session)+ const [reading, screen] = await Promise.all([+ this.deps.submission.read(record, capture, state.awaitingContent ?? '').catch(() => null),+ this.deps.readScreen(record, capture).catch(() => null),+ ])+ if (this.states.get(sessionId) !== state || state.awaitingFingerprint !== expected || state.deliveryId !== deliveryId) return true+ // Enter was executed after the pre-Enter dialog guard. A permission or question+ // that replaced the composer afterwards is acceptance, as it is for person input.+ const asked = screen?.messageHold === 'permission_open' || screen?.messageHold === 'question_open'+ if (!asked && !(reading && !reading.draft && reading.composer)) return false+ this.finishDelivery(sessionId, state, 'delivered')+ state.awaitingFingerprint = null+ state.awaitingContent = null+ state.observes = 0+ if (state.timer) clearTimeout(state.timer)+ state.timer = null+ this.drainOne(sessionId, state)+ return true+ }+/*** Our text left the composer: submitted, or queued by the TUI as a follow-up while busy. A real* turn_started will confirm and clear this; keep observing (bounded) WITHOUT pressing Enter — a second@@ -891,6 +1005,7 @@ export class SessionInputController {state.awaitingContent = nullstate.observes = 0this.settle(state, 'taken')+ if (this.swarmTypesWhileBusy(session.engine, state.queue[0]?.deliveryId)) this.drainOne(sessionId, state)}/**@@ -916,6 +1031,7 @@ export class SessionInputController {state.observes = 0state.ambiguousDispatch = falsethis.settle(state, 'taken')+ if (this.swarmTypesWhileBusy(session.engine, state.queue[0]?.deliveryId)) this.drainOne(sessionId, state)return true}@@ -930,7 +1046,12 @@ export class SessionInputController {private drainOne(sessionId: string, state: InputState): void {this.dropExpired(sessionId, state)- if (state.controlLocked || state.turnOpen || state.awaitingFingerprint || state.settling) return+ const current = this.controlSession(sessionId)+ const busySwarm = !!current && this.swarmTypesWhileBusy(current.engine, state.queue[0]?.deliveryId)+ // A person write may still be awaiting its terminal result when several chat+ // deliveries arrive. Reserve one Swarm receipt only after that writer finishes.+ if (busySwarm && state.writes) return+ if (state.controlLocked || (!busySwarm && (state.turnOpen || state.settling)) || state.awaitingFingerprint) returnif (state.queue[0]?.deliveryId && (state.dispatching || state.deliveryId)) returnconst next = state.queue.shift()if (!next) return@@ -941,7 +1062,8 @@ export class SessionInputController {if (!next.deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')return}- void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)+ if (busySwarm) this.scheduleWrite(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)+ else void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext, next.receipt)}private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, inputContext?: string, receipt?: MessageReceipt): void {diff --git a/cli/src/services/osDevice.spec.ts b/cli/src/services/osDevice.spec.tsindex 1fa405d3c..b7b82d89f 100644--- a/cli/src/services/osDevice.spec.ts+++ b/cli/src/services/osDevice.spec.ts@@ -96,6 +96,14 @@ describe('the Harness OS computer, managed from the phone', () => {expect(await notObject.ask({ action: 'status' })).toMatchObject({ update: { available: false, error: 'live_update.py status did not answer an object' } })})+ it('still reports status when the boot command line is unreadable and no hotspot is named', async () => {+ const { ask } = service({+ readFile: async () => { throw new Error('boot command line unavailable') },+ exec: async (file, args) => args[0] === SETUP ? ' \n' : file === '/usr/bin/python3' ? STATUS : '',+ })+ expect(await ask({ action: 'status' })).toMatchObject({ harnessOs: true, encrypted: false, hotspot: null, update: { available: true } })+ })+it('reads an update as available from the system channel or a runtime build ready', () => {expect(updateOf({ runtime: '/b/aaa', ready: null, system: { available: true, version: '2026.10.14' }, versions: {} })).toMatchObject({ available: true, runtime: 'aaa', version: '2026.10.14' })diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex f5652aa3d..935e78ef6 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -330,9 +330,6 @@ class SuperTabMessage {: 'Terminal answer';}- bool get queued => deliveries.any(- (d) => d['status'] == 'queued' || d['status'] == 'claimed',- );bool get uncertain => deliveries.any((d) => d['status'] == 'uncertain');}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 02e5bf6e7..4f7e5856c 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -1045,11 +1045,6 @@ class _SuperTabViewState extends State<SuperTabView>style: DesktopChrome.metadata(),),),- if (message.queued)- Padding(- padding: const EdgeInsets.only(top: 6),- child: Text('Queued', style: DesktopChrome.metadata()),- ),for (final delivery in message.deliveries.where((d) => d['status'] == 'uncertain',))diff --git a/desktop/test/super_tab_delivery_test.dart b/desktop/test/super_tab_delivery_test.dartindex adca690f8..ffe04b516 100644--- a/desktop/test/super_tab_delivery_test.dart+++ b/desktop/test/super_tab_delivery_test.dart@@ -12,6 +12,40 @@ import 'package:harness/super_tabs/workspace.dart';import 'support/super_tab_fixture.dart';void main() {+ testWidgets(+ 'queued and claimed messages have no queue label; uncertain review remains',+ (tester) async {+ final server = ConversationServer();+ for (final status in ['queued', 'claimed', 'uncertain']) {+ server.append('$status message');+ server.messages.last['deliveries'] = [+ {'id': status, 'agentId': 'lead-agent', 'status': status},+ ];+ }+ final controller = server.controller();+ addTearDown(controller.dispose);+ await controller.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: controller,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.text('queued message'), findsOneWidget);+ expect(find.text('claimed message'), findsOneWidget);+ expect(find.text('Queued'), findsNothing);+ expect(find.textContaining('Check delivery'), findsOneWidget);+ },+ );+final capture = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];setUpAll(() async {if (capture == null || !Platform.isMacOS) return;diff --git a/docs/plans/2026-10-22-swarm-deliver-at-once.md b/docs/plans/2026-10-22-swarm-deliver-at-once.mdnew file mode 100644index 000000000..9234619e3--- /dev/null+++ b/docs/plans/2026-10-22-swarm-deliver-at-once.md@@ -0,0 +1,65 @@+# Swarm immediate delivery implementation plan++**Goal:** Deliver Swarm chat input into Claude Code and Codex immediately during a running turn and remove the chat's Queued label.++**Architecture:** Identify Swarm deliveries by their existing `team:service:superTabs:` prefix. Reuse each engine's `typesWhileBusy` policy and submission reader. Keep Agent Messages on its current path. One pane writer and one pending delivery receipt remain serialized.++**Spec:** The Delivery builder workgroup brief: immediate typing for capable engines; preserve dialogs, questions, menus, human drafts, control locks and unavailable captures; confirm native queue acceptance without waiting for another turn; keep withheld notices and uncertain-delivery review.++**Constraints:** Node 24; no dependencies; CLI core and Super Tab coverage gates stay at 100%; tests use isolated homes, daemon ports and private tmux, never the running developer daemon. Own only session input, core input, kit screen holds, associated tests, and Desktop message presentation. Push a draft PR; do not mark ready, merge or release.++## Review focus++- Multiple Swarm messages during the same turn stay ordered and each gets its own receipt.+- A multiline draft with an empty first line stays untouched while busy.+- A dialog opening between paste and Enter still withholds Enter.+- Ambiguous terminal dispatch or unreadable submission evidence never becomes confirmed acceptance.+- Agent Messages and engines without busy typing retain their idle gate.++## Esc interruption evidence++An isolated real Claude Code 2.1.307 run used a disposable HOME/config, `--bare`, a fake API key,+a loopback streaming Anthropic fixture and private tmux. A follow-up submitted while the first+response streamed left the composer and entered the native queue. Esc interrupted that response+and automatically executed the exact queued follow-up; it did not restore an unsent draft. The+next conversation request included the interruption marker and follow-up, with an empty composer+while that response ran. This covers the tested version/configuration, not every future engine.++The fake Claude engine models this behavior. The Super Tab E2E asserts acknowledged busy input,+Esc, a new turn containing the exact queued Swarm message, no draft restoration and a retained+delivered receipt. Busy person-input checks observe acceptance only to drain waiting Swarm input;+overlays or unavailable readings leave the person receipt for its real turn event, and a persistent+draft cannot keep the observer polling indefinitely.++## Task 1: Immediate, safe native delivery++Files: `cli/src/lib/sessionInput.ts`, `cli/src/core/input.ts`, `cli/src/engines/kit/screen.ts`, their specs and `cli/e2e/superTabs.e2e.ts`.++- [x] Add failing tests for busy Claude/Codex delivery, ordered follow-ups, control locks, safe holds and native queue receipts; retain Agent Messages assertions.+- [x] Let only Swarm deliveries bypass turn-idle scheduling for engines declaring `typesWhileBusy`.+- [x] Reuse the kit's screen hold checks with an explicit busy allowance at both preflight and locked paste boundaries; still read every draft line.+- [x] Reuse the engine submission reader to settle an executed Swarm paste when its text leaves a visible composer. Never retry Enter for automatic traffic. Preserve uncertainty when evidence is missing.+- [x] Exercise the real isolated daemon with both fake engines busy; assert the prompt is submitted and acknowledged before the current turn ends. The fake already removes submitted text from its composer immediately and queues handling separately.++## Task 2: Chat presentation++Files: `desktop/lib/super_tabs/view.dart`, `desktop/lib/super_tabs/model.dart`, `desktop/test/super_tab_delivery_test.dart`.++- [x] Add a failing widget test covering queued and claimed messages without the label, alongside uncertain-delivery review.+- [x] Remove the label and its unused model getter; preserve uncertain review controls.++## Task 3: Validate and deliver++- [ ] Run CLI typecheck, affected input/screen specs, `npm run test:core`, `npm run test:super-tabs`, isolated Super Tab/input-safety end to end, and the default CLI suite. Bound workers to machine capacity.+- [ ] Run `flutter analyze` and affected Desktop tests on macOS.+- [ ] Review the full diff independently, fetch main and integrate any relevant changes; reuse checks only for unchanged inputs.+- [ ] Commit and push the branch, open a draft PR with exact evidence, report its head and any unavailable checks to the workgroup.++## Timing and evidence++Implementation started 2026-10-22 after the lead's explicit go. Record implementation, validation and publication separately in the PR; no merge or release is authorized.++## Review and scope decisions++- Independent review found two important native-queue races: a late start for the preceding follow-up invalidated the next receipt, and a matching start left the next follow-up waiting for turn end. Both were reproduced RED then fixed GREEN, including FIFO order and wrapped native prompts.+- The lead approved one test-only addition in `cli/src/services/osDevice.spec.ts` for an existing unreadable boot-command-line coverage gap on main. `osDevice.ts` remains unchanged.