The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Super Tab: group terminals, team roster and contributed machines (#1436)
Dee2d174499f9ad
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 114f02d98..24e97f0cc 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -70,6 +70,55 @@ afterAll(async () => {})describe('Super Tabs on a real Mongo replica set', () => {+ it('contributes project capacity without sharing the computer and fences host execution', async () => {+ const tab = (await store.create(owner, randomUUID(), 'Machine pool')).id+ const invitation = await run(tab, { type: 'invite.create', email: host.email, role: 'collaborator', conversationId: 'lead' })+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, host)+ const contribute = { type: 'machine.contribute' as const, machineId: 'pool-host', name: 'Host laptop', cwd: '/project', engines: ['codex' as const], maxAgents: 1 }+ await db.machine.create({ data: { machineId: 'pool-host', userId: host.sub, apiKey: 'fixture-pool-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await expect(run(tab, contribute)).rejects.toMatchObject({ code: 'HOST_REQUIRED' })+ await run(tab, contribute, host)+ expect(await db.machineShare.findUnique({ where: { machineId: 'pool-host' } })).toBeNull()+ const pools = await store.hostPools(host, 'pool-host')+ expect(pools).toHaveLength(1)+ const generation = pools[0]!.machine.generation+ const observation = { generation, resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9,+ projectDiskFreeBytes: 120e9, deviceType: 'Laptop', chip: 'Fixture CPU', os: 'macOS', gpuPercent: null }, quotas: [], tools: { git: true }, runningHarnessIds: [], stoppedHarnessIds: [] }+ await expect(store.observeMachine(owner, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })+ await store.observeMachine(host, tab, 'pool-host', observation)+ const request = { conversationId: 'lead', machineId: 'pool-host', engine: 'codex', name: 'Builder', cwd: '/project', worktree: true,+ requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ await expect(run(tab, { type: 'agent.start', request: { ...request, cwd: '/private' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })+ await expect(run(tab, { type: 'agent.start', request: { ...request, permissionMode: 'bypassPermissions' } })).rejects.toMatchObject({ code: 'OUTSIDE_CONTRIBUTION' })+ const starts = await Promise.allSettled([run(tab, { type: 'agent.start', request }), run(tab, { type: 'agent.start', request })])+ expect(starts.filter(r => r.status === 'fulfilled')).toHaveLength(1)+ expect(starts.filter(r => r.status === 'rejected')).toHaveLength(1)+ const startId = (starts.find(r => r.status === 'fulfilled') as PromiseFulfilledResult<Awaited<ReturnType<typeof run>>>).value.result.startId as string+ const queued = await store.start(owner, tab, startId)+ expect(queued.poolGeneration).toBe(generation)+ await expect(run(tab, { type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })+ await expect(store.start(peer, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })+ const hostRun = (command: Command) => store.execute(host, tab, { operationId: randomUUID(), command }, undefined, 'pool-host')+ await expect(hostRun(message('Not a generic proxy'))).rejects.toMatchObject({ code: 'FORBIDDEN' })+ await run(tab, { type: 'machine.pause', machineId: 'pool-host', paused: true }, host)+ await expect(hostRun({ type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'MACHINE_PAUSED' })+ await run(tab, { type: 'machine.pause', machineId: 'pool-host', paused: false }, host)+ await hostRun({ type: 'agent.startDispatch', startId })+ await expect(hostRun({ type: 'agent.startDispatch', startId })).rejects.toMatchObject({ code: 'START_CLAIMED' })+ await hostRun({ type: 'agent.started', startId, harnessId: 'pool-builder', configuration: config })+ const pendingAgent = (await store.read(owner, tab)).state.agents[0]!+ await expect(run(tab, { type: 'work.assign', conversationId: 'lead', agentId: pendingAgent.id })).rejects.toMatchObject({ code: 'START_PENDING' })+ await expect(run(tab, contribute, host)).rejects.toMatchObject({ code: 'STARTS_PENDING' })+ await expect(run(tab, { type: 'agent.startSettled', startId, warning: null })).rejects.toMatchObject({ code: 'HOST_REQUIRED' })+ await hostRun({ type: 'agent.startSettled', startId, warning: null })+ expect((await store.start(owner, tab, startId)).poolSettled).toBe(true)+ expect((await store.read(owner, tab)).state.agents[0]).toMatchObject({ contributorId: host.sub, machineOwnerId: host.sub, harnessId: 'pool-builder' })+ await run(tab, { type: 'member.remove', userId: host.sub })+ expect(await store.hostPools(host, 'pool-host')).toEqual([])+ await expect(store.observeMachine(host, tab, 'pool-host', observation)).rejects.toMatchObject({ code: 'CONTRIBUTION_REVOKED' })+ await expect(store.start(host, tab, startId, undefined, 'pool-host')).rejects.toMatchObject({ code: 'FORBIDDEN' })+ })+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 stringdiff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 546dfdde3..4b37b105b 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -8,6 +8,7 @@ import { SuperTabError } from '../superTabs/model.js'import { SuperTabStore } from '../superTabs/store.js'import { routingPolicySchema } from '../superTabs/routingPolicy.js'import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'+import { machineObservationSchema } from '../superTabs/machines.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const tabParams = z.object({ tabId: id })@@ -23,6 +24,8 @@ const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegat.refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.')const decisionParams = tabParams.extend({ decisionId: id })const hostParams = z.object({ machineId: id })+const hostStartParams = hostParams.extend({ tabId: id, startId: id })+const machineParams = hostParams.extend({ tabId: id })const deliveryParams = tabParams.extend({ agentId: id })const deliveryActionParams = deliveryParams.extend({ deliveryId: id })const deliveryAction = z.discriminatedUnion('type', [@@ -42,6 +45,18 @@ async function respond(reply: FastifyReply, action: () => Promise<unknown>) {/** 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.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/pools', { preHandler: validateParams(hostParams) },+ (req, reply) => respond(reply, () => store.hostPools(req.user!, req.params.machineId)))+ app.get<{ Params: z.infer<typeof hostStartParams> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId', { preHandler: validateParams(hostStartParams) },+ (req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, undefined, req.params.machineId)))+ app.post<{ Params: z.infer<typeof hostStartParams>; Body: z.infer<typeof operationSchema> }>('/api/super-tabs/hosts/:machineId/starts/:tabId/:startId',+ { preHandler: [validateParams(hostStartParams), validateBody(operationSchema)] }, (req, reply) => respond(reply, async () => {+ if (!('startId' in req.body.command) || req.body.command.startId !== req.params.startId) throw new SuperTabError('FORBIDDEN', 'The host request must name this start.', 403)+ return store.execute(req.user!, req.params.tabId, req.body, undefined, req.params.machineId)+ }))+ app.post<{ Params: z.infer<typeof machineParams>; Body: z.infer<typeof machineObservationSchema> }>('/api/super-tabs/:tabId/machines/:machineId',+ { preHandler: [validateParams(machineParams), validateBody(machineObservationSchema)] },+ (req, reply) => respond(reply, () => store.observeMachine(req.user!, req.params.tabId, req.params.machineId, req.body)))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)))diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 7bf8ef0c0..2210d1172 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,3 +1,4 @@+import { admitMachineStart, machineContribution } from './machines.js'import { z } from 'zod'import {activeWork, actorKey, agent, author, conversation, fail, person, stableId,@@ -29,6 +30,8 @@ export const startRequestSchema = z.object({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('machine.contribute'), machineId: id, name: title, cwd: path, engines: z.array(z.enum(['claude', 'codex'])).min(1).max(2), maxAgents: z.number().int().min(1).max(16) }).strict(),+ z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),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('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),@@ -39,6 +42,7 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('agent.start'), request: startRequestSchema, routeDecisionId: id.optional(), overrideReason: reason.optional() }).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.startSettled'), startId: id, warning: z.string().max(2000).nullable() }).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(),@@ -156,6 +160,23 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}switch (command.type) {+ case 'machine.contribute': {+ if (actor.kind !== 'person' || context.contribution?.machineOwnerId !== actor.userId) fail('OWNER_REQUIRED', 'Only the machine owner can contribute it.', 403)+ const contributor = person(state, actor.userId)+ state.machines ??= []+ if (!state.machines.some(m => m.machineId === command.machineId) && state.machines.length >= 32) fail('MACHINES_FULL', 'A Super Tab can have up to 32 contributed machines.')+ if (state.starts?.some(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error)) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')+ state.machines = state.machines.filter(m => m.machineId !== command.machineId)+ state.machines.push({ machineId: command.machineId, name: command.name, cwd: command.cwd, engines: [...new Set(command.engines)], maxAgents: command.maxAgents,+ contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused: false })+ break+ }+ case 'machine.pause': {+ const pool = machineContribution(state, command.machineId) ?? fail('NOT_FOUND', 'This machine has not been contributed.', 404)+ if (actor.kind !== 'person' || actor.userId !== pool.contributorId) fail('OWNER_REQUIRED', 'Only its contributor can change this machine.', 403)+ pool.paused = command.paused+ break+ }case 'tab.rename':controls(state, actor)state.name = command.name@@ -240,7 +261,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (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),+ const pool = admitMachineStart(state, command.request, context.now)+ state.starts.push({ ...(pool ? { poolGeneration: pool.generation } : {}), ...(command.routeDecisionId ? { routeDecisionId: command.routeDecisionId } : {}), 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@@ -257,6 +279,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}case 'agent.startDispatch':case 'agent.started':+ case 'agent.startSettled':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)@@ -269,10 +292,19 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {fail('CONTRIBUTION_REVOKED', 'The original machine grant was revoked.', 403)}+ admitMachineStart(state, start.request, context.now, start)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 = truebreak}+ if (command.type === 'agent.startSettled') {+ if (!start.poolGeneration || !start.harnessId || start.error) fail('START_PENDING', 'This contributed start is not ready to settle.')+ if (!start.poolSettled) message(start.request.conversationId, command.warning+ ? `${start.request.name}: ${command.warning}`+ : `${start.request.name} is ready for an assignment.`)+ start.poolSettled = true+ break+ }if (command.type === 'agent.startFailed') {if (start.harnessId) fail('ALREADY_STARTED', 'This agent already started.')start.error = command.error@@ -293,7 +325,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commagroup.agentIds.push(agentId)start.harnessId = command.harnessIdresult.agentId = agentId- message(group.id, `${start.request.name} joined. Ready for an assignment.`)+ message(group.id, start.poolGeneration+ ? `${start.request.name} joined. Preparing its model.`+ : `${start.request.name} joined. Ready for an assignment.`)break}case 'agent.configuration': {@@ -357,6 +391,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (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.machines = state.machines?.filter(m => m.contributorId !== member.id)state.people = state.people.filter(p => p.id !== member.id)state.invitations = state.invitations.filter(i => i.email !== member.email)result.removedUserId = member.id@@ -456,6 +491,10 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commabreak}case 'work.assign': {+ const target = agent(state, command.agentId)+ if (state.starts?.some(s => s.poolGeneration && !s.poolSettled && s.request.machineId === target.machineId && s.harnessId === target.harnessId)) {+ fail('START_PENDING', 'Wait for the host to finish this agent’s launch and model selection.')+ }controls(state, actor, command.conversationId)const group = open(state, command.conversationId)if (state.paused) fail('PAUSED', 'New work is paused in this Super Tab.')diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsnew file mode 100644index 000000000..30fd058e6--- /dev/null+++ b/backend/src/superTabs/machines.ts@@ -0,0 +1,75 @@+import { z } from 'zod'+import { fail, person, type AgentStart, type AgentStartRequest, type SuperTabState } from './model.js'++/** An explicit grant for this tab and project. It never creates a MachineShare. */+export interface ContributedMachine {+ machineId: string+ name: string+ contributorId: string+ membershipGeneration: string+ generation: string+ cwd: string+ engines: string[]+ maxAgents: number+ paused: boolean+ observation?: MachineObservation & { receivedAt: number }+}+const measure = z.number().finite().nonnegative().nullable()+const percent = z.number().min(0).max(100).nullable()+const resource = z.object({+ cpuPercent: percent, memoryTotalBytes: measure, memoryUsedBytes: measure,+ diskFreeBytes: measure, diskTotalBytes: measure,+ projectDiskFreeBytes: measure, projectDiskTotalBytes: measure.optional(),+ deviceType: z.string().max(120).nullable(), chip: z.string().max(120).nullable(), os: z.string().max(120).nullable(),+ gpuPercent: percent,+}).strict()+const quota = z.object({ engine: z.enum(['claude', 'codex']), known: z.boolean(),+ windows: z.array(z.object({ name: z.string().max(80), usedPercent: z.number().min(0).max(100),+ resetsAt: z.union([z.string().max(80), z.number().finite(), z.null()]) }).strict()).max(10),+}).strict()+export const machineObservationSchema = z.object({ generation: z.string().max(160), resources: resource,+ tools: z.record(z.string().max(80), z.boolean()).refine(v => Object.keys(v).length <= 20),+ quotas: z.array(quota).max(2), runningHarnessIds: z.array(z.string().max(160)).max(1000),+ stoppedHarnessIds: z.array(z.string().max(160)).max(1000),+}).strict()+export type MachineObservation = z.infer<typeof machineObservationSchema>++export function machineContribution(state: SuperTabState, machineId: string) {+ const pool = state.machines?.find(m => m.machineId === machineId)+ if (!pool) return null+ const contributor = person(state, pool.contributorId)+ if (contributor.role === 'viewer' || contributor.generation !== pool.membershipGeneration) {+ fail('CONTRIBUTION_REVOKED', 'This machine contribution was withdrawn.', 403)+ }+ return pool+}++/** Pending intents reserve slots too. Only an explicit host stop frees a launched slot. */+export function machineSlots(state: SuperTabState, pool: ContributedMachine) {+ const stopped = new Set(pool.observation?.stoppedHarnessIds ?? [])+ const running = new Set(pool.observation?.runningHarnessIds ?? [])+ for (const a of state.agents) if (a.machineId === pool.machineId && !stopped.has(a.harnessId)) running.add(a.harnessId)+ let pending = 0+ for (const start of state.starts ?? []) {+ if (start.request.machineId !== pool.machineId || start.error) continue+ if (start.harnessId) { if (!stopped.has(start.harnessId)) running.add(start.harnessId) }+ else pending+++ }+ return running.size + pending+}++export function admitMachineStart(state: SuperTabState, request: AgentStartRequest, now: number, start?: AgentStart) {+ const pool = machineContribution(state, request.machineId)+ if (!pool) return null+ if (start && start.poolGeneration !== pool.generation) fail('CONTRIBUTION_REVOKED', 'This machine contribution changed. Reconcile the original start.', 403)+ if (pool.paused) fail('MACHINE_PAUSED', 'New work is paused on this machine.')+ if (request.cwd !== pool.cwd || !pool.engines.includes(request.engine)+ || request.codexHome || request.gridModel || request.gridName || request.permissionMode) {+ fail('OUTSIDE_CONTRIBUTION', 'Use the contributed project, engine and default account settings.', 403)+ }+ if (!pool.observation || now - pool.observation.receivedAt > 45_000) {+ fail('MACHINE_OFFLINE', 'Wait for a fresh reading from the contributed machine.')+ }+ if (!start && machineSlots(state, pool) >= pool.maxAgents) fail('MACHINE_FULL', 'This machine has reached its contributed agent limit.')+ return pool+}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex c993cfc03..ca103bf5b 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -40,6 +40,9 @@ export interface AgentStartRequest {requirements: { memoryBytes: number; diskBytes: number; maxCpuPercent: number; tools: string[]; devices: string[]; quotaRequired: boolean }}export interface AgentStart {+ poolGeneration?: string+ poolSettled?: boolean+ routeDecisionId?: stringid: stringcreationId: stringactorKey: string@@ -100,6 +103,7 @@ export interface SuperTabState {conversations: Conversation[]invitations: Invitation[]starts?: AgentStart[]+ machines?: import('./machines.js').ContributedMachine[]}export type Actor =| { kind: 'person'; userId: string; email: string }diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 99f45d4f4..0f3daa259 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,3 +1,4 @@+import { machineContribution, machineObservationSchema, machineSlots, type MachineObservation } from './machines.js'import { createHash } from 'node:crypto'import type { Prisma, PrismaClient, SuperTab, SuperTabDelivery } from '@prisma/client'import type { AuthUser } from '../lib/ssoAuth.js'@@ -23,7 +24,7 @@ const stateOf = (row: SuperTab): SuperTabState => {}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),+ machineIds: [...new Set([...state.agents.map(a => a.machineId), ...(state.machines ?? []).map(m => m.machineId),...state.conversations.filter(activeWork).map(c => c.assignment!.execution.machineId)])],})@@ -113,11 +114,18 @@ export class SuperTabStore {}}- private async contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }) {+ private async contribution(tx: Transaction, state: SuperTabState, actor: Actor, command: { machineId: string }, pooled = false) {const contributorId = actor.kind === 'person' ? actor.userId : agent(state, actor.agentId).contributorIdperson(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)+ if (pooled) {+ const pool = machineContribution(state, command.machineId)+ if (pool) {+ if (pool.contributorId !== machine.userId) fail('CONTRIBUTION_REVOKED', 'The machine owner changed.', 403)+ return { machineOwnerId: machine.userId, contributorId: pool.contributorId, hostGrant: null }+ }+ }let hostGrant: string | null = nullif (machine.userId !== contributorId) {const contributor = actor.kind === 'person' ? { email: actor.email, autonomousEnv: state.environment } :@@ -172,14 +180,14 @@ export class SuperTabStore {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) }+ return { revision: row.revision, state: { ...visibleState(state, actor), machines: state.machines?.map(pool => ({ ...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, pool)) })) } }})}- async start(user: AuthUser, tabId: string, startId: string, asAgentId?: string) {+ async start(user: AuthUser, tabId: string, startId: string, asAgentId?: string, hostMachineId?: 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)+ const actor = hostMachineId ? await this.poolHostActor(tx, user, state, hostMachineId, startId) : 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) {@@ -188,8 +196,8 @@ export class SuperTabStore {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 (state.paused && !start.harnessId && !start.dispatched) fail('PAUSED', 'New work is paused in this Super Tab.')+ const grant = await this.contribution(tx, state, actor, start.request, true)if (grant.machineOwnerId !== start.machineOwnerId || (grant.hostGrant ?? null) !== start.hostGrant) {fail('CONTRIBUTION_REVOKED', 'This start belongs to a machine grant that was revoked.', 403)}@@ -197,12 +205,15 @@ export class SuperTabStore {})}- async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string) {+ async execute(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: 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)+ if (hostMachineId && !['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) fail('FORBIDDEN', 'A host can only settle its queued starts.', 403)+ const actor = hostMachineId && 'startId' in command+ ? await this.poolHostActor(tx, user, original, hostMachineId, command.startId)+ : 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 } })@@ -215,6 +226,10 @@ export class SuperTabStore {}if (command.type !== 'invite.accept') author(original, actor)const context: CommandContext = { operationId, now: this.now() }+ if ('startId' in command && ['agent.startDispatch', 'agent.started', 'agent.startFailed', 'agent.startSettled', 'route.modelResult'].includes(command.type)) {+ const start = original.starts?.find(s => s.id === command.startId)+ if (start?.poolGeneration && !hostMachineId) fail('HOST_REQUIRED', 'Only the contributed machine can confirm this start.', 403)+ }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)@@ -234,11 +249,11 @@ export class SuperTabStore {// 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 === 'machine.contribute' || 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, true)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)+ context.contribution = await this.contribution(tx, original, actor, start.request, true)}if (command.type === 'message.send' && command.replyTo) {const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })@@ -389,6 +404,59 @@ export class SuperTabStore {}/** Host polling discovers only registered sessions on its own machine, never unrelated tab transcripts. */+ /** Narrow authority: the machine owner can finish a specific queued start,+ * never submit arbitrary commands as its initiating person or lead. */+ private async poolHostActor(tx: Transaction, user: AuthUser, state: SuperTabState, machineId: string, startId: string): Promise<Actor> {+ const start = state.starts?.find(s => s.id === startId) ?? fail('NOT_FOUND', 'This start is unavailable.', 404)+ const pool = machineContribution(state, machineId)+ if (!pool || pool.contributorId !== user.sub || pool.generation !== start.poolGeneration || start.request.machineId !== machineId || start.machineOwnerId !== user.sub) {+ fail('FORBIDDEN', 'This start does not belong to this machine contribution.', 403)+ }+ 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)+ let actor: Actor+ if (start.actorKey.startsWith('agent:')) {+ const lead = agent(state, start.actorKey.slice(6))+ await this.agentGrant(tx, state, lead)+ actor = { kind: 'agent', agentId: lead.id, machineOwnerId: lead.machineOwnerId }+ } else {+ const member = person(state, start.actorKey.slice(7))+ actor = { kind: 'person', userId: member.id, email: member.email }+ }+ author(state, actor, true)+ return actor+ }++ async hostPools(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 => {+ const state = stateOf(row)+ let pool+ try { pool = machineContribution(state, machineId) } catch (error) { if (error instanceof SuperTabError) return []; throw error }+ if (!pool || pool.contributorId !== user.sub) return []+ const starts = (state.starts ?? []).filter(s => s.request.machineId === machineId && s.poolGeneration === pool.generation && (!s.harnessId || !s.poolSettled) && !s.error)+ return [{ tabId: row.id, paused: state.paused, machine: pool, starts, harnessIds: [...new Set([...state.agents.filter(a => a.machineId === machineId).map(a => a.harnessId), ...(state.starts ?? []).filter(s => s.request.machineId === machineId && s.harnessId).map(s => s.harnessId!)])] }]+ })+ })+ }++ async observeMachine(user: AuthUser, tabId: string, machineId: string, input: MachineObservation) {+ const observation = machineObservationSchema.parse(input)+ return transaction(this.db, async tx => {+ const row = await this.row(tx, user, tabId), state = structuredClone(stateOf(row))+ const pool = machineContribution(state, machineId)+ if (!pool || pool.contributorId !== user.sub || pool.generation !== observation.generation) fail('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403)+ 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)+ pool.observation = { ...observation, quotas: observation.quotas.filter(q => pool.engines.includes(q.engine)), receivedAt: this.now() }+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { state: json(state), revision: row.revision + 1 } })+ return { revision: row.revision + 1 }+ })+ }+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 } })diff --git a/cli/e2e/superTabMachines.e2e.ts b/cli/e2e/superTabMachines.e2e.tsnew file mode 100644index 000000000..25400a652--- /dev/null+++ b/cli/e2e/superTabMachines.e2e.ts@@ -0,0 +1,104 @@+/** Two accounts with no machine share. The owner executes a tab-scoped queue;+ * Mongo integration tests cover authorization, while this exercises real native receipts. */+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 { LocalClient } from './harness/client.js'+import { CLI_ROOT, until, type IsolatedDaemon } from './harness/daemon.js'+import { FakeBackend } from './harness/fakeBackend.js'+import { signedInDaemon } from './harness/fleet.js'++let relay: FakeBackend | undefined+const daemons: IsolatedDaemon[] = [], clients: LocalClient[] = []+afterEach(async () => {+ clients.splice(0).forEach(c => c.close())+ await Promise.allSettled(daemons.splice(0).map(d => d.close()))+ await relay?.close(); relay = undefined+})++it('queues a teammate start without granting general machine access and resumes the same native receipt', async () => {+ const backend = await FakeBackend.start(); relay = backend+ const specs = [+ { machineId: 'd1'.repeat(16), computerId: 'pool-lead-fixture', name: 'Lead fixture', token: 'fixture-lead-token', account: 'lead', email: '[email protected]' },+ { machineId: 'd2'.repeat(16), computerId: 'pool-member-fixture', name: 'Member fixture', token: 'fixture-member-token', account: 'member', email: '[email protected]' },+ ]+ for (const spec of specs) {+ backend.addMachine(spec)+ const d = await signedInDaemon(backend, spec, { ANTHROPIC_API_KEY: 'fixture-only', OPENAI_API_KEY: 'fixture-only' })+ daemons.push(d)+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))+ }+ const [a, b] = daemons, [leadMachine, memberMachine] = specs+ const project = join(b.projectsDir, 'contributed'); mkdirSync(project, { recursive: true })+ const agents: Array<Record<string, any>> = [], starts = new Map<string, Record<string, any>>()+ let generation = 'grant-1', observations = 0+ const pool = { machineId: memberMachine.machineId, generation, cwd: project, engines: ['codex'], maxAgents: 2, paused: false }+ const id = (machine: string, harness: string) => createHash('sha256').update(JSON.stringify([machine, harness])).digest('hex').slice(0, 24)+ backend.superTabs = async (method, raw, body, caller) => {+ const path = new URL(raw, backend.httpUrl).pathname+ if (path.endsWith('/pools')) {+ expect(path.split('/')[4]).toBe(caller.machineId)+ return { data: caller.machineId === memberMachine.machineId && generation ? [{ tabId: 'pool-tab', machine: pool, starts: [...starts.values()].filter(s => !s.harnessId || !s.poolSettled), harnessIds: agents.filter(a => a.machineId === caller.machineId).map(a => a.harnessId) }] : [] }+ }+ if (path.includes('/hosts/') && path.includes('/starts/')) {+ expect(caller.account).toBe('member')+ const start = starts.get(path.split('/').at(-1)!)!+ if (method === 'GET') return { data: start }+ const c = body.command+ if (c.type === 'agent.startDispatch') { expect(start.dispatched).toBe(false); start.dispatched = true }+ else if (c.type === 'agent.started') {+ start.harnessId = c.harnessId+ if (!agents.some(a => a.harnessId === c.harnessId)) agents.push({ id: id(caller.machineId, c.harnessId), machineId: caller.machineId, harnessId: c.harnessId, configuration: c.configuration })+ } else if (c.type === 'agent.startSettled') start.poolSettled = true+ else throw new Error(`Unexpected host operation ${c.type}`)+ return { data: { result: {} } }+ }+ if (path.includes('/hosts/')) return { data: path.endsWith('/assignments') ? [] : agents.filter(a => a.machineId === caller.machineId).map(agent => ({ tabId: 'pool-tab', agent, observers: [] })) }+ if (path.includes('/machines/')) { expect(caller.account).toBe('member'); expect(body.generation).toBe(generation); observations++; return { data: { revision: observations } } }+ if (path === '/api/super-tabs/pool-tab') return { data: { state: { id: 'pool-tab', agents }, revision: observations } }+ if (path.includes('/starts/')) return { data: starts.get(path.split('/').at(-1)!) }+ if (path.endsWith('/commands')) {+ const c = body.command+ if (c.type === 'agent.start') {+ expect(caller.account).toBe('lead')+ const startId = `start-${body.operationId}`+ if (!starts.has(startId)) starts.set(startId, { id: startId, poolGeneration: generation, creationId: `super-${startId}`, request: c.request, dispatched: false, harnessId: null })+ return { data: { result: { startId } } }+ }+ if (c.type === 'agent.configuration') return { data: { result: {} } }+ throw new Error(`Unexpected caller operation ${c.type}`)+ }+ if (path.endsWith('/deliveries')) return { data: [] }+ throw new Error(`Unexpected pool request ${path}`)+ }+ onTestFailed(() => daemons.forEach(d => console.log(d.log().split('\n').slice(-75).join('\n'))))+ await Promise.all(daemons.map(d => d.start()))+ await until('both fixture accounts connected', () => backend.nodeUp(leadMachine.machineId) && backend.nodeUp(memberMachine.machineId), 30000)+ const onA = await LocalClient.connect(a, { machineId: leadMachine.machineId }), onB = await LocalClient.connect(b, { machineId: memberMachine.machineId }); clients.push(onA, onB)+ const lead = await onA.request('agent_create', { engine: 'claude', cwd: a.projectsDir }, 90000)+ expect(lead.error, JSON.stringify(lead)).toBeUndefined()+ const leadId = id(leadMachine.machineId, lead.agent.id)+ agents.push({ id: leadId, machineId: leadMachine.machineId, harnessId: lead.agent.id })+ await onB.request('super_tabs', { action: 'wake' }, 30000)+ await until('owner reports contributed capacity', () => observations > 0, 45000)+ async function run(args: string[]) {+ let answer: Record<string, any> = {}+ const code = await superTabCommand(['--tab', 'pool-tab', '--agent', leadId, ...args], { where: () => ({ port: a.port, dataDir: a.dataDir, machineId: leadMachine.machineId, harnessPane: true }), print: line => { answer = JSON.parse(line) } })+ return { code, answer }+ }+ const request = { conversationId: 'lead', machineId: memberMachine.machineId, engine: 'codex', name: 'Pool builder', cwd: project, worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } }+ const queued = await run(['start', 'pool-builder', JSON.stringify(request)])+ expect(queued.answer, JSON.stringify(queued)).toMatchObject({ ok: true, queued: true })+ const joined = await until('owner completes the queued native receipt', async () => {+ const answer = (await run(['resume', queued.answer.startId])).answer+ return answer.harnessId ? answer : null+ }, 90000, 500)+ expect((await onB.request('agents_list')).agents).toHaveLength(1)+ expect((await onA.request('agents_list')).agents).toHaveLength(1)+ expect((await run(['start', 'pool-builder', JSON.stringify(request)])).answer.harnessId).toBe(joined.harnessId)+ expect((await onB.request('shared_machines', { action: 'get' })).emails).not.toContain(leadMachine.email)+ generation = ''+})diff --git a/cli/src/lib/machineHardware.spec.ts b/cli/src/lib/machineHardware.spec.tsindex 4b03bdf87..ea94c01bd 100644--- a/cli/src/lib/machineHardware.spec.ts+++ b/cli/src/lib/machineHardware.spec.ts@@ -1,5 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest'-import { parseDarwinGpus, parseDarwinMemory, parseLinuxMemory, parseNvidiaGpus,+import { parseDarwinDevice, parseDarwinGpus, parseDarwinMemory, parseLinuxMemory, parseNvidiaGpus,readMachineDisk, readMachineGpus, readMachineMemory } from './machineHardware.js'const mocks = vi.hoisted(() => ({ command: vi.fn(), readFile: vi.fn(), statfs: vi.fn() }))@@ -93,3 +93,9 @@ describe('optional hardware readings', () => {expect(await readMachineDisk()).toEqual({ diskFreeBytes: null, diskTotalBytes: null })})})++it('extracts device type and chip without retaining serials or UUIDs', () => {+ expect(parseDarwinDevice(JSON.stringify({ SPHardwareDataType: [{ machine_name: 'MacBook Pro', chip_type: 'Apple M2 Max', serial_number: 'private', platform_UUID: 'private' }] })))+ .toEqual({ deviceType: 'MacBook Pro', chip: 'Apple M2 Max' })+ expect(parseDarwinDevice('{}')).toEqual({ deviceType: null, chip: null })+})diff --git a/cli/src/lib/machineHardware.ts b/cli/src/lib/machineHardware.tsindex 50f1958de..c4ef0079a 100644--- a/cli/src/lib/machineHardware.ts+++ b/cli/src/lib/machineHardware.ts@@ -1,6 +1,6 @@import { execFile } from 'node:child_process'import { readFile, statfs } from 'node:fs/promises'-import { freemem, homedir, totalmem } from 'node:os'+import { cpus, freemem, homedir, totalmem } from 'node:os'import { parse } from 'node:path'import { promisify } from 'node:util'@@ -31,6 +31,26 @@ async function command(file: string, args: string[]): Promise<string> {})return stdout}++export function parseDarwinDevice(raw: string): { deviceType: string | null; chip: string | null } {+ const data = JSON.parse(raw) as { SPHardwareDataType?: Array<Record<string, unknown>> }+ const row = data.SPHardwareDataType?.[0]+ const label = (value: unknown) => typeof value === 'string' && value.length <= 120 ? value : null+ // Never retain serial numbers, device UUIDs or the unfiltered profiler output.+ return { deviceType: label(row?.machine_name), chip: label(row?.chip_type ?? row?.cpu_type) }+}+let device: Promise<{ deviceType: string | null; chip: string | null; os: string }> | undefined+export function readMachineDevice() {+ return device ??= (async () => {+ const base = { deviceType: null as string | null, chip: cpus()[0]?.model?.slice(0, 120) ?? null,+ os: process.platform === 'darwin' ? 'macOS' : process.platform === 'win32' ? 'Windows' : 'Linux' }+ try {+ if (process.platform === 'darwin') return { ...base, ...parseDarwinDevice(await command('/usr/sbin/system_profiler', ['SPHardwareDataType', '-json'])) }+ if (process.platform === 'linux') return { ...base, deviceType: (await readFile('/sys/class/dmi/id/product_name', 'utf8')).trim().slice(0, 120) || null }+ } catch { /* Device type is optional; utilization sampling still works. */ }+ return base+ })()+}function number(value: string | undefined): number | null {if (value == null || !/^\d+(?:\.\d+)?$/.test(value.trim())) return nullconst n = Number(value)diff --git a/cli/src/lib/machineResources.ts b/cli/src/lib/machineResources.tsindex 4bcf58403..fdf6a0bf2 100644--- a/cli/src/lib/machineResources.ts+++ b/cli/src/lib/machineResources.ts@@ -1,8 +1,11 @@import { cpus } from 'node:os'import { setTimeout as delay } from 'node:timers/promises'-import { readMachineMemory, readMachineGpus, readMachineDisk, type GpuResource, type MemoryPressure, type MemoryReading } from './machineHardware.js'+import { readMachineDevice, readMachineMemory, readMachineGpus, readMachineDisk, type GpuResource, type MemoryPressure, type MemoryReading } from './machineHardware.js'export interface MachineResources {+ deviceType?: string | null+ chip?: string | null+ os?: stringcpuPercent: number | nullmemoryUsedBytes: number | nullmemoryTotalBytes: number | null@@ -32,8 +35,8 @@ export function createMachineResourcesReader(deps: {} = {cpuTimes, memory: readMachineMemory, wait: () => delay(200), now: Date.now,hardware: async () => {- const [gpus, disk] = await Promise.all([readMachineGpus(), readMachineDisk()])- return { gpus, ...disk }+ const [gpus, disk, device] = await Promise.all([readMachineGpus(), readMachineDisk(), readMachineDevice()])+ return { gpus, ...disk, ...device }},}): () => Promise<MachineResources> {let cached: { at: number; value: MachineResources } | undefineddiff --git a/cli/src/superTabs/capacity.ts b/cli/src/superTabs/capacity.tsindex 320ac6ac2..d6aa7a7b5 100644--- a/cli/src/superTabs/capacity.ts+++ b/cli/src/superTabs/capacity.ts@@ -46,7 +46,7 @@ export async function readCapabilities(input: Json, deps = {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,+ return { ok: true, sampledAt: Date.now(), resources: { ...resources, projectDiskFreeBytes: disk?.freeBytes ?? null, projectDiskTotalBytes: disk?.totalBytes ?? null,projectDiskVolume: disk?.volume ?? null, projectDiskPath: disk?.path ?? null },tools: Object.fromEntries(toolValues), devices: Object.fromEntries(deviceValues),// A daemon from before the launch flags leaves this out, and a start then switches the model after it.diff --git a/cli/src/superTabs/disk.ts b/cli/src/superTabs/disk.tsindex bfed37ca7..8ad6f94a5 100644--- a/cli/src/superTabs/disk.ts+++ b/cli/src/superTabs/disk.ts@@ -2,7 +2,7 @@ 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 }+export interface CapacityDisk { freeBytes: number; totalBytes?: 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. */@@ -15,7 +15,7 @@ export async function readCapacityDisk(cwd: string, worktree = false, root = proconst disk = await statfs(path)const freeBytes = disk.bavail * disk.bsizeif (!Number.isSafeInteger(freeBytes) || freeBytes < 0) throw new Error('The destination disk capacity is unknown.')- return { freeBytes, volume: String(info.dev), path }+ return { freeBytes, totalBytes: disk.blocks * disk.bsize, volume: String(info.dev), path }} catch (error) {if (!worktree || (error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(path) === path) throw errorpath = dirname(path)diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.tsindex e3b57ef5b..f8e1771a9 100644--- a/cli/src/superTabs/host.ts+++ b/cli/src/superTabs/host.ts@@ -1,4 +1,5 @@import { publishObservers } from './observers.js'+import { ContributedMachines } from './machines.js'import { retainContributions } from './retention.js'import { configurationObservation } from './configuration.js'import { NativeRecorder, nativeJournalFile } from './native.js'@@ -77,6 +78,7 @@ export class SuperTabHost {private nextConfigurationsAt = 0private timer: ReturnType<typeof setTimeout> | null = nullprivate native: NativeRecorder | null = null+ private machines: ContributedMachines | null = nullconstructor(private readonly core: CoreApi, readonly machineId: string, options: SuperTabHostOptions = {}) {if (!identifier(machineId)) throw new SuperTabHostError('MACHINE_UNAVAILABLE', 'This machine is not signed in.')@@ -116,12 +118,13 @@ export class SuperTabHost {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 = setInterval(() => { void this.tick(); void this.reconcileStops(); void this.reconcileReceipts(); this.recordNative(); this.pollMachines() }, 1_000)this.timer.unref?.()void this.tick()void this.reconcileStops()void this.reconcileReceipts()this.recordNative()+ this.pollMachines()}stop(): void {this.stopped = true@@ -129,6 +132,7 @@ export class SuperTabHost {this.timer = nullthis.stopHearing()this.native?.stop()+ this.machines?.stop()this.authorized.clear()try { this.observers(this.core.dataDir, this.machineId, [], 0) } catch { /* The old snapshot expires. */ }void this.core.turns.leaseDeliveries('superTabs', {})@@ -139,6 +143,10 @@ export class SuperTabHost {this.native ??= new NativeRecorder(this.core, this.machineId)return this.native.prepare(tabId, contextId, renew, closed)}+ private pollMachines() {+ this.machines ??= new ContributedMachines(this.core, this.machineId)+ void this.machines.tick().catch(error => this.log(error instanceof Error ? error.message : String(error)))+ }private recordNative(): void {if (!this.native?.hasWork || this.stopped) returnconst failed = (error: unknown) => this.log(error instanceof Error ? error.message : String(error))diff --git a/cli/src/superTabs/machines.spec.ts b/cli/src/superTabs/machines.spec.tsnew file mode 100644index 000000000..40bc198a2--- /dev/null+++ b/cli/src/superTabs/machines.spec.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest'+import { fakeCore } from '../testing/fakeCore.js'+import { ContributedMachines } from './machines.js'+import { startAgent } from './start.js'++function fixture() {+ let now = 1000+ const core = fakeCore({ dataDir: '/isolated-pool-fixture', agents: {+ byAgent: vi.fn(id => id === 'running' ? { agentId: id } as never : undefined),+ stopped: vi.fn(async id => id === 'stopped'),+ } })+ const pool = { tabId: 'tab', machine: { machineId: 'host', generation: 'grant', cwd: '/repo', engines: ['codex'], paused: false },+ harnessIds: ['running', 'stopped'], starts: [{ id: 'start', dispatched: false }], paused: false }+ const backend = vi.fn(async (_core: unknown, method: string, path: string, _body?: unknown): Promise<unknown> => path.endsWith('/pools') ? [pool] : { revision: 1 })+ const request = vi.fn(async () => ({ providers: [{ provider: 'codex', outcome: 'answered', httpStatus: 200,+ body: { account_email: '[email protected]', secret: 'private-token', rate_limit: { primary_window: { used_percent: 25, reset_at: 1234567890 } } } }] }))+ const close = vi.fn(), open = vi.fn(async () => ({ machineId: 'host', request, close }))+ const capabilities = vi.fn(async () => ({ ok: true, resources: { cpuPercent: 20, memoryTotalBytes: 1000, memoryUsedBytes: 200, projectDiskFreeBytes: 1000 }, tools: { git: true } }))+ const start = vi.fn(async () => ({ ok: true }))+ const machine = new ContributedMachines(core, 'host', { backend, open, capabilities, start, now: () => now } as never)+ return { machine, pool, core, backend, open, close, capabilities, start, advance: () => { now += 16000 } }+}++describe('contributed machine executor', () => {+ it('publishes only scoped measurements and executes through the owner start endpoint', async () => {+ const f = fixture()+ await f.machine.tick()+ expect(f.open).toHaveBeenCalledOnce()+ expect(f.capabilities).toHaveBeenCalledWith({ cwd: '/repo', tools: ['git'], devices: [] })+ const body = f.backend.mock.calls.find(c => c[1] === 'POST')![3]+ expect(body).toMatchObject({ generation: 'grant', runningHarnessIds: ['running'], stoppedHarnessIds: ['stopped'], quotas: [{ engine: 'codex', known: true }] })+ expect(JSON.stringify(body)).not.toMatch(/private@example|private-token|account_email/)+ const [input, scoped, where] = (f.start.mock.calls as unknown[][])[0]!+ expect(input).toEqual({ tabId: 'tab', startId: 'start', hostDispatch: true })+ expect(where).toMatchObject({ machineId: 'host', dataDir: '/isolated-pool-fixture' })+ await (scoped as (p: unknown) => Promise<unknown>)({ action: 'startStatus' })+ expect(f.backend).toHaveBeenLastCalledWith(f.core, 'GET', '/api/super-tabs/hosts/host/starts/tab/start', undefined)+ expect(f.close).toHaveBeenCalledOnce()+ await f.machine.tick()+ expect(f.open).toHaveBeenCalledOnce()+ f.machine.stop(); f.advance(); await f.machine.tick()+ expect(f.open).toHaveBeenCalledOnce()+ })++ it('does not connect to a daemon without an explicit contribution', async () => {+ const f = fixture()+ f.backend.mockResolvedValue([{ tabId: 'tab', agent: { id: 'existing-agent' } }])+ await f.machine.tick()+ expect(f.open).not.toHaveBeenCalled()+ })++ it('pause blocks new work but still reconciles an already dispatched receipt', async () => {+ const f = fixture(); f.pool.machine.paused = true+ await f.machine.tick()+ expect(f.start).not.toHaveBeenCalled()+ f.pool.starts[0]!.dispatched = true+ f.advance(); await f.machine.tick()+ expect(f.start).toHaveBeenCalledOnce()+ })++ it('a lead queues a contributed start without connecting to that computer', async () => {+ const open = vi.fn()+ const scoped = vi.fn(async () => ({ ok: true, value: { creationId: 'creation', poolGeneration: 'grant', request: { machineId: 'host' } } }))+ const reply = await startAgent({ startId: 'start' }, scoped, { port: 14001, machineId: 'lead', dataDir: '/fixture' }, open)+ expect(reply).toMatchObject({ ok: true, queued: true, startId: 'start', machineId: 'host' })+ expect(open).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsnew file mode 100644index 000000000..443feb743--- /dev/null+++ b/cli/src/superTabs/machines.ts@@ -0,0 +1,80 @@+import type { CoreApi } from '../core/api.js'+import { openDaemon } from '../agentClient/daemon.js'+import { backend } from './host.js'+import { identifier, object } from './wire.js'+import { readCapabilities, quotaOf } from './capacity.js'+import { startAgent, type ScopedRequest } from './start.js'++const finite = (v: unknown) => typeof v === 'number' && Number.isFinite(v) ? v : null+const list = (v: unknown) => Array.isArray(v) ? v.map(object) : []++/** Separate from chat delivery: slow resource readers and agent launches never+ * hold up a delivery lease. Only a tab's explicit owner grant wakes this queue. */+export class ContributedMachines {+ private stopped = false+ private running: Promise<void> | null = null+ private next = 0+ private readonly cursors = new Map<string, number>()+ constructor(private readonly core: CoreApi, private readonly machineId: string,+ private readonly deps = { backend, open: openDaemon, capabilities: readCapabilities, start: startAgent, now: Date.now }) {}+ stop() { this.stopped = true }+ tick(): Promise<void> {+ if (this.stopped || this.deps.now() < this.next) return Promise.resolve()+ return this.running ??= this.poll().finally(() => { this.running = null; this.next = this.deps.now() + 15_000 })+ }+ private async poll() {+ const where = { dataDir: this.core.dataDir, port: this.core.daemon.port, machineId: this.machineId }+ const pools = list(await this.deps.backend(this.core, 'GET', `/api/super-tabs/hosts/${this.machineId}/pools`)).filter(row => identifier(row.tabId) && object(row.machine).machineId === this.machineId && identifier(object(row.machine).generation))+ if (this.stopped || pools.length === 0) return+ const local = await this.deps.open(where)+ try {+ // The existing usage reader owns its provider cache. Raw responses and+ // account credentials never leave this machine.+ const usage = await local.request('usage_read', {}, 20_000).catch(() => ({}))+ for (const row of pools) {+ try {+ if (this.stopped || !identifier(row.tabId)) return+ const pool = object(row.machine)+ if (!identifier(pool.generation) || pool.machineId !== this.machineId || typeof pool.cwd !== 'string') continue+ const observed = await this.deps.capabilities({ cwd: pool.cwd, tools: ['git'], devices: [] })+ if (this.stopped) return+ const resources = object('resources' in observed ? observed.resources : null)+ const gpus = list(resources.gpus).map(g => finite(g.utilizationPercent)).filter((n): n is number => n !== null)+ const ids = Array.isArray(row.harnessIds) ? row.harnessIds.filter(identifier) : []+ const stopped: string[] = []+ for (const id of ids) if (await this.core.agents.stopped?.(id)) stopped.push(id)+ const observation = { generation: pool.generation, tools: 'tools' in observed ? observed.tools : {},+ resources: { cpuPercent: finite(resources.cpuPercent), memoryUsedBytes: finite(resources.memoryUsedBytes), memoryTotalBytes: finite(resources.memoryTotalBytes),+ diskFreeBytes: finite(resources.diskFreeBytes), diskTotalBytes: finite(resources.diskTotalBytes), projectDiskFreeBytes: finite(resources.projectDiskFreeBytes), projectDiskTotalBytes: finite(resources.projectDiskTotalBytes),+ deviceType: typeof resources.deviceType === 'string' ? resources.deviceType : null,+ chip: typeof resources.chip === 'string' ? resources.chip : null, os: typeof resources.os === 'string' ? resources.os : null,+ gpuPercent: gpus.length ? Math.max(...gpus) : null },+ quotas: (Array.isArray(pool.engines) ? pool.engines : []).filter((e): e is string => e === 'claude' || e === 'codex').map(engine => {+ const q = quotaOf(usage, engine, false)+ return { engine, known: q.known, windows: q.windows }+ }), runningHarnessIds: ids.filter(id => !!this.core.agents.byAgent(id) && !stopped.includes(id)), stoppedHarnessIds: stopped }+ await this.deps.backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/machines/${this.machineId}`, observation)+ // Two launches per pass bounds expensive native work. Pending starts+ // keep their original receipt across network failures and host restarts.+ const pending = list(row.starts), cursor = this.cursors.get(String(row.tabId)) ?? 0+ this.cursors.set(String(row.tabId), cursor + 2)+ const round = pending.length ? [...pending.slice(cursor % pending.length), ...pending.slice(0, cursor % pending.length)].slice(0, 2) : []+ for (const start of round) {+ if (this.stopped) return+ if (!identifier(start.id) || ((row.paused || pool.paused) && !start.dispatched)) continue+ const path = `/api/super-tabs/hosts/${this.machineId}/starts/${row.tabId}/${start.id}`+ const scoped: ScopedRequest = async input => ({ ok: true, value: await this.deps.backend(this.core,+ input.action === 'startStatus' ? 'GET' : 'POST', path,+ input.action === 'startStatus' ? undefined : { operationId: input.operationId, command: input.command }) })+ try {+ const result = await this.deps.start({ tabId: row.tabId, startId: start.id, hostDispatch: true }, scoped, where, this.deps.open)+ if (result.ok === true && identifier(result.harnessId)) await scoped({ action: 'command', operationId: `settled-${start.id}`,+ command: { type: 'agent.startSettled', startId: start.id, warning: result.modelWarning ?? null } })+ }+ catch { /* Keep its durable receipt; another start must not be starved by this failure. */ }+ }+ } catch { /* Revocation or one unavailable project cannot block another contribution. */ }+ }+ } finally { local.close() }+ }+}diff --git a/cli/src/superTabs/routeCommand.spec.ts b/cli/src/superTabs/routeCommand.spec.tsindex 15a744415..6e62c9598 100644--- a/cli/src/superTabs/routeCommand.spec.ts+++ b/cli/src/superTabs/routeCommand.spec.ts@@ -575,3 +575,48 @@ describe('the context routeTask gives Jev', () => {expect(recorded(s).command.decision).not.toHaveProperty('context')})})+++describe('routing contributed capacity', () => {+ const healthy = () => ({ machineId: 'm1', name: 'Contributed laptop', cwd: '/owner/project', engines: ['claude'], paused: false,+ observation: { receivedAt: Date.now(), resources: { memoryTotalBytes: 32e9, memoryUsedBytes: 2e9, projectDiskFreeBytes: 200e9 },+ tools: { git: true }, runningHarnessIds: [], quotas: [{ engine: 'claude', known: true, windows: [{ name: '5-hour', usedPercent: 20, resetsAt: Date.now() + 3600000 }] }] } })+ async function runPool(pool: Record<string, any>, members = false, needs: Record<string, unknown> = {}) {+ const s = scoped({ context: { ok: true, value: { agentId: 'lead', tab: { state: { id: 'tab', agents: members ? agents : [agents[1]], conversations: conversations(), machines: [pool] } }, policy: { policy, warnings: [] }, machines: [] } } })+ const open = opener()+ const answer = await routeTask({ ...input, assessment: { ...input.assessment, needs } }, s, where, open)+ expect(open).not.toHaveBeenCalled()+ return { answer, s }+ }+ it('routes using owner measurements and the contributed project without opening that machine', async () => {+ const { answer } = await runPool(healthy())+ expect(answer.ok).toBe(true)+ expect(answer.next).toContain('/owner/project')+ const member = await runPool(healthy(), true)+ expect(member.answer.ok).toBe(true)+ })+ it.each([+ ['stale', (p: any) => { p.observation.receivedAt = 0 }],+ ['paused', (p: any) => { p.paused = true }],+ ['full', (p: any) => { p.availableSlots = 0 }],+ ['low disk', (p: any) => { p.observation.resources.projectDiskFreeBytes = 1 }],+ ['unknown memory', (p: any) => { delete p.observation.resources.memoryUsedBytes }],+ ['exhausted', (p: any) => { p.observation.quotas[0].windows[0].usedPercent = 100 }],+ ['no engines', (p: any) => { delete p.engines }],+ ])('withholds new starts when %s', async (_, change) => {+ const p = healthy(); change(p)+ const { answer } = await runPool(p)+ expect(answer.ok).not.toBe(true)+ })+ it('keeps unknown allowance and load distinct from zero', async () => {+ const p = healthy(); delete (p.observation.quotas[0].windows[0] as any).name+ expect((await runPool(p)).answer.ok).toBe(true)+ p.observation.quotas = []+ delete (p.observation as any).runningHarnessIds+ expect((await runPool(p)).answer.ok).toBe(true)+ expect((await runPool({ ...p, observation: {} }, true)).answer.ok).not.toBe(true)+ })+ it('refuses unobserved tools and devices, without probing arbitrary paths on a teammate computer', async () => {+ expect((await runPool(healthy(), false, { tools: ['docker'], devices: ['/dev/fixture'] })).answer.ok).not.toBe(true)+ })+})diff --git a/cli/src/superTabs/routeCommand.ts b/cli/src/superTabs/routeCommand.tsindex 3e91198e7..e410325c3 100644--- a/cli/src/superTabs/routeCommand.ts+++ b/cli/src/superTabs/routeCommand.ts@@ -117,11 +117,12 @@ export async function routeTask(input: { tabId: string; conversationId: string;const members = agents.filter(a => !busy.has(String(a.id)) && ENGINES.includes(String(object(a.configuration).engine))).map(a => withLaunchEffort(a, list(state.starts)))// The account's machines can start a new agent. A member may run on a machine only its collaborator can// open; the Lead tries that machine too, but a member there is unknown, never offline.- const machines = new Map<string, { name: string; status: string; account: boolean }>()+ const machines = new Map<string, { name: string; status: string; account: boolean; pool?: Json }>()for (const m of list(value.machines)) machines.set(String(m.machineId), { name: String(m.name), status: String(m.status ?? 'unknown'), account: true })// The Lead's own machine is the account's even when the list could not be read.if (!machines.has(where.machineId)) machines.set(where.machineId, { name: where.machineId, status: 'unknown', account: true })for (const m of members) if (!machines.has(String(m.machineId))) machines.set(String(m.machineId), { name: String(m.machineId), status: 'unknown', account: false })+ for (const pool of list(state.machines)) machines.set(String(pool.machineId), { name: String(pool.name), status: 'contributed', account: false, pool })const enabled = policy.models.filter(m => m.enabled)// The probes do not wait for the context reads: the machines, the task's folder and the group's talk and log are read@@ -176,15 +177,15 @@ export async function routeTask(input: { tabId: string; conversationId: string;warnings: [...(Array.isArray(effective.warnings) ? effective.warnings : []), ...(value.machinesUnreadable === true ? [MACHINES_UNREADABLE] : [])],next: verdict.pick.kind === 'member'? `Assign with: command OPERATION_ID {"type":"work.assign","conversationId":"${input.conversationId}","agentId":"${verdict.pick.agentId}"${decision}}`- : `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: 'Builder', cwd: assessment.needs.cwd ?? '/absolute/repo/on/that/machine',+ : `Start with: start OPERATION_ID ${JSON.stringify({ conversationId: input.conversationId, name: 'Builder', cwd: text(machines.get(verdict.pick.machineId)?.pool?.cwd) ?? assessment.needs.cwd ?? '/absolute/repo/on/that/machine',worktree: true, requirements: startRequirements(assessment.needs), machineId: verdict.pick.machineId, engine: verdict.pick.engine, model: verdict.pick.model,effort: verdict.pick.effort, ...(typeof routeDecisionId === 'string' ? { routeDecisionId } : {}) })}, then assign the started agent${decision ? ' with the same routeDecisionId' : ''}.`,}}-async function probeMachine(machineId: string, { name: machineName, status, account }: { name: string; status: string; account: boolean },+async function probeMachine(machineId: string, { name: machineName, status, account, pool }: { name: string; status: string; account: boolean; pool?: Json },members: Json[], allModels: Policy['models'], policy: Policy, a: Assessment, where: Where, open: typeof openDaemon): Promise<Probe[]> {- const models = account ? allModels : []+ const models = pool ? allModels.filter(m => Array.isArray(pool.engines) && pool.engines.includes(m.engine)) : account ? allModels : []const engines = [...new Set([...models.map(m => m.engine), ...members.map(m => String(object(m.configuration).engine) as 'claude' | 'codex')])]const memberProbe = (m: Json, refusals: string[] = [], quota = UNKNOWN_QUOTA, frame: MemberFrame | null = null): Probe => {const c = object(m.configuration), engine = String(c.engine) as 'claude' | 'codex'@@ -197,6 +198,25 @@ async function probeMachine(machineId: string, { name: machineName, status, accokind: 'new', machineId, machineName, engine: m.engine, model: m.model, effort: m.effort, quality: m.quality, cost: m.cost,quota, activity: 'new agent', known, refusals, load })const offline = () => models.map(m => newProbe(m, [OFFLINE], UNKNOWN_QUOTA, false))+ if (pool) {+ const observed = object(pool.observation), resources = object(observed.resources)+ const fresh = finite(observed.receivedAt) && Date.now() - observed.receivedAt < 45_000+ const quotas = list(observed.quotas)+ const quota = (engine: string) => { const q = quotas.find(q => q.engine === engine); return fresh && q ? quotaOf2({ known: q.known === true, windows: list(q.windows).filter(w => finite(w.usedPercent)).map(w => ({ usedPercent: w.usedPercent as number, resetsAt: w.resetsAt, name: text(w.name) ?? undefined })) }) : UNKNOWN_QUOTA }+ const blocked = [...(!fresh ? [OFFLINE] : []), ...(pool.paused ? ['New work is paused on this machine.'] : [])]+ const needs = startRequirements(a.needs), tools = object(observed.tools)+ const newReasons = [...blocked,+ ...(pool.availableSlots === 0 ? ['This machine has no available agent slots.'] : []),+ ...(!finite(resources.projectDiskFreeBytes) || resources.projectDiskFreeBytes < needs.diskBytes ? ['The project has insufficient measured free disk.'] : []),+ ...(!finite(resources.memoryTotalBytes) || !finite(resources.memoryUsedBytes) || resources.memoryTotalBytes - resources.memoryUsedBytes < needs.memoryBytes ? ['Insufficient measured free memory.'] : []),+ ...needs.tools.filter(t => tools[t] !== true).map(t => `Required tool not reported: ${t}.`),+ ...(needs.devices.length ? ['Required devices have not been reported.'] : [])]+ return [...members.map(m => memberProbe(m, fresh ? [] : [OFFLINE], quota(String(object(m.configuration).engine)))),+ ...models.map(m => newProbe(m, [...newReasons, ...(quota(m.engine).leftPercent === 0 ? ['Subscription exhausted.'] : [])], quota(m.engine), fresh && quota(m.engine).known,+ { agents: Array.isArray(observed.runningHarnessIds) ? observed.runningHarnessIds.length : null,+ freeMemoryBytes: finite(resources.memoryTotalBytes) && finite(resources.memoryUsedBytes) ? resources.memoryTotalBytes - resources.memoryUsedBytes : null,+ hasFolder: finite(resources.projectDiskFreeBytes) }))]+ }// The account says this machine is off, so nothing there can run or be asked.if (account && status === 'offline') return [...members.map(m => memberProbe(m, [OFFLINE])), ...offline()]let target: Daemondiff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 5d6b0a5f6..e9aee27eb 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -68,10 +68,15 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wher}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 }))+ routed ??= start.routeDecisionIdconst request = object(start.request), creationId = start.creationIdif (!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 }+ if (start.harnessId && (!start.poolGeneration || start.poolSettled)) return { ok: true, startId, machineId: request.machineId, harnessId: start.harnessId }+ // Contributed capacity is executed by its owner. A collaborator receives no+ // machine credentials and cannot issue arbitrary commands to that computer.+ if (start.poolGeneration && input.hostDispatch !== true) return { ok: true, queued: true, startId, machineId: request.machineId,+ detail: 'Queued on the contributed machine. Resume this start ID to read its receipt.' }const target = await open(where, request.machineId)/** What the agent runs now, as its frame says; null when the frame cannot say. */const ranNow = async (agentId: string, engine: string) => {@@ -174,7 +179,7 @@ export async function startAgent(input: Json, scoped: ScopedRequest, where: Wherconst matched = profile && profile.sessionId === nativeId && profile.engine === frame.engine ? profile : nullconst 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}`,+ const joined = start.harnessId ? { result: {} } : 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(() => {})diff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dartindex 4551eb154..ef5e8649a 100644--- a/desktop/integration_test/super_tab_native_test.dart+++ b/desktop/integration_test/super_tab_native_test.dart@@ -53,6 +53,50 @@ void main() {f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];final server = f.connection.server;server.state['name'] = 'Pilot';+ server.state['machines'] = [+ {+ 'machineId': 'm',+ 'name': 'Studio Mac',+ 'contributorId': 'owner',+ 'cwd': '/fixture/project',+ 'engines': ['claude', 'codex'],+ 'maxAgents': 4,+ 'paused': false,+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'resources': {+ 'deviceType': 'Mac Studio',+ 'chip': 'Apple M2 Max',+ 'os': 'macOS',+ 'cpuPercent': 14,+ 'gpuPercent': 2,+ 'memoryTotalBytes': 64000000000,+ 'memoryUsedBytes': 41600000000,+ 'diskTotalBytes': 1000000000000,+ 'diskFreeBytes': 130000000000,+ 'projectDiskTotalBytes': 1000000000000,+ 'projectDiskFreeBytes': 130000000000,+ },+ 'quotas': [+ for (final engine in ['claude', 'codex'])+ {+ 'engine': engine,+ 'known': true,+ 'windows': [+ {+ 'name': '5-hour',+ 'usedPercent': engine == 'claude' ? 50 : 12,+ 'resetsAt': DateTime.now()+ .add(const Duration(hours: 2))+ .millisecondsSinceEpoch,+ },+ ],+ },+ ],+ 'runningHarnessIds': [f.connection.native!['id']],+ },+ },+ ];(server.state['conversations'] as List)[0]['agentIds'] = ['lead-agent'];(server.state['conversations'] as List)[0]['leadId'] = 'lead-agent';(server.state['people'] as List).addAll(@@ -121,10 +165,9 @@ void main() {const Duration(seconds: 10),);debugPrint('Super Tab fixture: conversation settled');- expect(find.text('1 agent · 20 people'), findsOneWidget);+ expect(find.byTooltip('Invite people'), findsOneWidget);expect(find.text('CHATS'), findsNothing);- expect(find.text('New group'), findsOneWidget);- expect(find.text('Invite'), findsOneWidget);+ expect(find.text('New group'), findsNothing);final folder = Platform.environment['SUPER_TAB_NATIVE_SHOTS'];Future<void> shot(String name) async {if (folder == null) return;@@ -140,14 +183,9 @@ void main() {}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'));+ await tester.tap(+ find.byKey(ValueKey('super-member-${c!.snapshot!.agents.single.id}')),+ );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));@@ -193,7 +231,7 @@ void main() {await tester.tap(find.byType(PaneCloseButton));await tester.pumpAndSettle();expect(f.app.activeSwarm.panes, isEmpty);- expect(c!.terminalAgent('lead'), isNull);+ expect(c.terminalAgent('lead'), isNull);expect(find.byType(TerminalPanel), findsNothing);expect(reviews, 0);expect(@@ -211,9 +249,9 @@ void main() {'terminal': {'available': false},};f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];- await tester.tap(find.text('1 agent · 20 people'));- await tester.pumpAndSettle();- await tester.tap(find.text('Open terminal'));+ await tester.tap(+ find.byKey(ValueKey('super-member-${c.snapshot!.agents.single.id}')),+ );for (var i = 0;i < 120 &&diff --git a/desktop/lib/core/machine_resources.dart b/desktop/lib/core/machine_resources.dartindex 73c9e38fc..fdf46cbf5 100644--- a/desktop/lib/core/machine_resources.dart+++ b/desktop/lib/core/machine_resources.dart@@ -2,6 +2,11 @@class MachineResources {const MachineResources({this.cpuPercent,+ this.deviceType,+ this.chip,+ this.os,+ this.projectDiskFreeBytes,+ this.projectDiskTotalBytes,this.memoryUsedBytes,this.memoryTotalBytes,this.memoryPressure,@@ -11,6 +16,8 @@ class MachineResources {this.gpus = const [],});+ final String? deviceType, chip, os;+ final double? projectDiskFreeBytes, projectDiskTotalBytes;final double? cpuPercent, memoryUsedBytes, memoryTotalBytes;final String? memoryPressure;final double? swapUsedBytes, diskFreeBytes, diskTotalBytes;@@ -56,7 +63,16 @@ class MachineResources {diskTotal > 0 &&diskFree <= diskTotal;final pressure = json['memoryPressure'];+ String? label(String key) =>+ json[key] is String && (json[key] as String).length <= 120+ ? json[key] as String+ : null;return MachineResources(+ deviceType: label('deviceType'),+ chip: label('chip'),+ os: label('os'),+ projectDiskFreeBytes: number('projectDiskFreeBytes'),+ projectDiskTotalBytes: number('projectDiskTotalBytes'),cpuPercent: cpu != null && cpu <= 100 ? cpu : null,memoryUsedBytes: memoryValid ? used : null,memoryTotalBytes: memoryValid ? total : null,diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 2f6260cc6..cf54554ad 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -469,7 +469,7 @@ class _SwarmScreenState extends State<SwarmScreen> {final _newTabSources = <String, TerminalPane>{};Widget _startGuide() => WorkspaceWelcome(- key: ValueKey('welcome:${app.activeSwarmId}'),+ key: ValueKey('welcome:${app.activeSwarmId}:${app.activeSwarm.isSuperTab}'),onCommand: _runShortcut,composerBuilder: newHarnessOpensInBox? (recent) => _newHarnessEmbedded && _newHarness != null@@ -503,7 +503,8 @@ class _SwarmScreenState extends State<SwarmScreen> {: null,// What to pick up, opened into this tab the way Cmd-P opens it: a harness// as itself, a conversation Harness did not start as a harness resuming it.- app: app,+ // Super Tab creation uses the same form as Cmd-N, without recent sessions.+ app: app.activeSwarm.isSuperTab ? null : app,projects: _projects.projects,onOpen: (row) {if (_newHarness?.requestDismiss() == false) return;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 7c0b415c1..d7f119722 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -17460,11 +17460,12 @@ class AppNotifier extends ChangeNotifier {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 (pane.agentId case final agentId?) {+ controller?.hideTerminal(+ controller.selectedId,+ pane.machineId,+ agentId,+ );}}if (tab.isCompanions || tab.isDevices) {diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex a647aa5f4..3eebe3b09 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -57,6 +57,16 @@ class SuperTabController extends ChangeNotifier {}}}+ final hidden = initial['hiddenTerminals'];+ if (hidden is Map) {+ for (final entry in hidden.entries) {+ if (entry.key is String && entry.value is List) {+ _hiddenTerminals[entry.key as String] = (entry.value as List)+ .whereType<String>()+ .toSet();+ }+ }+ }final mentions = initial['mentions'];if (mentions is Map) {for (final group in mentions.entries) {@@ -102,6 +112,7 @@ class SuperTabController extends ChangeNotifier {Map<String, dynamic>? _pending;final _drafts = <String, String>{};final _terminals = <String, String>{};+ final _hiddenTerminals = <String, Set<String>>{};final _mentions = <String, Map<String, String>>{};final _readAt = <String, int>{};final _messages = <String, List<SuperTabMessage>>{};@@ -121,11 +132,47 @@ class SuperTabController extends ChangeNotifier {_pending == null ? null : superTabMap(_pending!['command']);String draft(String id) => _drafts[id] ?? '';SuperTabAgent? terminalAgent(String conversationId) {- if (accessRevoked) return null;+ return terminalAgents(conversationId).firstOrNull;+ }++ List<SuperTabAgent> terminalAgents(String conversationId) {+ if (accessRevoked) return const [];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;+ if (id == null || group == null) return const [];+ return snapshot!.agents+ .where(+ (agent) =>+ group.agentIds.contains(agent.id) &&+ (id == '*' || id == agent.id) &&+ !(_hiddenTerminals[conversationId]?.contains(agent.id) ?? false),+ )+ .toList();+ }++ void selectGroupTerminals(String conversationId) {+ if (_disposed ||+ accessRevoked ||+ snapshot?.conversation(conversationId) == null) {+ return;+ }+ _hiddenTerminals.remove(conversationId);+ _terminals[conversationId] = '*';+ _saveSoon();+ _changed();+ }++ void hideTerminal(String conversationId, String machineId, String harnessId) {+ final agent = terminalAgents(conversationId)+ .where((a) => a.machineId == machineId && a.harnessId == harnessId)+ .firstOrNull;+ if (agent == null) return;+ (_hiddenTerminals[conversationId] ??= {}).add(agent.id);+ if (terminalAgents(conversationId).isEmpty) {+ _terminals.remove(conversationId);+ }+ _saveSoon();+ _changed();}void selectTerminal(String conversationId, String? agentId) {@@ -135,7 +182,11 @@ class SuperTabController extends ChangeNotifier {true) {return;}- if (_terminals[conversationId] == agentId) return;+ if (_terminals[conversationId] == agentId &&+ _hiddenTerminals[conversationId] == null) {+ return;+ }+ _hiddenTerminals.remove(conversationId);if (agentId == null) {_terminals.remove(conversationId);} else {@@ -182,6 +233,10 @@ class SuperTabController extends ChangeNotifier {'selectedId': selectedId,'drafts': Map<String, String>.of(_drafts),'terminals': Map<String, String>.of(_terminals),+ 'hiddenTerminals': {+ for (final entry in _hiddenTerminals.entries)+ entry.key: entry.value.toList(),+ },'mentions': {for (final entry in _mentions.entries)entry.key: Map<String, String>.of(entry.value),diff --git a/desktop/lib/super_tabs/identity.dart b/desktop/lib/super_tabs/identity.dartnew file mode 100644index 000000000..074c167f9--- /dev/null+++ b/desktop/lib/super_tabs/identity.dart@@ -0,0 +1,56 @@+import 'package:flutter/material.dart';++import '../widgets/desktop_chrome.dart';++/// Stable across engine/model changes and shared by the roster and messages.+class SuperTabAvatar extends StatelessWidget {+ const SuperTabAvatar({+ super.key,+ required this.identity,+ required this.name,+ this.size = 30,+ });+ final String identity, name;+ final double size;++ @override+ Widget build(BuildContext context) {+ var hash = 0;+ for (final rune in identity.runes) {+ hash = (hash * 31 + rune) & 0x7fffffff;+ }+ hash = ((hash ^ (hash >> 16)) * 0x45d9f3b) & 0x7fffffff;+ final color = HSLColor.fromAHSL(+ 1,+ (hash % 360).toDouble(),+ .42,+ Theme.of(context).brightness == Brightness.dark ? .72 : .36,+ ).toColor();+ final words = name+ .trim()+ .split(RegExp(r'[\s@._-]+'))+ .where((w) => w.isNotEmpty)+ .toList();+ final initial = words.isEmpty+ ? '?'+ : words.first.characters.first.toUpperCase();+ return Container(+ width: size,+ height: size,+ alignment: Alignment.center,+ decoration: BoxDecoration(+ color: color.withValues(alpha: .14),+ shape: BoxShape.circle,+ ),+ child: Text(+ initial,+ style: DesktopChrome.control(+ medium: true,+ color: color,+ ).copyWith(fontSize: size * .43),+ ),+ );+ }+}++String superTabPersonName(String email) => email.split('@').first;diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartnew file mode 100644index 000000000..c43ec072e--- /dev/null+++ b/desktop/lib/super_tabs/machines.dart@@ -0,0 +1,775 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/machine_resources.dart';+import '../core/models.dart';+import '../core/test_run.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 '../state/app_state.dart';+import '../usage/models_menu_controller.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/engine_identity.dart';+import '../widgets/remote_folder_picker.dart';+import '../widgets/workspace_subscription_usage.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'identity.dart';+import 'model.dart';++class SuperTabMachines extends StatefulWidget {+ const SuperTabMachines({+ super.key,+ required this.controller,+ required this.onAddAgent,+ this.app,+ });+ final SuperTabController controller;+ final AppNotifier? app;+ final ValueChanged<SuperTabConversation> onAddAgent;+ @override+ State<SuperTabMachines> createState() => _SuperTabMachinesState();+}++class _SuperTabMachinesState extends State<SuperTabMachines> {+ final _samples = <String, (MachineResources, DateTime)>{};+ ModelsMenuController? _usage;+ Timer? _timer;+ bool _reading = false;+ int _revision = 0;+ SuperTabController get c => widget.controller;+ Set<String> get _ids => {+ for (final a in c.snapshot?.agents ?? const <SuperTabAgent>[]) a.machineId,+ for (final m in c.snapshot?.machines ?? const <Map<String, dynamic>>[])+ m['machineId'] as String,+ };++ @override+ void initState() {+ super.initState();+ if (!kUnderTest && widget.app != null) {+ _updateUsage();+ widget.app!.foreground.addListener(_foreground);+ unawaited(_refresh());+ }+ }++ void _changed() {+ if (mounted) setState(() {});+ }++ void _updateUsage() {+ if (kUnderTest || widget.app == null) return;+ if (!widget.app!.foreground.value) {+ _usage?.removeListener(_changed);+ _usage?.dispose();+ _usage = null;+ } else {+ _usage ??= ModelsMenuController(remote: widget.app!.readRemoteUsage)+ ..addListener(_changed)+ ..start();+ }+ }++ void _foreground() {+ _updateUsage();+ _revision++;+ _timer?.cancel();+ _samples.clear();+ _changed();+ if (widget.app?.foreground.value == true) unawaited(_refresh());+ }++ Future<void> _refresh() async {+ if (_reading || !mounted || widget.app?.foreground.value != true) return;+ _reading = true;+ final revision = _revision;+ try {+ final ids = _ids.toList();+ for (var i = 0; i < ids.length; i += 2) {+ await Future.wait(+ ids.skip(i).take(2).map((id) async {+ final value = await widget.app!.readMachineResources(id);+ if (!mounted || revision != _revision || !_ids.contains(id)) return;+ if (value == null) {+ _samples.remove(id);+ } else {+ _samples[id] = (value, DateTime.now());+ }+ }),+ );+ if (!mounted || revision != _revision) return;+ }+ _changed();+ } finally {+ _reading = false;+ if (mounted && widget.app?.foreground.value == true) {+ _timer = Timer(const Duration(seconds: 15), _refresh);+ }+ }+ }++ @override+ void dispose() {+ _revision++;+ _timer?.cancel();+ widget.app?.foreground.removeListener(_foreground);+ _usage?.removeListener(_changed);+ _usage?.dispose();+ super.dispose();+ }++ Future<void> _contribute({Map<String, dynamic>? existing}) async {+ final app = widget.app;+ if (app == null) return;+ existing ??= c.pendingCommand?['type'] == 'machine.contribute'+ ? c.pendingCommand+ : null;+ final choices = app.machineStates.values+ .where(+ (m) =>+ !m.machine.isShared &&+ !m.machine.isSharedMachine &&+ !m.needsLink &&+ (m.nodeOnline != false ||+ m.machine.machineId == existing?['machineId']),+ )+ .toList();+ String? machineId =+ existing?['machineId'] as String? ??+ choices.firstOrNull?.machine.machineId;+ String? folder = existing?['cwd'] as String?;+ var limit = (existing?['maxAgents'] as num?)?.toInt() ?? 2;+ final engines = {+ ...(existing?['engines'] as List? ?? const <String>[]).cast<String>(),+ };+ String? error;+ var busy = false;+ if (machineId != null) await app.probeEngines(machineId);+ if (!mounted) return;+ await showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ child: StatefulBuilder(+ builder: (context, update) {+ final recovering =+ c.pendingCommand?['type'] == 'machine.contribute';+ final locked = busy || recovering;+ final machine = app.stateOf(machineId ?? '');+ final installed = [+ 'claude',+ 'codex',+ ].where((e) => machine?.engines[e]?.installed == true).toList();+ Future<void> save() async {+ if (busy ||+ machineId == null ||+ folder == null ||+ engines.isEmpty) {+ return;+ }+ update(() {+ busy = true;+ error = null;+ });+ try {+ final capability = await app.superTabMachineRequest(+ machineId!,+ {+ 'action': 'capacity',+ 'cwd': folder,+ 'tools': ['git'],+ 'devices': [],+ },+ );+ if (capability['ok'] != true ||+ (capability['resources']+ as Map?)?['projectDiskFreeBytes'] ==+ null) {+ throw const SuperTabFailure(+ 'PROJECT_UNAVAILABLE',+ 'Choose an available project folder on this machine.',+ );+ }+ final result = c.pendingCommand?['type'] == 'machine.contribute'+ ? await c.retry()+ : await c.command({+ 'type': 'machine.contribute',+ 'machineId': machineId,+ 'name': machine!.machine.displayName,+ 'cwd': folder,+ 'engines': engines.toList()..sort(),+ 'maxAgents': limit,+ });+ if (result == null) {+ throw SuperTabFailure(+ 'CONTRIBUTION_FAILED',+ c.operationError ?? 'Could not contribute this machine.',+ );+ }+ await app.wakeSuperTabHost(machineId!);+ if (context.mounted) Navigator.pop(context);+ } catch (failure) {+ if (context.mounted) {+ update(() {+ busy = false;+ error = failure.toString();+ });+ }+ }+ }++ return AlertDialog(+ title: const Text('Contribute a machine'),+ content: SizedBox(+ width: 400,+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (choices.isEmpty)+ const Text(+ 'Connect a computer to Harness first. You can then contribute it here.',+ )+ else+ DropdownButtonFormField<String>(+ initialValue: machineId,+ decoration: const InputDecoration(+ labelText: 'Machine',+ ),+ items: [+ for (final m in choices)+ DropdownMenuItem(+ value: m.machine.machineId,+ child: Text(m.machine.displayName),+ ),+ ],+ onChanged: locked+ ? null+ : (id) async {+ update(() {+ machineId = id;+ folder = null;+ engines.clear();+ });+ if (id != null) await app.probeEngines(id);+ if (context.mounted) update(() {});+ },+ ),+ const SizedBox(height: 16),+ OutlinedButton.icon(+ icon: const Icon(AppIcons.folder, size: 16),+ label: Text(+ folder ?? 'Choose project folder',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ onPressed: locked || machineId == null+ ? null+ : () async {+ final picked = await showRemoteFolderPicker(+ context,+ notifier: app,+ machineId: machineId!,+ initialPath: folder,+ desktop: true,+ );+ if (context.mounted && picked != null) {+ update(() => folder = picked);+ }+ },+ ),+ const SizedBox(height: 12),+ Text(+ 'Allow the lead to start agents with',+ style: DesktopChrome.control(medium: true),+ ),+ for (final engine in installed)+ CheckboxListTile(+ contentPadding: EdgeInsets.zero,+ dense: true,+ title: Row(+ children: [+ EngineMark(engine: engine, size: 18),+ const SizedBox(width: 8),+ Text(engineIdentity(engine).label),+ ],+ ),+ subtitle: const Text(+ 'Account signed in on this machine',+ ),+ value: engines.contains(engine),+ onChanged: locked+ ? null+ : (value) => update(() {+ if (value == true) {+ engines.add(engine);+ } else {+ engines.remove(engine);+ }+ }),+ ),+ if (installed.isEmpty)+ Text(+ 'No supported engines reported by this machine.',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 12),+ DropdownButtonFormField<int>(+ initialValue: limit,+ decoration: const InputDecoration(+ labelText: 'Maximum agents at once',+ ),+ items: [+ for (final n in [1, 2, 3, 4, 6, 8, 12, 16])+ DropdownMenuItem(value: n, child: Text('$n')),+ ],+ onChanged: locked+ ? null+ : (n) => update(() => limit = n ?? limit),+ ),+ if (error != null)+ Padding(+ padding: const EdgeInsets.only(top: 12),+ child: Text(error!),+ ),+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ onPressed: busy ? null : () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed:+ busy ||+ machineId == null ||+ folder == null ||+ engines.isEmpty+ ? null+ : save,+ child: Text(+ busy+ ? 'Contributing…'+ : recovering+ ? 'Check contribution'+ : 'Contribute',+ ),+ ),+ ],+ );+ },+ ),+ ),+ );+ }++ Map<String, Object?> _quotaRow(Map<String, dynamic> quota, String machineId) {+ final windows =+ [for (final raw in quota['windows'] as List? ?? []) superTabMap(raw)]+ ..sort(+ (a, b) => ((b['usedPercent'] as num?) ?? 0).compareTo(+ (a['usedPercent'] as num?) ?? 0,+ ),+ );+ DateTime? reset(dynamic raw) => raw is num+ ? DateTime.fromMillisecondsSinceEpoch(+ raw > 100000000000 ? raw.toInt() : (raw * 1000).toInt(),+ )+ : raw is String+ ? DateTime.tryParse(raw)+ : null;+ final expired = windows.any(+ (w) => reset(w['resetsAt'])?.isBefore(DateTime.now()) == true,+ );+ final known = quota['known'] == true && windows.isNotEmpty && !expired;+ return {+ 'accountKey': 'machine:$machineId:${quota['engine']}',+ 'engine': quota['engine'],+ 'name': engineIdentity(quota['engine'] as String? ?? '').label,+ 'remainingPercent': known+ ? 100 - (windows.first['usedPercent'] as num)+ : null,+ 'details': [+ for (final w in windows)+ '${w['name']}: ${100 - (w['usedPercent'] as num)}% remaining${reset(w['resetsAt']) == null ? '' : ' · resets in ${_until(reset(w['resetsAt'])!)}'}',+ ],+ };+ }++ String _until(DateTime when) {+ final minutes = when.difference(DateTime.now()).inMinutes;+ return minutes <= 0+ ? 'now'+ : minutes < 60+ ? '${minutes}m'+ : minutes < 1440+ ? '${minutes ~/ 60}h ${minutes % 60}m'+ : '${minutes ~/ 1440}d';+ }++ String? _resetSummary(String detail) {+ final lines = detail.split('\n');+ final limiting = lines+ .where((l) => l.startsWith('Limiting window: '))+ .firstOrNull+ ?.substring(17);+ final line = lines+ .where(+ (l) =>+ l.contains('resets in') &&+ (limiting == null || l.contains(limiting)),+ )+ .firstOrNull;+ final reset = line == null+ ? null+ : RegExp(r'resets in ([^·\n]+)').firstMatch(line)?.group(1)?.trim();+ return reset == null ? null : 'Resets in $reset';+ }++ Widget _machine(String id) {+ final app = widget.app, state = app?.stateOf(id);+ final shared = c.snapshot?.machines+ .where((m) => m['machineId'] == id)+ .firstOrNull;+ final agents = c.snapshot!.agents.where((a) => a.machineId == id).toList();+ final contributor =+ shared?['contributorId'] as String? ??+ agents.firstOrNull?.contributorId;+ final person = c.snapshot!.people+ .where((p) => p.id == contributor)+ .firstOrNull;+ final observation = superTabMap(+ shared?['observation'] ?? const <String, dynamic>{},+ );+ final received = observation['receivedAt'];+ final fresh =+ received is num &&+ DateTime.now().millisecondsSinceEpoch - received < 45000;+ final online = shared == null+ ? state?.connectionStatus == ConnectionStatus.connected &&+ state?.nodeOnline != false+ : fresh;+ final sample = _samples[id];+ final resource = superTabMap(+ observation['resources'] ?? const <String, dynamic>{},+ );+ final value = fresh+ ? MachineResources.fromJson({+ ...resource,+ if (resource['gpuPercent'] != null)+ 'gpus': [+ {+ 'id': 'observed',+ 'name': 'GPU',+ 'utilizationPercent': resource['gpuPercent'],+ },+ ],+ })+ : online &&+ sample != null &&+ DateTime.now().difference(sample.$2) < const Duration(seconds: 45)+ ? sample.$1+ : null;+ final name =+ shared?['name'] as String? ??+ state?.machine.displayName ??+ 'Unavailable machine';+ final allowed = (shared?['engines'] as List?)?.cast<String>();+ var accounts =+ _usage?.rows+ .where(+ (row) =>+ (allowed == null || allowed.contains(row['engine'])) &&+ (state?.isLocalMachine == true+ ? row['local'] == true+ : (row['machines'] as List? ?? []).contains(+ state?.machine.displayName,+ )),+ )+ .toList() ??+ const <Map<String, Object?>>[];+ if (accounts.isEmpty && fresh) {+ accounts = [+ for (final raw in observation['quotas'] as List? ?? [])+ _quotaRow(superTabMap(raw), id),+ ];+ }+ final usage = WorkspaceSubscriptionUsage.fromRows(online ? accounts : []);+ final running = fresh+ ? (observation['runningHarnessIds'] as List? ?? []).length+ : agents+ .where(+ (a) =>+ state?.agents+ .where((n) => n.id == a.harnessId && !n.isStopped)+ .isNotEmpty ==+ true,+ )+ .length;+ final paused = shared?['paused'] == true;+ final diskTotal = value?.projectDiskTotalBytes ?? value?.diskTotalBytes;+ final diskFree = value?.projectDiskTotalBytes == null+ ? value?.diskFreeBytes+ : value?.projectDiskFreeBytes;+ final disk = diskTotal == null || diskTotal <= 0 || diskFree == null+ ? null+ : (1 - diskFree / diskTotal) * 100;+ return Padding(+ padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ InkWell(+ key: ValueKey('super-machine-$id'),+ borderRadius: BorderRadius.circular(8),+ onTap: () => showAppDialog<void>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(name),+ content: Text(+ [+ if (person != null) person.email,+ paused+ ? 'New work paused'+ : online+ ? 'Online'+ : 'Offline',+ if (shared?['cwd'] != null) shared!['cwd'] as String,+ if (allowed != null) 'Engines: ${allowed.join(', ')}',+ 'RAM: ${resourceBytes(value?.memoryTotalBytes)}',+ 'Disk: ${resourceBytes(value?.diskTotalBytes)}',+ for (final gpu in value?.gpus ?? const <MachineGpu>[])+ 'GPU: ${gpu.name}',+ if (usage.accounts.isNotEmpty) usage.detail,+ ].join('\n'),+ ),+ actions: [+ if (shared != null && contributor == c.accountId)+ TextButton(+ onPressed: () async {+ final result = await c.command({+ 'type': 'machine.pause',+ 'machineId': id,+ 'paused': !paused,+ });+ if (context.mounted && result != null) {+ Navigator.pop(context);+ }+ },+ child: Text(+ paused ? 'Resume new work' : 'Pause new work',+ ),+ ),+ if (contributor == c.accountId)+ TextButton(+ onPressed: () {+ Navigator.pop(context);+ unawaited(+ _contribute(existing: shared ?? {'machineId': id}),+ );+ },+ child: const Text('Configure'),+ ),+ if (c.canWrite && c.selected != null)+ TextButton(+ onPressed: () {+ final group = c.selected!;+ Navigator.pop(context);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) widget.onAddAgent(group);+ });+ },+ child: const Text('Attach running agent'),+ ),+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),+ ),+ ],+ ),+ ),+ child: Row(+ children: [+ Icon(+ AppIcons.monitor,+ size: 15,+ color: online+ ? DesktopChrome.foreground+ : DesktopChrome.muted,+ ),+ const SizedBox(width: 8),+ Expanded(+ child: Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ ),+ const SizedBox(width: 8),+ Text(+ paused+ ? 'Paused'+ : !online+ ? 'Offline'+ : shared == null+ ? '$running ${running == 1 ? 'agent' : 'agents'}'+ : '$running/${shared['maxAgents']}',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ ),+ if (person != null)+ Padding(+ padding: const EdgeInsets.only(top: 4),+ child: Text(+ superTabPersonName(person.email),+ style: DesktopChrome.metadata(),+ ),+ ),+ if (value != null)+ Padding(+ padding: const EdgeInsets.only(top: 4),+ child: Text(+ [+ if (value.deviceType != null) value.deviceType!,+ if (value.chip != null) value.chip!,+ if (value.os != null) value.os!,+ '${resourceBytes(value.memoryTotalBytes)} RAM',+ ].join(' · '),+ maxLines: 2,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ const SizedBox(height: 12),+ Row(+ children: [+ for (final metric in [+ ('CPU', value?.cpuPercent),+ ('GPU', value?.busiestGpu?.utilizationPercent),+ ('RAM', value?.memoryPercent),+ ('Disk', disk),+ ])+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(metric.$1, style: DesktopChrome.metadata()),+ Text(+ resourcePercent(metric.$2),+ style: DesktopChrome.text(medium: true),+ ),+ ],+ ),+ ),+ ],+ ),+ const SizedBox(height: 6),+ Text(+ 'Available: ${resourceBytes(value?.memoryTotalBytes == null ? null : value!.memoryTotalBytes! - value.memoryUsedBytes!)} RAM · ${resourceBytes(value?.projectDiskFreeBytes ?? value?.diskFreeBytes)} disk',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(height: 10),+ Text('Subscription remaining', style: DesktopChrome.metadata()),+ if (usage.accounts.isEmpty)+ Text('—', style: DesktopChrome.control())+ else+ Wrap(+ spacing: 16,+ runSpacing: 8,+ children: [+ for (final account in usage.accounts)+ Tooltip(+ message: account.detail,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ EngineMark(engine: account.engine, size: 16),+ const SizedBox(width: 6),+ Text(+ account.figure,+ style: DesktopChrome.control(+ medium: true,+ color:+ account.tone == WorkspaceUsageTone.exhausted+ ? grid.AppPalette.warn+ : null,+ ),+ ),+ ],+ ),+ if (_resetSummary(account.detail) case final reset?)+ Text(reset, style: DesktopChrome.metadata()),+ ],+ ),+ ),+ ],+ ),+ ],+ ),+ );+ }++ @override+ Widget build(BuildContext context) => Column(+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(16, 8, 12, 0),+ child: Row(+ children: [+ Expanded(+ child: Text(+ 'Machines · ${_ids.length}',+ style: DesktopChrome.metadata().copyWith(+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ if (c.canWrite && widget.app != null)+ AppIconButton(+ icon: AppIcons.plus,+ tooltip: 'Contribute a machine',+ onPressed: () => unawaited(_contribute()),+ ),+ ],+ ),+ ),+ Expanded(+ child: _ids.isEmpty+ ? Center(+ child: Padding(+ padding: const EdgeInsets.all(16),+ child: Text(+ 'Contribute a machine so the lead can start agents.',+ textAlign: TextAlign.center,+ style: DesktopChrome.metadata(),+ ),+ ),+ )+ : ListView.separated(+ itemCount: _ids.length,+ separatorBuilder: (_, _) => Divider(+ height: 1,+ indent: 16,+ endIndent: 16,+ color: DesktopChrome.rim,+ ),+ itemBuilder: (_, i) => _machine(_ids.elementAt(i)),+ ),+ ),+ ],+ );+}diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 0d37d2add..1c894209a 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -6,9 +6,10 @@ 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 'identity.dart';import 'message_text.dart';import 'model.dart';+import 'pull_requests.dart';/// Presentation only. Message identity and reply routing use backend IDs.class SuperTabMessageRow extends StatefulWidget {@@ -24,6 +25,7 @@ class SuperTabMessageRow extends StatefulWidget {this.replyAuthor,this.grouped = false,this.onReply,+ this.onOpenAgent,});final SuperTabMessage message;@@ -33,7 +35,7 @@ class SuperTabMessageRow extends StatefulWidget {final SuperTabMessage? reply;final String? replyAuthor;final bool grouped;- final VoidCallback? onReply;+ final VoidCallback? onReply, onOpenAgent;final VoidCallback onReturnToComposer;final List<Widget> receipts;@@ -187,20 +189,16 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {: ExcludeSemantics(child: Tooltip(message: _identityDetails,- child: message.fromAgent- ? EngineMark(- engine: widget.agent?.engine,- displayName: widget.author,- size: 28,- )- : AccountAvatar(- initial: accountInitial(+ child: SuperTabAvatar(+ identity:+ '${message.author['kind']}:${message.authorId}',+ name: message.fromAgent+ ? widget.author+ : superTabPersonName(message.authorName,- null,),- diameter: 28,- accent: DesktopChrome.muted,- ),+ size: 28,+ ),),),),@@ -218,17 +216,19 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {crossAxisAlignment:WrapCrossAlignment.center,children: [- Text(widget.author, style: authorStyle),+ InkWell(+ onTap: widget.onOpenAgent,+ child: 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(),+ child: EngineMark(+ engine: widget.agent?.engine,+ size: 14,),),if (message.createdAt case final time?)@@ -270,6 +270,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),),SuperTabMessageText(message.text),+ SuperTabPullRequestLinks(message.text),...widget.receipts,],),diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 133dfd935..072ec96dc 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -67,6 +67,10 @@ class SuperTabSnapshot {paused = row['paused'] == true,people = _list(row['people'], SuperTabPerson.fromJson),agents = _list(row['agents'], SuperTabAgent.fromJson),+ machines = _list(+ row['machines'] ?? const [],+ (m) => Map<String, dynamic>.unmodifiable(m),+ ),conversations = _list(row['conversations'],SuperTabConversation.fromJson,@@ -83,6 +87,7 @@ class SuperTabSnapshot {final bool paused;final List<SuperTabPerson> people;final List<SuperTabAgent> agents;+ final List<Map<String, dynamic>> machines;final List<SuperTabConversation> conversations;final List<Map<String, dynamic>> invitations;SuperTabConversation? conversation(String id) =>diff --git a/desktop/lib/super_tabs/pull_requests.dart b/desktop/lib/super_tabs/pull_requests.dartnew file mode 100644index 000000000..67daced8c--- /dev/null+++ b/desktop/lib/super_tabs/pull_requests.dart@@ -0,0 +1,261 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:url_launcher/url_launcher.dart';++import '../core/pull_request_status.dart';+import '../shared/theme/app_icons.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'model.dart';++List<Uri> superTabPullRequestLinks(String text) => {+ for (final match in RegExp(+ r'https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)\b',+ ).allMatches(text))+ Uri.parse(match.group(0)!),+}.toList();++class SuperTabPullRequestLinks extends StatelessWidget {+ const SuperTabPullRequestLinks(this.text, {super.key});+ final String text;+ @override+ Widget build(BuildContext context) {+ final links = superTabPullRequestLinks(text);+ if (links.isEmpty) return const SizedBox.shrink();+ return Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Wrap(+ spacing: 8,+ runSpacing: 6,+ children: [+ for (final link in links.take(4))+ OutlinedButton.icon(+ onPressed: () => unawaited(+ launchUrl(link, mode: LaunchMode.externalApplication),+ ),+ icon: const Icon(AppIcons.externalLink, size: 14),+ label: Text(+ '${link.pathSegments[1]} · PR #${link.pathSegments[3]}',+ ),+ ),+ ],+ ),+ );+ }+}++/// Links are evidence of a PR reference, never evidence that checks passed or+/// that its task is finished. Only the owning machine supplies current state.+class SuperTabPullRequests extends StatefulWidget {+ const SuperTabPullRequests({super.key, required this.controller, this.app});+ final SuperTabController controller;+ final AppNotifier? app;+ @override+ State<SuperTabPullRequests> createState() => _SuperTabPullRequestsState();+}++class _SuperTabPullRequestsState extends State<SuperTabPullRequests> {+ final _observed = <String, PullRequestStatus>{};+ bool _all = false, _loading = false;+ String? _scope;+ int _revision = 0;+ Timer? _timer;+ SuperTabController get c => widget.controller;+ List<SuperTabConversation> get _groups =>+ c.snapshot?.conversations+ .where((g) => _all || g.id == c.selectedId)+ .toList() ??+ const [];++ @override+ void initState() {+ super.initState();+ c.addListener(_changed);+ _changed();+ }++ @override+ void didUpdateWidget(SuperTabPullRequests oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.controller != c) {+ oldWidget.controller.removeListener(_changed);+ c.addListener(_changed);+ _scope = null;+ _changed();+ }+ }++ void _changed() {+ final scope = '${c.accountId}:${c.tabId}:${_all ? '*' : c.selectedId}';+ if (scope != _scope) {+ _scope = scope;+ _observed.clear();+ unawaited(_refresh());+ } else if (mounted) {+ setState(() {});+ }+ }++ Future<void> _refresh() async {+ final revision = ++_revision;+ _timer?.cancel();+ setState(() => _loading = true);+ final groups = _groups;+ if (_all) {+ // The controller owns paging and caches; this never changes selection.+ for (final group in groups) {+ if (!mounted || revision != _revision) return;+ await c.loadMessages(group.id);+ }+ }+ final agents =+ c.snapshot?.agents+ .where((a) => groups.any((g) => g.agentIds.contains(a.id)))+ .toList() ??+ const <SuperTabAgent>[];+ final values = <String, PullRequestStatus>{};+ for (var i = 0; i < agents.length; i += 2) {+ await Future.wait(+ agents.skip(i).take(2).map((agent) async {+ try {+ final answer = await widget.app?.readAgentPullRequest(+ agent.machineId,+ agent.harnessId,+ );+ final value = PullRequestStatus.fromResult(answer);+ if (value != null) values[agent.id] = value;+ } catch (_) {+ /* Missing access is unknown, not a passed check. */+ }+ }),+ );+ if (!mounted || revision != _revision) return;+ }+ if (!mounted || revision != _revision) return;+ setState(() {+ _observed+ ..clear()+ ..addAll(values);+ _loading = false;+ });+ if (widget.app != null && widget.app!.foreground.value) {+ _timer = Timer(const Duration(seconds: 60), _refresh);+ }+ }++ @override+ void dispose() {+ _revision++;+ _timer?.cancel();+ c.removeListener(_changed);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ final links = <String, ({Uri url, Set<String> groups, String? state})>{};+ void include(Uri url, String group, String? state) {+ final key = url.toString(), prior = links[url.toString()];+ links[key] = (+ url: url,+ groups: {...?prior?.groups, group},+ state: state ?? prior?.state,+ );+ }++ for (final group in _groups) {+ for (final message in c.messages(group.id)) {+ for (final match in RegExp(+ r'https://github\.com/([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)/pull/([1-9][0-9]*)\b',+ ).allMatches(message.text)) {+ include(Uri.parse(match.group(0)!), group.title, null);+ }+ }+ for (final agentId in group.agentIds) {+ if (_observed[agentId] case final pr?) {+ include(pr.url, group.title, pr.state);+ }+ }+ }+ return Column(+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 12, 20, 8),+ child: Row(+ children: [+ Expanded(+ child: Text(+ 'Pull requests',+ style: DesktopChrome.text(medium: true),+ ),+ ),+ DropdownButton<bool>(+ value: _all,+ underline: const SizedBox.shrink(),+ items: const [+ DropdownMenuItem(value: false, child: Text('This group')),+ DropdownMenuItem(value: true, child: Text('All groups')),+ ],+ onChanged: (value) {+ if (value == null) return;+ setState(() => _all = value);+ _changed();+ },+ ),+ ],+ ),+ ),+ if (_loading) const LinearProgressIndicator(minHeight: 2),+ Expanded(+ child: links.isEmpty+ ? Center(+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Text(+ _loading ? 'Reading pull requests…' : 'Pull requests shared in the conversation appear here.',+ textAlign: TextAlign.center,+ style: DesktopChrome.text(color: DesktopChrome.muted),+ ),+ ),+ )+ : ListView.separated(+ padding: const EdgeInsets.symmetric(+ horizontal: 20,+ vertical: 12,+ ),+ itemCount: links.length,+ separatorBuilder: (_, _) =>+ Divider(height: 24, color: DesktopChrome.rim),+ itemBuilder: (context, i) {+ final pr = links.values.elementAt(i),+ parts = pr.url.pathSegments;+ return ListTile(+ contentPadding: EdgeInsets.zero,+ title: Text(+ '${parts[0]}/${parts[1]} #${parts[3]}',+ style: DesktopChrome.control(medium: true),+ ),+ subtitle: Text(+ [+ if (_all) pr.groups.join(' · '),+ pr.state ?? 'View status on GitHub',+ ].join('\n'),+ style: DesktopChrome.metadata(),+ ),+ trailing: TextButton(+ onPressed: () => launchUrl(+ pr.url,+ mode: LaunchMode.externalApplication,+ ),+ child: const Text('Open on GitHub'),+ ),+ );+ },+ ),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartnew file mode 100644index 000000000..cdfb8823d--- /dev/null+++ b/desktop/lib/super_tabs/roster.dart@@ -0,0 +1,302 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/models.dart' show Agent;+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 '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/engine_identity.dart';+import 'controller.dart';+import 'identity.dart';+import 'machines.dart';+import 'model.dart';++/// Tab-wide membership above tab-wide execution capacity. Group selection does+/// not change who appears here or what machines the team has contributed.+class SuperTabRoster extends StatefulWidget {+ const SuperTabRoster({+ super.key,+ required this.controller,+ required this.onInvite,+ required this.onOpenAgent,+ required this.onAddAgent,+ this.app,+ });+ final SuperTabController controller;+ final AppNotifier? app;+ final VoidCallback onInvite;+ final ValueChanged<SuperTabAgent> onOpenAgent;+ final ValueChanged<SuperTabConversation> onAddAgent;+ @override+ State<SuperTabRoster> createState() => _SuperTabRosterState();+}++class _SuperTabRosterState extends State<SuperTabRoster> {+ double _membersFraction = .56;+ SuperTabController get c => widget.controller;++ Agent? _native(SuperTabAgent agent) => widget.app+ ?.stateOf(agent.machineId)+ ?.agents+ .where((a) => a.id == agent.harnessId)+ .firstOrNull;++ String _activity(SuperTabAgent agent) {+ if (widget.app?.questionFor(agent.machineId, agent.harnessId) != null) {+ return 'Needs you';+ }+ final work = c.snapshot?.conversations+ .where(+ (g) =>+ !g.archived &&+ g.assignment?['agentId'] == agent.id &&+ !const ['done', 'stopped'].contains(g.assignment?['status']),+ )+ .firstOrNull;+ if (work?.assignment?['status'] == 'needs_human') return 'Needs you';+ final native = _native(agent);+ if (native?.isStopped == true) return 'Stopped';+ if (widget.app?.stateOf(agent.machineId)?.nodeOnline == false) {+ return 'Offline';+ }+ if (native?.title case final title? when title.trim().isNotEmpty) {+ return title;+ }+ if (work != null) return work.title;+ return native == null ? 'Status unavailable' : 'Ready';+ }++ Future<void> _details(SuperTabAgent agent) => showAppDialog<void>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(c.snapshot!.agentName(agent.id)),+ content: SizedBox(+ width: 320,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(engineIdentity(agent.engine).label),+ for (final field in [+ ('Model', 'model'),+ ('Effort', 'effort'),+ ('Context', 'contextWindow'),+ ('Version', 'engineVersion'),+ ])+ if (agent.configuration[field.$2] case final value?)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text('${field.$1}: $value'),+ ),+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(+ widget.app?.stateOf(agent.machineId)?.machine.displayName ??+ 'Machine unavailable',+ ),+ ),+ ],+ ),+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),+ ),+ FilledButton(+ onPressed: () {+ Navigator.pop(context);+ widget.onOpenAgent(agent);+ },+ child: const Text('Open terminal'),+ ),+ ],+ ),+ );++ Widget _heading(String text, {VoidCallback? add, String? tooltip}) => Padding(+ padding: const EdgeInsets.fromLTRB(16, 14, 12, 6),+ child: Row(+ children: [+ Expanded(+ child: Text(+ text,+ style: DesktopChrome.metadata().copyWith(+ fontWeight: FontWeight.w600,+ ),+ ),+ ),+ if (add != null)+ AppIconButton(+ icon: AppIcons.plus,+ tooltip: tooltip ?? text,+ onPressed: add,+ ),+ ],+ ),+ );++ Widget _agent(SuperTabAgent agent) {+ final name = c.snapshot!.agentName(agent.id), activity = _activity(agent);+ final waiting = activity == 'Needs you';+ return GestureDetector(+ onSecondaryTapUp: (event) async {+ final choice = await showMenu<String>(+ context: context,+ position: RelativeRect.fromLTRB(+ event.globalPosition.dx,+ event.globalPosition.dy,+ event.globalPosition.dx,+ event.globalPosition.dy,+ ),+ items: [+ const PopupMenuItem(value: 'details', child: Text('Details')),+ ],+ );+ if (choice == 'details' && mounted) await _details(agent);+ },+ child: ListTile(+ key: ValueKey('super-member-${agent.id}'),+ dense: true,+ contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 1),+ horizontalTitleGap: 10,+ leading: SuperTabAvatar(identity: 'agent:${agent.id}', name: name),+ title: Row(+ children: [+ Flexible(+ child: Text(+ name,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),+ ),+ ),+ const SizedBox(width: 6),+ Tooltip(+ message: engineIdentity(agent.engine).label,+ child: EngineMark(engine: agent.engine, size: 14),+ ),+ ],+ ),+ subtitle: Text(+ activity,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(+ color: waiting ? grid.AppPalette.warn : null,+ ),+ ),+ onTap: () => widget.onOpenAgent(agent),+ onLongPress: () => unawaited(_details(agent)),+ ),+ );+ }++ Widget _members() {+ final state = c.snapshot;+ final leads =+ state?.agents.where((a) => state.isLead(a.id)).toList() ??+ const <SuperTabAgent>[];+ final agents =+ state?.agents.where((a) => !state.isLead(a.id)).toList() ??+ const <SuperTabAgent>[];+ return ListView(+ padding: const EdgeInsets.only(bottom: 12),+ children: [+ _heading('Leads · ${leads.length}'),+ for (final agent in leads) _agent(agent),+ _heading(+ 'Humans · ${state?.people.length ?? 0}',+ add: c.isOwner ? widget.onInvite : null,+ tooltip: 'Invite people',+ ),+ for (final person in state?.people ?? const <SuperTabPerson>[])+ ListTile(+ dense: true,+ horizontalTitleGap: 10,+ leading: SuperTabAvatar(+ identity: 'person:${person.id}',+ name: superTabPersonName(person.email),+ ),+ title: Text(+ superTabPersonName(person.email),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ onTap: () => showAppDialog<void>(+ context: context,+ builder: (context) => AlertDialog(+ title: Text(superTabPersonName(person.email)),+ content: Text('${person.email}\n${person.role}'),+ actions: [+ TextButton(+ onPressed: () {+ Navigator.pop(context);+ widget.onInvite();+ },+ child: const Text('Manage people'),+ ),+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),+ ),+ ],+ ),+ ),+ ),+ _heading('Agents · ${agents.length}'),+ for (final agent in agents) _agent(agent),+ ],+ );+ }++ @override+ Widget build(BuildContext context) => Material(+ color: DesktopChrome.surface,+ child: ListenableBuilder(+ listenable: Listenable.merge([c, if (widget.app != null) widget.app!]),+ builder: (context, _) => LayoutBuilder(+ builder: (context, size) => Column(+ children: [+ SizedBox(+ height: (size.maxHeight - 9) * _membersFraction,+ child: _members(),+ ),+ Semantics(+ label: 'Resize members and machines',+ child: MouseRegion(+ cursor: SystemMouseCursors.resizeRow,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onVerticalDragUpdate: (event) => setState(+ () => _membersFraction =+ (_membersFraction + event.delta.dy / size.maxHeight)+ .clamp(.25, .75),+ ),+ child: SizedBox(+ height: 9,+ child: Center(+ child: Divider(height: 1, color: DesktopChrome.rim),+ ),+ ),+ ),+ ),+ ),+ Expanded(+ child: SuperTabMachines(+ controller: c,+ app: widget.app,+ onAddAgent: widget.onAddAgent,+ ),+ ),+ ],+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex dd2edeb93..87fdbb040 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -8,7 +8,9 @@ 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 '../state/app_state.dart';+import 'roster.dart';+import 'pull_requests.dart';import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';@@ -28,6 +30,9 @@ class SuperTabView extends StatefulWidget {required this.machineName,this.terminal,this.onCloseTerminal,+ this.onOpenGroupTerminals,+ this.terminalsVisible = false,+ this.app,});final SuperTabController controller;final VoidCallback onInvite;@@ -35,7 +40,9 @@ class SuperTabView extends StatefulWidget {final ValueChanged<SuperTabAgent> onOpenTerminal;final String Function(String machineId) machineName;final Widget? terminal;- final VoidCallback? onCloseTerminal;+ final VoidCallback? onCloseTerminal, onOpenGroupTerminals;+ final bool terminalsVisible;+ final AppNotifier? app;@overrideState<SuperTabView> createState() => _SuperTabViewState();@@ -53,6 +60,8 @@ class _SuperTabViewState extends State<SuperTabView> {int _scrollRequest = 0;bool _jumpingToEnd = false;bool _sidebarOpen = false;+ bool _rosterOpen = false;+ bool _showPullRequests = false;final _loadingOlder = <String>{};int _mentionIndex = 0;String? _dismissedMention;@@ -168,7 +177,9 @@ class _SuperTabViewState extends State<SuperTabView> {void _readToEnd(String id, int sequence) {_following[id] = true;if (_newAfter.containsKey(id)) setState(() => _newAfter.remove(id));- c.markRead(id, through: sequence);+ if (!_terminalsVisible && !_showPullRequests) {+ c.markRead(id, through: sequence);+ }}void _jumpToLatest() {@@ -206,6 +217,11 @@ class _SuperTabViewState extends State<SuperTabView> {if (mounted && result != null) setState(() => _replies.remove(id));}+ void _closeRoster() {+ setState(() => _rosterOpen = false);+ if (!_terminalsVisible) _focus.requestFocus();+ }+void _closeSidebar() {setState(() => _sidebarOpen = false);WidgetsBinding.instance.addPostFrameCallback((_) {@@ -263,106 +279,6 @@ class _SuperTabViewState extends State<SuperTabView> {_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;@@ -446,191 +362,6 @@ class _SuperTabViewState extends State<SuperTabView> {);}- 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) &&- '${_agentName(a)} ${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(_agentName(agent), 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 = '';@@ -742,7 +473,18 @@ class _SuperTabViewState extends State<SuperTabView> {: null,),),- trailing: c.unread(group)+ trailing: _needsHuman(group).isNotEmpty+ ? Tooltip(+ message: 'Needs a human',+ child: Text(+ '? ${_needsHuman(group).length}',+ style: DesktopChrome.control(+ medium: true,+ color: grid.AppPalette.warn,+ ),+ ),+ )+ : c.unread(group)? Semantics(label: 'Unread messages',child: Container(@@ -768,162 +510,151 @@ class _SuperTabViewState extends State<SuperTabView> {),),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'),- ),- TextButton(- onPressed: c.snapshot != null- ? () {- _closeSidebar();- unawaited(showSuperTabRouting(context, c));- }- : null,- child: const Text('Routing'),- ),- ],+ padding: const EdgeInsets.fromLTRB(12, 8, 12, 12),+ child: Align(+ alignment: Alignment.centerLeft,+ child: AppIconButton(+ icon: AppIcons.settings,+ tooltip: 'Super Tab settings',+ onPressed: c.snapshot == null+ ? null+ : () {+ _closeSidebar();+ unawaited(showSuperTabRouting(context, c));+ },+ ),),),],),);- Widget _header(SuperTabConversation? group, bool narrow) => Container(+ List<SuperTabAgent> _needsHuman(SuperTabConversation group) =>+ c.snapshot?.agents+ .where(+ (agent) =>+ group.agentIds.contains(agent.id) &&+ (widget.app?.questionFor(agent.machineId, agent.harnessId) !=+ null ||+ (group.assignment?['status'] == 'needs_human' &&+ group.assignment?['agentId'] == agent.id)),+ )+ .toList() ??+ const [];++ void _openAgent(SuperTabAgent agent) {+ setState(() {+ _showPullRequests = false;+ _rosterOpen = false;+ });+ widget.onOpenTerminal(agent);+ }++ bool get _terminalsVisible =>+ widget.terminalsVisible || widget.terminal != null;++ Widget _header(+ SuperTabConversation? group,+ bool narrow,+ bool showRoster,+ ) => Container(constraints: const BoxConstraints(minHeight: 52),- padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),+ padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),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()),+ child: Row(+ children: [+ if (narrow)+ AppIconButton(+ icon: AppIcons.columns2,+ tooltip: 'Conversations',+ onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),+ ),+ Expanded(+ child: Text(+ group?.title ?? 'Loading conversation…',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.text(medium: true),+ ),+ ),+ TextButton(+ key: const ValueKey('super-chat'),+ style: TextButton.styleFrom(+ foregroundColor: !_terminalsVisible && !_showPullRequests+ ? DesktopChrome.accent+ : DesktopChrome.muted,+ ),+ onPressed: () {+ setState(() => _showPullRequests = false);+ widget.onCloseTerminal?.call();+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) _focus.requestFocus();+ });+ },+ child: const Text('Chat'),+ ),+ AppIconButton(+ icon: AppIcons.terminal,+ tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',+ color: _terminalsVisible ? DesktopChrome.accent : DesktopChrome.muted,+ onPressed: group?.agentIds.isNotEmpty == true+ ? () {+ setState(() => _showPullRequests = false);+ widget.onOpenGroupTerminals?.call();+ }+ : null,+ ),+ TextButton(+ style: TextButton.styleFrom(+ foregroundColor: _showPullRequests+ ? DesktopChrome.accent+ : DesktopChrome.muted,+ ),+ onPressed: () {+ widget.onCloseTerminal?.call();+ setState(() => _showPullRequests = true);+ },+ child: const Text('PRs'),+ ),+ if (!showRoster)+ AppIconButton(+ icon: AppIcons.users,+ tooltip: 'Members and machines',+ onPressed: () => setState(() => _rosterOpen = !_rosterOpen),+ ),+ 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((g) => g.archived) == true)+ const PopupMenuItem(+ value: 'archived',+ child: Text('Archived conversations'),),- ),- 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',),- 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',- ),- ),- ],- ],- ),- ],- );- },+ ),+ ],+ ],+ ),+ ],),);@@ -1048,6 +779,7 @@ class _SuperTabViewState extends State<SuperTabView> {? 'You': _authorName(message),agent: agent,+ onOpenAgent: agent == null ? null : () => _openAgent(agent),machineName: agent == null ? null : widget.machineName(agent.machineId),grouped: grouped,reply: reply,@@ -1121,7 +853,6 @@ class _SuperTabViewState extends State<SuperTabView> {final mentions = _mentionChoices;return Column(children: [- _header(group, narrow),if (c.error != null)Padding(padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),@@ -1276,6 +1007,30 @@ class _SuperTabViewState extends State<SuperTabView> {],),),+ if (group != null)+ for (final agent in _needsHuman(group))+ Padding(+ padding: const EdgeInsets.fromLTRB(20, 6, 20, 0),+ child: ListTile(+ key: ValueKey('super-needs-human-${agent.id}'),+ dense: true,+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(12),+ ),+ tileColor: grid.AppPalette.warn.withValues(alpha: .08),+ leading: Icon(+ AppIcons.messageCircleQuestionMark,+ color: grid.AppPalette.warn,+ size: 18,+ ),+ title: Text(+ '${_agentName(agent)} needs you',+ style: DesktopChrome.control(medium: true),+ ),+ trailing: const Icon(AppIcons.arrowRight, size: 16),+ onTap: () => _openAgent(agent),+ ),+ ),if (mentions.isNotEmpty)Padding(padding: const EdgeInsets.symmetric(horizontal: 20),@@ -1372,7 +1127,7 @@ class _SuperTabViewState extends State<SuperTabView> {key: const ValueKey('super-message-composer'),controller: _composer,focusNode: _focus,- autofocus: widget.terminal == null,+ autofocus: !_terminalsVisible,enabled: c.canWrite && group != null && !group.archived,minLines: 1,maxLines: MediaQuery.sizeOf(context).height < 600@@ -1436,41 +1191,88 @@ class _SuperTabViewState extends State<SuperTabView> {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),- ],- );- }+ constraints.maxWidth < MediaQuery.textScalerOf(context).scale(720);+ final showRoster =+ constraints.maxWidth >= MediaQuery.textScalerOf(context).scale(1080);+ final roster = SuperTabRoster(+ controller: c,+ app: widget.app,+ onInvite: widget.onInvite,+ onOpenAgent: _openAgent,+ onAddAgent: (group) {+ setState(() => _rosterOpen = false);+ widget.onAddAgent(group);+ },+ );return Stack(children: [ExcludeFocus(- excluding: narrow && _sidebarOpen,+ excluding: (narrow && _sidebarOpen) || (!showRoster && _rosterOpen),child: Row(children: [if (!narrow) ...[SizedBox(width: 220, child: _sidebar()),VerticalDivider(width: 1, color: DesktopChrome.rim),],- Expanded(child: _conversation(narrow)),- if (terminal != null) ...[+ Expanded(+ child: Column(+ children: [+ _header(c.selected, narrow, showRoster),+ Expanded(+ child: IndexedStack(+ index: _terminalsVisible+ ? 1+ : _showPullRequests+ ? 2+ : 0,+ children: [+ _conversation(narrow),+ terminal ?? const SizedBox.shrink(),+ _showPullRequests+ ? SuperTabPullRequests(+ controller: c,+ app: widget.app,+ )+ : const SizedBox.shrink(),+ ],+ ),+ ),+ ],+ ),+ ),+ if (showRoster) ...[VerticalDivider(width: 1, color: DesktopChrome.rim),- Expanded(child: terminal),+ SizedBox(width: 288, child: roster),],],),),+ if (!showRoster && _rosterOpen)+ Positioned.fill(+ child: BlockSemantics(+ child: FocusScope(+ autofocus: true,+ onKeyEvent: (_, event) {+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.escape) {+ _closeRoster();+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: GestureDetector(+ onTap: _closeRoster,+ child: ColoredBox(+ color: grid.AppDesktop.veil(Theme.of(context).brightness),+ child: Align(+ alignment: Alignment.centerRight,+ child: SizedBox(width: 288, child: roster),+ ),+ ),+ ),+ ),+ ),+ ),if (narrow && _sidebarOpen)Positioned.fill(child: BlockSemantics(diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex 4cbf586ee..9fd2974cd 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -13,8 +13,8 @@ import 'model.dart';import 'pane.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.+/// Keeps the app's one native canvas alive in the group's middle area.+/// Switching chat/terminals never constructs a second terminal renderer.class SuperTabWorkspace extends StatefulWidget {const SuperTabWorkspace({super.key,@@ -40,25 +40,29 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {// or a person's stop.(String, String)? _resumeRequest;Future<void> _terminalChange = Future.value();- TerminalPane? _nativePane;- Timer? _nativeHeartbeat;+ final _nativePanes = <TerminalPane>[];+ final _nativeHeartbeats = <Timer>[];void _clearNativeContext() {- _nativeHeartbeat?.cancel();- _nativeHeartbeat = null;- final pane = _nativePane;- _nativePane = null;+ for (final timer in _nativeHeartbeats) {+ timer.cancel();+ }+ _nativeHeartbeats.clear();+ final panes = _nativePanes.toList();+ _nativePanes.clear();_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));- }- });+ for (final pane in panes) {+ if (pane.inputContext == null && !pane.watchOnly) continue;+ 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@@ -68,19 +72,18 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}void _syncTerminal(SuperTabController controller, String swarmId) {- final agent = controller.terminalAgent(controller.selectedId);+ final agents = controller.terminalAgents(controller.selectedId);final request = (swarmId,controller.selectedId,- agent?.id,+ agents.isEmpty ? null : agents.map((a) => a.id).join(','),controller.accountId,controller.canWrite,);if (_terminalRequest == request) return;_clearNativeContext();_terminalRequest = request;- final resume =- agent != null && _resumeRequest == (controller.selectedId, agent.id);+ final resume = _resumeRequest;_resumeRequest = null;bool current() =>mounted &&@@ -95,16 +98,36 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {_,) async {if (!current()) return;- if (agent != null) {- await _open(agent, controller, swarmId, request.$2, current, resume);- if (current()) setState(() => _readyRequest = request);- } else {- final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;- for (final pane in tab?.panes.toList() ?? const []) {+ final tab = app.swarms.where((s) => s.id == swarmId).firstOrNull;+ for (final pane in tab?.panes.toList() ?? const <TerminalPane>[]) {+ if (!agents.any(+ (a) => a.machineId == pane.machineId && a.harnessId == pane.agentId,+ )) {if (!current()) return;await app.closePane(pane.id, swarmId: swarmId);}}+ for (final agent in agents) {+ if (!current()) return;+ await _open(+ agent,+ controller,+ swarmId,+ request.$2,+ current,+ resume == (request.$2, agent.id),+ );+ }+ if (current()) {+ if (tab != null) tab.zoomedPaneId = null;+ if (agents.length == 1) {+ if (tab?.panes.firstOrNull case final pane?) {+ app.focusPane(pane.id);+ pane.session?.focusInput();+ }+ }+ setState(() => _readyRequest = request);+ }});});}@@ -143,7 +166,11 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {?.isStopped;if (stopped == true) {if (!resume) {- controller.selectTerminal(conversationId, null);+ controller.hideTerminal(+ conversationId,+ agent.machineId,+ agent.harnessId,+ );return;}// Older idle cleanup may already have stopped a contributed harness.@@ -190,51 +217,68 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}}await app.assignAgentToPane(- tab.panes.firstOrNull?.id,+ null,agent.machineId,agent.harnessId,swarmId: swarmId,inputContext: inputContext,watchOnly: !controller.canWrite,+ autoTile: true,+ focus: false,);if (!current()) return;- if (tab.panes.firstOrNull case final pane?) {+ if (tab.panes+ .where(+ (p) =>+ p.machineId == agent.machineId &&+ p.agentId == agent.harnessId,+ )+ .firstOrNull+ case final pane?) {pane.composerVisible = false;- _nativePane = pane;+ _nativePanes.add(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')),- );+ _nativeHeartbeats.add(+ Timer.periodic(const Duration(seconds: 20), (timer) async {+ if (!current()) {+ timer.cancel();+ return;}- timer.cancel();- } finally {- renewing = false;- }- });+ if (renewing) return;+ renewing = true;+ try {+ await app.superTabMachineRequest(agent.machineId, {+ 'action': 'renewNative',+ 'tabId': controller.tabId,+ 'contextId': inputContext,+ });+ } catch (failure) {+ if (mounted && current()) {+ controller.hideTerminal(+ conversationId,+ agent.machineId,+ agent.harnessId,+ );+ 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);+ controller.hideTerminal(+ conversationId,+ agent.machineId,+ agent.harnessId,+ );ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(failure.toString())));}@@ -273,26 +317,20 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {listenable: controller,builder: (context, _) {_syncTerminal(controller, tab.id);- final selectedTerminal = controller.terminalAgent(- controller.selectedId,- );+ final agents = controller.terminalAgents(controller.selectedId);final showTerminal =_readyRequest == _terminalRequest &&- selectedTerminal != null &&- tab.panes.any(- (pane) =>- pane.machineId == selectedTerminal.machineId &&- pane.agentId == selectedTerminal.harnessId,- );- final terminal = selectedTerminal == null+ agents.isNotEmpty &&+ tab.panes.isNotEmpty;+ final lead = controller.snapshot?.agents+ .where((a) => controller.snapshot!.isLead(a.id))+ .firstOrNull;+ final terminal = lead == null? canvas: SuperPane(- machineId: selectedTerminal.machineId,- harnessId: selectedTerminal.harnessId,- title:- controller.snapshot?.isLead(selectedTerminal.id) == true- ? 'Lead'- : null,+ machineId: lead.machineId,+ harnessId: lead.harnessId,+ title: 'Lead',child: canvas,);return Stack(@@ -306,15 +344,42 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {unawaited(showSuperTabPeople(context, controller)),onAddAgent: widget.onAddAgent,onOpenTerminal: (agent) {+ final group =+ controller.selected?.agentIds.contains(agent.id) == true+ ? controller.selected+ : controller.snapshot?.conversations+ .where(+ (g) =>+ !g.archived &&+ g.assignment?['agentId'] == agent.id,+ )+ .firstOrNull ??+ controller.snapshot?.conversations+ .where(+ (g) =>+ !g.archived &&+ g.agentIds.contains(agent.id),+ )+ .firstOrNull;+ if (group == null) return;+ controller.select(group.id);_terminalRequest = null;_resumeRequest = (controller.selectedId, agent.id);controller.selectTerminal(controller.selectedId, agent.id);setState(() {});},+ onOpenGroupTerminals: () =>+ controller.selectGroupTerminals(controller.selectedId),+ terminalsVisible: agents.isNotEmpty,+ app: app,machineName: (machine) =>app.stateOf(machine)?.machine.displayName ??'Offline machine',- terminal: showTerminal ? terminal : null,+ terminal: showTerminal+ ? terminal+ : agents.isNotEmpty+ ? const Center(child: CircularProgressIndicator())+ : null,onCloseTerminal: () {controller.selectTerminal(controller.selectedId, null);},diff --git a/desktop/test/desktop_welcome_composer_test.dart b/desktop/test/desktop_welcome_composer_test.dartindex fe594a7eb..9d03441d5 100644--- a/desktop/test/desktop_welcome_composer_test.dart+++ b/desktop/test/desktop_welcome_composer_test.dart@@ -197,7 +197,7 @@ void main() {},);- testWidgets('Super Tab recents open an ordinary harness through the shared welcome page', (tester) async {+ testWidgets('Super Tab shortcut shows only the lead form and preserves existing harnesses', (tester) async {await setup(tester, storage: MemoryStore());app.currentUser = const CurrentUserProfile(id: 'owner',@@ -214,19 +214,19 @@ void main() {),];final pane = app.adoptSessionForTest(terminal('recent-existing', []));+ final originalTab = app.activeSwarm;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(find.text('Continue existing work'), findsNothing);+ expect(find.text('Recent harnesses'), findsNothing);+ expect(target.panes, isEmpty);+ expect(originalTab.panes.single, same(pane));expect(connection.starts, isEmpty);- expect(form, findsNothing);+ expect(form, findsOneWidget);expect(tester.takeException(), isNull);});diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex eb11760eb..faa4ceff6 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -86,11 +86,14 @@ void main() {find.descendant(of: reply, matching: find.text('Lead')),findsOneWidget,);- await tester.tap(find.text('1 agent · 1 person'));+ await tester.tap(find.byTooltip('Members and machines'));await tester.pumpAndSettle();expect(find.text('hi'), findsNothing);expect(find.text('Lead'), findsWidgets);- expect(find.text('Open terminal'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-member-lead-agent')),+ findsOneWidget,+ );},);@@ -209,6 +212,17 @@ void main() {'a human request belongs only to its group and clears with the recorded state',(tester) async {final server = ConversationServer();+ server.state['agents'] = [+ {+ 'id': 'builder',+ 'name': 'Builder',+ 'machineId': 'host',+ 'harnessId': 'session',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ (server.state['conversations'] as List)[1]['agentIds'] = ['builder'];final group = (server.state['conversations'] as List)[1] as Map;group['assignment'] = {'id': 'attempt',@@ -217,15 +231,15 @@ void main() {'result': 'Which device should I test?',};final c = await show(tester, server);- expect(find.text('Needs a human'), findsNothing);+ expect(find.text('Builder needs you'), findsNothing);c.select('offline');await tester.pumpAndSettle();- expect(find.text('Needs a human'), findsOneWidget);+ expect(find.text('Builder needs you'), findsOneWidget);group['assignment']['status'] = 'working';server.revision++;await c.refresh();await tester.pumpAndSettle();- expect(find.text('Needs a human'), findsNothing);+ expect(find.text('Builder needs you'), findsNothing);},);diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dartindex fafe2a3f4..caa1ea4d1 100644--- a/desktop/test/super_tab_controller_test.dart+++ b/desktop/test/super_tab_controller_test.dart@@ -6,6 +6,40 @@ import 'package:harness/super_tabs/controller.dart';import 'support/super_tab_fixture.dart';void main() {+ test('group terminal selection hides one pane, survives reopening, and follows membership', () async {+ final server = ConversationServer();+ server.state['agents'] = [+ for (final id in ['a', 'b'])+ {+ 'id': id,+ 'name': id,+ 'machineId': 'm',+ 'harnessId': 'native-$id',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'codex'},+ },+ ];+ (server.state['conversations'] as List)[1]['agentIds'] = ['a', 'b'];+ final c = server.controller();+ await c.refresh();+ c.selectGroupTerminals('offline');+ expect(c.terminalAgents('offline').map((a) => a.id), ['a', 'b']);+ c.hideTerminal('offline', 'm', 'native-a');+ expect(c.terminalAgents('offline').map((a) => a.id), ['b']);+ await c.flush();+ c.dispose();+ final restored = server.controller(initial: server.saved);+ await restored.refresh();+ expect(restored.terminalAgents('offline').map((a) => a.id), ['b']);+ restored.selectGroupTerminals('offline');+ expect(restored.terminalAgents('offline').map((a) => a.id), ['a', 'b']);+ (server.state['conversations'] as List)[1]['agentIds'] = ['a'];+ await restored.refresh();+ expect(restored.terminalAgents('offline').map((a) => a.id), ['a']);+ restored.revokeAccess('Removed');+ expect(restored.terminalAgents('offline'), isEmpty);+ restored.dispose();+ });test('terminal selections survive reopening and cannot cross accounts or group membership', () async {final server = ConversationServer();server.state['agents'] = [diff --git a/desktop/test/super_tab_delivery_test.dart b/desktop/test/super_tab_delivery_test.dartindex fbeb48411..adca690f8 100644--- a/desktop/test/super_tab_delivery_test.dart+++ b/desktop/test/super_tab_delivery_test.dart@@ -146,30 +146,11 @@ void main() {}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'));+ if (find.byTooltip('Members and machines').evaluate().isNotEmpty) {+ await tester.tap(find.byTooltip('Members and machines'));await tester.pumpAndSettle();}- await tester.tap(find.text('Invite'));+ await tester.tap(find.byTooltip('Invite people'));await tester.pumpAndSettle();expect(tester@@ -185,10 +166,13 @@ void main() {.hasFocus,isTrue,);- await shot('invite');- expect(tester.takeException(), isNull);+ await shot('people');await tester.tap(find.byTooltip('Close'));await tester.pumpAndSettle();+ if (find.byTooltip('Members and machines').evaluate().isNotEmpty) {+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ }await tester.tap(find.text('Check delivery to Lead'));await tester.pumpAndSettle();await shot('delivery');diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dartindex 0b6e185fa..eaefd31b7 100644--- a/desktop/test/super_tab_picker_test.dart+++ b/desktop/test/super_tab_picker_test.dart@@ -114,9 +114,15 @@ void main() {),);await tester.pumpAndSettle();- await tester.tap(find.byTooltip('0 agents · 1 person'));+ if (find.byTooltip('Members and machines').evaluate().isNotEmpty) {+ await tester.tap(find.byTooltip('Members and machines'));+ await tester.pumpAndSettle();+ }+ await tester.tap(+ find.byKey(const ValueKey('super-machine-teammate-machine')),+ );await tester.pumpAndSettle();- await tester.tap(find.text('Add agent'));+ await tester.tap(find.text('Attach running agent'));await tester.pumpAndSettle();return f;}diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex ebdc84c39..b99bed81a 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -4,6 +4,7 @@ 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 'package:harness/super_tabs/roster.dart';import 'support/super_tab_fixture.dart';@@ -115,68 +116,53 @@ void main() {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',- ),+ testWidgets('large text and a short window preserve group navigation', (+ 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(tester.takeException(), isNull);+ if (find.byTooltip('Conversations').evaluate().isNotEmpty) {+ await tester.tap(find.byTooltip('Conversations'));await tester.pumpAndSettle();- expect(controller.selected?.title, 'Device testing');- expect(tester.takeException(), isNull);- await tester.pumpWidget(const SizedBox());- await controller.flush();- controller.dispose();- },- );+ }+ await tester.tap(find.byKey(const ValueKey('super-group-offline')));+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'offline');+ expect(find.text('New group'), findsNothing);+ 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',@@ -257,25 +243,20 @@ void main() {expect(find.text('CHATS'), findsNothing);expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);expect(find.byKey(const ValueKey('super-group-offline')), findsOneWidget);+ expect(find.text('New group'), findsNothing);+ expect(find.byTooltip('Super Tab settings'), findsOneWidget);+ expect(find.byTooltip('Invite people'), findsOneWidget);expect(- tester.getCenter(find.text('New group')).dy,- greaterThan(- tester- .getCenter(find.byKey(const ValueKey('super-group-offline')))- .dy,- ),+ tester.getCenter(find.byTooltip('Invite people')).dx,+ greaterThan(800),);- 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]) {+ for (final rename in [true]) {testWidgets('${rename ? 'Rename' : 'New group'} clears its form when account access ends',(tester) async {@@ -324,7 +305,7 @@ void main() {}testWidgets(- '20 people remain a count and Add agent targets the selected group',+ 'global roster stays scrollable with 20 people and opens an agent directly',(tester) async {await tester.binding.setSurfaceSize(const Size(1100, 700));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -358,36 +339,37 @@ void main() {final controller = server.controller();await controller.refresh();controller.select('offline');- SuperTabConversation? target;+ SuperTabAgent? target;await tester.pumpWidget(MaterialApp(home: Scaffold(body: SuperTabView(controller: controller,onInvite: () {},- onAddAgent: (group) => target = group,- onOpenTerminal: (_) {},+ onAddAgent: (_) {},+ onOpenTerminal: (agent) => target = agent,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),+ expect(find.text('Humans · 20'), findsOneWidget);+ final member = find.byKey(const ValueKey('super-member-agent-0'));+ await tester.scrollUntilVisible(+ member,+ 150,+ scrollable: find+ .descendant(+ of: find.byType(SuperTabRoster),+ matching: find.byType(Scrollable),+ )+ .first,);- await tester.enterText(search, 'person19');+ await tester.tap(member);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(target?.id, 'agent-0');+ expect(find.byType(Dialog), findsNothing);expect(controller.snapshot!.conversations, hasLength(2));expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());@@ -397,7 +379,7 @@ void main() {);testWidgets(- 'a native terminal sits beside the conversation and uses a return action when narrow',+ 'native terminals fill the middle, preserve both sidebars, and return to chat',(tester) async {await tester.binding.setSurfaceSize(const Size(1100, 700));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -421,15 +403,14 @@ void main() {),);await tester.pumpAndSettle();- expect(- tester.getCenter(find.text('Native terminal fixture')).dx,- greaterThan(tester.getCenter(find.text('Review this result.')).dx),- );+ expect(find.text('Native terminal fixture'), findsOneWidget);+ expect(find.text('Review this result.'), findsNothing);+ expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);+ expect(find.byType(SuperTabRoster), findsOneWidget);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(find.text('Native terminal fixture'), findsOneWidget);+ await tester.tap(find.text('Chat'));expect(closed, isTrue);expect(server.posts,diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dartindex 68824ddc9..320fa3038 100644--- a/desktop/test/super_tab_workspace_test.dart+++ b/desktop/test/super_tab_workspace_test.dart@@ -7,6 +7,104 @@ import 'package:harness/super_tabs/workspace.dart';import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;void main() {+ testWidgets(+ 'group terminals show both members and closing one preserves the other',+ (tester) async {+ 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)[1]['agentIds'] = ['a', 'b'];+ f.app.machineStates['m']!.agents = [+ for (final id in ['a', 'b'])+ Agent.fromJson({+ 'id': 'native-$id',+ 'name': id,+ 'engine': 'codex',+ 'terminal': {'available': true},+ }),+ ];+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ c.select('offline');+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: const Text('Native terminals'),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await f.app.handleMachineEventForTest('m', {+ 'type': 'commander_question',+ 'agentId': 'native-b',+ 'payload': {+ 'requestId': 'q-fixture',+ 'questions': [+ {+ 'key': 'confirm',+ 'q': 'Use this approach?',+ 'options': ['Yes', 'No'],+ 'multi': false,+ },+ ],+ },+ });+ await tester.pumpAndSettle();+ await tester.tap(find.text('b needs you').first);+ await tester.pumpAndSettle();+ expect(f.app.activeSwarm.panes.single.agentId, 'native-b');+ await f.app.handleMachineEventForTest('m', {+ 'type': 'commander_question_close',+ 'agentId': 'native-b',+ 'payload': {'requestId': 'q-fixture'},+ });+ await tester.pumpAndSettle();+ expect(f.app.questionFor('m', 'native-b'), isNull);+ tester+ .widget<SuperTabView>(find.byType(SuperTabView))+ .onOpenGroupTerminals!();+ await tester.pumpAndSettle();+ expect(+ f.app.activeSwarm.panes.map((p) => p.agentId),+ unorderedEquals(['native-a', 'native-b']),+ );+ await f.app.requestClosePane(+ f.app.activeSwarm.panes.firstWhere((p) => p.agentId == 'native-a').id,+ );+ await tester.pumpAndSettle();+ expect(f.app.activeSwarm.panes.single.agentId, 'native-b');+ expect(c.terminalAgents('offline').single.id, 'b');+ expect(+ f.connection.calls.where(+ (c) => c.$1 == 'agent_close' || c.$1 == 'agent_create',+ ),+ isEmpty,+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );+for (final scenario in [(engine: 'codex', viewer: false, fail: false),(engine: 'claude', viewer: false, fail: false),diff --git a/docs/research/2026-10-17-one-human-many-agents/20-super-tab-implementation-review.md b/docs/research/2026-10-17-one-human-many-agents/20-super-tab-implementation-review.mdnew file mode 100644index 000000000..d542b5fcb--- /dev/null+++ b/docs/research/2026-10-17-one-human-many-agents/20-super-tab-implementation-review.md@@ -0,0 +1,59 @@+# Super Tab implementation review — 19 October 2026++The existing app tab contains a flat workgroup list, a chat/native-terminal/PR centre, and a right sidebar with Leads, Humans, Agents and contributed machines. The hidden Cmd-Option-Shift-T shortcut reuses the Cmd-N lead form without Recent harnesses. Clicking an agent opens its exact native terminal; hiding a pane preserves the running harness.++## Machine contribution++A collaborator explicitly contributes an owned machine, project folder, permitted engines/default accounts and concurrency limit. The machine owner executes queued starts through the existing durable native creation receipts. Contributions do not create whole-machine shares. Removing the contributor revokes the contribution. Pausing stops new dispatch while preserving running agents. Model settlement completes before work assignment is permitted.++Fresh host readings expose CPU/GPU, RAM and project-volume disk, available subscription windows and resets. Unknown readings remain unknown. Routing rejects stale/full/paused machines and candidates missing required resources/tools. The backend independently admits each launch and the host reserves native capacity.++## Review path++1. Use Cmd-Option-Shift-T and create a lead using the familiar form.+2. Click a member to focus its terminal; use the group terminal icon to show the group's panes. Hide a pane and reopen it.+3. A native pending question adds a local “needs you” notice. Clicking it goes to that terminal; the native question-close event clears it.+4. Humans + invites collaborators. Machines + contributes capacity; machine details configure or pause it and attach an existing harness.+5. Inspect PR references in chat and the PR view. References are actual observed links; unknown GitHub state is not presented as verified.++## Validation plan and evidence++Source scope: Desktop Super Tab UI/state and native macOS integration; CLI machine readings, routing and host launch protocol; backend Super Tab authorization, durable operations and Mongo transactions. Toolchain: pinned Flutter 3.47.2 and repository Node lockfiles. Use private test homes/daemons and synthetic engines only.++- Routing coverage: 100% statements, branches, functions and lines after the contributed-capacity cases.+- Desktop affected widget tests: creation, multi-pane hide/reopen, roster, narrow/large-text layouts and native question handoff. Final checks are recorded below when complete.+- macOS native fixture: actual Flutter terminal surface, both sidebars retained; synthetic accounts and harnesses.+- Backend: disposable Mongo replica-set integration tests, including owner-only queue execution, project scope, concurrency, pause and revocation.+- CLI: two disposable daemons demonstrate a teammate contributing capacity without a MachineShare; a repeated start uses the original native receipt.+- Existing `superTabsCollaboration.e2e.ts` currently fails at `GUEST_NOT_ALLOWED`: main's guest policy does not permit the old `super_tabs` capacity RPC. This change does not widen guest permissions. The new explicit contribution flow has its own end-to-end test.++## Delivery constraints++Use the official signed internal Desktop workflow, not a public feature-test release. New machine contribution requires the matching CLI and backend as well as Desktop. A Desktop-only artifact does not by itself deploy those changes. Existing remote terminal control permissions still apply: a collaborator allowed only to observe a terminal cannot type into it.++Implementation, validation, merge, build/publication and waiting are distinct phases. No merge or production publication is claimed by this document.++## Completed local checks++- 86 affected Desktop widget tests passed, including native-question notice → exact terminal → cleared question, multi-agent panes, hiding and reopening, dark/light and narrow/large-text layouts.+- Native macOS fixture passed with real terminal rendering and realistic CPU/GPU/RAM/disk/quota cards; screenshots saved locally under `/private/tmp/super-tab-review-final`.+- 265 CLI tests across 16 files passed; both TypeScript typechecks passed.+- Backend replica-set suite: 33 tests passed, including the final guard against changing a contribution during model settlement.+- Two-daemon contribution E2E passed again after integrating main's creator-scoped creation receipts (`1fb7c4fc08`). No real user harnesses were used for testing.+- Shared icon catalogue audit passed. Whole-tree Flutter analysis reported pre-existing third-party/deprecated and unrelated device-test warnings; it is not recorded as a clean whole-tree check.++Review PR: https://github.com/autonomous-ai/openharness/pull/1436++Official internal Desktop build: https://github.com/autonomous-ai/openharness/actions/runs/39294760131 (Desktop source `da0a3f9dacbd70e31cc78905f2208f77affa84b8`; the follow-up settlement fix changes backend files only).++Validation/build timing for this final review phase: required CI and internal build started around 17:30 UTC; native macOS and final local integration checks completed by 17:35 UTC. Earlier implementation time is not represented as build time. Publication and merge remain separate, and their final status is reported with the review handoff.++## Installed review build++The official internal build succeeded and was locally accepted by Gatekeeper as a notarized Developer ID app. It is installed at `/Users/ab/Applications/Harness SuperTab Oct19.app` and opened for review. Press Cmd-Option-Shift-T to create a Super Tab. Local CLI `0.4.23-dev.f2e4605215` is installed using the repository installer, with a binary-only rollback copy in `.harness/review/cli-rollback-before-f2e4605`. No user harnesses were used for tests.++[Apple Silicon DMG](https://storage.googleapis.com/s3-autonomous-upgrade-3/harness/desktop-internal/9207d418957f7828742b619a9d848fac/Harness-macos-arm64-1.2.94-da0a3f9.dmg)++SHA-256: `9e3a2d3f5e60add9380c1acde01e57744accd71c99bfa462bb76395730cf4682`.++The final broad CI run exposed one obsolete welcome-page assertion that expected Recent harnesses on Super Tab creation. The test now verifies the approved lead-only form and preservation of existing harnesses; all 15 tests in that file pass locally. This correction changes tests only, so the installed application's source remains current. Required CI must pass before merge. The matching backend has not been published by the internal app build; machine contribution needs that server rollout before it can be used against production.