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.

fix(cli): a refused dispatch and a never-created start release their machine capacity (#2361)

0xken15bfa94f6f1de6
diff --git a/cli/src/superTabs/reservations.spec.ts b/cli/src/superTabs/reservations.spec.ts
index 89974d289..529521a10 100644
--- a/cli/src/superTabs/reservations.spec.ts
+++ b/cli/src/superTabs/reservations.spec.ts
@@ -8,7 +8,7 @@ import { fakeCore } from '../testing/fakeCore.js'
import { builtinSqlite } from '../lib/sqliteBuiltin.js'
import type { CreationObservation } from '../lib/creationObservation.js'
import type { MachineResources } from '../lib/machineResources.js'
-import { CapacityReservations } from './reservations.js'
+import { CapacityReservations, START_DEADLINE_MS } from './reservations.js'
const books: CapacityReservations[] = [], folders: string[] = []
afterEach(() => { for (const book of books.splice(0)) book.stop(); for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }) })
@@ -72,7 +72,7 @@ it('keeps holding a start that has not launched, and times a launched agent the
const f = setup(), book = f.open()
free(f, 3 * GiB)
expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
- f.clock.now += 60 * MINUTE
+ f.clock.now += START_DEADLINE_MS - 1
expect(await book.reserve(agentInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
// Launched, but not in the core's live list (a reconnect in between): its window ran from the reservation and is over.
f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'agent-1' })
@@ -118,7 +118,7 @@ it('recovers an interrupted reservation reply after restart without reserving tw
expect(await second.reserve(input(1, 30, 60))).toMatchObject({ error: 'CAPACITY_RECEIPT_CONFLICT' })
})
-it.each(['missing', 'pending', 'unconfirmed', null] as const)('retains %s launches with no expiry or inferred stop', async state => {
+it.each(['missing', 'pending', 'unconfirmed', null] as const)('retains %s launches with no inferred stop', async state => {
const f = setup(), book = f.open()
await book.reserve(input())
f.native.set(id(1), state ? { creationId: id(1), state } : null)
@@ -230,7 +230,7 @@ it('keeps holding disk for a start inside its window and for one that has not la
const f = setup(), book = f.open()
freeDisk(f, 15 * GiB)
expect(await book.reserve(diskInput(1))).toMatchObject({ ok: true })
- f.clock.now += 60 * MINUTE
+ f.clock.now += START_DEADLINE_MS - 1
expect(await book.reserve(diskInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('disk') })
f.launch(1)
f.clock.now += 5 * MINUTE - 1
@@ -353,3 +353,140 @@ it('serializes real concurrent processes using one disk ledger', async () => {
expect(answers.filter(r => r.ok)).toHaveLength(1)
expect(answers.filter(r => r.error)).toEqual([expect.objectContaining({ error: 'CAPACITY_UNAVAILABLE' })])
}, 20_000)
+
+// Diego, 2026-10-30: a start the backend refused at dispatch never sent agent_create, and its row (2 GiB, 10 GiB) was held
+// for good: every later start on that machine counted it, and at 256 such rows every start there failed.
+it('gives back a start whose creation is still missing at the start deadline, so a later start is admitted', async () => {
+ const f = setup(), book = f.open(), start = (n: number) => input(n, 2 * GiB, 10 * GiB)
+ free(f, 3 * GiB); freeDisk(f, 15 * GiB)
+ expect(await book.reserve(start(1))).toMatchObject({ ok: true })
+ f.clock.now += START_DEADLINE_MS - 1
+ expect(await book.reserve(start(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('memory') })
+ free(f, 30 * GiB)
+ expect(await book.reserve(start(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('disk') })
+ free(f, 3 * GiB)
+ f.clock.now += 7 * 24 * 60 * MINUTE
+ expect(await book.reserve(start(2))).toMatchObject({ ok: true })
+ expect(await book.observe(id(1))).toMatchObject({ error: 'CAPACITY_RECEIPT_MISSING' })
+ // The review of #2361: the start may still be waiting in the backend after a host gap this long. Its next run is
+ // admitted again against what is free then, never ended: refused while start 2 holds the memory, then admitted.
+ expect(await book.reserve(start(1))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('memory') })
+ free(f, 30 * GiB); freeDisk(f, 30 * GiB)
+ expect(await book.reserve(start(1))).toMatchObject({ ok: true, reservationId: id(1) })
+ expect(await book.observe(id(1))).toMatchObject({ ok: true, released: false, harnessId: null })
+})
+
+it('times the deadline from the last run that confirmed the reservation, so a resumed start is not released under it', async () => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
+ f.clock.now += START_DEADLINE_MS - MINUTE
+ // A resume confirms the same reservation and goes on to dispatch and create.
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
+ f.clock.now += 2 * MINUTE
+ expect(await book.reserve(agentInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await book.observe(id(1))).toMatchObject({ released: false })
+ f.clock.now += START_DEADLINE_MS
+ expect(await book.reserve(agentInput(2))).toMatchObject({ ok: true })
+})
+
+it.each(['pending', 'unconfirmed', null] as const)('keeps holding a %s creation past the deadline, as it may still launch', async state => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
+ f.native.set(id(1), state ? { creationId: id(1), state } : null)
+ f.clock.now += 7 * 24 * 60 * MINUTE
+ expect(await book.reserve(agentInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await book.observe(id(1))).toMatchObject({ released: false })
+})
+
+it('keeps a launched creation that reads as missing past the deadline: its learned identity is not erased', async () => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ await book.reserve(agentInput(1))
+ f.launch(1)
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'agent-1', released: false })
+ f.native.set(id(1), { creationId: id(1), state: 'missing' })
+ f.clock.now += 7 * 24 * 60 * MINUTE
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'agent-1', released: false })
+ // Its window is over, so it no longer holds memory either way.
+ expect(await book.reserve(agentInput(2))).toMatchObject({ ok: true })
+})
+
+it('gives a deadline row back once, and never counts it below zero', async () => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ await book.reserve(agentInput(1))
+ f.clock.now += START_DEADLINE_MS
+ expect(await book.observe(id(1))).toMatchObject({ error: 'CAPACITY_RECEIPT_MISSING' })
+ expect(await book.observe(id(1))).toMatchObject({ error: 'CAPACITY_RECEIPT_MISSING' })
+ // Only the new start holds: with 3 GiB free one more 2 GiB start fits and a second does not.
+ expect(await book.reserve(agentInput(2))).toMatchObject({ ok: true })
+ expect(await book.reserve(agentInput(3))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+})
+
+it('does not release a row a run confirmed again while another start was reading it as past its deadline', async () => {
+ const f = setup(), book = f.open(), other = f.open()
+ free(f, 3 * GiB)
+ const start = f.clock.now
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
+ const gate = () => { let open!: () => void; const shut = new Promise<void>(resolve => { open = resolve }); return { shut, open, reached: false } }
+ const disk = gate(), native = gate()
+ const readDisk = f.deps.disk.getMockImplementation()!, readNative = vi.mocked(f.core.agents.creationStatus!).getMockImplementation()!
+ f.deps.disk.mockImplementationOnce(async (...args) => { disk.reached = true; await disk.shut; return readDisk(...args) })
+ // A resume just inside the deadline: its reconcile reads the row as live, then it samples the disk.
+ f.clock.now = start + START_DEADLINE_MS - 1
+ const resumed = book.reserve(agentInput(1))
+ await vi.waitFor(() => expect(disk.reached).toBe(true))
+ // Another start, past the deadline, reads the same row as missing and expired.
+ f.clock.now = start + START_DEADLINE_MS + 1
+ vi.mocked(f.core.agents.creationStatus!).mockImplementationOnce(async key => { native.reached = true; await native.shut; return readNative(key) })
+ const later = other.reserve(agentInput(2))
+ await vi.waitFor(() => expect(native.reached).toBe(true))
+ disk.open()
+ expect(await resumed).toMatchObject({ ok: true })
+ native.open()
+ expect(await later).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await book.observe(id(1))).toMatchObject({ released: false })
+})
+
+// The review of #2361: a dispatch the backend refused for now (a paused machine, a held Team account) keeps its start
+// waiting, so its row is given back and its next run reserves again.
+it('gives back the reservation of a start its machine has no creation for, and admits that start again later', async () => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true })
+ expect(await book.reserve(agentInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await book.giveBack(id(1))).toEqual({ ok: true, reservationId: id(1), returned: true })
+ expect(await book.giveBack(id(1))).toEqual({ ok: true, reservationId: id(1), returned: false })
+ expect(await book.reserve(agentInput(2))).toMatchObject({ ok: true })
+ expect(await book.reserve(agentInput(1))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ free(f, 5 * GiB)
+ expect(await book.reserve(agentInput(1))).toMatchObject({ ok: true, reservationId: id(1) })
+})
+
+it.each([
+ ['pending', { creationId: id(1), state: 'pending' as const }],
+ ['launched', { creationId: id(1), state: 'created' as const, agentId: 'agent-1' }],
+ ['unreadable', null],
+])('keeps the reservation of a %s creation when asked to give it back', async (_name, observation) => {
+ const f = setup(), book = f.open()
+ free(f, 3 * GiB)
+ await book.reserve(agentInput(1))
+ f.native.set(id(1), observation)
+ expect(await book.giveBack(id(1))).toMatchObject({ error: 'CREATION_PRESENT' })
+ expect(await book.reserve(agentInput(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+})
+
+it('keeps a launched row whose creation later reads as missing, and gives back only the creation named', async () => {
+ const f = setup(), book = f.open()
+ free(f, 5 * GiB)
+ await book.reserve(agentInput(1)); await book.reserve(agentInput(2))
+ f.launch(1)
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'agent-1' })
+ f.native.set(id(1), { creationId: id(1), state: 'missing' })
+ expect(await book.giveBack(id(1))).toEqual({ ok: true, reservationId: id(1), returned: false })
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'agent-1', released: false })
+ expect(await book.observe(id(2))).toMatchObject({ ok: true, released: false })
+ expect(await book.giveBack('not a creation id')).toEqual({ error: 'INVALID_REQUEST' })
+})
diff --git a/cli/src/superTabs/reservations.ts b/cli/src/superTabs/reservations.ts
index 564de42bb..1b8cc9bfe 100644
--- a/cli/src/superTabs/reservations.ts
+++ b/cli/src/superTabs/reservations.ts
@@ -26,6 +26,7 @@ interface Reservation {
export interface ReservationBook {
reserve(input: Json, closed?: AbortSignal): Promise<Json>
observe(creationId: unknown, closed?: AbortSignal): Promise<Json>
+ giveBack(creationId: unknown, closed?: AbortSignal): Promise<Json>
creationOf(harnessId: string): string | null
stop(): void
}
@@ -48,6 +49,13 @@ const unavailable = (detail: string): Json => ({ error: 'CAPACITY_UNAVAILABLE',
* so a reservation held past its start counted the agent twice: on Ken's MacBook Pro (2026-10-28) three settled builders
* using about 0.4 GiB held 6 GiB, and a start was refused with 7.85 GiB free. The window covers an agent still loading. */
export const START_WINDOW_MS = 5 * 60_000
+/** How long a start may hold its reservation while its machine has no creation for it: the backend's own start deadline
+ * (backend liveness.ts START_PREPARE_MS). A run reserves, claims its dispatch and sends agent_create within about two
+ * minutes, and one the backend refused at dispatch never sends it: such rows (2 GiB and 10 GiB each) were held for good on
+ * Diego's Mac (2026-10-30), and at MAX_ACTIVE of them every start there failed. Past it the row is given back, not ended:
+ * the start may still be waiting in the backend (a host asleep or down for longer), and its next run reserves again
+ * against what is free then. Each run that confirms the row restarts its deadline. */
+export const START_DEADLINE_MS = 15 * 60_000
const memoryOf = (core: CoreApi) => {
const read = createHarnessResourcesReader(() => core.agents.live())
return async () => new Map((await read()).agents.flatMap(row => row.memoryBytes === null ? [] : [[row.agentId, row.memoryBytes] as const]))
@@ -145,6 +153,7 @@ export class CapacityReservations implements ReservationBook {
}
private async reconcile(rows: Reservation[], closed?: AbortSignal): Promise<void> {
+ const deadline = this.now() - START_DEADLINE_MS
for (let index = 0; index < rows.length; index += 8) {
const observations = await Promise.all(rows.slice(index, index + 8).map(async row => {
const observation = await this.native(row.creation_id)
@@ -154,10 +163,15 @@ export class CapacityReservations implements ReservationBook {
const released = observation?.state === 'failed' || observation?.state === 'cancelled'
|| (!!harnessId && await this.core.agents.stopped?.(harnessId).catch(() => false) === true)
|| (observation?.state === 'created' && await this.core.agents.gone?.(harnessId!).catch(() => false) === true)
- return { row, harnessId, released }
+ // Only a confirmed missing creation: a pending, unconfirmed or unreadable one may still launch.
+ const expired = observation?.state === 'missing' && !harnessId
+ return { row, harnessId, released, expired }
}))
this.transaction(() => {
- for (const { row, harnessId, released } of observations) {
+ for (const { row, harnessId, released, expired } of observations) {
+ // The deadline is checked on the row as it is now: a run may have confirmed it again since it was read.
+ if (expired) this.db.prepare(`DELETE FROM reservations WHERE creation_id = ? AND fingerprint = ? AND released = 0
+ AND harness_id IS NULL AND created_at <= ?`).run(row.creation_id, row.fingerprint, deadline)
// A later reconciliation may already have learned the native ID.
// Missing/unavailable observations never erase that durable identity.
this.db.prepare(`UPDATE reservations SET harness_id = COALESCE(harness_id, ?), released = ?
@@ -192,6 +206,20 @@ export class CapacityReservations implements ReservationBook {
: { error: 'CAPACITY_RECEIPT_MISSING', detail: 'This start has no capacity receipt. Inspect the machine before starting another agent.' }
}
+ /** Gives back the reservation of a start whose dispatch the backend refused for now (superTabs/start.ts): the start keeps
+ * waiting, and its next run reserves again against what is free then. Only while its machine confirms no creation for it:
+ * a launched, pending or unreadable one may hold an agent, and keeps its row. */
+ async giveBack(creationId: unknown, closed?: AbortSignal): Promise<Json> {
+ if (!creationIdValid(creationId)) return { error: 'INVALID_REQUEST' }
+ this.check(closed)
+ const native = await this.native(creationId)
+ if (native?.state !== 'missing') return { error: 'CREATION_PRESENT', detail: 'This start may still launch on the machine, so its reservation stays.' }
+ return this.transaction(() => {
+ const gone = this.db.prepare('DELETE FROM reservations WHERE creation_id = ? AND released = 0 AND harness_id IS NULL').run(creationId) as { changes?: number }
+ return { ok: true, reservationId: creationId, returned: gone?.changes === 1 }
+ }, closed)
+ }
+
/** The Swarm start that created this harness: every start confirms the harness its native receipt names before it
* reports success, and a stopped one keeps its row. The core still checks the receipt itself. */
creationOf(harnessId: string): string | null {
@@ -224,9 +252,14 @@ export class CapacityReservations implements ReservationBook {
if (existing.volume !== destination.volume) return unavailable('The destination filesystem changed after this start reserved capacity. Inspect the machine before retrying this start.')
// Re-read under the same lock as new admissions: another request may have
// recorded a stop while this one was sampling the destination.
- return this.transaction(() => this.db.prepare('SELECT released FROM reservations WHERE creation_id = ?').get(creationId)?.released === 0
- ? { ok: true, reservationId: creationId }
- : { error: 'START_FINISHED', detail: 'This native start has ended. Create a new start request.' }, closed)
+ // A run that confirms a start not yet created goes on to dispatch and create it: its deadline starts again.
+ return this.transaction(() => {
+ if (this.db.prepare('SELECT released FROM reservations WHERE creation_id = ?').get(creationId)?.released !== 0) {
+ return { error: 'START_FINISHED', detail: 'This native start has ended. Create a new start request.' }
+ }
+ this.db.prepare('UPDATE reservations SET created_at = ? WHERE creation_id = ? AND released = 0 AND harness_id IS NULL').run(this.now(), creationId)
+ return { ok: true, reservationId: creationId }
+ }, closed)
}
if (native?.state !== 'missing') return unavailable('The machine could not confirm that this start is new. Resume its existing receipt before starting another agent.')
const freeMemory = bytes(resources?.memoryTotalBytes) && bytes(resources?.memoryUsedBytes) && resources.memoryUsedBytes <= resources.memoryTotalBytes
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 77a356dbf..54dfecfb8 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -457,13 +457,16 @@ it('keeps host capacity separate from account authority and closes it on disconn
const core = fakeCore()
const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))
const observe = vi.fn(async () => ({ ok: true, released: true }))
- const stop = vi.fn(), factory = vi.fn(() => ({ reserve, observe, creationOf: vi.fn(() => null), stop }))
+ const giveBack = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id', returned: true }))
+ const stop = vi.fn(), factory = vi.fn(() => ({ reserve, observe, giveBack, creationOf: vi.fn(() => null), stop }))
const service = superTabService(core, { reservations: factory })
const closed = new AbortController().signal
expect(factory).not.toHaveBeenCalled()
expect(await service.requests.super_tabs({ action: 'reserveCapacity', creationId: 'native-creation-id' }, visitor, closed)).toMatchObject({ ok: true })
expect(reserve).toHaveBeenCalledWith({ action: 'reserveCapacity', creationId: 'native-creation-id' }, closed)
expect(await service.requests.super_tabs({ action: 'observeCapacity', creationId: 'native-creation-id' }, visitor)).toMatchObject({ released: true })
+ expect(await service.requests.super_tabs({ action: 'returnCapacity', creationId: 'native-creation-id' }, visitor, closed)).toMatchObject({ returned: true })
+ expect(giveBack).toHaveBeenCalledWith('native-creation-id', closed)
expect(factory).toHaveBeenCalledTimes(1)
service.port.disconnected(); expect(stop).toHaveBeenCalledTimes(1)
await service.requests.super_tabs({ action: 'reserveCapacity' }, visitor)
@@ -478,7 +481,7 @@ it('keeps host capacity separate from account authority and closes it on disconn
it('gives the host this machine\'s record of the Swarm starts, to close a session the backend ends', async () => {
const core = fakeCore()
const creationOf = vi.fn((harnessId: string) => harnessId === 'harness' ? 'super-0123456789abcdef' : null)
- const factory = vi.fn(() => ({ reserve: vi.fn(), observe: vi.fn(), creationOf, stop: vi.fn() }))
+ const factory = vi.fn(() => ({ reserve: vi.fn(), observe: vi.fn(), giveBack: vi.fn(), creationOf, stop: vi.fn() }))
let options: SuperTabHostOptions = {}
const host = vi.fn((_core: unknown, _machine: string, given: SuperTabHostOptions) => {
options = given
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 2b0a12cb5..4511b0540 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -354,6 +354,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// only that host's admission/receipt, never its account or private roster.
if (payload.action === 'reserveCapacity') return await reservations().reserve(payload, closed)
if (payload.action === 'observeCapacity') return await reservations().observe(payload.creationId, closed)
+ if (payload.action === 'returnCapacity') return await reservations().giveBack(payload.creationId, closed)
// A backend-issued context scopes provenance only. Existing machine
// control is still required to open/write the native terminal itself.
if (payload.action === 'prepareNative' || payload.action === 'renewNative') {
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
index b60e283d9..bb0182a7c 100644
--- a/cli/src/superTabs/start.spec.ts
+++ b/cli/src/superTabs/start.spec.ts
@@ -4,6 +4,7 @@ import { existsSync } from 'node:fs'
import { homedir } from 'node:os'
import { BUDDY_SESSION_ENGINE, inspectCapacity, MODEL_REPORT_WAIT_MS, startAgent } from './start.js'
import { buildEngineCommandArgv } from '../lib/engineLaunch.js'
+import { SuperTabHostError } from './wire.js'
const teamDaemon = vi.hoisted(() => ({ value: false, relayed: true, offered: null as null | { slugs: string[]; listed: string[] } }))
vi.mock('./teamDaemon.js', async (original) => ({ ...await original<object>(), isTeamDaemon: () => teamDaemon.value }))
vi.mock('../team/relay.js', async (original) => ({ ...await original<object>(), teamRelayed: () => teamDaemon.relayed, offeredCodexModels: async () => teamDaemon.offered }))
@@ -1444,3 +1445,129 @@ describe('an agent that joins naming its model', () => {
expect(result).toMatchObject({ ok: true, configuration: { engine: 'codex', model: 'gpt-6-astra', effort: 'xhigh' } })
})
})
+
+// Diego, 2026-10-30: a start the backend refused at dispatch (a pause, a rule, a held Team account) had already reserved
+// 2 GiB and 10 GiB on its machine, and nothing released them: each such start held its row for good.
+describe('a dispatch claim the backend refuses', () => {
+ /** The fixture, with its dispatch claim answered by `refuse` instead. */
+ function refused(refuse: () => Promise<Record<string, unknown>>, record: Record<string, unknown> = {}) {
+ const f = fixture(), scoped = f.scoped.getMockImplementation()!
+ let claimed = false
+ f.scoped.mockImplementation(async payload => {
+ if ((payload.command as Record<string, unknown> | undefined)?.type === 'agent.startDispatch') { claimed = true; return refuse() }
+ // What the backend's record says once the claim was refused: another run's claim or failure lands in between.
+ if (payload.action === 'startStatus' && claimed) return { ok: true, value: { ...structuredClone(f.start), ...record } }
+ return scoped(payload)
+ })
+ return { f, answer: scoped }
+ }
+ const answered = (error: string, detail: string, status = 409) => async () => ({ error, detail, status })
+ const thrown = (error: string, detail: string, status = 403) => async () => { throw new SuperTabHostError(error, detail, status) }
+ const types = (f: ReturnType<typeof fixture>) => f.request.mock.calls.map(c => c[0] === 'super_tabs' ? `super_tabs:${String(c[1]?.action)}` : c[0])
+ const commands = (f: ReturnType<typeof fixture>) => f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown> | undefined).filter(Boolean)
+ const resume = (f: ReturnType<typeof fixture>) => startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)
+ const RESERVED = ['agent_create_status', 'super_tabs:capacity', 'engines_probe', 'usage_read', 'super_tabs:reserveCapacity']
+
+ it.each([
+ ['a routing rule answered to the Lead', answered('RULE_BROKEN', 'Only these machines. This start was not launched. Route again.', 403)],
+ ['a revoked grant thrown to a contributed host', thrown('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.')],
+ ['a Team account the backend fails starts for', thrown('TEAM_ACCOUNT_REQUIRED', 'This Mac has no Harness Team account.')],
+ ] as const)('cancels its creation, releases its capacity and fails the start when it can never pass: %s', async (_name, refuse) => {
+ const { f } = refused(refuse)
+ const detail = (await refuse().catch((error: Error) => ({ detail: error.message }))).detail
+ expect(await resume(f)).toMatchObject({ error: 'START_FAILED', startId: 'start', detail })
+ expect(types(f)).toEqual([...RESERVED, 'agent_create_cancel', 'super_tabs:observeCapacity'])
+ expect(f.request.mock.calls.find(c => c[0] === 'agent_create_cancel')![1]).toEqual({ creationId: 'super-native-receipt' })
+ expect(f.scoped.mock.calls.find(c => (c[0].command as Record<string, unknown> | undefined)?.type === 'agent.startFailed')![0])
+ .toMatchObject({ operationId: 'refused-start', command: { type: 'agent.startFailed', startId: 'start', error: detail } })
+ expect(f.close).toHaveBeenCalled()
+ })
+
+ // The review of #2361: these may pass by themselves, and the host retried such a start on every pass (machines.ts).
+ it.each([
+ ['a paused Swarm', answered('PAUSED', 'New work is paused in this Super Tab.')],
+ ['a paused machine, thrown to a contributed host', thrown('MACHINE_PAUSED', 'New work is paused on this machine.', 409)],
+ ['an offline machine', answered('MACHINE_OFFLINE', 'This machine is offline.')],
+ ['a Team account held for now', thrown('TEAM_ACCOUNT_HELD', 'The Harness Team account runs another project\'s Product Manager.')],
+ ['a decision the Lead owes', answered('WORKER_DECISION_REQUIRED', 'Answer the open decision first.')],
+ ['a code this client does not know', answered('SOMETHING_NEW', 'A newer refusal.', 400)],
+ ] as const)('keeps the start waiting and gives its capacity back when it may pass later: %s', async (_name, refuse) => {
+ const { f, answer } = refused(refuse)
+ const detail = (await refuse().catch((error: Error) => ({ detail: error.message }))).detail
+ await expect(resume(f)).rejects.toThrow(detail)
+ expect(types(f)).toEqual([...RESERVED, 'super_tabs:returnCapacity'])
+ expect(f.request.mock.calls.find(c => c[1]?.action === 'returnCapacity')![1]).toEqual({ action: 'returnCapacity', creationId: 'super-native-receipt' })
+ expect(commands(f).some(c => c!.type === 'agent.startFailed')).toBe(false)
+ expect(f.start.error).toBeNull()
+ // Its next run, once the refusal has passed, reserves again and launches the same creation.
+ f.scoped.mockImplementation(answer)
+ expect(await resume(f)).toMatchObject({ ok: true, harnessId: 'native' })
+ expect(f.request.mock.calls.filter(c => c[1]?.action === 'reserveCapacity')).toHaveLength(2)
+ expect(f.request.mock.calls.find(c => c[0] === 'agent_create')![1]).toMatchObject({ creationId: 'super-native-receipt' })
+ })
+
+ it.each([
+ ['a lost reply', async () => { throw new Error('socket closed') }],
+ ['a lost backend reply', async () => { throw new SuperTabHostError('BACKEND_UNAVAILABLE', 'Could not reach this Super Tab.', 503) }],
+ ['a transport code', async () => ({ error: 'BACKEND_UNREACHABLE', detail: 'unreachable', status: 502 })],
+ ['a code with no status', async () => ({ error: 'RULE_BROKEN', detail: 'Only these machines.' })],
+ ['a claim another run already holds', async () => ({ error: 'START_CLAIMED', detail: 'This native start was already requested.', status: 409 })],
+ ] as const)('keeps the creation and its capacity for %s', async (_name, refuse) => {
+ const { f } = refused(refuse)
+ await expect(resume(f)).rejects.toThrow()
+ expect(types(f)).toEqual(RESERVED)
+ expect(commands(f).some(c => c!.type === 'agent.startFailed')).toBe(false)
+ })
+
+ // The backend checks a pause, a rule and the machine before it checks the claim, so a run that claimed the start a moment
+ // earlier and is creating it now can make this run's claim read as one of them.
+ it.each([
+ ...[{ dispatched: true }, { harnessId: 'native' }, { dispatched: undefined }].map(record => ['RULE_BROKEN', record] as const),
+ ...[{ dispatched: true }, { harnessId: 'native' }].map(record => ['PAUSED', record] as const),
+ ])('keeps the creation and its capacity for a %s refusal when the start record is %o', async (code, record) => {
+ const { f } = refused(answered(code, 'Refused.'), record)
+ await expect(resume(f)).rejects.toThrow('Refused.')
+ expect(types(f)).toEqual(RESERVED)
+ })
+
+ it.each(['RULE_BROKEN', 'PAUSED'])('keeps the creation and its capacity for a %s refusal when the start record cannot be read', async code => {
+ const { f } = refused(answered(code, 'Refused.'))
+ const scoped = f.scoped.getMockImplementation()!
+ let claimed = false
+ f.scoped.mockImplementation(async payload => {
+ if ((payload.command as Record<string, unknown> | undefined)?.type === 'agent.startDispatch') claimed = true
+ return payload.action === 'startStatus' && claimed ? { error: 'BACKEND_UNREACHABLE', status: 502 } : scoped(payload)
+ })
+ await expect(resume(f)).rejects.toThrow('Refused.')
+ expect(types(f)).toEqual(RESERVED)
+ })
+
+ it('still throws the refusal when the machine cannot give the capacity back', async () => {
+ const { f } = refused(answered('PAUSED', 'New work is paused in this Super Tab.'))
+ const request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload, ms) => payload?.action === 'returnCapacity' ? Promise.reject(new Error('older daemon')) : request(type, payload, ms))
+ await expect(resume(f)).rejects.toThrow('New work is paused in this Super Tab.')
+ expect(types(f)).not.toContain('agent_create_cancel')
+ })
+
+ it.each([
+ ['its reply is lost', async () => { throw new Error('Cancellation reply interrupted') }],
+ ['it names another creation', async () => ({ creationId: 'another-creation-id', state: 'cancelled' })],
+ ['the creation launched after all', async () => ({ creationId: 'super-native-receipt', state: 'created', agent: { id: 'native' } })],
+ ] as const)('does not release the capacity when the cancel is not confirmed: %s', async (_name, cancel) => {
+ const { f } = refused(answered('RULE_BROKEN', 'Only these machines.', 403))
+ const request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload, ms) => type === 'agent_create_cancel' ? cancel() : request(type, payload, ms))
+ expect(await resume(f))
+ .toMatchObject({ error: 'START_UNCERTAIN', startId: 'start', creationId: 'super-native-receipt', detail: expect.stringContaining('Only these machines.') })
+ expect(types(f)).not.toContain('super_tabs:observeCapacity')
+ expect(commands(f).some(c => c!.type === 'agent.startFailed')).toBe(false)
+ })
+
+ it('releases without failing again a start the backend already failed', async () => {
+ const { f } = refused(thrown('TEAM_ACCOUNT_REQUIRED', 'This Mac has no Harness Team account.'), { error: 'This Mac has no Harness Team account.' })
+ expect(await resume(f)).toMatchObject({ error: 'START_FAILED', detail: 'This Mac has no Harness Team account.' })
+ expect(types(f)).toContain('super_tabs:observeCapacity')
+ expect(commands(f).some(c => c!.type === 'agent.startFailed')).toBe(false)
+ })
+})
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
index ef097460b..733e46716 100644
--- a/cli/src/superTabs/start.ts
+++ b/cli/src/superTabs/start.ts
@@ -38,9 +38,25 @@ const CANCELLED_START = 'The machine cancelled this request before starting an a
function requireSuccess(reply: Json): Json {
// The code says whether the backend answered (a refusal) or the reply was lost on the way (a transport code, or none).
if (reply.error || reply.ok !== true) throw Object.assign(new Error(String(reply.detail ?? reply.error ?? 'This Super Tab request did not succeed.')),
- { code: typeof reply.error === 'string' ? reply.error : null })
+ { code: typeof reply.error === 'string' ? reply.error : null, status: typeof reply.status === 'number' ? reply.status : null })
return object(reply.value)
}
+/** Whether the backend answered a command with its own refusal, so it did not record it: a 4xx answer with a code, as the
+ * Lead's daemon relays it or a contributed host's request throws it (wire.ts). A lost reply, a transport code or a server
+ * error may follow a recorded command and proves nothing. START_CLAIMED can mean another run of this start holds the
+ * claim and is creating it now: its row is left to the ledger's deadline (reservations.ts START_DEADLINE_MS). */
+function refusedByBackend(error: unknown): error is Error & { code: string } {
+ const { code, status } = (error ?? {}) as { code?: unknown; status?: unknown }
+ return error instanceof Error && typeof code === 'string' && code !== 'START_CLAIMED' && typeof status === 'number' && status >= 400 && status < 500
+}
+/** The backend's dispatch refusals (commands.ts agent.startDispatch, machines.ts admitMachineStart) that this start can never
+ * pass: a routing rule, its engine, its machine grant revoked or gone, the machine removed or outside the contribution, and
+ * the Team refusals the backend itself fails a start for (machines.ts LASTING_TEAM_REFUSALS). Any other code, unknown ones
+ * included, may pass by itself (a pause, an offline or full machine, a held Team account, a decision the Lead owes): that
+ * start keeps waiting, as its host retries it on every pass (superTabs/machines.ts). */
+const LASTING_REFUSALS = new Set(['RULE_BROKEN', 'REQUIREMENT_UNMET', 'REVIEW_REFUSED', 'STEPPED_UP', 'BUILD_REFUSED', 'SWARM_ENGINE',
+ 'FORBIDDEN', 'HOST_REQUIRED', 'CONTRIBUTION_REVOKED', 'MACHINE_REMOVED', 'OUTSIDE_CONTRIBUTION', 'NOT_SWARM_MACHINE', 'BUDDY_WINDOWS',
+ 'TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE'])
/** A Buddy's start note: its owner's chat, where it talks, and nothing to wait for. */
/** A project's Product Manager the Swarm started here (backend leadStart.ts): the Lead of the project's conversation, with
* the lines Desktop's own-machine launch gives one (desktop super_tabs/launch_prompt.dart). */
@@ -334,6 +350,32 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
/** Whether the agent was launched with them, so that nothing is left to switch. Unknown (undefined) when this
* invocation sent no create: a resumed start, which then reads what the agent runs. */
let launched: boolean | undefined
+ /** A dispatch the backend refused (a pause, a rule, the machine held or paused) sends no agent_create, and its reservation
+ * was held for good (Diego, 2026-10-30). The backend checks those before the claim itself, so a run that claimed this
+ * start a moment ago and is creating it now can make this one's claim read as one of them: only a start its record
+ * shows unclaimed and not launched gives anything back. One refused for now keeps waiting with its reservation given
+ * back, so its next run reserves again (the review of #2361: a paused machine's starts were lost). One refused for good
+ * is cancelled, which fences any late copy of a create, its row released and the start failed with the reason. */
+ const releaseRefused = async (refused: Error & { code: string }): Promise<Json> => {
+ const record = await scoped({ action: 'startStatus', startId }).then(requireSuccess).catch(() => null)
+ if (record?.dispatched !== false || record.harnessId) throw refused
+ if (!LASTING_REFUSALS.has(refused.code)) {
+ // An older daemon without the action keeps the row, as before; the ledger's deadline gives it back then.
+ await target.request('super_tabs', { action: 'returnCapacity', creationId }, 10_000).catch(() => null)
+ throw refused
+ }
+ const cancelled = await target.request('agent_create_cancel', { creationId }, 10_000).catch((): Json => ({}))
+ if (cancelled.error || cancelled.creationId !== creationId || cancelled.state !== 'cancelled') {
+ return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: `${refused.message} The machine did not confirm cancellation. Keep this start ID and resume it before starting another agent.` }
+ }
+ await target.request('super_tabs', { action: 'observeCapacity', creationId }, 10_000).catch(() => {})
+ // Its creation can no longer launch, so the start ends with the backend's reason and the Lead starts it elsewhere.
+ if (!record.error) {
+ requireSuccess(await scoped({ action: 'command', operationId: `refused-${startId}`, command: { type: 'agent.startFailed', startId, error: refused.message } }))
+ }
+ return { error: 'START_FAILED', startId, detail: refused.message }
+ }
try {
let refusal: string | null = null
let native = await target.request('agent_create_status', { creationId }, 10_000)
@@ -383,8 +425,13 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:
detail: reservation.detail ?? 'Update Harness on the execution machine to reserve capacity before starting this agent.' }
// A new invocation uses a new claim. A lost claim reply never authorizes
// native dispatch, even if retrying the backend operation returns a receipt.
- requireSuccess(await scoped({ action: 'command', operationId: `dispatch-${randomUUID()}`,
- command: { type: 'agent.startDispatch', startId } }))
+ try {
+ requireSuccess(await scoped({ action: 'command', operationId: `dispatch-${randomUUID()}`,
+ command: { type: 'agent.startDispatch', startId } }))
+ } catch (error) {
+ if (!refusedByBackend(error)) throw error
+ return await releaseRefused(error)
+ }
// Both direct and contributed-host starts reach this boundary. Existing
// native receipts are read above and never have their permissions changed.
// Engines without a full mode retain their existing approving launch flags.