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: closing a tab never stops a Buddy; Stop Harness and removal still do (#2270)

0xken15caa1e9bf06f7
diff --git a/cli/e2e/swarmSwitch.e2e.ts b/cli/e2e/swarmSwitch.e2e.ts
index 4efbfd7cf..d88abdf4d 100644
--- a/cli/e2e/swarmSwitch.e2e.ts
+++ b/cli/e2e/swarmSwitch.e2e.ts
@@ -44,13 +44,16 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom
}
/** What the Swarm's host keeps on a computer that contributed to one: its host file, which wakes the service at a start,
* and its retention naming `lead` as an active project's Lead, which the core never closes while the Swarm is on. */
-function swarmState(d: IsolatedDaemon, lead?: string): void {
+function swarmState(d: IsolatedDaemon, lead?: string, buddy?: string): void {
mkdirSync(join(d.dataDir, 'super-tabs'), { recursive: true, mode: 0o700 })
writeFileSync(join(d.dataDir, 'super-tabs', `host-${MACHINE}.json`), JSON.stringify({ version: 1, machineId: MACHINE }), { mode: 0o600 })
- if (lead) writeFileSync(join(d.dataDir, 'super-tabs', 'retained.json'), JSON.stringify({ version: 2, machineId: MACHINE, harnesses: [lead], leads: [lead] }), { mode: 0o600 })
+ if (lead || buddy) {
+ writeFileSync(join(d.dataDir, 'super-tabs', 'retained.json'), JSON.stringify({ version: 2, machineId: MACHINE,
+ harnesses: [lead, buddy].filter(Boolean), leads: lead ? [lead] : [], buddies: buddy ? [buddy] : [] }), { mode: 0o600 })
+ }
}
-const close = (client: LocalClient, agent: Record<string, any>) =>
- client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt, mode: 'now' }, 60_000)
+const close = (client: LocalClient, agent: Record<string, any>, mode = 'now') =>
+ client.request('agent_close', { agentId: agent.id, sessionId: agent.sessionId, createdAt: agent.createdAt, mode }, 60_000)
describe('the Swarm switch', () => {
let daemon: IsolatedDaemon | undefined
@@ -126,4 +129,23 @@ describe('the Swarm switch', () => {
expect(loaded.some((url) => url.includes('/src/superTabs/inCore.ts'))).toBe(true)
expect(loaded.some((url) => url.includes('/src/services/superTabsProcess.ts'))).toBe(true)
}, 240_000)
+
+ // Diego's Buddy, 10-30: closing the tab that showed it stopped it. A close (a window's, `harness close`, the cleanup) never
+ // stops a Buddy the host keeps, and says it kept running; Stop Harness, the machine owner's own action, still stops it
+ // (the Product Manager, 10-30).
+ it('on, a close never stops a Buddy, and Stop Harness still does', async () => {
+ const { d, client } = await fresh({ HARNESS_SWARM: '' })
+ const agent = await create(d, client, 'swarm-buddy')
+ await turn(client, agent.id, 'a Buddy answers its person')
+ await until('the Swarm\'s process, woken by its saved state', () => swarmStarts(d) > 0 || null, 60_000, 200)
+ swarmState(d, undefined, agent.id)
+ expect(await close(client, agent, 'inspect')).toMatchObject({ activity: expect.any(String), keptRunning: true })
+ for (const mode of ['idle', 'now']) {
+ expect(await close(client, agent, mode)).toMatchObject({ error: 'BUDDY_PROTECTED', keptRunning: true,
+ detail: 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.' })
+ }
+ expect((await row(client, agent.id))?.status).toBe('active')
+ expect((await client.request('agent_delete', { agentId: agent.id }, 90_000)).error).toBeUndefined()
+ await until('Stop Harness to stop the Buddy', async () => ((await row(client, agent.id))?.status ?? 'stopped') !== 'active' || null, 60_000, 500)
+ }, 240_000)
})
diff --git a/cli/src/core/agents/close.spec.ts b/cli/src/core/agents/close.spec.ts
index 907f3f8b5..826cdfc1c 100644
--- a/cli/src/core/agents/close.spec.ts
+++ b/cli/src/core/agents/close.spec.ts
@@ -51,6 +51,13 @@ describe('closing agents no window shows', () => {
expect(close.changed).toBe(deps.announceSession)
})
+ // Diego's Buddy, 10-30: the close service refuses a Buddy only if the guard the core is handed reaches it.
+ it('hands the close service the Lead and Buddy guards it was given', () => {
+ const leadProtected = (id: string) => id === 'lead', buddyProtected = (id: string) => id === 'buddy'
+ const { close } = setup({ leadProtected, buddyProtected })
+ expect([close.leadProtected?.('lead'), close.buddyProtected?.('buddy'), close.buddyProtected?.('lead')]).toEqual([true, true, false])
+ })
+
it('reads from its pane whether it waits at a question its engine asks before any conversation', async () => {
const at = (screen: string) => setup({ captureTerminal: vi.fn(async () => screen) }).close.atStartupQuestion!(row({ sessionId: '' }))
expect(await at(TAKEOVER.CLAUDE_MCP_SERVER_PROMPT)).toBe(true)
diff --git a/cli/src/core/agents/close.ts b/cli/src/core/agents/close.ts
index 251d6a133..4d5827068 100644
--- a/cli/src/core/agents/close.ts
+++ b/cli/src/core/agents/close.ts
@@ -37,6 +37,8 @@ export interface ClosingDeps {
stoppedAgents?: Pick<StoppedAgentStore, 'get' | 'resumeReservedAt'>
/** Whether the agent may be a Lead, which is never closed, as core/main.ts hands it in; absent, none is. */
leadProtected?: (agentId: string) => boolean
+ /** Whether the agent may be a Swarm Buddy, which a close never stops, as core/main.ts hands it in; absent, none is. */
+ buddyProtected?: (agentId: string) => boolean
}
/** How long a close waits for an engine worker that restarted under its read, before reading once more. */
@@ -44,7 +46,7 @@ export const CLOSE_READ_RECONNECT_MS = 10_000
export function createAgentClosing({
readScreen, registry, cleanupTabs, watcher, captureTerminal, sessionTurnState, openQuestions, terminals, sessionCheckpoints,
- stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true, leadProtected,
+ stopAgent, announceSession, engineReady, stoppedAgents, nativeRecoveryReady = () => true, leadProtected, buddyProtected,
}: ClosingDeps) {
const ready = (s: RegisteredSession): boolean =>
!s.identityHold && !s.admissionHold && !s.interpretationHold && nativeRecoveryReady(s)
@@ -101,6 +103,7 @@ export function createAgentClosing({
stop: stopAgent,
changed: announceSession,
leadProtected,
+ buddyProtected,
// Not live, not being resumed, and kept as stopped with the conversation the close names: it was closed. A record
// that cannot be read says nothing, and the close is answered as changed, as before.
closedAlready: request => {
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index d66264a60..b06478f00 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -2894,7 +2894,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
announceSession,
engineReady: (engine, ms) => engineLinks.ready(engine, ms),
stoppedAgents,
- ...(swarm ? { leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId) } : {}),
+ // A Swarm Buddy keeps running when a window closes its view (Diego, 10-30); Stop Harness above still stops it.
+ ...(swarm ? {
+ leadProtected: (agentId: string) => swarm.mayBeLead(env.ADAPTER_DATA_DIR, agentId),
+ buddyProtected: (agentId: string) => swarm.mayBeBuddy(env.ADAPTER_DATA_DIR, agentId),
+ } : {}),
})
backend.closeAgentService = closing.closeAgentService
backend.closeAgentService.start()
diff --git a/cli/src/lib/closeAgentService.spec.ts b/cli/src/lib/closeAgentService.spec.ts
index aeedf751b..c4eb65d2f 100644
--- a/cli/src/lib/closeAgentService.spec.ts
+++ b/cli/src/lib/closeAgentService.spec.ts
@@ -1,6 +1,6 @@
import { screenFor } from '../engines/screens.js'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { CloseAgentService, LEAD_PROTECTED_DETAIL, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'
+import { BUDDY_PROTECTED_DETAIL, CloseAgentService, LEAD_PROTECTED_DETAIL, inspectCloseActivity as inspectCloseReading, type CloseActivity, type CloseAgentServiceDeps, type AgentCloseRequest } from './closeAgentService.js'
import { registry, type RegisteredSession } from './registry.js'
import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
@@ -65,6 +65,33 @@ it.each(['now', 'idle', 'after_task'] as const)('refuses to close a Swarm Lead (
svc.dispose()
})
+// Diego's Buddy, 10-30: closing the tab that showed it stopped it, and two proposals waited 30 minutes. A close of a Buddy
+// is refused at once, before anything is read, saved or stopped, and says it kept running: a window closes only its view.
+it.each(['now', 'idle', 'after_task'] as const)('refuses to close a Swarm Buddy (%s), which keeps running', async mode => {
+ const svc = new CloseAgentService({ ...deps, buddyProtected: id => id === row.agentId })
+ expect(await svc.request(request(mode))).toEqual({ error: 'BUDDY_PROTECTED', detail: BUDDY_PROTECTED_DETAIL, keptRunning: true })
+ expect(BUDDY_PROTECTED_DETAIL).toBe('This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.')
+ expect(registry.byAgent(row.agentId)?.closePlan).toBeUndefined()
+ expect(deps.activity).not.toHaveBeenCalled()
+ expect(deps.stop).not.toHaveBeenCalled()
+ expect(registry.byAgent(row.agentId)).toBe(row)
+ // A review before a close still reads it, and says it will keep running, so no window asks to stop it.
+ expect(await svc.request(request('inspect'))).toEqual({ activity: 'idle', keptRunning: true })
+ // Cancelling a plan saved before it was a Buddy still clears it.
+ expect(await svc.request(request('cancel'))).toEqual({ cancelled: true })
+ svc.dispose()
+})
+
+it('closes a Buddy again once its person removed it (the guard no longer names it)', async () => {
+ let buddy = true
+ const svc = new CloseAgentService({ ...deps, buddyProtected: () => buddy })
+ expect(await svc.request(request('now'))).toMatchObject({ error: 'BUDDY_PROTECTED' })
+ buddy = false
+ expect(await svc.request(request('now'))).toEqual({ closed: true })
+ expect(deps.stop).toHaveBeenCalledTimes(1)
+ svc.dispose()
+})
+
it.each(['before', 'activity', 'checkpoint'] as const)('an expired native close lease preserves the worker at %s', async phase => {
const guarded = { ...request('now'), expiresAt: time + 1 }
if (phase === 'before') time += 2
diff --git a/cli/src/lib/closeAgentService.ts b/cli/src/lib/closeAgentService.ts
index c58010320..e5023b4b2 100644
--- a/cli/src/lib/closeAgentService.ts
+++ b/cli/src/lib/closeAgentService.ts
@@ -18,9 +18,14 @@ export type AgentClosePlan = {
}
/** Why the Lead of an active Swarm project is not closed (owner, 2026-10-23: it is never stopped, in any case). */
export const LEAD_PROTECTED_DETAIL = 'This harness is the Product Manager of a Swarm project. Delete its project first to stop it.'
+/** Why a Swarm Buddy is not closed (Diego, 10-30: closing the tab that showed his Buddy stopped it, and two proposals
+ * waited 30 minutes). A window closes only its view; the machine's owner still stops it with Stop Harness. */
+export const BUDDY_PROTECTED_DETAIL = 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.'
export type AgentCloseRequest = { agentId: string; sessionId: string; createdAt: string; mode: CloseMode; onlyIfHidden?: boolean; onlyIfOriginalLaunch?: boolean; expiresAt?: number }
/** `withoutConversation`: closed while still starting, before Harness could read its conversation, so none is kept. */
-export type AgentCloseResult = { closed?: true; withoutConversation?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity }
+/** `keptRunning`: a close refused for a session that keeps running on purpose (a Swarm Buddy): a window closes its view and
+ * stops nothing, as it does for a Swarm pane (desktop app_state.dart `canStop`). */
+export type AgentCloseResult = { closed?: true; withoutConversation?: true; deferred?: true; cancelled?: true; error?: string; detail?: string; activity?: CloseActivity; keptRunning?: true }
/**
* How long a close waits for a harness still starting to bind its first conversation, trying again meanwhile.
@@ -115,6 +120,8 @@ export interface CloseAgentServiceDeps {
closedAlready?(request: AgentCloseRequest): boolean
/** Whether the agent may be the Lead of an active Swarm project (superTabs/retention.ts `mayBeLead`): never closed. */
leadProtected?(agentId: string): boolean
+ /** Whether the agent may be a Swarm Buddy (superTabs/retention.ts `mayBeBuddy`): a close never stops it. Stop Harness does. */
+ buddyProtected?(agentId: string): boolean
/** Whether its pane shows a question the engine asks before any conversation: the folder's trust, or an MCP server the
* folder brings (`trust_open`). */
atStartupQuestion?(s: RegisteredSession): Promise<boolean>
@@ -122,6 +129,9 @@ export interface CloseAgentServiceDeps {
sleep?: (ms: number) => Promise<void>
}
+/** An inspect of a Buddy, read as any other, says it will keep running, so a window does not ask to stop it. */
+const keptRunning = (result: AgentCloseResult): AgentCloseResult => result.activity ? { ...result, keptRunning: true } : result
+
class CloseRefused extends Error {
constructor(readonly activity: CloseActivity) { super('The session is not idle.') }
}
@@ -167,6 +177,10 @@ export class CloseAgentService {
if (request.mode !== 'inspect' && this.deps.leadProtected?.(request.agentId)) {
return Promise.resolve({ error: 'LEAD_PROTECTED', detail: LEAD_PROTECTED_DETAIL })
}
+ const buddy = this.deps.buddyProtected?.(request.agentId) === true
+ if (buddy && request.mode !== 'inspect') {
+ return Promise.resolve({ error: 'BUDDY_PROTECTED', detail: BUDDY_PROTECTED_DETAIL, keptRunning: true })
+ }
// A job answers only a request of its own kind. When any job running for the agent answered every
// request, a close asked for while another window (or the cleanup preview) was inspecting the agent
// was answered with that inspect's `{ activity }` and never carried out, and an inspect beside a
@@ -174,7 +188,7 @@ export class CloseAgentService {
// the job ahead of it, then runs for itself against the agent as it was when it was asked.
const key = jobKey(request)
const pending = this.jobs.get(key)
- if (pending) return pending
+ if (pending) return buddy ? pending.then(keptRunning) : pending
const target = identity(current)
const revision = this.revisions.get(request.agentId) ?? 0
const ahead = this.queues.get(request.agentId)
@@ -186,7 +200,7 @@ export class CloseAgentService {
})
this.jobs.set(key, job)
this.queues.set(request.agentId, job)
- return job
+ return buddy ? job.then(keptRunning) : job
}
/**
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 5a017c3c7..6a08c2593 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -14,7 +14,7 @@ import { hostForm, swarmReply } from './fixtures/read/index.js'
import { CONTINUE } from './limitResume.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads } from './swarmReads.js'
-import { retainedHarnesses, retentionFile } from './retention.js'
+import { mayBeBuddy, retainedHarnesses, retentionFile } from './retention.js'
import { observerSource } from './observers.js'
import { ContributedMachines } from './machines.js'
import { createAccountHttp } from '../gateway/accountHttp.js'
@@ -2521,6 +2521,23 @@ describe('closing the sessions the backend ends', () => {
expect(t.commands).toHaveLength(1)
})
+ // Diego, 10-30: a close never stops a Buddy, yet its person removing it must. The host drops the Buddy from what it keeps
+ // before it closes the session, so the core's close guard no longer names it when the close arrives.
+ it('closes a Buddy its person removed, which the close guard no longer names by then', async () => {
+ const buddy = { tabId: 'tab', active: false, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', buddyOf: { personId: 'diego', generation: 'g1' } } }
+ const t = lifeFixture([buddy])
+ const guardAtClose: boolean[] = []
+ t.closeMember.mockImplementation(async () => { guardAtClose.push(mayBeBuddy(t.core.dataDir, 'harness')); return { closed: true as const } })
+ await t.poll()
+ expect([mayBeBuddy(t.core.dataDir, 'harness'), retainedHarnesses(t.core.dataDir).has('harness')]).toEqual([true, true])
+ expect(t.closeMember).not.toHaveBeenCalled()
+ t.rows.splice(0, 1, ended({ active: false }))
+ await t.poll()
+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))
+ expect(guardAtClose).toEqual([false])
+ expect(t.closeMember).toHaveBeenCalledWith('harness', undefined)
+ })
+
// Lead, 10-30: a Buddy removed, its person gone from the Swarm, or its chat purged with its project: the Swarm ends its
// session, and what its person sent it is listed no longer, rather than for the rest of the day. Its session need not run.
it('forgets what a Buddy\'s person sent it once the Swarm ends its session, and keeps other sessions\' lists', async () => {
diff --git a/cli/src/superTabs/inCore.ts b/cli/src/superTabs/inCore.ts
index fa287aba5..ca93f97e8 100644
--- a/cli/src/superTabs/inCore.ts
+++ b/cli/src/superTabs/inCore.ts
@@ -19,6 +19,6 @@ export { createSwarmAgents } from './inCore/agents.js'
export { SWARM_LAUNCH } from './inCore/launch.js'
export { createConfidentialPurge, isTeamDaemon, purgeRecord, teamAppPolicyFor } from './inCore/teamApps.js'
export { typesWhileBusy } from './inCore/deliveries.js'
-export { mayBeLead, retainedHarnesses, retainedLeads } from './retention.js'
+export { mayBeBuddy, mayBeLead, retainedHarnesses, retainedLeads } from './retention.js'
export { forwardAttachmentUpload } from '../lib/superTabAttachmentProxy.js'
export { startSuperTabs } from '../services/superTabs.js'
diff --git a/cli/src/superTabs/retention.spec.ts b/cli/src/superTabs/retention.spec.ts
index 9b419b062..170f7716b 100644
--- a/cli/src/superTabs/retention.spec.ts
+++ b/cli/src/superTabs/retention.spec.ts
@@ -2,7 +2,7 @@ import { mkdtempSync, readFileSync, rmSync, statSync, unlinkSync, utimesSync, wr
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
-import { mayBeLead, RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retainedLeads, retentionFile } from './retention.js'
+import { mayBeBuddy, mayBeLead, RETENTION_LAPSE_MS, retainContributions, retainedHarnesses, retainedLeads, retentionFile } from './retention.js'
const roots: string[] = []
const root = () => { const dir = mkdtempSync(join(tmpdir(), 'super-retention-')); roots.push(dir); return dir }
@@ -108,3 +108,56 @@ it('keeps a session the backend ends only while it was already a member', () =>
retainContributions(dir, 'machine', [], now)
expect([...retainedHarnesses(dir, now)]).toEqual([])
})
+
+// Diego's Buddy, 10-30: closing the tab that showed it stopped it, for 30 minutes, while two proposals waited. A Buddy is in
+// no open group and is no Lead, so nothing kept it. The server's roster marks it (its agent's buddyOf); only that keeps it.
+it('keeps a Buddy the roster marks, in no open group, until the roster ends or drops it', () => {
+ const dir = root(), now = Date.now()
+ const buddy = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', agent: { harnessId: 'buddy', machineId: 'machine', buddyOf: { personId: 'diego', generation: 'g1' } }, ...extra })
+ expect(mayBeBuddy(dir, 'buddy')).toBe(false)
+ retainContributions(dir, 'machine', [buddy({ active: false, lead: false }), row('worker', { active: false }), row('claims', { active: false, buddyOf: { personId: 'diego' } })], now)
+ expect([mayBeBuddy(dir, 'buddy'), mayBeBuddy(dir, 'worker'), mayBeBuddy(dir, 'claims')]).toEqual([true, false, false])
+ expect([...retainedHarnesses(dir, now)]).toEqual(['buddy'])
+ expect(mayBeLead(dir, 'buddy')).toBe(false)
+ // Another machine's Buddy, or a marker that is not a person's, keeps nothing here.
+ retainContributions(dir, 'machine', [buddy(), { tabId: 'tab', agent: { harnessId: 'away', machineId: 'other', buddyOf: { personId: 'diego' } } },
+ { tabId: 'tab', agent: { harnessId: 'odd', machineId: 'machine', buddyOf: { personId: '../x' } } }], now)
+ expect([mayBeBuddy(dir, 'away'), mayBeBuddy(dir, 'odd')]).toEqual([false, false])
+ // Removed by its person: the row that ends it names no Buddy, and the session stays kept only until the host closes it.
+ retainContributions(dir, 'machine', [{ tabId: 'tab', agent: { id: 'a', harnessId: 'buddy', machineId: 'machine' }, closeSession: true, active: false }], now)
+ expect(mayBeBuddy(dir, 'buddy')).toBe(false)
+ expect([...retainedHarnesses(dir, now)]).toEqual(['buddy'])
+ retainContributions(dir, 'machine', [], now)
+ expect([mayBeBuddy(dir, 'buddy'), retainedHarnesses(dir, now).has('buddy')]).toEqual([false, false])
+})
+
+// Like a Lead's (the review of #1635): a file nobody can read may name anyone, until the host's next roster rewrites it. A
+// file from before Buddies were kept names none: the next roster lists them.
+it('treats a close as possibly of a Buddy only while the file cannot be read', () => {
+ const dir = root(), file = retentionFile(dir)
+ retainContributions(dir, 'machine', [row('worker')])
+ writeFileSync(file, JSON.stringify({ version: 2, machineId: 'machine', harnesses: ['worker'], leads: [] }))
+ expect(mayBeBuddy(dir, 'worker')).toBe(false)
+ writeFileSync(file, '{')
+ expect(mayBeBuddy(dir, 'worker')).toBe(true)
+ writeFileSync(file, JSON.stringify({ version: 2, machineId: 'machine', harnesses: [], leads: [], buddies: ['../bad'] }))
+ expect(mayBeBuddy(dir, 'worker')).toBe(true)
+})
+
+// The Product Manager, 10-30: the owner of a computer always stops anything running on it with one explicit action. Stop
+// Harness refuses only a Lead (core/main.ts hands it `mayBeLead`), so a Buddy, a teammate's too, must never read as one.
+it('leaves every Buddy to Stop Harness: none reads as a Lead', () => {
+ const dir = root()
+ const buddyOf = (personId: string, harnessId: string) => ({ tabId: 'tab', agent: { harnessId, machineId: 'machine', buddyOf: { personId } }, active: false })
+ retainContributions(dir, 'machine', [buddyOf('owner', 'own-buddy'), buddyOf('teammate', 'their-buddy'), row('lead', { lead: true })])
+ expect([mayBeBuddy(dir, 'own-buddy'), mayBeBuddy(dir, 'their-buddy')]).toEqual([true, true])
+ expect([mayBeLead(dir, 'own-buddy'), mayBeLead(dir, 'their-buddy'), mayBeLead(dir, 'lead')]).toEqual([false, false, true])
+})
+
+// Unlike a Lead, a Buddy lapses with the roster: a machine signed out or unlinked for a week keeps no Buddy from a close.
+it('lets a Buddy lapse with a roster nobody confirms for a week', () => {
+ const dir = root(), now = Date.now()
+ retainContributions(dir, 'machine', [{ tabId: 'tab', agent: { harnessId: 'buddy', machineId: 'machine', buddyOf: { personId: 'diego' } } }], now)
+ expect(mayBeBuddy(dir, 'buddy', now + RETENTION_LAPSE_MS - 1000)).toBe(true)
+ expect(mayBeBuddy(dir, 'buddy', now + RETENTION_LAPSE_MS + 1000)).toBe(false)
+})
diff --git a/cli/src/superTabs/retention.ts b/cli/src/superTabs/retention.ts
index 1d8c2852c..0261d8263 100644
--- a/cli/src/superTabs/retention.ts
+++ b/cli/src/superTabs/retention.ts
@@ -11,8 +11,10 @@ import { dirname, join } from 'node:path'
import { identifier, object } from './wire.js'
/** `leads`: the Leads of active projects here, which never lapse (owner, 2026-10-23: the Lead of an active project is never
- * stopped in any case). Absent in a file from before Leads were kept. */
-interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[] }
+ * stopped in any case). Absent in a file from before Leads were kept.
+ * `buddies`: the Buddies here, which a close never stops (Diego, 10-30): only their person removing them, or the machine's
+ * owner with Stop Harness. Absent in a file from before Buddies were kept, which names none until the next roster. */
+interface Retention { version: 2; machineId: string; harnesses: string[]; leads?: string[]; buddies?: string[] }
export const retentionFile = (dataDir: string) => join(dataDir, 'super-tabs', 'retained.json')
export const RETENTION_LAPSE_MS = 7 * 24 * 60 * 60_000
const REFRESH_MS = 60 * 60_000
@@ -22,7 +24,8 @@ function read(file: string): Retention {
let value: Record<string, unknown> = {}
try { value = object(JSON.parse(readFileSync(file, 'utf8'))) } catch { /* reported below */ }
if (value.version !== 2 || !identifier(value.machineId) || !Array.isArray(value.harnesses) || !value.harnesses.every(identifier)
- || (value.leads !== undefined && (!Array.isArray(value.leads) || !value.leads.every(identifier)))) {
+ || (value.leads !== undefined && (!Array.isArray(value.leads) || !value.leads.every(identifier)))
+ || (value.buddies !== undefined && (!Array.isArray(value.buddies) || !value.buddies.every(identifier)))) {
throw new Error('Super Tab retention is unreadable. Automatic cleanup is paused.')
}
return value as unknown as Retention
@@ -53,6 +56,15 @@ export function mayBeLead(dataDir: string, agentId: string): boolean {
} catch { return true }
}
+/** Whether a close may reach a Buddy, for the core's close guard. Like `mayBeLead`, a file that cannot be read may name
+ * anyone until the host's next roster rewrites it; with no file, or one from before Buddies were kept, none is. Unlike a
+ * Lead, a Buddy lapses with a roster nobody confirms for a week, as every other member does. */
+export function mayBeBuddy(dataDir: string, agentId: string, now = Date.now()): boolean {
+ const file = retentionFile(dataDir)
+ if (!existsSync(file) || now - statSync(file).mtimeMs > RETENTION_LAPSE_MS) return false
+ try { return (read(file).buddies ?? []).includes(agentId) } catch { return true }
+}
+
export function retainContributions(dataDir: string, machineId: string, rows: unknown[], now = Date.now()): void {
if (!identifier(machineId)) throw new Error('Invalid Super Tab retention machine.')
const file = retentionFile(dataDir)
@@ -60,7 +72,7 @@ export function retainContributions(dataDir: string, machineId: string, rows: un
// file and another identity's entry. Unchanged rosters only refresh the lapse clock.
let previous: Retention | null = null
try { if (existsSync(file)) previous = read(file) } catch { /* rebuilt below */ }
- const ids = new Set<string>(), leads = new Set<string>()
+ const ids = new Set<string>(), leads = new Set<string>(), buddies = new Set<string>()
for (const item of rows) {
const row = object(item), agent = object(row.agent)
if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId) continue
@@ -70,11 +82,14 @@ export function retainContributions(dataDir: string, machineId: string, rows: un
if (previous?.machineId === machineId && previous.harnesses.includes(agent.harnessId)) ids.add(agent.harnessId)
continue
}
+ // A Buddy is in no open group, yet waits for its person however long (backend tidy.ts). Only the server marks one (its
+ // agent's buddyOf, set when a person adds their Buddy); a row that ends it carries no agent record, so it is no Buddy.
+ if (identifier(object(agent.buddyOf).personId)) buddies.add(agent.harnessId)
if (row.lead === true) leads.add(agent.harnessId)
- else if (row.active === false) continue
+ else if (row.active === false && !buddies.has(agent.harnessId)) continue
ids.add(agent.harnessId)
}
- const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort() }
+ const next: Retention = { version: 2, machineId, harnesses: [...ids].sort(), leads: [...leads].sort(), buddies: [...buddies].sort() }
if (previous && JSON.stringify(previous) === JSON.stringify(next)) {
if (now - statSync(file).mtimeMs > REFRESH_MS) utimesSync(file, new Date(now), new Date(now))
return
diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dart
index 0e03d33be..48d895c91 100644
--- a/desktop/test/session_close_test.dart
+++ b/desktop/test/session_close_test.dart
@@ -30,6 +30,11 @@ class _CloseConnection extends WsConn {
final targetedFailures = <(String, String), Map<String, dynamic>>{};
final requests = <String>[];
final closedOnInspect = <String>{};
+
+ /// Swarm Buddies, as the daemon guards them (CLI closeAgentService.ts
+ /// BUDDY_PROTECTED): an inspect reads them and says they keep running, and
+ /// every close is refused, saying the same.
+ final buddies = <String>{};
Completer<Map<String, dynamic>>? inspecting;
/// Runs as the daemon takes a close, before it answers: what the window
@@ -51,6 +56,21 @@ class _CloseConnection extends WsConn {
final mode = payload['mode'] as String;
final agentId = payload['agentId'] as String;
await whileClosing?.call(mode);
+ if (buddies.contains(agentId) && mode != 'cancel') {
+ if (mode == 'inspect') {
+ return {'activity': activities[agentId] ?? 'idle', 'keptRunning': true};
+ }
+ throw WsRequestFailure(
+ responseType: 'agent_close_result',
+ code: 'BUDDY_PROTECTED',
+ detail: 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.',
+ payload: const {
+ 'error': 'BUDDY_PROTECTED',
+ 'detail': 'This is a Swarm Buddy. Its person removes it from the Swarm, or Stop Harness stops it.',
+ 'keptRunning': true,
+ },
+ );
+ }
if (targetedFailures[(agentId, mode)] ?? failures[mode]
case final failure?) {
// Real WsConn throws refusals; returning a map would skip the production
@@ -921,6 +941,36 @@ void main() {
await tester.pumpWidget(const SizedBox());
});
+ // Diego's Buddy, 10-30: closing the tab that showed it stopped it, and two
+ // proposals waited 30 minutes. The tab closes; the Buddy, mid-answer, keeps
+ // running: no prompt to stop it, no Stop, no Stop Harness.
+ for (final activity in ['idle', 'working']) {
+ testWidgets(
+ 'closing a tab holding only a Buddy ($activity) closes the tab and keeps the Buddy',
+ (tester) async {
+ connection.buddies.add('a0');
+ connection.activities['a0'] = activity;
+ app.adoptSessionForTest(terminal('a0', []));
+ final tab = app.activeSwarm;
+ await mount(tester, app);
+ // Not awaited first: a prompt to stop it would hold the close open.
+ final closing = app.requestCloseSwarm(tab.id);
+ await tester.pumpAndSettle();
+ expect(find.byType(Dialog), findsNothing);
+ await closing;
+ expect(modes(), ['inspect', 'idle']);
+ expect(connection.requests, isNot(contains('agent_delete')));
+ expect(app.swarms, isNot(contains(tab)));
+ expect(app.allPanes, isEmpty);
+ expect(
+ app.stateOf('m')!.agents.where((a) => a.id == 'a0' && !a.isStopped),
+ hasLength(1),
+ );
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+
testWidgets('an inspection failure stops no member of the tab', (
tester,
) async {