Skip to content

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

Swarm New project: no 500 on a busy Swarm, no stuck Leads, a stuck request can be dropped (#1722)

0xken1548806588e899
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 80fb8b073..8bf5e56c4 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -88,15 +88,39 @@ const cleanupRows = (tabId: string, state: SuperTabState, machineId: string, own
* Swarms only waiting for this machine to close a removed agent's session. */
const HOST_TABS = { orderBy: { updatedAt: 'desc' as const }, take: 100 }
-/** Retrying a transaction never repeats a host action. All effects here are durable database writes. */
-async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promise<T>): Promise<T> {
- for (let attempt = 0; ; attempt++) {
- try { return await db.$transaction(body) } catch (error) {
- const code = error && typeof error === 'object' && 'code' in error ? error.code : null
- if (attempt >= 4 || (code !== 'P2034' && code !== 'P2002')) throw error
+/**
+ * Retrying a transaction never repeats a host action. All effects here are durable database writes.
+ *
+ * Every command rewrites the whole Swarm row, and a busy Swarm is written every few seconds: on 2026-10-26 a
+ * 1.16 MB row (revision 213,9xx) lost all five back-to-back retries of a person's `agent.add` to its agents' and
+ * hosts' writes, and the form showed a 500 on every Check status. Retries now wait, growing and jittered, and a
+ * command that still cannot get in says the Swarm is busy, as a 503: every client retries a 5xx, while a 4xx is final
+ * (a 409 would stop a host's terminal recording for good, cli superTabs/native.ts). The 5 s default
+ * transaction timeout also expired on that row's reads; Mongo's own transient errors (a lock wait) retry too.
+ */
+export async function transaction<T>(db: Pick<PrismaClient, '$transaction'>, body: (tx: Transaction) => Promise<T>,
+ sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms))): Promise<T> {
+ for (let attempt = 1; ; attempt++) {
+ try { return await db.$transaction(body, TRANSACTION_OPTIONS) } catch (error) {
+ if (!retryable(error)) throw error
+ if (attempt >= TRANSACTION_ATTEMPTS) {
+ // A unique key still taken after every retry is a real duplicate, not contention.
+ if ((error as { code?: unknown }).code === 'P2002') throw error
+ fail('SWARM_BUSY', 'This Swarm is busy. Try again in a moment.', 503)
+ }
+ await sleep(Math.random() * Math.min(TRANSACTION_BACKOFF_CAP_MS, TRANSACTION_BACKOFF_MS * 2 ** (attempt - 1)))
}
}
}
+const TRANSACTION_OPTIONS = { maxWait: 5_000, timeout: 15_000 }
+const TRANSACTION_ATTEMPTS = 8
+const TRANSACTION_BACKOFF_MS = 50
+const TRANSACTION_BACKOFF_CAP_MS = 1_500
+function retryable(error: unknown): boolean {
+ if (!error || typeof error !== 'object') return false
+ const code = 'code' in error ? error.code : null
+ return code === 'P2034' || code === 'P2002' || (error instanceof Error && error.message.includes('TransientTransactionError'))
+}
/** A Lead's start dispatches within seconds of being recorded; one still undispatched after this long was given up. */
export const ABANDONED_START_MS = 15 * 60_000
diff --git a/backend/src/superTabs/transaction.test.ts b/backend/src/superTabs/transaction.test.ts
new file mode 100644
index 000000000..97fd1e72a
--- /dev/null
+++ b/backend/src/superTabs/transaction.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest'
+import { transaction } from './store.js'
+import { SuperTabError } from './model.js'
+
+const conflict = () => Object.assign(new Error('Transaction failed due to a write conflict or a deadlock'), { code: 'P2034' })
+
+/** A database whose transaction fails with each of `failures` in turn, then runs the body. */
+function flaky(...failures: unknown[]) {
+ const $transaction = vi.fn(async (body: (tx: never) => Promise<unknown>, _options?: unknown) => {
+ const failure = failures.shift()
+ if (failure) throw failure
+ return body({} as never)
+ })
+ return { $transaction } as never as { $transaction: typeof $transaction }
+}
+
+describe('Swarm transactions', () => {
+ it('waits and retries a write conflict until the body gets in, with the longer timeout', async () => {
+ const db = flaky(conflict(), conflict(), conflict())
+ const waits: number[] = []
+ expect(await transaction(db as never, async () => 'done', async ms => { waits.push(ms) })).toBe('done')
+ expect(db.$transaction).toHaveBeenCalledTimes(4)
+ expect(db.$transaction.mock.calls[0][1]).toEqual({ maxWait: 5_000, timeout: 15_000 })
+ // Jittered under a cap that doubles: 50, 100, 200 ms.
+ waits.forEach((ms, i) => { expect(ms).toBeGreaterThanOrEqual(0); expect(ms).toBeLessThanOrEqual(50 * 2 ** i) })
+ })
+
+ it('retries Mongo transient errors such as a lock wait', async () => {
+ const lock = new Error('Error code 24 (LockTimeout): Unable to acquire IX lock, labels: {"TransientTransactionError"}')
+ const db = flaky(lock)
+ expect(await transaction(db as never, async () => 1, async () => {})).toBe(1)
+ })
+
+ it('never waits longer than the cap, and says the Swarm is busy once the attempts run out', async () => {
+ const db = flaky(...Array.from({ length: 8 }, conflict))
+ const waits: number[] = []
+ const failure = await transaction(db as never, async () => 1, async ms => { waits.push(ms) }).catch(error => error)
+ expect(failure).toBeInstanceOf(SuperTabError)
+ expect(failure).toMatchObject({ code: 'SWARM_BUSY', status: 503 })
+ expect(db.$transaction).toHaveBeenCalledTimes(8)
+ expect(waits).toHaveLength(7)
+ expect(Math.max(...waits)).toBeLessThanOrEqual(1_500)
+ })
+
+ it('rethrows a unique key still taken after every attempt, and anything else at once', async () => {
+ const taken = () => Object.assign(new Error('Unique constraint failed'), { code: 'P2002' })
+ const duplicate = flaky(...Array.from({ length: 8 }, taken))
+ await expect(transaction(duplicate as never, async () => 1, async () => {})).rejects.toMatchObject({ code: 'P2002' })
+ const other = flaky(new Error('boom'))
+ await expect(transaction(other as never, async () => 1, async () => {})).rejects.toThrow('boom')
+ expect(other.$transaction).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.ts
index 572c24f23..2921988c3 100644
--- a/cli/src/core/agents/create.spec.ts
+++ b/cli/src/core/agents/create.spec.ts
@@ -68,9 +68,10 @@ vi.mock('../../engines/kit/nativeHookFiles.js', () => ({
const trust = vi.hoisted(() => ({
claudeTrusts: vi.fn((_path: string) => false), codexTrusts: vi.fn((_path: string, _profile?: string | null) => false),
preTrustClaudeProject: vi.fn((_path: string): unknown => undefined), preTrustCodexProject: vi.fn((_path: string, _profile?: string | null): unknown => undefined),
+ acceptFullMode: vi.fn((_engine: string, _environment?: NodeJS.ProcessEnv): unknown => 'accepted'),
}))
-const { preTrustClaudeProject, preTrustCodexProject } = trust
-vi.mock('../../engines/launchPrep.js', () => ({ folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
+const { preTrustClaudeProject, preTrustCodexProject, acceptFullMode } = trust
+vi.mock('../../engines/launchPrep.js', () => ({ acceptFullMode: trust.acceptFullMode, folderTrust: (engine: string, profile?: string | null) => engine === 'claude'
? { trusts: (path: string) => trust.claudeTrusts(path), record: (path: string) => trust.preTrustClaudeProject(path) }
: engine === 'codex' ? { trusts: (path: string) => trust.codexTrusts(path, profile), record: (path: string) => trust.preTrustCodexProject(path, profile) } : null }))
vi.mock('../../lib/createAgentPane.js', () => ({ createAndRegisterPane: vi.fn() }))
@@ -191,6 +192,24 @@ describe('creating an agent', () => {
expect(place.swarmInstructions!.startsWith(mode === 'default' ? 'Use the swarm-dev skill for this session: the team process' : 'Use the built-in swarm-dev skill')).toBe(true)
})
+ // A Swarm Lead on the Mac Studio sat at Claude Code's "Yes, I accept" for full mode before its first turn (2026-10-26).
+ it('accepts full mode\'s warning for a Swarm agent the Swarm starts in full mode, and for nothing else', async () => {
+ await setup().create(request({ swarmRole: 'lead', permissionMode: 'full' }))
+ expect(acceptFullMode).toHaveBeenLastCalledWith('claude', undefined)
+ const launch = { current: () => true, environment: { HOME: root, CLAUDE_CONFIG_DIR: '/moved' }, prepareHooks: async () => true } as unknown as NativeLaunch
+ await setup({ native: async () => ({ ok: true, launch }) }).create(request({ swarmRole: 'dev', permissionMode: 'full' }))
+ expect(acceptFullMode).toHaveBeenLastCalledWith('claude', expect.objectContaining({ CLAUDE_CONFIG_DIR: '/moved' }))
+ await setup().create(request({ swarmRole: 'lead', permissionMode: 'auto' }))
+ await setup().create(request({ permissionMode: 'full' }))
+ expect(acceptFullMode).toHaveBeenCalledTimes(2)
+ // A settings file it cannot write leaves the engine to ask, and the launch goes on.
+ vi.mocked(acceptFullMode).mockImplementationOnce(() => { throw new Error('settings locked') }).mockImplementationOnce(() => { throw 'worse' })
+ expect(await setup().create(request({ swarmRole: 'lead', permissionMode: 'full' }))).toMatchObject({ ok: true })
+ expect(await setup().create(request({ swarmRole: 'lead', permissionMode: 'full' }))).toMatchObject({ ok: true })
+ expect(console.warn).toHaveBeenCalledWith('[agent] full mode acceptance · settings locked')
+ expect(console.warn).toHaveBeenCalledWith('[agent] full mode acceptance · worse')
+ })
+
it('keeps a selected Store harness when attaching a Swarm skill', async () => {
vi.mocked(installedDsh).mockReturnValueOnce(installed() as never).mockReturnValueOnce(installed() as never)
expect(await setup().create(request({ dsh: 'blender', swarmRole: 'dev' }))).toMatchObject({ ok: true })
diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.ts
index b7d4259e7..f0dc9d364 100644
--- a/cli/src/core/agents/create.ts
+++ b/cli/src/core/agents/create.ts
@@ -41,7 +41,7 @@ import type { LaunchAuthority, LaunchPreparation } from '../../lib/launchPrepara
import type { publishGridConfigDir } from '../../lib/publishedGridConfig.js'
import { nativeHookLocations } from '../../engines/kit/nativeLocations.js'
import { engineHooks } from '../../engines/hooks.js'
-import { folderTrust } from '../../engines/launchPrep.js'
+import { acceptFullMode, folderTrust } from '../../engines/launchPrep.js'
import { projectsRoot } from '../../lib/projectFolder.js'
import { NativeFiles } from '../../engines/kit/nativeFiles.js'
import type { registry, RegisteredSession } from '../../lib/registry.js'
@@ -285,6 +285,13 @@ export function createAgentCreator({
console.log(describeGridLaunch(engine, grid, built.launch.webSearch))
}
if (!current()) return stale()
+ // The Swarm starts its agents in full mode, so a machine that never accepted full mode's warning stops each one there
+ // before its first turn (Claude Code's "Yes, I accept", the Mac Studio, 2026-10-26). The Swarm's owner chose that mode
+ // for it; recorded the way the engine records the person's own yes, in the home this launch reads.
+ if (input.swarmRole && permissionMode === 'full') {
+ try { acceptFullMode(engine, native ? { ...native.environment, ...gridLaunch?.env, ...dshEnv } : undefined) }
+ catch (error) { console.warn(`[agent] full mode acceptance · ${error instanceof Error ? error.message : error}`) }
+ }
if (trustEmptyProject) {
try {
// A clone or user edit can arrive while dependencies are being prepared.
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index 7f729328d..e5cabff33 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -791,6 +791,29 @@ describe('agent_create with a receipt', () => {
expect(claudeTrusts).toHaveBeenCalledWith('/repo')
})
+ // WIN-DELL and the Mac Studio, 2026-10-26: Swarm Leads in a reused or fresh checkout of the project's repository sat at
+ // Claude Code's trust question, and so did the next Lead in a worktree of it, its source never answered.
+ it('trusts a Swarm agent\'s checkout of its remote project in the Swarm\'s full mode, and no other existing folder', async () => {
+ const { ask, replies } = setup()
+ const launch = async (payload: Record<string, unknown>, n: number) => { await ask({ creationId: `${CREATION}-${n}`, ...payload }); await vi.waitFor(() => expect(replies).toHaveLength(n)) }
+ const remote = { projectSource: 'remote', repositoryUrl: 'https://github.com/acme/app.git' }
+ await launch({ engine: 'claude', ...remote, swarmRole: 'lead', permissionMode: 'full' }, 1)
+ expect(preTrustClaudeProject).toHaveBeenCalledWith('/projects/prepared')
+ // The guard: the same checkout outside a Swarm or outside full mode, and a Swarm agent in a folder it was handed.
+ await launch({ engine: 'claude', ...remote, permissionMode: 'full' }, 2)
+ await launch({ engine: 'claude', ...remote, swarmRole: 'lead', permissionMode: 'auto' }, 3)
+ await launch({ engine: 'claude', cwd: dir, swarmRole: 'lead', permissionMode: 'full' }, 4)
+ await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/elsewhere', branchName: 'feature', swarmRole: 'lead', permissionMode: 'full' }, 5)
+ expect(preTrustClaudeProject).toHaveBeenCalledOnce()
+ // Claude Code only: a Codex Lead's checkout is not trusted for it.
+ await launch({ engine: 'codex', ...remote, swarmRole: 'lead', permissionMode: 'full' }, 6)
+ expect(preTrustCodexProject).not.toHaveBeenCalled()
+ // A worktree made from that checkout then inherits its answer.
+ vi.mocked(claudeTrusts).mockImplementation(path => path === '/projects/prepared')
+ await launch({ engine: 'claude', projectSource: 'worktree', gitSource: '/projects/prepared', branchName: 'feature', swarmRole: 'lead', permissionMode: 'full' }, 7)
+ expect(preTrustClaudeProject).toHaveBeenCalledTimes(2)
+ })
+
// A Codex agent on its own profile reads its trust from THAT profile's config.toml: the trust was
// read and written in ~/.codex alone, so it got Codex's trust prompt in a folder Harness had just made.
it('asks and records a Codex agent\'s trust in its own profile', async () => {
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index b2164e59c..2085c7de8 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -120,10 +120,21 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
// Only a folder this daemon just made EMPTY is one the engine need not ask about. A clone or
// the person's own repo is theirs to answer for (engines/kit/folderTrust.ts); a worktree gets only
// the answer its source repo already has. `branch` IS the source folder: nothing to record.
+ //
+ // One consented exception: a Swarm agent in the Swarm's full mode, in the checkout a remote project resolved
+ // to (cloned now, or one already there that holds that very repository). The person chose this repository
+ // and full mode for the Swarm, and machine trust favors that choice over a prompt. 2026-10-26: on WIN-DELL
+ // a Lead in a reused `harnesses\openharness` sat at Claude Code's trust question; on the Mac Studio a Lead in
+ // a fresh clone did, and the next Lead, in a worktree of it, asked again because the source had never been
+ // answered. Its Yes then landed under the source's key (Claude Code records a worktree's answer under its
+ // main repository), which made the source look trusted before the worktree started.
+ // Claude Code only: Codex's trust also sets its defaults for the person's own later sessions in that folder.
+ const swarmCheckout = input.engine === 'claude' && projectFolder.source === 'remote' && !!input.swarmRole
+ && input.permissionMode === 'full'
try {
// A Codex agent on its own profile reads its trust from that profile's config.toml, not ~/.codex.
const engineTrust = folderTrust(input.engine, input.codexHome)
- if (engineTrust && (projectFolder.source === 'new'
+ if (engineTrust && (projectFolder.source === 'new' || swarmCheckout
|| (projectFolder.source === 'worktree' && engineTrust.trusts(projectFolder.gitSource)))) {
engineTrust.record(preparedFolder)
}
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index b975f76d2..f1ff9c2f7 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -10,7 +10,7 @@ import type { RegisteredSession } from '../lib/registry.js'
import type { SessionInputDelivery } from '../lib/sessionInput.js'
import { TERMINAL_LEASE_REFUSED, type ProcessIdentity, type TerminalActionResult } from '../lib/terminalTypes.js'
import { CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'
-import { createInput, createMessageRequest, deviceInputDeps, messageWriter, sessionInputDeps, type InputDeps } from './input.js'
+import { createInput, createMessageRequest, deviceInputDeps, heldScreen, messageWriter, sessionInputDeps, type InputDeps } from './input.js'
import { createScreens } from './engines/screens.js'
import { screenFor } from '../engines/screens.js'
import { readerEngine } from '../engines/worker/protocol.js'
@@ -257,6 +257,7 @@ describe('the session input controller\'s dependencies', () => {
}),
} as unknown as InputDeps['terminal'],
})
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.useFakeTimers()
try {
const written = write('a1', 'hello')
@@ -265,9 +266,21 @@ describe('the session input controller\'s dependencies', () => {
} finally { vi.useRealTimers() }
expect(answers).toEqual([screen === null ? 'screen_unreadable' : 'prompt_hidden'])
expect(reads).toBe(13)
+ // The screen the Enter was held on is in the log, to read back what the reader missed.
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(`Enter held · ${answers[0]} · screen ${heldScreen(screen)}`))
+ warn.mockRestore()
}
})
+ it('logs the bottom of a held screen with its escapes visible, its secrets redacted and its rows cut', () => {
+ expect(heldScreen(null)).toBe('unread')
+ const rows = [...Array.from({ length: 20 }, (_, i) => `row ${i}`), '\u001b[2m───\u001b[0m', '>\u00a0token=abcdefgh1234', 'x'.repeat(500), '', ' ']
+ const logged = JSON.parse(heldScreen(rows.join('\n'))) as string[]
+ expect(logged).toHaveLength(15)
+ expect(logged[0]).toBe('row 8')
+ expect(logged.slice(-3)).toEqual(['\u001b[2m───\u001b[0m', '>\u00a0token=<redacted>', 'x'.repeat(400)])
+ })
+
it('presses the Enter of a message typed while its engine started once it binds its first conversation, and under no other change', async () => {
// An engine draws its composer before its first hook binds the conversation: a message typed in that gap
// finds its record rebuilt by the Enter. The screen is read under the record as it now stands only when it
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 42db338ee..2d2c404fa 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -15,6 +15,7 @@ import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js
import { deviceErrorText } from './cardText.js'
import { adaptSlashCommand } from '../lib/goalCommand.js'
import { sid } from '../lib/log.js'
+import { redactSecretsInText } from '../lib/logBundle.js'
import type { LiveEvent } from '../engines/kit/events.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { MoveGate } from '../lib/hostMove/gate.js'
@@ -103,10 +104,17 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminal
// Read under the record as it now stands when it is the launch typed into, bound to its first
// conversation since (sessionBinding.ts `launchBound`); under any other change, as typed, which
// the reading's fence refuses.
- const next = await readScreen(launchBound(session, resolve(id)), await captureTerminal(id))
+ const capture = await captureTerminal(id)
+ const next = await readScreen(launchBound(session, resolve(id)), capture)
const before = next ? next.messageHold : 'screen_unreadable'
if (before === 'popup_open') return null
- if (!before || !passingHold(before) || tries >= ENTER_CHECK_TRIES) return before
+ if (!before) return null
+ if (!passingHold(before) || tries >= ENTER_CHECK_TRIES) {
+ // The screen itself, as read: DESKTOP-0TFH0OJ (2026-10-25) held three Swarm messages' Enter as
+ // `prompt_hidden` while the same pane, read by hand a minute later, showed Claude Code's composer.
+ console.warn(`[inject] ${sid(id)} Enter held · ${before} · screen ${heldScreen(capture)}`)
+ return before
+ }
await new Promise((settle) => setTimeout(settle, ENTER_CHECK_RETRY_MS))
}
},
@@ -118,6 +126,17 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminal
const ENTER_CHECK_TRIES = 12
const ENTER_CHECK_RETRY_MS = 250
+/** The bottom of a capture for the log: escape sequences and odd spaces kept visible (JSON), secrets redacted,
+ * each row cut, so a composer the reader missed can be read back from the log. */
+export function heldScreen(capture: string | null): string {
+ if (capture === null) return 'unread'
+ const rows = capture.split('\n')
+ while (rows.length && !rows.at(-1)!.trim()) rows.pop()
+ return JSON.stringify(rows.slice(-HELD_SCREEN_ROWS).map((row) => redactSecretsInText(row).slice(0, HELD_SCREEN_ROW_CHARS)))
+}
+const HELD_SCREEN_ROWS = 15
+const HELD_SCREEN_ROW_CHARS = 400
+
/** What `SessionInputController` is given: every write takes the device's pane lock first. */
export function sessionInputDeps(
deps: InputDeps,
diff --git a/cli/src/engines/claude/launch.ts b/cli/src/engines/claude/launch.ts
index 64c111caa..ef0cefb1d 100644
--- a/cli/src/engines/claude/launch.ts
+++ b/cli/src/engines/claude/launch.ts
@@ -26,11 +26,25 @@ export const launch: EngineLaunch = {
* Claude Code asks "do you trust this folder?" the first time it opens a project, and keeps the answer as
* `projects[<path>].hasTrustDialogAccepted` in `.claude.json`: in CLAUDE_CONFIG_DIR, else the home folder
* itself (its own rule, 2.1.290). A yes covers the folders below. Copied from the former lib/claudeTrust.ts.
+ *
+ * A Git worktree (2.1.310, tried with the binary in a throwaway CLAUDE_CONFIG_DIR, 2026-10-26): it starts without
+ * asking when its own path, a folder above it within the worktree, or its MAIN repository says yes (`.git` →
+ * gitdir → commondir, backlink checked). Its own Yes is recorded under the main repository's key, never the
+ * worktree's. So the worktree's own path, which Harness records, is read; the main repository's key is not
+ * written, as it would answer for every worktree of that repository.
*/
trust: {
home: { variable: 'CLAUDE_CONFIG_DIR', otherwise: 'home' }, file: '.claude.json',
format: 'json', projects: 'projects', accepted: 'hasTrustDialogAccepted', entry: { allowedTools: [] },
},
+ /**
+ * "WARNING: Claude Code running in Bypass Permissions mode … Yes, I accept", the first time `--dangerously-skip-permissions`
+ * runs: a Swarm Lead on the Mac Studio sat there before its first turn (2026-10-26). Accepting writes
+ * `skipDangerousModePermissionPrompt: true` to the user settings, "Whether the user has accepted the bypass permissions
+ * mode dialog" in its settings schema, and the key its own message tells people to add (2.1.310; with it set the
+ * dialog is not shown, tried with the binary).
+ */
+ bypassAcceptance: { home: { variable: 'CLAUDE_CONFIG_DIR', otherwise: { folder: '.claude' } }, file: 'settings.json', key: 'skipDangerousModePermissionPrompt' },
/**
* `.mcp.json` in a folder above, such as the home's, is asked about as "New MCP server found in this project". Its
* default, "Continue without using this MCP server", adds the name to `disabledMcpjsonServers` in the folder's
diff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.ts
index 126629a4b..1c0050500 100644
--- a/cli/src/engines/facets/launch.ts
+++ b/cli/src/engines/facets/launch.ts
@@ -143,6 +143,14 @@ export type TrustContract = { home: LaunchHome; file: string } & (
| { format: 'toml'; table: string; key: string; value: string }
)
+/**
+ * The engine's one-time warning for the mode that approves everything, which it stops showing once `key` is true in
+ * `file` in its home: the setting its own "Yes, I accept" writes. Recorded by core, before a spawn, for a Swarm agent
+ * the Swarm starts in that mode (core/agents/create.ts); `false` there is the person's and stays. Applied by
+ * kit/folderTrust.ts `recordAcceptanceIn`.
+ */
+export interface BypassAcceptanceContract { home: LaunchHome; file: string; key: string }
+
/**
* The engine's question about MCP servers a folder inherits: a project file of servers (`file`, `servers` its map) in a
* folder ABOVE the one it opens, which it asks to use or not as it starts there. Its own "no", the question's default, is
@@ -286,6 +294,7 @@ export interface EngineLaunch {
trust?: TrustContract
/** Recorded with `trust`, for the same folders (kit/inheritedMcp.ts). */
inheritedMcp?: InheritedMcpContract
+ bypassAcceptance?: BypassAcceptanceContract
resumeRepair?: ResumeRepairContract
attribution?: AttributionContract
/** How the engine is told, as it starts, that it runs in Harness and how to use it (lib/agentAttribution.ts). */
diff --git a/cli/src/engines/kit/folderTrust.spec.ts b/cli/src/engines/kit/folderTrust.spec.ts
index 8a21ef33c..c5e369ce5 100644
--- a/cli/src/engines/kit/folderTrust.spec.ts
+++ b/cli/src/engines/kit/folderTrust.spec.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { launchClaudeConfigDir, launchCodexHome } from '../../lib/engineHomes.js'
import { launch as claude } from '../claude/launch.js'
import { launch as codex } from '../codex/launch.js'
-import { recordTrustIn, trustsIn } from './folderTrust.js'
+import { recordAcceptanceIn, recordTrustIn, trustsIn } from './folderTrust.js'
// The former lib/claudeTrust.spec.ts, its cases unchanged, against the two engines' declared trust (`trust` in
// claude/launch.ts and codex/launch.ts) applied by the kit, in the homes the former functions read.
@@ -283,3 +283,32 @@ describe('the config each engine actually reads', () => {
expect(claudeTrusts('/v')).toBe(true)
})
})
+
+// Claude Code's "Yes, I accept" for full mode writes this key to its user settings (2.1.310); a Swarm Lead on the Mac
+// Studio waited there before its first turn (2026-10-26).
+describe('full mode\'s warning accepted as the engine records it', () => {
+ const key = claude.bypassAcceptance!.key
+ it('adds the key to the settings, keeping everything else, once', () => {
+ const file = join(mkdtempSync(join(tmpdir(), 'accept-')), 'settings.json')
+ writeFileSync(file, JSON.stringify({ theme: 'dark', hooks: { Stop: [] } }))
+ expect(recordAcceptanceIn(file, key)).toBe('accepted')
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ theme: 'dark', hooks: { Stop: [] }, skipDangerousModePermissionPrompt: true })
+ expect(recordAcceptanceIn(file, key)).toBe('already')
+ })
+
+ it('creates missing settings, its folder too, holding the key alone', () => {
+ const file = join(mkdtempSync(join(tmpdir(), 'accept-')), '.claude', 'settings.json')
+ expect(recordAcceptanceIn(file, key)).toBe('accepted')
+ expect(JSON.parse(readFileSync(file, 'utf8'))).toEqual({ skipDangerousModePermissionPrompt: true })
+ expect(recordAcceptanceIn(file, key)).toBe('already')
+ })
+
+ it('leaves an unreadable or other-shaped file, and a value the person set, as it was', () => {
+ const folder = mkdtempSync(join(tmpdir(), 'accept-')), file = join(folder, 'settings.json')
+ for (const text of ['{not json', '[]', JSON.stringify({ [key]: false })]) {
+ writeFileSync(file, text)
+ expect(recordAcceptanceIn(file, key)).toBe('skipped')
+ expect(readFileSync(file, 'utf8')).toBe(text)
+ }
+ })
+})
diff --git a/cli/src/engines/kit/folderTrust.ts b/cli/src/engines/kit/folderTrust.ts
index 139d98209..d9a98122a 100644
--- a/cli/src/engines/kit/folderTrust.ts
+++ b/cli/src/engines/kit/folderTrust.ts
@@ -8,14 +8,16 @@
* of one): that answer is theirs. One consented exception is a Swarm's own project clones: clicking Add
* machine authorizes those checkouts and their Swarm agent worktrees (superTabs/cloneTrust.ts), including
* earlier contributions repaired after an update. It never authorizes the person's other repositories.
+ * The other is a Swarm agent in the Swarm's full mode in the checkout of its remote project's own repository
+ * (core/agents/launches.ts `swarmCheckout`). Any other existing folder stays the person's question.
* The callers decide (core/agents/create.ts, launches.ts). A worktree only inherits the answer its source
* repo already has.
*
* Only ever ADDS trust, never removes anything, and does nothing when the engine has never run here (no
* file), when the file does not parse, or when it already says yes.
*/
-import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
-import { posix, win32 } from 'node:path'
+import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname, posix, win32 } from 'node:path'
import type { TrustContract } from '../facets/launch.js'
type JsonTrust = Extract<TrustContract, { format: 'json' }>
@@ -92,6 +94,29 @@ function recordJson(trust: JsonTrust, file: string, cwd: string): 'trusted' | 'a
return 'trusted'
}
+/** Record the engine's acceptance of its warning for full mode (facets/launch.ts `BypassAcceptanceContract`) as `key` in
+ * the JSON settings `file`. Like trust, only ever adds: a file that is not an object, or a `key` the person set to anything
+ * else, stays as it is. A missing file is created holding the key alone: unlike `.claude.json`, which the engine writes on
+ * its first run, these settings may not exist yet on a fresh machine, whose first Lead would then stop at the warning. It is
+ * created before the engine's hooks are merged into it (core/agents/create.ts), and never over a file made meanwhile. */
+export function recordAcceptanceIn(file: string, key: string): 'accepted' | 'already' | 'skipped' {
+ if (!existsSync(file)) {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ try {
+ writeFileSync(file, JSON.stringify({ [key]: true }, null, 2), { mode: 0o600, flag: 'wx' })
+ return 'accepted'
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error
+ }
+ }
+ let settings: unknown
+ try { settings = JSON.parse(readFileSync(file, 'utf8')) } catch { return 'skipped' }
+ if (!isPlainObject(settings)) return 'skipped'
+ if (settings[key] !== undefined) return settings[key] === true ? 'already' : 'skipped'
+ replaceConfigFile(file, JSON.stringify({ ...settings, [key]: true }, null, 2))
+ return 'accepted'
+}
+
/** Its own entry, or a folder above it in the same Git repository, says yes: the inheritance Claude Code applies. Unreadable or absent
* settings read as no. */
function jsonTrusts(trust: JsonTrust, file: string, path: string): boolean {
diff --git a/cli/src/engines/kit/pane.spec.ts b/cli/src/engines/kit/pane.spec.ts
index b4ad566f6..8773ec61f 100644
--- a/cli/src/engines/kit/pane.spec.ts
+++ b/cli/src/engines/kit/pane.spec.ts
@@ -61,6 +61,21 @@ describe("Claude Code's composer on Windows", () => {
expect(composerState(defaultMode)).toBe('ready')
})
+ // DESKTOP-0TFH0OJ, 2026-10-26: in a 42-column pane Claude Code cut its footer at the edge, the composer read as absent, and
+ // each Swarm message was typed but its Enter held as `prompt_hidden`. Read through the pty host, as the daemon reads it.
+ it('finds the composer of a narrow pane, whose footer Claude Code cut at the edge', () => {
+ on('win32')
+ const narrow = (draft: string, footerRow: string) => ['✻ Brewed for 2s · done Thursday 9:07 PM', '', '─'.repeat(42),
+ `> ${draft}`, '─'.repeat(42), footerRow, ' × Auto-update failed: claude.exe in u…', ''].join('\n')
+ for (const cut of [' ⏵⏵ bypass permissions on (shift+tab to', ' ⏵⏵ bypass permi…', ' ⏸ plan mode on (shift…', ' ? for shortc…']) {
+ expect(composerState(narrow('', cut))).toBe('ready')
+ expect(composerState(narrow('[Pasted text #3 +10 lines]', cut))).toBe('ready')
+ expect(read(narrow('', cut)).hold).toBeNull()
+ }
+ // Indented output under a framed quote is still no footer.
+ expect(composerState(narrow('', ' continued output'))).not.toBe('ready')
+ })
+
it('reads Mac and Linux screens as before', () => {
on('darwin')
expect(read(claudeScreen('>'))).toMatchObject({ pane: { idle: false }, hold: 'team_waiting_idle' })
diff --git a/cli/src/engines/kit/pane.ts b/cli/src/engines/kit/pane.ts
index 76c2c734d..7b4de8157 100644
--- a/cli/src/engines/kit/pane.ts
+++ b/cli/src/engines/kit/pane.ts
@@ -214,8 +214,11 @@ function promptMarker(engine: AgentEngine): RegExp {
}
const COMPOSER_RULE = /^[─━]{3,}(?:.*[─━]{3,})?\s*$/
-/** A row only Claude Code's own footer draws: its shortcut hint, or its permission mode with the key that cycles it. */
-const CLAUDE_FOOTER = /^\s+(?:\? for shortcuts|.*\(shift\+tab to cycle\))/
+/** A row only Claude Code's own footer draws: its shortcut hint, or its permission mode with the key that cycles it. Claude
+ * Code cuts the row at the pane's width, so its start is enough: a mode's `⏵⏵`/`⏸`, or `? for sh…`. A 42-column pane on
+ * DESKTOP-0TFH0OJ (2026-10-26) showed `⏵⏵ bypass permissions on (shift+tab to`, its composer read as absent, and every
+ * Swarm message typed into it was held before its Enter as `prompt_hidden`. */
+const CLAUDE_FOOTER = /^\s+(?:\? for sh|[⏵⏸]+\s|.*\(shift\+tab to cycle\))/
/**
* The line of Claude Code's composer when it draws `>` for its marker, or -1. In the Harness terminal on Windows it draws
* `>` and a no-break space where it draws `❯` elsewhere, so the pane never read idle and every Super Tab delivery to it
diff --git a/cli/src/engines/launchPrep.spec.ts b/cli/src/engines/launchPrep.spec.ts
index 965c3a83c..b975b8c3a 100644
--- a/cli/src/engines/launchPrep.spec.ts
+++ b/cli/src/engines/launchPrep.spec.ts
@@ -1,9 +1,10 @@
+import { join } from 'node:path'
import { describe, expect, it, vi } from 'vitest'
-import { recordTrustIn, trustsIn } from './kit/folderTrust.js'
-import { folderTrust } from './launchPrep.js'
+import { recordAcceptanceIn, recordTrustIn, trustsIn } from './kit/folderTrust.js'
+import { acceptFullMode, folderTrust } from './launchPrep.js'
vi.mock('./kit/homeAdoption.js', async original => ({ ...await original<typeof import('./kit/homeAdoption.js')>(), homeIsNetworkOrDevice: (path: string) => path.startsWith('/net/') }))
-vi.mock('./kit/folderTrust.js', () => ({ trustsIn: vi.fn(() => true), recordTrustIn: vi.fn(() => 'trusted') }))
+vi.mock('./kit/folderTrust.js', () => ({ trustsIn: vi.fn(() => true), recordTrustIn: vi.fn(() => 'trusted'), recordAcceptanceIn: vi.fn(() => 'accepted') }))
describe('folder trust in a network home on Windows', () => {
it.each([['claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/net/x' }], ['codex', { HOME: '/home/u', CODEX_HOME: '/net/x' }]] as const)(
@@ -21,3 +22,15 @@ describe('folder trust in a network home on Windows', () => {
expect(trust.record('/work')).toBe('trusted')
})
})
+
+describe('full mode\'s warning accepted', () => {
+ it('in the settings.json of the CLAUDE_CONFIG_DIR the launch reads, never in a network home, and not for an engine without one', () => {
+ expect(acceptFullMode('claude', { HOME: '/home/u' })).toBe('accepted')
+ expect(recordAcceptanceIn).toHaveBeenLastCalledWith(join('/home/u', '.claude', 'settings.json'), 'skipDangerousModePermissionPrompt')
+ expect(acceptFullMode('claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/home/u/moved' })).toBe('accepted')
+ expect(recordAcceptanceIn).toHaveBeenLastCalledWith(join('/home/u/moved', 'settings.json'), 'skipDangerousModePermissionPrompt')
+ expect(acceptFullMode('claude', { HOME: '/home/u', CLAUDE_CONFIG_DIR: '/net/x' })).toBe('skipped')
+ expect(acceptFullMode('codex', { HOME: '/home/u' })).toBeNull()
+ expect(recordAcceptanceIn).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/cli/src/engines/launchPrep.ts b/cli/src/engines/launchPrep.ts
index b9802346a..0ca4af5ed 100644
--- a/cli/src/engines/launchPrep.ts
+++ b/cli/src/engines/launchPrep.ts
@@ -8,7 +8,7 @@
import { join } from 'node:path'
import { homeRoots, launchHomeOf } from '../lib/engineHomes.js'
import { homeIsNetworkOrDevice } from './kit/homeAdoption.js'
-import { recordTrustIn, trustsIn } from './kit/folderTrust.js'
+import { recordAcceptanceIn, recordTrustIn, trustsIn } from './kit/folderTrust.js'
import { recordInheritedMcp } from './kit/inheritedMcp.js'
import { repairHistory } from './kit/resumeRepair.js'
import { launchContract } from './launches.js'
@@ -54,6 +54,15 @@ export function folderTrust(engine: AgentEngine, profile?: string | null, enviro
}
}
+/** Record that full mode's one-time warning is accepted in `engine`'s settings, as its "Yes" would (`bypassAcceptance`); null
+ * for an engine with no such warning. A network or device home is never opened, as for trust. */
+export function acceptFullMode(engine: AgentEngine, environment?: NodeJS.ProcessEnv): 'accepted' | 'already' | 'skipped' | null {
+ const contract = launchContract(engine)?.bypassAcceptance
+ if (!contract) return null
+ const home = launchHomeOf(contract.home, null, environment)
+ return homeIsNetworkOrDevice(home) ? 'skipped' : recordAcceptanceIn(join(home, contract.file), contract.key)
+}
+
/** The session a resume relaunches. `codexHome` is the agent's own engine home, the row's profile. */
export interface ResumeSource {
engine: string
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 9cf55c21d..b17d3c844 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2085,6 +2085,18 @@ class AppNotifier extends ChangeNotifier {
failure['detail'] as String? ?? result['error'] as String? ?? 'The machine could not start this harness. You can change its settings and try again.',
);
}
+ // Nothing will start for these either: a cancel that went through (its
+ // journal delete did not), or a harness that started and stopped again.
+ // Read as pending, Check status repeated "not started yet" forever.
+ if (result['creationId'] == creationId &&
+ (result['state'] == 'cancelled' || result['state'] == 'unavailable')) {
+ throw SuperTabFailure(
+ 'CREATION_FAILED',
+ result['state'] == 'cancelled'
+ ? 'This startup request was cancelled. Try again to start this project.'
+ : 'The harness started and then stopped. Try again to start this project.',
+ );
+ }
if (result['creationId'] != creationId ||
result['state'] != 'created' ||
result['agent'] is! Map) {
@@ -2096,6 +2108,24 @@ class AppNotifier extends ChangeNotifier {
return Agent.fromJson(Map<String, dynamic>.from(result['agent'] as Map));
}
+ /// Asks [machineId] to drop a Swarm launch's request. The reply is its
+ /// receipt: `cancelled`, or what had already become of the request.
+ Future<Map<String, dynamic>> cancelSuperTabCreation(
+ String machineId,
+ String creationId,
+ ) async {
+ final revision = _authRevision, account = currentUser?.id;
+ final result = await _conn(machineId).request(
+ 'agent_create_cancel',
+ payload: {'creationId': creationId},
+ timeout: const Duration(seconds: 10),
+ );
+ if (!_authWorkCurrent(revision) || currentUser?.id != account) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ return result;
+ }
+
/// Where this computer keeps, per shared tab, the other accounts'
/// harnesses it has seen in the roster (R2): `{sharedTabId: [paneKey]}`,
/// one record per account, so one person's record on a shared computer
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
index 58b78c434..b93c2bd5e 100644
--- a/desktop/lib/state/harness_launch_integration.dart
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -66,4 +66,12 @@ class HarnessLaunchIntegration {
bool pending = false;
bool completed = false;
String? preparedPrompt;
+ // What a request was sent with. The journal keeps them, and a [pending]
+ // recovery shows them: Check status asks that machine, not the form's.
+ String? machineId, engine, folder;
+ // What a [pending] recovery is waiting for, in the person's words.
+ String? pendingNote;
+ // Drops a request recovery cannot finish. Null once dropped, or a question
+ // to confirm before dropping it anyway; throws when the request is kept.
+ Future<String?> Function({bool anyway})? discard;
}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 3f9dcf0db..0c3872e64 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -512,6 +512,19 @@ class NewHarnessController extends ChangeNotifier {
error = draft.error;
_warnedAboutClosing = draft.dismissalWarningShown;
}
+ // A recovering request shows what it was sent with: Check status asks
+ // its machine, whatever machine this form was opened on.
+ if (this.integration case final request? when request.pending) {
+ _machineId = request.machineId ?? _machineId;
+ if (request.engine case final engine?) {
+ _engine = engine;
+ _harnessId = null;
+ }
+ if (request.folder case final folder?) {
+ _project = NewHarnessProject.folder(folder);
+ }
+ status = request.pendingNote;
+ }
if ((projectName != null || _autoProject) &&
!checking &&
_project.folder == null &&
@@ -1290,7 +1303,8 @@ class NewHarnessController extends ChangeNotifier {
profile: _profile,
profileChosen: _profileChosen,
attempt: _attempt,
- integration: integration,
+ // A discarded request's launch is spent; the next form gets a fresh one.
+ integration: _discarded ? null : integration,
error: error,
dismissalWarningShown: _warnedAboutClosing,
projectsByMachine: Map.unmodifiable({
@@ -3773,6 +3787,46 @@ class NewHarnessController extends ChangeNotifier {
notifyListeners();
}
+ /// Only while a request is being recovered: once its creation failed, the
+ /// form is the person's again and Discard would delete what they retry.
+ bool get canDiscardPending =>
+ integration?.pending == true && integration?.discard != null;
+
+ /// The destination dropped its request; the form is closed, not reused.
+ bool get discarded => _discarded;
+ bool _discarded = false;
+
+ /// Drops a request the destination cannot finish. Null once it is gone or
+ /// kept (which the line then says), else the question to confirm before
+ /// dropping it anyway.
+ Future<String?> discardPending({bool anyway = false}) async {
+ final discard = integration?.discard;
+ if (busy || discard == null) return null;
+ busy = true;
+ error = null;
+ status = 'Discarding the request…';
+ notifyListeners();
+ try {
+ final question = await discard(anyway: anyway);
+ if (_disposed) return null;
+ busy = false;
+ status = null;
+ if (question == null) {
+ _discarded = true;
+ _attempt = null;
+ integration!
+ ..pending = false
+ ..resume = null
+ ..discard = null;
+ }
+ notifyListeners();
+ return question;
+ } catch (failure) {
+ _fail(failure.toString());
+ return null;
+ }
+ }
+
bool _warnedAboutClosing = false;
/// Every dismissal path observes the same in-flight receipt and completion.
@@ -4060,6 +4114,12 @@ class NewHarnessController extends ChangeNotifier {
final launchedWorktree =
_recoveredWorktreePreference ??
(isGitProject && !inWorktree ? worktree : null);
+ // A destination's journal keeps them for a later recovery's form.
+ // Only a real folder: a new project's or a clone's label is no path, and a
+ // recovery that unlocks the form after a failure would send it as one.
+ integration
+ ?..engine = base
+ ..folder = folder;
final failure = await app.createAgent(
_machineId,
engine: base,
@@ -4110,9 +4170,8 @@ class NewHarnessController extends ChangeNotifier {
}
destination.pending = false;
} catch (problem) {
- return _fail(
- 'Harness started. Could not join the conversation: $problem',
- );
+ // The destination says what started and what did not.
+ return _fail(problem.toString());
}
}
if (failure == null &&
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
index d8a18eb80..aec6135cf 100644
--- a/desktop/lib/super_tabs/launch.dart
+++ b/desktop/lib/super_tabs/launch.dart
@@ -129,6 +129,9 @@ class SuperTabLaunch {
: 'dev';
return prompt;
} on SuperTabFailure catch (failure) {
+ if (failure.code == 'PROJECT_UNAVAILABLE' && launch.started) {
+ integration.discard = launch.discard;
+ }
// Validation rejects the request before applying it. A lost response
// stays locked so retrying cannot create a second project or change
// the visibility of a project that may already exist.
@@ -152,9 +155,20 @@ class SuperTabLaunch {
saved['machineId'] = machine;
saved['creationId'] = receipt;
saved['phase'] = 'starting';
+ saved['engine'] = integration.engine;
+ saved['folder'] = integration.folder;
await launch.persist();
},
- complete: launch.complete,
+ complete: (machine, harnessId) async {
+ try {
+ await launch.join(machine, harnessId);
+ } catch (_) {
+ // The harness exists and its join did not finish: the journal now
+ // holds it, and the person may rather drop it than retry.
+ integration.discard = launch.discard;
+ rethrow;
+ }
+ },
stageAttachments: launch.stageAttachments,
needsAttachmentReview: () => saved['filesState'] == 'sending',
resolveAttachments: (resend) async {
@@ -180,9 +194,40 @@ class SuperTabLaunch {
}
: null,
)..pending = recovering;
+ if (recovering) {
+ integration
+ ..machineId = saved['machineId'] as String?
+ ..engine = saved['engine'] as String?
+ ..folder = saved['folder'] as String?
+ ..pendingNote = saved['phase'] == 'joining'
+ ? launch.startedNote
+ : launch.waitingNote
+ ..discard = launch.discard;
+ }
return integration;
}
+ /// A native start was asked for, so the journal must outlive this form.
+ bool get started =>
+ saved['phase'] == 'starting' || saved['phase'] == 'joining';
+ String get who => saved['lead'] == true ? 'Lead' : 'harness';
+ String get machineName {
+ final machine = saved['machineId'] as String?;
+ if (machine == null) return 'the machine';
+ return app.stateOf(machine)?.machine.displayName ?? machine;
+ }
+
+ String get startedNote =>
+ 'The $who started on $machineName. Check status to add it to the project.';
+ String get waitingNote {
+ final title =
+ saved['title'] ??
+ (saved['newProject'] == true ? 'New project' : 'Swarm');
+ return saved['lead'] == true
+ ? 'Waiting for $machineName to start the Lead for “$title”.'
+ : 'Waiting for $machineName to start the harness.';
+ }
+
void checkAccount() {
if (app.currentUser?.id != accountId) {
throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
@@ -256,12 +301,11 @@ class SuperTabLaunch {
final snapshot = SuperTabSnapshot.fromJson(superTabMap(current['state']));
final conversationId = saved['conversationId'] as String;
if (snapshot.conversation(conversationId) == null) {
- if (saved['phase'] != 'starting' && saved['phase'] != 'joining') {
- // Nothing can still be starting: reopening New Project should get a
- // fresh destination instead of loading this deleted project forever.
- await app.superTabs.storage.delete(key);
- checkAccount();
- }
+ if (started) throw projectUnavailable;
+ // Nothing can still be starting: reopening New Project should get a
+ // fresh destination instead of loading this deleted project forever.
+ await app.superTabs.storage.delete(key);
+ checkAccount();
throw const SuperTabFailure(
'PROJECT_UNAVAILABLE',
'This project is no longer available. Close this form and create a new project.',
@@ -294,6 +338,12 @@ class SuperTabLaunch {
return prompt;
}
+ // A started request's journal stays until the person discards it.
+ static const projectUnavailable = SuperTabFailure(
+ 'PROJECT_UNAVAILABLE',
+ 'This project is no longer available. Discard this request, then create a new project.',
+ );
+
Future<void> stageAttachments(
List<HarnessAttachment> files,
String prompt,
@@ -440,18 +490,146 @@ class SuperTabLaunch {
await app.superTabs.storage.delete(key);
}
+ /// [complete] in the person's words. The harness exists, so whatever went
+ /// wrong is the join, which Check status retries with the same receipt.
+ Future<void> join(
+ String machine,
+ String harnessId, {
+ Agent? recovered,
+ }) async {
+ try {
+ await complete(machine, harnessId, recovered: recovered);
+ } on SuperTabFailure catch (failure) {
+ // The backend no longer has the project's conversation.
+ if (failure.code == 'NOT_FOUND') throw projectUnavailable;
+ if (const {
+ 'ACCOUNT_CHANGED',
+ 'AGENT_UNAVAILABLE',
+ 'FILES_UNCONFIRMED',
+ }.contains(failure.code)) {
+ rethrow;
+ }
+ throw _joinFailed(failure);
+ } catch (failure) {
+ throw _joinFailed(failure);
+ }
+ }
+
+ SuperTabFailure _joinFailed(Object failure) => SuperTabFailure(
+ 'JOIN_FAILED',
+ 'The $who started on $machineName. Joining it to the project failed: '
+ '${'$failure'.replaceFirst(RegExp(r'\.$'), '')}. Check status to try again.',
+ );
+
Future<void> resume() async {
checkAccount();
final machine = saved['machineId'] as String;
- final native = await app.recoverSuperTabCreation(
- machine,
- saved['creationId'] as String,
- cancelIfMissing:
- saved['phase'] == 'starting' &&
- (saved['launchPrompt'] as String? ?? '').trim().length >
- kFirstTaskMaxLength &&
- (saved['files'] as List? ?? const []).isEmpty,
- );
- await complete(machine, native.id, recovered: native);
+ final Agent native;
+ try {
+ native = await app.recoverSuperTabCreation(
+ machine,
+ saved['creationId'] as String,
+ cancelIfMissing:
+ saved['phase'] == 'starting' &&
+ (saved['launchPrompt'] as String? ?? '').trim().length >
+ kFirstTaskMaxLength &&
+ (saved['files'] as List? ?? const []).isEmpty,
+ );
+ } on SuperTabFailure catch (failure) {
+ if (failure.code != 'CREATION_PENDING') rethrow;
+ throw SuperTabFailure(
+ 'CREATION_PENDING',
+ '$machineName has not started the $who yet.',
+ );
+ } catch (_) {
+ throw SuperTabFailure(
+ 'MACHINE_UNREACHABLE',
+ 'Could not reach $machineName. Check that it is online, then check status again.',
+ );
+ }
+ await join(machine, native.id, recovered: native);
+ }
+
+ /// [HarnessLaunchIntegration.discard]: a request that has not started is
+ /// cancelled on its machine first; one that started keeps running there.
+ Future<String?> discard({bool anyway = false}) async {
+ checkAccount();
+ // Its project goes too only when nothing can still join it: a started
+ // Lead keeps running and points at it, and one that may still start would.
+ var nothingWillJoin =
+ saved['phase'] != 'starting' && saved['phase'] != 'joining';
+ if (saved['phase'] == 'joining' && !anyway) {
+ return 'The $who keeps running on $machineName. Remove this request?';
+ }
+ if (saved['phase'] == 'starting' && !anyway) {
+ final creationId = saved['creationId'] as String;
+ final Map<String, dynamic> receipt;
+ try {
+ receipt = await app.cancelSuperTabCreation(
+ saved['machineId'] as String,
+ creationId,
+ );
+ } on SuperTabFailure {
+ rethrow;
+ } catch (_) {
+ return 'Could not reach $machineName, so it may still start the $who. Discard anyway?';
+ }
+ final state = receipt['creationId'] == creationId
+ ? receipt['state']
+ : null;
+ // A started harness can still join, so the request stays.
+ if (state == 'created') {
+ throw SuperTabFailure('CREATION_STARTED', startedNote);
+ }
+ // Unavailable: it started and is gone again, so nothing is left to keep.
+ if (!const {
+ 'cancelled',
+ 'missing',
+ 'failed',
+ 'unavailable',
+ }.contains(state)) {
+ return '$machineName is already starting the $who and could not stop it. Discard anyway?';
+ }
+ nothingWillJoin = true;
+ }
+ if (nothingWillJoin) await _deleteEmptyProject();
+ await app.superTabs.storage.delete(key);
+ checkAccount();
+ return null;
+ }
+
+ /// A new project nothing joined is only a name in the Swarm. Best effort:
+ /// a project left behind can still be deleted from its options, and must
+ /// not keep the person in this request.
+ Future<void> _deleteEmptyProject() async {
+ final projectId = saved['projectId'];
+ if (saved['newProject'] != true ||
+ saved['projectPrepared'] != true ||
+ projectId is! String) {
+ return;
+ }
+ try {
+ final current = await app.superTabs.map(
+ 'GET',
+ '/api/super-tabs/${saved['tabId']}',
+ );
+ checkAccount();
+ final snapshot = SuperTabSnapshot.fromJson(superTabMap(current['state']));
+ if (!snapshot.projects.any((p) => p.id == projectId) ||
+ snapshot.agents.any((a) => a.projectId == projectId)) {
+ return;
+ }
+ await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${saved['tabId']}/commands',
+ body: {
+ 'operationId': '${saved['operationId']}-discard',
+ 'command': {'type': 'project.delete', 'projectId': projectId},
+ },
+ );
+ } catch (_) {
+ // Unreachable, busy or not the owner's: the project stays.
+ }
+ checkAccount();
}
}
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index f35794091..1bfafc856 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -1679,11 +1679,16 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
),
],
+ // Only an error can repeat the required
+ // choice's reason; a status always shows.
if (!choosing &&
(box.error != null ||
box.status != null) &&
- box.error !=
- box.requiredChoice?.message) ...[
+ (box.error == null ||
+ box.error !=
+ box
+ .requiredChoice
+ ?.message)) ...[
const SizedBox(height: 12),
_status(),
],
@@ -2247,6 +2252,37 @@ class NewHarnessFormState extends State<NewHarnessForm> {
child: const Text('Cancel request'),
);
+ Widget _discardPendingButton() => TextButton(
+ key: const ValueKey('discard-pending-request'),
+ onPressed: box.busy ? null : () => unawaited(_discardPending()),
+ child: const Text('Discard request'),
+ );
+
+ Future<void> _discardPending() async {
+ final question = await box.discardPending();
+ if (question != null && mounted) {
+ final sure = await showDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ content: Text(question),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Keep request'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Discard anyway'),
+ ),
+ ],
+ ),
+ );
+ if (sure != true || !mounted) return;
+ await box.discardPending(anyway: true);
+ }
+ if (mounted && box.discarded) widget.onClose();
+ }
+
/// Offered beside the refusal of a typed project name whose folder is
/// already there: starts in that folder, only once pressed.
Widget _useExistingFolderButton() => TextButton(
@@ -2262,6 +2298,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (box.canCancelPending) _cancelPendingButton(),
+ if (box.canDiscardPending) _discardPendingButton(),
if (box.existingFolder != null) _useExistingFolderButton(),
if (box.integration?.roles case final roles?)
roles.isEmpty
@@ -3089,6 +3126,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
),
_buildButton(),
if (box.canCancelPending) _cancelPendingButton(),
+ if (box.canDiscardPending) _discardPendingButton(),
if (box.existingFolder != null) _useExistingFolderButton(),
if (!_picking && box.requiredChoice != null) ...[
SizedBox(height: _rowHeight),
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 4232f68fe..c23463238 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -218,6 +218,16 @@ class SuperTabFixtureConnection extends WsConn {
if (body?['command'] case final Map command
when command['type'] == 'agent.add') {
joins.add(Map<String, dynamic>.from(body!));
+ // As the backend: a deleted project's conversation is not found.
+ if (!(server.state['conversations'] as List).cast<Map>().any(
+ (g) => g['id'] == command['conversationId'],
+ )) {
+ throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This conversation is unavailable.',
+ statusCode: 404,
+ );
+ }
if (!server.receipts.containsKey(body['operationId'])) {
(server.state['agents'] as List).add({
'id': 'lead-agent',
diff --git a/desktop/test/swarm_launch_recovery_test.dart b/desktop/test/swarm_launch_recovery_test.dart
index aa35542f0..dbfcc25c7 100644
--- a/desktop/test/swarm_launch_recovery_test.dart
+++ b/desktop/test/swarm_launch_recovery_test.dart
@@ -1,12 +1,235 @@
+import 'dart:convert';
+
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/state/harness_launch_integration.dart';
import 'package:harness/state/new_harness.dart';
+import 'package:harness/super_tabs/launch.dart';
import 'package:harness/widgets/new_harness_form.dart';
import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+Map<String, dynamic>? journal(SuperTabLaunchFixture f) => f.store.values.entries
+ .where((e) => e.key.startsWith('super_tab.launch.'))
+ .map((e) => jsonDecode(e.value) as Map<String, dynamic>)
+ .firstOrNull;
+
+/// A New project whose launch reply was lost: its journal is `starting`.
+Future<SuperTabLaunchFixture> stuckProject() async {
+ final f = SuperTabLaunchFixture()..connection.loseCreate = true;
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');
+ final first = await f.box(engine: 'claude', newProject: true);
+ expect(await first.create(), NewHarnessOutcome.failed);
+ expect(journal(f)!['phase'], 'starting');
+ return f;
+}
+
+/// New project opened again, by default on another machine and agent than
+/// the request's.
+Future<NewHarnessController> reopen(
+ SuperTabLaunchFixture f, {
+ String machineId = 'elsewhere',
+}) async {
+ final box = NewHarnessController(
+ f.app,
+ machineId: machineId,
+ engine: 'codex',
+ folder: '/elsewhere',
+ integration: await SuperTabLaunch.open(
+ f.app,
+ f.app.activeSwarm,
+ 'new-project',
+ newProject: true,
+ ),
+ );
+ addTearDown(box.dispose);
+ await pumpEventQueue();
+ return box;
+}
+
void main() {
+ testWidgets('a stuck New project shows its own machine and is discarded '
+ 'there, and the next one starts fresh', (tester) async {
+ late SuperTabLaunchFixture f;
+ late NewHarnessController box;
+ late Map<String, dynamic> saved;
+ await tester.runAsync(() async {
+ f = await stuckProject();
+ // The request never reached the machine's launcher.
+ f.connection.native = null;
+ saved = journal(f)!;
+ box = await reopen(f);
+ });
+ expect(box.checking, isTrue);
+ expect(box.locked, isTrue);
+ expect(box.machineId, 'm');
+ expect(box.engine, 'claude');
+ expect(box.launchProjectLabel, 'Test host:/work/project');
+ var closed = 0;
+ await tester.binding.setSurfaceSize(const Size(1200, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox(
+ width: 850,
+ height: 500,
+ child: NewHarnessForm(
+ controller: box,
+ desktop: true,
+ onClose: () => closed++,
+ onCreated: () {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(
+ find.text('Waiting for Test host to start the Lead for “New project”.'),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Discard request'));
+ await tester.runAsync(pumpEventQueue);
+ await tester.pump();
+ expect(closed, 1);
+ expect(
+ f.connection.calls
+ .where((c) => c.$1 == 'agent_create_cancel')
+ .map((c) => c.$2['creationId']),
+ [saved['creationId']],
+ );
+ expect(journal(f), isNull);
+ // Nothing joined the project, so it goes too.
+ expect(
+ (f.connection.server.state['projects'] as List).map((p) => p['id']),
+ isNot(contains(saved['projectId'])),
+ );
+ await tester.pumpWidget(const SizedBox());
+
+ await tester.runAsync(() async {
+ final next = await reopen(f, machineId: 'm');
+ expect(next.checking, isFalse);
+ expect(next.integration!.creationId, isNot(saved['creationId']));
+ expect(
+ await next.create(),
+ NewHarnessOutcome.created,
+ reason: next.error,
+ );
+ final creations = f.connection.server.posts
+ .where((p) => (p['command'] as Map)['type'] == 'project.create')
+ .toList();
+ expect(creations, hasLength(2));
+ expect(creations.last['operationId'], isNot(saved['operationId']));
+ });
+ });
+
+ test('Discard keeps a request whose Lead already started', () async {
+ final f = await stuckProject();
+ final box = await reopen(f);
+ expect(await box.discardPending(), isNull);
+ expect(box.discarded, isFalse);
+ expect(
+ box.error,
+ 'The Lead started on Test host. Check status to add it to the project.',
+ );
+ expect(journal(f)!['phase'], 'starting');
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(journal(f), isNull);
+ });
+
+ test('Discard after a failed join leaves the Lead running', () async {
+ final f = await stuckProject();
+ final box = await reopen(f);
+ f.connection.server.refuse = {
+ 'code': 'INTERNAL',
+ 'message': 'An internal server error occurred',
+ };
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(
+ box.error,
+ 'The Lead started on Test host. Joining it to the project failed: '
+ 'An internal server error occurred. Check status to try again.',
+ );
+ expect(journal(f)!['phase'], 'joining');
+ expect(
+ await box.discardPending(),
+ 'The Lead keeps running on Test host. Remove this request?',
+ );
+ expect(journal(f), isNotNull);
+ final projectId = journal(f)!['projectId'];
+ expect(await box.discardPending(anyway: true), isNull);
+ expect(box.discarded, isTrue);
+ expect(journal(f), isNull);
+ expect(
+ f.connection.calls.map((c) => c.$1),
+ isNot(anyOf(contains('agent_create_cancel'), contains('agent_close'))),
+ );
+ // The running Lead points at its project, so the project stays.
+ expect(
+ (f.connection.server.state['projects'] as List).map((p) => p['id']),
+ contains(projectId),
+ );
+ });
+
+ test('a failed creation gives the form back without Discard', () async {
+ final f = await stuckProject();
+ final box = await reopen(f);
+ expect(box.canDiscardPending, isTrue);
+ f.connection.creationRecovery = (_, payload) async => {
+ 'creationId': payload['creationId'],
+ 'state': 'cancelled',
+ };
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(
+ box.error,
+ 'This startup request was cancelled. Try again to start this project.',
+ );
+ expect(box.checking, isFalse);
+ expect(box.canDiscardPending, isFalse);
+ });
+
+ test(
+ 'an unreachable machine keeps the request unless discarded anyway',
+ () async {
+ final f = await stuckProject();
+ final box = await reopen(f);
+ f.connection.creationRecovery = (_, _) async =>
+ throw StateError('Connection lost');
+ expect(
+ await box.discardPending(),
+ 'Could not reach Test host, so it may still start the Lead. Discard anyway?',
+ );
+ expect(journal(f), isNotNull);
+ expect(await box.discardPending(anyway: true), isNull);
+ expect(journal(f), isNull);
+ },
+ );
+
+ test('a deleted project offers Discard instead of a stuck request', () async {
+ final f = await stuckProject();
+ final projectId = journal(f)!['projectId'];
+ await f.connection.server.request(
+ 'POST',
+ '/api/super-tabs/$tabId/commands',
+ body: {
+ 'operationId': 'deleted-elsewhere',
+ 'command': {'type': 'project.delete', 'projectId': projectId},
+ },
+ );
+ final box = await reopen(f);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(
+ box.error,
+ 'This project is no longer available. Discard this request, then create a new project.',
+ );
+ expect(box.canDiscardPending, isTrue);
+ expect(await box.discardPending(anyway: true), isNull);
+ expect(journal(f), isNull);
+ });
+
for (final resend in [false, true]) {
testWidgets(
'uncertain Swarm files require an explicit resend=$resend choice',
diff --git a/docs/plans/2026-10-26-swarm-new-project-reliability.md b/docs/plans/2026-10-26-swarm-new-project-reliability.md
new file mode 100644
index 000000000..239d473d3
--- /dev/null
+++ b/docs/plans/2026-10-26-swarm-new-project-reliability.md
@@ -0,0 +1,269 @@
+# Swarm New Project reliability
+
+Status: ready to implement (2026-10-26). Owner: Ken.
+
+A Swarm's **New project** failed on three machines in one afternoon, each time for a different reason, and
+each failure left the form locked. This spec covers the four defects found. The phases are independent: each
+one can be built, reviewed and shipped on its own, in any order. Phase 1 is the most urgent.
+
+All evidence below was collected on 2026-10-26 from Ken's Mac (`MacbookPro.local`), the Windows PC
+`DESKTOP-0TFH0OJ` (`WIN-DELL`, CLI 0.4.67), the Mac Studio (`MACs-Mac-Studio.local`, CLI 0.4.68), production
+Mongo (read-only) and the backend pod logs (`argocd app logs production-autonomous-code-be`).
+
+## How New project works (what the phases touch)
+
+1. Desktop opens the New Harness form through `SuperTabLaunch.open` (`desktop/lib/super_tabs/launch.ts`),
+ which keeps a **journal** in the desktop store under
+ `super_tab.launch.<account>.<swarmTabLocalId>.new-project`
+ (`desktop/lib/screens/swarm_screen.dart:3846` passes the fixed id `new-project`).
+2. `prepare` sends `project.create` to the backend (`POST /api/super-tabs/<tab>/commands`) and records
+ `projectId` and `projectPrepared: true`.
+3. `beforeSubmit` records `machineId`, `creationId` and `phase: 'starting'`, then the native create
+ (`agent_create`) runs on the chosen machine. The machine keeps a receipt in
+ `~/.harness/cli/data/agent-creations/<creationId>.json` (+ `.claim`, `.result`).
+4. `complete` records `phase: 'joining'` and sends `agent.add` (operation id `joinId`), then
+ `project.rename`, then deletes the journal.
+5. While a journal has `phase` `starting` or `joining`, reopening New project restores it
+ (`recovering`), the form's button becomes **Check status**, and Check status calls `resume()` →
+ `AppNotifier.recoverSuperTabCreation` (`agent_create_status` on the journal's machine) → `complete`.
+
+---
+
+## Phase 1 — Backend: a busy Swarm answers its commands instead of 500
+
+### Problem
+
+`agent.add` (and any other command) on a busy Swarm fails with **500 "An internal server error occurred"**.
+The form shows "Harness started. Could not join the conversation: An internal server error occurred", and every
+Check status fails the same way.
+
+Backend log, the person's Check status at 07:15:51Z:
+
+```
+path: /api/super-tabs/c51479bd73b59e58176ad9e4/commands method: POST
+Invalid `prisma.superTab.update()` invocation: Transaction failed due to a write conflict or a deadlock.
+Please retry your transaction (Unhandled error)
+```
+
+The same 8-minute window also has, on the same Swarm: the same write conflict on `POST /native/<id>` and
+`POST /machines/<id>`, `Transaction already closed … timeout for this transaction was 5000 ms` on message and
+host reads, and `LockTimeout: Unable to acquire IX lock … within 5ms` on `SuperTabMention` /
+`SuperTabTerminalRequest`. All five backend pods (HPA max) restarted at 07:07Z.
+
+Why the Swarm conflicts: `SuperTab c51479bd73b59e58176ad9e4` has a 1.16 MB document (`state`: 195
+conversations, 134 starts, 100 releasedHarnesses), revision 213,9xx, and is written about every 3 s (four agents
+posting 8–16 commands an hour each, plus host and native writes). Every command reads and rewrites the whole
+document. `transaction()` in `backend/src/superTabs/store.ts:92` retries `P2034`/`P2002` four more times
+**immediately**, with no delay, so a slow command (contribution lookups + a 1 MB write) loses all five attempts
+to the faster writers.
+
+### Change
+
+In `backend/src/superTabs/store.ts`:
+
+- Retry `P2034` and `P2002`, and also Prisma errors whose message or meta carries Mongo's
+ `TransientTransactionError` label (the `LockTimeout` above), with **exponential backoff plus full jitter**:
+ base 50 ms, factor 2, cap 1.5 s, at most 8 attempts. Keep the existing rule that a retry never repeats a host
+ action (every effect in a transaction is a durable DB write).
+- Pass an explicit interactive-transaction `timeout` (15 s) and `maxWait` (5 s) to `db.$transaction`, so a
+ command on a large Swarm is not killed at the 5 s default.
+- When retries run out, answer `503 SWARM_BUSY` "This Swarm is busy. Try again in a moment." (the module's
+ `fail()`) instead of an unhandled 500. It must be a 5xx: every client retries a 5xx and treats a 4xx as final,
+ and a 409 on `POST /native/<id>` makes the host stop that terminal's recording for good
+ (`cli/src/superTabs/native.ts`, the `[400, 403, 404, 409]` branch). No client change is needed.
+- Check every other `$transaction` under `backend/src/superTabs/` (read paths such as conversation messages
+ and host reads hit the 5 s timeout too) and route them through the same helper.
+
+### Out of scope
+
+Shrinking the Swarm document (moving conversations, starts and released harnesses out of `state`, or
+splitting the row) is the real cure for the contention. Record it as a follow-up; do not start it here.
+
+### Tests and acceptance
+
+- Unit test the helper: a body failing with `P2034` N times then succeeding returns its value; delays grow
+ and stay within the cap (use fake timers); a non-retryable error is thrown at once; exhausting the attempts
+ throws `SWARM_BUSY` 503; a `P2002` still taken after every attempt is rethrown as it is.
+- Existing super-tab store tests stay green.
+- After deploy: Check status on the stuck Mac Studio journal (project `5701099db2a04f605ac0d4d4`, harness
+ `f34164d3-1f97-4d10-8a25-4e2fffdf2f06`) joins; pod logs show no `Unhandled error` write conflicts on
+ `/commands` for that Swarm over 30 minutes.
+
+---
+
+## Phase 2 — Desktop: a stuck New project request can be seen and dropped
+
+### Problem
+
+One journal stuck in `starting` or `joining` locks New project for its whole Swarm tab, on every machine,
+until someone edits `state.json` by hand (done twice today: Ken's Mac, and pending on WIN-DELL). Specifically:
+
+1. The journal key is fixed per tab (`…new-project`), so the next New project always restores the stuck one.
+2. While recovering, the machine and folder pickers show and accept new choices ("This Mac", "rosy-maple"),
+ but Check status ignores them and asks the **journal's** machine. Ken picked This Mac and Check status kept
+ asking WIN-DELL, then Mac Studio.
+3. There is no way out. `canCancelPending` covers only an ordinary held create (`AgentCreationAttempt`), not
+ the Swarm journal. Close twice leaves the journal in place.
+4. A journal whose project was deleted elsewhere stays forever: `prepare` deletes it only when `phase` is
+ neither `starting` nor `joining` (`launch.ts`, the `PROJECT_UNAVAILABLE` branch).
+5. The messages say nothing useful. "MACs-Mac-Studio.local has not confirmed the new harness yet" was shown while
+ the harness had been created and was waiting at Claude Code's trust prompt (see Phase 3).
+
+### Change
+
+In `desktop/lib/super_tabs/launch.ts`, `desktop/lib/state/new_harness.dart` and the form widgets:
+
+- **Show what is being checked.** While `integration.pending` (recovering), lock the engine, machine and
+ folder pickers to the journal's values (machine from `saved['machineId']`) and show a line such as
+ "Waiting for MACs-Mac-Studio.local to start the Lead for “New project”." Never display a different machine than
+ the one Check status asks.
+- **Say what the machine says.** Map `recoverSuperTabCreation` outcomes to plain lines:
+ - receipt `created`, join failed → "The Lead started on <machine>. Joining it to the project failed: <reason>.
+ Check status to try again."
+ - receipt pending/held → "<machine> has not started the Lead yet."
+ - harness created but needs the person (agent state `needs-input`) → "The Lead on <machine> is waiting for
+ you. Open it to answer." with an action that focuses that pane.
+- **Discard request.** Add a secondary action, shown only while recovering:
+ - `phase: 'starting'`: send `agent_create_cancel` for `creationId` to the journal's machine. On `cancelled`,
+ `missing` or `failed`, delete the journal. On `created`, do not delete: switch to the "Lead started" line
+ (it can still be joined).
+ - `phase: 'joining'` (harness exists, join failed): confirm "The Lead keeps running on <machine>. Remove
+ this request?" and delete the journal. Do not close the harness.
+ - Machine unreachable: say so, and keep the journal unless the person confirms "Discard anyway".
+ - If `projectPrepared` and the project has no agents, also delete the empty project (check whether a
+ `project.delete`/`project.remove` command exists in `backend/src/superTabs/commands.ts`; if none, leave the
+ project and list the gap in the PR).
+- **Deleted project.** When `prepare`/`complete` gets `PROJECT_UNAVAILABLE`, offer Discard request instead
+ of leaving the journal forever.
+- After a discard, reopening New project starts a fresh journal.
+
+### Tests and acceptance
+
+- Widget/state tests for: pickers locked and showing the journal's machine while recovering; Discard in
+ `starting` sends `agent_create_cancel` and removes the journal; `created` is not discarded; Discard in
+ `joining` removes the journal and leaves the harness; `PROJECT_UNAVAILABLE` offers Discard; the next New project
+ gets a new `operationId`/`creationId`.
+- Manual: reproduce on WIN-DELL's own Desktop, which still holds journal
+ `super_tab.launch.6a86d24c2ea251076eb4eebe.a697ce0e844cb84738fdeb5a8f0904c4.new-project` (`phase: joining`,
+ project `ed6c8957ca05794b6182a449`, harness `c25e2575`). Discard it from the form.
+
+---
+
+## Phase 3 — CLI: a Swarm Lead does not stop at Claude Code's startup dialogs
+
+### Problem
+
+Every new Lead on a machine whose folder Claude Code had not been asked about sat in `needs-input` before its
+first turn, which the form reports as "has not confirmed". Seen twice today:
+
+- **WIN-DELL, reused checkout.** The Lead's request had `projectFolder: { source: 'remote', repositoryUrl:
+ …/openharness.git }`. `prepareProjectFolder` (`cli/src/lib/projectFolder.ts:236`) found
+ `C:\Users\DELL\harnesses\openharness` already holding that repository and started there. Pre-trust is only
+ for an empty new folder or a Swarm clone (`cli/src/core/agents/create.ts:128`, `cli/src/superTabs/cloneTrust.ts`),
+ so Claude Code showed "Is this a project you created or one you trust?". Trust on the parent
+ `C:/Users/DELL/harnesses` does not count: Claude Code walks up only to the repository root.
+- **Mac Studio, worktree of a trusted repository.** The Lead ran in a new worktree
+ `/Users/mac/harnesses/worktrees/openharness/bold-pine` of `/Users/mac/harnesses/openharness`, whose
+ `~/.claude.json` entry already had `hasTrustDialogAccepted: true`. The trust prompt still appeared, the daemon
+ logged no `pre-trust` line, and after answering Yes the worktree still has no entry of its own in
+ `~/.claude.json`. `launches.ts:124-128` is meant to give a worktree its source's answer
+ (`projectFolder.source === 'worktree' && engineTrust.trusts(gitSource)`); for this launch it did not.
+ The same Lead then showed Claude Code's one-time **Bypass Permissions** acceptance ("Yes, I accept"),
+ because the Swarm forces full mode and that machine had never accepted it, and then a "Try the new fullscreen
+ renderer?" promotion.
+
+### Change
+
+1. **Find why the worktree did not inherit trust, and fix it.** Trace the Desktop New project launch with
+ Worktree on (`desktop/lib/core/project_folder.dart:185` → `agent_create` → `cli/src/core/agents/launches.ts`)
+ on Claude Code 2.1.310. Determine (a) whether this launch reaches line 127 with `source: 'worktree'`, and
+ (b) which `projects` key Claude Code reads for a git worktree (the worktree path, its main repository, or
+ its realpath), by trying it with the real binary in a throwaway `CLAUDE_CONFIG_DIR`. Record trust under the
+ key Claude Code actually reads. Name the finding in a code comment.
+2. **A Swarm Lead's reused checkout.** When a Swarm agent starts with the Swarm's forced full permission mode in
+ a folder that `prepareProjectFolder` reused because it `holdsRepository` of the project's own repository,
+ record Claude Code trust for that folder, and for a worktree made from it. The owner's standing decision is
+ that machine trust favors UX over prompts (the person chose this repository and full mode for the Swarm).
+ Keep the guard in `folderTrust.ts`: never for any other existing folder.
+3. **Bypass acceptance.** For a Swarm agent launched in full mode, apply Claude Code's documented setting
+ that records the bypass-permissions acceptance, in the same declared, data-driven way as trust
+ (`cli/src/engines/claude/launch.ts` contracts, applied by core before spawn). If Claude Code exposes no
+ setting for it, skip this item and say so in the PR.
+4. **Report what blocks a start.** When a Swarm agent's pane shows a startup modal (`trust_open`,
+ `permission_open`, a menu), its creation status should carry it, so Phase 2 can show "waiting for you"
+ rather than "not confirmed". The screen reading already classifies these (`cli/src/engines/kit/screen.ts`
+ `HOLDS`).
+
+### Tests and acceptance
+
+- Unit tests in `cli/src/engines/kit/folderTrust.spec.ts` / `launchPrep` goldens for the worktree key and the
+ reused-checkout case, including the guard (an unrelated existing folder is still not trusted).
+- `npm run test:core` at 100% for touched core files.
+- Manual: on a machine where the repository is trusted, New project with Worktree on starts a Lead that takes
+ its first turn without any prompt. On WIN-DELL with a fresh `harnesses/<repo>` checkout, the same.
+
+---
+
+## Phase 4 — CLI: a Swarm message is typed and sent on Windows
+
+### Problem
+
+On WIN-DELL, messages to the Lead (from the Swarm chat on Ken's Mac) were pasted but never submitted. The
+composer showed `> [Pasted text #3 +10 lines]`, and later deliveries waited with `team_waiting_draft`. The DELL
+daemon log (`~/.harness/cli/data/harness.log`):
+
+```
+23:38:44 [inject] 25ab99d4 typed, not sent · engine=claude · prompt_hidden opened before Enter
+23:40:14 [inject] 25ab99d4 typed, not sent · engine=claude · prompt_hidden opened before Enter
+23:42:38 [inject] 25ab99d4 typed, not sent · engine=claude · prompt_hidden opened before Enter
+```
+
+The check before Enter (`messageWriter` `beforeEnter`, `cli/src/core/input.ts`) read the pane 12 times over
+3 s, and each time `composerState` (`cli/src/engines/claude/composer.ts`) returned `absent`. Read a few
+minutes later from the console buffer, the same pane parses as `ready` with this repository's code and
+`process.platform = 'win32'`. The screen had `>` + U+00A0, `─` rules above and below, and the footer
+` ⏵⏵ bypass permissions on (shift+tab to cycle)`. CLI 0.4.67 already has the Windows `>` composer fix (#1649).
+So what the daemon read during those 3 s differed from that screen. Either it was a transient frame after the
+paste, or the pty-host capture (`op: 'capture'`, `cli/src/lib/ptyHostBackend.ts`) differs from the console.
+
+### Change
+
+1. **Log the screen the Enter was held on.** A patch exists, uncommitted, in worktree `rosy-maple`
+ (`cli/src/core/input.ts`, `cli/src/core/input.spec.ts`). When `beforeEnter` returns a hold it logs
+ `[inject] <agent> Enter held · <hold> · screen <json>`: the last 15 non-blank rows, escape sequences kept,
+ `redactSecretsInText` applied, each row cut at 400 chars (`heldScreen`). It has a test. Carry it over and
+ reimplement if needed. A dev build with it (`0.4.67-dev.ecad97507.dirty`) is installed on WIN-DELL and running.
+2. **Reproduce.** Send a multi-line message from the Swarm chat to a Claude Code Lead on WIN-DELL. Read the
+ `Enter held` line. To compare with what pty-host holds, capture through pty-host directly. A throwaway
+ script built from `cli/src/lib/ptyHost/client.ts` + `listDiscoveries(~/.harness/pty)` and run with the managed
+ node in session 1 (`schtasks /it`) works. Find the pane by `rootPid` from `op: 'inventory'` and
+ `op: 'jobPids'`.
+3. **Fix the reading** for the captured screen. Add that capture as a fixture to
+ `cli/src/engines/claude/composer.spec.ts` (and `kit/pane.spec.ts` if `claudeWindowsComposer` is involved).
+ If the capture is a transient frame, the fix may instead belong in the retry window. Then explain in the
+ comment why 3 s was not enough.
+
+### Tests and acceptance
+
+- The new fixture reads `ready`. Existing composer and pane specs stay green. `npm run test:core` passes.
+- Manual: three multi-line Swarm messages in a row to the WIN-DELL Lead are each submitted, with no
+ `typed, not sent` lines in the log.
+
+---
+
+## Machines and access for manual checks
+
+- WIN-DELL / `DESKTOP-0TFH0OJ`: `ssh [email protected]` (password auth through `expect`). Send PowerShell as
+ `-EncodedCommand`. Anything that touches the desktop session runs through `schtasks /create … /it`. A console
+ screen can be read with a small C# `AttachConsole` + `ReadConsoleOutputCharacterW` program compiled with the
+ in-box `csc.exe`. Clean up every temporary file and task.
+- Mac Studio: `ssh [email protected]` (key auth). Its host key differs from the entry in Ken's
+ `~/.ssh/known_hosts`, so use a separate known-hosts file.
+- Production Mongo is read-only (`.secrets/mongodb-prod-readonly.env`). Backend logs:
+ `argocd app logs production-autonomous-code-be --grpc-web --kind Pod --name <pod>`.
+
+## Validation and shipping
+
+Follow `docs/validation-and-release.md`. Phase 1 ships as a backend release. Phases 3–4 ship as a CLI
+release, then update WIN-DELL to it, replacing the dev build. Phase 2 ships as a Desktop release. Record the
+local coverage gates you ran in each PR.