The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Buddy: a thread can have its own Buddy session, in parallel (#2345)
0xken15e61bab0c9771
diff --git a/backend/integration/superTabBuddySessions.test.ts b/backend/integration/superTabBuddySessions.test.tsnew file mode 100644index 000000000..29d6d7378--- /dev/null+++ b/backend/integration/superTabBuddySessions.test.ts@@ -0,0 +1,339 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'+import type { Command } from '../src/superTabs/commands.js'+import { poolRows } from './hostRows.test-support.js'+import { endBuddySessions, liveBuddySessions } from '../scripts/buddy-sessions/end-all.js'++// Buddy thread sessions end to end through the store (buddySessions.ts; spec docs/superpowers/specs/2026-10-30-buddy-thread-+// sessions-design.md): a person's thread gets its own Buddy session beside the main one, which hears and answers only its+// thread, reads the main chat only up to where it started, and ends on its person's word, its host's, or its Buddy's removal.+let replica: MongoMemoryReplSet+let db: PrismaClient+const owner: AuthUser = { sub: '310000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '310000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_buddy_sessions_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const user of [owner, peer]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ for (const [machineId, user] of [['owner-mac', owner], ['peer-mac', peer]] as const) {+ await db.machine.create({ data: { machineId, userId: user.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ }+})+afterAll(async () => {+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm whose PM runs on the owner's Mac, peer a member whose Mac's host can run thread sessions (or not: `capable`). */+async function swarm({ capable = true, maxAgents = 6, engine = 'claude' } = {}) {+ // A clock the test moves on, for the start timeouts a machine's report checks (liveness.ts).+ const clock = { now: Date.now() }, running: string[] = []+ const store = new SuperTabStore(db, () => clock.now, { store: new MemoryAttachmentStore(), prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })+ const tab = (await store.create(owner, randomUUID(), 'Sessions', 'public')).id+ const execute = (command: Command, user = owner, asAgentId?: string, hostMachineId?: string) =>+ store.execute(user, tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId)+ const invitation = await execute({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)+ await execute({ type: 'agent.add', conversationId: 'lead', machineId: 'owner-mac', harnessId: randomUUID(), name: 'PM', configuration: config, lead: true })+ await execute({ type: 'machine.contribute', machineId: 'peer-mac', name: 'Peer Mac', cwd: '/swarm', scope: 'swarm', engines: engine === 'claude' ? ['claude'] : ['claude', engine], maxAgents }, peer)+ const generation = (await poolRows(store, peer, 'peer-mac')).find(p => p.tabId === tab)!.machine.generation+ /** peer-mac's report, as its host sends one every 15 seconds. */+ const report = () => store.observeMachine(peer, tab, 'peer-mac', { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9,+ diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [...running], stoppedHarnessIds: [], ...(capable ? { capabilities: ['buddySessions'] } : {}) })+ await report()+ const host = (command: Command) => execute(command, peer, undefined, 'peer-mac')+ /** peer's main Buddy, added and started by peer-mac's host. */+ const added = await execute({ type: 'buddy.create', projectId: 'lead', machineId: 'peer-mac', engine: 'claude' }, peer)+ const chat = String(added.result.conversationId)+ await host({ type: 'agent.startDispatch', startId: String(added.result.startId) })+ const mainHarness = randomUUID()+ running.push(mainHarness)+ const main = String((await host({ type: 'agent.started', startId: String(added.result.startId), harnessId: mainHarness, configuration: { ...config, engine } })).result.agentId)+ await host({ type: 'agent.startSettled', startId: String(added.result.startId), warning: null })+ /** peer's message in the main chat. */+ const say = async (text: string) => String((await execute({ type: 'message.send', conversationId: chat, text, replyTo: null, recipientIds: [] }, peer)).result.messageId)+ /** peer's reply in [root]'s thread, starting its session when `newSession`. */+ const reply = (root: string, text: string, extra: Partial<Extract<Command, { type: 'message.send' }>> = {}) =>+ execute({ type: 'message.send', conversationId: chat, text, replyTo: root, recipientIds: [], ...extra }, peer)+ /** Starts [root]'s session and its host launches it, as a running host does. */+ const session = async (root: string, text = 'Measure prod CPU for the last day') => {+ const sent = await reply(root, text, { newSession: true })+ const startId = String(sent.result.startId)+ await host({ type: 'agent.startDispatch', startId })+ const agentId = String((await host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)+ return { agentId, startId, first: String(sent.result.messageId) }+ }+ const deliveriesTo = async (agentId: string) => (await db.superTabDelivery.findMany({ where: { tabId: tab, agentId } }))+ return { store, tab, execute, host, chat, main, say, reply, session, deliveriesTo, clock, report }+}++const text = (page: { messages: Array<{ text: string }> }) => page.messages.map(m => m.text)++describe('a Buddy thread session', () => {+ it('starts from a thread reply on its Buddy\'s machine, with no message text in its start, and hears that reply once it joins', async () => {+ const f = await swarm()+ const root = await f.say('Two things today')+ const sent = await f.reply(root, 'Measure prod CPU for the last day', { newSession: true })+ const startId = String(sent.result.startId), first = String(sent.result.messageId)+ const pool = (await poolRows(f.store, peer, 'peer-mac')).find(p => p.tabId === f.tab)!+ const start = pool.buddyStarts!.find(s => s.id === startId)!+ expect(start.request).toMatchObject({ conversationId: f.chat, machineId: 'peer-mac', engine: 'claude', model: 'opus', effort: 'high',+ buddyOf: { personId: peer.sub }, buddySession: { thread: root } })+ expect(JSON.stringify(start)).not.toContain('Measure prod CPU')+ // Nobody hears it while the session starts: the main Buddy never does.+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: first } }))).toEqual([])+ await f.host({ type: 'agent.startDispatch', startId })+ const agentId = String((await f.host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)+ expect((await f.deliveriesTo(agentId)).map(d => d.messageId)).toEqual([first])+ expect((await f.deliveriesTo(f.main)).map(d => d.messageId)).not.toContain(first)+ const read = await f.store.read(peer, f.tab)+ expect(read.state.agents.find(a => a.id === agentId)).toMatchObject({ buddyOf: { personId: peer.sub }, buddySession: { thread: root } })+ // The main Buddy stays first: older clients take a Buddy chat's first agent for its Buddy.+ expect(read.state.conversations.find(c => c.id === f.chat)!.agentIds).toEqual([f.main, agentId])+ })++ it('answers a quick main-chat question while the session still holds its long one', async () => {+ const f = await swarm()+ const root = await f.say('Start here')+ const { agentId, first } = await f.session(root)+ // The session claims its long question and has not answered it.+ const long = (await f.store.deliveries(peer, f.tab, agentId)).find(d => d.messageId === first)!+ const sessionClaim = randomUUID()+ await f.store.delivery(peer, f.tab, agentId, long.id, { type: 'claim', claimId: sessionClaim })+ const quick = await f.say('What is the PR number for the login fix?')+ const waiting = (await f.store.deliveries(peer, f.tab, f.main)).find(d => d.messageId === quick)!+ const mainClaim = randomUUID()+ await f.store.delivery(peer, f.tab, f.main, waiting.id, { type: 'claim', claimId: mainClaim })+ await f.store.delivery(peer, f.tab, f.main, waiting.id, { type: 'ack', claimId: mainClaim, receipt: 'r', uncertain: false })+ await f.execute({ type: 'message.send', conversationId: f.chat, text: '#2290.', replyTo: quick, recipientIds: [] }, peer, f.main)+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: long.id } })).toMatchObject({ status: 'claimed' })+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: waiting.id } })).toMatchObject({ status: 'answered' })+ })++ it('keeps every reply in its thread: the person\'s reach it alone, and it can answer nowhere else', async () => {+ const f = await swarm()+ const root = await f.say('Start here'), elsewhere = await f.say('Another topic')+ const { agentId } = await f.session(root)+ const next = String((await f.reply(root, 'And memory too')).result.messageId)+ expect((await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: next } })).map(d => d.agentId)).toEqual([agentId])+ expect(await db.superTabMessage.findUniqueOrThrow({ where: { id: next } })).toMatchObject({ thread: root, buddySession: true })+ const post = (extra: Partial<Extract<Command, { type: 'message.send' }>>) =>+ f.execute({ type: 'message.send', conversationId: f.chat, text: 'Result', replyTo: null, recipientIds: [], ...extra }, peer, agentId)+ await expect(post({})).rejects.toMatchObject({ code: 'BUDDY_SESSION_THREAD' })+ await expect(post({ replyTo: elsewhere })).rejects.toMatchObject({ code: 'BUDDY_SESSION_THREAD' })+ await expect(post({ replyTo: next, alsoSend: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_THREAD' })+ const answer = String((await post({ replyTo: next })).result.messageId)+ expect(await db.superTabMessage.findUniqueOrThrow({ where: { id: answer } })).toMatchObject({ thread: root, buddySession: true })+ // The main Buddy never answers in it, and the person never sends it to the main chat.+ await expect(f.execute({ type: 'message.send', conversationId: f.chat, text: 'Me too', replyTo: root, recipientIds: [] }, peer, f.main))+ .rejects.toMatchObject({ code: 'BUDDY_SESSION_THREAD' })+ await expect(f.reply(root, 'Share it', { alsoSend: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_THREAD' })+ await expect(f.reply(root, 'To the main one', { recipientIds: [f.main] })).rejects.toMatchObject({ code: 'INVALID_RECIPIENT' })+ })++ it('reads its own thread and the 10 main-chat messages before it started, never later ones or another session\'s thread', async () => {+ const f = await swarm()+ const said: string[] = []+ for (let i = 1; i <= 12; i++) said.push(await f.say(`main ${i}`))+ const root = said.at(-1)!+ const a = await f.session(root)+ const later = await f.say('main after the start')+ const other = await f.say('Second topic')+ const b = await f.session(other, 'The other long question')+ // Its own chat read is its thread alone, whatever it asks for.+ const own = await f.store.messages(peer, f.tab, f.chat, {}, a.agentId)+ expect(text(own)).toEqual(['main 12', 'Measure prod CPU for the last day'])+ expect((own as { context?: Array<{ text: string }> }).context!.map(c => c.text)).toEqual(['main 3', 'main 4', 'main 5', 'main 6', 'main 7', 'main 8',+ 'main 9', 'main 10', 'main 11', 'main 12'])+ expect(JSON.stringify(own)).not.toContain('main after the start')+ expect(JSON.stringify(own)).not.toContain('The other long question')+ expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: other }, a.agentId))).toEqual([])+ expect(text(await f.store.messages(peer, f.tab, f.chat, { messageId: later }, a.agentId))).toEqual([])+ expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: other }, b.agentId))).toEqual(['Second topic', 'The other long question'])+ // A made-up thread reads as another thread: empty, saying nothing of what is there.+ expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: 'ffffffffffffffffffffffff' }, a.agentId))).toEqual([])+ // The main Buddy reads the main chat and the roots, never a session's replies, and counts none of them.+ const main = await f.store.messages(peer, f.tab, f.chat, {}, f.main)+ expect(text(main)).toContain('main after the start')+ expect(JSON.stringify(main)).not.toContain('Measure prod CPU')+ expect(JSON.stringify(main)).not.toContain('The other long question')+ expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: root }, f.main))).toEqual(['main 12'])+ expect(main.threads.filter(t => t.id === root || t.id === other)).toEqual([])+ // The person reads it all.+ expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: root }))).toEqual(['main 12', 'Measure prod CPU for the last day'])+ })++ it('runs at most 3 at once, and of two starts racing for the last place exactly one wins', async () => {+ const f = await swarm()+ const roots = [await f.say('one'), await f.say('two'), await f.say('three'), await f.say('four')]+ await f.session(roots[0]!)+ await f.reply(roots[1]!, 'second', { newSession: true })+ const raced = await Promise.allSettled([f.reply(roots[2]!, 'third', { newSession: true }), f.reply(roots[3]!, 'fourth', { newSession: true })])+ expect(raced.filter(r => r.status === 'fulfilled')).toHaveLength(1)+ expect(raced.flatMap(r => r.status === 'rejected' ? [(r.reason as { code?: string }).code] : [])).toEqual(['BUDDY_SESSIONS_FULL'])+ const chat = (await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!+ expect(chat.buddySessions).toHaveLength(3)+ await expect(f.reply(roots[0]!, 'again', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_EXISTS' })+ })++ it('ends on its person\'s word: its session closes, its line stays in the thread, and only a new session continues there', async () => {+ const f = await swarm()+ const root = await f.say('Start here')+ const { agentId } = await f.session(root)+ const queued = String((await f.reply(root, 'One more')).result.messageId)+ await expect(f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: root, reason: 'ended' }, owner)).rejects.toThrow()+ expect((await f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: root, reason: 'ended' }, peer)).result.ended).toBe(true)+ expect((await f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: root, reason: 'ended' }, peer)).result.ended).toBe(false)+ const read = await f.store.read(peer, f.tab)+ expect(read.state.agents.some(a => a.id === agentId)).toBe(false)+ expect(read.state.conversations.find(c => c.id === f.chat)!.buddySessions).toBeUndefined()+ expect(await db.superTabDelivery.findUniqueOrThrow({ where: { id: (await f.deliveriesTo(agentId)).find(d => d.messageId === queued)!.id } }))+ .toMatchObject({ status: 'cancelled' })+ const thread = await f.store.messages(peer, f.tab, f.chat, { thread: root })+ expect(thread.messages.at(-1)).toMatchObject({ text: 'Session ended: you ended it.', buddySession: true, author: { kind: 'agent', id: agentId },+ source: { kind: 'buddy-session-ended', reason: 'ended', thread: root } })+ await expect(f.reply(root, 'Plain reply')).rejects.toMatchObject({ code: 'BUDDY_SESSION_ENDED' })+ const again = await f.session(root, 'Carry on')+ // The new session reads the whole thread, the one before it included.+ expect(text(await f.store.messages(peer, f.tab, f.chat, {}, again.agentId))).toEqual(['Start here', 'Measure prod CPU for the last day', 'One more',+ 'Session ended: you ended it.', 'Carry on'])+ })++ it('ends when its host says it is idle or stopped, and when its start fails, saying why in the thread', async () => {+ const f = await swarm()+ const [a, b, c] = [await f.say('a'), await f.say('b'), await f.say('c')]+ await f.session(a)+ await f.session(b)+ const failing = String((await f.reply(c, 'Will fail', { newSession: true })).result.startId)+ // Its host acts as its person, as it confirms a closed session (agent.sessionClosed).+ await f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: a, reason: 'idle' }, peer)+ await f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: b, reason: 'stopped' }, peer)+ await f.host({ type: 'agent.startDispatch', startId: failing })+ await f.host({ type: 'agent.startFailed', startId: failing, error: 'Not enough memory' })+ const last = async (root: string) => (await f.store.messages(peer, f.tab, f.chat, { thread: root })).messages.at(-1)!.text+ expect(await last(a)).toBe('Session ended: idle for 30 minutes.')+ expect(await last(b)).toBe('Session ended: it stopped unexpectedly.')+ expect(await last(c)).toBe('Session ended: it couldn\'t start: Not enough memory')+ expect((await f.store.read(peer, f.tab)).state.conversations.find(x => x.id === f.chat)!.buddySessions).toBeUndefined()+ })++ it('goes with its Buddy: removing the Buddy ends every session and a start not yet running', async () => {+ const f = await swarm()+ const [a, b] = [await f.say('a'), await f.say('b')]+ const { agentId } = await f.session(a)+ const pending = String((await f.reply(b, 'pending', { newSession: true })).result.startId)+ await f.execute({ type: 'buddy.remove', projectId: 'lead' }, peer)+ const read = await f.store.read(peer, f.tab)+ expect(read.state.agents.filter(x => x.id === agentId || x.id === f.main)).toEqual([])+ // Each thread says its session ended, so an app offers New session there and never a plain reply (security review 1).+ for (const root of [a, b]) {+ expect((await f.store.messages(peer, f.tab, f.chat, { thread: root })).messages.at(-1)).toMatchObject({+ text: 'Session ended: its Buddy was removed or replaced.', buddySession: true, source: { kind: 'buddy-session-ended', reason: 'removed' } })+ }+ expect(read.state.conversations.find(c => c.id === f.chat)!.buddySessions).toBeUndefined()+ expect(read.state.starts?.find(s => s.id === pending)?.error).toBeTruthy()+ })++ it('is refused without saying whose: an old host, no Buddy, another person, a made-up thread, a plain main message', async () => {+ const old = await swarm({ capable: false })+ const root = await old.say('Start')+ await expect(old.reply(root, 'x', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_UNSUPPORTED' })+ const f = await swarm()+ const mine = await f.say('mine')+ await expect(f.execute({ type: 'message.send', conversationId: f.chat, text: 'x', replyTo: mine, recipientIds: [], newSession: true }, owner))+ .rejects.toThrow('unavailable')+ await expect(f.reply('ffffffffffffffffffffffff', 'x', { newSession: true })).rejects.toMatchObject({ code: 'INVALID_REPLY' })+ await expect(f.execute({ type: 'message.send', conversationId: f.chat, text: 'x', replyTo: null, recipientIds: [], newSession: true }, peer))+ .rejects.toMatchObject({ code: 'BUDDY_SESSION_CHAT' })+ await f.execute({ type: 'buddy.remove', projectId: 'lead' }, peer)+ await expect(f.reply(mine, 'x', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_NO_BUDDY' })+ })++ it('proposes to the PM only for its person\'s ask in its own thread', async () => {+ const f = await swarm()+ const root = await f.say('Start here')+ const { agentId, first } = await f.session(root)+ const mainAsk = await f.say('Send the other thing to the PM')+ const propose = (ownerMessageId: string) => f.execute({ type: 'buddy.propose', conversationId: f.chat, ownerMessageId, goal: 'CPU fix',+ scope: 'Backend', priority: 'normal' }, peer, agentId)+ await expect(propose(mainAsk)).rejects.toMatchObject({ code: 'PROPOSAL_UNASKED' })+ await expect(propose(first)).resolves.toBeTruthy()+ })++ it('starts only beside a Buddy running Claude Code: a Codex Buddy added before Codex was refused gets none (security review 1)', async () => {+ const f = await swarm({ engine: 'codex' })+ const root = await f.say('Start')+ await expect(f.reply(root, 'x', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_ENGINE' })+ expect((await f.store.read(peer, f.tab)).state.starts?.some(s => s.request.buddySession)).toBe(false)+ })++ it('ends a start that timed out through its own path: its thread says so, the main chat says nothing, and its place frees (security review 1)', async () => {+ const f = await swarm()+ const [a, b] = [await f.say('a'), await f.say('b')]+ const dispatched = String((await f.reply(a, 'Never launched', { newSession: true })).result.startId)+ await f.host({ type: 'agent.startDispatch', startId: dispatched })+ await f.reply(b, 'Never picked up', { newSession: true })+ f.clock.now += 6 * 60_000+ await f.report()+ for (const root of [a, b]) {+ const last = (await f.store.messages(peer, f.tab, f.chat, { thread: root })).messages.at(-1)!+ expect(last).toMatchObject({ buddySession: true, source: { kind: 'buddy-session-ended', reason: 'failed' } })+ expect(last.text).toMatch(/^Session ended: it couldn't start: Peer Mac /)+ expect(last.text).not.toContain('add the Buddy again')+ }+ const main = await f.store.messages(peer, f.tab, f.chat, {})+ expect(main.messages.filter(m => !m.thread || m.thread === m.id).map(m => m.text).join('\n')).not.toMatch(/Could not start|add the Buddy again/)+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!.buddySessions).toBeUndefined()+ // Its place is free again.+ await expect(f.session(a, 'Try again')).resolves.toBeTruthy()+ })++ it('can all be ended before a rollback, each through its own end path, after a dry run that ends nothing (spec Design 6)', async () => {+ const f = await swarm()+ const [a, b] = [await f.say('a'), await f.say('b')]+ await f.session(a)+ await f.reply(b, 'starting', { newSession: true })+ const live = (await liveBuddySessions(db)).filter(s => s.tabId === f.tab)+ expect(live.map(s => [s.conversationId, s.thread, s.personId]).sort()).toEqual([[f.chat, a, peer.sub], [f.chat, b, peer.sub]].sort())+ expect(await endBuddySessions(db, live, false)).toEqual({ ended: 0, failed: [] })+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!.buddySessions).toHaveLength(2)+ expect(await endBuddySessions(db, live, true)).toEqual({ ended: 2, failed: [] })+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!.buddySessions).toBeUndefined()+ expect((await f.store.messages(peer, f.tab, f.chat, { thread: a })).messages.at(-1)!.text).toBe('Session ended: Harness was updated. Start a new session to continue.')+ expect((await liveBuddySessions(db)).filter(s => s.tabId === f.tab)).toEqual([])+ })++ it('reacts only to what it reads, and its start says nothing in the main chat (security review 2)', async () => {+ const f = await swarm()+ const [a, b] = [await f.say('a'), await f.say('b')]+ const one = await f.session(a), two = await f.session(b)+ await f.host({ type: 'agent.startSettled', startId: one.startId, warning: null })+ const react = (messageId: string, agentId: string) => f.execute({ type: 'message.react', conversationId: f.chat, messageId, emoji: 'thumbs_up', on: true }, peer, agentId)+ await expect(react(a, one.agentId)).resolves.toBeTruthy()+ await expect(react(one.first, one.agentId)).resolves.toBeTruthy()+ const elsewhere = await f.say('main only')+ await expect(react(elsewhere, one.agentId)).rejects.toThrow()+ await expect(react(two.first, one.agentId)).rejects.toThrow()+ await expect(react(one.first, f.main)).rejects.toThrow()+ const main = await f.store.messages(peer, f.tab, f.chat, {})+ // Only the main Buddy's own ready line: the session's start added none.+ expect(main.messages.filter(m => (!m.thread || m.thread === m.id) && /is ready/.test(m.text))).toHaveLength(1)+ })+})diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex da4bd2287..33d9f3840 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1100,6 +1100,8 @@ model SuperTabMessage {thread String?/// A thread reply also shown in the conversation's main stream.alsoInChat Boolean?+ /// A reply in a Buddy thread session's thread (superTabs/buddySessions.ts): the main Buddy never reads it.+ buddySession Boolean?createdAt DateTime @default(now())/// Pages read by (sequence, id): older rows of one command share a sequence.diff --git a/backend/scripts/buddy-sessions/end-all.ts b/backend/scripts/buddy-sessions/end-all.tsnew file mode 100644index 000000000..9dc1bf6d8--- /dev/null+++ b/backend/scripts/buddy-sessions/end-all.ts@@ -0,0 +1,65 @@+/**+ * Ends every live Buddy thread session (src/superTabs/buddySessions.ts) before the backend is rolled back to a release+ * without them (spec docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md, Design 6). The previous release+ * would read each session as one more Buddy: its main Buddy would read session threads, and its Buddy removal would take one+ * Buddy and leave the rest running. Each end goes through the session's own end path, as the chat's own person (only they+ * may end one), with reason `maintenance`: its agent is closed by its host, and its thread says why.+ *+ * A dry run by default: it lists what it would end, by Swarm and chat id only. `--apply` ends them. Production is the+ * owner's to run (a prod write).+ *+ * DATABASE_URL=... NODE_ENV=production node --import tsx scripts/buddy-sessions/end-all.ts [--apply]+ */+import { randomUUID } from 'node:crypto'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../../src/lib/ssoAuth.js'+import { SuperTabStore } from '../../src/superTabs/store.js'++export interface SessionToEnd { tabId: string; conversationId: string; thread: string; personId: string }++/** Every live or starting session in every Swarm, read from the Buddy chats' records alone. */+export async function liveBuddySessions(db: PrismaClient): Promise<SessionToEnd[]> {+ const rows = await db.swarmGroup.aggregateRaw({ pipeline: [+ { $match: { deleted: false, 'data.kind': 'buddy', 'data.buddySessions.0': { $exists: true } } },+ { $project: { tabId: 1, key: 1, sessions: '$data.buddySessions', people: '$data.audience.people' } }] }) as unknown as+ Array<{ tabId: string; key: string; sessions: Array<{ thread: string }>; people?: Array<{ id: string }> }>+ return rows.flatMap(row => row.people?.[0] ? row.sessions.map(s => ({ tabId: row.tabId, conversationId: row.key, thread: s.thread, personId: row.people![0]!.id })) : [])+}++/** Ends [sessions] (or only lists them unless [apply]); returns how many ended and which failed, by id only. */+export async function endBuddySessions(db: PrismaClient, sessions: SessionToEnd[], apply: boolean, autonomousEnv = 'prod'):+ Promise<{ ended: number; failed: Array<SessionToEnd & { why: string }> }> {+ const store = new SuperTabStore(db)+ let ended = 0+ const failed: Array<SessionToEnd & { why: string }> = []+ for (const session of sessions) {+ if (!apply) continue+ const user = await db.user.findUnique({ where: { id: session.personId }, select: { email: true } })+ if (!user) { failed.push({ ...session, why: 'its person has no account' }); continue }+ const person: AuthUser = { sub: session.personId, email: user.email, autonomousEnv, role: 'user' }+ try {+ const done = await store.execute(person, session.tabId, { operationId: randomUUID(), command: { type: 'buddy.sessionEnd',+ conversationId: session.conversationId, thread: session.thread, reason: 'maintenance' } })+ if (done.result.ended) ended+++ } catch (error) {+ failed.push({ ...session, why: error instanceof Error ? error.message : String(error) })+ }+ }+ return { ended, failed }+}++if (import.meta.url === `file://${process.argv[1]}`) {+ const apply = process.argv.includes('--apply')+ const db = new PrismaClient()+ const sessions = await liveBuddySessions(db)+ console.log(`${sessions.length} live Buddy thread session(s)`)+ for (const s of sessions) console.log(` Swarm ${s.tabId} chat ${s.conversationId} thread ${s.thread}`)+ if (!apply) console.log('Dry run: nothing ended. Run again with --apply to end them.')+ else {+ const { ended, failed } = await endBuddySessions(db, sessions, true, process.env.AUTONOMOUS_ENV ?? 'prod')+ console.log(`Ended ${ended}.`)+ for (const f of failed) console.log(` Not ended: Swarm ${f.tabId} chat ${f.conversationId} thread ${f.thread}: ${f.why}`)+ if (failed.length) process.exitCode = 1+ }+ await db.$disconnect()+}diff --git a/backend/src/superTabs/buddyNews.ts b/backend/src/superTabs/buddyNews.tsindex c2a85e681..e62750aee 100644--- a/backend/src/superTabs/buddyNews.ts+++ b/backend/src/superTabs/buddyNews.ts@@ -14,7 +14,8 @@ const PROPOSAL_KIND = 'buddy-proposal'* nothing once its person left, rejoined or stopped reading the project. */function listeningBuddy(state: SuperTabState, personId: string, group: Conversation): Agent | undefined {const project = groupProject(state, group)- const buddy = state.agents.find(a => isBuddy(a) && a.buddyOf!.personId === personId && agentProjectId(state, a) === project.id)+ // The main Buddy alone: a thread session hears only its own thread (buddySessions.ts).+ const buddy = state.agents.find(a => isBuddy(a) && !a.buddySession && a.buddyOf!.personId === personId && agentProjectId(state, a) === project.id)return buddy && canReadGroup(state, { kind: 'agent', agentId: buddy.id, machineOwnerId: buddy.machineOwnerId }, group) ? buddy : undefined}diff --git a/backend/src/superTabs/buddySessions.ts b/backend/src/superTabs/buddySessions.tsnew file mode 100644index 000000000..8fa3c43d5--- /dev/null+++ b/backend/src/superTabs/buddySessions.ts@@ -0,0 +1,134 @@+/** Buddy thread sessions (docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md; Scholes, 10-30): by the person's+ * choice, a thread in their Buddy chat gets its own Buddy session, a second Buddy agent on the same machine, so a long+ * question there never holds a quick one in the main chat. A session hears and answers only its thread, reads the main chat+ * only up to where it started (a short excerpt), and ends when its person ends it, when it has been idle for 30 minutes+ * (its host says so), or with its main Buddy. The main Buddy reads none of its thread. */+import { isBuddy, isBuddyChat } from './buddies.js'+import { fail, stableId, type Agent, type AgentStart, type Author, type BuddySessionEntry, type Conversation, type MessageDraft, type SuperTabState } from './model.js'++/** At most this many live or starting sessions per Buddy chat, the main Buddy not counted. */+export const MAX_BUDDY_SESSIONS = 3+/** At most this many of the person's messages wait for a session that is still starting. */+export const MAX_SESSION_WAITING = 20+/** What a machine's host reports (`capabilities`) when it can run thread sessions. */+export const BUDDY_SESSION_CAPABILITY = 'buddySessions'+/** The main-chat excerpt a session starts from: the last CONTEXT_MESSAGES before it started, each cut to CONTEXT_CHARS, at+ * most CONTEXT_BYTES in all. */+export const CONTEXT_MESSAGES = 10+export const CONTEXT_CHARS = 500+export const CONTEXT_BYTES = 6 * 1024+/** The quiet line a session's end leaves in its thread. */+export const SESSION_ENDED_KIND = 'buddy-session-ended'+export type SessionEndReason = 'ended' | 'idle' | 'stopped' | 'failed' | 'removed' | 'maintenance'++export const isThreadSession = (agent: Pick<Agent, 'buddySession'> | undefined): boolean => !!agent?.buddySession+/** The chat's main Buddy: the Buddy in it that is not a thread session. */+export function mainBuddyOf(state: SuperTabState, chat: Conversation): Agent | undefined {+ return state.agents.find(a => chat.agentIds.includes(a.id) && isBuddy(a) && !a.buddySession)+}+/** The thread sessions running in [chat]. */+export const sessionAgentsOf = (state: SuperTabState, chat: Conversation): Agent[] =>+ state.agents.filter(a => chat.agentIds.includes(a.id) && isBuddy(a) && !!a.buddySession)++/**+ * [chat]'s live and starting sessions, its record pruned of any that ended without saying (its agent gone, its start failed+ * or gone): a removal path that missed the record never holds a slot. Changes [chat] only when something is pruned.+ */+export function liveSessions(state: SuperTabState, chat: Conversation): BuddySessionEntry[] {+ const entries = chat.buddySessions ?? []+ const live = entries.filter(entry => entry.agentId+ ? state.agents.some(a => a.id === entry.agentId && chat.agentIds.includes(a.id))+ : state.starts?.some(s => s.id === entry.startId && !s.error && !s.harnessId) === true)+ if (live.length !== entries.length) setSessions(chat, live)+ return live+}+export function setSessions(chat: Conversation, entries: BuddySessionEntry[]): void {+ if (entries.length) chat.buddySessions = entries+ else delete chat.buddySessions+}++/** The live or starting session of [thread] in [chat]. */+export const sessionOf = (state: SuperTabState, chat: Conversation, thread: string | null | undefined): BuddySessionEntry | undefined =>+ thread ? liveSessions(state, chat).find(e => e.thread === thread) : undefined++/** The person whose Buddy chat [chat] is, at the membership it was opened in. */+export const chatOwner = (chat: Conversation): { id: string; generation: string } | undefined => chat.audience?.people[0]++/** Refuses anyone but [chat]'s own person, at their current membership, with words that never say whose chat it is. */+export function requireChatOwner(state: SuperTabState, chat: Conversation, userId: string): { id: string; generation: string } {+ const owner = chatOwner(chat)+ const me = state.people.find(p => p.id === userId)+ if (!isBuddyChat(chat) || !owner || !me || owner.id !== me.id || owner.generation !== me.generation) {+ fail('BUDDY_SESSION_CHAT', 'Start or end a session in a thread of your own Buddy chat.', 403)+ }+ return owner+}++/** The words a session's end leaves in its thread, for its person. */+export function endedText(reason: SessionEndReason, detail?: string): string {+ switch (reason) {+ case 'ended': return 'Session ended: you ended it.'+ case 'idle': return 'Session ended: idle for 30 minutes.'+ case 'stopped': return 'Session ended: it stopped unexpectedly.'+ case 'failed': return `Session ended: it couldn't start${detail ? `: ${detail.slice(0, 300)}` : '.'}`+ case 'removed': return 'Session ended: its Buddy was removed or replaced.'+ case 'maintenance': return 'Session ended: Harness was updated. Start a new session to continue.'+ }+}++/**+ * The one way a session's end is recorded, for every path (commands, the start timeouts in liveness.ts): its entry leaves+ * [chat]'s record and a quiet line in its thread says why, to nobody (a reply to the thread's root, tagged as the session's,+ * so the main Buddy never reads it). Said by the session's agent when it ran, else by the chat's person. Closing the agent+ * itself is the caller's: only a command can (commands.ts removeAgent). Nothing when the entry is already gone.+ */+export function endSessionEntry(state: SuperTabState, chat: Conversation, entry: BuddySessionEntry, reason: SessionEndReason, detail?: string): MessageDraft[] {+ if (!(chat.buddySessions ?? []).some(e => e.startId === entry.startId)) return []+ setSessions(chat, (chat.buddySessions ?? []).filter(e => e.startId !== entry.startId))+ const agent = entry.agentId ? state.agents.find(a => a.id === entry.agentId) : undefined+ const owner = chatOwner(chat), person = owner && state.people.find(p => p.id === owner.id && p.generation === owner.generation)+ const author: Author | undefined = agent ? { kind: 'agent', id: agent.id, name: agent.name, displayName: agent.displayName ?? agent.name,+ membershipGeneration: agent.membershipGeneration } : person ? { kind: 'person', id: person.id, name: person.email, membershipGeneration: person.generation } : undefined+ if (!author) return []+ return [{ id: stableId(SESSION_ENDED_KIND, chat.id, entry.startId), conversationId: chat.id, author, text: endedText(reason, detail),+ replyTo: entry.thread, recipients: [], thread: entry.thread, buddySession: true, source: { kind: SESSION_ENDED_KIND, reason, thread: entry.thread } }]+}++/** A thread session's start that failed outside a command (liveness.ts timeouts): ended through its own path, never as its+ * main Buddy's start, so the main chat says nothing and the thread says why. */+export function failedSessionStart(state: SuperTabState, start: AgentStart): MessageDraft[] {+ const chat = start.request.buddySession && state.conversations.find(c => c.id === start.request.conversationId)+ const entry = chat ? (chat.buddySessions ?? []).find(e => e.startId === start.id) : undefined+ return chat && entry ? endSessionEntry(state, chat, entry, 'failed', start.error ?? undefined) : []+}++/** A message row as the session read check needs it. */+export interface SessionRow { id: string; thread?: string | null; buddySession?: boolean | null }++/**+ * Whether a Buddy [reader] reads [row] of its own Buddy chat (spec: Security, "No session reads another's thread"). A thread+ * session reads its own thread alone (its root and replies); the main Buddy reads every row but a session thread's replies.+ * Anyone else, and any other conversation, reads as before. The one predicate every agent read of a Buddy chat applies.+ */+export function sessionReadsRow(reader: Pick<Agent, 'buddyOf' | 'buddySession'> | undefined, group: Pick<Conversation, 'kind'>): (row: SessionRow) => boolean {+ if (!reader?.buddyOf || !isBuddyChat(group)) return () => true+ const own = reader.buddySession+ if (own) return row => row.id === own.thread || row.thread === own.thread+ return row => !row.buddySession+}++/** A main-chat row as the excerpt reads it. */+export interface ContextRow { id: string; sequence: number; text: string; author: { kind: string; name?: string; displayName?: string }; createdAt: Date }++/**+ * The main-chat excerpt a session starts from: [rows] (main-stream rows of its chat at or before its `from`, newest first,+ * as read), the newest CONTEXT_MESSAGES, oldest first, each cut to CONTEXT_CHARS, dropping the oldest until CONTEXT_BYTES fit.+ */+export function sessionContext(rows: readonly ContextRow[]): Array<{ id: string; sequence: number; author: string; text: string; createdAt: Date }> {+ const picked = rows.slice(0, CONTEXT_MESSAGES).map(row => ({ id: row.id, sequence: row.sequence, createdAt: row.createdAt,+ author: row.author.displayName ?? row.author.name ?? row.author.kind,+ text: [...row.text].length > CONTEXT_CHARS ? `${[...row.text].slice(0, CONTEXT_CHARS).join('')}…` : row.text })).reverse()+ const size = (list: typeof picked) => Buffer.byteLength(JSON.stringify(list.map(r => [r.author, r.text])))+ while (picked.length && size(picked) > CONTEXT_BYTES) picked.shift()+ return picked+}diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 315ebf0f5..6a6f698ca 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -6,7 +6,7 @@ import { tokensByModelSchema } from './costs/tokens.js'import {activeWork, actorKey, agent, agentRole, appendPullRequestUrls, author, conversation, crossProjectActive, fail, isLeads, person, stableId, syncLeads, numberConversations, nextConversationNumber, renderWorkTask,finishWorker, requireWorkerDecisions, reviewing, seenMachineIds, swarmGridName, visibleState, AGENT_ONLY, STATUS_LABELS, forRecipients,- type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,+ type Actor, type AgentConfiguration, type AgentStart, type AgentStartRequest, type BuddySessionEntry, type WorkTask, type Agent, type Author, type CommandEffects, type Conversation, type SuperTabState,} from './model.js'import { jobKindOf } from './evidence/jobKind.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'@@ -35,6 +35,7 @@ import { openReview, openReviewOf, projectPullRequest, verdictPending } from './import { carryOver, cheapAttempt, GRID_START_FAILED, REVIEW_FAILED, stepUp, stepUpRefusal } from './stepUp.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleDefaults, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, withRoleDefaults, type ProjectRole, type RoleDefaults, type RoleKind, type SwarmProject } from './projects.js'+import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, liveSessions, mainBuddyOf, MAX_BUDDY_SESSIONS, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, PROPOSAL_ASK_MS, proposalText, renameBuddy, requireBuddyCommand } from './buddies.js'import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'import { LEAD_NAME, launchRefusedLine, leadJoined, leadStartFailed, leadStarting, placeLead } from './leadStart.js'@@ -165,6 +166,9 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('buddy.chat'), projectId: id }).strict(),// A person names their own Buddy from its chat, or clears the name with null (buddies.ts renameBuddy).z.object({ type: z.literal('buddy.rename'), conversationId: id, name: z.string().max(200).nullable() }).strict(),+ // A person ends a thread session of their own Buddy chat (buddySessions.ts): `ended` from their app, `idle` and `stopped` from+ // their machine's host, which acts as them. Idempotent: a thread with no session is told so and nothing changes.+ z.object({ type: z.literal('buddy.sessionEnd'), conversationId: id, thread: id, reason: z.enum(['ended', 'idle', 'stopped', 'maintenance']) }).strict(),// The PM's private line to one person, in their Buddy chat of its project: Buddies replaced Chat with PM (Ken, 10-29).z.object({ type: z.literal('person.tell'), personId: id, text: z.string().trim().min(1).max(32_000) }).strict(),// A person's own Buddy in a project, on a machine of the Swarm (buddies.ts).@@ -201,7 +205,9 @@ export const commandSchema = z.discriminatedUnion('type', [// Text may be empty when the message carries files; applyCommand checks that one of them is there.z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),alsoSend: z.literal(true).optional(), attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(),- mentionsIfNoWorker: z.literal(true).optional(), agentOnly: z.literal(true).optional() }).strict(),+ mentionsIfNoWorker: z.literal(true).optional(), agentOnly: z.literal(true).optional(),+ // A person's thread reply in their own Buddy chat that starts the thread's own Buddy session (buddySessions.ts).+ newSession: z.literal(true).optional() }).strict(),z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean() }).strict(),z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),@@ -313,7 +319,9 @@ export interface CommandContext {* `threadSource` that root's source: a Buddy's proposal is news for its Buddy (buddyNews.ts). *//** `agentOnly`: a notice people cannot read (model.ts agentOnly), whose thread a reply does not join. */reply?: { id: string; conversationId: string; author: Author; createdAt: number; thread?: string | null; threadSource?: Record<string, unknown> | null- agentOnly?: true }+ agentOnly?: true+ /** In a Buddy chat: its thread has had a thread session (a `buddySession` reply), read by the store (buddySessions.ts). */+ sessionThread?: true }/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */openTags?: Array<{ messageId: string; createdAt: number }>/** For `buddy.rename` and `buddy.create`: the names chosen in this Swarm's Buddy chats, quiet ones included, read by the@@ -323,6 +331,8 @@ export interface CommandContext {proposal?: { id: string; conversationId: string; author: Author; source: Record<string, unknown> | null }/** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. */proposalAsk?: { id: string; conversationId: string; author: Author; source: boolean; createdAt: number+ /** The thread it is in: a thread session proposes only for its person's message in its own thread. */+ thread?: string | null/** The owner's newest message in that chat, which may always be named. */newestOwnerMessageId?: string }/** The message a Lead quotes as the owner's request for a rule or skill mode change, loaded from this tab by the store. */@@ -836,8 +846,102 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst contributor = member?.contributorId ?? state.machines?.find(m => m.machineId === machineId)?.contributorId ?? starterreturn teamWorkCheck(state, machineId, contributor, project, context.now, context.teamMachines, context.otherWorkspaceMachines)}+ /**+ * Routes a `message.send` in Buddy chat [chat] (buddySessions.ts): whether it is in a session thread (`inSession`, its reply+ * tagged so the main Buddy never reads it) and which session hears it (`to`, null while that session starts: its delivery is+ * written when it joins). Starts the thread's session for a person's `newSession`. Refuses a session's post outside its own+ * thread, the main Buddy's in a session thread, and a person's plain reply in a thread whose session ended.+ */+ const routeBuddySession = (chat: Conversation): { inSession: boolean; to: string | null } => {+ if (command.type !== 'message.send') return { inSession: false, to: null }+ const thread = command.replyTo && !context.reply?.agentOnly ? context.reply?.thread ?? null : null+ const self = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined+ const entry = sessionOf(state, chat, thread)+ if (self?.buddySession) {+ if (!thread || thread !== self.buddySession.thread || command.alsoSend || command.newSession) {+ fail('BUDDY_SESSION_THREAD', 'Answer only in your own thread: post with --reply-to a message in it.', 403)+ }+ return { inSession: true, to: null }+ }+ if (self) {+ if (entry || context.reply?.sessionThread) fail('BUDDY_SESSION_THREAD', 'That thread has its own session. Answer in the main chat or a thread without one.', 403)+ if (command.newSession) fail('BUDDY_SESSION_CHAT', 'Only the chat\'s person starts a session.', 403)+ return { inSession: false, to: null }+ }+ if (actor.kind !== 'person') return { inSession: false, to: null }+ if (command.newSession) {+ const owner = requireChatOwner(state, chat, actor.userId)+ if (!thread) fail('BUDDY_SESSION_CHAT', 'Start a session from a thread: reply to a message, then choose New session.', 400)+ if (entry) fail('BUDDY_SESSION_EXISTS', 'This thread already has its own session.')+ if (command.alsoSend) fail('BUDDY_SESSION_THREAD', 'A session\'s thread stays in the thread.', 400)+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')+ const main = mainBuddyOf(state, chat)+ if (!main || downSince(state, main, context.now)) fail('BUDDY_SESSION_NO_BUDDY', 'Start your Buddy first: a session runs beside it.')+ // Only Claude Code runs a Buddy's guard hook. A Codex Buddy added before Codex was refused (buddy.create) must not+ // start Codex sessions without it (security review 1 of #2345).+ if (main.configuration.engine !== 'claude') fail('BUDDY_SESSION_ENGINE', 'Sessions need a Buddy running Claude Code.', 403)+ const pool = machineContribution(state, main.machineId)+ if (!pool?.observation?.capabilities?.includes(BUDDY_SESSION_CAPABILITY)) {+ fail('BUDDY_SESSION_UNSUPPORTED', `Update Harness on ${pool?.name ?? 'your Buddy\'s computer'} to start sessions.`)+ }+ if (liveSessions(state, chat).length >= MAX_BUDDY_SESSIONS) fail('BUDDY_SESSIONS_FULL', `${MAX_BUDDY_SESSIONS} sessions are running. End one to start another.`)+ const contributor = person(state, main.contributorId)+ const request: AgentStartRequest = { conversationId: chat.id, machineId: main.machineId, engine: main.configuration.engine,+ ...(main.configuration.model ? { model: main.configuration.model } : {}), ...(main.configuration.effort ? { effort: main.configuration.effort } : {}),+ name: main.displayName ?? main.name, cwd: projectFolder(pool, groupProject(state, chat)), worktree: true, requirements: BUDDY_REQUIREMENTS,+ buddyOf: { personId: owner.id, generation: owner.generation },+ // The main chat's sequence before this message: the session's excerpt reads up to it (buddySessions.ts sessionContext).+ buddySession: { thread, from: chat.messageSeq ?? chat.lastMessageSequence } }+ // A slot for it on a Buddy-only machine, as for its main Buddy (buddy.create).+ if (pool.buddyOnly) pool.maxAgents = machineSlots(state, pool) + 1+ const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!+ state.starts ??= []+ if (state.starts.filter(s => !s.harnessId && !s.error).length >= 32) fail('STARTS_PENDING', 'Reconcile pending agent starts before adding more.')+ state.starts.push({ poolGeneration: admitted.generation, id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),+ contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: main.machineOwnerId,+ hostGrant: main.hostGrant ?? null, request, harnessId: null, dispatched: false, error: null, requestedAt: context.now })+ setSessions(chat, [...liveSessions(state, chat), { thread, startId: operationId, at: context.now, waiting: [operationId] }])+ result.startId = operationId+ return { inSession: true, to: null }+ }+ if (entry) {+ if (command.alsoSend) fail('BUDDY_SESSION_THREAD', 'A session\'s thread stays in the thread.', 400)+ if (!entry.agentId) {+ if ((entry.waiting?.length ?? 0) >= MAX_SESSION_WAITING) fail('BUDDY_SESSION_STARTING', 'This thread\'s session is still starting. Send again in a moment.')+ entry.waiting = [...entry.waiting ?? [], operationId]+ }+ return { inSession: true, to: entry.agentId ?? null }+ }+ if (thread && context.reply?.sessionThread) fail('BUDDY_SESSION_ENDED', 'This thread\'s session ended. Send with New session to continue.')+ return { inSession: false, to: null }+ }++ /** Ends [entry]'s session in [chat]: its agent leaves as any removed agent does (its host closes it and deletes its folder),+ * a start not yet running fails, and a quiet line in its thread says why, to nobody (buddySessions.ts). */+ const endBuddySession = (chat: Conversation, entry: BuddySessionEntry, reason: SessionEndReason, detail?: string) => {+ // Its line first, while its agent can still say it (buddySessions.ts endSessionEntry); then its agent closes.+ effects.messages.push(...endSessionEntry(state, chat, entry, reason, detail))+ const target = entry.agentId ? state.agents.find(a => a.id === entry.agentId) : undefined+ if (target) removeAgent(target)+ const start = state.starts?.find(s => s.id === entry.startId && !s.harnessId && !s.error)+ if (start) start.error = 'Its session ended before it started.'+ }+/** Deleting its project is the only removal that takes a Lead. `close: false` when its host already closed the session. */const removeAgent = (target: Agent, { lead = false, close = true } = {}) => {+ // A Buddy chat's record of its sessions (buddySessions.ts): a session leaves it, and a main Buddy takes its sessions with it.+ for (const chat of state.conversations.filter(c => isBuddyChat(c) && c.agentIds.includes(target.id))) {+ if (target.buddySession) setSessions(chat, (chat.buddySessions ?? []).filter(e => e.agentId !== target.id))+ else if (target.buddyOf) {+ // Each session's thread says it ended, as every end does (security review 1 of #2345): an app then offers New session there.+ for (const entry of [...chat.buddySessions ?? []]) effects.messages.push(...endSessionEntry(state, chat, entry, 'removed'))+ for (const start of state.starts ?? []) {+ if (start.request.conversationId === chat.id && start.request.buddySession && !start.harnessId && !start.error) start.error = 'Its Buddy was removed before it started.'+ }+ for (const other of sessionAgentsOf(state, chat)) removeAgent(other)+ delete chat.buddySessions+ }+ }if (!lead) protectLead(state, target.id)if (close && !state.closingSessions?.some(c => c.agentId === target.id && c.harnessId === target.harnessId)) {// A confidential session in a Team account keeps the account for its project until its host confirms the close, which@@ -1586,6 +1690,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma?? fail('BUDDY_OWNER_GONE', 'Your owner left this Swarm.', 403)const chat = conversation(state, command.conversationId)if (!isBuddyChat(chat) || !chat.agentIds.includes(self.id)) fail('BUDDY_FORBIDDEN', 'Name your own chat: a proposal comes from there.', 403)+ // A thread session proposes only for its person's message in its own thread, which is all it reads (buddySessions.ts).+ if (self.buddySession && context.proposalAsk && context.proposalAsk.id !== self.buddySession.thread && context.proposalAsk.thread !== self.buddySession.thread) {+ fail('PROPOSAL_UNASKED', 'Send a proposal only when your owner asks for it in your thread: name their message there.', 403)+ }// Its owner said to send it: their own message in its chat, never a row the system wrote, and each one asks once.const ask = context.proposalAskif (!ask || ask.id !== command.ownerMessageId || ask.conversationId !== chat.id || ask.source || ask.author.kind !== 'person'@@ -1610,7 +1718,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person removes their own Buddy.', 403)const project = readProject(state, actor, command.projectId), me = person(state, actor.userId)const chatId = buddyChatId(project.id, me)- const target = state.agents.find(a => a.buddyOf?.personId === me.id && agentProjectId(state, a) === project.id)+ const target = state.agents.find(a => a.buddyOf?.personId === me.id && !a.buddySession && agentProjectId(state, a) === project.id)const starting = state.starts?.filter(s => s.request.conversationId === chatId && !s.harnessId && !s.error) ?? []if (!target && !starting.length) fail('NOT_FOUND', 'You have no Buddy in this project.', 404)for (const start of starting) start.error = 'Removed by its owner before it started.'@@ -1626,6 +1734,16 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commacase 'buddy.rename':renameBuddy(state, actor, readConversation(state, actor, command.conversationId), command.name, context.buddyNames)break+ case 'buddy.sessionEnd': {+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person ends their own Buddy session.', 403)+ const chat = readConversation(state, actor, command.conversationId)+ requireChatOwner(state, chat, actor.userId)+ const entry = sessionOf(state, chat, command.thread)+ result.ended = !!entry+ if (!entry) break+ endBuddySession(chat, entry, command.reason)+ break+ }case 'person.tell': {const project = actor.kind === 'agent' ? ledProject(state, actor.agentId) : undefinedif (!project) fail('TELL_FORBIDDEN', 'Only a project\'s Lead sends a person a private line, in its own project.', 403)@@ -1647,8 +1765,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst chatId = buddyChatId(project.id, me)// A down Buddy is replaced (Desktop's Start again, review of #1992): its session closes in this same command, so a// start refused below leaves it as it was. A running or starting one is kept.- const existing = state.agents.find(a => a.buddyOf?.personId === me.id && agentProjectId(state, a) === project.id)- if ((existing && !downSince(state, existing, context.now)) || state.starts?.some(s => s.request.conversationId === chatId && !s.harnessId && !s.error)) {+ const existing = state.agents.find(a => a.buddyOf?.personId === me.id && !a.buddySession && agentProjectId(state, a) === project.id)+ if ((existing && !downSince(state, existing, context.now))+ || state.starts?.some(s => s.request.conversationId === chatId && !s.request.buddySession && !s.harnessId && !s.error)) {fail('BUDDY_EXISTS', 'You already have a Buddy in this project. Remove it to add another.')}if (existing) removeAgent(existing)@@ -1722,7 +1841,14 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (command.configuration && !start.poolSettled) settledConfiguration(start, command.configuration)// A Product Manager is never assigned work: its conversation already said where it started.// A warning is the people's to read (a start that went wrong); being ready is bookkeeping.- if (!start.poolSettled && !start.request.leadFor) message(start.request.conversationId, command.warning+ // A thread session says nothing in the main chat (security review 2 of #2345): its thread shows it working, and a+ // warning about its start goes in its thread alone.+ if (!start.poolSettled && start.request.buddySession) {+ if (command.warning) {+ message(start.request.conversationId, `${start.request.name}: ${command.warning}`, [], start.request.buddySession.thread, SYSTEM_ROW)+ Object.assign(effects.messages.at(-1)!, { thread: start.request.buddySession.thread, buddySession: true })+ }+ } else if (!start.poolSettled && !start.request.leadFor) message(start.request.conversationId, command.warning? `${start.request.name}: ${command.warning}`: start.request.buddyOf ? buddyReady(start.request.name) : `${start.request.name} is ready for an assignment.`, [], null,command.warning ? SYSTEM_ROW : bookkeeping(start.request.conversationId, SYSTEM_ROW))@@ -1735,6 +1861,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst counted = !start.errorstart.error = command.errorconst suspended = counted ? noteStartFailed(state, start, context.now) : null+ // A thread session's says so in its thread (buddySessions.ts), and frees its place.+ if (start.request.buddySession) {+ const chat = conversation(state, start.request.conversationId)+ const entry = (chat.buddySessions ?? []).find(e => e.startId === start.id)+ if (entry) endBuddySession(chat, entry, 'failed', command.error)+ break+ }// A Product Manager's start says so in its project's conversation (leadStart.ts).if (start.request.leadFor) {const ended = leadStartFailed(state, start, command.error)@@ -1768,12 +1901,26 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma...(start.request.gridModel ? { gridModel: start.request.gridModel } : {}),...(!start.request.gridModel && (start.request.model ?? 'default') === 'default' ? { launchedDefault: true as const } : {}),...(start.request.buddyOf ? { buddyOf: start.request.buddyOf } : {}),+ ...(start.request.buddySession ? { buddySession: start.request.buddySession } : {}),...(teamAccountPool(machineContribution(state, start.request.machineId)) ? { teamAccount: true as const } : {}),...(command.startedSession ? { startedSession: { ...command.startedSession, creationId: start.creationId } } : {}) })- group.agentIds.push(agentId)+ // A main Buddy stays first, as older clients take a Buddy chat's first agent for its Buddy (buddySessions.ts).+ if (start.request.buddyOf && !start.request.buddySession) group.agentIds.unshift(agentId)+ else group.agentIds.push(agentId)start.harnessId = command.harnessIdnoteStartSucceeded(state, start)result.agentId = agentId+ // A thread session joins its chat's record, and hears the person's messages sent while it started, by delivery as any+ // other: its host's person check, run: judging and read grant apply to them too (spec: Security).+ if (start.request.buddySession) {+ const entry = (group.buddySessions ?? []).find(e => e.startId === start.id)+ const owner = chatOwner(group)+ if (!entry || !owner) fail('BUDDY_SESSION_ENDED', 'This session ended before it started.')+ entry.agentId = agentId+ effects.lateDeliveries = (entry.waiting ?? []).map(messageId => ({ messageId, conversationId: group.id, agentId,+ author: { kind: 'person' as const, id: owner.id, generation: owner.generation } }))+ delete entry.waiting+ }if (start.request.leadFor) {// Taking over from a Lead that left, as agent.add does.if (group.leadId && !group.agentIds.includes(group.leadId)) keepLead(group, agentId)@@ -2005,7 +2152,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafor (const start of state.starts?.filter(s => s.request.buddyOf?.personId === member.id && !s.harnessId && !s.error) ?? []) {start.error = 'Its person left the Swarm before it started.'}- for (const target of state.agents.filter(a => a.contributorId === member.id || a.buddyOf?.personId === member.id)) removeAgent(target)+ // A main Buddy takes its thread sessions with it (removeAgent), so each is removed once.+ for (const target of state.agents.filter(a => a.contributorId === member.id || a.buddyOf?.personId === member.id)) {+ if (state.agents.some(a => a.id === target.id)) removeAgent(target)+ }state.people = state.people.filter(p => p.id !== member.id)state.invitations = state.invitations.filter(i => i.email !== member.email)result.removedUserId = member.id@@ -2050,16 +2200,22 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// #2243): the Lead already reads the group. The assigned worker keeps its own rule above; a note to itself stays its own.const memberToLead = actor.kind === 'agent' && !command.agentOnly && assigned !== actor.agentId && group.leadId&& group.leadId !== actor.agentId && group.agentIds.includes(group.leadId) ? [group.leadId] : []+ // Buddy thread sessions (buddySessions.ts): a session thread's replies reach its session alone and stay in its thread; the+ // main Buddy hears the rest. Decided here from the thread, so every client, an old one or the phone, is routed alike.+ const session = isBuddyChat(group) ? routeBuddySession(group) : undefined+ if (command.newSession && !session) fail('BUDDY_SESSION_CHAT', 'Start a session from a thread of your own Buddy chat.', 400)// A Buddy chat has no Lead: its owner talks to its Buddy.- const automatic = actor.kind === 'person' ? (replyAgent && group.agentIds.includes(replyAgent) ? replyAgent- : isBuddyChat(group) ? group.agentIds[0] ?? null : group.leadId) : agentRecipient+ const automatic = actor.kind === 'person' ? (isBuddyChat(group) ? (session?.inSession ? session.to : mainBuddyOf(state, group)?.id ?? null)+ : replyAgent && group.agentIds.includes(replyAgent) ? replyAgent : group.leadId) : agentRecipient// In the Leads conversation everything posted reaches every other Lead; naming some only adds emphasis.const everyLead = isLeads(group) ? group.agentIds.filter(id => actor.kind !== 'agent' || id !== actor.agentId) : []const recipients = [...new Set([...command.recipientIds, ...everyLead, ...memberToLead,...(command.recipientIds.length || everyLead.length || !automatic ? [] : [automatic])])]for (const id of recipients) {- agent(state, id)+ const target = agent(state, id)if (!group.agentIds.includes(id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)+ // In a Buddy chat a session hears its own thread alone, and the main Buddy none of it.+ if (session && (session.inSession ? id !== session.to : !!target.buddySession)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)}// A tag would tell a person about a notice they cannot see.if (command.agentOnly && (actor.kind !== 'agent' || recipients.length !== 1 || recipients[0] !== actor.agentId || mentions.length)) {@@ -2071,6 +2227,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// recipients read (the Lead answering a stalled alert) stays in the chat: people open a thread from its root.const thread = command.replyTo && !context.reply?.agentOnly ? context.reply?.thread : nullif (thread) Object.assign(effects.messages.at(-1)!, { thread, ...(command.alsoSend ? { alsoInChat: true } : {}) })+ if (session?.inSession) Object.assign(effects.messages.at(-1)!, { buddySession: true })recordPost(state, group, actor, { replyTo: command.replyTo, text, reply: context.reply, openTags: context.openTags }, context.now)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)leadActed(group.id, 'post')diff --git a/backend/src/superTabs/liveness.ts b/backend/src/superTabs/liveness.tsindex 2ddcc096c..72bea5620 100644--- a/backend/src/superTabs/liveness.ts+++ b/backend/src/superTabs/liveness.ts@@ -1,5 +1,6 @@import { activeWork, forRecipients, stableId, type Agent, type AgentStart, type Assignment, type Author, type Conversation, type MessageDraft,type SuperTabState, type TaskLiveness } from './model.js'+import { failedSessionStart } from './buddySessions.js'import { noteStartFailed } from './engineHealth.js'import { machineOffline, sessionStopped } from './lostReason.js'import { agentDisplayName } from './agentNames.js'@@ -400,8 +401,10 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {start.error = `${machineName(state, start.request.machineId)}${LEAD_PICKUP_SUFFIX}`return leadNotice(state, start, leadStartFailed(state, start, start.error))}- start.error = `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`- return buddyNotice(state, start)+ start.error = start.request.buddySession ? `${machineName(state, start.request.machineId)} did not start this session.`+ : `${machineName(state, start.request.machineId)} did not start this Buddy. Update Harness on it, then add the Buddy again.`+ // A thread session's start ends through its own path: its thread says why, never the main chat (buddySessions.ts).+ return start.request.buddySession ? failedSessionStart(state, start) : buddyNotice(state, start)}if (!start.dispatched || start.harnessId || start.error || start.dispatchedAt === undefined || now - start.dispatchedAt <= START_RUN_MS) return []// Only its own machine's report can say it is preparing; one before preparingStartIds never does, so its starts get 3 minutes.@@ -415,7 +418,7 @@ function failStalledStarts(state: SuperTabState, now: number): MessageDraft[] {const suspended = noteStartFailed(state, start, now)if (start.request.leadFor) return leadNotice(state, start, leadStartFailed(state, start, start.error))// Never a lookup that throws: these checks run inside every machine's report.- if (start.request.buddyOf) return buddyNotice(state, start)+ if (start.request.buddyOf) return start.request.buddySession ? failedSessionStart(state, start) : buddyNotice(state, start)const group = state.conversations.find(c => c.id === start.request.conversationId)// Recorded in this write: once the start has ended, no later poll loads it.if (group) recordTaskState(state, group, now)diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 12340ddb5..846da2e38 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -84,10 +84,18 @@ export interface Agent {/** A Buddy (buddies.ts): the person it brainstorms with, at the membership they added it in. Its role stays a builder's* for older readers; this is what makes it a Buddy, and what refuses it every command but its own chat and proposals. */buddyOf?: { personId: string; generation: string }+ /** A Buddy's thread session (buddySessions.ts): it hears and answers only the thread rooted at `thread`, and reads the main+ * chat only up to `from`, the sequence before the message that started it. The main Buddy has none. */+ buddySession?: BuddySession/** Joined on a Harness Team account's machine: kept, so a machine row that went never brings back the rules of an* ordinary machine (projects.ts teamSessionAccess, security re-review of #2089). */teamAccount?: true}+/** A thread session's thread root and the main chat's last sequence it may read (buddySessions.ts). */+export interface BuddySession { thread: string; from: number }+/** A Buddy chat's live or starting thread session, at most MAX_BUDDY_SESSIONS (buddySessions.ts). `agentId` once it runs;+ * `waiting`, the person's messages sent while it started, delivered to it when it joins. */+export interface BuddySessionEntry { thread: string; startId: string; agentId?: string; at: number; waiting?: string[] }export type AgentRole = 'builder' | 'reviewer'export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'export interface AgentStartRequest {@@ -109,6 +117,9 @@ export interface AgentStartRequest {requirements: { memoryBytes: number; diskBytes: number; maxCpuPercent: number; tools: string[]; devices: string[]; quotaRequired: boolean }/** A Buddy's start (buddies.ts): written by buddy.create alone, never taken from an agent.start. */buddyOf?: { personId: string; generation: string }+ /** A Buddy thread session's start (buddySessions.ts): written by message.send with newSession alone. Ids only, never text:+ * starts are listed to the Lead. */+ buddySession?: BuddySession/** A project's Product Manager's start (leadStart.ts): written by lead.start alone, never taken from an agent.start. Its* agent becomes the Lead of the project's Lead conversation once it runs. */leadFor?: { projectId: string; personId: string; generation: string }@@ -251,6 +262,8 @@ export interface Conversation {/** The name a Buddy chat's owner chose for their Buddy (buddies.ts renameBuddy): kept here, which outlives the Buddy, so* one added again takes it. Absent: the default, "<person>'s Buddy". */buddyName?: string+ /** A Buddy chat's live and starting thread sessions (buddySessions.ts); absent while it has none. */+ buddySessions?: BuddySessionEntry[]/** The person who asked for this work: whoever opened it, or the person its Lead named (leaderboard/record.ts). */requesterId?: string/** What the leaderboard counts here (leaderboard/record.ts); bookkeeping readers never get whole. */@@ -392,6 +405,8 @@ export interface MessageDraft {thread?: string/** A thread reply also shown in the conversation's main stream. */alsoInChat?: true+ /** A reply in a Buddy thread session's thread (buddySessions.ts): the main Buddy never reads it. */+ buddySession?: true}/** A notice for one agent alone (a skill update): delivered to it like any message, never shown to people or other agents. */export const AGENT_ONLY = { kind: 'agent-only' }@@ -412,7 +427,7 @@ export const NOTICE_READERS = {'update-request': 'recipients', 'digest-request': 'recipients', overlap: 'recipients',// Each its own case in commands.ts, decided by the row (forRecipients): statuses, briefs, merges, starts, removals.system: 'people',- rule: 'people', 'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people',+ rule: 'people', 'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people', 'buddy-session-ended': 'people','decision-delegated': 'people', 'machine-removed': 'people', 'machine-left': 'people', ship: 'people', 'auto-review': 'people','auto-archive': 'people', native: 'people',// The nightly routing reflection, for the project's people; never a Buddy's (buddies.ts routingRow).@@ -477,6 +492,8 @@ export interface CommandEffects {/** Decisions asked, and a decision answered, written outside the tab state by the store (decisions.ts). */decisions?: import('./decisions.js').DecisionDraft[]decisionAnswer?: import('./decisions.js').DecisionAnswer+ /** Deliveries of messages already stored: a Buddy thread session's first messages, sent while it started (buddySessions.ts). */+ lateDeliveries?: Array<{ messageId: string; conversationId: string; agentId: string; author: { kind: 'person'; id: string; generation: string } }>}export class SuperTabError extends Error {/** `unreachable`: the caller cannot reach this Swarm at all (not, or no longer, a member). The person routes answer it asdiff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 7e0ac1f06..54d458100 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -101,13 +101,13 @@ export async function messagesPast(tx: Transaction, at: { tabId: string; convers* which is sent as $expr and left to the planner (roadmap Phase 3; plan test in integration/superTabNamedReads.test.ts).*/export async function messagesById(tx: Transaction, tabId: string, conversationId: string, ids: string[]):- Promise<Array<Pick<SuperTabMessage, 'id' | 'source' | 'recipientIds'>>> {+ Promise<Array<Pick<SuperTabMessage, 'id' | 'source' | 'recipientIds' | 'thread' | 'buddySession'>>> {if (!ids.length) return []const rows = await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: ids }, tabId, conversationId } },- { $project: { source: 1, recipientIds: 1 } }])+ { $project: { source: 1, recipientIds: 1, thread: 1, buddySession: 1 } }])return rows.map(row => {- const { id, source, recipientIds } = prismaRow<SuperTabMessage>('SuperTabMessage', row)- return { id, source, recipientIds }+ const { id, source, recipientIds, thread, buddySession } = prismaRow<SuperTabMessage>('SuperTabMessage', row)+ return { id, source, recipientIds, thread: thread ?? null, buddySession: buddySession ?? null }})}@@ -135,10 +135,12 @@ export async function deliveredCopies(tx: Transaction, tabId: string, rows: Read/** `routing`: a route, override or rule row (buddies.ts routingRow), which a Buddy never reads, as a reply or a thread's root.* `count`: how many of the thread's rows this one stands for (pageThreads); a row without it is one. */export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean; routing: boolean- count?: number }+ count?: number+ /** A reply in a Buddy thread session's thread (buddySessions.ts), which the main Buddy never counts. */+ session?: boolean }/** The rows of one thread that every reader sees or skips alike: one author, and one kind of row (agentOnly, routingRow). */-interface ThreadPart { thread: string; root: boolean; kind?: unknown; only?: unknown; to: boolean }+interface ThreadPart { thread: string; root: boolean; kind?: unknown; only?: unknown; to: boolean; session?: boolean | null }/** One row of a part, by its place in the thread. */interface ThreadPlace { s: number; i: string; at: unknown; author: Author; slot?: number }@@ -154,7 +156,8 @@ interface ThreadPlace { s: number; i: string; at: unknown; author: Author; slot?export async function pageThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<ThreadReply[]> {const root = { $eq: ['$_id', '$thread'] }const part = { thread: '$thread', root, kind: '$source.kind', only: '$source.recipientsOnly',- to: { $gt: [{ $size: { $ifNull: ['$recipientIds', []] } }, 0] }, author: { kind: '$author.kind', id: '$author.id' } }+ to: { $gt: [{ $size: { $ifNull: ['$recipientIds', []] } }, 0] }, author: { kind: '$author.kind', id: '$author.id' },+ session: { $eq: ['$buddySession', true] } }// (sequence, id) lead each place, so the database's min and max order rows as the sort below does (ids are ASCII).const place = { s: '$sequence', i: '$_id', at: '$createdAt', author: '$author' }// No $sort: it makes the planner walk the conversation's sequence index instead.@@ -179,7 +182,7 @@ export async function pageThreads(tx: Transaction, tabId: string, conversationIdconst row = (key: ThreadPart, at: ThreadPlace) => {let kept = rows.get(at.i)if (!kept) rows.set(at.i, kept = { thread: key.thread, id: at.i, author: at.author, mentions: [], sequence: at.s, createdAt: new Date(ms(at.at)),- agentOnly: hidden(key), routing: routingRow({ kind: key.kind }), count: 0, slots: [] })+ agentOnly: hidden(key), routing: routingRow({ kind: key.kind }), ...(key.session ? { session: true } : {}), count: 0, slots: [] })return kept}for (const p of parts) {diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex c2258bfc1..211273dae 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -15,7 +15,7 @@ const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,- requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },+ requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', buddySessions: [], liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },}diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex ac10d8a10..5c21e69b5 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status','assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'liveness', 'leadAction', 'stepUp',+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'buddySessions', 'liveness', 'leadAction', 'stepUp','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt'],} as constconst LIGHT_GROUP = {diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 5dd6bdc96..f2dfcbc86 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -111,6 +111,11 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatemember(command.personId ?? undefined)breakcase 'message.send': {+ // A thread session's start counts its machine's slots, as buddy.create's does (buddySessions.ts).+ if (command.newSession) {+ const start = effects.state.starts?.find(s => !before.starts?.some(b => b.id === s.id))+ if (start) { slots(start.request.machineId); head() }+ }// An answer to waiting work is credited to the person it waits on (leaderboard/record.ts): a concurrent change to who// that is meets the answer here.const waiting = before.conversations.find(c => c.id === command.conversationId)diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex f63ba0cd6..02a94c84c 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -24,7 +24,8 @@ import { retryTransient } from './retry.js'import { buddyChatId, type ChosenBuddyName } from './buddies.js'import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'-import { isBuddy, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'+import { SESSION_ENDED_KIND, sessionContext, sessionReadsRow, type ContextRow } from './buddySessions.js'+import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'import { lostReasonWithoutMachine } from './lostReason.js'import { LEAD_NAME } from './leadStart.js'import { confidentialSessions, otherRegistrations, recordConfidential } from './confidential.js'@@ -46,7 +47,7 @@ import { activeMember, addMember, hasWorkspaceAccess, listWorkspaces, memberId,import { WORKSPACE_LABEL, type WorkspaceRole } from './workspaces.js'import {activeWork, actorKey, agent, agentOnly, agentRole, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,- SuperTabError, forRecipients, isLeads, knownKind, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type Conversation, type MessageDraft, type Person, type SuperTabState,+ SuperTabError, forRecipients, isLeads, knownKind, parkLaterConversations, syncLeads, type Actor, type Agent, type Assignment, type Author, type CommandEffects, type Conversation, type MessageDraft, type Person, type SuperTabState,} from './model.js'import type { HoldReason } from './holdReason.js'import { stuck } from './deliverySettle.js'@@ -1069,7 +1070,14 @@ export class SuperTabStore {}async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string) {- try { return await this.executeOnce(user, tabId, input, asAgentId, hostMachineId) } catch (error) {+ try {+ const done = await this.executeOnce(user, tabId, input, asAgentId, hostMachineId)+ // Buddy thread sessions' first warning (spec Design 4): starts, refusals by code and ends by reason, ids only, in the+ // server log that prod watch reads.+ if (input.command?.type === 'message.send' && input.command.newSession && done.result.startId) logger.info('Buddy session started', { tabId, startId: done.result.startId })+ return done+ } catch (error) {+ if (input.command?.type === 'message.send' && input.command.newSession && error instanceof SuperTabError) logger.info('Buddy session refused', { tabId, code: error.code })// A queued start its machine will not take for good — no Harness Team account, or one that is not private — fails// with that reason instead of waiting there: its host would otherwise try to launch it on every pass, and it would// hold a slot. A stale check or an offline machine may pass again by itself, so that start keeps waiting.@@ -1232,9 +1240,14 @@ export class SuperTabStore {// The thread's root says whose proposal the reply answers (buddyNews.ts): the reply itself, or one more read by id.const root = reply?.thread && reply.thread !== reply.id? await tx.superTabMessage.findFirst({ where: { id: reply.thread, tabId, conversationId: command.conversationId }, select: { source: true } }) : reply+ // In a Buddy chat: whether the thread ever had a session (buddySessions.ts), by the thread index, one row at most.+ const buddyChat = original.conversations.find(c => c.id === command.conversationId)+ const sessionThread = reply?.thread && buddyChat && isBuddyChat(buddyChat)+ ? !!await tx.superTabMessage.findFirst({ where: { tabId, conversationId: command.conversationId, thread: reply.thread, buddySession: true }, select: { id: true } })+ : falseif (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime(),thread: reply.thread, threadSource: (root?.source ?? null) as Record<string, unknown> | null,- ...(agentOnly(reply.source, reply.recipientIds) ? { agentOnly: true } : {}) }+ ...(agentOnly(reply.source, reply.recipientIds) ? { agentOnly: true } : {}), ...(sessionThread ? { sessionThread: true as const } : {}) }}if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy'@@ -1257,7 +1270,7 @@ export class SuperTabStore {const ownerId = (asked?.author as unknown as Author | undefined)?.idconst newest = recent.find(m => !m.source && (m.author as unknown as Author).kind === 'person' && (m.author as unknown as Author).id === ownerId)if (asked) context.proposalAsk = { id: asked.id, conversationId: asked.conversationId, author: asked.author as unknown as Author,- source: !!asked.source, createdAt: asked.createdAt.getTime(), ...(newest ? { newestOwnerMessageId: newest.id } : {}) }+ source: !!asked.source, createdAt: asked.createdAt.getTime(), thread: asked.thread, ...(newest ? { newestOwnerMessageId: newest.id } : {}) }}if (command.type === 'message.send' && actor.kind === 'agent') {const recent = await tx.superTabMessage.findMany({ where: { tabId, conversationId: command.conversationId },@@ -1286,7 +1299,7 @@ export class SuperTabStore {claimed = context.attachments.map(a => a.id)}if (command.type === 'buddy.propose' && command.attachmentIds?.length) ({ attachments: context.attachments, claimed, proposed } = await this.proposable(tx, original, actor, command))- if (command.type === 'message.react') context.reaction = await this.reactionTarget(tx, tabId, actor, command)+ if (command.type === 'message.react') context.reaction = await this.reactionTarget(tx, tabId, actor, command, original)if ((command.type === 'member.avatar' || command.type === 'agent.avatar') && command.avatar?.kind === 'upload') {context.avatarUpload = await this.avatarUpload(tx, tabId, actor, command.avatar.id)}@@ -1500,6 +1513,7 @@ export class SuperTabStore {}await recordEvidence(tx, tabId, original, effects.state, context.now)await this.writeMessages(tx, tabId, effects.state, effects.messages, sequences)+ if (effects.lateDeliveries?.length) await this.writeLateDeliveries(tx, tabId, effects.state, effects.lateDeliveries)if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)if (command.type === 'work.assign') await resolveWhenWorked(tx, tabId, command.conversationId, context.now)// The Lead acting on a group ends the tags it held back about it (mentions.ts), before this command's own are written.@@ -1754,10 +1768,15 @@ export class SuperTabStore {/** The message a reaction names, when it is in that conversation and this actor may see it, and whether the actor already* reacted to it with that emoji. An agent-only notice is its recipient's alone. */- private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand): Promise<ReactionTarget | undefined> {+ private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand, state: SuperTabState): Promise<ReactionTarget | undefined> {const message = await tx.superTabMessage.findFirst({ where: { id: command.messageId, tabId, conversationId: command.conversationId },- select: { id: true, source: true, recipientIds: true } })+ select: { id: true, source: true, recipientIds: true, thread: true, buddySession: true } })if (!message || (agentOnly(message.source, message.recipientIds) && !(actor.kind === 'agent' && message.recipientIds.includes(actor.agentId)))) return undefined+ // A Buddy reacts only to what it may read (buddySessions.ts): a session to its own thread, the main Buddy to no session's+ // replies (security review 2 of #2345). Refused as a message it cannot see.+ const group = state.conversations.find(c => c.id === command.conversationId)+ const reader = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined+ if (group && !sessionReadsRow(reader, group)(message)) return undefinedif ((await deliveredCopies(tx, tabId, [message])).size) return undefinedreturn { messageId: message.id, reacted: !!await tx.superTabReaction.findUnique({ where: { id: reactionId(tabId, actor, command) } }) }}@@ -2003,7 +2022,8 @@ export class SuperTabStore {...(message.attachments ? { attachments: json(message.attachments) } : {}),text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [],// A top-level message is its own thread's root; only a row written before threads has none (its replies stay inline).- thread: message.thread ?? message.id, ...(message.alsoInChat ? { alsoInChat: true } : {}) })+ thread: message.thread ?? message.id, ...(message.alsoInChat ? { alsoInChat: true } : {}),+ ...(message.buddySession ? { buddySession: true } : {}) })for (const recipient of [...message.recipients, ...message.buddyRecipients ?? []]) {const target = agent(state, recipient)const group = conversation(state, message.conversationId)@@ -2016,6 +2036,13 @@ export class SuperTabStore {}}if (rows.length) await tx.superTabMessage.createMany({ data: rows })+ for (const message of messages) {+ // Once committed, so a retried write logs once.+ if (message.source?.kind === SESSION_ENDED_KIND && !kept.has(message.id)) {+ const reason = message.source.reason+ afterCommit(tx, () => logger.info('Buddy session ended', { tabId, reason }))+ }+ }if (kept.size) {const have = new Set((await tx.superTabDelivery.findMany({ where: { messageId: { in: [...kept] } }, select: { id: true } })).map(d => d.id))deliveries = deliveries.filter(d => !have.has(d.id))@@ -2024,6 +2051,27 @@ export class SuperTabStore {for (const delivery of deliveries) this.announce(tx, { machineId: delivery.machineId, tabId, agentId: delivery.agentId })}+ /** A Buddy thread session's first deliveries (buddySessions.ts): its person's messages sent in its thread while it started,+ * each written once (its id is the message's and the agent's, as writeMessages makes it), only for a stored message of+ * that conversation by that person in a session thread. */+ private async writeLateDeliveries(tx: Transaction, tabId: string, state: SuperTabState, late: NonNullable<CommandEffects['lateDeliveries']>) {+ const deliveries: Prisma.SuperTabDeliveryCreateManyInput[] = []+ // At most MAX_SESSION_WAITING, each by its primary key (hotFilters.test.ts: no `in` filter on a hot collection).+ for (const l of late) {+ const row = await tx.superTabMessage.findUnique({ where: { id: l.messageId }, select: { tabId: true, conversationId: true, author: true, buddySession: true } })+ const author = row?.author as unknown as Author | undefined+ if (!row || row.tabId !== tabId || row.conversationId !== l.conversationId || !row.buddySession || author?.kind !== 'person' || author.id !== l.author.id+ || author.membershipGeneration !== l.author.generation) continue+ if (await tx.superTabDelivery.findUnique({ where: { id: stableId(l.messageId, l.agentId) }, select: { id: true } })) continue+ const target = agent(state, l.agentId)+ deliveries.push({ id: stableId(l.messageId, l.agentId), tabId, conversationId: l.conversationId, messageId: l.messageId, agentId: l.agentId,+ machineId: target.machineId, machineOwnerId: target.machineOwnerId, assignmentId: null, membershipGeneration: target.membershipGeneration,+ authorKind: 'person', authorId: l.author.id, authorGeneration: l.author.generation })+ }+ if (deliveries.length) await tx.superTabDelivery.createMany({ data: deliveries })+ for (const delivery of deliveries) this.announce(tx, { machineId: delivery.machineId, tabId, agentId: delivery.agentId })+ }+/** Once `tx` commits, never for an attempt that failed or was retried: told earlier, a host could read before the delivery* is visible, and wait 30 s for its next read. */private announce(tx: Transaction, waiting: DeliveriesWaiting): void {@@ -2042,13 +2090,23 @@ export class SuperTabStore {const group = readConversation(state, actor, conversationId)// A Buddy reads its project's workgroups but never how work is routed: a route row names the machines that could run it// and why others could not (security review 2 of #2115). Left out like an agent-only notice (readsRow), so no page is shorter.- const buddy = isBuddyReader(state, actor), readable = readsRow(actor, buddy)+ const buddy = isBuddyReader(state, actor), rowRead = readsRow(actor, buddy)+ // A Buddy thread session reads its own thread alone, and the main Buddy none of a session's (buddySessions.ts): the one+ // check every agent read of a Buddy chat applies, here and through every row it points at below.+ const reader = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId) : undefined+ const sessionRead = sessionReadsRow(reader, group), own = isBuddyChat(group) ? reader?.buddySession : undefined+ const readable = (m: Pick<SuperTabMessage, 'id' | 'source' | 'recipientIds' | 'thread' | 'buddySession'>) => rowRead(m) && sessionRead(m)+ // A session reads its chat through its own thread, so it never walks the main chat to fill a page; another thread reads empty.+ if (own) {+ if (cursor.thread && cursor.thread !== own.thread) return { messages: [], next: null, threads: [], reactionSeq: group.reactionSeq ?? 0 }+ cursor = { ...cursor, thread: own.thread }+ }// One thread is read only through a root this reader may read. A hidden root (an agent-only note to someone else; for a// Buddy, a route row) reads as one that is not in this conversation, and as an exact message it may not see: an empty// page, never its replies alone (review 2 of #2168). By its id, through the primary key.if (cursor.thread) {const root = await tx.superTabMessage.findFirst({ where: { tabId, conversationId, id: cursor.thread },- select: { id: true, source: true, recipientIds: true } })+ select: { id: true, source: true, recipientIds: true, thread: true, buddySession: true } })// A task chat's copy of a Lead's notice stored before it was marked is read by no one either (pageReads.ts).if (!root || !readable(root) || (await deliveredCopies(tx, tabId, [root])).size) {return { messages: [], next: null, threads: [], reactionSeq: group.reactionSeq ?? 0 }@@ -2088,7 +2146,9 @@ export class SuperTabStore {// The threads the page's rows are in, so a poll that brings only a reply still moves its root's reply line.const roots = [...new Set(page.flatMap(m => m.thread && !hidden.has(m.thread) ? [m.thread] : []))]const threadRows = roots.length ? await pageThreads(tx, tabId, conversationId, roots) : []- const summaries = threadRows.length ? threadSummaries(state, group, buddy ? threadRows.filter(r => !r.routing) : threadRows) : []+ // The main Buddy counts none of a session thread's replies, as it reads none (buddySessions.ts).+ const counted = buddy ? threadRows.filter(r => !r.routing && (own || !(isBuddyChat(group) && r.session))) : threadRows+ const summaries = counted.length ? threadSummaries(state, group, counted) : []const threads = buddy ? summaries.map(t => ({ ...t, authors: t.authors.map(authorForBuddy) })) : summaries// A lost task's rows and a machine leaving name the machine; a Buddy reads them without it (security reviews of #2115), and// an agent's rows without its membership (delta review 1 of #2258).@@ -2096,12 +2156,24 @@ export class SuperTabStore {? { ...m, ...(m.thread && hidden.has(m.thread) ? { thread: null } : {}), ...(m.replyTo && hidden.has(m.replyTo) ? { replyTo: null } : {}) } : m)// Whose Buddy hears a row is its person's own: its news shows to that Buddy alone.const shownTo = (m: SuperTabMessage, d: PageDelivery) => !buddyNews(m, d) || (actor.kind === 'agent' && actor.agentId === d.agentId)+ // A session's own thread read carries the main-chat excerpt it started from (buddySessions.ts sessionContext).+ const context = own && !forward && cursor.before === undefined && !cursor.messageId ? await this.sessionExcerpt(tx, tabId, conversationId, own.from, rowRead) : undefinedreturn { messages: shown.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],- deliveries: deliveries.filter(d => d.messageId === m.id && shownTo(m, d)) })), next, threads,+ deliveries: deliveries.filter(d => d.messageId === m.id && shownTo(m, d)) })), next, threads, ...(context ? { context } : {}),// A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).reactionSeq: group.reactionSeq ?? 0 }}+ /** The main-chat excerpt a Buddy thread session starts from: main-stream rows at or before `from` it may read (never a session+ * thread's, never a reply only in its thread), by the conversation's sequence index, at most 50 rows read for 10 kept. */+ private async sessionExcerpt(tx: Transaction, tabId: string, conversationId: string, from: number,+ rowRead: (m: Pick<SuperTabMessage, 'source' | 'recipientIds'>) => boolean) {+ const rows = await tx.superTabMessage.findMany({ where: { tabId, conversationId, sequence: { lte: from } }, orderBy: [{ sequence: 'desc' }, { id: 'desc' }],+ take: 50, select: { id: true, sequence: true, text: true, author: true, createdAt: true, thread: true, alsoInChat: true, buddySession: true, source: true, recipientIds: true } })+ const main = rows.filter(r => !r.buddySession && (!r.thread || r.thread === r.id || r.alsoInChat) && rowRead(r))+ return sessionContext(main.map(r => ({ ...r, author: r.author as unknown as ContextRow["author"] })))+ }+/** What the person missed in one conversation since `after` (catchUp.ts), from the rows past it they may read, as a page* shows them: the same read check and row filter as messages(). People only, reading as themselves: agents read every* message as it comes. At most CATCH_UP_SCAN rows are read; `more` says there were more. */diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 39cf4ae97..9547293a4 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -5,6 +5,6 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts','integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',- 'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',+ 'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/cli/src/lib/buddyGuard.spec.ts b/cli/src/lib/buddyGuard.spec.tsindex c3bb97f7b..8d119d3eb 100644--- a/cli/src/lib/buddyGuard.spec.ts+++ b/cli/src/lib/buddyGuard.spec.ts@@ -103,6 +103,9 @@ describe('a Buddy\'s guard (Ken, 10-29: reads without a prompt, refuses everythi// Its Super Tab commands, as the pane it runs in identifies it (superTabs/command.ts callerOf).'harness super-tab --tab t status','harness super-tab --tab t messages chat',+ // A thread session reads its own thread (spec 2026-10-30-buddy-thread-sessions).+ 'harness super-tab --tab t messages chat --thread root-1',+ 'harness super-tab --tab t messages chat --thread root-1 --before 40 m-1','harness super-tab --tab t message chat m1','harness super-tab --tab t decisions --answered',"harness super-tab --tab t post chat 'see /etc and ../up, as text' op-3 --reply-to m1",@@ -163,6 +166,8 @@ describe('a Buddy\'s guard (Ken, 10-29: reads without a prompt, refuses everythi'harness super-tab --tab t --agent me status','harness super-tab --tab t --port 18474 status','harness super-tab --tab t --machine other status',+ 'harness super-tab --tab t messages chat --thread root-1 --agent other',+ 'harness super-tab --tab t messages chat --thread root-1 --machine other','harness super-tab --tab t command op {}','harness super-tab --tab t start op {}','harness super-tab --tab t resume start-1',diff --git a/cli/src/lib/buddyGuard.ts b/cli/src/lib/buddyGuard.tsindex 6f344d9f8..0e995cfb3 100644--- a/cli/src/lib/buddyGuard.ts+++ b/cli/src/lib/buddyGuard.ts@@ -1,8 +1,8 @@import { spawnSync } from 'node:child_process'import { createHash, randomUUID } from 'node:crypto'-import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync,+import { chmodSync, closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync,writeFileSync } from 'node:fs'-import { basename, dirname, isAbsolute, join } from 'node:path'+import { basename, dirname, isAbsolute, join, relative } from 'node:path'import { homedir, tmpdir } from 'node:os'import { isTeamAccount } from '../team/config.js'import { buddyAccountFile } from './buddyAccount.js'@@ -24,7 +24,11 @@ export interface BuddyWide { home: string; denied: readonly string[];/** This launch, at random: a grant from before a relaunch is none (delta reviews of #2310). */launch: string/** Where the host keeps the account signed in on this machine (`writeBuddyAccount`): a grant holds only for it. */- accountFile: string }+ accountFile: string+ /** Where every Swarm session's folder on this machine is (Harness's worktrees folder): closed to this one's reads but its+ * own folder, so a Buddy's thread session never reads another session's folder or the files sent to it (spec+ * 2026-10-30-buddy-thread-sessions). The guard's alone: closing it in the sandbox would close the session's own folder. */+ otherSessions?: readonly string[] }/** Where each engine Harness runs keeps its sessions, history and sign-in in a home: closed to a Buddy, as other agents on* this machine keep Swarm chats there (delta reviews of #2310). Typed by the engine list, so a new engine names its own. */@@ -70,9 +74,9 @@ const SYSTEM_READABLE = process.platform === 'darwin'/** Wide mode for one person's Buddy: [home] is theirs, [dataDir] Harness's data folder (its lists, approvals, downloads and* agent records stay closed), [tmpDirs] where Claude Code keeps other sessions' tool output, and [repos] the project's repositories (owner/name), the only ones gh api reads. */export function buddyWideOf(input: { home: string; dataDir: string; tmpDirs: readonly string[]; repos: readonly string[]; hosts?: readonly string[];- system?: readonly string[]; launch?: string; closed?: readonly string[] }): BuddyWide {+ system?: readonly string[]; launch?: string; closed?: readonly string[]; otherSessions?: readonly string[] }): BuddyWide {return { home: input.home, launch: input.launch ?? randomUUID(), accountFile: buddyAccountFile(input.dataDir), readable: [input.home, ...(input.system ?? SYSTEM_READABLE)], repos: input.repos, hosts: input.hosts ?? [], sessionTemp: input.tmpDirs, denied: [...CLOSED_IN_HOME.map(path => join(input.home, path)), input.dataDir, ...input.tmpDirs, ...(input.closed ?? [])],- approvalsDir: join(input.dataDir, 'buddy-approvals') }+ approvalsDir: join(input.dataDir, 'buddy-approvals'), ...(input.otherSessions?.length ? { otherSessions: input.otherSessions } : {}) }}/** What a Buddy's launch reads of its machine to decide wide mode (`buddyLaunchWide`). */@@ -142,7 +146,19 @@ export function buddyLaunchWide(root: string, facts: BuddyLaunchFacts = launchFaif (facts.team || !(facts.platform === 'darwin' || (facts.platform === 'linux' && facts.hasBwrap)) || !facts.engineHomes) return null// Where Claude Code keeps every session's tool output on this machine.const tmpDirs = [...new Set([`/tmp/claude-${facts.uid}`, `/private/tmp/claude-${facts.uid}`, join(tmpdir(), `claude-${facts.uid}`)])]- return buddyWideOf({ home: facts.home, dataDir: facts.dataDir, tmpDirs, repos: githubRepos(root), hosts: configHosts(facts.home), closed: facts.engineHomes })+ return buddyWideOf({ home: facts.home, dataDir: facts.dataDir, tmpDirs, repos: githubRepos(root), hosts: configHosts(facts.home), closed: facts.engineHomes,+ otherSessions: sessionsFolderOf(root, facts.home) })+}++/** Harness's worktrees folder, where every Swarm session's folder is (lib/gitProject.ts), when [root] is one of them: a+ * Buddy or thread session in a worktree of its own. None for a folder elsewhere, which nothing here would close. */+function sessionsFolderOf(root: string, home: string): string[] {+ const real = (path: string) => { try { return realpathSync(path) } catch { return null } }+ // lib/projectFolder.ts projectsRoot, which this module does not import: it brings git and every source host with it.+ const worktrees = join(home, process.env.HARNESS_OS === '1' ? 'projects' : 'harnesses', 'worktrees'), at = real(root), folder = real(worktrees)+ if (!at || !folder) return []+ const inside = relative(folder, at)+ return inside && !inside.startsWith('..') && !isAbsolute(inside) ? [worktrees] : []}@@ -385,7 +401,8 @@ const SECRET_NAMES = [/^\.env/i, /\.env$/i, /\.(pem|key|p12|pfx|jks|keystore|kdb/^\.claude/i, /^\.codex/i, /ro-?prod|prod-?db/i, /^\.?(netrc|npmrc|pypirc|pgpass|htpasswd|git-credentials)$/i]const secretName = (path) => path.split(sep).some((part) => SECRET_NAMES.some((name) => name.test(part)))const realRoots = (paths) => paths.map((path) => realOf(path) ?? path)-const DENIED = WIDE ? realRoots(WIDE.denied) : []+// Other sessions' folders (WIDE.otherSessions) are closed as these are; its own folder is read as its folder, before any of this.+const DENIED = WIDE ? realRoots([...WIDE.denied, ...(WIDE.otherSessions ?? [])]) : []// What may be read outside the folder at all: the person's home and the system folders named for it. Everything else is// closed, the process and device folders and every temporary folder among it (security reviews 1 and 2 of #2310: on Linux// /proc/<pid>/environ held the read-only DB URL while db-size ran; on macOS /private/var/folders held other processes'diff --git a/cli/src/lib/buddyGuard.wide.spec.ts b/cli/src/lib/buddyGuard.wide.spec.tsindex 8bc1a403d..b5dac4496 100644--- a/cli/src/lib/buddyGuard.wide.spec.ts+++ b/cli/src/lib/buddyGuard.wide.spec.ts@@ -690,6 +690,68 @@ describe('wide mode only while the host has granted it', () => {})})+// Spec 2026-10-30-buddy-thread-sessions: a thread session is a Buddy of its own, in a worktree of its own. Its grant is its+// own, at its own launch, and no session reads another's folder.+describe('a Buddy\'s thread sessions', () => {+ const worktrees = join(home, 'harnesses', 'worktrees'), mine = join(worktrees, 'openharness', 'session-b'), theirs = join(worktrees, 'openharness', 'main-buddy')+ file(join(mine, 'own.txt'))+ file(join(theirs, 'sent-to-main.txt'), 'private\n')+ const readsB = { file: join(dataDir, 'buddy-reads', 'session-b.json'), drops: join(dataDir, 'paste-drops') }+ const wideB = buddyWideOf({ home, dataDir, tmpDirs: [tmpClaude], repos: ['autonomous-ai/openharness'], launch: 'launch-b', otherSessions: [worktrees] })+ const scriptB = join(parent, 'buddy-guard-b.mjs')+ writeFileSync(scriptB, buddyGuardSource(mine, readsB, wideB))+ const grantB = () => grantBuddyWide(readsB, { session: 'harness-b', wide: true, account: 'person-1', launch: 'launch-b' })+ const decideB = (tool: string, input: Record<string, unknown>) => {+ const run = spawnSync(process.execPath, [scriptB], { input: JSON.stringify({ hook_event_name: 'PreToolUse', tool_name: tool, tool_input: input, cwd: mine }),+ encoding: 'utf8', timeout: 10_000 })+ expect(run.status).toBe(0)+ return JSON.parse(run.stdout).hookSpecificOutput.permissionDecision+ }+ const notes = join(home, 'work', 'notes.txt')+ afterAll(grant)++ it('gets no grant from the main session\'s, and the main session none from its own', () => {+ grant()+ rmSync(readsB.file, { force: true })+ expect([decide('Read', { file_path: notes }), decideB('Read', { file_path: notes })]).toEqual(['allow', 'deny'])+ // The main session's list copied as its own still names the main session's launch: no grant.+ writeFileSync(readsB.file, readFileSync(reads.file, 'utf8'))+ expect(decideB('Read', { file_path: notes })).toBe('deny')+ // Its own grant, written at its own person's message: its own reads open, and the main session's grant taken back+ // changes nothing for it.+ grantB()+ expect(decideB('Read', { file_path: notes })).toBe('allow')+ revokeBuddyWide(reads)+ expect([decide('Read', { file_path: notes }), decideB('Read', { file_path: notes })]).toEqual(['deny', 'allow'])+ // Its grant written into the main session's list names its own launch: the main session still has none.+ writeFileSync(reads.file, readFileSync(readsB.file, 'utf8'))+ expect(decide('Read', { file_path: notes })).toBe('deny')+ })++ it('reads its own folder and never another session\'s, by any tool or path', () => {+ grantB()+ expect(decideB('Read', { file_path: join(mine, 'own.txt') })).toBe('allow')+ expect(decideB('Read', { file_path: notes })).toBe('allow')+ for (const [tool, input] of [+ ['Read', { file_path: join(theirs, 'sent-to-main.txt') }], ['Grep', { pattern: 'private', path: join(theirs, 'sent-to-main.txt') }],+ ['LS', { path: theirs }], ['Glob', { pattern: '**/*.txt', path: worktrees }], ['Glob', { pattern: '*', path: join(home, 'harnesses') }],+ ['Bash', { command: `cat ${join(theirs, 'sent-to-main.txt')}`, description: 'x' }], ['Bash', { command: `ls ${theirs}`, description: 'x' }],+ ['Read', { file_path: join(mine, '..', 'main-buddy', 'sent-to-main.txt') }],+ ] as const) expect([tool, decideB(tool, input)]).toEqual([tool, 'deny'])+ })++ it('closes the worktrees folder at launch for a Buddy in a worktree, and nothing for one elsewhere', () => {+ const launchHome = join(parent, 'launch-sessions'), at = join(launchHome, 'harnesses', 'worktrees', 'app', 'session')+ mkdirSync(at, { recursive: true })+ const facts = { platform: 'darwin' as NodeJS.Platform, team: false, home: launchHome, dataDir, uid: 501, hasBwrap: false, engineHomes: [] }+ expect(buddyLaunchWide(at, facts)!.otherSessions).toEqual([join(launchHome, 'harnesses', 'worktrees')])+ expect(buddyLaunchWide(launchHome, facts)).not.toHaveProperty('otherSessions')+ // The sandbox does not close it: its own folder is in it.+ expect((buddySandboxSettings(at, buddyLaunchWide(at, facts)!).filesystem as { denyRead: string[] }).denyRead)+ .not.toContain(join(launchHome, 'harnesses', 'worktrees'))+ })+})+describe('a grant taken back at launch', () => {afterAll(grant)it('takes back the grant in a session\'s list, keeping what else it lists, and leaves no list where there was none', () => {diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex 0d9a44aaf..aa81623fe 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -549,6 +549,24 @@ describe('built-in Swarm skills', () => {})})+ // Security review 1 of #2345: in a project that does not ignore .claude, a Buddy's own files there left its worktree reading+ // as uncommitted work, so an ended session's folder was never removed.+ it('keeps a Buddy\'s own .claude files out of Git in a project that does not ignore .claude, and leaves a project\'s own ignore file alone', () => {+ const workspace = fixture()+ execFileSync('git', ['init', '-q', workspace])+ prepareSwarmSkill(workspace, { role: 'buddy', key: 'session', mode: 'default' }, folderOnly)+ expect(execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: workspace, encoding: 'utf8' })).toBe('')+ // A relaunch writes it again.+ prepareSwarmSkill(workspace, { role: 'buddy', key: 'session', mode: 'default' }, folderOnly)+ expect(execFileSync('git', ['status', '--porcelain', '--untracked-files=all'], { cwd: workspace, encoding: 'utf8' })).toBe('')+ const project = fixture()+ execFileSync('git', ['init', '-q', project])+ mkdirSync(join(project, '.claude'))+ writeFileSync(join(project, '.claude', '.gitignore'), 'notes/\n')+ prepareSwarmSkill(project, { role: 'buddy', key: 'other', mode: 'default' }, folderOnly)+ expect(readFileSync(join(project, '.claude', '.gitignore'), 'utf8')).toBe('notes/\n')+ })+// Diego, 10-30: the ignore file itself was left untracked, so every Swarm worktree read as uncommitted work and neither// the cleanup of a removed agent nor the weekly sweep ever removed one. The whole folder stays out of Git, including// git add -A; every launch writes the file again, so committing it kept nothing (#1533 wanted generated skills unstaged).@@ -728,6 +746,28 @@ describe('the Buddy skill talks in its owner\'s chat and waits for nothing (Scho})})+// Spec 2026-10-30-buddy-thread-sessions: a thread session runs with the same guard and rules as the main Buddy. Its folder+// is locked by the same launch, so its files differ only where they name its own folder, its own list and its own launch.+describe('a Buddy\'s thread session\'s folder', () => {+ it.each([['folder only', false], ['wide mode', true]] as const)('is locked exactly as the main Buddy\'s, in %s', (_, wide) => {+ const home = fixture(), dataDir = join(home, '.data')+ const wideOf = (launch: string) => wide ? () => buddyWideOf({ home, dataDir, tmpDirs: ['/tmp/claude-501'], repos: ['autonomous-ai/openharness'], launch }) : folderOnly+ const sessions = [['main-key', 'launch-main'], ['session-key', 'launch-session']].map(([key, launch]) => {+ const root = realpathSync(fixture())+ prepareSwarmSkill(root, { role: 'buddy', key: key!, mode: 'default' }, wideOf(launch!))+ const neutral = (text: string) => text.split(root).join('<FOLDER>').split(buddyReadsOf(key!).file).join('<READS>').split(launch!).join('<LAUNCH>')+ return { root, key, launch, settings: readFileSync(join(root, '.claude', 'settings.local.json'), 'utf8'), guard: readFileSync(join(root, '.claude', 'buddy-guard.mjs'), 'utf8'), neutral }+ })+ const [main, session] = sessions as [typeof sessions[0], typeof sessions[0]]+ expect(session.guard).not.toBe(main.guard)+ expect(session.neutral(session.guard)).toBe(main.neutral(main.guard))+ expect(session.neutral(session.settings)).toBe(main.neutral(main.settings))+ // Each names only its own list and launch.+ expect(session.guard).not.toContain(buddyReadsOf(main.key!).file)+ if (wide) expect(session.guard).not.toContain(main.launch)+ })+})+describe('a Buddy\'s folder (Lead\'s ruling on the privacy review of #1992)', () => {it('runs every Claude Code tool call past its guard, refuses the rest without asking, denies file editing, and leaves its files read-only', () => {const workspace = fixture()diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex d63a36432..002dcbecc 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -739,6 +739,21 @@ function harnessClaudeHooks(): Record<string, unknown[]> {* also reads outside its folder and runs its person's approved reads, its shell in Claude Code's sandbox* (docs/specs/2026-10-30-buddy-read-access.md).*/+/** What a Buddy's launch writes in its folder's .claude, ignored by a file that ignores itself too: in a project that does+ * not ignore .claude, these left every ended Buddy's worktree reading as uncommitted work, so neither the close nor the+ * weekly sweep removed it (security review 1 of #2345; the same as .harness/.gitignore, #2266). */+export const BUDDY_IGNORE = '/settings.local.json\n/buddy-guard.mjs\n/buddy-launch\n/.gitignore\n'+function ignoreBuddyFiles(root: string): void {+ const file = join(root, '.claude', '.gitignore')+ // A project's own file stays exactly as it is: only a missing one, or the one this wrote, is written.+ if (existsSync(file)) {+ const stat = lstatSync(file)+ if (!stat.isFile() || stat.isSymbolicLink() || readFileSync(file, 'utf8') !== BUDDY_IGNORE) return+ chmodSync(file, 0o600)+ }+ writeFileSync(file, BUDDY_IGNORE, { mode: 0o600 })+}+function lockBuddyFolder(root: string, key: string, wide: BuddyWide | null): void {const settings = join(root, '.claude', 'settings.local.json'), guard = join(root, '.claude', 'buddy-guard.mjs')mkdirSync(join(root, '.claude'), { recursive: true })@@ -752,6 +767,7 @@ function lockBuddyFolder(root: string, key: string, wide: BuddyWide | null): voiif (wide) writeFileSync(launchFile, `${wide.launch}\n`, { mode: 0o600 }); else rmSync(launchFile, { force: true })writeFileSync(guard, buddyGuardSource(root, buddyReadsOf(key), wide), { mode: 0o600 })writeFileSync(settings, `${JSON.stringify(buddyClaudeSettings(guard, wide ? buddySandboxSettings(root, wide) : null), null, 2)}\n`, { mode: 0o600 })+ ignoreBuddyFiles(root)const walk = (dir: string) => {for (const entry of readdirSync(dir, { withFileTypes: true })) {if (dir === root && (entry.name === '.harness' || entry.name === '.git')) continuediff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.tsindex 87aaaa088..0d2cb08c1 100644--- a/cli/src/superTabs/cards.spec.ts+++ b/cli/src/superTabs/cards.spec.ts@@ -935,6 +935,18 @@ describe('leadsOf Buddies', () => {expect(leadsOf(on(), 'm1', idle, undefined, 'pm-web').leads.find(l => l.projectId === 'web')).toMatchObject({ chat: lead, sideChat: lead })})+ // Spec 2026-10-30-buddy-thread-sessions: a thread session is a second Buddy agent in the chat, answering in its thread only.+ it('takes the main Buddy for the block, never a thread session listed first', () => {+ const session = agent('s1', { name: "diego's Buddy", displayName: 'Thread', buddyOf: { personId: 'me', generation: 'g1' }, configuration: { engine: 'claude' },+ buddySession: { thread: 'root-1', from: 3 } })+ const state = chats({ buddies: true, agents: [...chats().agents as object[], session, buddy()],+ conversations: [...swarm().conversations, pm({ agentIds: ['s1', 'y1'] }), group()] })+ expect(web(state).buddy).toMatchObject({ chatId: 'pm-web', name: "diego's Buddy", engine: 'codex', local: 'h-y1' })+ // A chat with only a thread session (its main Buddy removed) has no Buddy for the block.+ const alone = chats({ buddies: true, agents: [...chats().agents as object[], session], conversations: [...swarm().conversations, pm({ agentIds: ['s1'] }), group()] })+ expect(web(alone)).not.toHaveProperty('buddy')+ })+it('never puts a read-only Chat with PM on the face while Buddies are on', () => {const chatWithPm = conv('cpm-web', null, { projectId: 'web', agentIds: ['a1'], audience: { people: [{ id: 'me' }] } })const state = on({ conversations: [...swarm().conversations, pm({ agentIds: ['y1'] }), chatWithPm] })diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.tsindex b648ce645..0e1d5b53d 100644--- a/cli/src/superTabs/cards.ts+++ b/cli/src/superTabs/cards.ts@@ -64,10 +64,12 @@ function buddyChatOf(conversations: Json[], projectId: string, me: string | undereturn conversations.find(c => isReadersBuddyChat(c, me) && inProject(c, projectId) && c.archived !== true && cardId(c.id))}/** The reader's Buddies in their chat: the chat's agents that are a Buddy of the reader. One whose `buddyOf` names someone- * else (an agent id reused or misfiled) is not. */+ * else (an agent id reused or misfiled) is not, and neither is a thread session (spec 2026-10-30-buddy-thread-sessions),+ * which answers in its own thread: the dial's Buddy is the main one. */function buddiesIn(agents: Json[], chat: Json, me: string | undefined): Json[] {const ids = idsOf(chat.agentIds)- return agents.filter(a => typeof a.id === 'string' && ids.includes(a.id) && me !== undefined && object(a.buddyOf).personId === me)+ return agents.filter(a => typeof a.id === 'string' && ids.includes(a.id) && me !== undefined && object(a.buddyOf).personId === me+ && (a.buddySession === undefined || a.buddySession === null))}/** The name Desktop shows and draws an agent by (super_tabs/identity.dart). */const agentName = (agent: Json): string => String(agent.displayName ?? agent.name ?? '')diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.tsindex c7b4b3c67..61fb6ca69 100644--- a/cli/src/superTabs/command.spec.ts+++ b/cli/src/superTabs/command.spec.ts@@ -681,6 +681,19 @@ it('parses archived status pages and older message pages', () => {}})+// A Buddy's thread session reads its own thread (spec 2026-10-30-buddy-thread-sessions), paged as the conversation is.+it('parses one thread\'s messages, and its older pages', () => {+ const at = ['--tab', 'tab']+ expect(parseSuperTabArgs([...at, 'messages', 'chat', '--thread', 'root-1'], where).payload).toMatchObject({ action: 'messages', conversationId: 'chat', thread: 'root-1' })+ expect(parseSuperTabArgs([...at, 'messages', 'chat', '--thread', 'root-1', '--before', '40', 'm-1'], where).payload)+ .toMatchObject({ action: 'messages', conversationId: 'chat', thread: 'root-1', before: 40, beforeId: 'm-1' })+ for (const argv of [['messages', 'chat', '--thread'], ['messages', 'chat', '--thread', 'a b'], ['messages', 'chat', '--thread', '../x'],+ ['messages', 'chat', '--thread', 'root-1', '--before', '40'], ['messages', 'chat', '--thread', 'root-1', 'extra'],+ ['messages', 'chat', '--thread', 'root-1', '--before', 'x', 'm-1']]) {+ expect(() => parseSuperTabArgs([...at, ...argv], where)).toThrow('harness super-tab')+ }+})+// Cost records (Dee, 2026-10-29): what routed attempts cost and how they went, over the last days.it('reads the cost summary of the last 7 days, or of --days N up to 90', () => {expect(parseSuperTabArgs([...prefix, 'costs'], where).payload).toMatchObject({ action: 'costs', days: 7 })diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.tsindex 78fea165f..cc5d4347e 100644--- a/cli/src/superTabs/command.ts+++ b/cli/src/superTabs/command.ts@@ -28,7 +28,7 @@ function harnessIn(frames: PaneFrame[], pane: string, machineId: string): booleaconst ELSEWHERE = 'From a harness, Swarm commands go to this computer\'s own Harness only: leave out --machine and --port, or give this computer\'s own.'-const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--archived [PAGE]] | messages GROUP [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status [--archived [PAGE]] | messages GROUP [--thread ROOT] [--before SEQUENCE MESSAGE_ID] | message GROUP MESSAGE_ID | decisions [--answered] | costs [--days N] | post GROUP TEXT|- OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]... | react GROUP MESSAGE_ID EMOJI OPERATION_ID [--off] | command OPERATION_ID JSON | propose OPERATION_ID JSON [--attach PATH]... | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | route GROUP JSON | plan [JSON] | remove-machine MACHINE_ID [--yes] | set-agents MACHINE_ID COUNT | screen AGENT [--scrollback N] | type AGENT [TEXT] [--key K]... | help'/** The actions that take an id and then one JSON argument, and what that id names. */const JSON_ACTIONS: Readonly<Record<string, string>> = { command: 'OPERATION_ID', propose: 'OPERATION_ID', start: 'OPERATION_ID', capacity: 'MACHINE_ID', route: 'GROUP' }const stdinHint = (action: string) => `or send the JSON on stdin with - in its place: ${action} ${JSON_ACTIONS[action]} - <<'JSON' (the JSON on the next lines, then JSON alone on a line)`@@ -104,6 +104,14 @@ export function parseSuperTabArgs(argv: readonly string[], where: Where, stdin:&& Number.isSafeInteger(Number(third)) && identifier(positional[4])) {Object.assign(payload, { conversationId: first, before: Number(third), beforeId: positional[4] })}+ // One thread, its root and replies (a Buddy's thread session reads its own this way, with the main-chat messages it started+ // from), paged as the conversation is.+ else if (action === 'messages' && identifier(first) && second === '--thread' && identifier(third) && (positional.length === 4+ || (positional.length === 7 && positional[4] === '--before' && /^(0|[1-9][0-9]{0,15})$/.test(positional[5] ?? '')+ && Number.isSafeInteger(Number(positional[5])) && identifier(positional[6])))) {+ Object.assign(payload, { conversationId: first, thread: third,+ ...(positional.length === 7 ? { before: Number(positional[5]), beforeId: positional[6] } : {}) })+ }// A Buddy's archived tasks, a page at a time from the page the last one named (cli/src/superTabs/buddyStatus.ts).else if (action === 'status' && first === '--archived' && (positional.length === 2 || positional.length === 3 && /^[A-Za-z0-9_-]{1,512}$/.test(second ?? ''))) {Object.assign(payload, { archived: true, ...(second ? { before: second } : {}) })diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.tsindex 26904146b..2e64c7198 100644--- a/cli/src/superTabs/host.spec.ts+++ b/cli/src/superTabs/host.spec.ts@@ -10,7 +10,8 @@ import { PASTE_DROPS_DIR } from '../lib/pasteDropFiles.js'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'import { fakeCore } from '../testing/fakeCore.js'-import { backend, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'+import { backend, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'+import { TerminalHost } from './terminal.js'import { hostForm, swarmReply } from './fixtures/read/index.js'import { CONTINUE } from './limitResume.js'import { HostFeed } from './hostFeed.js'@@ -1365,6 +1366,11 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {['its person from an earlier membership', { author: { ...person, membershipGeneration: 'before' } }, {}, {}],['another person\'s Buddy chat', {}, { conversations: [{ ...buddyChat, buddyOwnerId: 'sam' }] }, {}],['its chat once archived', {}, { conversations: [{ ...buddyChat, archived: true }] }, {}],+ // Security review 1 of #2345: a thread session hears its person only in its own thread.+ ['a thread session, from a message outside its thread', { thread: 'main-root' }, { agents: [{ ...buddyAgent, buddySession: { thread: 'root-1', from: 1 } }] }, {}],+ // Security re-check 2 of #2345: a session whose thread cannot be read fails closed, even for a message naming the same.+ ['a thread session whose thread id is malformed', { thread: 'not an id/..' }, { agents: [{ ...buddyAgent, buddySession: { thread: 'not an id/..', from: 1 } }] }, {}],+ ['a thread session with no thread at all', {}, { agents: [{ ...buddyAgent, buddySession: 'garbage' }] }, {}],])('records nothing for %s, and still delivers the message', async (_, message, read, claim) => {const { host, delivered, guard } = approving({ text: 'run: argocd app list', ...message }, read, claim)await host.tick()@@ -1386,6 +1392,13 @@ describe('what a Buddy\'s own person sends it in their Buddy chat', () => {expect(delivered[0]!.text).toContain('Your owner sent run: lines, but wider reads are off for you on this computer, so nothing was approved.')})+ it('records them for a thread session from its person\'s message in its own thread', async () => {+ const { host, delivered } = approving({ text: 'run: argocd app list', thread: 'root-1' }, { agents: [{ ...buddyAgent, buddySession: { thread: 'root-1', from: 1 } }] })+ await host.tick()+ expect(delivered).toHaveLength(1)+ expect(recorded()).toEqual(['argocd app list'])+ })+// Delta reviews of #2310: a delivery tried again must not add time to an approval.it('dates each approval by when its person sent the message, not when it was delivered', async () => {const sent = Date.now() - 10 * 24 * 60 * 60 * 1000@@ -2618,6 +2631,152 @@ function lifeFixture(rows: Record<string, unknown>[], options: SuperTabHostOptio}const leadRow = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', lead: true, active: true, agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }, ...extra })+// Spec 2026-10-30-buddy-thread-sessions: a Buddy's thread session never stays on its person's machine once its thread is done+// with it. Its host asks the backend to end it, as the machine's owner, when idle or when its terminal is gone.+describe('ending a Buddy\'s thread sessions', () => {+ const BUDDY_OF = { personId: 'peer', generation: 'g' }+ const sessionRow = (extra: Record<string, unknown> = {}) => ({ tabId: 'tab', active: true,+ agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1', projectId: 'proj', buddyOf: BUDDY_OF, buddySession: { thread: 'root-1', from: 7 } }, ...extra })+ const ends = (t: ReturnType<typeof lifeFixture>) => t.commands.filter(c => (c.command as Record<string, unknown>)?.type === 'buddy.sessionEnd')+ const chat = buddyChatIdOf('proj', 'peer', 'g')+ let progress: ReturnType<typeof vi.spyOn> | undefined+ afterEach(() => { progress?.mockRestore(); progress = undefined })+ /** Time passing as the host sees it awake: a look each minute, never a gap it would take for sleep. */+ const awake = async (t: ReturnType<typeof lifeFixture>, ms: number) => { for (let left = ms; left > 0; left -= 60_000) await t.poll(Math.min(60_000, left)) }++ it('ends one idle for 30 minutes, once, naming its own chat and thread, as the backend computes the chat', async () => {+ const t = lifeFixture([sessionRow()])+ t.live(true)+ await t.poll()+ await awake(t, BUDDY_SESSION_IDLE_MS - 1)+ expect(ends(t)).toEqual([])+ await t.poll(1)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ expect(ends(t)[0]).toEqual({ operationId: 'buddy-session-end-agent-idle', command: { type: 'buddy.sessionEnd', conversationId: chat, thread: 'root-1', reason: 'idle' } })+ // The backend's own id for the person's chat (backend buddies.ts buddyChatId).+ expect(chat).toBe(createHash('sha256').update(JSON.stringify(['buddy', 'proj', 'peer', 'g'])).digest('hex').slice(0, 24))+ for (let i = 0; i < 3; i++) await t.poll(60_000)+ expect(ends(t)).toHaveLength(1)+ })++ it('never ends one still working: a screen that keeps changing keeps it, however long the question takes', async () => {+ let clock = 0+ progress = vi.spyOn(TerminalHost.prototype, 'progressOf').mockImplementation(() => ({ harness: clock }))+ const t = lifeFixture([sessionRow()])+ t.live(true)+ for (let i = 0; i < 120; i++) { clock += 60_000; await t.poll(60_000) }+ expect(ends(t)).toEqual([])+ // Its screen stops changing: idle 30 minutes later, not before.+ const still = clock+ progress.mockImplementation(() => ({ harness: still }))+ await awake(t, BUDDY_SESSION_IDLE_MS - 1)+ expect(ends(t)).toEqual([])+ await t.poll(1)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ })++ it('never ends one a delivery waits for', async () => {+ const t = lifeFixture([sessionRow()])+ t.live(true)+ const backendOf = t.core.account.backend+ t.core.account.backend = async (method, path, body) => method === 'GET' && path.includes('/agents/agent/deliveries')+ ? { status: 200, body: { data: [{ id: 'waiting', conversationId: chat, status: 'queued' }] } } : backendOf(method, path, body)+ await awake(t, 2 * BUDDY_SESSION_IDLE_MS)+ expect(ends(t)).toEqual([])+ })++ it('ends one whose terminal is gone for a minute as stopped, and never one gone for less', async () => {+ const t = lifeFixture([sessionRow()])+ await t.poll()+ await t.poll(BUDDY_SESSION_GONE_MS - 1)+ expect(ends(t)).toEqual([])+ await t.poll(1)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ expect((ends(t)[0]!.command as Record<string, unknown>).reason).toBe('stopped')+ })++ it('never ends the main Buddy, another machine\'s session or one the backend is already ending', async () => {+ const main = { ...sessionRow(), agent: { ...sessionRow().agent, buddySession: undefined } }+ const other = sessionRow({ agent: { ...sessionRow().agent, id: 'elsewhere', machineId: 'machine-2' } })+ const closing = sessionRow({ closeSession: true, agent: { ...sessionRow().agent, id: 'closing', harnessId: 'closing' } })+ const t = lifeFixture([main, other, closing])+ t.live(true)+ await awake(t, 2 * BUDDY_SESSION_IDLE_MS)+ expect(ends(t)).toEqual([])+ })++ it('asks again with backoff while the backend does not answer, with the same operation', async () => {+ const t = lifeFixture([sessionRow()])+ const backendOf = t.core.account.backend+ let refusals = 2+ t.core.account.backend = async (method, path, body) => (body as any)?.command?.type === 'buddy.sessionEnd' && refusals-- > 0+ ? (t.commands.push(body as Record<string, unknown>), { status: 503, body: { success: false, error: { code: 'BACKEND_UNAVAILABLE', message: 'down' } } })+ : backendOf(method, path, body)+ await t.poll()+ await t.poll(BUDDY_SESSION_GONE_MS)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ await t.poll(4_999)+ expect(ends(t)).toHaveLength(1)+ await t.poll(1)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(2))+ await t.poll(10_000)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(3))+ expect(new Set(ends(t).map(c => c.operationId))).toEqual(new Set(['buddy-session-end-agent-stopped']))+ for (let i = 0; i < 3; i++) await t.poll(60_000)+ expect(ends(t)).toHaveLength(3)+ })++ // Security review 1 of #2345: a Mac asleep over 30 minutes ended a working session as it woke.+ it('never ends a session as its Mac wakes: idle time counts from the wake', async () => {+ progress = vi.spyOn(TerminalHost.prototype, 'progressOf').mockImplementation(() => ({ harness: 0 }))+ const t = lifeFixture([sessionRow()])+ t.live(true)+ await awake(t, 10 * 60_000)+ await t.poll(40 * 60_000)+ expect(ends(t)).toEqual([])+ await awake(t, BUDDY_SESSION_IDLE_MS - 60_000)+ expect(ends(t)).toEqual([])+ await awake(t, 60_000)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ expect(BUDDY_SESSION_SLEEP_GAP_MS).toBeLessThan(BUDDY_SESSION_IDLE_MS)+ })++ // Security review 1 of #2345: once decided, an end was retried even after the session had new work.+ it('drops an end the backend did not take once the session has work again', async () => {+ const t = lifeFixture([sessionRow()])+ t.live(true)+ const backendOf = t.core.account.backend+ let waiting = false+ t.core.account.backend = async (method, path, body) => {+ if ((body as any)?.command?.type === 'buddy.sessionEnd') {+ t.commands.push(body as Record<string, unknown>)+ return { status: 503, body: { success: false, error: { code: 'BACKEND_UNAVAILABLE', message: 'down' } } }+ }+ if (method === 'GET' && path.includes('/agents/agent/deliveries')) return { status: 200, body: { data: waiting ? [{ id: 'new-work', conversationId: chat, status: 'queued' }] : [] } }+ return backendOf(method, path, body)+ }+ await t.poll()+ await awake(t, BUDDY_SESSION_IDLE_MS)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ waiting = true+ await awake(t, 15 * 60_000)+ expect(ends(t)).toHaveLength(1)+ })++ // Security review 1 of #2345: a delivery this host has settled (withheld) kept the session from ever going idle.+ it('ends one idle with only a settled delivery listed', async () => {+ const t = lifeFixture([sessionRow({ leadsConversationId: 'leads' })])+ t.live(true)+ const backendOf = t.core.account.backend+ t.core.account.backend = async (method, path, body) => method === 'GET' && path.includes('/agents/agent/deliveries')+ ? { status: 200, body: { data: [{ id: 'withheld', conversationId: 'leads', status: 'queued' }] } } : backendOf(method, path, body)+ await t.poll()+ await awake(t, BUDDY_SESSION_IDLE_MS + 60_000)+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))+ expect((ends(t)[0]!.command as Record<string, unknown>).reason).toBe('idle')+ })+})+describe('keeping a Swarm Lead alive', () => {// The owner, 2026-10-23: a Lead whose session died (a machine restart, a kill) stalls its whole project until someone// reopens it by hand. Its host reopens it on its own conversation; a crash loop must not spin.@@ -2702,6 +2861,58 @@ describe('closing the sessions the backend ends', () => {expect(t.commands).toHaveLength(1)})+ // Security review 1 of #2345: what a Buddy's person sent it stayed in its Claude Code transcript and paste cache after its+ // session ended. Its own traces go once it is closed; another session's stay, the same paste included only when theirs names it.+ it('removes an ended Buddy session\'s own Claude Code transcript, history and pastes, and nothing of another session', async () => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude')+ const folder = '/work/worktrees/openharness/buddy-session', other = '/work/worktrees/openharness/someone-else'+ const slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')+ try {+ for (const cwd of [folder, other]) { mkdirSync(join(claude, 'projects', slug(cwd)), { recursive: true }); writeFileSync(join(claude, 'projects', slug(cwd), 'x.jsonl'), 'transcript') }+ mkdirSync(join(claude, 'paste-cache'), { recursive: true })+ for (const hash of ['ownpaste', 'theirpaste']) writeFileSync(join(claude, 'paste-cache', `${hash}.txt`), hash)+ writeFileSync(join(claude, 'history.jsonl'), [+ JSON.stringify({ sessionId: 'buddy-sid', project: folder, pastedContents: { 1: { contentHash: 'ownpaste' } } }),+ JSON.stringify({ sessionId: 'other-sid', project: other, pastedContents: { 1: { contentHash: 'theirpaste' } } }),+ ].join('\n') + '\n')+ const t = lifeFixture([ended()], { claudeHome: home })+ t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: 'buddy-sid', engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)+ await t.poll()+ await vi.waitFor(() => expect(t.commands).toHaveLength(1))+ expect(existsSync(join(claude, 'projects', slug(folder)))).toBe(false)+ expect(existsSync(join(claude, 'paste-cache', 'ownpaste.txt'))).toBe(false)+ expect(existsSync(join(claude, 'projects', slug(other), 'x.jsonl'))).toBe(true)+ expect(existsSync(join(claude, 'paste-cache', 'theirpaste.txt'))).toBe(true)+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).not.toContain('buddy-sid')+ expect(readFileSync(join(claude, 'history.jsonl'), 'utf8')).toContain('other-sid')+ } finally { rmSync(home, { recursive: true, force: true }) }+ })++ // Security re-check 2 of #2345: what to scrub was known only in memory, so a host restarted between the close and the scrub+ // left the transcript for good. It is written to the journal before the close, and the restarted host scrubs from there.+ it('still scrubs an ended Buddy session\'s traces when its host restarts between the close and the scrub', async () => {+ const home = realpathSync(mkdtempSync(join(tmpdir(), 'buddy-home-'))), claude = join(home, '.claude')+ const folder = '/work/worktrees/openharness/buddy-session', slug = (cwd: string) => cwd.replace(/[^A-Za-z0-9]/g, '-')+ try {+ mkdirSync(join(claude, 'projects', slug(folder)), { recursive: true })+ writeFileSync(join(claude, 'projects', slug(folder), 'x.jsonl'), 'transcript')+ const t = lifeFixture([ended()], { claudeHome: home })+ t.core.agents.byAgent = vi.fn(() => ({ agentId: 'harness', sessionId: 'buddy-sid', engine: 'claude', cwd: folder, swarmSkill: { role: 'buddy', key: 'k' } }) as never)+ // The first host's close never returns: it stops before the scrub.+ t.closeMember.mockImplementation(() => new Promise(() => {}))+ await t.poll()+ expect(t.saved().scrubs).toEqual({ agent: { agentId: 'agent', sessionId: 'buddy-sid', cwd: folder, engine: 'claude', codexHome: null } })+ t.host.stop()+ // Restarted: the session is no longer registered here, and the close goes through.+ t.core.agents.byAgent = vi.fn(() => undefined as never)+ t.closeMember.mockImplementation(async () => ({ closed: true as const }))+ const again = t.open({ claudeHome: home })+ await again.tick()+ await vi.waitFor(() => expect(existsSync(join(claude, 'projects', slug(folder)))).toBe(false))+ await vi.waitFor(() => expect(t.saved().scrubs).toBeUndefined())+ } finally { rmSync(home, { recursive: true, force: true }) }+ })+// Diego, 10-30: removing an agent or deleting its project left its worktree to the weekly sweep, up to a week later. It goes// once its close is acknowledged, under the stopped worker's own rules (machines.ts removeStoppedWorktree).it('removes the ended session\'s worktree only once its close is acknowledged, and a failed removal is only logged', async () => {diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex fad3b58c8..4b2a1431f 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -16,7 +16,8 @@ import { computerId } from '../lib/daemonState.js'import { noticeReason, WithheldDeliveries } from './withheld.js'import { attentionOf } from './attention.js'import { prepareContribution, prepareTeamContribution } from './contribution.js'-import { hostname } from 'node:os'+import { homedir, hostname } from 'node:os'+import { scrubClaudeSession, type PurgeTarget } from './inCore/teamPurge.js'import { replacementObservations } from './replacements.js'import { TerminalHost } from './terminal.js'import { LimitResume } from './limitResume.js'@@ -119,7 +120,9 @@ interface Entry {stage: 'prepared' | 'submitting' | 'delivered' | 'uncertain'receipt?: string}-interface Journal { version: 1; machineId: string; entries: Record<string, Entry> }+/** `scrubs`: the Claude Code traces of ended Buddy sessions still to remove, by agent id, written before their close, so a host+ * restarted between the close and the scrub still removes them (security re-check 2 of #2345). Older hosts drop it. */+interface Journal { version: 1; machineId: string; entries: Record<string, Entry>; scrubs?: Record<string, PurgeTarget> }/** `skillMode` is the agent's project's skills; a row without it (an older backend, a project from before modes) is orchestration. */interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string; releaseId?: string }; skillMode?: unknown; lead?: unknown; role?: unknownleadsConversationId?: unknown }@@ -136,6 +139,8 @@ export interface SuperTabHostOptions {agentCommand?: (core: CoreApi, machineId: string) => Promise<string>/** The Swarm start this machine made of a harness (superTabs/reservations.ts), or null. */startReceipt?: (harnessId: string) => string | null+ /** The home whose Claude Code data an ended Buddy session's own traces are removed from; this user's, unless a spec says. */+ claudeHome?: string/** The machine's host form and Swarm reads, shared with the service's other readers (superTabs/service.ts). */sources?: SwarmSources/** What the contributed-machine executor reaches the local daemon with (superTabs/machines.ts), for a spec. */@@ -205,6 +210,18 @@ const endingKey = (target: HostAgent) => `${target.tabId}:${target.agent.id}:${t* (backend commands.ts, `stableId(machineId, harnessId)`): this host's own record of which agent each of its sessions is. */const agentIdOf = (machineId: string, harnessId: string) =>createHash('sha256').update(JSON.stringify([machineId, harnessId])).digest('hex').slice(0, 24)+/** A person's Buddy chat in a project (backend buddies.ts `buddyChatId`, `stableId('buddy', projectId, personId, generation)`). */+export const buddyChatIdOf = (projectId: string, personId: string, generation: string) =>+ createHash('sha256').update(JSON.stringify(['buddy', projectId, personId, generation])).digest('hex').slice(0, 24)+/** A Buddy's thread session (spec 2026-10-30-buddy-thread-sessions) ends after this long with its screen unchanged, nothing+ * waiting for it and nothing delivered to it: a session still working on a long question changes its screen. */+export const BUDDY_SESSION_IDLE_MS = 30 * 60_000+/** How long a thread session's terminal may be missing before it counts as stopped, so a slow read is never taken for one. */+export const BUDDY_SESSION_GONE_MS = 60_000+/** A gap this long between two looks at a thread session means this machine slept (the host looks every few seconds): its+ * idle time counts from the wake, so a Mac that slept through 30 minutes never ends a working session as it wakes (security+ * review 1 of #2345). */+export const BUDDY_SESSION_SLEEP_GAP_MS = 2 * 60_000const writeJournal = (file: string, journal: Journal) => {mkdirSync(dirname(file), { recursive: true, mode: 0o700 })const temporary = `${file}.next`@@ -262,6 +279,10 @@ export class SuperTabHost {/** Per agent's list, when it was last read, what it held, and whether any of it is still in this host's hands: input in* flight needs a fresh read each second for its 2.5 s lease (accept), so only a list with nothing to do may wait. */private readonly lists = new Map<string, { readAt: number; ids: string[]; busy: boolean }>()+ /** Each of this machine's thread sessions, by `tabId:agentId`: when it last did anything, since when its terminal is gone,+ * and its end once asked of the backend. */+ private readonly threadSessions = new Map<string, { activeAt: number; seenAt: number; missingSince?: number; ending?: 'idle' | 'stopped'+ ended?: true; running: boolean; failures: number; retryAt: number }>()private stopped = falseprivate running: Promise<void> | null = nullprivate stopsRunning: Promise<void> | null = null@@ -274,6 +295,7 @@ export class SuperTabHost {private receiptCursor = 0private readonly agentCommand: (core: CoreApi, machineId: string) => Promise<string>private readonly startReceipt: (harnessId: string) => string | null+ private readonly claudeHome: string/** Asked once, on the first delivery: the answer cannot change while this daemon runs (superTabs/shortCommand.ts). */private prefix: Promise<string> | null = nullprivate configurationsRunning: Promise<void> | null = null@@ -309,7 +331,7 @@ export class SuperTabHost {private readonly keepAlives = new Map<string, { running: boolean; failures: number; retryAt: number; reason?: string }>()/** Per session the backend ends: a close or acknowledgement in progress, how far it got, and when the next try may run. */private readonly endings = new Map<string, { running: boolean; closed: boolean; acked: boolean; failures: number; retryAt: number- forgotten?: boolean; unforgotten?: string }>()+ forgotten?: boolean; unforgotten?: string; scrub?: PurgeTarget | null; scrubbed?: true }>()/** Deliveries withheld from an agent that leads nothing, each said once. */private readonly unreadable = new Set<string>()/** The machine's host form and Swarm reads: the tick, stops, releases and skill notices read Swarms only through them. */@@ -332,6 +354,7 @@ export class SuperTabHost {this.prepareTeam = options.prepareTeam ?? ((core, input) => prepareTeamContribution(core, input))this.agentCommand = options.agentCommand ?? defaultAgentCommandthis.startReceipt = options.startReceipt ?? (() => null)+ this.claudeHome = options.claudeHome ?? homedir()this.now = options.now ?? Date.nowthis.write = options.write ?? writeJournalthis.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))@@ -360,6 +383,15 @@ export class SuperTabHost {}this.journal.entries[id] = entry}+ // Only a target this host could have written: its own agent id, a Claude Code session in a folder. Another is dropped,+ // never trusted, so a hand-edited journal cannot point the scrub elsewhere than a session folder's own traces.+ for (const [agentId, value] of Object.entries(object(saved.scrubs))) {+ const t = object(value)+ if (agentId === t.agentId && identifier(agentId) && t.engine === 'claude' && typeof t.cwd === 'string' && t.cwd.startsWith('/')+ && (t.sessionId === null || typeof t.sessionId === 'string') && t.codexHome === null) {+ (this.journal.scrubs ??= {})[agentId] = { agentId, sessionId: t.sessionId as string | null, cwd: t.cwd, engine: 'claude', codexHome: null }+ }+ }}this.persist()this.stopHearing = core.turns.onDelivery(event => this.heard(event))@@ -854,6 +886,7 @@ export class SuperTabHost {}}}+ this.watchThreadSessions(data)await this.leases()// Off the poll, so the backend calls of a notice never delay the next lease renewal. Owed at most once per text release.this.skillsRunning ??= (async () => { for (const target of running) await this.refreshSkill(target) })()@@ -885,6 +918,63 @@ export class SuperTabHost {}, error => failed(error instanceof Error ? error.message : String(error))).finally(() => { state.running = false })}+ /** A Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions) end on their own, so none is left running on its+ * person's machine: idle for BUDDY_SESSION_IDLE_MS, with no screen change, nothing waiting for it and nothing delivered+ * in that time, or its terminal gone for BUDDY_SESSION_GONE_MS. This host asks the backend as the machine's owner, who is+ * the Buddy's person (a Buddy runs only on its person's own machine); the backend then ends it, and this host closes it+ * as any session the backend ends (endSession). Asked once, retried with backoff while the backend does not answer. */+ private watchThreadSessions(data: unknown[]): void {+ const present = new Set<string>()+ for (const item of data) {+ const row = object(item), agent = object(row.agent), session = object(agent.buddySession), buddyOf = object(agent.buddyOf)+ if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continue+ if (row.closeSession === true || row.stopRequested === true || !identifier(session.thread)) continue+ if (!identifier(buddyOf.personId) || !identifier(buddyOf.generation)) continue+ const key = `${row.tabId}:${agent.id}`, now = this.now()+ present.add(key)+ let state = this.threadSessions.get(key)+ if (!state) this.threadSessions.set(key, state = { activeAt: now, seenAt: now, running: false, failures: 0, retryAt: 0 })+ // Asleep: idle time counts from the wake.+ if (now - state.seenAt >= BUDDY_SESSION_SLEEP_GAP_MS) state.activeAt = now+ state.seenAt = now+ // A delivery still in this host's hands is work, and so is a screen that changed. One settled (withheld, or waiting on a+ // person as uncertain) is not: it would keep the session from ever going idle (security review 1 of #2345).+ const list = this.lists.get(`list:${row.tabId}:${agent.id}`)+ if (list?.busy) state.activeAt = now+ const shown = this.terminal.progressOf([agent.harnessId])[agent.harnessId]+ if (typeof shown === 'number' && shown > state.activeAt) state.activeAt = shown+ const live = !!this.core.agents.byAgent(agent.harnessId) && this.core.agents.terminalAvailable(agent.harnessId)+ if (live) delete state.missingSince+ else state.missingSince ??= now+ // Idle only on a list read this pass or lately with nothing unsettled: one never read says nothing of what waits.+ const reason = !live ? (now - state.missingSince! >= BUDDY_SESSION_GONE_MS ? 'stopped' : null)+ : list && !list.busy && now - state.activeAt >= BUDDY_SESSION_IDLE_MS ? 'idle' : null+ // Judged again each pass: an end not yet taken is dropped once the session works again, so a retry never ends a session+ // that has new work (security review 1 of #2345).+ if (state.ended) continue+ if (!reason) {+ if (!state.running) { delete state.ending; state.failures = 0; state.retryAt = 0 }+ continue+ }+ if (state.ending !== reason) { state.ending = reason; state.failures = 0; state.retryAt = 0 }+ if (state.running || now < state.retryAt) continue+ const projectId = identifier(agent.projectId) ? agent.projectId : 'lead'+ const conversationId = buddyChatIdOf(projectId, buddyOf.personId, buddyOf.generation)+ state.running = true+ const ending = reason, short = String(agent.harnessId).slice(0, 8)+ // One id per session and reason: a retry is the same request, and a changed reason never reuses an id for another.+ void backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/commands`, { operationId: `buddy-session-end-${agent.id}-${ending}`,+ command: { type: 'buddy.sessionEnd', conversationId, thread: session.thread, reason: ending } })+ .then(() => { state.ended = true; this.log(`Ended thread session ${short} in Swarm ${row.tabId}: ${ending}.`) })+ .catch(error => {+ state.retryAt = this.now() + Math.min(END_RETRY_MAX_MS, END_RETRY_MS * 2 ** state.failures++)+ this.log(`Could not end thread session ${short} in Swarm ${row.tabId} (${ending}): ${error instanceof Error ? error.message : String(error)}`)+ })+ .finally(() => { state.running = false })+ }+ for (const key of this.threadSessions.keys()) if (!present.has(key)) this.threadSessions.delete(key)+ }+/** Deleting a project left its Lead's session running, and removing an agent left its session behind (owner, 2026-10-23:* no zombie agents). The backend marks the session; this closes it, keeping its conversation, and says so once. */private endSession(target: HostAgent): void {@@ -910,6 +1000,19 @@ export class SuperTabHost {}const close = this.core.agents.closeMemberif (!close) return+ // A Buddy's own Claude Code traces, known while its session is still registered here (security review 1 of #2345): what its+ // person sent it, kept in its transcript and Claude Code's paste cache, goes with its session. Its folder is its own+ // worktree, so its transcripts and history lines are its alone; a paste goes only when one of its own history lines names it+ // (teamPurge.ts scrubClaudeSession, never a sweep by pattern).+ // Recorded before the close (security re-check 2 of #2345): after a restart its session is no longer registered here, and+ // only the journal still knows what to remove.+ if (state.scrub === undefined) {+ const recorded = this.journal.scrubs?.[agent.id]+ const session = recorded ? undefined : this.core.agents.byAgent(agent.harnessId)+ state.scrub = recorded ?? (session?.swarmSkill?.role === 'buddy' && session.engine === 'claude' && typeof session.cwd === 'string'+ ? { agentId: agent.id, sessionId: session.sessionId ?? null, cwd: session.cwd, engine: 'claude', codexHome: null } : null)+ if (state.scrub && !recorded) { (this.journal.scrubs ??= {})[agent.id] = state.scrub; this.persist() }+ }if (state.running || state.acked || this.now() < state.retryAt) returnstate.running = truevoid (async () => {@@ -923,6 +1026,15 @@ export class SuperTabHost {if (!result.closed) throw new Error(`Could not close a session the Swarm ended (${result.error ?? 'unknown'}${result.detail ? `: ${result.detail}` : ''}).`)state.closed = true}+ if (state.scrub && !state.scrubbed) {+ await scrubClaudeSession(this.claudeHome, state.scrub)+ state.scrubbed = true+ if (this.journal.scrubs?.[agent.id]) {+ delete this.journal.scrubs[agent.id]+ if (!Object.keys(this.journal.scrubs).length) delete this.journal.scrubs+ this.persist()+ }+ }if (this.stopped || !state.forgotten) returnawait backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `session-closed-${agent.id}-${agent.harnessId}`,command: { type: 'agent.sessionClosed', agentId: agent.id, harnessId: agent.harnessId } })@@ -1284,7 +1396,13 @@ export class SuperTabHost {&& typeof owner.generation === 'string' && owner.generation === author.membershipGeneration&& chat.kind === 'buddy' && chat.buddyOwnerId === author.id && chat.archived !== true&& Array.isArray(chat.agentIds) && chat.agentIds.includes(entry.agentId) && chat.projectId === agent.projectId- return own ? { onTheirMachine: agent!.machineOwnerId === author.id } : null+ // A thread session's person speaks to it only in its own thread: a message anywhere else grants it nothing, however it+ // came (security review 1 of #2345).+ // A session whose thread cannot be read fails closed: it is still a session, so nothing from anywhere grants it (re-check 2).+ const isSession = agent?.buddySession !== undefined && agent?.buddySession !== null+ const session = object(agent?.buddySession)+ const inThread = !isSession || (identifier(session.thread) && (message.id === session.thread || message.thread === session.thread))+ return own && inThread ? { onTheirMachine: agent!.machineOwnerId === author.id } : null}/** The message a reply answers, quoted into the delivery: agents skipped the command that reads it, and a Lead took Ken'sdiff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsindex 5fb278f16..abe1e5335 100644--- a/cli/src/superTabs/machines.spec.ts+++ b/cli/src/superTabs/machines.spec.ts@@ -244,12 +244,12 @@ describe('contributed machine executor', () => {await f.machine.tick()expect((f.start.mock.calls as unknown[][]).map(call => call[0])).toEqual([{ tabId: 'tab', startId: 'lead-start', hostDispatch: true }])})- it('says in its reading that it starts Product Managers, to a backend that asks, and to no other', async () => {+ it('says in its reading that it starts Product Managers and a Buddy\'s thread sessions, to a backend that asks, and to no other', async () => {const f = fixture()Object.assign(f.pool, { capabilitiesWanted: true })await f.machine.tick()const posted = (g: typeof f) => g.backend.mock.calls.filter(c => c[1] === 'POST').map(c => c[3] as Record<string, unknown>)- expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart'] })+ expect(posted(f)[0]).toMatchObject({ capabilities: ['leadStart', 'buddySessions'] })// A backend from before them does not ask, and would refuse the field.const older = fixture()await older.machine.tick()diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 86ad4fd82..6f7c29e20 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -155,8 +155,9 @@ const CLEANING_WAIT = 'Waiting for this machine to finish cleaning up this Swarm/** A host's starts: its workers', and its Buddies' and Product Managers', which the backend lists apart so that a host from* before them never launches one as a worker. */const startsOf = (row: Record<string, unknown>) => [...list(row.starts), ...list(row.buddyStarts), ...list(row.leadStarts)]-/** What this host launches beyond workers, said in its reading (backend leadStart.ts): a project's Product Manager. */-const CAPABILITIES = ['leadStart']+/** What this host launches beyond workers, said in its reading (backend leadStart.ts): a project's Product Manager, and a+ * Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions), which the backend offers only on a host that says so. */+const CAPABILITIES = ['leadStart', 'buddySessions']/** The backend's answer that this machine may no longer act in the Swarm: signed out, its contribution revoked or its host* unavailable (backend store.ts observeMachine), or the Swarm gone. */const lostAccess = (error: unknown) => error instanceof SuperTabHostError && [401, 403, 404].includes(error.status)diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex 4405353bd..b6f14bfac 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -1251,6 +1251,21 @@ describe('a Buddy\'s status', () => {expect(t.call.mock.calls.slice(calls).filter(([, path]) => String(path).includes('/messages?'))).toEqual([])})+ it('reads one thread, with the main-chat messages a thread session started from, and refuses a thread that is not an id', async () => {+ const t = buddySetup()+ vi.mocked(t.core.account.backend).mockImplementation(async (_method: string, path: string) => ({ status: 200, body: { success: true, data:+ path.includes('/messages?') ? { messages: [{ id: 'root-1', thread: 'root-1' }], next: null, context: [{ id: 'older', text: 'earlier' }] }+ : swarmData(t.agent, path) } }))+ expect(await t.ask({ action: 'messages', tabId: 'tab', agentId: t.agentId, conversationId: 'chat', thread: 'root-1' }, owner))+ .toMatchObject({ ok: true, value: { context: [{ id: 'older', text: 'earlier' }] } })+ expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/conversations/chat/messages?asAgentId=${t.agentId}&thread=root-1`, undefined)+ await t.ask({ action: 'messages', tabId: 'tab', agentId: t.agentId, conversationId: 'chat', thread: 'root-1', before: 40, beforeId: 'm-1' }, owner)+ expect(t.call).toHaveBeenCalledWith('GET', `/api/super-tabs/tab/conversations/chat/messages?asAgentId=${t.agentId}&before=40&beforeId=m-1&thread=root-1`, undefined)+ const calls = t.call.mock.calls.length+ expect(await t.ask({ action: 'messages', tabId: 'tab', agentId: t.agentId, conversationId: 'chat', thread: 'a&b=c' }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })+ expect(t.call.mock.calls.slice(calls).filter(([, path]) => String(path).includes('/messages?'))).toEqual([])+ })+it('leaves every other agent\'s status as it was', async () => {const t = setup()const value = object(object(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).value)diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex abd30f383..ec9bbc77b 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -52,7 +52,7 @@ const HELP = {leads: 'The Leads conversation (leadsConversationId in a Lead\'s status) is one conversation for the whole Swarm, outside every project. Only Leads and people post there, and only Leads among agents receive it. Before assigning, look at otherProjectsWork; if your task touches the same code, say so there and agree an order first, then tell your own project. The Swarm posts there by itself when two projects\' active tasks own the same code.',// Help without --tab cannot tell who asks, so it does not list a Lead's own options; this tells a Lead where they are.leadOptions: 'Leads: run help with --tab ID for options only a Lead has.',- messages: 'messages GROUP: read recent messages in a conversation, thread replies included: each names its thread, the root message it answers there. A post with --reply-to lands in that message\'s thread.',+ messages: 'messages GROUP: read recent messages in a conversation, thread replies included: each names its thread, the root message it answers there. A post with --reply-to lands in that message\'s thread. messages GROUP --thread ROOT reads one thread, its root and replies; a Buddy\'s thread session also gets there, as context, the main-chat messages it started from.',message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',decisions: 'decisions [--answered]: the decisions you asked of people, still open, or with --answered those answered (each with its choice and note). A Lead also sees those asked in its project. When your work needs a person to decide, ask through work.status needs_human with ask: the question as its result, 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until a notice in that conversation says it was answered; then read the answer here with --answered. The notice carries none of the answer. A decision is not a private channel: to tell one person something directly, a Lead sends person.tell; it lands in their Buddy chat, which the Lead cannot read. Project members watching the Lead\'s terminal see what it sends: put nothing there you would not say in the project chat.',costs: 'costs [--days N]: what the attempts routed in the last N days (7 unless set, at most 90) cost and how they went, per engine, model, effort and kind of job: attempts, first-review pass rate, shipped, median minutes to ship, tokens, API-equivalent cost and actual per-token spend in US dollars, and cost per shipped change, with the prices and their sources; models has the same per engine and model alone (a grid model by its own name), and stepUps counts the attempts that stepped up from a cheaper model. Only attempts routed since cost records began, in the groups you may read.',@@ -581,7 +581,9 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =const paged = payload.before !== undefined || payload.beforeId !== undefinedif (paged && !(Number.isSafeInteger(payload.before) && Number(payload.before) >= 0 && identifier(payload.beforeId))) return { error: 'INVALID_REQUEST' }const before = paged ? `&before=${payload.before}&beforeId=${payload.beforeId}` : ''- const page = await backend(core, 'GET', `${path}/conversations/${encodeURIComponent(String(payload.conversationId))}/messages?${identity}${before}`)+ if (payload.thread !== undefined && !identifier(payload.thread)) return { error: 'INVALID_REQUEST' }+ const thread = payload.thread !== undefined ? `&thread=${payload.thread}` : ''+ const page = await backend(core, 'GET', `${path}/conversations/${encodeURIComponent(String(payload.conversationId))}/messages?${identity}${before}${thread}`)return { ok: true, value: markAnswered(page, [], agentId) }}if (payload.action === 'message' && identifier(payload.conversationId) && identifier(payload.messageId)) {diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex d365c652e..b60e283d9 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest'import { join } from 'node:path'import { existsSync } from 'node:fs'import { homedir } from 'node:os'-import { inspectCapacity, MODEL_REPORT_WAIT_MS, startAgent } from './start.js'+import { BUDDY_SESSION_ENGINE, inspectCapacity, MODEL_REPORT_WAIT_MS, startAgent } from './start.js'import { buildEngineCommandArgv } from '../lib/engineLaunch.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 }))@@ -271,6 +271,46 @@ it.each(['claude', 'codex'])('starts a %s Buddy with the built-in swarm-buddy skexpect(payload.prompt).not.toContain('swarm-dev')})+it.each(['claude'])('starts a %s thread session as a Buddy in every way, told its thread and to answer only there, with no message text', async engine => {+ const plain = fixture()+ plain.start.request = { ...plain.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' } } as typeof plain.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-main', request: plain.start.request }, plain.scoped, where, plain.open)+ const main = plain.request.mock.calls.find(call => call[0] === 'agent_create')![1]!+ const f = fixture()+ f.start.request = { ...f.start.request, engine, buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'root-1', from: 42 } } as typeof f.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-main', request: f.start.request }, f.scoped, where, f.open)+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!+ const chat = f.start.request.conversationId+ // Everything but the prompt is the main Buddy's: its role, permissions, worktree and skill.+ const { prompt, ...rest } = payload, { prompt: mainPrompt, ...mainRest } = main+ expect(rest).toEqual(mainRest)+ expect(prompt).not.toBe(mainPrompt)+ expect(prompt).toContain('Use the built-in swarm-buddy skill for this session.')+ expect(prompt).toContain(`harness super-tab --tab tab messages ${chat} --thread root-1`)+ expect(prompt).toContain(`post ${chat} 'your message' UNIQUE_OPERATION_ID --reply-to MESSAGE_ID`)+ expect(prompt).toContain('only in this thread')+ expect(prompt).not.toContain('greet')+ expect(prompt).not.toContain('assign')+})++it('refuses a Codex thread session before anything launches: Codex runs without the Buddy guard hook (security review 1 of #2345)', async () => {+ const f = fixture()+ f.start.request = { ...f.start.request, engine: 'codex', buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'root-1', from: 1 } } as typeof f.start.request+ const result = await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-codex-session', request: f.start.request }, f.scoped, where, f.open)+ expect(result).toMatchObject({ error: 'START_FAILED', detail: BUDDY_SESSION_ENGINE })+ expect(f.request.mock.calls.some(call => call[0] === 'agent_create')).toBe(false)+ expect(f.scoped).toHaveBeenCalledWith(expect.objectContaining({ command: expect.objectContaining({ type: 'agent.startFailed', error: BUDDY_SESSION_ENGINE }) }))+})++it('starts a plain Buddy for a thread session whose thread is not an id', async () => {+ const f = fixture()+ f.start.request = { ...f.start.request, buddyOf: { personId: 'peer', generation: 'g' }, buddySession: { thread: 'x; rm -rf ~', from: 1 } } as typeof f.start.request+ await startAgent({ action: 'start', tabId: 'tab', operationId: 'buddy-odd', request: f.start.request }, f.scoped, where, f.open)+ const payload = f.request.mock.calls.find(call => call[0] === 'agent_create')![1]!+ expect(payload.prompt).not.toContain('rm -rf')+ expect(payload.prompt).not.toContain('--thread')+})+it('starts no Buddy with full permissions or the GitHub App\'s token: Claude refusing what its guard does not allow, Codex in its read-only sandbox asking', async () => {for (const [engine, mode, bypass] of [['claude', 'buddy', false], ['codex', 'readOnlyAsk', false]] as const) {const f = fixture()diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 8639a09cd..ef097460b 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -51,6 +51,23 @@ function leadPrompt(tabId: string, chat: string, mode: SwarmSkillMode | null): sfunction buddyPrompt(tabId: string, chat: string, mode: SwarmSkillMode | null): string {return `You are a person's Buddy in a shared Super Tab. ${mode ? `${swarmSkillUse('buddy', mode)} ` : ''}Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Your chat with your owner is conversation ${chat}: read it with harness super-tab --tab ${tabId} messages ${chat}, and reply there with harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID. Then greet your owner there and ask what they have in mind. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`}+/** A thread session's start note (docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md): the same Buddy, for one+ * thread of its owner's chat. Ids only, never a message's text: a start record is listed in the Lead's status. */+function buddySessionPrompt(tabId: string, chat: string, thread: string, mode: SwarmSkillMode | null): string {+ return `You are a person's Buddy in a shared Super Tab, in a session of your own for one thread of your owner's chat. ${mode ? `${swarmSkillUse('buddy', mode)} ` : ''}Run harness super-tab --tab ${tabId} status until this harness appears in the roster. Your thread is the one rooted at message ${thread} in conversation ${chat}. Read it, with the main-chat messages it started from, with harness super-tab --tab ${tabId} messages ${chat} --thread ${thread}. Answer your owner only in this thread: harness super-tab --tab ${tabId} post ${chat} 'your message' UNIQUE_OPERATION_ID --reply-to MESSAGE_ID, naming a message in this thread. Your owner's newest message in the thread is the one to answer first. Your Buddy's other rules are unchanged. If sandbox restrictions block this local command, request permission to run it outside the sandbox.`+}++/** Why a thread session that is not Claude Code's never starts. */+export const BUDDY_SESSION_ENGINE = 'A thread session runs only with Claude Code, under its Buddy guard.'++/** The thread a Buddy start's session is for, if it is one (backend `AgentStartRequest.buddySession`). */+export function buddySessionThread(request: Json): string | null {+ const session = request.buddySession+ if (!session || typeof session !== 'object') return null+ const thread = (session as Json).thread+ return typeof thread === 'string' && /^[A-Za-z0-9_-]{1,160}$/.test(thread) ? thread : null+}+export async function inspectCapacity(target: Daemon, request: Json) {const wanted = object(request.requirements)const requirements: Requirements = {@@ -344,6 +361,12 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:return { error: 'START_FAILED', startId, detail }}}+ // A Buddy thread session runs only under Claude Code, whose Buddy guard hook holds it: a Codex session would run without+ // that hook (security review 1 of #2345). The backend refuses one too; this refuses it here before anything launches.+ if (request.buddySession !== undefined && request.engine !== 'claude') {+ requireSuccess(await scoped({ action: 'command', operationId: `refused-${startId}`, command: { type: 'agent.startFailed', startId, error: BUDDY_SESSION_ENGINE } }))+ return { error: 'START_FAILED', startId, detail: BUDDY_SESSION_ENGINE }+ }const resources = await inspectCapacity(target, request)if (resources.capacity.error === 'GUEST_NOT_ALLOWED') return {error: 'CONTRIBUTION_REQUIRED', startId,@@ -369,6 +392,8 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:const skilled = ['claude', 'codex'].includes(String(request.engine)), reviewer = request.role === 'reviewer'// A Buddy's start names its owner (backend buddies.ts): it brainstorms in their chat and is never assigned work.const buddy = !!request.buddyOf && typeof request.buddyOf === 'object'+ // A thread session (spec 2026-10-30-buddy-thread-sessions): launched as a Buddy in every way, its prompt aside.+ const session = buddy ? buddySessionThread(request) : null// A project's Product Manager (backend leadStart.ts): the Lead of its project's conversation once it runs.const lead = !buddy && !!request.leadFor && typeof request.leadFor === 'object'// A contributed machine's host cannot read the tab as a Lead does: it asked the backend whose work this is when it@@ -388,7 +413,8 @@ async function startOnce(input: Json, scoped: ScopedRequest, where: Where, open:...(asks ? { permissionMode: asks } : permissionModeFlags(request.engine as AgentEngine, 'full') ? { permissionMode: 'full' } : {}),...(mode ? { swarmRole: role, swarmSkillMode: mode } : {}),...(github ? { swarmGitHub: true } : {}),- prompt: buddy ? buddyPrompt(String(input.tabId), String(request.conversationId), mode)+ prompt: buddy ? (session ? buddySessionPrompt(String(input.tabId), String(request.conversationId), session, mode)+ : buddyPrompt(String(input.tabId), String(request.conversationId), mode)): lead ? `${leadPrompt(String(input.tabId), String(request.conversationId), mode)}${github ? ` ${githubPromptLine(github.requester)}` : ''}` : `You are joining a shared Super Tab${reviewer ? ' as a Reviewer' : ''}. ${mode ? `${swarmSkillUse(role, mode)} ` : ''}Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. ${reviewer? `Do not review yet. You review work in conversation ${request.conversationId} when it is ready for review.`: `Do not begin project work yet. Your lead will assign work in conversation ${request.conversationId}.`} Reply in that conversation using harness super-tab --tab ${input.tabId} post ${request.conversationId} 'your message' UNIQUE_OPERATION_ID. Run harness super-tab help for commands. If sandbox restrictions block this local command, request permission to run it outside the sandbox.${github ? ` ${githubPromptLine(github.requester)}` : ''}`,diff --git a/desktop/lib/super_tabs/buddy_sessions.dart b/desktop/lib/super_tabs/buddy_sessions.dartnew file mode 100644index 000000000..2e91a07f0--- /dev/null+++ b/desktop/lib/super_tabs/buddy_sessions.dart@@ -0,0 +1,207 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/appearance_prefs_store.dart';+import '../state/app_state.dart';+import '../state/harness_activity.dart';+import '../terminal/terminal_theme.dart';+import '../terminal/terminal_theme_store.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/harness_activity_mark.dart';+import 'controller.dart';+import 'message_row.dart' show SuperTabLink;+import 'model.dart';++// Buddy thread sessions (spec docs/superpowers/specs/2026-10-30-buddy-thread-+// sessions-design.md): a thread of the reader's own Buddy chat may have its own+// Buddy session, answering there while the Buddy keeps answering the chat. What+// shows here is only what changes: which session answers a thread, whether it+// is working, and a quiet way to end it. Status uses the one activity+// vocabulary (HarnessActivity), never a mark of its own.++/// What a session is doing, as the activity vocabulary says it.+typedef SuperTabSessionActivity = HarnessActivity Function(+ SuperTabBuddySession session,+);++/// A session's activity as this computer reads it: starting until its agent+/// joins, offline while its machine reports it gone, else what this computer+/// sees of its terminal, or "Status unavailable" when it sees nothing.+HarnessActivity superTabSessionActivity(+ SuperTabController c,+ AppNotifier? app,+ SuperTabBuddySession session,+) {+ final agent = c.sessionAgent(session);+ if (agent == null) return HarnessActivity.starting;+ if (agent.downSince != null) return HarnessActivity.offline;+ if (app == null) return HarnessActivity.unknown;+ return harnessActivity(app, agent.machineId, agent.harnessId) ??+ HarnessActivity.unknown;+}++/// The words beside a session's mark; offline names its machine ([machine],+/// as people read it) when known.+String superTabSessionWords(HarnessActivity activity, {String? machine}) =>+ switch (activity) {+ HarnessActivity.starting => 'Starting…',+ HarnessActivity.offline =>+ machine != null ? '$machine is offline' : 'Its computer is offline',+ HarnessActivity.idle => 'Idle',+ _ => activity.label,+ };++/// Why a session ended, as its thread says it.+String superTabSessionEndedWords(String? reason) => switch (reason) {+ 'idle' => 'Session ended: idle for 30 minutes',+ 'ended' => 'Session ended: you ended it',+ 'stopped' => 'Session ended: it stopped unexpectedly',+ 'failed' => 'Session ended: it couldn\'t start',+ 'removed' => 'Session ended: its Buddy was removed or replaced',+ 'maintenance' => 'Session ended: Harness was updated',+ _ => 'Session ended',+};++Widget _mark(HarnessActivity activity) => ActivityMark(+ activity: activity,+ tooltip: false,+ showIdle: true,+ color: activityColor(+ activity,+ terminalThemeFor(grid.AppTheme.surfacePalette, terminalThemeStore.value),+ color: appearancePrefsStore.value.prompt.color,+ ),+);++/// The line under the thread pane's header: which session answers the+/// thread and what it is doing, with End session as a quiet text action; or+/// why its last session ended. Nothing for a thread with neither.+class SuperTabThreadSessionLine extends StatefulWidget {+ const SuperTabThreadSessionLine({+ super.key,+ required this.controller,+ required this.root,+ required this.activityOf,+ });++ final SuperTabController controller;+ final String root;+ final SuperTabSessionActivity activityOf;++ @override+ State<SuperTabThreadSessionLine> createState() =>+ _SuperTabThreadSessionLineState();+}++class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {+ // The thread an End session is under way for: its answer changes nothing+ // once another thread is shown.+ String? _ending;++ Future<void> _end() async {+ final root = widget.root;+ if (_ending == root) return;+ setState(() => _ending = root);+ await widget.controller.endThreadSession(root);+ if (!mounted || _ending != root) return;+ setState(() => _ending = null);+ }++ @override+ void didUpdateWidget(SuperTabThreadSessionLine old) {+ super.didUpdateWidget(old);+ if (old.root != widget.root) _ending = null;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final c = widget.controller;+ final session = c.threadSession(widget.root);+ final Widget line;+ if (session != null) {+ final activity = widget.activityOf(session);+ final machineId = c.sessionAgent(session)?.machineId;+ final machine = machineId == null+ ? null+ : c.sessionMachineName(machineId);+ final words =+ 'Own session · ${superTabSessionWords(activity, machine: machine)}';+ line = Row(+ children: [+ _mark(activity),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: Text(+ words,+ key: const ValueKey('super-thread-session-state'),+ style: DesktopChrome.control(),+ overflow: TextOverflow.ellipsis,+ ),+ ),+ if (c.canWrite)+ SuperTabLink(+ key: const ValueKey('super-thread-session-end'),+ label: _ending == widget.root ? 'Ending session' : 'End session',+ // Disabled while its end is on its way: pointer, keyboard and+ // screen readers alike.+ onTap: _ending == widget.root ? null : () => unawaited(_end()),+ child: Text(+ _ending == widget.root ? 'Ending…' : 'End session',+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ ),+ ],+ );+ } else if (c.threadSessionEnded(widget.root) case final ended?) {+ line = Text(+ superTabSessionEndedWords(ended.sessionEndReason),+ key: const ValueKey('super-thread-session-ended'),+ style: DesktopChrome.control(color: DesktopChrome.muted),+ );+ } else {+ return const SizedBox.shrink();+ }+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: line,+ ),+ Divider(height: 1, thickness: 1, color: DesktopChrome.rim),+ ],+ );+ }+}++/// " · ⠋ Own session" at the end of a thread's line in the chat, while the+/// thread has a session of its own.+class SuperTabThreadSessionMark extends StatelessWidget {+ const SuperTabThreadSessionMark({super.key, required this.activity});++ final HarnessActivity activity;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ return Semantics(+ label: 'Own session, ${superTabSessionWords(activity)}',+ excludeSemantics: true,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(' · ', style: DesktopChrome.metadata()),+ _mark(activity),+ const SizedBox(width: grid.AppDesktop.menuInset),+ Text('Own session', style: DesktopChrome.metadata()),+ ],+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 64b585ead..222b32c6a 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -13,6 +13,7 @@ import '../state/harness_attachments.dart';import 'attachment_upload.dart';import 'avatar_upload.dart';import 'message_link.dart';+import 'identity.dart' show superTabMachineName;import 'model.dart';import 'buddy_chat.dart';import 'catch_up.dart';@@ -1361,6 +1362,7 @@ class SuperTabController extends ChangeNotifier {/// is after its files have gone up.Future<Map<String, dynamic>?> sendThreadReply({bool alsoSend = false,+ bool newSession = false,VoidCallback? onSending,}) async {final open = openedThread;@@ -1389,7 +1391,9 @@ class SuperTabController extends ChangeNotifier {'text': text,'replyTo': open.root,'recipientIds': const <String>[],- if (alsoSend) 'alsoSend': true,+ // A session's thread stays in the thread: never also sent.+ if (alsoSend && !newSession) 'alsoSend': true,+ if (newSession) 'newSession': true,if (ids.isNotEmpty) 'attachmentIds': ids,});if (_pending case final pending? when !identical(pending, before)) {@@ -1405,6 +1409,105 @@ class SuperTabController extends ChangeNotifier {return result;}+ // ── Buddy thread sessions (spec 2026-10-30-buddy-thread-sessions) ───────++ /// How many thread sessions a Buddy chat may run at once (backend limit).+ static const maxBuddySessions = 3;++ /// The open thread's chat when it is the reader's own Buddy chat, where a+ /// thread may have a session of its own; null anywhere else.+ SuperTabConversation? get _ownBuddyChat {+ final id = openedThread?.conversationId ?? selectedId;+ final chat = snapshot?.conversation(id);+ return chat != null &&+ chat.isBuddyChat &&+ chat.buddyOwnerId == accountId &&+ !accessRevoked+ ? chat+ : null;+ }++ /// Whether the open chat's thread composer shows New session: the reader's+ /// own Buddy chat, with a Buddy, or in [root]'s thread that had a session+ /// (its reply must start a new one). It may still show disabled, saying why+ /// ([threadSessionBlocked]).+ bool offersThreadSessions([String? root]) {+ final chat = _ownBuddyChat;+ if (chat == null) return false;+ return buddy(chat.projectId) != null || (root != null && _hadSession(root));+ }++ /// Why the open Buddy chat cannot start a session now, as the disabled+ /// choice says it; null when it can, as far as this computer can tell (the+ /// server still decides, and its refusal shows in the composer).+ String? get threadSessionBlocked {+ final chat = _ownBuddyChat;+ if (chat == null) return null;+ if (snapshot?.paused == true) return 'New work is paused in this Swarm';+ final main = buddy(chat.projectId);+ if (main == null || main.downSince != null) return 'Start your Buddy first';+ if (main.engine != 'claude') return 'Sessions need a Claude Code Buddy';+ // The host says what it can run in its report; a machine this computer+ // has no report of is left to the server.+ final pool = snapshot?.pool(main.machineId);+ final observation = pool?['observation'];+ if (observation is Map) {+ final capabilities = observation['capabilities'];+ if (capabilities is! List || !capabilities.contains('buddySessions')) {+ return 'Update Harness on ${sessionMachineName(main.machineId) ?? 'your Buddy\'s computer'} to start sessions';+ }+ }+ return null;+ }++ /// The Swarm's name for [machineId], as people read it; null when unknown.+ String? sessionMachineName(String machineId) {+ final name = snapshot?.pool(machineId)?['name'];+ return name is String && name.isNotEmpty ? superTabMachineName(name) : null;+ }++ /// Whether [root]'s thread has a reply from or to a thread session.+ bool _hadSession(String root) =>+ threadMessages(root).any((m) => m.buddySession);++ /// The live or starting session answering [root] in the reader's own Buddy+ /// chat; null when none does, or anywhere else.+ SuperTabBuddySession? threadSession(String root) =>+ _ownBuddyChat?.sessionFor(root);++ /// The session agent of [session], once it started.+ SuperTabAgent? sessionAgent(SuperTabBuddySession session) =>+ session.agentId == null ? null : snapshot?.agent(session.agentId!);++ /// The row saying [root]'s last session ended (its ended line, else its+ /// last session reply), while no session answers there: a plain reply+ /// would be refused, so a new one must start. Any session reply locks it,+ /// ended line or not.+ SuperTabMessage? threadSessionEnded(String root) {+ if (_ownBuddyChat == null || threadSession(root) != null) return null;+ final messages = threadMessages(root);+ return messages.where((m) => m.sessionEnded).lastOrNull ??+ messages.where((m) => m.buddySession).lastOrNull;+ }++ /// Whether the open Buddy chat already runs [maxBuddySessions] sessions.+ bool get buddySessionsFull =>+ (_ownBuddyChat?.buddySessions.length ?? 0) >= maxBuddySessions;++ /// Ends [root]'s session in the reader's own Buddy chat. Closing the thread+ /// pane only hides it; this stops it. False when refused or not sent.+ Future<bool> endThreadSession(String root) async {+ final chat = _ownBuddyChat;+ if (chat == null || chat.sessionFor(root) == null) return false;+ return await command({+ 'type': 'buddy.sessionEnd',+ 'conversationId': chat.id,+ 'thread': root,+ 'reason': 'ended',+ }) !=+ null;+ }+List<SuperTabMessage> messages(String id) => List.unmodifiable((_messages[id] ?? const <SuperTabMessage>[]).where(_listed),);@@ -2198,9 +2301,11 @@ class SuperTabController extends ChangeNotifier {_indexed()?.buddyChats[projectId];/// The signed-in person's Buddy in [projectId]; null when they have none.+ /// Its main session only: a thread's own session is never "the Buddy".SuperTabAgent? buddy(String projectId) => snapshot?.agents.where(- (a) => a.isBuddy && a.buddyOf == accountId && a.projectId == projectId,+ (a) =>+ a.isMainBuddy && a.buddyOf == accountId && a.projectId == projectId,).firstOrNull;@@ -2211,6 +2316,8 @@ class SuperTabController extends ChangeNotifier {final chat = _indexed()?.buddyChats[projectId]?.id;return snapshot?.buddyStarts.reversed.where((start) {final request = superTabMap(start['request']);+ // A thread session's start is its thread's, never the Buddy's own.+ if (request['buddySession'] != null) return false;return superTabMap(request['buddyOf'])['personId'] == accountId &&(request['projectId'] == projectId ||(chat != null && request['conversationId'] == chat));diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex fb396cdc7..96e317e8a 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -52,6 +52,7 @@ class SuperTabMessageRow extends StatefulWidget {this.thread,this.threadUnread = false,this.onOpenThread,+ this.threadTrailing,this.member,this.link,this.linkTarget,@@ -72,6 +73,9 @@ class SuperTabMessageRow extends StatefulWidget {/// reply's mark.final VoidCallback? onOpenThread;+ /// Ends the thread line: the mark of a thread's own Buddy session.+ final Widget? threadTrailing;+/// Who a thread's reply author is in the Swarm now, for the faces on its/// reply line; without it each shows the face its recorded name gives.final SuperTabMemberOf? member;@@ -531,6 +535,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {unread: widget.threadUnread,onOpen: open,member: widget.member,+ trailing: widget.threadTrailing,),...widget.receipts,],@@ -699,7 +704,8 @@ class SuperTabLink extends StatefulWidget {required this.child,});- final VoidCallback onTap;+ /// Null disables it, for pointer, keyboard and screen readers alike.+ final VoidCallback? onTap;final String label;final Widget child;@@ -714,13 +720,16 @@ class _SuperTabLinkState extends State<SuperTabLink> {Widget build(BuildContext context) {grid.AppTheme.watch(context);final radius = BorderRadius.circular(DesktopChrome.controlRadius);+ final enabled = widget.onTap != null;return Semantics(button: true,+ enabled: enabled,label: widget.label,child: InkWell(onTap: widget.onTap,+ canRequestFocus: enabled,onFocusChange: (focused) => setState(() => _focused = focused),- mouseCursor: SystemMouseCursors.click,+ mouseCursor: enabled ? SystemMouseCursors.click : MouseCursor.defer,borderRadius: radius,hoverColor: Colors.transparent,focusColor: Colors.transparent,@@ -759,9 +768,13 @@ class SuperTabThreadLine extends StatelessWidget {required this.unread,required this.onOpen,this.member,+ this.trailing,});final SuperTabThread thread;++ /// Drawn after the line's link, outside it: a thread session's mark.+ final Widget? trailing;final bool unread;final VoidCallback onOpen;@@ -795,36 +808,38 @@ class SuperTabThreadLine extends StatelessWidget {grid.AppTheme.watch(context);final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';final last = thread.lastAt;- return Padding(- padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),- child: SuperTabLink(- label: unread ? '$count, unread' : count,- onTap: onOpen,- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (final author in thread.authors) ...[- _face(author),- const SizedBox(width: grid.AppDesktop.menuInset),- ],+ final link = SuperTabLink(+ label: unread ? '$count, unread' : count,+ onTap: onOpen,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final author in thread.authors) ...[+ _face(author),+ const SizedBox(width: grid.AppDesktop.menuInset),+ ],+ Text(+ count,+ key: ValueKey('super-thread-count-${thread.id}'),+ style: DesktopChrome.control(+ color: DesktopChrome.accent,+ ).copyWith(fontWeight: unread ? FontWeight.w700 : FontWeight.w500),+ ),+ if (last != null) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),Text(- count,- key: ValueKey('super-thread-count-${thread.id}'),- style: DesktopChrome.control(color: DesktopChrome.accent)- .copyWith(- fontWeight: unread ? FontWeight.w700 : FontWeight.w500,- ),+ 'Last reply ${superTabAgo(DateTime.now().difference(last))}',+ style: DesktopChrome.metadata(),),- if (last != null) ...[- const SizedBox(width: grid.AppDesktop.controlGap),- Text(- 'Last reply ${superTabAgo(DateTime.now().difference(last))}',- style: DesktopChrome.metadata(),- ),- ],],- ),+ ],),);+ return Padding(+ padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),+ child: trailing == null+ ? link+ : Row(mainAxisSize: MainAxisSize.min, children: [link, trailing!]),+ );}}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex a111ad07d..80d941c82 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -129,6 +129,7 @@ class SuperTabAgent {{'personId': final String person} => person,_ => null,},+ buddySession = SuperTabBuddySessionOf.fromJson(row['buddySession']),limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),alerting = List.unmodifiable((row['alerting'] as List?)?.whereType<String>() ?? const <String>[],@@ -175,10 +176,48 @@ class SuperTabAgent {/// The person whose Buddy it is; null for any other agent.final String? buddyOf;++ /// Set on a Buddy's thread session (spec 2026-10-30-buddy-thread-sessions):+ /// the thread it answers in. Null on the main Buddy and every other agent.+ final SuperTabBuddySessionOf? buddySession;++ /// A person's main Buddy: a Buddy that is no thread's session.+ bool get isMainBuddy => isBuddy && buddySession == null;final Map<String, dynamic> configuration;String get engine => configuration['engine'] as String? ?? '';}+/// What makes an agent a thread session: its thread's root and the sequence+/// of the message that started it (backend model.ts `Agent.buddySession`).+class SuperTabBuddySessionOf {+ const SuperTabBuddySessionOf(this.thread, this.from);+ final String thread;+ final int from;++ static SuperTabBuddySessionOf? fromJson(Object? value) {+ if (value is! Map) return null;+ final json = superTabMap(value);+ final thread = json['thread'];+ if (thread is! String || thread.isEmpty) return null;+ final from = json['from'];+ return SuperTabBuddySessionOf(thread, from is num ? from.toInt() : 0);+ }+}++/// One live or starting thread session of a Buddy chat (backend model.ts+/// `Conversation.buddySessions`): no [agentId] while it starts.+class SuperTabBuddySession {+ SuperTabBuddySession.fromJson(Map<String, dynamic> json)+ : thread = json['thread'] is String ? json['thread'] as String : '',+ startId = json['startId'] is String ? json['startId'] as String : '',+ agentId = json['agentId'] is String ? json['agentId'] as String : null,+ at = json['at'] is num ? (json['at'] as num).toInt() : 0;+ final String thread, startId;+ final String? agentId;+ final int at;+ bool get starting => agentId == null;+}+class SuperTabTask {SuperTabTask.fromJson(Map<String, dynamic> row): goal = _text(row, 'goal'),@@ -200,6 +239,12 @@ class SuperTabConversation {kind = row['kind'] as String?,buddyOwnerId = row['buddyOwnerId'] as String?,buddyName = row['buddyName'] as String?,+ buddySessions = List.unmodifiable(+ (row['buddySessions'] is List ? row['buddySessions'] as List : const [])+ .whereType<Map>()+ .map((json) => SuperTabBuddySession.fromJson(superTabMap(json)))+ .where((session) => session.thread.isNotEmpty),+ ),number = (row['number'] as num?)?.toInt(),title = _text(row, 'title'),leadId = row['leadId'] as String?,@@ -255,6 +300,14 @@ class SuperTabConversation {/// The name a Buddy chat's person chose for their Buddy, kept while no/// Buddy runs; null for the default (backend buddies.ts renameBuddy).final String? buddyName;++ /// A Buddy chat's thread sessions, live or starting (at most 3); empty on+ /// every other conversation and from older backends.+ final List<SuperTabBuddySession> buddySessions;++ /// The live or starting session answering [thread], if any.+ SuperTabBuddySession? sessionFor(String thread) =>+ buddySessions.where((s) => s.thread == thread).firstOrNull;final SuperTabTask? task;final int? number;String get label => number == null ? title : '#$number $title';@@ -934,6 +987,7 @@ class SuperTabMessage {replyTo = row['replyTo'] as String?,thread = row['thread'] as String?,alsoInChat = row['alsoInChat'] == true,+ buddySession = row['buddySession'] == true,sequence = (row['sequence'] as num).toInt(),author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),@@ -958,6 +1012,18 @@ class SuperTabMessage {/// A thread reply also shown in the conversation's main stream.final bool alsoInChat;++ /// A reply in a Buddy thread session's thread, from the person or that+ /// session (spec 2026-10-30-buddy-thread-sessions).+ final bool buddySession;++ /// The line the server writes in a thread when its session ends.+ bool get sessionEnded => source['kind'] == 'buddy-session-ended';++ /// Why its session ended, for [sessionEnded] rows: `ended`, `idle`,+ /// `stopped` or `failed`.+ String? get sessionEndReason =>+ sessionEnded ? source['reason'] as String? : null;bool get threadReply => thread != null && thread != id;/// Whether the main stream lists it: a thread reply only when also sent.diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartindex 26a725f31..2eebbe865 100644--- a/desktop/lib/super_tabs/thread_panel.dart+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -11,6 +11,7 @@ import '../state/harness_attachments.dart';import '../widgets/desktop_chrome.dart';import '../widgets/new_harness_attachments.dart';import '../widgets/new_harness_paste.dart';+import 'buddy_sessions.dart';import 'composer_files.dart';import 'composer_newline.dart';import 'controller.dart';@@ -26,6 +27,7 @@ class SuperTabThreadPanel extends StatefulWidget {required this.root,required this.row,required this.outgoing,+ this.sessionActivity,});final SuperTabController controller;@@ -37,6 +39,10 @@ class SuperTabThreadPanel extends StatefulWidget {/// Draws a reply on its way.final Widget Function(SuperTabOutgoing sent) outgoing;+ /// What a thread's own Buddy session is doing, as this computer reads it;+ /// without it, what the Swarm alone says.+ final SuperTabSessionActivity? sessionActivity;+@overrideState<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();}@@ -48,6 +54,8 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {final _focus = FocusNode();final _scroll = ScrollController();bool _alsoSend = false;+ // The reply starts this thread's own Buddy session (reader's Buddy chat).+ bool _newSession = false;// Whether the list is scrolled away from its newest reply, the replies// there were when the thread opened or was last read to its end (set once// the thread's replies are known), and the latest replies and rows (replies@@ -81,6 +89,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {// Each thread keeps its own draft._composer.text = c.threadDraft(widget.root);_alsoSend = false;+ _newSession = false;}}@@ -163,6 +172,30 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {bool get _writable =>c.canWrite && c.selected?.archived == false && !c.hasPendingAction;+ /// The thread's last session ended: a reply here must start a new one.+ bool get _sessionLocked =>+ c.offersThreadSessions(widget.root) &&+ c.threadSessionEnded(widget.root) != null;++ /// Whether the composer offers New session: the reader's own Buddy chat,+ /// with their Buddy running, in a thread no session answers now.+ bool get _offersSession =>+ c.offersThreadSessions(widget.root) &&+ c.threadSession(widget.root) == null;++ /// Whether this reply starts a session.+ bool get _startsSession =>+ _offersSession &&+ (_sessionLocked ||+ (_newSession &&+ !c.buddySessionsFull &&+ c.threadSessionBlocked == null));++ /// A session's thread stays in the thread: Also send is not offered there,+ /// nor for a reply that starts one.+ bool get _offersAlsoSend =>+ !_startsSession && c.threadSession(widget.root) == null;+/// The files waiting to go with this thread's next reply.HarnessAttachments get _files =>c.threadAttachments(c.selectedId, widget.root);@@ -186,14 +219,18 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {final root = widget.root;c.setThreadDraft(root, _composer.text);await c.sendThreadReply(- alsoSend: _alsoSend,+ alsoSend: _offersAlsoSend && _alsoSend,+ newSession: _startsSession,// The reply is on its way (its files have gone up): the box is free for// the next one, unless another thread is shown by now.onSending: () {if (!mounted || widget.root != root) return;if (c.threadDraft(root).isEmpty) {_composer.clear();- setState(() => _alsoSend = false);+ setState(() {+ _alsoSend = false;+ _newSession = false;+ });}},);@@ -254,6 +291,14 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {),),Divider(height: 1, thickness: 1, color: DesktopChrome.rim),+ SuperTabThreadSessionLine(+ key: ValueKey('super-thread-session-${widget.root}'),+ controller: c,+ root: widget.root,+ activityOf:+ widget.sessionActivity ??+ (session) => superTabSessionActivity(c, null, session),+ ),Expanded(child: Stack(children: [@@ -455,38 +500,21 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {Row(children: [Expanded(- child: MergeSemantics(- child: Row(- children: [- Checkbox(+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: grid.AppDesktop.controlGap,+ children: [+ if (_offersSession) _sessionChoice(writable),+ if (_offersAlsoSend)+ _choice(key: const ValueKey('super-thread-also-send'),- visualDensity: VisualDensity.compact,- materialTapTargetSize:- MaterialTapTargetSize.shrinkWrap,value: _alsoSend,+ label: _alsoSendLabel,onChanged: writable- ? (on) =>- setState(() => _alsoSend = on ?? false)+ ? (on) => setState(() => _alsoSend = on): null,),- Flexible(- child: GestureDetector(- onTap: writable- ? () => setState(() => _alsoSend = !_alsoSend)- : null,- child: MouseRegion(- cursor: writable- ? SystemMouseCursors.click- : MouseCursor.defer,- child: Text(- _alsoSendLabel,- style: DesktopChrome.control(),- ),- ),- ),- ),- ],- ),+ ],),),NewHarnessAttachButton(@@ -517,4 +545,76 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {),);}++ /// New session, left of Also send: checked and locked once the thread's+ /// session ended, unavailable (and saying why) at the limit.+ Widget _sessionChoice(bool writable) {+ final locked = _sessionLocked;+ // What the server would refuse is said before sending: a block (paused,+ // no Buddy, an older host) before the limit.+ final blocked = c.threadSessionBlocked;+ final full = !locked && blocked == null && c.buddySessionsFull;+ final choice = _choice(+ key: const ValueKey('super-thread-new-session'),+ value: locked || (_newSession && !full && blocked == null),+ label: blocked != null+ ? 'New session · $blocked'+ : full+ ? 'New session · ${SuperTabController.maxBuddySessions} running, end one first'+ : 'New session',+ onChanged: writable && !locked && !full && blocked == null+ ? (on) => setState(() => _newSession = on)+ : null,+ );+ return Tooltip(+ message:+ blocked ??+ (locked+ ? 'This thread\'s session ended. Your reply starts a new one.'+ : full+ ? 'End a session to start another'+ : 'Answer this thread in its own session, while your Buddy keeps '+ 'answering the chat'),+ child: choice,+ );+ }++ /// A quiet checkbox and its label, both pressable, read as one control.+ Widget _choice({+ required Key key,+ required bool value,+ required String label,+ required ValueChanged<bool>? onChanged,+ }) => MergeSemantics(+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Checkbox(+ key: key,+ visualDensity: VisualDensity.compact,+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ value: value,+ onChanged: onChanged == null ? null : (on) => onChanged(on ?? false),+ ),+ Flexible(+ child: GestureDetector(+ onTap: onChanged == null ? null : () => onChanged(!value),+ child: MouseRegion(+ cursor: onChanged == null+ ? MouseCursor.defer+ : SystemMouseCursors.click,+ child: Text(+ label,+ style: DesktopChrome.control(+ color: onChanged == null && !value+ ? DesktopChrome.muted+ : null,+ ),+ ),+ ),+ ),+ ),+ ],+ ),+ );}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 49022c944..d8fe2dd66 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -53,6 +53,7 @@ import 'terminal_row.dart';import 'thread_panel.dart';import 'work_details.dart';import 'project_sidebar.dart';+import 'buddy_sessions.dart';import 'swarm_switcher.dart' show fallBackToPersonal;import 'project_options.dart';import 'pane_layout.dart';@@ -1022,6 +1023,8 @@ class _SuperTabViewState extends State<SuperTabView>final agents = snapshot.agents.where((agent) =>group.agentIds.contains(agent.id) &&+ // A thread's own session answers only there: nobody tags it.+ agent.buddySession == null &&'${_agentName(agent)} ${agent.engine}'.toLowerCase().contains(mention.query,),@@ -2508,6 +2511,16 @@ class _SuperTabViewState extends State<SuperTabView>},thread: thread,threadUnread: thread != null && c.threadUnread(thread),+ // A thread its own Buddy session answers says so on its line.+ threadTrailing: switch (thread == null || inThread+ ? null+ : c.threadSession(thread.id)) {+ final session? => SuperTabThreadSessionMark(+ key: ValueKey('super-thread-session-mark-${thread!.id}'),+ activity: superTabSessionActivity(c, widget.app, session),+ ),+ null => null,+ },onOpenThread:!inThread && root != null && (thread != null || message.threadReply)? () => c.openThread(root)@@ -2565,6 +2578,8 @@ class _SuperTabViewState extends State<SuperTabView>_message(message, grouped, byId, inThread: true),// The thread panel groups its own rows; one on its way keeps its name.outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),+ sessionActivity: (session) =>+ superTabSessionActivity(c, widget.app, session),);}diff --git a/desktop/test/super_tab_buddy_sessions_shots_test.dart b/desktop/test/super_tab_buddy_sessions_shots_test.dartnew file mode 100644index 000000000..dfdee7220--- /dev/null+++ b/desktop/test/super_tab_buddy_sessions_shots_test.dart@@ -0,0 +1,224 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_BUDDY_SESSION_SHOTS'];++/// Buddy thread sessions as the PR shows them, the spec's five mockups in+/// both appearances: a thread with no session, the limit, a working session,+/// the chat's thread line, and an ended session; and a choice the server+/// would refuse (paused), saying why.+void main() {+ setUpAll(() async {+ if (shots == null) return;+ await loadPreviewFonts();+ // The activity marks are Braille and symbols, which the preview fonts+ // lack; the roster's captures load them from the system the same way.+ if (!Platform.isMacOS) return;+ for (final font in [+ ('.AppleSystemUIFontMonospaced', '/System/Library/Fonts/SFNSMono.ttf'),+ ('Menlo', '/System/Library/Fonts/Menlo.ttc'),+ ('Apple Symbols', '/System/Library/Fonts/Apple Symbols.ttf'),+ ]) {+ final bytes = ByteData.sublistView(await File(font.$2).readAsBytes());+ await (FontLoader(font.$1)..addFont(Future.value(bytes))).load();+ }+ });++ const owner = {'kind': 'person', 'id': 'owner', 'name': '[email protected]'};+ const wren = {+ 'kind': 'agent',+ 'id': 'buddy-main',+ 'name': 'Wren',+ 'displayName': 'Wren',+ };+ const session = {+ 'kind': 'agent',+ 'id': 'session-1',+ 'name': 'Wren',+ 'displayName': 'Wren',+ };++ Map<String, dynamic> agent(String id, String harness, {String? thread}) => {+ 'id': id,+ 'name': 'Wren',+ 'displayName': 'Wren',+ 'machineId': 'm',+ 'harnessId': harness,+ 'contributorId': 'owner',+ 'machineOwnerId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'buddySession': ?(thread == null ? null : {'thread': thread, 'from': 1}),+ 'configuration': {'engine': 'claude', 'model': 'opus'},+ };++ for (final brightness in Brightness.values) {+ for (final state in [+ 'no-session',+ 'limit',+ 'working',+ 'chat',+ 'ended',+ 'blocked',+ ]) {+ testWidgets('screenshot $state (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).first['email'] = '[email protected]';+ final chat = (server.state['conversations'] as List)[1] as Map+ ..['kind'] = 'buddy'+ ..['buddyOwnerId'] = 'owner'+ ..['title'] = 'Wren'+ ..['buddyName'] = 'Wren'+ ..['agentIds'] = ['buddy-main'];+ (server.state['agents'] as List).add(agent('buddy-main', 'a1'));+ // New work paused: the choice says why before sending.+ if (state == 'blocked') server.state['paused'] = true;+ final now = DateTime.now().toUtc();+ void say(+ String text,+ Map<String, Object> author, {+ String? thread,+ int minutesAgo = 0,+ Map<String, Object>? source,+ }) {+ server.append(text, conversationId: 'offline');+ server.messages.last+ ..['author'] = author+ ..['createdAt'] = now+ .subtract(Duration(minutes: minutesAgo))+ .toIso8601String();+ if (thread != null) {+ server.messages.last+ ..['thread'] = thread+ ..['replyTo'] = thread+ ..['buddySession'] = true;+ }+ if (source != null) server.messages.last['source'] = source;+ }++ say(+ 'Measure prod CPU for the last day and say what changed.',+ owner,+ minutesAgo: 12,+ );+ if (state == 'working' || state == 'chat' || state == 'ended') {+ say(+ 'Reading the last 24 h of pod logs, one pod at a time…',+ session,+ thread: 'message-1',+ minutesAgo: 10,+ );+ }+ say('What\'s the PR number for the login fix?', owner, minutesAgo: 2);+ say('#2290.', wren, minutesAgo: 2);+ if (state == 'ended') {+ say(+ 'Session ended: idle for 30 minutes.',+ owner,+ thread: 'message-1',+ source: {+ 'kind': 'buddy-session-ended',+ 'reason': 'idle',+ 'thread': 'message-1',+ },+ );+ // Said by the session that ended (backend commands.ts).+ server.messages.last['author'] = session;+ }+ if (state == 'working' || state == 'chat') {+ chat['buddySessions'] = [+ {+ 'thread': 'message-1',+ 'startId': 's1',+ 'agentId': 'session-1',+ 'at': 1,+ },+ ];+ chat['agentIds'] = ['buddy-main', 'session-1'];+ (server.state['agents'] as List).add(+ agent('session-1', 'a5', thread: 'message-1'),+ );+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a5',+ });+ }+ if (state == 'limit') {+ chat['buddySessions'] = [+ for (final t in ['t1', 't2', 't3'])+ {'thread': t, 'startId': 's$t', 'agentId': 'session-$t', 'at': 1},+ ];+ }+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ app: app,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ c.select('offline');+ await tester.pumpAndSettle();+ if (state != 'chat') {+ c.openThread('message-1');+ await tester.pumpAndSettle();+ }+ // The working mark spins: stop on one frame.+ await tester.pump(const Duration(milliseconds: 50));+ await tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/buddy-session-$state-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ if (state == 'working' || state == 'chat') {+ // Its turn ends, so no turn watchdog outlives the test.+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a5',+ });+ // Its preview's short debounce runs out too.+ await tester.pump(const Duration(milliseconds: 100));+ }+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);+ }+ }+}diff --git a/desktop/test/super_tab_buddy_sessions_test.dart b/desktop/test/super_tab_buddy_sessions_test.dartnew file mode 100644index 000000000..c87649c22--- /dev/null+++ b/desktop/test/super_tab_buddy_sessions_test.dart@@ -0,0 +1,661 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_row.dart' show SuperTabLink;+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// Buddy thread sessions on Desktop (spec docs/superpowers/specs/2026-10-30-+/// buddy-thread-sessions-design.md): in the reader's own Buddy chat a thread+/// may get its own Buddy session. The thread pane offers New session, says+/// which session answers and whether it works, and ends it quietly; the chat's+/// thread line marks a thread its session answers.+void main() {+ final newSession = find.byKey(const ValueKey('super-thread-new-session'));+ final alsoSend = find.byKey(const ValueKey('super-thread-also-send'));+ final composer = find.byKey(const ValueKey('super-thread-composer'));+ final send = find.byKey(const ValueKey('super-thread-send'));+ final state = find.byKey(const ValueKey('super-thread-session-state'));+ final end = find.byKey(const ValueKey('super-thread-session-end'));+ final ended = find.byKey(const ValueKey('super-thread-session-ended'));++ late SuperTabController shown;++ void testSessions(+ String description,+ Future<void> Function(WidgetTester tester) body,+ ) => testWidgets(description, (tester) async {+ await body(tester);+ await tester.pumpWidget(const SizedBox());+ await shown.flush();+ });++ Map<String, dynamic> chatOf(ConversationServer server) =>+ (server.state['conversations'] as List)[1] as Map<String, dynamic>;++ /// The reader's own Buddy chat ('offline' in the fixture) with their Buddy+ /// running, a root, and a second thread to switch to.+ ConversationServer buddyChat({bool buddy = true}) {+ final server = ConversationServer()..threads = true;+ final chat = chatOf(server)+ ..['kind'] = 'buddy'+ ..['buddyOwnerId'] = 'owner'+ ..['title'] = 'Wren';+ if (buddy) {+ (server.state['agents'] as List).add({+ 'id': 'buddy-main',+ 'name': 'Wren',+ 'displayName': 'Wren',+ 'machineId': 'mac',+ 'harnessId': 'h-main',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'configuration': {'engine': 'claude'},+ });+ chat['agentIds'] = ['buddy-main'];+ }+ server.append(+ 'Measure prod CPU for the last day',+ conversationId: 'offline',+ );+ server.append('What is the PR number?', conversationId: 'offline');+ return server;+ }++ /// A thread session of [thread], started (with [agentId]) or starting.+ void addSession(+ ConversationServer server,+ String thread, {+ String? agentId,+ bool down = false,+ }) {+ final chat = chatOf(server);+ chat['buddySessions'] = [+ ...(chat['buddySessions'] as List? ?? const []),+ {+ 'thread': thread,+ 'startId': 'start-$thread',+ 'agentId': ?agentId,+ 'at': 1,+ },+ ];+ if (agentId != null) {+ (server.state['agents'] as List).add({+ 'id': agentId,+ 'name': 'Wren',+ 'displayName': 'Wren',+ 'machineId': 'mac',+ 'harnessId': 'h-$agentId',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'buddySession': {'thread': thread, 'from': 1},+ 'configuration': {'engine': 'claude'},+ if (down) 'downSince': '2026-10-30T00:00:00Z',+ });+ chat['agentIds'] = [...chat['agentIds'] as List, agentId];+ }+ }++ /// The Buddy's machine as its pool row reads, its host able to run sessions+ /// unless [capable] is false.+ Map<String, dynamic> machine({bool capable = true}) => {+ 'machineId': 'mac',+ 'name': 'Studio',+ 'contributorId': 'owner',+ 'scope': 'swarm',+ 'engines': ['claude'],+ 'observation': {+ 'receivedAt': 1,+ 'runningHarnessIds': <String>[],+ 'stoppedHarnessIds': <String>[],+ if (capable) 'capabilities': ['buddySessions'],+ },+ };++ /// A reply in [thread] from or to its session, with no ended line.+ void sessionReply(ConversationServer server, String thread, String text) {+ server.append(text, conversationId: 'offline');+ server.messages.last+ ..['thread'] = thread+ ..['replyTo'] = thread+ ..['buddySession'] = true;+ }++ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ Brightness brightness = Brightness.dark,+ bool select = true,+ }) async {+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = shown = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ if (select) {+ c.select('offline');+ await tester.pumpAndSettle();+ }+ addTearDown(c.dispose);+ return c;+ }++ Future<void> openThread(+ WidgetTester tester,+ SuperTabController c,+ String root,+ ) async {+ c.openThread(root);+ await tester.pumpAndSettle();+ }++ Checkbox box(WidgetTester tester, Finder finder) =>+ tester.widget<Checkbox>(finder);++ Map<String, dynamic> lastCommand(ConversationServer server) =>+ Map<String, dynamic>.from(server.posts.last['command'] as Map);++ testSessions('New session sits beside Also send, hides it, and is sent', (+ tester,+ ) async {+ final server = buddyChat();+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');++ expect(newSession, findsOneWidget);+ expect(alsoSend, findsOneWidget);+ expect(box(tester, newSession).value, isFalse);+ // Before Also send in reading order: left of it on one row, or above it+ // where a narrow pane wraps them.+ final a = tester.getRect(newSession), b = tester.getRect(alsoSend);+ expect(a.top < b.top || (a.top == b.top && a.left < b.left), isTrue);+ expect(+ find.byTooltip(+ 'Answer this thread in its own session, while your Buddy keeps '+ 'answering the chat',+ ),+ findsOneWidget,+ );++ await tester.tap(newSession);+ await tester.pump();+ expect(box(tester, newSession).value, isTrue);+ // A session's thread stays in the thread.+ expect(alsoSend, findsNothing);++ await tester.enterText(composer, 'Measure it now');+ await tester.pump();+ await tester.tap(send);+ await tester.pumpAndSettle();+ final sent = lastCommand(server);+ expect(sent['type'], 'message.send');+ expect(sent['replyTo'], 'message-1');+ expect(sent['newSession'], isTrue);+ expect(sent.containsKey('alsoSend'), isFalse);+ // The next reply starts as plain again.+ expect(box(tester, newSession).value, isFalse);+ });++ testSessions('a New session tick stays with its own thread', (tester) async {+ final server = buddyChat();+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ await tester.tap(newSession);+ await tester.pump();+ expect(box(tester, newSession).value, isTrue);+ await openThread(tester, c, 'message-2');+ expect(box(tester, newSession).value, isFalse);+ expect(alsoSend, findsOneWidget);+ });++ testSessions('a plain reply in a Buddy chat sends no new session', (+ tester,+ ) async {+ final server = buddyChat();+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ await tester.enterText(composer, 'Just a note');+ await tester.pump();+ await tester.tap(send);+ await tester.pumpAndSettle();+ expect(lastCommand(server).containsKey('newSession'), isFalse);+ });++ testSessions('New session is offered only in the reader\'s own Buddy chat, '+ 'with their Buddy running', (tester) async {+ // A workgroup's thread.+ final work = ConversationServer()..threads = true;+ work.append('A workgroup topic');+ var c = await show(tester, work, select: false);+ await openThread(tester, c, 'message-1');+ expect(newSession, findsNothing);+ expect(alsoSend, findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ await shown.flush();++ // Their Buddy chat, with no Buddy running.+ c = await show(tester, buddyChat(buddy: false));+ await openThread(tester, c, 'message-1');+ expect(newSession, findsNothing);+ });++ testSessions('at the limit the choice is unavailable and says why', (+ tester,+ ) async {+ final server = buddyChat();+ for (final thread in ['t-a', 't-b', 't-c']) {+ addSession(server, thread, agentId: 'session-$thread');+ }+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(find.text('New session · 3 running, end one first'), findsOneWidget);+ expect(box(tester, newSession).onChanged, isNull);+ expect(box(tester, newSession).value, isFalse);+ expect(find.byTooltip('End a session to start another'), findsOneWidget);+ // Tapping the words does nothing either; a reply goes plain.+ await tester.tap(find.text('New session · 3 running, end one first'));+ await tester.enterText(composer, 'Plain');+ await tester.pump();+ await tester.tap(send);+ await tester.pumpAndSettle();+ expect(lastCommand(server).containsKey('newSession'), isFalse);+ });++ testSessions('a starting session says so, and its thread offers no choice', (+ tester,+ ) async {+ final server = buddyChat();+ addSession(server, 'message-1');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(tester.widget<Text>(state).data, 'Own session · Starting…');+ expect(newSession, findsNothing);+ expect(alsoSend, findsNothing);+ });++ testSessions('a session on a computer that went offline names it', (+ tester,+ ) async {+ final server = buddyChat();+ addSession(server, 'message-1', agentId: 'session-1', down: true);+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ // A machine this computer has no row for is not guessed at.+ expect(+ tester.widget<Text>(state).data,+ 'Own session · Its computer is offline',+ );+ server.state['machines'] = [machine()];+ server.revision++;+ await c.refresh();+ await tester.pumpAndSettle();+ expect(tester.widget<Text>(state).data, 'Own session · Studio is offline');+ });++ testSessions('End session is a quiet text action that ends that thread\'s '+ 'session', (tester) async {+ final server = buddyChat();+ addSession(server, 'message-1', agentId: 'session-1');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(end, findsOneWidget);+ // Not a button: no filled or outlined button anywhere in the line.+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-thread-session-message-1')),+ matching: find.byWidgetPredicate(+ (w) => w is ButtonStyleButton || w is MaterialButton,+ ),+ ),+ findsNothing,+ );+ await tester.tap(end);+ await tester.pumpAndSettle();+ expect(lastCommand(server), {+ 'type': 'buddy.sessionEnd',+ 'conversationId': 'offline',+ 'thread': 'message-1',+ 'reason': 'ended',+ });+ });++ testSessions('an ended session\'s thread says why, and a reply must start '+ 'a new one', (tester) async {+ final server = buddyChat();+ server.append(+ 'Session ended: idle for 30 minutes.',+ conversationId: 'offline',+ );+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['buddySession'] = true+ ..['source'] = {+ 'kind': 'buddy-session-ended',+ 'reason': 'idle',+ 'thread': 'message-1',+ };+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(+ tester.widget<Text>(ended).data,+ 'Session ended: idle for 30 minutes',+ );+ expect(box(tester, newSession).value, isTrue);+ expect(box(tester, newSession).onChanged, isNull);+ expect(alsoSend, findsNothing);+ await tester.enterText(composer, 'Go on');+ await tester.pump();+ await tester.tap(send);+ await tester.pumpAndSettle();+ expect(lastCommand(server)['newSession'], isTrue);+ });++ testSessions('the chat\'s thread line marks a thread its session answers', (+ tester,+ ) async {+ final server = buddyChat();+ server.append('Reading the pod logs…', conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['buddySession'] = true;+ server.append('Second topic', conversationId: 'offline');+ server.append('A reply', conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-4'+ ..['replyTo'] = 'message-4';+ addSession(server, 'message-1', agentId: 'session-1');+ await show(tester, server);+ expect(+ find.byKey(const ValueKey('super-thread-session-mark-message-1')),+ findsOneWidget,+ );+ expect(find.text('Own session'), findsOneWidget);+ // A thread without a session has a plain line.+ expect(+ find.byKey(const ValueKey('super-thread-session-mark-message-4')),+ findsNothing,+ );+ });++ test('the Buddy is the main session, never a thread\'s own', () async {+ final server = buddyChat();+ // A session listed first, and its start, must not stand for the Buddy.+ addSession(server, 'message-1', agentId: 'session-1');+ final agents = server.state['agents'] as List;+ agents.insert(0, agents.removeLast());+ server.state['starts'] = [+ {+ 'id': 'start-message-1',+ 'request': {+ 'conversationId': 'offline',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'buddySession': {'thread': 'message-1', 'from': 1},+ },+ 'harnessId': null,+ 'error': null,+ },+ ];+ final c = shown = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ expect(c.buddy('lead')?.id, 'buddy-main');+ expect(c.buddyStart('lead'), isNull);+ expect(c.snapshot!.agent('session-1')!.isMainBuddy, isFalse);+ expect(c.snapshot!.agent('buddy-main')!.isMainBuddy, isTrue);+ await c.flush();+ });++ testSessions('access lost while a session\'s thread is open clears it all', (+ tester,+ ) async {+ final server = buddyChat();+ addSession(server, 'message-1', agentId: 'session-1');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(state, findsOneWidget);+ c.revokeAccess('You no longer have access to this Swarm.');+ await tester.pumpAndSettle();+ expect(state, findsNothing);+ expect(end, findsNothing);+ expect(newSession, findsNothing);+ expect(c.threadSession('message-1'), isNull);+ expect(c.offersThreadSessions('message-1'), isFalse);+ expect(await c.endThreadSession('message-1'), isFalse);+ });++ testSessions('a late End session answer leaves another thread as it is', (+ tester,+ ) async {+ final server = buddyChat();+ addSession(server, 'message-1', agentId: 'session-1');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ final hold = server.holdCommands = Completer<void>();+ await tester.tap(end);+ await tester.pump();+ expect(find.text('Ending…'), findsOneWidget);++ // Another thread is opened while the answer is on its way.+ await openThread(tester, c, 'message-2');+ expect(find.text('Ending…'), findsNothing);+ expect(newSession, findsOneWidget);+ expect(box(tester, newSession).value, isFalse);+ hold.complete();+ server.holdCommands = null;+ await tester.pumpAndSettle();+ expect(find.text('Ending…'), findsNothing);+ expect(state, findsNothing);+ expect(newSession, findsOneWidget);+ expect(box(tester, newSession).value, isFalse);+ });++ testSessions('a first read that failed and then recovered still offers New '+ 'session', (tester) async {+ final server = buddyChat()..failReads = true;+ final c = await show(tester, server, select: false);+ expect(c.snapshot, isNull);+ server.failReads = false;+ await c.refresh();+ c.select('offline');+ await tester.pumpAndSettle();+ await openThread(tester, c, 'message-1');+ expect(newSession, findsOneWidget);+ expect(box(tester, newSession).onChanged, isNotNull);+ });++ testSessions('any session reply locks New session, ended line or not', (+ tester,+ ) async {+ final server = buddyChat();+ sessionReply(server, 'message-1', 'Reading the logs…');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(box(tester, newSession).value, isTrue);+ expect(box(tester, newSession).onChanged, isNull);+ expect(alsoSend, findsNothing);+ expect(tester.widget<Text>(ended).data, 'Session ended');+ });++ testSessions('after the Buddy is removed, an old session thread stays '+ 'locked and says why', (tester) async {+ final server = buddyChat(buddy: false);+ sessionReply(server, 'message-1', 'Reading the logs…');+ server.append(+ 'Session ended: its Buddy was removed or replaced.',+ conversationId: 'offline',+ );+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['buddySession'] = true+ ..['source'] = {+ 'kind': 'buddy-session-ended',+ 'reason': 'removed',+ 'thread': 'message-1',+ };+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(+ tester.widget<Text>(ended).data,+ 'Session ended: its Buddy was removed or replaced',+ );+ expect(box(tester, newSession).value, isTrue);+ expect(box(tester, newSession).onChanged, isNull);+ expect(find.text('New session · Start your Buddy first'), findsOneWidget);+ // A thread with no session past offers nothing without a Buddy.+ await openThread(tester, c, 'message-2');+ expect(newSession, findsNothing);+ });++ testSessions('New session says why the server would refuse it, before '+ 'sending', (tester) async {+ final server = buddyChat();+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ Future<void> blockedBy(String reason) async {+ server.revision++;+ await c.refresh();+ await tester.pumpAndSettle();+ expect(find.text('New session · $reason'), findsOneWidget);+ expect(box(tester, newSession).onChanged, isNull);+ expect(box(tester, newSession).value, isFalse);+ }++ server.state['paused'] = true;+ await blockedBy('New work is paused in this Swarm');+ server.state['paused'] = false;+ final main = (server.state['agents'] as List).last as Map<String, dynamic>;+ main['downSince'] = '2026-10-30T00:00:00Z';+ await blockedBy('Start your Buddy first');+ main.remove('downSince');+ main['configuration'] = {'engine': 'codex'};+ await blockedBy('Sessions need a Claude Code Buddy');+ main['configuration'] = {'engine': 'claude'};+ server.state['machines'] = [machine(capable: false)];+ await blockedBy('Update Harness on Studio to start sessions');+ // A block wins over the limit: it is what would be refused.+ addSession(server, 'message-2', agentId: 's2');+ final chat = chatOf(server);+ chat['buddySessions'] = [+ ...chat['buddySessions'] as List,+ {'thread': 'x', 'startId': 'sx', 'at': 1},+ {'thread': 'y', 'startId': 'sy', 'at': 1},+ ];+ await blockedBy('Update Harness on Studio to start sessions');+ server.state['machines'] = [machine()];+ chat['buddySessions'] = <dynamic>[];+ server.revision++;+ await c.refresh();+ await tester.pumpAndSettle();+ expect(find.text('New session'), findsOneWidget);+ expect(box(tester, newSession).onChanged, isNotNull);+ });++ testSessions('Ending… cannot be pressed again while its end is on its way', (+ tester,+ ) async {+ final server = buddyChat();+ addSession(server, 'message-1', agentId: 'session-1');+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ final hold = server.holdCommands = Completer<void>();+ await tester.tap(end);+ await tester.pump();+ final sent = server.posts.length;+ expect(find.text('Ending…'), findsOneWidget);+ final link = tester.widget<SuperTabLink>(end);+ expect(link.onTap, isNull);+ expect(+ tester.getSemantics(end),+ isSemantics(isButton: true, hasEnabledState: true, isEnabled: false),+ );+ await tester.tap(end, warnIfMissed: false);+ await tester.pump();+ expect(server.posts.length, sent);+ hold.complete();+ server.holdCommands = null;+ await tester.pumpAndSettle();+ });++ testSessions('a session start that failed never shows as the Buddy\'s own, '+ 'nor as Starting…', (tester) async {+ final server = buddyChat();+ // The backend ended it (no entry left) after its start timed out.+ server.state['starts'] = [+ {+ 'id': 'start-message-1',+ 'request': {+ 'conversationId': 'offline',+ 'machineId': 'mac',+ 'engine': 'claude',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'buddySession': {'thread': 'message-1', 'from': 1},+ },+ 'harnessId': null,+ 'error': 'This start timed out.',+ },+ ];+ final c = await show(tester, server);+ await openThread(tester, c, 'message-1');+ expect(c.buddyStart('lead'), isNull);+ expect(find.textContaining("Couldn't start"), findsNothing);+ expect(state, findsNothing);+ expect(box(tester, newSession).onChanged, isNotNull);+ });++ test('unexpected types in session fields never break the read', () async {+ final server = buddyChat();+ final chat = chatOf(server);+ chat['buddySessions'] = {'thread': 'message-1'};+ (server.state['agents'] as List).add({+ 'id': 'odd',+ 'name': 'Odd',+ 'machineId': 'mac',+ 'harnessId': 'h-odd',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'buddySession': {'thread': 5, 'from': 'x'},+ 'configuration': {'engine': 'claude'},+ });+ final c = server.controller();+ addTearDown(c.dispose);+ await c.refresh();+ expect(c.snapshot, isNotNull);+ expect(c.snapshot!.conversation('offline')!.buddySessions, isEmpty);+ expect(c.snapshot!.agent('odd')!.buddySession, isNull);+ chat['buddySessions'] = [+ {'thread': 'message-1', 'startId': 3, 'agentId': 7, 'at': 'soon'},+ 'not a session',+ ];+ (server.state['agents'] as List).last['buddySession'] = {+ 'thread': 'message-1',+ 'from': 'x',+ };+ server.revision++;+ await c.refresh();+ final session = c.snapshot!.conversation('offline')!.buddySessions.single;+ expect(session.startId, '');+ expect(session.agentId, isNull);+ expect(session.at, 0);+ expect(c.snapshot!.agent('odd')!.buddySession!.from, 0);+ });+}diff --git a/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md b/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.mdnew file mode 100644index 000000000..9e9d159bf--- /dev/null+++ b/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md@@ -0,0 +1,493 @@+# Buddy thread sessions: a thread can have its own Buddy session, in parallel++Status: design · 2026-10-30 · requested by Scholes · Engineer: Atlas · group #1421. Scope (Scholes, through the Lead, 10-30):+backend, CLI host and Desktop. The phone is out of this task: it only reads the new fields so its parity test passes.++## Why++A person talks to their Buddy in one chat, and the Buddy answers one message at a time. A long question ("measure prod+CPU for the last day and tell me what changed") holds every later one, so "what's the PR number again?" waits minutes.+Scholes wants a way to start a thread that has its own Buddy session working in parallel. By default, the chat works as+it does today: one session, one message after another.++Done when: a person starts a thread with **New session**, asks it a long question, and gets an answer to a quick+question in the main Buddy chat while the thread is still working.++## What exists today (read from the code, main 9a82d88)++- **One Buddy per person and project.** `buddy.create` refuses a second one (`BUDDY_EXISTS`, `commands.ts:1632`). It+ starts on the person's own machine (`BUDDY_OWN_MACHINE`) in a worktree of its own (`super-tab/<startId>`).+- **Routing.** In a Buddy chat, a person's message goes to the replied-to agent if it is in the chat, and otherwise to+ `group.agentIds[0]` (`commands.ts:2034-2036`). A thread reply is routed like any other message.+- **Threads.** A top-level message's `thread` is its own id, and a reply's `thread` is its root (`store.ts:1967`,+ `:1192-1200`). Threads never nest, and they can't be closed. Reading with a `{thread}` cursor exists+ (`store.messages`).+- **Order.** The server queues one delivery per recipient. The host on the person's machine claims each agent's list in+ order and types it into that agent's terminal, which holds it while the agent is busy (`host.ts:763-812`). The order is+ kept per agent, so a second agent gets its own queue.+- **Guard.** Each launch writes the session's own `.claude/settings.local.json`, `buddy-guard.mjs` and `buddy-launch`+ into its folder (`lockBuddyFolder`, `swarmSkills.ts:742`).+- **Wide reads (#2310).** A grant holds for one session (its reads list, keyed by the session label), one launch (a+ random id in that folder), the signed-in account, and an hour. The host grants it at each delivery of the person's own+ message (`grantBuddyWide`, `host.ts:1207-1247`).+- **Audience.** A Buddy agent reads its chat only while it is in `agentIds` and its person still reads the project+ (`buddyReads`). The PM and the Swarm owner never read it.+- **Desktop.** **Reply** on a message opens the thread pane (`thread_panel.dart`): the header reads `Thread` with a ×+ (`Close thread`); below it are the root, the replies, and a composer with the hint `Reply` and an `Also send to the+ chat` checkbox, then 📎 and ↑. Under a root in the chat, the thread line reads `N replies · Last reply 5m ago`. Neither+ the chat nor the thread shows whether the Buddy is working; only the sidebar's Buddy row shows an activity mark.++## The model++A **thread session** is a second Buddy agent in the same Buddy chat, tied to one thread. It is started like the main+Buddy, on the same machine with the same engine, guard and skill, in its own worktree. It differs in three ways:++- It hears only its thread.+- It answers only in its thread.+- It ends when its thread is done with it.++The main Buddy (the **main session**) is unchanged.++Ruling: a thread session is a separate agent, not a second process under the main Buddy's agent. Why: delivery, claims,+audience, the folder lock, the wide grant and stopping are all per agent today, so each session gets its own of each with+no new path. Cost if wrong: each session counts as one agent on the machine (`set-agents`), so a full machine refuses+it, and says so.++### Starting one++- **Where.** The Desktop thread composer, in the person's own Buddy chat, shows a **New session** checkbox when the+ thread has no live session. Checking it and sending the reply starts the session, and that reply is its first message.+ A thread that does not exist yet is started the same way: **Reply** on any main-chat message opens the thread pane.+- **Command.** `message.send` gains `newSession: true`. The server accepts it only when every condition below holds,+ and otherwise refuses with the reason shown:+ - The author is a person, in their own Buddy chat.+ - The message is a thread reply (`replyTo` set, landing in a thread).+ - The thread has no live or starting session.+ - The main Buddy exists, and its machine's host says it can run sessions (see Compatibility).+ - The chat has fewer than 3 live or starting sessions (`BUDDY_SESSIONS_FULL`: "3 sessions are running. End one to+ start another.").+- **What it writes,** in the same command:+ - The message, tagged `buddySession: true`.+ - An `AgentStart` with `buddyOf`, `buddySession: { thread: root, from: <the message's sequence> }`, and the main+ Buddy's machine, engine and model.+ - An entry `{ thread, startId, at }` in the chat's `buddySessions` (at most 3).+- **First delivery.** On `agent.started` for a thread session, the server sets `agentId` on the chat's entry and writes+ a delivery to the new agent for each of the person's `buddySession` messages in that thread, in order, that is still+ waiting. So the first message reaches it through the same `accept()` as any other: the person check, the `run:`+ judging and the wide grant all apply.+- **Its first prompt** (`buddyPrompt` for a session) names its chat and thread, and says:+ - It answers only in this thread, with `--reply-to`.+ - Its starting context is the thread plus the main-chat excerpt below.+ - The PM rule is unchanged.++ No message text goes into the start record. Start records are listed in the Lead's status.++### The starting context ("short summary of the main chat")++The session reads, through the server only:++- the thread's root and its replies;+- the **10 main-chat messages before the session started** (sequence ≤ `from`), each cut to 500 characters, at most 6 KB+ in all, oldest first.++The server builds this when the session reads it (`messages CHAT --thread ROOT` returns it as `context`). It is never+stored, and it is fixed by `from`, so it reads the same each time.++Ruling: an excerpt, not a written summary. Why: the main session is the busy one, so it can't stop to write a summary,+and the thread session may not read the main chat itself. Cost if wrong: an excerpt of the last 10 messages may miss an+older topic. The person can paste what is missing into the thread.++### Routing, both ways++- **To a session.** A person's reply in a thread with a live or starting session goes only to that session, and is+ tagged `buddySession: true`. If the session is still starting, it waits for the first delivery above. This is decided+ by the server from the thread, so it holds for every client, old Desktop and the phone included.+- **To the main session.** Everything else goes to the main Buddy: main-chat messages, and threads without a session.+ The main Buddy is picked by `!agent.buddySession`, no longer by `agentIds[0]`.+- **A thread whose session ended.** A plain reply is refused: "This thread's session ended. Send with New session to+ continue." Desktop checks **New session** for it. The new session reads the whole thread, including the replies from+ the session before it.+- **Back.**+ - A thread session's `post` must use `--reply-to` a message in its own thread (`BUDDY_SESSION_THREAD`).+ - It can't use `alsoSend`.+ - Its posts are tagged `buddySession: true`.+ - So a reply can never land in the main chat.++### Stopping++A session ends in these cases:++1. **The person ends it**: **End session** in the thread pane. Closing the pane (×) only hides it. Closing the pane to+ ask a quick question in the main chat is the reason this feature exists, so it must not stop the session. Threads+ can't be closed today, so "thread closed" means **End session**.+2. **30 minutes idle.** The host on the person's machine judges this from what it already reports per session:+ - no screen or transcript change (`harnessProgress`) for 30 minutes;+ - no open delivery to the session;+ - no person message in its thread for 30 minutes.++ A session still working on a long question changes its screen, so it is not idle. The host sends+ `buddy.sessionEnd { agentId, reason: 'idle' }` as the machine's owner, who is the person.+3. **The main Buddy is removed**, or the person loses the project or leaves the Swarm. Every path that removes the main+ Buddy removes its thread sessions in the same write.+4. **Its start fails**, or its process stops unexpectedly. Then the entry is removed and the session is ended, never+ restarted.++Ending uses the existing path:+- `removeAgent` puts the session in `closingSessions`, removes it from the chat's `agentIds` and `buddySessions`, and+ cancels its open deliveries.+- The host's `endSession` then forgets its reads list, closes the terminal, confirms with `agent.sessionClosed`, and+ removes its worktree.+- A quiet line in the thread says why it ended: "Session ended: idle for 30 minutes." / "…: you ended it." / "…: it+ couldn't start: <why>." / "…: it stopped unexpectedly."++## Security++Every thread session runs with the same guard and rules as the main one. Nothing is loosened.++- **Same guard, same skill.** `lockBuddyFolder` runs unchanged for a session, in its own folder. A test compares a+ session's settings and guard file with the main Buddy's, byte for byte, apart from the folder path, the reads-list path+ and the launch id. The Buddy skill text is unchanged; only the first prompt adds the thread paragraph.+- **Sends to the PM only when the person asks.**+ - `buddy.propose` from a session needs `ownerMessageId` to be the person's own message in that session's thread.+ - The guard's secret check and "summaries only" apply as they do today.+ - `harness send/new/tell/close` stay refused from its pane (`buddyPane.ts`).+- **The wide-read grant (#2310).** A session gets its own grant or none. It never shares or inherits the main+ session's:+ - Its own reads list (keyed by its own session label), its own launch id in its own folder, and its own owner mark.+ A grant written for the main session names another session and another launch, so the session's guard refuses it.+ - The host grants it only at the delivery of the person's own message in that session's thread, with the same checks+ as today: `fromOwnPerson`, on the person's machine, signed in as them, and an hour at most. This is why the first+ message arrives as a delivery and not through the prompt. Until then, and whenever a check fails, the session reads+ its own folder alone.+ - `run:` approvals stay per person on this machine, as ruled in #2310. An approval given in a thread also covers the+ main session. Approvals unlock only reads the grammar allows.+- **No session reads another's thread.** One server predicate, `buddySessionReads(agent, message)`, is applied on+ every agent read path of a Buddy chat: messages list, one message, thread read, change feed, the message in a claim,+ and `status`'s chat summary.+ - A thread session reads only messages whose `thread` is its root, plus the starting context above.+ - The main session does not read `buddySession` messages: other sessions' threads, past or present.+ - The person reads everything, as today.+- **Local copies.** Each session is a separate terminal, transcript and folder.+ - Wide mode already closes `~/.claude` (transcripts and the paste cache), `/tmp/claude-<uid>` and Harness's data+ folder.+ - New: the guard also closes every other Swarm session folder on the machine (the worktrees root except its own).+ Another session's downloaded attachments and folder can't be read in wide mode.++| # | Threat | Control | Test |+|---|---|---|---|+| S1 | A session reads the main chat beyond its excerpt | `buddySessionReads` on every agent read path | One test per read path, made-up and real ids |+| S2 | The main session reads a session's thread | Same predicate (`buddySession` messages) | Same |+| S3 | A reply lands in the main chat | `BUDDY_SESSION_THREAD`; no `alsoSend` | Command tests |+| S4 | The wide grant reaches a session nobody granted | Per-session list, launch id and account; granted only at that session's own deliveries | Host and guard tests: the main grant is refused by the session's guard and the reverse |+| S5 | Another session's folder or files are read in wide mode | The guard closes other session folders | Guard test |+| S6 | Someone else starts or ends a session | The person in their own chat; the host's end as the machine owner, who is the person | Command tests, other person, PM, other project |+| S7 | A planted PR in a thread asks for a proposal | `ownerMessageId` must be the person's message in that thread | Command test |++## Desktop (ASCII mockups, from `thread_panel.dart`, `view.dart` and `message_row.dart`)++Only what changes is drawn. Everything else stays as it is. Words follow the design system: one focal action (Send),+quiet borderless controls in the composer row, `ActivityMark` with words for status, and nothing new in the sidebar.++**1. The thread composer in a Buddy chat, with no session.** **New session** sits on the left of the existing row. When+it is checked, **Also send to the chat** is hidden: a session's thread stays in the thread.++```+┌─Thread──────────────────────────────────[×]┐+│ (Q) quang 10:41 │+│ Measure prod CPU for the last day and say │+│ what changed │+│ │+│┌──────────────────────────────────────────┐│+││Reply ││+││☐ New session ☐ Also send to the chat 📎 ↑││+│└──────────────────────────────────────────┘│+└────────────────────────────────────────────┘+ tooltip on New session: "Answer this thread in its own session, while+ your Buddy keeps answering the chat"+```++**2. At the limit.** The checkbox is disabled and says why.++```+││☐ New session · 3 running, end one first 📎 ↑││+```++**3. A thread with a session.** One line under the header shows which session answers and whether it's working, with+**End session** as a quiet text button. The states are: `Starting…`, `⠋ Working`, `✓ Idle` and `◌ Your Mac is+offline`, each with words.++```+┌─Thread──────────────────────────────────[×]┐+│ ⠋ Own session · Working End session │+│────────────────────────────────────────────│+│ (Q) quang 10:41 │+│ Measure prod CPU for the last day … │+│ 2 replies ──────────────────────────────── │+│ (W) Wren ◆ 10:42 │+│ Reading the last 24 h of pod logs… │+│┌──────────────────────────────────────────┐│+││Reply 📎 ↑││+│└──────────────────────────────────────────┘│+└────────────────────────────────────────────┘+```++**4. The main chat while it works.** The thread line under the root gains the same mark. The main composer is+unchanged, and the main Buddy answers there as usual.++```+│ (Q) quang 10:41 │+│ Measure prod CPU for the last day and say what… │+│ (Q)(W) 2 replies · Last reply 1m ago · ⠋ Own session│+│ (Q) quang 10:43 │+│ what's the PR number for the login fix? │+│ (W) Wren ◆ 10:43 │+│ #2290. │+│┌───────────────────────────────────────────────────┐│+││Message Wren 📎 ↑││+│└───────────────────────────────────────────────────┘│+```++**5. After it ends.** The line under the header says why. **New session** is checked and locked, because a plain reply+there would be refused.++```+│ Session ended: idle for 30 minutes │+...+││☑ New session 📎 ↑││+```++Ruling: no session list in the sidebar or the header. Why: "less is better". The threads are where the sessions are,+and the thread line shows which ones are working. Cost if wrong: with 3 sessions, the person scrolls to find them.++## Design (docs/feature-design-rules.md)++Reviewed revision: ______ Reviewer (another engine): ______++1. **Growth.**++ | Record | Created | Updated | Finished / removed |+ |---|---|---|---|+ | Chat `buddySessions` entry | New session | `agentId` at start | End, idle, failed start, unexpected stop, main Buddy removed, access lost. At most 3, so it can't grow. |+ | Session `Agent` | `agent.started` | liveness, as any agent | `removeAgent`, then `closingSessions` until the host confirms (existing) |+ | Session `AgentStart` | New session | dispatch and start (existing) | Existing start lifecycle (`finishedAt`, purge) |+ | Message `buddySession` tag | each message in a session thread | never | with its message (existing message lifecycle) |+ | Worktree, guard, reads list on the Mac | launch | grant at each person message | `endSession` removes them (existing) |+ | Ended line in the thread | at end | never | with the chat |++ Leave and rejoin: a new membership generation has a new Buddy chat. The old sessions ended when access was lost.+ Recreated under the same key: an entry is keyed by thread and start id, and a new session in the same thread is a+ new start.+2. **Concurrency.** Each New session writes the Buddy chat's group part, which `message.send` writes anyway (its+ message sequence), and that write checks the part's version. So two quick starts on two threads, or two on one thread,+ serialize. The second re-reads and is refused at the limit or as "already has a session".+ - Ending removes the entry in the same group write. A reply racing an end either reaches the session first, and its+ delivery is cancelled with the agent, or it sees no session and is refused.+ - A session's post after its end is refused, because its agent is gone.+ - On the host, each agent's delivery list is claimed on its own, so a busy main session never holds a session's+ delivery, nor the reverse. Test: a delivery held for the main session while a session's delivery is accepted.+ - Thin slice: two concurrent New session sends against a live store; exactly one start.+3. **Read cost.**+ - Routing reads only the chat's `buddySessions` (at most 3 entries), which is already loaded.+ - A session's reads are thread reads on the existing `[tabId, conversationId, thread, sequence]` index.+ - The excerpt is one indexed read of at most 10 main-stream messages before `from`.+ - The main session's reads add `buddySession != true` to the query it already runs.+ - Nothing new per host poll: the host's idle check uses data it already holds.+ - Test: a session's thread read loads only its thread's rows.+ - Removals: an ended session leaves `agentIds` and `buddySessions` through the existing change feed, so Desktop drops+ its marks.+4. **Scale.**+ - At most 3 sessions per person per project.+ - At 10x people, there are 10x Claude processes, each on its own person's Mac. The server holds at most 3 small+ entries per chat.+ - The first warning is sessions refused because the machine is full, and Macs low on memory: each session is one+ Claude Code process (about 300–600 MB).+ - **Where it shows** (security review 1: the usage counters this line first named do not exist, and the fixed usage+ vocabulary is shared with the CLI, so this uses the server log instead). The backend logs three lines with ids only:+ - `Buddy session started` (Swarm and start id);+ - `Buddy session refused` (Swarm and refusal code: `BUDDY_SESSIONS_FULL`, `BUDDY_SESSION_UNSUPPORTED`,+ `BUDDY_SESSION_ENGINE`, `BUDDY_SESSION_NO_BUDDY` and the machine's capacity refusals);+ - `Buddy session ended`, with the reason (`ended`, `idle`, `stopped`, `failed`, `removed`, `maintenance`), logged+ once committed.++ Prod watch reads them from the backend's logs (ArgoCD app logs). The first alarm: refusals for capacity above 10%+ of starts in a day, or `failed` ends above 10% of starts.+5. **Compatibility.** Every reader of a new field, from a search of the code:+ - **Server** (`agentIds[0]` in `commands.ts:2036`; `BUDDY_EXISTS` at `:1632`; `nameTaken` and `renameBuddy` in+ `buddies.ts`; pending-start lookups at `:1597` and `:1633`; `stopIdleWorkers`, which skips Buddies; `deliveryAllowed`;+ `buddyReads`): each picks the main Buddy by `!buddySession`, or counts only the main Buddy. Rename renames both.+ - **Old CLI host:** it doesn't report `buddySessions` in its machine report, so the server refuses New session ("Update+ Harness on <machine> to use sessions"). An old host never runs a session it doesn't understand.+ - **Old Desktop and the phone:**+ - They show a session's replies as ordinary thread replies from the Buddy.+ - Replies in a session thread still reach that session, because the server routes by thread.+ - A plain reply in an ended thread shows `Not sent` with the reason.+ - Sessions end on their own after 30 minutes idle.+ - Old Desktop's own Buddy pickers read `agentIds.first`; the server keeps the main Buddy first in `agentIds`, even+ after a restart.+ - **Phone parity:** `mobile/lib/swarm/model.dart` reads the new fields (`buddySession` on messages and agents, and+ `buddySessions` on conversations), with no UI, so `desktop_parity_test.dart` holds. This is coordinated with Tony,+ whose work is in `mobile/lib/swarm`.+ - **Rolling deploy:** a new client against an old server never sees the host capability, so it never offers New+ session.+6. **Migration and rollback.**+ - No data migration: every field is optional and absent on old rows.+ - Deploy order: backend first, then CLI (hosts report the capability), then Desktop.+ - What the previous release does with each new field and state, if live sessions were left (security review 1: the+ earlier text here was wrong):+ - It ignores `buddySessions`, `buddySession` on agents and starts, and the message tag.+ - It reads each session agent as one more Buddy in the chat:+ - The main Buddy reads session threads again. No other person can read anything, but sessions are no longer kept+ apart.+ - A session may post anywhere in the chat.+ - Its Buddy removal takes the first Buddy it finds, which may be a session, and leaves the others running.+ - A person's message goes to `agentIds[0]`, which this release keeps as the main Buddy.+ - It refuses `buddy.sessionEnd` (an unknown command), so the host can no longer end idle sessions: they would run on+ the person's Mac until their Buddy was removed.+ - New Desktop's `newSession` is refused by its strict schema; the composer shows the error.+ - **So the rollback ends every session first, while this release still runs:**+ 1. `node --import tsx backend/scripts/buddy-sessions/end-all.ts`: a dry run that lists the live sessions by Swarm+ and chat id.+ 2. The same with `--apply`. Each session ends through its own end path, as the chat's person, with reason+ `maintenance`. Its host closes it and deletes its folder, and its thread says "Session ended: Harness was+ updated." This is a prod write, so Ken runs it.+ 3. The dry run again shows none.+ 4. Roll the backend back.++ A session started between steps 2 and 4 would be left: run step 2 again right before step 4. The integration test+ `can all be ended before a rollback` runs steps 1–3 on a live store.+ - Rolling back only the CLI: an older host stops reporting the capability, so New session is refused there. A+ session it already runs is left without the idle end until the Buddy is removed, so the same script runs first.+ - Rolling back only Desktop: the choice disappears, and the server keeps routing by thread.+ - Production check: no migration runs. The read-only anomaly query counts Buddy chats whose `agentIds` hold more+ than one agent today (expected 0), so the main-Buddy-first rule holds on existing data.+7. **Audience.** It doesn't change who can read anything: the chat is still read only by its person. The new rule is+ between that person's own sessions (the Security section). The guards are named for every copy:+ - API reads and the change feed: `buddySessionReads`.+ - The agent's terminal: only its own deliveries.+ - The start record: no text.+ - Logs: ids only.+ - Desktop caches: cleared with the chat on access loss (existing), and a session's marks leave with its agent.+8. **Identity.** A session runs exactly as the main Buddy does:+ - It runs on the person's own machine (`BUDDY_OWN_MACHINE`), under their own account and engine sign-in.+ - Wide mode is never on a Team account.+ - The host's idle end is sent as the machine's owner, who is the Buddy's person; the server checks+ `machineOwnerId === buddyOf.personId`.+ - Anyone else is refused.+9. **Failure.** Who notices each, and what the person sees:++ | Failure | What the person sees | Recovery |+ |---|---|---|+ | Start refused (limit, machine full, old host, Mac offline) | The thread composer says why before sending; the server refuses with the same words | Send without New session, or end a session |+ | Start fails on the Mac | Ended line "couldn't start: <why>" in the thread; the reply stays | New session again |+ | Process stops unexpectedly | Ended line "stopped unexpectedly" | New session again |+ | Mac offline while working | `◌ Your Mac is offline` in the thread line and pane | Replies wait as deliveries; the session resumes or idles out when it returns |+ | Idle end | Ended line "idle for 30 minutes" | New session |+ | Reply to an ended thread | `Not sent` with the reason; Desktop pre-checks New session | Send with New session |+ | Access lost mid-screen | The thread pane closes, and marks and cached rows clear with the chat; in-flight answers are dropped | Existing access-loss path, tested for sessions |+ | A late answer for a replaced thread or chat | Ignored by Desktop (results checked against the open thread and session) | Test |++10. **Platforms.**+ - macOS and Linux: as the main Buddy. Wide mode: macOS, and Linux with bubblewrap.+ - Windows: sessions run with folder-only reads, as its Buddy does.+ - Desktop (macOS, Windows, Linux, web) gets the choice and the marks.+ - The phone shows session replies as thread replies and gets no choice (out of scope; Scholes, 10-30).++## Tests (acceptance checks)++- **Parallel answer** (backend integration plus host): a session holds a long-running delivery while a main-chat+ question is delivered to the main Buddy and answered.+- **Replies stay in the thread:**+ - A session's `post` without `--reply-to`, or to a main-chat message, is refused.+ - `alsoSend` is refused.+ - A person's thread reply is routed to the session only.+- **Stopping:**+ - End session.+ - The host's idle check: 30 minutes with no progress, no deliveries and no messages ends it, and a working session is+ never ended.+ - Removing the Buddy removes its sessions.+ - Each case: the folder, the reads list and the agent are gone.+- **Limit of 3:**+ - The fourth is refused with the reason.+ - Two concurrent starts against a live store make one start.+ - Desktop disables the choice with the reason.+- **Guard identical:** byte compare as above; the wide grant isn't shared in either direction.+- **No cross-thread reads:** every agent read path, for a session and for the main Buddy, with real and made-up ids.+- **Privacy edges (10-29):**+ - Access revoked while the thread pane is open.+ - Ids from another project's or another person's Buddy chat are refused alike, with no title leak.+ - A reused agent id or name across projects.+ - A failed first load of the session line, with a bounded retry and no stuck `Starting…`.+- **Full backend Super Tab integration suite** (`npm run test:super-tabs`) before Ready; CLI Buddy specs; Desktop+ widget tests and light/dark screenshots.++## Open questions (provisional rulings, not waiting on anyone)++- "Thread closed" means **End session**, because threads have no close today. Closing the pane only hides it.+- A session uses the main Buddy's engine and model; there is no picker ("less is better").++## Contract between backend, CLI host and Desktop (build reference)++Records and views:+- `Agent.buddySession?: { thread: string; from: number }`: a thread session. `thread` is the root message id; `from` is+ the sequence of the message that started it. The main Buddy has none.+- `AgentStartRequest.buddySession?`: the same, written only by `message.send` with `newSession`. Never any message text.+- `Conversation.buddySessions?: Array<{ thread: string; startId: string; agentId?: string; at: number }>`: a Buddy chat's+ live or starting sessions, at most 3. `agentId` is set once started.+- `Message.buddySession?: true`: a reply in a session thread, from the person or the session.+- Message `source.kind === 'buddy-session-ended'` with `source.reason` (`ended` | `idle` | `stopped` | `failed`) and+ `source.thread`: the quiet line in the thread when a session ends.+- Machine observation `buddySessions?: true`: the host can run thread sessions. Without it, New session is refused with+ `BUDDY_SESSION_UNSUPPORTED`.++Commands:+- `message.send` takes `newSession?: true`. Refusals:+ - `BUDDY_SESSIONS_FULL`: 3 running.+ - `BUDDY_SESSION_EXISTS`: the thread has one.+ - `BUDDY_SESSION_UNSUPPORTED`: old host.+ - `BUDDY_SESSION_CHAT`: not the person's own Buddy chat, or not a thread reply.+ - `BUDDY_SESSION_NO_BUDDY`: no main Buddy running.++ A plain person reply in a thread whose session ended is refused with `BUDDY_SESSION_ENDED`.+- `buddy.sessionEnd { conversationId, thread, reason: 'ended' | 'idle' | 'stopped' }`: from the chat's person only.+ Desktop sends `ended`. The host on the person's machine sends `idle` and `stopped`. It is idempotent: an already-ended+ thread is a no-op.+- A session agent's `message.send` must reply in its own thread (`BUDDY_SESSION_THREAD`) and can't set `alsoSend`.+ The main Buddy can't reply in a session thread (`BUDDY_SESSION_THREAD`).++Reads:+- A session agent reading its chat gets only its own thread's rows. Read with `thread = its root`, the page also carries+ `context`: up to 10 main-stream rows with sequence ≤ `from`, oldest first, each text cut to 500 characters, 6 KB in all.+- The main Buddy's reads leave out every `buddySession` row, and thread summaries count none of them.+- Project reads (the project chat, workgroups) are the same for every session. Buddy news goes to the main session+ only.++## Changes from the security reviews of e87c2dc++Review 1 said Hold; review 2 passed with two notes. Each change has a test that fails without it.++- **Claude Code only.** The server refuses New session unless the main Buddy runs Claude Code (`BUDDY_SESSION_ENGINE`). The host+ also refuses to launch a session start on any other engine. Codex runs no Buddy guard hook, and a Codex Buddy from before the+ Codex refusal could otherwise have started sessions without one.+- **A session start that fails outside a command** (the pickup and run timeouts in `liveness.ts`) ends through the+ session's own end path (`buddySessions.ts` `endSessionEntry`). Its thread says why, its place frees, and the main chat+ says nothing. It was handled as a failed main Buddy start, telling the person to add their Buddy again.+- **Every end leaves its line**, Buddy removal and replacement included (`removed`), and Desktop locks New session on any+ session reply in a thread, not only on that line.+- **Desktop offers New session only when the server would take it.** Otherwise the choice is disabled with the server's+ reason: the Swarm is paused, the Buddy is down or missing, the Buddy doesn't run Claude Code, or its machine's host lacks+ the `buddySessions` capability. "Ending…" can't be pressed twice, the offline line names the computer, and wrong field+ types never break the read (Desktop and phone).+- **The host's end decision** is worked out again on every pass: an end the backend didn't take is dropped once the+ session has work again. Its operation id names the reason, so a retry is identical.+ - A gap of 2 minutes or more between passes counts as sleep, and the idle clock restarts at wake.+ - Only deliveries still in the host's hands count as work.+- **Ended sessions' folders.** Each Buddy launch writes a self-ignoring `.claude/.gitignore`, never over a project's own, so+ the worktree reads clean and its removal goes through.+- **What a session leaves on the Mac.** When a Claude Code Buddy session ends (main or thread), the host removes its own+ transcript folder, its history lines and the delivered messages those lines name, and nothing of another session's.+ Left: if Harness restarts mid-close, the scrub is skipped.+- **Wide reads.** For a thread session, only its person's message in its own thread grants wide reads or records `run:`+ approvals.+- **Reactions** pass the same session read check as reads (review 2).+- **No main-chat line for a session's start** (review 2). A start warning goes in its thread.+- **Design 4 and 6** now name the log lines that exist and the real rollback steps (above).diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 6fab975b1..943c1064b 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -129,6 +129,8 @@ class SuperTabAgent {{'personId': final String person} => person,_ => null,},+ // Read as the desktop does; the phone draws no thread sessions yet.+ buddySession = SuperTabBuddySessionOf.fromJson(row['buddySession']),limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),alerting = List.unmodifiable((row['alerting'] as List?)?.whereType<String>() ?? const <String>[],@@ -187,10 +189,41 @@ class SuperTabAgent {/// The person whose Buddy it is; null for any other agent.final String? buddyOf;++ /// Set on a Buddy's thread session (desktop model.dart); null otherwise.+ final SuperTabBuddySessionOf? buddySession;final Map<String, dynamic> configuration;String get engine => configuration['engine'] as String? ?? '';}+/// A thread session's thread and starting sequence (desktop model.dart).+class SuperTabBuddySessionOf {+ const SuperTabBuddySessionOf(this.thread, this.from);+ final String thread;+ final int from;++ static SuperTabBuddySessionOf? fromJson(Object? value) {+ if (value is! Map) return null;+ final json = superTabMap(value);+ final thread = json['thread'];+ if (thread is! String || thread.isEmpty) return null;+ final from = json['from'];+ return SuperTabBuddySessionOf(thread, from is num ? from.toInt() : 0);+ }+}++/// One live or starting thread session of a Buddy chat (desktop model.dart).+class SuperTabBuddySession {+ SuperTabBuddySession.fromJson(Map<String, dynamic> json)+ : thread = json['thread'] is String ? json['thread'] as String : '',+ startId = json['startId'] is String ? json['startId'] as String : '',+ agentId = json['agentId'] is String ? json['agentId'] as String : null,+ at = json['at'] is num ? (json['at'] as num).toInt() : 0;+ final String thread, startId;+ final String? agentId;+ final int at;+}+class SuperTabTask {SuperTabTask.fromJson(Map<String, dynamic> row): goal = _text(row, 'goal'),@@ -212,6 +245,12 @@ class SuperTabConversation {kind = row['kind'] as String?,buddyOwnerId = row['buddyOwnerId'] as String?,buddyName = row['buddyName'] as String?,+ buddySessions = List.unmodifiable(+ (row['buddySessions'] is List ? row['buddySessions'] as List : const [])+ .whereType<Map>()+ .map((json) => SuperTabBuddySession.fromJson(superTabMap(json)))+ .where((session) => session.thread.isNotEmpty),+ ),number = (row['number'] as num?)?.toInt(),title = _text(row, 'title'),leadId = row['leadId'] as String?,@@ -274,6 +313,9 @@ class SuperTabConversation {/// The name a Buddy chat's person chose for their Buddy, kept while no/// Buddy runs; null for the default (backend buddies.ts renameBuddy).final String? buddyName;++ /// A Buddy chat's live or starting thread sessions (desktop model.dart).+ final List<SuperTabBuddySession> buddySessions;final SuperTabTask? task;final int? number;String get label => number == null ? title : '#$number $title';@@ -1008,6 +1050,7 @@ class SuperTabMessage {replyTo = row['replyTo'] as String?,thread = row['thread'] as String?,alsoInChat = row['alsoInChat'] == true,+ buddySession = row['buddySession'] == true,sequence = (row['sequence'] as num).toInt(),author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),@@ -1032,6 +1075,9 @@ class SuperTabMessage {/// A thread reply also shown in the conversation's main stream.final bool alsoInChat;++ /// A reply in a Buddy thread session's thread (desktop model.dart).+ final bool buddySession;bool get threadReply => thread != null && thread != id;/// Whether the main stream lists it: a thread reply only when also sent.diff --git a/mobile/test/swarm/swarm_buddy_session_parse_test.dart b/mobile/test/swarm/swarm_buddy_session_parse_test.dartnew file mode 100644index 000000000..19d786a64--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_session_parse_test.dart@@ -0,0 +1,49 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++/// Buddy thread sessions' fields (desktop model.dart, spec 2026-10-30-buddy-+/// thread-sessions): the phone reads them as the desktop does, and a value of+/// an unexpected type never breaks the read.+void main() {+ test('unexpected types in session fields never break the read', () {+ expect(SuperTabBuddySessionOf.fromJson({'thread': 5, 'from': 'x'}), isNull);+ expect(SuperTabBuddySessionOf.fromJson('not a map'), isNull);+ expect(+ SuperTabBuddySessionOf.fromJson({'thread': 'r', 'from': 'x'})!.from,+ 0,+ );+ final odd = SuperTabBuddySession.fromJson({+ 'thread': 'r',+ 'startId': 3,+ 'agentId': 7,+ 'at': 'soon',+ });+ expect([odd.thread, odd.startId, odd.agentId, odd.at], ['r', '', null, 0]);+ Map<String, dynamic> chat(Object? sessions) => {+ 'id': 'c',+ 'kind': 'buddy',+ 'buddyOwnerId': 'p',+ 'title': 'Wren',+ 'agentIds': <String>[],+ 'archived': false,+ 'brief': '',+ 'checks': <dynamic>[],+ 'assignment': null,+ 'lastMessageSequence': 0,+ 'buddySessions': sessions,+ };+ expect(+ SuperTabConversation.fromJson(chat({'thread': 'r'})).buddySessions,+ isEmpty,+ );+ expect(+ SuperTabConversation.fromJson(+ chat([+ 'nope',+ {'thread': 'r', 'startId': 's'},+ ]),+ ).buddySessions.single.startId,+ 's',+ );+ });+}