Skip to content

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

Build Super Tab shared conversations (#1405)

Dee343d517362a9
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
new file mode 100644
index 000000000..04180b33f
--- /dev/null
+++ b/backend/integration/superTabs.test.ts
@@ -0,0 +1,509 @@
+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 Fastify, { type FastifyInstance } from 'fastify'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+let app: FastifyInstance
+const owner: AuthUser = { sub: '100000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const peer: AuthUser = { sub: '100000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const host: AuthUser = { sub: '100000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'codex', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const run = (tab: string, command: Command, user = owner, asAgentId?: string, operationId = randomUUID()) =>
+ store.execute(user, tab, { operationId, command }, asAgentId)
+async function fixture() {
+ const tab = (await store.create(owner, randomUUID(), 'Pilot')).id
+ const lead = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Lead', configuration: config, lead: true })).result.agentId as string
+ return { tab, lead }
+}
+const message = (text: string): Command => ({ type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [] })
+async function invite(tab: string, role: 'collaborator' | 'viewer' = 'collaborator') {
+ const invitation = await run(tab, { type: 'invite.create', email: peer.email, role, conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
+}
+
+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(`super_tab_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 } } })
+ store = new SuperTabStore(db)
+ for (const user of [owner, peer, host]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`,
+ email: user.email, autonomousEnv: user.autonomousEnv } })
+ await db.machine.create({ data: { machineId: 'test-host', userId: host.sub, apiKey: 'fixture-only', managerId: 'fixture',
+ autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machineShare.create({ data: { machineId: 'test-host', ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email, peer.email] } })
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ // External SSO is replaced with three fixture accounts; every permission/transaction below is real.
+ app.addHook('onRequest', async (request, reply) => {
+ const user = [owner, peer, host].find(u => `Bearer ${u.sub}` === request.headers.authorization)
+ if (!user) return reply.code(401).send({ success: false })
+ request.user = user
+ })
+ await app.register(superTabRoutes, { store })
+ await app.ready()
+})
+afterAll(async () => {
+ await app?.close()
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe('Super Tabs on a real Mongo replica set', () => {
+ it('resolves a reply beyond recent history without crossing conversation or membership boundaries', async () => {
+ const { tab, lead } = await fixture()
+ const question = (await run(tab, message('Should pending edits survive restart?'), host, lead)).result.messageId as string
+ for (let i = 0; i < 101; i++) await run(tab, message(`Later update ${i}`), host, lead)
+ expect((await store.messages(host, tab, 'lead', {}, lead)).messages.some(row => row.id === question)).toBe(false)
+ const url = `/api/super-tabs/${tab}/conversations/lead/messages?asAgentId=${lead}&messageId=${question}`
+ const headers = { authorization: `Bearer ${host.sub}` }
+ const original = await app.inject({ url, headers })
+ expect(original.statusCode).toBe(200)
+ expect(original.json().data.messages).toMatchObject([{ id: question, text: 'Should pending edits survive restart?' }])
+ expect(original.json().data.messages).toHaveLength(1)
+ expect((await app.inject({ url: `${url}&before=100`, headers })).statusCode).toBe(400)
+ const group = (await run(tab, { type: 'conversation.create', title: 'Other work', brief: '', checks: [] })).result.conversationId as string
+ expect((await store.messages(host, tab, group, { messageId: question }, lead)).messages).toEqual([])
+ expect((await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages?messageId=${question}`,
+ headers: { authorization: `Bearer ${peer.sub}` } })).statusCode).toBe(403)
+ await run(tab, { type: 'agent.remove', agentId: lead })
+ const removed = await app.inject({ url, headers })
+ expect(removed.statusCode).toBe(409)
+ expect(removed.json().error.code).toBe('AGENT_UNAVAILABLE')
+ })
+
+ it('records native turns once, in order, with verified source metadata and no input echo', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ const request = { operationId: randomUUID(), conversationId: 'lead', agentId: lead }
+ const { contextId } = await store.native.open(peer, tab, request)
+ expect(await store.native.open(peer, tab, request)).toEqual({ contextId })
+ await expect(store.native.read(peer, tab, contextId)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ expect(await store.native.read(host, tab, contextId)).toMatchObject({ agentId: lead, machineId: 'test-host',
+ operator: { id: peer.sub, kind: 'person' }, lastEventId: null })
+ const prompt = { turnId: randomUUID(), kind: 'prompt' as const, previousEventId: null,
+ text: 'A native intervention', truncated: false, interrupted: false }
+ await expect(store.native.append(owner, tab, contextId, prompt)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ const posted = await Promise.all(Array.from({ length: 3 }, () => store.native.append(host, tab, contextId, prompt)))
+ expect(posted[1]).toEqual(posted[0])
+ await expect(store.native.append(host, tab, contextId, { ...prompt, text: 'Changed content' })).rejects.toMatchObject({ code: 'OPERATION_REUSED' })
+ const first = posted[0] as { eventId: string }
+ const answer = { ...prompt, kind: 'answer' as const, text: 'A native answer', interrupted: true }
+ await expect(store.native.append(host, tab, contextId, answer)).rejects.toMatchObject({ code: 'NATIVE_ORDER_CHANGED' })
+ await expect(store.native.append(host, tab, contextId, { ...answer, turnId: randomUUID(), previousEventId: first.eventId }))
+ .rejects.toMatchObject({ code: 'NATIVE_PROMPT_MISSING' })
+ const second = await store.native.append(host, tab, contextId, { ...answer, previousEventId: first.eventId })
+ expect(await store.native.append(host, tab, contextId, prompt)).toEqual(first)
+ const rows = (await store.messages(owner, tab, 'lead', {})).messages
+ expect(rows).toHaveLength(2)
+ expect(rows[0]).toMatchObject({ text: prompt.text, author: { kind: 'agent', id: lead },
+ source: { kind: 'native', phase: 'prompt', operator: { id: peer.sub, kind: 'person' } } })
+ expect(rows[1]).toMatchObject({ replyTo: first.eventId, text: answer.text, source: { interrupted: true, phase: 'answer' } })
+ expect(rows[0]!.source).not.toHaveProperty('contextId')
+ expect(rows[1]!.sequence).toBeGreaterThan(rows[0]!.sequence)
+ expect((await store.native.read(host, tab, contextId)).lastEventId).toBe((second as { eventId: string }).eventId)
+ expect(await store.deliveries(host, tab, lead)).toEqual([])
+ const forged = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/native/${contextId}`,
+ headers: { authorization: `Bearer ${host.sub}` }, payload: { ...prompt, operator: { id: owner.sub } } })
+ expect(forged.statusCode).toBe(400)
+ })
+
+ it('keeps native observations in the chosen group and informs its lead without reviving a withdrawn context', async () => {
+ const { tab, lead } = await fixture()
+ const group = (await run(tab, { type: 'conversation.create', title: 'Implementation', brief: '', checks: [] })).result.conversationId as string
+ const worker = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Builder', configuration: config, lead: false })).result.agentId as string
+ const request = { operationId: randomUUID(), conversationId: group, agentId: worker }
+ const { contextId } = await store.native.open(owner, tab, request)
+ await expect(store.native.open(owner, tab, { ...request, conversationId: 'lead' })).rejects.toMatchObject({ code: 'AGENT_UNAVAILABLE' })
+ const event = { turnId: randomUUID(), kind: 'prompt' as const, previousEventId: null,
+ text: 'Change this implementation', truncated: false, interrupted: false }
+ const receipt = await store.native.append(host, tab, contextId, event) as { eventId: string }
+ expect((await store.messages(owner, tab, 'lead', {})).messages).toHaveLength(0)
+ expect((await store.messages(owner, tab, group, {})).messages).toHaveLength(1)
+ expect(await store.deliveries(host, tab, worker)).toEqual([])
+ const notifications = await store.deliveries(host, tab, lead)
+ expect(notifications).toHaveLength(1)
+ expect(notifications[0]).toMatchObject({ conversationId: group, nativeContextId: contextId, messageId: receipt.eventId })
+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: worker, present: false, lead: false })
+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: worker, present: true, lead: false })
+ await expect(store.native.read(host, tab, contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ await expect(store.native.open(owner, tab, request)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ expect(await store.deliveries(host, tab, lead)).toEqual([])
+ expect((await db.superTabDelivery.findUnique({ where: { id: notifications[0]!.id } }))!.status).toBe('cancelled')
+ expect(await store.native.open(owner, tab, { ...request, operationId: randomUUID() })).not.toEqual({ contextId })
+ })
+
+ it('requires machine control as well as collaboration and fences removal, re-invitation and changed machine grants', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab, 'viewer')
+ const request = { operationId: randomUUID(), conversationId: 'lead', agentId: lead }
+ await expect(store.native.open(peer, tab, request)).rejects.toMatchObject({ code: 'READ_ONLY' })
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ await invite(tab)
+ const { contextId } = await store.native.open(peer, tab, request)
+ const event = { turnId: randomUUID(), kind: 'gap' as const, previousEventId: null,
+ text: 'Caller text must not impersonate a gap explanation', truncated: false, interrupted: false }
+ await store.native.append(host, tab, contextId, event)
+ expect((await store.messages(owner, tab, 'lead', {})).messages[0]!.text).toContain('Some terminal activity could not be recorded')
+ const original = (await db.machineShare.findUnique({ where: { machineId: 'test-host' } }))!
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [owner.email],
+ grantVersions: nextMachineShareGrants(original, [owner.email], null) } })
+ try {
+ await expect(store.native.open(peer, tab, { ...request, operationId: randomUUID() })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ await expect(store.native.read(host, tab, contextId)).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: {
+ emails: original.emails, grantVersions: nextMachineShareGrants({ ...original, emails: [owner.email] }, original.emails, null),
+ } })
+ await expect(store.native.read(host, tab, contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ } finally {
+ const current = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: original.emails,
+ grantVersions: nextMachineShareGrants(current, original.emails, null) } })
+ }
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ await invite(tab)
+ await expect(store.native.read(host, tab, contextId)).rejects.toMatchObject({ code: 'NATIVE_CONTEXT_REVOKED' })
+ })
+
+ it('keeps an ordered configuration history, rejects stale observations and authorizes the execution host alone', async () => {
+ const { tab, lead } = await fixture()
+ await run(tab, { type: 'work.define', conversationId: 'lead', brief: 'A measured result', checks: [{ description: 'Verified evidence', independent: false }] })
+ const assigned = await run(tab, { type: 'work.assign', conversationId: 'lead', agentId: lead })
+ const before = (await store.read(owner, tab)).state.agents[0]!.configurationVersion!
+ const command: Command = { type: 'agent.configuration', previousVersion: before,
+ configuration: { ...config, model: 'observed-model', effort: 'max', contextWindow: null } }
+ await expect(run(tab, command)).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ await expect(run(tab, command, peer, lead)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ const id = randomUUID()
+ const first = await run(tab, command, host, lead, id)
+ expect(await run(tab, command, host, lead, id)).toEqual(first)
+ await expect(run(tab, command, host, lead)).rejects.toMatchObject({ code: 'STALE_CONFIGURATION' })
+ const current = (await store.read(owner, tab)).state.agents[0]!
+ await run(tab, { ...command, previousVersion: current.configurationVersion! }, host, lead)
+ const records = await db.superTabConfiguration.findMany({ where: { tabId: tab, agentId: lead }, orderBy: { revision: 'asc' } })
+ expect(records).toHaveLength(2)
+ expect(records[0]!.configuration).toEqual(config)
+ expect(records[1]).toMatchObject({ configuration: command.configuration, actorKey: `agent:${lead}`, assignmentIds: [assigned.result.assignmentId] })
+ expect((await store.read(owner, tab)).state.conversations[0]!.assignment!.configuration).toEqual(config)
+ const next = { ...command, previousVersion: current.configurationVersion!, configuration: config }
+ const race = await Promise.allSettled([run(tab, next, host, lead), run(tab, { ...next, configuration: { ...config, effort: 'low' } }, host, lead)])
+ expect(race.filter(r => r.status === 'fulfilled')).toHaveLength(1)
+ expect(await db.superTabConfiguration.count({ where: { tabId: tab } })).toBe(3)
+ await run(tab, { type: 'agent.remove', agentId: lead })
+ await expect(run(tab, next, host, lead)).rejects.toMatchObject({ code: 'AGENT_UNAVAILABLE' })
+ expect(await db.superTabConfiguration.count({ where: { tabId: tab } })).toBe(3)
+ })
+
+ it('a withdrawn host can retire its receipt without regaining conversation access', async () => {
+ const { tab, lead } = await fixture()
+ await run(tab, message('Keep the execution receipt after removal.'))
+ const first = (await store.deliveries(host, tab, lead))[0]!
+ await store.delivery(host, tab, lead, first.id, { type: 'claim', claimId: 'claim' })
+ await store.delivery(host, tab, lead, first.id, { type: 'ack', claimId: 'claim', receipt: 'unclear', uncertain: true })
+ await run(tab, { type: 'agent.remove', agentId: lead })
+ expect(await store.deliveryReceipt(host, tab, lead, first.id)).toEqual({ id: first.id, status: 'cancelled' })
+ await expect(store.deliveries(host, tab, lead)).rejects.toMatchObject({ code: 'AGENT_UNAVAILABLE' })
+ await expect(store.deliveryReceipt(peer, tab, lead, first.id)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ // Reassigning the machine does not transfer the former owner's receipts.
+ await db.machine.update({ where: { machineId: 'test-host' }, data: { userId: peer.sub } })
+ try {
+ await expect(store.deliveryReceipt(peer, tab, lead, first.id)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ await expect(store.deliveryReceipt(host, tab, lead, first.id)).rejects.toMatchObject({ code: 'HOST_UNAVAILABLE' })
+ } finally {
+ await db.machine.update({ where: { machineId: 'test-host' }, data: { userId: host.sub } })
+ }
+ })
+
+ it('resolves uncertain input once, preserves native evidence, and fences late host acknowledgements', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ await run(tab, message('Check the exact revision.'))
+ const first = (await store.deliveries(host, tab, lead))[0]!
+ const claimId = randomUUID()
+ await store.delivery(host, tab, lead, first.id, { type: 'claim', claimId })
+ await store.delivery(host, tab, lead, first.id, { type: 'ack', claimId, receipt: 'lost-native-ack', uncertain: true })
+ const resend: Command = { type: 'delivery.resolve', deliveryId: first.id, resolution: 'resend' }
+ await expect(run(tab, resend, host, lead)).rejects.toMatchObject({ code: 'HUMAN_REQUIRED' })
+ const operationId = randomUUID()
+ const repeated = await Promise.all(Array.from({ length: 3 }, () => run(tab, resend, peer, undefined, operationId)))
+ expect(new Set(repeated.map(r => r.result.messageId)).size).toBe(1)
+ const pending = await store.deliveries(host, tab, lead)
+ expect(pending).toHaveLength(1)
+ expect(pending[0]!.id).not.toBe(first.id)
+ expect(await store.deliveryReceipt(host, tab, lead, first.id)).toEqual({ id: first.id, status: 'superseded' })
+ expect((await db.superTabDelivery.findUnique({ where: { id: first.id } }))!.receipt).toBe('lost-native-ack')
+ await expect(run(tab, resend, peer)).rejects.toMatchObject({ code: 'DELIVERY_RESOLVED' })
+ await expect(store.delivery(host, tab, lead, first.id, { type: 'ack', claimId, receipt: 'late', uncertain: false }))
+ .rejects.toMatchObject({ code: 'DELIVERY_RESOLVED' })
+ const rows = (await store.messages(owner, tab, 'lead', {})).messages
+ expect(rows).toHaveLength(2)
+ expect(rows[1]!.text).toBe(rows[0]!.text)
+ expect(rows[1]!.replyTo).toBe(rows[0]!.id)
+ expect(rows[1]!.author).toMatchObject({ id: peer.sub, kind: 'person' })
+ const second = pending[0]!
+ await store.delivery(host, tab, lead, second.id, { type: 'claim', claimId: 'second-claim' })
+ await store.delivery(host, tab, lead, second.id, { type: 'ack', claimId: 'second-claim', receipt: 'unclear', uncertain: true })
+ await run(tab, { type: 'delivery.resolve', deliveryId: second.id, resolution: 'received' })
+ expect(await store.deliveries(host, tab, lead)).toEqual([])
+ expect(await store.deliveryReceipt(host, tab, lead, second.id)).toEqual({ id: second.id, status: 'confirmed' })
+ await expect(store.deliveryReceipt(peer, tab, lead, second.id)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ expect((await store.messages(owner, tab, 'lead', {})).messages.at(-1)!.text).toContain('confirmed')
+ })
+
+ it('a viewer cannot resolve input and a changed machine grant cannot be used to resend it', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab, 'viewer')
+ await run(tab, message('Do not replay after revocation.'))
+ const delivery = (await store.deliveries(host, tab, lead))[0]!
+ await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: 'claim' })
+ await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId: 'claim', receipt: 'unclear', uncertain: true })
+ const command: Command = { type: 'delivery.resolve', deliveryId: delivery.id, resolution: 'resend' }
+ await expect(run(tab, command, peer)).rejects.toMatchObject({ code: 'READ_ONLY' })
+ const share = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [] } })
+ try {
+ await expect(run(tab, command)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ await run(tab, { ...command, resolution: 'cancel' })
+ expect((await db.superTabDelivery.findUnique({ where: { id: delivery.id } }))!.status).toBe('cancelled')
+ } finally {
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: share.emails } })
+ }
+ })
+
+ it('commits exactly one tab and message under concurrent retries and rejects reused operation IDs', async () => {
+ const operationId = randomUUID()
+ const created = await Promise.all(Array.from({ length: 5 }, () => store.create(owner, operationId, 'Concurrent')))
+ expect(new Set(created.map(c => c.id)).size).toBe(1)
+ await expect(store.create(owner, operationId, 'Different')).rejects.toMatchObject({ code: 'OPERATION_REUSED' })
+ const { tab, lead } = await fixture()
+ const sendId = randomUUID()
+ const sends = await Promise.all(Array.from({ length: 5 }, () => run(tab, message('Exactly once.'), owner, undefined, sendId)))
+ expect(new Set(sends.map(s => s.result.messageId)).size).toBe(1)
+ expect(await db.superTabMessage.count({ where: { tabId: tab } })).toBe(1)
+ expect(await store.deliveries(host, tab, lead)).toHaveLength(1)
+ await expect(run(tab, message('Different'), owner, undefined, sendId)).rejects.toMatchObject({ code: 'OPERATION_REUSED' })
+ })
+
+ it('joins without machine access, permits viewers to leave, and denies stale access after removal', async () => {
+ const { tab } = await fixture()
+ await expect(store.read(peer, tab)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ await invite(tab, 'viewer')
+ expect((await store.read(peer, tab)).state.people).toHaveLength(2)
+ await expect(run(tab, message('Run this.'), peer)).rejects.toMatchObject({ code: 'READ_ONLY' })
+ const operationId = randomUUID()
+ const leave: Command = { type: 'member.remove', userId: peer.sub }
+ await run(tab, leave, peer, undefined, operationId)
+ await run(tab, leave, peer, undefined, operationId)
+ await expect(store.read(peer, tab)).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ await expect(store.read({ ...owner, autonomousEnv: 'stag' }, tab)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+
+ it('durably resumes a claim, never steals it on timeout, and does not resurrect revoked messages on rejoin', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ await run(tab, message('Instruction from a collaborator.'), peer)
+ const delivery = (await store.deliveries(host, tab, lead))[0]!
+ const claimId = randomUUID()
+ const first = await store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId })
+ expect(first.delivery.status).toBe('claimed')
+ // Simulate a backend restart: no in-memory object carries delivery ownership.
+ const restarted = new SuperTabStore(db)
+ expect((await restarted.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId })).message!.text).toContain('collaborator')
+ await expect(restarted.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() })).rejects.toMatchObject({ code: 'CLAIM_CONFLICT' })
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ await invite(tab)
+ expect(await store.deliveries(host, tab, lead)).toHaveLength(0)
+ await expect(store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId, receipt: 'receipt', uncertain: false })).rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })
+ expect((await store.messages(owner, tab, 'lead', {})).messages).toHaveLength(1)
+ })
+
+ it('allows one claim winner and preserves the original native receipt', async () => {
+ const { tab, lead } = await fixture()
+ await run(tab, message('One native turn.'))
+ const delivery = (await store.deliveries(host, tab, lead))[0]!
+ const claims = await Promise.allSettled([randomUUID(), randomUUID()].map(claimId => store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId })))
+ expect(claims.filter(r => r.status === 'fulfilled')).toHaveLength(1)
+ const won = claims.find(r => r.status === 'fulfilled')!
+ if (won.status !== 'fulfilled') throw new Error('No claim winner')
+ const claimId = won.value.delivery.claimId!
+ await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId, receipt: 'native-turn-1', uncertain: false })
+ await store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId, receipt: 'native-turn-1', uncertain: false })
+ await expect(store.delivery(host, tab, lead, delivery.id, { type: 'ack', claimId, receipt: 'different', uncertain: false })).rejects.toMatchObject({ code: 'RECEIPT_CONFLICT' })
+ expect(await store.deliveries(host, tab, lead)).toHaveLength(0)
+ })
+
+ it('serializes revocation against claims and exposes no pending instruction after removal', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ await run(tab, message('Racing with removal.'), peer)
+ const delivery = (await store.deliveries(host, tab, lead))[0]!
+ const results = await Promise.allSettled([
+ store.delivery(host, tab, lead, delivery.id, { type: 'claim', claimId: randomUUID() }),
+ run(tab, { type: 'member.remove', userId: peer.sub }),
+ ])
+ expect(results[1]!.status).toBe('fulfilled')
+ expect(await store.deliveries(host, tab, lead)).toHaveLength(0)
+ expect((await db.superTabDelivery.findUnique({ where: { id: delivery.id } }))!.status).toBe('cancelled')
+ })
+
+ it('holds a cross-tab assignment until host-confirmed stop and retains the previous attempt', async () => {
+ const one = await fixture()
+ const two = await fixture()
+ const session = randomUUID()
+ const attach: Command = { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: session,
+ name: 'Worker', configuration: config, lead: false }
+ const worker = (await run(one.tab, attach)).result.agentId as string
+ await run(two.tab, attach)
+ const define: Command = { type: 'work.define', conversationId: 'lead', brief: 'Check the fixture.', checks: [{ description: 'Test passes.', independent: true }] }
+ await run(one.tab, define); await run(two.tab, define)
+ const assignmentId = (await run(one.tab, { type: 'work.assign', conversationId: 'lead', agentId: worker })).result.assignmentId as string
+ await expect(run(two.tab, { type: 'work.assign', conversationId: 'lead', agentId: worker })).rejects.toMatchObject({ code: 'AGENT_BUSY' })
+ await run(one.tab, { type: 'agent.remove', agentId: worker })
+ expect(await store.hostAssignments(host, 'test-host')).toContainEqual({ tabId: one.tab, assignmentId, harnessId: session })
+ await expect(store.hostAssignments(owner, 'test-host')).rejects.toMatchObject({ code: 'HOST_UNAVAILABLE' })
+ await expect(store.stopped(owner, one.tab, assignmentId, 'forged')).rejects.toMatchObject({ code: 'FORBIDDEN' })
+ await store.stopped(host, one.tab, assignmentId, 'native-stop-receipt')
+ expect((await store.read(owner, one.tab)).state.conversations[0]!.assignment?.status).toBe('stopped')
+ await store.stopped(host, one.tab, assignmentId, 'native-stop-receipt')
+ expect(await store.hostAssignments(host, 'test-host')).not.toContainEqual({ tabId: one.tab, assignmentId, harnessId: session })
+ expect(await db.superTabDelivery.count({ where: { tabId: one.tab, assignmentId, status: 'queued' } })).toBe(0)
+ await run(two.tab, { type: 'work.assign', conversationId: 'lead', agentId: worker })
+ await run(one.tab, define)
+ expect((await db.superTabAttempt.findUnique({ where: { id: assignmentId } }))!.snapshot).toMatchObject({ assignment: { status: 'stopped', configuration: config } })
+ })
+
+ it('rejects unshared hosts and spoofed agent identities through the HTTP API', async () => {
+ const { tab, lead } = await fixture()
+ const headers = { authorization: `Bearer ${owner.sub}` }
+ expect((await app.inject({ url: `/api/super-tabs/${tab}` })).statusCode).toBe(401)
+ expect((await app.inject({ url: `/api/super-tabs/${tab}`, headers })).statusCode).toBe(200)
+ expect((await app.inject({ url: `/api/super-tabs/${tab}?asAgentId=${lead}`, headers })).statusCode).toBe(403)
+ const malformed = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers,
+ payload: { operationId: randomUUID(), command: { ...message('No spoofing.'), contributorId: owner.sub } } })
+ expect(malformed.statusCode).toBe(400)
+ await db.machine.create({ data: { machineId: 'private-host', userId: peer.sub, apiKey: 'private-fixture', managerId: 'fixture', autonomousEnv: 'prod' } })
+ await expect(run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'private-host', harnessId: 'private', name: 'Private', configuration: config, lead: false })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ const post = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/commands`, headers,
+ payload: { operationId: randomUUID(), command: message('A shared conversation.') } })
+ expect(post.statusCode).toBe(200)
+ const history = await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages`, headers })
+ expect(history.json().data.messages[0].text).toBe('A shared conversation.')
+ })
+
+ it('rechecks the machine share at delivery even while the contributor remains in the tab', async () => {
+ const { tab } = await fixture()
+ await invite(tab)
+ const agentId = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Peer worker', configuration: config, lead: false }, peer)).result.agentId as string
+ await run(tab, { ...message('Only on an authorized machine.'), recipientIds: [agentId] } as Command)
+ expect(await store.deliveries(host, tab, agentId)).toHaveLength(1)
+ try {
+ const before = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [owner.email],
+ grantVersions: nextMachineShareGrants(before, [owner.email], null) } })
+ expect((await store.read(peer, tab)).state.people).toHaveLength(2)
+ await expect(store.deliveries(host, tab, agentId)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ } finally {
+ const before = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [owner.email, peer.email],
+ grantVersions: nextMachineShareGrants(before, [owner.email, peer.email], null) } })
+ }
+ // The host may have been offline throughout the revocation. A restored share
+ // still cannot revive a contribution made under the earlier grant.
+ await expect(store.deliveries(host, tab, agentId)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ })
+
+ it('also withholds outgoing instructions from an agent whose machine grant was revoked', async () => {
+ const { tab, lead } = await fixture()
+ await invite(tab)
+ const worker = (await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'test-host', harnessId: randomUUID(),
+ name: 'Peer worker', configuration: config, lead: false }, peer)).result.agentId as string
+ await store.execute(host, tab, { operationId: randomUUID(), command: { ...message('Delegated before revocation.'), recipientIds: [worker] } as Command }, lead)
+ const [delivery] = await store.deliveries(host, tab, worker)
+ expect(delivery).toBeTruthy()
+ const before = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ try {
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [peer.email],
+ grantVersions: nextMachineShareGrants(before, [peer.email], null) } })
+ expect(await store.deliveries(host, tab, worker)).toEqual([])
+ await expect(store.delivery(host, tab, worker, delivery!.id, { type: 'claim', claimId: randomUUID() })).rejects.toMatchObject({ code: 'DELIVERY_REVOKED' })
+ } finally {
+ const current = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [owner.email, peer.email],
+ grantVersions: nextMachineShareGrants(current, [owner.email, peer.email], null) } })
+ }
+ expect(await store.deliveries(host, tab, worker)).toEqual([])
+ })
+
+ it('derives session-only observer access from accepted membership and removes it with that membership', async () => {
+ const { tab, lead } = await fixture()
+ const state = (await store.read(owner, tab)).state
+ const native = state.agents.find(a => a.id === lead)!.harnessId
+ expect(await store.mayObserve(peer, tab, 'test-host', native, host.sub)).toBe(false)
+ await invite(tab, 'viewer')
+ expect(await store.mayObserve(peer, tab, 'test-host', native, host.sub)).toBe(true)
+ expect(await store.mayObserve(peer, tab, 'test-host', 'another-session', host.sub)).toBe(false)
+ const grants = (await store.hostTabs(host, 'test-host')).find(t => t.tabId === tab)
+ expect(grants?.observers).toContainEqual({ email: peer.email, userId: peer.sub })
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ expect(await store.mayObserve(peer, tab, 'test-host', native, host.sub)).toBe(false)
+ expect((await store.hostTabs(host, 'test-host')).find(t => t.tabId === tab)?.observers).not.toContainEqual({ email: peer.email, userId: peer.sub })
+ })
+
+ it('serializes native start claims and fences a restored target-machine grant', async () => {
+ const { tab } = await fixture()
+ const request = { conversationId: 'lead', machineId: 'test-host', engine: 'claude', name: 'Builder', cwd: '/fixture/repo', worktree: true,
+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }
+ const intent = randomUUID()
+ const starts = await Promise.all(Array.from({ length: 3 }, () => run(tab, { type: 'agent.start', request }, owner, undefined, intent)))
+ const startId = starts[0]!.result.startId as string
+ expect(new Set(starts.map(s => s.result.startId)).size).toBe(1)
+ expect((await store.read(owner, tab)).state.starts).toHaveLength(1)
+ const claims = await Promise.allSettled(Array.from({ length: 2 }, () => run(tab, { type: 'agent.startDispatch', startId })))
+ expect(claims.filter(c => c.status === 'fulfilled')).toHaveLength(1)
+ expect((await store.start(owner, tab, startId)).dispatched).toBe(true)
+ const original = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ try {
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [peer.email],
+ grantVersions: nextMachineShareGrants(original, [peer.email], null) } })
+ await expect(store.start(owner, tab, startId)).rejects.toMatchObject({ code: 'HOST_REQUIRED' })
+ } finally {
+ const current = await db.machineShare.findUniqueOrThrow({ where: { machineId: 'test-host' } })
+ await db.machineShare.update({ where: { machineId: 'test-host' }, data: { emails: [owner.email, peer.email],
+ grantVersions: nextMachineShareGrants(current, [owner.email, peer.email], null) } })
+ }
+ await expect(store.start(owner, tab, startId)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ await expect(run(tab, { type: 'agent.started', startId, harnessId: 'must-not-join', configuration: config })).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ })
+
+ it('does not authorize a host through a contributor’s obsolete email address', async () => {
+ const { tab, lead } = await fixture()
+ await run(tab, message('Requires the current machine grant.'))
+ try {
+ await db.user.update({ where: { id: owner.sub }, data: { email: '[email protected]' } })
+ await expect(store.deliveries(host, tab, lead)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })
+ } finally {
+ await db.user.update({ where: { id: owner.sub }, data: { email: owner.email } })
+ }
+ })
+})
diff --git a/backend/package-lock.json b/backend/package-lock.json
index f82c816b3..e3df75725 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -28,6 +28,7 @@
"@vitest/coverage-v8": "4.1.11",
"concurrently": "^9.1.2",
"esbuild": "^0.27.2",
+ "mongodb-memory-server-core": "^10.4.3",
"prisma": "^5.22.0",
"tsx": "^4.16.2",
"typescript": "^5.5.3",
@@ -746,6 +747,16 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@mongodb-js/saslprep": {
+ "version": "1.6.1",
+ "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.1.tgz",
+ "integrity": "sha512-D4CQtk9IwjCLAvCf1xvHEod3960q8XMUzfmdRU9qjUNlHnesGuTOvJcOTaPm9koZ1caUKA2aTbszZiAkcmSgmg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "sparse-bitfield": "^3.0.3"
+ }
+ },
"node_modules/@noble/curves": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-2.4.0.tgz",
@@ -1170,6 +1181,23 @@
"undici-types": "~6.21.0"
}
},
+ "node_modules/@types/webidl-conversions": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.3.tgz",
+ "integrity": "sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/whatwg-url": {
+ "version": "11.0.5",
+ "resolved": "https://registry.npmjs.org/@types/whatwg-url/-/whatwg-url-11.0.5.tgz",
+ "integrity": "sha512-coYR071JRaHa+xoEvvYqvnIHaVqaYrLPbsufM9BF63HkwI5Lgmy2QR8Q5K/lYDYo5AK82wOvSOS0UsLTpTG7uQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/webidl-conversions": "*"
+ }
+ },
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
@@ -1329,6 +1357,16 @@
"integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
"license": "MIT"
},
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/ajv": {
"version": "8.20.0",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
@@ -1426,6 +1464,16 @@
"js-tokens": "^10.0.0"
}
},
+ "node_modules/async-mutex": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/async-mutex/-/async-mutex-0.5.0.tgz",
+ "integrity": "sha512-1A94B18jkJ3DYq284ohPxoXbfTA5HsQ7/Mf4DEhcyLx3Bz27Rh59iScbB6EPiP+B+joue6YCxcMXSbFC1tZKwA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
"node_modules/atomic-sleep": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz",
@@ -1455,6 +1503,129 @@
"fastq": "^1.17.1"
}
},
+ "node_modules/b4a": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
+ "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
+ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.4.tgz",
+ "integrity": "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz",
+ "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.4",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
+ "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.5",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.5.tgz",
+ "integrity": "sha512-iM9qJCruvpt2rPaLsrumVDru9pogI7PHziHIa9kTNRFt8C8HuSa+kI9kFezK+NvHEFnnz71rKGZ1EAilq/3V/Q==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/bson": {
+ "version": "6.10.4",
+ "resolved": "https://registry.npmjs.org/bson/-/bson-6.10.4.tgz",
+ "integrity": "sha512-WIsKqkSC0ABoBJuT1LEX+2HEvNmNKKgnTAyd0fL8qzK4SH2i9NXg+t08YtdZp/V9IZ33cxe3iV4yM0qg8lMQng==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=16.20.1"
+ }
+ },
+ "node_modules/camelcase": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz",
+ "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
@@ -1539,6 +1710,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/commondir": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/commondir/-/commondir-1.0.1.tgz",
+ "integrity": "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/concurrently": {
"version": "9.2.4",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.2.4.tgz",
@@ -1723,6 +1901,16 @@
"integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==",
"license": "MIT"
},
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
@@ -1745,6 +1933,13 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"license": "MIT"
},
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/fast-json-stringify": {
"version": "7.0.1",
"resolved": "https://registry.npmjs.org/fast-json-stringify/-/fast-json-stringify-7.0.1.tgz",
@@ -1870,6 +2065,50 @@
}
}
},
+ "node_modules/find-cache-dir": {
+ "version": "3.3.2",
+ "resolved": "https://registry.npmjs.org/find-cache-dir/-/find-cache-dir-3.3.2.tgz",
+ "integrity": "sha512-wXZV5emFEjrridIgED11OoUKLxiYjAcqot/NJdAkOhlJ+vGzwhOAfcG5OX1jP+S0PcjEn8bdMJv+g2jwQ3Onig==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "commondir": "^1.0.1",
+ "make-dir": "^3.0.2",
+ "pkg-dir": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/avajs/find-cache-dir?sponsor=1"
+ }
+ },
+ "node_modules/find-cache-dir/node_modules/make-dir": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
+ "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "semver": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/find-cache-dir/node_modules/semver": {
+ "version": "6.3.1",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
+ "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ }
+ },
"node_modules/find-my-way": {
"version": "9.9.0",
"resolved": "https://registry.npmjs.org/find-my-way/-/find-my-way-9.9.0.tgz",
@@ -1884,6 +2123,20 @@
"node": ">=20"
}
},
+ "node_modules/find-up": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz",
+ "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "locate-path": "^5.0.0",
+ "path-exists": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/follow-redirects": {
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz",
@@ -1960,6 +2213,20 @@
"node": ">=8.0.0"
}
},
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
"node_modules/ioredis": {
"version": "5.11.1",
"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.11.1.tgz",
@@ -2383,6 +2650,19 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/locate-path": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
+ "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-locate": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/magic-string": {
"version": "0.30.21",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
@@ -2421,6 +2701,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/memory-pager": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/memory-pager/-/memory-pager-1.5.0.tgz",
+ "integrity": "sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/mnemonist": {
"version": "0.40.0",
"resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.40.0.tgz",
@@ -2430,6 +2717,88 @@
"obliterator": "^2.0.4"
}
},
+ "node_modules/mongodb": {
+ "version": "6.21.0",
+ "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-6.21.0.tgz",
+ "integrity": "sha512-URyb/VXMjJ4da46OeSXg+puO39XH9DeQpWCslifrRn9JWugy0D+DvvBvkm2WxmHe61O/H19JM66p1z7RHVkZ6A==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@mongodb-js/saslprep": "^1.3.0",
+ "bson": "^6.10.4",
+ "mongodb-connection-string-url": "^3.0.2"
+ },
+ "engines": {
+ "node": ">=16.20.1"
+ },
+ "peerDependencies": {
+ "@aws-sdk/credential-providers": "^3.188.0",
+ "@mongodb-js/zstd": "^1.1.0 || ^2.0.0",
+ "gcp-metadata": "^5.2.0",
+ "kerberos": "^2.0.1",
+ "mongodb-client-encryption": ">=6.0.0 <7",
+ "snappy": "^7.3.2",
+ "socks": "^2.7.1"
+ },
+ "peerDependenciesMeta": {
+ "@aws-sdk/credential-providers": {
+ "optional": true
+ },
+ "@mongodb-js/zstd": {
+ "optional": true
+ },
+ "gcp-metadata": {
+ "optional": true
+ },
+ "kerberos": {
+ "optional": true
+ },
+ "mongodb-client-encryption": {
+ "optional": true
+ },
+ "snappy": {
+ "optional": true
+ },
+ "socks": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/mongodb-connection-string-url": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-3.0.2.tgz",
+ "integrity": "sha512-rMO7CGo/9BFwyZABcKAWL8UJwH/Kc2x0g72uhDWzG48URRax5TCIcJ7Rc3RZqffZzO/Gwff/jyKwCU9TN8gehA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@types/whatwg-url": "^11.0.2",
+ "whatwg-url": "^14.1.0 || ^13.0.0"
+ }
+ },
+ "node_modules/mongodb-memory-server-core": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/mongodb-memory-server-core/-/mongodb-memory-server-core-10.4.3.tgz",
+ "integrity": "sha512-IPjlw73IoSYopnqBibQKxmAXMbOEPf5uGAOsBcaUiNH/TOI7V19WO+K7n5KYtnQ9FqzLGLpvwCGuPOTBSg4s5Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "async-mutex": "^0.5.0",
+ "camelcase": "^6.3.0",
+ "debug": "^4.4.3",
+ "find-cache-dir": "^3.3.2",
+ "follow-redirects": "^1.15.11",
+ "https-proxy-agent": "^7.0.6",
+ "mongodb": "^6.9.0",
+ "new-find-package-json": "^2.0.0",
+ "semver": "^7.7.3",
+ "tar-stream": "^3.1.7",
+ "tslib": "^2.8.1",
+ "yauzl": "^3.2.0"
+ },
+ "engines": {
+ "node": ">=16.20.1"
+ }
+ },
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
@@ -2455,6 +2824,19 @@
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
+ "node_modules/new-find-package-json": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/new-find-package-json/-/new-find-package-json-2.0.0.tgz",
+ "integrity": "sha512-lDcBsjBSMlj3LXH2v/FW3txlh2pYTjmbOXPYJD93HI5EwuLzI11tdHSIpUMmfq/IOsldj4Ps8M8flhm+pCK4Ew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">=12.22.0"
+ }
+ },
"node_modules/obliterator": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/obliterator/-/obliterator-2.0.5.tgz",
@@ -2484,6 +2866,55 @@
"node": ">=14.0.0"
}
},
+ "node_modules/p-limit": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz",
+ "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-try": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/p-locate": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz",
+ "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "p-limit": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/p-try": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz",
+ "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/path-exists": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
+ "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
@@ -2491,6 +2922,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/pend": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -2548,6 +2986,19 @@
"integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==",
"license": "MIT"
},
+ "node_modules/pkg-dir": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz",
+ "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "find-up": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.28",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
@@ -2613,6 +3064,16 @@
],
"license": "MIT"
},
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/quick-format-unescaped": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
@@ -2847,6 +3308,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/sparse-bitfield": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/sparse-bitfield/-/sparse-bitfield-3.0.3.tgz",
+ "integrity": "sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "memory-pager": "^1.0.2"
+ }
+ },
"node_modules/split2": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz",
@@ -2876,6 +3347,18 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/streamx": {
+ "version": "2.28.1",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",
+ "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
@@ -2920,6 +3403,39 @@
"url": "https://github.com/chalk/supports-color?sponsor=1"
}
},
+ "node_modules/tar-stream": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz",
+ "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.9.0",
+ "bare-fs": "^4.8.2",
+ "fast-fifo": "^1.3.2",
+ "streamx": "^2.28.1"
+ }
+ },
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
"node_modules/thread-stream": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz",
@@ -2991,6 +3507,19 @@
"node": ">=20"
}
},
+ "node_modules/tr46": {
+ "version": "5.1.1",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
+ "integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/tree-kill": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
@@ -3699,6 +4228,30 @@
}
}
},
+ "node_modules/webidl-conversions": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
+ "integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "14.2.0",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
+ "integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tr46": "^5.1.0",
+ "webidl-conversions": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -3794,6 +4347,19 @@
"node": ">=12"
}
},
+ "node_modules/yauzl": {
+ "version": "3.4.0",
+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz",
+ "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "pend": "~1.2.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/zod": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.5.4.tgz",
diff --git a/backend/package.json b/backend/package.json
index 5bd589de8..b236dab6b 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -22,6 +22,7 @@
"start:local": "concurrently -k -n server,worker -c cyan,magenta \"node dist/server.js\" \"node dist/worker.js\"",
"test": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run",
"test:watch": "vitest",
+ "test:super-tabs": "vitest run --config vitest.super-tabs.config.ts",
"test:agent-messages": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run src/lib/agentMessageShares.test.ts src/routes/agentMessages.test.ts src/lib/agentMessagesWs.test.ts --coverage --coverage.include=src/lib/agentMessageShares.ts --coverage.include=src/routes/agentMessages.ts --coverage.include=src/lib/agentMessagesWs.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.functions=100 --coverage.thresholds.branches=100",
"test:sharing": "NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= vitest run src/routes/harnessShares.test.ts src/routes/harnessLinks.test.ts src/lib/observerWs.test.ts --coverage --coverage.include=src/routes/harnessShares.ts --coverage.include=src/routes/harnessLinks.ts --coverage.include=src/lib/observerWs.ts --coverage.thresholds.lines=100 --coverage.thresholds.statements=100 --coverage.thresholds.branches=100 --coverage.thresholds.functions=100",
"postinstall": "prisma generate"
@@ -46,6 +47,7 @@
"@vitest/coverage-v8": "4.1.11",
"concurrently": "^9.1.2",
"esbuild": "^0.27.2",
+ "mongodb-memory-server-core": "^10.4.3",
"prisma": "^5.22.0",
"tsx": "^4.16.2",
"typescript": "^5.5.3",
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index f97ed04ec..c3aa69ccb 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -817,6 +817,8 @@ model HarnessReview {
/// Discovery metadata for one account-bound, view-only invitation. Content remains on the owner
/// daemon, which independently authorizes every observer against its durable local grant list.
model HarnessShare {
+ /// A session view derived from this Super Tab; membership is rechecked at admission.
+ superTabId String?
id String @id @map("_id")
ownerId String
machineId String
@@ -852,6 +854,9 @@ model MachineShare {
/// The owner's email domain while "Everyone at @domain" is on; null when off. Written by the backend
/// from the owner's verified address, never taken from the client, and never a public domain.
domain String?
+ /// Stable while an email/domain grant continues; a removed and restored grant
+ /// gets a new version so old Super Tab contributions cannot resume silently.
+ grantVersions Json?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@ -975,6 +980,141 @@ model AgentMessageMember {
}
/// Explicit account opt-ins; missing choices stay off. Each write changes one feature.
+// Super Tabs own their roster and history independently of desktop pane layout. Revision writes
+// serialize membership changes, commands and delivery claims inside Mongo transactions.
+model SuperTab {
+ id String @id @map("_id")
+ ownerId String
+ autonomousEnv String
+ memberIds String[]
+ invitedEmails String[]
+ machineIds String[]
+ revision Int @default(0)
+ state Json
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([autonomousEnv, memberIds])
+ @@index([autonomousEnv, invitedEmails])
+ @@index([autonomousEnv, machineIds])
+}
+
+model SuperTabMessage {
+ id String @id @map("_id")
+ tabId String
+ conversationId String
+ sequence Int
+ author Json
+ source Json?
+ text String
+ replyTo String?
+ recipientIds String[]
+ createdAt DateTime @default(now())
+
+ @@index([tabId, conversationId, sequence])
+}
+
+model SuperTabOperation {
+ id String @id @map("_id")
+ tabId String
+ actorKey String
+ requestHash String
+ revision Int
+ result Json
+ createdAt DateTime @default(now())
+
+ @@index([tabId])
+}
+
+// A conversation-scoped provenance receipt. It grants no terminal access.
+// Only the recorded execution host can append observations, and every append
+// rechecks the person's membership and both machine grants.
+model SuperTabNativeContext {
+ id String @id @map("_id")
+ tabId String
+ conversationId String
+ agentId String
+ userId String
+ binding Json
+ lastEventId String?
+ revoked Boolean @default(false)
+ createdAt DateTime @default(now())
+
+ @@index([tabId, revoked])
+}
+
+model SuperTabDelivery {
+ id String @id @map("_id")
+ tabId String
+ conversationId String
+ messageId String
+ nativeContextId String?
+ assignmentId String?
+ agentId String
+ machineId String
+ machineOwnerId String?
+ membershipGeneration String
+ authorKind String
+ authorId String
+ authorGeneration String
+ status String @default("queued")
+ claimId String?
+ receipt String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([tabId, agentId, status, createdAt])
+ @@index([machineId, status])
+}
+
+// One independent harness owns at most one active assignment across all Super Tabs.
+model SuperTabRun {
+ id String @id @map("_id")
+ tabId String
+ assignmentId String @unique
+ machineId String
+ harnessId String
+ createdAt DateTime @default(now())
+}
+
+model SuperTabAttempt {
+ id String @id @map("_id")
+ tabId String
+ conversationId String
+ snapshot Json
+ createdAt DateTime @default(now())
+
+ @@index([tabId, conversationId, createdAt])
+}
+
+model SuperTabStopReceipt {
+ id String @id @map("_id")
+ tabId String
+ assignmentId String
+ machineId String
+ harnessId String
+ machineOwnerId String
+ receipt String
+ createdAt DateTime @default(now())
+
+ @@unique([tabId, assignmentId])
+}
+
+// Configuration observations stay outside the tab snapshot so a long-running
+// assignment keeps its complete history without making every tab read grow.
+model SuperTabConfiguration {
+ id String @id @map("_id")
+ tabId String
+ agentId String
+ revision Int
+ configuration Json
+ assignmentIds String[]
+ actorKey String
+ observedAt DateTime
+
+ @@index([tabId, agentId, revision])
+}
+
model ExperimentalSettings {
id String @id @map("_id") @db.ObjectId
userId String
diff --git a/backend/src/lib/machineAccess.test.ts b/backend/src/lib/machineAccess.test.ts
index 13cdacea3..561dbb5af 100644
--- a/backend/src/lib/machineAccess.test.ts
+++ b/backend/src/lib/machineAccess.test.ts
@@ -17,7 +17,7 @@ import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'
const pub = (n: number) => Buffer.alloc(32, n).toString('base64')
const kim = { sub: 'kim', email: ' [email protected] ', role: 'user', autonomousEnv: 'prod' as const }
const share = (patch: Record<string, unknown> = {}) => ({ id: 's1', machineId: 'm1', ownerId: 'owner', autonomousEnv: 'prod',
- emails: [] as string[], domain: null as string | null, createdAt: new Date(), updatedAt: new Date(), ...patch })
+ emails: [] as string[], domain: null as string | null, grantVersions: null, createdAt: new Date(), updatedAt: new Date(), ...patch })
const machine = (patch: Record<string, unknown> = {}) => ({ machineId: 'm1', userId: 'owner', autonomousEnv: 'prod', name: 'Studio',
hostname: 'studio.local', billingStatus: 'not_required', ...patch })
diff --git a/backend/src/lib/machineAccess.ts b/backend/src/lib/machineAccess.ts
index 19379a58b..ed805713a 100644
--- a/backend/src/lib/machineAccess.ts
+++ b/backend/src/lib/machineAccess.ts
@@ -18,23 +18,15 @@ import { activeMachineKeys } from './deviceKeyLog.js'
import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'
import { storedAutonomousEnvironment } from './autonomousEnvironment.js'
import type { AuthUser } from './ssoAuth.js'
+import { sharedVia, type ShareVia } from './machineSharePolicy.js'
-export type ShareVia = 'email' | 'domain'
+export { sharedVia, type ShareVia } from './machineSharePolicy.js'
/** The most machines one account is shown as shared with it, and the most a machine lists as using it. */
export const SHARED_LIST_MAX = 200
const normalized = (email: string): string => email.trim().toLowerCase()
-/** How `share` reaches `email`: named, at the owner's domain, or not at all. */
-export function sharedVia(share: Pick<MachineShare, 'emails' | 'domain'>, email: string): ShareVia | null {
- const address = normalized(email)
- if (share.emails.includes(address)) return 'email'
- const domain = emailDomain(address)
- if (share.domain && domain === share.domain && !isPublicEmailDomain(domain)) return 'domain'
- return null
-}
-
/** Whether `user` may use `machine`, which another account owns: how it was shared with them, or null. */
export async function sharedMachineAccess(user: AuthUser, machine: Pick<Machine, 'machineId' | 'userId' | 'autonomousEnv'>): Promise<ShareVia | null> {
if (machine.userId === user.sub) return null
diff --git a/backend/src/lib/machineSharePolicy.test.ts b/backend/src/lib/machineSharePolicy.test.ts
new file mode 100644
index 000000000..0bcf0a4e5
--- /dev/null
+++ b/backend/src/lib/machineSharePolicy.test.ts
@@ -0,0 +1,18 @@
+import { expect, it } from 'vitest'
+import { machineShareGrant, nextMachineShareGrants } from './machineSharePolicy.js'
+
+it('keeps continuing grants while rotating a removed and restored email or domain', () => {
+ const first = { id: 'share', emails: ['[email protected]', '[email protected]'], domain: 'team.test', grantVersions: null }
+ const a = machineShareGrant(first, '[email protected]'), b = machineShareGrant(first, '[email protected]')
+ const domain = machineShareGrant(first, '[email protected]')
+ const same = { ...first, grantVersions: nextMachineShareGrants(first, first.emails, first.domain) }
+ expect(machineShareGrant(same, '[email protected]')).toBe(a)
+ expect(machineShareGrant(same, '[email protected]')).toBe(domain)
+ const removed = { ...same, emails: ['[email protected]'], domain: null, grantVersions: nextMachineShareGrants(same, ['[email protected]'], null) }
+ expect(machineShareGrant(removed, '[email protected]')).toBeNull()
+ const restored = { ...first, grantVersions: nextMachineShareGrants(removed, first.emails, first.domain) }
+ expect(machineShareGrant(restored, '[email protected]')).not.toBe(a)
+ expect(machineShareGrant(restored, '[email protected]')).toBe(b)
+ expect(machineShareGrant(restored, '[email protected]')).not.toBe(domain)
+ expect(nextMachineShareGrants(null, ['[email protected]'], null)).toHaveProperty('email:[email protected]')
+})
diff --git a/backend/src/lib/machineSharePolicy.ts b/backend/src/lib/machineSharePolicy.ts
new file mode 100644
index 000000000..4e1e0c598
--- /dev/null
+++ b/backend/src/lib/machineSharePolicy.ts
@@ -0,0 +1,32 @@
+import type { MachineShare } from '@prisma/client'
+import { randomUUID } from 'node:crypto'
+import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'
+
+export type ShareVia = 'email' | 'domain'
+
+/** The shared policy decision, usable inside a transaction without opening Redis connections. */
+export function sharedVia(share: Pick<MachineShare, 'emails' | 'domain'>, email: string): ShareVia | null {
+ const address = email.trim().toLowerCase()
+ if (share.emails.includes(address)) return 'email'
+ const domain = emailDomain(address)
+ return share.domain && domain === share.domain && !isPublicEmailDomain(domain) ? 'domain' : null
+}
+
+type GrantPolicy = Pick<MachineShare, 'id' | 'emails' | 'domain' | 'grantVersions'>
+const versionsOf = (share: GrantPolicy) => share.grantVersions && typeof share.grantVersions === 'object' && !Array.isArray(share.grantVersions)
+ ? share.grantVersions as Record<string, unknown> : {}
+const grantVersion = (share: GrantPolicy, key: string) => {
+ const existing = versionsOf(share)[key]
+ return typeof existing === 'string' ? existing : `${share.id}:${key}`
+}
+export function machineShareGrant(share: GrantPolicy, email: string): string | null {
+ const via = sharedVia(share, email)
+ return via ? grantVersion(share, via === 'email' ? `email:${email.trim().toLowerCase()}` : `domain:${share.domain}`) : null
+}
+/** Unchanged grants keep their version, including policies saved before this field existed. */
+export function nextMachineShareGrants(before: GrantPolicy | null, emails: string[], domain: string | null): Record<string, string> {
+ return Object.fromEntries([
+ ...emails.map(email => [`email:${email}`, before?.emails.includes(email) ? grantVersion(before, `email:${email}`) : randomUUID()]),
+ ...(domain ? [[`domain:${domain}`, before?.domain === domain ? grantVersion(before, `domain:${domain}`) : randomUUID()]] : []),
+ ])
+}
diff --git a/backend/src/lib/webWs.test.ts b/backend/src/lib/webWs.test.ts
index e3cd11b16..25aef6a16 100644
--- a/backend/src/lib/webWs.test.ts
+++ b/backend/src/lib/webWs.test.ts
@@ -12,10 +12,10 @@ describe('frames a web client may never forge', () => {
it('refuses the backend-authoritative frames that are not `__`-prefixed', () => {
// machine_meta names the account's private grid — the inference endpoint every agent on that
// computer is then pointed at. machine_revoked makes the adapter clear its session and exit.
- // desk_changed / zoo_changed / machines_changed make every window on that computer re-read from the backend:
+ // desk_changed / zoo_changed / machines_changed / connectors_changed make every window re-read from the backend:
// forged in a loop, that is request amplification against our own API. device_keys_changed makes the
// daemon re-read its device key log; devlog_append_result is the backend's answer to its own append.
- expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['desk_changed', 'device_keys_changed', 'devlog_append_result', 'machine_meta', 'machine_revoked', 'machines_changed', 'zoo_changed'])
+ expect([...BACKEND_ONLY_DOWN_TYPES].sort()).toEqual(['connectors_changed', 'desk_changed', 'device_keys_changed', 'devlog_append_result', 'machine_meta', 'machine_revoked', 'machines_changed', 'zoo_changed'])
})
it('covers only frames that are NOT already caught by the `__` rule', () => {
diff --git a/backend/src/routes/harnessShares.test.ts b/backend/src/routes/harnessShares.test.ts
index 35a2f7a17..bdf0b6bba 100644
--- a/backend/src/routes/harnessShares.test.ts
+++ b/backend/src/routes/harnessShares.test.ts
@@ -4,8 +4,9 @@ import { randomUUID } from 'node:crypto'
const mocks = vi.hoisted(() => ({
prisma: { harnessShare: { findFirst: vi.fn(), findMany: vi.fn(), findUnique: vi.fn(), upsert: vi.fn(), updateMany: vi.fn() },
machine: { findFirst: vi.fn(), findMany: vi.fn() }, user: { findMany: vi.fn(), findUnique: vi.fn() } },
- presence: vi.fn(), changed: vi.fn(), listChanged: vi.fn(), auth: vi.fn(),
+ mayObserve: vi.fn(), presence: vi.fn(), changed: vi.fn(), listChanged: vi.fn(), auth: vi.fn(),
}))
+vi.mock('../superTabs/store.js', () => ({ SuperTabStore: class { mayObserve = mocks.mayObserve } }))
vi.mock('../lib/prisma.js', () => ({ prisma: mocks.prisma, machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] } }))
vi.mock('../lib/bus.js', () => ({ getAgentPresenceMany: mocks.presence, publishShareChanged: mocks.changed,
publishDeviceMachineListChanged: mocks.listChanged }))
@@ -159,4 +160,17 @@ describe('account-bound harness invitations', () => {
mocks.prisma.machine.findFirst.mockResolvedValueOnce({ ...machine, billingStatus: 'pending' })
expect(await recipientShare('share', ken)).toBeNull()
})
+ it('rechecks Super Tab membership for session admission and excludes revoked views from inventory', async () => {
+ mocks.auth.mockResolvedValue(ken)
+ const share = { id: 'share', ...input(), superTabId: 'a'.repeat(24), ownerId: owner.sub, expiresAt: new Date(input().expiresAt) }
+ mocks.prisma.harnessShare.findFirst.mockResolvedValue(share)
+ mocks.prisma.harnessShare.findMany.mockResolvedValue([share])
+ mocks.mayObserve.mockResolvedValue(true)
+ expect(await recipientShare('share', ken)).toEqual(share)
+ expect(mocks.mayObserve).toHaveBeenCalledWith(ken, share.superTabId, 'm1', 'agent-1', owner.sub)
+ mocks.mayObserve.mockResolvedValue(false)
+ expect(await recipientShare('share', ken)).toBeNull()
+ expect((await app.inject({ method: 'GET', url: '/api/harness-shares', headers: auth })).json().data.machines).toEqual([])
+ })
+
})
diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.ts
index 1bcc23771..031f5c50c 100644
--- a/backend/src/routes/harnessShares.ts
+++ b/backend/src/routes/harnessShares.ts
@@ -1,5 +1,6 @@
import type { FastifyInstance } from 'fastify'
import { z } from 'zod'
+import { SuperTabStore } from '../superTabs/store.js'
import { prisma, machineAlive } from '../lib/prisma.js'
import { getAgentPresenceMany, publishDeviceMachineListChanged, publishShareChanged } from '../lib/bus.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
@@ -9,6 +10,7 @@ import type { AuthUser } from '../lib/ssoAuth.js'
const params = z.object({ id: z.string().uuid() })
const body = z.object({
+ superTabId: z.string().regex(/^[a-f0-9]{24}$/).nullable().optional(),
machineId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),
agentId: z.string().min(1).max(160),
recipientEmail: z.string().trim().toLowerCase().email().max(254),
@@ -46,7 +48,9 @@ export async function recipientShare(id: string, user: AuthUser) {
const machine = await prisma.machine.findFirst({ where: {
machineId: share.machineId, userId: share.ownerId, autonomousEnv: user.autonomousEnv, ...machineAlive,
} })
- return machine && machineBillingAllowsDataPlane(machine) ? share : null
+ if (!machine || !machineBillingAllowsDataPlane(machine)) return null
+ if (share.superTabId && !await new SuperTabStore(prisma).mayObserve(user, share.superTabId, share.machineId, share.agentId, share.ownerId)) return null
+ return share
}
export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
@@ -55,8 +59,12 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
recipientEmail: req.user!.email.trim().toLowerCase(), autonomousEnv: req.user!.autonomousEnv,
revokedAt: null, expiresAt: { gt: new Date() },
}, orderBy: { createdAt: 'asc' }, take: 1000 })
+ const visible: typeof shares = []
+ for (const share of shares) {
+ if (!share.superTabId || await new SuperTabStore(prisma).mayObserve(req.user!, share.superTabId, share.machineId, share.agentId, share.ownerId)) visible.push(share)
+ }
const machines = await prisma.machine.findMany({ where: {
- machineId: { in: [...new Set(shares.map(s => s.machineId))] },
+ machineId: { in: [...new Set(visible.map(s => s.machineId))] },
autonomousEnv: req.user!.autonomousEnv, ...machineAlive,
} })
const allowed = machines.filter(machineBillingAllowsDataPlane)
@@ -64,7 +72,7 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
select: { id: true, name: true, email: true } })
const presence = await getAgentPresenceMany(allowed.map(m => m.machineId))
sendSuccess(reply, { machines: allowed.flatMap(machine => {
- const grants = shares.filter(s => s.machineId === machine.machineId && s.ownerId === machine.userId)
+ const grants = visible.filter(s => s.machineId === machine.machineId && s.ownerId === machine.userId)
if (grants.length === 0) return []
const owner = owners.find(o => o.id === machine.userId)
return [{ machineId: machine.machineId, name: machine.name, authMode: 'remote',
@@ -93,7 +101,7 @@ export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
|| existing.agentId !== input.agentId || existing.recipientEmail !== input.recipientEmail)) {
return sendError(reply, 'This invitation cannot be changed.', 'FORBIDDEN', 403)
}
- const data = { ...input, expiresAt: new Date(input.expiresAt), revokedAt: null,
+ const data = { ...input, superTabId: input.superTabId ?? null, expiresAt: new Date(input.expiresAt), revokedAt: null,
ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv }
await prisma.harnessShare.upsert({ where: { id: req.params.id },
create: { id: req.params.id, ...data }, update: data })
diff --git a/backend/src/routes/machineShares.test.ts b/backend/src/routes/machineShares.test.ts
index a0cb8e352..1faaada16 100644
--- a/backend/src/routes/machineShares.test.ts
+++ b/backend/src/routes/machineShares.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import Fastify, { type FastifyInstance } from 'fastify'
const mocks = vi.hoisted(() => ({
prisma: {
+ $transaction: vi.fn(),
machine: { findFirst: vi.fn() },
machineShare: { findUnique: vi.fn(), upsert: vi.fn(), deleteMany: vi.fn() },
machineShareAdd: { findMany: vi.fn(), upsert: vi.fn(), deleteMany: vi.fn() },
@@ -31,6 +32,7 @@ describe('sharing a machine', () => {
const auth = { authorization: 'Bearer fixture' }
beforeEach(async () => {
vi.resetAllMocks()
+ mocks.prisma.$transaction.mockImplementation(async work => work(mocks.prisma))
mocks.auth.mockResolvedValue(dee)
mocks.prisma.machine.findFirst.mockResolvedValue(machine)
mocks.prisma.machineShare.findUnique.mockResolvedValue(null)
@@ -88,8 +90,8 @@ describe('sharing a machine', () => {
const res = await put({ emails: [' [email protected] ', '[email protected]', '[email protected]', '[email protected]'], sameDomain: true })
expect(res.statusCode).toBe(200)
expect(mocks.prisma.machineShare.upsert).toHaveBeenCalledWith({ where: { machineId: M1 },
- create: { machineId: M1, ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io' },
- update: { ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io' } })
+ create: { machineId: M1, ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io', grantVersions: expect.any(Object) },
+ update: { ownerId: 'dee', autonomousEnv: 'prod', emails: ['[email protected]'], domain: 'acme.io', grantVersions: expect.any(Object) } })
expect(res.json().data).toEqual({ emails: ['[email protected]'], sameDomain: true, domain: 'acme.io', members })
expect(mocks.shareChanged).toHaveBeenCalledWith(M1)
expect(mocks.prisma.user.findMany).toHaveBeenCalledWith(expect.objectContaining({ where: { OR: [
@@ -97,6 +99,14 @@ describe('sharing a machine', () => {
expect(mocks.listChanged.mock.calls.map(c => c[0]).sort()).toEqual(['ann', 'kim', 'lee'])
})
+ it('retries a concurrent policy update before choosing versions for the resulting grants', async () => {
+ mocks.prisma.$transaction.mockRejectedValueOnce({ code: 'P2034' })
+ const res = await put({ emails: ['[email protected]'], sameDomain: false })
+ expect(res.statusCode).toBe(200)
+ expect(mocks.prisma.$transaction).toHaveBeenCalledTimes(2)
+ expect(mocks.prisma.machineShare.upsert).toHaveBeenCalledOnce()
+ })
+
it('refuses everyone at a public domain', async () => {
mocks.auth.mockResolvedValue({ ...dee, email: '[email protected]' })
const res = await put({ emails: [], sameDomain: true })
diff --git a/backend/src/routes/machineShares.ts b/backend/src/routes/machineShares.ts
index 0b4052490..2f3803606 100644
--- a/backend/src/routes/machineShares.ts
+++ b/backend/src/routes/machineShares.ts
@@ -11,6 +11,7 @@
* is (lib/machineAccess.ts), so these change no one's access.
*/
import type { FastifyInstance } from 'fastify'
+import { nextMachineShareGrants } from '../lib/machineSharePolicy.js'
import type { MachineShare } from '@prisma/client'
import { z } from 'zod'
import { prisma, machineAlive } from '../lib/prisma.js'
@@ -51,6 +52,31 @@ async function policyView(share: MachineShare | null, user: AuthUser) {
}
}
+/** A concurrent share edit must reread the current grant versions. Reusing a
+ * stale policy after a revocation could otherwise revive an old contribution. */
+async function writePolicy(machineId: string, user: AuthUser, emails: string[], domain: string | null) {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ return await prisma.$transaction(async tx => {
+ const before = await tx.machineShare.findUnique({ where: { machineId } })
+ let after: MachineShare | null = null
+ if (!emails.length && !domain) {
+ await tx.machineShare.deleteMany({ where: { machineId } })
+ await tx.machineShareAdd.deleteMany({ where: { machineId } })
+ } else {
+ const data = { ownerId: user.sub, autonomousEnv: user.autonomousEnv, emails, domain,
+ grantVersions: nextMachineShareGrants(before, emails, domain) }
+ after = await tx.machineShare.upsert({ where: { machineId }, create: { machineId, ...data }, update: data })
+ }
+ return { before, after }
+ })
+ } catch (error) {
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null
+ if (attempt >= 4 || (code !== 'P2034' && code !== 'P2002')) throw error
+ }
+ }
+}
+
/**
* Everyone a change of the policy may add the machine to or take it from, their apps and daemons told to
* read their Machines again: the addresses before and after, everyone at the domain before and after, and
@@ -98,16 +124,7 @@ export async function machineShareRoutes(app: FastifyInstance): Promise<void> {
return sendError(reply, `Everyone at @${domain ?? 'your domain'} is not offered: it is a public email domain.`, 'PUBLIC_DOMAIN', 400)
}
}
- const before = await prisma.machineShare.findUnique({ where: { machineId } })
- let after: MachineShare | null = null
- if (!emails.length && !domain) {
- // Shared with no one: the row goes, and with it every colleague's add.
- await prisma.machineShare.deleteMany({ where: { machineId } })
- await prisma.machineShareAdd.deleteMany({ where: { machineId } })
- } else {
- const data = { ownerId: user.sub, autonomousEnv: user.autonomousEnv, emails, domain }
- after = await prisma.machineShare.upsert({ where: { machineId }, create: { machineId, ...data }, update: data })
- }
+ const { before, after } = await writePolicy(machineId, user, emails, domain)
await publishMachineShareChanged(machineId).catch(() => 0)
await tellAffected(machineId, user.sub, before, after)
sendSuccess(reply, await policyView(after, user))
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
new file mode 100644
index 000000000..46e4e4b1c
--- /dev/null
+++ b/backend/src/routes/superTabs.ts
@@ -0,0 +1,85 @@
+import type { FastifyInstance, FastifyReply } from 'fastify'
+import { z } from 'zod'
+import { prisma } from '../lib/prisma.js'
+import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'
+import { sendError, sendSuccess } from '../utils/response.js'
+import { operationSchema } from '../superTabs/commands.js'
+import { SuperTabError } from '../superTabs/model.js'
+import { SuperTabStore } from '../superTabs/store.js'
+import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'
+
+const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+const tabParams = z.object({ tabId: id })
+const agentQuery = z.object({ asAgentId: id.optional() }).strict()
+const create = z.object({ operationId: id, name: z.string().trim().min(1).max(160) }).strict()
+const operation = operationSchema.extend({ asAgentId: id.optional() })
+const listQuery = z.object({ after: id.optional() }).strict()
+const startParams = tabParams.extend({ startId: id })
+const nativeParams = tabParams.extend({ contextId: id })
+const messageParams = tabParams.extend({ conversationId: id })
+const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegative().safe().optional(),
+ before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional() })
+ .refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')
+const hostParams = z.object({ machineId: id })
+const deliveryParams = tabParams.extend({ agentId: id })
+const deliveryActionParams = deliveryParams.extend({ deliveryId: id })
+const deliveryAction = z.discriminatedUnion('type', [
+ z.object({ type: z.literal('claim'), claimId: id }).strict(),
+ z.object({ type: z.literal('ack'), claimId: id, receipt: z.string().min(1).max(2000), uncertain: z.boolean() }).strict(),
+])
+const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()
+
+async function respond(reply: FastifyReply, action: () => Promise<unknown>) {
+ try { sendSuccess(reply, await action()) } catch (error) {
+ if (!(error instanceof SuperTabError)) throw error
+ sendError(reply, error.message, error.code, error.status)
+ }
+}
+
+/** Uses the normal authenticated control API. It never accepts caller-provided host/contributor identities. */
+export async function superTabRoutes(app: FastifyInstance, options: { store?: SuperTabStore } = {}) {
+ const store = options.store ?? new SuperTabStore(prisma)
+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof openNativeSchema> }>('/api/super-tabs/:tabId/native',
+ { preHandler: [validateParams(tabParams), validateBody(openNativeSchema)] },
+ (req, reply) => respond(reply, () => store.native.open(req.user!, req.params.tabId, req.body)))
+ app.get<{ Params: z.infer<typeof nativeParams> }>('/api/super-tabs/:tabId/native/:contextId',
+ { preHandler: validateParams(nativeParams) },
+ (req, reply) => respond(reply, () => store.native.read(req.user!, req.params.tabId, req.params.contextId)))
+ app.post<{ Params: z.infer<typeof nativeParams>; Body: z.infer<typeof nativeEventSchema> }>('/api/super-tabs/:tabId/native/:contextId',
+ { preHandler: [validateParams(nativeParams), validateBody(nativeEventSchema)] },
+ (req, reply) => respond(reply, () => store.native.append(req.user!, req.params.tabId, req.params.contextId, req.body)))
+ app.get<{ Querystring: z.infer<typeof listQuery> }>('/api/super-tabs', { preHandler: validateQuery(listQuery) },
+ (req, reply) => respond(reply, () => store.list(req.user!, req.query.after)))
+ app.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },
+ (req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name)))
+ app.get('/api/super-tabs/invitations', (req, reply) => respond(reply, () => store.invitations(req.user!)))
+ app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId', { preHandler: validateParams(hostParams) },
+ (req, reply) => respond(reply, () => store.hostTabs(req.user!, req.params.machineId)))
+ app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/assignments', { preHandler: validateParams(hostParams) },
+ (req, reply) => respond(reply, () => store.hostAssignments(req.user!, req.params.machineId)))
+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId',
+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.read(req.user!, req.params.tabId, req.query.asAgentId)))
+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof operation> }>('/api/super-tabs/:tabId/commands',
+ { preHandler: [validateParams(tabParams), validateBody(operation)] },
+ (req, reply) => respond(reply, () => store.execute(req.user!, req.params.tabId,
+ { operationId: req.body.operationId, command: req.body.command }, req.body.asAgentId)))
+ app.get<{ Params: z.infer<typeof startParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/starts/:startId',
+ { preHandler: [validateParams(startParams), validateQuery(agentQuery)] },
+ (req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, req.query.asAgentId)))
+ app.get<{ Params: z.infer<typeof messageParams>; Querystring: z.infer<typeof messageQuery> }>('/api/super-tabs/:tabId/conversations/:conversationId/messages',
+ { preHandler: [validateParams(messageParams), validateQuery(messageQuery)] },
+ (req, reply) => respond(reply, () => store.messages(req.user!, req.params.tabId, req.params.conversationId, req.query, req.query.asAgentId)))
+ app.get<{ Params: z.infer<typeof deliveryParams> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries',
+ { preHandler: validateParams(deliveryParams) },
+ (req, reply) => respond(reply, () => store.deliveries(req.user!, req.params.tabId, req.params.agentId)))
+ app.post<{ Params: z.infer<typeof deliveryActionParams>; Body: z.infer<typeof deliveryAction> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',
+ { preHandler: [validateParams(deliveryActionParams), validateBody(deliveryAction)] },
+ (req, reply) => respond(reply, () => store.delivery(req.user!, req.params.tabId, req.params.agentId, req.params.deliveryId, req.body)))
+ app.get<{ Params: z.infer<typeof deliveryActionParams> }>('/api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',
+ { preHandler: validateParams(deliveryActionParams) },
+ (req, reply) => respond(reply, () => store.deliveryReceipt(req.user!, req.params.tabId, req.params.agentId, req.params.deliveryId)))
+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof stop> }>('/api/super-tabs/:tabId/stopped',
+ { preHandler: [validateParams(tabParams), validateBody(stop)] },
+ (req, reply) => respond(reply, () => store.stopped(req.user!, req.params.tabId, req.body.assignmentId, req.body.receipt)))
+}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 7f31dfeab..c584a1d57 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -25,6 +25,7 @@ import { deskRoutes } from './routes/desk.js'
import { connectorRoutes } from './routes/connectors.js'
import { connectorVaultRoutes } from './routes/connectorVault.js'
import { agentMessagesRoutes } from './routes/agentMessages.js'
+import { superTabRoutes } from './routes/superTabs.js'
import { zooRoutes } from './routes/zoo.js'
import { experimentalSettingsRoutes } from './routes/experimentalSettings.js'
import { describeDaemonsSwitch } from './lib/daemonsSwitch.js'
@@ -203,6 +204,7 @@ async function start(): Promise<void> {
await app.register(connectorRoutes) // sign-in to GitHub, Slack, Google… for local agents (lib/connectorGateway.ts)
await app.register(connectorVaultRoutes) // those connections sealed for the account's computers, which keep them in step
await app.register(agentMessagesRoutes) // which tabs' harnesses may message each other (lib/agentMessages.ts)
+ await app.register(superTabRoutes)
await app.register(experimentalSettingsRoutes, { daemons: DAEMONS })
// Availability is separate from opt-in: every account starts off, and its collection is retained.
await app.register(zooRoutes, { daemons: DAEMONS, requireAccountOptIn: true })
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
new file mode 100644
index 000000000..c21f19b7d
--- /dev/null
+++ b/backend/src/superTabs/commands.test.ts
@@ -0,0 +1,218 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, visibleState, type Actor, type AgentConfiguration } from './model.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'codex', model: 'test-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+function fixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: 1000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invite = (role: 'viewer' | 'collaborator' = 'collaborator') => {
+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ }
+ const add = (harnessId: string, contributorId = 'owner', group = 'lead', lead = false) => {
+ const result = run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId,
+ name: harnessId, configuration: config, lead }, contributorId === 'owner' ? owner : peer,
+ { contribution: { machineOwnerId: 'host-owner', contributorId } })
+ return result.result.agentId as string
+ }
+ const group = () => run({ type: 'conversation.create', title: 'Offline editing', brief: 'Save edits while offline.',
+ checks: [{ description: 'Reconnect preserves the edits.', independent: true }] }).result.conversationId as string
+ return { run, invite, add, group, get state() { return state } }
+}
+
+describe('Super Tab collaboration policy', () => {
+ it('records host-observed runtime changes without rewriting an assignment\'s starting configuration', () => {
+ const f = fixture(), group = f.group(), worker = f.add('worker', 'owner', group)
+ f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ const before = f.state.agents[0]!.configurationVersion!
+ const observed = { ...config, model: 'another-model', effort: 'max', contextWindow: null }
+ const command: Command = { type: 'agent.configuration', previousVersion: before, configuration: observed }
+ expect(() => f.run(command)).toThrow('Only the execution host')
+ const actor: Actor = { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }
+ const changed = f.run(command, actor)
+ expect(changed.messages).toEqual([])
+ expect(f.state.agents[0]!.configuration).toEqual(observed)
+ expect(f.state.conversations[1]!.assignment!.configuration).toEqual(config)
+ expect(() => f.run(command, actor)).toThrow('current agent configuration')
+ const version = f.state.agents[0]!.configurationVersion!
+ f.run({ ...command, previousVersion: version }, actor)
+ expect(f.state.agents[0]!.configurationVersion).toBe(version)
+ f.run({ ...command, configuration: config, previousVersion: version }, actor)
+ expect(f.state.agents[0]!.configurationVersion).not.toBe(before)
+ })
+
+ it('fences observations from an earlier contribution of the same native harness', () => {
+ const f = fixture(), worker = f.add('worker')
+ const before = f.state.agents[0]!.configurationVersion!
+ f.run({ type: 'agent.remove', agentId: worker })
+ expect(f.add('worker')).toBe(worker)
+ expect(f.state.agents[0]!.configurationVersion).not.toBe(before)
+ expect(() => f.run({ type: 'agent.configuration', previousVersion: before, configuration: { ...config, model: 'old observation' } },
+ { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' })).toThrow('current agent configuration')
+ })
+
+ it('records the native launch request without dispatching it a second time', () => {
+ const f = fixture()
+ const result = f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'lead',
+ name: 'Lead', configuration: config, lead: true, initialMessage: 'Discuss the architecture.' }, owner,
+ { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } })
+ expect(result.messages).toEqual([expect.objectContaining({ text: 'Discuss the architecture.', recipients: [], author: expect.objectContaining({ kind: 'person', id: 'owner' }) })])
+ expect(f.state.conversations[0]!.leadId).toBe(result.result.agentId)
+ })
+ it('keeps adding an agent separate from creating conversations and assigning work', () => {
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true)
+ const group = f.group()
+ const worker = f.add('worker', 'owner', group)
+ expect(f.state.conversations.map(c => c.title)).toEqual(['Lead', 'Offline editing'])
+ expect(f.state.conversations[1]).toMatchObject({ leadId: lead, agentIds: [lead, worker], assignment: null })
+ f.run({ type: 'conversation.agent', conversationId: 'lead', agentId: worker, present: true, lead: false })
+ expect(f.state.agents).toHaveLength(2)
+ expect(f.state.conversations).toHaveLength(2)
+ })
+
+ it('routes a human reply to its author, and does not create agent chatter loops', () => {
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true)
+ const worker = f.add('worker')
+ const posted = f.run({ type: 'message.send', conversationId: 'lead', text: 'Which behavior?', replyTo: null, recipientIds: [] },
+ { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' }).messages[0]!
+ expect(posted.recipients).toEqual([])
+ const reply = f.run({ type: 'message.send', conversationId: 'lead', text: 'Keep the local copy.', replyTo: posted.id, recipientIds: [] }, owner,
+ { reply: { id: posted.id, conversationId: 'lead', author: posted.author } })
+ expect(reply.messages[0]!.recipients).toEqual([worker])
+ const fresh = f.run({ type: 'message.send', conversationId: 'lead', text: 'Continue.', replyTo: null, recipientIds: [] })
+ expect(fresh.messages[0]!.recipients).toEqual([lead])
+ expect(() => f.run({ type: 'message.send', conversationId: 'lead', text: 'Cross-group reply', replyTo: posted.id, recipientIds: [] }, owner,
+ { reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author } })).toThrow('Reply to a message in this conversation')
+ })
+
+ it('lets a viewer read and leave, but not send, assign, attach or invite', () => {
+ const f = fixture()
+ f.invite('viewer')
+ const commands: Command[] = [
+ { type: 'message.send', conversationId: 'lead', text: 'Run this', replyTo: null, recipientIds: [] },
+ { type: 'work.assign', conversationId: 'lead', agentId: 'worker' },
+ { type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'worker', name: 'Worker', configuration: config, lead: false },
+ { type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' },
+ ]
+ for (const command of commands) expect(() => f.run(command, peer)).toThrow('read-only')
+ expect(visibleState(f.state, peer).people).toHaveLength(2)
+ f.run({ type: 'member.remove', userId: 'peer' }, peer)
+ expect(() => visibleState(f.state, peer)).toThrow('no longer have access')
+ })
+
+ it('requires the addressed account to accept an unexpired invitation and keeps other invitations private', () => {
+ const f = fixture()
+ const invited = f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' })
+ const command: Command = { type: 'invite.accept', inviteId: invited.result.inviteId as string }
+ expect(() => f.run(command, { kind: 'person', userId: 'stranger', email: '[email protected]' })).toThrow('unavailable')
+ expect(() => f.run(command, peer, { now: 1000 + 7 * 86400000 })).toThrow('expired')
+ f.run(command, peer)
+ f.run({ type: 'invite.create', email: '[email protected]', role: 'viewer', conversationId: 'lead' })
+ expect(visibleState(f.state, owner).invitations).toHaveLength(1)
+ expect(visibleState(f.state, peer).invitations).toHaveLength(0)
+ const snapshot = visibleState(f.state, owner)
+ snapshot.people.splice(0)
+ expect(f.state.people).toHaveLength(2)
+ })
+
+ it('withdraws a departing contributor and preserves execution identity until the host confirms a stop', () => {
+ const f = fixture()
+ f.invite()
+ const group = f.group()
+ const worker = f.add('worker', 'peer', group)
+ const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
+ const removed = f.run({ type: 'member.remove', userId: 'peer' })
+ expect(removed.cancelledAgents).toEqual([worker])
+ expect(f.state.conversations[1]!.assignment).toMatchObject({ status: 'reconciling', execution: { machineId: 'host', harnessId: 'worker', machineOwnerId: 'host-owner' } })
+ f.invite()
+ expect(f.state.agents).toHaveLength(0)
+ const stop: Command = { type: 'work.status', conversationId: group, assignmentId, status: 'stopped', result: 'Host receipt' }
+ expect(() => f.run(stop)).toThrow('confirm the stop')
+ f.run(stop, owner, { confirmedStopped: true })
+ expect(f.state.conversations[1]!.assignment!.status).toBe('stopped')
+ })
+
+ it('keeps ownership exclusive and requires independent evidence before closing an attempt', () => {
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true)
+ const group = f.group()
+ const worker = f.add('worker', 'owner', group)
+ const second = f.group()
+ const assigned = f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ const assignmentId = assigned.result.assignmentId as string
+ expect(assigned.messages[0]!.recipients).toEqual([worker])
+ expect(() => f.run({ type: 'work.assign', conversationId: second, agentId: worker })).toThrow('active assignment')
+ expect(() => f.run({ type: 'conversation.agent', conversationId: group, agentId: worker, present: true, lead: true })).toThrow('replacing its lead')
+ const done: Command = { type: 'work.status', conversationId: group, assignmentId, status: 'done', result: 'Revision fixture-1' }
+ expect(() => f.run(done)).toThrow('evidence')
+ const check: Command = { type: 'work.check', conversationId: group, assignmentId,
+ checkId: f.state.conversations[1]!.checks[0]!.id, passed: true, evidence: 'Reconnect test passed on revision fixture-1.' }
+ expect(() => f.run(check, { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' })).toThrow('Another agent')
+ f.run(check, { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' })
+ const completion = f.run(done, { kind: 'agent', agentId: worker, machineOwnerId: 'host-owner' })
+ expect(completion.messages[0]).toMatchObject({ conversationId: group, text: 'Done\n\nRevision fixture-1', recipients: [lead] })
+ expect(() => f.run(check)).toThrow('new attempt')
+ expect(() => f.run({ ...done, status: 'working' })).toThrow('new attempt')
+ const retry = f.run({ type: 'work.assign', conversationId: group, agentId: worker })
+ expect(retry.previousAttempts[0]!.assignment).toMatchObject({ id: assignmentId, status: 'done', configuration: config })
+ expect(f.state.conversations[1]!.checks[0]!.evidence).toBeNull()
+ })
+
+ it('allows discussion while paused and refuses new work, without mutating rejected state', () => {
+ const f = fixture()
+ f.run({ type: 'tab.pause', paused: true })
+ const before = JSON.stringify(f.state)
+ expect(() => f.group()).toThrow('paused')
+ expect(JSON.stringify(f.state)).toBe(before)
+ expect(f.run({ type: 'message.send', conversationId: 'lead', text: 'Let’s reconsider.', replyTo: null, recipientIds: [] }).messages).toHaveLength(1)
+ })
+
+ it('lets a person create an empty group and define its acceptance criteria before delegation', () => {
+ const f = fixture()
+ const id = f.run({ type: 'conversation.create', title: 'Sketch', brief: '', checks: [] }).result.conversationId as string
+ const worker = f.add('worker', 'owner', id)
+ expect(() => f.run({ type: 'work.assign', conversationId: id, agentId: worker })).toThrow('acceptance checks')
+ f.run({ type: 'work.define', conversationId: id, brief: 'Document the flow.', checks: [{ description: 'A person reviews the document.', independent: true }] })
+ f.run({ type: 'work.assign', conversationId: id, agentId: worker })
+ expect(() => f.run({ type: 'conversation.archive', conversationId: id, archived: true })).toThrow('active assignment')
+ })
+
+ it('rejects spoofed grant fields and execution identities', () => {
+ expect(commandSchema.safeParse({ type: 'tab.pause', paused: false, machineOwnerId: 'someone' }).success).toBe(false)
+ const f = fixture()
+ const lead = f.add('lead', 'owner', 'lead', true)
+ expect(() => f.run({ type: 'tab.pause', paused: false }, { kind: 'agent', agentId: lead, machineOwnerId: 'stranger' })).toThrow('execution host')
+ expect(() => f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'extra', name: 'Extra', configuration: config, lead: false })).toThrow('explicitly shared')
+ })
+})
+
+it('starts only in the chosen conversation, captures authority, and never assigns on join', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true), group = f.group()
+ const actor: Actor = { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }
+ const contribution = { machineOwnerId: 'target-owner', contributorId: 'owner', hostGrant: 'grant-1' }
+ const request = { conversationId: group, machineId: 'target', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }
+ const startId = f.run({ type: 'agent.start', request }, actor, { contribution }).result.startId as string
+ expect(f.state.starts![0]).toMatchObject({ request, hostGrant: 'grant-1', dispatched: false })
+ expect(f.state.agents).toHaveLength(1)
+ expect(f.state.conversations).toHaveLength(2)
+ expect(() => f.run({ type: 'agent.startDispatch', startId }, actor, { contribution: { ...contribution, hostGrant: 'new-grant' } })).toThrow('revoked')
+ f.run({ type: 'agent.startDispatch', startId }, actor, { contribution })
+ expect(() => f.run({ type: 'agent.startDispatch', startId }, actor, { contribution })).toThrow('already requested')
+ const worker = f.run({ type: 'agent.started', startId, harnessId: 'native-worker', configuration: { ...config, engine: 'claude' } }, actor, { contribution }).result.agentId
+ expect(f.state.agents).toHaveLength(2)
+ expect(f.state.conversations[1]).toMatchObject({ agentIds: [lead, worker], assignment: null })
+ expect(f.state.conversations[0]!.agentIds).toEqual([lead])
+ f.run({ type: 'tab.pause', paused: true })
+ expect(() => f.run({ type: 'agent.start', request }, actor, { contribution })).toThrow('paused')
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
new file mode 100644
index 000000000..18f53876b
--- /dev/null
+++ b/backend/src/superTabs/commands.ts
@@ -0,0 +1,421 @@
+import { z } from 'zod'
+import {
+ activeWork, actorKey, agent, author, conversation, fail, person, stableId,
+ type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,
+} from './model.js'
+
+const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+const title = z.string().trim().min(1).max(160)
+const text = z.string().trim().min(1).max(32_000)
+const configuration = z.object({
+ engine: z.string().min(1).max(80), model: z.string().max(200).nullable(),
+ effort: z.string().max(80).nullable(), contextWindow: z.number().int().positive().safe().nullable(),
+ engineVersion: z.string().max(160).nullable(),
+}).strict()
+const path = z.string().min(1).max(4096).regex(/^\//).refine(value => !/[\x00-\x1f\x7f]/.test(value))
+export const startRequestSchema = z.object({
+ conversationId: id, machineId: id, engine: z.string().min(1).max(80), name: title, cwd: path,
+ worktree: z.boolean(), branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(),
+ permissionMode: z.string().min(1).max(80).optional(), codexHome: path.optional(),
+ gridModel: z.string().min(1).max(2048).optional(), gridName: z.string().min(1).max(2048).optional(),
+ requirements: z.object({ memoryBytes: z.number().int().nonnegative().safe(), diskBytes: z.number().int().nonnegative().safe(),
+ maxCpuPercent: z.number().min(0).max(100), tools: z.array(z.string().regex(/^[A-Za-z0-9_.+-]{1,80}$/)).max(20),
+ devices: z.array(path).max(20), quotaRequired: z.boolean() }).strict(),
+}).strict()
+const check = z.object({ description: z.string().trim().min(1).max(1000), independent: z.boolean() }).strict()
+
+export const commandSchema = z.discriminatedUnion('type', [
+ z.object({ type: z.literal('tab.rename'), name: title }).strict(),
+ z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),
+ z.object({ type: z.literal('conversation.create'), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),
+ z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),
+ z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),
+ z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), initialMessage: text.optional() }).strict(),
+ z.object({ type: z.literal('agent.start'), request: startRequestSchema }).strict(),
+ z.object({ type: z.literal('agent.startDispatch'), startId: id }).strict(),
+ z.object({ type: z.literal('agent.started'), startId: id, harnessId: id, configuration }).strict(),
+ z.object({ type: z.literal('agent.startFailed'), startId: id, error: text }).strict(),
+ z.object({ type: z.literal('agent.remove'), agentId: id }).strict(),
+ z.object({ type: z.literal('agent.configuration'), previousVersion: id.nullable(), configuration }).strict(),
+ z.object({ type: z.literal('conversation.agent'), conversationId: id, agentId: id, present: z.boolean(), lead: z.boolean() }).strict(),
+ z.object({ type: z.literal('invite.create'), email: z.email().max(320), role: z.enum(['collaborator', 'viewer']), conversationId: id }).strict(),
+ z.object({ type: z.literal('invite.revoke'), inviteId: id }).strict(),
+ z.object({ type: z.literal('invite.accept'), inviteId: id }).strict(),
+ z.object({ type: z.literal('member.remove'), userId: id }).strict(),
+ z.object({ type: z.literal('message.send'), conversationId: id, text, replyTo: id.nullable(), recipientIds: z.array(id).max(16) }).strict(),
+ z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),
+ z.object({ type: z.literal('work.define'), conversationId: id, brief: text, checks: z.array(check).min(1).max(40) }).strict(),
+ z.object({ type: z.literal('work.assign'), conversationId: id, agentId: id }).strict(),
+ z.object({ type: z.literal('work.status'), conversationId: id, assignmentId: id,
+ status: z.enum(['working', 'needs_human', 'review', 'done', 'stopped']), result: text.nullable() }).strict(),
+ z.object({ type: z.literal('work.check'), conversationId: id, assignmentId: id, checkId: id, passed: z.boolean(), evidence: text }).strict(),
+])
+export type Command = z.infer<typeof commandSchema>
+export const operationSchema = z.object({ operationId: id, command: commandSchema }).strict()
+
+export interface CommandContext {
+ operationId: string
+ now: number
+ /** Read from host ownership/access records by the store, never copied from the request. */
+ contribution?: { machineOwnerId: string; contributorId: string; hostGrant?: string | null }
+ /** Loaded from this tab and conversation by the store. */
+ reply?: { id: string; conversationId: string; author: Author }
+ /** A host's receipt, not an elapsed lease, proves that an assignment stopped. */
+ confirmedStopped?: boolean
+ /** An uncertain receipt and its original message, read transactionally. */
+ delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string }
+}
+
+function controls(state: SuperTabState, actor: Actor, conversationId = 'lead'): void {
+ if (actor.kind === 'agent' && conversation(state, conversationId).leadId !== actor.agentId) {
+ fail('LEAD_REQUIRED', 'The coordinating lead owns this action.', 403)
+ }
+}
+function owner(state: SuperTabState, actor: Actor): void {
+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Super Tab owner can manage invitations.', 403)
+}
+function open(state: SuperTabState, conversationId: string) {
+ const group = conversation(state, conversationId)
+ if (group.archived) fail('ARCHIVED', 'Reopen this conversation before changing its work.')
+ return group
+}
+
+/** Pure policy/state transition. The store commits its state, messages and delivery records in one transaction. */
+export function applyCommand(original: SuperTabState, actor: Actor, input: Command, context: CommandContext): CommandEffects {
+ const command = commandSchema.parse(input)
+ const state = structuredClone(original)
+ const result: Record<string, unknown> = {}
+ const effects: CommandEffects = { state, messages: [], cancelledAgents: [], previousAttempts: [], result }
+ const operationId = stableId(state.id, actorKey(actor), context.operationId)
+
+ // Acceptance is the only operation a non-member can perform; the verified account email owns the invite.
+ if (command.type === 'invite.accept') {
+ if (actor.kind !== 'person') fail('FORBIDDEN', 'A person must accept this invitation.', 403)
+ const invite = state.invitations.find(i => i.id === command.inviteId)
+ if (!invite || invite.email !== actor.email.trim().toLowerCase()) fail('NOT_FOUND', 'This invitation is unavailable.', 404)
+ if (invite.expiresAt <= context.now) fail('EXPIRED', 'This invitation expired.', 410)
+ if (!state.people.some(p => p.id === actor.userId)) {
+ state.people.push({ id: actor.userId, email: invite.email, role: invite.role, generation: invite.id })
+ }
+ state.invitations = state.invitations.filter(i => i.id !== invite.id)
+ result.conversationId = invite.conversationId
+ return effects
+ }
+
+ const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
+ const sender = author(state, actor, !leaving)
+ const rememberAttempt = (group: ReturnType<typeof conversation>) => {
+ if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,
+ brief: group.brief, checks: group.checks, assignment: group.assignment }))
+ }
+ const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null) => {
+ effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients })
+ result.messageId = operationId
+ }
+ const removeAgent = (target: Agent) => {
+ state.agents = state.agents.filter(a => a.id !== target.id)
+ effects.cancelledAgents.push(target.id)
+ for (const group of state.conversations) {
+ group.agentIds = group.agentIds.filter(a => a !== target.id)
+ if (group.leadId === target.id) group.leadId = null
+ if (group.assignment?.agentId === target.id && activeWork(group)) group.assignment.status = 'reconciling'
+ }
+ }
+
+ switch (command.type) {
+ case 'tab.rename':
+ controls(state, actor)
+ state.name = command.name
+ break
+ case 'tab.pause':
+ controls(state, actor)
+ state.paused = command.paused
+ break
+ case 'conversation.create': {
+ controls(state, actor)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ if (actor.kind === 'agent' && (!command.brief || !command.checks.length)) {
+ fail('BRIEF_REQUIRED', 'Delegated work needs a brief and acceptance checks.', 400)
+ }
+ const leadId = conversation(state, 'lead').leadId
+ state.conversations.push({ id: operationId, title: command.title, leadId, agentIds: leadId ? [leadId] : [],
+ archived: false, brief: command.brief, assignment: null, lastMessageSequence: 0,
+ checks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),
+ })
+ result.conversationId = operationId
+ if (command.brief) message(operationId, command.brief)
+ break
+ }
+ case 'conversation.rename':
+ controls(state, actor, command.conversationId)
+ open(state, command.conversationId).title = command.title
+ break
+ case 'conversation.archive': {
+ controls(state, actor, command.conversationId)
+ const group = conversation(state, command.conversationId)
+ if (group.id === 'lead') fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')
+ if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')
+ group.archived = command.archived
+ break
+ }
+ case 'agent.add': {
+ controls(state, actor, command.conversationId)
+ const group = open(state, command.conversationId)
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'This session must be explicitly shared by an authorized contributor.', 403)
+ const contributor = person(state, grant.contributorId)
+ if (contributor.role === 'viewer') fail('READ_ONLY', 'A viewer cannot contribute agents.', 403)
+ const agentId = stableId(command.machineId, command.harnessId)
+ const existing = state.agents.find(a => a.id === agentId)
+ if (!existing) state.agents.push({ id: agentId, machineId: command.machineId, harnessId: command.harnessId,
+ machineOwnerId: grant.machineOwnerId, contributorId: grant.contributorId, membershipGeneration: contributor.generation,
+ hostGrant: grant.hostGrant ?? null,
+ name: command.name, configuration: command.configuration, configurationVersion: operationId })
+ if (existing && (existing.machineOwnerId !== grant.machineOwnerId || existing.contributorId !== grant.contributorId)) {
+ fail('ALREADY_SHARED', 'This session already has a contributor. Use the existing tab agent.')
+ }
+ if (existing && (existing.hostGrant ?? null) !== (grant.hostGrant ?? null)) {
+ fail('CONTRIBUTION_REVOKED', 'Reconcile and remove this old contribution before adding it under the new machine share.', 403)
+ }
+ if (!group.agentIds.includes(agentId)) group.agentIds.push(agentId)
+ if (command.lead) {
+ if (group.leadId && group.leadId !== agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')
+ group.leadId = agentId
+ }
+ result.agentId = agentId
+ // Creation already handed this first request to the native harness (and
+ // any attachments through its existing launch path). Record it once in
+ // the shared conversation without delivering the same request twice.
+ if (command.initialMessage) {
+ if (actor.kind !== 'person') fail('FORBIDDEN', 'Only a person can record their initial launch request.', 403)
+ message(group.id, command.initialMessage)
+ }
+ break
+ }
+ case 'agent.start': {
+ controls(state, actor, command.request.conversationId)
+ open(state, command.request.conversationId)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'Choose a machine shared with the contributor.', 403)
+ const contributor = person(state, grant.contributorId)
+ if (contributor.role === 'viewer') fail('READ_ONLY', 'A viewer cannot start agents.', 403)
+ 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({ id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),
+ contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,
+ hostGrant: grant.hostGrant ?? null, request: command.request, harnessId: null, dispatched: false, error: null })
+ result.startId = operationId
+ break
+ }
+ case 'agent.startDispatch':
+ case 'agent.started':
+ case 'agent.startFailed': {
+ const start = state.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
+ if (start.actorKey !== actorKey(actor)) fail('FORBIDDEN', 'Only the initiating lead can complete this start.', 403)
+ if (person(state, start.contributorId).generation !== start.membershipGeneration) fail('FORBIDDEN', 'This contribution was withdrawn.', 403)
+ controls(state, actor, start.request.conversationId)
+ if (command.type === 'agent.startDispatch') {
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ open(state, start.request.conversationId)
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'The original machine grant is unavailable.', 403)
+ if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {
+ fail('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.', 403)
+ }
+ if (start.dispatched || start.error || start.harnessId) fail('START_CLAIMED', 'This native start was already requested. Read its creation status; do not start another.')
+ start.dispatched = true
+ break
+ }
+ if (command.type === 'agent.startFailed') {
+ if (start.harnessId) fail('ALREADY_STARTED', 'This agent already started.')
+ start.error = command.error
+ message(start.request.conversationId, `Could not start ${start.request.name}: ${command.error}`)
+ break
+ }
+ if (start.error) fail('START_FAILED', 'This start failed. Use a new start request.')
+ if (start.harnessId && start.harnessId !== command.harnessId) fail('ALREADY_STARTED', 'This start already has a native harness.')
+ const grant = context.contribution ?? fail('HOST_REQUIRED', 'The original machine grant is unavailable.', 403)
+ if (grant.machineOwnerId !== start.machineOwnerId || grant.contributorId !== start.contributorId ||
+ (grant.hostGrant ?? null) !== start.hostGrant) fail('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.', 403)
+ const group = open(state, start.request.conversationId)
+ const agentId = stableId(start.request.machineId, command.harnessId)
+ if (state.agents.some(a => a.id === agentId)) fail('ALREADY_SHARED', 'This native harness is already in the tab.')
+ state.agents.push({ id: agentId, machineId: start.request.machineId, harnessId: command.harnessId,
+ machineOwnerId: start.machineOwnerId, contributorId: start.contributorId, membershipGeneration: start.membershipGeneration,
+ hostGrant: start.hostGrant, name: start.request.name, configuration: command.configuration, configurationVersion: operationId })
+ group.agentIds.push(agentId)
+ start.harnessId = command.harnessId
+ result.agentId = agentId
+ message(group.id, `${start.request.name} joined. Ready for an assignment.`)
+ break
+ }
+ case 'agent.configuration': {
+ if (actor.kind !== 'agent') fail('HOST_REQUIRED', 'Only the execution host can record an observed configuration.', 403)
+ const target = agent(state, actor.agentId)
+ if ((target.configurationVersion ?? null) !== command.previousVersion) {
+ fail('STALE_CONFIGURATION', 'Read the current agent configuration before reporting another observation.')
+ }
+ if (Object.entries(command.configuration).some(([key, value]) => target.configuration[key as keyof typeof target.configuration] !== value)) {
+ target.configuration = command.configuration
+ target.configurationVersion = operationId
+ }
+ break
+ }
+ case 'agent.remove': {
+ const target = agent(state, command.agentId)
+ if (actor.kind !== 'person' || (actor.userId !== state.ownerId && actor.userId !== target.contributorId)) {
+ fail('FORBIDDEN', 'Only the contributor or tab owner can withdraw this agent.', 403)
+ }
+ removeAgent(target)
+ break
+ }
+ case 'conversation.agent': {
+ controls(state, actor, command.conversationId)
+ const group = open(state, command.conversationId)
+ agent(state, command.agentId)
+ if (!command.present) {
+ if (activeWork(group) && (group.assignment?.agentId === command.agentId || group.leadId === command.agentId)) {
+ fail('WORK_ACTIVE', 'Reconcile this agent’s assignment before removing it from the conversation.')
+ }
+ group.agentIds = group.agentIds.filter(id => id !== command.agentId)
+ if (group.leadId === command.agentId) group.leadId = null
+ } else {
+ if (!group.agentIds.includes(command.agentId)) group.agentIds.push(command.agentId)
+ if (command.lead) {
+ if (group.leadId && group.leadId !== command.agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')
+ group.leadId = command.agentId
+ }
+ }
+ break
+ }
+ case 'invite.create': {
+ owner(state, actor)
+ conversation(state, command.conversationId)
+ const email = command.email.trim().toLowerCase()
+ if (state.people.some(p => p.email === email)) fail('ALREADY_MEMBER', 'This person is already in the Super Tab.')
+ state.invitations = state.invitations.filter(i => i.email !== email)
+ state.invitations.push({ id: operationId, email, role: command.role, conversationId: command.conversationId,
+ expiresAt: context.now + 7 * 86_400_000 })
+ result.inviteId = operationId
+ break
+ }
+ case 'invite.revoke':
+ owner(state, actor)
+ state.invitations = state.invitations.filter(i => i.id !== command.inviteId)
+ break
+ case 'member.remove': {
+ if (actor.kind !== 'person' || (actor.userId !== state.ownerId && actor.userId !== command.userId)) {
+ fail('FORBIDDEN', 'Only the owner can remove another person.', 403)
+ }
+ if (command.userId === state.ownerId) fail('OWNER_REQUIRED', 'The owner cannot leave their Super Tab.')
+ const member = person(state, command.userId)
+ for (const target of state.agents.filter(a => a.contributorId === member.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
+ break
+ }
+ case 'message.send': {
+ const group = open(state, command.conversationId)
+ if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the conversation.', 403)
+ if (command.replyTo && (!context.reply || context.reply.id !== command.replyTo || context.reply.conversationId !== group.id)) {
+ fail('INVALID_REPLY', 'Reply to a message in this conversation.', 400)
+ }
+ const replyAgent = context.reply?.author.kind === 'agent' ? context.reply.author.id : null
+ const automatic = actor.kind === 'person' ? (replyAgent && group.agentIds.includes(replyAgent) ? replyAgent : group.leadId) : null
+ const recipients = [...new Set(command.recipientIds.length ? command.recipientIds : automatic ? [automatic] : [])]
+ for (const id of recipients) {
+ agent(state, id)
+ if (!group.agentIds.includes(id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)
+ }
+ // The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.
+ message(group.id, command.text, recipients, command.replyTo)
+ break
+ }
+ case 'delivery.resolve': {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person must inspect an uncertain delivery before resolving it.', 403)
+ const delivery = context.delivery
+ if (!delivery || delivery.id !== command.deliveryId) fail('DELIVERY_RESOLVED', 'This delivery no longer needs checking.')
+ const group = conversation(state, delivery.conversationId)
+ const target = agent(state, delivery.agentId)
+ if (command.resolution === 'resend') {
+ open(state, group.id)
+ if (!group.agentIds.includes(target.id)) fail('INVALID_RECIPIENT', 'This agent is no longer in the conversation.', 400)
+ message(group.id, delivery.text, [target.id], delivery.messageId)
+ } else {
+ message(group.id, command.resolution === 'received'
+ ? `Checked ${target.name}’s terminal and confirmed the earlier instruction was received.`
+ : `Dismissed the delivery warning for ${target.name}. This does not stop work already received.`, [], delivery.messageId)
+ }
+ result.deliveryId = delivery.id
+ result.resolution = command.resolution
+ break
+ }
+ case 'work.define': {
+ controls(state, actor, command.conversationId)
+ const group = open(state, command.conversationId)
+ if (activeWork(group)) fail('WORK_ACTIVE', 'Finish or stop the current assignment before changing its acceptance checks.')
+ rememberAttempt(group)
+ group.assignment = null
+ group.brief = command.brief
+ group.checks = command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null }))
+ message(group.id, command.brief)
+ break
+ }
+ case 'work.assign': {
+ controls(state, actor, command.conversationId)
+ const group = open(state, command.conversationId)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')
+ if (activeWork(group)) fail('WORK_ACTIVE', 'The current assignment must finish or be reconciled before reassignment.')
+ if (!group.brief || !group.checks.length) fail('BRIEF_REQUIRED', 'Record the brief and acceptance checks before assigning work.', 400)
+ const worker = agent(state, command.agentId)
+ if (state.conversations.some(c => activeWork(c) && c.assignment?.agentId === worker.id)) fail('AGENT_BUSY', 'This agent already owns an active assignment.')
+ if (!group.agentIds.includes(worker.id)) group.agentIds.push(worker.id)
+ rememberAttempt(group)
+ group.assignment = { id: operationId, agentId: worker.id, status: 'working', configuration: structuredClone(worker.configuration),
+ execution: { machineId: worker.machineId, harnessId: worker.harnessId, machineOwnerId: worker.machineOwnerId }, result: null }
+ group.checks.forEach(c => { c.evidence = null; c.passedBy = null })
+ result.assignmentId = operationId
+ message(group.id, `${group.brief}\n\nAcceptance checks:\n${group.checks.map(c => `- ${c.description}`).join('\n')}`, [worker.id])
+ break
+ }
+ case 'work.status': {
+ const group = open(state, command.conversationId)
+ const assignment = group.assignment
+ if (!assignment || assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
+ if (!activeWork(group)) fail('ATTEMPT_CLOSED', 'Assign a new attempt to continue this work.')
+ if (actor.kind === 'agent' && actor.agentId !== assignment.agentId && actor.agentId !== group.leadId) fail('FORBIDDEN', 'Only the assigned agent or coordinating lead can update this work.', 403)
+ if (command.status === 'stopped' && !context.confirmedStopped) fail('STOP_UNCONFIRMED', 'Wait for the execution host to confirm the stop.')
+ if (assignment.status === 'reconciling' && command.status !== 'stopped') fail('RECONCILING', 'Reconcile the previous assignment before continuing.')
+ if (command.status === 'done' && (!command.result || !group.checks.every(c => c.passedBy && c.evidence))) {
+ fail('CHECKS_PENDING', 'Completion needs a result and evidence for every acceptance check.')
+ }
+ const changed = assignment.status !== command.status || assignment.result !== command.result
+ assignment.status = command.status
+ assignment.result = command.result
+ if (changed) {
+ const label = { working: 'Working', needs_human: 'Needs a human', review: 'Ready for review', done: 'Done', stopped: 'Stopped' }[command.status]
+ const lead = group.leadId
+ const tellLead = actor.kind === 'agent' && actor.agentId === assignment.agentId && lead && lead !== actor.agentId &&
+ ['needs_human', 'review', 'done'].includes(command.status)
+ message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}`, tellLead ? [lead] : [])
+ }
+ break
+ }
+ case 'work.check': {
+ const group = open(state, command.conversationId)
+ if (!group.assignment || group.assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
+ if (!activeWork(group)) fail('ATTEMPT_CLOSED', 'Assign a new attempt before changing its acceptance evidence.')
+ if (group.assignment.status === 'reconciling') fail('RECONCILING', 'Reconcile the previous assignment before continuing.')
+ const check = group.checks.find(c => c.id === command.checkId) ?? fail('NOT_FOUND', 'This acceptance check is unavailable.', 404)
+ if (actor.kind === 'agent' && !group.agentIds.includes(actor.agentId)) fail('FORBIDDEN', 'This agent does not participate in the review.', 403)
+ if (check.independent && actor.kind === 'agent' && actor.agentId === group.assignment.agentId) fail('INDEPENDENT_REVIEW', 'Another agent or a person must perform this check.')
+ check.evidence = command.evidence
+ check.passedBy = command.passed ? actorKey(actor) : null
+ break
+ }
+ }
+ // MongoDB limits a document to 16 MiB. Leave room for indexes and metadata, and refuse before losing state.
+ if (Buffer.byteLength(JSON.stringify(state)) > 8 * 1024 * 1024) fail('TAB_TOO_LARGE', 'This Super Tab has reached its metadata limit.', 413)
+ return effects
+}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
new file mode 100644
index 000000000..569a3cffa
--- /dev/null
+++ b/backend/src/superTabs/model.ts
@@ -0,0 +1,170 @@
+import { createHash } from 'node:crypto'
+
+export type Role = 'owner' | 'collaborator' | 'viewer'
+export interface Person { id: string; email: string; role: Role; generation: string }
+export interface AgentConfiguration {
+ engine: string
+ model: string | null
+ effort: string | null
+ contextWindow: number | null
+ engineVersion: string | null
+}
+export interface Agent {
+ id: string
+ machineId: string
+ harnessId: string
+ machineOwnerId: string
+ contributorId: string
+ membershipGeneration: string
+ hostGrant?: string | null
+ name: string
+ configuration: AgentConfiguration
+ /** The last configuration operation fences delayed observations, including re-contribution. */
+ configurationVersion?: string
+}
+export interface AgentStartRequest {
+ conversationId: string
+ machineId: string
+ engine: string
+ name: string
+ cwd: string
+ worktree: boolean
+ branchRef?: string
+ permissionMode?: string
+ codexHome?: string
+ gridModel?: string
+ gridName?: string
+ requirements: { memoryBytes: number; diskBytes: number; maxCpuPercent: number; tools: string[]; devices: string[]; quotaRequired: boolean }
+}
+export interface AgentStart {
+ id: string
+ creationId: string
+ actorKey: string
+ contributorId: string
+ membershipGeneration: string
+ machineOwnerId: string
+ hostGrant: string | null
+ request: AgentStartRequest
+ harnessId: string | null
+ dispatched: boolean
+ error: string | null
+}
+export type WorkStatus = 'planned' | 'working' | 'needs_human' | 'review' | 'done' | 'stopped' | 'reconciling'
+export interface Check {
+ id: string
+ description: string
+ independent: boolean
+ evidence: string | null
+ passedBy: string | null
+}
+export interface Assignment {
+ id: string
+ agentId: string
+ status: WorkStatus
+ configuration: AgentConfiguration
+ execution: { machineId: string; harnessId: string; machineOwnerId: string }
+ result: string | null
+}
+export interface Conversation {
+ id: string
+ title: string
+ leadId: string | null
+ agentIds: string[]
+ archived: boolean
+ brief: string
+ checks: Check[]
+ assignment: Assignment | null
+ lastMessageSequence: number
+}
+export interface Invitation {
+ id: string
+ email: string
+ role: 'collaborator' | 'viewer'
+ conversationId: string
+ expiresAt: number
+}
+export interface SuperTabState {
+ version: 1
+ id: string
+ name: string
+ ownerId: string
+ environment: string
+ paused: boolean
+ people: Person[]
+ agents: Agent[]
+ conversations: Conversation[]
+ invitations: Invitation[]
+ starts?: AgentStart[]
+}
+export type Actor =
+ | { kind: 'person'; userId: string; email: string }
+ | { kind: 'agent'; agentId: string; machineOwnerId: string }
+export interface Author { kind: 'person' | 'agent'; id: string; name: string; membershipGeneration: string }
+export interface MessageDraft {
+ id: string
+ conversationId: string
+ author: Author
+ text: string
+ replyTo: string | null
+ recipients: string[]
+}
+export interface CommandEffects {
+ state: SuperTabState
+ messages: MessageDraft[]
+ cancelledAgents: string[]
+ previousAttempts: Array<{ conversationId: string; brief: string; checks: Check[]; assignment: Assignment }>
+ result: Record<string, unknown>
+}
+export class SuperTabError extends Error {
+ constructor(readonly code: string, message: string, readonly status = 409) {
+ super(message)
+ this.name = 'SuperTabError'
+ }
+}
+export function fail(code: string, message: string, status = 409): never { throw new SuperTabError(code, message, status) }
+export const stableId = (...parts: string[]): string => createHash('sha256').update(JSON.stringify(parts)).digest('hex').slice(0, 24)
+export const actorKey = (actor: Actor): string => actor.kind === 'person' ? `person:${actor.userId}` : `agent:${actor.agentId}`
+export const activeWork = (group: Conversation): boolean => !!group.assignment &&
+ !['done', 'stopped'].includes(group.assignment.status)
+
+export function person(state: SuperTabState, id: string): Person {
+ return state.people.find(p => p.id === id) ?? fail('FORBIDDEN', 'You no longer have access to this Super Tab.', 403)
+}
+export function agent(state: SuperTabState, id: string): Agent {
+ const found = state.agents.find(a => a.id === id) ?? fail('AGENT_UNAVAILABLE', 'This agent is no longer in the Super Tab.')
+ if (person(state, found.contributorId).generation !== found.membershipGeneration) {
+ fail('AGENT_UNAVAILABLE', 'This agent must be shared again before it can participate.')
+ }
+ return found
+}
+export function conversation(state: SuperTabState, id: string): Conversation {
+ return state.conversations.find(c => c.id === id) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404)
+}
+export function author(state: SuperTabState, actor: Actor, write = false): Author {
+ if (actor.kind === 'person') {
+ const member = person(state, actor.userId)
+ if (write && member.role === 'viewer') fail('READ_ONLY', 'You have read-only access to this Super Tab.', 403)
+ return { kind: 'person', id: member.id, name: member.email, membershipGeneration: member.generation }
+ }
+ const member = agent(state, actor.agentId)
+ if (member.machineOwnerId !== actor.machineOwnerId) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)
+ if (write && person(state, member.contributorId).role === 'viewer') fail('READ_ONLY', 'This contribution is read-only.', 403)
+ return { kind: 'agent', id: member.id, name: member.name, membershipGeneration: member.membershipGeneration }
+}
+
+export function createSuperTab(id: string, name: string, owner: { id: string; email: string }, environment: string): SuperTabState {
+ return {
+ version: 1, id, name, ownerId: owner.id, environment, paused: false,
+ people: [{ ...owner, email: owner.email.trim().toLowerCase(), role: 'owner', generation: id }],
+ agents: [], invitations: [],
+ conversations: [{ id: 'lead', title: 'Lead', leadId: null, agentIds: [], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0 }],
+ }
+}
+
+/** Pending invitations are management data, not part of the shared conversation. */
+export function visibleState(state: SuperTabState, actor: Actor): SuperTabState {
+ author(state, actor)
+ const visible = structuredClone(state)
+ if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []
+ return visible
+}
diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.ts
new file mode 100644
index 000000000..b10a72556
--- /dev/null
+++ b/backend/src/superTabs/native.ts
@@ -0,0 +1,176 @@
+import { createHash } from 'node:crypto'
+import type { Prisma, SuperTab, SuperTabNativeContext } from '@prisma/client'
+import { z } from 'zod'
+import type { AuthUser } from '../lib/ssoAuth.js'
+import { activeWork, agent, author, conversation, fail, stableId, SuperTabError,
+ type Actor, type Agent, type Author, type SuperTabState } from './model.js'
+
+const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
+export const openNativeSchema = z.object({ operationId: id, conversationId: id, agentId: id }).strict()
+export const nativeEventSchema = z.object({
+ turnId: id, kind: z.enum(['prompt', 'answer', 'gap']), previousEventId: id.nullable(),
+ text: z.string().max(16_000), truncated: z.boolean(), interrupted: z.boolean(),
+}).strict()
+type NativeEvent = z.infer<typeof nativeEventSchema>
+type Transaction = Prisma.TransactionClient
+type Grant = { machineOwnerId: string; contributorId: string; hostGrant: string | null }
+interface Binding {
+ tabId: string; conversationId: string; agentId: string; harnessId: string; machineId: string; machineOwnerId: string
+ operator: Author; contributorId: string; contributionGeneration: string; contributionGrant: string | null; inputGrant: string | null
+}
+interface Deps {
+ transaction<T>(body: (tx: Transaction) => Promise<T>): Promise<T>
+ row(tx: Transaction, user: AuthUser, tabId: string): Promise<{ row: SuperTab; state: SuperTabState }>
+ agentGrant(tx: Transaction, state: SuperTabState, target: Agent): Promise<void>
+ contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }): Promise<Grant>
+}
+const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
+const digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex')
+
+/** A host reports what its native engine observed; it cannot create human-authored
+ * messages. The human attached to the source is the authenticated opener of that
+ * terminal context, not an inference from a device name or the machine owner. */
+export class SuperTabNativeStore {
+ constructor(private readonly deps: Deps) {}
+
+ private async validate(tx: Transaction, state: SuperTabState, record: SuperTabNativeContext) {
+ if (record.revoked) fail('NATIVE_CONTEXT_REVOKED', 'Reopen the terminal from this conversation.', 403)
+ const binding = record.binding as unknown as Binding
+ const operator = author(state, { kind: 'person', userId: binding.operator.id, email: binding.operator.name }, true)
+ const target = agent(state, record.agentId)
+ const group = conversation(state, record.conversationId)
+ if (operator.membershipGeneration !== binding.operator.membershipGeneration || group.archived || !group.agentIds.includes(target.id)
+ || target.harnessId !== binding.harnessId || target.machineId !== binding.machineId || target.machineOwnerId !== binding.machineOwnerId
+ || target.contributorId !== binding.contributorId || target.membershipGeneration !== binding.contributionGeneration
+ || (target.hostGrant ?? null) !== binding.contributionGrant) {
+ fail('NATIVE_CONTEXT_REVOKED', 'This terminal context no longer belongs to the current contribution.', 403)
+ }
+ await this.deps.agentGrant(tx, state, target)
+ // Read the person's current identity, rather than trusting a name supplied by
+ // a terminal client or reusing an old email after an account change.
+ const user = await tx.user.findUnique({ where: { id: operator.id }, select: { email: true, autonomousEnv: true } })
+ if (!user || user.autonomousEnv !== state.environment) fail('NATIVE_CONTEXT_REVOKED', 'The terminal opener is unavailable.', 403)
+ const grant = await this.deps.contribution(tx, state, { kind: 'person', userId: operator.id, email: user.email }, target)
+ if (grant.machineOwnerId !== binding.machineOwnerId || grant.hostGrant !== binding.inputGrant) {
+ fail('NATIVE_CONTEXT_REVOKED', 'The terminal opener no longer has the original machine access.', 403)
+ }
+ return { binding, target, group }
+ }
+
+ async open(user: AuthUser, tabId: string, input: z.infer<typeof openNativeSchema>) {
+ const request = openNativeSchema.parse(input)
+ return this.deps.transaction(async tx => {
+ const { state } = await this.deps.row(tx, user, tabId)
+ const operator = author(state, { kind: 'person', userId: user.sub, email: user.email }, true)
+ const target = agent(state, request.agentId), group = conversation(state, request.conversationId)
+ if (group.archived || !group.agentIds.includes(target.id)) fail('AGENT_UNAVAILABLE', 'Choose an agent in this conversation.')
+ await this.deps.agentGrant(tx, state, target)
+ const grant = await this.deps.contribution(tx, state, { kind: 'person', userId: user.sub, email: user.email }, target)
+ const contextId = stableId('native', tabId, user.sub, request.operationId)
+ const prior = await tx.superTabNativeContext.findUnique({ where: { id: contextId } })
+ if (prior) {
+ if (prior.conversationId !== request.conversationId || prior.agentId !== request.agentId) fail('OPERATION_REUSED', 'Use a new operation ID for a different terminal.')
+ await this.validate(tx, state, prior)
+ return { contextId }
+ }
+ const binding: Binding = { tabId, conversationId: group.id, agentId: target.id, harnessId: target.harnessId,
+ machineId: target.machineId, machineOwnerId: target.machineOwnerId, operator,
+ contributorId: target.contributorId, contributionGeneration: target.membershipGeneration,
+ contributionGrant: target.hostGrant ?? null, inputGrant: grant.hostGrant }
+ await tx.superTabNativeContext.create({ data: { id: contextId, tabId, conversationId: group.id,
+ agentId: target.id, userId: user.sub, binding: json(binding) } })
+ return { contextId }
+ })
+ }
+
+ private async hosted(tx: Transaction, user: AuthUser, tabId: string, contextId: string) {
+ const { row, state } = await this.deps.row(tx, user, tabId)
+ const record = await tx.superTabNativeContext.findFirst({ where: { id: contextId, tabId } })
+ ?? fail('NOT_FOUND', 'This terminal context is unavailable.', 404)
+ const binding = record.binding as unknown as Binding
+ if (binding.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can record this terminal.', 403)
+ const verified = await this.validate(tx, state, record)
+ return { ...verified, row, state, record }
+ }
+
+ async read(user: AuthUser, tabId: string, contextId: string) {
+ return this.deps.transaction(async tx => {
+ const { binding, record } = await this.hosted(tx, user, tabId, contextId)
+ return { contextId, ...binding, lastEventId: record.lastEventId }
+ })
+ }
+
+ async allowsDelivery(tx: Transaction, state: SuperTabState, contextId: string): Promise<boolean> {
+ const record = await tx.superTabNativeContext.findFirst({ where: { id: contextId, tabId: state.id } })
+ if (!record) return false
+ try { await this.validate(tx, state, record); return true }
+ catch (error) { if (error instanceof SuperTabError) return false; throw error }
+ }
+
+ async append(user: AuthUser, tabId: string, contextId: string, input: NativeEvent) {
+ const event = nativeEventSchema.parse(input)
+ return this.deps.transaction(async tx => {
+ const { row, state, record, binding, target, group } = await this.hosted(tx, user, tabId, contextId)
+ const eventId = stableId('native-event', contextId, event.turnId, event.kind), requestHash = digest(event)
+ const prior = await tx.superTabOperation.findUnique({ where: { id: eventId } })
+ if (prior) {
+ if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'This native observation already has different content.')
+ return prior.result
+ }
+ if (record.lastEventId !== event.previousEventId) fail('NATIVE_ORDER_CHANGED', 'Reconcile the recorded terminal observations before continuing.')
+ const promptId = stableId('native-event', contextId, event.turnId, 'prompt')
+ if (event.kind === 'answer' && !await tx.superTabOperation.findUnique({ where: { id: promptId } })) {
+ fail('NATIVE_PROMPT_MISSING', 'The terminal prompt was not recorded. Record the observation gap first.')
+ }
+ const revision = row.revision + 1
+ group.lastMessageSequence = revision
+ const observedBy = author(state, { kind: 'agent', agentId: target.id, machineOwnerId: user.sub }, true)
+ const text = event.kind === 'gap' ? 'Some terminal activity could not be recorded. Check the native session for the full conversation.' : event.text
+ // Inform the coordinating lead without replaying this input into the agent
+ // that already received it. Its resulting programmatic turn is not native input.
+ const recipients = event.kind !== 'gap' && group.leadId && group.leadId !== target.id ? [group.leadId] : []
+ await tx.superTabMessage.create({ data: { id: eventId, tabId, conversationId: group.id, sequence: revision,
+ author: json(observedBy), source: json({ kind: 'native', phase: event.kind, turnId: event.turnId,
+ operator: binding.operator, truncated: event.truncated, interrupted: event.interrupted }),
+ text, replyTo: event.kind === 'answer' ? promptId : null, recipientIds: recipients } })
+ for (const recipient of recipients) {
+ const lead = agent(state, recipient)
+ await tx.superTabDelivery.create({ data: { id: stableId(eventId, recipient), tabId, conversationId: group.id,
+ messageId: eventId, nativeContextId: contextId, agentId: recipient, machineId: lead.machineId, machineOwnerId: lead.machineOwnerId,
+ assignmentId: activeWork(group) && group.assignment?.agentId === recipient ? group.assignment.id : null,
+ membershipGeneration: lead.membershipGeneration, authorKind: 'person', authorId: binding.operator.id,
+ authorGeneration: binding.operator.membershipGeneration } })
+ }
+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision, state: json(state) } })
+ await tx.superTabNativeContext.update({ where: { id: contextId }, data: { lastEventId: eventId } })
+ const result = { eventId, revision }
+ await tx.superTabOperation.create({ data: { id: eventId, tabId, actorKey: `agent:${target.id}`, requestHash, revision, result } })
+ return result
+ })
+ }
+}
+
+/** Removal followed by rejoining must not revive an old terminal binding. */
+export async function revokeNativeContexts(tx: Transaction, before: SuperTabState, after: SuperTabState) {
+ const conditions: Prisma.SuperTabNativeContextWhereInput[] = []
+ for (const member of before.people) {
+ const current = after.people.find(p => p.id === member.id)
+ if (!current || current.generation !== member.generation || current.role === 'viewer') conditions.push({ userId: member.id })
+ }
+ for (const target of before.agents) if (!after.agents.some(a => a.id === target.id)) conditions.push({ agentId: target.id })
+ for (const group of before.conversations) {
+ const current = after.conversations.find(c => c.id === group.id)
+ if (!current || current.archived) conditions.push({ conversationId: group.id })
+ else {
+ const removed = group.agentIds.filter(id => !current.agentIds.includes(id))
+ if (removed.length) conditions.push({ conversationId: group.id, agentId: { in: removed } })
+ }
+ }
+ if (conditions.length) {
+ const where = { tabId: before.id, revoked: false, OR: conditions }
+ const revoked = await tx.superTabNativeContext.findMany({ where, select: { id: true } })
+ await tx.superTabNativeContext.updateMany({ where, data: { revoked: true } })
+ if (revoked.length) await tx.superTabDelivery.updateMany({ where: { tabId: before.id,
+ nativeContextId: { in: revoked.map(r => r.id) }, status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })
+ }
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
new file mode 100644
index 000000000..d6e9b317f
--- /dev/null
+++ b/backend/src/superTabs/store.ts
@@ -0,0 +1,459 @@
+import { createHash } from 'node:crypto'
+import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery } from '@prisma/client'
+import type { AuthUser } from '../lib/ssoAuth.js'
+import { machineAlive } from '../lib/prisma.js'
+import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
+import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
+import { applyCommand, operationSchema, type Command, type CommandContext } from './commands.js'
+import { revokeNativeContexts, SuperTabNativeStore } from './native.js'
+import {
+ activeWork, actorKey, agent, author, conversation, createSuperTab, fail, person, stableId, visibleState,
+ SuperTabError, type Actor, type Agent, type Author, type SuperTabState,
+} from './model.js'
+
+type Transaction = Prisma.TransactionClient
+const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
+const hash = (value: unknown): string => createHash('sha256').update(JSON.stringify(value)).digest('hex')
+const stateOf = (row: SuperTab): SuperTabState => {
+ const state = row.state as unknown as SuperTabState
+ if (state.version !== 1) fail('UPDATE_REQUIRED', 'Update Harness to open this Super Tab.', 409)
+ return state
+}
+const indexes = (state: SuperTabState) => ({
+ memberIds: state.people.map(p => p.id), invitedEmails: state.invitations.map(i => i.email),
+ machineIds: [...new Set([...state.agents.map(a => a.machineId),
+ ...state.conversations.filter(activeWork).map(c => c.assignment!.execution.machineId)])],
+})
+
+/** Retrying a transaction never repeats a host action. All effects here are durable database writes. */
+async function transaction<T>(db: PrismaClient, body: (tx: Transaction) => Promise<T>): Promise<T> {
+ for (let attempt = 0; ; attempt++) {
+ try { return await db.$transaction(body) } catch (error) {
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null
+ if (attempt >= 4 || (code !== 'P2034' && code !== 'P2002')) throw error
+ }
+ }
+}
+
+/** Persistent coordination. Host adapters own execution and must confirm their local session grants. */
+export class SuperTabStore {
+ readonly native: SuperTabNativeStore
+ constructor(private readonly db: PrismaClient, private readonly now: () => number = Date.now) {
+ this.native = new SuperTabNativeStore({
+ transaction: body => transaction(db, body),
+ row: async (tx, user, tabId) => { const row = await this.row(tx, user, tabId); return { row, state: stateOf(row) } },
+ agentGrant: (tx, state, target) => this.agentGrant(tx, state, target),
+ contribution: (tx, state, actor, command) => this.contribution(tx, state, actor, command),
+ })
+ }
+
+ private async row(tx: Transaction, user: AuthUser, tabId: string) {
+ return await tx.superTab.findFirst({ where: { id: tabId, autonomousEnv: user.autonomousEnv } }) ??
+ fail('NOT_FOUND', 'This Super Tab is unavailable.', 404)
+ }
+
+ private async actor(tx: Transaction, user: AuthUser, state: SuperTabState, agentId?: string): Promise<Actor> {
+ if (!agentId) return { kind: 'person', userId: user.sub, email: user.email }
+ const target = agent(state, agentId)
+ if (target.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)
+ await this.agentGrant(tx, state, target)
+ return { kind: 'agent', agentId, machineOwnerId: user.sub }
+ }
+
+ private async agentGrant(tx: Transaction, state: SuperTabState, target: Agent): Promise<void> {
+ const machine = await tx.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId,
+ autonomousEnv: state.environment, ...machineAlive } })
+ if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ if (target.contributorId !== machine.userId) {
+ person(state, target.contributorId)
+ const contributor = await tx.user.findUnique({ where: { id: target.contributorId }, select: { email: true, autonomousEnv: true } })
+ const share = await tx.machineShare.findUnique({ where: { machineId: machine.machineId } })
+ if (!contributor || contributor.autonomousEnv !== state.environment || !share || share.ownerId !== machine.userId ||
+ share.autonomousEnv !== state.environment || !sharedVia(share, contributor.email) ||
+ machineShareGrant(share, contributor.email) !== target.hostGrant) {
+ fail('CONTRIBUTION_REVOKED', 'The contributor no longer has access to this machine.', 403)
+ }
+ }
+ }
+
+ private async contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }) {
+ const contributorId = actor.kind === 'person' ? actor.userId : agent(state, actor.agentId).contributorId
+ person(state, contributorId)
+ const machine = await tx.machine.findFirst({ where: { machineId: command.machineId, autonomousEnv: state.environment, ...machineAlive } })
+ if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This machine is unavailable.', 403)
+ let hostGrant: string | null = null
+ if (machine.userId !== contributorId) {
+ const contributor = actor.kind === 'person' ? { email: actor.email, autonomousEnv: state.environment } :
+ await tx.user.findUnique({ where: { id: contributorId }, select: { email: true, autonomousEnv: true } })
+ const share = await tx.machineShare.findUnique({ where: { machineId: command.machineId } })
+ if (!contributor || contributor.autonomousEnv !== state.environment || !share || share.ownerId !== machine.userId ||
+ share.autonomousEnv !== state.environment || !sharedVia(share, contributor.email)) {
+ fail('HOST_REQUIRED', 'This machine has not been shared with the contributor.', 403)
+ }
+ hostGrant = machineShareGrant(share, contributor.email)
+ }
+ return { machineOwnerId: machine.userId, contributorId, hostGrant }
+ }
+
+ async create(user: AuthUser, operationId: string, name: string) {
+ const id = stableId('super-tab', user.autonomousEnv, user.sub, operationId)
+ const requestHash = hash({ name })
+ return transaction(this.db, async tx => {
+ const prior = await tx.superTabOperation.findUnique({ where: { id } })
+ if (prior) {
+ if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')
+ return { id, revision: prior.revision }
+ }
+ const state = createSuperTab(id, name, { id: user.sub, email: user.email }, user.autonomousEnv)
+ await tx.superTab.create({ data: { id, ownerId: user.sub, autonomousEnv: user.autonomousEnv, ...indexes(state), state: json(state) } })
+ await tx.superTabOperation.create({ data: { id, tabId: id, actorKey: `person:${user.sub}`, requestHash, revision: 0, result: { id } } })
+ return { id, revision: 0 }
+ })
+ }
+
+ async list(user: AuthUser, after?: string) {
+ const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, memberIds: { has: user.sub },
+ ...(after ? { id: { gt: after } } : {}) }, orderBy: { id: 'asc' }, take: 101 })
+ return { tabs: rows.slice(0, 100).map(row => {
+ const state = stateOf(row)
+ return { id: row.id, name: state.name, ownerId: row.ownerId, revision: row.revision, paused: state.paused }
+ }), next: rows.length > 100 ? rows[99]!.id : null }
+ }
+
+ async invitations(user: AuthUser) {
+ const email = user.email.trim().toLowerCase()
+ const rows = await this.db.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, invitedEmails: { has: email } }, take: 100 })
+ return rows.flatMap(row => {
+ const state = stateOf(row)
+ return state.invitations.filter(i => i.email === email && i.expiresAt > this.now())
+ .map(i => ({ tabId: row.id, name: state.name, inviteId: i.id, role: i.role, expiresAt: i.expiresAt }))
+ })
+ }
+
+ async read(user: AuthUser, tabId: string, asAgentId?: string) {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const state = stateOf(row)
+ const actor = await this.actor(tx, user, state, asAgentId)
+ return { revision: row.revision, state: visibleState(state, actor) }
+ })
+ }
+
+ async start(user: AuthUser, tabId: string, startId: string, asAgentId?: string) {
+ return transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const actor = await this.actor(tx, user, state, asAgentId)
+ author(state, actor, true)
+ const start = state.starts?.find(s => s.id === startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
+ if (start.actorKey !== actorKey(actor) || person(state, start.contributorId).generation !== start.membershipGeneration) {
+ fail('FORBIDDEN', 'Only the original initiating lead can resume this start.', 403)
+ }
+ const group = conversation(state, start.request.conversationId)
+ if (actor.kind === 'agent' && group.leadId !== actor.agentId) fail('LEAD_REQUIRED', 'The coordinating lead changed.', 403)
+ if (group.archived) fail('ARCHIVED', 'This conversation is archived.')
+ if (state.paused && !start.harnessId) fail('PAUSED', 'New work is paused in this Super Tab.')
+ const grant = await this.contribution(tx, state, actor, start.request)
+ if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {
+ fail('CONTRIBUTION_REVOKED', 'This start belongs to a machine grant that was revoked.', 403)
+ }
+ return start
+ })
+ }
+
+ async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string) {
+ const { operationId, command } = operationSchema.parse(input)
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const original = stateOf(row)
+ const actor = await this.actor(tx, user, original, asAgentId)
+ const receiptId = stableId(tabId, actorKey(actor), operationId)
+ const requestHash = hash(command)
+ const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })
+ if (prior) {
+ if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')
+ // A leave may be retried by its original author. Nothing except that operation's receipt is returned.
+ const selfLeave = actor.kind === 'person' && command.type === 'member.remove' && command.userId === actor.userId
+ if (!selfLeave) author(original, actor)
+ return { revision: prior.revision, result: prior.result }
+ }
+ if (command.type !== 'invite.accept') author(original, actor)
+ const context: CommandContext = { operationId, now: this.now() }
+ if (command.type === 'delivery.resolve') {
+ author(original, actor, true)
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person must inspect an uncertain delivery before resolving it.', 403)
+ const delivery = await tx.superTabDelivery.findFirst({ where: { id: command.deliveryId, tabId } })
+ if (!delivery || delivery.status !== 'uncertain') fail('DELIVERY_RESOLVED', 'This delivery no longer needs checking.')
+ const message = await tx.superTabMessage.findUnique({ where: { id: delivery.messageId } })
+ if (!message) fail('NOT_FOUND', 'The original instruction is unavailable.', 404)
+ if (command.resolution === 'resend') {
+ if (!this.deliveryAllowed(original, delivery) || !await this.senderAllowed(tx, original, delivery)) {
+ fail('DELIVERY_REVOKED', 'This instruction is no longer authorized.', 403)
+ }
+ await this.agentGrant(tx, original, agent(original, delivery.agentId))
+ }
+ context.delivery = { ...delivery, text: message.text }
+ await tx.superTabDelivery.update({ where: { id: delivery.id }, data: {
+ status: command.resolution === 'received' ? 'confirmed' : command.resolution === 'resend' ? 'superseded' : 'cancelled',
+ // The native receipt remains intact; the operation records the person's resolution.
+ } })
+ }
+ if (command.type === 'agent.add') context.contribution = await this.contribution(tx, original, actor, command)
+ if (command.type === 'agent.start') context.contribution = await this.contribution(tx, original, actor, command.request)
+ if (command.type === 'agent.started' || command.type === 'agent.startDispatch') {
+ const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)
+ context.contribution = await this.contribution(tx, original, actor, start.request)
+ }
+ if (command.type === 'message.send' && command.replyTo) {
+ const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })
+ if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author }
+ }
+ if (command.type === 'work.status' && command.status === 'stopped') {
+ const proof = await tx.superTabStopReceipt.findUnique({ where: { tabId_assignmentId: { tabId, assignmentId: command.assignmentId } } })
+ const execution = conversation(original, command.conversationId).assignment?.execution
+ context.confirmedStopped = !!proof && !!execution && proof.machineId === execution.machineId &&
+ proof.harnessId === execution.harnessId && proof.machineOwnerId === execution.machineOwnerId
+ }
+ const effects = applyCommand(original, actor, command, context)
+ await revokeNativeContexts(tx, original, effects.state)
+ const revision = row.revision + 1
+ if (command.type === 'agent.add' || command.type === 'agent.started' || command.type === 'agent.configuration') {
+ for (const target of effects.state.agents) {
+ if (target.configurationVersion !== receiptId) continue
+ const previous = original.agents.find(a => a.id === target.id)
+ if (previous?.configurationVersion === target.configurationVersion) continue
+ await tx.superTabConfiguration.create({ data: {
+ id: stableId(tabId, target.id, operationId), tabId, agentId: target.id, revision,
+ configuration: json(target.configuration), actorKey: actorKey(actor), observedAt: new Date(context.now),
+ assignmentIds: effects.state.conversations.filter(group => activeWork(group) && group.assignment?.agentId === target.id)
+ .map(group => group.assignment!.id),
+ } })
+ }
+ }
+ for (const message of effects.messages) conversation(effects.state, message.conversationId).lastMessageSequence = revision
+ if (command.type === 'work.assign') {
+ const assigned = conversation(effects.state, command.conversationId).assignment!
+ const running = await tx.superTabRun.findUnique({ where: { id: assigned.agentId } })
+ if (running) fail('AGENT_BUSY', 'This agent already owns active work in a Super Tab.')
+ await tx.superTabRun.create({ data: { id: assigned.agentId, tabId, assignmentId: assigned.id,
+ machineId: assigned.execution.machineId, harnessId: assigned.execution.harnessId } })
+ }
+ for (const group of original.conversations.filter(activeWork)) {
+ const changed = conversation(effects.state, group.id)
+ if (activeWork(changed)) continue
+ await tx.superTabRun.deleteMany({ where: { tabId, assignmentId: group.assignment!.id } })
+ await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId: group.assignment!.id,
+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })
+ }
+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: {
+ revision, state: json(effects.state), ...indexes(effects.state),
+ } })
+ for (const message of effects.messages) {
+ await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,
+ sequence: revision, author: json(message.author), text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })
+ for (const recipient of message.recipients) {
+ const target = agent(effects.state, recipient)
+ const group = conversation(effects.state, message.conversationId)
+ await tx.superTabDelivery.create({ data: { id: stableId(message.id, recipient), tabId,
+ conversationId: message.conversationId, messageId: message.id, agentId: recipient, machineId: target.machineId,
+ machineOwnerId: target.machineOwnerId,
+ assignmentId: activeWork(group) && group.assignment?.agentId === recipient ? group.assignment.id : null,
+ membershipGeneration: target.membershipGeneration, authorKind: message.author.kind,
+ authorId: message.author.id, authorGeneration: message.author.membershipGeneration } })
+ }
+ }
+ const revoked = [
+ ...original.people.filter(p => !effects.state.people.some(n => n.id === p.id && n.generation === p.generation))
+ .map(p => ({ authorKind: 'person', authorId: p.id, authorGeneration: p.generation })),
+ ...original.agents.filter(a => !effects.state.agents.some(n => n.id === a.id && n.membershipGeneration === a.membershipGeneration))
+ .map(a => ({ authorKind: 'agent', authorId: a.id, authorGeneration: a.membershipGeneration })),
+ ]
+ const cancelled: Prisma.SuperTabDeliveryWhereInput[] = [
+ ...revoked, ...(effects.cancelledAgents.length ? [{ agentId: { in: effects.cancelledAgents } }] : []),
+ ]
+ if (cancelled.length) await tx.superTabDelivery.updateMany({ where: { tabId,
+ status: { in: ['queued', 'claimed', 'uncertain'] }, OR: cancelled }, data: { status: 'cancelled' } })
+ for (const attempt of effects.previousAttempts) {
+ await tx.superTabAttempt.create({ data: { id: attempt.assignment.id, tabId, conversationId: attempt.conversationId, snapshot: json(attempt) } })
+ }
+ await tx.superTabOperation.create({ data: { id: receiptId, tabId, actorKey: actorKey(actor), requestHash,
+ revision, result: json(effects.result) } })
+ return { revision, result: effects.result }
+ })
+ }
+
+ async messages(user: AuthUser, tabId: string, conversationId: string, cursor: { after?: number; before?: number; messageId?: string }, asAgentId?: string) {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const state = stateOf(row)
+ author(state, await this.actor(tx, user, state, asAgentId))
+ conversation(state, conversationId)
+ const forward = cursor.after !== undefined
+ const rows = await tx.superTabMessage.findMany({ where: { tabId, conversationId,
+ ...(cursor.messageId ? { id: cursor.messageId } : {}),
+ ...(forward ? { sequence: { gt: cursor.after } } : cursor.before !== undefined ? { sequence: { lt: cursor.before } } : {}) },
+ orderBy: { sequence: forward ? 'asc' : 'desc' }, take: 101 })
+ const page = rows.slice(0, 100)
+ const next = rows.length > 100 ? page.at(-1)!.sequence : null
+ if (!forward) page.reverse()
+ const deliveries = page.length ? await tx.superTabDelivery.findMany({ where: { tabId, messageId: { in: page.map(m => m.id) } },
+ select: { id: true, messageId: true, agentId: true, status: true, receipt: true } }) : []
+ return { messages: page.map(m => ({ ...m, deliveries: deliveries.filter(d => d.messageId === m.id) })), next, revision: row.revision }
+ })
+ }
+
+ /** Host polling discovers only registered sessions on its own machine, never unrelated tab transcripts. */
+ async hostTabs(user: AuthUser, machineId: string) {
+ return transaction(this.db, async tx => {
+ const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, take: 100 })
+ const result = []
+ for (const row of rows) {
+ const state = stateOf(row)
+ const people = await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } })
+ for (const target of state.agents.filter(a => a.machineId === machineId && a.machineOwnerId === user.sub)) {
+ try { agent(state, target.id); await this.agentGrant(tx, state, target) }
+ catch (error) { if (error instanceof SuperTabError) continue; throw error }
+ result.push({ tabId: row.id, revision: row.revision, paused: state.paused, agent: target,
+ observers: people.filter(p => p.id !== user.sub).map(p => ({ email: p.email, userId: p.id })) })
+ }
+ }
+ return result
+ })
+ }
+
+ async mayObserve(user: AuthUser, tabId: string, machineId: string, harnessId: string, machineOwnerId: string): Promise<boolean> {
+ try {
+ return await transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ person(state, user.sub)
+ const target = state.agents.find(a => a.machineId === machineId && a.harnessId === harnessId && a.machineOwnerId === machineOwnerId)
+ if (!target) return false
+ agent(state, target.id)
+ await this.agentGrant(tx, state, target)
+ return true
+ })
+ } catch (error) { if (error instanceof SuperTabError) return false; throw error }
+ }
+
+ /** Execution identity survives removing a contributor. The host sees only
+ * its outstanding native sessions, without regaining conversation access. */
+ async hostAssignments(user: AuthUser, machineId: string) {
+ return transaction(this.db, async tx => {
+ const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ const rows = await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, machineIds: { has: machineId } }, take: 100 })
+ return rows.flatMap(row => stateOf(row).conversations.filter(activeWork).flatMap(group => {
+ const work = group.assignment!
+ return work.execution.machineId === machineId && work.execution.machineOwnerId === user.sub
+ ? [{ tabId: row.id, assignmentId: work.id, harnessId: work.execution.harnessId }] : []
+ }))
+ })
+ }
+
+ private deliveryAllowed(state: SuperTabState, delivery: SuperTabDelivery): boolean {
+ const target = state.agents.find(a => a.id === delivery.agentId)
+ const group = state.conversations.find(c => c.id === delivery.conversationId)
+ if (!target || target.membershipGeneration !== delivery.membershipGeneration || !group || group.archived || !group.agentIds.includes(target.id)) return false
+ const sender = delivery.authorKind === 'person' ? state.people.find(p => p.id === delivery.authorId) : state.agents.find(a => a.id === delivery.authorId)
+ if (!sender) return false
+ const generation = 'generation' in sender ? sender.generation : sender.membershipGeneration
+ return generation === delivery.authorGeneration && (!('role' in sender) || sender.role !== 'viewer')
+ }
+
+ private async senderAllowed(tx: Transaction, state: SuperTabState, delivery: SuperTabDelivery): Promise<boolean> {
+ if (delivery.nativeContextId && !await this.native.allowsDelivery(tx, state, delivery.nativeContextId)) return false
+ if (delivery.authorKind !== 'agent') return true
+ try { await this.agentGrant(tx, state, agent(state, delivery.authorId)); return true }
+ catch (error) { if (error instanceof SuperTabError) return false; throw error }
+ }
+
+ async deliveries(user: AuthUser, tabId: string, agentId: string) {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const state = stateOf(row)
+ author(state, await this.actor(tx, user, state, agentId), true)
+ const rows = await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: ['queued', 'claimed', 'uncertain'] } },
+ orderBy: { createdAt: 'asc' }, take: 100 })
+ const allowed: SuperTabDelivery[] = []
+ for (const delivery of rows) {
+ if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)) allowed.push(delivery)
+ }
+ return allowed
+ })
+ }
+
+ /** A withdrawn host can retire its own journal without regaining shared
+ * conversation access. Machine ownership is captured when input is created. */
+ async deliveryReceipt(user: AuthUser, tabId: string, agentId: string, deliveryId: string) {
+ return transaction(this.db, async tx => {
+ const state = stateOf(await this.row(tx, user, tabId))
+ const row = await tx.superTabDelivery.findFirst({ where: { id: deliveryId, tabId, agentId } })
+ if (!row) fail('NOT_FOUND', 'This delivery is unavailable.', 404)
+ const previous = state.agents.find(a => a.id === agentId && a.membershipGeneration === row.membershipGeneration)
+ const owner = row.machineOwnerId ?? previous?.machineOwnerId
+ if (owner !== user.sub) fail('FORBIDDEN', 'Only the recorded execution host can read this receipt.', 403)
+ const machine = await tx.machine.findFirst({ where: { machineId: row.machineId, userId: owner,
+ autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ return { id: row.id, status: row.status }
+ })
+ }
+
+ /** No timeout reclaims an instruction: the same durable claim resumes, or the host reconciles it. */
+ async delivery(user: AuthUser, tabId: string, agentId: string, deliveryId: string,
+ action: { type: 'claim'; claimId: string } | { type: 'ack'; claimId: string; receipt: string; uncertain: boolean }) {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const state = stateOf(row)
+ author(state, await this.actor(tx, user, state, agentId), true)
+ const delivery = await tx.superTabDelivery.findFirst({ where: { id: deliveryId, tabId, agentId } })
+ if (!delivery || !this.deliveryAllowed(state, delivery) || delivery.status === 'cancelled' ||
+ !await this.senderAllowed(tx, state, delivery)) fail('DELIVERY_REVOKED', 'This instruction is no longer authorized.', 403)
+ if (delivery.status === 'confirmed' || delivery.status === 'superseded') {
+ fail('DELIVERY_RESOLVED', 'A person has already resolved this delivery.')
+ }
+ if (delivery.claimId && delivery.claimId !== action.claimId) fail('CLAIM_CONFLICT', 'Reconcile the existing delivery before claiming it again.')
+ if (action.type === 'ack' && !delivery.claimId) fail('NOT_CLAIMED', 'Claim this instruction before acknowledging it.')
+ const status = action.type === 'claim' ? delivery.status === 'queued' ? 'claimed' : delivery.status : action.uncertain ? 'uncertain' : 'delivered'
+ if (delivery.status === 'delivered' && action.type === 'ack' && (action.uncertain || delivery.receipt !== action.receipt)) {
+ fail('RECEIPT_CONFLICT', 'A delivered instruction keeps its original host receipt.')
+ }
+ // This write conflicts with concurrent revocation, even when only the delivery record changed.
+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision: { increment: 1 } } })
+ const updated = await tx.superTabDelivery.update({ where: { id: delivery.id }, data: { status, claimId: action.claimId,
+ ...(action.type === 'ack' ? { receipt: action.receipt } : {}) } })
+ const message = await tx.superTabMessage.findUnique({ where: { id: delivery.messageId } })
+ return { delivery: updated, message }
+ })
+ }
+
+ /** Only the recorded execution host may attest that the actual session/attempt has stopped. */
+ async stopped(user: AuthUser, tabId: string, assignmentId: string, receipt: string) {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ const state = stateOf(row)
+ const group = state.conversations.find(c => c.assignment?.id === assignmentId)
+ const assignment = group?.assignment
+ if (!assignment || assignment.execution.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can confirm this stop.', 403)
+ const execution = assignment.execution
+ const machine = await tx.machine.findFirst({ where: { machineId: execution.machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })
+ if (!machine) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)
+ const id = stableId('stop', tabId, assignmentId)
+ const prior = await tx.superTabStopReceipt.findUnique({ where: { id } })
+ if (prior && prior.receipt !== receipt) fail('RECEIPT_CONFLICT', 'This stop already has a host receipt.')
+ if (group && activeWork(group)) {
+ assignment.status = 'stopped'
+ assignment.result = 'The execution host confirmed that this harness stopped.'
+ await tx.superTabRun.deleteMany({ where: { tabId, assignmentId } })
+ await tx.superTabDelivery.updateMany({ where: { tabId, assignmentId,
+ status: { in: ['queued', 'claimed', 'uncertain'] } }, data: { status: 'cancelled' } })
+ }
+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: {
+ revision: { increment: 1 }, state: json(state), ...indexes(state),
+ } })
+ if (!prior) await tx.superTabStopReceipt.create({ data: { id, tabId, assignmentId, ...execution, receipt } })
+ return { confirmed: true }
+ })
+ }
+}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
new file mode 100644
index 000000000..9f687d48e
--- /dev/null
+++ b/backend/vitest.super-tabs.config.ts
@@ -0,0 +1,4 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({ test: { include: ['integration/superTabs.test.ts'], hookTimeout: 120000, testTimeout: 30000,
+ fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.ts
index 45a1f27ab..f9d96c490 100644
--- a/cli/e2e/agentClient.e2e.ts
+++ b/cli/e2e/agentClient.e2e.ts
@@ -3,8 +3,8 @@
* the `harness` verbs as it would through its shell tool. It lists the harnesses, starts one with a task, waits for
* it, reads its answer, and closes it; it may not close one it did not start. Neither may message the other while
* they share no tab (owner, 2026-10-11: Agent Messages off means off). The fake engines answer by echoing
- * (harness/fakeEngine.mjs). A harness it starts says so in the pull requests it opens: in the arguments its engine is
- * launched with, each launch, while the account has that on.
+ * (harness/fakeEngine.mjs). Agent-started harnesses retain their coordination instructions, without
+ * adding Harness attribution to pull requests, even if an older account setting still asks for it.
*
* What agents may do is the account's (Settings ▸ Experimental, every switch off by default): signed in to the fake
* backend, which answers the account's experiments and its tabs (there are none), and turned on where a test needs it.
@@ -19,8 +19,6 @@ import { LocalClient } from './harness/client.js'
import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
-/** The line (lib/agentAttribution.ts), as a reader of the pull request sees it. */
-const AGENT_ATTRIBUTION_LINE = '🤝 Started by another agent in [Harness](https://harness.autonomous.ai) — agents that run agents.'
const HARNESS_INSTRUCTIONS = 'You are running in Harness, and the person can watch you. You can hand work to other agents (Claude Code, Codex) that run in their own harnesses: `harness new`, `harness wait`, `harness show`, `harness close` (see `harness --help`). Start one only for work that can run in parallel, needs another model, or takes long; do quick work yourself, and close each one once you have its answer. Only use or close harnesses you started.'
const ME: FakeMachine = { machineId: 'b8'.repeat(16), computerId: 'e2e-computer-0000-0000-0000000000b8', name: 'studio', token: 'e2e-token-agent-client' }
const signIn = (d: IsolatedDaemon) => writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({
@@ -553,7 +551,7 @@ describe('Harness for agents, end to end', () => {
expect(again.err).toContain('Settings ▸ Experimental')
})
- it('a harness an agent starts says so in the pull requests it opens, on every launch, while the account has it on', async () => {
+ it('keeps delegation instructions without PR attribution, even with an older account setting', async () => {
const { d } = await signedIn({ agents_start_agents: true, agent_pull_request_line: true })
const client = await LocalClient.connect(d, { machineId: ME.machineId })
const live = (name: string) => until(`${name} to be up`, async () => {
@@ -571,24 +569,30 @@ describe('Harness for agents, end to end', () => {
expect(await commandsIn(d, String(lead.tmuxPane))).toContain(`--append-system-prompt ${HARNESS_INSTRUCTIONS}`)
const run = (...args: string[]) => harness(d, String(lead.tmuxPane), args)
- // Claude Code, started by it: Claude Code's own pull request line kept, and Harness's after it.
+ // An older account switch must not add attribution to a new Claude harness.
expect((await run('new', 'claude', 'kid', '--name', 'kid', '--', 'hello kid')).code).toBe(0)
const kid = await live('kid')
- // `ps` may print the emoji and the dash as it likes; the rest is as the engine was given it.
- expect(await commandsIn(d, String(kid.tmuxPane))).toMatch(new RegExp(`--settings \\{"attribution":\\{"pr":"${ascii('🤖 Generated with [Claude Code](https://claude.com/claude-code)')}\\\\n${ascii(AGENT_ATTRIBUTION_LINE)}"\\}\\}`))
+ const kidCommand = await commandsIn(d, String(kid.tmuxPane))
+ expect(kidCommand).toContain(HARNESS_INSTRUCTIONS)
+ expect(kidCommand).not.toContain('--settings')
- // Codex, started by it: told as Codex is told its own attribution.
+ // Codex receives delegation instructions, without an instruction to mark PRs.
expect((await run('new', 'codex', 'kidx', '--name', 'kidx', '--', 'hello kidx')).code).toBe(0)
const kidx = await live('kidx')
- // Codex, started by it: told how to use Harness, then told as Codex is told its own attribution, in one value.
- expect(await commandsIn(d, String(kidx.tmuxPane))).toMatch(new RegExp(`-c developer_instructions="${ascii(HARNESS_INSTRUCTIONS)}.*When you create or update a pull request, .*\`${ascii(AGENT_ATTRIBUTION_LINE)}\``))
+ const codexCommand = await commandsIn(d, String(kidx.tmuxPane))
+ expect(codexCommand).toContain(HARNESS_INSTRUCTIONS)
+ expect(codexCommand).not.toContain('When you create or update a pull request')
+ expect(codexCommand).not.toContain('Started by another agent')
- // A restart launches it again from its row: the line comes back with it.
+ // Restarting a saved harness does not restore the removed attribution.
const restarted = await client.request('agent_restart', { agentId: kid.id }, 90_000)
expect(restarted.error, JSON.stringify(restarted)).toBeUndefined()
- await until('kid to come back with its line', async () => {
+ await until('kid to come back with delegation instructions', async () => {
const row = await live('kid')
- return row.tmuxPane && (await commandsIn(d, String(row.tmuxPane))).includes('"attribution"') ? row : null
+ const command = row.tmuxPane ? await commandsIn(d, String(row.tmuxPane)) : ''
+ if (!command.includes(HARNESS_INSTRUCTIONS)) return null
+ expect(command).not.toContain('--settings')
+ return row
}, 60_000, 500)
// Turned off by the person: the next one an agent starts has no line.
@@ -618,9 +622,6 @@ async function enginesIn(d: IsolatedDaemon, pane: string): Promise<string> {
return (await commandsIn(d, pane)).split('\n').filter((line) => /^(?:codex|claude)\s/.test(line)).join('\n')
}
-/** [text] as a pattern that matches it whatever `ps` prints for a character outside ASCII. */
-const ascii = (text: string): string => [...text].map((ch) => /[ -~]/.test(ch) ? ch.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : '.+?').join('')
-
/** The command lines of the processes in [pane], as `ps` prints them: the engine's carries the arguments it was launched
* with (the fake engines' process title is their engine's name, then their arguments, as a CLI's is). */
async function commandsIn(d: IsolatedDaemon, pane: string): Promise<string> {
diff --git a/cli/e2e/agentMessages.e2e.ts b/cli/e2e/agentMessages.e2e.ts
index 004b172e4..e553f9578 100644
--- a/cli/e2e/agentMessages.e2e.ts
+++ b/cli/e2e/agentMessages.e2e.ts
@@ -168,7 +168,7 @@ describe('Agent Messages, end to end', () => {
await new Promise((settle) => setTimeout(settle, 17_000))
expect(reads(relay), 'off for the account, the tabs are never read').toBe(0)
const on = await settings(d, { agentMessages: true })
- expect(await on.json()).toEqual({ agentsStartAgents: false, pullRequestLine: true, agentMessages: true, signedIn: true })
+ expect(await on.json()).toEqual({ agentsStartAgents: false, pullRequestLine: true, agentMessages: true, agentMessagesHideSummary: false, signedIn: true })
expect(relay.experiments).toEqual({ agent_pull_request_line: true, agent_messages: true })
await until('Agent Messages to wake for the setting turned on', () => reads(relay) >= 1 || null, 30_000, 200)
const notes = await notesFor(d, 2)
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index d5a159d87..a96ba5412 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -257,6 +257,9 @@ export class IsolatedDaemon {
}
// A daemon never finds the developer's own gh (shared tabs' tasks run it): a stub that refuses, until a test writes its own.
await writeFile(join(dirs.bin, 'gh'), GH_FORBIDDEN_STUB, { mode: 0o755 })
+ // Engine probes and usage readers must not consult the person's macOS
+ // Keychain merely because the fixture itself runs on a Mac.
+ await writeFile(join(dirs.bin, 'security'), '#!/bin/sh\nexit 44\n', { mode: 0o755 })
const env = daemonEnvironment(tmux.env, {
NODE_ENV: 'test',
HOME: dirs.home,
diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.ts
index ec699fce5..50b3b6a4c 100644
--- a/cli/e2e/harness/fakeBackend.ts
+++ b/cli/e2e/harness/fakeBackend.ts
@@ -103,6 +103,11 @@ const json = (value: unknown): string => JSON.stringify(value)
const bytes = (raw: RawData): Uint8Array => new Uint8Array(Array.isArray(raw) ? Buffer.concat(raw) : raw instanceof ArrayBuffer ? raw : Buffer.from(raw))
export class FakeBackend {
+ /** Optional Super Tab control-plane fixture. Native creation, input and relay
+ * still go through the real daemon; database policy has its own integration suite. */
+ superTabs: ((method: string, path: string, body: Record<string, any>, machine: FakeMachine) => Promise<{
+ status?: number; data?: unknown; error?: { code: string; message: string }
+ }>) | null = null
/** Opt-in fixture: older scenarios keep the endpoint absent, as on an older backend. */
productUsage: { enabled: boolean; revision: number; reports: Record<string, unknown>[]; stallReports?: boolean } | null = null
readonly seen: string[] = []
@@ -156,6 +161,18 @@ export class FakeBackend {
res.setHeader('content-type', 'application/json')
if (backend.down) { res.statusCode = 503; res.end(json({ success: false, error: { code: 'UNAVAILABLE' } })); return }
if (!machine) { res.statusCode = 401; res.end(json({ success: false, error: { code: 'UNAUTHORIZED' } })); return }
+ if (backend.superTabs && req.url?.startsWith('/api/super-tabs')) {
+ const handler = backend.superTabs
+ let raw = ''
+ req.on('data', chunk => { raw += chunk })
+ req.on('end', () => {
+ void Promise.resolve().then(() => handler(req.method!, req.url!, JSON.parse(raw || '{}'), machine)).then(result => {
+ res.statusCode = result.status ?? 200
+ res.end(json({ success: !result.error, data: result.data, error: result.error }))
+ }, error => { res.statusCode = 500; res.end(json({ success: false, error: { code: 'FIXTURE', message: String(error) } })) })
+ })
+ return
+ }
const usage = backend.productUsage
if (usage && req.url === '/api/product-usage/settings' && req.method === 'GET') {
res.end(json({ success: true, data: { enabled: usage.enabled, revision: usage.revision } })); return
diff --git a/cli/e2e/superTabs.e2e.ts b/cli/e2e/superTabs.e2e.ts
new file mode 100644
index 000000000..b325e2595
--- /dev/null
+++ b/cli/e2e/superTabs.e2e.ts
@@ -0,0 +1,285 @@
+/** Super Tab on the actual native protocol: real master/services, private tmux,
+ * fake engines and loopback coordination. Database authorization/transactions
+ * are covered separately by backend's replica-set integration tests. */
+import { createHash } from 'node:crypto'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { superTabCommand } from '../src/superTabs/command.js'
+import { object } from '../src/superTabs/wire.js'
+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'
+
+const ME: FakeMachine = { machineId: 'b8'.repeat(16), computerId: 'e2e-super-tab-computer', name: 'Fixture', token: 'e2e-super-tab-token' }
+const TAB = 'fixture-tab'
+let daemon: IsolatedDaemon | undefined, backend: FakeBackend | undefined
+const clients: LocalClient[] = []
+afterEach(async () => {
+ clients.splice(0).forEach(client => client.close())
+ await daemon?.close(); daemon = undefined
+ await backend?.close(); backend = undefined
+})
+
+it('starts either engine once, posts to its captured group and delivers shared input through the native core', async () => {
+ const relay = await FakeBackend.start(); backend = relay; relay.addMachine(ME)
+ const d = await IsolatedDaemon.create({ submissionGate: true, env: {
+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,
+ ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential',
+ } }); daemon = d
+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token,
+ autonomousEnv: 'prod', computerId: ME.computerId, machineId: ME.machineId,
+ expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',
+ }), { mode: 0o600 })
+ onTestFailed(() => console.log(d.log().split('\n').slice(-160).join('\n')))
+ const agents: Array<Record<string, any>> = []
+ const starts = new Map<string, Record<string, any>>()
+ const posts: Array<Record<string, any>> = []
+ const pending = new Map<string, Record<string, any>>()
+ const assignments: Array<Record<string, string>> = []
+ const stopReceipts: Array<Record<string, any>> = []
+ const nativeContexts = new Map<string, Record<string, any>>()
+ const nativeRecords = new Map<string, Record<string, any>>()
+ const nativeSends: Array<Record<string, any>> = []
+ let loseNativeReply = true
+ let revision = 0, allowed = true, deliveryReads = 0
+ const idFor = (harnessId: string) => createHash('sha256').update(JSON.stringify([ME.machineId, harnessId])).digest('hex').slice(0, 24)
+ relay.superTabs = async (method, raw, body) => {
+ const url = new URL(raw, relay.httpUrl), path = url.pathname
+ if (path === `/api/super-tabs/hosts/${ME.machineId}/assignments`) return { data: assignments }
+ if (path.endsWith('/stopped')) { stopReceipts.push(body); assignments.length = 0; return { data: { confirmed: true } } }
+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: allowed ? agents.map(agent => ({ tabId: TAB, agent, observers: [] })) : [] }
+ if (!allowed) return { status: 403, error: { code: 'FORBIDDEN', message: 'The contribution was withdrawn.' } }
+ if (path === `/api/super-tabs/${TAB}/native` && method === 'POST') {
+ const agent = agents.find(a => a.id === body.agentId)!
+ const contextId = body.operationId
+ nativeContexts.set(contextId, { contextId, tabId: TAB, conversationId: body.conversationId,
+ machineId: ME.machineId, harnessId: agent.harnessId, lastEventId: null })
+ return { data: { contextId } }
+ }
+ if (path.startsWith(`/api/super-tabs/${TAB}/native/`)) {
+ const contextId = path.split('/').at(-1)!, context = nativeContexts.get(contextId)!
+ if (method === 'GET') return { data: context }
+ nativeSends.push({ ...body, contextId })
+ const eventId = createHash('sha256').update(JSON.stringify(['native-event', contextId, body.turnId, body.kind])).digest('hex').slice(0, 24)
+ if (nativeRecords.has(eventId)) expect(nativeRecords.get(eventId)).toEqual({ ...body, contextId })
+ else {
+ expect(body.previousEventId).toBe(context.lastEventId)
+ nativeRecords.set(eventId, { ...body, contextId }); context.lastEventId = eventId
+ }
+ if (loseNativeReply) { loseNativeReply = false; return { status: 503, error: { code: 'BACKEND_UNAVAILABLE', message: 'Lost fixture reply' } } }
+ return { data: { eventId } }
+ }
+ if (path === `/api/super-tabs/${TAB}`) return { data: { revision, state: { id: TAB, agents } } }
+ if (path === `/api/super-tabs/${TAB}/conversations/feature/messages`) {
+ expect(agents.some(agent => agent.id === url.searchParams.get('asAgentId'))).toBe(true)
+ return { data: { messages: [{ id: url.searchParams.get('messageId'), text: 'Should the offline queue survive restart?' }] } }
+ }
+ if (path.startsWith(`/api/super-tabs/${TAB}/starts/`)) return { data: starts.get(path.split('/').at(-1)!) }
+ if (path.endsWith('/commands')) {
+ const command = object(body.command)
+ if (command.type === 'agent.start') {
+ const startId = `start-${body.operationId}`
+ if (!starts.has(startId)) starts.set(startId, { id: startId, creationId: `super-${startId}`, request: command.request, dispatched: false, harnessId: null })
+ return { data: { result: { startId } } }
+ }
+ const start = starts.get(String(command.startId))
+ if (command.type === 'agent.startDispatch') {
+ if (start!.dispatched) throw new Error('Duplicate dispatch')
+ start!.dispatched = true
+ } else if (command.type === 'agent.started') {
+ start!.harnessId = command.harnessId
+ const id = idFor(String(command.harnessId))
+ if (!agents.some(a => a.id === id)) agents.push({ id, harnessId: command.harnessId, machineId: ME.machineId, configuration: command.configuration })
+ return { data: { result: { agentId: id } } }
+ } else if (command.type === 'message.send') posts.push(command)
+ else if (command.type === 'agent.configuration') {
+ const agent = agents.find(a => a.id === body.asAgentId)!
+ if ((agent.configurationVersion ?? null) !== command.previousVersion) throw new Error('Stale configuration')
+ agent.configuration = command.configuration
+ agent.configurationVersion = body.operationId
+ }
+ else if (command.type === 'agent.startFailed') start!.error = command.error
+ else throw new Error(`Unexpected command ${command.type}`)
+ revision++
+ return { data: { result: {} } }
+ }
+ const delivery = /\/agents\/([^/]+)\/deliveries(?:\/([^/]+))?$/.exec(path)
+ if (delivery) {
+ const value = pending.get(delivery[1])
+ if (method === 'GET') {
+ deliveryReads++
+ return { data: delivery[2] ? value : value && value.status !== 'delivered' ? [value] : [] }
+ }
+ if (!value || value.id !== delivery[2]) throw new Error('Unknown delivery')
+ if (value.claimId && value.claimId !== body.claimId) throw new Error('Claim changed')
+ if (body.type === 'claim') {
+ value.claimId = body.claimId
+ return { data: { message: value.message } }
+ }
+ value.status = body.uncertain ? 'uncertain' : 'delivered'
+ value.receipt = body.receipt
+ return { data: {} }
+ }
+ throw new Error(`Unexpected request ${method} ${raw}`)
+ }
+ await d.start()
+ const client = await LocalClient.connect(d, { machineId: ME.machineId }); clients.push(client)
+ const cwd = join(d.projectsDir, 'project'); mkdirSync(cwd, { recursive: true })
+ const lead = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)
+ expect(lead.error, JSON.stringify(lead)).toBeUndefined()
+ const leadId = idFor(lead.agent.id)
+ agents.push({ id: leadId, machineId: ME.machineId, harnessId: lead.agent.id })
+ const where = { port: d.port, dataDir: d.dataDir, machineId: ME.machineId, harnessPane: true }
+ async function run(args: string[], agent = leadId) {
+ let answer: Record<string, any> = {}
+ const code = await superTabCommand(['--tab', TAB, '--agent', agent, ...args], { where: () => where,
+ print: text => { answer = JSON.parse(text) } })
+ return { code, answer }
+ }
+ for (const engine of ['claude', 'codex']) {
+ const request = { conversationId: 'feature', machineId: ME.machineId, engine, name: `Builder ${engine}`,
+ cwd, worktree: false, permissionMode: 'auto', requirements: { memoryBytes: 0, diskBytes: 1,
+ maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false } }
+ let started = await run(['start', engine, JSON.stringify(request)])
+ if (started.answer.error === 'START_PENDING') started = await until('native creation to finish', async () => {
+ const result = await run(['resume', `start-${engine}`])
+ return result.answer.error === 'START_PENDING' ? null : result
+ }, 60_000, 500)
+ expect(started.code, JSON.stringify(started.answer)).toBe(0)
+ expect(started.answer.harnessId).toBeTruthy()
+ const same = await run(['start', engine, JSON.stringify(request)])
+ expect(same.answer.harnessId).toBe(started.answer.harnessId)
+ const target = idFor(started.answer.harnessId)
+ const posted = await run(['post', 'feature', `${engine} ready`, `hello-${engine}`], target)
+ expect(posted.code, JSON.stringify(posted.answer)).toBe(0)
+ expect(posts.at(-1)).toMatchObject({ conversationId: 'feature', text: `${engine} ready` })
+ pending.set(target, { id: `delivery-${engine}`, status: 'queued', claimId: null,
+ message: { id: `message-${engine}`, conversationId: 'feature', replyTo: `question-${engine}`, author: { name: 'Fixture human' }, text: `verify-super-tab-${engine}` } })
+ await until('native input acknowledgement', () => pending.get(target)?.status === 'delivered' || null, 60_000, 250)
+ const submitted = readFileSync(join(d.root, 'submitted-prompts'), 'utf8').split('\n').filter(Boolean).map(line => JSON.parse(line) as string)
+ expect(submitted.filter(prompt => prompt.includes(`verify-super-tab-${engine}`))).toHaveLength(1)
+ expect(submitted.find(prompt => prompt.includes(`verify-super-tab-${engine}`))).toContain(`In reply to message question-${engine}.`)
+ expect(submitted.find(prompt => prompt.includes(`verify-super-tab-${engine}`))).toContain(`message 'feature' 'question-${engine}'`)
+ const original = await run(['message', 'feature', `question-${engine}`], target)
+ expect(original.code, JSON.stringify(original.answer)).toBe(0)
+ expect(original.answer.value.messages).toEqual([{ id: `question-${engine}`, text: 'Should the offline queue survive restart?' }])
+ const model = engine === 'claude' ? 'sonnet' : 'gpt-6-luna'
+ // Wait for the native turn to settle before using the app's existing model controls.
+ await until('worker idle before its model change', async () => {
+ const rows = await client.request('agents_list')
+ const ended = client.frames.filter(frame => frame.type === 'turn_ended' && frame.agentId === started.answer.harnessId && !frame.replay)
+ return ended.length >= 2 && rows.agents.some((a: Record<string, any>) => a.id === started.answer.harnessId && a.activity?.state === 'idle') || null
+ }, 30_000, 250)
+ const changed = await client.request('agent_update', { agentId: started.answer.harnessId,
+ selectedModel: `runtime-v1:${started.answer.harnessId}:${engine}:${model}@high` }, 45_000)
+ expect(changed.error, JSON.stringify(changed)).toBeUndefined()
+ await until('shared roster to reflect the observed native runtime', () => {
+ const config = agents.find(a => a.id === target)?.configuration
+ return config?.model === model && config.effort === 'high' || null
+ }, 20_000, 250)
+ // The same route as Desktop: authenticated conversation context, host
+ // preparation, then bytes typed into the real native terminal stream.
+ const contextId = `native-${engine}-context-fixture`
+ expect(await client.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/native`,
+ body: { operationId: contextId, conversationId: 'feature', agentId: target } })).toMatchObject({ value: { contextId } })
+ expect(await client.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId }))
+ .toMatchObject({ ok: true, inputContext: contextId })
+ const openId = `terminal-${engine}`, terminal = client.next(frame => frame.type === 'terminal_ready' && frame.payload?.requestId === openId)
+ client.send('terminal_open', { requestId: openId, protocolVersion: 3, agentId: started.answer.harnessId,
+ cols: 100, rows: 30, inputContext: contextId })
+ const streamId = (await terminal).payload!.streamId as string
+ await client.waitForBinary(frame => frame.streamId === streamId && frame.kind === TerminalBinaryKind.keyframe)
+ const intervention = `native-intervention-${engine}`
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from(intervention) })
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.from('\r') })
+ await until('native prompt and answer in the correct conversation', () => {
+ const rows = [...nativeRecords.values()].filter(row => row.contextId === contextId)
+ return rows.length >= 2 ? rows : null
+ }, 30_000, 100)
+ const observed = [...nativeRecords.values()].filter(row => row.contextId === contextId)
+ expect(observed.map(row => row.kind)).toEqual(['prompt', 'answer'])
+ expect(observed[0]!.text).toBe(intervention)
+ expect(observed[1]!.text).toContain(intervention)
+ expect(observed[0]!.turnId).toBe(observed[1]!.turnId)
+ const composed = `native-composed-intervention-${engine}`
+ client.send('message', { agentId: started.answer.harnessId, content: composed, inputContext: contextId })
+ await until('composed native input to retain the same conversation context', () => {
+ const rows = [...nativeRecords.values()].filter(row => row.contextId === contextId)
+ return rows.length >= 4 ? rows : null
+ }, 30_000, 100)
+ const composedRows = [...nativeRecords.values()].filter(row => row.contextId === contextId).slice(2)
+ expect(composedRows.map(row => row.kind)).toEqual(['prompt', 'answer'])
+ expect(composedRows[0]!.text).toBe(composed)
+ expect(composedRows[1]!.text).toContain(composed)
+ client.send('terminal_close', { streamId })
+ const unknownId = `unattributed-${engine}`
+ const unknownReady = client.next(frame => frame.type === 'terminal_ready' && frame.payload?.requestId === unknownId)
+ client.send('terminal_open', { requestId: unknownId, protocolVersion: 3, agentId: started.answer.harnessId, cols: 100, rows: 30 })
+ const unknownStream = (await unknownReady).payload!.streamId as string
+ await client.waitForBinary(frame => frame.streamId === unknownStream && frame.kind === TerminalBinaryKind.keyframe)
+ const privateInput = `unattributed-intervention-${engine}`
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId: unknownStream, seq: 0, compressed: false, bytes: Buffer.from(privateInput) })
+ client.sendBinary({ kind: TerminalBinaryKind.input, streamId: unknownStream, seq: 1, compressed: false, bytes: Buffer.from('\r') })
+ await until('an explicit gap instead of guessed attribution', () => [...nativeRecords.values()].some(row => row.contextId === contextId && row.kind === 'gap') || null, 20_000, 100)
+ expect([...nativeRecords.values()].some(row => String(row.text).includes(privateInput))).toBe(false)
+ expect(readFileSync(join(d.dataDir, 'super-tabs', `native-${ME.machineId}.json`), 'utf8')).not.toContain(privateInput)
+ client.send('terminal_close', { streamId: unknownStream })
+ }
+ expect(nativeSends.length).toBeGreaterThan(nativeRecords.size)
+ // The backend survived, but this host has no local intent/receipt. It must
+ // surface the missing evidence without creating a new claim or typing again.
+ const orphan = { id: 'delivery-without-journal', status: 'claimed', claimId: 'original-claim', receipt: '',
+ message: { id: 'message-without-journal', conversationId: 'lead', author: { name: 'Fixture human' }, text: 'do-not-replay-without-journal' } }
+ pending.set(leadId, orphan)
+ await until('missing journal to become visible for recovery', () => orphan.status === 'uncertain' || null, 15_000, 250)
+ expect(orphan.claimId).toBe('original-claim')
+ expect(orphan.receipt).toContain('no local receipt')
+ const reads = deliveryReads
+ await until('further host polls without replay', () => deliveryReads > reads + 3 || null, 10_000, 250)
+ expect(readFileSync(join(d.root, 'submitted-prompts'), 'utf8')).not.toContain('do-not-replay-without-journal')
+ const refused = await run(['start', 'refused-mode', JSON.stringify({
+ conversationId: 'feature', machineId: ME.machineId, engine: 'claude', name: 'Refused builder',
+ cwd, worktree: false, permissionMode: 'not-a-mode', requirements: { memoryBytes: 0, diskBytes: 1,
+ maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false },
+ })])
+ expect(refused.code, JSON.stringify(refused.answer)).toBe(1)
+ expect(refused.answer).toMatchObject({ error: 'START_FAILED', detail: expect.stringContaining('permission mode') })
+ expect(starts.get('start-refused-mode')!.error).toContain('before starting an agent')
+ const creationId = starts.get('start-refused-mode')!.creationId
+ expect(await client.request('agent_create_status', { creationId })).toMatchObject({ creationId, state: 'cancelled' })
+ // Even a delayed valid create cannot revive the cancelled request.
+ expect(await client.request('agent_create', { engine: 'claude', cwd, creationId }, 30_000)).toMatchObject({ creationId, state: 'cancelled' })
+ expect((await run(['resume', 'start-refused-mode'])).answer).toMatchObject({ error: 'START_FAILED' })
+ const listed = await client.request('agents_list')
+ expect(listed.agents).toHaveLength(3)
+ const worker = listed.agents.find((a: Record<string, any>) => a.id === starts.get('start-claude')!.harnessId)
+ assignments.push({ tabId: TAB, assignmentId: 'worker-attempt', harnessId: worker.id })
+ const closed = await client.request('agent_close', { agentId: worker.id, sessionId: worker.sessionId, createdAt: worker.createdAt, mode: 'now' }, 60_000)
+ expect(closed, JSON.stringify(closed)).toMatchObject({ closed: true })
+ await until('execution host to confirm the stop', () => stopReceipts.length === 1 || null, 15_000, 250)
+ expect(stopReceipts[0]).toMatchObject({ assignmentId: 'worker-attempt', receipt: expect.stringContaining('native-stopped:') })
+ expect(await client.request('super_tabs', { action: 'observeCapacity', creationId: starts.get('start-claude')!.creationId }))
+ .toMatchObject({ ok: true, harnessId: worker.id, released: true })
+ // Two callers see the same free memory. Only one may reserve most of it,
+ // even though neither has started its native process yet.
+ const capacity = await client.request('super_tabs', { action: 'capacity', cwd })
+ const freeMemory = capacity.resources.memoryTotalBytes - capacity.resources.memoryUsedBytes
+ expect(Number.isFinite(freeMemory) && freeMemory > 0).toBe(true)
+ const memoryBytes = Math.floor(freeMemory * 0.7)
+ const reservations = await Promise.all([1, 2].map(n => client.request('super_tabs', {
+ action: 'reserveCapacity', creationId: `fixture-capacity-${n}`, cwd,
+ requirements: { memoryBytes, diskBytes: 0, maxCpuPercent: 100 },
+ })))
+ expect(reservations.filter(r => r.ok)).toHaveLength(1)
+ expect(reservations.filter(r => r.error)).toEqual([expect.objectContaining({ error: 'CAPACITY_UNAVAILABLE' })])
+ const reserved = reservations.find(r => r.ok)!.reservationId
+ expect(await client.request('agent_create_cancel', { creationId: reserved })).toMatchObject({ state: 'cancelled' })
+ expect(await client.request('super_tabs', { action: 'observeCapacity', creationId: reserved })).toMatchObject({ released: true })
+ allowed = false
+ const denied = await run(['post', 'feature', 'not allowed', 'after-removal'])
+ expect(denied.code).toBe(1)
+ expect(posts.some(p => p.text === 'not allowed')).toBe(false)
+}, 300_000)
diff --git a/cli/e2e/superTabsCollaboration.e2e.ts b/cli/e2e/superTabsCollaboration.e2e.ts
new file mode 100644
index 000000000..9c2d0b4de
--- /dev/null
+++ b/cli/e2e/superTabsCollaboration.e2e.ts
@@ -0,0 +1,194 @@
+/** Two accounts, two real daemons and an encrypted remote machine connection.
+ * Coordination uses the loopback fixture; database policy is exercised separately
+ * by backend/integration/superTabs.test.ts against a disposable replica set. */
+import { createHash } from 'node:crypto'
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, expect, it, onTestFailed } from 'vitest'
+import { b64e, newIdentity } from '../src/lib/e2ee/core.js'
+import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'
+import { superTabCommand } from '../src/superTabs/command.js'
+import { LocalClient } from './harness/client.js'
+import { CLI_ROOT, until, type IsolatedDaemon } from './harness/daemon.js'
+import { FakeBackend } from './harness/fakeBackend.js'
+import { signedInDaemon, writeE2ee } from './harness/fleet.js'
+
+const TAB = 'shared-work', GROUP = 'offline-editing'
+let backend: FakeBackend | undefined
+const daemons: IsolatedDaemon[] = [], clients: LocalClient[] = []
+afterEach(async () => {
+ for (const client of clients.splice(0)) client.close()
+ await Promise.allSettled(daemons.splice(0).map(daemon => daemon.close()))
+ await backend?.close(); backend = undefined
+})
+
+it('lets one person’s lead use a teammate’s shared machine while preserving account and conversation boundaries', async () => {
+ const relay = await FakeBackend.start(); backend = relay
+ const specs = [
+ { machineId: 'a6'.repeat(16), computerId: 'super-tab-starter', name: 'Starter Mac', token: 'fixture-starter-token', account: 'starter', email: '[email protected]', identity: newIdentity() },
+ { machineId: 'b6'.repeat(16), computerId: 'super-tab-member', name: 'Member Mac', token: 'fixture-member-token', account: 'member', email: '[email protected]', identity: newIdentity() },
+ ]
+ for (const spec of specs) {
+ relay.addMachine({ ...spec, pub: b64e(spec.identity.pub) })
+ const daemon = await signedInDaemon(relay, spec, {
+ ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential',
+ })
+ daemons.push(daemon)
+ await writeE2ee(daemon, { 'identity.json': { priv: b64e(spec.identity.priv), pub: b64e(spec.identity.pub) } })
+ writeFileSync(join(daemon.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
+ }
+ const [starter, member] = specs, [a, b] = daemons
+ onTestFailed(() => daemons.forEach((daemon, i) => console.log(`Fixture machine ${i}:\n${daemon.log().split('\n').slice(-90).join('\n')}`)))
+ const agents: Array<Record<string, any>> = [], messages: Array<Record<string, any>> = []
+ const starts = new Map<string, Record<string, any>>(), pending = new Map<string, Record<string, any>>()
+ const contexts = new Map<string, Record<string, any>>(), observations: Array<Record<string, any>> = []
+ const groups = new Map<string, Set<string>>([[GROUP, new Set()]])
+ let revision = 0, contributionAllowed = true
+ const agentId = (machine: string, harness: string) => createHash('sha256').update(JSON.stringify([machine, harness])).digest('hex').slice(0, 24)
+ const failure = () => ({ status: 403, error: { code: 'FORBIDDEN', message: 'This contribution is no longer shared.' } })
+ relay.superTabs = async (method, raw, body, caller) => {
+ const path = new URL(raw, relay.httpUrl).pathname
+ if (path.startsWith('/api/super-tabs/hosts/')) {
+ expect(path.split('/')[4]).toBe(caller.machineId)
+ return { data: path.endsWith('/assignments') ? [] : contributionAllowed
+ ? agents.filter(agent => agent.machineId === caller.machineId).map(agent => ({ tabId: TAB, agent, observers: [] })) : [] }
+ }
+ if (!contributionAllowed) return failure()
+ if (path === `/api/super-tabs/${TAB}/native` && method === 'POST') {
+ expect(caller.account).toBe(starter.account)
+ const target = agents.find(agent => agent.id === body.agentId)!
+ contexts.set(body.operationId, { contextId: body.operationId, tabId: TAB, conversationId: body.conversationId,
+ harnessId: target.harnessId, machineId: target.machineId, operatorAccount: caller.account, lastEventId: null })
+ return { data: { contextId: body.operationId } }
+ }
+ if (path.startsWith(`/api/super-tabs/${TAB}/native/`)) {
+ const context = contexts.get(path.split('/').at(-1)!)!
+ expect(caller.machineId).toBe(context.machineId)
+ if (method === 'GET') return { data: context }
+ const eventId = createHash('sha256').update(JSON.stringify(['native-event', context.contextId, body.turnId, body.kind])).digest('hex').slice(0, 24)
+ if (!observations.some(row => row.eventId === eventId)) {
+ expect(body.previousEventId).toBe(context.lastEventId)
+ observations.push({ ...body, eventId, operatorAccount: context.operatorAccount, executionAccount: caller.account, conversationId: context.conversationId })
+ context.lastEventId = eventId
+ }
+ return { data: { eventId } }
+ }
+ if (path === `/api/super-tabs/${TAB}`) return { data: { revision, state: { id: TAB, agents } } }
+ if (path.includes('/starts/')) return { data: starts.get(path.split('/').at(-1)!) }
+ if (path.endsWith('/commands')) {
+ const command = body.command, author = body.asAgentId ? agents.find(agent => agent.id === body.asAgentId)! : null
+ if (author) expect(author.machineId).toBe(caller.machineId)
+ if (command.type === 'agent.start') {
+ const startId = `start-${body.operationId}`
+ if (!starts.has(startId)) starts.set(startId, { id: startId, creationId: `super-${startId}`, request: command.request, dispatched: false, harnessId: null })
+ return { data: { result: { startId } } }
+ }
+ if (command.type === 'agent.startDispatch') {
+ const start = starts.get(command.startId)!
+ expect(start.dispatched).toBe(false); start.dispatched = true
+ } else if (command.type === 'agent.started') {
+ const start = starts.get(command.startId)!, id = agentId(start.request.machineId, command.harnessId)
+ start.harnessId = command.harnessId
+ if (!agents.some(agent => agent.id === id)) agents.push({ id, machineId: start.request.machineId, harnessId: command.harnessId, configuration: command.configuration })
+ groups.get(GROUP)!.add(id)
+ return { data: { result: { agentId: id } } }
+ } else if (command.type === 'agent.configuration') {
+ author!.configuration = command.configuration; author!.configurationVersion = body.operationId
+ } else if (command.type === 'conversation.agent') {
+ (groups.get(command.conversationId) ?? groups.set(command.conversationId, new Set()).get(command.conversationId)!).add(command.agentId)
+ } else if (command.type === 'message.send') {
+ const message = { id: `message-${++revision}`, conversationId: command.conversationId,
+ text: command.text, author: { name: author?.id ?? caller.email, account: caller.account }, recipientIds: command.recipientIds }
+ messages.push(message)
+ for (const id of command.recipientIds) pending.set(id, { id: `delivery-${revision}-${id}`, status: 'queued', claimId: null, message })
+ } else throw new Error(`Unexpected command ${command.type}`)
+ return { data: { result: {} } }
+ }
+ const delivery = /\/agents\/([^/]+)\/deliveries(?:\/([^/]+))?$/.exec(path)
+ if (delivery) {
+ const target = agents.find(agent => agent.id === delivery[1])!
+ expect(target.machineId).toBe(caller.machineId)
+ const value = pending.get(target.id)
+ if (method === 'GET') return { data: delivery[2] ? value : value && value.status !== 'delivered' ? [value] : [] }
+ expect(body.claimId).toBe(value!.claimId ?? body.claimId)
+ if (body.type === 'claim') { value!.claimId = body.claimId; return { data: { message: value!.message } } }
+ value!.status = body.uncertain ? 'uncertain' : 'delivered'
+ return { data: {} }
+ }
+ throw new Error(`Unexpected route ${method} ${path}`)
+ }
+ await Promise.all(daemons.map(daemon => daemon.start()))
+ await until('both accounts connected', () => relay.nodeUp(starter.machineId) && relay.nodeUp(member.machineId), 30_000)
+ const onA = await LocalClient.connect(a, { machineId: starter.machineId }), onB = await LocalClient.connect(b, { machineId: member.machineId })
+ clients.push(onA, onB)
+ // The gateway connects before all edge services finish starting. Observe
+ // readiness with a read; never replay the sharing mutation to warm the host.
+ await Promise.all([onA, onB].map(client => until('shared machines service ready', async () => {
+ const policy = await client.request('shared_machines', { action: 'get' }, 30_000)
+ return policy.error === 'SERVICE_UNAVAILABLE' ? null : policy
+ }, 30_000)))
+ expect(await onB.request('shared_machines', { action: 'set', emails: [starter.email], sameDomain: false }, 30_000)).toMatchObject({ emails: [starter.email] })
+ expect(await onA.request('shared_machines', { action: 'add', machineId: member.machineId }, 30_000)).toMatchObject({ ok: true })
+ await until('shared machine pinned', () => {
+ try { return JSON.parse(readFileSync(join(a.dataDir, 'e2e', 'machinePeers.json'), 'utf8')).some((peer: any) => peer.machineId === member.machineId && peer.shared) || null } catch { return null }
+ }, 30_000)
+ const projectA = join(a.projectsDir, 'project'), projectB = join(b.projectsDir, 'project')
+ mkdirSync(projectA, { recursive: true }); mkdirSync(projectB, { recursive: true })
+ const lead = await onA.request('agent_create', { engine: 'claude', cwd: projectA, bypassPermission: true }, 90_000)
+ expect(lead.error, JSON.stringify(lead)).toBeUndefined()
+ const leadId = agentId(starter.machineId, lead.agent.id)
+ agents.push({ id: leadId, machineId: starter.machineId, harnessId: lead.agent.id }); groups.get(GROUP)!.add(leadId)
+ const where = { port: a.port, dataDir: a.dataDir, machineId: starter.machineId, harnessPane: true }
+ async function run(args: string[]) {
+ let answer: Record<string, any> = {}
+ const code = await superTabCommand(['--tab', TAB, '--agent', leadId, ...args], { where: () => where, print: line => { answer = JSON.parse(line) } })
+ return { code, answer }
+ }
+ const request = { conversationId: GROUP, machineId: member.machineId, engine: 'codex', name: 'Member builder', cwd: projectB,
+ worktree: false, permissionMode: 'auto', requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: ['git'], devices: [], quotaRequired: false } }
+ let started = await run(['start', 'remote-builder', JSON.stringify(request)])
+ if (started.answer.error === 'START_PENDING') started = await until('remote creation receipt', async () => {
+ const next = await run(['resume', 'start-remote-builder']); return next.answer.error === 'START_PENDING' ? null : next
+ }, 60_000, 500)
+ expect(started.code, JSON.stringify(started.answer)).toBe(0)
+ expect((await run(['start', 'remote-builder', JSON.stringify(request)])).answer.harnessId).toBe(started.answer.harnessId)
+ const workerId = agentId(member.machineId, started.answer.harnessId)
+ expect((await onB.request('agents_list')).agents).toHaveLength(1)
+ expect((await onA.request('agents_list')).agents).toHaveLength(1)
+ const viaA = await LocalClient.connect(a, { machineId: member.machineId }); clients.push(viaA)
+ // Machine control does not make the member's account a proxy for the starter.
+ expect(await viaA.request('super_tabs', { action: 'backend', method: 'GET', path: `/api/super-tabs/${TAB}` }))
+ .toMatchObject({ error: 'OWNER_REQUIRED' })
+ expect((await run(['command', 'assign-instruction', JSON.stringify({ type: 'message.send', conversationId: GROUP,
+ text: 'Verify offline editing on the member machine', replyTo: null, recipientIds: [workerId] })])).code).toBe(0)
+ await until('member host delivers the lead instruction', () => pending.get(workerId)?.status === 'delivered' || null, 45_000)
+ expect(messages.at(-1)!.author.account).toBe(starter.account)
+ expect(await onB.request('super_tabs', { action: 'command', tabId: TAB, agentId: workerId, operationId: 'member-result',
+ command: { type: 'message.send', conversationId: GROUP, text: 'The member machine verified the requested behavior.', replyTo: null, recipientIds: [leadId] } }))
+ .toMatchObject({ ok: true })
+ await until('starter host delivers the member result', () => pending.get(leadId)?.status === 'delivered' || null, 45_000)
+ expect(messages.at(-1)!.author.account).toBe(member.account)
+ expect((await run(['command', 'reuse-member', JSON.stringify({ type: 'conversation.agent', conversationId: 'onboarding', agentId: workerId, present: true, lead: false })])).code).toBe(0)
+ expect(groups.get('onboarding')!.has(workerId)).toBe(true)
+ expect((await onB.request('agents_list')).agents).toHaveLength(1)
+ const contextId = 'starter-on-member-terminal'
+ expect(await onA.request('super_tabs', { action: 'backend', method: 'POST', path: `/api/super-tabs/${TAB}/native`,
+ body: { operationId: contextId, conversationId: GROUP, agentId: workerId } })).toMatchObject({ value: { contextId } })
+ expect(await viaA.request('super_tabs', { action: 'prepareNative', tabId: TAB, contextId })).toMatchObject({ inputContext: contextId })
+ const ready = viaA.next(frame => frame.type === 'terminal_ready' && frame.payload?.requestId === 'member-terminal')
+ viaA.send('terminal_open', { requestId: 'member-terminal', protocolVersion: 3, agentId: started.answer.harnessId, cols: 100, rows: 30, inputContext: contextId })
+ const streamId = (await ready).payload!.streamId as string
+ await viaA.waitForBinary(frame => frame.streamId === streamId && frame.kind === TerminalBinaryKind.keyframe)
+ viaA.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from('Keep this change focused') })
+ viaA.sendBinary({ kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.from('\r') })
+ await until('remote terminal observation', () => observations.length >= 2 || null, 30_000)
+ expect(observations.map(row => row.kind)).toEqual(['prompt', 'answer'])
+ expect(observations.every(row => row.operatorAccount === starter.account && row.executionAccount === member.account && row.conversationId === GROUP)).toBe(true)
+ expect([...relay.webSent.values()].flat().filter(frame => ['super_tabs', 'agent_create', 'terminal_open'].includes(String(frame.type)))
+ .every(frame => !!(frame.payload as any)?.__e2e)).toBe(true)
+ contributionAllowed = false
+ expect(await onB.request('shared_machines', { action: 'set', emails: [], sameDomain: false }, 30_000)).toMatchObject({ emails: [] })
+ await until('removed machine connection closes', () => viaA.closed || null, 30_000)
+ expect((await run(['post', GROUP, 'Cannot post after withdrawal', 'after-withdrawal'])).code).toBe(1)
+ expect((await onB.request('agents_list')).agents).toHaveLength(1)
+}, 240_000)
diff --git a/cli/src/backendSocket.devices.spec.ts b/cli/src/backendSocket.devices.spec.ts
index 2f1ef2752..32b49504a 100644
--- a/cli/src/backendSocket.devices.spec.ts
+++ b/cli/src/backendSocket.devices.spec.ts
@@ -31,7 +31,8 @@ describe('Devices host ownership', () => {
await dispatchDown(socket, sealed, 'remote')
role.mockReturnValue('web')
await dispatchDown(socket, sealed, 'remote')
- expect(routed).toEqual([{ local: false, owner: false, connection: 'remote', requestId: 'one' }, { local: false, owner: true, connection: 'remote', requestId: 'one' }])
+ expect(routed).toEqual([{ local: false, owner: false, accountOwner: false, connection: 'remote', requestId: 'one' },
+ { local: false, owner: true, accountOwner: false, connection: 'remote', requestId: 'one' }])
expect(reply).toHaveBeenLastCalledWith('remote', `${type}_result`, 'one', { ok: true, owner: true })
const local: unknown[] = []
socket.registerLocalClient('local:tool', { sendFrame: frame => { local.push(frame); return true }, sendBinary: () => true }, { tool: true })
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 61a457bb5..451a87b3d 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -417,8 +417,8 @@ describe('viewer forwarding authentication', () => {
role.mockReturnValue('web')
await dispatchDown(socket, sealed, 'remote')
expect(routed).toEqual([
- { type: 'memory_snapshot', asker: { local: false, owner: false, connection: 'remote', requestId: 'one' } },
- { type: 'memory_snapshot', asker: { local: false, owner: true, connection: 'remote', requestId: 'one' } },
+ { type: 'memory_snapshot', asker: { local: false, owner: false, accountOwner: false, connection: 'remote', requestId: 'one' } },
+ { type: 'memory_snapshot', asker: { local: false, owner: true, accountOwner: false, connection: 'remote', requestId: 'one' } },
])
expect(ownerCommands).not.toHaveBeenCalled()
expect(sealedReply).toHaveBeenCalledWith('remote', 'memory_snapshot_result', 'one', { memories: [] })
@@ -1067,13 +1067,13 @@ describe('BackendSocket outbound queue', () => {
await vi.waitFor(() => {
expect(wrapReply).toHaveBeenCalledWith('web-1', 'session_search_result', 's-1', { hits: [], indexed: 3, pending: 0, ready: true, tookMs: 1 })
})
- expect(routed[0]).toEqual({ type: 'session_search', payload: { requestId: 's-1', query: 'dial scroll', limit: 12 }, asker: { local: false, owner: true, connection: 'web-1', requestId: 's-1' } })
+ expect(routed[0]).toEqual({ type: 'session_search', payload: { requestId: 's-1', query: 'dial scroll', limit: 12 }, asker: { local: false, owner: true, accountOwner: false, connection: 'web-1', requestId: 's-1' } })
// A device's session may not act as the owner, and the service is told so.
role.mockReturnValue('device')
ask('session_search', { requestId: 's-2', query: 'dial' })
await vi.waitFor(() => expect(routed).toHaveLength(2))
- expect(routed[1].asker).toEqual({ local: false, owner: false, connection: 'web-1', requestId: 's-2' })
+ expect(routed[1].asker).toEqual({ local: false, owner: false, accountOwner: false, connection: 'web-1', requestId: 's-2' })
// A type no service declared is the socket's own: an unknown one is refused at once, in the clear,
// as a reply that carries nothing is.
@@ -2755,7 +2755,7 @@ describe('agent_fork RPC', () => {
lookup.mockReturnValue(undefined)
ask('agent_fork', 'deleted')
await vi.waitFor(() => expect(frames).toContainEqual({
- type: 'agent_fork_result', payload: { requestId: 'deleted', creationId, state: 'unavailable' },
+ type: 'agent_fork_result', payload: { requestId: 'deleted', creationId, state: 'unavailable', createdAgentId: FORK.agentId },
}))
expect(fork).toHaveBeenCalledTimes(1)
} finally {
@@ -4098,7 +4098,7 @@ describe('relay down-frames are default-deny: sealed, or the backend\'s own', ()
const serviceRouter = vi.fn(() => true)
socket.serviceRouter = serviceRouter
await dispatch(sealedDown(socket, 'web-1', 'dsh_install', { requestId: 'r', id: 'acme/some-dsh' }).frame, 'web-1')
- expect(serviceRouter).toHaveBeenCalledWith('dsh_install', expect.objectContaining({ id: 'acme/some-dsh' }), { local: false, owner: expect.any(Boolean), connection: 'web-1', requestId: 'r' }, expect.any(Function))
+ expect(serviceRouter).toHaveBeenCalledWith('dsh_install', expect.objectContaining({ id: 'acme/some-dsh' }), { local: false, owner: expect.any(Boolean), accountOwner: false, connection: 'web-1', requestId: 'r' }, expect.any(Function))
})
it('refuses a plaintext RPC even from the backend itself (connId \'\'), which would read the reply', async () => {
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 8773f1c06..91363a0c5 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -914,7 +914,8 @@ export class BackendSocket {
// A request a service answers, in its own process or in this one: routed to it, or answered
// SERVICE_UNAVAILABLE while it is off. Never waited on in line: the next frame is not held for it.
// Who asked is established here, after the gates above, and the service trusts only that.
- const asker: Asker = { local, owner, connection: connId, ...(typeof requestId === 'string' ? { requestId } : {}) }
+ const asker: Asker = { local, owner, ...(!local ? { accountOwner: this.remoteClient(connId)?.accountOwner === true } : {}),
+ connection: connId, ...(typeof requestId === 'string' ? { requestId } : {}) }
// A window that draws row state asks for the models list with `rowState`, and the list's changes are
// pushed to it in that form (`pushGridModels`). Noted here, by connection: the models service answers
// the list, and a request reaches it without its connection.
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d944636d4..0bb69d341 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -2507,6 +2507,7 @@ async function logsExportCommand(json: boolean): Promise<void> {
}
import { orchestratorCommand } from './orchestrator/command.js'
+import { superTabCommand } from './superTabs/command.js'
import { paneOwner, sendCommand } from './messages/command.js'
import { agentOrigin, closeCommand, psCommand, showCommand, waitCommand, whoamiCommand } from './agentClient/commands.js'
import { agentsHelp, helpFor } from './agentClient/help.js'
@@ -2578,6 +2579,9 @@ switch (cmd) {
case 'orchestrator':
orchestratorCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
+ case 'super-tab':
+ superTabCommand(rest).then(code => { process.exitCode = code }).catch(onError)
+ break
case 'login':
// The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the
// account: the desktop app reads that line and does not wait for a restart it observes anyway.
diff --git a/cli/src/core/agents/launches.spec.ts b/cli/src/core/agents/launches.spec.ts
index e15350dba..502ef8559 100644
--- a/cli/src/core/agents/launches.spec.ts
+++ b/cli/src/core/agents/launches.spec.ts
@@ -840,7 +840,7 @@ describe('agent_create_status', () => {
expect(created).toStrictEqual({ creationId: CREATION, state: 'created', agent: { id: 'forked' }, level: 'handoff', resumed: true })
expect(Object.keys(created!)).toEqual(['creationId', 'state', 'agent', 'level', 'resumed'])
outcome({ state: 'created', agentId: 'deleted-since' })
- expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unavailable' })
+ expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'unavailable', createdAgentId: 'deleted-since' })
outcome({ state: 'failed', error: 'ENGINE_MISSING', detail: 'claude is not installed', preparedFolder: '/projects/prepared' })
expect(await status({ creationId: CREATION })).toStrictEqual({ creationId: CREATION, state: 'failed', preparedFolder: '/projects/prepared', failure: { code: 'ENGINE_MISSING', detail: 'claude is not installed' } })
outcome({ state: 'unconfirmed' })
diff --git a/cli/src/core/agents/launches.ts b/cli/src/core/agents/launches.ts
index 0f952be69..e8938e126 100644
--- a/cli/src/core/agents/launches.ts
+++ b/cli/src/core/agents/launches.ts
@@ -234,7 +234,7 @@ export function createLaunchRequests({ receipts, createAgent, prepareCreate, pre
const session = byAgent(status.agentId)
return session
? { state: 'created', agent: await toProject(session), ...(status.level ? { level: status.level } : {}), ...(status.resumed !== undefined ? { resumed: status.resumed } : {}) }
- : { state: 'unavailable' }
+ : { state: 'unavailable', createdAgentId: status.agentId }
}
// A recorded refusal is a completed outcome. Keep it separate from transport/dispatch errors
// so clients can distinguish "safe to correct the choices" from "outcome still unknown".
diff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.ts
index efbb92e01..0635bae2b 100644
--- a/cli/src/core/api.spec.ts
+++ b/cli/src/core/api.spec.ts
@@ -6,6 +6,17 @@ import { FAIL, readFallback } from './serviceHost.js'
const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession
describe('the core API services stand on', () => {
+ it('exposes an optional native-turn observer without importing feature state', () => {
+ const nativeTurns = vi.fn(async () => null)
+ expect(createCoreApi({ ...coreDeps(), nativeTurns }).transcripts.nativeTurns).toBe(nativeTurns)
+ expect(createCoreApi(coreDeps()).transcripts.nativeTurns).toBeUndefined()
+ })
+ it('carries the existing native creation-status provider without inventing one for an older core', async () => {
+ const creationStatus = vi.fn(async (creationId: string) => ({ creationId, state: 'cancelled' as const }))
+ const core = createCoreApi({ ...coreDeps(), creationStatus })
+ expect(await core.agents.creationStatus!('creation-fixture-1234')).toEqual({ creationId: 'creation-fixture-1234', state: 'cancelled' })
+ expect(createCoreApi(coreDeps()).agents.creationStatus).toBeUndefined()
+ })
it('gives a service with no lane of the core\'s nothing to seal with, and never its frame back in the clear', async () => {
await expect(LANE_OFF.hello('m', 'pub')).rejects.toThrow(/no E2EE identity/)
expect(await LANE_OFF.welcome('m', {})).toBe(false)
@@ -40,6 +51,7 @@ describe('the core API services stand on', () => {
expect(DELIVERIES_OFF.deliver('a', 'hello', 'd1')).toBeUndefined()
expect(DELIVERIES_OFF.cancelDelivery('d1')).toBe(false)
expect(DELIVERIES_OFF.onDelivery(() => {})()).toBeUndefined()
+ expect(await DELIVERIES_OFF.leaseDeliveries('test', {})).toBe(false)
})
it('resolves an agent in a service\'s own copy as the registry does: by agent id, then session id', () => {
@@ -88,7 +100,7 @@ describe('the core API services stand on', () => {
tabRelay: TAB_RELAY_OFF,
connectorVault: CONNECTOR_VAULT_OFF,
observer: vi.fn(() => true),
- turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(async () => []), asks: vi.fn(async () => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },
+ turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(async () => []), asks: vi.fn(async () => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}), leaseDeliveries: vi.fn(async () => false) },
questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },
machine: { id: vi.fn(() => 'machine-1'), computerId: vi.fn(() => 'computer-1'), name: vi.fn(() => 'Studio') },
activityText: vi.fn(async () => 'Reading 3 files'),
@@ -125,6 +137,9 @@ describe('the core API services stand on', () => {
const terminals = { ...TERMINALS_OFF, open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }
expect(createCoreApi({ ...deps, terminals }).terminals).toBe(terminals)
expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])
+ expect(await core.agents.stopped!('live')).toBe(false)
+ expect(await core.agents.stopped!('unknown')).toBe(false)
+ expect(await core.agents.stopped!('stopped')).toBe(true)
expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])
expect(core.agents.displayName).toBe(projectDisplayName)
expect(core.transcripts.databaseHistory).toBe(deps.databaseHistory)
@@ -320,7 +335,7 @@ describe('the core API services stand on', () => {
})
it('starts with every port empty: a service fills its own when it starts', () => {
- expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null })
+ expect(emptyPorts()).toEqual({ usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null })
expect(emptyPorts()).not.toBe(emptyPorts())
})
diff --git a/cli/src/core/api.ts b/cli/src/core/api.ts
index cbcedb3c4..14634daa8 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -18,6 +18,7 @@ import type { GridAssignmentProcess, GridAssignmentAnswer } from '../lib/gridAss
* returns. The core routes them to it; a port is only for what the core itself must ask.
*/
import type { RecentTurn } from '../cable/cableHost.js'
+import type { NativeTurnRead } from '../lib/nativeTurnObservations.js'
import type { ReviewedAnswer } from '../cable/questionInbox.js'
import type { AgentEngine } from '../engines/types.js'
import type { AppSwarms } from '../cable/cableSession.js'
@@ -34,6 +35,7 @@ import { GRID_FLEET_MAX_TIMEOUT_MS } from '../lib/gridFleetProtocol.js'
import type { GridLaunchAnswer, GridLaunchOverride, GridLaunchRequest } from '../lib/gridLaunchWire.js'
import type { NewAgentModel } from '../lib/newAgentModel.js'
import type { LastTurnText, LiveEvent } from '../engines/kit/events.js'
+import type { CreationObservation } from '../lib/creationObservation.js'
import type { SessionRecaps } from '../lib/recapReads.js'
import type { SessionInputDelivery } from '../lib/sessionInput.js'
import type { AgentCloseRequest, AgentCloseResult } from '../lib/closeAgentService.js'
@@ -159,6 +161,12 @@ export interface CoreApi {
cloud?(): RegisteredSession[]
/** Whether the agent's terminal is attached: a frame without one reads to the apps as "agent gone". */
terminalAvailable(agentId: string): boolean
+ /** Fresh native lifecycle evidence. Absence from a live snapshot alone is
+ * not a stop: a saved stopped record must also exist in the core. */
+ stopped?(agentId: string): Promise<boolean>
+ /** The exact durable native creation receipt. Null means unavailable, never
+ * proof that a launch was missing, cancelled or failed. */
+ creationStatus?(creationId: string): Promise<CreationObservation | null>
/** Send the agent's frame to the apps again. */
sync(session: RegisteredSession): void
/** The Model/Effort choices an agent's engine offers (opaque `runtime-v1` ids): one agent's, or
@@ -221,6 +229,10 @@ export interface CoreApi {
/** Hear what becomes of each delivery: queued, written, its turn started, refused and why, or past
* knowing. Returns how to stop hearing. */
onDelivery(listener: (event: TurnDelivery) => void): () => void
+ /** Replace a service's short-lived permission to write queued typed deliveries.
+ * IDs use `team:service:<service>:`; expired or absent permission means wait.
+ * This guards the final terminal write even when its authorizing service stops. */
+ leaseDeliveries(service: string, leases: Record<string, number>): Promise<boolean>
}
questions: {
/** Answer a live agent's question, keyed by the question keys it asked with. */
@@ -235,6 +247,9 @@ export interface CoreApi {
/** A session's last turn as its engine recorded it: what was asked and the final answer; null when
* there is none yet. Read from the end of its transcript, bounded (core/transcripts/lastTurn.ts). */
lastTurn(sessionId: string): Promise<LastTurnText | null>
+ /** Bounded live prompt/answer observations, starting at a requested cursor.
+ * An omitted cursor establishes the current boundary, without past history. */
+ nativeTurns?: NativeTurnRead
}
/** The sign-in the core holds for every service: a service never holds a credential itself. */
account: {
@@ -539,10 +554,11 @@ export type TurnDelivery = SessionInputDelivery
/** The delivery members of a core that delivers nothing for this service: nothing is written, nothing is
* taken back, and nothing is heard. */
-export const DELIVERIES_OFF: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {
+export const DELIVERIES_OFF: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery' | 'leaseDeliveries'> = {
deliver: () => {},
cancelDelivery: () => false,
onDelivery: () => () => {},
+ leaseDeliveries: async () => false,
}
/** A turn's card for the devices: the dial's and the Wi-Fi device's tiles and their notifications. */
@@ -570,9 +586,13 @@ export function resolveAgent(agents: readonly RegisteredSession[], id: string):
export interface Asker {
/** A process on this machine (the desktop app, `hn`, a script), over the local socket. */
local: boolean
- /** Whether it may act as this machine's owner: a local process, or the owner's paired app over the
- * relay. A device or an observer may not. */
+ /** Whether it may control this machine: a local process, a paired app, or a verified machine share.
+ * A device or an observer may not. Account-backed services also check accountOwner. */
owner: boolean
+ /** Authority to use the host account, separately from control of a shared machine.
+ * Established by the gateway's pairing record, never by the request payload.
+ * Absent in older transports; a local owner remains authoritative. */
+ accountOwner?: boolean
/** The connection it came over (a window's, a remote client's), as the core names it, and the id it
* asked under: what a service keys work by that belongs to one connection (the Model Manager's grid
* commands, which a cancel on the same connection stops; a limit on how many at once per connection).
@@ -617,6 +637,9 @@ export const MEMORY_REQUESTS = ['memory_snapshot', 'memory_about_put', 'memory_d
/** The router (services/router.ts), an experiment: where a task a person typed or said should go, decided for
* the client that asks, which acts on it. */
export const ROUTER_REQUESTS = ['route_decide'] as const
+export const SUPER_TAB_REQUESTS = ['super_tabs'] as const
+export interface SuperTabsPort { connected(): void; disconnected(): void; stop(): void }
+export const SUPER_TAB_FALLBACKS: PortFallbacks<SuperTabsPort> = { connected: undefined, disconnected: undefined, stop: undefined }
/** The project and folder readers (services/projects.ts). */
export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const
/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */
@@ -772,12 +795,13 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];
orchestrator: { requests: ORCHESTRATOR_REQUESTS, state: ['orchestrator/*.json'] },
// Its invitations and links: a harness was shared from here. Or a shared tab held here (Agent Messages' file): the
// observers its members are granted are derived and renewed by Share, and taken back once one leaves.
- sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json', 'agent-messages/shared-tabs.json'] },
+ sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json', 'agent-messages/shared-tabs.json', 'super-tabs/host-*.json'] },
// Request-only, on from its first request until the daemon stops: another machine's Memories pane asks, and
// the package's own files are its state.
memory: { requests: MEMORY_REQUESTS, state: [] },
// Request-only too: it keeps nothing, and asks Jev only when a client asks it.
router: { requests: ROUTER_REQUESTS, state: [] },
+ superTabs: { requests: SUPER_TAB_REQUESTS, state: ['super-tabs/host-*.json'] },
// Cloud agents. Its harnesses: one was started here, and is watched again as the daemon starts. A New Harness
// for one, an answer or a message to one wakes it too (its port's calls, core/agents/cloud.ts).
cloud: { requests: CLOUD_REQUESTS, state: ['cloud/harnesses.json'] },
@@ -1305,6 +1329,7 @@ export type RemoteRole = 'web' | 'device'
* the relay. Nothing here is a secret. */
export interface RemoteClient {
role: RemoteRole
+ accountOwner?: boolean
label: string | null
identity: string
direct: boolean
@@ -1608,10 +1633,11 @@ export interface CorePorts {
recaps: RecapsPort | null
agentCleanup: AgentCleanupPort | null
cloud: CloudPort | null
+ superTabs: SuperTabsPort | null
}
export function emptyPorts(): CorePorts {
- return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null }
+ return { usage: null, store: null, search: null, viewers: null, models: null, workspaces: null, messages: null, devices: null, wifi: null, monitor: null, orchestrator: null, sharing: null, recaps: null, agentCleanup: null, cloud: null, superTabs: null }
}
export interface CoreApiDeps {
@@ -1641,6 +1667,7 @@ export interface CoreApiDeps {
backend: CoreApi['account']['backend']
onNotice: CoreApi['account']['onNotice']
create: CoreApi['agents']['create']
+ creationStatus?: CoreApi['agents']['creationStatus']
dsh: CoreApi['agents']['dsh']
windows: CoreApi['clients']['windows']
daemon: DaemonAddress
@@ -1677,6 +1704,7 @@ export interface CoreApiDeps {
/** The running cloud harnesses as list rows (`agents.cloud`). */
cloudRows?: () => RegisteredSession[]
lastTurn: CoreApi['transcripts']['lastTurn']
+ nativeTurns?: NativeTurnRead
/** Where a turn's cards and recaps go: the devices, and the apps. Only their own frame types reach these. */
turnCard: CoreApi['clients']['turnCard']
turnSummary: CoreApi['clients']['turnSummary']
@@ -1686,9 +1714,9 @@ export interface CoreApiDeps {
export function createCoreApi({
dataDir, registry, stoppedAgents, databaseHistory, syncSession, runtimeModels, viewerChanged,
gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, tabKey, tabRelay, connectorVault, observer, privateGridName, machineName, backend, onNotice,
- runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText, activitySnapshot, activity, summaries,
+ runtimeProfile, setRuntime, fork, create, creationStatus, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF, conversations = CONVERSATIONS_OFF, viewerFrame, machine, activityText, activitySnapshot, activity, summaries,
closeAgent, activityAt,
- signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, cloud, cloudRows, lastTurn, turnCard, turnSummary,
+ signedIn, environment, machines, sendLocal, sendToWindow, hasWindow, devicesChanged, dialWatching, wifi, cloud, cloudRows, lastTurn, nativeTurns, turnCard, turnSummary,
log = (line) => console.warn(line),
}: CoreApiDeps): CoreApi {
// The devices reach the windows through these alone, and only with their own frames: a devices process
@@ -1705,6 +1733,7 @@ export function createCoreApi({
conversations,
agents: {
all: () => [...registry.list(), ...stoppedAgents.list()],
+ stopped: async id => !registry.byAgent(id) && stoppedAgents.list().some(s => s.agentId === id),
live: () => registry.list(),
displayName: projectDisplayName,
byAgent: (agentId) => registry.byAgent(agentId),
@@ -1718,6 +1747,7 @@ export function createCoreApi({
setRuntime,
fork,
create,
+ ...(creationStatus ? { creationStatus } : {}),
dsh,
activityText,
activitySnapshot,
@@ -1739,7 +1769,7 @@ export function createCoreApi({
},
turns,
questions,
- transcripts: { databaseHistory, lastTurn },
+ transcripts: { databaseHistory, lastTurn, ...(nativeTurns ? { nativeTurns } : {}) },
account: { mintGridName, accessToken, lane, observerKey, tabKey, tabRelay, connectorVault, privateGridName, machineName, backend,
identity: accountIdentity(backend), onNotice, signedIn, environment, machines },
clients: {
diff --git a/cli/src/core/deliveries.spec.ts b/cli/src/core/deliveries.spec.ts
index 1fcdb97c1..81fc5f62c 100644
--- a/cli/src/core/deliveries.spec.ts
+++ b/cli/src/core/deliveries.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { TurnDelivery } from './api.js'
-import { createDeliveries, HELD_DELIVERIES, KEPT_DELIVERERS, type DeliveriesDeps } from './deliveries.js'
+import { createDeliveries, DELIVERY_LEASE_MS, HELD_DELIVERIES, KEPT_DELIVERERS, type DeliveriesDeps } from './deliveries.js'
const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliverers'>> = {}, ready = true) => {
const deps = {
@@ -17,6 +17,35 @@ const setup = (over: Partial<Pick<DeliveriesDeps, 'submit' | 'cancel' | 'deliver
const event = (deliveryId: string, state: TurnDelivery['state'] = 'queued'): TurnDelivery => ({ deliveryId, sessionId: 'agent-1', state })
describe('delivered turns', () => {
+ it('expires a service permission at the terminal write and replaces it on revocation', async () => {
+ let clock = 10_000
+ const deliveries = createDeliveries({ submit: vi.fn(), cancel: vi.fn(() => false), tell: vi.fn(), deliverers: new Set(['worker']), now: () => clock })
+ const id = 'team:service:worker:one'
+ expect(deliveries.canWrite('team:legacy')).toBeNull()
+ expect(deliveries.canWrite(id)).toBe(false)
+ expect(await deliveries.turns.leaseDeliveries('worker', { [id]: clock + 60_000 })).toBe(true)
+ expect(deliveries.canWrite(id)).toBe(true)
+ clock += DELIVERY_LEASE_MS
+ expect(deliveries.canWrite(id)).toBe(false)
+ expect(deliveries.answer('worker', 'lease_deliveries', { leases: { [id]: clock + 1000 } })).toEqual({ leased: true })
+ expect(deliveries.canWrite(id)).toBe(true)
+ await deliveries.turns.leaseDeliveries('worker', {})
+ expect(deliveries.canWrite(id)).toBe(false)
+ expect(deliveries.answer('worker', 'deliver', { deliveryId: id, agentId: 'a', text: 'x' })).toEqual({})
+ })
+
+ it('cannot grant, cancel or submit another service namespace or unbounded permissions', async () => {
+ const { deliveries, deps } = setup()
+ const id = 'team:service:other:one'
+ expect(deliveries.answer('orchestrator', 'deliver', { deliveryId: id, agentId: 'a', text: 'x' })).toEqual({ error: 'INVALID_DELIVERY' })
+ expect(deliveries.answer('orchestrator', 'cancel_delivery', { deliveryId: id })).toEqual({ error: 'INVALID_DELIVERY' })
+ expect(await deliveries.turns.leaseDeliveries('unknown', {})).toBe(false)
+ for (const leases of [null, 4, [], { [id]: Date.now() }, { 'team:service:orchestrator:a': 'later' }, { 'team:service:orchestrator:a': Infinity }, { [`team:service:orchestrator:${'x'.repeat(240)}`]: 100 }, Object.fromEntries(Array.from({ length: HELD_DELIVERIES + 1 }, (_, i) => [`team:service:orchestrator:${i}`, 100]))]) {
+ expect(deliveries.answer('orchestrator', 'lease_deliveries', { leases })).toEqual({ leased: false })
+ }
+ expect(deps.submit).not.toHaveBeenCalled()
+ expect(deps.cancel).not.toHaveBeenCalled()
+ })
it('writes a delivery from the core\'s own process into the agent, and takes one back at once', () => {
const { deps, deliveries } = setup({ cancel: vi.fn(() => false) })
deliveries.turns.deliver('agent-1', 'hello', 'd1')
diff --git a/cli/src/core/deliveries.ts b/cli/src/core/deliveries.ts
index ff60c51bf..5c9781150 100644
--- a/cli/src/core/deliveries.ts
+++ b/cli/src/core/deliveries.ts
@@ -23,6 +23,11 @@ export const HELD_DELIVERIES = 1_000
* makes a few a minute. */
export const KEPT_DELIVERERS = 10_000
+/** A service must keep checking authority while a turn waits for an idle terminal. */
+export const DELIVERY_LEASE_MS = 3_000
+const guarded = (id: string) => id.startsWith('team:service:')
+const owned = (service: string, id: string) => id.startsWith(`team:service:${service}:`) && id.length <= 240
+
export interface DeliveriesDeps {
/** Write the text into the agent under the delivery id (core/input.ts `submitAgent`). */
submit(agentId: string, text: string, deliveryId: string): void
@@ -33,6 +38,7 @@ export interface DeliveriesDeps {
/** The services in their own processes that may deliver turns: writing into an agent is no other's to ask. */
deliverers: ReadonlySet<string>
log?: (line: string) => void
+ now?: () => number
}
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -40,6 +46,16 @@ const text = (value: unknown): string => (typeof value === 'string' ? value : ''
export function createDeliveries(deps: DeliveriesDeps) {
const log = deps.log ?? ((line: string) => console.warn(line))
const listeners = new Set<(event: TurnDelivery) => void>()
+ const now = deps.now ?? Date.now
+ const leases = new Map<string, Map<string, number>>()
+ const lease = (service: string, input: unknown): boolean => {
+ if (!deps.deliverers.has(service) || !input || typeof input !== 'object' || Array.isArray(input)) return false
+ const entries = Object.entries(input)
+ if (entries.length > HELD_DELIVERIES || entries.some(([id, until]) => !owned(service, id) || typeof until !== 'number' || !Number.isFinite(until))) return false
+ const ceiling = now() + DELIVERY_LEASE_MS
+ leases.set(service, new Map(entries.map(([id, until]) => [id, Math.min(until as number, ceiling)])))
+ return true
+ }
/** Which process made each delivery, oldest first. */
const makers = new Map<string, string>()
/**
@@ -74,19 +90,28 @@ export function createDeliveries(deps: DeliveriesDeps) {
if (maker) deps.tell(maker, event)
}
- const turns: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery'> = {
+ const turns: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery' | 'leaseDeliveries'> = {
deliver: (agentId, content, deliveryId) => submit(agentId, content, deliveryId),
cancelDelivery: (deliveryId) => cancel(deliveryId),
onDelivery: (listener) => {
listeners.add(listener)
return () => { listeners.delete(listener) }
},
+ leaseDeliveries: async (service, input) => lease(service, input),
}
return {
/** The delivery members of the core's own `CoreApi`, for the services in its process. */
turns,
+ /** Null leaves older delivery namespaces to their existing policy. An unknown
+ * guarded ID is denied, including after a core restart forgets all leases. */
+ canWrite(deliveryId: string): boolean | null {
+ if (!guarded(deliveryId)) return null
+ const service = deliveryId.split(':')[2]
+ return (leases.get(service)?.get(deliveryId) ?? 0) > now()
+ },
+
/** The core's input says what became of a delivery: every listener here hears it, each guarded, and the
* process that made it is told. A listener that throws costs that listener the event, never the input
* that said it or another listener. */
@@ -102,10 +127,12 @@ export function createDeliveries(deps: DeliveriesDeps) {
/** A service in its own process delivering a turn, or taking one back (`service_query`): null when the
* query is not one of these. Refused for a service that is not a deliverer. */
answer(service: string, query: string, payload: Payload): Payload | null {
- if (query !== 'deliver' && query !== 'cancel_delivery') return null
+ if (query !== 'deliver' && query !== 'cancel_delivery' && query !== 'lease_deliveries') return null
if (!deps.deliverers.has(service)) return { error: 'NOT_A_DELIVERER' }
+ if (query === 'lease_deliveries') return { leased: lease(service, payload.leases) }
const deliveryId = text(payload.deliveryId)
if (!deliveryId) return { error: 'INVALID_DELIVERY' }
+ if (guarded(deliveryId) && !owned(service, deliveryId)) return { error: 'INVALID_DELIVERY' }
if (query === 'cancel_delivery') return { cancelled: cancel(deliveryId) }
const agentId = text(payload.agentId)
if (!agentId || typeof payload.text !== 'string') return { error: 'INVALID_DELIVERY' }
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index 32ee53a2d..9edcbe1a3 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
-import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
+import { answerExperimentQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'
const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSession
const experiments = new Set(['orchestrator'])
@@ -27,19 +27,61 @@ describe('the cloud agents\' doors', () => {
})
describe('what an experiment in its own process may ask of the core', () => {
+ it('reads exact creation observations without treating an unavailable provider as an absent launch', async () => {
+ const id = 'creation-fixture-1234'
+ const known = { creationId: id, state: 'cancelled' as const }
+ const core = fakeCore({ agents: { creationStatus: async () => known } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'creation_status', { creationId: id })).toEqual({ observation: known })
+ expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'creation_status', {})).toEqual({ observation: null })
+ expect(await creationForExperiment(null, id)).toBeNull()
+ const read = vi.fn(async (input, reply) => { reply({ ...input, state: 'created', agent: { id: 'native', private: 'not projected' } }) })
+ expect(await creationForExperiment(read, 'invalid')).toBeNull()
+ expect(read).not.toHaveBeenCalled()
+ expect(await creationForExperiment(read, id)).toEqual({ creationId: id, state: 'created', agentId: 'native' })
+ expect(await creationForExperiment(async () => {}, id)).toBeNull()
+ expect(await creationForExperiment(async () => { throw new Error('Disk unavailable') }, id)).toBeNull()
+ expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'cancelled' }) }, id)).toEqual(known)
+ expect(await creationForExperiment(async (_, reply) => { reply({ creationId: 'other', state: 'cancelled' }) }, id)).toBeNull()
+ expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'unavailable', createdAgentId: 'closed-native' }) }, id))
+ .toEqual({ creationId: id, state: 'created', agentId: 'closed-native' })
+ expect(await creationForExperiment(async (input, reply) => { reply({ ...input, state: 'unavailable' }) }, id)).toBeNull()
+ })
+ it('requires fresh native stop evidence, including when a core is older', async () => {
+ const core = fakeCore({ agents: { stopped: async id => id === 'stopped' } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'stopped', { agentId: 'stopped' })).toEqual({ stopped: true })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'stopped', { agentId: 'live' })).toEqual({ stopped: false })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'stopped', {})).toEqual({ stopped: false })
+ expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'stopped', { agentId: 'unknown' })).toEqual({ stopped: false })
+ })
+
+ it('bounds native observation queries and keeps an older core unavailable', async () => {
+ const cursor = { epoch: 'fixture-observation-epoch', sequence: 0 }
+ const page = { cursor, observations: [], gap: false }, nativeTurns = vi.fn(async () => page)
+ const core = fakeCore({ transcripts: { nativeTurns } })
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'native_turns', { agentId: 'native' })).toEqual({ page })
+ expect(nativeTurns).toHaveBeenLastCalledWith('native', undefined)
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'native_turns', { agentId: 'native', cursor })).toEqual({ page })
+ expect(nativeTurns).toHaveBeenLastCalledWith('native', cursor)
+ for (const payload of [{}, { agentId: 'native', cursor: null }, { agentId: 'native', cursor: { ...cursor, sequence: -1 } }]) {
+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'native_turns', payload)).toEqual({ error: 'INVALID_REQUEST' })
+ }
+ expect(await answerExperimentQuery(fakeCore(), experiments, 'orchestrator', 'native_turns', { agentId: 'native' })).toEqual({ page: null })
+ })
+
it('shows the live agents as the apps are shown them: name, terminal and harness', async () => {
const core = fakeCore({
agents: {
live: () => [agent('a1'), agent('a2')],
displayName: (session) => `name of ${session.agentId}`,
terminalAvailable: (agentId) => agentId === 'a1',
+ runtimeProfile: session => session.agentId === 'a1' ? 'runtime-v1:a1:claude:opus@high' : null,
dsh: (session) => (session.agentId === 'a1' ? { viewerUrl: 'http://127.0.0.1:1/' } as never : null),
},
})
expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'shown', {})).toEqual({
agents: [
- { ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, dshContext: { viewerUrl: 'http://127.0.0.1:1/' } },
- { ...agent('a2'), displayName: 'name of a2', terminalAvailable: false, dshContext: null },
+ { ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, selectedModel: 'runtime-v1:a1:claude:opus@high', dshContext: { viewerUrl: 'http://127.0.0.1:1/' } },
+ { ...agent('a2'), displayName: 'name of a2', terminalAvailable: false, selectedModel: null, dshContext: null },
],
})
})
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index cce8b0045..28c5436de 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -6,6 +6,7 @@
* - `shown`: the live agents as the apps are shown them: each with its name, whether its terminal is there,
* and what its frame says about its harness (its viewer);
* - `create`: create an agent, as the window's `agent_create` does;
+ * - `creation_status`: read the exact native receipt without exposing its launch request;
* - `stop_turn`: stop an agent's turn;
* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);
* - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;
@@ -25,11 +26,13 @@
*/
import type { BackendSocket } from '../backendSocket.js'
import type { AgentCreateRequest, CoreApi } from './api.js'
+import { creationObservation } from '../lib/creationObservation.js'
+import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
-type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud'>
+type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'transcripts'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'stopped', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -41,6 +44,7 @@ export function shownAgents(core: Pick<CoreApi, 'agents'>): Payload {
...session,
displayName: core.agents.displayName(session),
terminalAvailable: core.agents.terminalAvailable(session.agentId),
+ selectedModel: core.agents.runtimeProfile(session),
dshContext: core.agents.dsh(session),
})),
}
@@ -62,6 +66,15 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
switch (query) {
case 'shown':
return shownAgents(core)
+ case 'stopped':
+ return { stopped: !!text(payload.agentId) && await core.agents.stopped?.(text(payload.agentId)) === true }
+ case 'creation_status':
+ return { observation: await core.agents.creationStatus?.(text(payload.creationId)) ?? null }
+ case 'native_turns': {
+ const cursor = payload.cursor === undefined ? undefined : nativeTurnCursorIn(payload.cursor)
+ if (!/^[A-Za-z0-9_-]{1,160}$/.test(text(payload.agentId)) || cursor === null) return { error: 'INVALID_REQUEST' }
+ return { page: await core.transcripts.nativeTurns?.(text(payload.agentId), cursor) ?? null }
+ }
case 'create': {
if (!text(payload.engine) || !text(payload.cwd) || typeof payload.prompt !== 'string' || typeof payload.name !== 'string') return { ok: false, error: 'INVALID_REQUEST' }
const request: AgentCreateRequest = {
@@ -128,3 +141,18 @@ export async function createForExperiment(create: BackendSocket['onCreateAgent']
const result = await create({ ...request, grid: null, codexHome: null, agent: null, permissionMode: null })
return result.ok ? { ok: true, agentId: result.session.agentId } : { ok: false, error: result.error, ...(result.detail ? { detail: result.detail } : {}) }
}
+
+/** Read the window's receipt through its existing provider; never infer a
+ * cancelled launch from a missing callback, an old core or a failed read. */
+export async function creationForExperiment(read: BackendSocket['createStatusProvider'], creationId: string) {
+ if (!read || !/^[A-Za-z0-9_-]{16,96}$/.test(creationId)) return null
+ let reply: Record<string, unknown> | null = null
+ try { await read({ creationId }, value => { reply = value }) } catch { return null }
+ const frame = reply as Record<string, unknown> | null
+ const agent = frame?.agent as { id?: unknown } | undefined
+ // A closed terminal is unavailable to a window, but its durable creation
+ // receipt still identifies what launched. A service can check its stop.
+ return creationObservation(creationId, frame?.state === 'unavailable'
+ ? { ...frame, state: 'created', agentId: frame.createdAgentId }
+ : { ...frame, agentId: agent?.id })
+}
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index 707dc2e22..84f751495 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -447,6 +447,19 @@ describe('createInput', () => {
describe('message', () => {
afterEach(() => vi.restoreAllMocks())
+ it('carries a bounded opaque context with the actual composed message, without treating it as identity', async () => {
+ const promptTyped = vi.fn(), run = deps({ promptTyped }), inputs = createInput(run.deps)
+ const context = 'conversation-input-context'
+ inputs.messageRequest({ agentId: 'a1', content: 'Scoped composed input', inputContext: context })
+ await vi.waitFor(() => expect(promptTyped).toHaveBeenCalledWith(agents.get('a1'), READY_PANE, expect.any(Object), context))
+ inputs.input.forget('a1')
+ const plain = vi.fn(), request = createMessageRequest(plain)
+ request({ agentId: 'a1', content: 'Unscoped', inputContext: { user: 'untrusted' } })
+ expect(plain).toHaveBeenCalledWith('a1', 'Unscoped')
+ // An observer is optional; a scoped message still uses the original writer.
+ expect(await messageWriter(deps().deps)('a1', 'Without observer', undefined, context)).toEqual(ok)
+ })
+
it('writes what a person typed into the agent the frame names, and reads no tab an older window still names', () => {
const typed = vi.fn()
const inputs = createInput({ ...deps().deps, typed })
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 82f4bf775..35030ac0c 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -25,6 +25,7 @@ import type { ScreenReading } from '../engines/facets/screen.js'
import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'
import type { TerminalControl } from './terminals/control.js'
import { launchBound } from './engines/sessionBinding.js'
+import { inputContextIn } from '../lib/nativeTurnObservations.js'
type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }
@@ -52,7 +53,7 @@ export interface InputDeps {
emit: (sessionId: string, events: LiveEvent[]) => void
/** A prompt is about to be typed, and `capture` is the pane as read right before: what is on it belongs
* to the turns before the one it starts (the question watcher's, lib/askQuestion.ts `notePrompt`). */
- promptTyped?: (session: RegisteredSession, capture: string | null, screen: ScreenReading) => void
+ promptTyped?: (session: RegisteredSession, capture: string | null, screen: ScreenReading, inputContext?: string) => void
/** The person sent text to an agent from a window or the phone (a `message` frame, by agent or session id): one
* another agent started is theirs from then on (services/agentCleanup.ts). */
typed?: (id: string) => void
@@ -72,7 +73,7 @@ export interface InputDeps {
* it so.
*/
export function messageWriter({ readScreen, resolve, terminal: { captureTerminal, validateTerminal, submitTerminalAction }, promptTyped }: Pick<InputDeps, 'resolve' | 'terminal' | 'promptTyped' | 'readScreen'>) {
- return async (id: string, text: string, hold?: (session: RegisteredSession, screen: ScreenReading | null) => string | null): Promise<TerminalActionResult> => {
+ return async (id: string, text: string, hold?: (session: RegisteredSession, screen: ScreenReading | null) => string | null, inputContext?: string): Promise<TerminalActionResult> => {
const session = resolve(id)
if (!session) return terminalActionNotStarted('terminal agent is unavailable')
// The engine first, then its screen. A check of the engine can wait, seconds, for an answer: a probe
@@ -86,7 +87,8 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminal
if (!screen) return terminalActionNotStarted(hold?.(session, null) ?? 'screen_unreadable')
const reason = hold?.(session, screen) ?? screen.messageHold
if (reason) return terminalActionNotStarted(reason)
- promptTyped?.(session, capture, screen)
+ if (inputContext) promptTyped?.(session, capture, screen, inputContext)
+ else promptTyped?.(session, capture, screen)
return submitTerminalAction(id, text, {
beforeEnter: async () => {
// A read that came back empty, or a composer caught between frames, is asked again for a moment
@@ -134,7 +136,7 @@ export function sessionInputDeps(
},
validateRuntime: validateTerminal,
// Typed into the pane as it stands, a draft or a running turn included, under the pane's write lock.
- inject: (id, text) => deviceInput().legacyWrite(id, () => writeMessage(id, text)),
+ inject: (id, text, inputContext) => deviceInput().legacyWrite(id, () => writeMessage(id, text, undefined, inputContext)),
// An Agent Messages turn waits for a ready composer, and for its mailbox to still want it written.
injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {
if (!resolve(id)) return terminalActionNotStarted('team_waiting_unavailable')
@@ -213,7 +215,7 @@ export function createInput(deps: InputDeps) {
releaseInput()
}
}
- const submitAgent = (id: string, content: string, deliveryId?: string): void => {
+ const submitAgent = (id: string, content: string, deliveryId?: string, inputContext?: string): void => {
const record = resolve(id)
const sessionId = record?.sessionId ?? id
const engine = record?.engine ?? 'claude'
@@ -226,9 +228,11 @@ export function createInput(deps: InputDeps) {
console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)
}
console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)
- input.submit(record?.agentId ?? sessionId, adapted, deliveryId)
+ const target = record?.agentId ?? sessionId
+ if (inputContext) input.submit(target, adapted, deliveryId, inputContext)
+ else input.submit(target, adapted, deliveryId)
}
- const messageRequest = createMessageRequest(submitAgent, deps.typed)
+ const messageRequest = createMessageRequest((id, content, context) => submitAgent(id, content, undefined, context), deps.typed)
return { input, deviceInput, acquireTerminalControl, submitAgent, messageRequest }
}
@@ -239,7 +243,7 @@ export function createInput(deps: InputDeps) {
*
* Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md).
*/
-export function createMessageRequest(submit: (id: string, content: string) => void, typed?: (id: string) => void) {
+export function createMessageRequest(submit: (id: string, content: string, inputContext?: string) => void, typed?: (id: string) => void) {
return (payload: Record<string, unknown>): void => {
const content = payload.content as string | undefined
const target = (payload.agentId as string | undefined) || (payload.sessionId as string | undefined)
@@ -249,7 +253,9 @@ export function createMessageRequest(submit: (id: string, content: string) => vo
typed?.(target)
// From the relay this is only reached sealed: text typed into an agent is never taken from the relay
// in the clear.
- submit(target, content)
+ const context = inputContextIn(payload.inputContext)
+ if (context) submit(target, content, context)
+ else submit(target, content)
}
}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index a05b98f6b..faa7ff324 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -81,6 +81,7 @@ import { createKeepAbandonedConversation } from '../lib/keepAbandonedConversatio
import { RESUME_READINESS_BUDGET_MS } from '../lib/resumeStoppedAgent.js'
import { createConversationOwners } from './agents/conversationOwners.js'
import { OpenTabProtection } from '../lib/openTabProtection.js'
+import { createNativeTurnObservations, nativeTurnBinding } from '../lib/nativeTurnObservations.js'
import { sessionCheckpoints } from '../lib/sessionCheckpoint.js'
import { repairProjectCwds } from '../lib/cwdRepair.js'
import { stoppedAgents } from '../lib/stoppedAgents.js'
@@ -172,6 +173,7 @@ import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorT
import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'
import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'
import { createServiceHost, testFaults } from './serviceHost.js'
+import { SUPER_TAB_REQUESTS, SUPER_TAB_FALLBACKS } from './api.js'
import { startStalls } from './stall.js'
import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'
import { createViewerStreams } from './viewerStreams.js'
@@ -188,7 +190,7 @@ import { createDeliveries } from './deliveries.js'
import { createTerminalWatch } from './terminalWatch.js'
import { createSharingLink } from './sharingLink.js'
import { createAgentSettingsSync, createExperimentHooks, wakeExperiments } from './experiments.js'
-import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'
+import { answerExperimentQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'
import { answerConnectorsQuery } from './connectorsQueries.js'
import { answerSharedMachinesQuery } from './sharedMachinesQueries.js'
import { inlineSharedMachinesPort } from '../lib/sharedMachinesPort.js'
@@ -770,7 +772,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const tabRelay = tabRelayOf(() => gatewayOps.tabRelay)
// The prompt of each agent's last turn start: what the one-line summary of a working agent says (turns/summaries.ts).
const turnPrompts = new Map<string, string>()
+ const nativeTurns = createNativeTurnObservations({ resolve: id => nativeTurnBinding(registry.byAgent(id)) })
const coreApi = createCoreApi({
+ nativeTurns: async (agentId, cursor) => nativeTurns.read(agentId, cursor),
cloud: cloudDoors,
cloudRows: () => (cloudAgents?.dialRows() ?? []) as unknown as RegisteredSession[],
// Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).
@@ -872,6 +876,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
},
// The window's `agent_create` for an experiment's agents (core/experimentQueries.ts).
create: (request) => createForExperiment(backendRef?.onCreateAgent ?? null, request),
+ creationStatus: creationId => creationForExperiment(backendRef?.createStatusProvider ?? null, creationId),
// The window's `agent_close`, for the agent cleanup (services/agentCleanup.ts): createCoreApi lets it close only
// a harness another agent started. Read when it closes one, never now: the close service is built further down.
closeAgent: (request) => backendRef?.closeAgentService?.request(request) ?? Promise.resolve({ error: 'UNSUPPORTED' }),
@@ -1072,6 +1077,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// an older desktop and typing from a phone get it too; an agent on its own login has no `grid`.
onInput: (agentId, typed, from) => {
if (typed) browser.typed(agentId, from)
+ if (typed) nativeTurns.typed(agentId, from.inputContext, from.submitted === true)
const grid = registry.resolve(agentId)?.grid
if (grid) ports.models?.prewarm(grid)
// The person typing into a harness another agent started makes it theirs (services/agentCleanup.ts).
@@ -1212,7 +1218,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
deliveries: {
settled: (event) => deliveries.settled(event),
// Whether Agent Messages still wants one of its typed deliveries written (core/messagesLink.ts).
- canWrite: (deliveryId) => ports.messages?.canWrite(deliveryId) ?? false,
+ canWrite: (deliveryId) => deliveries.canWrite(deliveryId) ?? ports.messages?.canWrite(deliveryId) ?? false,
},
device: () => wifiCore.feed,
clients: backend,
@@ -1222,7 +1228,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Reassigned further down (the funnel): always the current one.
emit: (sessionId, events) => emitSessionEvents(sessionId, events),
// Declared further down: read as a prompt is typed, never now.
- promptTyped: (session, capture, screen) => { if (session.sessionId) questionWatcher.notePrompt(session.sessionId, capture, screen.question) },
+ promptTyped: (session, capture, screen, inputContext) => {
+ nativeTurns.submitting(session.agentId, inputContext)
+ if (session.sessionId) questionWatcher.notePrompt(session.sessionId, capture, screen.question)
+ },
// The person sent a harness text from a window or the phone (services/agentCleanup.ts).
typed: (id) => ports.agentCleanup?.typed(id),
})
@@ -1552,6 +1561,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
if (!outOfProcess.has('windowNames')) serviceHost.serve('windowNames', inline!.startWindowNames, coreApi, WINDOW_NAMES_REQUESTS)
if (!outOfProcess.has('memory')) serviceHost.serve('memory', inline!.startMemory, coreApi, MEMORY_REQUESTS)
if (!outOfProcess.has('router')) serviceHost.serve('router', inline!.startRouter, coreApi, ROUTER_REQUESTS)
+ if (!outOfProcess.has('superTabs')) serviceHost.start('superTabs', inline!.startSuperTabs, coreApi, SUPER_TAB_FALLBACKS, SUPER_TAB_REQUESTS)
if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)
// Connected services' MCP bridge and the Connectors screen (services/connectors.ts): here, or in the edge host.
if (!outOfProcess.has('connectors')) serviceHost.serve('connectors', inline!.startConnectors, coreApi, CONNECTORS_REQUESTS)
@@ -1642,6 +1652,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
search: sessionSearch,
turnStartedAt,
prompts: turnPrompts,
+ nativeTurns,
input,
deviceInput,
submission: submissions,
diff --git a/cli/src/core/messagesLink.spec.ts b/cli/src/core/messagesLink.spec.ts
index f34b0af95..960323a38 100644
--- a/cli/src/core/messagesLink.spec.ts
+++ b/cli/src/core/messagesLink.spec.ts
@@ -41,7 +41,7 @@ describe('Agent Messages in its own process, as the core keeps it', () => {
daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'machine-7', autonomousEnv: 'prod' },
account: { signedIn: () => signedIn },
})
- expect(await l.answer('shown', {})).toEqual({ agents: [{ ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, dshContext: null }] })
+ expect(await l.answer('shown', {})).toEqual({ agents: [{ ...agent('a1'), displayName: 'name of a1', terminalAvailable: true, selectedModel: null, dshContext: null }] })
expect(await l.answer('daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7', autonomousEnv: 'prod', signedIn: true })
signedIn = false
expect(await l.answer('daemon', {})).toMatchObject({ signedIn: false })
diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.ts
index 30789df03..9277dd7ac 100644
--- a/cli/src/core/turns/funnel.spec.ts
+++ b/cli/src/core/turns/funnel.spec.ts
@@ -41,6 +41,24 @@ function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {
describe('the event funnel', () => {
afterEach(() => vi.restoreAllMocks())
+ it('offers native observation after client dispatch without letting an observer break the turn', () => {
+ vi.spyOn(console, 'log').mockImplementation(() => {})
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const ingest = vi.fn()
+ const { funnel, calls } = setup('claude', { nativeTurns: { ingest } })
+ const events = [started(), text(), ended()]
+ funnel('s1', events)
+ expect(ingest).toHaveBeenLastCalledWith('a1', events, false)
+ funnel('s1', events, { replay: true })
+ expect(ingest).toHaveBeenLastCalledWith('a1', events, true)
+ funnel('s1', events, { resumed: true })
+ expect(ingest).toHaveBeenLastCalledWith('a1', events, true)
+ calls.length = 0
+ ingest.mockImplementationOnce(() => { expect(calls).toContain('send turn_ended'); throw new Error('Observer failed') })
+ funnel('s1', events)
+ expect(calls.slice(-2)).toEqual(['mirror', 'device stream'])
+ })
+
it('sends the clients a shell result without its outputTail, and still feeds the commander mirror with it', () => {
const sent: Array<{ payload: object }> = []
const { funnel, deps } = setup('claude', { clients: { send: vi.fn((f: { payload: object }) => { sent.push(f) }) } as never })
diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.ts
index b2ac3c635..92b8bfab7 100644
--- a/cli/src/core/turns/funnel.ts
+++ b/cli/src/core/turns/funnel.ts
@@ -58,6 +58,8 @@ export interface FunnelDeps {
startHeartbeat: (sessionId: string) => void
questionWatcher: Pick<QuestionWatcher, 'start' | 'noteTurnStart' | 'stop'>
mirror: Pick<TurnRecaps, 'ingest'>
+ /** On-demand, bounded native prompt/answer observers. No consumer is awaited. */
+ nativeTurns?: { ingest(agentId: string, events: readonly Events[number][], replay: boolean): void }
/** How a consumer outside the core is called ([outsideConsumers]). */
outside?: OutsideConsumers
}
@@ -100,7 +102,7 @@ export function outsideConsumers(options: {
/** The funnel itself, over what it feeds. */
export function funnelFor({
bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, prompts, input,
- deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, outside = outsideConsumers(),
+ deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, nativeTurns, outside = outsideConsumers(),
}: FunnelDeps) {
return (sessionId: string, events: Events, opts?: EmitOptions): void => {
if (!events.length || !bySession(sessionId)?.active) return
@@ -173,6 +175,7 @@ export function funnelFor({
// stops once mirror.heartbeat() reads it idle, which is at once while the recaps are off.
}
}
+ if (nativeTurns) outside('native-turns', () => nativeTurns.ingest(agentIdFor(sessionId), events, !!(opts?.resumed || opts?.replay)))
mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })
// Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.
if (!opts?.replay) outside('devices', () => device()?.stream(agentIdFor(sessionId), events))
diff --git a/cli/src/gateway/gateway.spec.ts b/cli/src/gateway/gateway.spec.ts
index 1040b9849..01b0f0259 100644
--- a/cli/src/gateway/gateway.spec.ts
+++ b/cli/src/gateway/gateway.spec.ts
@@ -64,12 +64,12 @@ const queuedFor = (socket: BackendSocket, connId: string): Frame[] =>
/** A paired client with a live session on `connId`: it proves its identity with a hello and reads the
* welcome, as the phone app does, so what it seals opens under the gateway's real session. */
-async function pairedClient(socket: BackendSocket, connId: string, opts: { role?: 'web' | 'device'; label?: string } = {}) {
+async function pairedClient(socket: BackendSocket, connId: string, opts: { role?: 'web' | 'device'; label?: string; shared?: boolean } = {}) {
const gateway = gatewayOf(socket)
const identity = C.newIdentity()
const pub = C.b64e(identity.pub)
- const store = (gateway.e2ee as unknown as { store: { addPaired(pub: string, label: string, at: number, role: string): void } }).store
- store.addPaired(pub, opts.label ?? 'Dee’s phone', Date.now(), opts.role ?? 'web')
+ const store = (gateway.e2ee as unknown as { store: { addPaired(pub: string, label: string, at: number, role: string, peer?: { shared?: boolean }): void } }).store
+ store.addPaired(pub, opts.label ?? 'Dee’s phone', Date.now(), opts.role ?? 'web', { shared: opts.shared })
const eph = C.newEphemeral()
await dispatchDown(socket, { type: 'e2e_hello', payload: { identityPub: pub, ephPub: C.b64e(eph.pub), sig: C.b64e(C.helloSig(identity.priv, MACHINE, eph.pub)) } }, connId)
const welcome = queuedFor(socket, connId).find((frame) => frame.type === 'e2e_welcome')!
@@ -88,7 +88,7 @@ describe('a remote client, as the core hears it', () => {
const socket = relaySocket(MACHINE)
expect(socket.remoteClient('phone-1')).toBeNull()
const phone = await pairedClient(socket, 'phone-1', { label: 'Dee’s phone' })
- expect(socket.remoteClient('phone-1')).toEqual({ role: 'web', label: 'Dee’s phone', identity: phone.pub, direct: false })
+ expect(socket.remoteClient('phone-1')).toEqual({ role: 'web', label: 'Dee’s phone', identity: phone.pub, direct: false, accountOwner: true })
await dispatchDown(socket, { type: '__client_disconnected', payload: {} }, 'phone-1')
expect(socket.remoteClient('phone-1')).toBeNull()
await socket.stop()
@@ -100,13 +100,16 @@ describe('a remote client, as the core hears it', () => {
socket.serviceRouter = (type, _payload, asker, reply) => { asked.push({ type, asker }); reply({ ok: true }); return true }
const phone = await pairedClient(socket, 'phone-1', { role: 'web' })
const dial = await pairedClient(socket, 'dial-1', { role: 'device', label: 'Desk dial' })
+ const colleague = await pairedClient(socket, 'colleague', { shared: true })
// A field in the payload claiming the owner's role is the sender's word; the session is the gateway's.
await dispatchDown(socket, phone.seal('dsh_list', { requestId: 'p', owner: false }), 'phone-1')
- await dispatchDown(socket, dial.seal('dsh_list', { requestId: 'd', owner: true, local: true, role: 'web' }), 'dial-1')
+ await dispatchDown(socket, dial.seal('dsh_list', { requestId: 'd', owner: true, local: true, role: 'web', accountOwner: true }), 'dial-1')
+ await dispatchDown(socket, colleague.seal('dsh_list', { requestId: 'c', owner: true, local: true, accountOwner: true }), 'colleague')
// With the connection and the request id it asked under, which a service keys a connection's own work by.
expect(asked).toEqual([
- { type: 'dsh_list', asker: { local: false, owner: true, connection: 'phone-1', requestId: 'p' } },
- { type: 'dsh_list', asker: { local: false, owner: false, connection: 'dial-1', requestId: 'd' } },
+ { type: 'dsh_list', asker: { local: false, owner: true, accountOwner: true, connection: 'phone-1', requestId: 'p' } },
+ { type: 'dsh_list', asker: { local: false, owner: false, accountOwner: false, connection: 'dial-1', requestId: 'd' } },
+ { type: 'dsh_list', asker: { local: false, owner: true, accountOwner: false, connection: 'colleague', requestId: 'c' } },
])
await socket.stop()
})
diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.ts
index 10aac6fa4..c0275afa3 100644
--- a/cli/src/gateway/gateway.ts
+++ b/cli/src/gateway/gateway.ts
@@ -147,6 +147,7 @@ export class RelayGateway implements GatewayPort {
onIdentityRevoked: identity => { this.deviceUnpaired(identity); this.onDirectDeviceRevoked?.(fingerprint(b64d(identity))) },
onSessionOpened: (connId, role, identity) => this.core.client(connId, {
role, label: this.e2ee.sessionLabel(connId), identity, direct: this.directDeviceSinks.has(connId),
+ accountOwner: role === 'web' && this.e2ee.pairedPeers().some(peer => peer.identityPub === identity && !peer.shared),
}),
onSessionDropped: (connId) => this.core.client(connId, null),
onPeerLinked: (peer) => {
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 6a8c2433f..42a8b4d0e 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -404,6 +404,7 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
// The router (services/routerProcess.ts), an experiment: started at its first request. A few decisions in
// flight, each one bounded Jev answer.
router: { services: ['router'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
+ superTabs: { services: ['superTabs'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
// Cloud agents (services/cloudProcess.ts), an experiment: started once one is on, for a saved harness or a
// request. A timer and a bounded look per working harness, and each conversation read a file at a time.
cloud: { services: ['cloud'], heapLimitMiB: 128, rssLimitMiB: 384, onDemand: true },
diff --git a/cli/src/lib/agentAttribution.spec.ts b/cli/src/lib/agentAttribution.spec.ts
index 0030b2875..925e657f3 100644
--- a/cli/src/lib/agentAttribution.spec.ts
+++ b/cli/src/lib/agentAttribution.spec.ts
@@ -16,12 +16,9 @@ afterEach(() => { rmSync(dataDir, { recursive: true, force: true }); signedOutFo
/** A launch that reads no settings: nothing the person set. */
const place = { cwd: null, read: () => null }
-const claudeLine = ['--settings', JSON.stringify({ attribution: { pr: `🤖 Generated with [Claude Code](https://claude.com/claude-code)\n${AGENT_ATTRIBUTION_LINE}` } })]
const claudeTold = ['--append-system-prompt', HARNESS_INSTRUCTIONS]
/** Codex is told besides that its sandbox cannot reach Harness (engines/codex/launch.ts). */
const CODEX_TOLD = `${HARNESS_INSTRUCTIONS} Codex's sandbox cannot reach Harness: run each harness command outside it, with escalated permissions.`
-/** The pull request line told as an instruction too: a setting alone was dropped once a task spelled out the body. */
-const claudePrTold = expect.stringContaining(`its body must include this exact line once, near the end and after any other attribution line: \`${AGENT_ATTRIBUTION_LINE}\``)
const codexValue = (...texts: string[]) => ['-c', `developer_instructions=${JSON.stringify(texts.join('\n\n'))}`]
describe('what Harness tells an agent as it starts', () => {
@@ -30,21 +27,12 @@ describe('what Harness tells an agent as it starts', () => {
expect(HARNESS_INSTRUCTIONS).toBe('You are running in Harness, and the person can watch you. You can hand work to other agents (Claude Code, Codex) that run in their own harnesses: `harness new`, `harness wait`, `harness show`, `harness close` (see `harness --help`). Start one only for work that can run in parallel, needs another model, or takes long; do quick work yourself, and close each one once you have its answer. Only use or close harnesses you started.')
})
- it('tells every harness how to use Harness, and adds the pull request line only to one another agent started', () => {
- const told = agentLaunchArgs('claude', 'agent', place, dataDir)
- expect(told).toEqual([...claudeLine, '--append-system-prompt', claudePrTold])
- expect(told[3].startsWith(`${HARNESS_INSTRUCTIONS}\n\nWhen you create or update a pull request`)).toBe(true)
- expect(agentLaunchArgs('claude', null, place, dataDir)).toEqual(claudeTold)
- expect(agentLaunchArgs('claude', undefined, place, dataDir)).toEqual(claudeTold)
- // Codex keeps both in one config value: a second -c of the same key would replace the first.
- const instruction = expect.stringContaining(AGENT_ATTRIBUTION_LINE)
- const both = agentLaunchArgs('codex', 'agent', place, dataDir)
- expect(both).toHaveLength(2)
- expect(JSON.parse(both[1].slice('developer_instructions='.length))).toEqual(expect.stringMatching(new RegExp(`^${CODEX_TOLD.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\n\nWhen you create or update a pull request`)))
- expect(both[1]).toEqual(instruction)
- expect(agentLaunchArgs('codex', null, place, dataDir)).toEqual(codexValue(CODEX_TOLD))
- // An engine with no way to be told: nothing.
- expect(agentLaunchArgs('opencode', 'agent', place, dataDir)).toEqual([])
+ it('keeps legacy spawn instructions but never adds retired PR branding', () => {
+ for (const startedBy of ['agent', null, undefined] as const) {
+ expect(agentLaunchArgs('claude', startedBy, place, dataDir)).toEqual(claudeTold)
+ expect(agentLaunchArgs('codex', startedBy, place, dataDir)).toEqual(codexValue(CODEX_TOLD))
+ expect(agentLaunchArgs('opencode', startedBy, place, dataDir)).toEqual([])
+ }
})
it('tells an agent nothing of Harness, and adds no line, for an account that never turned either on, or signed out', () => {
@@ -58,15 +46,12 @@ describe('what Harness tells an agent as it starts', () => {
expect(agentLaunchArgs('claude', 'agent', place, dataDir)).toEqual([])
})
- it('follows the person\'s switches: no instructions once agents may not start agents, no line once that is off', () => {
- setAgentSettingsForTest(dataDir, { agentsStartAgents: false })
- expect(agentLaunchArgs('claude', null, place, dataDir)).toEqual([])
- // The pull request line, and its instruction, without Harness's own instructions.
- expect(agentLaunchArgs('claude', 'agent', place, dataDir)).toEqual([...claudeLine, '--append-system-prompt', claudePrTold])
- expect(agentLaunchArgs('claude', 'agent', place, dataDir)[3].startsWith('When you create or update a pull request')).toBe(true)
- expect(agentLaunchArgs('codex', null, place, dataDir)).toEqual([])
+ it('does not revive PR branding when the saved compatibility flag remains on', () => {
+ setAgentSettingsForTest(dataDir, { agentsStartAgents: false, pullRequestLine: true })
+ expect(agentLaunchArgs('claude', 'agent', place, dataDir)).toEqual([])
+ expect(agentLaunchArgs('codex', 'agent', place, dataDir)).toEqual([])
setAgentSettingsForTest(dataDir, { agentsStartAgents: true, pullRequestLine: false })
- expect(agentLaunchArgs('claude', 'agent', { cwd: '/w', read: () => null }, dataDir)).toEqual(claudeTold)
+ expect(agentLaunchArgs('claude', 'agent', place, dataDir)).toEqual(claudeTold)
setAgentSettingsForTest(dataDir, { agentsStartAgents: false })
expect(agentLaunchArgs('claude', 'agent', { cwd: '/w', read: () => { throw new Error('read nothing') } }, dataDir)).toEqual([])
})
diff --git a/cli/src/lib/agentAttribution.ts b/cli/src/lib/agentAttribution.ts
index dc9c60755..397b68e5e 100644
--- a/cli/src/lib/agentAttribution.ts
+++ b/cli/src/lib/agentAttribution.ts
@@ -1,13 +1,7 @@
-/**
- * A harness another agent started says so in the pull requests it opens: one line beside the engine's own
- * ("🤖 Generated with Claude Code"), so every reader of the pull request, and their agents, sees it was made in
- * Harness (docs/design/2026-10-11-agent-client.md, "Pull requests"). A harness a person started is not marked.
- *
- * Who started a harness is its row's (`startedBy`, sent by `harness new` when an agent runs it); how each engine is
- * told is its launch contract's (`EngineLaunch.attribution`, engines/launches.ts `attributionArgs`). The person turns
- * it on for the account with `harness settings pull-request-line on` or in Settings ▸ Experimental (lib/agentSettings.ts),
- * read at each launch, so a relaunch follows it too.
- */
+/** Legacy agent-spawn instructions remain readable for existing harnesses.
+ * Super Tab supplies its own scoped coordination instructions. New launches
+ * no longer add Harness branding to pull requests, including old accounts
+ * whose saved pullRequestLine compatibility field is still true. */
import { env } from '../config/env.js'
import { agentInstructionArgs, launchContract, type AttributionPlace } from '../engines/launches.js'
import { readAgentSettings } from './agentSettings.js'
@@ -31,16 +25,15 @@ export const HARNESS_INSTRUCTIONS = 'You are running in Harness, and the person
+ 'do quick work yourself, and close each one once you have its answer. Only use or close harnesses you started.'
/**
- * A launch's argv for what Harness tells the agent: the instructions above while agents may start agents, and the pull
- * request line for a harness another agent started while the person has that on. Read at each launch, so a relaunch
- * follows the switches as they are then.
+ * A launch’s argv for legacy agent-spawn instructions, read at each launch.
+ * The retired PR branding preference never changes a new launch.
*/
-export function agentLaunchArgs(engine: string, startedBy: StartedBy | null | undefined, place: AttributionPlace,
+export function agentLaunchArgs(engine: string, _startedBy: StartedBy | null | undefined, place: AttributionPlace,
dataDir: string = env.ADAPTER_DATA_DIR): string[] {
const settings = readAgentSettings(dataDir)
return agentInstructionArgs(engine, {
instructions: settings.agentsStartAgents ? HARNESS_INSTRUCTIONS : null,
- prLine: startedBy === 'agent' && settings.pullRequestLine ? AGENT_ATTRIBUTION_LINE : null,
+ prLine: null,
}, place)
}
diff --git a/cli/src/lib/creationObservation.spec.ts b/cli/src/lib/creationObservation.spec.ts
new file mode 100644
index 000000000..d3d08ebc9
--- /dev/null
+++ b/cli/src/lib/creationObservation.spec.ts
@@ -0,0 +1,18 @@
+import { expect, it } from 'vitest'
+import { creationObservation } from './creationObservation.js'
+
+const id = 'creation-fixture-1234'
+it('projects only an exact known creation receipt without native launch details', () => {
+ for (const state of ['missing', 'pending', 'unconfirmed', 'failed', 'cancelled']) {
+ expect(creationObservation(id, { creationId: id, state, request: { private: 'omitted' } })).toEqual({ creationId: id, state })
+ }
+ expect(creationObservation(id, { creationId: id, state: 'created', agentId: 'native', extra: true })).toEqual({ creationId: id, state: 'created', agentId: 'native' })
+})
+it('keeps unknown, mismatched and malformed replies distinct from a missing launch', () => {
+ expect(creationObservation('short', {})).toBeNull()
+ for (const value of [null, 'missing', {}, { creationId: 'another', state: 'cancelled' },
+ { creationId: id, state: 'future' }, { creationId: id, state: 'created' },
+ { creationId: id, state: 'created', agentId: '../outside' }]) {
+ expect(creationObservation(id, value)).toBeNull()
+ }
+})
diff --git a/cli/src/lib/creationObservation.ts b/cli/src/lib/creationObservation.ts
new file mode 100644
index 000000000..b0d12b352
--- /dev/null
+++ b/cli/src/lib/creationObservation.ts
@@ -0,0 +1,17 @@
+/** A creation receipt projected without its launch request or credentials. */
+export type CreationObservation = {
+ creationId: string
+ state: 'missing' | 'pending' | 'unconfirmed' | 'failed' | 'cancelled'
+} | { creationId: string; state: 'created'; agentId: string }
+
+export function creationObservation(creationId: string, value: unknown): CreationObservation | null {
+ if (!/^[A-Za-z0-9_-]{16,96}$/.test(creationId) || !value || typeof value !== 'object') return null
+ const row = value as Record<string, unknown>
+ if (row.creationId !== creationId) return null
+ if (row.state === 'created') {
+ return typeof row.agentId === 'string' && /^[A-Za-z0-9_-]{1,160}$/.test(row.agentId)
+ ? { creationId, state: 'created', agentId: row.agentId } : null
+ }
+ return ['missing', 'pending', 'unconfirmed', 'failed', 'cancelled'].includes(row.state as string)
+ ? { creationId, state: row.state as Exclude<CreationObservation['state'], 'created'> } : null
+}
diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.ts
index 935ade76f..93c38abf5 100644
--- a/cli/src/lib/e2ee/applicationFrames.ts
+++ b/cli/src/lib/e2ee/applicationFrames.ts
@@ -34,6 +34,7 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt
'os_device',
// Sharing a machine across accounts (services/sharedMachines.ts): the addresses it is shared with.
'shared_machines',
+ 'super_tabs',
// A sign-in a phone caught for a page a harness's program opened (core/terminals/browser.ts): it holds the code.
'browser_callback', ...ROUTE_COMMAND_TYPES])
const MACHINE_RESULTS = new Set([...MACHINE_REQUESTS].map(type => `${type}_result`))
diff --git a/cli/src/lib/engineStop.real.spec.ts b/cli/src/lib/engineStop.real.spec.ts
index c8c9c1226..0234965f9 100644
--- a/cli/src/lib/engineStop.real.spec.ts
+++ b/cli/src/lib/engineStop.real.spec.ts
@@ -177,8 +177,8 @@ real('a stopped engine in a real pane', () => {
const p = await open(shell, engine, f, 'extra' in launch ? launch.extra : {})
const up = await until('the engine to start', () => f.lines().find((line) => line.startsWith('up ')))
const pid = Number(up.split(' ')[1])
- // Codex is given its writer flag, then the arguments as they were.
- if (engine === 'codex') expect(JSON.parse(up.slice(up.indexOf('[')))).toEqual(['--no-daemon'])
+ // Keep the native writer and inline transcript settings through the wrapper.
+ if (engine === 'codex') expect(JSON.parse(up.slice(up.indexOf('[')))).toEqual(['--no-daemon', '-c', 'tui.fullscreen_transcript=false'])
// Ctrl+Z: the whole group stops, the shell continues it, and the engine takes the terminal again.
await p.keys('C-z')
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 4ba1d2945..74f379c6e 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -345,29 +345,18 @@ describe('buildLaunchOverrides — a pane opened as a named agent comes back as
})
})
-describe('buildLaunchOverrides — a harness another agent started keeps its pull request line', () => {
- const pr = (args: string[]) => JSON.parse(args[args.indexOf('--settings') + 1]!).attribution.pr as string
- beforeEach(() => { setAgentSettingsForTest(env.ADAPTER_DATA_DIR, { pullRequestLine: true }) })
-
- it('appends it after everything else, on its own login and on a grid, read from the settings the relaunch reads', async () => {
- const read = vi.fn((path: string) => path === '/workspace/.claude/settings.json' ? '{"attribution":{"pr":"Mine"}}' : null)
- const own = await buildLaunchOverrides(deps({ readAttribution: read }).d, 'claude', { startedBy: 'agent', cwd: '/workspace' }, 'a')
- expect(own.ok).toBe(true)
- if (!own.ok) return
- expect(own.overrides.extraArgs[0]).toBe('--settings')
- expect(pr(own.overrides.extraArgs)).toBe(`Mine\n${AGENT_ATTRIBUTION_LINE}`)
- expect(read).toHaveBeenCalledWith('/workspace/.claude/settings.local.json')
- const grid = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'codex', { startedBy: 'agent', gridLaunch: GRID, cwd: null }, 'a')
- expect(grid.ok).toBe(true)
- if (!grid.ok) return
- expect(grid.overrides.extraArgs.at(-2)).toBe('-c')
- expect(grid.overrides.extraArgs.at(-1)).toMatch(/^developer_instructions=".*Started by another agent in \[Harness\]/)
- })
-
- it('adds nothing for the person\'s harness, or for an engine with no way to say it', async () => {
- const read = vi.fn(() => null)
- expect(await buildLaunchOverrides(deps({ readAttribution: read }).d, 'claude', { startedBy: null, cwd: '/w' }, 'a')).toMatchObject({ ok: true, overrides: { extraArgs: [] } })
- expect(await buildLaunchOverrides(deps({ readAttribution: read }).d, 'opencode', { startedBy: 'agent', cwd: '/w' }, 'a')).toMatchObject({ ok: true, overrides: { extraArgs: [] } })
+describe('buildLaunchOverrides — retired PR branding', () => {
+ it('leaves native attribution alone even when an old account enabled Harness branding', async () => {
+ setAgentSettingsForTest(env.ADAPTER_DATA_DIR, { pullRequestLine: true })
+ const read = vi.fn(() => '{"attribution":{"pr":"Mine"}}')
+ for (const engine of ['claude', 'codex', 'opencode'] as const) {
+ const own = await buildLaunchOverrides(deps({ readAttribution: read }).d, engine, { startedBy: 'agent', cwd: '/workspace' }, 'a')
+ const personal = await buildLaunchOverrides(deps({ readAttribution: read }).d, engine, { startedBy: null, cwd: '/workspace' }, 'a')
+ expect(own).toEqual(personal)
+ expect(JSON.stringify(own)).not.toContain(AGENT_ATTRIBUTION_LINE)
+ const grid = await buildLaunchOverrides(deps({ readAttribution: read }).d, engine, { startedBy: 'agent', gridLaunch: GRID, cwd: null }, 'a')
+ expect(JSON.stringify(grid)).not.toContain(AGENT_ATTRIBUTION_LINE)
+ }
expect(read).not.toHaveBeenCalled()
})
})
@@ -388,7 +377,7 @@ describe('buildLaunchOverrides — every harness is told how to use Harness', ()
if (!codex.ok) return
expect(codex.overrides.extraArgs.filter((arg) => arg.startsWith('developer_instructions='))).toHaveLength(1)
expect(codex.overrides.extraArgs.at(-1)).toContain('You are running in Harness')
- expect(codex.overrides.extraArgs.at(-1)).toContain('Started by another agent in [Harness]')
+ expect(codex.overrides.extraArgs.at(-1)).not.toContain('Started by another agent in [Harness]')
})
})
diff --git a/cli/src/lib/nativeConversation.spec.ts b/cli/src/lib/nativeConversation.spec.ts
index a7745c957..9daa682c5 100644
--- a/cli/src/lib/nativeConversation.spec.ts
+++ b/cli/src/lib/nativeConversation.spec.ts
@@ -148,7 +148,9 @@ it('does not decode a partial body character after a valid header with leading b
})
it('holds path aliases that loop and pools that exceed the candidate budget', async () => {
const loop = join(home, 'rollout-loop.jsonl'); symlinkSync(loop, loop); held = [loop]
- await expect(find()).rejects.toThrow('alias depth limit')
+ // macOS's longer temporary root can exhaust the component budget first;
+ // either explicit bound must hold the identity instead of following the loop.
+ await expect(find()).rejects.toThrow(/alias depth limit|path component limit/)
const own = rollout(); held = Array(65).fill(own)
await expect(find()).rejects.toThrow('descriptor limit')
})
diff --git a/cli/src/lib/nativeTurnObservations.spec.ts b/cli/src/lib/nativeTurnObservations.spec.ts
new file mode 100644
index 000000000..017594303
--- /dev/null
+++ b/cli/src/lib/nativeTurnObservations.spec.ts
@@ -0,0 +1,206 @@
+import { expect, it, vi } from 'vitest'
+import { createNativeTurnObservations, inputContextIn, nativeSubmitKey, nativeTurnBinding, nativeTurnCursorIn, nativeTurnPageIn,
+ NATIVE_TURN_LEASE_MS, NATIVE_TURN_TEXT_LIMIT } from './nativeTurnObservations.js'
+import type { LiveEvent } from '../engines/kit/events.js'
+
+const context = 'fixture-native-context'
+const start = (userMessage = 'Review this change'): LiveEvent => ({ type: 'turn_started', payload: { userMessage } })
+const text = (content = 'The change is ready.'): LiveEvent => ({ type: 'text_delta', payload: { content } })
+const end = (aborted = false): LiveEvent => ({ type: 'turn_ended', payload: aborted ? { aborted: true } : {} })
+function setup() {
+ let time = 0, sequence = 0
+ let binding: { sessionId: string; engine: string; runtime: string } | null = { sessionId: 'session', engine: 'claude', runtime: 'tmux/%1' }
+ const resolve = vi.fn(() => binding)
+ const turns = createNativeTurnObservations({ resolve, now: () => time, id: () => `fixture-observation-${++sequence}` })
+ return { turns, resolve, advance: (ms: number) => { time += ms }, bind: (next: typeof binding) => { binding = next } }
+}
+
+it('records only observed live prompts and answers, with a stable turn identity and no tools or thinking', () => {
+ const f = setup()
+ f.turns.ingest('agent', [start('Private old prompt'), text('Private old answer'), end()])
+ const before = f.turns.read('agent')!
+ expect(before.observations).toEqual([])
+ f.turns.typed('agent', context)
+ f.turns.typed('agent', context, true)
+ f.turns.ingest('agent', [start(), { type: 'thinking_delta', payload: { content: 'private reasoning' } },
+ { type: 'tool_start', payload: { id: 'tool', tool: 'Read', input: 'private file' } }, text(), end()])
+ const page = f.turns.read('agent', before.cursor)!
+ expect(page.gap).toBe(false)
+ expect(page.observations).toEqual([
+ { sequence: 1, turnId: 'fixture-observation-2', kind: 'prompt', text: 'Review this change', inputContext: context, interrupted: false, truncated: false },
+ { sequence: 2, turnId: 'fixture-observation-2', kind: 'answer', text: 'The change is ready.', inputContext: context, interrupted: false, truncated: false },
+ ])
+ expect(f.turns.read('agent', page.cursor)?.observations).toEqual([])
+ page.observations[0].text = 'Mutated by reader'
+ expect(f.turns.read('agent', before.cursor)?.observations[0].text).toBe('Review this change')
+ expect(nativeTurnPageIn(page)).toEqual(page)
+})
+
+it('does not infer identity from a draft, ambiguous input, a previous turn or a programmatic paste', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ f.turns.typed('agent', context)
+ f.turns.ingest('agent', [start('An autonomous turn'), end()])
+ f.turns.typed('agent', 'other-valid-context', true)
+ f.turns.ingest('agent', [start('Mixed draft'), end()])
+ f.turns.typed('agent', context, true)
+ f.turns.submitting('agent')
+ f.turns.typed('agent', context, true)
+ f.turns.ingest('agent', [start('Programmatic paste'), end()])
+ f.turns.ingest('agent', [start('Queued unclaimed input'), end(), start('Second queued unclaimed input'), end()])
+ f.turns.typed('agent', context, true)
+ f.turns.ingest('agent', [start('Native prompt'), end(), start('Another autonomous turn'), end()])
+ expect(f.turns.read('agent', cursor)!.observations.filter(e => e.kind === 'prompt').map(e => e.inputContext))
+ .toEqual([null, null, null, null, null, context, null])
+ f.turns.typed('not-observed', context, true)
+ f.turns.submitting('not-observed')
+})
+
+it('retains several queued native submissions from one context, and withholds ambiguous or excessive queues', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ for (let n = 0; n < 3; n++) f.turns.typed('agent', context, true)
+ for (let n = 0; n < 3; n++) f.turns.ingest('agent', [start(), end()])
+ expect(f.turns.read('agent', cursor)!.observations.map(e => e.inputContext)).toEqual(Array(6).fill(context))
+ const next = f.turns.read('agent')!.cursor
+ f.turns.typed('agent', context, true)
+ f.turns.typed('agent', 'other-native-context', true)
+ f.turns.ingest('agent', [start(), end(), start(), end()])
+ expect(f.turns.read('agent', next)!.observations.every(e => e.inputContext === null)).toBe(true)
+ for (let n = 0; n < 40; n++) f.turns.typed('agent', context, true)
+ f.turns.submitting('agent')
+ const overflow = f.turns.read('agent')!.cursor
+ for (let n = 0; n < 40; n++) f.turns.ingest('agent', [start(), end()])
+ expect(f.turns.read('agent', overflow)!.observations.every(e => e.inputContext === null)).toBe(true)
+})
+
+it('keeps unknown and malformed input context unknown', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ f.turns.typed('agent', 'bad')
+ f.turns.typed('agent', context, true)
+ f.turns.ingest('agent', [start(), end()])
+ expect(f.turns.read('agent', cursor)?.observations[0].inputContext).toBeNull()
+ const page = f.turns.read('agent', cursor)!
+ expect(page.observations.every(event => event.unattributedInput === true)).toBe(true)
+ expect(nativeTurnPageIn(page)).toEqual(page)
+ expect(nativeTurnPageIn({ ...page, observations: [{ ...page.observations[0], unattributedInput: 'yes' }] })).toBeNull()
+ const beforeProgrammatic = f.turns.read('agent')!.cursor
+ f.turns.submitting('agent'); f.turns.ingest('agent', [start(), end()])
+ expect(f.turns.read('agent', beforeProgrammatic)!.observations.every(event => !event.unattributedInput)).toBe(true)
+ expect(inputContextIn({ id: context })).toBeNull()
+})
+
+it('attributes a composed native message at its actual write boundary and withholds overlapping provenance', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ f.turns.submitting('agent', context)
+ f.turns.ingest('agent', [start('Composed message'), text(), end()])
+ expect(f.turns.read('agent', cursor)!.observations.every(event => event.inputContext === context)).toBe(true)
+ const before = f.turns.read('agent')!.cursor
+ f.turns.typed('agent', 'another-native-context', true)
+ f.turns.submitting('agent', context)
+ f.turns.ingest('agent', [start(), end(), start(), end()])
+ expect(f.turns.read('agent', before)!.observations.every(event => event.inputContext === null && event.unattributedInput)).toBe(true)
+})
+
+it('marks unfinished turns interrupted and caps long prompt/answer content without collecting tool output', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ const long = 'x'.repeat(NATIVE_TURN_TEXT_LIMIT + 10)
+ f.turns.ingest('agent', [text('before prompt'), start(long), text(long), text(long), start('Next'), end(true), end()])
+ const events = f.turns.read('agent', cursor)!.observations
+ expect(events).toHaveLength(4)
+ expect(events[0]).toMatchObject({ kind: 'prompt', truncated: true, text: long.slice(0, NATIVE_TURN_TEXT_LIMIT) })
+ expect(events[1]).toMatchObject({ kind: 'answer', truncated: true, interrupted: true, text: long.slice(0, NATIVE_TURN_TEXT_LIMIT) })
+ expect(events[3]).toMatchObject({ kind: 'answer', text: '', interrupted: true })
+})
+
+it('keeps a bounded Unicode prefix and never appends later output after truncation', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ const prefix = 'x'.repeat(NATIVE_TURN_TEXT_LIMIT - 1)
+ f.turns.ingest('agent', [start(`${prefix}🙂`), text(`${prefix}🙂`), text('unrelated later output'), end()])
+ expect(f.turns.read('agent', cursor)!.observations.map(e => e.text)).toEqual([prefix, prefix])
+ const current = f.turns.read('agent')!.cursor
+ f.turns.ingest('agent', [start(), text('x'.repeat(NATIVE_TURN_TEXT_LIMIT)), text('overflow'), end()])
+ expect(f.turns.read('agent', current)!.observations[1]).toMatchObject({ truncated: true, text: 'x'.repeat(NATIVE_TURN_TEXT_LIMIT) })
+})
+
+it('starts a new reader at the current boundary and makes replay/rebinding gaps explicit', () => {
+ const f = setup(), before = f.turns.read('agent')!.cursor
+ f.turns.ingest('agent', [start(), text(), end()])
+ expect(f.turns.read('agent')!.observations).toEqual([])
+ f.turns.ingest('agent', [start('Old replayed prompt'), text('Old answer'), end()], true)
+ const replayed = f.turns.read('agent', before)!
+ expect(replayed).toMatchObject({ observations: [], gap: true })
+ f.bind({ sessionId: 'new-session', engine: 'codex', runtime: 'tmux/%2' })
+ const rebound = f.turns.read('agent', replayed.cursor)!
+ expect(rebound).toMatchObject({ observations: [], gap: true })
+ f.bind(null)
+ expect(f.turns.read('agent', rebound.cursor)).toBeNull()
+ f.turns.typed('agent', context)
+})
+
+it('expires unused leases, retains none of the unobserved interval and detects impossible cursors', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ f.turns.ingest('agent', [start(), end()])
+ f.advance(NATIVE_TURN_LEASE_MS)
+ f.turns.ingest('agent', [start('Unobserved'), end()])
+ const renewed = f.turns.read('agent', cursor)!
+ expect(renewed).toMatchObject({ gap: true, observations: [] })
+ expect(f.turns.read('agent', { ...renewed.cursor, sequence: 1000 })).toMatchObject({ gap: true, observations: [] })
+})
+
+it('bounds global retained text and reports precisely when a reader fell behind', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ for (let n = 0; n < 40; n++) f.turns.ingest('agent', [start('x'.repeat(NATIVE_TURN_TEXT_LIMIT)), text('y'.repeat(NATIVE_TURN_TEXT_LIMIT)), end()])
+ const page = f.turns.read('agent', cursor)!
+ expect(page.gap).toBe(true)
+ expect(page.observations.reduce((size, e) => size + e.text.length, 0)).toBeLessThanOrEqual(1024 * 1024)
+ expect(page.observations[0].sequence).toBeGreaterThan(1)
+ const floor = page.observations[0].sequence - 1
+ expect(f.turns.read('agent', { ...cursor, sequence: floor })?.gap).toBe(false)
+})
+
+it('bounds record counts and active subscriptions without a background timer', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ for (let n = 0; n < 300; n++) f.turns.ingest('agent', [start(''), end()])
+ expect(f.turns.read('agent', cursor)?.observations).toHaveLength(512)
+ for (let n = 1; n < 256; n++) expect(f.turns.read(`agent-${n}`)).not.toBeNull()
+ expect(f.turns.read('one-too-many')).toBeNull()
+ f.advance(NATIVE_TURN_LEASE_MS)
+ expect(f.turns.read('one-too-many')).not.toBeNull()
+})
+
+it('uses real clock and unique epochs by default', () => {
+ const turns = createNativeTurnObservations({ resolve: () => ({ sessionId: 'session', engine: 'claude', runtime: 'tmux/%1' }) })
+ expect(nativeTurnCursorIn(turns.read('agent')?.cursor)).not.toBeNull()
+})
+
+it('binds an observation to the actual native conversation and runtime', () => {
+ expect(nativeTurnBinding(undefined)).toBeNull()
+ expect(nativeTurnBinding({ sessionId: '', engine: 'claude', primaryRuntimeKey: null })).toBeNull()
+ expect(nativeTurnBinding({ sessionId: 'session', engine: 'claude', primaryRuntimeKey: null })).toEqual({ sessionId: 'session', engine: 'claude', runtime: '' })
+ expect(nativeTurnBinding({ sessionId: 'session', engine: 'claude', primaryRuntimeKey: 'tmux/%1' })).toEqual({ sessionId: 'session', engine: 'claude', runtime: 'tmux/%1' })
+})
+
+it.each(['\r', '\n', '\r\n', '\x1b[13u', '\x1b[13;1u'])('recognizes a standalone submit key: %j', key => {
+ expect(nativeSubmitKey(Buffer.from(key))).toBe(true)
+})
+it.each(['', 'draft\r', '\x1b\r', '\x1b[13;2u', '\x1b[I', '\x03', 'a long pasted text\n'])('leaves non-submit or ambiguous input unclaimed: %j', key => {
+ expect(nativeSubmitKey(Buffer.from(key))).toBe(false)
+})
+it('does not strip high bits from a malformed escape sequence', () => {
+ expect(nativeSubmitKey(Uint8Array.from([0x9b, 0x5b, 0x31, 0x33, 0x75]))).toBe(false)
+})
+
+it('rejects malformed page envelopes and cursor values instead of advancing a durable consumer', () => {
+ const f = setup(), cursor = f.turns.read('agent')!.cursor
+ f.turns.ingest('agent', [start(), end()])
+ const page = f.turns.read('agent', cursor)!, first = page.observations[0]
+ for (const bad of [null, 2, {}, { epoch: context, sequence: -1 }, { epoch: 'short', sequence: 0 }]) expect(nativeTurnCursorIn(bad)).toBeNull()
+ for (const bad of [null, 2, {}, { ...page, gap: 'yes' }, { ...page, observations: {} }, { ...page, observations: Array(513).fill(first) }]) {
+ expect(nativeTurnPageIn(bad)).toBeNull()
+ }
+ for (const event of [null, 3, { ...first, sequence: 4 }, { ...first, sequence: 0.5 },
+ { ...first, turnId: '' }, { ...first, kind: 'tool' }, { ...first, text: false },
+ { ...first, text: 'x'.repeat(NATIVE_TURN_TEXT_LIMIT + 1) }, { ...first, truncated: 0 },
+ { ...first, interrupted: 0 }, { ...first, inputContext: '' },
+ ]) expect(nativeTurnPageIn({ ...page, observations: [event] })).toBeNull()
+ expect(nativeTurnPageIn({ ...page, observations: [first, first] })).toBeNull()
+})
diff --git a/cli/src/lib/nativeTurnObservations.ts b/cli/src/lib/nativeTurnObservations.ts
new file mode 100644
index 000000000..36c9a4e54
--- /dev/null
+++ b/cli/src/lib/nativeTurnObservations.ts
@@ -0,0 +1,207 @@
+import { randomUUID } from 'node:crypto'
+import type { LiveEvent } from '../engines/kit/events.js'
+
+export interface NativeTurnCursor { epoch: string; sequence: number }
+export interface NativeTurnObservation {
+ sequence: number
+ turnId: string
+ kind: 'prompt' | 'answer'
+ text: string
+ truncated: boolean
+ interrupted: boolean
+ /** Opaque context supplied by the input client. It proves no identity or
+ * permission; a consumer must validate it against its own authority. */
+ inputContext: string | null
+ /** Accepted terminal input had no unambiguous context. Contains no identity. */
+ unattributedInput?: boolean
+}
+export interface NativeTurnPage {
+ cursor: NativeTurnCursor
+ observations: NativeTurnObservation[]
+ /** The core restarted, the session changed, the lease expired, or bounded
+ * history was evicted. A consumer must not describe that interval as complete. */
+ gap: boolean
+}
+export type NativeTurnRead = (agentId: string, cursor?: NativeTurnCursor) => Promise<NativeTurnPage | null>
+export interface NativeTurnBinding { sessionId: string; engine: string; runtime: string }
+export function nativeTurnBinding(session: { sessionId: string; engine: string; primaryRuntimeKey: string | null } | undefined): NativeTurnBinding | null {
+ return session?.sessionId ? { sessionId: session.sessionId, engine: session.engine, runtime: session.primaryRuntimeKey ?? '' } : null
+}
+interface Turn { id: string; text: string; truncated: boolean; inputContext: string | null; unattributedInput: boolean }
+interface ObservedAgent {
+ binding: string; epoch: string; sequence: number; floor: number; until: number
+ draftContext: string | null | undefined
+ pendingContexts: Array<{ context: string | null; native: boolean }>
+ turn: Turn | null
+ observations: Map<number, NativeTurnObservation>
+}
+export const NATIVE_TURN_TEXT_LIMIT = 16_000
+export const NATIVE_TURN_LEASE_MS = 30_000
+const MAX_AGENTS = 256, MAX_RECORDS = 512, MAX_CHARACTERS = 1024 * 1024
+function clippedText(value: string, limit: number): string {
+ if (value.length <= limit) return value
+ const last = value.charCodeAt(limit - 1)
+ const end = last >= 0xd800 && last <= 0xdbff ? limit - 1 : limit
+ // V8 can retain a giant source string behind a short slice. Copy only the
+ // bounded prefix, without splitting an emoji's surrogate pair.
+ return Buffer.from(value.slice(0, end), 'utf16le').toString('utf16le')
+}
+export const inputContextIn = (value: unknown): string | null =>
+ typeof value === 'string' && /^[A-Za-z0-9_-]{16,160}$/.test(value) ? value : null
+/** The app flushes a submit key separately from text. Meta/Shift+Enter and
+ * multiline pastes are not submissions; ambiguous mixed frames stay unknown. */
+export function nativeSubmitKey(bytes: Uint8Array): boolean {
+ return (bytes.length === 1 && (bytes[0] === 13 || bytes[0] === 10))
+ || (bytes.length === 2 && bytes[0] === 13 && bytes[1] === 10)
+ || (bytes.length <= 7 && ['\x1b[13u', '\x1b[13;1u'].includes(Buffer.from(bytes).toString('latin1')))
+}
+export function nativeTurnCursorIn(value: unknown): NativeTurnCursor | null {
+ if (!value || typeof value !== 'object') return null
+ const cursor = value as Record<string, unknown>
+ return typeof cursor.epoch === 'string' && /^[A-Za-z0-9_-]{16,160}$/.test(cursor.epoch)
+ && Number.isSafeInteger(cursor.sequence) && (cursor.sequence as number) >= 0
+ ? { epoch: cursor.epoch, sequence: cursor.sequence as number } : null
+}
+
+/** A bounded, on-demand view of actual live turns. It contains neither tool
+ * output nor history from before observation began. Consumers own durable
+ * recording; the core never waits for them or writes their feature state. */
+export function createNativeTurnObservations(deps: {
+ resolve(agentId: string): NativeTurnBinding | null
+ now?: () => number
+ id?: () => string
+}) {
+ const now = deps.now ?? Date.now, id = deps.id ?? randomUUID
+ const agents = new Map<string, ObservedAgent>()
+ const held = new Map<string, { row: ObservedAgent; event: NativeTurnObservation }>()
+ let characters = 0
+ const remove = (key: string, row: ObservedAgent, event: NativeTurnObservation) => {
+ held.delete(key); row.observations.delete(event.sequence)
+ row.floor = Math.max(row.floor, event.sequence)
+ characters -= event.text.length
+ }
+ const forget = (agentId: string, row: ObservedAgent) => {
+ for (const event of row.observations.values()) remove(`${row.epoch}:${event.sequence}`, row, event)
+ agents.delete(agentId)
+ }
+ const current = (agentId: string): ObservedAgent | null => {
+ const row = agents.get(agentId)
+ if (!row) return null
+ const binding = deps.resolve(agentId)
+ if (row.until <= now() || !binding || JSON.stringify(binding) !== row.binding) { forget(agentId, row); return null }
+ return row
+ }
+ const append = (row: ObservedAgent, value: Omit<NativeTurnObservation, 'sequence'>) => {
+ const event = { ...value, sequence: ++row.sequence }
+ row.observations.set(event.sequence, event)
+ held.set(`${row.epoch}:${event.sequence}`, { row, event }); characters += event.text.length
+ while (held.size > MAX_RECORDS || characters > MAX_CHARACTERS) {
+ const [key, first] = held.entries().next().value!
+ remove(key, first.row, first.event)
+ }
+ }
+ const finish = (row: ObservedAgent, interrupted: boolean) => {
+ const turn = row.turn
+ if (!turn) return
+ append(row, { turnId: turn.id, kind: 'answer', text: turn.text, truncated: turn.truncated,
+ interrupted, inputContext: turn.inputContext, ...(turn.unattributedInput ? { unattributedInput: true } : {}) })
+ row.turn = null
+ }
+ return {
+ read(agentId: string, cursor?: NativeTurnCursor): NativeTurnPage | null {
+ const binding = deps.resolve(agentId)
+ if (!binding) return null
+ let row = current(agentId)
+ if (!row) {
+ // No timer while nobody observes. Expired leases are swept only when
+ // another reader needs a slot, and an unread agent keeps no content.
+ for (const key of agents.keys()) current(key)
+ if (agents.size >= MAX_AGENTS) return null
+ row = { binding: JSON.stringify(binding), epoch: id(), sequence: 0, floor: 0,
+ until: now() + NATIVE_TURN_LEASE_MS, draftContext: undefined, pendingContexts: [], turn: null, observations: new Map() }
+ agents.set(agentId, row)
+ }
+ row.until = now() + NATIVE_TURN_LEASE_MS
+ const gap = !!cursor && (cursor.epoch !== row.epoch || cursor.sequence < row.floor || cursor.sequence > row.sequence)
+ // A new observer starts at the current boundary; it never imports old
+ // prompts because some other consumer happened to observe this agent.
+ const events = cursor && cursor.epoch === row.epoch && cursor.sequence <= row.sequence
+ ? [...row.observations.values()].filter(event => event.sequence > cursor.sequence) : []
+ return { cursor: { epoch: row.epoch, sequence: row.sequence }, observations: events.map(event => ({ ...event })), gap }
+ },
+ /** Called for accepted human typing, not terminal escape-code replies.
+ * Multiple input contexts before a prompt are explicitly ambiguous. */
+ typed(agentId: string, context: unknown, submitted = false): void {
+ const row = current(agentId)
+ if (!row) return
+ const next = inputContextIn(context)
+ row.draftContext = row.draftContext === undefined || row.draftContext === next ? next : null
+ if (submitted) {
+ // Engines may queue several native prompts. A context change while
+ // submissions are still pending is ambiguous; do not guess which
+ // person or conversation owns a later accepted prompt.
+ if (row.pendingContexts.some(value => value.context !== row.draftContext) || row.pendingContexts.length >= 32) {
+ for (const pending of row.pendingContexts) pending.context = null
+ row.draftContext = null
+ }
+ if (row.pendingContexts.length < 32) row.pendingContexts.push({ context: row.draftContext, native: true })
+ row.draftContext = undefined
+ }
+ },
+ /** A programmatic paste supersedes any unsent native-input provenance. */
+ submitting(agentId: string, inputContext?: string): void {
+ const row = current(agentId)
+ if (row) {
+ const context = inputContextIn(inputContext), ambiguous = row.pendingContexts.length > 0
+ row.draftContext = undefined
+ for (const pending of row.pendingContexts) pending.context = null
+ if (row.pendingContexts.length < 32) row.pendingContexts.push({ context: ambiguous ? null : context, native: context !== null })
+ }
+ },
+ ingest(agentId: string, events: readonly LiveEvent[], replay = false): void {
+ const row = current(agentId)
+ if (!row) return
+ if (replay) { forget(agentId, row); return }
+ for (const event of events) {
+ if (event.type === 'turn_started') {
+ finish(row, true)
+ const turnId = id(), pending = row.pendingContexts.shift(), inputContext = pending?.context ?? null
+ const unattributedInput = pending?.native === true && inputContext === null
+ row.turn = { id: turnId, text: '', truncated: false, inputContext, unattributedInput }
+ append(row, { turnId, kind: 'prompt', text: clippedText(event.payload.userMessage, NATIVE_TURN_TEXT_LIMIT),
+ truncated: event.payload.userMessage.length > NATIVE_TURN_TEXT_LIMIT, interrupted: false, inputContext,
+ ...(unattributedInput ? { unattributedInput: true } : {}) })
+ } else if (event.type === 'text_delta' && row.turn && !row.turn.truncated) {
+ const room = NATIVE_TURN_TEXT_LIMIT - row.turn.text.length
+ row.turn.text += clippedText(event.payload.content, room)
+ row.turn.truncated ||= event.payload.content.length > room
+ } else if (event.type === 'turn_ended') finish(row, event.payload.aborted === true)
+ }
+ },
+ }
+}
+
+/** Strict process boundary: malformed/older-core replies are unavailable,
+ * never an empty page that advances a consumer's durable cursor. */
+export function nativeTurnPageIn(value: unknown): NativeTurnPage | null {
+ if (!value || typeof value !== 'object') return null
+ const row = value as Record<string, unknown>, cursor = nativeTurnCursorIn(row.cursor)
+ if (!cursor || typeof row.gap !== 'boolean' || !Array.isArray(row.observations) || row.observations.length > MAX_RECORDS) return null
+ let previous = 0
+ const observations: NativeTurnObservation[] = []
+ for (const value of row.observations) {
+ if (!value || typeof value !== 'object') return null
+ const event = value as Record<string, unknown>
+ if (!Number.isSafeInteger(event.sequence) || (event.sequence as number) <= previous || (event.sequence as number) > cursor.sequence
+ || !inputContextIn(event.turnId) || !['prompt', 'answer'].includes(String(event.kind))
+ || typeof event.text !== 'string' || event.text.length > NATIVE_TURN_TEXT_LIMIT
+ || typeof event.truncated !== 'boolean' || typeof event.interrupted !== 'boolean'
+ || (event.unattributedInput !== undefined && typeof event.unattributedInput !== 'boolean')
+ || (event.inputContext !== null && !inputContextIn(event.inputContext))) return null
+ previous = event.sequence as number
+ observations.push({ sequence: previous, turnId: event.turnId as string, kind: event.kind as 'prompt' | 'answer',
+ text: event.text, truncated: event.truncated, interrupted: event.interrupted, inputContext: event.inputContext as string | null,
+ ...(event.unattributedInput === true ? { unattributedInput: true } : {}) })
+ }
+ return { cursor, observations, gap: row.gap }
+}
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index a4de43935..e9fff26ac 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -34,6 +34,25 @@ const codexComposer = (draft: string, footer = ' ? for shortcuts') => `\n\u001b
describe('SessionInputController', () => {
afterEach(() => vi.useRealTimers())
+ it('retains each composed message context while waiting for the pane lock and the preceding turn', async () => {
+ vi.useFakeTimers()
+ const inject = vi.fn(async () => true)
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
+ getSession: () => session(), validateRuntime: async () => true, inject, sendKey: async () => true,
+ capture: async () => codexComposer(''), onError: vi.fn() })
+ const release = controller.acquireControl('s1')!
+ controller.submit('s1', 'first', undefined, 'first-native-context')
+ controller.submit('s1', 'second', undefined, 'second-native-context')
+ expect(inject).not.toHaveBeenCalled()
+ release()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(inject).toHaveBeenNthCalledWith(1, 'h1', 'first', 'first-native-context')
+ controller.onTurnStarted('s1', 'first'); controller.onTurnEnded('s1')
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(inject).toHaveBeenNthCalledWith(2, 'h1', 'second', 'second-native-context')
+ controller.forget('s1')
+ })
+
describe('a message not typed because of what its pane shows', () => {
const held = (reason: string): TerminalActionResult => ({ state: 'failed', dispatch: 'not_started', reason })
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index 7a24a3053..9c1d81d7b 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -73,6 +73,7 @@ export interface SessionInputDelivery {
interface QueuedInput {
deliveryId?: string
+ inputContext?: string
content: string
bytes: number
expiresAt: number
@@ -111,7 +112,7 @@ export interface SessionInputDeps {
getSession: (sessionId: string) => RegisteredSession | undefined
validateRuntime: (session: RegisteredSession) => Promise<boolean>
/** Boolean is retained for direct controller tests and legacy embedders. Production returns dispatch evidence. */
- inject: (terminalTarget: string, content: string) => Promise<boolean | TerminalActionResult>
+ inject: (terminalTarget: string, content: string, inputContext?: string) => Promise<boolean | TerminalActionResult>
/** Host serializes the preflight and paste with other terminal writers. */
injectTeam?: (terminalTarget: string, content: string, deliveryId: string) => Promise<boolean | TerminalActionResult>
sendKey: (terminalTarget: string, key: string) => Promise<boolean | TerminalActionResult>
@@ -257,7 +258,7 @@ export class SessionInputController {
return false
}
- submit(sessionId: string, content: string, deliveryId?: string): void {
+ submit(sessionId: string, content: string, deliveryId?: string, inputContext?: string): void {
const session = this.controlSession(sessionId)
if (!session) {
this.delivery(sessionId, deliveryId, 'rejected', 'agent_gone')
@@ -270,7 +271,7 @@ export class SessionInputController {
|| (deliveryId && (state.deliveryId || state.dispatching || state.turnOpen || state.awaitingFingerprint || state.settling))
|| (!this.typesWhileBusy(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {
console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)
- this.enqueue(sessionId, state, content, deliveryId)
+ this.enqueue(sessionId, state, content, deliveryId, inputContext)
return
}
this.delivery(sessionId, deliveryId, 'queued')
@@ -282,7 +283,7 @@ export class SessionInputController {
// agent as it is by then, which a restart in between may have changed.
// With nothing in flight the write starts at once, so a cancel or a control request that follows
// the submit sees it, as before.
- const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId)
+ const write = (): Promise<void> => this.inject(sessionId, this.controlSession(sessionId) ?? session, content, deliveryId, inputContext)
const running = state.writes ? state.writes.then(write, write) : write()
const settled: Promise<void> = running.catch(() => {}).then(() => { if (state.writes === settled) state.writes = undefined })
state.writes = settled
@@ -474,7 +475,7 @@ export class SessionInputController {
}
/** Preserve the established injection path for every caller that opts out of receipts. */
- private async injectLegacy(sessionId: string, session: RegisteredSession, content: string): Promise<void> {
+ private async injectLegacy(sessionId: string, session: RegisteredSession, content: string, inputContext?: string): Promise<void> {
const state = this.state(sessionId)
if (!(await this.deps.validateRuntime(session))) {
console.warn(`[inject] ${sid(sessionId)} abort · engine=${session.engine} · process not running`)
@@ -498,7 +499,7 @@ export class SessionInputController {
// would corrupt it into a run-on prompt anyway, which is worse and harder to notice.
await this.deps.sendKey(session.agentId, 'C-u')
}
- const delivery = await this.injectWhenLeased(() => this.deps.inject(session.agentId, content),
+ const delivery = await this.injectWhenLeased(() => this.write(session.agentId, content, inputContext),
() => this.controlSession(session.agentId) !== undefined)
const accepted = typeof delivery === 'boolean'
? delivery
@@ -531,13 +532,17 @@ export class SessionInputController {
this.armSubmitCheck(sessionId, session, state)
}
- private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string): Promise<void> {
+ private write(id: string, content: string, inputContext?: string) {
+ return inputContext ? this.deps.inject(id, content, inputContext) : this.deps.inject(id, content)
+ }
+
+ private async inject(sessionId: string, session: RegisteredSession, content: string, deliveryId?: string, inputContext?: string): Promise<void> {
const state = this.state(sessionId)
if (!deliveryId) {
// A local submission keeps its original scheduling. Overlap removes our ability
// to attribute a later terminal turn to the lamp; it must not block local input.
this.finishDelivery(sessionId, state, 'unknown', 'prompt_mismatch')
- return this.injectLegacy(sessionId, session, content)
+ return this.injectLegacy(sessionId, session, content, inputContext)
}
state.deliveryId = deliveryId
state.deliveryFingerprint = undefined
@@ -576,7 +581,7 @@ export class SessionInputController {
if (state.cancelled || this.states.get(sessionId) !== state) return
state.writing = true
const delivery = await this.injectWhenLeased(() => (deliveryId.startsWith('team:') && this.deps.injectTeam
- ? this.deps.injectTeam(session.agentId, content, deliveryId) : this.deps.inject(session.agentId, content)),
+ ? this.deps.injectTeam(session.agentId, content, deliveryId) : this.write(session.agentId, content, inputContext)),
() => !state.cancelled && this.states.get(sessionId) === state)
state.writing = false
if (state.cancelled || this.states.get(sessionId) !== state) return
@@ -869,10 +874,10 @@ export class SessionInputController {
if (!next.deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This harness is no longer available.')
return
}
- void this.inject(sessionId, session, next.content, next.deliveryId)
+ void this.inject(sessionId, session, next.content, next.deliveryId, next.inputContext)
}
- private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string): void {
+ private enqueue(sessionId: string, state: InputState, content: string, deliveryId?: string, inputContext?: string): void {
const bytes = Buffer.byteLength(content, 'utf8')
const queuedBytes = state.queue.reduce((sum, item) => sum + item.bytes, 0)
if (state.queue.length >= MAX_QUEUE_ITEMS || queuedBytes + bytes > MAX_QUEUE_BYTES) {
@@ -880,7 +885,7 @@ export class SessionInputController {
if (!deliveryId?.startsWith('team:')) this.deps.onError(sessionId, 'This agent already has too many queued messages. Try again after the current operation finishes.')
return
}
- state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId })
+ state.queue.push({ content, bytes, expiresAt: Date.now() + ITEM_TTL_MS, deliveryId, inputContext })
this.delivery(sessionId, deliveryId, 'queued')
}
diff --git a/cli/src/lib/terminalClose.real.spec.ts b/cli/src/lib/terminalClose.real.spec.ts
index f2b5d53b2..fe9c2f6d8 100644
--- a/cli/src/lib/terminalClose.real.spec.ts
+++ b/cli/src/lib/terminalClose.real.spec.ts
@@ -56,9 +56,9 @@ it.runIf(process.env.RUN_REAL_TMUX_DISCOVERY === '1')('saves and closes an inact
}
const actualKill = backend.kill.bind(backend)
const kill = vi.spyOn(backend, 'kill')
- kill.mockImplementation(async runtime => {
+ kill.mockImplementation(async (runtime, allowed) => {
await savedScreen() // The backup must exist before the pane is killed.
- return actualKill(runtime)
+ return actualKill(runtime, allowed)
})
const stop = createStopAgentService({ registry, stoppedAgents,
restartJobs: new AgentRestartCoordinator(), stopJobs: new Map(), tmuxBackend: backend,
@@ -76,7 +76,7 @@ it.runIf(process.env.RUN_REAL_TMUX_DISCOVERY === '1')('saves and closes an inact
expect(await close.request({ ...request, mode: 'idle' })).toMatchObject({ error: 'SESSION_NOT_IDLE' })
expect(kill).not.toHaveBeenCalled()
expect(await close.request({ ...request, mode: 'now' })).toEqual({ closed: true })
- expect(kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: pane })
+ expect(kill).toHaveBeenCalledExactlyOnceWith({ backend: 'tmux', paneId: pane }, expect.any(Function))
expect(registry.byAgent(row.agentId)).toBeUndefined()
await savedScreen()
expect(await server.run('list-panes', '-t', 'terminal-close', '-F', '#{pane_id}')).toBe(neighbor)
diff --git a/cli/src/lib/terminalStreamManager.spec.ts b/cli/src/lib/terminalStreamManager.spec.ts
index 739fd8e16..867d4a39a 100644
--- a/cli/src/lib/terminalStreamManager.spec.ts
+++ b/cli/src/lib/terminalStreamManager.spec.ts
@@ -341,6 +341,31 @@ describe('TerminalStreamManager', () => {
expect(stream.sizes.at(-1)).toEqual({ cols: 140, rows: 50 })
})
+ it('carries an opaque native input context without letting it grant terminal control', async () => {
+ const onInput = vi.fn(), inputContext = 'fixture-native-input-context'
+ manager = newManager({ onInput })
+ await manager.handleFrame('web-1', 'terminal_open', {
+ requestId: 'context', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24, inputContext,
+ })
+ const streamId = sent.find(frame => frame.type === 'terminal_ready' && frame.connId === 'web-1')!.payload.streamId as string
+ await manager.handleFrame('web-2', 'terminal_open', {
+ requestId: 'watch-context', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24, watch: true, inputContext,
+ })
+ const watchId = sent.find(frame => frame.type === 'terminal_ready' && frame.connId === 'web-2')!.payload.streamId as string
+ await manager.handleBinary('web-2', { kind: TerminalBinaryKind.input, streamId: watchId, seq: 0, compressed: false, bytes: Buffer.from('\r') })
+ expect(onInput).not.toHaveBeenCalled()
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.input, streamId, seq: 0, compressed: false, bytes: Buffer.from('hello') })
+ expect(onInput).toHaveBeenLastCalledWith('agent-1', true, { connId: 'web-1', kind: null, inputContext })
+ await manager.handleBinary('web-1', { kind: TerminalBinaryKind.input, streamId, seq: 1, compressed: false, bytes: Buffer.from('\r') })
+ expect(onInput).toHaveBeenLastCalledWith('agent-1', true, { connId: 'web-1', kind: null, inputContext, submitted: true })
+ await manager.handleFrame('web-3', 'terminal_open', {
+ requestId: 'invalid-context', protocolVersion: 3, agentId: 'agent-1', cols: 80, rows: 24, inputContext: { userId: 'do-not-trust' },
+ })
+ const other = sent.find(frame => frame.type === 'terminal_ready' && frame.connId === 'web-3')!.payload.streamId as string
+ await manager.handleBinary('web-3', { kind: TerminalBinaryKind.input, streamId: other, seq: 0, compressed: false, bytes: Buffer.from('hello') })
+ expect(onInput).toHaveBeenLastCalledWith('agent-1', true, { connId: 'web-3', kind: null })
+ })
+
it.each([[1, 1], [30, 30], [80, 8], [300, 120]])(
'opens and resizes a terminal at its actual %i×%i pane size', async (cols, rows) => {
const open = vi.spyOn(terminals, 'openStream')
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index 924fd8091..888957404 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto'
import { typedByPerson } from './typedInput.js'
+import { inputContextIn, nativeSubmitKey } from './nativeTurnObservations.js'
import { unlink } from 'node:fs/promises'
import { deflateSync } from 'node:zlib'
import { ENGINES } from '../engines/types.js'
@@ -114,6 +115,8 @@ interface ActiveStream {
ownerId: string
/** What the client declared on open, or what `describeClient` could tell; absent when neither knew. */
client?: TerminalClientDescriptor
+ /** Opaque input provenance only. It does not affect the control lease. */
+ inputContext?: string
streamId: string
/** A stream opened as a WATCHER: it renders, but it never took the control lease and its input is
* refused. See the `takeover: false` branch of `open()`. */
@@ -191,7 +194,7 @@ export interface TerminalStreamManagerDeps {
* `from`: the stream's connection and what its client said it is on `terminal_open`, so a page a program in the
* pane opens can go to the phone the person is typing on (core/terminals/browser.ts).
*/
- onInput?: (agentId: string, typed: boolean, from: { connId: string, kind: string | null }) => void
+ onInput?: (agentId: string, typed: boolean, from: { connId: string, kind: string | null; inputContext?: string; submitted?: boolean }) => void
}
function sizeFrom(payload: FramePayload): TerminalStreamSize | null {
@@ -561,6 +564,7 @@ export class TerminalStreamManager {
connId,
ownerId,
...(client ? { client } : {}),
+ ...(inputContextIn(payload.inputContext) ? { inputContext: payload.inputContext as string } : {}),
streamId,
watching,
watchOnly: watching && watchOnly,
@@ -690,7 +694,7 @@ export class TerminalStreamManager {
}
state.lastInputSeq = inputSeq
state.expiresAt = this.now() + HEARTBEAT_TIMEOUT_MS
- this.tookInput(state, typedByPerson(bytes))
+ this.tookInput(state, typedByPerson(bytes), nativeSubmitKey(bytes))
// Not awaited. `writeRaw` hands its `send-keys` to the control client's FIFO synchronously, so
// keystroke order is already fixed by the time it returns its promise — and the seq above is
// spent, so the next frame cannot race this one. Awaiting the reply held the whole local
@@ -718,8 +722,9 @@ export class TerminalStreamManager {
}
/** See `TerminalStreamManagerDeps.onInput`. A listener's failure is its own: input is never held by it. */
- private tookInput(state: ActiveStream, typed: boolean): void {
- try { this.deps.onInput?.(state.agentId, typed, { connId: state.connId, kind: state.client?.kind ?? null }) } catch (error) {
+ private tookInput(state: ActiveStream, typed: boolean, submitted = false): void {
+ try { this.deps.onInput?.(state.agentId, typed, { connId: state.connId, kind: state.client?.kind ?? null,
+ ...(state.inputContext ? { inputContext: state.inputContext } : {}), ...(submitted ? { submitted: true } : {}) }) } catch (error) {
this.diagnostic(state, 'input_listener_failed', { reason: error instanceof Error ? error.message : String(error) })
}
}
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index 27b292d88..29a5fcc39 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -52,6 +52,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M
['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],
['memory', async () => (await import('./services/memoryProcess.js')).runMemoryService],
['router', async () => (await import('./services/routerProcess.js')).runRouterService],
+ ['superTabs', async () => (await import('./services/superTabsProcess.js')).runSuperTabsService],
['cloud', async () => (await import('./services/cloudProcess.js')).runCloudService],
// Not a service the core knows: the master runs it beside them (harnessd/services.ts `UPDATER_HOST`).
['updater', async () => (await import('./services/updaterProcess.js')).runUpdaterService],
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index c0c402aa9..1982b9913 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -28,6 +28,7 @@ import { startShell } from './shell.js'
import { startSharedMachines } from './sharedMachines.js'
import { startSharing } from './sharing.js'
import { startStoreInCore } from './store.js'
+import { startSuperTabs } from './superTabs.js'
import { startUsageInCore } from './usage.js'
import { startViewers } from './viewers.js'
import { startWifi } from './wifi.js'
@@ -36,6 +37,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startSuperTabs, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 8756d465c..12777e351 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -36,6 +36,7 @@ export { startOsDevice } from './osDevice.js'
export { startProjects } from './projects.js'
export { startRecaps } from './recaps.js'
export { startRouter } from './router.js'
+export { startSuperTabs } from './superTabs.js'
export { startSearch } from './search.js'
export { startShell } from './shell.js'
export { startSharing } from './sharing.js'
diff --git a/cli/src/services/process.spec.ts b/cli/src/services/process.spec.ts
index b1fcdabc3..07612e5fb 100644
--- a/cli/src/services/process.spec.ts
+++ b/cli/src/services/process.spec.ts
@@ -212,10 +212,15 @@ describe('a service in its own process', () => {
// The connection and the client's own request id, when the core gave them: what a grid command is a job of.
socket().say({ type: 'session_search', payload: { requestId: 'r4' }, asker: { local: true, owner: true, connection: 'local:1', requestId: 'cmd-1' } })
socket().say({ type: 'session_search', payload: { requestId: 'r5' }, asker: { local: true, owner: true, connection: 7, requestId: null } })
- await vi.waitFor(() => expect(asked).toHaveLength(5))
+ socket().say({ type: 'session_search', payload: { requestId: 'r6', accountOwner: true }, asker: { local: false, owner: true, accountOwner: false } })
+ socket().say({ type: 'session_search', payload: { requestId: 'r7' }, asker: { local: false, owner: true, accountOwner: true } })
+ socket().say({ type: 'session_search', payload: { requestId: 'r8', accountOwner: true }, asker: { local: false, owner: true, accountOwner: 'yes' } })
+ await vi.waitFor(() => expect(asked).toHaveLength(8))
expect(asked).toEqual([
{ local: true, owner: true }, { local: false, owner: false }, { local: false, owner: false },
{ local: true, owner: true, connection: 'local:1', requestId: 'cmd-1' }, { local: true, owner: true },
+ { local: false, owner: true, accountOwner: false }, { local: false, owner: true, accountOwner: true },
+ { local: false, owner: true },
])
})
diff --git a/cli/src/services/process.ts b/cli/src/services/process.ts
index 9dc2855d5..b12557c7d 100644
--- a/cli/src/services/process.ts
+++ b/cli/src/services/process.ts
@@ -228,7 +228,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
catch (error) { log(`[service ${options.name}] binary frame failed · ${describe(error)}`) }
return
}
- let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; connection?: unknown; requestId?: unknown } }
+ let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; accountOwner?: unknown; connection?: unknown; requestId?: unknown } }
try { frame = JSON.parse(raw.toString()) as typeof frame } catch { return }
const payload = frame.payload ?? {}
if (frame.type === 'connected') {
@@ -270,6 +270,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces
const asker: Asker = {
local: frame.asker?.local === true,
owner: frame.asker?.owner === true,
+ ...(typeof frame.asker?.accountOwner === 'boolean' ? { accountOwner: frame.asker.accountOwner } : {}),
...(typeof frame.asker?.connection === 'string' ? { connection: frame.asker.connection } : {}),
...(typeof frame.asker?.requestId === 'string' ? { requestId: frame.asker.requestId } : {}),
}
diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.ts
index 4cb144fa7..fa5cb2583 100644
--- a/cli/src/services/processCoreApi.spec.ts
+++ b/cli/src/services/processCoreApi.spec.ts
@@ -3,11 +3,59 @@ import { TAB_KEY_OFF, TAB_RELAY_OFF } from '../core/api.js'
import type { RegisteredSession } from '../lib/registry.js'
import { agentsIn, daemonIn, isSession, processCoreApi, UNASKED, type ShownAgent } from './processCoreApi.js'
import { turnsLink } from './turnsLink.js'
+
+it('grants typed deliveries only in its connected service namespace and refuses a missing or failed core', async () => {
+ const ask = vi.fn(async () => ({ leased: true }))
+ const api = processCoreApi('/data', 'worker', { ask })
+ expect(await api.turns.leaseDeliveries('other', {})).toBe(false)
+ expect(ask).not.toHaveBeenCalled()
+ expect(await api.turns.leaseDeliveries('worker', { delivery: 100 })).toBe(true)
+ expect(ask).toHaveBeenCalledWith('lease_deliveries', { leases: { delivery: 100 } })
+ ask.mockRejectedValueOnce(new Error('Disconnected'))
+ expect(await api.turns.leaseDeliveries('worker', {})).toBe(false)
+ expect(await processCoreApi('/data', 'worker').turns.leaseDeliveries('worker', {})).toBe(false)
+})
import { usageTarget } from '../lib/agentUsageWire.js'
const agent = (agentId: string, over: Partial<RegisteredSession> = {}) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, ...over }) as RegisteredSession
describe('the core API a light service runs on in its own process', () => {
+ it('validates native observation pages and never advances a cursor on an unavailable core', async () => {
+ const cursor = { epoch: 'fixture-observation-epoch', sequence: 0 }, page = { cursor, observations: [], gap: false }
+ const ask = vi.fn(async (): Promise<Record<string, unknown>> => ({ page }))
+ const api = processCoreApi('/data', 'worker', { ask })
+ expect(await api.transcripts.nativeTurns!('native')).toEqual(page)
+ expect(ask).toHaveBeenLastCalledWith('native_turns', { agentId: 'native' })
+ expect(await api.transcripts.nativeTurns!('native', cursor)).toEqual(page)
+ expect(ask).toHaveBeenLastCalledWith('native_turns', { agentId: 'native', cursor })
+ ask.mockResolvedValueOnce({ page: { ...page, observations: [{}] } })
+ expect(await api.transcripts.nativeTurns!('native', cursor)).toBeNull()
+ ask.mockRejectedValueOnce(new Error('Disconnected'))
+ expect(await api.transcripts.nativeTurns!('native', cursor)).toBeNull()
+ expect(await processCoreApi('/data', 'worker').transcripts.nativeTurns!('native')).toBeNull()
+ })
+ it('accepts only the requested native creation receipt from the core', async () => {
+ const id = 'creation-fixture-1234', observation = { creationId: id, state: 'cancelled' }
+ const ask = vi.fn(async (): Promise<Record<string, unknown>> => ({ observation }))
+ const api = processCoreApi('/data', 'worker', { ask })
+ expect(await api.agents.creationStatus!(id)).toEqual(observation)
+ expect(ask).toHaveBeenCalledWith('creation_status', { creationId: id })
+ ask.mockResolvedValueOnce({ observation: { ...observation, creationId: 'other' } })
+ expect(await api.agents.creationStatus!(id)).toBeNull()
+ ask.mockResolvedValueOnce({})
+ expect(await api.agents.creationStatus!(id)).toBeNull()
+ ask.mockRejectedValueOnce(new Error('Core unavailable'))
+ expect(await api.agents.creationStatus!(id)).toBeNull()
+ expect(await processCoreApi('/data', 'worker').agents.creationStatus!(id)).toBeNull()
+ })
+ it('retains the observed runtime profile and treats absent or malformed older projections as unknown', () => {
+ const api = processCoreApi('/data', 'worker')
+ const selectedModel = 'runtime-v1:a1:claude:opus@high'
+ expect(api.agents.runtimeProfile({ ...agent('a1'), selectedModel } as ShownAgent)).toBe(selectedModel)
+ for (const value of [undefined, null, 42, {}]) {
+ expect(api.agents.runtimeProfile({ ...agent('a1'), selectedModel: value } as ShownAgent)).toBeNull()
+ }
+ })
it('reads only an exact validated usage snapshot, without reading a transcript', async () => {
const target = usageTarget(agent('a', { transcriptPath: '/fixture/session', registeredAt: 1 }))
expect(await processCoreApi('/data', 'projects').usage!(target)).toBeNull()
@@ -261,3 +309,15 @@ describe('the core API a light service runs on in its own process', () => {
expect(isSession({ sessionId: 's' })).toBe(false)
})
})
+
+it('asks for native stop evidence and treats an absent or failed link as unknown', async () => {
+ const ask = vi.fn(async (): Promise<Record<string, unknown>> => ({ stopped: true }))
+ const api = processCoreApi('/data', 'superTabs', { ask })
+ expect(await api.agents.stopped!('a')).toBe(true)
+ expect(ask).toHaveBeenLastCalledWith('stopped', { agentId: 'a' })
+ ask.mockResolvedValueOnce({ stopped: false })
+ expect(await api.agents.stopped!('a')).toBe(false)
+ ask.mockRejectedValueOnce(new Error('offline'))
+ expect(await api.agents.stopped!('a')).toBe(false)
+ expect(await processCoreApi('/data', 'superTabs').agents.stopped!('a')).toBe(false)
+})
diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.ts
index 582dbd6f1..1b56a4ed0 100644
--- a/cli/src/services/processCoreApi.ts
+++ b/cli/src/services/processCoreApi.ts
@@ -18,11 +18,13 @@ import { CONNECTOR_VAULT_OFF, CONVERSATIONS_OFF, DAEMON_UNKNOWN, DELIVERIES_OFF,
import type { AgentDshContext } from '../lib/agentFrame.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { turnsLink } from './turnsLink.js'
+import { creationObservation } from '../lib/creationObservation.js'
+import { nativeTurnPageIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
/** An agent as the core shows it to an experiment (core/experimentQueries.ts `shown`). */
-export type ShownAgent = RegisteredSession & { displayName?: string; terminalAvailable?: boolean; dshContext?: AgentDshContext | null }
+export type ShownAgent = RegisteredSession & { displayName?: string; terminalAvailable?: boolean; selectedModel?: string | null; dshContext?: AgentDshContext | null }
/** The agents a process was last told of, and how it asks the core to act. Those it is never told of read
* as none, and with no way to ask, it acts on nothing. */
@@ -111,12 +113,18 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
live,
displayName: (session) => (session as ShownAgent).displayName ?? '',
byAgent: (agentId) => live().find((session) => session.agentId === agentId),
+ stopped: async agentId => (await ask?.('stopped', { agentId }).catch(() => null))?.stopped === true,
+ creationStatus: async creationId => creationObservation(creationId,
+ (await ask?.('creation_status', { creationId }).catch(() => null))?.observation),
resolve: (id) => resolveAgent(live(), id),
advertised: () => view.advertised?.() ?? [],
terminalAvailable: (agentId) => live().find((session) => session.agentId === agentId)?.terminalAvailable === true,
sync: () => {},
runtimeModels: async () => [],
- runtimeProfile: () => null,
+ runtimeProfile: session => {
+ const profile = (session as ShownAgent).selectedModel
+ return typeof profile === 'string' ? profile : null
+ },
setRuntime: () => {},
fork: async () => ({ ok: false, error: 'UNSUPPORTED' }),
create: async (request) => {
@@ -148,9 +156,16 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVie
recent: async () => [],
asks: async () => [],
...(view.deliveries?.turns ?? DELIVERIES_OFF),
+ // The connected service identity decides the namespace; the payload cannot
+ // grant another process permission to write a queued instruction.
+ leaseDeliveries: async (maker, leases) => maker === service &&
+ (await ask?.('lease_deliveries', { leases }).catch(() => null))?.leased === true,
},
questions: { answer: () => {}, answerReviewed: async () => false },
- transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn },
+ transcripts: { databaseHistory: () => undefined, lastTurn: UNASKED.lastTurn,
+ nativeTurns: async (agentId, cursor) => nativeTurnPageIn(
+ (await ask?.('native_turns', { agentId, ...(cursor ? { cursor } : {}) }).catch(() => null))?.page),
+ },
account: {
mintGridName: async () => null,
diff --git a/cli/src/services/sharing.ts b/cli/src/services/sharing.ts
index 0e7596aff..d90452b5c 100644
--- a/cli/src/services/sharing.ts
+++ b/cli/src/services/sharing.ts
@@ -17,6 +17,7 @@
* wants are derived from (sharing/rosterGrants.ts): the messages process is that file's only writer.
* The observers' frames reach it through its port, as the relay hands them over.
*/
+import { observerSource } from '../superTabs/observers.js'
import { join } from 'node:path'
import type { CoreApi, CorePorts, ServiceRequests, TerminalWatch } from '../core/api.js'
import { SHARE_REQUESTS } from '../core/api.js'
@@ -58,7 +59,10 @@ export const viewerPage = (core: Pick<CoreApi, 'agents'>) => (agentId: string):
export function startSharing(core: CoreApi, ports: CorePorts, options: SharingOptions = {}): ServiceRequests {
const viewers = options.viewers ?? new SharedViewerPool(viewerPage(core))
+ const superTabs = observerSource(core.dataDir, () => core.daemon.machineId())
const owner = new HarnessShareOwner({
+ derivedGrants: superTabs.current,
+ allowsGrant: superTabs.allows,
machineId: () => core.daemon.machineId(),
key: {
publicKey: async () => b64d(await core.account.observerKey.publicKey()),
diff --git a/cli/src/services/superTabs.spec.ts b/cli/src/services/superTabs.spec.ts
new file mode 100644
index 000000000..33e495277
--- /dev/null
+++ b/cli/src/services/superTabs.spec.ts
@@ -0,0 +1,14 @@
+import { expect, it, vi } from 'vitest'
+import { emptyPorts } from '../core/api.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { startSuperTabs } from './superTabs.js'
+
+it('installs the same Super Tab handlers and stoppable lifetime in inline mode', async () => {
+ const core = fakeCore(), ports = emptyPorts()
+ const host = { machineId: 'machine-1', start: vi.fn(), stop: vi.fn() }
+ const requests = startSuperTabs(core, ports, { host: () => host as never })
+ expect(await requests.super_tabs({ action: 'wake' }, { owner: true, local: true })).toEqual({ ok: true })
+ expect(host.start).toHaveBeenCalledOnce()
+ ports.superTabs!.stop()
+ expect(host.stop).toHaveBeenCalledOnce()
+})
diff --git a/cli/src/services/superTabs.ts b/cli/src/services/superTabs.ts
new file mode 100644
index 000000000..f2459bcb8
--- /dev/null
+++ b/cli/src/services/superTabs.ts
@@ -0,0 +1,10 @@
+import type { CoreApi, CorePorts, ServiceRequests } from '../core/api.js'
+import { superTabService, type SuperTabServiceOptions } from '../superTabs/service.js'
+
+/** No feature state lives in the core. Inline mode uses the same host journal and guards. */
+export function startSuperTabs(core: CoreApi, ports: CorePorts, options?: SuperTabServiceOptions): ServiceRequests {
+ const service = superTabService(core, options)
+ ports.superTabs = service.port
+ service.port.connected()
+ return service.requests
+}
diff --git a/cli/src/services/superTabsProcess.spec.ts b/cli/src/services/superTabsProcess.spec.ts
new file mode 100644
index 000000000..df25f92e5
--- /dev/null
+++ b/cli/src/services/superTabsProcess.spec.ts
@@ -0,0 +1,84 @@
+import { expect, it, vi } from 'vitest'
+import type { CoreApi } from '../core/api.js'
+import { runServiceProcess, type ServiceProcessOptions } from './process.js'
+import { runSuperTabsService } from './superTabsProcess.js'
+
+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+const owner = { owner: true, local: true }
+const flush = () => new Promise(resolve => setTimeout(resolve, 0))
+
+function setup(withPort = true) {
+ let api!: CoreApi, wire!: ServiceProcessOptions
+ const port = { connected: vi.fn(), disconnected: vi.fn(), stop: vi.fn() }
+ const stopped = vi.fn()
+ const process = runSuperTabsService({ dataDir: '/not-a-real-data-dir', socketPath: '/not-a-real-socket', machineId: 'm', token: 't',
+ run: options => { wire = options; return { stop: stopped } },
+ start: (core, ports) => {
+ api = core
+ if (withPort) ports.superTabs = port
+ return { super_tabs: payload => ({ value: payload.action, agents: core.agents.live().map(a => a.agentId), machine: core.daemon.machineId() }) }
+ },
+ })
+ return { process, port, stopped, wire: () => wire, api: () => api }
+}
+
+it('refreshes native identity before requests and backend calls; disconnecting withdraws the host', async () => {
+ const t = setup()
+ await expect(t.api().account.backend('GET', '/api/super-tabs')).rejects.toThrow('Core disconnected')
+ const query = vi.fn(async (name: string) => name === 'shown' ? { agents: [{ agentId: 'one' }] }
+ : name === 'daemon' ? { command: 'harness', port: 14001, machineId: 'm' }
+ : { status: 200, body: { success: true, data: {} } })
+ t.wire().onConnected!({ query })
+ expect(await t.wire().requests.super_tabs!({ action: 'status' }, owner)).toEqual({ value: 'status', agents: ['one'], machine: 'm' })
+ await flush()
+ expect(t.port.connected).toHaveBeenCalledOnce()
+ expect(await t.api().account.backend('GET', '/api/super-tabs')).toEqual({ status: 200, body: { success: true, data: {} } })
+ t.wire().onEvent!({ kind: 'delivery', event: { deliveryId: 'd', sessionId: 'one', state: 'queued' } })
+ t.wire().onDisconnected!()
+ expect(t.port.disconnected).toHaveBeenCalledOnce()
+ expect(t.api().agents.live()).toEqual([])
+ expect(t.api().daemon.machineId()).toBe('')
+ await expect(t.wire().requests.super_tabs!({}, owner)).rejects.toThrow('Core disconnected')
+ t.process.stop()
+ expect(t.port.stop).toHaveBeenCalledOnce()
+ expect(t.stopped).toHaveBeenCalledOnce()
+})
+
+it('does not revive an old identity when a pending read returns after disconnect', async () => {
+ const t = setup()
+ let resolve!: (value: Record<string, unknown>) => void
+ const answer = new Promise<Record<string, unknown>>(done => { resolve = done })
+ t.wire().onConnected!({ query: () => answer })
+ t.wire().onDisconnected!()
+ resolve({ agents: [{ agentId: 'old' }], command: 'harness', port: 14001, machineId: 'old' })
+ await flush()
+ expect(t.api().agents.live()).toEqual([])
+ expect(t.port.connected).not.toHaveBeenCalled()
+ t.process.stop()
+})
+
+it('can stop a failed port and tolerates missing identity without adopting an old roster', async () => {
+ const t = setup(false)
+ t.wire().onConnected!({ query: async () => ({}) })
+ await flush()
+ expect(await t.wire().requests.super_tabs!({}, owner)).toEqual({ value: undefined, agents: [], machine: '' })
+ t.wire().onDisconnected!(); t.process.stop()
+ expect(t.stopped).toHaveBeenCalledOnce()
+})
+
+it('does not start a host when disconnect occurs between a successful identity read and its continuation', async () => {
+ const t = setup()
+ t.wire().onConnected!({ query: async () => ({ command: 'harness', port: 14001, machineId: 'm', agents: [] }) })
+ for (let step = 0; step < 10 && !t.api().daemon.machineId(); step++) await Promise.resolve()
+ expect(t.api().daemon.machineId()).toBe('m')
+ t.wire().onDisconnected!()
+ await flush()
+ expect(t.port.connected).not.toHaveBeenCalled()
+ t.process.stop()
+})
+
+it('uses the real service wrapper and process runner by default without connecting in the fixture', () => {
+ const handle = runSuperTabsService({ dataDir: '/not-a-real-data-dir', socketPath: '/not-a-real-socket', machineId: 'm', token: 't' })
+ expect(runServiceProcess).toHaveBeenCalledWith(expect.objectContaining({ name: 'superTabs' }))
+ handle.stop()
+})
diff --git a/cli/src/services/superTabsProcess.ts b/cli/src/services/superTabsProcess.ts
new file mode 100644
index 000000000..ed738285d
--- /dev/null
+++ b/cli/src/services/superTabsProcess.ts
@@ -0,0 +1,50 @@
+import { emptyPorts, type DaemonAddress } from '../core/api.js'
+import { startSuperTabs } from './superTabs.js'
+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'
+import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'
+import { turnsLink } from './turnsLink.js'
+
+export interface SuperTabsServiceOptions {
+ dataDir: string; socketPath: string; machineId: string; token: string
+ run?: typeof runServiceProcess
+ start?: typeof startSuperTabs
+}
+
+/** A private process owns the host loop. Losing the core disconnects it and expires all input leases. */
+export function runSuperTabsService(options: SuperTabsServiceOptions): ServiceProcess {
+ let core: CoreConnection | null = null
+ let live: ShownAgent[] = []
+ let daemon: DaemonAddress | null = null
+ const ask = (query: string, payload: Record<string, unknown>) => core
+ ? core.query(query, payload) : Promise.reject(new Error('Core disconnected'))
+ const turns = turnsLink(ask)
+ let reading: Promise<void> | null = null
+ const ready = (): Promise<void> => {
+ const connection = core
+ return reading ??= Promise.all([ask('shown', {}), ask('daemon', {})]).then(([agents, address]) => {
+ if (core !== connection) throw new Error('Core changed while reading its identity')
+ live = agentsIn(agents) ?? []
+ daemon = daemonIn(address)
+ }).finally(() => { reading = null })
+ }
+ const base = processCoreApi(options.dataDir, 'superTabs', { live: () => live, ask, deliveries: turns, daemon: () => daemon })
+ // Every authority read also refreshes the native registry. A stopped/replaced
+ // harness cannot receive work through a stale process-side snapshot.
+ const api = { ...base, account: { ...base.account, backend: async (method: string, path: string, body?: unknown) => {
+ await ready()
+ return base.account.backend(method, path, body)
+ } } }
+ const ports = emptyPorts()
+ const requests = (options.start ?? startSuperTabs)(api, ports)
+ const service = (options.run ?? runServiceProcess)({
+ name: 'superTabs', socketPath: options.socketPath, machineId: options.machineId, token: options.token,
+ requests: { super_tabs: async (payload, asker, closed) => { await ready(); return requests.super_tabs(payload, asker, closed) } },
+ onEvent: payload => { turns.heard(payload) },
+ onConnected: connection => {
+ core = connection
+ void ready().then(() => { if (core === connection) ports.superTabs?.connected() }).catch(() => {})
+ },
+ onDisconnected: () => { core = null; live = []; daemon = null; ports.superTabs?.disconnected() },
+ })
+ return { stop: () => { ports.superTabs?.stop(); return service.stop() } }
+}
diff --git a/cli/src/sharing/owner.spec.ts b/cli/src/sharing/owner.spec.ts
index 2bc7e6c99..79a942f47 100644
--- a/cli/src/sharing/owner.spec.ts
+++ b/cli/src/sharing/owner.spec.ts
@@ -265,6 +265,42 @@ describe('owner authority and read-only observation', () => {
owner.receive(id, 'observer_open', { shareId: grant.id, email: grant.recipientEmail, ephemeral: b64e(newEphemeral().pub) })
const carolOf = () => store.all().find(g => g.recipientEmail === '[email protected]')!
+ it('preserves unread legacy rosters while replacing only the current Super Tab grants', async () => {
+ await owner.stop()
+ const grant = (email: string, tab: string) => ({ agentId: 'agent', email, tab, name: 'api', engine: 'codex', ownerPublicKey: KEY })
+ const expiry = new Date(Date.now() + 10 * DAY).toISOString()
+ store.derive('machine', [grant('[email protected]', TAB), grant('[email protected]', TAB), grant('[email protected]', 'super:old')], expiry, 0)
+ store.derive('machine', [grant('[email protected]', TAB), grant('[email protected]', 'super:old')], expiry, 0)
+ store.derive('other-machine', [grant('[email protected]', TAB)], expiry, 0)
+ store.invite({ machineId: 'machine', agentId: 'agent', recipientEmail: '[email protected]', name: 'Manual', engine: 'codex', ownerPublicKey: KEY, expiresAt: expiry })
+ rosters.mockResolvedValue(null)
+ let wanted = [grant('[email protected]', 'super:current')]
+ owner = new HarnessShareOwner({ machineId: () => machineId, identity, grants: store, rosters,
+ derivedGrants: () => wanted, resolveAgent: id => agents.get(id), send, publish, terminals: {} as TerminalBackendCoordinator })
+ await derive()
+ const active = () => store.all().filter(g => !g.revoked).map(g => g.recipientEmail).sort()
+ expect(publish.mock.calls.some(call => (call[2] as any)?.superTabId === 'current')).toBe(true)
+ wanted = []
+ await vi.advanceTimersByTimeAsync(1000); await owner.sync()
+ expect(active()).toEqual(['[email protected]', '[email protected]', '[email protected]'])
+ })
+
+ it('refuses and closes an observer immediately when its external grant authority expires', async () => {
+ await owner.stop()
+ let allowed = true
+ owner = new HarnessShareOwner({ machineId: () => machineId, identity, grants: store,
+ derivedGrants: () => [{ agentId: 'agent', email: '[email protected]', tab: 'super:tab', name: 'api', engine: 'codex' }],
+ allowsGrant: () => allowed, resolveAgent: id => agents.get(id), send, publish, terminals: {} as TerminalBackendCoordinator })
+ await derive(); await open(carolOf())
+ expect(frames.at(-1)?.type).toBe('observer_welcome')
+ allowed = false
+ await owner.receive('observer:carol', 'observer_frame', {})
+ expect(frames.at(-1)?.type).toBe('observer_closed')
+ await open(carolOf(), 'observer:new')
+ expect(frames.at(-1)).toMatchObject({ id: 'observer:new', type: 'observer_closed' })
+ })
+
it('derives a grant for every other account in the tab, publishes it, and lets that observer watch', async () => {
holding(tab())
expect(await derive()).toEqual({ invited: 2, revoked: 0 })
diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.ts
index ff40ae640..cbef973c7 100644
--- a/cli/src/sharing/owner.ts
+++ b/cli/src/sharing/owner.ts
@@ -4,7 +4,7 @@ import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'
import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'
import { encodeTerminalLocal } from '../lib/terminalBinary.js'
import { TerminalStreamManager } from '../lib/terminalStreamManager.js'
-import { HarnessGrantStore, inviteSchema, type HarnessGrant } from './grants.js'
+import { HarnessGrantStore, inviteSchema, type HarnessGrant, type DerivedGrant } from './grants.js'
import { ownerHandshake, signedOwnerHandshake, type ObserverCipher, type OwnerKey } from './crypto.js'
import { HarnessCollaborationStore, linkVisibility, type CommentAuthor } from './collaboration.js'
import { rosterGrants } from './rosterGrants.js'
@@ -40,6 +40,8 @@ export interface ShareOwnerDeps {
/** The shared tabs' rosters this computer verified against their pins, and the account signed in here, which the
* observers each tab wants are derived from (`harness_share_rosters`); null when either cannot be read. */
rosters?: () => Promise<{ accountId: string; rosters: Roster[]; consent: ReadonlySet<string> } | null>
+ derivedGrants?: () => Array<Omit<DerivedGrant, 'ownerPublicKey'>>
+ allowsGrant?: (grant: HarnessGrant) => boolean
now?: () => number
}
@@ -67,6 +69,7 @@ export class HarnessShareOwner {
payload: { bytes: Buffer.from(bytes).toString('base64') } })
},
})
+ let derivedSignature = ''
let ticks = 0
this.timer = setInterval(() => {
for (const [id, observer] of this.observers) {
@@ -75,7 +78,10 @@ export class HarnessShareOwner {
// Derived again every 30 s: the renewals fall due, and a roster change whose nudge never came is caught here. A
// refused grant is tried again at most hourly from here: up to 256 of them every 30 s would hammer the backend.
// One already waiting to run makes another pointless; it publishes what waits as it ends.
- if (++ticks % 30 === 0 && this.derivesQueued === 0) void this.derive(this.now() - HOUR).catch(ignore)
+ const signature = JSON.stringify(this.deps.derivedGrants?.() ?? [])
+ const changed = signature !== derivedSignature
+ derivedSignature = signature
+ if ((++ticks % 30 === 0 || changed) && this.derivesQueued === 0) void this.derive(this.now() - HOUR).catch(ignore)
}, 1000)
this.timer.unref()
// Once as it starts: a member removed while Share was off loses the view now, and a refused grant is tried again.
@@ -88,6 +94,7 @@ export class HarnessShareOwner {
|| observer.author?.owner === true || this.invited(link.agentId, observer.grant.recipientEmail))
}
return !!this.deps.grants.active(observer.grant.id, observer.grant.recipientEmail, this.deps.machineId())
+ && (this.deps.allowsGrant?.(observer.grant) ?? true)
&& !!this.deps.resolveAgent(observer.grant.agentId)
}
private invited(agentId: string, email: string): boolean {
@@ -129,7 +136,7 @@ export class HarnessShareOwner {
const grant: HarnessGrant | null = link && (link.visibility === 'public' || author?.owner || this.invited(link.agentId, email))
? { ...link, recipientEmail: email, createdAt: '', expiresAt: '', revoked: false, publicationError: null, tab: null, failedAt: null }
: payload.linkId ? null : this.deps.grants.active(String(payload.shareId), email, this.deps.machineId())
- if (!grant || !this.deps.resolveAgent(grant.agentId) || this.observers.size >= 100) {
+ if (!grant || !(this.deps.allowsGrant?.(grant) ?? true) || !this.deps.resolveAgent(grant.agentId) || this.observers.size >= 100) {
this.deps.send(connId, 'observer_closed', { reason: 'Sharing ended or invitation expired' }); return
}
try {
@@ -261,9 +268,12 @@ export class HarnessShareOwner {
// A roster file that cannot be read, or an account that cannot be said, revokes nothing: a passing read error
// would otherwise take every member's view away and give it back a moment later.
const source = await this.deps.rosters?.().catch(() => null)
- if (!source) return { invited: 0, revoked: 0 }
+ if (!source && !this.deps.derivedGrants) return { invited: 0, revoked: 0 }
const machineId = this.deps.machineId()
- const wanted = rosterGrants(source.rosters, { machineId, accountId: source.accountId }, source.consent)
+ const legacy = source ? rosterGrants(source.rosters, { machineId, accountId: source.accountId }, source.consent)
+ : this.deps.grants.all().filter(g => g.machineId === machineId && g.tab && !g.tab.startsWith('super:') && !g.revoked)
+ .map(g => ({ agentId: g.agentId, email: g.recipientEmail, tab: g.tab!, name: g.name, engine: g.engine }))
+ const wanted = [...legacy, ...this.deps.derivedGrants?.() ?? []]
// Asked only when there is something to grant: in Share's own process each ask goes to the gateway.
const key = wanted.length ? await this.ownerPublicKey().catch(() => null) : ''
// Without this machine's key (its gateway is down) nothing new can be published, but a member who left must still
@@ -303,7 +313,8 @@ export class HarnessShareOwner {
const result = await this.deps.publish(grant.revoked ? 'DELETE' : 'PUT', `/api/harness-shares/${grant.id}`,
grant.revoked ? undefined : { machineId: grant.machineId, agentId: grant.agentId,
recipientEmail: grant.recipientEmail, name: grant.name, engine: grant.engine,
- ownerPublicKey: grant.ownerPublicKey, expiresAt: grant.expiresAt })
+ ownerPublicKey: grant.ownerPublicKey, expiresAt: grant.expiresAt,
+ ...(grant.tab?.startsWith('super:') ? { superTabId: grant.tab.slice(6) } : {}) })
if (result.status >= 200 && result.status < 300 || grant.revoked && result.status === 404) {
// A revoke may have happened while this network request was in flight.
const current = this.deps.grants.all().find(g => g.id === grant.id)
diff --git a/cli/src/superTabs/capacity.spec.ts b/cli/src/superTabs/capacity.spec.ts
new file mode 100644
index 000000000..ece9cc618
--- /dev/null
+++ b/cli/src/superTabs/capacity.spec.ts
@@ -0,0 +1,28 @@
+import { expect, it, vi } from 'vitest'
+import { admission, quotaOf, readCapabilities } from './capacity.js'
+const requirements = { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: ['/dev/test'], quotaRequired: false }
+it('uses the destination filesystem and reports missing tools/devices without executing commands', async () => {
+ const deps = { resources: vi.fn(async () => ({ cpuPercent: 25, memoryTotalBytes: 1000, memoryUsedBytes: 300 })),
+ disk: vi.fn(async () => ({ freeBytes: 500, volume: 'volume', path: '/fixture/repo' })), tool: vi.fn(async () => true), device: vi.fn(async () => true) }
+ const capacity = await readCapabilities({ cwd: '/fixture/repo', tools: ['git'], devices: ['/dev/test'] }, deps)
+ expect(deps.disk).toHaveBeenCalledWith('/fixture/repo', false)
+ expect(admission(capacity, { installed: true }, quotaOf({}, 'codex', false), requirements)).toMatchObject({ allowed: true, unknown: ['Subscription allowance is unknown for this account.'] })
+ deps.disk.mockRejectedValueOnce(new Error('not mounted'))
+ const missing = await readCapabilities({ cwd: '/fixture/repo', tools: [], devices: [] }, deps)
+ expect(admission(missing, { installed: true }, quotaOf({}, 'codex', false), requirements)).toMatchObject({ allowed: false })
+ expect(await readCapabilities({ cwd: '/fixture', tools: ['git; whoami'] }, deps)).toMatchObject({ error: 'INVALID_REQUEST' })
+ expect(deps.tool).toHaveBeenCalledTimes(1)
+})
+it('keeps unknown quota distinct from unused quota and honors all limiting windows', () => {
+ const input = { providers: [{ provider: 'codex', account: 'opaque', email: '[email protected]', outcome: 'answered', httpStatus: 200,
+ body: { rate_limit: { primary_window: { used_percent: 10, reset_at: 1000 }, secondary_window: { used_percent: 100, reset_at: 2000 } } } }] }
+ const quota = quotaOf(input, 'codex', false)
+ expect(quota).toEqual({ known: true, account: 'opaque', windows: [{ usedPercent: 10, resetsAt: 1000 }, { usedPercent: 100, resetsAt: 2000 }] })
+ expect(quotaOf(input, 'codex', true)).toMatchObject({ known: false, account: null })
+ const capacity = { resources: { cpuPercent: 95, memoryTotalBytes: 1000, memoryUsedBytes: 950, projectDiskFreeBytes: 10 }, tools: {}, devices: {} }
+ const result = admission(capacity, { installed: true }, quota, requirements)
+ expect(result.allowed).toBe(false)
+ expect(result.reasons).toHaveLength(6)
+ expect(admission({}, { installed: true, signedIn: false }, quotaOf({}, 'codex', false), requirements).reasons).toContain('The selected agent engine is not signed in on this machine.')
+ expect(admission({}, {}, quotaOf({}, 'claude', false), { ...requirements, quotaRequired: true }).reasons).toContain('The requested subscription allowance could not be verified.')
+})
diff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.ts
new file mode 100644
index 000000000..861bde789
--- /dev/null
+++ b/cli/src/superTabs/capacity.ts
@@ -0,0 +1,89 @@
+import { access } from 'node:fs/promises'
+import { constants } from 'node:fs'
+import { isAbsolute } from 'node:path'
+import { readMachineResources } from '../lib/machineResources.js'
+import { commandAvailableInInteractiveShell } from '../lib/engineLaunch.js'
+import { object } from './wire.js'
+import { readCapacityDisk } from './disk.js'
+
+type Json = Record<string, unknown>
+export interface Requirements {
+ memoryBytes: number; diskBytes: number; maxCpuPercent: number
+ tools: string[]; devices: string[]; quotaRequired: boolean
+}
+export async function readCapabilities(input: Json, deps = {
+ resources: readMachineResources,
+ disk: readCapacityDisk,
+ tool: commandAvailableInInteractiveShell,
+ device: async (path: string) => { await access(path, constants.R_OK | constants.W_OK); return true },
+}) {
+ const cwd = input.cwd, tools = input.tools ?? [], devices = input.devices ?? []
+ if (typeof cwd !== 'string' || !isAbsolute(cwd) || cwd.length > 4096 || /[\x00-\x1f\x7f]/.test(cwd)
+ || (input.worktree !== undefined && typeof input.worktree !== 'boolean')
+ || !Array.isArray(tools) || tools.length > 20 || !tools.every(t => typeof t === 'string' && /^[A-Za-z0-9_.+-]{1,80}$/.test(t))
+ || !Array.isArray(devices) || devices.length > 20 || !devices.every(d => typeof d === 'string' && isAbsolute(d) && d.length <= 4096 && !/[\x00-\x1f\x7f]/.test(d))) {
+ return { error: 'INVALID_REQUEST', detail: 'Name an absolute project path and up to 20 tools and devices.' }
+ }
+ const probeTools = async () => {
+ const answers: Array<readonly [string, boolean]> = []
+ for (let index = 0; index < tools.length; index += 4) {
+ answers.push(...await Promise.all(tools.slice(index, index + 4).map(async t => [t, await deps.tool(t).catch(() => false)] as const)))
+ }
+ return answers
+ }
+ // Requested only before admission. No new polling, command execution or shell
+ // interpolation; the tool probe is the same bounded one native launches use.
+ const [resources, disk, toolValues, deviceValues] = await Promise.all([
+ deps.resources().catch(() => null), deps.disk(cwd, input.worktree === true).catch(() => null),
+ probeTools(),
+ Promise.all(devices.map(async d => [d, await deps.device(d).catch(() => false)] as const)),
+ ])
+ return { ok: true, sampledAt: Date.now(), resources: { ...resources, projectDiskFreeBytes: disk?.freeBytes ?? null,
+ projectDiskVolume: disk?.volume ?? null, projectDiskPath: disk?.path ?? null },
+ tools: Object.fromEntries(toolValues), devices: Object.fromEntries(deviceValues) }
+}
+
+const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
+/** Only measured windows leave the account reader. No credentials, emails or
+ * invented token counts; an unreported/custom-profile allowance is unknown. */
+export function quotaOf(reply: Json, engine: string, customAccount: boolean) {
+ const reading = !customAccount && Array.isArray(reply.providers) ? reply.providers.map(object).find(r => r.provider === engine) : null
+ const windows: Array<{ usedPercent: number; resetsAt: unknown }> = []
+ if (reading?.outcome === 'answered' && reading.httpStatus === 200) {
+ const body = object(reading.body)
+ const raw = engine === 'claude' ? [body.five_hour, body.seven_day]
+ : engine === 'codex' ? [object(body.rate_limit).primary_window, object(body.rate_limit).secondary_window] : []
+ for (const value of raw) {
+ const w = object(value), used = w.utilization ?? w.used_percentage ?? w.used_percent
+ if (finite(used) && used >= 0 && used <= 100) windows.push({ usedPercent: used, resetsAt: w.resets_at ?? w.reset_at ?? null })
+ }
+ }
+ return { known: windows.length > 0, account: typeof reading?.account === 'string' ? reading.account : null, windows }
+}
+export function admission(capacity: Json, engine: Json, quota: ReturnType<typeof quotaOf>, requirements: Requirements, customAccount = false) {
+ const reasons: string[] = [], unknown: string[] = []
+ const resources = object(capacity.resources), tools = object(capacity.tools), devices = object(capacity.devices)
+ if (engine.installed !== true) reasons.push('The selected agent engine is not installed on this machine.')
+ if (engine.signedIn === false && !customAccount) reasons.push('The selected agent engine is not signed in on this machine.')
+ const memory = finite(resources.memoryTotalBytes) && finite(resources.memoryUsedBytes)
+ ? resources.memoryTotalBytes - resources.memoryUsedBytes : null
+ for (const [label, value, needed] of [
+ ['Available memory', memory, requirements.memoryBytes],
+ ['Project disk space', resources.projectDiskFreeBytes, requirements.diskBytes],
+ ] as const) {
+ if (!finite(value)) { unknown.push(`${label} is unknown.`); if (needed > 0) reasons.push(`${label} could not be verified.`) }
+ else if (value < needed) reasons.push(`${label} is ${value} bytes; this work requires ${needed}.`)
+ }
+ if (!finite(resources.cpuPercent)) {
+ unknown.push('CPU use is unknown.')
+ if (requirements.maxCpuPercent < 100) reasons.push('CPU headroom could not be verified.')
+ } else if (resources.cpuPercent > requirements.maxCpuPercent) reasons.push(`CPU use is ${resources.cpuPercent}%; the requested maximum is ${requirements.maxCpuPercent}%.`)
+ if (resources.memoryPressure === 'critical') reasons.push('The machine reports critical memory pressure.')
+ for (const t of requirements.tools) if (tools[t] !== true) reasons.push(`Required tool unavailable: ${t}.`)
+ for (const d of requirements.devices) if (devices[d] !== true) reasons.push(`Required device unavailable: ${d}.`)
+ if (!quota.known) {
+ unknown.push('Subscription allowance is unknown for this account.')
+ if (requirements.quotaRequired) reasons.push('The requested subscription allowance could not be verified.')
+ } else if (quota.windows.some(w => w.usedPercent >= 100)) reasons.push('The subscription has an exhausted usage window. Wait for a fresh allowance reading or choose another account.')
+ return { allowed: reasons.length === 0, reasons, unknown }
+}
diff --git a/cli/src/superTabs/command.spec.ts b/cli/src/superTabs/command.spec.ts
new file mode 100644
index 000000000..a6a12c1e7
--- /dev/null
+++ b/cli/src/superTabs/command.spec.ts
@@ -0,0 +1,42 @@
+import { expect, it, vi } from 'vitest'
+import { parseSuperTabArgs, superTabCommand } from './command.js'
+const where = { port: 14001, dataDir: '/fixture', machineId: 'machine' }
+const prefix = ['--tab', 'tab', '--agent', 'agent']
+it('keeps an explicit stable receipt for agent messages and arbitrary work commands', () => {
+ expect(parseSuperTabArgs([...prefix, 'post', 'lead', 'Ready', 'op-1'], where).payload).toMatchObject({ action: 'command', operationId: 'op-1', command: { type: 'message.send', conversationId: 'lead', text: 'Ready' } })
+ expect(parseSuperTabArgs([...prefix, 'command', 'op-2', '{"type":"work.assign"}'], where).payload).toMatchObject({ command: { type: 'work.assign' } })
+ expect(parseSuperTabArgs(['--port', '14002', '--machine', 'target', ...prefix, 'messages', 'lead'], where)).toMatchObject({ where: { port: 14002, machineId: 'target' }, payload: { conversationId: 'lead' } })
+ expect(parseSuperTabArgs(['help'], where).payload.action).toBe('help')
+ expect(parseSuperTabArgs([...prefix, 'message', 'lead', 'old-question'], where).payload)
+ .toMatchObject({ action: 'message', conversationId: 'lead', messageId: 'old-question' })
+ expect(parseSuperTabArgs([...prefix, 'post', 'lead', '--tab', 'literal'], where).payload.command).toMatchObject({ text: '--tab' })
+ expect(parseSuperTabArgs(['--tab', 'tab', 'status'], where).payload.agentId).toBe('')
+ for (const argv of [[], ['status'], [...prefix, 'post', 'lead', 'Ready'], [...prefix, 'messages', '../other'],
+ [...prefix, 'message', 'lead'], [...prefix, 'message', 'lead', '../other'], [...prefix, 'message', 'lead', 'id', 'extra'],
+ ['--port', 'no', 'help'], ['--machine', '', 'help'], [...prefix, 'status', 'extra']]) {
+ expect(() => parseSuperTabArgs(argv, where)).toThrow('harness super-tab')
+ }
+})
+it('finds the native caller without requiring an ID in the initial launch prompt', async () => {
+ const request = vi.fn(async (type: string) => type === 'agents_list'
+ ? { agents: [{ id: 'native', engine: 'codex', tmuxPane: '%42', status: 'active' }] }
+ : { ok: true })
+ const close = vi.fn(), print = vi.fn()
+ const deps = { where: () => where, pane: '%42', open: async () => ({ request, close, machineId: 'machine' }), print }
+ expect(await superTabCommand(['--tab', 'tab', 'status'], deps)).toBe(0)
+ expect(request).toHaveBeenLastCalledWith('super_tabs', expect.objectContaining({ harnessId: 'native' }), 30_000)
+ expect(await superTabCommand(['--tab', 'tab', 'status'], { ...deps, pane: '%43' })).toBe(1)
+ expect(print.mock.calls.at(-1)![0]).toContain('inside the participating harness')
+ expect(close).toHaveBeenCalledTimes(2)
+})
+it('uses the existing daemon transport and retains a receipt in an uncertain answer', async () => {
+ const print = vi.fn(), close = vi.fn(), request = vi.fn(async () => ({ ok: true }))
+ const open = vi.fn(async () => ({ request, close, machineId: 'machine' }))
+ const deps = { where: () => where, open, print }
+ expect(await superTabCommand([...prefix, 'post', 'lead', 'Ready', 'op'], deps)).toBe(0)
+ expect(close).toHaveBeenCalledOnce()
+ request.mockRejectedValueOnce(new Error('Connection lost'))
+ expect(await superTabCommand([...prefix, 'post', 'lead', 'Ready', 'op'], deps)).toBe(1)
+ expect(JSON.parse(print.mock.calls.at(-1)![0])).toEqual({ error: 'Connection lost', operationId: 'op' })
+ expect(close).toHaveBeenCalledTimes(2)
+})
diff --git a/cli/src/superTabs/command.ts b/cli/src/superTabs/command.ts
new file mode 100644
index 000000000..74b4d56ea
--- /dev/null
+++ b/cli/src/superTabs/command.ts
@@ -0,0 +1,83 @@
+import { inspectCapacity, startAgent } from './start.js'
+import { object } from './host.js'
+import { openDaemon, whereFor, type Daemon, type Where } from '../agentClient/daemon.js'
+import { callerOf, type Frame } from '../agentClient/model.js'
+import { identifier } from './host.js'
+
+const USAGE = 'harness super-tab --tab ID [--agent ID] [--port N --machine ID] status | messages GROUP | message GROUP MESSAGE_ID | post GROUP TEXT OPERATION_ID | command OPERATION_ID JSON | start OPERATION_ID JSON | resume START_ID | capacity MACHINE_ID JSON | help'
+export function parseSuperTabArgs(argv: readonly string[], where: Where) {
+ const positional: string[] = []
+ let tabId = '', agentId = ''
+ const target = { ...where }
+ for (let i = 0; i < argv.length; i++) {
+ const flag = argv[i]
+ if (flag === '--tab') tabId = argv[++i] ?? ''
+ else if (flag === '--agent') agentId = argv[++i] ?? ''
+ else if (flag === '--port') target.port = Number(argv[++i])
+ else if (flag === '--machine') target.machineId = argv[++i] ?? ''
+ else { positional.push(...argv.slice(i)); break }
+ }
+ if (!Number.isInteger(target.port) || target.port < 1 || target.port > 65535 || !identifier(target.machineId)) throw new Error(USAGE)
+ const [action, first, second, third] = positional
+ if (action !== 'help' && (!identifier(tabId) || (agentId && !identifier(agentId)))) throw new Error(USAGE)
+ const payload: Record<string, unknown> = { action, tabId, agentId }
+ if (action === 'messages' && identifier(first) && positional.length === 2) payload.conversationId = first
+ else if (action === 'message' && identifier(first) && identifier(second) && positional.length === 3) {
+ Object.assign(payload, { conversationId: first, messageId: second })
+ }
+ else if (action === 'post' && identifier(first) && second?.trim() && identifier(third) && positional.length === 4) {
+ Object.assign(payload, { action: 'command', operationId: third,
+ command: { type: 'message.send', conversationId: first, text: second, replyTo: null, recipientIds: [] } })
+ } else if (action === 'command' && identifier(first) && second && positional.length === 3) {
+ Object.assign(payload, { operationId: first, command: JSON.parse(second) })
+ } else if (action === 'start' && identifier(first) && second && positional.length === 3) {
+ Object.assign(payload, { operationId: first, request: JSON.parse(second) })
+ } else if (action === 'resume' && identifier(first) && positional.length === 2) payload.startId = first
+ else if (action === 'capacity' && identifier(first) && second && positional.length === 3) {
+ Object.assign(payload, { targetMachineId: first, request: JSON.parse(second) })
+ } else if (!['status', 'help'].includes(action) || positional.length !== 1) throw new Error(USAGE)
+ return { where: target, payload }
+}
+
+export async function superTabCommand(argv: readonly string[], deps: {
+ where?: () => Where; open?: typeof openDaemon; print?: (text: string) => void; pane?: string
+} = {}): Promise<number> {
+ let daemon: Daemon | null = null
+ let operationId: unknown
+ const print = deps.print ?? console.log
+ try {
+ const request = parseSuperTabArgs(argv, (deps.where ?? (() => whereFor(process.env.TMUX_PANE)))())
+ operationId = request.payload.operationId
+ daemon = await (deps.open ?? openDaemon)(request.where)
+ if (request.payload.action !== 'help' && !request.payload.agentId) {
+ const listed = await daemon.request('agents_list')
+ const frames = Array.isArray(listed.agents) ? listed.agents as Frame[] : []
+ const caller = callerOf(frames, deps.pane ?? process.env.TMUX_PANE, request.where.machineId)
+ if (!caller) throw new Error('Run this command inside the participating harness, or supply its --agent ID.')
+ request.payload.harnessId = caller.agentId
+ }
+ const source = daemon
+ const scoped = (payload: Record<string, unknown>) => source.request('super_tabs', {
+ tabId: request.payload.tabId, agentId: request.payload.agentId, harnessId: request.payload.harnessId, ...payload,
+ }, 30_000)
+ let result: Record<string, unknown>
+ if (['start', 'resume'].includes(String(request.payload.action))) {
+ result = await startAgent(request.payload, scoped, request.where, deps.open)
+ } else if (request.payload.action === 'capacity') {
+ // Establish current Super Tab participation before inspecting a machine;
+ // the native relay independently enforces that account's machine access.
+ const known = await scoped({ action: 'status' })
+ if (known.error) result = known
+ else {
+ const target = await (deps.open ?? openDaemon)(request.where, String(request.payload.targetMachineId))
+ try { result = { ok: true, ...await inspectCapacity(target, object(request.payload.request)) } }
+ finally { target.close() }
+ }
+ } else result = await daemon.request('super_tabs', request.payload, 30_000)
+ print(JSON.stringify({ ...result, ...(operationId ? { operationId } : {}) }))
+ return result.error ? 1 : 0
+ } catch (error) {
+ print(JSON.stringify({ error: error instanceof Error ? error.message : String(error), ...(operationId ? { operationId } : {}) }))
+ return 1
+ } finally { daemon?.close() }
+}
diff --git a/cli/src/superTabs/configuration.spec.ts b/cli/src/superTabs/configuration.spec.ts
new file mode 100644
index 000000000..ed2690fd0
--- /dev/null
+++ b/cli/src/superTabs/configuration.spec.ts
@@ -0,0 +1,43 @@
+import { expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../lib/registry.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { configurationObservation } from './configuration.js'
+
+const previous = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+const row = { tabId: 'tab', agent: { id: 'agent', machineId: 'machine', harnessId: 'harness', configuration: previous, configurationVersion: 'version-1' } }
+function fixture() {
+ return fakeCore({ agents: {
+ byAgent: () => ({ agentId: 'harness', engine: 'claude' }) as RegisteredSession,
+ terminalAvailable: () => true, runtimeProfile: vi.fn(() => 'runtime-v1:harness:claude:sonnet@high'),
+ } })
+}
+
+it('records only the observed engine/model/effort and does not carry a previous model\'s context window', () => {
+ const core = fixture()
+ const update = configurationObservation(core, 'machine', row)!
+ expect(update.body).toMatchObject({ asAgentId: 'agent', command: { type: 'agent.configuration', previousVersion: 'version-1',
+ configuration: { ...previous, model: 'sonnet', contextWindow: null } } })
+ expect(configurationObservation(core, 'machine', row)).toEqual(update)
+ expect(configurationObservation(core, 'machine', { ...row, agent: { ...row.agent, configurationVersion: 'version-2' } })!.body.operationId)
+ .not.toBe(update.body.operationId)
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@max')
+ expect(configurationObservation(core, 'machine', row)!.body.command.configuration.contextWindow).toBe(200000)
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:opus@high')
+ expect(configurationObservation(core, 'machine', row)).toBeNull()
+})
+
+it('refuses an unknown, mismatched, unavailable or unrelated native reading', () => {
+ const core = fixture()
+ for (const profile of [null, '', 'runtime-v1:other:claude:sonnet@high', 'runtime-v1:harness:codex:model@high']) {
+ vi.mocked(core.agents.runtimeProfile).mockReturnValue(profile)
+ expect(configurationObservation(core, 'machine', row)).toBeNull()
+ }
+ expect(configurationObservation(core, 'other', row)).toBeNull()
+ expect(configurationObservation(core, 'machine', { ...row, tabId: '../tab' })).toBeNull()
+ expect(configurationObservation(core, 'machine', { ...row, agent: { ...row.agent, configurationVersion: {} } })).toBeNull()
+ core.agents.byAgent = () => undefined
+ expect(configurationObservation(core, 'machine', row)).toBeNull()
+ core.agents.byAgent = () => ({ agentId: 'harness', engine: 'claude' }) as RegisteredSession
+ core.agents.terminalAvailable = () => false
+ expect(configurationObservation(core, 'machine', row)).toBeNull()
+})
diff --git a/cli/src/superTabs/configuration.ts b/cli/src/superTabs/configuration.ts
new file mode 100644
index 000000000..9c775f031
--- /dev/null
+++ b/cli/src/superTabs/configuration.ts
@@ -0,0 +1,30 @@
+import { createHash } from 'node:crypto'
+import type { CoreApi } from '../core/api.js'
+import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'
+import { identifier, object } from './wire.js'
+
+/** Use the same observed profile as the app. Unknown readings are not changes,
+ * and a model's context size is never inferred from its name. */
+export function configurationObservation(core: CoreApi, machineId: string, value: unknown) {
+ const row = object(value), agent = object(row.agent), previous = object(agent.configuration)
+ if (![row.tabId, agent.id, agent.harnessId].every(identifier) || agent.machineId !== machineId) return null
+ if (agent.configurationVersion != null && !identifier(agent.configurationVersion)) return null
+ const native = core.agents.byAgent(String(agent.harnessId))
+ if (!native || !core.agents.terminalAvailable(native.agentId)) return null
+ const profile = parseRuntimeProfile(core.agents.runtimeProfile(native))
+ if (!profile || profile.sessionId !== native.agentId || profile.engine !== native.engine || profile.model.length > 200) return null
+ const sameModel = previous.engine === native.engine && previous.model === profile.model
+ const configuration = {
+ engine: native.engine, model: profile.model, effort: profile.effort,
+ contextWindow: sameModel && Number.isSafeInteger(previous.contextWindow) && Number(previous.contextWindow) > 0 ? previous.contextWindow : null,
+ engineVersion: previous.engine === native.engine && typeof previous.engineVersion === 'string' ? previous.engineVersion : null,
+ }
+ if (Object.entries(configuration).every(([key, part]) => previous[key] === part)) return null
+ const previousVersion = agent.configurationVersion ?? null
+ const operationId = `configuration-${createHash('sha256').update(JSON.stringify([row.tabId, agent.id, previousVersion, configuration])).digest('hex')}`
+ return {
+ path: `/api/super-tabs/${row.tabId}/commands`,
+ body: { operationId, asAgentId: agent.id,
+ command: { type: 'agent.configuration', previousVersion, configuration } },
+ }
+}
diff --git a/cli/src/superTabs/disk.spec.ts b/cli/src/superTabs/disk.spec.ts
new file mode 100644
index 000000000..d51240261
--- /dev/null
+++ b/cli/src/superTabs/disk.spec.ts
@@ -0,0 +1,18 @@
+import { afterEach, expect, it } from 'vitest'
+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { readCapacityDisk } from './disk.js'
+const directories: string[] = []
+afterEach(() => { for (const path of directories.splice(0)) rmSync(path, { recursive: true, force: true }) })
+it('samples the actual managed worktree parent even when its source is elsewhere', async () => {
+ const parent = mkdtempSync(join(tmpdir(), 'super-tab-disk-')); directories.push(parent)
+ const root = join(parent, 'not-created-yet')
+ const ordinary = await readCapacityDisk(parent)
+ expect(await readCapacityDisk('/unmounted/source/repo', true, root)).toMatchObject({ volume: ordinary.volume, path: parent })
+ mkdirSync(join(root, 'worktrees'), { recursive: true })
+ expect(await readCapacityDisk('/unmounted/source/repo', true, root)).toMatchObject({ path: join(root, 'worktrees') })
+ await expect(readCapacityDisk('/unmounted/source/repo', false, root)).rejects.toThrow()
+ rmSync(join(root, 'worktrees'), { recursive: true }); writeFileSync(join(root, 'worktrees'), 'not a folder')
+ await expect(readCapacityDisk(parent, true, root)).rejects.toThrow('not a directory')
+})
diff --git a/cli/src/superTabs/disk.ts b/cli/src/superTabs/disk.ts
new file mode 100644
index 000000000..bfed37ca7
--- /dev/null
+++ b/cli/src/superTabs/disk.ts
@@ -0,0 +1,24 @@
+import { stat, statfs } from 'node:fs/promises'
+import { dirname, join } from 'node:path'
+import { projectsRoot } from '../lib/projectFolder.js'
+
+export interface CapacityDisk { freeBytes: number; volume: string; path: string }
+
+/** A managed worktree may live on a different volume from its source repo.
+ * Sample its existing parent without creating a folder during admission. */
+export async function readCapacityDisk(cwd: string, worktree = false, root = projectsRoot()): Promise<CapacityDisk> {
+ let path = worktree ? join(root, 'worktrees') : cwd
+ for (;;) {
+ try {
+ const info = await stat(path)
+ if (!info.isDirectory()) throw new Error('The destination is not a directory.')
+ const disk = await statfs(path)
+ const freeBytes = disk.bavail * disk.bsize
+ if (!Number.isSafeInteger(freeBytes) || freeBytes < 0) throw new Error('The destination disk capacity is unknown.')
+ return { freeBytes, volume: String(info.dev), path }
+ } catch (error) {
+ if (!worktree || (error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(path) === path) throw error
+ path = dirname(path)
+ }
+ }
+}
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
new file mode 100644
index 000000000..a4ba7311b
--- /dev/null
+++ b/cli/src/superTabs/host.spec.ts
@@ -0,0 +1,237 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { CoreApi, TurnDelivery } from '../core/api.js'
+import { fakeCore } from '../testing/fakeCore.js'
+import { backend, hostJournalFile, SuperTabHost } from './host.js'
+
+const roots: string[] = []
+const hosts: SuperTabHost[] = []
+afterEach(() => { for (const host of hosts.splice(0)) host.stop(); for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+
+function setup(messageFields: Record<string, unknown> = {}) {
+ const dir = mkdtempSync(join(tmpdir(), 'super-tab-host-')); roots.push(dir)
+ const listeners = new Set<(e: TurnDelivery) => void>()
+ const row = { tabId: 'tab', agent: { id: 'agent', harnessId: 'harness', machineId: 'machine-1' } }
+ let removed = false, revoked = false, status = 'queued', claimId: string | null = null
+ const receipts: Record<string, unknown>[] = []
+ const call: CoreApi['account']['backend'] = vi.fn(async (method, path, body) => {
+ let data: unknown
+ if (path.includes('/hosts/')) data = removed ? [] : [row]
+ else if (revoked) return { status: 403, body: { success: false, error: { code: 'FORBIDDEN', message: 'Grant removed' } } }
+ else if (method === 'GET') data = status === 'delivered' ? [] : [{ id: 'delivery', claimId, status }]
+ else {
+ const command = body as Record<string, unknown>
+ if (command.type === 'claim') { claimId = command.claimId as string; status = 'claimed' }
+ else { receipts.push(command); status = command.uncertain ? 'uncertain' : 'delivered' }
+ data = { delivery: { id: 'delivery', claimId, status }, message: { id: 'message', conversationId: 'lead', text: 'Build the agreed feature.', author: { name: 'Collaborator' }, ...messageFields } }
+ }
+ return { status: 200, body: { success: true, data } }
+ })
+ const core = fakeCore({ dataDir: dir,
+ agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never), terminalAvailable: vi.fn(() => true) },
+ account: { backend: call },
+ turns: { onDelivery: vi.fn(fn => { listeners.add(fn); return () => { listeners.delete(fn) } }) },
+ })
+ const open = () => { const host = new SuperTabHost(core, 'machine-1', { log: vi.fn() }); hosts.push(host); return host }
+ const event = (state: TurnDelivery['state'], reason?: string) => {
+ for (const fn of listeners) fn({ deliveryId: 'team:service:superTabs:delivery', sessionId: 'harness', state, reason })
+ }
+ const saved = () => JSON.parse(readFileSync(hostJournalFile(dir, 'machine-1'), 'utf8'))
+ return { core, call, open, event, receipts, saved, dir, remove: () => { removed = true }, revoke: (value = true) => { revoked = value }, foreignClaim: () => { claimId = 'another-process' } }
+}
+
+describe('Super Tab native delivery handoff', () => {
+ it('preserves the exact reply reference when a short human answer reaches an agent', async () => {
+ const t = setup({ replyTo: 'question-2', text: 'Yes, keep them.' })
+ await t.open().tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledWith('harness', expect.stringContaining(
+ 'In reply to message question-2. Read it before interpreting the answer:'
+ ), 'team:service:superTabs:delivery')
+ expect(vi.mocked(t.core.turns.deliver).mock.calls[0]?.[1]).toContain('Message message from Collaborator:\nYes, keep them.')
+ })
+
+ it('keeps a slow configuration observation out of the native delivery and lease path', async () => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.agents.byAgent).mockReturnValue({ agentId: 'harness', engine: 'claude' } as never)
+ vi.mocked(t.core.agents.runtimeProfile).mockReturnValue('runtime-v1:harness:claude:sonnet@high')
+ const original = vi.mocked(t.call).getMockImplementation()!
+ let release!: () => void
+ const gate = new Promise<void>(resolve => { release = resolve })
+ let observations = 0
+ vi.mocked(t.call).mockImplementation(async (...args) => {
+ if (args[1].endsWith('/commands')) {
+ observations++
+ await gate
+ return { status: 200, body: { data: {} } }
+ }
+ return original(...args)
+ })
+ await host.tick(); await host.tick()
+ expect(observations).toBe(1)
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.core.turns.leaseDeliveries).toHaveBeenCalled()
+ host.stop(); release()
+ await Promise.resolve()
+ })
+ it('retires a human-resolved journal entry without resubmitting its native input', async () => {
+ const t = setup(), host = t.open()
+ await host.tick(); t.event('unknown', 'lost acknowledgement'); await host.tick()
+ const original = vi.mocked(t.core.account.backend).getMockImplementation()!
+ vi.mocked(t.core.account.backend).mockImplementation(async (method, path, body) => {
+ if (method === 'GET' && path.endsWith('/deliveries/delivery')) {
+ return { status: 200, body: { success: true, data: { id: 'delivery', status: 'confirmed' } } }
+ }
+ return original(method, path, body)
+ })
+ await host.reconcileReceipts()
+ expect(t.saved().entries).toEqual({})
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ })
+ it('persists before typing, keeps one native delivery during polls, and acknowledges the exact receipt', async () => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.turns.deliver).mockImplementation(() => expect(t.saved().entries.delivery.stage).toBe('submitting'))
+ await host.tick(); await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.core.turns.deliver).toHaveBeenCalledWith('harness', expect.stringContaining('post'), 'team:service:superTabs:delivery')
+ expect(t.core.turns.leaseDeliveries).toHaveBeenCalledWith('superTabs', expect.objectContaining({ 'team:service:superTabs:delivery': expect.any(Number) }))
+ t.event('queued'); t.event('delivered')
+ const receipt = t.saved().entries.delivery.receipt
+ await host.tick()
+ expect(t.receipts).toEqual([expect.objectContaining({ receipt, uncertain: false })])
+ expect(t.saved().entries).toEqual({})
+ await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not type again after a crash between submission and its native acknowledgement', async () => {
+ const t = setup(), first = t.open()
+ await first.tick(); first.stop()
+ const restarted = t.open()
+ await restarted.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.receipts).toEqual([expect.objectContaining({ uncertain: true, receipt: expect.stringContaining('restarted') })])
+ })
+
+ it('replays a saved receipt after a lost backend acknowledgement without another native send', async () => {
+ const t = setup(), first = t.open()
+ await first.tick(); t.event('delivered'); first.stop()
+ const restarted = t.open()
+ await restarted.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.receipts[0].uncertain).toBe(false)
+ })
+
+ it('retries an explicitly withheld busy-terminal write but never an ambiguous paste', async () => {
+ const t = setup(), host = t.open()
+ await host.tick(); t.event('rejected', 'team_waiting_busy')
+ await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)
+ t.event('unknown', 'dispatch_ambiguous')
+ await host.tick(); await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(2)
+ expect(t.receipts.every(r => r.uncertain === true)).toBe(true)
+ })
+
+ it('withdraws queued input on removal or revoked machine access and cannot revive it by re-sharing', async () => {
+ const t = setup(), host = t.open()
+ await host.tick(); t.revoke(); await host.tick()
+ expect(t.core.turns.cancelDelivery).toHaveBeenCalledWith('team:service:superTabs:delivery')
+ expect(t.core.turns.leaseDeliveries).toHaveBeenLastCalledWith('superTabs', {})
+ t.revoke(false); await host.tick()
+ expect(t.core.turns.deliver).toHaveBeenCalledTimes(1)
+ expect(t.receipts[0].uncertain).toBe(true)
+ t.remove(); await host.tick()
+ })
+
+ it('exposes a claim without a local receipt for human recovery without taking over execution', async () => {
+ const t = setup(), host = t.open()
+ t.foreignClaim(); await host.tick()
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ expect(t.receipts).toEqual([expect.objectContaining({
+ claimId: 'another-process', uncertain: true, receipt: expect.stringContaining('no local receipt'),
+ })])
+ expect(t.saved().entries.delivery).toMatchObject({ claimId: 'another-process', stage: 'uncertain' })
+ expect(t.core.turns.cancelDelivery).toHaveBeenCalledWith('team:service:superTabs:delivery')
+ expect(t.core.turns.leaseDeliveries).toHaveBeenLastCalledWith('superTabs', {})
+ expect(vi.mocked(t.call).mock.calls.some(([, , body]) => (body as any)?.type === 'claim')).toBe(false)
+ vi.mocked(t.core.agents.byAgent).mockReturnValue(undefined)
+ await host.tick()
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ })
+
+ it('retains a recovered claim across another lost acknowledgement and restart', async () => {
+ const t = setup(), first = t.open()
+ t.foreignClaim()
+ const original = vi.mocked(t.call).getMockImplementation()!
+ vi.mocked(t.call).mockImplementation(async (...args) => {
+ const result = await original(...args)
+ if ((args[2] as any)?.type === 'ack') throw new Error('Lost reply')
+ return result
+ })
+ await first.tick()
+ const receipt = t.saved().entries.delivery.receipt
+ first.stop()
+ vi.mocked(t.call).mockImplementation(original)
+ await t.open().tick()
+ expect(t.receipts).toEqual([
+ { type: 'ack', claimId: 'another-process', uncertain: true, receipt },
+ { type: 'ack', claimId: 'another-process', uncertain: true, receipt },
+ ])
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ })
+
+ it('preserves an existing uncertain native receipt when its journal is missing', async () => {
+ const t = setup(), host = t.open()
+ const original = vi.mocked(t.call).getMockImplementation()!
+ vi.mocked(t.call).mockImplementation(async (...args) => args[0] === 'GET' && args[1].endsWith('/deliveries')
+ ? { status: 200, body: { data: [{ id: 'delivery', status: 'uncertain', claimId: 'old-claim', receipt: 'Native paste was ambiguous.' }] } }
+ : original(...args))
+ await host.tick()
+ expect(t.saved().entries.delivery).toMatchObject({ claimId: 'old-claim', stage: 'uncertain', receipt: 'Native paste was ambiguous.' })
+ expect(t.receipts).toEqual([])
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ })
+
+ it('refuses to type without a durable local intent or the core guard', async () => {
+ const t = setup(), host = t.open()
+ vi.mocked(t.core.turns.leaseDeliveries).mockResolvedValue(false)
+ await host.tick()
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ host.stop()
+ expect(() => new SuperTabHost(t.core, 'machine-1', { write: () => { throw new Error('Disk full') } })).toThrow('Disk full')
+ writeFileSync(hostJournalFile(t.dir, 'machine-1'), 'not json')
+ expect(() => t.open()).toThrow()
+ })
+
+ it('preserves the backend error code and never treats an error body as an empty roster', async () => {
+ const t = setup()
+ t.revoke()
+ await expect(backend(t.core, 'GET', '/api/super-tabs/tab')).rejects.toMatchObject({ code: 'FORBIDDEN', status: 403 })
+ })
+})
+
+it('confirms a stopped assignment only with fresh native evidence, including after contribution removal', async () => {
+ const t = setup()
+ const stopped = vi.fn(async (id: string) => id === 'gone')
+ t.core.agents.stopped = stopped
+ const proof: unknown[] = []
+ vi.mocked(t.core.account.backend).mockImplementation(async (method, path, body) => {
+ if (method === 'GET') return { status: 200, body: { data: [
+ { tabId: 'tab', assignmentId: 'work-1', harnessId: 'gone' },
+ { tabId: 'tab', assignmentId: 'work-2', harnessId: 'unconfirmed' },
+ { tabId: '', assignmentId: 'bad', harnessId: 'gone' },
+ ] } }
+ expect(path).toBe('/api/super-tabs/tab/stopped'); proof.push(body)
+ return { status: 200, body: { data: { confirmed: true } } }
+ })
+ const host = t.open()
+ await host.reconcileStops()
+ expect(proof).toEqual([{ assignmentId: 'work-1', receipt: 'native-stopped:machine-1:gone:work-1' }])
+ await host.reconcileStops()
+ expect(proof).toHaveLength(1)
+ host.stop()
+ await host.reconcileStops()
+ expect(proof).toHaveLength(1)
+})
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
new file mode 100644
index 000000000..58ec0e358
--- /dev/null
+++ b/cli/src/superTabs/host.ts
@@ -0,0 +1,358 @@
+import { publishObservers } from './observers.js'
+import { configurationObservation } from './configuration.js'
+import { NativeRecorder, nativeJournalFile } from './native.js'
+import { randomUUID } from 'node:crypto'
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import type { CoreApi, TurnDelivery } from '../core/api.js'
+import { shellQuote } from '../orchestrator/prompts.js'
+
+type Json = Record<string, unknown>
+export class SuperTabHostError extends Error {
+ constructor(readonly code: string, message: string, readonly status = 503) { super(message) }
+}
+export { identifier, object } from './wire.js'
+import { identifier, object } from './wire.js'
+
+/** The core signs each request. Neither the service nor its journal holds an account credential. */
+export async function backend(core: CoreApi, method: string, path: string, body?: unknown): Promise<unknown> {
+ const reply = await core.account.backend(method, path, body)
+ if (reply.status < 200 || reply.status >= 300 || reply.body.success === false) {
+ const error = object(reply.body.error)
+ throw new SuperTabHostError(String(error.code ?? reply.body.code ?? 'BACKEND_UNAVAILABLE'),
+ String(error.message ?? reply.body.message ?? 'Could not reach this Super Tab.'), reply.status)
+ }
+ return reply.body.data
+}
+
+interface Entry {
+ tabId: string
+ agentId: string
+ harnessId: string
+ deliveryId: string
+ claimId: string
+ stage: 'prepared' | 'submitting' | 'delivered' | 'uncertain'
+ receipt?: string
+}
+interface Journal { version: 1; machineId: string; entries: Record<string, Entry> }
+interface HostAgent { tabId: string; agent: { id: string; harnessId: string; machineId: string } }
+export interface SuperTabHostOptions {
+ now?: () => number
+ write?: (file: string, journal: Journal) => void
+ log?: (message: string) => void
+ observers?: typeof publishObservers
+}
+
+export const hostJournalFile = (dataDir: string, machineId: string) => join(dataDir, 'super-tabs', `host-${machineId}.json`)
+const typedId = (entry: Entry) => `team:service:superTabs:${entry.deliveryId}`
+const writeJournal = (file: string, journal: Journal) => {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ const temporary = `${file}.next`
+ writeFileSync(temporary, JSON.stringify(journal), { mode: 0o600, flush: true })
+ renameSync(temporary, file)
+}
+
+/** Owns only the handoff between a durable backend claim and the core's native input.
+ * A process restart never interprets a lost acknowledgement as permission to type twice. */
+export class SuperTabHost {
+ private readonly file: string
+ private readonly journal: Journal
+ private readonly now: () => number
+ private readonly write: (file: string, journal: Journal) => void
+ private readonly log: (message: string) => void
+ private readonly observers: typeof publishObservers
+ private readonly active = new Set<string>()
+ private readonly authorized = new Map<string, number>()
+ private readonly stopHearing: () => void
+ private stopped = false
+ private running: Promise<void> | null = null
+ private stopsRunning: Promise<void> | null = null
+ private nextStopsAt = 0
+ private receiptsRunning: Promise<void> | null = null
+ private nextReceiptsAt = 0
+ private receiptCursor = 0
+ private configurationsRunning: Promise<void> | null = null
+ private nextConfigurationsAt = 0
+ private timer: ReturnType<typeof setTimeout> | null = null
+ private native: NativeRecorder | null = null
+
+ constructor(private readonly core: CoreApi, readonly machineId: string, options: SuperTabHostOptions = {}) {
+ if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')
+ this.file = hostJournalFile(core.dataDir, machineId)
+ this.observers = options.observers ?? publishObservers
+ this.now = options.now ?? Date.now
+ this.write = options.write ?? writeJournal
+ this.log = options.log ?? (message => console.warn(`[super-tabs] ${message}`))
+ this.journal = { version: 1, machineId, entries: {} }
+ if (existsSync(this.file)) {
+ const raw = readFileSync(this.file, 'utf8')
+ if (raw.length > 4 * 1024 * 1024) throw new Error('Super Tab host journal is too large. Reconcile it before resuming.')
+ const saved = object(JSON.parse(raw))
+ if (saved.version !== 1 || saved.machineId !== machineId || !saved.entries || typeof saved.entries !== 'object') {
+ throw new Error('Super Tab host journal is unreadable. Reconcile it before resuming.')
+ }
+ for (const [id, value] of Object.entries(saved.entries)) {
+ const e = object(value)
+ if (id !== e.deliveryId || ![e.tabId, e.agentId, e.harnessId, e.deliveryId, e.claimId].every(identifier)
+ || !['prepared', 'submitting', 'delivered', 'uncertain'].includes(String(e.stage))) throw new Error('Invalid Super Tab delivery receipt.')
+ const entry = e as unknown as Entry
+ // The old process may have typed it, even when it never heard the core's receipt.
+ if (entry.stage === 'submitting') {
+ entry.stage = 'uncertain'
+ entry.receipt = 'The host restarted before native delivery was confirmed. Inspect the session before retrying.'
+ }
+ this.journal.entries[id] = entry
+ }
+ }
+ this.persist()
+ this.stopHearing = core.turns.onDelivery(event => this.heard(event))
+ if (existsSync(nativeJournalFile(core.dataDir, machineId))) {
+ try { this.native = new NativeRecorder(core, machineId) } catch (error) { this.log(String(error)) }
+ }
+ }
+
+ private persist(): void { this.write(this.file, this.journal) }
+ start(): void {
+ if (this.stopped || this.timer) return
+ this.timer = setInterval(() => { void this.tick(); void this.reconcileStops(); void this.reconcileReceipts(); this.recordNative() }, 1_000)
+ this.timer.unref?.()
+ void this.tick()
+ void this.reconcileStops()
+ void this.reconcileReceipts()
+ this.recordNative()
+ }
+ stop(): void {
+ this.stopped = true
+ if (this.timer) clearInterval(this.timer)
+ this.timer = null
+ this.stopHearing()
+ this.native?.stop()
+ this.authorized.clear()
+ try { this.observers(this.core.dataDir, this.machineId, [], 0) } catch { /* The old snapshot expires. */ }
+ void this.core.turns.leaseDeliveries('superTabs', {})
+ for (const id of this.active) this.core.turns.cancelDelivery(id)
+ this.active.clear()
+ }
+ prepareNative(tabId: unknown, contextId: unknown, renew: boolean, closed?: AbortSignal) {
+ this.native ??= new NativeRecorder(this.core, this.machineId)
+ return this.native.prepare(tabId, contextId, renew, closed)
+ }
+ private recordNative(): void {
+ if (!this.native?.hasWork || this.stopped) return
+ const failed = (error: unknown) => this.log(error instanceof Error ? error.message : String(error))
+ void this.native.capture().catch(failed)
+ void this.native.flush().catch(failed)
+ }
+ tick(): Promise<void> {
+ if (this.stopped) return Promise.resolve()
+ return this.running ??= this.poll().catch(error => {
+ this.log(error instanceof Error ? error.message : String(error))
+ }).finally(() => { this.running = null })
+ }
+
+ /** A saved native stop, never a timeout or missing live snapshot, releases
+ * ownership. This also runs for contributions withdrawn while working. */
+ reconcileStops(): Promise<void> {
+ if (this.stopped || !this.core.agents.stopped || this.now() < this.nextStopsAt) return Promise.resolve()
+ return this.stopsRunning ??= this.checkStops().catch(error => {
+ this.log(error instanceof Error ? error.message : String(error))
+ }).finally(() => { this.stopsRunning = null; this.nextStopsAt = this.now() + 5_000 })
+ }
+ private async checkStops(): Promise<void> {
+ const rows = await backend(this.core, 'GET', `/api/super-tabs/hosts/${this.machineId}/assignments`)
+ if (!Array.isArray(rows)) throw new Error('Invalid Super Tab execution list.')
+ for (const value of rows) {
+ if (this.stopped) return
+ const work = object(value)
+ if (![work.tabId, work.assignmentId, work.harnessId].every(identifier)) continue
+ if (!await this.core.agents.stopped!(String(work.harnessId)) || this.stopped) continue
+ await backend(this.core, 'POST', `/api/super-tabs/${work.tabId}/stopped`, {
+ assignmentId: work.assignmentId,
+ receipt: `native-stopped:${this.machineId}:${work.harnessId}:${work.assignmentId}`,
+ })
+ }
+ }
+
+ /** Retire local intent only after an authoritative terminal delivery state.
+ * This runs independently so a slow receipt lookup cannot stall live leases. */
+ reconcileReceipts(): Promise<void> {
+ if (this.stopped || this.now() < this.nextReceiptsAt) return Promise.resolve()
+ return this.receiptsRunning ??= this.checkReceipts().catch(error => {
+ this.log(error instanceof Error ? error.message : String(error))
+ }).finally(() => { this.receiptsRunning = null; this.nextReceiptsAt = this.now() + 5_000 })
+ }
+ private async checkReceipts(): Promise<void> {
+ const pending = Object.values(this.journal.entries).filter(e => e.stage === 'uncertain' || e.stage === 'delivered')
+ for (let i = 0; i < Math.min(pending.length, 20); i++) {
+ if (this.stopped) return
+ const entry = pending[(this.receiptCursor++) % pending.length]
+ try {
+ const result = object(await backend(this.core, 'GET', `/api/super-tabs/${entry.tabId}/agents/${entry.agentId}/deliveries/${entry.deliveryId}`))
+ if (this.stopped) return
+ if (result.id !== entry.deliveryId || !['delivered', 'confirmed', 'superseded', 'cancelled'].includes(String(result.status))) continue
+ if (this.journal.entries[entry.deliveryId] !== entry || this.active.has(typedId(entry))) continue
+ delete this.journal.entries[entry.deliveryId]
+ this.persist()
+ } catch { /* Missing authority or a network failure is not a receipt. */ }
+ }
+ }
+
+ private async leases(): Promise<boolean> {
+ return this.core.turns.leaseDeliveries('superTabs', Object.fromEntries(this.authorized))
+ }
+ private async poll(): Promise<void> {
+ const requestedAt = this.now()
+ const data = await backend(this.core, 'GET', `/api/super-tabs/hosts/${this.machineId}`)
+ if (this.stopped) return
+ if (!Array.isArray(data)) throw new Error('Invalid Super Tab host roster.')
+ this.observers(this.core.dataDir, this.machineId, data, requestedAt + 2500)
+ // Runtime observations cannot delay the live input leases. A stale host
+ // observation is fenced by the backend's per-agent configuration version.
+ if (!this.configurationsRunning && this.now() >= this.nextConfigurationsAt) {
+ this.configurationsRunning = this.recordConfigurations(data).finally(() => {
+ this.configurationsRunning = null
+ this.nextConfigurationsAt = this.now() + 5_000
+ })
+ }
+ const seen = new Set<string>()
+ for (const item of data) {
+ const row = object(item), agent = object(row.agent)
+ if (!identifier(row.tabId) || !identifier(agent.id) || !identifier(agent.harnessId) || agent.machineId !== this.machineId) continue
+ const target = row as unknown as HostAgent
+ // Never adopt another live session as a replacement for the recorded harness.
+ if (!this.core.agents.byAgent(target.agent.harnessId) || !this.core.agents.terminalAvailable(target.agent.harnessId)) continue
+ const path = `/api/super-tabs/${target.tabId}/agents/${target.agent.id}/deliveries`
+ try {
+ const deliveries = await backend(this.core, 'GET', path)
+ if (this.stopped) return
+ if (!Array.isArray(deliveries)) throw new Error('Invalid Super Tab delivery list.')
+ for (const item of deliveries) {
+ const delivery = object(item)
+ if (!identifier(delivery.id)) continue
+ seen.add(delivery.id)
+ await this.accept(target, delivery, path)
+ }
+ } catch (error) {
+ // Authority checks and network failures both withhold input. A later fresh read may grant it again.
+ this.log(error instanceof Error ? error.message : String(error))
+ }
+ }
+ if (this.stopped) return
+ for (const entry of Object.values(this.journal.entries)) {
+ const id = typedId(entry)
+ if (!seen.has(entry.deliveryId)) {
+ this.authorized.delete(id)
+ if (this.active.delete(id)) {
+ entry.stage = 'uncertain'
+ entry.receipt = 'Authority or the recorded native session became unavailable. Inspect the session before retrying.'
+ this.persist()
+ this.core.turns.cancelDelivery(id)
+ }
+ }
+ }
+ await this.leases()
+ }
+
+ private async accept(target: HostAgent, delivery: Json, path: string): Promise<void> {
+ const deliveryId = delivery.id as string
+ let entry = this.journal.entries[deliveryId]
+ if (!entry) {
+ if (Object.keys(this.journal.entries).length >= 1_000) throw new Error('Reconcile pending Super Tab deliveries before accepting more.')
+ if (delivery.claimId && !identifier(delivery.claimId)) throw new Error('Invalid Super Tab delivery claim.')
+ // Losing the host journal cannot turn a backend claim into fresh input.
+ // Retain its identity and expose the uncertainty for a human to resolve;
+ // this neither takes over its execution nor says whether it was written.
+ entry = { tabId: target.tabId, agentId: target.agent.id, harnessId: target.agent.harnessId,
+ deliveryId, claimId: delivery.claimId as string || randomUUID(),
+ stage: delivery.claimId ? 'uncertain' : 'prepared',
+ ...(delivery.claimId ? { receipt: delivery.status === 'uncertain' && typeof delivery.receipt === 'string' && delivery.receipt
+ ? delivery.receipt
+ : 'The host has no local receipt for this claimed instruction. Inspect the native session before confirming or resending it.' } : {}) }
+ this.journal.entries[deliveryId] = entry
+ this.persist()
+ if (delivery.claimId) this.core.turns.cancelDelivery(typedId(entry))
+ }
+ const id = typedId(entry)
+ if (entry.stage === 'submitting' && !this.active.has(id)) {
+ entry.stage = 'uncertain'
+ entry.receipt = 'Native submission was interrupted. Inspect the session before retrying.'
+ this.persist()
+ }
+ if (entry.stage === 'delivered' || entry.stage === 'uncertain') {
+ if (delivery.status === 'uncertain' && delivery.receipt === entry.receipt) return
+ await backend(this.core, 'POST', `${path}/${deliveryId}`, { type: 'ack', claimId: entry.claimId,
+ receipt: entry.receipt, uncertain: entry.stage === 'uncertain' })
+ if (entry.stage === 'delivered') { delete this.journal.entries[deliveryId]; this.persist() }
+ this.authorized.delete(id)
+ return
+ }
+ if (this.active.has(id)) {
+ this.authorized.set(id, this.now() + 2_500)
+ return
+ }
+ const result = object(await backend(this.core, 'POST', `${path}/${deliveryId}`, { type: 'claim', claimId: entry.claimId }))
+ if (this.stopped) return
+ const message = object(result.message)
+ if (typeof message.text !== 'string' || !identifier(message.conversationId)) throw new Error('The delivery has no message.')
+ this.authorized.set(id, this.now() + 2_500)
+ if (!(await this.leases()) || this.stopped) { this.authorized.delete(id); return }
+ if (this.active.has(id)) return
+ // The durable intent must exist before the core can write. A thrown disk write must not deliver.
+ entry.stage = 'submitting'
+ this.persist()
+ this.active.add(id)
+ this.core.turns.deliver(entry.harnessId, this.prompt(entry, message), id)
+ }
+
+ private async recordConfigurations(rows: unknown[]): Promise<void> {
+ for (const row of rows) {
+ if (this.stopped) return
+ try {
+ const observation = configurationObservation(this.core, this.machineId, row)
+ if (observation) await backend(this.core, 'POST', observation.path, observation.body)
+ } catch (error) {
+ this.log(error instanceof Error ? error.message : String(error))
+ }
+ }
+ }
+
+ private prompt(entry: Entry, message: Json): string {
+ const command = `${this.core.daemon.command} super-tab --port ${this.core.daemon.port} --machine ${shellQuote(this.machineId)} --tab ${shellQuote(entry.tabId)} --agent ${shellQuote(entry.agentId)}`
+ const group = message.conversationId as string
+ const reply = identifier(message.replyTo)
+ ? `In reply to message ${message.replyTo}. Read it before interpreting the answer: ${command} message ${shellQuote(group)} ${shellQuote(message.replyTo)}\n\n`
+ : ''
+ const source = object(message.source)
+ const native = source.kind === 'native'
+ ? `This is an observed native ${String(source.phase)} in ${String(object(message.author).name ?? 'an agent')}’s terminal, opened by ${String(object(source.operator).name ?? 'a collaborator')}. The input already reached that agent. Keep the shared work coordinated; do not replay the same instruction.\n\n`
+ : ''
+ return `You are participating in a shared Super Tab conversation (${group}). Other humans and agents see messages posted there.\n`
+ + `Read its state: ${command} status\nRead this conversation: ${command} messages ${shellQuote(group)}\n`
+ + `Reply there: ${command} post ${shellQuote(group)} 'your message' UNIQUE_OPERATION_ID\n`
+ + `Manage agreed work and delegation: ${command} help. Use independently verifiable outcomes; local helper subagents need no separate group.\n`
+ + `Ask questions and post results in this conversation. Include the exact revision, evidence and usable output links. Replies to these delivered instructions must be posted here explicitly.\n\n`
+ + native + reply + `Message ${String(message.id)} from ${String(object(message.author).name ?? 'a collaborator')}:\n${message.text}`
+ }
+
+ private heard(event: TurnDelivery): void {
+ const entry = Object.values(this.journal.entries).find(e => typedId(e) === event.deliveryId)
+ if (this.stopped || !entry || event.sessionId !== entry.harnessId || !this.active.has(event.deliveryId)) return
+ if (event.state === 'queued') return
+ this.active.delete(event.deliveryId)
+ this.authorized.delete(event.deliveryId)
+ if (event.state === 'rejected' && event.reason?.startsWith('team_waiting_')) {
+ // The core explicitly withheld the terminal write (busy, human draft, or
+ // expired authority). A later fresh check may retry the same claim safely.
+ entry.stage = 'prepared'
+ delete entry.receipt
+ } else {
+ entry.stage = event.state === 'delivered' || event.state === 'started' ? 'delivered' : 'uncertain'
+ entry.receipt = `${event.state}: ${event.reason ?? 'Native session input receipt'}`.slice(0, 2000)
+ }
+ try { this.persist() } catch (error) {
+ // The on-disk 'submitting' intent remains the truth if saving its outcome failed.
+ this.log(error instanceof Error ? error.message : String(error))
+ }
+ void this.leases()
+ }
+}
diff --git a/cli/src/superTabs/native.spec.ts b/cli/src/superTabs/native.spec.ts
new file mode 100644
index 000000000..edc8c047c
--- /dev/null
+++ b/cli/src/superTabs/native.spec.ts
@@ -0,0 +1,213 @@
+import { createHash } from 'node:crypto'
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { createNativeTurnObservations } from '../lib/nativeTurnObservations.js'
+import { NativeRecorder, nativeJournalFile } from './native.js'
+
+const roots: string[] = []
+afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
+const alpha = 'context_alpha_123456', beta = 'context_beta_1234567'
+function setup() {
+ const root = mkdtempSync(join(tmpdir(), 'super-tab-native-')); roots.push(root)
+ let now = 100, revoked = false, loseReply = false
+ const observer = createNativeTurnObservations({ resolve: () => ({ sessionId: 'session', engine: 'codex', runtime: 'runtime' }), now: () => 100 })
+ const contexts = new Map<string, { lastEventId: string | null }>([[alpha, { lastEventId: null }], [beta, { lastEventId: null }]])
+ const records = new Map<string, Record<string, unknown>>(), sent: Record<string, unknown>[] = []
+ const backend = vi.fn(async (method: string, path: string, body?: unknown) => {
+ if (revoked) return { status: 403, body: { success: false, error: { code: 'NATIVE_CONTEXT_REVOKED', message: 'Removed' } } }
+ const id = path.split('/').at(-1)!, context = contexts.get(id)!
+ if (method === 'GET') return { status: 200, body: { data: { contextId: id, tabId: 'tab', machineId: 'machine-1', harnessId: 'harness', ...context } } }
+ const value = body as Record<string, unknown>
+ sent.push(value)
+ const eventId = createHash('sha256').update(JSON.stringify(['native-event', id, value.turnId, value.kind])).digest('hex').slice(0, 24)
+ if (records.has(eventId)) expect(records.get(eventId)).toEqual(value)
+ else {
+ expect(value.previousEventId).toBe(context.lastEventId)
+ records.set(eventId, value); context.lastEventId = eventId
+ }
+ if (loseReply) { loseReply = false; return { status: 503, body: { success: false } } }
+ return { status: 200, body: { data: { eventId } } }
+ })
+ const core = fakeCore({ dataDir: root, account: { backend }, agents: { byAgent: vi.fn(() => ({ agentId: 'harness' }) as never) },
+ transcripts: { nativeTurns: vi.fn(async (id, cursor) => observer.read(id, cursor)) } })
+ const open = () => new NativeRecorder(core, 'machine-1', { now: () => now })
+ const file = nativeJournalFile(root, 'machine-1')
+ const prompt = (text: string, context: string | null = alpha) => {
+ observer.typed('harness', context, true)
+ observer.ingest('harness', [{ type: 'turn_started', payload: { userMessage: text } }])
+ }
+ const answer = (text: string) => observer.ingest('harness', [{ type: 'text_delta', payload: { content: text } }, { type: 'turn_ended', payload: {} }])
+ const saved = () => JSON.parse(readFileSync(file, 'utf8'))
+ return { core, open, observer, backend, sent, records, prompt, answer, saved, file, contexts,
+ time: (value: number) => { now = value }, revoke: () => { revoked = true }, lose: () => { loseReply = true } }
+}
+
+describe('durable native conversation recording', () => {
+ it('starts at the current boundary and records only the prepared conversation, without writing native input', async () => {
+ const t = setup(), host = t.open()
+ t.observer.read('harness'); t.prompt('Private history'); t.answer('Private answer')
+ expect(await host.prepare('tab', alpha)).toEqual({ ok: true, inputContext: alpha })
+ t.prompt('Shared input'); t.answer('Shared answer')
+ t.prompt('Another conversation', beta); t.answer('Not shared here')
+ await host.capture()
+ expect(t.sent).toEqual([])
+ expect(t.saved().agents.harness.outbox.map((e: { text: string }) => e.text)).toEqual(['Shared input', 'Shared answer'])
+ await host.flush()
+ expect(t.sent.map(e => e.text)).toEqual(['Shared input', 'Shared answer'])
+ expect(t.saved().agents.harness.outbox).toEqual([])
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ expect(statSync(t.file).mode & 0o777).toBe(0o600)
+ const unchanged = statSync(t.file).mtimeMs
+ await host.capture()
+ expect(statSync(t.file).mtimeMs).toBe(unchanged)
+ })
+
+ it('reports ambiguous native activity without exporting its content or treating ordinary deliveries as gaps', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha)
+ t.observer.submitting('harness')
+ t.observer.ingest('harness', [{ type: 'turn_started', payload: { userMessage: 'Ordinary delivered instruction' } }, { type: 'turn_ended', payload: {} }])
+ await host.capture(); await host.flush()
+ expect(t.sent).toEqual([])
+ t.prompt('Unknown person and conversation', null); t.answer('Do not expose this answer')
+ await host.capture(); await host.flush()
+ expect(t.sent).toEqual([expect.objectContaining({ kind: 'gap', text: '' })])
+ })
+
+ it('replays an identical saved observation after a lost backend acknowledgement and restart', async () => {
+ const t = setup(), first = t.open()
+ await first.prepare('tab', alpha); t.prompt('One input'); t.answer('One answer'); await first.capture()
+ t.lose(); await expect(first.flush()).rejects.toThrow(); first.stop()
+ const restarted = t.open(); await restarted.capture(); await restarted.flush()
+ expect(t.sent).toHaveLength(3)
+ expect(t.sent[0]).toEqual(t.sent[1])
+ expect(t.records.size).toBe(2)
+ expect(t.saved().agents.harness.outbox).toEqual([])
+ })
+
+ it('keeps capturing while the network is slow and preserves the global observation order across contexts', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha); await host.prepare('tab', beta)
+ t.prompt('First'); t.answer('First answer'); await host.capture()
+ const implementation = t.backend.getMockImplementation()!
+ let release!: () => void
+ const gate = new Promise<void>(resolve => { release = resolve })
+ t.backend.mockImplementationOnce(async (...args) => { await gate; return implementation(...args) })
+ const sending = host.flush()
+ t.prompt('Second', beta); t.answer('Second answer'); await host.capture()
+ expect(t.saved().agents.harness.outbox).toHaveLength(4)
+ release(); await sending
+ expect(t.sent.map(e => e.text)).toEqual(['First', 'First answer', 'Second', 'Second answer'])
+ })
+
+ it('retains the old cursor if its durable write fails', async () => {
+ const t = setup(), first = t.open()
+ await first.prepare('tab', alpha); first.stop()
+ const before = t.saved().agents.harness.cursor
+ const failed = new NativeRecorder(t.core, 'machine-1', { write: () => { throw new Error('Disk full') } })
+ t.prompt('Recover after storage failure'); t.answer('Recovered answer')
+ await expect(failed.capture()).rejects.toThrow('Disk full')
+ expect(t.saved().agents.harness.cursor).toEqual(before)
+ expect(t.sent).toEqual([])
+ failed.stop()
+ const restarted = t.open(); await restarted.capture(); await restarted.flush()
+ expect(t.sent.map(e => e.text)).toEqual(['Recover after storage failure', 'Recovered answer'])
+ })
+
+ it('reports discontinuity explicitly and does not send an answer without its prompt', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha)
+ t.prompt('Before restart'); await host.capture(); await host.flush()
+ t.observer.ingest('harness', [], true)
+ await host.capture(); await host.flush()
+ expect(t.sent.map(e => e.kind)).toEqual(['prompt', 'gap'])
+ t.prompt('After restart'); t.answer('After restart answer'); await host.capture(); await host.flush()
+ expect(t.sent.map(e => e.kind)).toEqual(['prompt', 'gap', 'prompt', 'answer'])
+ })
+
+ it('finishes an already observed turn after closing the view, then stops observing the idle terminal', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha); t.prompt('Long task'); await host.capture(); await host.flush()
+ t.time(100_000); t.answer('Completed after the view closed'); await host.capture(); await host.flush(); await host.capture()
+ expect(t.sent.map(e => e.kind)).toEqual(['prompt', 'answer'])
+ expect(t.saved().agents).toEqual({})
+ await expect(host.prepare('tab', alpha, true)).rejects.toThrow('expired')
+ })
+
+ it('withholds revoked content, refuses the old context and never turns it into native input', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha); t.prompt('Pending private observation'); await host.capture()
+ t.revoke(); await expect(host.flush()).rejects.toThrow('Removed')
+ expect(t.saved().agents.harness.outbox).toEqual([])
+ expect(t.saved().agents.harness.contexts[alpha].blocked).toContain('recording stopped')
+ await expect(host.prepare('tab', alpha, true)).rejects.toThrow('Removed')
+ expect(t.core.turns.deliver).not.toHaveBeenCalled()
+ })
+
+ it('retires a confirmed stopped harness after reporting any unfinished recorded turn', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha); t.prompt('Interrupted task'); await host.capture(); await host.flush()
+ vi.mocked(t.core.transcripts.nativeTurns!).mockResolvedValue(null)
+ t.core.agents.stopped = vi.fn(async () => ({ agentId: 'harness' }) as never)
+ await host.capture(); await host.flush(); await host.capture()
+ expect(t.sent.map(e => e.kind)).toEqual(['prompt', 'gap'])
+ expect(host.hasWork).toBe(false)
+ expect(t.saved().agents).toEqual({})
+ })
+
+ it('reports unread activity after a lease expires and retires old views while another stays open', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha)
+ t.prompt('Cannot establish when this delayed input arrived'); t.answer('Do not silently lose this boundary')
+ t.time(100_000)
+ await expect(host.prepare('tab', alpha, true)).rejects.toThrow('expired')
+ await host.prepare('tab', beta)
+ await host.capture(); await host.flush(); await host.capture()
+ expect(t.sent).toEqual([expect.objectContaining({ kind: 'gap', text: '' })])
+ expect(Object.keys(t.saved().agents.harness.contexts)).toEqual([beta])
+ t.prompt('Current conversation', beta); t.answer('Still recorded')
+ await host.capture(); await host.flush()
+ expect(t.sent.map(e => e.kind)).toEqual(['gap', 'prompt', 'answer'])
+ })
+
+ it('refuses lost, corrupt or replaced journals and a disconnected host', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha)
+ rmSync(t.file)
+ await expect(host.capture()).rejects.toThrow('missing')
+ expect(() => t.open()).toThrow('missing')
+ writeFileSync(t.file, '{}')
+ await expect(host.capture()).rejects.toThrow('replaced')
+ expect(() => t.open()).toThrow('Invalid')
+ host.stop(); await expect(host.prepare('tab', alpha)).rejects.toThrow('disconnected')
+ })
+
+ it('refuses an in-place journal change even when the filesystem identity is unchanged', async () => {
+ const t = setup(), host = t.open()
+ await host.prepare('tab', alpha)
+ const original = readFileSync(t.file, 'utf8'), inode = statSync(t.file).ino
+ writeFileSync(t.file, `${original}\n`)
+ expect(statSync(t.file).ino).toBe(inode)
+ await expect(host.capture()).rejects.toThrow('changed')
+ await expect(host.prepare('tab', alpha, true)).rejects.toThrow('changed')
+ expect(t.sent).toEqual([])
+ })
+
+ it('checks the exact execution machine, native support, cancellation and renewal', async () => {
+ const t = setup(), host = t.open()
+ await expect(host.prepare('../wrong', alpha)).rejects.toThrow('no longer')
+ const aborted = new AbortController(); aborted.abort()
+ await expect(host.prepare('tab', alpha, false, aborted.signal)).rejects.toThrow('no longer')
+ t.backend.mockResolvedValueOnce({ status: 200, body: { data: { contextId: alpha, machineId: 'elsewhere' } } } as never)
+ await expect(host.prepare('tab', alpha)).rejects.toThrow('exact contributed terminal')
+ vi.mocked(t.core.transcripts.nativeTurns!).mockResolvedValueOnce(null)
+ await expect(host.prepare('tab', alpha)).rejects.toThrow('Update')
+ await host.prepare('tab', alpha)
+ t.time(80_000); await host.prepare('tab', alpha, true); t.time(100_000)
+ t.prompt('Still open'); t.answer('Recorded'); await host.capture(); await host.flush()
+ expect(t.sent).toHaveLength(2)
+ })
+})
diff --git a/cli/src/superTabs/native.ts b/cli/src/superTabs/native.ts
new file mode 100644
index 000000000..9b5c4ed07
--- /dev/null
+++ b/cli/src/superTabs/native.ts
@@ -0,0 +1,272 @@
+import { createHash, randomUUID } from 'node:crypto'
+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync, type BigIntStats } from 'node:fs'
+import { dirname, join } from 'node:path'
+import type { CoreApi } from '../core/api.js'
+import { nativeTurnCursorIn, type NativeTurnCursor, type NativeTurnObservation } from '../lib/nativeTurnObservations.js'
+import { backend, SuperTabHostError } from './host.js'
+import { identifier, object } from './wire.js'
+
+interface Context {
+ tabId: string; baseline: NativeTurnCursor; until: number; head: string | null; blocked?: string
+}
+interface Event {
+ contextId: string; turnId: string; kind: 'prompt' | 'answer' | 'gap'; previousEventId: string | null
+ text: string; truncated: boolean; interrupted: boolean
+}
+interface RecordedAgent {
+ cursor: NativeTurnCursor; contexts: Record<string, Context>; turns: Record<string, string>; outbox: Event[]
+}
+interface Journal { version: 1; machineId: string; agents: Record<string, RecordedAgent> }
+const MAX_BYTES = 8 * 1024 * 1024, MAX_EVENTS = 1024, CONTEXT_LEASE = 90_000
+// An unlinked file's inode can be reused immediately on Linux. Include change
+// metadata so replacement or an in-place edit cannot revive stale journal state.
+const journalIdentity = (stat: BigIntStats) => `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`
+const eventId = (event: Event) => createHash('sha256').update(JSON.stringify(['native-event', event.contextId, event.turnId, event.kind])).digest('hex').slice(0, 24)
+export const nativeJournalFile = (dataDir: string, machineId: string) => join(dataDir, 'super-tabs', `native-${machineId}.json`)
+const validIdOrNull = (value: unknown) => value === null || identifier(value)
+const copyEvent = (event: NativeTurnObservation): Omit<Event, 'contextId' | 'previousEventId'> => ({
+ turnId: event.turnId, kind: event.kind, text: event.text, truncated: event.truncated, interrupted: event.interrupted,
+})
+
+/** Durable conversation recording stays outside the core. Capturing a bounded
+ * page never waits for the backend; flushing the outbox never writes into an agent. */
+export class NativeRecorder {
+ private journal: Journal
+ private readonly file: string
+ private stopped = false
+ private capturing: Promise<void> = Promise.resolve()
+ private flushing: Promise<void> | null = null
+ private captureRunning: Promise<void> | null = null
+ private identity: string | null = null
+ private readonly now: () => number
+ private readonly write: (file: string, value: string) => void
+ constructor(private readonly core: CoreApi, private readonly machineId: string, options: {
+ now?: () => number; write?: (file: string, value: string) => void
+ } = {}) {
+ if (!identifier(machineId)) throw new Error('This machine is unavailable.')
+ this.now = options.now ?? Date.now
+ this.file = nativeJournalFile(core.dataDir, machineId)
+ this.write = options.write ?? ((file, value) => {
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
+ const temporary = `${file}.${randomUUID()}.next`
+ writeFileSync(temporary, value, { mode: 0o600, flush: true, flag: 'wx' })
+ renameSync(temporary, file)
+ writeFileSync(`${file}.ready`, '1', { mode: 0o600, flush: true })
+ })
+ this.journal = { version: 1, machineId, agents: {} }
+ if (existsSync(`${this.file}.ready`) && !existsSync(this.file)) throw new Error('The terminal recording journal is missing. Restore it before reconnecting.')
+ if (existsSync(this.file)) {
+ const stat = lstatSync(this.file, { bigint: true })
+ if (!stat.isFile() || stat.size > MAX_BYTES) throw new Error('The terminal recording journal is unavailable.')
+ this.identity = journalIdentity(stat)
+ const saved = object(JSON.parse(readFileSync(this.file, 'utf8')))
+ if (saved.version !== 1 || saved.machineId !== machineId || !saved.agents || typeof saved.agents !== 'object' || Array.isArray(saved.agents)) throw new Error('Invalid terminal recording journal.')
+ for (const [harnessId, value] of Object.entries(object(saved.agents))) {
+ const row = object(value), cursor = nativeTurnCursorIn(row.cursor)
+ if (!identifier(harnessId) || !cursor || !Array.isArray(row.outbox) || row.outbox.length > MAX_EVENTS) throw new Error('Invalid terminal recording cursor.')
+ if (!row.contexts || typeof row.contexts !== 'object' || Array.isArray(row.contexts)
+ || !row.turns || typeof row.turns !== 'object' || Array.isArray(row.turns)) throw new Error('Invalid terminal recording contexts.')
+ const contexts = object(row.contexts), turns = object(row.turns)
+ if (Object.keys(contexts).length > 256 || Object.keys(turns).length > 256) throw new Error('Too many terminal recording contexts.')
+ for (const [id, entry] of Object.entries(contexts)) {
+ const c = object(entry)
+ if (!identifier(id) || !identifier(c.tabId) || !nativeTurnCursorIn(c.baseline) || !Number.isFinite(c.until)
+ || !validIdOrNull(c.head) || (c.blocked !== undefined && typeof c.blocked !== 'string')) throw new Error('Invalid terminal context.')
+ }
+ for (const [id, contextId] of Object.entries(turns)) if (!identifier(id) || !identifier(contextId) || !contexts[contextId]) throw new Error('Invalid terminal turn.')
+ for (const value of row.outbox) {
+ const e = object(value)
+ if (!identifier(e.contextId) || !contexts[e.contextId] || !identifier(e.turnId) || !['prompt', 'answer', 'gap'].includes(String(e.kind))
+ || !validIdOrNull(e.previousEventId) || typeof e.text !== 'string' || e.text.length > 16_000
+ || typeof e.truncated !== 'boolean' || typeof e.interrupted !== 'boolean') throw new Error('Invalid terminal observation.')
+ }
+ }
+ if (Object.keys(object(saved.agents)).length > 128) throw new Error('Too many recorded terminals.')
+ this.journal = saved as unknown as Journal
+ }
+ }
+
+ private available(): void {
+ if (this.stopped || this.core.daemon.machineId() !== this.machineId) throw new Error('This recording host disconnected.')
+ if (existsSync(`${this.file}.ready`) && !existsSync(this.file)) throw new Error('The terminal recording journal is missing.')
+ if (this.identity) {
+ const stat = lstatSync(this.file, { bigint: true })
+ if (!stat.isFile() || journalIdentity(stat) !== this.identity) throw new Error('The terminal recording journal was replaced or changed.')
+ }
+ }
+ private commit(change: (next: Journal) => void): void {
+ this.available()
+ const next = structuredClone(this.journal)
+ change(next)
+ const raw = JSON.stringify(next)
+ if (Buffer.byteLength(raw) > MAX_BYTES) throw new Error('Terminal recording is full. Reconnect after pending observations have synced.')
+ this.write(this.file, raw)
+ const stat = lstatSync(this.file, { bigint: true })
+ this.identity = journalIdentity(stat)
+ this.journal = next
+ }
+ private serial<T>(action: () => Promise<T>): Promise<T> {
+ const next = this.capturing.catch(() => {}).then(action)
+ this.capturing = next.then(() => {}, () => {})
+ return next
+ }
+ stop(): void { this.stopped = true }
+ get hasWork(): boolean { return Object.keys(this.journal.agents).length > 0 }
+
+ prepare(tabId: unknown, contextId: unknown, renew = false, closed?: AbortSignal): Promise<{ ok: true; inputContext: string }> {
+ return this.serial(async () => {
+ this.available()
+ if (!identifier(tabId) || !identifier(contextId) || closed?.aborted) throw new Error('This terminal request is no longer available.')
+ const verified = object(await backend(this.core, 'GET', `/api/super-tabs/${tabId}/native/${contextId}`))
+ this.available()
+ const harnessId = verified.harnessId
+ if (closed?.aborted || verified.contextId !== contextId || verified.tabId !== tabId || verified.machineId !== this.machineId
+ || !identifier(harnessId) || !this.core.agents.byAgent(harnessId) || !validIdOrNull(verified.lastEventId)) {
+ throw new Error('The exact contributed terminal is unavailable on this machine.')
+ }
+ const existing = this.journal.agents[harnessId]?.contexts[contextId]
+ if (existing?.blocked) throw new Error(existing.blocked)
+ if (renew && (!existing || existing.until <= this.now())) throw new Error('Terminal recording expired. Reopen the terminal from this conversation.')
+ const page = await this.core.transcripts.nativeTurns?.(harnessId)
+ this.available()
+ if (!page || closed?.aborted) throw new Error('Update this machine’s Harness to record native terminal conversations.')
+ if (!existing && !this.journal.agents[harnessId] && Object.keys(this.journal.agents).length >= 128) throw new Error('Too many recorded terminals are active.')
+ if (!existing && Object.keys(this.journal.agents[harnessId]?.contexts ?? {}).length >= 256) throw new Error('Too many terminal contexts are active.')
+ this.commit(next => {
+ const row = next.agents[harnessId] ??= { cursor: page.cursor, contexts: {}, turns: {}, outbox: [] }
+ if (existing) row.contexts[contextId]!.until = this.now() + CONTEXT_LEASE
+ else {
+ row.contexts[contextId] = { tabId, baseline: page.cursor, until: this.now() + CONTEXT_LEASE, head: verified.lastEventId as string | null }
+ if (verified.lastEventId) this.enqueue(row, contextId, { turnId: randomUUID(), kind: 'gap', text: '', truncated: false, interrupted: false })
+ }
+ })
+ return { ok: true, inputContext: contextId }
+ })
+ }
+
+ private enqueue(row: RecordedAgent, contextId: string, event: Omit<Event, 'contextId' | 'previousEventId'>): void {
+ if (row.outbox.length >= MAX_EVENTS) throw new Error('The terminal recording outbox is full.')
+ const context = row.contexts[contextId]!
+ const last = row.outbox.findLast(e => e.contextId === contextId)
+ row.outbox.push({ ...event, contextId, previousEventId: last ? eventId(last) : context.head })
+ }
+
+ private expired(row: RecordedAgent): string[] {
+ const retained = new Set([...Object.values(row.turns), ...row.outbox.map(e => e.contextId)])
+ return Object.keys(row.contexts).filter(id => row.contexts[id]!.until <= this.now() && !retained.has(id))
+ }
+ private prune(next: Journal, harnessId: string): void {
+ const row = next.agents[harnessId]!
+ for (const id of this.expired(row)) delete row.contexts[id]
+ if (!Object.keys(row.contexts).length) delete next.agents[harnessId]
+ }
+
+ capture(): Promise<void> {
+ return this.captureRunning ??= this.serial(async () => {
+ this.available()
+ for (const harnessId of Object.keys(this.journal.agents)) {
+ const before = this.journal.agents[harnessId]!
+ // Reserve enough space for a complete bounded core page and one gap per
+ // context. Never acknowledge a partially retained page.
+ if (before.outbox.length + 512 + Object.keys(before.contexts).length > MAX_EVENTS) continue
+ // Read the final boundary before retiring an expired view. A delayed
+ // host must report lost activity instead of silently dropping its cursor.
+ const page = await this.core.transcripts.nativeTurns?.(harnessId, before.cursor)
+ this.available()
+ if (!page) {
+ if (await this.core.agents.stopped?.(harnessId)) {
+ this.commit(next => {
+ const row = next.agents[harnessId]!
+ for (const id of new Set(Object.values(row.turns))) this.enqueue(row, id,
+ { turnId: randomUUID(), kind: 'gap', text: '', truncated: false, interrupted: true })
+ row.turns = {}
+ for (const c of Object.values(row.contexts)) c.until = 0
+ this.prune(next, harnessId)
+ })
+ }
+ continue
+ }
+ if (!page.gap && page.cursor.epoch === before.cursor.epoch && page.cursor.sequence === before.cursor.sequence) {
+ if (this.expired(before).length) this.commit(next => this.prune(next, harnessId))
+ continue
+ }
+ // Store observations and the cursor in the same durable write. A crash
+ // cannot advance the cursor without retaining its unsent records.
+ this.commit(next => {
+ const row = next.agents[harnessId]!
+ const gaps = new Set<string>()
+ const gap = (id: string) => {
+ if (gaps.has(id)) return
+ gaps.add(id)
+ this.enqueue(row, id, { turnId: randomUUID(), kind: 'gap', text: '', truncated: false, interrupted: false })
+ }
+ if (page.gap || page.observations.some(event => event.kind === 'prompt' && event.unattributedInput)) {
+ for (const [id, c] of Object.entries(row.contexts)) {
+ if (!c.blocked) gap(id)
+ }
+ if (page.gap) row.turns = {}
+ }
+ for (const observation of page.observations) {
+ const contextId = observation.inputContext, context = contextId ? row.contexts[contextId] : undefined
+ // Never export a prompt with unknown provenance, or content from a
+ // different conversation that happens to share the same harness.
+ if (!contextId || !context || context.blocked) continue
+ if (context.baseline.epoch === page.cursor.epoch && observation.sequence <= context.baseline.sequence) continue
+ if (observation.kind === 'prompt') {
+ if (context.until <= this.now()) { gap(contextId); continue }
+ row.turns[observation.turnId] = contextId
+ this.enqueue(row, contextId, copyEvent(observation))
+ } else if (row.turns[observation.turnId] === contextId) {
+ this.enqueue(row, contextId, copyEvent(observation))
+ delete row.turns[observation.turnId]
+ } else if (context.until > this.now()) {
+ this.enqueue(row, contextId, { turnId: observation.turnId, kind: 'gap', text: '', truncated: false, interrupted: true })
+ }
+ }
+ row.cursor = page.cursor
+ this.prune(next, harnessId)
+ })
+ }
+ }).finally(() => { this.captureRunning = null })
+ }
+
+ flush(): Promise<void> {
+ if (this.stopped) return Promise.resolve()
+ return this.flushing ??= this.send().finally(() => { this.flushing = null })
+ }
+ private async send(): Promise<void> {
+ let failure: unknown
+ for (const harnessId of Object.keys(this.journal.agents)) {
+ for (let sent = 0; sent < 32; sent++) {
+ this.available()
+ const row = this.journal.agents[harnessId], event = row?.outbox[0]
+ if (!event) break
+ const context = row.contexts[event.contextId]!
+ if (context.blocked) break
+ const { contextId, ...body } = event
+ try {
+ const result = object(await backend(this.core, 'POST', `/api/super-tabs/${context.tabId}/native/${contextId}`, body))
+ this.available()
+ if (result.eventId !== eventId(event)) throw new Error('The backend did not confirm this exact native observation.')
+ this.commit(next => {
+ const current = next.agents[harnessId]!
+ current.contexts[contextId]!.head = result.eventId as string
+ current.outbox.shift()
+ })
+ } catch (error) {
+ if (error instanceof SuperTabHostError && [400, 403, 404, 409].includes(error.status)) {
+ this.commit(next => {
+ const current = next.agents[harnessId]!
+ current.contexts[contextId]!.blocked = 'Terminal recording stopped because access or its recording history changed. Reopen it from the conversation.'
+ current.outbox = current.outbox.filter(e => e.contextId !== contextId)
+ for (const [turnId, id] of Object.entries(current.turns)) if (id === contextId) delete current.turns[turnId]
+ })
+ }
+ failure ??= error
+ break
+ }
+ }
+ }
+ if (failure) throw failure
+ }
+}
diff --git a/cli/src/superTabs/observers.spec.ts b/cli/src/superTabs/observers.spec.ts
new file mode 100644
index 000000000..3a9d082ee
--- /dev/null
+++ b/cli/src/superTabs/observers.spec.ts
@@ -0,0 +1,50 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { expect, it, vi } from 'vitest'
+import { b64e, newEphemeral, newIdentity } from '../lib/e2ee/core.js'
+import { recipientHandshake } from '../sharing/crypto.js'
+import { HarnessGrantStore } from '../sharing/grants.js'
+import { HarnessShareOwner } from '../sharing/owner.js'
+import { observerSnapshotFile, observerSource, publishObservers } from './observers.js'
+
+it('expires session authority and closes an existing encrypted terminal observer after removal', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'super-observer-')), key = newIdentity()
+ const grants = new HarnessGrantStore(join(dir, 'grants.json'))
+ let now = Date.now()
+ const source = observerSource(dir, () => 'machine', () => now)
+ const rows = [{ tabId: 'tab', agent: { machineId: 'machine', harnessId: 'native', name: 'Builder', configuration: { engine: 'codex' } },
+ observers: [{ email: '[email protected]' }] }]
+ publishObservers(dir, 'machine', rows, now + 2500)
+ const sent: Array<{ id: string; type: string; payload: Record<string, unknown> }> = []
+ const close = vi.fn(), frame = vi.fn(async () => true), publish = vi.fn(async () => ({ status: 200, body: {} }))
+ const owner = new HarnessShareOwner({ machineId: () => 'machine', identity: key, grants, now: () => now,
+ derivedGrants: source.current, allowsGrant: source.allows,
+ resolveAgent: id => id === 'native' ? { agentId: 'native', active: true } as never : undefined,
+ streams: () => ({ handleFrame: frame, closeConnection: close, stop: async () => {} }),
+ send: (id, type, payload) => { sent.push({ id, type, payload }); return true }, publish })
+ try {
+ await owner.manage('harness_share_rosters', {}); await owner.sync()
+ const grant = grants.all()[0]!
+ expect(grant.tab).toBe('super:tab')
+ expect(publish).toHaveBeenCalledWith('PUT', expect.any(String), expect.objectContaining({ superTabId: 'tab', agentId: 'native' }))
+ const ephemeral = newEphemeral()
+ await owner.receive('observer:peer', 'observer_open', { shareId: grant.id, email: '[email protected]', ephemeral: b64e(ephemeral.pub) })
+ const welcome = sent.find(f => f.type === 'observer_welcome')!
+ const cipher = recipientHandshake(ephemeral, 'machine', grant.id, b64e(key.pub), welcome.payload as never)
+ await owner.receive('observer:peer', 'observer_frame', cipher.seal({ type: 'terminal_open', payload: { agentId: 'native' } }) as never)
+ expect(frame).toHaveBeenCalledOnce()
+ publishObservers(dir, 'machine', [], now + 2500); now += 201
+ await owner.receive('observer:peer', 'observer_frame', cipher.seal({ type: 'terminal_alive', payload: {} }) as never)
+ expect(close).toHaveBeenCalledWith('observer:peer')
+ expect(frame).toHaveBeenCalledOnce()
+ publishObservers(dir, 'machine', rows, now + 2500); now += 201
+ expect(source.allows(grant)).toBe(true)
+ now += 2501
+ expect(source.allows(grant)).toBe(false)
+ await owner.receive('observer:stale', 'observer_open', { shareId: grant.id, email: '[email protected]', ephemeral: b64e(newEphemeral().pub) })
+ expect(sent.at(-1)).toMatchObject({ type: 'observer_closed' })
+ writeFileSync(observerSnapshotFile(dir, 'machine'), '{'); now += 201
+ expect(source.current()).toEqual([])
+ } finally { await owner.stop(); rmSync(dir, { recursive: true, force: true }) }
+})
diff --git a/cli/src/superTabs/observers.ts b/cli/src/superTabs/observers.ts
new file mode 100644
index 000000000..769a0c504
--- /dev/null
+++ b/cli/src/superTabs/observers.ts
@@ -0,0 +1,60 @@
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { DerivedGrant, HarnessGrant } from '../sharing/grants.js'
+import { identifier, object } from './wire.js'
+
+type Wanted = Omit<DerivedGrant, 'ownerPublicKey'>
+const PREFIX = 'super:'
+export function superTabOf(grant: Pick<HarnessGrant, 'tab'>): string | null {
+ return grant.tab?.startsWith(PREFIX) ? grant.tab.slice(PREFIX.length) : null
+}
+export function observerSnapshotFile(dataDir: string, machineId: string) {
+ return join(dataDir, 'super-tabs', `observers-${machineId}.json`)
+}
+/** Ephemeral authorization, not a durable grant. A stalled or dead producer's
+ * snapshot expires; restarting Share never extends it from the clock alone. */
+export function publishObservers(dataDir: string, machineId: string, rows: unknown[], until: number) {
+ const wanted: Wanted[] = []
+ for (const value of rows) {
+ const row = object(value), agent = object(row.agent)
+ if (!identifier(row.tabId) || !identifier(agent.harnessId) || agent.machineId !== machineId || !Array.isArray(row.observers)) continue
+ for (const observer of row.observers.map(object)) {
+ if (typeof observer.email !== 'string') continue
+ wanted.push({ tab: `${PREFIX}${row.tabId}`, agentId: agent.harnessId, email: observer.email.trim().toLowerCase(),
+ name: typeof agent.name === 'string' ? agent.name : 'Agent', engine: typeof object(agent.configuration).engine === 'string' ? String(object(agent.configuration).engine) : null })
+ }
+ }
+ const dir = join(dataDir, 'super-tabs'), file = observerSnapshotFile(dataDir, machineId)
+ mkdirSync(dir, { recursive: true, mode: 0o700 })
+ writeFileSync(`${file}.next`, JSON.stringify({ machineId, until, wanted }), { mode: 0o600 })
+ renameSync(`${file}.next`, file)
+}
+export function observerSource(dataDir: string, machine: () => string, now = Date.now) {
+ let readAt = -Infinity, id = '', until = 0, wanted: Wanted[] = []
+ const current = (): Wanted[] => {
+ const machineId = machine(), time = now()
+ if (time - readAt >= 200 || machineId !== id) {
+ id = machineId; readAt = time; until = 0; wanted = []
+ if (identifier(machineId)) try {
+ const raw = readFileSync(observerSnapshotFile(dataDir, machineId), 'utf8')
+ if (raw.length <= 4 * 1024 * 1024) {
+ const saved = object(JSON.parse(raw))
+ if (saved.machineId === machineId && typeof saved.until === 'number' && saved.until <= time + 3000 && Array.isArray(saved.wanted)) {
+ until = saved.until
+ wanted = saved.wanted.filter(w => {
+ const value = object(w)
+ return typeof value.tab === 'string' && value.tab.startsWith(PREFIX) && identifier(value.agentId)
+ && typeof value.email === 'string' && typeof value.name === 'string' && (value.engine === null || typeof value.engine === 'string')
+ }) as Wanted[]
+ }
+ }
+ } catch { /* An unavailable or partially replaced authority file withholds viewing. */ }
+ }
+ return time < until ? wanted : []
+ }
+ return {
+ current,
+ allows: (grant: HarnessGrant): boolean => !superTabOf(grant) || current().some(w =>
+ w.tab === grant.tab && w.agentId === grant.agentId && w.email === grant.recipientEmail),
+ }
+}
diff --git a/cli/src/superTabs/reservations.spec.ts b/cli/src/superTabs/reservations.spec.ts
new file mode 100644
index 000000000..14c5a5a34
--- /dev/null
+++ b/cli/src/superTabs/reservations.spec.ts
@@ -0,0 +1,206 @@
+import { afterEach, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { fakeCore } from '../testing/fakeCore.js'
+import { builtinSqlite } from '../lib/sqliteBuiltin.js'
+import type { CreationObservation } from '../lib/creationObservation.js'
+import type { MachineResources } from '../lib/machineResources.js'
+import { CapacityReservations } from './reservations.js'
+
+const books: CapacityReservations[] = [], folders: string[] = []
+afterEach(() => { for (const book of books.splice(0)) book.stop(); for (const folder of folders.splice(0)) rmSync(folder, { recursive: true, force: true }) })
+const id = (n: number) => `fixture-creation-${n}`
+const input = (n = 1, memory = 60, disk = 60) => ({ creationId: id(n), cwd: '/fixture/repo', requirements: { memoryBytes: memory, diskBytes: disk, maxCpuPercent: 80 } })
+function setup() {
+ const directory = mkdtempSync(join(tmpdir(), 'super-tab-capacity-')); folders.push(directory)
+ const native = new Map<string, CreationObservation | null>(), stopped = new Set<string>()
+ const core = fakeCore({ dataDir: directory, agents: {
+ creationStatus: vi.fn(async key => native.has(key) ? native.get(key)! : { creationId: key, state: 'missing' as const }),
+ stopped: vi.fn(async key => stopped.has(key)),
+ } })
+ const resources: MachineResources = { cpuPercent: 20, memoryTotalBytes: 150, memoryUsedBytes: 50 }
+ const deps = { resources: vi.fn(async () => resources),
+ disk: vi.fn(async (cwd: string) => ({ freeBytes: 100, volume: cwd === '/second-volume' ? 'second' : 'first', path: cwd })),
+ sqlite: () => builtinSqlite() as never }
+ const open = () => { const book = new CapacityReservations(core, 'machine-1', deps); books.push(book); return book }
+ return { directory, file: join(directory, 'super-tabs/capacity.sqlite'), core, native, stopped, resources, deps, open }
+}
+
+it('serializes simultaneous starts across books and accounts for their declared budgets', async () => {
+ const f = setup(), a = f.open(), b = f.open()
+ const answers = await Promise.all([a.reserve(input(1)), b.reserve(input(2))])
+ expect(answers.filter(r => r.ok)).toHaveLength(1)
+ expect(answers.filter(r => r.error)).toEqual([expect.objectContaining({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('memory') })])
+ expect(statSync(f.file).mode & 0o777).toBe(0o600)
+ expect(statSync(join(f.directory, 'super-tabs')).mode & 0o777).toBe(0o700)
+})
+
+it('recovers an interrupted reservation reply after restart without reserving twice', async () => {
+ const f = setup(), first = f.open()
+ expect(await first.reserve(input())).toMatchObject({ ok: true, reservationId: id(1) })
+ first.stop()
+ const second = f.open()
+ expect(await second.reserve(input())).toMatchObject({ ok: true })
+ expect(await second.reserve(input(2, 40, 40))).toMatchObject({ ok: true })
+ expect(await second.reserve(input(3, 1, 1))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await second.reserve(input(1, 30, 60))).toMatchObject({ error: 'CAPACITY_RECEIPT_CONFLICT' })
+})
+
+it.each(['missing', 'pending', 'unconfirmed', null] as const)('retains %s launches with no expiry or inferred stop', async state => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ f.native.set(id(1), state ? { creationId: id(1), state } : null)
+ expect(await book.reserve(input(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ expect(await book.observe(id(1))).toMatchObject({ ok: true, released: false, harnessId: null })
+})
+
+it.each(['failed', 'cancelled'] as const)('releases only the exact durable %s receipt and prevents its reuse', async state => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ f.native.set(id(1), { creationId: id(1), state })
+ expect(await book.reserve(input(2))).toMatchObject({ ok: true })
+ expect(await book.reserve(input())).toMatchObject({ error: 'START_FINISHED' })
+ f.native.set(id(1), null)
+ expect(await book.observe(id(1))).toMatchObject({ ok: true, released: true })
+})
+
+it('retains a learned harness identity after its native window disappears and requires a confirmed stop', async () => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'native' })
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'native', released: false })
+ book.stop()
+ f.native.set(id(1), null)
+ const restarted = f.open()
+ expect(await restarted.reserve(input(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.stopped.add('native')
+ expect(await restarted.reserve(input(2))).toMatchObject({ ok: true })
+ expect(await restarted.observe(id(1))).toMatchObject({ harnessId: 'native', released: true })
+})
+
+it('recovers a harness that started and stopped before the service observed its creation', async () => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'already-closed' })
+ f.stopped.add('already-closed')
+ expect(await book.observe(id(1))).toMatchObject({ harnessId: 'already-closed', released: true })
+ expect(await book.reserve(input(2))).toMatchObject({ ok: true })
+})
+
+it('reserves disk on its destination volume and keeps separate volumes independent', async () => {
+ const f = setup(), book = f.open()
+ await book.reserve(input(1, 0, 60))
+ expect(await book.reserve(input(2, 0, 60))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('disk') })
+ expect(await book.reserve({ ...input(3, 0, 60), cwd: '/second-volume', worktree: true })).toMatchObject({ ok: true })
+ expect(f.deps.disk).toHaveBeenLastCalledWith('/second-volume', true)
+})
+
+it('refuses to reuse a reservation when an unmount moves the same path to a different volume', async () => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ f.deps.disk.mockResolvedValueOnce({ freeBytes: 100, volume: 'replacement', path: '/fixture/repo' })
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', detail: expect.stringContaining('filesystem changed') })
+ expect(await book.reserve(input(2))).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+})
+
+it('refuses unknown native/disk/memory readings and critical or excessive load', async () => {
+ const f = setup(), book = f.open()
+ f.native.set(id(1), null)
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.native.delete(id(1)); f.deps.disk.mockRejectedValueOnce(new Error('unmounted'))
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.resources.memoryUsedBytes = null
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.resources.memoryUsedBytes = 50; f.resources.memoryPressure = 'critical'
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.resources.memoryPressure = null; f.resources.cpuPercent = 99
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.resources.cpuPercent = null
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.resources.cpuPercent = 20
+ expect(await book.reserve(input())).toMatchObject({ ok: true })
+})
+
+it('does not trust a receipt for another creation or a changed native identity', async () => {
+ const f = setup(), book = f.open()
+ f.native.set(id(1), { creationId: id(2), state: 'missing' })
+ expect(await book.reserve(input())).toMatchObject({ error: 'CAPACITY_UNAVAILABLE' })
+ f.native.delete(id(1)); await book.reserve(input())
+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'native' })
+ await book.observe(id(1))
+ f.native.set(id(1), { creationId: id(1), state: 'created', agentId: 'other-native' })
+ await expect(book.observe(id(1))).rejects.toThrow('identity changed')
+})
+
+it.each([{ creationId: 'short' }, { cwd: 'relative' }, { worktree: 'yes' },
+ { requirements: { memoryBytes: -1 } }, { requirements: { diskBytes: Infinity } },
+ { requirements: { memoryBytes: Number.MAX_SAFE_INTEGER + 1 } }, { requirements: { maxCpuPercent: 101 } },
+])('rejects malformed admission without probing the host: %j', async value => {
+ const f = setup(), book = f.open()
+ expect(await book.reserve({ ...input(), ...value })).toMatchObject({ error: 'INVALID_REQUEST' })
+ expect(f.deps.resources).not.toHaveBeenCalled()
+})
+
+it('cancels an in-flight admission on disconnect or request cancellation', async () => {
+ const f = setup(), book = f.open(), controller = new AbortController()
+ let finish!: () => void
+ f.deps.resources.mockImplementationOnce(async () => { await new Promise<void>(resolve => { finish = resolve }); return f.resources })
+ const pending = book.reserve(input(), controller.signal)
+ await vi.waitFor(() => expect(finish).toBeTypeOf('function'))
+ controller.abort(); finish()
+ await expect(pending).rejects.toThrow('disconnected')
+ expect(await book.observe(id(1))).toMatchObject({ error: 'CAPACITY_RECEIPT_MISSING' })
+ f.deps.resources.mockImplementationOnce(async () => { book.stop(); return f.resources })
+ await expect(book.reserve(input())).rejects.toThrow('disconnected')
+ expect(await f.open().observe(id(1))).toMatchObject({ error: 'CAPACITY_RECEIPT_MISSING' })
+})
+
+it('does not write an old host admission after its machine identity changes', async () => {
+ const f = setup(), book = f.open()
+ f.deps.resources.mockImplementationOnce(async () => { f.core.daemon.machineId = () => 'another-machine'; return f.resources })
+ await expect(book.reserve(input())).rejects.toThrow('disconnected')
+ expect(() => new CapacityReservations(f.core, '', f.deps)).toThrow('no confirmed machine identity')
+})
+
+it('refuses a replaced, lost, corrupt or unsupported ledger without silently discarding reservations', async () => {
+ const f = setup(), book = f.open()
+ await book.reserve(input())
+ const saved = readFileSync(f.file)
+ rmSync(f.file); writeFileSync(f.file, saved, { mode: 0o600 })
+ await expect(book.reserve(input(2))).rejects.toThrow('changed on disk')
+ book.stop(); rmSync(f.file)
+ expect(() => f.open()).toThrow('missing')
+ writeFileSync(f.file, 'corrupted', { mode: 0o600 })
+ expect(() => f.open()).toThrow()
+ rmSync(f.file)
+ const target = join(f.directory, 'elsewhere'); writeFileSync(target, saved, { mode: 0o600 }); symlinkSync(target, f.file)
+ expect(() => f.open()).toThrow()
+ expect(() => new CapacityReservations(f.core, 'machine-1', { ...f.deps, sqlite: () => null })).toThrow('Update the Harness CLI runtime')
+})
+
+it('serializes real concurrent processes using one disk ledger', async () => {
+ const f = setup(); f.open().stop()
+ const script = `
+ import { CapacityReservations } from './src/superTabs/reservations.ts';
+ import { builtinSqlite } from './src/lib/sqliteBuiltin.ts';
+ const core = { dataDir: process.argv[1], daemon: { machineId: () => 'machine-1' }, agents: {
+ creationStatus: async creationId => ({ creationId, state: 'missing' }), stopped: async () => false
+ } };
+ const book = new CapacityReservations(core, 'machine-1', {
+ resources: async () => { await new Promise(r => setTimeout(r, 150)); return { cpuPercent: 0, memoryTotalBytes: 100, memoryUsedBytes: 0 } },
+ disk: async () => ({ freeBytes: 100, volume: 'volume', path: '/repo' }), sqlite: builtinSqlite
+ });
+ try { console.log(JSON.stringify(await book.reserve({ creationId: process.argv[2], cwd: '/repo', requirements: { memoryBytes: 70, diskBytes: 70 } }))); }
+ finally { book.stop(); }
+ `
+ const run = promisify(execFile)
+ const answers = await Promise.all([1, 2].map(async n => {
+ const result = await run(process.execPath, ['--import', 'tsx', '--input-type=module', '-e', script, f.directory, id(n)], { timeout: 15_000 })
+ return JSON.parse(result.stdout.trim())
+ }))
+ expect(answers.filter(r => r.ok)).toHaveLength(1)
+ expect(answers.filter(r => r.error)).toEqual([expect.objectContaining({ error: 'CAPACITY_UNAVAILABLE' })])
+}, 20_000)
diff --git a/cli/src/superTabs/reservations.ts b/cli/src/superTabs/reservations.ts
new file mode 100644
index 000000000..84361392e
--- /dev/null
+++ b/cli/src/superTabs/reservations.ts
@@ -0,0 +1,208 @@
+import { createHash } from 'node:crypto'
+import { closeSync, constants, existsSync, fsyncSync, lstatSync, openSync, writeFileSync } from 'node:fs'
+import { isAbsolute, join } from 'node:path'
+import type { CoreApi } from '../core/api.js'
+import { builtinSqlite } from '../lib/sqliteBuiltin.js'
+import { hardenPrivateStateFileIfPresent, readPrivateStateFile, secureStateDirectory } from '../lib/secureState.js'
+import { creationObservation, type CreationObservation } from '../lib/creationObservation.js'
+import { readMachineResources } from '../lib/machineResources.js'
+import { readCapacityDisk } from './disk.js'
+import { object } from './wire.js'
+
+type Json = Record<string, unknown>
+interface Statement {
+ all(...args: unknown[]): Json[]
+ get(...args: unknown[]): Json | undefined
+ run(...args: unknown[]): unknown
+}
+interface Database { exec(sql: string): void; prepare(sql: string): Statement; close(): void }
+type DatabaseConstructor = new (path: string) => Database
+interface Reservation {
+ creation_id: string; fingerprint: string; memory_bytes: number; disk_bytes: number
+ volume: string; harness_id: string | null; released: number
+}
+export interface ReservationBook {
+ reserve(input: Json, closed?: AbortSignal): Promise<Json>
+ observe(creationId: unknown, closed?: AbortSignal): Promise<Json>
+ stop(): void
+}
+interface Dependencies {
+ resources: typeof readMachineResources
+ disk: typeof readCapacityDisk
+ sqlite: () => DatabaseConstructor | null
+}
+const MAX_ACTIVE = 256
+const MAX_FILE_BYTES = 32 * 1024 * 1024
+const MARKER = 'super-tab-capacity-v1\n'
+const creationIdValid = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{16,96}$/.test(v)
+const bytes = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0
+const finite = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
+const unavailable = (detail: string): Json => ({ error: 'CAPACITY_UNAVAILABLE', detail })
+
+/** All Super Tabs on this host share one ledger. SQLite serializes admission
+ * across service restarts/overlap; no asynchronous work runs inside its write
+ * transaction. Unknown native outcomes keep their budget, without a timeout. */
+export class CapacityReservations implements ReservationBook {
+ private readonly db: Database
+ private readonly file: string
+ private readonly identity: { dev: number; ino: number }
+ private stopped = false
+
+ constructor(private readonly core: CoreApi, private readonly machineId: string,
+ private readonly deps: Dependencies = { resources: readMachineResources, disk: readCapacityDisk,
+ sqlite: () => builtinSqlite() as unknown as DatabaseConstructor | null }) {
+ if (!/^[A-Za-z0-9_-]{1,160}$/.test(machineId)) throw new Error('The execution host has no confirmed machine identity.')
+ const Database = deps.sqlite()
+ if (!Database) throw new Error('Update the Harness CLI runtime on this machine to reserve capacity for Super Tab agents.')
+ secureStateDirectory(core.dataDir)
+ const directory = join(core.dataDir, 'super-tabs')
+ secureStateDirectory(directory)
+ this.file = join(directory, 'capacity.sqlite')
+ const marker = `${this.file}.ready`
+ const initialized = existsSync(marker)
+ if (initialized && readPrivateStateFile(marker, 128) !== MARKER) throw new Error('The capacity ledger marker is unreadable.')
+ if (!hardenPrivateStateFileIfPresent(this.file, MAX_FILE_BYTES)) {
+ if (initialized) throw new Error('The capacity ledger is missing. Restore it before starting more agents.')
+ try {
+ const fd = openSync(this.file, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600)
+ try { fsyncSync(fd) } finally { closeSync(fd) }
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
+ hardenPrivateStateFileIfPresent(this.file, MAX_FILE_BYTES)
+ }
+ this.identity = lstatSync(this.file)
+ this.db = new Database(this.file)
+ try {
+ this.db.exec('PRAGMA busy_timeout = 1000; PRAGMA synchronous = FULL;')
+ this.transaction(() => {
+ const version = this.db.prepare('PRAGMA user_version').get()?.user_version
+ if (version === 0 && !initialized) {
+ if (this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").get()) throw new Error('Unrecognized capacity ledger.')
+ this.db.exec(`CREATE TABLE reservations (
+ creation_id TEXT PRIMARY KEY, fingerprint TEXT NOT NULL,
+ memory_bytes INTEGER NOT NULL CHECK(memory_bytes >= 0), disk_bytes INTEGER NOT NULL CHECK(disk_bytes >= 0),
+ volume TEXT NOT NULL, harness_id TEXT, released INTEGER NOT NULL DEFAULT 0 CHECK(released IN (0, 1)),
+ created_at INTEGER NOT NULL
+ ); PRAGMA user_version = 1;`)
+ } else if (version !== 1) throw new Error('The capacity ledger version is unavailable. Restore it or update Harness.')
+ this.rows()
+ })
+ if (!initialized) {
+ try { writeFileSync(marker, MARKER, { flag: 'wx', mode: 0o600, flush: true }) }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error }
+ if (readPrivateStateFile(marker, 128) !== MARKER) throw new Error('The capacity ledger marker is unreadable.')
+ }
+ } catch (error) { this.db.close(); throw error }
+ }
+
+ stop(): void { if (!this.stopped) { this.stopped = true; this.db.close() } }
+
+ private check(closed?: AbortSignal): void {
+ if (this.stopped || closed?.aborted || this.core.daemon.machineId() !== this.machineId) throw new Error('The execution host disconnected. Resume this start after reconnecting.')
+ const current = lstatSync(this.file)
+ if (!current.isFile() || current.dev !== this.identity.dev || current.ino !== this.identity.ino || current.size > MAX_FILE_BYTES) {
+ throw new Error('The capacity ledger changed on disk. Restore it before starting more agents.')
+ }
+ }
+
+ private transaction<T>(work: () => T, closed?: AbortSignal): T {
+ this.check(closed)
+ this.db.exec('BEGIN IMMEDIATE')
+ try { const value = work(); this.db.exec('COMMIT'); return value }
+ catch (error) { this.db.exec('ROLLBACK'); throw error }
+ }
+
+ private rows(): Reservation[] {
+ const rows = this.db.prepare('SELECT * FROM reservations WHERE released = 0 LIMIT ?').all(MAX_ACTIVE + 1)
+ if (rows.length > MAX_ACTIVE || rows.some(row => !creationIdValid(row.creation_id)
+ || typeof row.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(row.fingerprint)
+ || !bytes(row.memory_bytes) || !bytes(row.disk_bytes) || typeof row.volume !== 'string'
+ || (row.harness_id !== null && (typeof row.harness_id !== 'string' || !/^[A-Za-z0-9_-]{1,160}$/.test(row.harness_id))))) {
+ throw new Error('The capacity ledger is unreadable. Restore it before starting more agents.')
+ }
+ return rows as unknown as Reservation[]
+ }
+
+ private async native(id: string): Promise<CreationObservation | null> {
+ return creationObservation(id, await this.core.agents.creationStatus?.(id).catch(() => null))
+ }
+
+ private async reconcile(rows: Reservation[], closed?: AbortSignal): Promise<void> {
+ for (let index = 0; index < rows.length; index += 8) {
+ const observations = await Promise.all(rows.slice(index, index + 8).map(async row => {
+ const observation = await this.native(row.creation_id)
+ const harnessId = observation?.state === 'created' ? observation.agentId : row.harness_id
+ if (row.harness_id && harnessId !== row.harness_id) throw new Error('The native creation identity changed. Inspect this machine before starting more agents.')
+ const released = observation?.state === 'failed' || observation?.state === 'cancelled'
+ || (!!harnessId && await this.core.agents.stopped?.(harnessId).catch(() => false) === true)
+ return { row, harnessId, released }
+ }))
+ this.transaction(() => {
+ for (const { row, harnessId, released } of observations) {
+ // A later reconciliation may already have learned the native ID.
+ // Missing/unavailable observations never erase that durable identity.
+ this.db.prepare(`UPDATE reservations SET harness_id = COALESCE(harness_id, ?), released = ?
+ WHERE creation_id = ? AND fingerprint = ? AND released = 0`).run(harnessId, released ? 1 : 0, row.creation_id, row.fingerprint)
+ }
+ }, closed)
+ }
+ }
+
+ async observe(creationId: unknown, closed?: AbortSignal): Promise<Json> {
+ if (!creationIdValid(creationId)) return { error: 'INVALID_REQUEST' }
+ this.check(closed)
+ const rows = this.rows().filter(row => row.creation_id === creationId)
+ await this.reconcile(rows, closed)
+ this.check(closed)
+ const row = this.db.prepare('SELECT harness_id, released FROM reservations WHERE creation_id = ?').get(creationId)
+ return row ? { ok: true, reservationId: creationId, harnessId: row.harness_id, released: row.released === 1 }
+ : { error: 'CAPACITY_RECEIPT_MISSING', detail: 'This start has no capacity receipt. Inspect the machine before starting another agent.' }
+ }
+
+ async reserve(input: Json, closed?: AbortSignal): Promise<Json> {
+ const { creationId, cwd } = input, request = object(input.requirements)
+ const memory = request.memoryBytes ?? 0, disk = request.diskBytes ?? 0, cpu = request.maxCpuPercent ?? 100
+ if (!creationIdValid(creationId) || typeof cwd !== 'string' || !isAbsolute(cwd) || cwd.length > 4096 || /[\x00-\x1f\x7f]/.test(cwd)
+ || (input.worktree !== undefined && typeof input.worktree !== 'boolean') || !bytes(memory) || !bytes(disk)
+ || !finite(cpu) || cpu < 0 || cpu > 100) return { error: 'INVALID_REQUEST', detail: 'Use a native creation ID, absolute project path and nonnegative resource requirements.' }
+ const fingerprint = createHash('sha256').update(JSON.stringify([cwd, input.worktree === true, memory, disk, cpu])).digest('hex')
+ this.check(closed)
+ const prior = this.db.prepare('SELECT fingerprint FROM reservations WHERE creation_id = ?').get(creationId)
+ if (prior && prior.fingerprint !== fingerprint) return { error: 'CAPACITY_RECEIPT_CONFLICT', detail: 'This start already reserved different resources. Keep its original settings.' }
+ await this.reconcile(this.rows(), closed)
+ this.check(closed)
+ const existing = this.db.prepare('SELECT released, volume FROM reservations WHERE creation_id = ?').get(creationId)
+ if (existing?.released === 1) return { error: 'START_FINISHED', detail: 'This native start has ended. Create a new start request.' }
+ const [native, resources, destination] = await Promise.all([
+ this.native(creationId), this.deps.resources().catch(() => null), this.deps.disk(cwd, input.worktree === true).catch(() => null),
+ ])
+ this.check(closed)
+ if (!destination || !bytes(destination.freeBytes) || !destination.volume) return unavailable('The destination disk capacity could not be verified.')
+ if (existing) {
+ if (existing.volume !== destination.volume) return unavailable('The destination filesystem changed after this start reserved capacity. Inspect the machine before retrying this start.')
+ // Re-read under the same lock as new admissions: another request may have
+ // recorded a stop while this one was sampling the destination.
+ return this.transaction(() => this.db.prepare('SELECT released FROM reservations WHERE creation_id = ?').get(creationId)?.released === 0
+ ? { ok: true, reservationId: creationId }
+ : { error: 'START_FINISHED', detail: 'This native start has ended. Create a new start request.' }, closed)
+ }
+ if (native?.state !== 'missing') return unavailable('The machine could not confirm that this start is new. Resume its existing receipt before starting another agent.')
+ const freeMemory = bytes(resources?.memoryTotalBytes) && bytes(resources?.memoryUsedBytes) && resources.memoryUsedBytes <= resources.memoryTotalBytes
+ ? resources.memoryTotalBytes - resources.memoryUsedBytes : null
+ if (resources?.memoryPressure === 'critical') return unavailable('The machine reports critical memory pressure.')
+ if ((!finite(resources?.cpuPercent) && cpu < 100) || (finite(resources?.cpuPercent) && resources.cpuPercent > cpu)) return unavailable('The machine does not have the requested CPU headroom.')
+ return this.transaction(() => {
+ const duplicate = this.db.prepare('SELECT fingerprint, released, volume FROM reservations WHERE creation_id = ?').get(creationId)
+ if (duplicate) return duplicate.fingerprint === fingerprint && duplicate.released === 0 && duplicate.volume === destination.volume ? { ok: true, reservationId: creationId }
+ : { error: 'CAPACITY_RECEIPT_CONFLICT', detail: 'This native start already has a different or finished capacity reservation.' }
+ const active = this.rows()
+ if (active.length >= MAX_ACTIVE) return unavailable('Reconcile pending starts on this machine before starting more agents.')
+ const memoryHeld = active.reduce((sum, row) => sum + row.memory_bytes, 0)
+ const diskHeld = active.filter(row => row.volume === destination.volume).reduce((sum, row) => sum + row.disk_bytes, 0)
+ if (memory > 0 && (!finite(freeMemory) || memory > freeMemory - memoryHeld)) return unavailable('Available memory is already in use or reserved for other agents. Choose another machine or wait for work to finish.')
+ if (disk > destination.freeBytes - diskHeld) return unavailable('Destination disk space is already in use or reserved for other agents. Choose another machine or free space before retrying.')
+ this.db.prepare(`INSERT INTO reservations (creation_id, fingerprint, memory_bytes, disk_bytes, volume, created_at)
+ VALUES (?, ?, ?, ?, ?, ?)`).run(creationId, fingerprint, memory, disk, destination.volume, Date.now())
+ return { ok: true, reservationId: creationId }
+ }, closed)
+ }
+}
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
new file mode 100644
index 000000000..ae70bc9d8
--- /dev/null
+++ b/cli/src/superTabs/service.spec.ts
@@ -0,0 +1,96 @@
+import { createHash } from 'node:crypto'
+import { expect, it, vi } from 'vitest'
+import { fakeCore } from '../testing/fakeCore.js'
+import { superTabService } from './service.js'
+import type { SuperTabHost } from './host.js'
+
+const owner = { local: true, owner: true }, visitor = { local: false, owner: false }
+function setup() {
+ const agentId = createHash('sha256').update(JSON.stringify(['machine-1', 'native'])).digest('hex').slice(0, 24)
+ const agent = { id: agentId, machineId: 'machine-1', harnessId: 'native' }
+ const call = vi.fn(async () => ({ status: 200, body: { success: true, data: { state: { agents: [agent] } } } }))
+ const core = fakeCore({ account: { backend: call }, agents: { byAgent: vi.fn(() => ({ agentId: 'native' }) as never) } })
+ const start = vi.fn(), stop = vi.fn()
+ const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start, stop }) as unknown as SuperTabHost })
+ return { ...service, call, core, agent, agentId, start, stop, ask: service.requests.super_tabs }
+}
+it('keeps a shared machine controller out of the host account while accepting its own paired apps', async () => {
+ const t = setup()
+ for (const accountOwner of [undefined, false]) {
+ expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab', accountOwner: true },
+ { local: false, owner: true, accountOwner })).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(t.call).not.toHaveBeenCalled()
+ expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab' },
+ { local: false, owner: true, accountOwner: true })).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenCalledOnce()
+})
+it('lets a shared host be woken without exposing its account proxy or agent identity', async () => {
+ const t = setup()
+ expect(await t.ask({ action: 'wake' }, visitor)).toEqual({ ok: true })
+ expect(t.start).toHaveBeenCalledOnce()
+ for (const action of ['backend', 'status', 'command', 'help']) {
+ expect(await t.ask({ action }, visitor)).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(t.call).not.toHaveBeenCalled()
+ t.port.disconnected(); expect(t.stop).toHaveBeenCalledOnce()
+})
+it('limits the owner proxy to Super Tab endpoints and preserves backend failures', async () => {
+ const t = setup()
+ for (const path of ['/api/auth/me', '/api/super-tabs/../auth/me', '/api/super-tabs%2F..', 'https://elsewhere.invalid', '/api/super-tabs#other']) {
+ expect(await t.ask({ action: 'backend', method: 'GET', path }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
+ }
+ expect(await t.ask({ action: 'backend', method: 'DELETE', path: '/api/super-tabs' }, owner)).toMatchObject({ error: 'INVALID_REQUEST' })
+ expect(t.call).not.toHaveBeenCalled()
+ expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab?asAgentId=agent' }, owner)).toMatchObject({ ok: true })
+ vi.mocked(t.core.account.backend).mockResolvedValueOnce({ status: 403, body: { success: false, error: { code: 'FORBIDDEN', message: 'Access withdrawn' } } })
+ expect(await t.ask({ action: 'backend', method: 'GET', path: '/api/super-tabs/tab' }, owner)).toEqual({ error: 'FORBIDDEN', detail: 'Access withdrawn', status: 403 })
+})
+it('resolves a native caller to its exact contribution and rechecks it before every agent command', async () => {
+ const t = setup()
+ expect(await t.ask({ action: 'status', tabId: 'tab', harnessId: 'native' }, owner)).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenLastCalledWith('GET', `/api/super-tabs/tab?asAgentId=${t.agentId}`, undefined)
+ const command = { type: 'message.send', conversationId: 'lead', text: 'Ready', replyTo: null, recipientIds: [] }
+ expect(await t.ask({ action: 'command', tabId: 'tab', agentId: t.agentId, operationId: 'op', command }, owner)).toMatchObject({ ok: true, operationId: 'op' })
+ expect(t.call).toHaveBeenLastCalledWith('POST', '/api/super-tabs/tab/commands', { operationId: 'op', command, asAgentId: t.agentId })
+ expect(await t.ask({ action: 'message', tabId: 'tab', agentId: t.agentId, conversationId: 'lead', messageId: 'old-question' }, owner)).toMatchObject({ ok: true })
+ expect(t.call).toHaveBeenLastCalledWith('GET', `/api/super-tabs/tab/conversations/lead/messages?asAgentId=${t.agentId}&messageId=old-question`, undefined)
+ t.agent.machineId = 'another-machine'
+ expect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
+ t.agent.machineId = 'machine-1'; vi.mocked(t.core.agents.byAgent).mockReturnValue(undefined)
+ expect(await t.ask({ action: 'status', tabId: 'tab', agentId: t.agentId }, owner)).toMatchObject({ error: 'AGENT_UNAVAILABLE' })
+})
+
+it('keeps host capacity separate from account authority and closes it on disconnect or identity change', async () => {
+ const core = fakeCore()
+ const reserve = vi.fn(async () => ({ ok: true, reservationId: 'native-creation-id' }))
+ const observe = vi.fn(async () => ({ ok: true, released: true }))
+ const stop = vi.fn(), factory = vi.fn(() => ({ reserve, observe, stop }))
+ const service = superTabService(core, { reservations: factory })
+ const closed = new AbortController().signal
+ expect(factory).not.toHaveBeenCalled()
+ expect(await service.requests.super_tabs({ action: 'reserveCapacity', creationId: 'native-creation-id' }, visitor, closed)).toMatchObject({ ok: true })
+ expect(reserve).toHaveBeenCalledWith({ action: 'reserveCapacity', creationId: 'native-creation-id' }, closed)
+ expect(await service.requests.super_tabs({ action: 'observeCapacity', creationId: 'native-creation-id' }, visitor)).toMatchObject({ released: true })
+ expect(factory).toHaveBeenCalledTimes(1)
+ service.port.disconnected(); expect(stop).toHaveBeenCalledTimes(1)
+ await service.requests.super_tabs({ action: 'reserveCapacity' }, visitor)
+ expect(factory).toHaveBeenCalledTimes(2)
+ core.daemon.machineId = () => 'changed-machine'
+ await service.requests.super_tabs({ action: 'reserveCapacity' }, visitor)
+ expect(stop).toHaveBeenCalledTimes(2)
+ expect(factory).toHaveBeenLastCalledWith(core, 'changed-machine')
+ service.port.stop(); expect(stop).toHaveBeenCalledTimes(3)
+})
+
+it('lets a machine client prepare only a backend-verified terminal context', async () => {
+ const core = fakeCore(), prepareNative = vi.fn(async () => ({ ok: true, inputContext: 'context_1234567890' }))
+ const service = superTabService(core, { host: () => ({ machineId: 'machine-1', start: vi.fn(), stop: vi.fn(), prepareNative }) as unknown as SuperTabHost })
+ const signal = new AbortController().signal
+ expect(await service.requests.super_tabs({ action: 'prepareNative', tabId: 'tab', contextId: 'context_1234567890' }, visitor, signal))
+ .toEqual({ ok: true, inputContext: 'context_1234567890' })
+ expect(prepareNative).toHaveBeenLastCalledWith('tab', 'context_1234567890', false, signal)
+ await service.requests.super_tabs({ action: 'renewNative', tabId: 'tab', contextId: 'context_1234567890' }, visitor)
+ expect(prepareNative).toHaveBeenLastCalledWith('tab', 'context_1234567890', true, undefined)
+ expect(core.account.backend).not.toHaveBeenCalled()
+})
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
new file mode 100644
index 000000000..fbec15e9b
--- /dev/null
+++ b/cli/src/superTabs/service.ts
@@ -0,0 +1,121 @@
+import { readCapabilities } from './capacity.js'
+import { existsSync } from 'node:fs'
+import { createHash } from 'node:crypto'
+import type { CoreApi, ServiceRequests, SuperTabsPort } from '../core/api.js'
+import { backend, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError } from './host.js'
+import { CapacityReservations, type ReservationBook } from './reservations.js'
+
+const HELP = {
+ status: 'Read the shared tab roster and work.',
+ messages: 'messages GROUP: read recent messages in a conversation.',
+ message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',
+ post: 'post GROUP TEXT OPERATION_ID: reply in that conversation. Use a unique ID per message and reuse it after an interrupted request.',
+ start: 'start OPERATION_ID JSON: create one agent in a conversation on a machine you can access. Repeat exactly after an interruption; it follows the same native creation receipt. It does not assign work.',
+ resume: 'resume START_ID: finish a pending start without creating another agent.',
+ capacity: 'capacity MACHINE_ID JSON: inspect machine, engine and quota headroom. JSON uses the start request fields below. Unknown allowances are not reported as free tokens.',
+ startRequest: { conversationId: 'GROUP', machineId: 'MACHINE', engine: 'codex', name: 'Builder', cwd: '/absolute/repo/on/that/machine', worktree: true, requirements: { memoryBytes: 2147483648, diskBytes: 10737418240, maxCpuPercent: 85, tools: ['git'], devices: [], quotaRequired: false } },
+ command: 'command OPERATION_ID JSON: send one of the commands below. Reuse exactly the same ID and JSON after an interrupted request.',
+ commands: [
+ { type: 'message.send', conversationId: 'GROUP', text: 'A message addressed to an agent', replyTo: null, recipientIds: ['AGENT'] },
+ { type: 'conversation.create', title: 'Outcome', brief: 'An independently assignable result', checks: [{ description: 'Observable acceptance evidence', independent: false }] },
+ { type: 'conversation.agent', conversationId: 'GROUP', agentId: 'AGENT', present: true, lead: false },
+ { type: 'work.define', conversationId: 'GROUP', brief: 'What to deliver', checks: [{ description: 'Observable acceptance evidence', independent: false }] },
+ { type: 'work.assign', conversationId: 'GROUP', agentId: 'AGENT' },
+ { type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'working', result: null },
+ { type: 'work.check', conversationId: 'GROUP', assignmentId: 'ATTEMPT', checkId: 'CHECK', passed: true, evidence: 'Exact test command, revision and observed result' },
+ { type: 'work.status', conversationId: 'GROUP', assignmentId: 'ATTEMPT', status: 'done', result: 'Exact revision, evidence and deliverable links' },
+ ],
+}
+
+export interface SuperTabServiceOptions {
+ capacity?: typeof readCapabilities
+ host?: (core: CoreApi, machineId: string) => SuperTabHost
+ reservations?: (core: CoreApi, machineId: string) => ReservationBook
+}
+export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {
+ let host: SuperTabHost | null = null
+ let book: ReservationBook | null = null, bookMachine: string | null = null
+ const reservations = () => {
+ const machine = core.daemon.machineId()
+ if (bookMachine !== machine) { book?.stop(); book = null; bookMachine = machine }
+ book ??= (options.reservations ?? ((api, id) => new CapacityReservations(api, id)))(core, machine)
+ return book
+ }
+ const wake = () => {
+ const machine = core.daemon.machineId()
+ if (host?.machineId !== machine) { host?.stop(); host = null }
+ host ??= (options.host ?? ((api, id) => new SuperTabHost(api, id)))(core, machine)
+ host.start()
+ return host
+ }
+ const disconnect = () => { host?.stop(); host = null; book?.stop(); book = null; bookMachine = null }
+ const port = {
+ connected: () => {
+ if (identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))) wake()
+ },
+ disconnected: disconnect,
+ stop: disconnect,
+ }
+ const requests: ServiceRequests = {
+ super_tabs: async (payload, asker, closed) => {
+ try {
+ // Existing machine access routes the frame. Waking reads this host's own
+ // registered contributions only, and grants the caller no account access.
+ if (payload.action === 'wake') { wake(); return { ok: true } }
+ if (payload.action === 'capacity') return (options.capacity ?? readCapabilities)(payload)
+ // Machine access also authorizes native creation. These actions expose
+ // only that host's admission/receipt, never its account or private roster.
+ if (payload.action === 'reserveCapacity') return await reservations().reserve(payload, closed)
+ if (payload.action === 'observeCapacity') return await reservations().observe(payload.creationId, closed)
+ // A backend-issued context scopes provenance only. Existing machine
+ // control is still required to open/write the native terminal itself.
+ if (payload.action === 'prepareNative' || payload.action === 'renewNative') {
+ return await wake().prepareNative(payload.tabId, payload.contextId, payload.action === 'renewNative', closed)
+ }
+ if (!asker.owner || (!asker.local && asker.accountOwner !== true)) return { error: 'OWNER_REQUIRED' }
+ if (payload.action === 'backend') {
+ const { method, path } = payload
+ if (!['GET', 'POST'].includes(String(method)) || typeof path !== 'string'
+ || !/^\/api\/super-tabs(?:\/[A-Za-z0-9_-]+)*(?:\?[A-Za-z0-9_=&%-]+)?$/.test(path)) {
+ return { error: 'INVALID_REQUEST', detail: 'Choose a Super Tab endpoint.' }
+ }
+ const value = await backend(core, method as string, path, payload.body)
+ return { ok: true, value }
+ }
+ if (payload.action === 'help') return { ok: true, help: HELP }
+ const agentId = identifier(payload.agentId) ? payload.agentId
+ : identifier(payload.harnessId) ? createHash('sha256').update(JSON.stringify([core.daemon.machineId(), payload.harnessId])).digest('hex').slice(0, 24) : null
+ if (!identifier(payload.tabId) || !agentId) return { error: 'INVALID_REQUEST' }
+ const path = `/api/super-tabs/${payload.tabId}`
+ const identity = `asAgentId=${agentId}`
+ const answer = object(await backend(core, 'GET', `${path}?${identity}`))
+ const state = object(answer.state)
+ const agent = Array.isArray(state.agents) ? state.agents.map(object).find(a => a.id === agentId) : undefined
+ if (!agent || agent.machineId !== core.daemon.machineId() || typeof agent.harnessId !== 'string' || !core.agents.byAgent(agent.harnessId)) {
+ return { error: 'AGENT_UNAVAILABLE', detail: 'This agent is not a running contribution on this machine.' }
+ }
+ wake()
+ if (payload.action === 'startStatus' && identifier(payload.startId)) {
+ return { ok: true, value: await backend(core, 'GET', `${path}/starts/${payload.startId}?${identity}`) }
+ }
+ if (payload.action === 'status') return { ok: true, value: answer }
+ if (payload.action === 'messages' && identifier(payload.conversationId)) {
+ return { ok: true, value: await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}`) }
+ }
+ if (payload.action === 'message' && identifier(payload.conversationId) && identifier(payload.messageId)) {
+ return { ok: true, value: await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}&messageId=${payload.messageId}`) }
+ }
+ if (payload.action === 'command' && identifier(payload.operationId) && payload.command && typeof payload.command === 'object' && !Array.isArray(payload.command)) {
+ return { ok: true, operationId: payload.operationId, value: await backend(core, 'POST', `${path}/commands`,
+ { operationId: payload.operationId, command: payload.command, asAgentId: agentId }) }
+ }
+ return { error: 'INVALID_REQUEST' }
+ } catch (error) {
+ return error instanceof SuperTabHostError
+ ? { error: error.code, detail: error.message, status: error.status }
+ : { error: 'SUPER_TAB_UNAVAILABLE', detail: error instanceof Error ? error.message : 'This Super Tab is unavailable.' }
+ }
+ },
+ }
+ return { requests, port }
+}
diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.ts
new file mode 100644
index 000000000..817f5c6a2
--- /dev/null
+++ b/cli/src/superTabs/start.spec.ts
@@ -0,0 +1,181 @@
+import { expect, it, vi } from 'vitest'
+import { startAgent } from './start.js'
+const where = { port: 14001, machineId: 'lead-machine', dataDir: '/fixture' }
+function fixture(options: { refuse?: string; loseCancel?: boolean; loseFailure?: boolean } = {}) {
+ const start = { creationId: 'super-native-receipt', error: null as string | null, request: { machineId: 'target', conversationId: 'group', engine: 'claude', name: 'Builder', cwd: '/repo', worktree: true,
+ requirements: { memoryBytes: 100, diskBytes: 200, maxCpuPercent: 80, tools: ['git'], devices: [], quotaRequired: false } }, dispatched: false }
+ let nativeState = 'missing', lostJoin = false
+ const scoped = vi.fn(async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
+ if (payload.action === 'startStatus') return { ok: true, value: structuredClone(start) }
+ const cmd = payload.command as Record<string, unknown>
+ if (cmd.type === 'agent.startDispatch') start.dispatched = true
+ if (cmd.type === 'agent.startFailed') {
+ if (options.loseFailure) { options.loseFailure = false; throw new Error('Failure receipt interrupted') }
+ start.error = String(cmd.error)
+ }
+ if (cmd.type === 'agent.started' && lostJoin) { lostJoin = false; throw new Error('Join interrupted') }
+ return { ok: true, value: { result: cmd.type === 'agent.start' ? { startId: 'start' } : { agentId: 'worker' } } }
+ })
+ const request = vi.fn(async (type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> => {
+ if (type === 'agent_create_status') return { creationId: start.creationId, state: nativeState, ...(nativeState === 'created' ? { agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } } : {}) }
+ if (type === 'engines_probe') return { engines: [{ engine: 'claude', installed: true }] }
+ if (type === 'usage_read') return { providers: [] }
+ if (type === 'super_tabs') {
+ if (payload.action === 'reserveCapacity') return { ok: true, reservationId: start.creationId }
+ if (payload.action === 'observeCapacity') return { ok: true, reservationId: start.creationId, harnessId: 'native', released: nativeState === 'cancelled' }
+ return { ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 100, projectDiskFreeBytes: 1000 }, tools: { git: true }, devices: {} }
+ }
+ if (type === 'agent_create') {
+ if (options.refuse) return { error: options.refuse, detail: 'This agent does not support that permission mode.' }
+ nativeState = 'created'; return { creationId: start.creationId, state: 'created', agent: { id: 'native', engine: 'claude', selectedModel: 'runtime-v1:native:claude:fixture-model@high' } }
+ }
+ if (type === 'agent_create_cancel') {
+ nativeState = 'cancelled'
+ if (options.loseCancel) { options.loseCancel = false; throw new Error('Cancellation reply interrupted') }
+ return { creationId: start.creationId, state: nativeState }
+ }
+ throw new Error(type)
+ })
+ const close = vi.fn(), open = vi.fn(async () => ({ machineId: 'target', request, close }))
+ return { scoped, start, request, open, close, loseJoin: () => { lostJoin = true }, forget: () => { nativeState = 'missing' } }
+}
+it('uses one native creation receipt and joins its captured group after a lost join reply', async () => {
+ const f = fixture(); f.loseJoin()
+ const input = { action: 'start', tabId: 'tab', operationId: 'user-intent', request: f.start.request }
+ await expect(startAgent(input, f.scoped, where, f.open)).rejects.toThrow('Join interrupted')
+ expect(f.close).toHaveBeenCalledOnce()
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ ok: true, harnessId: 'native', agentId: 'worker' })
+ const launches = f.request.mock.calls.filter(c => c[0] === 'agent_create')
+ expect(launches).toHaveLength(1)
+ expect(f.open).toHaveBeenCalledWith(where, 'target')
+ const commands = f.scoped.mock.calls.map(c => c[0].command as Record<string, unknown>).filter(Boolean)
+ expect(commands.find(c => c.type === 'agent.started')).toMatchObject({ startId: 'start', harnessId: 'native', configuration: { engine: 'claude', model: 'fixture-model', effort: 'high' } })
+ expect(commands.some(c => c.type === 'work.assign')).toBe(false)
+})
+it('does not recreate when a previously dispatched start loses its native receipt', async () => {
+ const f = fixture(); f.start.dispatched = true
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN', creationId: 'super-native-receipt' })
+ expect(f.request.mock.calls.map(c => c[0])).toEqual(['agent_create_status'])
+})
+it('withholds native creation when capacity or authority cannot be verified', async () => {
+ const f = fixture()
+ f.start.request.requirements.diskBytes = 2000
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ error: 'CAPACITY_UNAVAILABLE', allowed: false })
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)
+ f.scoped.mockResolvedValueOnce({ error: 'FORBIDDEN', detail: 'Machine sharing was withdrawn.' })
+ await expect(startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).rejects.toThrow('withdrawn')
+ expect(f.open).toHaveBeenCalledOnce()
+})
+
+it('closes a refused start only after the machine durably fences its creation receipt', async () => {
+ const f = fixture({ refuse: 'INVALID_PERMISSION_MODE' })
+ const input = { action: 'resume', tabId: 'tab', startId: 'start' }
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_FAILED', detail: 'This agent does not support that permission mode.' })
+ expect(f.request.mock.calls.map(c => c[0]).filter(type => type.startsWith('agent_create'))).toEqual(['agent_create_status', 'agent_create', 'agent_create_cancel'])
+ expect(f.start.error).toContain('before starting an agent')
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_FAILED' })
+ expect(f.open).toHaveBeenCalledOnce()
+ expect(f.scoped.mock.calls.some(c => (c[0].command as any)?.type === 'agent.started')).toBe(false)
+})
+
+it('recovers a lost cancellation reply without dispatching another start', async () => {
+ const f = fixture({ refuse: 'INVALID_PERMISSION_MODE', loseCancel: true })
+ const input = { action: 'resume', tabId: 'tab', startId: 'start' }
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN' })
+ expect(f.start.error).toBeNull()
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_FAILED' })
+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+ expect(f.close).toHaveBeenCalledTimes(2)
+})
+
+it('retries the exact shared failure command after a lost acknowledgement', async () => {
+ const f = fixture({ refuse: 'INVALID_PERMISSION_MODE', loseFailure: true })
+ const input = { action: 'resume', tabId: 'tab', startId: 'start' }
+ await expect(startAgent(input, f.scoped, where, f.open)).rejects.toThrow('Failure receipt interrupted')
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_FAILED' })
+ const failures = f.scoped.mock.calls.map(c => c[0]).filter(p => (p.command as any)?.type === 'agent.startFailed')
+ expect(failures).toHaveLength(2)
+ expect(failures[0]).toEqual(failures[1])
+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+})
+
+it.each(['CREATION_CONFLICT', 'CREATION_STORAGE_FAILED', 'INTERNAL', 'NEW_UNKNOWN_ERROR'])('keeps %s uncertain without cancelling a potentially dispatched intent', async (error) => {
+ const f = fixture({ refuse: error })
+ const input = { action: 'resume', tabId: 'tab', startId: 'start' }
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_REFUSED' })
+ expect(f.start.error).toBeNull()
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create_cancel')).toBe(false)
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN' })
+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+})
+
+it.each([
+ { creationId: 'different', state: 'cancelled' },
+ { error: 'UNSUPPORTED' },
+])('requires the exact cancellation receipt: %j', async (answer) => {
+ const f = fixture({ refuse: 'INVALID_PERMISSION_MODE' }), request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload) => type === 'agent_create_cancel' ? answer : request(type, payload))
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN' })
+ expect(f.start.error).toBeNull()
+})
+
+it.each(['pending', 'unconfirmed', 'created'])('preserves native %s evidence when cancellation does not win', async (state) => {
+ const f = fixture({ refuse: 'INVALID_PERMISSION_MODE' }), request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload) => type === 'agent_create_cancel'
+ ? { creationId: f.start.creationId, state, agent: { id: 'native', engine: 'claude' } }
+ : request(type, payload))
+ const result = await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)
+ expect(result).toMatchObject(state === 'created' ? { ok: true, harnessId: 'native' } : { error: 'START_PENDING', state })
+ expect(f.start.error).toBeNull()
+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+})
+
+it.each([
+ { error: 'CAPACITY_UNAVAILABLE', detail: 'Memory was reserved by another start.' },
+ { error: 'UNSUPPORTED' },
+ { ok: true, reservationId: 'different-creation' },
+ null,
+])('requires an exact durable capacity reservation before claiming/dispatching a start: %j', async answer => {
+ const f = fixture(), request = f.request.getMockImplementation()!
+ f.request.mockImplementation(async (type, payload) => {
+ if (type === 'super_tabs' && payload?.action === 'reserveCapacity') {
+ if (answer === null) throw new Error('Lost reservation reply')
+ return answer
+ }
+ return request(type, payload)
+ })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open)).toHaveProperty('error')
+ expect(f.start.dispatched).toBe(false)
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)
+ expect(f.close).toHaveBeenCalledOnce()
+})
+
+it('retains a created agent when recording its reservation is interrupted, then joins it once', async () => {
+ const f = fixture(), request = f.request.getMockImplementation()!
+ let interrupted = true
+ f.request.mockImplementation(async (type, payload) => {
+ if (interrupted && type === 'super_tabs' && payload?.action === 'observeCapacity') {
+ interrupted = false; throw new Error('Lost receipt reply')
+ }
+ return request(type, payload)
+ })
+ const input = { action: 'resume', tabId: 'tab', startId: 'start' }
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ error: 'START_UNCERTAIN' })
+ expect(await startAgent(input, f.scoped, where, f.open)).toMatchObject({ ok: true, harnessId: 'native' })
+ expect(f.request.mock.calls.filter(c => c[0] === 'agent_create')).toHaveLength(1)
+ expect(f.scoped.mock.calls.filter(c => (c[0].command as any)?.type === 'agent.started')).toHaveLength(1)
+})
+
+it.each([true, false])('reconciles a previously created but unavailable harness only with stop proof (%s)', async released => {
+ const f = fixture(), request = f.request.getMockImplementation()!
+ f.start.dispatched = true
+ f.request.mockImplementation(async (type, payload) => {
+ if (type === 'agent_create_status') return { creationId: f.start.creationId, state: 'unavailable', createdAgentId: 'native' }
+ if (type === 'super_tabs' && payload?.action === 'observeCapacity') return { ok: true, reservationId: f.start.creationId, harnessId: 'native', released }
+ return request(type, payload)
+ })
+ expect(await startAgent({ action: 'resume', tabId: 'tab', startId: 'start' }, f.scoped, where, f.open))
+ .toMatchObject({ error: released ? 'START_FAILED' : 'START_UNCERTAIN' })
+ expect(f.start.error === null).toBe(!released)
+ expect(f.request.mock.calls.some(c => c[0] === 'agent_create')).toBe(false)
+})
diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.ts
new file mode 100644
index 000000000..49a371b0d
--- /dev/null
+++ b/cli/src/superTabs/start.ts
@@ -0,0 +1,141 @@
+import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'
+import { randomUUID } from 'node:crypto'
+import { openDaemon, type Daemon, type Where } from '../agentClient/daemon.js'
+import { admission, quotaOf, type Requirements } from './capacity.js'
+import { identifier, object } from './host.js'
+
+type Json = Record<string, unknown>
+export type ScopedRequest = (payload: Json) => Promise<Json>
+const text = (v: unknown) => typeof v === 'string' ? v : null
+const number = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null
+// These native validations run before dispatch. Storage errors, conflicts and
+// unknown failures deliberately stay uncertain: they cannot prove no launch.
+const PRE_DISPATCH_REFUSALS = new Set([
+ 'INVALID_ENGINE', 'INVALID_CWD', 'INVALID_PROJECT_SOURCE', 'INVALID_REPOSITORY',
+ 'INVALID_GRID', 'INVALID_CODEX_HOME', 'INVALID_DSH', 'INVALID_PROMPT',
+ 'PROMPT_TOO_LONG', 'PROMPT_UNSUPPORTED', 'INVALID_AGENT', 'AGENT_UNSUPPORTED',
+ 'INVALID_PERMISSION_MODE', 'INVALID_SESSION', 'INVALID_STARTED_BY', 'UNSUPPORTED_ON_REMOTE',
+])
+const CANCELLED_START = 'The machine cancelled this request before starting an agent. Review its settings and create a new start request.'
+function requireSuccess(reply: Json): Json {
+ if (reply.error || reply.ok !== true) throw new Error(String(reply.detail ?? reply.error ?? 'This Super Tab request did not succeed.'))
+ return object(reply.value)
+}
+export async function inspectCapacity(target: Daemon, request: Json) {
+ const wanted = object(request.requirements)
+ const requirements: Requirements = {
+ memoryBytes: number(wanted.memoryBytes) ?? 0, diskBytes: number(wanted.diskBytes) ?? 0,
+ maxCpuPercent: number(wanted.maxCpuPercent) ?? 100,
+ tools: Array.isArray(wanted.tools) ? wanted.tools as string[] : [], devices: Array.isArray(wanted.devices) ? wanted.devices as string[] : [],
+ quotaRequired: wanted.quotaRequired === true,
+ }
+ const [capability, engines, usage] = await Promise.allSettled([
+ target.request('super_tabs', { action: 'capacity', cwd: request.cwd, worktree: request.worktree === true, tools: requirements.tools, devices: requirements.devices }, 20_000),
+ target.request('engines_probe', { engines: [request.engine] }, 20_000),
+ target.request('usage_read', {}, 20_000),
+ ])
+ const capacity = capability.status === 'fulfilled' ? capability.value : {}
+ const choices = engines.status === 'fulfilled' && Array.isArray(engines.value.engines) ? engines.value.engines.map(object) : []
+ const engine = choices.find(e => e.engine === request.engine) ?? {}
+ const quota = quotaOf(usage.status === 'fulfilled' ? usage.value : {}, String(request.engine), !!request.codexHome || !!request.gridModel)
+ return { capacity, engine, quota, ...admission(capacity, engine, quota, requirements, !!request.codexHome || !!request.gridModel) }
+}
+
+/** Starts through the ordinary native launch protocol, with its durable receipt.
+ * This CLI owns no machine credential and does not change legacy spawn settings.
+ * Every invocation resumes the backend intent before it may open a native pane. */
+export async function startAgent(input: Json, scoped: ScopedRequest, where: Where, open: typeof openDaemon = openDaemon): Promise<Json> {
+ let startId = input.startId
+ if (input.action === 'start') {
+ const result = requireSuccess(await scoped({ action: 'command', operationId: input.operationId,
+ command: { type: 'agent.start', request: input.request } }))
+ startId = object(result.result).startId
+ }
+ if (!identifier(startId)) throw new Error('The start has no durable receipt. Do not create an agent without it.')
+ const start = requireSuccess(await scoped({ action: 'startStatus', startId }))
+ const request = object(start.request), creationId = start.creationId
+ if (!identifier(request.machineId) || !identifier(creationId)) throw new Error('This start receipt is invalid.')
+ if (start.error) return { error: 'START_FAILED', startId, detail: start.error }
+ if (start.harnessId) return { ok: true, startId, machineId: request.machineId, harnessId: start.harnessId }
+ const target = await open(where, request.machineId)
+ try {
+ let refusal: string | null = null
+ let native = await target.request('agent_create_status', { creationId }, 10_000)
+ if (native.creationId !== creationId) return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'The machine did not confirm the requested creation receipt. Nothing was dispatched.' }
+ if (native.state === 'missing') {
+ if (start.dispatched) return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'This start was submitted but its machine has no receipt. Inspect the machine before creating another agent.' }
+ const resources = await inspectCapacity(target, request)
+ if (!resources.allowed) return { error: 'CAPACITY_UNAVAILABLE', startId, ...resources }
+ const reservation = await target.request('super_tabs', { action: 'reserveCapacity', creationId,
+ cwd: request.cwd, worktree: request.worktree === true, requirements: request.requirements }, 20_000).catch(() => null)
+ if (!reservation || (reservation.ok === true && reservation.reservationId !== creationId)) {
+ return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'The machine did not confirm its capacity reservation. Keep this start ID and resume it; nothing was dispatched.' }
+ }
+ if (reservation.error || reservation.ok !== true) return { error: reservation.error ?? 'CAPACITY_UNAVAILABLE', startId,
+ detail: reservation.detail ?? 'Update Harness on the execution machine to reserve capacity before starting this agent.' }
+ // A new invocation uses a new claim. A lost claim reply never authorizes
+ // native dispatch, even if retrying the backend operation returns a receipt.
+ requireSuccess(await scoped({ action: 'command', operationId: `dispatch-${randomUUID()}`,
+ command: { type: 'agent.startDispatch', startId } }))
+ const payload: Json = { engine: request.engine, name: request.name, creationId, startedBy: 'agent',
+ prompt: `You are joining a shared Super Tab. Run harness super-tab --tab ${input.tabId} status until this harness appears in the roster. 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.`,
+ ...(request.worktree ? { projectSource: 'worktree', gitSource: request.cwd, branchName: `super-tab/${startId}`, ...(request.branchRef ? { branchRef: request.branchRef } : {}) } : { cwd: request.cwd }),
+ }
+ for (const key of ['permissionMode', 'codexHome', 'gridModel', 'gridName']) if (request[key] !== undefined) payload[key] = request[key]
+ native = await target.request('agent_create', payload, 25_000)
+ if (PRE_DISPATCH_REFUSALS.has(String(native.error))) {
+ refusal = String(native.detail ?? native.error)
+ // A durable cancellation also fences a delayed copy of this create.
+ // If dispatch won, keep its receipt and reconcile it normally instead.
+ native = await target.request('agent_create_cancel', { creationId }, 10_000).catch(() => ({}))
+ if (native.error || native.creationId !== creationId) {
+ return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: `${refusal} The machine did not confirm cancellation. Keep this start ID and resume it before starting another agent.` }
+ }
+ }
+ }
+ if (native.error) return { error: 'START_REFUSED', startId, creationId,
+ detail: String(native.detail ?? native.error) }
+ if (native.creationId !== creationId) return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'The machine answered for a different creation receipt. Nothing further was dispatched.' }
+ if (native.state === 'failed' || native.state === 'cancelled') {
+ await target.request('super_tabs', { action: 'observeCapacity', creationId }, 10_000).catch(() => {})
+ const failure = object(native.failure)
+ // The shared command stays byte-identical if its reply is lost and the
+ // next invocation sees only the durable cancellation tombstone.
+ const detail = native.state === 'cancelled' ? CANCELLED_START : String(failure.detail ?? failure.code ?? 'Native creation failed.')
+ requireSuccess(await scoped({ action: 'command', operationId: `failed-${startId}`, command: { type: 'agent.startFailed', startId, error: detail } }))
+ return { error: 'START_FAILED', startId, detail: refusal ?? detail }
+ }
+ const frame = object(native.agent)
+ const nativeId = native.state === 'unavailable' ? native.createdAgentId : frame.id
+ if (!['created', 'unavailable'].includes(String(native.state)) || !identifier(nativeId)) {
+ return { error: 'START_PENDING', startId, creationId, state: native.state ?? 'unknown',
+ detail: 'Keep this start ID. Run resume with it to check the same native creation; do not make another start request.' }
+ }
+ const reservation = await target.request('super_tabs', { action: 'observeCapacity', creationId }, 10_000).catch(() => null)
+ if (reservation?.ok !== true || reservation.reservationId !== creationId || reservation.harnessId !== nativeId) {
+ return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'The agent was created, but its capacity receipt is not confirmed. Keep this start ID and resume it before starting another agent.' }
+ }
+ if (reservation.released === true) {
+ const detail = 'The agent was created and has since stopped. Create a new start request to continue.'
+ requireSuccess(await scoped({ action: 'command', operationId: `failed-${startId}`, command: { type: 'agent.startFailed', startId, error: detail } }))
+ return { error: 'START_FAILED', startId, detail }
+ }
+ if (native.state !== 'created') return { error: 'START_UNCERTAIN', startId, creationId,
+ detail: 'The created agent is unavailable, but its stop is not confirmed. Inspect the execution machine before starting another agent.' }
+ const profile = parseRuntimeProfile(frame.selectedModel)
+ const matched = profile && profile.sessionId === nativeId && profile.engine === frame.engine ? profile : null
+ const configuration = { engine: text(frame.engine) ?? String(request.engine), model: matched?.model ?? null, effort: matched?.effort ?? null,
+ contextWindow: number(frame.contextWindow), engineVersion: text(frame.engineVersion) }
+ const joined = requireSuccess(await scoped({ action: 'command', operationId: `joined-${startId}`,
+ command: { type: 'agent.started', startId, harnessId: nativeId, configuration } }))
+ await target.request('super_tabs', { action: 'wake' }).catch(() => {})
+ await target.request('harness_share_rosters', {}).catch(() => {})
+ return { ok: true, startId, machineId: request.machineId, harnessId: nativeId, ...object(joined.result) }
+ } finally { target.close() }
+}
diff --git a/cli/src/superTabs/wire.ts b/cli/src/superTabs/wire.ts
new file mode 100644
index 000000000..2d1e00877
--- /dev/null
+++ b/cli/src/superTabs/wire.ts
@@ -0,0 +1,3 @@
+type Json = Record<string, unknown>
+export const object = (v: unknown): Json => v && typeof v === 'object' && !Array.isArray(v) ? v as Json : {}
+export const identifier = (v: unknown): v is string => typeof v === 'string' && /^[A-Za-z0-9_-]{1,160}$/.test(v)
diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.ts
index f3520acec..a243e7b6f 100644
--- a/cli/src/testing/fakeCore.ts
+++ b/cli/src/testing/fakeCore.ts
@@ -43,6 +43,7 @@ export function fakeCore(over: Overrides = {}): CoreApi {
turns: {
send: vi.fn(), stop: vi.fn(), recent: vi.fn(async () => []), asks: vi.fn(async () => []),
deliver: vi.fn(), cancelDelivery: vi.fn(() => false), onDelivery: vi.fn(() => () => {}),
+ leaseDeliveries: vi.fn(async () => true),
...over.turns,
},
questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => false), ...over.questions },
diff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dart
new file mode 100644
index 000000000..2a12f3245
--- /dev/null
+++ b/desktop/integration_test/super_tab_native_test.dart
@@ -0,0 +1,186 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:integration_test/integration_test.dart';
+import 'package:window_manager/window_manager.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/super_tabs/workspace.dart';
+import 'package:harness/widgets/pane_grid.dart';
+
+import '../test/super_tab_launch_test.dart'
+ show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;
+
+/// A real Flutter/macOS surface with in-memory accounts and native protocol
+/// fixtures. It never opens a production daemon, account, harness or database.
+void main() {
+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');
+ final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized()
+ ..framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
+ testWidgets(
+ 'native Super Tab keeps group context, people and terminal in one workspace',
+ (tester) async {
+ debugPrint('Super Tab fixture: initialize window');
+ await windowManager.ensureInitialized().timeout(
+ const Duration(seconds: 10),
+ );
+ await windowManager
+ .setSize(const Size(1280, 800))
+ .timeout(const Duration(seconds: 10));
+ await windowManager.show().timeout(const Duration(seconds: 10));
+ await windowManager.focus().timeout(const Duration(seconds: 10));
+ debugPrint('Super Tab fixture: create lead');
+ final f = SuperTabLaunchFixture();
+ f.connection.nativeSurface = true;
+ f.app.machineStates['m']!.terminalCapabilityAvailable = true;
+ await tester.runAsync(() async {
+ final box = await f.box(engine: 'claude');
+ expect(
+ await box.create().timeout(const Duration(seconds: 20)),
+ NewHarnessOutcome.created,
+ reason: box.error,
+ );
+ });
+ debugPrint('Super Tab fixture: show conversation');
+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];
+ final server = f.connection.server;
+ server.state['name'] = 'Pilot';
+ (server.state['conversations'] as List)[0]['agentIds'] = ['lead-agent'];
+ (server.state['conversations'] as List)[0]['leadId'] = 'lead-agent';
+ (server.state['people'] as List).addAll(
+ List.generate(
+ 19,
+ (i) => {
+ 'id': 'person-$i',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ },
+ ),
+ );
+ server.append(
+ 'Let’s agree on the offline editing behavior before building.',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ server.append(
+ 'Keep changes on the device and sync when the connection returns.',
+ );
+ debugPrint('Super Tab fixture: load conversation controller');
+ final c = await tester.runAsync(() async {
+ final controller = await f.app.superTabs
+ .open(tabId)
+ .timeout(const Duration(seconds: 10));
+ debugPrint('Super Tab fixture: refresh conversation');
+ await controller.refresh().timeout(const Duration(seconds: 10));
+ return controller;
+ });
+ expect(c, isNotNull);
+ debugPrint(
+ 'Super Tab fixture: render first frame '
+ '(lifecycle=${binding.lifecycleState}, '
+ 'framesEnabled=${binding.framesEnabled}, '
+ 'visible=${await windowManager.isVisible()}, '
+ 'minimized=${await windowManager.isMinimized()}, '
+ 'focused=${await windowManager.isFocused()})',
+ );
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (context, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: PaneGrid(notifier: f.app, swarmMode: true),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ debugPrint('Super Tab fixture: first frame painted');
+ await tester.pumpAndSettle(
+ const Duration(milliseconds: 100),
+ EnginePhase.sendSemanticsUpdate,
+ const Duration(seconds: 10),
+ );
+ debugPrint('Super Tab fixture: conversation settled');
+ expect(find.text('1 agent · 20 people'), findsOneWidget);
+ expect(find.text('CHATS'), findsNothing);
+ expect(find.text('New group'), findsOneWidget);
+ expect(find.text('Invite'), findsOneWidget);
+ final folder = Platform.environment['SUPER_TAB_NATIVE_SHOTS'];
+ Future<void> shot(String name) async {
+ if (folder == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await render.toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(folder).create(recursive: true);
+ await File('$folder/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ }
+
+ await shot('conversation');
+ debugPrint('Super Tab fixture: open participants');
+ await tester.tap(find.text('1 agent · 20 people'));
+ debugPrint('Super Tab fixture: participants tapped');
+ await tester.pumpAndSettle();
+ debugPrint('Super Tab fixture: participants settled');
+ expect(find.text('Lead'), findsWidgets);
+ expect(find.text('Open terminal'), findsOneWidget);
+ await tester.tap(find.text('Open terminal'));
+ debugPrint('Super Tab fixture: terminal requested');
+ for (var i = 0; i < 30 && f.app.activeSwarm.panes.isEmpty; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ expect(f.app.activeSwarm.panes, hasLength(1));
+ final machine = f.app.machineStates['m']!;
+ debugPrint(
+ 'Super Tab fixture: native prerequisites '
+ 'online=${machine.nodeOnline} capability=${machine.terminalCapabilityAvailable} '
+ 'agents=${machine.agents.map((a) => '${a.id}:${a.terminalAvailable}').join(',')} '
+ 'session=${f.app.activeSwarm.panes.single.session?.status}',
+ );
+ // A live terminal keeps its cursor animated. Wait for the protocol's
+ // readiness, not for the entire window to stop scheduling frames.
+ for (
+ var i = 0;
+ i < 120 && f.app.activeSwarm.panes.single.session?.streamId == null;
+ i++
+ ) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ expect(
+ f.app.activeSwarm.panes.single.session?.streamId,
+ SuperTabFixtureConnection.streamId,
+ reason: 'Native terminal did not attach: ${f.connection.terminalCalls}',
+ );
+ expect(f.app.activeSwarm.panes.single.inputContext, isNotNull);
+ await tester.pump(const Duration(milliseconds: 100));
+ debugPrint('Super Tab fixture: terminal ready');
+ await shot('terminal');
+ expect(find.byType(PaneGrid), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await c!.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ timeout: const Timeout(Duration(minutes: 2)),
+ );
+}
diff --git a/desktop/lib/e2ee/envelope.dart b/desktop/lib/e2ee/envelope.dart
index 64800f03c..09c91ab5a 100644
--- a/desktop/lib/e2ee/envelope.dart
+++ b/desktop/lib/e2ee/envelope.dart
@@ -38,6 +38,7 @@ const Set<String> encryptedDownTypes = {
'connectors',
// Sharing a machine across accounts (CLI services/sharedMachines.ts): the addresses it is shared with.
'shared_machines',
+ 'super_tabs',
'orchestrator',
'route_task',
'route_send',
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 3f06c8fda..1273ea226 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -69,6 +69,10 @@ import '../state/harness_activity.dart';
import '../state/harness_attachments.dart';
import '../state/harness_placement.dart';
import '../state/new_harness.dart';
+import '../state/harness_launch_integration.dart';
+import '../super_tabs/launch.dart';
+import '../super_tabs/workspace.dart';
+import '../super_tabs/actions.dart';
import 'swarm_menu_bus.dart';
import '../state/device_form.dart';
import '../state/device_finder.dart';
@@ -520,6 +524,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
!app.activeSwarm.isStore &&
!app.activeSwarm.isDevices &&
!app.activeSwarm.isOrchestrator &&
+ (!app.activeSwarm.isSuperTab || app.activeSwarm.superTabId == null) &&
_newHarness == null &&
_search == null &&
!_pickingFolder &&
@@ -904,6 +909,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_searchOverlay?.remove();
_searchOverlay?.dispose();
_searchDevice?.close();
+ _stopSuperTabPickerWatch?.call();
_search?.dispose();
_pickerModels?.dispose();
_previewControls.dispose();
@@ -2108,6 +2114,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
'swarm.select_${app.profileSwarms.indexOf(swarm) + 1}',
),
'kind': swarm.kind,
+ if (swarm.superTabId != null &&
+ app.superTabs.peek(swarm.superTabId!)?.canWrite == true)
+ 'superTabPaused':
+ app.superTabs.peek(swarm.superTabId!)?.snapshot?.paused ??
+ false,
'agentCount': _tabAgents(swarm).length,
'engine': swarm.isStore ? 'store' : _tabEngine(swarm),
'iconAsset': swarm.isStore
@@ -2489,6 +2500,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
// offered.
case 'invitePeople':
unawaited(_invitePeople(_nativeTabId(args)));
+ case 'pauseSuperTab':
+ unawaited(_pauseSuperTab(_nativeTabId(args)));
case 'stopSharingTab':
unawaited(_stopSharingTab(_nativeTabId(args)));
case 'moveTabHere':
@@ -2853,9 +2866,36 @@ class _SwarmScreenState extends State<SwarmScreen> {
workspaceTabNames(app)[id] ?? swarm.name,
keymap: _keymap,
);
- if (name != null) app.renameSwarm(id, name);
+ if (name == null) return;
+ if (swarm.superTabId case final tabId?) {
+ final controller = await app.superTabs.open(tabId);
+ final result = await controller.command({
+ 'type': 'tab.rename',
+ 'name': name,
+ });
+ if (result == null && mounted)
+ _showPaneActionHint(
+ controller.operationError ?? 'Could not rename the Super Tab.',
+ );
+ } else {
+ app.renameSwarm(id, name);
+ }
});
+ Future<void> _pauseSuperTab(String swarmId) async {
+ final id = app.swarms.where((s) => s.id == swarmId).firstOrNull?.superTabId;
+ if (id == null) return;
+ final controller = await app.superTabs.open(id);
+ final result = await controller.command({
+ 'type': 'tab.pause',
+ 'paused': controller.snapshot?.paused != true,
+ });
+ if (result == null && mounted)
+ _showPaneActionHint(
+ controller.operationError ?? 'Could not change new work.',
+ );
+ }
+
/// The tab a native action names, or the active one (File's rows).
String _nativeTabId(Map args) =>
args['id'] is String ? args['id'] as String : app.activeSwarmId;
@@ -3434,6 +3474,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
String? engine,
String? projectName,
String? task,
+ String? superTabConversationId,
HarnessPlacement? placement,
_NewHarnessSource source = _NewHarnessSource.workspace,
bool Function()? stillCurrent,
@@ -3457,6 +3498,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
placement = HarnessPlacement.newTab;
}
final target = swarmId ?? search?.targetId ?? app.activeSwarmId;
+ final superTab = app.swarms
+ .where((s) => s.id == target && s.isSuperTab)
+ .firstOrNull;
+ final conversation = superTabConversationId ??
+ (superTab?.superTabId == null
+ ? 'lead'
+ : search != null && _superTabAddTarget?.swarmId == target
+ ? _superTabAddTarget!.groupId
+ : app.superTabs.peek(superTab!.superTabId!)?.selectedId ?? 'lead');
final requestedSplit = split ?? search?.split;
if (app.activeSwarmId != target) return;
_rememberWorkingProject();
@@ -3528,7 +3578,20 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.panes.isEmpty &&
!app.activeSwarm.isStore &&
!app.activeSwarm.isDevices &&
- !app.activeSwarm.isOrchestrator;
+ !app.activeSwarm.isOrchestrator &&
+ (!app.activeSwarm.isSuperTab || app.activeSwarm.superTabId == null);
+ HarnessLaunchIntegration? integration;
+ if (superTab != null &&
+ requestedSplit == null &&
+ placement != HarnessPlacement.newTab) {
+ try {
+ integration = await SuperTabLaunch.open(app, superTab, conversation);
+ } catch (failure) {
+ _showPaneActionHint(failure.toString());
+ return;
+ }
+ if (!mounted || app.activeSwarmId != target) return;
+ }
final welcomeOrigin = embedded
? _newHarnessDrafts.keys
.where((key) => key.welcomeTabId == target)
@@ -3536,6 +3599,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
: null;
_openNewHarness(
machineId: id,
+ integration: integration,
// ⌘⇧T is how a shell is made; New Harness from a shell means an agent.
engine: engine ?? (isTerminalEngine(inherited) ? null : inherited),
harnessId: engine == null ? agent?.dsh : null,
@@ -3638,6 +3702,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
PaneSplitRequest? split,
HarnessPlacement? placement,
bool embedded = false,
+ HarnessLaunchIntegration? integration,
}) {
// A dialog's pop future can complete before didChangeDependencies refreshes
// the cached route flag. Its live route already owns the next prompt.
@@ -3720,6 +3785,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
split: split,
placement: placement,
attachments: HarnessAttachments(onDeliveryProblem: _showPaneActionHint),
+ integration: integration,
);
_newHarnessFormKey = GlobalKey<NewHarnessFormState>();
_newHarnessDevicePort = DeviceFormPort();
@@ -4186,6 +4252,30 @@ class _SwarmScreenState extends State<SwarmScreen> {
PaneSplitRequest? split,
HarnessPlacement? placement,
}) async {
+ final adding = _superTabAddTarget;
+ _superTabAddTarget = null;
+ if (adding != null &&
+ adding.swarmId == target &&
+ selected.destination.agentId != null) {
+ try {
+ final agents = selected.agents.isEmpty
+ ? [selected.destination]
+ : selected.agents;
+ for (final chosen in agents) {
+ if (chosen.machineId == null || chosen.agentId == null) continue;
+ await addSuperTabAgent(
+ app,
+ adding.tabId,
+ adding.groupId,
+ chosen.machineId!,
+ chosen.agentId!,
+ );
+ }
+ } catch (failure) {
+ if (mounted) _showPaneActionHint(failure.toString());
+ }
+ return;
+ }
final command = selected.destination.commandId;
if (command != null) {
// The result list is gone before a dialog or focus-changing command runs.
@@ -5844,6 +5934,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
PaneSplitRequest? split,
String query = '',
HarnessPlacement? placement,
+ ({String swarmId, String tabId, String groupId})? superTabTarget,
}) {
if (_search != null ||
!mounted ||
@@ -5864,15 +5955,68 @@ class _SwarmScreenState extends State<SwarmScreen> {
_searchReturnFocus ??= FocusManager.instance.primaryFocus == _searchFocus
? null
: FocusManager.instance.primaryFocus;
+ _superTabAddTarget = superTabTarget;
if (_native) _preparePaneFocus();
// Search is an overlay, so late pane attachment needs an explicit focus
// boundary to keep its programmatic focus request out of the picker.
_canvasFocus.descendantsAreFocusable = false;
_searchInputKey = GlobalKey();
_resourcePreviewKey = GlobalKey();
+ final contribution = superTabTarget == null
+ ? null
+ : app.superTabs.peek(superTabTarget.tabId);
+ final groupTitle = superTabTarget == null
+ ? null
+ : contribution?.snapshot?.conversation(superTabTarget.groupId)?.title;
_search = SwarmSearchController(
app,
_navigation.recent,
+ harnessContext: superTabTarget == null
+ ? null
+ : HarnessPickerContext(
+ title: 'Add agent to ${groupTitle ?? 'conversation'}',
+ description: 'Shared with everyone in ${app.activeSwarm.name}.',
+ action: 'Add agent',
+ unavailable: (row) {
+ final shared = app.superTabs.peek(superTabTarget.tabId)?.snapshot;
+ final agent = shared?.agents.where(
+ (agent) => agent.machineId == row.machineId &&
+ agent.harnessId == row.agentId,
+ ).firstOrNull;
+ if (agent != null) {
+ return shared!.conversation(superTabTarget.groupId)
+ ?.agentIds.contains(agent.id) == true
+ ? 'Already in this conversation.'
+ : null;
+ }
+ final native = app.stateOf(row.machineId ?? '')?.agents
+ .where((agent) => agent.id == row.agentId)
+ .firstOrNull;
+ return native != null &&
+ native.engine != 'terminal' &&
+ native.terminalAvailable &&
+ !native.isStopped
+ ? null
+ : 'Choose a running agent.';
+ },
+ ),
+ additionalDestinations: [
+ if (superTabTarget != null)
+ for (final agent
+ in app.superTabs.peek(superTabTarget.tabId)?.snapshot?.agents ??
+ [])
+ SwarmDestination(
+ id: agentDestinationId(agent.machineId, agent.harnessId),
+ title: agent.name,
+ detail:
+ '${engineIdentity(agent.engine).label} · ${app.stateOf(agent.machineId)?.machine.displayName ?? 'Shared agent'}',
+ swarmId: superTabTarget.swarmId,
+ current: false,
+ machineId: agent.machineId,
+ agentId: agent.harnessId,
+ engine: agent.engine,
+ ),
+ ],
projects: _projects,
commands: _searchCommands,
recentCommands: () => _navigation.recentCommands,
@@ -5883,9 +6027,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
),
adding: adding,
offersCreate: adding,
- offersHarnessCreate: split != null,
+ offersHarnessCreate: split != null || superTabTarget != null,
activityFirst: split == null,
- selectOnEmptyQuery: split != null,
+ selectOnEmptyQuery: split != null || superTabTarget != null,
// Results read downward from the input.
resultsFromBottom: false,
noteFor: _easterNote,
@@ -5893,13 +6037,31 @@ class _SwarmScreenState extends State<SwarmScreen> {
placement:
placement ??
(adding && split == null
- ? (app.activeSwarm.isUtility || app.activeSwarm.isOrchestrator
+ ? (app.activeSwarm.isUtility ||
+ app.activeSwarm.isOrchestrator ||
+ (superTabTarget == null &&
+ app.activeSwarm.isSuperTab &&
+ app.activeSwarm.superTabId != null)
? HarnessPlacement.newTab
: HarnessPlacement.currentTab)
: null),
catalog: _searchCatalog,
)..setQuery(query);
final deviceSearch = _search!;
+ if (contribution != null && superTabTarget != null) {
+ void guardContribution() {
+ if (!mounted || !identical(_search, deviceSearch)) return;
+ final group = contribution.snapshot?.conversation(superTabTarget.groupId);
+ if (!contribution.canWrite || group == null || group.archived) {
+ _closeSearch();
+ } else {
+ deviceSearch.refreshAvailability();
+ }
+ }
+ contribution.addListener(guardContribution);
+ _stopSuperTabPickerWatch = () =>
+ contribution.removeListener(guardContribution);
+ }
_searchDevice = DeviceFinder(
deviceSearch,
isComposing: () =>
@@ -6088,6 +6250,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
void _closeSearch({bool restoreFocus = true}) {
if (_search == null) return;
+ _stopSuperTabPickerWatch?.call();
+ _stopSuperTabPickerWatch = null;
_machineSearchVisible = false;
_storeSearchVisible = false;
// Enable the chosen terminal synchronously, before activation requests its
@@ -6327,12 +6491,16 @@ class _SwarmScreenState extends State<SwarmScreen> {
// What was typed and found nothing is what the new harness starts on.
final task = choice.destination.task;
final machineId = _search!.scopedMachineId;
+ final conversationId = _superTabAddTarget?.swarmId == target
+ ? _superTabAddTarget!.groupId
+ : null;
_closeSearch(restoreFocus: false);
await _newAgent(
machineId: machineId,
swarmId: target,
split: split,
task: task,
+ superTabConversationId: conversationId,
placement: placement,
);
return;
@@ -6517,24 +6685,45 @@ class _SwarmScreenState extends State<SwarmScreen> {
FocusManager.instance.applyFocusChangesIfNeeded();
}
- Future<void> _addAgent({String query = '#'}) async {
+ ({String swarmId, String tabId, String groupId})? _superTabAddTarget;
+ VoidCallback? _stopSuperTabPickerWatch;
+
+ Future<void> _addAgent({String query = '#', String? conversationId}) async {
if ((app.activeSwarm.isUtility || app.activeSwarm.isOrchestrator) &&
!_newTab()) {
return;
}
- if (_search?.changePlacement(HarnessPlacement.currentTab) == true) {
+ if (!app.activeSwarm.isSuperTab &&
+ _search?.changePlacement(HarnessPlacement.currentTab) == true) {
_focusSearch();
return;
}
_closeSearch(restoreFocus: false);
+ final tab = app.activeSwarm;
+ final superTabTarget = tab.isSuperTab && tab.superTabId != null
+ ? (
+ swarmId: tab.id,
+ tabId: tab.superTabId!,
+ groupId:
+ conversationId ??
+ app.superTabs.peek(tab.superTabId!)?.selectedId ??
+ 'lead',
+ )
+ : null;
+ if (superTabTarget != null) {
+ final controller = app.superTabs.peek(superTabTarget.tabId);
+ final group = controller?.snapshot?.conversation(superTabTarget.groupId);
+ if (controller?.canWrite != true || group == null || group.archived) return;
+ }
_openSearch(
adding: true,
placement: HarnessPlacement.currentTab,
- query: query,
+ query: superTabTarget == null ? query : '',
+ superTabTarget: superTabTarget,
);
}
- bool _newTab() {
+ bool _newTab({bool superTab = false}) {
if (!mounted || _dialogOpen || _spokenPaletteOpen || !_routeIsCurrent) {
return false;
}
@@ -6551,6 +6740,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
dismissTransientMenus();
_preparePaneFocus();
app.newSwarm(newTabPage: true);
+ if (superTab) app.markSuperTabDraft(app.activeSwarmId);
_newTabSources.removeWhere(
(id, _) => !app.swarms.any((tab) => tab.id == id),
);
@@ -7064,6 +7254,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
'app.daemon': _openCompanions,
'app.daemon_talk': _talkToDaemon,
'agent.add': _addAgent,
+ 'super_tab.new': () => _newTab(superTab: true),
if (kDebugSurfaceEnabled) 'app.onboarding_review': _newTab,
'agent.rename': () => _editAgent(),
'agent.work': () async {
@@ -7195,7 +7386,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
number >= 1 &&
number <= app.profileSwarms.length;
}
- if (id == 'swarm.new') return true;
+ if (id == 'swarm.new' || id == 'super_tab.new') return true;
if (id == 'swarm.reopen') return app.canReopenLastClosed;
if (id == 'swarm.next' || id == 'swarm.previous') {
return app.profileSwarms.length > 1;
@@ -7593,7 +7784,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
!_creatureEnabled) ||
app.activeSwarm.isOrchestrator,
child: Padding(
- padding: app.panes.isEmpty
+ padding: app.panes.isEmpty || app.activeSwarm.isSuperTab
? EdgeInsets.zero
: const EdgeInsets.fromLTRB(
kWorkspaceInset,
@@ -7601,155 +7792,162 @@ class _SwarmScreenState extends State<SwarmScreen> {
kWorkspaceInset,
0,
),
- child: Focus.withExternalFocusNode(
- focusNode: _canvasFocus,
- includeSemantics: false,
- child: Stack(
- children: [
- Positioned.fill(
- child: PaneShareStatus(
- visible:
- widget
- .chrome
- ?.showsShareStatus ==
- true,
- child: PaneOpacity(
- opacity: appearancePrefsStore
- .value
- .effectivePaneOpacity,
- child: PaneGrid(
- notifier: app,
- swarmMode: true,
- onOpenModels:
- _openPaneModels,
- onSplitPane:
- (paneId, axis) =>
- unawaited(
- _splitAgent(
- axis,
- paneId: paneId,
+ child: SuperTabWorkspace(
+ app: app,
+ onAddAgent: (group) => unawaited(
+ _addAgent(conversationId: group.id),
+ ),
+ canvas: Focus.withExternalFocusNode(
+ focusNode: _canvasFocus,
+ includeSemantics: false,
+ child: Stack(
+ children: [
+ Positioned.fill(
+ child: PaneShareStatus(
+ visible:
+ widget
+ .chrome
+ ?.showsShareStatus ==
+ true,
+ child: PaneOpacity(
+ opacity: appearancePrefsStore
+ .value
+ .effectivePaneOpacity,
+ child: PaneGrid(
+ notifier: app,
+ swarmMode: true,
+ onOpenModels:
+ _openPaneModels,
+ onSplitPane:
+ (paneId, axis) =>
+ unawaited(
+ _splitAgent(
+ axis,
+ paneId:
+ paneId,
+ ),
),
- ),
- devicesViewer:
- app.devicesEnabled
- ? _devicesViewer
- : null,
- devicesConversation:
- app.devicesEnabled
- ? _devicesConversation
- : null,
- companionViewer:
- _creatureEnabled
- ? _companionViewer
- : null,
- companionConversation:
- _creatureEnabled
- ? _companionConversation
- : null,
- soloFocused: _compact(
- context,
- ),
- empty:
- app.panes.isEmpty &&
- !app
- .activeSwarm
- .isUtility &&
- !app
- .activeSwarm
- .isOrchestrator
- ? newHarnessOpensInBox ||
- app
- .activeSwarm
- .isNewTabPage
- ? _startGuide()
- : HarnessStartPage(
- key: ValueKey(
- 'harness-start:${app.activeSwarmId}',
- ),
- focusNode:
- _startSearchFocus,
- createSearch: () => SwarmSearchController(
- app,
- _navigation
- .recent,
- projects:
- _projects,
- commands:
- _searchCommands,
- recentCommands: () =>
- _navigation
- .recentCommands,
- // The first box a new
- // person meets is the same
- // box: its placeholder
- // promises `?` and a way
- // to create, so it has them.
- modes:
- _searchModes,
- adding:
- true,
- offersCreate:
- true,
- placement:
- HarnessPlacement
- .currentTab,
- catalog:
- _searchCatalog,
- ),
- onNewTab:
- _newTab,
- onNewPane: () =>
- unawaited(
- _addAgent(
- query: '',
+ devicesViewer:
+ app.devicesEnabled
+ ? _devicesViewer
+ : null,
+ devicesConversation:
+ app.devicesEnabled
+ ? _devicesConversation
+ : null,
+ companionViewer:
+ _creatureEnabled
+ ? _companionViewer
+ : null,
+ companionConversation:
+ _creatureEnabled
+ ? _companionConversation
+ : null,
+ soloFocused: _compact(
+ context,
+ ),
+ empty:
+ app.panes.isEmpty &&
+ !app
+ .activeSwarm
+ .isUtility &&
+ !app
+ .activeSwarm
+ .isOrchestrator
+ ? newHarnessOpensInBox ||
+ app
+ .activeSwarm
+ .isNewTabPage
+ ? _startGuide()
+ : HarnessStartPage(
+ key: ValueKey(
+ 'harness-start:${app.activeSwarmId}',
+ ),
+ focusNode:
+ _startSearchFocus,
+ createSearch: () => SwarmSearchController(
+ app,
+ _navigation
+ .recent,
+ projects:
+ _projects,
+ commands:
+ _searchCommands,
+ recentCommands:
+ () =>
+ _navigation.recentCommands,
+ // The first box a new
+ // person meets is the same
+ // box: its placeholder
+ // promises `?` and a way
+ // to create, so it has them.
+ modes:
+ _searchModes,
+ adding:
+ true,
+ offersCreate:
+ true,
+ placement:
+ HarnessPlacement
+ .currentTab,
+ catalog:
+ _searchCatalog,
+ ),
+ onNewTab:
+ _newTab,
+ onNewPane: () =>
+ unawaited(
+ _addAgent(
+ query: '',
+ ),
+ ),
+ onCommands:
+ _showSearchCommands,
+ onQuickStart:
+ _learning
+ .offer
+ ? _startQuickStart
+ : null,
+ onPractice:
+ _practiceKeyboard,
+ onNew: () => _newAgent(
+ placement:
+ HarnessPlacement
+ .currentTab,
+ ),
+ onNewWithTask:
+ (
+ task,
+ ) => _newAgent(
+ task:
+ task,
+ placement:
+ HarnessPlacement.currentTab,
),
- ),
- onCommands:
- _showSearchCommands,
- onQuickStart:
- _learning
- .offer
- ? _startQuickStart
- : null,
- onPractice:
- _practiceKeyboard,
- onNew: () => _newAgent(
- placement:
- HarnessPlacement
- .currentTab,
- ),
- onNewWithTask:
- (
- task,
- ) => _newAgent(
- task:
- task,
- placement:
- HarnessPlacement.currentTab,
- ),
- onStore:
- _openStore,
- onResourceSearch:
- (
- query,
- ) => _openSearch(
- adding:
- true,
- query:
- query,
- ),
- onChoose:
- _chooseStartSearch,
- )
- : null,
+ onStore:
+ _openStore,
+ onResourceSearch:
+ (
+ query,
+ ) => _openSearch(
+ adding:
+ true,
+ query:
+ query,
+ ),
+ onChoose:
+ _chooseStartSearch,
+ )
+ : null,
+ ),
),
),
),
- ),
- if (_firstConnection(context)
- case final connect?)
- Positioned.fill(child: connect),
- ],
+ if (_firstConnection(context)
+ case final connect?)
+ Positioned.fill(child: connect),
+ ],
+ ),
),
),
),
@@ -8418,6 +8616,22 @@ class _SwarmScreenState extends State<SwarmScreen> {
'swarm.select_${index + 1}',
),
onRename: () => _rename(swarm.id),
+ onPauseNewWork:
+ menus &&
+ swarm.superTabId != null &&
+ app.superTabs
+ .peek(swarm.superTabId!)
+ ?.canWrite ==
+ true
+ ? () => unawaited(_pauseSuperTab(swarm.id))
+ : null,
+ newWorkPaused:
+ swarm.superTabId != null &&
+ app.superTabs
+ .peek(swarm.superTabId!)
+ ?.snapshot
+ ?.paused ==
+ true,
label: labels[index],
selected: selected,
tooltip: tabHint.isEmpty ? null : tabHint,
diff --git a/desktop/lib/settings/experimental_features.dart b/desktop/lib/settings/experimental_features.dart
index 3e166924b..1a0a476d3 100644
--- a/desktop/lib/settings/experimental_features.dart
+++ b/desktop/lib/settings/experimental_features.dart
@@ -54,6 +54,10 @@ enum ExperimentalFeature {
const ExperimentalFeature(this.id, this.label, this.description);
final String id, label, description;
+ /// Super Tab owns coordination. Keep the old wire values readable for existing
+ /// clients and sessions, without asking people to assemble the feature here.
+ bool get visibleInSettings => this == focusBarCreature || this == shareButton;
+
/// The switch shows the opposite of the stored value.
bool get inverted => this == agentMessagesHideSummary;
bool get available => switch (this) {
diff --git a/desktop/lib/settings/sections/experimental_section.dart b/desktop/lib/settings/sections/experimental_section.dart
index f06519e45..dd1768f29 100644
--- a/desktop/lib/settings/sections/experimental_section.dart
+++ b/desktop/lib/settings/sections/experimental_section.dart
@@ -37,7 +37,9 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
@override
Widget build(BuildContext context) {
final preferences = widget.store ?? _fallbackStore;
- final features = ExperimentalFeature.values.where((f) => f.available);
+ final features = ExperimentalFeature.values.where(
+ (f) => f.available && f.visibleInSettings,
+ );
return SectionScaffold(
title: 'Experimental',
subtitle: 'Try features that are still taking shape. Account experiments sync across your devices.',
@@ -115,16 +117,9 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
)
: null,
),
- // Product usage sharing is the account's, as the experiments are, and sits among them as one more row,
- // after the agents' own pull request line (owner, 2026-10-17).
- if (feature == ExperimentalFeature.agentPullRequestLine &&
- !kIsWeb &&
- widget.notifier != null)
- ProductUsageSetting(
- notifier: widget.notifier!,
- compact: true,
- ),
],
+ if (!kIsWeb && widget.notifier != null)
+ ProductUsageSetting(notifier: widget.notifier!, compact: true),
],
),
),
diff --git a/desktop/lib/settings/sections/tab_invites_section.dart b/desktop/lib/settings/sections/tab_invites_section.dart
index b61d8e98f..40afd40dc 100644
--- a/desktop/lib/settings/sections/tab_invites_section.dart
+++ b/desktop/lib/settings/sections/tab_invites_section.dart
@@ -10,6 +10,7 @@ import '../../shared/theme/app_theme.dart';
import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/setting_row.dart';
import '../../state/app_state.dart';
+import '../../super_tabs/model.dart';
/// Settings ▸ Tab invites: the invitations to shared tabs waiting for an
/// answer, and the tabs whose owner's computer has a new key.
@@ -23,11 +24,85 @@ class TabInvitesSection extends StatefulWidget {
}
class _TabInvitesSectionState extends State<TabInvitesSection> {
+ List<Map<String, dynamic>> _superInvites = [], _superTabs = [];
+ String? _superError, _accepting;
+ bool _loadingSuper = true;
+ Timer? _refreshTimer;
+ int _read = 0;
@override
void initState() {
super.initState();
// Read when the panel opens, so an invitation that arrived a moment ago is here.
unawaited(widget.notifier.sharedTabs.refresh());
+ unawaited(_refreshSuper());
+ _refreshTimer = Timer.periodic(
+ const Duration(seconds: 15),
+ (_) => unawaited(_refreshSuper()),
+ );
+ }
+
+ @override
+ void dispose() {
+ _refreshTimer?.cancel();
+ super.dispose();
+ }
+
+ Future<void> _refreshSuper() async {
+ final read = ++_read;
+ try {
+ final client = widget.notifier.superTabs;
+ final answers = await Future.wait([
+ client.request('GET', '/api/super-tabs/invitations'),
+ client.request('GET', '/api/super-tabs'),
+ ]);
+ if (!mounted || read != _read) return;
+ setState(() {
+ _superInvites = (answers[0] as List).map(superTabMap).toList();
+ _superTabs = (superTabMap(answers[1])['tabs'] as List)
+ .map(superTabMap)
+ .toList();
+ _superError = null;
+ _loadingSuper = false;
+ });
+ } catch (failure) {
+ if (mounted && read == _read) {
+ setState(() {
+ _superError = failure.toString();
+ _loadingSuper = false;
+ });
+ }
+ }
+ }
+
+ Future<void> _acceptSuper(Map<String, dynamic> invite) async {
+ if (_accepting != null) return;
+ setState(() => _accepting = invite['inviteId'] as String);
+ try {
+ final app = widget.notifier;
+ final reply = await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${invite['tabId']}/commands',
+ body: {
+ 'operationId': 'accept-${invite['inviteId']}',
+ 'command': {'type': 'invite.accept', 'inviteId': invite['inviteId']},
+ },
+ );
+ final tabId = invite['tabId'] as String;
+ final controller = await app.superTabs.open(tabId);
+ await controller.refresh();
+ final result = superTabMap(reply['result']);
+ if (result['conversationId'] is String) {
+ controller.select(result['conversationId'] as String);
+ }
+ if (!mounted) return;
+ app.openSuperTab(tabId, invite['name'] as String);
+ await _refreshSuper();
+ if (mounted) await Navigator.of(context).maybePop();
+ } catch (failure) {
+ if (mounted) setState(() => _superError = failure.toString());
+ } finally {
+ if (mounted) setState(() => _accepting = null);
+ }
}
static String _expires(String iso) {
@@ -46,7 +121,51 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
child: SingleChildScrollView(
child: ListenableBuilder(
listenable: widget.notifier.sharedTabs,
- builder: (context, _) => _body(context),
+ builder: (context, _) => Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (_loadingSuper) const LinearProgressIndicator(),
+ if (_superError != null)
+ SettingRow(
+ title: 'Could not load Super Tabs',
+ detail: _superError,
+ control: TextButton(
+ onPressed: _refreshSuper,
+ child: const Text('Retry'),
+ ),
+ ),
+ for (final invite in _superInvites)
+ SettingRow(
+ title: invite['name'] as String,
+ detail:
+ 'Super Tab · ${invite['role'] == 'viewer' ? 'Can view' : 'Can collaborate'}',
+ control: FilledButton(
+ onPressed: _accepting == null
+ ? () => _acceptSuper(invite)
+ : null,
+ child: Text(
+ _accepting == invite['inviteId'] ? 'Joining…' : 'Accept',
+ ),
+ ),
+ ),
+ for (final tab in _superTabs)
+ SettingRow(
+ title: tab['name'] as String,
+ detail: 'Super Tab',
+ control: TextButton(
+ onPressed: () {
+ widget.notifier.openSuperTab(
+ tab['id'] as String,
+ tab['name'] as String,
+ );
+ Navigator.of(context).maybePop();
+ },
+ child: const Text('Open'),
+ ),
+ ),
+ _body(context),
+ ],
+ ),
),
),
);
@@ -59,13 +178,15 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
case SharedTabsState.unknown:
return const _Skeleton();
case SharedTabsState.off:
- return const Text(
- 'Turn on "Agents in the same tab can message each other" in Experimental to get invitations.',
- );
+ return _superInvites.isEmpty && !_loadingSuper && _superError == null
+ ? const Text('No invitations.')
+ : const SizedBox.shrink();
case SharedTabsState.tooOld:
return UpdateHarnessLine(widget.notifier);
case SharedTabsState.unsupported:
- return const Text('Shared tabs aren\'t available on the Harness service yet.');
+ return const Text(
+ 'Shared tabs aren\'t available on the Harness service yet.',
+ );
case SharedTabsState.unavailable:
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -100,7 +221,9 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
alignment: Alignment.centerLeft,
child: FilledButton(
key: Key('tab-invite-accept-${invite.id}'),
- onPressed: () => unawaited(showAcceptInvite(context, widget.notifier, invite)),
+ onPressed: () => unawaited(
+ showAcceptInvite(context, widget.notifier, invite),
+ ),
child: const Text('Accept'),
),
),
@@ -110,16 +233,21 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
key: Key('tab-invite-untrusted-${u.sharedTabId}'),
decoration: BoxDecoration(
color: AppPalette.warn.withValues(alpha: 0.10),
- border: Border.all(color: AppPalette.warn.withValues(alpha: 0.28)),
+ border: Border.all(
+ color: AppPalette.warn.withValues(alpha: 0.28),
+ ),
borderRadius: BorderRadius.circular(14),
),
child: SettingRow(
- title: '${_line(shortSharedText(u.ownerEmail), 'The owner')}\'s computer has a new key.',
+ title:
+ '${_line(shortSharedText(u.ownerEmail), 'The owner')}\'s computer has a new key.',
control: Align(
alignment: Alignment.centerLeft,
child: OutlinedButton(
key: Key('tab-invite-trust-${u.sharedTabId}'),
- onPressed: () => unawaited(showTrustAgain(context, widget.notifier, u.sharedTabId)),
+ onPressed: () => unawaited(
+ showTrustAgain(context, widget.notifier, u.sharedTabId),
+ ),
child: const Text('Trust again'),
),
),
@@ -129,7 +257,8 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
);
}
- static String _line(String text, String fallback) => text.isEmpty ? fallback : text;
+ static String _line(String text, String fallback) =>
+ text.isEmpty ? fallback : text;
}
/// Waiting, drawn in the shape of the answer: rows.
@@ -138,7 +267,8 @@ class _Skeleton extends StatelessWidget {
@override
Widget build(BuildContext context) {
- final fill = Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.08);
+ final fill = Theme.of(context).colorScheme.onSurface
+ .withValues(alpha: 0.08);
return Semantics(
label: 'Loading invitations',
child: Column(
@@ -146,7 +276,10 @@ class _Skeleton extends StatelessWidget {
children: [
for (var i = 0; i < 2; i++)
DecoratedBox(
- decoration: BoxDecoration(color: fill, borderRadius: BorderRadius.circular(14)),
+ decoration: BoxDecoration(
+ color: fill,
+ borderRadius: BorderRadius.circular(14),
+ ),
child: const SizedBox(height: 64, width: double.infinity),
),
],
diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dart
index ff549279f..08307f8fe 100644
--- a/desktop/lib/shared/theme/app_icons.dart
+++ b/desktop/lib/shared/theme/app_icons.dart
@@ -63,6 +63,7 @@ abstract final class AppIcons {
static const copy = LucideIcons.copy400;
static const copyPlus = LucideIcons.copyPlus400;
static const cornerDownLeft = LucideIcons.cornerDownLeft400;
+ static const reply = LucideIcons.reply400;
static const cpu = LucideIcons.cpu400;
static const database = LucideIcons.database400;
static const dot = LucideIcons.dot400;
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index 666b5ed32..25f0914a5 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -689,6 +689,13 @@ final harnessCommands = <HarnessCommand>[
ShortcutGroup.actions,
keywords: ['hide guide', 'dismiss tutorial'],
),
+ const HarnessCommand(
+ 'super_tab.new',
+ 'New Super Tab',
+ ShortcutGroup.actions,
+ extraKeys: ['cmd+alt+shift+t'],
+ hidden: true,
+ ),
if (kDebugSurfaceEnabled)
const HarnessCommand(
'app.debug',
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 27fddb072..32d84a3bb 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -4,6 +4,7 @@ import '../measurement/product_connections.dart';
import '../core/crash_log.dart';
import '../measurement/desktop_setup_report.dart';
import 'attached_task_delivery.dart';
+import 'harness_attachments.dart';
import 'task_route.dart';
import '../core/permission_modes.dart';
@@ -86,6 +87,9 @@ import '../autonomous_device/autonomous_device_cli.dart';
import '../settings/config_store.dart';
import '../settings/experimental_features.dart';
import '../core/local_key_value_store.dart';
+import '../core/harness_file_store.dart';
+import '../super_tabs/client.dart';
+import '../super_tabs/controller.dart';
import '../measurement/setup_preference_store.dart';
import '../devices/device_hosts.dart';
import '../stats/harness_stats.dart';
@@ -275,12 +279,15 @@ class AgentCreationAttempt {
this.background = false,
String? creationId,
this.holdWait,
+ this.beforeSubmit,
}) : _id = creationId ?? _newCreationId();
/// How long a request the machine holds is waited for before the create
/// answers ([AppNotifier._createFollowingHold]). Null answers at once with
/// what it waits for, as a form wants: the person reads it and may cancel.
final Duration? holdWait;
+ final Future<void> Function(String machineId, String creationId)?
+ beforeSubmit;
String _id;
String? _machineId, _targetId;
Map<String, dynamic>? _choices;
@@ -371,8 +378,7 @@ class MachineState {
/// another account shares (`isShared`) or a whole machine another account
/// shares (`isSharedMachine`). Its daemon answers as its owner, so shared
/// tabs never ask it, and a harness on it is never this account's own.
- bool get belongsToOtherAccount =>
- machine.isShared || machine.isSharedMachine;
+ bool get belongsToOtherAccount => machine.isShared || machine.isSharedMachine;
int _agentRevision = 0;
final _agentRemovals = <String, int>{};
final _agentStopRevisions = <String, int>{};
@@ -1096,6 +1102,7 @@ class AppNotifier extends ChangeNotifier {
!_disposed && revision == _authRevision;
int _invalidateAuthWork() {
+ _closeAttachmentSessions();
_phoneOffer = false;
_closeOwnerMemories();
_stopMachineRecovery();
@@ -1357,12 +1364,14 @@ class AppNotifier extends ChangeNotifier {
CurrentUserProfile? get currentUser => _currentUser;
set currentUser(CurrentUserProfile? profile) {
if (_currentUser?.id != profile?.id) {
+ _closeAttachmentSessions();
_closeOwnerMemories();
deviceHosts.clear();
_deviceReads.clear();
}
_currentUser = profile;
final id = profile?.id;
+ superTabs.bind(id);
experimentalFeatures.bind(
id,
transport: id == null ? null : _experimentTransport,
@@ -1631,6 +1640,147 @@ class AppNotifier extends ChangeNotifier {
return best;
}
+ late final superTabs = SuperTabClient(
+ storage: localStore ?? HarnessFileStore.shared,
+ onSnapshot: (controller) {
+ if (_disposed || controller.accountId != currentUser?.id) return;
+ var shown = false;
+ for (final tab in swarms.where((s) => s.superTabId == controller.tabId)) {
+ if (tab.name != controller.snapshot!.name || !tab.nameIsCustom) {
+ tab.name = controller.snapshot!.name;
+ tab.nameIsCustom = true;
+ shown = true;
+ }
+ }
+ if (shown) _persistLayout();
+ notifyListeners();
+ },
+ transport: (method, path, {body}) async {
+ final target = sharedTabsTarget;
+ if (target == null) {
+ throw const SuperTabFailure(
+ 'MACHINE_UNAVAILABLE',
+ 'Connect one of your machines to open Super Tab.',
+ );
+ }
+ final result = await superTabMachineRequest(target.machine.machineId, {
+ 'action': 'backend',
+ 'method': method,
+ 'path': path,
+ 'body': ?body,
+ });
+ return result['value'];
+ },
+ );
+
+ Future<Map<String, dynamic>> superTabMachineRequest(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ final revision = _authRevision;
+ final result = await _conn(machineId).request(
+ 'super_tabs',
+ payload: payload,
+ timeout: const Duration(seconds: 30),
+ );
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ if (result['error'] != null) {
+ throw SuperTabFailure(
+ result['error'].toString(),
+ result['detail'] as String? ?? 'Could not reach this Super Tab.',
+ statusCode: (result['status'] as num?)?.toInt() ?? 0,
+ );
+ }
+ return result;
+ }
+
+ Future<void> wakeSuperTabHost(String machineId) async {
+ await superTabMachineRequest(machineId, {'action': 'wake'});
+ // Share derives only the session views authorized by the tab. Its existing
+ // observer protocol never exposes this machine's general command surface.
+ await _conn(machineId).request('harness_share_rosters');
+ }
+
+ void bindSuperTab(String swarmId, String tabId, String name) {
+ final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
+ if (swarm == null) return;
+ swarm.kind = 'superTab';
+ swarm.superTabId = tabId;
+ swarm.name = name;
+ swarm.nameIsCustom = true;
+ swarm.isNewTabPage = false;
+ _persistLayout();
+ notifyListeners();
+ }
+
+ void openSuperTab(String tabId, String name) {
+ final existing = swarms.where((s) => s.superTabId == tabId).firstOrNull;
+ if (existing != null) {
+ selectSwarm(existing.id);
+ return;
+ }
+ newSwarm(newTabPage: true);
+ bindSuperTab(activeSwarmId, tabId, name);
+ }
+
+ void markSuperTabDraft(String swarmId) {
+ final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
+ if (swarm == null) return;
+ swarm.kind = 'superTab';
+ _persistLayout();
+ notifyListeners();
+ }
+
+ /// Opening a recent harness uses the welcome page as an ordinary workspace.
+ /// Consume only a successful open; a missing result leaves creation available.
+ void finishSuperTabDraftNavigation(String swarmId) {
+ final swarm = swarms.where((s) => s.id == swarmId).firstOrNull;
+ if (swarm == null ||
+ !swarm.isSuperTab ||
+ swarm.superTabId != null ||
+ swarm.panes.isEmpty) {
+ return;
+ }
+ swarm.kind = 'harness';
+ _persistLayout();
+ notifyListeners();
+ }
+
+ Future<Agent> recoverSuperTabCreation(
+ String machineId,
+ String creationId,
+ ) async {
+ final revision = _authRevision;
+ final result = await _conn(machineId).request(
+ 'agent_create_status',
+ payload: {'creationId': creationId},
+ timeout: const Duration(seconds: 10),
+ );
+ if (!_authWorkCurrent(revision)) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ if (result['creationId'] == creationId && result['state'] == 'failed') {
+ final failure = result['failure'] is Map
+ ? result['failure'] as Map
+ : const {};
+ throw SuperTabFailure(
+ 'CREATION_FAILED',
+ failure['detail'] as String? ?? result['error'] as String? ?? 'The machine could not start this harness. You can change its settings and try again.',
+ );
+ }
+ if (result['creationId'] != creationId ||
+ result['state'] != 'created' ||
+ result['agent'] is! Map) {
+ throw const SuperTabFailure(
+ 'CREATION_PENDING',
+ 'The machine has not confirmed this launch. Check status before starting another agent.',
+ );
+ }
+ return Agent.fromJson(Map<String, dynamic>.from(result['agent'] as Map));
+ }
+
/// Where this computer keeps, per shared tab, the other accounts'
/// harnesses it has seen in the roster (R2): `{sharedTabId: [paneKey]}`,
/// one record per account, so one person's record on a shared computer
@@ -1822,7 +1972,10 @@ class AppNotifier extends ChangeNotifier {
swarm.panes.where((p) => p.agentId != null).length >=
PaneLayoutStore.maxPanes;
- static bool _sameSeen(Map<String, Set<String>> a, Map<String, Set<String>> b) {
+ static bool _sameSeen(
+ Map<String, Set<String>> a,
+ Map<String, Set<String>> b,
+ ) {
if (a.length != b.length) return false;
for (final MapEntry(:key, :value) in a.entries) {
final other = b[key];
@@ -3217,6 +3370,7 @@ class AppNotifier extends ChangeNotifier {
..titleAgentId = saved.titleAgentId
..orchestratorId = saved.orchestratorId
..orchestratorMachineId = saved.orchestratorMachineId
+ ..superTabId = saved.superTabId
..gridColumns = saved.gridColumns
..presets.addAll(saved.presets)
..paneSizes.addAll(saved.paneSizes);
@@ -10416,10 +10570,7 @@ class AppNotifier extends ChangeNotifier {
/// scheduling turn to the socket's incoming queue. Matching frames enter the
/// session's ordered renderer queue synchronously, regardless of tab order.
Future<void> _handleTerminalBinary(String machineId, Uint8List raw) async {
- final targets = panesFor(machineId)
- .map((pane) => pane.session)
- .whereType<TerminalSession>()
- .toList();
+ final targets = _terminalSessionsFor(machineId).toList();
if (targets.isEmpty) return;
final clear = decodeTerminalLocal(raw);
if (clear == null) {
@@ -13306,6 +13457,17 @@ class AppNotifier extends ChangeNotifier {
);
if (result['creationId'] != creation._id) return unconfirmed;
} else {
+ if (creation.beforeSubmit case final prepare?) {
+ try {
+ await prepare(machineId, creation._id);
+ } catch (failure) {
+ // The native request has not been sent. A failed local journal write
+ // must leave the form editable instead of waiting on a nonexistent receipt.
+ return creation._complete(
+ 'Could not save the launch request: $failure',
+ );
+ }
+ }
result = await connection.request(
operation,
payload: {...launchChoices, 'creationId': creation._id},
@@ -15928,8 +16090,9 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
- static bool _listedIn(SharedTab tab, String machineId, String agentId) =>
- tab.harnesses.any((h) => h.machineId == machineId && h.agentId == agentId);
+ static bool _listedIn(SharedTab tab, String machineId, String agentId) => tab
+ .harnesses
+ .any((h) => h.machineId == machineId && h.agentId == agentId);
/// Listed in [tab], or still `Joining…`: an add this computer's daemon holds
/// for the owner's computer. Withdrawn then, it must be taken back too, or
@@ -15968,12 +16131,19 @@ class AppNotifier extends ChangeNotifier {
/// Make [machineId]'s [agentId] the leader of [deskTabId]. A refusal keeps the
/// old leader and is told in the transient notice.
- Future<void> setTabLeader(String deskTabId, String machineId, String agentId) =>
- _writeLeader(deskTabId, AgentMessageLeader(machineId, agentId));
+ Future<void> setTabLeader(
+ String deskTabId,
+ String machineId,
+ String agentId,
+ ) => _writeLeader(deskTabId, AgentMessageLeader(machineId, agentId));
- Future<void> clearTabLeader(String deskTabId) => _writeLeader(deskTabId, null);
+ Future<void> clearTabLeader(String deskTabId) =>
+ _writeLeader(deskTabId, null);
- Future<void> _writeLeader(String deskTabId, AgentMessageLeader? leader) async {
+ Future<void> _writeLeader(
+ String deskTabId,
+ AgentMessageLeader? leader,
+ ) async {
final auth = _authRevision;
try {
final answer = await api.setAgentMessageTab(
@@ -16083,11 +16253,10 @@ class AppNotifier extends ChangeNotifier {
/// desk as an ordinary pane.
Future<void> removeFromSharedTab(String machineId, String agentId) async {
if (!canRemoveFromSharedTab(machineId, agentId)) return;
- await _shareAction(
- sharedTabHolding(machineId, agentId)!,
- 'share_remove',
- {'machineId': machineId, 'agentId': agentId},
- );
+ await _shareAction(sharedTabHolding(machineId, agentId)!, 'share_remove', {
+ 'machineId': machineId,
+ 'agentId': agentId,
+ });
}
/// The `share_add` for a person's pane in a shared tab; null when none is
@@ -16101,7 +16270,8 @@ class AppNotifier extends ChangeNotifier {
}) {
final tab = sharedTabs.tabForDesk(deskTabId);
final state = machineStates[machineId];
- if (tab == null || state == null || state.belongsToOtherAccount) return null;
+ if (tab == null || state == null || state.belongsToOtherAccount)
+ return null;
// The owner's harnesses join by being in its desk tab.
if (_ownsSharedTab(tab) || _listedIn(tab, machineId, agentId)) return null;
final agent = state.agents.where((a) => a.id == agentId).firstOrNull;
@@ -16115,7 +16285,11 @@ class AppNotifier extends ChangeNotifier {
}, onFailure: onFailure);
}
- void _shareRemoveIfShared(String deskTabId, String machineId, String agentId) {
+ void _shareRemoveIfShared(
+ String deskTabId,
+ String machineId,
+ String agentId,
+ ) {
final tab = sharedTabs.tabForDesk(deskTabId);
if (tab == null ||
_ownsSharedTab(tab) ||
@@ -16149,7 +16323,9 @@ class AppNotifier extends ChangeNotifier {
if (_disposed) return;
// The computer that is away is the one holding the harness, named when it
// is one of the person's own.
- final holder = machineStates[body['machineId'] ?? (body['harness'] as Map?)?['machineId']];
+ final holder =
+ machineStates[body['machineId'] ??
+ (body['harness'] as Map?)?['machineId']];
_lastError = sharedTabErrorText(
e,
machine: holder != null && !holder.belongsToOtherAccount
@@ -16171,6 +16347,8 @@ class AppNotifier extends ChangeNotifier {
PaneSplitRequest? split,
bool autoTile = false,
bool focus = true,
+ String? inputContext,
+ bool watchOnly = false,
/// A rail click, a drag, a picker — a person. The device's own doors pass
/// [AttachIntent.automatic]: they put an agent on screen without anybody
@@ -16217,6 +16395,12 @@ class AppNotifier extends ChangeNotifier {
.where((p) => p.machineId == machineId && p.agentId == agentId)
.firstOrNull;
if (paneId == null && existing != null) {
+ existing.inputContext = inputContext;
+ existing.watchOnly = watchOnly;
+ await existing.session?.setInputContext(
+ inputContext,
+ watchOnly: watchOnly,
+ );
if (focus && target == activeSwarm) focusPane(existing.id);
// A pane a refused share_add left unshared: a person's retry shares it.
if (intent == AttachIntent.person) {
@@ -16238,6 +16422,9 @@ class AppNotifier extends ChangeNotifier {
}
final replaced = targetPanes.where((p) => p.id == paneId).firstOrNull;
if (replaced == shared && shared != null) {
+ shared.inputContext = inputContext;
+ shared.watchOnly = watchOnly;
+ await shared.session?.setInputContext(inputContext, watchOnly: watchOnly);
if (focus && target == activeSwarm) focusPane(shared.id);
return;
}
@@ -16253,9 +16440,7 @@ class AppNotifier extends ChangeNotifier {
// A shared desk tab holds the desk's 9 harnesses: a 10th would never
// reach the desk ([deskTabFull]). Placement asks quietly and tries again
// later; a person is told.
- if (existing == null &&
- replaced?.agentId == null &&
- deskTabFull(target)) {
+ if (existing == null && replaced?.agentId == null && deskTabFull(target)) {
if (intent == AttachIntent.person) {
_lastError =
'This tab holds ${PaneLayoutStore.maxPanes} harnesses. Close one, then try again.';
@@ -16292,6 +16477,9 @@ class AppNotifier extends ChangeNotifier {
final pane =
shared ??
TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: agentId);
+ pane.inputContext = inputContext;
+ pane.watchOnly = watchOnly;
+ pane.session?.stageInputContext(inputContext, watchOnly: watchOnly);
final firstAgent = targetPanes.every((pane) => pane.agentId == null);
if (machine.machine.isShared) {
pane.sharedHarness = machine.machine.sharedHarnesses
@@ -16416,6 +16604,9 @@ class AppNotifier extends ChangeNotifier {
_stopOfflineRetry(machineId);
notifyListeners();
if (target == activeSwarm || pane.session != null) {
+ if (pane.session case final session?) {
+ await session.setInputContext(inputContext, watchOnly: watchOnly);
+ }
await _attachSession(pane, intent: intent);
}
}
@@ -16480,6 +16671,8 @@ class AppNotifier extends ChangeNotifier {
agentName: agent.displayName,
engineId: agent.engine,
client: localClientDescriptor(),
+ inputContext: pane.inputContext,
+ watchOnly: pane.watchOnly,
// Only a person at this window may take the terminal from whoever holds
// it; everything else opens as a watcher. See [AttachIntent].
takeover: intent == AttachIntent.person,
@@ -16508,6 +16701,99 @@ class AppNotifier extends ChangeNotifier {
await terminal.open(waitForViewportSize: true);
}
+ // File delivery for a new background harness uses the same native terminal
+ // protocol, without manufacturing a pane or changing the selected group.
+ final _attachmentSessions = <TerminalSession>{};
+
+ Iterable<TerminalSession> _terminalSessionsFor(String machineId) sync* {
+ yield* panesFor(machineId).map((p) => p.session).nonNulls;
+ yield* _attachmentSessions.where((s) => s.machineId == machineId);
+ }
+
+ void _closeAttachmentSessions() {
+ final sessions = _attachmentSessions.toList();
+ _attachmentSessions.clear();
+ for (final session in sessions) {
+ unawaited(session.close().whenComplete(session.dispose));
+ }
+ }
+
+ Future<String?> deliverBackgroundAttachments({
+ required String machineId,
+ required String agentId,
+ required List<HarnessAttachment> files,
+ required String task,
+ }) async {
+ final machine = machineStates[machineId];
+ final revision = _authRevision, account = currentUser?.id;
+ bool current() =>
+ currentUser?.id == account &&
+ machine != null &&
+ _machineWorkCurrent(machine, revision);
+ if (!current() || machine!.machine.isShared) {
+ return 'This machine is no longer available for file delivery.';
+ }
+ if (!machine.agents.any((a) => a.id == agentId)) {
+ await _loadMachineData(machine, force: true);
+ }
+ if (!current()) return 'The account changed. No files were sent.';
+ final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;
+ if (agent == null) {
+ return 'The new harness is not available on its machine.';
+ }
+ final existing = panesFor(machineId)
+ .where((p) => p.agentId == agentId)
+ .map((p) => p.session)
+ .nonNulls
+ .firstOrNull;
+ final connection = _conn(machineId);
+ final session =
+ existing ??
+ TerminalSession(
+ machineId: machineId,
+ agentId: agentId,
+ agentName: agent.displayName,
+ engineId: agent.engine,
+ client: localClientDescriptor(),
+ takeover: true,
+ send: (type, payload) => current() || type == 'terminal_close'
+ ? connection.sendTerminalFrame(type, payload)
+ : Future.value(false),
+ sendBinary: (frame) {
+ if (!current()) return Future.value(false);
+ final bytes = encodeTerminalLocal(frame);
+ return bytes == null
+ ? Future.value(false)
+ : connection.sendTerminalBinary(bytes);
+ },
+ onOpenStalled: () async {
+ if (current()) await _forceRedial(machineId);
+ },
+ resyncTimeout: const Duration(seconds: 15),
+ );
+ if (existing == null) _attachmentSessions.add(session);
+ try {
+ if (existing == null) await session.open();
+ return await deliverAttachedTask(
+ this,
+ machineId: machineId,
+ agentId: agentId,
+ files: files,
+ task: task,
+ terminal: session,
+ stillWanted: current,
+ );
+ } finally {
+ if (_attachmentSessions.remove(session)) {
+ try {
+ await session.close();
+ } finally {
+ session.dispose();
+ }
+ }
+ }
+ }
+
Future<void> _detachSession(
TerminalPane pane, {
required bool sendClose,
@@ -17001,6 +17287,15 @@ class AppNotifier extends ChangeNotifier {
if (tab == null) return;
final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;
if (pane == null) return;
+ if (tab.superTabId case final superTabId?) {
+ final controller = superTabs.peek(superTabId);
+ final selected = controller?.terminalAgent(controller.selectedId);
+ if (selected != null &&
+ selected.machineId == pane.machineId &&
+ selected.harnessId == pane.agentId) {
+ controller!.selectTerminal(controller.selectedId, null);
+ }
+ }
if (tab.isCompanions || tab.isDevices) {
await closeSwarm(tab.id, persist: persist);
return;
@@ -17866,10 +18161,18 @@ class AppNotifier extends ChangeNotifier {
? 'devices'
: isCompanions
? 'companions'
+ : raw['kind'] == 'superTab'
+ ? 'superTab'
: raw['kind'] == 'orchestrator'
? 'orchestrator'
: 'harness',
)
+ ..superTabId =
+ raw['superTabId'] is String &&
+ RegExp(r'^[a-f0-9]{24}$')
+ .hasMatch(raw['superTabId'] as String)
+ ? raw['superTabId'] as String
+ : null
..orchestratorId =
raw['orchestratorId'] is String &&
RegExp(r'^[a-f0-9]{32}$')
@@ -18691,8 +18994,8 @@ class AppNotifier extends ChangeNotifier {
// Each session still sees terminal frames: ready replies match their own
// request/agent, while transport errors must reach the whole machine.
if (type.startsWith('terminal_')) {
- for (final pane in panesFor(machineId).toList()) {
- await pane.session?.handleFrame(type, payload);
+ for (final session in _terminalSessionsFor(machineId).toList()) {
+ await session.handleFrame(type, payload);
}
return;
}
@@ -19556,6 +19859,7 @@ class AppNotifier extends ChangeNotifier {
agentMessagesRemote.dispose();
agentMessages.dispose();
sharedTabs.dispose();
+ superTabs.dispose();
for (final project in _orchestratorProjects.values) {
project.dispose();
}
@@ -19575,6 +19879,7 @@ class AppNotifier extends ChangeNotifier {
agentAlerts.dispose();
agentUnread.dispose();
_disposed = true;
+ _closeAttachmentSessions();
_sharingDiscoveryTimer?.cancel();
_deafMachineListTimer?.cancel();
_stopMachineRecovery();
diff --git a/desktop/lib/state/attached_task_delivery.dart b/desktop/lib/state/attached_task_delivery.dart
index 2932b824f..a11873465 100644
--- a/desktop/lib/state/attached_task_delivery.dart
+++ b/desktop/lib/state/attached_task_delivery.dart
@@ -70,14 +70,25 @@ Future<String?> deliverAttachedTask(
required String agentId,
required List<HarnessAttachment> files,
required String task,
+ TerminalSession? terminal,
+ bool Function()? stillWanted,
}) async {
appLog.info('attach', 'waiting on $agentId for ${files.length} file(s)');
- final session = await _readySession(app, machineId, agentId);
+ final session = await _readySession(
+ app,
+ machineId,
+ agentId,
+ terminal: terminal,
+ stillWanted: stillWanted,
+ );
if (session == null) {
appLog.warn('attach', '$agentId never took input');
return 'The harness did not open in time. Attach the files in its pane.';
}
for (final file in files) {
+ if (stillWanted != null && !stillWanted()) {
+ return 'Attachment delivery stopped.';
+ }
if (!await session.pasteFile(file.name, file.bytes) ||
!await session.pasteText(' ')) {
appLog.warn('attach', '${file.name} did not reach $agentId');
@@ -86,6 +97,9 @@ Future<String?> deliverAttachedTask(
}
appLog.info('attach', '${files.length} file(s) in $agentId; sending task');
if (task.trim().isEmpty) return null;
+ if (stillWanted != null && !stillWanted()) {
+ return 'The files are attached, but the task was not sent.';
+ }
return await session.sendComposerText(task)
? null
: 'The files are attached, but the task was not sent.';
@@ -95,8 +109,10 @@ Future<String?> deliverAttachedTask(
Future<TerminalSession?> _readySession(
AppNotifier app,
String machineId,
- String agentId,
-) async {
+ String agentId, {
+ TerminalSession? terminal,
+ bool Function()? stillWanted,
+}) async {
var claimed = false;
TerminalSession? watchedSession;
Terminal? watchedTerminal;
@@ -109,12 +125,14 @@ Future<TerminalSession?> _readySession(
.where((agent) => agent.id == agentId)
.firstOrNull;
if (agent?.launchState != 'ready') return null;
- final session = app
- .panesFor(machineId)
- .where((pane) => pane.agentId == agentId)
- .map((pane) => pane.session)
- .nonNulls
- .firstOrNull;
+ final session =
+ terminal ??
+ app
+ .panesFor(machineId)
+ .where((pane) => pane.agentId == agentId)
+ .map((pane) => pane.session)
+ .nonNulls
+ .firstOrNull;
if (session == null) return null;
// Output and replacement keyframes need not change the agent inventory.
// Watch both so the queued task wakes up when the new composer is drawn.
@@ -156,7 +174,12 @@ Future<TerminalSession?> _readySession(
Timer? settle;
check = () {
if (found.isCompleted) return;
- if (watchedSession != null &&
+ if (stillWanted != null && !stillWanted() || terminal?.closedHere == true) {
+ found.complete(null);
+ return;
+ }
+ if (terminal == null &&
+ watchedSession != null &&
!app.panesFor(machineId).any((pane) => pane.agentId == agentId)) {
found.complete(null);
return;
diff --git a/desktop/lib/state/harness_launch_integration.dart b/desktop/lib/state/harness_launch_integration.dart
new file mode 100644
index 000000000..d63ecd307
--- /dev/null
+++ b/desktop/lib/state/harness_launch_integration.dart
@@ -0,0 +1,30 @@
+import 'harness_attachments.dart';
+
+/// An optional destination around the existing New Harness launch. Preparing
+/// may add instructions; completion registers the confirmed native session.
+/// Neither callback starts an agent. Retry keeps the same native receipt.
+class HarnessLaunchIntegration {
+ HarnessLaunchIntegration({
+ required this.creationId,
+ required this.prepare,
+ required this.complete,
+ required this.beforeSubmit,
+ this.stageAttachments,
+ this.needsAttachmentReview,
+ this.resolveAttachments,
+ this.resume,
+ this.actionLabel = 'New Harness',
+ });
+ final String creationId, actionLabel;
+ final Future<String> Function(String machineId, String task) prepare;
+ final Future<void> Function(String machineId, String harnessId) complete;
+ final Future<void> Function(String machineId, String creationId) beforeSubmit;
+ Future<void> Function()? resume;
+ final Future<void> Function(List<HarnessAttachment> files, String prompt)?
+ stageAttachments;
+ final bool Function()? needsAttachmentReview;
+ final Future<void> Function(bool resend)? resolveAttachments;
+ bool pending = false;
+ bool completed = false;
+ String? preparedPrompt;
+}
diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dart
index 2e8f83f49..d830f025d 100644
--- a/desktop/lib/state/new_harness.dart
+++ b/desktop/lib/state/new_harness.dart
@@ -30,6 +30,7 @@ import 'app_state.dart';
import 'attached_task_delivery.dart';
import 'harness_placement.dart';
import 'harness_attachments.dart';
+import 'harness_launch_integration.dart';
import 'pane_arrangement.dart';
/// Whether New Harness opens as a line in the box, or as the full form.
@@ -300,6 +301,7 @@ class NewHarnessDraft {
this.profile,
this.profileChosen = false,
this.attempt,
+ this.integration,
this.error,
this.dismissalWarningShown = false,
this.projectsByMachine = const {},
@@ -321,6 +323,7 @@ class NewHarnessDraft {
final LocalCodexProfile? profile;
final bool profileChosen;
final AgentCreationAttempt? attempt;
+ final HarnessLaunchIntegration? integration;
final String? error;
// The visible "Escape again" message must keep the same meaning if the
// unresolved prompt is dismissed and then restored.
@@ -429,7 +432,9 @@ class NewHarnessController extends ChangeNotifier {
ModelsMenuController? modelUsage,
Random? random,
this.attachments,
+ HarnessLaunchIntegration? integration,
}) : _random = random ?? Random(),
+ integration = draft?.integration ?? integration,
placement =
placement ?? (split == null ? HarnessPlacement.currentTab : null),
_targetId = swarmId ?? app.activeSwarmId,
@@ -1192,6 +1197,7 @@ class NewHarnessController extends ChangeNotifier {
profile: _profile,
profileChosen: _profileChosen,
attempt: _attempt,
+ integration: integration,
error: error,
dismissalWarningShown: _warnedAboutClosing,
projectsByMachine: Map.unmodifiable({
@@ -3443,12 +3449,19 @@ class NewHarnessController extends ChangeNotifier {
/// never came back may have worked, and asking again must ask the machine
/// what happened to THAT request rather than start a second harness.
AgentCreationAttempt? _attempt;
+ final HarnessLaunchIntegration? integration;
+ String get actionLabel => integration?.actionLabel ?? 'New Harness';
+ bool get needsAttachmentReview =>
+ integration?.needsAttachmentReview?.call() == true;
+ String get pendingActionLabel =>
+ needsAttachmentReview ? 'Review files' : 'Check status';
/// The person has been told a typed task will not be sent, and pressed again.
bool _dropAccepted = false;
/// A reply was lost; Return now checks on it instead of creating again.
- bool get checking => _attempt?.awaitingConfirmation == true;
+ bool get checking =>
+ _attempt?.awaitingConfirmation == true || integration?.pending == true;
bool get canCancelPending => _attempt?.canCancelPending == true;
/// The check [followHeld] is making. Nobody pressed for it, so it shows
@@ -3525,10 +3538,30 @@ class NewHarnessController extends ChangeNotifier {
/// [quiet] is [followHeld]'s: a check on a held request that changes
/// nothing on screen until it has an answer.
- Future<NewHarnessOutcome> create({bool quiet = false}) async {
+ Future<NewHarnessOutcome> create({
+ bool quiet = false,
+ bool? resendAttachments,
+ }) async {
if (busy || linkingProfile) {
return NewHarnessOutcome.failed;
}
+ final resume =
+ resendAttachments != null && integration?.resolveAttachments != null
+ ? () => integration!.resolveAttachments!(resendAttachments)
+ : integration?.resume;
+ if (resume != null) {
+ busy = true;
+ status = 'Checking on the harness…';
+ notifyListeners();
+ try {
+ await resume();
+ busy = false;
+ integration!.pending = false;
+ return NewHarnessOutcome.created;
+ } catch (failure) {
+ return _fail(failure.toString());
+ }
+ }
if (!checking && usesProfile && _profile != null) {
if (loadingProfiles) {
return _fail(
@@ -3554,6 +3587,11 @@ class NewHarnessController extends ChangeNotifier {
focusField(choice.field);
return _fail(choice.message);
}
+ if (integration != null && (isCloud || !takesTask)) {
+ return _fail(
+ 'Choose an agent that runs on a machine, such as Claude Code or Codex.',
+ );
+ }
if (isCloud) return _createCloud();
if (!checking) {
_syncGitProject();
@@ -3636,7 +3674,10 @@ class NewHarnessController extends ChangeNotifier {
// A cached availability probe must not block that first launch.
final recheck = checking;
if (!recheck) {
- _attempt = AgentCreationAttempt();
+ _attempt = AgentCreationAttempt(
+ background: integration != null,
+ beforeSubmit: integration?.beforeSubmit,
+ );
_warnedAboutClosing = false;
_installing = null;
}
@@ -3700,6 +3741,15 @@ class NewHarnessController extends ChangeNotifier {
permissionMode != null && permissionModeApproves(permissionMode);
final folder = _project.folder;
final firstMessage = task.trim();
+ String launchMessage = firstMessage;
+ if (integration case final destination?) {
+ try {
+ launchMessage = destination.preparedPrompt ??= await destination
+ .prepare(_machineId, firstMessage);
+ } catch (failure) {
+ return _fail(failure.toString());
+ }
+ }
// Files ride into the live terminal after creation, and the task follows
// them there (see deliverAttachedTask), so neither is a launch argument.
final files = takesTask
@@ -3710,6 +3760,13 @@ class NewHarnessController extends ChangeNotifier {
'Update Harness CLI on $machineLabel to attach files, or remove them.',
);
}
+ if (integration?.stageAttachments case final stage? when !recheck) {
+ try {
+ await stage(files, launchMessage);
+ } catch (failure) {
+ return _fail(failure.toString());
+ }
+ }
final launchSetup = LaunchSetup(
engine: base,
harnessId: harness,
@@ -3736,8 +3793,8 @@ class NewHarnessController extends ChangeNotifier {
model: _model,
dsh: harness,
// Sent exactly as written; an agent that cannot take one is never sent it.
- prompt: takesTask && files.isEmpty && firstMessage.isNotEmpty
- ? firstMessage
+ prompt: takesTask && files.isEmpty && launchMessage.isNotEmpty
+ ? launchMessage
: null,
// A new project named by the person, or after its task, names the agent
// too — until the engine titles the session. So does a first message
@@ -3755,8 +3812,25 @@ class NewHarnessController extends ChangeNotifier {
// Before the disposed check: on an empty tab the new pane replaces this
// box as soon as it opens, disposing it while createAgent returns — and
// the files still have to follow the harness there.
- if (failure == null && files.isNotEmpty) {
- _deliverFiles(attempt.agentId, files, firstMessage);
+ final destination = integration;
+ if (failure == null && attempt.agentId != null && destination != null) {
+ destination.pending = true;
+ try {
+ if (!destination.completed) {
+ await destination.complete(_machineId, attempt.agentId!);
+ destination.completed = true;
+ }
+ destination.pending = false;
+ } catch (problem) {
+ return _fail(
+ 'Harness started. Could not join the conversation: $problem',
+ );
+ }
+ }
+ if (failure == null &&
+ files.isNotEmpty &&
+ destination?.stageAttachments == null) {
+ _deliverFiles(attempt.agentId, files, launchMessage);
}
// Creation can replace an embedded form before this future returns. Save
// the confirmed choices even if that form has already been disposed.
@@ -3772,6 +3846,7 @@ class NewHarnessController extends ChangeNotifier {
}
if (_disposed) return NewHarnessOutcome.failed;
if (failure != null) {
+ if (!checking) integration?.preparedPrompt = null;
// A folder already made for this attempt is the project now: a retry
// goes into it rather than making a second one beside it.
if (!checking && attempt.preparedFolder != null) {
@@ -3852,7 +3927,7 @@ class NewHarnessController extends ChangeNotifier {
busy = false;
status = null;
error = message;
- notifyListeners();
+ if (!_disposed) notifyListeners();
return NewHarnessOutcome.failed;
}
diff --git a/desktop/lib/state/swarm.dart b/desktop/lib/state/swarm.dart
index 2ce318dfc..0ea9ce85b 100644
--- a/desktop/lib/state/swarm.dart
+++ b/desktop/lib/state/swarm.dart
@@ -33,7 +33,12 @@ class Swarm {
/// Marks a deliberately opened tab so subsequent actions use its destination.
bool isNewTabPage;
bool get isBlankNewTab =>
- isNewTabPage && kind == 'harness' && panes.isEmpty && presets.isEmpty;
+ isNewTabPage &&
+ (kind == 'harness' || (isSuperTab && superTabId == null)) &&
+ panes.isEmpty &&
+ presets.isEmpty;
+ bool get isSuperTab => kind == 'superTab';
+ String? superTabId;
bool get isStore => kind == 'store';
bool get isCompanions => kind == 'companions';
bool get isDevices => kind == 'devices';
@@ -99,7 +104,7 @@ class Swarm {
}
bool get isEmptyStarter =>
- name == defaultName && panes.isEmpty && presets.isEmpty;
+ !isSuperTab && name == defaultName && panes.isEmpty && presets.isEmpty;
PaneArrangement? get manualLayout => paneSizes['${panes.length}:manual'];
@@ -176,6 +181,7 @@ class Swarm {
if (titleMachineId != null) 'titleMachineId': titleMachineId,
if (titleAgentId != null) 'titleAgentId': titleAgentId,
if (kind != 'harness') 'kind': kind,
+ if (superTabId != null) 'superTabId': superTabId,
if (isOrchestrator) 'orchestratorId': orchestratorId,
if (isOrchestrator) 'orchestratorMachineId': orchestratorMachineId,
'focus': agents.indexWhere((p) => p.id == focusedPaneId),
@@ -256,6 +262,7 @@ class ClosedSwarm extends ClosedWork {
titleMachineId = swarm.titleMachineId,
titleAgentId = swarm.titleAgentId,
kind = swarm.kind,
+ superTabId = swarm.superTabId,
orchestratorId = swarm.orchestratorId,
orchestratorMachineId = swarm.orchestratorMachineId,
gridColumns = swarm.gridColumns,
@@ -284,6 +291,7 @@ class ClosedSwarm extends ClosedWork {
/// So a closed store tab reopens as the store, not as an empty harness tab.
final String kind;
+ final String? superTabId;
final String? orchestratorId, orchestratorMachineId;
final String? engine;
final int index;
diff --git a/desktop/lib/state/swarm_navigation.dart b/desktop/lib/state/swarm_navigation.dart
index d796b09c3..f82e37409 100644
--- a/desktop/lib/state/swarm_navigation.dart
+++ b/desktop/lib/state/swarm_navigation.dart
@@ -844,6 +844,28 @@ List<SwarmDestination> rankSwarmLocations(
];
}
+Future<void> _attachSearchHarness(
+ AppNotifier app,
+ String machineId,
+ String agentId, {
+ required String swarmId,
+ PaneSplitRequest? split,
+ bool autoTile = false,
+}) {
+ final attachment = app.assignAgentToPane(
+ null,
+ machineId,
+ agentId,
+ swarmId: swarmId,
+ split: split,
+ autoTile: autoTile,
+ );
+ // Membership is synchronous; a slow terminal connection must not leave a
+ // visible ordinary harness carrying the draft's lead-creation behavior.
+ app.finishSuperTabDraftNavigation(swarmId);
+ return attachment;
+}
+
Future<bool> activateSwarmSearchSelection(
AppNotifier app,
SwarmSearchSelection selection, {
@@ -852,8 +874,41 @@ Future<bool> activateSwarmSearchSelection(
PaneSplitRequest? split,
HarnessPlacement? placement,
TakeOver? takeOver,
+}) async {
+ final opened = await _activateSwarmSearchSelection(
+ app,
+ selection,
+ destinationSwarmId: destinationSwarmId,
+ projects: projects,
+ split: split,
+ placement: placement,
+ takeOver: takeOver,
+ );
+ if (opened) app.finishSuperTabDraftNavigation(destinationSwarmId);
+ return opened;
+}
+
+Future<bool> _activateSwarmSearchSelection(
+ AppNotifier app,
+ SwarmSearchSelection selection, {
+ required String destinationSwarmId,
+ List<SavedSwarmProject> projects = const [],
+ PaneSplitRequest? split,
+ HarnessPlacement? placement,
+ TakeOver? takeOver,
}) async {
final destination = selection.destination;
+ final source = app.swarms
+ .where((tab) => tab.id == destinationSwarmId)
+ .firstOrNull;
+ // Search opens native work. Only the separate Add agent flow contributes it
+ // to a shared conversation, so a completed Super Tab cannot be its canvas.
+ if (source?.isSuperTab == true && source?.superTabId != null) {
+ if (split != null) return false;
+ if (placement != null || destination.external != null) {
+ placement = HarnessPlacement.newTab;
+ }
+ }
if (destination.external case final external?) {
final machineId = destination.machineId;
if (machineId == null || split != null) return false;
@@ -879,7 +934,64 @@ Future<bool> activateSwarmSearchSelection(
}
return true;
}
- if (placement != null) {
+ if (selection.agents.isNotEmpty) {
+ var target = app.swarms
+ .where((swarm) => swarm.id == destinationSwarmId)
+ .firstOrNull;
+ if (target == null || split != null) return false;
+ final separateTab =
+ placement == HarnessPlacement.newTab ||
+ (target.isSuperTab && target.superTabId != null);
+ final currentPanes = separateTab ? const <TerminalPane>[] : target.panes;
+ final catalog = SwarmSearchCatalog().read(app, projects);
+ final byId = {for (final row in catalog) row.id: row};
+ final members = <SwarmDestination>[];
+ final seen = <String>{};
+ for (final chosen in selection.agents) {
+ final row = byId[chosen.id];
+ if (row?.agentId == null ||
+ !(app.machineStates[row!.machineId]?.agents.any(
+ (agent) => agent.id == row.agentId,
+ ) ??
+ false)) {
+ return false;
+ }
+ if (seen.add(row.id) &&
+ !currentPanes.any(
+ (pane) =>
+ pane.machineId == row.machineId && pane.agentId == row.agentId,
+ )) {
+ members.add(row);
+ }
+ }
+ if (members.isEmpty ||
+ currentPanes.length + members.length > AppNotifier.maxPanes) {
+ return false;
+ }
+ // Validate the complete selection before recording any membership. Every
+ // add records its destination synchronously, before attachment can wait.
+ for (final row in members) {
+ await _resumeStoppedDestination(app, row);
+ }
+ if (!app.swarms.contains(target)) return false;
+ if (separateTab) {
+ app.newSwarm();
+ target = app.activeSwarm;
+ }
+ final openedTab = target;
+ await Future.wait([
+ for (final row in members)
+ _attachSearchHarness(app, row.machineId!, row.agentId!, swarmId: openedTab.id),
+ ]);
+ return app.swarms.contains(openedTab) &&
+ members.every(
+ (row) => openedTab.panes.any(
+ (pane) =>
+ pane.machineId == row.machineId && pane.agentId == row.agentId,
+ ),
+ );
+ }
+ if (placement != null && !destination.isGroup) {
final machineId = destination.machineId;
final agentId = destination.agentId;
if (machineId == null || agentId == null || destination.isCommand) {
@@ -927,8 +1039,8 @@ Future<bool> activateSwarmSearchSelection(
app.newSwarm();
target = app.activeSwarm;
}
- await app.assignAgentToPane(
- null,
+ await _attachSearchHarness(
+ app,
machineId,
agentId,
swarmId: target.id,
@@ -941,54 +1053,6 @@ Future<bool> activateSwarmSearchSelection(
(pane) => pane.machineId == machineId && pane.agentId == agentId,
);
}
- if (selection.agents.isNotEmpty) {
- final target = app.swarms
- .where((swarm) => swarm.id == destinationSwarmId)
- .firstOrNull;
- if (target == null || split != null) return false;
- final catalog = SwarmSearchCatalog().read(app, projects);
- final byId = {for (final row in catalog) row.id: row};
- final members = <SwarmDestination>[];
- final seen = <String>{};
- for (final chosen in selection.agents) {
- final row = byId[chosen.id];
- if (row?.agentId == null ||
- !(app.machineStates[row!.machineId]?.agents.any(
- (agent) => agent.id == row.agentId,
- ) ??
- false)) {
- return false;
- }
- if (seen.add(row.id) &&
- !target.panes.any(
- (pane) =>
- pane.machineId == row.machineId && pane.agentId == row.agentId,
- )) {
- members.add(row);
- }
- }
- if (members.isEmpty ||
- target.panes.length + members.length > AppNotifier.maxPanes) {
- return false;
- }
- // Validate the complete selection before recording any membership. Every
- // add records its destination synchronously, before attachment can wait.
- for (final row in members) {
- await _resumeStoppedDestination(app, row);
- }
- if (!app.swarms.contains(target)) return false;
- await Future.wait([
- for (final row in members)
- app.addAgentToSwarm(row.machineId!, row.agentId!, swarmId: target.id),
- ]);
- return app.swarms.contains(target) &&
- members.every(
- (row) => target.panes.any(
- (pane) =>
- pane.machineId == row.machineId && pane.agentId == row.agentId,
- ),
- );
- }
if (selection.action == SwarmSearchAction.open && !destination.isGroup) {
return activateSwarmDestination(
app,
@@ -999,7 +1063,7 @@ Future<bool> activateSwarmSearchSelection(
if (selection.action == SwarmSearchAction.addHere) {
if (destination.agentId == null) {
if (split != null || destination.isCommand) return false;
- final target = app.swarms
+ var target = app.swarms
.where((swarm) => swarm.id == destinationSwarmId)
.firstOrNull;
final catalog = SwarmSearchCatalog().read(app, projects);
@@ -1009,11 +1073,15 @@ Future<bool> activateSwarmSearchSelection(
!setEquals(destination.members, live.members)) {
return false;
}
+ final separateTab =
+ placement == HarnessPlacement.newTab ||
+ (target.isSuperTab && target.superTabId != null);
+ final currentPanes = separateTab ? const <TerminalPane>[] : target.panes;
final members = catalog
.where(
(row) =>
destination.members.contains(row.id) &&
- !target.panes.any(
+ !currentPanes.any(
(pane) =>
pane.machineId == row.machineId &&
pane.agentId == row.agentId,
@@ -1021,7 +1089,7 @@ Future<bool> activateSwarmSearchSelection(
)
.toList();
if (members.isEmpty ||
- target.panes.length + members.length > AppNotifier.maxPanes ||
+ currentPanes.length + members.length > AppNotifier.maxPanes ||
members.any(
(row) =>
!(app.machineStates[row.machineId]?.agents.any(
@@ -1031,21 +1099,26 @@ Future<bool> activateSwarmSearchSelection(
)) {
return false;
}
- if (target.panes.isEmpty && target.name == Swarm.defaultName) {
- app.renameSwarm(target.id, destination.title);
- }
// Every membership is recorded before awaiting any attachment. A slow
// machine cannot retarget the add or hold up the other agents.
for (final row in members) {
await _resumeStoppedDestination(app, row);
}
if (!app.swarms.contains(target)) return false;
+ if (separateTab) {
+ app.newSwarm();
+ target = app.activeSwarm;
+ }
+ final openedTab = target;
+ if (openedTab.panes.isEmpty && openedTab.name == Swarm.defaultName) {
+ app.renameSwarm(openedTab.id, destination.title);
+ }
await Future.wait([
for (final row in members)
- app.addAgentToSwarm(row.machineId!, row.agentId!, swarmId: target.id),
+ _attachSearchHarness(app, row.machineId!, row.agentId!, swarmId: openedTab.id),
]);
return members.every(
- (row) => target.panes.any(
+ (row) => openedTab.panes.any(
(pane) =>
pane.machineId == row.machineId && pane.agentId == row.agentId,
),
@@ -1067,23 +1140,29 @@ Future<bool> activateSwarmSearchSelection(
(split != null && !app.isPaneSplitCurrent(split))) {
return false;
}
- await app.assignAgentToPane(
- null,
+ var target = app.swarms.singleWhere((s) => s.id == destinationSwarmId);
+ if (target.isSuperTab && target.superTabId != null) {
+ app.newSwarm();
+ target = app.activeSwarm;
+ }
+ final targetId = target.id;
+ await _attachSearchHarness(
+ app,
destination.machineId!,
destination.agentId!,
- swarmId: destinationSwarmId,
+ swarmId: targetId,
split: split,
);
- if (app.activeSwarmId == destinationSwarmId) {
+ if (app.activeSwarmId == targetId) {
app.revealAgentView(
destination.machineId!,
destination.agentId!,
- preferredSwarmId: destinationSwarmId,
+ preferredSwarmId: targetId,
);
}
return app.swarms.any(
(s) =>
- s.id == destinationSwarmId &&
+ s.id == targetId &&
s.panes.any(
(p) =>
p.machineId == destination.machineId &&
@@ -1123,12 +1202,18 @@ Future<bool> activateSwarmSearchSelection(
final target = app.swarms
.where((swarm) => swarm.id == destinationSwarmId)
.firstOrNull;
- if (target != null && target.panes.isEmpty) {
+ if (target != null &&
+ placement != HarnessPlacement.newTab &&
+ target.panes.isEmpty &&
+ (!target.isSuperTab || target.superTabId == null)) {
app.selectSwarm(target.id);
} else {
app.newSwarm(name: group.title);
}
- await app.seedSwarm(group.title, agents);
+ final opened = app.activeSwarmId;
+ final attachment = app.seedSwarm(group.title, agents);
+ app.finishSuperTabDraftNavigation(opened);
+ await attachment;
return true;
}
@@ -1142,6 +1227,7 @@ bool canOpenSwarmGroup(
Swarm? _matchingGroupSwarm(AppNotifier app, SwarmDestination destination) {
bool matches(Swarm swarm) =>
+ !swarm.isSuperTab &&
// Empty tabs only match their name; two empty projects are distinct.
(destination.members.isNotEmpty || swarm.name == destination.title) &&
swarm.panes.length == destination.members.length &&
@@ -1656,26 +1742,37 @@ Future<bool> activateSwarmDestination(
return false;
}
await _resumeStoppedDestination(app, destination);
- if (!app.swarms.any((s) => s.id == destinationSwarmId)) return false;
- await app.addAgentToSwarm(
+ var target = app.swarms
+ .where((s) => s.id == destinationSwarmId)
+ .firstOrNull;
+ if (target == null) return false;
+ if (target.isSuperTab && target.superTabId != null) {
+ app.newSwarm();
+ target = app.activeSwarm;
+ }
+ final targetId = target.id;
+ await _attachSearchHarness(
+ app,
destination.machineId!,
destination.agentId!,
- swarmId: destinationSwarmId,
+ swarmId: targetId,
);
- if (app.activeSwarmId == destinationSwarmId) {
+ if (app.activeSwarmId == targetId) {
final pane = app.focusedPane;
if (pane?.machineId == destination.machineId &&
pane?.agentId == destination.agentId) {
app.focusPane(pane!.id, reveal: true);
}
}
- return app.swarms.any(
+ final opened = app.swarms.any(
(s) =>
- s.id == destinationSwarmId &&
+ s.id == targetId &&
s.panes.any(
(p) =>
p.machineId == destination.machineId &&
p.agentId == destination.agentId,
),
);
+ if (opened) app.finishSuperTabDraftNavigation(targetId);
+ return opened;
}
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index d7576cbb8..fc1aa259c 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -34,6 +34,19 @@ const kHarnessPickerHint = kSwarmSearchHint;
const kSwarmCreateRowId = 'create:harness';
+/// A session picker can choose a contribution without opening a native pane.
+/// The caller owns that purpose and revalidates its authority on submission.
+class HarnessPickerContext {
+ const HarnessPickerContext({
+ required this.title,
+ required this.description,
+ required this.action,
+ required this.unavailable,
+ });
+ final String title, description, action;
+ final String? Function(SwarmDestination) unavailable;
+}
+
/// The Machines picker's two runs of rows: the account's computers, then its phones and apps.
enum MachineSearchSection {
computers('Computers'),
@@ -85,6 +98,8 @@ class SwarmSearchController extends ChangeNotifier {
this.offersHarnessCreate = true,
this.resultsFromBottom = false,
this.noteFor,
+ this.additionalDestinations = const [],
+ this.harnessContext,
this._placement,
this._split,
bool previewInitiallyVisible = true,
@@ -95,7 +110,7 @@ class SwarmSearchController extends ChangeNotifier {
_locations = locations ?? SwarmLocationCatalog(),
targetId = app.activeSwarmId,
targetName = app.activeSwarm.name {
- if (activityFirst && history == null && !navigating) {
+ if (activityFirst && history == null && !navigating && harnessContext == null) {
_content = SessionContentSearch(
machines: () => app.searchableMachineIds,
ask: (machineId, words, when) =>
@@ -117,6 +132,8 @@ class SwarmSearchController extends ChangeNotifier {
/// A line the box answers a query with, shown as the first row and never
/// taken by Return (the daemons' easter words: `xyzzy`).
final String? Function(String query)? noteFor;
+ final List<SwarmDestination> additionalDestinations;
+ final HarnessPickerContext? harnessContext;
final SwarmProjectStore? projects;
final ModelSearchCatalog? models;
bool modelDownloadsVisible = false;
@@ -1017,7 +1034,8 @@ class SwarmSearchController extends ChangeNotifier {
HarnessPlacement? get placement => _placement;
PaneSplitRequest? _split;
PaneSplitRequest? get split => _split;
- bool get allowsCommands => history == null && !navigating;
+ bool get allowsCommands =>
+ harnessContext == null && history == null && !navigating;
bool get isCommandMode =>
allowsCommands && (commandsOnly || query.trimLeft().startsWith('>'));
@@ -1163,6 +1181,7 @@ class SwarmSearchController extends ChangeNotifier {
bool _previewVisible;
bool get previewVisible => _previewVisible;
bool get supportsPreview =>
+ harnessContext == null &&
history == null && (setupLayout || !isCommandMode && !isHelpMode);
bool get canPreview =>
supportsPreview &&
@@ -1172,6 +1191,7 @@ class SwarmSearchController extends ChangeNotifier {
rows.any((row) => !row.isCreate);
bool get hasPreview =>
+ harnessContext == null &&
_previewVisible &&
(canPreview ||
setupLayout ||
@@ -1253,7 +1273,8 @@ class SwarmSearchController extends ChangeNotifier {
/// Cmd-T and Cmd-P change where Enter opens the result, while the query,
/// highlighted result and project/machine scope remain the person's choices.
bool changePlacement(HarnessPlacement placement) {
- if (!adding ||
+ if (harnessContext != null ||
+ !adding ||
navigating ||
history != null ||
targetId != app.activeSwarmId) {
@@ -1270,7 +1291,9 @@ class SwarmSearchController extends ChangeNotifier {
}
int get capacity {
- if (placement == HarnessPlacement.newTab) return AppNotifier.maxPanes;
+ if (harnessContext != null || placement == HarnessPlacement.newTab) {
+ return AppNotifier.maxPanes;
+ }
final target = app.swarms
.where((swarm) => swarm.id == targetId)
.firstOrNull;
@@ -1382,6 +1405,7 @@ class SwarmSearchController extends ChangeNotifier {
String get commandQuery => query.trimLeft().replaceFirst(_commandPrefix, '');
String get primaryAction =>
+ harnessContext?.action ??
placement?.action ??
switch (split?.axis) {
PaneResizeAxis.x => 'Split right',
@@ -1389,7 +1413,10 @@ class SwarmSearchController extends ChangeNotifier {
null => 'Open Harness',
};
- String actionLabel(SwarmDestination? row) => row?.isAgentChoice == true
+ String actionLabel(SwarmDestination? row) =>
+ harnessContext != null && row?.agentId != null
+ ? harnessContext!.action
+ : row?.isAgentChoice == true
? 'Change agent'
: row?.isCreate == true
? isModelMode
@@ -1473,11 +1500,17 @@ class SwarmSearchController extends ChangeNotifier {
return;
}
final storeChanged = isStoreMode && _refreshStore();
- final next = navigating
+ final base = navigating
? _locations.read(app, projects?.projects ?? const [])
: history == null
? _cache.read(app, projects?.projects ?? const [], recent: recent)
: [...history!.menuDestinations(app), ...closedWorkDestinations(app)];
+ final next = additionalDestinations.isEmpty
+ ? base
+ : <String, SwarmDestination>{
+ for (final row in additionalDestinations) row.id: row,
+ for (final row in base) row.id: row,
+ }.values.toList();
final splitCurrent = split == null || app.isPaneSplitCurrent(split!);
if (!force &&
sessionFilter == SessionFilter.all &&
@@ -1528,6 +1561,12 @@ class SwarmSearchController extends ChangeNotifier {
notifyListeners();
}
+ /// A contribution's permissions and membership can change without changing
+ /// the native machine catalog. Keep the person's query and selection intact.
+ void refreshAvailability() {
+ if (harnessContext != null) notifyListeners();
+ }
+
void _modelsChanged() {
if (!isModelMode) return;
_filter();
@@ -2204,6 +2243,10 @@ class SwarmSearchController extends ChangeNotifier {
matchQuery.trim().isNotEmpty)
? 1
: cursor.clamp(0, rows.length - 1);
+ if (harnessContext != null && preferred == null) {
+ final agent = rows.indexWhere((row) => row.agentId != null && canSubmit(row));
+ if (agent >= 0) cursor = agent;
+ }
// Nor on a row Return cannot take: "Already added", dimmed, with its
// reason stranded at the bottom. Only when the position is ours to pick —
// a row somebody arrowed to stays theirs.
@@ -2378,6 +2421,9 @@ class SwarmSearchController extends ChangeNotifier {
/// Read live state at activation too: a rendered row can outlive a disconnect.
String? sessionUnavailable(SwarmDestination? row) {
+ if (harnessContext != null && row?.agentId != null) {
+ return harnessContext!.unavailable(row!);
+ }
if (row?.external case final external?) {
// Short: it is a row's note. The preview says what to do about it. Its
// preview's answer is the fresher, when there is one.
@@ -2452,9 +2498,12 @@ class SwarmSearchController extends ChangeNotifier {
: row.members.any((id) => !_presentIds.contains(id));
bool alreadyHere(SwarmDestination row) =>
+ harnessContext == null &&
adding && row.agentId != null && _presentIds.contains(row.id);
- bool canAdd(SwarmDestination? row) => row?.external != null
+ bool canAdd(SwarmDestination? row) => harnessContext != null
+ ? adding && row?.agentId != null && sessionUnavailable(row) == null
+ : row?.external != null
// A conversation Harness did not start becomes a new harness: room for
// one more pane, or a tab of its own.
? !navigating &&
diff --git a/desktop/lib/state/terminal_pane.dart b/desktop/lib/state/terminal_pane.dart
index b703fac37..b1082b713 100644
--- a/desktop/lib/state/terminal_pane.dart
+++ b/desktop/lib/state/terminal_pane.dart
@@ -81,6 +81,10 @@ class TerminalPane {
TerminalSession? session;
+ /// Ephemeral input provenance. Never persisted in shared pane layout.
+ String? inputContext;
+ bool watchOnly = false;
+
/// Browser viewer input, installed only while its renderer is mounted.
bool Function()? focusViewerInput;
SharedHarness? sharedHarness;
diff --git a/desktop/lib/super_tabs/actions.dart b/desktop/lib/super_tabs/actions.dart
new file mode 100644
index 000000000..d0c0082c2
--- /dev/null
+++ b/desktop/lib/super_tabs/actions.dart
@@ -0,0 +1,63 @@
+import '../state/app_state.dart';
+import 'controller.dart';
+
+Future<void> addSuperTabAgent(
+ AppNotifier app,
+ String tabId,
+ String conversationId,
+ String machineId,
+ String harnessId,
+) async {
+ final c = await app.superTabs.open(tabId);
+ await c.refresh();
+ final existing = c.snapshot?.agents
+ .where((a) => a.machineId == machineId && a.harnessId == harnessId)
+ .firstOrNull;
+ Map<String, dynamic> command;
+ if (existing != null) {
+ command = {
+ 'type': 'conversation.agent',
+ 'conversationId': conversationId,
+ 'agentId': existing.id,
+ 'present': true,
+ 'lead': false,
+ };
+ } else {
+ final native = app
+ .stateOf(machineId)
+ ?.agents
+ .where((a) => a.id == harnessId)
+ .firstOrNull;
+ if (native == null || native.engine == 'terminal') {
+ throw const SuperTabFailure(
+ 'AGENT_UNAVAILABLE',
+ 'Choose a running agent.',
+ );
+ }
+ command = {
+ 'type': 'agent.add',
+ 'conversationId': conversationId,
+ 'machineId': machineId,
+ 'harnessId': harnessId,
+ 'name': native.displayName,
+ 'lead': false,
+ 'configuration': {
+ 'engine': native.engine ?? '',
+ 'model': native.modelName,
+ 'effort': native.modelEffort,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ };
+ }
+ final result = await c.command(command);
+ if (result == null) {
+ throw SuperTabFailure(
+ 'ADD_FAILED',
+ c.operationError ?? 'Could not add the agent.',
+ );
+ }
+ if (existing == null) {
+ await app.wakeSuperTabHost(machineId);
+ }
+}
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
new file mode 100644
index 000000000..1308a730d
--- /dev/null
+++ b/desktop/lib/super_tabs/client.dart
@@ -0,0 +1,127 @@
+import 'dart:async';
+import 'dart:convert';
+
+import '../core/local_key_value_store.dart';
+import 'controller.dart';
+import 'model.dart';
+
+typedef SuperTabTransport = Future<Object?> Function(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+});
+
+/// Account-scoped client state. Backend membership never comes from the saved
+/// layout, and a late response cannot cross an account change.
+class SuperTabClient {
+ SuperTabClient({
+ required this.transport,
+ required this.storage,
+ this.onSnapshot,
+ });
+ final SuperTabTransport transport;
+ final LocalKeyValueStore storage;
+ final void Function(SuperTabController)? onSnapshot;
+ String? _account;
+ int _generation = 0;
+ final _controllers = <String, Future<SuperTabController>>{};
+ final _loaded = <String, SuperTabController>{};
+ SuperTabController? peek(String id) => _loaded[id];
+
+ void bind(String? account) {
+ if (_account == account) return;
+ _account = account;
+ _generation++;
+ for (final controller in _loaded.values) {
+ controller.revokeAccess(
+ 'The account changed. Open this Super Tab again.',
+ );
+ }
+ for (final future in _controllers.values) {
+ unawaited(
+ future
+ .then((c) async {
+ c.dispose();
+ await c.flush();
+ })
+ .catchError((Object _) {}),
+ );
+ }
+ _controllers.clear();
+ _loaded.clear();
+ }
+
+ Future<Object?> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (_account == null) {
+ throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Super Tab.');
+ }
+ final generation = _generation;
+ final result = await transport(method, path, body: body);
+ if (generation != _generation) {
+ throw const SuperTabFailure(
+ 'ACCOUNT_CHANGED',
+ 'The account changed. Open this Super Tab again.',
+ );
+ }
+ return result;
+ }
+
+ Future<Map<String, dynamic>> map(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async => superTabMap(await request(method, path, body: body));
+
+ Future<SuperTabController> open(String id) =>
+ _controllers.putIfAbsent(id, () {
+ final generation = _generation;
+ return _open(id).catchError((Object failure, StackTrace stack) {
+ if (_generation == generation) _controllers.remove(id);
+ Error.throwWithStackTrace(failure, stack);
+ });
+ });
+
+ Future<SuperTabController> _open(String id) async {
+ final account = _account;
+ final generation = _generation;
+ if (account == null) {
+ throw const SuperTabFailure('SIGNED_OUT', 'Sign in to use Super Tab.');
+ }
+ final key = 'super_tab.$account.$id';
+ final raw = await storage.read(key);
+ if (generation != _generation) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ final saved = raw == null
+ ? <String, dynamic>{}
+ : superTabMap(jsonDecode(raw));
+ final controller = SuperTabController(
+ tabId: id,
+ accountId: account,
+ initial: saved,
+ request: (method, path, {body}) {
+ if (generation != _generation) {
+ throw const SuperTabFailure('FORBIDDEN', 'The account changed.');
+ }
+ return map(method, path, body: body);
+ },
+ save: (state) => storage.write(key, jsonEncode(state)),
+ );
+ var seenRevision = -1;
+ controller.addListener(() {
+ if (controller.snapshot != null && controller.revision != seenRevision) {
+ seenRevision = controller.revision;
+ onSnapshot?.call(controller);
+ }
+ });
+ _loaded[id] = controller;
+ controller.start();
+ return controller;
+ }
+
+ void dispose() => bind(null);
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
new file mode 100644
index 000000000..a647aa5f4
--- /dev/null
+++ b/desktop/lib/super_tabs/controller.dart
@@ -0,0 +1,497 @@
+import 'dart:async';
+import 'dart:math';
+
+import 'package:flutter/foundation.dart';
+
+import 'model.dart';
+
+typedef SuperTabRequest = Future<Map<String, dynamic>> Function(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+});
+
+String superTabOperationId() {
+ final random = Random.secure();
+ return List.generate(
+ 16,
+ (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0'),
+ ).join();
+}
+
+class SuperTabFailure implements Exception {
+ const SuperTabFailure(this.code, this.message, {this.statusCode = 0});
+ final String code, message;
+ final int statusCode;
+ @override
+ String toString() => message;
+}
+
+/// Personal navigation/drafts live on this client. Membership, work and messages
+/// live on the backend; refreshing never selects another person's conversation.
+class SuperTabController extends ChangeNotifier {
+ SuperTabController({
+ required this.tabId,
+ required this.accountId,
+ required this.request,
+ required this.save,
+ Map<String, dynamic> initial = const {},
+ this.pollInterval = const Duration(seconds: 3),
+ }) {
+ if (initial['tabId'] == tabId && initial['accountId'] == accountId) {
+ selectedId = initial['selectedId'] as String? ?? 'lead';
+ final drafts = initial['drafts'];
+ if (drafts is Map) {
+ for (final entry in drafts.entries) {
+ if (entry.key is String && entry.value is String) {
+ _drafts[entry.key as String] = entry.value as String;
+ }
+ }
+ }
+ final read = initial['readAt'];
+ final terminals = initial['terminals'];
+ if (terminals is Map) {
+ for (final entry in terminals.entries) {
+ if (entry.key is String && entry.value is String) {
+ _terminals[entry.key as String] = entry.value as String;
+ }
+ }
+ }
+ final mentions = initial['mentions'];
+ if (mentions is Map) {
+ for (final group in mentions.entries) {
+ if (group.key is String && group.value is Map) {
+ _mentions[group.key as String] = {
+ for (final mention in (group.value as Map).entries)
+ if (mention.key is String && mention.value is String)
+ mention.key as String: mention.value as String,
+ };
+ }
+ }
+ }
+ if (read is Map) {
+ for (final entry in read.entries) {
+ if (entry.key is String && entry.value is num) {
+ _readAt[entry.key as String] = (entry.value as num).toInt();
+ }
+ }
+ }
+ if (initial['pending'] is Map) {
+ final value = superTabMap(initial['pending']);
+ if (value['operationId'] is String && value['command'] is Map) {
+ _pending = value;
+ operationError = 'Check the pending action before sending it again.';
+ }
+ }
+ }
+ }
+
+ final String tabId, accountId;
+ final SuperTabRequest request;
+ final Future<void> Function(Map<String, dynamic> state) save;
+ final Duration pollInterval;
+ SuperTabSnapshot? snapshot;
+ String selectedId = 'lead';
+ int revision = -1;
+ String? error, operationError;
+ bool loading = false, saving = false, accessRevoked = false;
+ bool _disposed = false;
+ Timer? _poll, _draftSave;
+ Future<void>? _refreshing;
+ Future<void> _persisting = Future.value();
+ Map<String, dynamic>? _pending;
+ final _drafts = <String, String>{};
+ final _terminals = <String, String>{};
+ final _mentions = <String, Map<String, String>>{};
+ final _readAt = <String, int>{};
+ final _messages = <String, List<SuperTabMessage>>{};
+ final _before = <String, int?>{};
+ final _reading = <String>{};
+
+ String get _path => '/api/super-tabs/${Uri.encodeComponent(tabId)}';
+ SuperTabConversation? get selected => snapshot?.conversation(selectedId);
+ bool get isOwner => snapshot?.ownerId == accountId;
+ bool get canWrite =>
+ !_disposed &&
+ !accessRevoked &&
+ (snapshot?.people.where((p) => p.id == accountId).firstOrNull?.canWrite ??
+ false);
+ bool get hasPendingAction => _pending != null;
+ Map<String, dynamic>? get pendingCommand =>
+ _pending == null ? null : superTabMap(_pending!['command']);
+ String draft(String id) => _drafts[id] ?? '';
+ SuperTabAgent? terminalAgent(String conversationId) {
+ if (accessRevoked) return null;
+ final id = _terminals[conversationId];
+ final group = snapshot?.conversation(conversationId);
+ if (id == null || group?.agentIds.contains(id) != true) return null;
+ return snapshot?.agents.where((a) => a.id == id).firstOrNull;
+ }
+
+ void selectTerminal(String conversationId, String? agentId) {
+ if (_disposed || accessRevoked) return;
+ if (agentId != null &&
+ snapshot?.conversation(conversationId)?.agentIds.contains(agentId) !=
+ true) {
+ return;
+ }
+ if (_terminals[conversationId] == agentId) return;
+ if (agentId == null) {
+ _terminals.remove(conversationId);
+ } else {
+ _terminals[conversationId] = agentId;
+ }
+ _saveSoon();
+ _changed();
+ }
+
+ List<SuperTabMessage> messages(String id) =>
+ List.unmodifiable(_messages[id] ?? const []);
+ bool hasOlder(String id) => _before[id] != null;
+ bool unread(SuperTabConversation group) =>
+ group.lastMessageSequence > (_readAt[group.id] ?? 0);
+
+ void start() {
+ if (_disposed) return;
+ unawaited(refresh());
+ _poll?.cancel();
+ if (pollInterval > Duration.zero) {
+ _poll = Timer.periodic(pollInterval, (_) => unawaited(refresh()));
+ }
+ }
+
+ void _changed() {
+ if (!_disposed) notifyListeners();
+ }
+
+ /// Open dialogs and native panes lose their content immediately, before
+ /// account cleanup waits for an in-flight read or a draft write.
+ void revokeAccess(String message) {
+ if (_disposed) return;
+ accessRevoked = true;
+ error = message;
+ snapshot = null;
+ _messages.clear();
+ _poll?.cancel();
+ _changed();
+ }
+
+ Map<String, dynamic> _localState() => {
+ 'tabId': tabId,
+ 'accountId': accountId,
+ 'selectedId': selectedId,
+ 'drafts': Map<String, String>.of(_drafts),
+ 'terminals': Map<String, String>.of(_terminals),
+ 'mentions': {
+ for (final entry in _mentions.entries)
+ entry.key: Map<String, String>.of(entry.value),
+ },
+ 'readAt': Map<String, int>.of(_readAt),
+ if (_pending != null) 'pending': _pending,
+ };
+
+ Future<void> _persist() {
+ // Serial writes prevent an older autosave from restoring a resolved receipt.
+ final next = _persisting
+ .catchError((Object _) {})
+ .then((_) => save(_localState()));
+ _persisting = next;
+ return next;
+ }
+
+ void _saveSoon() {
+ _draftSave?.cancel();
+ _draftSave = Timer(const Duration(milliseconds: 200), () {
+ unawaited(
+ _persist().catchError((Object _) {
+ error = 'Could not save this draft on this computer.';
+ _changed();
+ }),
+ );
+ });
+ }
+
+ void setDraft(String conversationId, String value) {
+ _drafts[conversationId] = value;
+ _mentions[conversationId]?.removeWhere(
+ (_, token) => !containsMention(value, token),
+ );
+ _saveSoon();
+ }
+
+ static bool containsMention(String text, String token) =>
+ RegExp('(?:^|\\s)${RegExp.escape(token)}(?=\$|\\s|[.,!?;:])')
+ .hasMatch(text);
+
+ void mention(String conversationId, String agentId, String token) {
+ if (containsMention(draft(conversationId), token)) {
+ (_mentions[conversationId] ??= {})[agentId] = token;
+ _saveSoon();
+ _changed();
+ }
+ }
+
+ Map<String, String> mentions(String conversationId) =>
+ Map.unmodifiable(_mentions[conversationId] ?? const {});
+
+ void select(String id) {
+ if (snapshot?.conversation(id) == null || id == selectedId) return;
+ selectedId = id;
+ _saveSoon();
+ _changed();
+ unawaited(loadMessages(id));
+ }
+
+ /// A visible transcript passes its loaded boundary: a newer snapshot may
+ /// already advertise messages that have not arrived on this client yet.
+ void markRead(String id, {int? through}) {
+ final advertised = snapshot?.conversation(id)?.lastMessageSequence ?? 0;
+ final last = through == null ? advertised : min(through, advertised);
+ if ((_readAt[id] ?? 0) >= last) return;
+ _readAt[id] = last;
+ _saveSoon();
+ _changed();
+ }
+
+ Future<void> refresh() {
+ if (_disposed || accessRevoked) return Future.value();
+ return _refreshing ??= _read().whenComplete(() => _refreshing = null);
+ }
+
+ Future<void> _read() async {
+ loading = snapshot == null;
+ _changed();
+ try {
+ final answer = await request('GET', _path);
+ if (_disposed || accessRevoked) return;
+ final nextRevision = (answer['revision'] as num).toInt();
+ final next = SuperTabSnapshot.fromJson(superTabMap(answer['state']));
+ if (next.id != tabId) {
+ throw const FormatException('A different Super Tab was returned.');
+ }
+ if (nextRevision >= revision) {
+ snapshot = next;
+ if (next.conversation(selectedId) == null) selectedId = 'lead';
+ revision = nextRevision;
+ error = null;
+ }
+ await loadMessages(selectedId);
+ } catch (failure) {
+ _readFailure(failure);
+ } finally {
+ loading = false;
+ _changed();
+ }
+ }
+
+ void _readFailure(Object failure) {
+ if (_disposed) return;
+ error = failure is SuperTabFailure
+ ? failure.message
+ : 'Could not refresh this conversation. Try again.';
+ if (failure is SuperTabFailure &&
+ const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
+ accessRevoked = true;
+ snapshot = null;
+ _messages.clear();
+ _poll?.cancel();
+ }
+ }
+
+ Future<void> loadMessages(String id, {bool older = false}) async {
+ if (_disposed ||
+ accessRevoked ||
+ _reading.contains(id) ||
+ snapshot?.conversation(id) == null) {
+ return;
+ }
+ if (older && !hasOlder(id)) return;
+ _reading.add(id);
+ try {
+ final known = _messages[id];
+ final tail = known != null && known.isNotEmpty
+ ? known.last.sequence
+ : null;
+ final query = older
+ ? '?before=${_before[id]}'
+ : tail != null
+ ? '?after=$tail'
+ : '';
+ var answer = await request(
+ 'GET',
+ '$_path/conversations/${Uri.encodeComponent(id)}/messages$query',
+ );
+ if (!_disposed &&
+ !older &&
+ tail != null &&
+ (answer['messages'] as List).isEmpty) {
+ // No new text: refresh delivery receipts in the page already shown.
+ answer = await request(
+ 'GET',
+ '$_path/conversations/${Uri.encodeComponent(id)}/messages?before=${tail + 1}',
+ );
+ }
+ if (_disposed || accessRevoked) return;
+ final incoming = (answer['messages'] as List)
+ .map((m) => SuperTabMessage.fromJson(superTabMap(m)))
+ .toList();
+ if (incoming.any((m) => m.conversationId != id)) {
+ throw const FormatException('A different conversation was returned.');
+ }
+ final combined = {
+ for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,
+ for (final m in incoming) m.id: m,
+ };
+ _messages[id] = combined.values.toList()
+ ..sort((a, b) => a.sequence.compareTo(b.sequence));
+ if (older || !_before.containsKey(id)) {
+ _before[id] = (answer['next'] as num?)?.toInt();
+ }
+ _changed();
+ } catch (failure) {
+ _readFailure(failure);
+ _changed();
+ } finally {
+ _reading.remove(id);
+ }
+ }
+
+ Future<Map<String, dynamic>?> command(Map<String, dynamic> command) async {
+ if (_disposed || !_maySend(command) || saving || _pending != null) {
+ return null;
+ }
+ _pending = {
+ 'operationId': superTabOperationId(),
+ 'command': Map<String, dynamic>.of(command),
+ };
+ return retry();
+ }
+
+ Future<Map<String, dynamic>?> retry() async {
+ final pending = _pending;
+ if (_disposed ||
+ saving ||
+ pending == null ||
+ !_maySend(superTabMap(pending['command']))) {
+ return null;
+ }
+ saving = true;
+ operationError = null;
+ _changed();
+ try {
+ // The receipt ID reaches durable local storage before the request can reach the server.
+ await _persist();
+ if (_disposed) return null;
+ final answer = await request('POST', '$_path/commands', body: pending);
+ if (_disposed) return null;
+ final result = superTabMap(answer['result']);
+ final command = superTabMap(pending['command']);
+ if (command['type'] == 'message.send') {
+ final id = command['conversationId'] as String;
+ if (_drafts[id]?.trim() == command['text']) {
+ _drafts.remove(id);
+ _mentions.remove(id);
+ }
+ }
+ if (command['type'] == 'conversation.create' &&
+ result['conversationId'] is String) {
+ // A successful create selects its confirmed destination even when the
+ // following read is offline. Never leave the old group's composer active.
+ selectedId = result['conversationId'] as String;
+ }
+ _pending = null;
+ try {
+ await _persist();
+ } catch (_) {
+ _pending = pending;
+ rethrow;
+ }
+ await refresh();
+ if (!_disposed &&
+ revision < ((answer['revision'] as num?)?.toInt() ?? revision)) {
+ await refresh();
+ }
+ return result;
+ } catch (failure) {
+ if (!_disposed) {
+ operationError = failure is SuperTabFailure
+ ? failure.message
+ : 'The action is not confirmed. Retry to check it.';
+ if (failure is SuperTabFailure &&
+ failure.statusCode >= 400 &&
+ failure.statusCode < 500 &&
+ !const {408, 429}.contains(failure.statusCode)) {
+ // A definitive rejection made no change. Preserve the draft and let
+ // the person correct it; a lost reply retains its exact receipt ID.
+ _pending = null;
+ try {
+ await _persist();
+ } catch (_) {
+ _pending = pending;
+ }
+ }
+ if (failure is SuperTabFailure &&
+ const {
+ 'FORBIDDEN',
+ 'NOT_FOUND',
+ 'READ_ONLY',
+ }.contains(failure.code)) {
+ await refresh();
+ }
+ }
+ return null;
+ } finally {
+ saving = false;
+ _changed();
+ }
+ }
+
+ bool _maySend(Map<String, dynamic> command) =>
+ canWrite ||
+ (!accessRevoked &&
+ snapshot != null &&
+ command['type'] == 'member.remove' &&
+ command['userId'] == accountId);
+
+ Future<Map<String, dynamic>?> send({
+ String? replyTo,
+ List<String> recipients = const [],
+ }) {
+ final text = draft(selectedId).trim();
+ if (text.isEmpty || selected == null || selected!.archived) {
+ return Future.value(null);
+ }
+ final addressed = recipients.isEmpty
+ ? mentions(selectedId).entries
+ .where((entry) => containsMention(text, entry.value))
+ .map((entry) => entry.key)
+ .toList()
+ : recipients;
+ if (addressed.any((id) => !selected!.agentIds.contains(id))) {
+ operationError = 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.';
+ _changed();
+ return Future.value(null);
+ }
+ return command({
+ 'type': 'message.send',
+ 'conversationId': selectedId,
+ 'text': text,
+ 'replyTo': replyTo,
+ 'recipientIds': addressed,
+ });
+ }
+
+ Future<void> flush() async {
+ _draftSave?.cancel();
+ await _persist();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _poll?.cancel();
+ _draftSave?.cancel();
+ // The owner awaits flush when changing account or closing the tab.
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/super_tabs/dialog_scope.dart b/desktop/lib/super_tabs/dialog_scope.dart
new file mode 100644
index 000000000..f7de67f2b
--- /dev/null
+++ b/desktop/lib/super_tabs/dialog_scope.dart
@@ -0,0 +1,41 @@
+import 'package:flutter/material.dart';
+
+import 'controller.dart';
+
+/// Keep a modal tied to the account and tab that opened it. Revocation removes
+/// its captured form contents before a different account can see or submit them.
+class SuperTabDialogScope extends StatelessWidget {
+ const SuperTabDialogScope({
+ super.key,
+ required this.controller,
+ required this.child,
+ this.requireWrite = true,
+ });
+
+ final SuperTabController controller;
+ final Widget child;
+ final bool requireWrite;
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ if (!controller.accessRevoked &&
+ controller.snapshot != null &&
+ (!requireWrite || controller.canWrite)) {
+ // The shared backdrop owns a fallback focus node for Escape. A form
+ // gets its own scope so its initial editor wins that fallback.
+ return FocusScope(autofocus: true, child: child);
+ }
+ return AlertDialog(
+ content: const Text('This action is no longer available.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ },
+ );
+}
diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dart
new file mode 100644
index 000000000..e7e595475
--- /dev/null
+++ b/desktop/lib/super_tabs/launch.dart
@@ -0,0 +1,266 @@
+import 'dart:convert';
+
+import '../core/models.dart';
+import '../state/app_state.dart';
+import '../state/harness_attachments.dart';
+import '../state/harness_launch_integration.dart';
+import '../state/swarm.dart';
+import 'controller.dart';
+import 'model.dart';
+
+/// Captures a conversation before opening New Harness. Its journal survives a
+/// closed form or process; a recovered launch only reads the native receipt.
+class SuperTabLaunch {
+ SuperTabLaunch._(
+ this.app,
+ this.swarmId,
+ this.accountId,
+ this.key,
+ this.saved,
+ );
+ final AppNotifier app;
+ final String swarmId, accountId, key;
+ final Map<String, dynamic> saved;
+
+ static Future<HarnessLaunchIntegration> open(
+ AppNotifier app,
+ Swarm tab,
+ String conversationId,
+ ) async {
+ final account = app.currentUser?.id;
+ if (account == null) {
+ throw const SuperTabFailure(
+ 'SIGNED_OUT',
+ 'Sign in to create a Super Tab.',
+ );
+ }
+ final key = 'super_tab.launch.$account.${tab.id}.$conversationId';
+ final raw = await app.superTabs.storage.read(key);
+ if (app.currentUser?.id != account) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ final saved = raw == null
+ ? <String, dynamic>{
+ 'operationId': superTabOperationId(),
+ 'joinId': superTabOperationId(),
+ 'tabId': tab.superTabId,
+ 'conversationId': conversationId,
+ 'lead': tab.superTabId == null,
+ }
+ : superTabMap(jsonDecode(raw));
+ final launch = SuperTabLaunch._(app, tab.id, account, key, saved);
+ final recovering =
+ saved['phase'] == 'starting' || saved['phase'] == 'joining';
+ late final HarnessLaunchIntegration integration;
+ integration = HarnessLaunchIntegration(
+ creationId: saved['creationId'] as String? ?? superTabOperationId(),
+ actionLabel: saved['lead'] == true ? 'New Super Tab' : 'New Harness',
+ prepare: launch.prepare,
+ beforeSubmit: (machine, receipt) async {
+ saved['machineId'] = machine;
+ saved['creationId'] = receipt;
+ saved['phase'] = 'starting';
+ await launch.persist();
+ },
+ complete: launch.complete,
+ stageAttachments: launch.stageAttachments,
+ needsAttachmentReview: () => saved['filesState'] == 'sending',
+ resolveAttachments: (resend) async {
+ launch.checkAccount();
+ saved['filesState'] = resend ? 'pending' : 'delivered';
+ await launch.persist();
+ await launch.resume();
+ },
+ resume: recovering
+ ? () async {
+ try {
+ await launch.resume();
+ } on SuperTabFailure catch (failure) {
+ if (failure.code == 'CREATION_FAILED') {
+ saved.remove('phase');
+ saved.remove('creationId');
+ await launch.persist();
+ integration.pending = false;
+ integration.resume = null;
+ }
+ rethrow;
+ }
+ }
+ : null,
+ )..pending = recovering;
+ return integration;
+ }
+
+ void checkAccount() {
+ if (app.currentUser?.id != accountId) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ }
+
+ Future<void> persist() async {
+ checkAccount();
+ await app.superTabs.storage.write(key, jsonEncode(saved));
+ checkAccount();
+ }
+
+ Future<String> prepare(String machine, String task) async {
+ checkAccount();
+ saved['initialMessage'] = task;
+ saved['machineId'] = machine;
+ await persist();
+ if (saved['tabId'] == null) {
+ final created = await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs',
+ body: {'operationId': saved['operationId'], 'name': 'Super Tab'},
+ );
+ saved['tabId'] = created['id'];
+ await persist();
+ }
+ final command = 'harness super-tab --tab ${saved['tabId']}';
+ final prompt =
+ 'You are an agent in a shared Harness Super Tab. '
+ '${saved['lead'] == true ? 'You are its coordinating lead. Start by discussing the person’s request; build after they authorize it.' : 'Join the conversation before beginning the person’s request.'}\n'
+ 'First run `$command status`. Registration may still be finishing: if it reports AGENT_UNAVAILABLE, wait briefly and retry. '
+ 'Do not start work or post until it confirms your participation.\n'
+ 'Read the conversation: `$command messages ${saved['conversationId']}`. '
+ 'Post explanations, questions and results with `$command post ${saved['conversationId']} "message" UNIQUE_OPERATION_ID`. '
+ 'Reuse that operation ID and exact message after a lost reply. Your native terminal is not the shared conversation.\n'
+ 'If sandbox restrictions block this local Harness command, request permission to run it outside the sandbox. '
+ 'For work groups, assignments, acceptance evidence and messages to other agents, use `$command help`. '
+ 'Use a group for an independently assignable outcome with acceptance checks. Reuse existing groups and agents. '
+ 'Engine-native helper subagents do not need a group. Questions stay in the conversation where the work happens. '
+ 'Report exact revisions, evidence and links appropriate to the project.\n\n'
+ 'The person’s request:\n${task.isEmpty ? 'Ask what they would like to work on.' : task}';
+ saved['launchPrompt'] = prompt;
+ await persist();
+ return prompt;
+ }
+
+ Future<void> stageAttachments(
+ List<HarnessAttachment> files,
+ String prompt,
+ ) async {
+ checkAccount();
+ saved['files'] = [
+ for (final file in files)
+ {'name': file.name, 'bytes': base64Encode(file.bytes)},
+ ];
+ saved['launchPrompt'] = prompt;
+ saved['filesState'] = 'pending';
+ await persist();
+ }
+
+ Future<void> complete(
+ String machine,
+ String harnessId, {
+ Agent? recovered,
+ }) async {
+ checkAccount();
+ saved['machineId'] = machine;
+ saved['harnessId'] = harnessId;
+ saved['phase'] = 'joining';
+ final native =
+ recovered ??
+ app
+ .stateOf(machine)
+ ?.agents
+ .where((a) => a.id == harnessId)
+ .firstOrNull;
+ if (native == null) {
+ throw const SuperTabFailure(
+ 'AGENT_UNAVAILABLE',
+ 'Waiting for the new harness to appear on its machine.',
+ );
+ }
+ saved['command'] ??= {
+ 'type': 'agent.add',
+ 'conversationId': saved['conversationId'],
+ 'machineId': machine,
+ 'harnessId': harnessId,
+ 'name': native.displayName,
+ 'lead': saved['lead'],
+ 'configuration': {
+ 'engine': native.engine ?? '',
+ 'model': native.modelName,
+ 'effort': native.modelEffort,
+ 'contextWindow': null,
+ 'engineVersion': null,
+ },
+ if ((saved['initialMessage'] as String? ?? '').isNotEmpty)
+ 'initialMessage': saved['initialMessage'],
+ };
+ await persist();
+ final tabId = saved['tabId'] as String;
+ await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/$tabId/commands',
+ body: {'operationId': saved['joinId'], 'command': saved['command']},
+ );
+ // Waking the exact host starts only its authorized contributions. It is
+ // safe to retry, and never grants machine access to the tab's members.
+ await app.wakeSuperTabHost(machine);
+ if (saved['lead'] == true) {
+ final name = Swarm.titleFor(native);
+ final title =
+ saved['title'] as String? ??
+ (name == Swarm.defaultName ? 'Super Tab' : name);
+ saved['title'] = title;
+ await persist();
+ await app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/$tabId/commands',
+ body: {
+ 'operationId': '${saved['joinId']}-name',
+ 'command': {'type': 'tab.rename', 'name': title},
+ },
+ );
+ checkAccount();
+ }
+ final controller = await app.superTabs.open(tabId);
+ await controller.refresh();
+ checkAccount();
+ final files = (saved['files'] as List? ?? []).map((value) {
+ final file = superTabMap(value);
+ return HarnessAttachment(
+ file['name'] as String,
+ base64Decode(file['bytes'] as String),
+ );
+ }).toList();
+ if (files.isNotEmpty && saved['filesState'] != 'delivered') {
+ if (saved['filesState'] == 'sending') {
+ throw const SuperTabFailure(
+ 'FILES_UNCONFIRMED',
+ 'The harness started, but file delivery was interrupted. Open its terminal to check before sending the files or request again.',
+ );
+ }
+ saved['filesState'] = 'sending';
+ await persist();
+ final problem = await app.deliverBackgroundAttachments(
+ machineId: machine,
+ agentId: harnessId,
+ files: files,
+ task: saved['launchPrompt'] as String,
+ );
+ checkAccount();
+ if (problem != null) throw SuperTabFailure('FILES_UNCONFIRMED', problem);
+ saved['filesState'] = 'delivered';
+ saved.remove('files');
+ await persist();
+ }
+ if (saved['lead'] == true) {
+ app.bindSuperTab(swarmId, tabId, saved['title'] as String);
+ }
+ await app.superTabs.storage.delete(key);
+ }
+
+ Future<void> resume() async {
+ checkAccount();
+ final machine = saved['machineId'] as String;
+ final native = await app.recoverSuperTabCreation(
+ machine,
+ saved['creationId'] as String,
+ );
+ await complete(machine, native.id, recovered: native);
+ }
+}
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
new file mode 100644
index 000000000..5f70260ef
--- /dev/null
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -0,0 +1,353 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_icon_button.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/engine_identity.dart';
+import '../widgets/workspace_account_button.dart';
+import 'message_text.dart';
+import 'model.dart';
+
+/// Presentation only. Message identity and reply routing use backend IDs.
+class SuperTabMessageRow extends StatefulWidget {
+ const SuperTabMessageRow({
+ super.key,
+ required this.message,
+ required this.author,
+ required this.onReturnToComposer,
+ required this.receipts,
+ this.agent,
+ this.machineName,
+ this.reply,
+ this.grouped = false,
+ this.onReply,
+ });
+
+ final SuperTabMessage message;
+ final String author;
+ final SuperTabAgent? agent;
+ final String? machineName;
+ final SuperTabMessage? reply;
+ final bool grouped;
+ final VoidCallback? onReply;
+ final VoidCallback onReturnToComposer;
+ final List<Widget> receipts;
+
+ /// Compact only a few short updates. Reports and long runs retain their own
+ /// speaker identity, so scrolling through agent output does not lose the who.
+ static Set<String> consecutiveUpdates(List<SuperTabMessage> messages) {
+ final joined = <String>{};
+ var first = 0;
+ for (var i = 1; i < messages.length; i++) {
+ if (i - first < 3 &&
+ groupsWith(messages[i], messages[i - 1]) &&
+ groupsWith(messages[i], messages[first])) {
+ joined.add(messages[i].id);
+ } else {
+ first = i;
+ }
+ }
+ return joined;
+ }
+
+ static bool groupsWith(SuperTabMessage current, SuperTabMessage? previous) {
+ if (previous == null ||
+ current.replyTo != null ||
+ previous.replyTo != null ||
+ current.text.length > 280 ||
+ previous.text.length > 280 ||
+ current.text.contains('\n') ||
+ previous.text.contains('\n') ||
+ current.text.contains('?') ||
+ previous.text.contains('?') ||
+ current.text.contains('?') ||
+ previous.text.contains('?') ||
+ current.authorId.isEmpty ||
+ current.authorId != previous.authorId ||
+ current.authorName != previous.authorName ||
+ current.author['kind'] != previous.author['kind'] ||
+ current.author['membershipGeneration'] !=
+ previous.author['membershipGeneration'] ||
+ current.terminalNote != previous.terminalNote) {
+ return false;
+ }
+ final now = current.createdAt, before = previous.createdAt;
+ if (now == null || before == null) return false;
+ final elapsed = now.difference(before);
+ return !elapsed.isNegative &&
+ elapsed <= const Duration(minutes: 5) &&
+ DateUtils.isSameDay(now.toLocal(), before.toLocal());
+ }
+
+ @override
+ State<SuperTabMessageRow> createState() => _SuperTabMessageRowState();
+}
+
+class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
+ final _focus = FocusNode(debugLabel: 'Super Tab message actions');
+ bool _hovered = false, _focused = false;
+
+ @override
+ void dispose() {
+ _focus.dispose();
+ super.dispose();
+ }
+
+ Future<void> _copy() async {
+ await Clipboard.setData(ClipboardData(text: widget.message.text));
+ if (!mounted) return;
+ ScaffoldMessenger.maybeOf(context)?.showSnackBar(
+ const SnackBar(
+ content: Text('Message copied'),
+ duration: Duration(seconds: 2),
+ ),
+ );
+ }
+
+ String get _identityDetails {
+ final agent = widget.agent;
+ if (agent == null) {
+ return widget.message.fromAgent ? 'Agent' : widget.message.authorName;
+ }
+ return [
+ engineIdentity(agent.engine).label,
+ for (final key in ['model', 'effort', 'contextWindow'])
+ if (agent.configuration[key] case final Object value) '$value',
+ if (widget.machineName case final String machine) machine,
+ ].join(' · ');
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final message = widget.message;
+ final active = _hovered || _focused;
+ final authorStyle = DesktopChrome.text(medium: true)
+ .copyWith(fontWeight: FontWeight.w600);
+ return Padding(
+ padding: EdgeInsets.only(top: widget.grouped ? 0 : 12),
+ child: MouseRegion(
+ onEnter: (_) => setState(() => _hovered = true),
+ onExit: (_) => setState(() => _hovered = false),
+ child: Focus(
+ focusNode: _focus,
+ onFocusChange: (focused) => setState(() => _focused = focused),
+ onKeyEvent: (_, event) {
+ if (event is! KeyDownEvent) return KeyEventResult.ignored;
+ final keys = HardwareKeyboard.instance;
+ if (event.logicalKey == LogicalKeyboardKey.escape) {
+ widget.onReturnToComposer();
+ return KeyEventResult.handled;
+ }
+ if (!_focus.hasPrimaryFocus) return KeyEventResult.ignored;
+ if (event.logicalKey == LogicalKeyboardKey.keyR &&
+ !keys.isMetaPressed &&
+ !keys.isControlPressed &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed &&
+ widget.onReply != null) {
+ widget.onReply!();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey == LogicalKeyboardKey.keyC &&
+ (keys.isMetaPressed || keys.isControlPressed) &&
+ !keys.isAltPressed) {
+ _copy();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: Semantics(
+ container: true,
+ label: widget.grouped ? widget.author : null,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: active ? grid.AppSurface.hoverFill : Colors.transparent,
+ border: Border.all(
+ color: _focus.hasPrimaryFocus
+ ? DesktopChrome.focusRing
+ : Colors.transparent,
+ ),
+ ),
+ child: Stack(
+ children: [
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 6, 20, 6),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SizedBox(
+ width: 28,
+ child: widget.grouped
+ ? null
+ : ExcludeSemantics(
+ child: Tooltip(
+ message: _identityDetails,
+ child: message.fromAgent
+ ? EngineMark(
+ engine: widget.agent?.engine,
+ displayName: message.authorName,
+ size: 28,
+ )
+ : AccountAvatar(
+ initial: accountInitial(
+ message.authorName,
+ null,
+ ),
+ diameter: 28,
+ accent: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (!widget.grouped) ...[
+ Padding(
+ padding: const EdgeInsets.only(right: 64),
+ child: Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ crossAxisAlignment:
+ WrapCrossAlignment.center,
+ children: [
+ Text(widget.author, style: authorStyle),
+ if (message.fromAgent)
+ Tooltip(
+ message: _identityDetails,
+ child: Text(
+ widget.agent == null
+ ? 'Agent'
+ : engineIdentity(
+ widget.agent!.engine,
+ ).label,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ if (message.createdAt case final time?)
+ Tooltip(
+ message: MaterialLocalizations.of(
+ context,
+ ).formatFullDate(time.toLocal()),
+ child: Text(
+ TimeOfDay.fromDateTime(
+ time.toLocal(),
+ ).format(context),
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ ],
+ ),
+ ),
+ const SizedBox(height: 4),
+ ],
+ if (message.replyTo != null)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 8),
+ child: SuperTabReplyPreview(
+ author:
+ widget.reply?.authorName ??
+ 'Earlier message',
+ text:
+ widget.reply?.text ??
+ 'The original message isn’t loaded.',
+ ),
+ ),
+ if (message.terminalNote case final note?)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 6),
+ child: Text(
+ note,
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ SuperTabMessageText(message.text),
+ ...widget.receipts,
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ Positioned(
+ top: 0,
+ right: 12,
+ child: Opacity(
+ opacity: active ? 1 : 0,
+ alwaysIncludeSemantics: true,
+ child: Material(
+ color: DesktopChrome.surface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ side: BorderSide(color: DesktopChrome.rim),
+ ),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (widget.onReply != null)
+ AppIconButton(
+ icon: AppIcons.reply,
+ tooltip: 'Reply',
+ onPressed: widget.onReply,
+ ),
+ AppIconButton(
+ icon: AppIcons.copy,
+ tooltip: 'Copy message',
+ onPressed: _copy,
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class SuperTabReplyPreview extends StatelessWidget {
+ const SuperTabReplyPreview({
+ super.key,
+ required this.author,
+ required this.text,
+ });
+ final String author, text;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ padding: const EdgeInsets.only(left: 10),
+ decoration: BoxDecoration(
+ border: Border(left: BorderSide(color: DesktopChrome.muted, width: 2)),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ author,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: 2),
+ Text(
+ text.replaceAll(RegExp(r'\s+'), ' '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dart
new file mode 100644
index 000000000..32b6ff407
--- /dev/null
+++ b/desktop/lib/super_tabs/message_text.dart
@@ -0,0 +1,86 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';
+
+import '../core/open_in_browser.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+
+/// Shared content is selectable, never executable. Markdown images are labels,
+/// not automatic network requests or reads from a collaborator's local disk.
+class SuperTabMessageText extends StatelessWidget {
+ const SuperTabMessageText(this.text, {super.key});
+ final String text;
+
+ static Uri? webLink(String? href) {
+ final uri = href == null ? null : Uri.tryParse(href);
+ return uri != null &&
+ (uri.scheme == 'https' || uri.scheme == 'http') &&
+ uri.host.isNotEmpty
+ ? uri
+ : null;
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final body = DesktopChrome.text();
+ final heading = body.copyWith(fontWeight: FontWeight.w600);
+ return MarkdownBody(
+ data: text,
+ selectable: true,
+ softLineBreak: true,
+ styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(
+ p: body,
+ a: TextStyle(
+ color: DesktopChrome.accent,
+ decoration: TextDecoration.underline,
+ ),
+ h1: heading.copyWith(fontSize: 17),
+ h2: heading.copyWith(fontSize: 16),
+ h3: heading,
+ h4: heading,
+ h5: heading,
+ h6: heading,
+ strong: const TextStyle(fontWeight: FontWeight.w600),
+ code: grid.AppType.mono(
+ color: DesktopChrome.foreground,
+ height: 1.5,
+ ).copyWith(backgroundColor: DesktopChrome.field),
+ blockSpacing: 8,
+ listIndent: 20,
+ listBullet: body,
+ blockquote: body.copyWith(color: DesktopChrome.muted),
+ blockquotePadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 4,
+ ),
+ blockquoteDecoration: BoxDecoration(
+ border: Border(left: BorderSide(color: DesktopChrome.rim, width: 2)),
+ ),
+ codeblockPadding: const EdgeInsets.all(12),
+ codeblockDecoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),
+ ),
+ tableHead: heading,
+ tableBody: body,
+ tableBorder: TableBorder.all(color: DesktopChrome.rim),
+ tableCellsPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ vertical: 8,
+ ),
+ horizontalRuleDecoration: BoxDecoration(
+ border: Border(top: BorderSide(color: DesktopChrome.rim)),
+ ),
+ ),
+ onTapLink: (_, href, _) {
+ final uri = webLink(href);
+ if (uri != null) openInBrowser(uri);
+ },
+ imageBuilder: (uri, title, alt) => Text(
+ alt?.isNotEmpty == true ? 'Image: $alt' : 'Image',
+ style: DesktopChrome.metadata(),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
new file mode 100644
index 000000000..d9da4e3b1
--- /dev/null
+++ b/desktop/lib/super_tabs/model.dart
@@ -0,0 +1,134 @@
+/// Backend records are independent of the desktop's visible panes and tab layout.
+Map<String, dynamic> superTabMap(Object? value) => value is Map
+ ? Map<String, dynamic>.from(value)
+ : throw const FormatException('Invalid Super Tab response.');
+
+String _text(Map<String, dynamic> value, String key) => value[key] is String
+ ? value[key] as String
+ : throw FormatException('Missing Super Tab $key.');
+
+List<T> _list<T>(Object? value, T Function(Map<String, dynamic>) read) =>
+ value is List
+ ? List.unmodifiable(value.map((row) => read(superTabMap(row))))
+ : throw const FormatException('Invalid Super Tab list.');
+
+class SuperTabPerson {
+ SuperTabPerson.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ email = _text(row, 'email'),
+ role = _text(row, 'role');
+ final String id, email, role;
+ bool get canWrite => role == 'owner' || role == 'collaborator';
+}
+
+class SuperTabAgent {
+ SuperTabAgent.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ name = _text(row, 'name'),
+ machineId = _text(row, 'machineId'),
+ harnessId = _text(row, 'harnessId'),
+ contributorId = _text(row, 'contributorId'),
+ configuration = Map.unmodifiable(superTabMap(row['configuration']));
+ final String id, name, machineId, harnessId, contributorId;
+ final Map<String, dynamic> configuration;
+ String get engine => configuration['engine'] as String? ?? '';
+}
+
+class SuperTabConversation {
+ SuperTabConversation.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ title = _text(row, 'title'),
+ leadId = row['leadId'] as String?,
+ agentIds = List.unmodifiable((row['agentIds'] as List).cast<String>()),
+ archived = row['archived'] == true,
+ checks = _list(
+ row['checks'] ?? const [],
+ (check) => Map<String, dynamic>.unmodifiable(check),
+ ),
+ brief = _text(row, 'brief'),
+ lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,
+ assignment = row['assignment'] == null
+ ? null
+ : Map.unmodifiable(superTabMap(row['assignment']));
+ final String id, title, brief;
+ final String? leadId;
+ final List<String> agentIds;
+ final bool archived;
+ final List<Map<String, dynamic>> checks;
+ final int lastMessageSequence;
+ final Map<String, dynamic>? assignment;
+}
+
+class SuperTabSnapshot {
+ SuperTabSnapshot.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ name = _text(row, 'name'),
+ ownerId = _text(row, 'ownerId'),
+ paused = row['paused'] == true,
+ people = _list(row['people'], SuperTabPerson.fromJson),
+ agents = _list(row['agents'], SuperTabAgent.fromJson),
+ conversations = _list(
+ row['conversations'],
+ SuperTabConversation.fromJson,
+ ),
+ invitations = _list(
+ row['invitations'],
+ (row) => Map<String, dynamic>.unmodifiable(row),
+ ) {
+ if (row['version'] != 1) {
+ throw const FormatException('Update Harness to open this Super Tab.');
+ }
+ }
+ final String id, name, ownerId;
+ final bool paused;
+ final List<SuperTabPerson> people;
+ final List<SuperTabAgent> agents;
+ final List<SuperTabConversation> conversations;
+ final List<Map<String, dynamic>> invitations;
+ SuperTabConversation? conversation(String id) =>
+ conversations.where((c) => c.id == id).firstOrNull;
+ SuperTabAgent? agent(String id) =>
+ agents.where((a) => a.id == id).firstOrNull;
+}
+
+class SuperTabMessage {
+ SuperTabMessage.fromJson(Map<String, dynamic> row)
+ : id = _text(row, 'id'),
+ conversationId = _text(row, 'conversationId'),
+ text = _text(row, 'text'),
+ replyTo = row['replyTo'] as String?,
+ sequence = (row['sequence'] as num).toInt(),
+ author = Map.unmodifiable(superTabMap(row['author'])),
+ source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),
+ createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),
+ deliveries = _list(
+ row['deliveries'] ?? const [],
+ (d) => Map<String, dynamic>.unmodifiable(d),
+ );
+ final String id, conversationId, text;
+ final String? replyTo;
+ final int sequence;
+ final Map<String, dynamic> author;
+ final Map<String, dynamic> source;
+ final DateTime? createdAt;
+ final List<Map<String, dynamic>> deliveries;
+ String get authorName => author['name'] as String? ?? 'Unknown';
+ String get authorId => author['id'] as String? ?? '';
+ bool get fromAgent => author['kind'] == 'agent';
+ bool get fromTerminal => source['kind'] == 'native';
+ String? get terminalNote {
+ if (!fromTerminal) return null;
+ final phase = source['phase'];
+ if (phase == 'gap') return 'Terminal recording interrupted';
+ final operator =
+ superTabMap(source['operator'] ?? const {})['name'] as String?;
+ return phase == 'prompt' && operator != null
+ ? 'Terminal input · session opened by $operator'
+ : 'Terminal answer';
+ }
+
+ bool get queued => deliveries.any(
+ (d) => d['status'] == 'queued' || d['status'] == 'claimed',
+ );
+ bool get uncertain => deliveries.any((d) => d['status'] == 'uncertain');
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
new file mode 100644
index 000000000..d3b5f4f3f
--- /dev/null
+++ b/desktop/lib/super_tabs/view.dart
@@ -0,0 +1,1483 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
+import '../widgets/desktop_chrome.dart';
+import '../widgets/engine_identity.dart';
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'model.dart';
+import 'message_row.dart';
+import 'work_details.dart';
+
+/// The contents of one app tab. Its title stays in the app's existing tab bar.
+/// [terminal] is the existing native pane, with its own controls and input.
+class SuperTabView extends StatefulWidget {
+ const SuperTabView({
+ super.key,
+ required this.controller,
+ required this.onInvite,
+ required this.onAddAgent,
+ required this.onOpenTerminal,
+ required this.machineName,
+ this.terminal,
+ this.onCloseTerminal,
+ });
+ final SuperTabController controller;
+ final VoidCallback onInvite;
+ final ValueChanged<SuperTabConversation> onAddAgent;
+ final ValueChanged<SuperTabAgent> onOpenTerminal;
+ final String Function(String machineId) machineName;
+ final Widget? terminal;
+ final VoidCallback? onCloseTerminal;
+
+ @override
+ State<SuperTabView> createState() => _SuperTabViewState();
+}
+
+class _SuperTabViewState extends State<SuperTabView> {
+ final _composer = TextEditingController();
+ final _focus = FocusNode(debugLabel: 'Super Tab message');
+ final _scroll = <String, ScrollController>{};
+ final _latest = <String, int>{};
+ final _following = <String, bool>{};
+ final _newAfter = <String, int>{};
+ final _replies = <String, SuperTabMessage>{};
+ String? _selected;
+ int _scrollRequest = 0;
+ bool _jumpingToEnd = false;
+ bool _sidebarOpen = false;
+ final _loadingOlder = <String>{};
+ int _mentionIndex = 0;
+ String? _dismissedMention;
+ SuperTabController get c => widget.controller;
+
+ @override
+ void initState() {
+ super.initState();
+ c.addListener(_changed);
+ _changed();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.controller != c) {
+ oldWidget.controller.removeListener(_changed);
+ c.addListener(_changed);
+ for (final scroll in _scroll.values) {
+ scroll.dispose();
+ }
+ _scroll.clear();
+ _latest.clear();
+ _following.clear();
+ _newAfter.clear();
+ _replies.clear();
+ _selected = null;
+ _changed();
+ }
+ }
+
+ void _changed() {
+ if (!mounted) return;
+ if (c.accessRevoked) {
+ _replies.clear();
+ _newAfter.clear();
+ }
+ final id = c.selectedId;
+ final firstView = !_scroll.containsKey(id);
+ final scroll = _scroll.putIfAbsent(id, ScrollController.new);
+ final atEnd = scroll.hasClients
+ ? scroll.position.extentAfter < 40
+ : (_following[id] ?? true);
+ final previous = _latest[id] ?? 0;
+ final latest = c.messages(id).lastOrNull?.sequence ?? 0;
+ final grew = latest > previous && !_loadingOlder.contains(id);
+ _latest[id] = latest;
+ if (grew && !atEnd) _newAfter.putIfAbsent(id, () => previous);
+ final draft = c.accessRevoked ? '' : c.draft(id);
+ if (_selected != id) {
+ _scrollRequest++;
+ _jumpingToEnd = false;
+ }
+ if (_selected != id || _composer.text != draft) {
+ _composer.value = TextEditingValue(
+ text: draft,
+ selection: TextSelection.collapsed(offset: draft.length),
+ );
+ }
+ _selected = id;
+ setState(() {});
+ if (firstView || (grew && atEnd)) {
+ _followEnd(id);
+ }
+ }
+
+ void _followEnd(String id) {
+ final request = ++_scrollRequest;
+ _jumpingToEnd = true;
+ void advance(int attempt) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ final scroll = _scroll[id];
+ if (!mounted ||
+ request != _scrollRequest ||
+ c.selectedId != id ||
+ scroll == null ||
+ !scroll.hasClients) {
+ return;
+ }
+ scroll.jumpTo(scroll.position.maxScrollExtent);
+ // A lazy list refines its extent after laying out variable-height code
+ // and replies. A single jump can stop above the actual last message.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted ||
+ request != _scrollRequest ||
+ c.selectedId != id ||
+ !scroll.hasClients) {
+ return;
+ }
+ if (scroll.position.extentAfter > 1 && attempt < 12) {
+ advance(attempt + 1);
+ } else {
+ _jumpingToEnd = false;
+ if (scroll.position.extentAfter < 40) {
+ _readToEnd(id, _latest[id] ?? 0);
+ }
+ }
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ }
+
+ advance(0);
+ }
+
+ void _readToEnd(String id, int sequence) {
+ _following[id] = true;
+ if (_newAfter.containsKey(id)) setState(() => _newAfter.remove(id));
+ c.markRead(id, through: sequence);
+ }
+
+ void _jumpToLatest() {
+ _followEnd(c.selectedId);
+ _focus.requestFocus();
+ }
+
+ @override
+ void dispose() {
+ c.removeListener(_changed);
+ _composer.dispose();
+ _focus.dispose();
+ for (final scroll in _scroll.values) {
+ scroll.dispose();
+ }
+ super.dispose();
+ }
+
+ Future<void> _send() async {
+ final mentions = _mentionChoices;
+ if (mentions.isNotEmpty) {
+ _chooseMention(mentions[_mentionIndex.clamp(0, mentions.length - 1)]);
+ return;
+ }
+ if (!c.canWrite ||
+ c.selected == null ||
+ c.selected!.archived ||
+ c.saving ||
+ c.hasPendingAction ||
+ _composer.text.trim().isEmpty) {
+ return;
+ }
+ final id = c.selectedId;
+ final result = await c.send(replyTo: _replies[id]?.id);
+ if (mounted && result != null) setState(() => _replies.remove(id));
+ }
+
+ void _closeSidebar() {
+ setState(() => _sidebarOpen = false);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && !_sidebarOpen) _focus.requestFocus();
+ });
+ }
+
+ ({int start, int end, String query})? get _mentionAtCursor {
+ final value = _composer.value;
+ if (!value.selection.isValid ||
+ !value.selection.isCollapsed ||
+ (value.composing.isValid && !value.composing.isCollapsed)) {
+ return null;
+ }
+ final end = value.selection.baseOffset;
+ final prefix = value.text.substring(0, end);
+ final match = RegExp(r'(?:^|\s)@([^@\n]*)$').firstMatch(prefix);
+ if (match == null || prefix == _dismissedMention) return null;
+ final start = prefix.lastIndexOf('@');
+ final query = match.group(1)!;
+ if (c.mentions(c.selectedId).values.contains('@${query.trimRight()}')) {
+ return null;
+ }
+ return (start: start, end: end, query: query.toLowerCase());
+ }
+
+ List<SuperTabAgent> get _mentionChoices {
+ final mention = _mentionAtCursor;
+ if (mention == null) return const [];
+ return c.snapshot?.agents
+ .where(
+ (agent) =>
+ c.selected?.agentIds.contains(agent.id) == true &&
+ '${agent.name} ${agent.engine}'.toLowerCase().contains(
+ mention.query,
+ ),
+ )
+ .take(6)
+ .toList() ??
+ const [];
+ }
+
+ void _chooseMention(SuperTabAgent agent) {
+ final at = _mentionAtCursor;
+ if (at == null) return;
+ final token = '@${agent.name}';
+ final text = _composer.text.replaceRange(at.start, at.end, '$token ');
+ c.setDraft(c.selectedId, text);
+ c.mention(c.selectedId, agent.id, token);
+ _composer.value = TextEditingValue(
+ text: text,
+ selection: TextSelection.collapsed(offset: at.start + token.length + 1),
+ );
+ setState(() => _mentionIndex = 0);
+ _focus.requestFocus();
+ }
+
+ Future<void> _newGroup() async {
+ final c = this.c;
+ var name = '';
+ String? error;
+ bool busy = false;
+ final id = await showAppDialog<String>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: StatefulBuilder(
+ builder: (context, update) {
+ Future<void> create() async {
+ if (busy || name.trim().isEmpty) return;
+ update(() {
+ busy = true;
+ error = null;
+ });
+ final answer = c.hasPendingAction
+ ? await c.retry()
+ : await c.command({
+ 'type': 'conversation.create',
+ 'title': name.trim(),
+ 'brief': '',
+ 'checks': <dynamic>[],
+ });
+ if (!context.mounted) return;
+ if (answer?['conversationId'] case final String id) {
+ Navigator.of(context).pop(id);
+ } else {
+ update(() {
+ busy = false;
+ error = c.operationError ?? 'Could not create the group.';
+ });
+ }
+ }
+
+ return PopScope(
+ canPop: !busy,
+ child: AlertDialog(
+ title: const Text('New group'),
+ content: SizedBox(
+ width: 340,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ TextField(
+ onChanged: (value) => update(() => name = value),
+ autofocus: true,
+ enabled: !busy && !c.hasPendingAction,
+ maxLength: 160,
+ decoration: const InputDecoration(
+ labelText: 'Name',
+ hintText: 'Offline editing',
+ counterText: '',
+ ),
+ onSubmitted: (_) => unawaited(create()),
+ ),
+ const SizedBox(height: 12),
+ Text(
+ 'A shared conversation with your lead.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (error != null)
+ Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Text(error!, style: DesktopChrome.control()),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.of(context).pop(),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: busy || name.trim().isEmpty
+ ? null
+ : () => unawaited(create()),
+ child: Text(
+ busy
+ ? 'Creating…'
+ : c.hasPendingAction
+ ? 'Retry'
+ : 'Create',
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ ),
+ ),
+ );
+ if (!mounted || widget.controller != c || id == null) return;
+ c.select(id);
+ _closeSidebar();
+ }
+
+ Future<void> _earlier() async {
+ final id = c.selectedId, scroll = _scroll[c.selectedId];
+ if (scroll == null || !scroll.hasClients || !_loadingOlder.add(id)) return;
+ final offset = scroll.offset, extent = scroll.position.maxScrollExtent;
+ try {
+ await c.loadMessages(id, older: true);
+ await WidgetsBinding.instance.endOfFrame;
+ if (mounted && c.selectedId == id && scroll.hasClients) {
+ scroll.jumpTo(
+ (offset + scroll.position.maxScrollExtent - extent).clamp(
+ 0.0,
+ scroll.position.maxScrollExtent,
+ ),
+ );
+ }
+ } finally {
+ _loadingOlder.remove(id);
+ }
+ }
+
+ Future<void> _groupAction(String action, SuperTabConversation group) async {
+ final c = this.c;
+ if (action == 'archived') {
+ await _archived();
+ return;
+ }
+ if (action == 'work') {
+ await showSuperTabWork(context, c, group.id);
+ return;
+ }
+ if (action == 'archive') {
+ await c.command({
+ 'type': 'conversation.archive',
+ 'conversationId': group.id,
+ 'archived': !group.archived,
+ });
+ return;
+ }
+ var title = group.title, busy = false;
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: StatefulBuilder(
+ builder: (context, update) => AlertDialog(
+ title: const Text('Rename conversation'),
+ content: TextFormField(
+ initialValue: title,
+ autofocus: true,
+ maxLength: 160,
+ onChanged: (value) => update(() => title = value),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: busy || title.trim().isEmpty
+ ? null
+ : () async {
+ update(() => busy = true);
+ final result = await c.command({
+ 'type': 'conversation.rename',
+ 'conversationId': group.id,
+ 'title': title.trim(),
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ },
+ child: const Text('Save'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _participants(SuperTabConversation group) async {
+ final c = this.c;
+ var query = '';
+ var handedOff = false;
+ final addition = await showAppDialog<SuperTabConversation>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ requireWrite: false,
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final state = c.snapshot;
+ if (state == null) {
+ return AlertDialog(
+ content: const Text('This conversation is unavailable.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.of(context).pop(),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ }
+ final currentGroup = state.conversation(group.id) ?? group;
+ final agents = state.agents
+ .where(
+ (a) =>
+ currentGroup.agentIds.contains(a.id) &&
+ '${a.name} ${a.engine} ${widget.machineName(a.machineId)}'
+ .toLowerCase()
+ .contains(query),
+ )
+ .toList();
+ final people = state.people
+ .where((p) => p.email.toLowerCase().contains(query))
+ .toList();
+ return Dialog(
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ shape: const RoundedRectangleBorder(),
+ child: DesktopDialogSurface(
+ child: SizedBox(
+ width: 400,
+ height: 460,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Participants',
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ AppIconButton(
+ icon: AppIcons.close,
+ tooltip: 'Close participants',
+ onPressed: () => Navigator.of(context).pop(),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ TextField(
+ autofocus: true,
+ decoration: const InputDecoration(
+ hintText: 'Find a person or agent',
+ ),
+ onChanged: (value) => update(
+ () => query = value.trim().toLowerCase(),
+ ),
+ ),
+ const SizedBox(height: 12),
+ Expanded(
+ child: ListView(
+ children: [
+ for (final agent in agents)
+ _participantAgent(agent, () {
+ Navigator.of(context).pop();
+ handedOff = true;
+ widget.onOpenTerminal(agent);
+ }),
+ for (final person in people)
+ ListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(
+ person.email,
+ style: DesktopChrome.control(),
+ ),
+ subtitle: Text(
+ person.role == 'owner'
+ ? 'Owner'
+ : person.role == 'viewer'
+ ? 'Viewer'
+ : 'Collaborator',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ if (agents.isEmpty && people.isEmpty)
+ const Padding(
+ padding: EdgeInsets.symmetric(vertical: 24),
+ child: Text('No matches.'),
+ ),
+ ],
+ ),
+ ),
+ if (c.canWrite)
+ Align(
+ alignment: Alignment.centerRight,
+ child: TextButton(
+ onPressed: () {
+ Navigator.of(context).pop(currentGroup);
+ handedOff = true;
+ },
+ child: const Text('Add agent'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ if (addition != null) {
+ // The workspace enables its picker when the modal route is gone. Wait
+ // for that dependency update before handing focus to the next surface.
+ await WidgetsBinding.instance.endOfFrame;
+ if (mounted &&
+ identical(c, this.c) &&
+ c.canWrite &&
+ c.snapshot?.conversation(addition.id) != null) {
+ widget.onAddAgent(addition);
+ }
+ }
+ if (mounted && !handedOff) _focus.requestFocus();
+ }
+
+ Widget _participantAgent(SuperTabAgent agent, VoidCallback open) => Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final identity = Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(agent.name, style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 4),
+ Text(
+ '${engineIdentity(agent.engine).label} · ${widget.machineName(agent.machineId)}',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ );
+ final action = TextButton(
+ onPressed: open,
+ child: const Text('Open terminal'),
+ );
+ if (MediaQuery.textScalerOf(context).scale(13) > 18 ||
+ constraints.maxWidth < 320) {
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [identity, const SizedBox(height: 8), action],
+ );
+ }
+ return Row(
+ children: [
+ Expanded(child: identity),
+ const SizedBox(width: 12),
+ action,
+ ],
+ );
+ },
+ ),
+ );
+
+ Future<void> _archived() async {
+ final c = this.c;
+ var query = '';
+ final selected = await showAppDialog<String>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ requireWrite: false,
+ child: StatefulBuilder(
+ builder: (context, update) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final groups =
+ c.snapshot?.conversations
+ .where(
+ (group) =>
+ group.archived &&
+ group.title.toLowerCase().contains(query),
+ )
+ .toList() ??
+ <SuperTabConversation>[];
+ return AlertDialog(
+ title: const Text('Archived conversations'),
+ content: SizedBox(
+ width: 400,
+ height: 320,
+ child: Column(
+ children: [
+ TextField(
+ autofocus: true,
+ decoration: const InputDecoration(
+ hintText: 'Find a conversation',
+ ),
+ onChanged: (value) =>
+ update(() => query = value.trim().toLowerCase()),
+ ),
+ const SizedBox(height: 12),
+ Expanded(
+ child: groups.isEmpty
+ ? const Center(
+ child: Text('No archived conversations.'),
+ )
+ : ListView(
+ children: [
+ for (final group in groups)
+ ListTile(
+ title: Text(
+ group.title,
+ style: DesktopChrome.control(),
+ ),
+ onTap: () =>
+ Navigator.pop(context, group.id),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ ),
+ );
+ if (!mounted || widget.controller != c || selected == null) return;
+ c.select(selected);
+ }
+
+ Widget _sidebar() => Material(
+ color: DesktopChrome.surface,
+ child: Column(
+ children: [
+ Expanded(
+ child: ListView(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 12),
+ children: [
+ for (final group
+ in c.snapshot?.conversations ?? <SuperTabConversation>[])
+ if (!group.archived)
+ Padding(
+ padding: const EdgeInsets.only(bottom: 2),
+ child: Semantics(
+ selected: c.selectedId == group.id,
+ child: ListTile(
+ key: ValueKey('super-group-${group.id}'),
+ dense: true,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.rowRadius,
+ ),
+ ),
+ selected: c.selectedId == group.id,
+ selectedTileColor: DesktopChrome.activeSelection,
+ title: Text(
+ group.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(
+ medium: c.unread(group),
+ color: c.selectedId == group.id
+ ? DesktopChrome.onSelection
+ : null,
+ ),
+ ),
+ trailing: c.unread(group)
+ ? Semantics(
+ label: 'Unread messages',
+ child: Container(
+ width: 6,
+ height: 6,
+ decoration: BoxDecoration(
+ shape: BoxShape.circle,
+ color: c.selectedId == group.id
+ ? DesktopChrome.onSelection
+ : DesktopChrome.accent,
+ ),
+ ),
+ )
+ : null,
+ onTap: () {
+ c.select(group.id);
+ _closeSidebar();
+ },
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(8, 8, 8, 12),
+ child: Wrap(
+ spacing: DesktopChrome.controlGap,
+ runSpacing: DesktopChrome.controlGap,
+ children: [
+ TextButton(
+ onPressed:
+ c.canWrite &&
+ !c.hasPendingAction &&
+ c.snapshot?.paused != true
+ ? () => unawaited(_newGroup())
+ : null,
+ child: const Text('New group'),
+ ),
+ TextButton(
+ onPressed: c.snapshot != null
+ ? () {
+ _closeSidebar();
+ widget.onInvite();
+ }
+ : null,
+ child: Text(c.isOwner ? 'Invite' : 'People'),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+
+ Widget _header(SuperTabConversation? group, bool narrow) => Container(
+ constraints: const BoxConstraints(minHeight: 52),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
+ decoration: BoxDecoration(
+ border: Border(bottom: BorderSide(color: DesktopChrome.rim)),
+ ),
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final people = c.snapshot?.people.length ?? 0;
+ final agents = group?.agentIds.length ?? 0;
+ final participants =
+ '$agents ${agents == 1 ? 'agent' : 'agents'} · $people ${people == 1 ? 'person' : 'people'}';
+ final compact =
+ constraints.maxWidth < MediaQuery.textScalerOf(context).scale(520);
+ return Row(
+ children: [
+ if (narrow)
+ AppIconButton(
+ icon: AppIcons.columns2,
+ tooltip: 'Conversations',
+ onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),
+ ),
+ Expanded(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ group?.title ?? 'Loading conversation…',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(medium: true),
+ ),
+ if (group?.assignment?['status'] == 'needs_human')
+ TextButton.icon(
+ onPressed: () => showSuperTabWork(context, c, group!.id),
+ style: TextButton.styleFrom(
+ foregroundColor: grid.AppPalette.warn,
+ padding: const EdgeInsets.symmetric(
+ horizontal: 8,
+ vertical: 6,
+ ),
+ minimumSize: const Size(0, 32),
+ ),
+ icon: const Icon(
+ AppIcons.messageCircleQuestionMark,
+ size: 16,
+ ),
+ label: const Text(
+ 'Needs a human',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (group != null)
+ Tooltip(
+ message: participants,
+ child: TextButton(
+ onPressed: () => unawaited(_participants(group)),
+ child: compact
+ ? Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ const Icon(AppIcons.users, size: 18),
+ const SizedBox(width: 6),
+ Text(
+ '${agents + people}',
+ semanticsLabel: participants,
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ )
+ : Text(participants, style: DesktopChrome.metadata()),
+ ),
+ ),
+ if (group != null)
+ PopupMenuButton<String>(
+ tooltip: 'Conversation options',
+ icon: const Icon(AppIcons.ellipsis, size: 18),
+ onSelected: (action) => unawaited(_groupAction(action, group)),
+ itemBuilder: (_) => [
+ const PopupMenuItem(
+ value: 'work',
+ child: Text('Work details'),
+ ),
+ if (c.snapshot?.conversations.any(
+ (group) => group.archived,
+ ) ==
+ true)
+ const PopupMenuItem(
+ value: 'archived',
+ child: Text('Archived conversations'),
+ ),
+ if (c.canWrite && !c.hasPendingAction && !c.saving) ...[
+ const PopupMenuItem(value: 'rename', child: Text('Rename')),
+ if (group.id != 'lead')
+ PopupMenuItem(
+ value: 'archive',
+ enabled:
+ group.assignment == null ||
+ const [
+ 'done',
+ 'stopped',
+ ].contains(group.assignment!['status']),
+ child: Text(
+ group.archived ? 'Reopen conversation' : 'Archive',
+ ),
+ ),
+ ],
+ ],
+ ),
+ ],
+ );
+ },
+ ),
+ );
+
+ Future<void> _reviewDelivery(
+ SuperTabMessage message,
+ Map<String, dynamic> delivery,
+ ) async {
+ final c = this.c;
+ final agent = c.snapshot?.agent(delivery['agentId'] as String);
+ final resolution = await showAppDialog<String>(
+ context: context,
+ builder: (context) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) => !c.canWrite
+ ? AlertDialog(
+ content: const Text(
+ 'This delivery is no longer available to change.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ )
+ : AlertDialog(
+ title: DesktopDialogHeader(
+ title: 'Check delivery to ${agent?.name ?? 'agent'}',
+ padding: EdgeInsets.zero,
+ onClose: () => Navigator.pop(context),
+ ),
+ content: SizedBox(
+ width: 440,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (agent != null) ...[
+ TextButton(
+ onPressed: () => Navigator.pop(context, 'open'),
+ child: const Text('Open terminal'),
+ ),
+ const SizedBox(height: 16),
+ ],
+ const Text(
+ 'This instruction may already have reached the terminal. Inspect it before sending again.',
+ ),
+ const SizedBox(height: 16),
+ SelectableText(message.text),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ Wrap(
+ spacing: DesktopChrome.controlGap,
+ runSpacing: DesktopChrome.controlGap,
+ alignment: WrapAlignment.end,
+ children: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, 'cancel'),
+ child: const Text('Dismiss warning'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(context, 'received'),
+ child: const Text('Already received'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, 'resend'),
+ child: const Text('Send again'),
+ ),
+ ],
+ ),
+ ],
+ ),
+ ),
+ );
+ if (!mounted ||
+ widget.controller != c ||
+ resolution == null ||
+ !c.canWrite) {
+ return;
+ }
+ if (resolution == 'open') {
+ if (agent != null) {
+ c.select(message.conversationId);
+ widget.onOpenTerminal(agent);
+ }
+ return;
+ }
+ await c.command({
+ 'type': 'delivery.resolve',
+ 'deliveryId': delivery['id'],
+ 'resolution': resolution,
+ });
+ }
+
+ Widget _message(
+ SuperTabMessage message,
+ bool grouped,
+ Map<String, SuperTabMessage> byId,
+ ) {
+ final agent = message.fromAgent
+ ? c.snapshot?.agent(message.authorId)
+ : null;
+ return SuperTabMessageRow(
+ key: ValueKey('super-message-${message.id}'),
+ message: message,
+ author: message.authorId == c.accountId && !message.fromAgent
+ ? 'You'
+ : message.authorName,
+ agent: agent,
+ machineName: agent == null ? null : widget.machineName(agent.machineId),
+ grouped: grouped,
+ reply: byId[message.replyTo],
+ onReply: c.canWrite && c.selected?.archived == false
+ ? () {
+ setState(() => _replies[c.selectedId] = message);
+ _focus.requestFocus();
+ }
+ : null,
+ onReturnToComposer: _focus.requestFocus,
+ receipts: [
+ if (message.source['truncated'] == true ||
+ message.source['interrupted'] == true)
+ Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Text(
+ message.source['truncated'] == true
+ ? 'Excerpt · open the terminal for the full response'
+ : 'Response interrupted',
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ if (message.queued)
+ Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Text('Queued', style: DesktopChrome.metadata()),
+ ),
+ for (final delivery in message.deliveries.where(
+ (d) => d['status'] == 'uncertain',
+ ))
+ TextButton(
+ onPressed: c.canWrite && delivery['id'] is String
+ ? () => _reviewDelivery(message, delivery)
+ : null,
+ child: Text(
+ 'Check delivery to ${c.snapshot?.agent(delivery['agentId'] as String)?.name ?? 'agent'}',
+ ),
+ ),
+ ],
+ );
+ }
+
+ Widget _date(DateTime time) => Padding(
+ padding: const EdgeInsets.fromLTRB(20, 20, 20, 4),
+ child: Row(
+ children: [
+ Expanded(child: Divider(color: DesktopChrome.rim)),
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Text(
+ MaterialLocalizations.of(context).formatMediumDate(time.toLocal()),
+ style: DesktopChrome.metadata(),
+ ),
+ ),
+ Expanded(child: Divider(color: DesktopChrome.rim)),
+ ],
+ ),
+ );
+
+ Widget _conversation(bool narrow) {
+ final group = c.selected;
+ final messages = c.messages(c.selectedId);
+ final byId = {for (final message in messages) message.id: message};
+ final grouped = SuperTabMessageRow.consecutiveUpdates(messages);
+ final newAfter = _newAfter[c.selectedId];
+ final newCount = newAfter == null
+ ? 0
+ : messages.where((message) => message.sequence > newAfter).length;
+ final reply = _replies[c.selectedId];
+ final mentions = _mentionChoices;
+ return Column(
+ children: [
+ _header(group, narrow),
+ if (c.error != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
+ child: Row(
+ children: [
+ Expanded(child: Text(c.error!, style: DesktopChrome.control())),
+ if (!c.accessRevoked)
+ TextButton(
+ onPressed: () => unawaited(c.refresh()),
+ child: const Text('Retry'),
+ ),
+ ],
+ ),
+ ),
+ Expanded(
+ child: c.loading
+ ? const Center(child: CircularProgressIndicator())
+ : messages.isEmpty
+ ? Center(
+ child: Text(
+ c.accessRevoked
+ ? 'Conversation unavailable.'
+ : group == null
+ ? 'Loading conversation…'
+ : group.id == 'lead'
+ ? 'Discuss the plan with your lead.'
+ : 'Start the conversation.',
+ style: DesktopChrome.text(color: DesktopChrome.muted),
+ ),
+ )
+ : Stack(
+ children: [
+ NotificationListener<ScrollNotification>(
+ onNotification: (event) {
+ if (event.depth != 0) return false;
+ if (event is ScrollStartNotification &&
+ event.dragDetails != null) {
+ _scrollRequest++;
+ _jumpingToEnd = false;
+ }
+ if (_jumpingToEnd) return false;
+ final id = c.selectedId;
+ final atEnd = event.metrics.extentAfter < 40;
+ _following[id] = atEnd;
+ if (atEnd) {
+ final sequence = messages.lastOrNull?.sequence ?? 0;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && c.selectedId == id) {
+ _readToEnd(id, sequence);
+ }
+ });
+ }
+ return false;
+ },
+ child: ListView.builder(
+ controller: _scroll[c.selectedId],
+ key: PageStorageKey(
+ 'super-messages-${c.tabId}-${c.selectedId}',
+ ),
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ itemCount: messages.length + 1,
+ itemBuilder: (context, index) {
+ if (index == 0) {
+ return c.hasOlder(c.selectedId)
+ ? Align(
+ child: TextButton(
+ onPressed: () => unawaited(_earlier()),
+ child: const Text('Earlier messages'),
+ ),
+ )
+ : const SizedBox.shrink();
+ }
+ final message = messages[index - 1];
+ final previous = index > 1
+ ? messages[index - 2]
+ : null;
+ final time = message.createdAt;
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (time != null &&
+ !DateUtils.isSameDay(
+ time.toLocal(),
+ previous?.createdAt?.toLocal(),
+ ))
+ _date(time),
+ _message(
+ message,
+ grouped.contains(message.id),
+ byId,
+ ),
+ ],
+ );
+ },
+ ),
+ ),
+ if (newCount > 0)
+ Positioned(
+ bottom: 12,
+ left: 20,
+ right: 20,
+ child: Center(
+ child: FilledButton.icon(
+ key: const ValueKey('super-new-messages'),
+ onPressed: _jumpToLatest,
+ icon: const Icon(AppIcons.chevronDown, size: 16),
+ label: Text(
+ '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ if (c.operationError != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 24),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ c.operationError!,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving ? null : () => unawaited(c.retry()),
+ child: const Text('Retry'),
+ ),
+ ],
+ ),
+ ),
+ if (reply != null)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 8, 16, 0),
+ child: Row(
+ children: [
+ Expanded(
+ child: SuperTabReplyPreview(
+ author: 'Replying to ${reply.authorName}',
+ text: reply.text,
+ ),
+ ),
+ AppIconButton(
+ icon: AppIcons.close,
+ tooltip: 'Cancel reply',
+ onPressed: () =>
+ setState(() => _replies.remove(c.selectedId)),
+ ),
+ ],
+ ),
+ ),
+ if (mentions.isNotEmpty)
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 20),
+ child: Material(
+ color: DesktopChrome.surface,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (var i = 0; i < mentions.length; i++)
+ ListTile(
+ dense: true,
+ selected:
+ i == _mentionIndex.clamp(0, mentions.length - 1),
+ title: Text(mentions[i].name),
+ subtitle: Text(
+ '${mentions[i].engine} · ${widget.machineName(mentions[i].machineId)}',
+ ),
+ onTap: () => _chooseMention(mentions[i]),
+ ),
+ ],
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 20),
+ child: Focus(
+ onKeyEvent: (node, event) {
+ final keys = HardwareKeyboard.instance;
+ final composing = _composer.value.composing;
+ if (_focus.hasFocus &&
+ event is KeyDownEvent &&
+ mentions.isNotEmpty &&
+ !keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isAltPressed &&
+ !keys.isShiftPressed &&
+ !(composing.isValid && !composing.isCollapsed)) {
+ final key = event.logicalKey;
+ if (key == LogicalKeyboardKey.arrowDown ||
+ key == LogicalKeyboardKey.arrowUp) {
+ setState(
+ () => _mentionIndex =
+ (_mentionIndex +
+ (key == LogicalKeyboardKey.arrowDown ? 1 : -1)) %
+ mentions.length,
+ );
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.tab ||
+ key == LogicalKeyboardKey.enter) {
+ _chooseMention(
+ mentions[_mentionIndex.clamp(0, mentions.length - 1)],
+ );
+ return KeyEventResult.handled;
+ }
+ if (key == LogicalKeyboardKey.escape) {
+ setState(
+ () => _dismissedMention = _composer.text.substring(
+ 0,
+ _composer.selection.baseOffset,
+ ),
+ );
+ return KeyEventResult.handled;
+ }
+ }
+ if (_focus.hasFocus &&
+ event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.enter &&
+ !keys.isShiftPressed &&
+ !keys.isControlPressed &&
+ !keys.isMetaPressed &&
+ !keys.isAltPressed &&
+ !(composing.isValid && !composing.isCollapsed)) {
+ unawaited(_send());
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ color: DesktopChrome.field,
+ borderRadius: BorderRadius.circular(
+ DesktopChrome.controlRadius,
+ ),
+ border: Border.all(color: DesktopChrome.rim),
+ ),
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(14, 8, 8, 8),
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.end,
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('super-message-composer'),
+ controller: _composer,
+ focusNode: _focus,
+ autofocus: widget.terminal == null,
+ enabled: c.canWrite && group != null && !group.archived,
+ minLines: 1,
+ maxLines: MediaQuery.sizeOf(context).height < 600
+ ? 3
+ : 8,
+ maxLength: 32000,
+ keyboardType: TextInputType.multiline,
+ style: DesktopChrome.text(),
+ decoration: InputDecoration(
+ hintText: group == null
+ ? 'Loading conversation…'
+ : c.canWrite
+ ? 'Message ${group.title}'
+ : 'Read-only conversation',
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ filled: false,
+ counterText: '',
+ ),
+ onChanged: (text) {
+ c.setDraft(c.selectedId, text);
+ setState(() {
+ _mentionIndex = 0;
+ _dismissedMention = null;
+ });
+ },
+ ),
+ ),
+ ValueListenableBuilder(
+ valueListenable: _composer,
+ builder: (context, value, _) => AppIconButton(
+ icon: AppIcons.arrowUp,
+ tooltip: 'Send message',
+ color: DesktopChrome.accent,
+ onPressed:
+ c.canWrite &&
+ group != null &&
+ !group.archived &&
+ !c.saving &&
+ !c.hasPendingAction &&
+ value.text.trim().isNotEmpty
+ ? () => unawaited(_send())
+ : null,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) => LayoutBuilder(
+ builder: (context, constraints) {
+ grid.AppTheme.watch(context);
+ final terminal = widget.terminal;
+ final narrow =
+ constraints.maxWidth <
+ MediaQuery.textScalerOf(context).scale(terminal == null ? 640 : 980);
+ if (narrow && terminal != null) {
+ return Column(
+ children: [
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TextButton.icon(
+ onPressed: widget.onCloseTerminal,
+ icon: const Icon(AppIcons.arrowLeft, size: 16),
+ label: const Text('Back to conversation'),
+ ),
+ ),
+ Expanded(child: terminal),
+ ],
+ );
+ }
+ return Stack(
+ children: [
+ ExcludeFocus(
+ excluding: narrow && _sidebarOpen,
+ child: Row(
+ children: [
+ if (!narrow) ...[
+ SizedBox(width: 220, child: _sidebar()),
+ VerticalDivider(width: 1, color: DesktopChrome.rim),
+ ],
+ Expanded(child: _conversation(narrow)),
+ if (terminal != null) ...[
+ VerticalDivider(width: 1, color: DesktopChrome.rim),
+ Expanded(child: terminal),
+ ],
+ ],
+ ),
+ ),
+ if (narrow && _sidebarOpen)
+ Positioned.fill(
+ child: BlockSemantics(
+ child: FocusScope(
+ autofocus: true,
+ onKeyEvent: (_, event) {
+ if (event is KeyDownEvent &&
+ event.logicalKey == LogicalKeyboardKey.escape) {
+ _closeSidebar();
+ return KeyEventResult.handled;
+ }
+ return KeyEventResult.ignored;
+ },
+ child: GestureDetector(
+ onTap: _closeSidebar,
+ child: ColoredBox(
+ color: grid.AppDesktop.veil(Theme.of(context).brightness),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: SizedBox(
+ width: 240,
+ child: Material(
+ color: DesktopChrome.surface,
+ elevation: 8,
+ child: _sidebar(),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+ },
+ );
+}
diff --git a/desktop/lib/super_tabs/work_details.dart b/desktop/lib/super_tabs/work_details.dart
new file mode 100644
index 000000000..3e883295c
--- /dev/null
+++ b/desktop/lib/super_tabs/work_details.dart
@@ -0,0 +1,165 @@
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../widgets/desktop_chrome.dart';
+
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'message_text.dart';
+
+Future<void> showSuperTabWork(
+ BuildContext context,
+ SuperTabController c,
+ String groupId,
+) => showAppDialog<void>(
+ context: context,
+ builder: (context) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final group = c.snapshot?.conversation(groupId);
+ final assignment = group?.assignment;
+ return AlertDialog(
+ title: Text(group?.title ?? 'Work details'),
+ content: SizedBox(
+ width: 520,
+ child: SingleChildScrollView(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ if (group?.brief.isNotEmpty == true)
+ SuperTabMessageText(group!.brief)
+ else
+ const Text(
+ 'The lead hasn’t defined an assignment in this conversation yet.',
+ ),
+ if (assignment != null) ...[
+ const SizedBox(height: 16),
+ Text(
+ '${c.snapshot?.agent(assignment['agentId'] as String)?.name ?? 'Agent unavailable'} · ${(assignment['status'] as String).replaceAll('_', ' ')}',
+ ),
+ ],
+ for (final check
+ in group?.checks ?? <Map<String, dynamic>>[]) ...[
+ const SizedBox(height: 16),
+ Text(
+ check['description'] as String,
+ style: DesktopChrome.control(medium: true),
+ ),
+ if (check['independent'] == true)
+ const Text('Requires an independent check.'),
+ if (check['evidence'] is String)
+ SuperTabMessageText(check['evidence'] as String),
+ Text(check['passedBy'] == null ? 'Not verified' : 'Verified'),
+ if (c.canWrite && assignment != null)
+ TextButton(
+ onPressed: c.saving || c.hasPendingAction
+ ? null
+ : () => _record(
+ context,
+ c,
+ groupId,
+ assignment['id'] as String,
+ check['id'] as String,
+ ),
+ child: const Text('Record check'),
+ ),
+ ],
+ if (assignment?['result'] is String) ...[
+ const SizedBox(height: 20),
+ Text('Result', style: DesktopChrome.control(medium: true)),
+ SuperTabMessageText(assignment!['result'] as String),
+ ],
+ if (c.operationError != null) Text(c.operationError!),
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving ? null : c.retry,
+ child: const Text('Check pending action'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ },
+ ),
+);
+
+Future<void> _record(
+ BuildContext context,
+ SuperTabController c,
+ String group,
+ String attempt,
+ String check,
+) async {
+ var evidence = '', passed = true, busy = false;
+ await showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: StatefulBuilder(
+ builder: (context, update) => AlertDialog(
+ title: const Text('Record check'),
+ content: SizedBox(
+ width: 460,
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ TextField(
+ autofocus: true,
+ minLines: 3,
+ maxLines: 8,
+ decoration: const InputDecoration(
+ hintText: 'What did you verify? Include the revision, method and result.',
+ ),
+ onChanged: (value) => update(() => evidence = value),
+ ),
+ SwitchListTile(
+ title: const Text('Passed'),
+ value: passed,
+ onChanged: busy
+ ? null
+ : (value) => update(() => passed = value),
+ ),
+ if (c.operationError != null) Text(c.operationError!),
+ ],
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: busy ? null : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: busy || evidence.trim().isEmpty
+ ? null
+ : () async {
+ update(() => busy = true);
+ final result = await c.command({
+ 'type': 'work.check',
+ 'conversationId': group,
+ 'assignmentId': attempt,
+ 'checkId': check,
+ 'passed': passed,
+ 'evidence': evidence.trim(),
+ });
+ if (!context.mounted) return;
+ if (result != null) {
+ Navigator.pop(context);
+ } else {
+ update(() => busy = false);
+ }
+ },
+ child: const Text('Save'),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dart
new file mode 100644
index 000000000..db2bf4317
--- /dev/null
+++ b/desktop/lib/super_tabs/workspace.dart
@@ -0,0 +1,560 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_select_field.dart';
+import '../state/app_state.dart';
+import '../state/terminal_pane.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'dialog_scope.dart';
+import 'model.dart';
+import 'view.dart';
+
+/// Keeps the app's one native canvas alive while placing it beside a shared
+/// conversation. Switching tabs never constructs a second terminal renderer.
+class SuperTabWorkspace extends StatefulWidget {
+ const SuperTabWorkspace({
+ super.key,
+ required this.app,
+ required this.canvas,
+ required this.onAddAgent,
+ });
+ final AppNotifier app;
+ final Widget canvas;
+ final ValueChanged<SuperTabConversation> onAddAgent;
+
+ @override
+ State<SuperTabWorkspace> createState() => _SuperTabWorkspaceState();
+}
+
+class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {
+ final _canvasKey = GlobalKey();
+ AppNotifier get app => widget.app;
+ (String, String, String?, String, bool)? _terminalRequest;
+ (String, String, String?, String, bool)? _readyRequest;
+ Future<void> _terminalChange = Future.value();
+ TerminalPane? _nativePane;
+ Timer? _nativeHeartbeat;
+
+ void _clearNativeContext() {
+ _nativeHeartbeat?.cancel();
+ _nativeHeartbeat = null;
+ final pane = _nativePane;
+ _nativePane = null;
+ _readyRequest = null;
+ if (pane == null || (pane.inputContext == null && !pane.watchOnly)) return;
+ pane.inputContext = null;
+ pane.watchOnly = false;
+ final session = pane.session;
+ session?.stageInputContext(null);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (pane.inputContext == null && !pane.watchOnly) {
+ unawaited(session?.setInputContext(null));
+ }
+ });
+ }
+
+ @override
+ void dispose() {
+ _clearNativeContext();
+ super.dispose();
+ }
+
+ void _syncTerminal(SuperTabController controller, String swarmId) {
+ final agent = controller.terminalAgent(controller.selectedId);
+ final request = (
+ swarmId,
+ controller.selectedId,
+ agent?.id,
+ controller.accountId,
+ controller.canWrite,
+ );
+ if (_terminalRequest == request) return;
+ _clearNativeContext();
+ _terminalRequest = request;
+ bool current() =>
+ mounted &&
+ _terminalRequest == request &&
+ app.activeSwarmId == swarmId &&
+ app.currentUser?.id == controller.accountId &&
+ controller.canWrite == request.$5;
+ // Native attachment may wait for machine discovery. Serialize replacements
+ // and discard any request superseded by another group or account.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _terminalChange = _terminalChange.catchError((Object _) {}).then((
+ _,
+ ) async {
+ if (!current()) return;
+ if (agent != null) {
+ await _open(agent, controller, swarmId, request.$2, current);
+ if (current()) setState(() => _readyRequest = request);
+ } else {
+ final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;
+ for (final pane in tab?.panes.toList() ?? const []) {
+ if (!current()) return;
+ await app.closePane(pane.id, swarmId: swarmId);
+ }
+ }
+ });
+ });
+ }
+
+ Future<void> _open(
+ SuperTabAgent agent,
+ SuperTabController controller,
+ String swarmId,
+ String conversationId,
+ bool Function() current,
+ ) async {
+ try {
+ final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;
+ if (tab == null) return;
+ var machine = app.stateOf(agent.machineId);
+ if (machine?.agents.any((a) => a.id == agent.harnessId) != true) {
+ await app.refreshMachines();
+ if (!current() || !app.swarms.any((s) => s.id == swarmId)) return;
+ machine = app.stateOf(agent.machineId);
+ }
+ if (machine?.agents.any((a) => a.id == agent.harnessId) != true) {
+ throw const SuperTabFailure(
+ 'TERMINAL_UNAVAILABLE',
+ 'The shared terminal is not available yet. Its execution machine must be online.',
+ );
+ }
+ if (!current()) return;
+ String? inputContext;
+ // A narrowly shared harness remains its existing read-only observer.
+ // Controlling a machine and joining a Super Tab are separate grants.
+ if (controller.canWrite && machine?.machine.isShared != true) {
+ final issued = await controller.request(
+ 'POST',
+ '/api/super-tabs/${controller.tabId}/native',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'conversationId': conversationId,
+ 'agentId': agent.id,
+ },
+ );
+ if (!current()) return;
+ inputContext = issued['contextId'] as String?;
+ if (inputContext == null ||
+ !RegExp(r'^[A-Za-z0-9_-]{16,160}$').hasMatch(inputContext)) {
+ throw const SuperTabFailure(
+ 'NATIVE_UNAVAILABLE',
+ 'Could not prepare terminal sharing. Try opening it again.',
+ );
+ }
+ final prepared = await app.superTabMachineRequest(agent.machineId, {
+ 'action': 'prepareNative',
+ 'tabId': controller.tabId,
+ 'contextId': inputContext,
+ });
+ if (!current()) return;
+ if (prepared['inputContext'] != inputContext) {
+ throw const SuperTabFailure(
+ 'NATIVE_UNAVAILABLE',
+ 'This machine could not confirm terminal sharing.',
+ );
+ }
+ }
+ await app.assignAgentToPane(
+ tab.panes.firstOrNull?.id,
+ agent.machineId,
+ agent.harnessId,
+ swarmId: swarmId,
+ inputContext: inputContext,
+ watchOnly: !controller.canWrite,
+ );
+ if (!current()) return;
+ if (tab.panes.firstOrNull case final pane?) {
+ pane.composerVisible = false;
+ _nativePane = pane;
+ }
+ if (inputContext != null) {
+ var renewing = false;
+ _nativeHeartbeat = Timer.periodic(const Duration(seconds: 20), (
+ timer,
+ ) async {
+ if (!current()) {
+ timer.cancel();
+ return;
+ }
+ if (renewing) return;
+ renewing = true;
+ try {
+ await app.superTabMachineRequest(agent.machineId, {
+ 'action': 'renewNative',
+ 'tabId': controller.tabId,
+ 'contextId': inputContext,
+ });
+ } catch (failure) {
+ if (mounted && current()) {
+ controller.selectTerminal(conversationId, null);
+ ScaffoldMessenger.of(context).showSnackBar(
+ SnackBar(content: Text('Terminal sharing paused. $failure')),
+ );
+ }
+ timer.cancel();
+ } finally {
+ renewing = false;
+ }
+ });
+ }
+ } catch (failure) {
+ if (mounted && current()) {
+ controller.selectTerminal(conversationId, null);
+ ScaffoldMessenger.of(context)
+ .showSnackBar(SnackBar(content: Text(failure.toString())));
+ }
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final canvas = KeyedSubtree(key: _canvasKey, child: widget.canvas);
+ final tab = app.activeSwarm;
+ final id = tab.superTabId;
+ if (!tab.isSuperTab || id == null) {
+ _clearNativeContext();
+ _terminalRequest = null;
+ return canvas;
+ }
+ return FutureBuilder<SuperTabController>(
+ future: app.superTabs.open(id),
+ builder: (context, state) {
+ final controller = state.data;
+ if (controller == null ||
+ controller.tabId != id ||
+ controller.accountId != app.currentUser?.id) {
+ return Stack(
+ children: [
+ Offstage(child: canvas),
+ Center(
+ child: state.hasError
+ ? Text(state.error.toString())
+ : const CircularProgressIndicator(),
+ ),
+ ],
+ );
+ }
+ return ListenableBuilder(
+ listenable: controller,
+ builder: (context, _) {
+ _syncTerminal(controller, tab.id);
+ final selectedTerminal = controller.terminalAgent(
+ controller.selectedId,
+ );
+ final showTerminal =
+ _readyRequest == _terminalRequest &&
+ selectedTerminal != null &&
+ tab.panes.any(
+ (pane) =>
+ pane.machineId == selectedTerminal.machineId &&
+ pane.agentId == selectedTerminal.harnessId,
+ );
+ return Stack(
+ fit: StackFit.expand,
+ children: [
+ if (!showTerminal) Offstage(child: canvas),
+ SuperTabView(
+ key: ValueKey('${controller.accountId}:$id'),
+ controller: controller,
+ onInvite: () =>
+ unawaited(showSuperTabPeople(context, controller)),
+ onAddAgent: widget.onAddAgent,
+ onOpenTerminal: (agent) {
+ _terminalRequest = null;
+ controller.selectTerminal(controller.selectedId, agent.id);
+ setState(() {});
+ },
+ machineName: (machine) =>
+ app.stateOf(machine)?.machine.displayName ??
+ 'Offline machine',
+ terminal: showTerminal ? canvas : null,
+ onCloseTerminal: () {
+ controller.selectTerminal(controller.selectedId, null);
+ },
+ ),
+ ],
+ );
+ },
+ );
+ },
+ );
+ }
+}
+
+Future<void> showSuperTabPeople(
+ BuildContext context,
+ SuperTabController controller,
+) => showAppDialog<void>(
+ context: context,
+ builder: (_) => SuperTabDialogScope(
+ controller: controller,
+ requireWrite: false,
+ child: _People(controller: controller),
+ ),
+);
+
+class _People extends StatefulWidget {
+ const _People({required this.controller});
+ final SuperTabController controller;
+ @override
+ State<_People> createState() => _PeopleState();
+}
+
+class _PeopleState extends State<_People> {
+ final _email = TextEditingController();
+ final _search = TextEditingController();
+ String _role = 'collaborator';
+ SuperTabController get c => widget.controller;
+ @override
+ void initState() {
+ super.initState();
+ _email.addListener(_emailChanged);
+ }
+
+ void _emailChanged() => setState(() {});
+ @override
+ void dispose() {
+ _email.removeListener(_emailChanged);
+ _email.dispose();
+ _search.dispose();
+ super.dispose();
+ }
+
+ Future<void> _invite() async {
+ if (!c.isOwner ||
+ c.saving ||
+ c.hasPendingAction ||
+ _email.text.trim().isEmpty) {
+ return;
+ }
+ final result = await c.command({
+ 'type': 'invite.create',
+ 'email': _email.text.trim(),
+ 'role': _role,
+ 'conversationId': c.selectedId,
+ });
+ if (result != null && mounted) _email.clear();
+ }
+
+ Future<void> _remove(SuperTabPerson person) async {
+ final yes = await showAppDialog<bool>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ requireWrite: false,
+ child: AlertDialog(
+ title: Text(
+ person.id == c.accountId
+ ? 'Leave Super Tab?'
+ : 'Remove ${person.email}?',
+ ),
+ content: const Text(
+ 'Their access and agent contributions will be withdrawn. Running harnesses stay on their machines.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Cancel'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: Text(person.id == c.accountId ? 'Leave' : 'Remove'),
+ ),
+ ],
+ ),
+ ),
+ );
+ if (yes != true) return;
+ final result = await c.command({
+ 'type': 'member.remove',
+ 'userId': person.id,
+ });
+ if (result != null && person.id == c.accountId && mounted) {
+ Navigator.pop(context);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ if (c.accessRevoked) {
+ return AlertDialog(
+ content: Text(c.error ?? 'This Super Tab is no longer available.'),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ }
+ final query = _search.text.trim().toLowerCase();
+ final people =
+ c.snapshot?.people
+ .where((p) => p.email.toLowerCase().contains(query))
+ .toList() ??
+ [];
+ return Dialog(
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ shape: const RoundedRectangleBorder(),
+ child: DesktopDialogSurface(
+ child: SizedBox(
+ width: 460,
+ height: 520,
+ child: Padding(
+ padding: const EdgeInsets.all(24),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ DesktopDialogHeader(
+ title: 'People',
+ padding: EdgeInsets.zero,
+ onClose: () => Navigator.pop(context),
+ ),
+ if (c.isOwner) ...[
+ const SizedBox(height: 12),
+ TextField(
+ controller: _email,
+ autofocus: true,
+ decoration: const InputDecoration(
+ hintText: 'Email address',
+ ),
+ onSubmitted: (_) => _invite(),
+ ),
+ Row(
+ children: [
+ Expanded(
+ child: ExcludeFocus(
+ excluding: c.saving || c.hasPendingAction,
+ child: ExcludeSemantics(
+ excluding: c.saving || c.hasPendingAction,
+ child: IgnorePointer(
+ ignoring: c.saving || c.hasPendingAction,
+ child: AppSelectField<String>(
+ value: _role,
+ semanticLabel: 'Invitation access',
+ textStyle: DesktopChrome.control(),
+ options: const [
+ SelectOption(
+ value: 'collaborator',
+ label: 'Can collaborate',
+ detail: 'Read every conversation and send messages to the shared agents.',
+ ),
+ SelectOption(
+ value: 'viewer',
+ label: 'Can view',
+ detail: 'Read every conversation without sending messages or changing work.',
+ ),
+ ],
+ onChanged: (role) {
+ if (!c.saving && !c.hasPendingAction) {
+ setState(() => _role = role);
+ }
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ const SizedBox(width: 12),
+ FilledButton(
+ onPressed:
+ c.saving ||
+ c.hasPendingAction ||
+ _email.text.trim().isEmpty
+ ? null
+ : _invite,
+ child: const Text('Invite'),
+ ),
+ ],
+ ),
+ Text(
+ 'They’ll find the invitation in Harness Settings → Tab invites.',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ if (c.operationError != null)
+ Padding(
+ padding: const EdgeInsets.symmetric(vertical: 8),
+ child: Text(c.operationError!),
+ ),
+ if (c.hasPendingAction)
+ TextButton(
+ onPressed: c.saving ? null : c.retry,
+ child: const Text('Check pending action'),
+ ),
+ const SizedBox(height: 12),
+ TextField(
+ controller: _search,
+ decoration: const InputDecoration(
+ hintText: 'Find a person',
+ ),
+ onChanged: (_) => setState(() {}),
+ ),
+ const SizedBox(height: 8),
+ Expanded(
+ child: ListView(
+ children: [
+ for (final person in people)
+ ListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(person.email),
+ subtitle: Text(
+ person.role == 'owner'
+ ? 'Owner'
+ : person.role == 'viewer'
+ ? 'Viewer'
+ : 'Collaborator',
+ style: DesktopChrome.metadata(),
+ ),
+ trailing:
+ person.role != 'owner' &&
+ (c.isOwner || person.id == c.accountId)
+ ? TextButton(
+ onPressed: c.saving
+ ? null
+ : () => _remove(person),
+ child: Text(
+ person.id == c.accountId
+ ? 'Leave'
+ : 'Remove',
+ ),
+ )
+ : null,
+ ),
+ for (final invitation
+ in c.snapshot?.invitations ??
+ <Map<String, dynamic>>[])
+ ListTile(
+ contentPadding: EdgeInsets.zero,
+ title: Text(invitation['email'] as String),
+ subtitle: const Text('Invited'),
+ trailing: TextButton(
+ onPressed: c.saving
+ ? null
+ : () => c.command({
+ 'type': 'invite.revoke',
+ 'inviteId': invitation['id'],
+ }),
+ child: const Text('Revoke'),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ },
+ );
+}
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index b9bca2af8..d3f4f631d 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -152,7 +152,13 @@ class TerminalSession extends ChangeNotifier {
final TerminalBinarySender sendBinary;
final Duration resyncTimeout;
- final bool readOnly;
+ final bool _readOnly;
+ bool get readOnly => _readOnly || _watchOnly;
+ String? _inputContext;
+ String? _openedInputContext;
+ bool _watchOnly;
+ bool _openedWatchOnly = false;
+ String? get inputContext => _inputContext;
// A controllable clock keeps coalescing tests independent of host scheduling.
final DateTime Function() _now;
@@ -213,10 +219,19 @@ class TerminalSession extends ChangeNotifier {
this.client,
this.onOpenStalled,
this.takeover = true,
- this.readOnly = false,
+ bool readOnly = false,
+ String? inputContext,
+ bool watchOnly = false,
this.resyncTimeout = const Duration(seconds: 4),
DateTime Function()? now,
- }) : _now = now ?? DateTime.now {
+ }) : _now = now ?? DateTime.now,
+ // ignore: prefer_initializing_formals
+ _readOnly = readOnly,
+ // The public parameter deliberately omits the private field's underscore.
+ // ignore: prefer_initializing_formals
+ _inputContext = inputContext,
+ // ignore: prefer_initializing_formals
+ _watchOnly = watchOnly {
terminal = _newTerminal();
}
@@ -305,7 +320,10 @@ class TerminalSession extends ChangeNotifier {
bool get acceptsInput =>
!readOnly &&
+ !_watchOnly &&
!watching &&
+ _inputContext == _openedInputContext &&
+ _watchOnly == _openedWatchOnly &&
status == TerminalSessionStatus.controlling &&
streamId != null;
@@ -333,6 +351,31 @@ class TerminalSession extends ChangeNotifier {
notifyListeners();
}
+ /// An opaque provenance hint, never an access grant. Staging a new scope
+ /// immediately withholds input until its replacement stream is ready.
+ void stageInputContext(String? value, {bool watchOnly = false}) {
+ if (_inputContext == value && _watchOnly == watchOnly) return;
+ _inputContext = value;
+ _watchOnly = watchOnly;
+ _inputBytes.clear();
+ }
+
+ Future<void> setInputContext(String? value, {bool watchOnly = false}) async {
+ stageInputContext(value, watchOnly: watchOnly);
+ if (_disposed ||
+ (_openedInputContext == value && _openedWatchOnly == watchOnly)) {
+ return;
+ }
+ await _open(
+ initialCols: _measuredViewport?.cols ?? cols,
+ initialRows: _measuredViewport?.rows ?? rows,
+ waitForViewportSize: false,
+ resetRecovery: true,
+ preserveTerminal: true,
+ allowRedial: false,
+ );
+ }
+
Future<void> open({
int initialCols = 80,
int initialRows = 24,
@@ -453,11 +496,15 @@ class TerminalSession extends ChangeNotifier {
'rows': rows,
'compression': const ['zlib', 'none'],
if (client != null) 'client': client!.toJson(),
+ if (_inputContext != null) 'inputContext': _inputContext,
+ if (_watchOnly) 'watchOnly': true,
// Absent is the takeover an open has always been; `false` asks the daemon
// to leave whoever holds the terminal alone and hand this one a watcher.
if (!takeover) 'takeover': false,
};
_openAskedTakeover = takeover;
+ _openedInputContext = _inputContext;
+ _openedWatchOnly = _watchOnly;
var sent = await send('terminal_open', openPayload);
if (!_isCurrent(generation) ||
status != TerminalSessionStatus.opening ||
@@ -1039,6 +1086,7 @@ class TerminalSession extends ChangeNotifier {
'content': content,
'agentId': agentId,
'mode': 'auto',
+ if (_inputContext != null) 'inputContext': _inputContext,
if (!kIsWeb && client?.kind == 'desktop') 'usageIntent': 'interactive',
});
}
@@ -1672,7 +1720,7 @@ class TerminalSession extends ChangeNotifier {
appLog.warn(
'terminal',
'failed machine=$machineId agent=$agentId stream=$streamId code=$code'
- '${message == null ? '' : ' message=$message'}',
+ '${message == null ? '' : ' message=$message'}',
);
_generation++;
_cancelTimers();
diff --git a/desktop/lib/widgets/desktop_search_panel.dart b/desktop/lib/widgets/desktop_search_panel.dart
index 1276f9256..dcc8321da 100644
--- a/desktop/lib/widgets/desktop_search_panel.dart
+++ b/desktop/lib/widgets/desktop_search_panel.dart
@@ -97,8 +97,8 @@ class DesktopSearchPanel extends StatelessWidget {
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: maxWidth,
+ constraints: BoxConstraints(
+ maxWidth: search.harnessContext == null ? maxWidth : 680,
maxHeight: maxHeight,
),
child: DesktopDialogSurface(
@@ -107,6 +107,37 @@ class DesktopSearchPanel extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
+ if (search.harnessContext case final purpose?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(24, 20, 24, 4),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Tooltip(
+ message: purpose.title,
+ child: Text(
+ purpose.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.heading(),
+ ),
+ ),
+ const SizedBox(height: 4),
+ Tooltip(
+ message: purpose.description,
+ child: Text(
+ purpose.description,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.text(
+ size: 13,
+ color: DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
if (search.split != null)
Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
@@ -161,27 +192,28 @@ class DesktopSearchPanel extends StatelessWidget {
),
),
),
- ListenableBuilder(
- listenable: search,
- builder: (context, _) => _toolbarButton(
- context,
- key: const ValueKey('search-toggle-preview'),
- tooltip: search.previewVisible
- ? 'Hide preview'
- : 'Show preview',
- isSelected: search.previewVisible,
- onPressed: search.supportsPreview
- ? () {
- search.togglePreview();
- onRefocus();
- }
- : null,
- icon: const AppPaneIcon(
- AppPaneSymbol.splitRight,
- size: 18,
+ if (search.harnessContext == null)
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => _toolbarButton(
+ context,
+ key: const ValueKey('search-toggle-preview'),
+ tooltip: search.previewVisible
+ ? 'Hide preview'
+ : 'Show preview',
+ isSelected: search.previewVisible,
+ onPressed: search.supportsPreview
+ ? () {
+ search.togglePreview();
+ onRefocus();
+ }
+ : null,
+ icon: const AppPaneIcon(
+ AppPaneSymbol.splitRight,
+ size: 18,
+ ),
),
),
- ),
_toolbarButton(
context,
key: const ValueKey('search-close'),
@@ -192,41 +224,45 @@ class DesktopSearchPanel extends StatelessWidget {
],
),
),
- ListenableBuilder(
- listenable: search,
- builder: (context, _) => SingleChildScrollView(
- scrollDirection: Axis.horizontal,
- padding: const EdgeInsets.fromLTRB(20, 2, 20, 14),
- child: Row(
- spacing: 6,
- children: [
- if (showsBack && search.canGoBack)
- DesktopPill(
- key: const ValueKey('search-back'),
- label: 'Back',
- leading: const Icon(AppIcons.chevronLeft, size: 14),
- capsule: true,
- quiet: true,
- onPressed: () {
- if (search.back()) onRefocus();
+ if (search.harnessContext == null)
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => SingleChildScrollView(
+ scrollDirection: Axis.horizontal,
+ padding: const EdgeInsets.fromLTRB(20, 2, 20, 14),
+ child: Row(
+ spacing: 6,
+ children: [
+ if (showsBack && search.canGoBack)
+ DesktopPill(
+ key: const ValueKey('search-back'),
+ label: 'Back',
+ leading: const Icon(
+ AppIcons.chevronLeft,
+ size: 14,
+ ),
+ capsule: true,
+ quiet: true,
+ onPressed: () {
+ if (search.back()) onRefocus();
+ },
+ ),
+ _SearchScopes(
+ selected: _prefix,
+ onRefocus: onRefocus,
+ onChanged: (prefix) {
+ final words = search.wordsQuery;
+ search.setQuery(
+ prefix.isEmpty
+ ? words
+ : '$prefix $words'.trimRight(),
+ );
},
),
- _SearchScopes(
- selected: _prefix,
- onRefocus: onRefocus,
- onChanged: (prefix) {
- final words = search.wordsQuery;
- search.setQuery(
- prefix.isEmpty
- ? words
- : '$prefix $words'.trimRight(),
- );
- },
- ),
- ],
+ ],
+ ),
),
),
- ),
if (_machineHooks(context) case final hooks?)
ListenableBuilder(
listenable: search,
@@ -243,7 +279,7 @@ class DesktopSearchPanel extends StatelessWidget {
onRefocus: onRefocus,
// Keep the dialog, editor, and footer stationary while a
// query gains a preview or changes to an empty result.
- fitRows: false,
+ fitRows: search.harnessContext != null,
// The scope control already explains the empty search.
// Give results the full width until there is a preview.
showPreview: !search.showsTypeHints,
@@ -270,7 +306,34 @@ class DesktopSearchPanel extends StatelessWidget {
)
: const SizedBox.shrink(),
),
- if (KeyHints.visibleOf(context)) ...[
+ if (search.harnessContext != null) ...[
+ Divider(height: 1, color: DesktopChrome.rim),
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: 24,
+ vertical: 12,
+ ),
+ child: Row(
+ children: [
+ if (KeyHints.visibleOf(context))
+ _hint(context, 'picker.cancel', 'Close'),
+ const Spacer(),
+ ListenableBuilder(
+ listenable: search,
+ builder: (context, _) => FilledButton(
+ onPressed: search.canAccept
+ ? () {
+ final choice = search.submit();
+ if (choice != null) onChoose(choice);
+ }
+ : null,
+ child: Text(search.actionLabel(search.selected)),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ] else if (KeyHints.visibleOf(context)) ...[
Divider(height: 1, color: DesktopChrome.rim),
Padding(
padding: const EdgeInsets.symmetric(
diff --git a/desktop/lib/widgets/desktop_workspace_tab.dart b/desktop/lib/widgets/desktop_workspace_tab.dart
index d28d8ee1d..b5d697656 100644
--- a/desktop/lib/widgets/desktop_workspace_tab.dart
+++ b/desktop/lib/widgets/desktop_workspace_tab.dart
@@ -49,6 +49,8 @@ class DesktopWorkspaceTab extends StatefulWidget {
this.onStopSharing,
this.onMoveHere,
this.onLeave,
+ this.onPauseNewWork,
+ this.newWorkPaused = false,
});
final String id, label;
@@ -56,6 +58,8 @@ class DesktopWorkspaceTab extends StatefulWidget {
final ValueListenable<bool> showShortcuts;
final VoidCallback? onSelect, onClose;
final VoidCallback? onRename;
+ final VoidCallback? onPauseNewWork;
+ final bool newWorkPaused;
final String? shortcutHint, tooltip, activityLabel;
/// The status cell: an [ActivityMark].
@@ -195,6 +199,7 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
final _menu = MenuController();
bool get _hasMenu =>
+ widget.onPauseNewWork != null ||
widget.onInvitePeople != null ||
widget.onShowAgentMessages != null ||
widget.onStopSharing != null ||
@@ -249,6 +254,15 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {
},
);
return [
+ if (widget.onPauseNewWork != null) ...[
+ if (widget.onRename != null)
+ row('rename', 'Rename Tab…', widget.onRename),
+ row(
+ 'pause',
+ widget.newWorkPaused ? 'Resume new work' : 'Pause new work',
+ widget.onPauseNewWork,
+ ),
+ ],
if (widget.onInvitePeople != null)
row('invite', 'Invite People…', widget.onInvitePeople),
if (widget.onShowAgentMessages != null)
diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dart
index a0d88a974..3865206cd 100644
--- a/desktop/lib/widgets/new_harness_form.dart
+++ b/desktop/lib/widgets/new_harness_form.dart
@@ -382,7 +382,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
_Row.worktree => 'Worktree',
_Row.approvals => 'Approvals',
_Row.profile => widget.desktop ? 'Account' : 'Profile',
- _Row.start => 'New Harness',
+ _Row.start => box.actionLabel,
};
/// What the row currently answers — or, while its list is open, what the
@@ -399,7 +399,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
_Row.approvals => box.modeLabel,
_Row.profile =>
box.profileLabel ?? (widget.desktop ? 'Default account' : 'Default'),
- _Row.start => box.checking ? 'Check status' : _label(row),
+ _Row.start => box.checking ? box.pendingActionLabel : _label(row),
};
// These leave this form for a native sheet, account flow or another route.
@@ -899,6 +899,33 @@ class NewHarnessFormState extends State<NewHarnessForm> {
Future<void> _start() async {
if (box.busy) return;
+ bool? resendAttachments;
+ if (box.needsAttachmentReview) {
+ resendAttachments = await showDialog<bool>(
+ context: context,
+ builder: (context) => AlertDialog(
+ title: const Text('Check file delivery'),
+ content: const Text(
+ 'The files and first message may already have reached the harness. Open it from Recent harnesses to check. Before sending again, clear any unfinished text in its terminal.',
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ ),
+ TextButton(
+ onPressed: () => Navigator.pop(context, false),
+ child: const Text('Already sent'),
+ ),
+ FilledButton(
+ onPressed: () => Navigator.pop(context, true),
+ child: const Text('Send again'),
+ ),
+ ],
+ ),
+ );
+ if (!mounted || resendAttachments == null) return;
+ }
_restoreChoiceFocus = false;
if (box.requiredChoice case final choice?) {
box.focusField(choice.field);
@@ -909,7 +936,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {
return;
}
_checkingLaunch = box.checking;
- final outcome = await box.create();
+ final outcome = await box.create(resendAttachments: resendAttachments);
if (!mounted) return;
switch (outcome) {
case NewHarnessOutcome.created:
@@ -2201,8 +2228,8 @@ class NewHarnessFormState extends State<NewHarnessForm> {
final label = box.busy
? (_checkingLaunch ? 'Checking…' : 'Starting…')
: box.checking
- ? 'Check status'
- : 'New Harness';
+ ? box.pendingActionLabel
+ : box.actionLabel;
return FocusTraversalOrder(
order: const NumericFocusOrder(10),
child: FilledButton(
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 7298683af..823b2aeac 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -823,6 +823,7 @@ class _TerminalPanelState extends State<TerminalPanel>
/// notice must still allow it: setup prompts need a controlling client.
bool get _inputBlocked =>
!widget.readOnly &&
+ !widget.session.readOnly &&
// A watcher is the same situation seen from the other side: this window
// has the output but another client has the terminal, and the band's
// button is how a person here asks for it.
@@ -2408,7 +2409,7 @@ class _TerminalPanelState extends State<TerminalPanel>
child: TerminalComposer(
session: session,
focusNode: _composerFocus,
- inputEnabled: !widget.readOnly,
+ inputEnabled: !widget.readOnly && !session.readOnly,
),
),
],
@@ -2472,7 +2473,7 @@ class _TerminalPanelState extends State<TerminalPanel>
name: session.agentName,
status: session.status,
notice: widget.notice,
- readOnly: widget.readOnly,
+ readOnly: widget.readOnly || session.readOnly,
error: session.errorMessage ?? session.errorCode,
link: session.linkMode,
machine: machine?.machine,
@@ -2512,7 +2513,7 @@ class _TerminalPanelState extends State<TerminalPanel>
notifier: widget.notifier,
session: session,
notice: widget.notice,
- readOnly: widget.readOnly,
+ readOnly: widget.readOnly || session.readOnly,
compact: widget.compactHeader,
zoomed: widget.zoomed,
onToggleZoom: widget.onToggleZoom == null
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index c39db83e9..a8a6c36ec 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -633,6 +633,7 @@ class WsConn {
!type.startsWith('api_connections') &&
!type.startsWith('connectors') &&
!type.startsWith('orchestrator') &&
+ !type.startsWith('super_tabs') &&
!type.startsWith('route_') &&
!type.startsWith('harness_share_') &&
// Pair responses can contain retained memory quotations and one-use
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index b5a80f8b7..3ee3c6146 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -2506,6 +2506,7 @@ private final class SwarmTabStrip: NSView {
tab.activity = HarnessNativeActivity(row["activity"] as? [String: Any])
tab.canShowAgentMessages = row["canShowAgentMessages"] as? Bool == true
tab.canInvitePeople = row["canInvitePeople"] as? Bool == true
+ tab.superTabPaused = row["superTabPaused"] as? Bool
tab.applyShared(row["shared"] as? [String: Any])
tab.emit = { [weak self, weak tab] method, args in
guard let self, let tab, self.actionsEnabled,
@@ -2922,6 +2923,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
var canInvitePeople = false {
didSet { if canInvitePeople != oldValue { updateMessagesItems() } }
}
+ var superTabPaused: Bool? { didSet { updateMessagesItems() } }
+ private var pauseSuperTabItem: NSMenuItem?
func applyShared(_ shared: [String: Any]?) {
let count = shared?["count"] as? Int
let role = count == nil ? nil : shared?["role"] as? String
@@ -3085,6 +3088,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
return item
}
_ = item("Rename Tab…", #selector(renameSwarm))
+ pauseSuperTabItem = item("Pause new work", #selector(pauseSuperTab))
let separator = NSMenuItem.separator()
menu.addItem(separator)
messagesSeparator = separator
@@ -3154,6 +3158,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
/// The menu's Show Agent Messages (only where the tab has a log), its sharing rows, and their separator when any
/// of them shows.
private func updateMessagesItems() {
+ pauseSuperTabItem?.isHidden = superTabPaused == nil
+ pauseSuperTabItem?.title = superTabPaused == true ? "Resume new work" : "Pause new work"
for item in messagesItems { item.isHidden = !canShowAgentMessages }
for (action, item) in shareItems { item.isHidden = !offers(action) }
messagesSeparator?.isHidden = (messagesItems + Array(shareItems.values)).allSatisfy(\.isHidden)
@@ -3369,6 +3375,9 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati
@objc private func selectSwarm() { if actionsEnabled { emit?("select", ["id": swarmId]) } }
@objc private func closeSwarm() { if actionsEnabled { emit?("close", ["id": swarmId]) } }
@objc private func renameSwarm() { if actionsEnabled { emit?("rename", ["id": swarmId]) } }
+ @objc private func pauseSuperTab() {
+ if actionsEnabled && superTabPaused != nil { emit?("pauseSuperTab", ["id": swarmId]) }
+ }
@objc private func showMessages() {
if actionsEnabled && canShowAgentMessages { emit?("showAgentMessages", ["id": swarmId]) }
}
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index 9c7088864..e28d00089 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -251,6 +251,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "6.0.0"
+ flutter_markdown_plus:
+ dependency: "direct main"
+ description:
+ name: flutter_markdown_plus
+ sha256: fce641d6c2106cc495de1cd603f97a4f9d615a97a64011928ded380dbdade935
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.0.12"
flutter_riverpod:
dependency: "direct main"
description:
@@ -367,6 +375,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.20"
+ markdown:
+ dependency: transitive
+ description:
+ name: markdown
+ sha256: ee85086ad7698b42522c6ad42fe195f1b9898e4d974a1af4576c1a3a176cada9
+ url: "https://pub.dev"
+ source: hosted
+ version: "7.3.1"
matcher:
dependency: transitive
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index 8a96cea82..e9d909534 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -42,6 +42,9 @@ dependencies:
cupertino_icons: ^1.0.8
lucide_icons_flutter: ^3.1.15
flutter_svg: ^2.3.0
+ # Selectable agent messages, code and tables. Pure Flutter/Dart; no native
+ # plugin. Super Tab disables automatic images and permits only web links.
+ flutter_markdown_plus: ^1.0.12
dio: ^5.11.0
web_socket_channel: ^3.0.3
flutter_riverpod: ^2.6.1
diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dart
index c58fb798e..fe594a7eb 100644
--- a/desktop/test/desktop_welcome_composer_test.dart
+++ b/desktop/test/desktop_welcome_composer_test.dart
@@ -197,6 +197,39 @@ void main() {
},
);
+ testWidgets('Super Tab recents open an ordinary harness through the shared welcome page', (tester) async {
+ await setup(tester, storage: MemoryStore());
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ app.machineStates['m']!.agents = [
+ Agent(
+ id: 'recent-existing',
+ name: 'Continue existing work',
+ engine: 'codex',
+ terminalAvailable: true,
+ lastOpenedAt: DateTime.now(),
+ lastActivityAt: DateTime.now(),
+ ),
+ ];
+ final pane = app.adoptSessionForTest(terminal('recent-existing', []));
+ await tester.pumpAndSettle();
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true, shift: true);
+ await tester.pumpAndSettle();
+ final target = app.activeSwarm;
+ expect(target.isSuperTab, isTrue);
+ expect(form, findsOneWidget);
+ await tester.tap(find.text('Continue existing work'));
+ await tester.pumpAndSettle();
+ expect(target.isSuperTab, isFalse);
+ expect(target.panes.single.agentId, 'recent-existing');
+ expect(target.panes.single, same(pane));
+ expect(connection.starts, isEmpty);
+ expect(form, findsNothing);
+ expect(tester.takeException(), isNull);
+ });
+
testWidgets('Cmd-P round trip opens a fresh form with successful defaults', (
tester,
) async {
diff --git a/desktop/test/experimental_features_test.dart b/desktop/test/experimental_features_test.dart
index 2a8e3cd50..3ebfc5d4c 100644
--- a/desktop/test/experimental_features_test.dart
+++ b/desktop/test/experimental_features_test.dart
@@ -97,75 +97,44 @@ void main() {
server.readOverride = () async => {
...server.snapshot,
'revision': 1,
- 'features': {...server.features, ExperimentalFeature.agentMessages.id: 'on'},
+ 'features': {
+ ...server.features,
+ ExperimentalFeature.agentMessages.id: 'on',
+ },
};
await store.refresh();
expect(store.error, isNotNull);
expect(store.enabled(ExperimentalFeature.agentMessages), isFalse);
});
- testWidgets('what agents may do: three account switches, each off until turned on', (
- tester,
- ) async {
- final server = AccountSettings('a');
- final store = await open(server);
- await tester.pumpWidget(
- MaterialApp(home: Scaffold(body: ExperimentalSection(store: store))),
- );
- await tester.pumpAndSettle();
- final copy = {
- 'Agents can start other agents':
- 'Turn on to let Claude Code and Codex start, wait for and close harnesses of their own; '
- 'their instructions say how. Off, each agent works alone.',
- 'Mark pull requests from agent-started harnesses':
- 'Turn on to have a harness another agent started add one line to the pull requests it '
- 'opens: 🤝 Started by another agent in Harness.',
- 'Agents in the same tab can message each other':
- 'Turn on to let Claude Code and Codex in one tab send each other messages with harness send. Invite people to a tab and their harnesses join it from their own computers.',
- };
- for (final MapEntry(key: label, value: detail) in copy.entries) {
- expect(find.text(label), findsOneWidget);
- expect(find.text(detail), findsOneWidget);
- }
- for (final id in ['agents_start_agents', 'agent_pull_request_line', 'agent_messages']) {
- final toggle = find.byKey(ValueKey('experimental-$id'));
- await tester.ensureVisible(toggle);
- expect(tester.widget<Switch>(toggle).value, isFalse);
- await tester.tap(toggle);
+ testWidgets(
+ 'Super Tab coordination no longer needs account experiment switches',
+ (tester) async {
+ final server = AccountSettings('a');
+ final store = await open(server);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(body: ExperimentalSection(store: store)),
+ ),
+ );
await tester.pumpAndSettle();
- expect(tester.widget<Switch>(toggle).value, isTrue);
- }
- expect(server.writes.map((w) => (w.$2.id, w.$3)), [
- ('agents_start_agents', true),
- ('agent_pull_request_line', true),
- ('agent_messages', true),
- ]);
- await tester.pumpWidget(const SizedBox());
- });
-
- testWidgets('the summary switch is stored inverted: checked when agent_messages_hide_summary is off', (tester) async {
- final server = AccountSettings('a');
- final store = await open(server);
- await tester.pumpWidget(
- MaterialApp(home: Scaffold(body: ExperimentalSection(store: store))),
- );
- await tester.pumpAndSettle();
- const title = 'Share a one-line summary of what your harnesses are doing with people in your shared tabs';
- expect(find.text(title), findsOneWidget);
- final toggle = find.byKey(const ValueKey('experimental-agent_messages_hide_summary'));
- await tester.ensureVisible(toggle);
- expect(tester.widget<Switch>(toggle).value, isTrue);
- await tester.tap(toggle);
- await tester.pumpAndSettle();
- expect(server.writes.last.$2.id, 'agent_messages_hide_summary');
- expect(server.writes.last.$3, isTrue);
- expect(tester.widget<Switch>(toggle).value, isFalse);
- await tester.tap(toggle);
- await tester.pumpAndSettle();
- expect(server.writes.last.$3, isFalse);
- expect(tester.widget<Switch>(toggle).value, isTrue);
- await tester.pumpWidget(const SizedBox());
- });
+ expect(find.text('Focus-bar creature'), findsOneWidget);
+ expect(find.text('Share button'), findsOneWidget);
+ for (final feature in ExperimentalFeature.values.where(
+ (f) => !f.visibleInSettings,
+ )) {
+ expect(find.text(feature.label), findsNothing);
+ expect(
+ find.byKey(ValueKey('experimental-${feature.id}')),
+ findsNothing,
+ );
+ }
+ // Opening the simplified settings must not enable account-wide execution or
+ // change an older tab's saved sharing choices.
+ expect(server.writes, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
test('a pending save is not presented as saved, and a failed save can be retried', () async {
final server = AccountSettings('a');
diff --git a/desktop/test/new_harness_entry_rules_test.dart b/desktop/test/new_harness_entry_rules_test.dart
index 8f30625f3..2c9082dd0 100644
--- a/desktop/test/new_harness_entry_rules_test.dart
+++ b/desktop/test/new_harness_entry_rules_test.dart
@@ -25,7 +25,7 @@ import 'keymap_host_test.dart' show MemoryKeymap, key;
import 'keymap_runtime_test.dart' as configured;
import 'support/mixed_agents.dart';
import 'swarm_screen_test.dart' show terminal;
-import 'swarm_state_test.dart' show createApp;
+import 'swarm_state_test.dart' show createApp, MemoryStore;
const _products = [
{
@@ -125,11 +125,13 @@ void main() {
bool workingPane = true,
bool history = true,
bool remotePane = false,
+ bool superTabReady = false,
}) async {
connections = {
for (final id in ['m', 'studio', 'build']) id: _Connection(id),
};
- app = createApp(connectionForTest: (id) => connections[id]!);
+ app = createApp(connectionForTest: (id) => connections[id]!, store: superTabReady ? MemoryStore() : null);
+ if (superTabReady) app.currentUser = const CurrentUserProfile(id: 'owner', email: '[email protected]');
seedMixedAgents(app);
app.machineStates['m']!.localOnly = true;
app.gitProjectReaderForTest = (_, _) async => {'isGit': false};
@@ -204,6 +206,24 @@ void main() {
await acceptSetupOrSearch(tester);
}
+ testWidgets('the hidden Super Tab shortcut reuses New Tab without changing Cmd-T', (tester) async {
+ await mount(tester, store: false, superTabReady: true);
+ final before = app.swarms.length;
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true, alt: true, shift: true);
+ await tester.pumpAndSettle();
+ expect(app.swarms, hasLength(before + 1));
+ expect(app.activeSwarm.isSuperTab, isTrue);
+ expect(find.byType(NewHarnessForm), findsOneWidget);
+ expect(find.text('New Super Tab'), findsOneWidget);
+ expect(box(tester).actionLabel, 'New Super Tab');
+ expect(connections.values.expand((c) => c.starts), isEmpty);
+ await key(tester, LogicalKeyboardKey.keyT, cmd: true);
+ await tester.pumpAndSettle();
+ expect(app.activeSwarm.kind, 'harness');
+ expect(box(tester).actionLabel, 'New Harness');
+ await tester.pumpWidget(const SizedBox());
+ });
+
for (final shortcut in [LogicalKeyboardKey.keyN, LogicalKeyboardKey.keyP]) {
testWidgets(
'${shortcut.keyLabel == 'N' ? 'Cmd-N' : 'command palette'} starts a pane with no extra launch controls',
diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dart
new file mode 100644
index 000000000..549d8d29d
--- /dev/null
+++ b/desktop/test/super_tab_chat_test.dart
@@ -0,0 +1,284 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_markdown_plus/flutter_markdown_plus.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';
+import 'package:harness/super_tabs/message_text.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ testWidgets(
+ 'a keyboard reply keeps its quoted context after sending and refreshing',
+ (tester) async {
+ final server = ConversationServer()
+ ..append('Should edits survive restarting the app?');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'builder',
+ 'name': 'Builder',
+ };
+ final c = await show(tester, server);
+ final row = find.byKey(const ValueKey('super-message-message-1'));
+ tester
+ .widget<Focus>(
+ find.descendant(of: row, matching: find.byType(Focus)).first,
+ )
+ .focusNode!
+ .requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyR);
+ await tester.pump();
+ expect(find.text('Replying to Builder'), findsOneWidget);
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ expect(tester.widget<TextField>(composer).focusNode!.hasFocus, isTrue);
+ await tester.enterText(composer, 'Yes, persist the local queue.');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect((server.posts.single['command'] as Map)['replyTo'], 'message-1');
+ await c.refresh();
+ await tester.pumpAndSettle();
+ final reply = find.byKey(const ValueKey('super-message-message-2'));
+ expect(
+ find.descendant(of: reply, matching: find.byType(SuperTabReplyPreview)),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: reply,
+ matching: find.text('Should edits survive restarting the app?'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('Replying to Builder'), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'incoming agent traffic preserves history and offers a scoped catch-up action',
+ (tester) async {
+ final server = ConversationServer();
+ for (var i = 0; i < 35; i++) {
+ server.append(
+ 'Agent update $i: checking the offline queue and reconnect behavior.',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'builder-$i',
+ 'name': 'Builder $i',
+ };
+ }
+ final c = await show(tester, server);
+ ScrollController scroll() => tester
+ .widget<ListView>(
+ find.byKey(const PageStorageKey('super-messages-tab-lead')),
+ )
+ .controller!;
+ scroll().jumpTo(0);
+ await tester.pumpAndSettle();
+ final reading = scroll().offset;
+ server.append('The reconnect check passed.');
+ server.append('The restart check passed too.');
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(scroll().offset, reading);
+ expect(find.text('2 new messages'), findsOneWidget);
+ expect(c.unread(c.selected!), isTrue);
+ await tester.tap(find.byKey(const ValueKey('super-new-messages')));
+ await tester.pumpAndSettle();
+ expect(find.text('2 new messages'), findsNothing);
+ expect(scroll().position.extentAfter, lessThan(40));
+ expect(c.unread(c.selected!), isFalse);
+ expect(find.text('The restart check passed too.'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets(
+ 'revocation removes the quoted original as well as the transcript',
+ (tester) async {
+ final server = ConversationServer()..append('A private question');
+ final c = await show(tester, server);
+ await tester.tap(find.byTooltip('Reply'));
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabReplyPreview), findsOneWidget);
+ c.revokeAccess('Access removed.');
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabReplyPreview), findsNothing);
+ expect(find.text('A private question'), findsNothing);
+ expect(
+ tester
+ .widget<TextField>(
+ find.byKey(const ValueKey('super-message-composer')),
+ )
+ .controller!
+ .text,
+ isEmpty,
+ );
+ },
+ );
+
+ testWidgets(
+ 'a human request belongs only to its group and clears with the recorded state',
+ (tester) async {
+ final server = ConversationServer();
+ final group = (server.state['conversations'] as List)[1] as Map;
+ group['assignment'] = {
+ 'id': 'attempt',
+ 'agentId': 'builder',
+ 'status': 'needs_human',
+ 'result': 'Which device should I test?',
+ };
+ final c = await show(tester, server);
+ expect(find.text('Needs a human'), findsNothing);
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(find.text('Needs a human'), findsOneWidget);
+ group['assignment']['status'] = 'working';
+ server.revision++;
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(find.text('Needs a human'), findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'Markdown preserves readable code and never loads message images',
+ (tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 400,
+ child: const SuperTabMessageText(
+ '## Checked\n\n**Restart** preserves the queue.\n\n'
+ '\u0060\u0060\u0060dart\nawait queue.flush();\n\u0060\u0060\u0060\n\n'
+ '![Local image](file:///private/example.png)\n\n'
+ '![Remote image](https://example.com/tracking.png)',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byType(MarkdownBody), findsOneWidget);
+ expect(find.text('Checked'), findsOneWidget);
+ expect(
+ find.textContaining('queue.flush()', findRichText: true),
+ findsWidgets,
+ );
+ expect(find.text('Image: Local image'), findsOneWidget);
+ expect(find.text('Image: Remote image'), findsOneWidget);
+ expect(find.byType(Image), findsNothing);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ test('message links permit only explicit http and https destinations', () {
+ for (final href in [
+ null,
+ '',
+ '/tmp/code',
+ 'file:///tmp/code',
+ 'javascript:alert(1)',
+ 'data:text/plain,hello',
+ 'https:///',
+ ]) {
+ expect(SuperTabMessageText.webLink(href), isNull);
+ }
+ expect(
+ SuperTabMessageText.webLink('https://example.com/check#result')?.host,
+ 'example.com',
+ );
+ expect(SuperTabMessageText.webLink('http://localhost:3000')?.port, 3000);
+ });
+
+ test(
+ 'grouping preserves author, day, reply and native source boundaries',
+ () {
+ final server = ConversationServer()
+ ..append('First update')
+ ..append('Second update');
+ SuperTabMessage message(int i) =>
+ SuperTabMessage.fromJson(server.messages[i]);
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isTrue);
+ server.append('Third update');
+ server.append('Fourth update');
+ expect(
+ SuperTabMessageRow.consecutiveUpdates(
+ server.messages.map(SuperTabMessage.fromJson).toList(),
+ ),
+ {'message-2', 'message-3'},
+ );
+ server.messages[1]['text'] = 'Should edits survive sign-out?';
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ expect(SuperTabMessageRow.groupsWith(message(2), message(1)), isFalse);
+ server.messages[1]['text'] = '保留修改?';
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ server.messages[1]['text'] = 'Second update';
+ server.messages[1]['author'] = {
+ 'kind': 'agent',
+ 'id': 'owner',
+ 'name': '[email protected]',
+ };
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ server.messages[1]['author'] = server.messages[0]['author'];
+ server.messages[1]['createdAt'] = '2026-10-19T00:00:00Z';
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ server.messages[1]['createdAt'] = server.messages[0]['createdAt'];
+ server.messages[1]['replyTo'] = 'message-1';
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ server.messages[1].remove('replyTo');
+ server.messages[1]['source'] = {'kind': 'native', 'phase': 'prompt'};
+ expect(SuperTabMessageRow.groupsWith(message(1), message(0)), isFalse);
+ },
+ );
+
+ test(
+ 'reading loaded messages cannot mark an unfetched tail as read',
+ () async {
+ final server = ConversationServer()..append('Visible');
+ final c = server.controller();
+ await c.refresh();
+ server.append('Not loaded');
+ c.snapshot = SuperTabSnapshot.fromJson(server.state);
+ c.markRead('lead', through: c.messages('lead').last.sequence);
+ expect(c.unread(c.selected!), isTrue);
+ await c.loadMessages('lead');
+ c.markRead('lead', through: c.messages('lead').last.sequence);
+ expect(c.unread(c.selected!), isFalse);
+ await c.flush();
+ c.dispose();
+ },
+ );
+}
diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dart
new file mode 100644
index 000000000..fafe2a3f4
--- /dev/null
+++ b/desktop/test/super_tab_controller_test.dart
@@ -0,0 +1,285 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ test('terminal selections survive reopening and cannot cross accounts or group membership', () async {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'worker',
+ 'name': 'Worker',
+ 'machineId': 'm',
+ 'harnessId': 'native',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ (server.state['conversations'] as List)[1]['agentIds'] = ['worker'];
+ final first = server.controller();
+ await first.refresh();
+ first.selectTerminal('offline', 'worker');
+ first.selectTerminal('lead', 'worker');
+ expect(first.terminalAgent('lead'), isNull);
+ await first.flush();
+ first.dispose();
+ final restored = server.controller(initial: server.saved);
+ await restored.refresh();
+ expect(restored.terminalAgent('offline')?.id, 'worker');
+ final other = server.controller(initial: server.saved, account: 'other');
+ await other.refresh();
+ expect(other.terminalAgent('offline'), isNull);
+ other.dispose();
+ (server.state['conversations'] as List)[1]['agentIds'] = <String>[];
+ await restored.refresh();
+ expect(restored.terminalAgent('offline'), isNull);
+ restored.dispose();
+ });
+ test(
+ 'mentions keep stable agent identities through rename, reopen and deletion',
+ () async {
+ final server = ConversationServer();
+ (server.state['conversations'] as List)[0]['agentIds'] = ['worker-1'];
+ final first = server.controller();
+ await first.refresh();
+ first.setDraft('lead', '@Worker 1 review this.');
+ first.mention('lead', 'worker-1', '@Worker 1');
+ await first.flush();
+ first.dispose();
+ final reopened = server.controller(initial: server.saved);
+ await reopened.refresh();
+ await reopened.send();
+ expect((server.posts.single['command'] as Map)['recipientIds'], [
+ 'worker-1',
+ ]);
+ reopened.setDraft('lead', '@Worker 1 again');
+ reopened.mention('lead', 'worker-1', '@Worker 1');
+ reopened.setDraft('lead', '@Worker 10 again');
+ expect(reopened.mentions('lead'), isEmpty);
+ reopened.setDraft('lead', '@Worker 1 check');
+ reopened.mention('lead', 'worker-1', '@Worker 1');
+ (server.state['conversations'] as List)[0]['agentIds'] = <String>[];
+ await reopened.refresh();
+ expect(await reopened.send(), isNull);
+ expect(server.posts, hasLength(1));
+ expect(reopened.operationError, contains('no longer'));
+ await reopened.flush();
+ reopened.dispose();
+ },
+ );
+ Future<SuperTabController> open(ConversationServer server) async {
+ final controller = server.controller();
+ addTearDown(() async {
+ await controller.flush();
+ controller.dispose();
+ });
+ await controller.refresh();
+ return controller;
+ }
+
+ test(
+ 'new groups and incoming activity preserve personal selection and drafts',
+ () async {
+ final server = ConversationServer();
+ final controller = await open(server);
+ controller.setDraft('lead', 'Architecture notes');
+ controller.select('offline');
+ controller.setDraft('offline', 'Keep local changes');
+ server.append('Another person answered.');
+ (server.state['conversations'] as List).add(
+ conversationFixture('onboarding', 'Onboarding'),
+ );
+ await controller.refresh();
+ expect(controller.selectedId, 'offline');
+ expect(controller.draft('offline'), 'Keep local changes');
+ expect(controller.draft('lead'), 'Architecture notes');
+ expect(
+ controller.unread(controller.snapshot!.conversation('lead')!),
+ isTrue,
+ );
+ controller.markRead('lead');
+ expect(
+ controller.unread(controller.snapshot!.conversation('lead')!),
+ isFalse,
+ );
+ },
+ );
+
+ test(
+ 'a lost send reply reuses its durable receipt after closing and reopening',
+ () async {
+ final server = ConversationServer()..loseReply = true;
+ final first = server.controller();
+ await first.refresh();
+ first.setDraft('lead', 'Build the agreed plan.');
+ expect(await first.send(), isNull);
+ expect(server.messages, hasLength(1));
+ expect(first.hasPendingAction, isTrue);
+ expect(first.draft('lead'), 'Build the agreed plan.');
+ await first.flush();
+ first.dispose();
+ final reopened = server.controller(initial: server.saved);
+ addTearDown(() async {
+ await reopened.flush();
+ reopened.dispose();
+ });
+ await reopened.refresh();
+ await reopened.retry();
+ expect(server.posts[0]['operationId'], server.posts[1]['operationId']);
+ expect(server.messages, hasLength(1));
+ expect(reopened.hasPendingAction, isFalse);
+ expect(reopened.draft('lead'), isEmpty);
+ expect(server.saved!.containsKey('pending'), isFalse);
+ },
+ );
+
+ test('typing a new draft during a send does not let the acknowledgement erase it', () async {
+ final server = ConversationServer();
+ final waiting = Completer<void>();
+ final controller = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ save: server.save,
+ pollInterval: Duration.zero,
+ request: (method, path, {body}) async {
+ if (method == 'POST') await waiting.future;
+ return server.request(method, path, body: body);
+ },
+ );
+ addTearDown(() async {
+ await controller.flush();
+ controller.dispose();
+ });
+ await controller.refresh();
+ controller.setDraft('lead', 'First message');
+ final sending = controller.send();
+ await Future<void>.delayed(Duration.zero);
+ controller.setDraft('lead', 'Second message');
+ waiting.complete();
+ await sending;
+ expect(controller.draft('lead'), 'Second message');
+ expect(server.messages.single['text'], 'First message');
+ });
+
+ test('a failed local receipt save cannot send and a definitive server rejection keeps an editable draft', () async {
+ final server = ConversationServer();
+ final controller = await open(server);
+ controller.setDraft('lead', 'Hold this draft');
+ server.failSave = true;
+ await controller.send();
+ expect(server.posts, isEmpty);
+ server.failSave = false;
+ server.reject = true;
+ await controller.retry();
+ expect(controller.hasPendingAction, isFalse);
+ expect(controller.draft('lead'), 'Hold this draft');
+ server.reject = false;
+ await controller.send();
+ expect(server.messages, hasLength(1));
+ });
+
+ test(
+ 'reconnecting after more than a page of messages fills the gap in order',
+ () async {
+ final server = ConversationServer()..append('First');
+ final controller = await open(server);
+ for (var i = 0; i < 250; i++) {
+ server.append('Message $i');
+ }
+ for (var i = 0; i < 3; i++) {
+ await controller.refresh();
+ }
+ expect(controller.messages('lead'), hasLength(251));
+ expect(
+ controller.messages('lead').map((m) => m.sequence),
+ List.generate(251, (i) => i + 1),
+ );
+ },
+ );
+
+ test('drafts and pending sends cannot cross accounts', () async {
+ final server = ConversationServer()..loseReply = true;
+ final first = await open(server);
+ first.setDraft('lead', 'Private draft');
+ await first.send();
+ await first.flush();
+ final other = server.controller(initial: server.saved, account: 'other');
+ addTearDown(other.dispose);
+ expect(other.draft('lead'), isEmpty);
+ expect(other.hasPendingAction, isFalse);
+ });
+
+ test(
+ 'a confirmed new group cannot send into the old group when its read fails',
+ () async {
+ final server = ConversationServer();
+ final controller = await open(server);
+ controller.setDraft('lead', 'Keep this in Lead');
+ server.failReads = true;
+ final result = await controller.command({
+ 'type': 'conversation.create',
+ 'title': 'New feature',
+ 'brief': '',
+ 'checks': <dynamic>[],
+ });
+ expect(controller.selectedId, result!['conversationId']);
+ expect(controller.selected, isNull);
+ controller.setDraft(controller.selectedId, 'Work here');
+ expect(await controller.send(), isNull);
+ expect(server.messages, isEmpty);
+ server.failReads = false;
+ await controller.refresh();
+ await controller.send();
+ expect(
+ server.messages.single['conversationId'],
+ result['conversationId'],
+ );
+ expect(controller.draft('lead'), 'Keep this in Lead');
+ },
+ );
+
+ test('viewers cannot send messages but can leave', () async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'viewer'},
+ ];
+ final controller = await open(server);
+ controller.setDraft('lead', 'Cannot send');
+ expect(await controller.send(), isNull);
+ expect(server.posts, isEmpty);
+ await controller.command({'type': 'member.remove', 'userId': 'owner'});
+ expect((server.posts.single['command'] as Map)['type'], 'member.remove');
+ });
+
+ test('revocation hides cached transcripts and a late response cannot restore them', () async {
+ final server = ConversationServer()..append('Shared history');
+ var revoked = false;
+ final controller = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ save: server.save,
+ pollInterval: Duration.zero,
+ request: (method, path, {body}) async {
+ if (revoked) {
+ throw const SuperTabFailure(
+ 'FORBIDDEN',
+ 'You no longer have access.',
+ statusCode: 403,
+ );
+ }
+ return server.request(method, path, body: body);
+ },
+ );
+ addTearDown(controller.dispose);
+ await controller.refresh();
+ expect(controller.messages('lead'), hasLength(1));
+ revoked = true;
+ await controller.refresh();
+ expect(controller.snapshot, isNull);
+ expect(controller.messages('lead'), isEmpty);
+ expect(controller.canWrite, isFalse);
+ });
+}
diff --git a/desktop/test/super_tab_delivery_test.dart b/desktop/test/super_tab_delivery_test.dart
new file mode 100644
index 000000000..fbeb48411
--- /dev/null
+++ b/desktop/test/super_tab_delivery_test.dart
@@ -0,0 +1,229 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.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 'package:harness/super_tabs/workspace.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ final capture = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];
+ setUpAll(() async {
+ if (capture == null || !Platform.isMacOS) return;
+ final bytes = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+ for (final profile in [
+ (
+ name: 'dark',
+ brightness: Brightness.dark,
+ size: const Size(1280, 800),
+ scale: 1.0,
+ ),
+ (
+ name: 'light',
+ brightness: Brightness.light,
+ size: const Size(1280, 800),
+ scale: 1.0,
+ ),
+ (
+ name: 'large',
+ brightness: Brightness.dark,
+ size: const Size(800, 480),
+ scale: 2.0,
+ ),
+ ]) {
+ testWidgets(
+ 'uncertain input requires an explicit human choice in ${profile.name} appearance',
+ (tester) async {
+ await tester.binding.setSurfaceSize(profile.size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = profile.brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ 'machineId': 'm',
+ 'harnessId': 'native',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ (server.state['people'] as List).addAll(
+ List.generate(
+ 19,
+ (i) => {
+ 'id': 'person-$i',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ },
+ ),
+ );
+ (server.state['conversations'] as List).add(
+ conversationFixture('onboarding', 'Onboarding'),
+ );
+ (server.state['conversations'] as List)[0]['agentIds'] = ['lead-agent'];
+ (server.state['conversations'] as List)[0]['leadId'] = 'lead-agent';
+ server.append(
+ 'Let’s agree on the offline editing behavior before building.',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ server.append(
+ 'Keep changes on the device and sync when the connection returns.',
+ );
+ server.messages.last['deliveries'] = [
+ {'id': 'delivery', 'agentId': 'lead-agent', 'status': 'uncertain'},
+ ];
+ final controller = server.controller();
+ await controller.refresh();
+ String? opened;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: profile.brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(profile.scale),
+ highContrast: profile.scale > 1,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => SuperTabView(
+ controller: controller,
+ onInvite: () => showSuperTabPeople(context, controller),
+ onAddAgent: (_) {},
+ onOpenTerminal: (agent) => opened = agent.id,
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ Future<void> shot(String name) async {
+ if (capture == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(capture).create(recursive: true);
+ await File('$capture/${profile.name}-$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+
+ await shot('conversation');
+ await tester.tap(find.byTooltip('1 agent · 20 people'));
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<EditableText>(
+ find
+ .descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(EditableText),
+ )
+ .first,
+ )
+ .focusNode
+ .hasFocus,
+ isTrue,
+ );
+ await shot('people');
+ await tester.tap(find.byTooltip('Close participants'));
+ await tester.pumpAndSettle();
+ if (find.byTooltip('Conversations').evaluate().isNotEmpty) {
+ await tester.tap(find.byTooltip('Conversations'));
+ await tester.pumpAndSettle();
+ }
+ await tester.tap(find.text('Invite'));
+ await tester.pumpAndSettle();
+ expect(
+ tester
+ .widget<EditableText>(
+ find
+ .descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(EditableText),
+ )
+ .first,
+ )
+ .focusNode
+ .hasFocus,
+ isTrue,
+ );
+ await shot('invite');
+ expect(tester.takeException(), isNull);
+ await tester.tap(find.byTooltip('Close'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Check delivery to Lead'));
+ await tester.pumpAndSettle();
+ await shot('delivery');
+ expect(server.posts, isEmpty);
+ await tester.tap(find.text('Open terminal'));
+ await tester.pumpAndSettle();
+ expect(opened, 'lead-agent');
+ expect(server.posts, isEmpty);
+ await tester.tap(find.text('Check delivery to Lead'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Already received'));
+ await tester.pumpAndSettle();
+ expect((server.posts.single['command'] as Map), {
+ 'type': 'delivery.resolve',
+ 'deliveryId': 'delivery',
+ 'resolution': 'received',
+ });
+ expect(
+ server.messages,
+ hasLength(2),
+ reason:
+ 'Confirmation does not submit the original instruction again.',
+ );
+ await tester.tap(find.text('Check delivery to Lead'));
+ await tester.pumpAndSettle();
+ controller.revokeAccess('Access removed.');
+ await tester.pumpAndSettle();
+ expect(find.byType(SelectableText), findsNothing);
+ expect(find.text('Send again'), findsNothing);
+ expect(server.posts, hasLength(1));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+ }
+}
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
new file mode 100644
index 000000000..6f23cd9b9
--- /dev/null
+++ b/desktop/test/super_tab_launch_test.dart
@@ -0,0 +1,525 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/state/app_state.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/harness_attachments.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/super_tabs/launch.dart';
+import 'package:harness/super_tabs/client.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show createApp, MemoryStore;
+
+const tabId = '0123456789abcdef01234567';
+
+class SuperTabFixtureConnection extends WsConn {
+ SuperTabFixtureConnection(this.store)
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ ) {
+ server.state['id'] = tabId;
+ }
+ final MemoryStore store;
+ final server = ConversationServer();
+ final calls = <(String, Map<String, dynamic>)>[];
+ final joins = <Map<String, dynamic>>[];
+ bool loseCreate = false, loseJoin = false;
+ bool failNative = false;
+ bool nativeSurface = false;
+ bool failFiles = false, failCreation = false, changeAccountOnUpload = false;
+ late AppNotifier app;
+ final sentFiles = <Uint8List>[];
+ final terminalCalls = <(String, Map<String, dynamic>)>[];
+ static const streamId = '00112233-4455-6677-8899-aabbccddeeff';
+ Map<String, dynamic>? native;
+
+ Future<void> event(String type, Map<String, dynamic> payload) =>
+ app.handleMachineEventForTest('m', {'type': type, 'payload': payload});
+
+ @override
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ terminalCalls.add((type, Map.of(payload)));
+ if (type == 'terminal_open') {
+ await event('terminal_ready', {
+ 'requestId': payload['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': streamId,
+ 'agentId': 'native-lead',
+ });
+ await app.handleTerminalBinaryForTest(
+ 'm',
+ encodeTerminalLocal(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: streamId,
+ seq: 0,
+ bytes: Uint8List.fromList(utf8.encode('›\r\n? for shortcuts')),
+ compressed: false,
+ cols: 100,
+ rows: 30,
+ ),
+ )!,
+ );
+ }
+ if (type == 'terminal_chunked_upload_begin') {
+ if (changeAccountOnUpload) {
+ app.currentUser = const CurrentUserProfile(
+ id: 'different',
+ email: '[email protected]',
+ );
+ return false;
+ }
+ await event('terminal_chunked_upload_begin_result', {
+ 'streamId': streamId,
+ 'accepted': !failFiles,
+ });
+ }
+ return true;
+ }
+
+ @override
+ Future<bool> sendTerminalBinary(Uint8List raw) async {
+ final frame = decodeTerminalLocal(raw)!;
+ if (frame.kind == TerminalBinaryKind.pasteFile) {
+ sentFiles.add(frame.bytes);
+ await event('terminal_paste_file_result', {
+ 'streamId': streamId,
+ 'path': '/fixture/design.png',
+ });
+ }
+ return true;
+ }
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ calls.add((type, Map.of(payload)));
+ if (nativeSurface && type == 'terminal_capabilities') {
+ return {'protocolVersion': 3, 'backend': 'tmux', 'available': true};
+ }
+ if (nativeSurface && type == 'agents_list') {
+ return {
+ 'agents': [if (native != null) native],
+ };
+ }
+ if (type == 'super_tabs') {
+ if (payload['action'] == 'wake') return {'ok': true};
+ if (payload['action'] == 'prepareNative' ||
+ payload['action'] == 'renewNative') {
+ return failNative
+ ? {
+ 'error': 'NATIVE_UNAVAILABLE',
+ 'detail': 'Fixture recording unavailable.',
+ }
+ : {'ok': true, 'inputContext': payload['contextId']};
+ }
+ if (payload['method'] == 'POST' &&
+ (payload['path'] as String?)?.endsWith('/native') == true) {
+ return {
+ 'ok': true,
+ 'value': {'contextId': (payload['body'] as Map)['operationId']},
+ };
+ }
+ if (payload['path'] == '/api/super-tabs' && payload['method'] == 'POST') {
+ return {
+ 'ok': true,
+ 'value': {'id': tabId, 'revision': 0},
+ };
+ }
+ final body = payload['body'] as Map<String, dynamic>?;
+ if (body?['command'] case final Map command
+ when command['type'] == 'agent.add') {
+ joins.add(Map<String, dynamic>.from(body!));
+ if (!server.receipts.containsKey(body['operationId'])) {
+ (server.state['agents'] as List).add({
+ 'id': 'lead-agent',
+ 'machineId': 'm',
+ 'harnessId': command['harnessId'],
+ 'name': 'Lead',
+ 'contributorId': 'owner',
+ 'configuration': command['configuration'],
+ });
+ if (command['initialMessage'] is String) {
+ server.append(command['initialMessage'] as String);
+ }
+ }
+ }
+ final value = await server.request(
+ payload['method'] as String,
+ payload['path'] as String,
+ body: body,
+ );
+ if (loseJoin &&
+ body?['command'] is Map &&
+ (body!['command'] as Map)['type'] == 'agent.add') {
+ loseJoin = false;
+ throw StateError('Lost the join reply after committing');
+ }
+ return {'ok': true, 'value': value};
+ }
+ if (type == 'agent_create') {
+ final records = store.values.entries.where(
+ (e) => e.key.startsWith('super_tab.launch.'),
+ );
+ expect(records, hasLength(1));
+ final saved = jsonDecode(records.single.value) as Map;
+ expect(saved['phase'], 'starting');
+ expect(saved['creationId'], payload['creationId']);
+ native = {
+ 'id': 'native-lead',
+ 'name': 'Lead',
+ 'engine': payload['engine'],
+ 'terminal': {'available': true},
+ 'project': {'cwd': '/work/project', 'label': 'Project'},
+ };
+ if (loseCreate) {
+ loseCreate = false;
+ throw TimeoutException('Lost launch reply');
+ }
+ }
+ if (type == 'agent_create' || type == 'agent_create_status') {
+ if (failCreation) {
+ return {
+ 'creationId': payload['creationId'],
+ 'state': 'failed',
+ 'failure': {'detail': 'Fixture engine unavailable'},
+ };
+ }
+ return {
+ 'creationId': payload['creationId'],
+ 'state': native == null ? 'missing' : 'created',
+ 'agent': native,
+ };
+ }
+ return switch (type) {
+ 'git_project_info' => {'isGit': false, 'refreshed': true},
+ 'engines_probe' => {
+ 'engines': [
+ {'engine': 'codex', 'installed': true, 'supportsCodexHome': true},
+ {'engine': 'claude', 'installed': true},
+ ],
+ },
+ 'codex_profiles_list' => {'profiles': <dynamic>[]},
+ 'dsh_list' => {'dsh': <dynamic>[]},
+ 'fs_list_dir' => {'path': '/work/project', 'entries': <dynamic>[]},
+ _ => {},
+ };
+ }
+}
+
+class SuperTabLaunchFixture {
+ SuperTabLaunchFixture() {
+ connection = SuperTabFixtureConnection(store);
+ app = createApp(
+ store: store,
+ connectionForTest: (_) => connection,
+ connected: true,
+ );
+ app.machineStates['m']!
+ ..localOnly = true
+ ..terminalPasteFileAvailable = true
+ ..terminalPasteRawAvailable = true
+ ..agents = [];
+ connection.app = app;
+ app.gitProjectReaderForTest = (_, _) async => {
+ 'isGit': false,
+ 'refreshed': true,
+ };
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ app.markSuperTabDraft(app.activeSwarmId);
+ addTearDown(app.dispose);
+ }
+ final store = MemoryStore();
+ late final AppNotifier app;
+ late final SuperTabFixtureConnection connection;
+
+ Future<NewHarnessController> box({
+ String engine = 'codex',
+ HarnessAttachments? attachments,
+ }) async {
+ final integration = await SuperTabLaunch.open(app, app.activeSwarm, 'lead');
+ final box = NewHarnessController(
+ app,
+ machineId: 'm',
+ engine: engine,
+ folder: '/work/project',
+ task: 'Discuss the architecture.',
+ integration: integration,
+ attachments: attachments,
+ );
+ addTearDown(box.dispose);
+ await Future<void>.delayed(Duration.zero);
+ return box;
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ test('switching accounts while files are being sent closes the background writer', () async {
+ final f = SuperTabLaunchFixture()..connection.changeAccountOnUpload = true;
+ final files = HarnessAttachments()
+ ..add([
+ HarnessAttachment('design.png', Uint8List.fromList([1])),
+ ]);
+ final box = await f.box(engine: 'claude', attachments: files);
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.error, contains('account changed'));
+ expect(f.connection.sentFiles, isEmpty);
+ expect(f.connection.terminalCalls.where((c) => c.$1 == 'message'), isEmpty);
+ expect(
+ f.connection.terminalCalls.where((c) => c.$1 == 'terminal_close'),
+ hasLength(1),
+ );
+ });
+
+ test('a confirmed failed creation makes a reopened form editable', () async {
+ final f = SuperTabLaunchFixture()..connection.loseCreate = true;
+ expect(await (await f.box()).create(), NewHarnessOutcome.failed);
+ f.connection.failCreation = true;
+ final recovered = await f.box();
+ expect(await recovered.create(), NewHarnessOutcome.failed);
+ expect(recovered.error, contains('Fixture engine unavailable'));
+ expect(recovered.checking, isFalse);
+ f.connection.failCreation = false;
+ expect(
+ await recovered.create(),
+ NewHarnessOutcome.created,
+ reason: recovered.error,
+ );
+ });
+
+ test(
+ 'account changes clear an already open conversation synchronously',
+ () async {
+ final server = ConversationServer()
+ ..append('Only the first account can see this.');
+ final client = SuperTabClient(
+ storage: MemoryStore(),
+ transport: server.request,
+ )..bind('owner');
+ addTearDown(client.dispose);
+ final controller = await client.open('tab');
+ await controller.refresh();
+ expect(controller.messages('lead'), hasLength(1));
+ client.bind('different');
+ expect(controller.snapshot, isNull);
+ expect(controller.messages('lead'), isEmpty);
+ expect(controller.canWrite, isFalse);
+ },
+ );
+ for (final engine in ['claude', 'codex']) {
+ test(
+ '$engine files reach the background harness before its first request without creating a pane',
+ () async {
+ final f = SuperTabLaunchFixture();
+ final files = HarnessAttachments()
+ ..add([
+ HarnessAttachment('design.png', Uint8List.fromList([1, 2, 3])),
+ ]);
+ final box = await f.box(engine: engine, attachments: files);
+ expect(
+ await box.create(),
+ NewHarnessOutcome.created,
+ reason: box.error,
+ );
+ expect(f.connection.sentFiles.single, [1, 2, 3]);
+ expect(
+ f.connection.calls
+ .firstWhere((c) => c.$1 == 'agent_create')
+ .$2['prompt'],
+ isNull,
+ );
+ expect(
+ f.connection.terminalCalls
+ .singleWhere((c) => c.$1 == 'message')
+ .$2['content'],
+ contains('Discuss the architecture.'),
+ );
+ expect(f.connection.terminalCalls.last.$1, 'terminal_close');
+ expect(f.app.activeSwarm.panes, isEmpty);
+ expect(
+ f.store.values.keys.where(
+ (key) => key.startsWith('super_tab.launch.'),
+ ),
+ isEmpty,
+ );
+ },
+ );
+ }
+
+ test('a reopened launch retains its staged files and never launches another harness', () async {
+ final f = SuperTabLaunchFixture()..connection.loseCreate = true;
+ final files = HarnessAttachments()
+ ..add([
+ HarnessAttachment('design.png', Uint8List.fromList([9, 8])),
+ ]);
+ final first = await f.box(engine: 'claude', attachments: files);
+ expect(await first.create(), NewHarnessOutcome.failed);
+ final recovered = await f.box();
+ // The inventory arrives independently of the lost creation response.
+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];
+ expect(
+ await recovered.create(),
+ NewHarnessOutcome.created,
+ reason: recovered.error,
+ );
+ expect(f.connection.sentFiles.single, [9, 8]);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ });
+
+ test('uncertain files are kept for recovery and never pasted again automatically', () async {
+ final f = SuperTabLaunchFixture()..connection.failFiles = true;
+ final files = HarnessAttachments()
+ ..add([
+ HarnessAttachment('design.png', Uint8List.fromList([1])),
+ ]);
+ final first = await f.box(engine: 'claude', attachments: files);
+ expect(await first.create(), NewHarnessOutcome.failed);
+ f.connection.failFiles = false;
+ final recovered = await f.box();
+ expect(await recovered.create(), NewHarnessOutcome.failed);
+ expect(recovered.error, contains('file delivery was interrupted'));
+ expect(
+ f.connection.terminalCalls.where(
+ (c) => c.$1 == 'terminal_chunked_upload_begin',
+ ),
+ hasLength(1),
+ );
+ expect(f.connection.sentFiles, isEmpty);
+ expect(
+ f.store.values.keys.where((key) => key.startsWith('super_tab.launch.')),
+ hasLength(1),
+ );
+ expect(recovered.needsAttachmentReview, isTrue);
+ expect(
+ await recovered.create(resendAttachments: true),
+ NewHarnessOutcome.created,
+ reason: recovered.error,
+ );
+ expect(f.connection.sentFiles.single, [1]);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ });
+ for (final engine in ['codex', 'claude']) {
+ test(
+ '$engine lead uses the native form and joins without opening a terminal or another tab',
+ () async {
+ final f = SuperTabLaunchFixture(), initialTab = f.app.activeSwarmId;
+ final box = await f.box(engine: engine);
+ expect(box.actionLabel, 'New Super Tab');
+ expect(
+ await box.create(),
+ NewHarnessOutcome.created,
+ reason: box.error,
+ );
+ final creates = f.connection.calls.where((c) => c.$1 == 'agent_create');
+ expect(creates, hasLength(1));
+ expect(creates.single.$2['engine'], engine);
+ expect(
+ creates.single.$2['prompt'],
+ contains('Discuss the architecture.'),
+ );
+ expect(
+ creates.single.$2['prompt'],
+ contains('harness super-tab --tab $tabId'),
+ );
+ expect(f.app.swarms, hasLength(1));
+ expect(f.app.activeSwarmId, initialTab);
+ expect(f.app.activeSwarm.superTabId, tabId);
+ expect(f.app.activeSwarm.panes, isEmpty);
+ expect(
+ f.connection.server.messages.single['text'],
+ 'Discuss the architecture.',
+ );
+ },
+ );
+ }
+
+ test('lost join acknowledgement retries the same contribution without a second native launch', () async {
+ final f = SuperTabLaunchFixture()..connection.loseJoin = true;
+ final box = await f.box();
+ expect(await box.create(), NewHarnessOutcome.failed);
+ expect(box.checking, isTrue);
+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ expect(f.connection.joins, hasLength(2));
+ expect(f.connection.joins[0], f.connection.joins[1]);
+ expect(f.connection.server.messages, hasLength(1));
+ });
+
+ test(
+ 'reopening after a lost native launch reply only checks its saved receipt',
+ () async {
+ final f = SuperTabLaunchFixture()..connection.loseCreate = true;
+ final first = await f.box();
+ expect(await first.create(), NewHarnessOutcome.failed);
+ final reopened = await f.box(engine: 'claude');
+ expect(reopened.checking, isTrue);
+ expect(
+ await reopened.create(),
+ NewHarnessOutcome.created,
+ reason: reopened.error,
+ );
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ expect(
+ f.connection.calls.where((c) => c.$1 == 'agent_create_status'),
+ hasLength(1),
+ );
+ expect(
+ (f.connection.joins.single['command']
+ as Map)['configuration']['engine'],
+ 'codex',
+ );
+ },
+ );
+
+ test(
+ 'late account responses cannot open a previous account’s conversation',
+ () async {
+ final response = Completer<Object?>();
+ final client = SuperTabClient(
+ storage: MemoryStore(),
+ transport: (_, _, {body}) => response.future,
+ )..bind('first');
+ addTearDown(client.dispose);
+ final pending = client.request('GET', '/api/super-tabs');
+ client.bind('second');
+ response.complete({'tabs': []});
+ await expectLater(
+ pending,
+ throwsA(predicate((e) => e.toString().contains('account changed'))),
+ );
+ },
+ );
+}
diff --git a/desktop/test/super_tab_native_messages_test.dart b/desktop/test/super_tab_native_messages_test.dart
new file mode 100644
index 000000000..6de9f2aeb
--- /dev/null
+++ b/desktop/test/super_tab_native_messages_test.dart
@@ -0,0 +1,237 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.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 'support/super_tab_fixture.dart';
+
+void main() {
+ final capture = Platform.environment['HARNESS_SUPER_TAB_CAPTURE'];
+ setUpAll(() async {
+ if (capture == null || !Platform.isMacOS) return;
+ final bytes = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(bytes))).load();
+ }
+ await (FontLoader(grid.AppType.monoFamily)
+ ..addFont(rootBundle.load('assets/fonts/roboto-mono/RobotoMono.ttf')))
+ .load();
+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(
+ rootBundle.load(
+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',
+ ),
+ ))
+ .load();
+ });
+ for (final profile in [
+ (
+ name: 'dark',
+ brightness: Brightness.dark,
+ size: const Size(1280, 800),
+ scale: 1.0,
+ ),
+ (
+ name: 'light',
+ brightness: Brightness.light,
+ size: const Size(1280, 800),
+ scale: 1.0,
+ ),
+ (
+ name: 'large',
+ brightness: Brightness.dark,
+ size: const Size(800, 480),
+ scale: 2.0,
+ ),
+ ]) {
+ testWidgets(
+ 'native message sources use the shared conversation style in ${profile.name}',
+ (tester) async {
+ await tester.binding.setSurfaceSize(profile.size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = profile.brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'leo',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ server.state['agents'] = [
+ {
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ 'machineId': 'm',
+ 'harnessId': 'native',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ for (final name in ['Builder', 'Reviewer'])
+ {
+ 'id': name.toLowerCase(),
+ 'name': name,
+ 'machineId': 'm',
+ 'harnessId': name.toLowerCase(),
+ 'contributorId': 'leo',
+ 'configuration': {
+ 'engine': name == 'Builder' ? 'codex' : 'claude',
+ },
+ },
+ ];
+ final group = (server.state['conversations'] as List)[1] as Map;
+ group['agentIds'] = ['lead-agent', 'builder', 'reviewer'];
+ group['leadId'] = 'lead-agent';
+ group['assignment'] = {
+ 'id': 'attempt',
+ 'agentId': 'builder',
+ 'status': 'needs_human',
+ 'result': 'Can someone verify offline editing on a real device?',
+ };
+ server.append(
+ 'Verify offline edits through a restart and reconnect.',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ server.messages.last['source'] = {
+ 'kind': 'native',
+ 'phase': 'prompt',
+ 'operator': {'id': 'leo', 'name': '[email protected]'},
+ };
+ if (profile.scale == 1) {
+ server.append(
+ '@Builder, check persistence. @Reviewer, check account switching.',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ server.messages.last['source'] = {
+ 'kind': 'native',
+ 'phase': 'answer',
+ };
+ server.append(
+ '**Checks passed**\n'
+ '- Restart preserves pending edits.\n'
+ '- Reconnect syncs once, including interrupted writes.\n\n'
+ '\u0060await queue.flush();\u0060',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'builder',
+ 'name': 'Builder',
+ };
+ server.append(
+ 'Should pending edits survive sign-out?',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'builder',
+ 'name': 'Builder',
+ };
+ final question = server.messages.last['id'];
+ server.append(
+ 'Yes. Keep them on the device; ask before syncing to another account.',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'leo',
+ 'name': 'Leo',
+ };
+ server.messages.last['replyTo'] = question;
+ server.append(
+ 'Can someone verify offline editing on a real device? The software checks passed.',
+ conversationId: 'offline',
+ );
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ }
+ final controller = server.controller(
+ initial: {
+ 'tabId': 'tab',
+ 'accountId': 'owner',
+ 'selectedId': 'offline',
+ },
+ );
+ await controller.refresh();
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: profile.brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(
+ textScaler: TextScaler.linear(profile.scale),
+ highContrast: profile.scale > 1,
+ ),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final source = find.text(
+ 'Terminal input · session opened by [email protected]',
+ );
+ expect(source, findsOneWidget);
+ await tester.ensureVisible(source);
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ if (capture != null) {
+ await tester.runAsync(
+ () => precacheImage(
+ const AssetImage('assets/engine-icons/codex.png'),
+ tester.element(find.byType(SuperTabView)),
+ ),
+ );
+ await tester.pump();
+ final render =
+ boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ await tester.runAsync(() async {
+ final image = await render.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(capture).create(recursive: true);
+ await File('$capture/native-${profile.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+ }
+}
diff --git a/desktop/test/super_tab_navigation_test.dart b/desktop/test/super_tab_navigation_test.dart
new file mode 100644
index 000000000..157a9f25e
--- /dev/null
+++ b/desktop/test/super_tab_navigation_test.dart
@@ -0,0 +1,180 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/swarm_navigation.dart';
+
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ test(
+ 'a successful recent open consumes only the empty Super Tab draft',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final draft = app.activeSwarm;
+ app.markSuperTabDraft(draft.id);
+ final row = swarmDestinations(app)
+ .singleWhere((row) => row.agentId == 'a0');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row),
+ destinationSwarmId: draft.id,
+ placement: HarnessPlacement.currentTab,
+ ),
+ isTrue,
+ );
+ expect(app.activeSwarm, same(draft));
+ expect(draft.isSuperTab, isFalse);
+ expect(draft.superTabId, isNull);
+ expect(draft.panes.single.agentId, 'a0');
+ expect(app.swarms, hasLength(1));
+ },
+ );
+
+ test('a disappeared recent result preserves the Super Tab draft', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final draft = app.activeSwarm;
+ app.markSuperTabDraft(draft.id);
+ final row = swarmDestinations(app)
+ .singleWhere((row) => row.agentId == 'a0');
+ app.machineStates['m']!.agents = [];
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row),
+ destinationSwarmId: draft.id,
+ placement: HarnessPlacement.currentTab,
+ ),
+ isFalse,
+ );
+ expect(draft.isSuperTab, isTrue);
+ expect(draft.panes, isEmpty);
+ expect(app.swarms, hasLength(1));
+ });
+
+ test('ordinary new-tab allocation never consumes a Super Tab draft', () {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final draft = app.activeSwarm;
+ app.markSuperTabDraft(draft.id);
+ app.newSwarm();
+ expect(app.activeSwarm, isNot(same(draft)));
+ expect(app.activeSwarm.isSuperTab, isFalse);
+ expect(draft.isSuperTab, isTrue);
+ });
+
+ for (final placement in [
+ null,
+ HarnessPlacement.currentTab,
+ HarnessPlacement.newTab,
+ ]) {
+ test(
+ 'ordinary search from a completed Super Tab uses its own canvas ($placement)',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final shared = app.activeSwarm;
+ app.bindSuperTab(shared.id, 'shared-tab', 'Pilot');
+ final row = swarmDestinations(app)
+ .singleWhere((row) => row.agentId == 'a0');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row),
+ destinationSwarmId: shared.id,
+ placement: placement,
+ ),
+ isTrue,
+ );
+ expect(shared.superTabId, 'shared-tab');
+ expect(shared.name, 'Pilot');
+ expect(shared.panes, isEmpty);
+ expect(app.activeSwarm.isSuperTab, isFalse);
+ expect(app.panes.single.agentId, 'a0');
+ },
+ );
+ }
+
+ test(
+ 'opening an existing view focuses it without consuming the draft',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ final original = app.activeSwarm;
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ app.newSwarm(newTabPage: true);
+ final draft = app.activeSwarm;
+ app.markSuperTabDraft(draft.id);
+ final row = swarmDestinations(app)
+ .singleWhere((row) => row.agentId == 'a0');
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ SwarmSearchSelection(row),
+ destinationSwarmId: draft.id,
+ ),
+ isTrue,
+ );
+ expect(app.activeSwarm, same(original));
+ expect(app.panes.single, same(pane));
+ expect(draft.isSuperTab, isTrue);
+ expect(draft.panes, isEmpty);
+ },
+ );
+
+ for (final placement in [
+ null,
+ HarnessPlacement.currentTab,
+ HarnessPlacement.newTab,
+ ]) {
+ for (final mode in ['group', 'add group', 'multiple', 'add one']) {
+ test(
+ 'search $mode leaves shared membership and its terminal intact ($placement)',
+ () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ app.machineStates['m']!.agents = app.machineStates['m']!.agents
+ .take(2)
+ .toList();
+ final shared = app.activeSwarm;
+ final pane = app.adoptSessionForTest(terminal('a0', []));
+ app.bindSuperTab(shared.id, 'shared-tab', 'Pilot');
+ final catalog = SwarmSearchCatalog().read(app, []);
+ final group = catalog.singleWhere((row) => row.isMachine);
+ final agents = catalog.where((row) => row.agentId != null).toList();
+ final selection = switch (mode) {
+ 'group' => SwarmSearchSelection(group),
+ 'add group' => SwarmSearchSelection(
+ group,
+ SwarmSearchAction.addHere,
+ ),
+ 'multiple' => SwarmSearchSelection.multiple(agents),
+ _ => SwarmSearchSelection(
+ agents.singleWhere((row) => row.agentId == 'a1'),
+ SwarmSearchAction.addHere,
+ ),
+ };
+ expect(
+ await activateSwarmSearchSelection(
+ app,
+ selection,
+ destinationSwarmId: shared.id,
+ placement: placement,
+ ),
+ isTrue,
+ );
+ expect(shared.superTabId, 'shared-tab');
+ expect(shared.name, 'Pilot');
+ expect(shared.panes, [pane]);
+ expect(app.activeSwarm.isSuperTab, isFalse);
+ expect(
+ app.panes.map((pane) => pane.agentId).toSet(),
+ mode == 'add one' ? {'a1'} : {'a0', 'a1'},
+ );
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dart
new file mode 100644
index 000000000..0b6e185fa
--- /dev/null
+++ b/desktop/test/super_tab_picker_test.dart
@@ -0,0 +1,346 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/screens/swarm_screen.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shortcuts/app_keymap.dart';
+import 'package:harness/state/harness_placement.dart';
+import 'package:harness/state/new_harness.dart';
+import 'package:harness/state/swarm_catalog.dart';
+import 'package:harness/widgets/new_harness_form.dart';
+import 'package:harness/widgets/swarm_switcher.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+void main() {
+ setUpAll(() async {
+ if (Platform.environment['SUPER_TAB_PICKER_SHOTS'] != null) {
+ await loadPreviewFonts();
+ }
+ });
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final picture = GlobalKey();
+
+ Future<SuperTabLaunchFixture> open(
+ WidgetTester tester, {
+ Size size = const Size(1280, 800),
+ Brightness brightness = Brightness.dark,
+ double scale = 1,
+ }) async {
+ final oldEntry = newHarnessOpensInBox;
+ newHarnessOpensInBox = true;
+ addTearDown(() => newHarnessOpensInBox = oldEntry);
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ f.connection.server.state['agents'] = <dynamic>[
+ {
+ 'id': 'remote-agent',
+ 'name': 'Teammate builder',
+ 'machineId': 'teammate-machine',
+ 'harnessId': 'teammate-session',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ f.app.machineStates['m']!.agents = [
+ const Agent(
+ id: 'local-agent',
+ name: 'Local builder',
+ engine: 'codex',
+ terminalAvailable: true,
+ ),
+ const Agent(
+ id: 'stopped',
+ name: 'Stopped builder',
+ engine: 'codex',
+ terminalAvailable: false,
+ ),
+ const Agent(
+ id: 'shell',
+ name: 'Plain shell',
+ engine: 'terminal',
+ terminalAvailable: true,
+ ),
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ c.select('offline');
+ await f.app.agentPreference.remember('codex');
+ await f.app.projectHistory.select('m', '/work/project');
+ final map = MemoryKeymap();
+ addTearDown(map.dispose);
+ final projects = SwarmProjectStore();
+ addTearDown(projects.dispose);
+ tester.view.devicePixelRatio = 1;
+ tester.view.physicalSize = size;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ final oldBrightness = grid.AppTheme.brightness.value;
+ final oldPalette = grid.AppTheme.palette.value;
+ grid.AppTheme.brightness.value = brightness;
+ grid.AppTheme.palette.value = grid.AppTheme.paletteFor(brightness);
+ addTearDown(() {
+ grid.AppTheme.brightness.value = oldBrightness;
+ grid.AppTheme.palette.value = oldPalette;
+ });
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: picture,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => KeymapProvider(
+ keymap: map,
+ child: MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ ),
+ home: SwarmScreen(
+ notifier: f.app,
+ nativeTabs: false,
+ projectStore: projects,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.byTooltip('0 agents · 1 person'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Add agent'));
+ await tester.pumpAndSettle();
+ return f;
+ }
+
+ for (final (name, brightness, size, scale) in [
+ ('dark', Brightness.dark, const Size(1280, 800), 1.0),
+ ('light', Brightness.light, const Size(1280, 800), 1.0),
+ ('large', Brightness.dark, const Size(800, 480), 2.0),
+ ]) {
+ testWidgets('Add agent fits the app at $name', (tester) async {
+ final f = await open(
+ tester,
+ size: size,
+ brightness: brightness,
+ scale: scale,
+ );
+ await tester.enterText(input, 'Teammate builder');
+ await tester.pumpAndSettle();
+ expect(find.text('Add agent to Offline editing'), findsOneWidget);
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ final results = find.byType(SwarmSearchResults);
+ expect(
+ tester.widget<SwarmSearchResults>(results).search.hasPreview,
+ isFalse,
+ );
+ final chosenName = find.descendant(
+ of: results,
+ matching: find.text('Teammate builder'),
+ );
+ expect(chosenName, findsOneWidget);
+ final viewport = tester.getRect(results);
+ final label = tester.getRect(chosenName);
+ expect(label.top, greaterThanOrEqualTo(viewport.top));
+ expect(label.bottom, lessThanOrEqualTo(viewport.bottom));
+ expect(tester.takeException(), isNull);
+ final directory = Platform.environment['SUPER_TAB_PICKER_SHOTS'];
+ if (directory != null) {
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(directory).create(recursive: true);
+ await File('$directory/$name.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.pumpWidget(const SizedBox());
+ await f.app.superTabs.peek(tabId)!.flush();
+ f.app.superTabs.dispose();
+ });
+ }
+
+ testWidgets(
+ 'Add agent names its group and reuses a teammate agent without machine access or another pane',
+ (tester) async {
+ final f = await open(tester);
+ final shared = f.app.activeSwarm;
+ expect(find.text('Add agent to Offline editing'), findsOneWidget);
+ expect(find.text('Shared with everyone in Pilot.'), findsOneWidget);
+ expect(find.text('Models'), findsNothing);
+ expect(find.text('Store'), findsNothing);
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final remote = search.rows.singleWhere(
+ (row) => row.agentId == 'teammate-session',
+ );
+ expect(remote.isAgentChoice, isFalse);
+ expect(search.canSubmit(remote), isTrue);
+ expect(search.actionLabel(remote), 'Add agent');
+ expect(search.rows.where((row) => row.agentId == 'stopped'), isEmpty);
+ expect(
+ search.canSubmit(
+ search.rows.singleWhere((row) => row.agentId == 'shell'),
+ ),
+ isFalse,
+ );
+ expect(search.selected?.isCreate, isFalse);
+ expect(f.app.stateOf('teammate-machine'), isNull);
+ // Navigation underneath an open picker cannot change its contribution target.
+ f.app.superTabs.peek(tabId)!.select('lead');
+ await tester.enterText(input, 'Teammate builder');
+ await tester.pumpAndSettle();
+ await tester.tap(find.widgetWithText(FilledButton, 'Add agent'));
+ await tester.pumpAndSettle();
+ expect(f.connection.server.posts.last['command'], {
+ 'type': 'conversation.agent',
+ 'conversationId': 'offline',
+ 'agentId': 'remote-agent',
+ 'present': true,
+ 'lead': false,
+ });
+ expect(f.app.activeSwarm, same(shared));
+ expect(shared.panes, isEmpty);
+ expect(
+ f.connection.calls.where((call) => call.$1 == 'agent_create'),
+ isEmpty,
+ );
+ expect(f.connection.joins, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pumpAndSettle();
+ final ordinary = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(ordinary.harnessContext, isNull);
+ expect(ordinary.placement, HarnessPlacement.newTab);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await f.app.superTabs.peek(tabId)!.flush();
+ f.app.superTabs.dispose();
+ },
+ );
+
+ testWidgets(
+ 'withdrawing conversation access closes Add agent without contributing',
+ (tester) async {
+ final f = await open(tester);
+ f.app.superTabs.peek(tabId)!.revokeAccess('Access was removed.');
+ await tester.pumpAndSettle();
+ expect(input, findsNothing);
+ expect(find.text('Add agent to Offline editing'), findsNothing);
+ expect(f.connection.server.posts, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await f.app.superTabs.peek(tabId)!.flush();
+ f.app.superTabs.dispose();
+ },
+ );
+
+ testWidgets(
+ 'a teammate added elsewhere cannot be added again from a stale picker',
+ (tester) async {
+ final f = await open(tester);
+ await tester.enterText(input, 'Teammate builder');
+ await tester.pumpAndSettle();
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ expect(search.canAccept, isTrue);
+ (f.connection.server.state['conversations'] as List)[1]['agentIds'] = [
+ 'remote-agent',
+ ];
+ await f.app.superTabs.peek(tabId)!.refresh();
+ await tester.pumpAndSettle();
+ expect(search.canAccept, isFalse);
+ expect(
+ tester
+ .widget<FilledButton>(
+ find.widgetWithText(FilledButton, 'Add agent'),
+ )
+ .onPressed,
+ isNull,
+ );
+ expect(
+ search.sessionUnavailable(search.selected),
+ 'Already in this conversation.',
+ );
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(f.connection.server.posts, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await f.app.superTabs.peek(tabId)!.flush();
+ f.app.superTabs.dispose();
+ },
+ );
+
+ testWidgets('archiving the target conversation closes Add agent', (
+ tester,
+ ) async {
+ final f = await open(tester);
+ (f.connection.server.state['conversations'] as List)[1]['archived'] = true;
+ await f.app.superTabs.peek(tabId)!.refresh();
+ await tester.pumpAndSettle();
+ expect(input, findsNothing);
+ expect(f.connection.server.posts, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await f.app.superTabs.peek(tabId)!.flush();
+ f.app.superTabs.dispose();
+ });
+
+ testWidgets('New Harness from Add agent retains the captured conversation', (
+ tester,
+ ) async {
+ final f = await open(tester);
+ final c = f.app.superTabs.peek(tabId)!;
+ c.select('lead');
+ final search = tester
+ .widget<SwarmSearchResults>(find.byType(SwarmSearchResults))
+ .search;
+ final create = search.rows.singleWhere((row) => row.id == 'create:harness');
+ search.move(search.rows.indexOf(create) - search.cursor);
+ await key(tester, LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final box = tester
+ .widget<NewHarnessForm>(find.byType(NewHarnessForm))
+ .controller;
+ box.setFolder('/work/project');
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('new-harness-field-start')));
+ await tester.pumpAndSettle();
+ expect(box.error, isNull);
+ expect(box.checking, isFalse);
+ expect(
+ f.connection.joins.single['command'],
+ containsPair('conversationId', 'offline'),
+ );
+ expect(f.connection.joins.single['command'], containsPair('lead', false));
+ expect(f.app.swarms, hasLength(1));
+ expect(f.app.panes, isEmpty);
+ // A successful join clears its journal; it was never a new Super Tab.
+ expect(
+ f.store.values.entries
+ .where((entry) => entry.key.startsWith('super_tab.launch.'))
+ .map((entry) => jsonDecode(entry.value)),
+ isEmpty,
+ );
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ });
+}
diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dart
new file mode 100644
index 000000000..ebdc84c39
--- /dev/null
+++ b/desktop/test/super_tab_view_test.dart
@@ -0,0 +1,496 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ testWidgets(
+ 'native observations keep their agent author and show source and truncation clearly',
+ (tester) async {
+ final server = ConversationServer();
+ server.append('Adjust the native implementation.');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'builder',
+ 'name': 'Builder',
+ };
+ server.messages.last['source'] = {
+ 'kind': 'native',
+ 'phase': 'prompt',
+ 'operator': {'name': '[email protected]'},
+ 'truncated': true,
+ };
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Builder'), findsOneWidget);
+ expect(
+ find.text('Terminal input · session opened by [email protected]'),
+ findsOneWidget,
+ );
+ expect(
+ find.text('Excerpt · open the terminal for the full response'),
+ findsOneWidget,
+ );
+ expect(find.text('Adjust the native implementation.'), findsOneWidget);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+ testWidgets('archived conversations remain searchable and can be reopened', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ (server.state['conversations'] as List)[1]['archived'] = true;
+ server.append('Verified the offline result.', conversationId: 'offline');
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ await tester.tap(find.byTooltip('Conversation options'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Archived conversations'));
+ await tester.pumpAndSettle();
+ final search = find.descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(TextField),
+ );
+ await tester.enterText(search, 'offline');
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Offline editing'));
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'offline');
+ expect(find.text('Verified the offline result.'), findsOneWidget);
+ expect(
+ tester
+ .widget<TextField>(
+ find.byKey(const ValueKey('super-message-composer')),
+ )
+ .enabled,
+ isFalse,
+ );
+ await tester.tap(find.byTooltip('Conversation options'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Reopen conversation'));
+ await tester.pumpAndSettle();
+ expect(server.posts.single['command'], {
+ 'type': 'conversation.archive',
+ 'conversationId': 'offline',
+ 'archived': false,
+ });
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ });
+
+ testWidgets(
+ 'large text and a short window preserve navigation and creation',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(800, 480));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = Brightness.light;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final server = ConversationServer();
+ (server.state['conversations'] as List)[1]['title'] =
+ 'Offline editing across mobile and desktop';
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.light),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(2)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ if (find.byTooltip('Conversations').evaluate().isNotEmpty) {
+ await tester.tap(find.byTooltip('Conversations'));
+ await tester.pumpAndSettle();
+ }
+ await tester.tap(find.text('New group'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ expect(
+ tester
+ .widget<FilledButton>(find.widgetWithText(FilledButton, 'Create'))
+ .onPressed,
+ isNull,
+ );
+ final name = find.descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(TextField),
+ );
+ await tester.enterText(name, 'Device testing');
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Create'));
+ await tester.pumpAndSettle();
+ expect(controller.selected?.title, 'Device testing');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ testWidgets(
+ 'the narrow sidebar owns keyboard focus and Escape returns to the draft',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(600, 520));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ await tester.enterText(composer, 'Keep this draft');
+ await tester.tap(find.byTooltip('Conversations'));
+ await tester.pumpAndSettle();
+ final field = tester.widget<TextField>(composer);
+ expect(field.focusNode!.hasFocus, isFalse);
+ for (var step = 0; step < 8; step++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(field.focusNode!.hasFocus, isFalse);
+ }
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(field.controller!.text, 'Keep this draft');
+ expect(server.posts, isEmpty);
+ await tester.tap(find.byTooltip('Conversations'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-group-offline')));
+ await tester.pumpAndSettle();
+ expect(controller.selectedId, 'offline');
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(controller.draft('lead'), 'Keep this draft');
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ testWidgets(
+ 'flat sidebar keeps local actions in its footer without repeating the app tab name',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1100, 700));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Pilot'), findsNothing);
+ expect(find.text('CHATS'), findsNothing);
+ expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);
+ expect(
+ tester.getCenter(find.text('New group')).dy,
+ greaterThan(
+ tester
+ .getCenter(find.byKey(const ValueKey('super-group-offline')))
+ .dy,
+ ),
+ );
+ final invite = tester.getCenter(find.text('Invite'));
+ final create = tester.getCenter(find.text('New group'));
+ expect(invite.dy >= create.dy, isTrue);
+ if (invite.dy == create.dy) expect(invite.dx, greaterThan(create.dx));
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ for (final rename in [false, true]) {
+ testWidgets(
+ '${rename ? 'Rename' : 'New group'} clears its form when account access ends',
+ (tester) async {
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ if (rename) {
+ await tester.tap(find.byTooltip('Conversation options'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Rename'));
+ } else {
+ await tester.tap(find.text('New group'));
+ }
+ await tester.pumpAndSettle();
+ final field = find.descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(TextField),
+ );
+ await tester.enterText(field, 'Private draft for previous account');
+ controller.revokeAccess('Account changed.');
+ await tester.pumpAndSettle();
+ expect(find.text('Private draft for previous account'), findsNothing);
+ expect(find.text(rename ? 'Save' : 'Create'), findsNothing);
+ expect(server.posts, isEmpty);
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+ }
+
+ testWidgets(
+ '20 people remain a count and Add agent targets the selected group',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1100, 700));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer();
+ (server.state['people'] as List).addAll(
+ List.generate(
+ 19,
+ (i) => {
+ 'id': 'person-${i + 1}',
+ 'email': 'person${i + 1}@example.com',
+ 'role': 'collaborator',
+ },
+ ),
+ );
+ server.state['agents'] = List.generate(
+ 3,
+ (i) => {
+ 'id': 'agent-$i',
+ 'name': 'Worker $i',
+ 'machineId': 'host-$i',
+ 'harnessId': 'session-$i',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ );
+ (server.state['conversations'] as List)[1]['agentIds'] = [
+ 'agent-0',
+ 'agent-1',
+ 'agent-2',
+ ];
+ final controller = server.controller();
+ await controller.refresh();
+ controller.select('offline');
+ SuperTabConversation? target;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (group) => target = group,
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('3 agents · 20 people'), findsOneWidget);
+ expect(find.text('Worker 0'), findsNothing);
+ await tester.tap(find.text('3 agents · 20 people'));
+ await tester.pumpAndSettle();
+ final search = find.descendant(
+ of: find.byType(Dialog),
+ matching: find.byType(TextField),
+ );
+ await tester.enterText(search, 'person19');
+ await tester.pumpAndSettle();
+ expect(find.text('[email protected]'), findsOneWidget);
+ expect(find.text('[email protected]'), findsNothing);
+ await tester.tap(find.text('Add agent'));
+ await tester.pumpAndSettle();
+ expect(target?.id, 'offline');
+ expect(controller.snapshot!.conversations, hasLength(2));
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ testWidgets(
+ 'a native terminal sits beside the conversation and uses a return action when narrow',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1100, 700));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final server = ConversationServer()..append('Review this result.');
+ final controller = server.controller();
+ await controller.refresh();
+ var closed = false;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ terminal: const Center(child: Text('Native terminal fixture')),
+ onCloseTerminal: () => closed = true,
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ tester.getCenter(find.text('Native terminal fixture')).dx,
+ greaterThan(tester.getCenter(find.text('Review this result.')).dx),
+ );
+ await tester.binding.setSurfaceSize(const Size(800, 700));
+ await tester.pumpAndSettle();
+ expect(find.text('Back to conversation'), findsOneWidget);
+ expect(find.text('Review this result.'), findsNothing);
+ await tester.tap(find.text('Back to conversation'));
+ expect(closed, isTrue);
+ expect(
+ server.posts,
+ isEmpty,
+ reason: 'Hiding a terminal never sends a process-stop command.',
+ );
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+
+ testWidgets(
+ 'Enter respects IME composition and sends into the selected conversation',
+ (tester) async {
+ final server = ConversationServer();
+ final controller = server.controller();
+ await controller.refresh();
+ controller.select('offline');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final field = find.byKey(const ValueKey('super-message-composer'));
+ await tester.tap(field);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'Draft',
+ selection: TextSelection.collapsed(offset: 5),
+ composing: TextRange(start: 0, end: 5),
+ ),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(server.posts, isEmpty);
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: 'Draft',
+ selection: TextSelection.collapsed(offset: 5),
+ ),
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(server.posts, hasLength(1));
+ expect(
+ (server.posts.single['command'] as Map)['conversationId'],
+ 'offline',
+ );
+ await tester.pumpWidget(const SizedBox());
+ await controller.flush();
+ controller.dispose();
+ },
+ );
+}
diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dart
new file mode 100644
index 000000000..980346b9f
--- /dev/null
+++ b/desktop/test/super_tab_workspace_test.dart
@@ -0,0 +1,183 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/super_tabs/workspace.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+void main() {
+ testWidgets(
+ 'each group restores its terminal and closing it never stops the agent',
+ (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1100, 700));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final state = f.connection.server.state;
+ state['agents'] = [
+ for (final id in ['a', 'b'])
+ {
+ 'id': id,
+ 'name': id,
+ 'machineId': 'm',
+ 'harnessId': 'native-$id',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ (state['conversations'] as List)[0]['agentIds'] = ['a'];
+ (state['conversations'] as List)[1]['agentIds'] = ['b'];
+ f.app.machineStates['m']!.agents = [
+ for (final id in ['a', 'b'])
+ Agent.fromJson({'id': 'native-$id', 'name': id, 'engine': 'codex'}),
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: Text(
+ 'Terminal ${f.app.activeSwarm.panes.firstOrNull?.agentId}',
+ ),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ c.selectTerminal('lead', 'a');
+ await tester.pumpAndSettle();
+ expect(find.text('Terminal native-a'), findsOneWidget);
+ final firstContext = f.app.activeSwarm.panes.single.inputContext;
+ expect(firstContext, isNotNull);
+ expect(
+ f.connection.calls
+ .where((call) => call.$2['action'] == 'prepareNative')
+ .single
+ .$2['contextId'],
+ firstContext,
+ );
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(find.text('Terminal native-a'), findsNothing);
+ expect(f.app.activeSwarm.panes, isEmpty);
+ c.selectTerminal('offline', 'b');
+ await tester.pumpAndSettle();
+ expect(find.text('Terminal native-b'), findsOneWidget);
+ expect(f.app.activeSwarm.panes.single.inputContext, isNot(firstContext));
+ c.select('lead');
+ await tester.pumpAndSettle();
+ expect(find.text('Terminal native-a'), findsOneWidget);
+ expect(f.app.activeSwarm.panes, hasLength(1));
+ (state['people'] as List)[0]['role'] = 'viewer';
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(f.app.activeSwarm.panes.single.watchOnly, isTrue);
+ expect(f.app.activeSwarm.panes.single.inputContext, isNull);
+ (state['people'] as List)[0]['role'] = 'owner';
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(f.app.activeSwarm.panes.single.watchOnly, isFalse);
+ // Native pane Close and the narrow Back action have the same personal state.
+ await f.app.closePane(f.app.activeSwarm.panes.single.id);
+ await tester.pumpAndSettle();
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(c.terminalAgent('lead'), isNull);
+ expect(f.app.activeSwarm.panes, isEmpty);
+ final scopes = f.connection.calls
+ .where(
+ (call) => (call.$2['path'] as String?)?.endsWith('/native') == true,
+ )
+ .map((call) => (call.$2['body'] as Map)['conversationId']);
+ expect(scopes, containsAll(['lead', 'offline']));
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(find.text('Terminal native-b'), findsOneWidget);
+ // Rapid navigation does not display or reattach a superseded selection.
+ c.select('lead');
+ c.select('offline');
+ await tester.pumpAndSettle();
+ expect(f.app.activeSwarm.panes.single.agentId, 'native-b');
+ (state['conversations'] as List)[1]['agentIds'] = <String>[];
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(f.app.activeSwarm.panes, isEmpty);
+ expect(
+ f.connection.calls.where((call) => call.$1 == 'agent_close'),
+ isEmpty,
+ );
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+
+ testWidgets(
+ 'a host recording failure leaves the conversation usable and does not stop its harness',
+ (tester) async {
+ final f = SuperTabLaunchFixture();
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final state = f.connection.server.state;
+ state['agents'] = [
+ {
+ 'id': 'a',
+ 'name': 'Lead',
+ 'machineId': 'm',
+ 'harnessId': 'native-a',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ (state['conversations'] as List)[0]['agentIds'] = ['a'];
+ f.app.machineStates['m']!.agents = [
+ Agent.fromJson({'id': 'native-a', 'name': 'Lead', 'engine': 'codex'}),
+ ];
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListenableBuilder(
+ listenable: f.app,
+ builder: (_, _) => SuperTabWorkspace(
+ app: f.app,
+ canvas: const Text('Native terminal'),
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ c.selectTerminal('lead', 'a');
+ await tester.pumpAndSettle();
+ expect(find.text('Native terminal'), findsOneWidget);
+ f.connection.failNative = true;
+ await tester.pump(const Duration(seconds: 21));
+ await tester.pumpAndSettle();
+ expect(c.terminalAgent('lead'), isNull);
+ expect(f.app.activeSwarm.panes, isEmpty);
+ expect(find.textContaining('Terminal sharing paused'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-message-composer')),
+ findsOneWidget,
+ );
+ expect(
+ f.connection.calls.where((call) => call.$1 == 'agent_close'),
+ isEmpty,
+ );
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ f.app.superTabs.dispose();
+ await tester.pump();
+ },
+ );
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
new file mode 100644
index 000000000..87cd674ee
--- /dev/null
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -0,0 +1,140 @@
+import 'dart:convert';
+
+import 'package:harness/super_tabs/controller.dart';
+
+Map<String, dynamic> conversationFixture(String id, String title) => {
+ 'id': id,
+ 'title': title,
+ 'leadId': null,
+ 'agentIds': <String>[],
+ 'archived': false,
+ 'brief': '',
+ 'checks': <dynamic>[],
+ 'assignment': null,
+ 'lastMessageSequence': 0,
+};
+
+class ConversationServer {
+ int revision = 0;
+ bool loseReply = false, reject = false, failSave = false, failReads = false;
+ Map<String, dynamic>? saved;
+ final posts = <Map<String, dynamic>>[];
+ final receipts = <String, Map<String, dynamic>>{};
+ final messages = <Map<String, dynamic>>[];
+ final state = <String, dynamic>{
+ 'version': 1,
+ 'id': 'tab',
+ 'name': 'Pilot',
+ 'ownerId': 'owner',
+ 'paused': false,
+ 'people': <dynamic>[
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ ],
+ 'agents': <dynamic>[],
+ 'invitations': <dynamic>[],
+ 'conversations': [
+ conversationFixture('lead', 'Lead'),
+ conversationFixture('offline', 'Offline editing'),
+ ],
+ };
+ Future<void> save(Map<String, dynamic> value) async {
+ if (failSave) throw StateError('Disk full');
+ saved = jsonDecode(jsonEncode(value)) as Map<String, dynamic>;
+ }
+
+ void append(String text, {String conversationId = 'lead'}) {
+ revision++;
+ messages.add({
+ 'id': 'message-$revision',
+ 'conversationId': conversationId,
+ 'sequence': revision,
+ 'text': text,
+ 'createdAt': '2026-10-18T00:00:00Z',
+ 'author': {'kind': 'person', 'id': 'owner', 'name': '[email protected]'},
+ 'deliveries': <dynamic>[],
+ });
+ (state['conversations'] as List).cast<Map<String, dynamic>>().firstWhere(
+ (g) => g['id'] == conversationId,
+ )['lastMessageSequence'] = revision;
+ }
+
+ Future<Map<String, dynamic>> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (method == 'POST') {
+ posts.add(Map<String, dynamic>.from(body!));
+ if (reject) {
+ throw const SuperTabFailure(
+ 'INVALID_RECIPIENT',
+ 'Choose an agent in this conversation.',
+ statusCode: 400,
+ );
+ }
+ final operationId = body['operationId'] as String;
+ if (receipts[operationId] case final receipt?) return receipt;
+ final command = body['command'] as Map;
+ final output = <String, dynamic>{};
+ if (command['type'] == 'message.send') {
+ append(
+ command['text'] as String,
+ conversationId: command['conversationId'] as String,
+ );
+ messages.last['replyTo'] = command['replyTo'];
+ output['messageId'] = 'message-$revision';
+ } else if (command['type'] == 'conversation.create') {
+ revision++;
+ final id = 'group-$revision';
+ (state['conversations'] as List).add(
+ conversationFixture(id, command['title'] as String),
+ );
+ output['conversationId'] = id;
+ }
+ final result = {'revision': revision, 'result': output};
+ receipts[operationId] = result;
+ if (loseReply) {
+ loseReply = false;
+ throw StateError('Connection lost after commit');
+ }
+ return result;
+ }
+ if (failReads) throw StateError('Offline');
+ final uri = Uri.parse(path);
+ if (uri.pathSegments.last == 'messages') {
+ final conversationId = uri.pathSegments[4];
+ final after = int.tryParse(uri.queryParameters['after'] ?? '');
+ final before = int.tryParse(uri.queryParameters['before'] ?? '');
+ var rows = messages
+ .where(
+ (m) =>
+ m['conversationId'] == conversationId &&
+ (after == null || (m['sequence'] as int) > after) &&
+ (before == null || (m['sequence'] as int) < before),
+ )
+ .toList();
+ if (after == null) rows = rows.reversed.toList();
+ final page = rows.take(100).toList();
+ final next = rows.length > 100 ? page.last['sequence'] : null;
+ return {
+ 'messages': after == null ? page.reversed.toList() : page,
+ 'next': next,
+ 'revision': revision,
+ };
+ }
+ return jsonDecode(jsonEncode({'revision': revision, 'state': state}))
+ as Map<String, dynamic>;
+ }
+
+ SuperTabController controller({
+ Map<String, dynamic>? initial,
+ String account = 'owner',
+ }) => SuperTabController(
+ tabId: 'tab',
+ accountId: account,
+ request: request,
+ save: save,
+ initial: initial ?? const {},
+ pollInterval: Duration.zero,
+ );
+}
diff --git a/desktop/test/terminal_session_test.dart b/desktop/test/terminal_session_test.dart
index f6c1285ba..3071c5917 100644
--- a/desktop/test/terminal_session_test.dart
+++ b/desktop/test/terminal_session_test.dart
@@ -91,6 +91,64 @@ void main() {
expect(identical(session.terminal, before), isTrue);
});
+ test('changing input context withholds typing until the new stream is ready and preserves its terminal', () async {
+ await ready();
+ await session.handleBinary(
+ output(
+ 0,
+ 'retained screen'.codeUnits,
+ keyframe: true,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ final terminal = session.terminal;
+ expect(session.acceptsInput, isTrue);
+ session.stageInputContext('context_alpha_123456');
+ expect(session.acceptsInput, isFalse);
+ await session.setInputContext('context_alpha_123456');
+ final opening = sent
+ .lastWhere((frame) => frame.type == 'terminal_open')
+ .payload;
+ expect(opening['inputContext'], 'context_alpha_123456');
+ expect(identical(session.terminal, terminal), isTrue);
+ await session.handleFrame('terminal_ready', {
+ 'requestId': opening['requestId'],
+ 'protocolVersion': 3,
+ 'streamId': streamId,
+ 'agentId': 'agent-1',
+ });
+ await session.handleBinary(
+ output(
+ 0,
+ 'retained screen'.codeUnits,
+ keyframe: true,
+ cols: 100,
+ rows: 30,
+ ),
+ );
+ expect(session.acceptsInput, isTrue);
+ final latestTerminal = session.terminal;
+ expect(await session.sendComposerText('Scoped composed input'), isTrue);
+ expect(
+ sent
+ .lastWhere((frame) => frame.type == 'message')
+ .payload['inputContext'],
+ 'context_alpha_123456',
+ );
+ session.stageInputContext(null);
+ expect(session.acceptsInput, isFalse);
+ await session.setInputContext(null);
+ expect(
+ sent
+ .lastWhere((frame) => frame.type == 'terminal_open')
+ .payload
+ .containsKey('inputContext'),
+ isFalse,
+ );
+ expect(identical(session.terminal, latestTerminal), isTrue);
+ });
+
test(
'a renderer that keeps failing still gives up rather than looping',
() async {
@@ -109,6 +167,25 @@ void main() {
},
);
+ test('a watch-only scope cannot take control or submit text', () async {
+ await ready();
+ await session.handleBinary(
+ output(0, 'screen'.codeUnits, keyframe: true, cols: 100, rows: 30),
+ );
+ session.stageInputContext(null, watchOnly: true);
+ expect(session.readOnly, isTrue);
+ expect(session.acceptsInput, isFalse);
+ expect(await session.sendComposerText('Do not send'), isFalse);
+ await session.setInputContext(null, watchOnly: true);
+ expect(
+ sent
+ .lastWhere((frame) => frame.type == 'terminal_open')
+ .payload['watchOnly'],
+ isTrue,
+ );
+ expect(sent.where((frame) => frame.type == 'message'), isEmpty);
+ });
+
test('a tmux passthrough sequence is swallowed, not painted', () async {
await ready();
@@ -1454,22 +1531,28 @@ void main() {
await reopening;
});
- test('a stream the daemon no longer has is reopened in place at once', () async {
- await ready();
- await session.handleBinary(
- output(0, utf8.encode('screen'), keyframe: true, cols: 100, rows: 30),
- );
- await session.handleFrame('terminal_error', {
- 'streamId': streamId,
- 'code': 'TERMINAL_STREAM_NOT_FOUND',
- 'message': 'no live terminal stream',
- });
- await pumpEventQueue();
+ test(
+ 'a stream the daemon no longer has is reopened in place at once',
+ () async {
+ await ready();
+ await session.handleBinary(
+ output(0, utf8.encode('screen'), keyframe: true, cols: 100, rows: 30),
+ );
+ await session.handleFrame('terminal_error', {
+ 'streamId': streamId,
+ 'code': 'TERMINAL_STREAM_NOT_FOUND',
+ 'message': 'no live terminal stream',
+ });
+ await pumpEventQueue();
- expect(sent.where((frame) => frame.type == 'terminal_open'), hasLength(2));
- expect(session.status, TerminalSessionStatus.opening);
- expect(session.errorCode, isNot('TERMINAL_STREAM_NOT_FOUND'));
- });
+ expect(
+ sent.where((frame) => frame.type == 'terminal_open'),
+ hasLength(2),
+ );
+ expect(session.status, TerminalSessionStatus.opening);
+ expect(session.errorCode, isNot('TERMINAL_STREAM_NOT_FOUND'));
+ },
+ );
test('a missing-stream report about another stream is ignored', () async {
await ready();
diff --git a/docs/naming-system.md b/docs/naming-system.md
index a0313cd6a..2b6357ee1 100644
--- a/docs/naming-system.md
+++ b/docs/naming-system.md
@@ -53,6 +53,7 @@ and **Browser**. Technical documentation may still call the terminal interface a
| **A harness** in the workspace | A running agent session with its own conversation and working context. | Start three Codex harnesses. |
| **A harness** in the Store | A reusable setup containing agent instructions, tools, and an optional viewer. | Install the Blender harness. |
| **Tab** | A workspace group of harnesses. | Frontend and Backend tabs. |
+| **Super Tab** | A collaborative tab with a lead, member agents and shared conversations. | Discuss the plan with the lead, then follow work in its group conversations. |
| **Pane** | A visible view of a harness, terminal, or viewer. | Split right; close pane. |
| **Terminal** | A shell for entering commands. | New terminal. |
| **Project** | The files and working context for the work, on a particular computer. | Choose the website project. |
@@ -78,10 +79,12 @@ no CLI keeps its maker's name (Fo).
A pane is a view, so closing a pane or tab closes views. **Stop Harness** ends the
running harness. Adding harnesses to a tab groups them without a separate team
-setup. **Agent Messages** lets the harnesses in a tab message each other
-(`harness send`); it is an experiment of the account, in Settings ▸ Experimental, off
-by default, and **Show Agent Messages** opens a tab's log. The word *tab* can also name the keyboard key or a
-browser tab; context distinguishes them.
+setup. **Super Tab** adds shared conversations and coordination across explicitly contributed agents;
+people and agents participate in the same flat conversation list. Its creation flow is experimental
+and hidden during initial validation. Existing tabs keep their behavior. The older **Agent Messages**
+protocol (`harness send`) and stored account settings remain compatible, while Super Tab owns its
+coordination controls. The word *tab* can also name the keyboard key or a browser tab; context
+distinguishes them.
A project belongs to a computer; identical paths on different computers do not
identify the same project. Use the actual project or computer name when that
diff --git a/docs/plans/2026-10-18-super-tab-build.md b/docs/plans/2026-10-18-super-tab-build.md
new file mode 100644
index 000000000..b60ae5754
--- /dev/null
+++ b/docs/plans/2026-10-18-super-tab-build.md
@@ -0,0 +1,401 @@
+# Super Tab implementation and validation
+
+Status: in progress, 18 October 2026. The interaction contract is
+[Super Tab MVP](../research/2026-10-17-one-human-many-agents/17-super-tab-mvp.md).
+This is a new tab type. Existing tabs and running sessions are not converted.
+
+## Implemented so far
+
+- Backend-owned conversations, people, invitations, agent contributions and work attempts.
+- Transactional commands, stable operation receipts, message history and delivery claims.
+- Assignment ownership across tabs; independent acceptance evidence; explicit host stop receipts.
+- Revocation checks for contributors, viewers, execution hosts and machine sharing.
+- Client conversation state: personal selection, drafts, unread positions, paginated history,
+ and durable receipt IDs for retrying an uncertain send.
+- Flat conversation sidebar, compact participants, local human questions, invitations and membership controls.
+- Hidden Cmd+Option+Shift+T creation using the existing New Harness form and native creation receipts.
+- Lead selection, machine, project, provider, account, worktree and attachment controls retained.
+- Add agent attaches to the captured conversation; native terminal inspection keeps the existing pane instance.
+- Daemon service and agent CLI for conversation commands and durable native message delivery.
+- Revocable input leases and durable host journals prevent replay after uncertain execution.
+- Mentions retain agent identity across restarts; work details show acceptance checks and exact result links.
+- Session-only terminal views reuse the existing encrypted observer protocol, with backend membership checks and expiring host authority.
+- Scoped agent start/resume with native creation receipts and single-dispatch claims; machine and quota admission.
+- Background attachment delivery through the native terminal protocol, retained launch files,
+ explicit recovery after an uncertain transfer, and account-change cancellation.
+- Native stopped-session evidence releases backend assignments, including a removed contributor's work.
+- Per-conversation native terminal selection survives navigation and restart; closing its pane clears the selection without stopping the harness.
+- Explicit recovery for uncertain input: inspect the terminal, confirm receipt, dismiss the warning, or deliberately resend with a new delivery identity.
+- Host receipt reconciliation preserves native evidence and can retire cancelled input after its agent is withdrawn, without restoring conversation access.
+- A backend delivery claim whose local host journal was lost becomes an explicit uncertain delivery. It retains the original claim, withholds native input, preserves any existing receipt, and uses the conversation's human recovery controls.
+- Shared desktop typography, colors, selectors, modal backdrop and focus behavior; readable large-text controls and searchable archived conversations.
+- Recent-harness navigation consumes an empty Super Tab draft only after opening work; ordinary search opens native work outside completed Super Tabs and preserves their conversations and terminal selection.
+- Definitive native-start refusals are reconciled through durable cancellation receipts. Lost cancellation or backend replies resume the same identity, and unknown/storage/conflict failures never become permission to launch again.
+- Add agent uses the existing desktop picker with a focused conversation title, sharing scope and one action. A teammate's contributed agent can join another conversation without machine access or another native pane. The participants dialog hands focus over after closing; creating a new harness retains the captured conversation. Membership and archive changes update or dismiss an open picker.
+- Runtime model/effort observations follow the native profile into the shared roster. Per-agent versions fence delayed updates and re-contributions. A separate configuration history records the initial configuration and observed changes against active assignment IDs; an assignment's starting configuration stays intact. Unknown context size is not inferred from a model name.
+- Autonomous starts reserve declared memory and destination disk budgets in one durable ledger on the execution host, shared across Super Tabs and concurrent service instances. A retry retains its reservation. Pending or unknown launches keep capacity; only a native failed/cancelled receipt or a confirmed stop releases it. Worktrees sample the managed workspace's filesystem, and a retry refuses a changed destination volume. Current CPU/memory pressure and known quota checks remain in admission.
+- Experimental settings cleanup and retired PR branding, preserving compatibility fields and usage controls.
+- Shared native prompt/answer recording with an authenticated conversation context, ordered durable receipts,
+ bounded core observations, and explicit gaps when provenance or continuity cannot be established.
+ Raw terminal input and composed/queued messages retain the same context. No private pre-open history is imported.
+- Native terminal viewers use the existing watch-only protocol. Account, membership, contribution and machine-grant
+ changes invalidate recording authority; the UI closes a failed recording view without stopping its harness.
+
+The desktop surface is connected, but the complete workflow is not ready. Scoped autonomous
+agent starts and capacity checks are connected through the existing native creation protocol.
+Terminal access, native stop reconciliation and explicit uncertain-delivery recovery are connected.
+Shared recording of native interventions is connected and covered by isolated fixtures. The
+implementation can enter automatic PR CI and review; rollout still requires the acceptance below.
+
+## Validation plan
+
+These changes cross shared state, authentication and protocol boundaries. Before rollout:
+
+| Scope | Required evidence |
+| --- | --- |
+| Backend | Typecheck, complete backend unit suite, isolated replica-set transaction/API integration |
+| CLI | Typecheck, complete CLI suite, affected core/services/harnessd coverage gates and relevant E2E |
+| Desktop | Analyze, complete desktop suite, affected macOS/native integration |
+| End to end | Two accounts and machines, both initial lead engines, shared group work, invitation/removal, native terminal, exact result |
+| Recovery | Lost start/send replies, busy and disconnected agents, removed/reinvited members, stale machine/account grants, restart/reconciliation |
+| Product | Physical hidden shortcut, creation form defaults/destinations/IME, narrow window, 20 people, focus/draft preservation |
+| Release | Required CI and independent review of the final stable head, merge, official review build and publication verification |
+
+Use the repository's pinned toolchains and isolated fixtures. Do not use the user's live
+harnesses or the live database. A passing backend fixture does not establish native execution
+or product readiness. Preserve valid evidence for unchanged scopes instead of repeating full suites.
+
+## Current evidence
+
+Focused checks completed during implementation (18 October):
+
+- Backend and CLI typechecks passed.
+- Backend commands and session-share access: 24 tests passed; machine policy/access/sharing checks also passed.
+- `npm run test:super-tabs`: 12 integration tests passed in a disposable, loopback-only
+ MongoDB 7.0.24 replica set. Includes transactional retry, cross-tab assignment ownership,
+ host-confirmed stop, concurrent native start claims and machine-share removal/restoration fencing for queued instructions.
+- CLI Super Tab, terminal sharing and architecture checks: 63 tests passed. PR attribution and launch overrides: 47 passed.
+- CLI launch argv goldens: 2 tests passed without recording. Launch-shape recording showed no
+ fixture changes; a normal comparison run remains to do.
+- Focused core/process coverage: 77 tests, 100% statements, branches, functions and lines for
+ changed API/delivery/process wrapper files at that checkpoint. Full coverage gates remain.
+- Flutter creation, attachment, shortcut, keymap and state regression checks: 98 passed.
+- Flutter conversation surface/state and entry rules: 40 passed, including hidden shortcut,
+ persistent mention identity and lost acknowledgements.
+- Flutter Super Tab launch/account recovery and conversation state: 15 passed for both lead engines, lost native/join
+ replies and account changes. Experimental settings: 15 passed earlier.
+- Latest attachment, account and conversation checks: 29 Flutter tests passed. Includes files reaching
+ both engines without a pane, retained files after restart, explicit resend after uncertainty,
+ a failed creation becoming editable, and closing a background writer on account change.
+- Native daemon fixture (`cli/e2e/superTabs.e2e.ts`): passed in 15 seconds. Real master/core/services,
+ private tmux and fake Claude Code/Codex engines; starts once, posts to the captured group,
+ types a shared instruction once, refuses a revoked contribution and confirms an actual native stop.
+ Its coordination HTTP fixture does not establish database or external SSO behavior.
+- Latest backend replica-set integration: 12 passed, including automatic stopped-assignment release.
+ CLI focused native lifecycle/service checks: 87 passed. Focused coverage for `core/api.ts`,
+ `core/experimentQueries.ts` and `services/processCoreApi.ts`: 70 tests, 100% in all four measures.
+- Delivery recovery integration: 15 tests passed in a fresh replica set, including concurrent human resolution,
+ late host acknowledgements, machine-grant changes, withdrawn hosts and reassigned machine ownership.
+ Backend typecheck passed after adding recorded execution ownership to delivery receipts.
+- CLI host reconciliation: 10 tests passed, including retiring a confirmed receipt without typing it again.
+- Desktop UI, navigation, conversation state and launch regression batch: 35 passed. The 11 affected UI checks
+ passed again after the final focus and large-text corrections; the unchanged state/launch evidence is retained.
+ Focused Dart analysis and the shared icon audit passed.
+- Flutter VM renders with the actual macOS system font were inspected in light and dark appearance at 1280×800,
+ and at 200% text with Increase Contrast in an 800×480 window. Reviewed conversation, participants, Invite and
+ uncertain-delivery surfaces. Fixed a clipped footer label, inaccessible recovery action, generic dropdown,
+ double dialog frame and missing initial search/email focus. These are synthetic fixtures, not native window evidence.
+- Native macOS fixture compiled successfully, loaded its synthetic conversation, then timed out at the first rendered
+ frame after two minutes. Flutter reported that it could not foreground the test app. A read of console flags confirmed
+ `CGSSessionScreenIsLocked: true`. Native interaction, physical shortcut/IME and full terminal acceptance remain unverified;
+ repeat them once the console is unlocked. The fixture uses in-memory accounts and terminal traffic, never real harnesses.
+- Restored the ordinary macOS debug app with `scripts/build-macos-debug.sh --no-pub --target lib/main.dart`
+ and the pinned Flutter toolchain. Build, renderer configuration and local signature verification passed.
+ This is a local artifact, not an official release or a complete end-to-end acceptance result.
+- Navigation and creation regression: 99 Flutter tests passed across Super Tab navigation/launch, search,
+ normal tab state/navigation and the welcome composer. Includes the actual hidden shortcut and recent row in
+ a widget fixture, retained terminal identity, failed selection, existing-view focus and group/multiple-agent
+ navigation with all placements. Focused Dart analysis passed. This evidence uses injected Flutter keys,
+ not physical macOS shortcut acceptance; the local debug artifact predates these navigation changes.
+- Native-start refusal recovery: CLI typecheck and 20 focused start/command/capacity tests passed. The real-daemon
+ fixture passed in 15.63 seconds, including both fake engines, a refused permission mode, its durable cancellation,
+ a delayed create that cannot revive it, and a resume that retains the failed result. No production sessions were used.
+- Agent picker and ordinary navigation regression: 153 Flutter tests passed across the actual workspace picker,
+ Super Tab view/launch/navigation and normal search identity, previews, rendering and keyboard edge cases. After the
+ final live-membership guards, all 8 picker tests passed again, including a disabled action when a teammate already
+ added the agent, removal of access and archiving the target. Inspected light/dark 1280×800 and 200% text at 800×480
+ fixture renders; the contribution picker has no unrelated preview/actions and its selected row remains visible.
+ Focused Dart analysis had no errors or warnings; it reported two existing brace-style informational diagnostics
+ in `swarm_screen.dart`. These checks do not replace native or official-build acceptance.
+- Missing-host-journal recovery: CLI typecheck and 15 focused host/service tests passed. The real-daemon fixture
+ passed in 14.93 seconds with the original native delivery identity retained, an uncertain receipt exposed for
+ human review, and later host polls verified not to type the instruction. Unit checks also cover another lost
+ backend acknowledgement/restart and preservation of an existing uncertain native receipt. No claim is stolen
+ or automatically replayed. The backend's existing transactional acknowledgement/resolution path is unchanged.
+- Runtime observations: backend and CLI typechecks passed; 13 backend policy tests, 16 disposable replica-set
+ integration tests and 18 CLI configuration/host/service tests passed. The integration test verifies host-only
+ authority, immutable starting configuration, ordered history, duplicate/lost replies, concurrent/stale updates
+ and withdrawal. A slow configuration write does not hold up native delivery or its leases.
+ The expanded native fixture passed in 21.86 seconds, switching both fake Claude Code and Codex through the app's
+ existing `agent_update` controls and observing the changed model/effort through the separate service process.
+ The fixture waits for both actual turns to finish before switching; an idle snapshot from the prior turn was
+ insufficient. The generic runtime projection is isolated in `f7ab9240ca`; its 42 focused API/process/architecture
+ checks passed with 100% statements, branches, functions and lines for the two changed boundary files.
+- Runtime observation microbenchmark: Node 22.23.1, 100 unchanged agents, 5,000 passes after warm-up, same synthetic
+ native roster on this Mac. Existing traversal averaged 0.00076 ms/pass and 0.90 µs CPU; traversal plus observations
+ averaged 0.0729 ms/pass and 72.76 µs CPU. Neither retained additional RSS after collection. Observations run at most
+ once every five seconds on the existing roster read. This isolates local parsing/comparison cost, excludes network
+ writes and is not a full-daemon or customer workload performance result.
+- Prepared a generic native-creation observation seam for resource reservation recovery. It projects only an
+ exact creation ID, state and created harness ID through the existing receipt provider and service boundary;
+ unavailable, malformed or older-core replies stay unknown. CLI typecheck passed. The 94 affected API, query,
+ process, parser and architecture tests passed with 100% statements, branches, functions and lines for all four
+ included boundary/parser files. The reservation caller and its real-daemon integration are now implemented below.
+- Closed native creation identities remain observable even after their terminal is unavailable. This lets the
+ service reconcile a harness that started and stopped before it could record the launch. The generic change is
+ isolated in `032d68194f`. Its 96 launch/query/architecture checks passed with 100% statements, branches, functions
+ and lines for both changed core files. The affected backend-socket cases passed (10 selected; 216 unselected).
+- Host capacity reservations: CLI typecheck and 54 focused capacity, storage, start and service checks passed.
+ Tests cover two actual concurrent Node processes sharing the ledger, duplicate/lost replies, service restarts,
+ missing/pending/unknown native outcomes, cancellation, stopped harnesses, changed host identity, request cancellation,
+ private file permissions, lost/corrupt/replaced storage and destination-volume changes. One reservation cannot
+ be reused with different requirements. Node runtimes without builtin SQLite refuse this new feature with an
+ update instruction; they do not crash the daemon or silently skip reservation.
+ The real-daemon fixture passed in 18.50 seconds with both fake engines, concurrent host admission and release
+ after native cancellation and stop. The later destination-volume retry guard and narrowed created-ID handling
+ passed the focused regression batch and typecheck; they do not change the fixture's first-admission path.
+- Capacity admission microbenchmark: Node 22.23.1, 10 retained pending reservations, 100 admissions after 20 warm-ups.
+ Fixed in-process native/resource readers with real local SQLite writes: existing preflight averaged 0.00223 ms
+ and 2.57 µs CPU; preflight plus reservation averaged 0.671 ms and 600.6 µs CPU per admission. Observed RSS grew
+ 0.5 MiB and 5.8 MiB respectively without forced collection. This measures local admission work, not retained
+ memory, cross-process/network latency, native launch, or full-daemon performance. Reservation runs on demand;
+ it adds no polling timer. Declared budgets are conservative admission allowances, not OS-enforced quotas.
+
+- Native recording backend: 19 replica-set integration tests passed in 8.75 seconds, including ordered retries,
+ lost acknowledgements, forged source rejection, group isolation, lead notification without echo, viewer denial,
+ removal/rejoin fencing and machine-grant changes. Backend and CLI typechecks passed.
+- Native host recording: 48 focused host/service/architecture tests passed, including independent capture during
+ slow backend writes, journal recovery, lost replies, access revocation, visible gaps after expiry and retirement
+ of expired views while another remains open. The private outbox advances its cursor only with durable content.
+- Generic input observation boundaries: 223 tests passed with 100% per-file statements, branches, functions and
+ lines for the changed API/query/funnel/process wrapper/observer files. The composed-input follow-up passed
+ 168 tests with 100% in all four measures for `core/input.ts` and `lib/nativeTurnObservations.ts`.
+- Real-daemon native recording fixture passed in 37.95 seconds for both fake engines: raw and composed prompts,
+ matching answers, a lost backend reply, and ambiguous input that produces a gap without exporting its contents.
+ This exercises the real daemon/service/terminal paths, not a signed desktop build or live engine subscriptions.
+- Desktop native recording checks: 114 affected Flutter tests passed; the composed-message follow-up passed all
+ 77 terminal session tests. Focused analysis found no issues. Three system-font fixture renders were inspected in
+ light/dark appearance and at 200% text. Metadata and actions use the existing design tokens and control family.
+ These renders establish layout evidence, not physical keyboard, IME or full-app acceptance.
+- Complete core/service coverage gate: 2,770 tests passed, 100% per-file coverage in all four measures.
+ Daemon supervisor gate: 273 passed, one platform-specific systemd check skipped on macOS; 100% coverage.
+ Machine sharing gate: 75 passed, 100% coverage, including expiring Super Tab authority while preserving unread legacy rosters.
+- Full backend unit run: 1,543 passed, one stale backend-frame expectation failed, 11 external-provider tests skipped.
+ The unchanged production refusal list already included `connectors_changed`; its expectation was corrected and
+ both frame-contract tests passed. Combined evidence covers all enabled backend unit tests; the original full run was not green.
+- Full CLI unit run: 16,107 passed, six failed, 106 skipped. The new sharing fixture was corrected and its entire
+ coverage gate passed. A symlink-loop expectation now accepts whichever of the two explicit bounded-path limits is
+ reached first on the host's temporary path. Unchanged loopback/tmux tests passed when isolated. The private Darwin
+ helper was built and verified for native identity tests; 131 native/path checks passed, one transient process probe
+ failed and then passed in isolation. Original full-run failures and targeted follow-ups remain separate evidence.
+- Full macOS Flutter run: 6,880 passed, 46 failed, 12 skipped. It exposed two unnecessary waits introduced around
+ ordinary creation and initial pane attachment; both were removed. Follow-ups passed 105 creation/recovery checks
+ and 44 pane/Super Tab checks. Nine files initially failed to connect to Flutter's test process; their serial rerun
+ completed 176 checks with five configured skips and found the pane timing issue fixed in the subsequent 44-test batch.
+ Focused feature analysis is clean; `app_state.dart` retains 12 pre-existing brace-style info diagnostics.
+- Native observation microbenchmark (Node 22.23.1, 10,000 turns after 1,000 warm-ups): baseline 0.156 µs wall time
+ per turn, unobserved 0.468 µs, observed 3.757 µs. The observed case retained about 64 KB more heap after collection;
+ RSS rose about 16.8 MiB. This measures input classification and bounded observation only, excluding transport,
+ network, backend and the rest of the core; it is not a full-daemon benchmark.
+
+- Two-account/two-machine E2E passed in 14.43 seconds. A lead on the starter's real isolated daemon
+ launches a worker on a teammate's explicitly shared machine over the encrypted relay. The agents exchange
+ work, the worker joins a second group without restarting, and native terminal observations retain the
+ starter's identity as opener while the teammate's host records execution. Revoking the machine grant
+ disconnects the remote client without stopping the worker. Coordination HTTP and engines are fixtures;
+ database authorization is covered separately by the replica-set integration above.
+- That journey found an account-authority bug: a shared machine controller could use the execution host's
+ account proxy. The gateway now conveys verified account authority separately from machine control,
+ and the Super Tab service requires it for account-backed requests. Forged payload flags do not affect it.
+ The generic boundary is committed separately as `2a976f84f7`; the feature guard and E2E are `a23509e729`.
+ Gateway/transport/service checks passed 497 tests; one unrelated fake-Grid subprocess test timed out at
+ five seconds and passed when isolated. The complete affected API/process coverage scope passed 73 tests
+ with 100% statements, branches, functions and lines. The wider unchanged core gate evidence remains valid.
+- Final appearance and keyboard pass (`85df17ec14`): 13 conversation/native-message Flutter checks passed,
+ including keyboard containment in the collapsed sidebar, Escape returning to the preserved draft and
+ selecting a group without losing that draft. Focused Dart analysis found no issues. Conversation links
+ now refresh with the app appearance; composer geometry and the sidebar backdrop use the shared tokens.
+ Light/dark and 200% text system-font renders were inspected again. These remain widget fixtures.
+- Local macOS review app rebuilt successfully from the final UI source with the repository's renderer/signing
+ script. The CLI release bundle built with the private Darwin helper; its probe and all 56 packaged service
+ modules loaded in a disposable home. These artifacts have not been installed over a live app or daemon,
+ and the app is not an official signed/notarized internal build. Backend rollout is still required.
+- Required real-tmux suite: 60 passed, six failed, seven installed-engine rows unavailable (86.32 seconds).
+ The failures were stale expectations in unchanged tests: Codex's existing inline-transcript launch flag
+ and the existing guarded-kill callback. Both production contracts match the base commit. The fixtures now
+ check the complete launch arguments and forward the kill guard; all six affected cases passed in 10 seconds.
+ The original full run remains recorded as failed. The remaining 27 cases in the focused follow-up were
+ filtered out, not newly unavailable. Every terminal/server and home belonged to the disposable fixtures.
+
+Broad component runs and their targeted corrections are recorded above. Real-engine/native desktop
+acceptance, full-app visual inspection, final review, CI, merge, official build and release remain.
+No production deployment has occurred.
+
+Implementation remains on `feat/super-tab`, draft PR #1405. Earlier pushes failed with connection resets
+or timed out, leaving the implementation local. GitHub connectivity recovered on the conversation
+refinement pass: fetch confirmed the remote at `f2625cdafd` and main at `7476ac0303`.
+The implementation through `51a36295e5` was pushed successfully and the PR marked
+ready for automatic CI and review. The first signed internal Desktop build succeeded in
+[run 39181201156](https://github.com/autonomous-ai/openharness/actions/runs/39181201156).
+It used the Desktop inputs from that head; the subsequent exact-message lookup
+correction affected backend/CLI only. The large-text fixes below change Desktop
+inputs and require a new review build. This internal build is not a public release.
+The original research worktree's merge remains untouched.
+
+## Remaining implementation and acceptance
+
+- Review the final stable head. Preserve the broad-suite
+ results and targeted corrections above; CI must still validate the pushed head before merge.
+- Finish physical shortcut/IME and full-app visual acceptance on an official review build.
+ Publish only after the remaining implementation and validation pass, following the normal release schedule.
+
+## Follow-through
+
+### Conversation refinement validation plan, 18 October
+
+The Slack/Discord study and implementation choices are in the MVP's conversation
+craft section. This pass changes Desktop message presentation, reply parsing,
+the visible read boundary and the CLI host's native delivery text. It preserves
+the existing coordination protocol and backend reply routing.
+Run the affected Super Tab widget/controller tests, Markdown safety and keyboard
+tests, and the icon audit. Inspect system-font renders in both appearances and
+at 200% text, including a busy agent group and an active human question. Run the
+isolated macOS workspace/terminal fixture, then restore the ordinary app entrypoint.
+The new pure Flutter Markdown dependency invalidates previous Desktop build inputs;
+the final automatic Desktop CI suite and official build must use the new lockfile.
+Earlier backend/CLI evidence remains applicable to unchanged source. Run CLI
+typecheck, the host tests and the real-daemon Super Tab fixture for the changed
+native prompt, including both supported engine paths.
+
+GitHub connectivity and an unlocked Mac were verified on the resumed pass. Native
+rendering now works. The fixture's original animation settle timed out; a bounded
+protocol-readiness wait then exposed incorrect fixture capability/agent data.
+Increasing its timeout alone did not solve it. The fixture now uses the actual
+`terminal.available` wire shape and native capability response. The real macOS
+window test passes, including 20 participants, the shared conversation, the actual
+native terminal stream and its group input context. Its accounts, server and
+engine output are isolated fixtures; it does not establish live subscription or
+production-backend acceptance.
+
+- Final affected Desktop batch: 49 tests passed in about six seconds, covering
+ keyboard replies, preserved reply context, access revocation, human requests
+ scoped to their group, safe Markdown rendering, read boundaries, native launch
+ recovery, delivery decisions and workspace terminal restoration. The earlier
+ mixed batch was interrupted after a test-cleanup hang; it was not a passing run.
+- The first catch-up check found a variable-height list stopping above the actual
+ last message. The corrected follow-to-end behavior passes the regression and
+ preserves the position of someone reading older messages.
+- Dark, light and 200% system-font renders were inspected, with agent and human
+ identities, readable code, an explicit reply and a local human question. The
+ real macOS conversation and adjacent terminal captures were also inspected.
+ Focused Dart analysis found no issues. The shared icon audit passed (668 Dart
+ files, 160 catalogue symbols and 603 references).
+- CLI host: all 14 focused tests passed; CLI typecheck passed. The real-daemon
+ Super Tab E2E passed both Claude and Codex fixture paths in 34.17 seconds
+ (48.42 seconds including bundle setup). Native delivery retains the reply ID,
+ so a short answer is interpreted with the original question.
+- Review found that an older question could fall outside the agent CLI's recent
+ history. Exact-message lookup now uses the same tab/group and current caller
+ authorization. Backend and CLI typechecks passed; 23 focused CLI tests passed.
+ The replica-set run passed 19 tests and failed the new test's expected removal
+ status (404 versus the existing `AGENT_UNAVAILABLE` 409 contract). After fixing
+ that expectation, the complete new case passed: original beyond 100 messages,
+ conflicting filters, another group, non-member and withdrawn agent. The other
+ 19 cases were filtered in that follow-up, not rerun. The real-daemon fixture
+ passed exact lookup through both engine paths in 36.06 seconds (49.83 seconds
+ including bundle setup). Desktop source and its validation remain unchanged.
+- The ordinary local macOS app was rebuilt successfully after the native fixture;
+ it is no longer the integration-test entrypoint. The signed internal workflow
+ and automatic CI are in progress. Full-app physical/live-engine acceptance and
+ coordinated backend/daemon rollout remain unverified.
+
+Keep the host's durable native delivery receipt separate from backend acknowledgement. A timeout
+does not prove an instruction was not executed. Check authority immediately before queued input
+can be written. Retain assignment identity after removing its contributor so the execution host
+can still reconcile it. Verify machine unshare/re-share behavior as part of the runtime work.
+
+Measure implementation, validation, waiting, merge and publication separately from the user's
+original request. The current draft is an implementation checkpoint, not a release receipt.
+
+### CI corrections and review build, 18 October
+
+[Automatic CI at `0d1ee0815e`](https://github.com/autonomous-ai/openharness/actions/runs/39181485948)
+finished with failures in CLI shard 4 and Desktop shards 2/4. The remaining selected
+checks passed. The failed run is not passing evidence.
+
+- Two remote-device fixtures needed the explicit `accountOwner: false` field from
+ the verified authority change. The local-owner contract is unchanged.
+- Linux can immediately reuse an unlinked journal file's inode. Recording now
+ checks device, inode, size and nanosecond modification/change times, and refreshes
+ this identity after its own atomic writes. Replacement or an in-place change
+ refuses further recording instead of accepting stale memory. CLI typecheck and
+ all 29 affected device/recording/host tests passed in 1.59 seconds.
+- Both large-text layout failures reproduced locally with the deterministic test
+ font. The Add agent heading no longer consumes the result viewport; the selected
+ result stays fully visible. Compact headers show the participant count with full
+ details in accessibility/tooltip text. Text scale also informs sidebar collapse.
+ Opening Invite dismisses the compact sidebar before handing focus to the dialog.
+- The first combined follow-up passed 58 tests, failed one stale large-text Invite
+ navigation expectation, and could not load the shared picker test because its
+ Flutter test process failed the WebSocket handshake. After updating the navigation,
+ the complete delivery and shared-picker files passed all 40 tests in six seconds.
+ The original mixed command remains failed; no production assertion was removed.
+- All 11 picker/native-message checks also passed with real-font capture enabled.
+ Inspected the corrected 800×480, 200% text screenshots. Focused analysis and the
+ shared icon audit passed. The chat regression passed all eight tests, including
+ keeping question-marked updates separate from adjacent short posts.
+- The first official internal build completed signing, notarization, Gatekeeper
+ acceptance and verification of both macOS variants and all four downloads.
+ The downloaded copy launched as version 1.2.91; the installed app remains 1.2.90.
+ An empty creation page was inspected and its disposable tab closed. No instruction
+ was submitted to a live harness. Native UI automation did not activate either
+ the hidden shortcut or the ordinary Cmd-P command, so physical shortcut/IME
+ acceptance remains unverified. This is not evidence of a Super Tab-only failure.
+
+Publish the corrected head once, keep it stable through automatic CI, and run the
+required branch CLI end-to-end workflow. Rebuild the official internal Desktop
+artifact from the corrected inputs. Coordinated backend/daemon rollout remains
+necessary before the signed app can provide the full shared workflow.
+
+### Internal review installation and end-to-end follow-up, 18 October
+
+- Automatic PR CI passed for `0c135930bf`, including `ci/required`:
+ https://github.com/autonomous-ai/openharness/actions/runs/39182958100.
+ The corrected signed internal Desktop build also passed:
+ https://github.com/autonomous-ai/openharness/actions/runs/39182985112.
+ Its downloaded Apple Silicon ZIP matched the published checksum; local signature
+ and Gatekeeper checks passed. The internal 1.2.91 app and checked
+ `0.4.19-dev.0c135930bf` daemon were installed for review, with previous artifacts
+ retained. No public Desktop or CLI release was made.
+- The full branch CLI E2E run completed with failures:
+ https://github.com/autonomous-ai/openharness/actions/runs/39184795010.
+ The Mac full-disk checks passed. One new collaboration test raced edge-service
+ startup; it now waits on a read before making the sharing mutation. The old PR
+ attribution test now verifies that delegation instructions survive while removed
+ attribution stays absent, including after restart. A settings assertion now
+ includes the existing summary-visibility field.
+- The targeted follow-up used the same checked bundle, disposable homes and private
+ tmux servers: five cases passed, two Pi recovery cases failed, 40 were unselected
+ (109.17 seconds). All three corrected scenarios passed, as did both held-history
+ Close cases. The two Pi failures are identical to existing main-branch failures:
+ https://github.com/autonomous-ai/openharness/actions/runs/39104876562.
+ That existing main run also records the same queued-Close registry transaction
+ failure and stale settings assertion. The original full run remains failed;
+ these follow-ups do not relabel it as green.
+- This follow-up changes tests and this record only. Backend, daemon and Desktop
+ build inputs are unchanged; their prior validation and internal artifacts remain
+ applicable. Native keyboard automation still does not verify the hidden chord or
+ IME. Shared conversations need the matching backend before user review.
+- For this rollout the user accepted deploying the matching backend while the
+ feature stays behind its shortcut. Future feature review should use an isolated
+ internal setup before a public release.
diff --git a/docs/research/2026-10-17-one-human-many-agents/17-super-tab-mvp.md b/docs/research/2026-10-17-one-human-many-agents/17-super-tab-mvp.md
new file mode 100644
index 000000000..992664128
--- /dev/null
+++ b/docs/research/2026-10-17-one-human-many-agents/17-super-tab-mvp.md
@@ -0,0 +1,245 @@
+# Super Tab MVP interaction spec
+
+18 October 2026, review revision 09. Implementation authorized 18 October 2026. This replaces earlier UI proposals in this research folder and incorporates the subsequent corrections: a new tab type, no migration flow, and Invite in the sidebar footer.
+
+**A Super Tab is a Harness tab where people work with a lead and member agents. Open it, talk to the lead, and watch delegated work become shared group conversations.** All conversations appear in one flat sidebar. Questions, decisions and results stay with the conversation that produced them.
+
+## Create it with a hidden shortcut, reusing the Cmd+T page
+
+**ST-008 — Creation.** For this initial iteration, **Cmd+Option+Shift+T** opens a new Super Tab creation page. This is a hidden shortcut: no visible entry in the tab bar, ordinary creation page, menus, command search or shortcut help. It reuses the existing Cmd+T page, its composer, recent harnesses, controls and controller, with its primary action set to New Super Tab. Ordinary Cmd+T keeps its current page and New Harness action. Cmd+Shift+T remains New Terminal, and Cmd+Option+T retains its existing daemon action. The proposed Super Tab chord is unused in the repository's current default bindings; register it through the existing keymap rather than a separate raw key handler, and respect explicit user remaps.
+
+Choose the agent engine, computer and repository, enter the initial request, and adjust the existing model/provider, approval, account, attachment, worktree and branch settings as needed. Remembered settings prefill the form and remain editable. A person can choose Claude Code for one lead and Codex for another.
+
+The primary action for this flow is **New Super Tab**. Submission creates the configured agent as the lead in that tab and opens its conversation. Opening the form starts nothing. An empty prompt is allowed, as in the current composer. The project supplies the initial tab name; the tab's existing rename action remains available.
+
+The recent-harness list keeps its existing open behavior. Existing work is brought into a Super Tab deliberately, through Add agent. Opening a recent harness does not silently publish its history or restart it as a lead.
+
+A failed start stays with the composer and preserves the chosen settings. A pending or uncertain start reuses its receipt, so retry cannot create another lead. Only the requested lead starts at creation.
+
+## The workspace
+
+The Super Tab initially contains the Lead conversation. This illustration shows the same workspace after the lead has begun delegating. Names and activity are illustrative.
+
+```text
++---------------------------------------------------------------------------+
+| [Pilot] [Website] [New Tab] [+] [Search] [Account] |
++---------------------------------------------------------------------------+
+| | Offline editing [...] |
+| | [3 agents · 20 people] |
++----------------------+----------------------------------------------------+
+| Lead | Lead |
+| > Offline editing | Storage is done. Reconnect is ready to test. |
+| Onboarding | |
+| | Reconnect |
+| | Can someone check reconnecting on the test device? |
+| | [Firmware + device test steps, revision abc123] |
+| | |
+| | Maya |
+| | I'll try it now. |
+| | |
+| | Lead |
+| | Thanks. The device check is the remaining step. |
+| | |
+| +----------------------------------------------------+
+| [New group] [Invite] | Message... [Send] |
++----------------------+----------------------------------------------------+
+```
+
+The top row is the existing **global app bar**, which already displays the Super Tab's name. Do not repeat that name above the sidebar. **New group and Invite belong together in the sidebar footer, inside the Super Tab.** The adjacent **conversation header belongs to the selected conversation**: its title, a compact participant count and its menu. Results appear in messages.
+
+The participant count shows the agents assigned to this conversation and the people with access to the Super Tab. All of those people can read every conversation; there is no second invitation or group-access list. Twenty people still take one count in the header. Selecting the count opens a searchable, scrollable list with names and roles. Agent rows identify the engine and machine and offer **Open terminal**. **Add agent** appears with the agents in this list. Human membership is managed through the tab's Invite/People control.
+
+The sketch describes placement. Implementation uses the existing Harness typography, colors, controls and native terminal styling.
+
+**ST-001 — Flat navigation.** The sidebar has no heading or sections for leads, people or tasks. It starts with one **Lead** conversation; work groups appear at the same level. The name and an ordinary unread indicator are enough. The lead conversation appears first because it is the first conversation. New groups appear without changing the person's selection, scroll position or draft. Agent chatter does not continually reorder the list. Navigation is personal; another collaborator opening a conversation does not move anyone else's screen.
+
+**ST-002 — Conversations and agents.** Selecting a row opens that conversation in the same main area. A lead is an agent role; a task is the work discussed in a group. The Lead conversation is for planning and coordination; work groups contain the agents responsible for their outcome. All are shared with the Super Tab's collaborators. This MVP does not add separate conversations for individual workers. Adding ten agents creates no extra sidebar conversations. Address a particular worker with an @mention in its work group; inspect its session through Open terminal.
+
+**ST-003 — The local controls.** The sidebar's **New group** action creates a named conversation with the lead and focuses its message composer for the brief. **Add agent** in a conversation's participant list adds an agent to that conversation. These are separate actions, each with one purpose. Add agent reuses the existing running-harness picker, including agents already shared with the tab, with New Harness available from that picker. Cmd+N opens the existing new-harness composer to create a member in the current Super Tab and selected conversation. Its destination is captured when opened and retained during a pending launch.
+
+The existing tab context menu contains Rename and Pause new work. A conversation's menu contains Work details, Rename and Archive. Completed groups remain readable and can be archived; active assignments must be resolved before archiving. Conversation search reuses the app's search surface, includes archived groups, and identifies the Super Tab in each result.
+
+## Discuss, build and intervene
+
+**ST-009 — Plan with the lead.** The initial request appears as the person's first message to the chosen lead. Brainstorm, research and agree on the approach in that conversation. Saying build authorizes delegation within the agreed scope and existing execution permissions. A new tab starts with the Lead + members playbook; there is no template-selection step in this MVP.
+
+**ST-010 — Delegate into work groups.** Reuse an existing group when it already owns the outcome. Create a new group when the agreed work can be handed to an independent harness with a named responsible agent and an acceptance check of its own. The lead posts that brief and check as the first message, names the group for the outcome, and adds the agents doing the work. For example, "Offline editing survives a reconnect" and "New users can complete onboarding" can progress independently. Writing a reconnect test belongs in Offline editing. A tool call, helper subagent or agent start does not create a group by itself. These are delegation rules for the lead, not a word-count or estimated-duration threshold.
+
+The lead reports new groups in the Lead conversation. Engine-native subagents remain available inside each harness. Work that fits in one harness can stay there. The reason to use a Super Tab is shared coordination across independent sessions, engines, machines and people: for example, one person's Codex harness works alongside another person's Claude Code harness, and either person can answer the device-check question in the work group. A group is justified by that shared work, not by an assumption that every task benefits from more agents.
+
+More leads can be added later using ordinary agent creation and the existing role action; that role change does not create another sidebar conversation. Each work group has one coordinating lead, and each active assignment has one recorded owner. This keeps several leads from dispatching the same work. A group carries durable work state, assignments, PRs and checks even though its primary presentation is a conversation.
+
+**ST-004 — Message routing.** In the Lead conversation, the tab's coordinating lead handles an unaddressed human request. In a work group, its coordinating lead handles it. An explicit mention directs a message to the named agent in that conversation; a reply to an agent's question reaches that agent and the assignment waiting for its answer. Assigned agents receive relevant decisions, answers and work updates. Posting a message does not wake every agent in the tab. Instructions that affect a member's current assignment are recorded with that work and made available to its coordinating lead.
+
+The shared conversation shows human messages, agent explanations, decisions, questions, useful progress and results. Detailed tool output and terminal traffic stay in the native harness. The author is always identified. New human-relevant messages use ordinary unread indicators; routine agent coordination does not generate a stream of notifications. People choose the existing notification preferences.
+
+**ST-007 — Human help stays in the conversation.** An agent asks where the work is happening: in the lead conversation or the relevant group. Include enough context to answer, a recommendation when useful, and a result to try when applicable. Any collaborator can reply there. The answer reaches the waiting agents and remains attached to the work. A dependency can wait while unrelated work continues. There is no global human-request list, bottom strip or separate human-approval room.
+
+**ST-006 — Native terminals.** Choose Open terminal on an agent's row in the participant list. Its existing native terminal opens **to the right of the conversation, inside this Super Tab's content area**. The sidebar stays in place, and the conversation keeps its own composer. The terminal header identifies the agent and machine and retains the existing engine controls and keyboard behavior. The shared conversation and terminal use the same running harness. Inputs are ordered, attributed and reflected in the shared record when they affect the work. Closing the terminal pane returns that space to the conversation and does not stop the harness.
+
+Direct terminal prompts and their answers are recorded in the conversation from which the terminal was opened. The record identifies the observing agent and the authenticated person who opened the session; it does not claim that the machine owner authored the text. A visible interruption replaces content whose conversation cannot be established. Tool output, private history from before opening, and unknown input are not imported. A viewer can inspect the shared terminal but cannot type through it. Loss of recording authority closes this terminal view with an explanation while the harness continues running.
+
+The conversation's lead is informed of recorded work from its member agents. The observed input is never replayed into the agent that already received it. Agents still post questions and results for ordinary delivered group instructions through the shared conversation command, as instructed when they receive that work.
+
+```text
+Same Super Tab, after Open terminal:
++----------------------+----------------------------+--------------------------+
+| | Offline editing | Reconnect · Lab Mac [x] |
+| | [3 agents · 20 people] | |
+| Lead | Shared messages | Existing native terminal |
+| > Offline editing | | |
+| Onboarding | | |
+| | | |
+| [New group] [Invite] | Message... [Send] | Native agent input |
++----------------------+----------------------------+--------------------------+
+```
+
+There is one optional terminal pane, initially closed. Opening another agent's terminal replaces the one shown in that pane without stopping either agent. It belongs to the selected conversation. Switching conversations preserves each one's draft, scroll position and terminal selection. The illustration labels existing input areas; it does not add a second wrapper composer over the native terminal. On a narrow window, the terminal uses the main area with **Back to conversation**; the app does not squeeze both into unusable columns.
+
+## People and contributions
+
+**ST-013 — Invite and manage people inside the Super Tab.** Invite is in the sidebar footer, next to New group. It opens a compact panel showing current people, pending invitations and an email field. The list scrolls and supports name/email search as it grows; it does not expand the workspace header. The owner can invite, cancel a pending invitation, or choose Remove from a person's menu. Default invitations allow collaboration; the existing viewer option remains read-only. For collaborators who cannot manage membership, the same location offers People and their own Leave action.
+
+```text
++-----------------------------------------+
+| People in Pilot |
+| |
+| You Owner |
+| Maya [...] |
+| Sam [...] |
+| |
+| Email address... [Invite] |
++-----------------------------------------+
+```
+
+Membership covers this entire Super Tab, including the Lead conversation and work groups. People can read and reply in any group without joining it separately. Invite makes the scope clear: collaborators can read these conversations and prompt the agents deliberately shared into this tab.
+
+The invitation remembers the conversation it came from. After acceptance, the teammate lands there and can read the brief and recent decisions immediately; a lead can provide a short catch-up in that conversation. A person can contribute ideas, test a result or answer questions without adding a machine or an agent.
+
+Removal ends subsequent access, posting and control through this tab's grant; prior messages retain attribution. Leaving or being removed withdraws agents contributed solely through that membership from this tab. Their processes are not silently killed. Active work is reconciled before reassignment. Independently granted team machine/model access is managed separately and is not widened by membership changes.
+
+**ST-011 — Add or start agents.** A collaborator opens the selected conversation's participant list and chooses Add agent to select a running harness, or starts a member through the existing Cmd+N form. The picker shows the session's engine, machine and project so the correct one is shared. An existing tab agent is added to this conversation without restarting or sharing it again. Attaching an outside session preserves its context and working state and explicitly shows that access is shared with the entire Super Tab. Adding it to the Lead conversation makes it available for the lead to assign; adding it to a work group supplies that group's context without claiming an assignment already held by someone else. Additional leads are roles on these agents, not another workspace level.
+
+The lead can reuse eligible agents or start workers on already authorized machines within the permitted capacity. Agent messaging is part of Super Tab coordination; opening this mode should not require discovering an unrelated experimental UI switch. Starting agents still respects the applicable execution and spawning grants. If capacity or permission is missing, the lead explains what is missing in the conversation and uses the existing setup controls to resolve it. Sharing a tab does not itself grant access to another person's machine or account.
+
+**ST-014 — Contribute capacity once.** Machines and model connections use the existing machine, account and model management surfaces. Their owners explicitly choose the people or team allowed to use them and the supported limits. Those grants are reusable across eligible Super Tabs. Adding a running agent contributes its context and capability; it does not create additional machine or model allowance. Credentials remain on authorized execution hosts.
+
+The contribution flow reuses **Machines → select a machine → Share**. A person names specific teammates or enables their team’s email domain. For a new computer, install Harness there and sign in with that person’s own account first; it appears in their Machines list. This grant is reusable across Super Tabs. Joining a Super Tab does not require contributing a machine. Sharing a whole machine grants broader access than contributing one selected running agent; the sharing surface must keep that distinction clear.
+
+**Add agent targets the selected conversation.** In Lead, the agent becomes available for delegation. In a work group, it joins that group’s discussion. The same session can participate in other groups without restarting. Adding an agent does not itself assign work or create another conversation.
+
+**ST-015 — Dispatch within capacity.** Match assignments to permissions, repository/tool availability, CPU, memory, disk, VM/device requirements and known account limits. Shared host and account limits apply across simultaneous work in all tabs. Missing or stale quota data is shown as unknown. Record the actual engine, model, effort, context and machine per attempt for later performance evaluation. Detailed resource information belongs in the existing resource/agent detail surfaces, not in every conversation row.
+
+Autonomous starts reserve their declared memory and disk budgets on the execution host before native dispatch. All Super Tabs on that host share the reservation ledger. Interrupted or pending starts keep the same reservation until a native cancellation, failure or confirmed stop establishes that its capacity can be released. Disk admission checks the destination filesystem; a managed worktree may use a different volume from its source repository. These are conservative admission budgets, with live CPU/memory-pressure checks, rather than OS-enforced quotas or predictions of future token use.
+
+## Results and completion
+
+**ST-012 — Review the actual result.** The responsible agent posts the actual deliverable, how to inspect or test it, the build/revision and the evidence already collected in the conversation. Link labels describe their destinations. There is no universal Try build button and no promise that every project can run inside Harness.
+
+| Result | What appears in the message | Where the person uses it |
+| --- | --- | --- |
+| Website | Preview URL and what to check | The existing browser |
+| Mobile app | Test distribution link or build artifact, supported device and install/test steps | The appropriate device or simulator |
+| Desktop app | Build artifact, supported operating system and launch/test steps | The appropriate computer |
+| Hardware or firmware | Artifact, target hardware, setup procedure and physical checks | The actual device or existing authorized device tooling |
+| CLI, library or research | Patch/package/document, commands or review instructions and expected results | The relevant terminal, editor or document reader |
+
+Use existing link, file and viewer handling where it applies. The message identifies required access, equipment or setup; an unavailable result remains visibly unavailable. Hardware checks that need a person are requested in this same conversation. Feedback is a reply to the result message, retaining its build/revision. Opening a link is not evidence that a test passed. PRs, review findings, logs, screenshots and recordings remain linked from the work group.
+
+A merged PR is not sufficient for completion when the brief calls for deployment, enablement or a real-world check. The team's playbook retains independent review and evidence requirements; an agent's own completion claim is not a substitute. A group remains waiting on the concrete outstanding check, visible in its messages and work details. Once the agreed acceptance checks pass, the lead posts the result and marks the work complete. The conversation stays available for follow-up or reopening.
+
+## Interaction and recovery details
+
+| Situation | What the person experiences |
+| --- | --- |
+| First creation | The selected lead opens with the initial prompt; only that conversation is present. |
+| Switching conversations | Draft, scroll position and unread position are preserved per conversation. |
+| Agent is busy | A sent message shows Queued until its recipient can take it. Urgent interruption uses the existing native agent controls. |
+| Agent or host is offline | The affected conversation explains the issue. Pending delivery remains visibly pending; unrelated work continues. |
+| Model limit reached | The lead records which work is waiting and uses another authorized eligible agent when permitted. Unknown reset times are not invented. |
+| Human question | It is an ordinary message in its originating conversation; any collaborator can answer there. |
+| Failed send or start | The same draft or operation can be retried with a visible receipt state; retry does not duplicate it. |
+| Collaborators give conflicting directions | Both authors and their messages remain visible. The responsible agent asks for clarification in that conversation before taking incompatible actions. |
+| Close the terminal pane | Hide that terminal for this person; the conversation expands. The agent keeps running on its execution machine. |
+| Close the Super Tab | Remove it from this person's app tab bar. The shared conversations, collaborators and running agents remain; reopen it through the existing History surface. |
+| Stop Harness | End the selected running agent session through the existing explicit Stop Harness action. Record its work as stopped after host confirmation, before reassignment. Closing a pane or tab never invokes this action. |
+| Pause new work | The Super Tab's local menu stops new dispatch and agent starts. Current operations finish; stopping a running harness uses its existing Stop action. |
+| Narrow window | The sidebar can collapse; an open terminal uses the main area with Back to conversation. Input remains usable. |
+| Keyboard and accessibility | Existing Cmd+T/Cmd+N, app search, Enter/Shift+Enter, IME behavior, focus return and native controls retain their meanings. Navigation does not steal focus from typing. |
+
+**ST-016 — Backend authority.** Our backend owns conversations, membership, work state and delivery records. Closing the owner's app does not remove coordination. Execution still needs its host online: work on a sleeping laptop waits, while agents on available team machines continue. Pane visibility is not membership and does not limit the number of agents the tab can coordinate.
+
+**ST-017 — Reliable delivery and ownership.** Retries cannot duplicate a conversation, group, assignment or accepted instruction. Busy-agent delivery uses supported engine behavior. A disconnected worker's ownership is reconciled before replacement; elapsed time alone does not establish that it stopped. Lead replacement restores the brief, assignments, decisions and pending deliveries. Stop/pause, revocation and recovery are backend behaviors, not labels that depend on a lead remembering a prompt.
+
+**ST-005 — Shared context.** Every conversation in a Super Tab is visible to its authorized people. The lead posts the brief and relevant context when delegating. Attaching a running agent shares only the selected session/work context deliberately. Unrelated sessions and account data are not imported because someone joined a tab.
+
+**ST-018 — Permissions.** Viewing conversations, prompting agents, changing membership and executing on machines are checked at their respective boundaries. Revocation ends subsequent access through the revoked grant. Pending deliveries recheck authorization. Terminal access and restored sessions preserve the same scope. Viewer status cannot be bypassed by opening a terminal or calling an agent tool directly.
+
+## Experimental settings
+
+**ST-020 — Coordination belongs to Super Tab.** Remove the visible account switches for Agents can start other agents, Agents in the same tab can message each other, the one-line activity summary, and the pull-request attribution line. Preserve readable legacy settings for existing clients and sessions. A Super Tab enables its own coordination within its explicit session and machine grants; creating one does not enable account-wide execution. New launches should not be instructed to add Harness branding to pull-request descriptions. Focus-bar creature, Share button and product usage sharing remain. The hidden creation shortcut is the only new entry point for now.
+
+## MVP delivery boundary
+
+The first version includes this creation flow, the shared conversations, lead delegation, heterogeneous agents across authorized machines, people joining and contributing, results, review and verification, and recovery. Lead + members is the first template. The Peers template, template editor, full leaderboard and learned quota/performance optimization follow the MVP; basic capacity checks and attempt recording start now. This is the implementation scope.
+
+**ST-019 — Additive adoption.** Super Tab is a new tab type. Existing tabs and sessions keep working. Create a fresh Super Tab and deliberately attach selected running agents through Add agent, preserving their session and working context. There is no separate migration or conversion flow. Validate the complete workflow in disposable sessions before making it available for daily use.
+
+The implementation reuses the existing composer, machine sharing, harness picker and native terminals. It adds backend coordination, flat group conversations and lead roles. Membership and work are independent of visible panes and of the owner's app remaining open. Implementation and acceptance evidence are tracked in [the build record](../../plans/2026-10-18-super-tab-build.md); the presence of code does not establish rollout readiness.
+
+Implementation references: [creation entry rules](../../../desktop/design/new-harness-entry-rules.md), [desktop design system](../../../desktop/design/desktop-design-system.md), [shared-tab flows](../../../desktop/lib/agent_messages/shared_tab_dialogs.dart), [tab leader state](../../../desktop/lib/state/app_state.dart), and [shared-tab model](../../../desktop/lib/agent_messages/shared_tabs_model.dart).
+
+## Acceptance before rollout
+
+| Check | Evidence required |
+| --- | --- |
+| Creation | Use the hidden Cmd+Option+Shift+T shortcut to create Codex and Claude Code leads through the reused page with different selected machines/repos/settings. Verify prompts and exact destinations, failure recovery and no duplicate launches. Verify ordinary Cmd+T, Cmd+Shift+T, Cmd+Option+T and explicit user remaps retain their existing behavior, and that the new command stays absent from normal menus/help. |
+| Control scope | Global navigation remains global. Invite belongs to the Super Tab's sidebar footer beside New group; group members, results and messages remain scoped to their conversation. |
+| Work loop | Plan with the lead, create a work group, delegate across two machines/engines, review, test and open the exact result. |
+| Joining | Invite a second person into the originating conversation. They can participate without contributing resources, then attach a running agent without restarting it. |
+| Sharing and removal | Exercise collaborator and viewer access, pending invite cancellation, removal, terminal control and revoked queued messages. |
+| Human help | Ask and answer in a lead conversation and a work group; verify the answer reaches only the relevant agents and unblocks the intended work. |
+| Scaling and focus | Exercise 20 people and more agents than visible panes. Participant names stay in the scrollable list; adding workers creates no sidebar chats. New groups, worker activity and another person's navigation do not move the current conversation or overwrite a draft. |
+| Delegation boundaries | Keep helper subagents and reconnect tests inside the existing outcome. Create a separate group only for separately owned, independently verifiable delegated work; record its brief and check. |
+| Terminal and close behavior | Open the named agent to the right, replace it with another, close the pane, close/reopen the Super Tab, and explicitly Stop Harness. Check exact session identity, personal navigation, team access and process lifetime at each step; exercise the narrow-window return path. |
+| Recovery | Exercise busy delivery, lost replies, a model limit, a disconnected machine, backend recovery and lead replacement without duplicate dispatch. |
+| Results and verification | Cover web, mobile, desktop, hardware and non-runnable results with real destinations and correct instructions. Tie feedback to its revision and group; keep unfinished device checks visible after merge. |
+| Additive adoption | Existing tabs keep working; attaching a running agent preserves its identity and context and clearly grants access to its selected session. Exercise the full work loop in disposable sessions. |
+
+Implementation is authorized. A review build and rollout still require the acceptance evidence above; a new Super Tab does not replace or convert an existing tab automatically.
+
+## Conversation craft: Slack and Discord study, 18 October
+
+The primary workflow is agents coordinating in shared groups. People read, direct,
+review and answer in those same conversations. The useful benchmark is how quickly
+someone can identify speakers, recover context and contribute without losing their
+place. This study uses the products' published interaction and accessibility guides;
+it does not establish user-count rankings or a comparative usability score.
+
+| What the references get right | Super Tab decision |
+| --- | --- |
+| [Slack's message display](https://slack.com/help/articles/213893898-Change-how-messages-are-displayed) separates speaker identity from message content. [Discord's spacing](https://discord.com/blog/making-discord-on-desktop-look-just-right-display-settings-to-ease-the-eyes) groups consecutive posts from one speaker and separates speaker changes. | Give both people and agents a name and identity: account initials for people, existing engine marks for agents. At most three short, single-line updates by the same author can share a header within five minutes. Long or multiline posts, question-marked updates, replies, source changes and dates retain their own header. This only reduces repeated visual noise; messages keep their own IDs and actions. Keep system typography and the Harness palette. |
+| [Discord replies](https://support.discord.com/hc/en-us/articles/360057382374-Replies-FAQ) retain the original message's context. | A person's “yes” must identify the agent's exact question; review feedback must identify the result being reviewed. Show an inline excerpt and author in the same flat group. A reply to an agent routes to that agent while it is still a participant; native delivery includes the original message reference and asks the agent to read it. The relationship survives sending and reopening. An unloaded original is labeled explicitly. |
+| [Slack unread handling](https://slack.com/help/articles/226410907-View-all-your-unread-messages) supports catching up separately from incoming activity. | Reading history must not jump as agents post. Show a new-message control and retain the reading position. Following the latest messages remains automatic when already at the end. |
+| [Slack notification controls](https://slack.com/help/articles/201355156-Configure-your-Slack-notifications) distinguish ordinary traffic from directed attention. | Routine agent traffic stays quiet. A recorded human request is visible in its originating group and clears when its work state changes. No global queue or new notification settings in this pass. |
+| [Discord keyboard navigation](https://support.discord.com/hc/en-us/articles/1500000056121-Keyboard-Navigation-FAQ) exposes message actions and clear focus without requiring a mouse. | Message actions appear on hover or focus. Keep a keyboard reply path, Escape back to the composer, existing app shortcuts, per-group drafts and IME-safe sending. |
+
+Code, lists and linked evidence should be readable as part of a conversation.
+Render Markdown with the existing type/color roles; retain selectable text and
+copyable source. Shared message content must not automatically fetch images,
+read local files or execute commands. Web links open only after a person clicks.
+Full model, effort and machine information belongs in identity details rather than
+being repeated as a dashboard on every message. Typing or working indicators must
+come from recorded activity, never invented timers.
+
+These are coordination decisions, not a social-chat feature checklist. Short
+updates can share a name visually, but agents should post useful decisions,
+questions and results rather than narrate every tool call. Replies are optional
+when ordinary conversation is already clear. There are no nested reply rooms,
+reaction systems or new global attention feeds in this pass.
+
+Reply context must also work at agent speed: the original question may already
+be outside the latest page of messages. Native delivery includes the exact
+`message GROUP MESSAGE_ID` lookup command. It reads within the same tab and group
+and rechecks the caller's current contribution; it does not depend on the
+original being in the latest 100 messages.