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
Polish Super Tab group panes and simplify machine setup (#1439)
Deea22efe7cb109
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 24e97f0cc..1848ddbaf 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -772,3 +772,13 @@ describe('Super Tabs on a real Mongo replica set', () => {await expect(run(tab, { type: 'route.record', conversationId: 'lead', decision } as Command, host, lead)).rejects.toMatchObject({ code: 'RATE_LIMITED', status: 429 })})})++it('allocates workgroup numbers transactionally and replays the same number after a lost reply', async () => {+ const tab = (await store.create(owner, randomUUID(), 'Numbered work')).id+ const operations = [randomUUID(), randomUUID(), randomUUID()]+ const command: Command = { type: 'conversation.create', title: 'Work', brief: '', checks: [] }+ const results = await Promise.all(operations.map(id => run(tab, command, owner, undefined, id)))+ expect(results.map(r => r.result.number).sort()).toEqual([1, 2, 3])+ expect((await run(tab, command, owner, undefined, operations[0])).result).toEqual(results[0]!.result)+ expect((await store.read(owner, tab)).state.conversations.map(c => c.number)).toEqual([undefined, 1, 2, 3])+})diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex a3d5c4550..6a7c52d19 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -445,3 +445,36 @@ describe('decisions linked to work', () => {expect(effects.routeDecisions[0]).toMatchObject({ op: 'final', final, override: { by: 'lead', reason: 'The opus agent is already warm.' } })})})++it('assigns stable workgroup numbers through old snapshots, rename, archive and new groups', () => {+ const f = fixture(), first = f.group(), second = f.group()+ expect(f.state.conversations.map(c => c.number)).toEqual([undefined, 1, 2])+ delete f.state.conversations[1]!.number+ delete f.state.conversations[2]!.number+ expect(visibleState(f.state, owner).conversations.map(c => c.number)).toEqual([undefined, 1, 2])+ expect(f.state.conversations[1]!.number).toBeUndefined()+ f.run({ type: 'conversation.rename', conversationId: first, title: 'Renamed' })+ f.run({ type: 'conversation.archive', conversationId: second, archived: true })+ const third = f.group()+ expect(f.state.conversations.map(c => [c.id, c.number])).toEqual([['lead', undefined], [first, 1], [second, 2], [third, 3]])+})+it('records the lead project once and accepts installed engines beyond Claude and Codex', () => {+ const f = fixture(), project = { cwd: '/repo', repositoryUrl: 'https://github.com/example/project' }+ f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: 'lead', name: 'Lead', configuration: config, lead: true, project }, owner,+ { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })+ expect(f.state.project).toEqual({ machineId: 'host', ...project })+ expect(() => f.run({ type: 'tab.project', machineId: 'host', project })).toThrow('already has a project')+ const command = commandSchema.parse({ type: 'machine.contribute', machineId: 'host', name: 'Workstation', cwd: '/repo', engines: ['claude', 'codex', 'pi', 'opencode'], maxAgents: 4 })+ f.run(command, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })+ expect(f.state.machines![0]!.engines).toEqual(['claude', 'codex', 'pi', 'opencode'])+})+it('restricts recording a legacy project to the owner or controlling lead', () => {+ const f = fixture(); f.invite()+ const command: Command = { type: 'tab.project', machineId: 'host', project: { cwd: '/repo', repositoryUrl: null } }+ expect(() => f.run(command, peer)).toThrow()+ f.run(command)+ expect(f.state.project).toMatchObject({ machineId: 'host', cwd: '/repo' })+})+it('rejects embedded credentials in shared project metadata', () => {+ expect(commandSchema.safeParse({ type: 'tab.project', machineId: 'host', project: { cwd: '/repo', repositoryUrl: 'https://[email protected]/example/project' } }).success).toBe(false)+})diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 2210d1172..0a117cb4b 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -1,7 +1,7 @@import { admitMachineStart, machineContribution } from './machines.js'import { z } from 'zod'import {- activeWork, actorKey, agent, author, conversation, fail, person, stableId,+ activeWork, actorKey, agent, author, conversation, fail, person, stableId, numberConversations,type Actor, type Agent, type Author, type CommandEffects, type SuperTabState,} from './model.js'import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type RouteDecision, type RouteFinal, type RouteOverride } from './routeRecord.js'@@ -17,6 +17,15 @@ const configuration = z.object({engineVersion: z.string().max(160).nullable(),}).strict()const path = z.string().min(1).max(4096).regex(/^\//).refine(value => !/[\x00-\x1f\x7f]/.test(value))+const project = z.object({ cwd: path, repositoryUrl: z.string().max(4096).refine(value => {+ if (/[\x00-\x20\x7f]/.test(value)) return false+ if (/^git@[^/@:]+:[^@]+$/.test(value)) return true+ try {+ const uri = new URL(value)+ return ['https:', 'http:', 'ssh:', 'git:'].includes(uri.protocol) && !!uri.hostname && !uri.password &&+ (!uri.username || (uri.protocol === 'ssh:' && uri.username === 'git'))+ } catch { return false }+}, 'Share a repository URL without credentials.').nullable() }).strict()export const startRequestSchema = z.object({conversationId: id, machineId: id, engine: z.string().min(1).max(80), name: title, cwd: path,worktree: z.boolean(), branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(),@@ -30,15 +39,16 @@ 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.contribute'), machineId: id, name: title, cwd: path, engines: z.array(z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/)).min(1).max(32), 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.project'), machineId: id, project }).strict(),z.object({ type: z.literal('tab.pause'), paused: z.boolean() }).strict(),z.object({ type: z.literal('tab.routingPolicy'), policy: routingOverrideSchema.nullable() }).strict(),z.object({ type: z.literal('conversation.create'), title, brief: z.string().trim().max(8000), checks: z.array(check).max(40) }).strict(),z.object({ type: z.literal('conversation.rename'), conversationId: id, title }).strict(),z.object({ type: z.literal('conversation.archive'), conversationId: id, archived: z.boolean() }).strict(),- z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), initialMessage: text.optional() }).strict(),+ z.object({ type: z.literal('agent.add'), conversationId: id, machineId: id, harnessId: id, name: title, configuration, lead: z.boolean(), project: project.optional(), initialMessage: text.optional() }).strict(),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(),@@ -100,6 +110,7 @@ function open(state: SuperTabState, conversationId: string) {export function applyCommand(original: SuperTabState, actor: Actor, input: Command, context: CommandContext): CommandEffects {const command = commandSchema.parse(input)const state = structuredClone(original)+ numberConversations(state)const result: Record<string, unknown> = {}const effects: CommandEffects = { state, messages: [], cancelledAgents: [], previousAttempts: [], routeDecisions: [], result }const operationId = stableId(state.id, actorKey(actor), context.operationId)@@ -160,6 +171,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}switch (command.type) {+ case 'tab.project': {+ controls(state, actor)+ if (actor.kind === 'person') owner(state, actor)+ if (state.project) fail('PROJECT_SET', 'This Super Tab already has a project.')+ state.project = { machineId: command.machineId, ...command.project }+ break+ }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)@@ -197,11 +215,13 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('BRIEF_REQUIRED', 'Delegated work needs a brief and acceptance checks.', 400)}const leadId = conversation(state, 'lead').leadId- state.conversations.push({ id: operationId, title: command.title, leadId, agentIds: leadId ? [leadId] : [],+ const number = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1+ state.conversations.push({ id: operationId, number, title: command.title, leadId, agentIds: leadId ? [leadId] : [],archived: false, brief: command.brief, assignment: null, lastMessageSequence: 0,checks: command.checks.map((c, i) => ({ ...c, id: stableId(operationId, String(i)), evidence: null, passedBy: null })),})result.conversationId = operationId+ result.number = numberif (command.brief) message(operationId, command.brief)break}@@ -220,6 +240,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commacase 'agent.add': {controls(state, actor, command.conversationId)const group = open(state, command.conversationId)+ if (group.id === 'lead' && command.lead && command.project && !state.project) {+ state.project = { machineId: command.machineId, ...command.project }+ }const grant = context.contribution ?? fail('HOST_REQUIRED', 'This session must be explicitly shared by an authorized contributor.', 403)const contributor = person(state, grant.contributorId)if (contributor.role === 'viewer') fail('READ_ONLY', 'A viewer cannot contribute agents.', 403)diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.tsindex 30fd058e6..90199c1c3 100644--- a/backend/src/superTabs/machines.ts+++ b/backend/src/superTabs/machines.ts@@ -23,13 +23,13 @@ const resource = z.object({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(),+const quota = z.object({ engine: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), 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),+ quotas: z.array(quota).max(32), 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>diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex ca103bf5b..beffc7c7e 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -73,6 +73,8 @@ export interface Assignment {}export interface Conversation {id: string+ /** Stable, tab-local workgroup reference. Lead has no number. */+ number?: numbertitle: stringleadId: string | nullagentIds: string[]@@ -93,6 +95,7 @@ export interface SuperTabState {version: 1id: stringname: string+ project?: { machineId: string; cwd: string; repositoryUrl: string | null }ownerId: stringenvironment: string/** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */@@ -152,6 +155,15 @@ export function agent(state: SuperTabState, id: string): Agent {export function conversation(state: SuperTabState, id: string): Conversation {return state.conversations.find(c => c.id === id) ?? fail('NOT_FOUND', 'This conversation is unavailable.', 404)}++/** Legacy groups keep their append order, including archived groups. Persisted+ * numbers are never reassigned; the store serializes concurrent additions. */+export function numberConversations(state: SuperTabState): void {+ let next = Math.max(0, ...state.conversations.map(c => c.number ?? 0)) + 1+ for (const group of state.conversations) {+ if (group.id !== 'lead' && group.number == null) group.number = next+++ }+}export function author(state: SuperTabState, actor: Actor, write = false): Author {if (actor.kind === 'person') {const member = person(state, actor.userId)@@ -177,6 +189,7 @@ export function createSuperTab(id: string, name: string, owner: { id: string; emexport function visibleState(state: SuperTabState, actor: Actor): SuperTabState {author(state, actor)const visible = structuredClone(state)+ numberConversations(visible)if (actor.kind !== 'person' || actor.userId !== state.ownerId) visible.invitations = []return visible}diff --git a/cli/e2e/superTabMachines.e2e.ts b/cli/e2e/superTabMachines.e2e.tsindex 25400a652..522a25a73 100644--- a/cli/e2e/superTabMachines.e2e.ts+++ b/cli/e2e/superTabMachines.e2e.ts@@ -57,7 +57,7 @@ it('queues a teammate start without granting general machine access and resumes}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 === '/api/super-tabs/pool-tab') return { data: { state: { id: 'pool-tab', agents, project: { machineId: memberMachine.machineId, cwd: project, repositoryUrl: null } }, revision: observations } }if (path.includes('/starts/')) return { data: starts.get(path.split('/').at(-1)!) }if (path.endsWith('/commands')) {const c = body.command@@ -77,6 +77,18 @@ it('queues a teammate start without granting general machine access and resumesawait 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 setup = { action: 'prepareContribution', tabId: 'pool-tab', operationId: 'fixture-setup' }+ const prepared = await until('one-field machine preparation', async () => {+ const value = await onB.request('super_tabs', setup, 30000)+ expect(value.error, JSON.stringify(value)).toBeUndefined()+ return value.state === 'ready' ? value : null+ }, 45000, 250)+ expect(prepared.cwd).toBe(project)+ expect(prepared.engines).toEqual(expect.arrayContaining(['claude', 'codex']))+ expect(prepared.maxAgents).toBeGreaterThan(0)+ expect((await onB.request('agents_list')).agents).toHaveLength(0)+ const { requestId: _requestId, ...receipt } = prepared+ expect(await onB.request('super_tabs', setup)).toMatchObject(receipt)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)diff --git a/cli/src/superTabs/contribution.spec.ts b/cli/src/superTabs/contribution.spec.tsnew file mode 100644index 000000000..e5d65fe48--- /dev/null+++ b/cli/src/superTabs/contribution.spec.ts@@ -0,0 +1,79 @@+import { describe, expect, it, vi } from 'vitest'+import { fakeCore } from '../testing/fakeCore.js'+import { ContributionPreparations, prepareContribution } from './contribution.js'++const GiB = 1024 ** 3+function fixture() {+ const core = fakeCore()+ const state: Record<string, unknown> = { project: { machineId: core.daemon.machineId(), cwd: '/repo', repositoryUrl: 'https://github.com/example/project' } }+ const backend = vi.fn(async () => ({ state }))+ const close = vi.fn()+ const request = vi.fn(async () => ({ engines: [+ { engine: 'claude', installed: true, signedIn: true },+ { engine: 'codex', installed: true, signedIn: false },+ { engine: 'pi', installed: true },+ { engine: 'opencode', installed: false },+ { engine: 'terminal', installed: true },+ ] }))+ const open = vi.fn(async () => ({ request, close }))+ const prepare = vi.fn(async () => '/clone')+ const capacity = vi.fn(async () => ({ ok: true, resources: { memoryTotalBytes: 32 * GiB, memoryUsedBytes: 16 * GiB, projectDiskFreeBytes: 100 * GiB } }))+ const deps = { backend, open, prepare, capacity }+ const run = () => prepareContribution(core, { tabId: 'tab' }, deps as never)+ return { run, state, deps, core, request, close }+}+describe('one-field machine preparation', () => {+ it('uses the lead project on its host and probes all engines without inventing authentication', async () => {+ const f = fixture()+ expect(await f.run()).toEqual({ ok: true, state: 'ready', cwd: '/repo', engines: ['claude', 'pi'], maxAgents: 4 })+ expect(f.request).toHaveBeenCalledWith('engines_probe', { accounts: true }, 20000)+ expect(f.deps.prepare).not.toHaveBeenCalled()+ expect(f.close).toHaveBeenCalledOnce()+ })+ it('prepares the repository on another machine and reuses an existing contribution', async () => {+ const f = fixture(); (f.state.project as Record<string, unknown>).machineId = 'another'+ expect(await f.run()).toMatchObject({ cwd: '/clone' })+ expect(f.deps.prepare).toHaveBeenCalledWith({ source: 'remote', repositoryUrl: 'https://github.com/example/project.git', name: 'project' })+ f.state.machines = [{ machineId: f.core.daemon.machineId(), cwd: '/existing' }]+ expect(await f.run()).toMatchObject({ cwd: '/existing' })+ expect(f.deps.prepare).toHaveBeenCalledOnce()+ })+ it('does not clone paths or credential-bearing URLs from shared metadata', async () => {+ const f = fixture()+ for (const repositoryUrl of [null, 'file:///private/repo', 'https://[email protected]/example/project', 'ext::command']) {+ f.state.project = { machineId: 'other', repositoryUrl }+ await expect(f.run()).rejects.toThrow()+ }+ expect(f.deps.prepare).not.toHaveBeenCalled()+ expect(f.deps.open).not.toHaveBeenCalled()+ })+ it('fails when no installed engine or project disk can be read and closes the connection', async () => {+ const f = fixture()+ f.request.mockResolvedValueOnce({ engines: [] })+ await expect(f.run()).rejects.toThrow('Sign in')+ f.deps.capacity.mockResolvedValueOnce({ error: 'INVALID_REQUEST' } as never)+ await expect(f.run()).rejects.toThrow('project folder')+ expect(f.close).toHaveBeenCalledTimes(2)+ })+ it('keeps a slow clone in one bounded receipt and preserves errors for polling', async () => {+ let resolve!: (value: Record<string, unknown>) => void+ const prepare = vi.fn(() => new Promise<Record<string, unknown>>(r => { resolve = r }))+ const jobs = new ContributionPreparations(prepare), input = { operationId: 'setup', tabId: 'tab' }+ expect(jobs.read(input)).toMatchObject({ state: 'preparing' })+ expect(jobs.read(input)).toMatchObject({ state: 'preparing' })+ expect(prepare).toHaveBeenCalledOnce()+ expect(jobs.read({ ...input, tabId: 'elsewhere' })).toEqual({ error: 'OPERATION_CONFLICT' })+ resolve({ ok: true, state: 'ready', cwd: '/clone' }); await Promise.resolve()+ expect(jobs.read(input)).toMatchObject({ state: 'ready', cwd: '/clone' })+ jobs.clear(); jobs.read(input); expect(prepare).toHaveBeenCalledTimes(2)+ const failed = new ContributionPreparations(async () => { throw new Error('Clone failed') })+ failed.read(input); await Promise.resolve()+ expect(failed.read(input)).toEqual({ error: 'SETUP_FAILED', detail: 'Clone failed' })+ })+ it('bounds pending setups and refuses invalid receipt keys', () => {+ const jobs = new ContributionPreparations(() => new Promise(() => {}))+ expect(jobs.read({ tabId: 'tab' })).toEqual({ error: 'INVALID_REQUEST' })+ for (let i = 0; i < 32; i++) jobs.read({ tabId: 'tab', operationId: `setup-${i}` })+ expect(jobs.read({ tabId: 'tab', operationId: 'extra' })).toMatchObject({ error: 'SETUP_BUSY' })+ })+})diff --git a/cli/src/superTabs/contribution.ts b/cli/src/superTabs/contribution.tsnew file mode 100644index 000000000..18d1e9b8c--- /dev/null+++ b/cli/src/superTabs/contribution.ts@@ -0,0 +1,73 @@+import type { CoreApi } from '../core/api.js'+import { openDaemon } from '../agentClient/daemon.js'+import { parseProjectFolder, prepareProjectFolder } from '../lib/projectFolder.js'+import { readCapabilities } from './capacity.js'+import { backend, identifier, object } from './host.js'++type Json = Record<string, unknown>+const GiB = 1024 ** 3++/** Owner-only setup. Reuses the regular checkout preparation and engine probe;+ * it neither launches an agent nor grants the team access to the computer. */+export async function prepareContribution(core: CoreApi, input: Json, deps = {+ backend, open: openDaemon, prepare: prepareProjectFolder, capacity: readCapabilities,+}): Promise<Json> {+ if (!identifier(input.tabId)) throw new Error('Choose a Super Tab.')+ const answer = object(await deps.backend(core, 'GET', `/api/super-tabs/${input.tabId}`))+ const state = object(answer.state), project = object(state.project)+ const machineId = core.daemon.machineId()+ const existing = (Array.isArray(state.machines) ? state.machines.map(object) : []).find(m => m.machineId === machineId)+ let cwd = existing?.cwd+ if (typeof cwd !== 'string') {+ if (project.machineId === machineId && typeof project.cwd === 'string') cwd = project.cwd+ else {+ if (typeof project.repositoryUrl !== 'string') throw new Error('The lead needs to share a repository before this machine can join.')+ const source = parseProjectFolder({ projectSource: 'remote', repositoryUrl: project.repositoryUrl })+ if (!source) throw new Error('The project repository is unavailable.')+ cwd = await deps.prepare(source)+ }+ }+ const connection = await deps.open({ dataDir: core.dataDir, port: core.daemon.port, machineId })+ try {+ const [probe, capability] = await Promise.all([+ connection.request('engines_probe', { accounts: true }, 20_000),+ deps.capacity({ cwd, tools: ['git'], devices: [] }),+ ])+ const engines = (Array.isArray(probe.engines) ? probe.engines.map(object) : [])+ .filter(e => identifier(e.engine) && e.engine !== 'terminal' && e.installed === true && e.signedIn !== false)+ .map(e => e.engine as string)+ if (!engines.length) throw new Error('Sign in to an agent on this machine, then try again.')+ const resources = object('resources' in capability ? capability.resources : null)+ if (capability.ok !== true || typeof resources.projectDiskFreeBytes !== 'number') throw new Error('The project folder is unavailable on this machine.')+ const available = typeof resources.memoryTotalBytes === 'number' && typeof resources.memoryUsedBytes === 'number'+ ? Math.max(0, resources.memoryTotalBytes - resources.memoryUsedBytes) : 0+ // A conservative ceiling; each actual start still reserves measured memory+ // and disk and rechecks the engine's current subscription allowance.+ const maxAgents = Math.max(1, Math.min(8, Math.floor(available / (4 * GiB))))+ return { ok: true, state: 'ready', cwd, engines: [...new Set(engines)], maxAgents }+ } finally { connection.close() }+}++/** Cloning can outlive one RPC. Poll the same receipt instead of blocking the+ * core/service request or dispatching another checkout after a timeout. */+export class ContributionPreparations {+ private readonly jobs = new Map<string, { tabId: string; result: Json }>()+ constructor(private readonly prepare: (input: Json) => Promise<Json>) {}+ clear(): void { this.jobs.clear() }+ read(input: Json): Json {+ if (!identifier(input.operationId) || !identifier(input.tabId)) return { error: 'INVALID_REQUEST' }+ const known = this.jobs.get(input.operationId)+ if (known) return known.tabId === input.tabId ? known.result : { error: 'OPERATION_CONFLICT' }+ if (this.jobs.size >= 32) {+ const finished = [...this.jobs].find(([, job]) => job.result.state !== 'preparing')+ if (!finished) return { error: 'SETUP_BUSY', detail: 'Wait for the other machine setup to finish.' }+ this.jobs.delete(finished[0])+ }+ const job = { tabId: input.tabId, result: { ok: true, state: 'preparing' } as Json }+ this.jobs.set(input.operationId, job)+ void this.prepare(input).then(result => { job.result = result }, error => {+ job.result = { error: 'SETUP_FAILED', detail: error instanceof Error ? error.message : 'Could not prepare this machine.' }+ })+ return job.result+ }+}diff --git a/cli/src/superTabs/machines.ts b/cli/src/superTabs/machines.tsindex 443feb743..83596fd5d 100644--- a/cli/src/superTabs/machines.ts+++ b/cli/src/superTabs/machines.ts@@ -49,7 +49,7 @@ export class ContributedMachines {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 => {+ quotas: (Array.isArray(pool.engines) ? pool.engines : []).filter((e): e is string => typeof e === 'string').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 }diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex f1fb7486f..7946975b1 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -10,7 +10,7 @@ vi.mock('../lib/jev/jevClient.js', async importOriginal => ({ ...await importOriconst createJev = vi.mocked(createJevDecide)const owner = { local: true, owner: true }, visitor = { local: false, owner: false }-function setup(options: { jev?: () => JevDecide } = {}) {+function setup(options: { jev?: () => JevDecide; prepareContribution?: typeof import('./contribution.js').prepareContribution } = {}) {const agentId = createHash('sha256').update(JSON.stringify(['machine-1', 'native'])).digest('hex').slice(0, 24)const agent = { id: agentId, machineId: 'machine-1', harnessId: 'native' }const call = vi.fn(async () => ({ status: 200, body: { success: true, data: { state: { agents: [agent] } } } }))@@ -284,3 +284,18 @@ it('refuses routing to anyone but the group Lead, and past 30 decisions in the rexpect(await ask('g1')).toMatchObject({ ok: true })expect(decide).toHaveBeenCalledTimes(2)})++it('prepares machines only for their owner and clears setup receipts on disconnect', async () => {+ const prepareContribution = vi.fn(async () => ({ ok: true, state: 'ready' }))+ const t = setup({ prepareContribution })+ const request = { action: 'prepareContribution', tabId: 'tab', operationId: 'setup' }+ expect(await t.ask(request, visitor)).toEqual({ error: 'OWNER_REQUIRED' })+ expect(await t.ask(request, { local: false, owner: true, accountOwner: false })).toEqual({ error: 'OWNER_REQUIRED' })+ expect(prepareContribution).not.toHaveBeenCalled()+ expect(await t.ask(request, owner)).toMatchObject({ state: 'preparing' })+ expect(await t.ask(request, owner)).toMatchObject({ state: 'ready' })+ expect(prepareContribution).toHaveBeenCalledOnce()+ t.port.disconnected()+ await t.ask(request, owner)+ expect(prepareContribution).toHaveBeenCalledTimes(2)+})diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex efbd3884d..65ce65e1c 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -8,6 +8,7 @@ import { createJevDecide, type JevDecide } from '../lib/jev/jevClient.js'import { machineChoices } from '../lib/newCommand.js'import { START_REQUIREMENTS } from './capacity.js'import { CapacityReservations, type ReservationBook } from './reservations.js'+import { ContributionPreparations, prepareContribution } from './contribution.js'const HELP = {status: 'Read the shared tab roster and work.',@@ -36,6 +37,7 @@ const HELP = {const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []export interface SuperTabServiceOptions {+ prepareContribution?: typeof prepareContributioncapacity?: typeof readCapabilitieshost?: (core: CoreApi, machineId: string) => SuperTabHostreservations?: (core: CoreApi, machineId: string) => ReservationBook@@ -43,6 +45,7 @@ export interface SuperTabServiceOptions {jev?: (core: CoreApi) => JevDecide}export function superTabService(core: CoreApi, options: SuperTabServiceOptions = {}): { requests: ServiceRequests; port: SuperTabsPort } {+ const preparations = new ContributionPreparations(input => (options.prepareContribution ?? prepareContribution)(core, input))let host: SuperTabHost | null = nulllet book: ReservationBook | null = null, bookMachine: string | null = nullconst reservations = () => {@@ -58,7 +61,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =host.start()return host}- const disconnect = () => { host?.stop(); host = null; book?.stop(); book = null; bookMachine = null }+ const disconnect = () => { preparations.clear(); host?.stop(); host = null; book?.stop(); book = null; bookMachine = null }const port = {connected: () => {if (identifier(core.daemon.machineId()) && existsSync(hostJournalFile(core.dataDir, core.daemon.machineId()))) wake()@@ -83,6 +86,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =return await wake().prepareNative(payload.tabId, payload.contextId, payload.action === 'renewNative', closed)}if (!asker.owner || (!asker.local && asker.accountOwner !== true)) return { error: 'OWNER_REQUIRED' }+ if (payload.action === 'prepareContribution') return preparations.read(payload)if (payload.action === 'backend') {const { method, path } = payloadif (!['GET', 'POST'].includes(String(method)) || typeof path !== 'string'diff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dartindex ef5e8649a..271136a7b 100644--- a/desktop/integration_test/super_tab_native_test.dart+++ b/desktop/integration_test/super_tab_native_test.dart@@ -228,18 +228,25 @@ void main() {reviews++;return false;};- await tester.tap(find.byType(PaneCloseButton));- await tester.pumpAndSettle();- expect(f.app.activeSwarm.panes, isEmpty);- expect(c.terminalAgent('lead'), isNull);- expect(find.byType(TerminalPanel), findsNothing);+ expect(find.byType(PaneCloseButton), findsNothing);+ await f.app.requestClosePane(f.app.activeSwarm.panes.single.id);+ await tester.pump(const Duration(milliseconds: 100));+ expect(f.app.activeSwarm.panes, hasLength(1));+ expect(c.terminalAgent('lead'), isNotNull);expect(reviews, 0);expect(f.connection.calls.where((call) => call.$1 == 'agent_close'),isEmpty,);- expect(c.snapshot!.agents, hasLength(1));- await shot('hidden-terminal');+ await tester.tap(find.byTooltip('Chat'));+ await tester.pump(const Duration(milliseconds: 100));+ await tester.tap(find.byTooltip('Add machine'));+ await tester.pumpAndSettle();+ expect(find.text('Choose project folder'), findsNothing);+ expect(find.text('Maximum agents at once'), findsNothing);+ await shot('add-machine');+ Navigator.of(tester.element(find.byType(AlertDialog))).pop();+ await tester.pumpAndSettle();// An earlier app/daemon may already have cleaned up this member. Reopening// must resume its exact saved conversation before preparing recording.f.connection.native = {@@ -288,6 +295,42 @@ void main() {await tester.pump(const Duration(milliseconds: 100));expect(find.byType(TerminalPanel), findsOneWidget);await shot('resumed-terminal');+ final group = (server.state['conversations'] as List)[1] as Map;+ group['number'] = 1;+ group['agentIds'] = ['lead-agent', 'worker-a', 'worker-b', 'worker-c'];+ group['leadId'] = 'lead-agent';+ for (final name in ['a', 'b', 'c']) {+ (server.state['agents'] as List).add({+ 'id': 'worker-$name',+ 'name': 'Builder $name',+ 'machineId': 'm',+ 'harnessId': 'native-$name',+ 'contributorId': 'owner',+ 'configuration': {'engine': name == 'b' ? 'pi' : 'codex'},+ });+ f.app.machineStates['m']!.agents.add(+ Agent.fromJson({+ 'id': 'native-$name',+ 'name': 'Builder $name',+ 'engine': name == 'b' ? 'pi' : 'codex',+ 'status': 'stopped',+ 'terminal': {'available': false},+ }),+ );+ }+ await c.refresh();+ c.select('offline');+ c.selectGroupTerminals('offline');+ for (var i = 0; i < 120 && f.app.activeSwarm.panes.length != 4; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ await tester.pump(const Duration(milliseconds: 200));+ expect(f.app.activeSwarm.panes, hasLength(4));+ expect(find.byType(PaneCloseButton), findsNothing);+ expect(find.text('#1 Offline editing'), findsWidgets);+ expect(tester.takeException(), isNull);+ await shot('group-terminals');+await tester.pumpWidget(const SizedBox());await c.flush();f.app.superTabs.dispose();diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex cf54554ad..fd45ebfea 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -1968,6 +1968,7 @@ class _SwarmScreenState extends State<SwarmScreen> {],},'footerCovered':+ app.activeSwarm.isSuperTab ||(!_routeIsCurrent && !_footerPreviewCurrent) ||(_newHarnessOverlay != null && !_newHarnessHidden) ||_searchOverlay != null,@@ -8019,14 +8020,15 @@ class _SwarmScreenState extends State<SwarmScreen> {],),),- MediaQuery.withNoTextScaling(- child: _native- ? SizedBox(- key: const ValueKey('workspace-status-bar'),- height: _statusBarHeight,- )- : _statusBar(),- ),+ if (!app.activeSwarm.isSuperTab)+ MediaQuery.withNoTextScaling(+ child: _native+ ? SizedBox(+ key: const ValueKey('workspace-status-bar'),+ height: _statusBarHeight,+ )+ : _statusBar(),+ ),],),),@@ -8137,8 +8139,9 @@ class _SwarmScreenState extends State<SwarmScreen> {// Include the pane's former bottom gutter in this row, so its controls sit// halfway between the pane edge and window bottom. Pane height is unchanged.// Keep inventory controls discoverable on the first, empty welcome screen.- double get _statusBarHeight =>- workspaceBarControlHeight(context) + kWorkspaceInset;+ double get _statusBarHeight => app.activeSwarm.isSuperTab+ ? 0+ : workspaceBarControlHeight(context) + kWorkspaceInset;Widget _statusBar() {final compactFooter = widget.chrome?.compactFooter;diff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex 08307f8fe..30fe566e5 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -94,6 +94,7 @@ abstract final class AppIcons {static const gamepad2 = LucideIcons.gamepad2400;static const gauge = LucideIcons.gauge400;static const gitBranch = LucideIcons.gitBranch400;+ static const gitPullRequest = LucideIcons.gitPullRequest400;static const globe = LucideIcons.globe400;static const hand = LucideIcons.hand400;static const heart = LucideIcons.heart400;diff --git a/desktop/lib/shared/widgets/app_icon_button.dart b/desktop/lib/shared/widgets/app_icon_button.dartindex a14e2e6ef..a7a6d7350 100644--- a/desktop/lib/shared/widgets/app_icon_button.dart+++ b/desktop/lib/shared/widgets/app_icon_button.dart@@ -18,9 +18,13 @@ class AppIconButton extends StatefulWidget {this.destructive = false,this.spinning = false,this.focusNode,+ this.selected,});final IconData icon;++ /// Navigation controls keep a visible well and selected semantics.+ final bool? selected;final VoidCallback? onPressed;final String? tooltip;@@ -166,6 +170,7 @@ class _AppIconButtonState extends State<AppIconButton>return Semantics(value: widget.spinning ? 'Working' : null,+ selected: widget.selected,child: IconButton(focusNode: widget.focusNode,tooltip: widget.tooltip,@@ -208,7 +213,11 @@ class _AppIconButtonState extends State<AppIconButton>? active: resting;}),- backgroundColor: const WidgetStatePropertyAll(Colors.transparent),+ backgroundColor: WidgetStatePropertyAll(+ widget.selected == true+ ? AppSurface.selectedFill+ : Colors.transparent,+ ),overlayColor: WidgetStateProperty.resolveWith((states) {if (states.contains(WidgetState.disabled)) {return Colors.transparent;diff --git a/desktop/lib/sharing/shared_harness_bar.dart b/desktop/lib/sharing/shared_harness_bar.dartindex 1e05ea8ab..82868c7d1 100644--- a/desktop/lib/sharing/shared_harness_bar.dart+++ b/desktop/lib/sharing/shared_harness_bar.dart@@ -64,7 +64,7 @@ class SharedHarnessBar extends StatelessWidget {final SharedPaneStatus status;final bool commentsSelected;final VoidCallback onToggleComments;- final VoidCallback onClose;+ final VoidCallback? onClose;/// Null hides the Terminal/Viewer switch: the pane shows one of them only.final bool? viewerSelected;@@ -92,11 +92,13 @@ class SharedHarnessBar extends StatelessWidget {),child: LayoutBuilder(builder: (context, constraints) {- final close = AppIconButton(- icon: AppIcons.close,- tooltip: 'Close shared harness',- onPressed: onClose,- );+ final close = onClose == null+ ? const SizedBox.shrink()+ : AppIconButton(+ icon: AppIcons.close,+ tooltip: 'Close shared harness',+ onPressed: onClose,+ );final actions = Wrap(spacing: 8,runSpacing: 8,diff --git a/desktop/lib/sharing/shared_harness_panel.dart b/desktop/lib/sharing/shared_harness_panel.dartindex 5f9096a33..90474e3b6 100644--- a/desktop/lib/sharing/shared_harness_panel.dart+++ b/desktop/lib/sharing/shared_harness_panel.dart@@ -39,7 +39,7 @@ class SharedHarnessPanel extends StatefulWidget {final TerminalPane pane;final SharedHarness grant;final bool hasAccess, visible;- final VoidCallback onClose;+ final VoidCallback? onClose;final bool link;final String? linkEnvironment;final VoidCallback? onSignIn;diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex d7f119722..cc4930393 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -3084,6 +3084,7 @@ class AppNotifier extends ChangeNotifier {Future<void> requestClosePane(int paneId) {final tab = activeSwarm;+ if (tab.isSuperTab && tab.superTabId != null) return Future.value();final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;if (pane == null) return Future.value();if (tab.isCompanions || tab.isDevices) return requestCloseSwarm(tab.id);@@ -16508,8 +16509,43 @@ class AppNotifier extends ChangeNotifier {}}- /// Put an agent into a specific tile, or into a NEW tile when [paneId] is- /// null — which is what a drop on the empty slot means.+ /// Keep a group member visible while its terminal is unavailable.+ void reserveSuperTabPane(String swarmId, String machineId, String harnessId) {+ final tab = swarms+ .where((s) => s.id == swarmId && s.superTabId != null)+ .firstOrNull;+ if (tab == null || _disposed) return;+ final existing = tab.panes+ .where((p) => p.machineId == machineId && p.agentId == harnessId)+ .firstOrNull;+ if (existing != null) {+ existing.inputContext = null;+ existing.watchOnly = true;+ existing.session?.stageInputContext(null, watchOnly: true);+ unawaited(existing.session?.setInputContext(null, watchOnly: true));+ return;+ }+ if (tab.panes.length >= maxPanes) return;+ final controller = superTabs.peek(tab.superTabId!);+ if (controller?.snapshot?.agents.any(+ (a) => a.machineId == machineId && a.harnessId == harnessId,+ ) !=+ true) {+ return;+ }+ tab.panes.add(+ TerminalPane(id: _nextPaneId++, machineId: machineId, agentId: harnessId)+ ..watchOnly = true,+ );+ tab.presets.remove(tab.panes.length);+ tab.paneSizes.removeWhere(+ (key, _) => key.startsWith('${tab.panes.length}:'),+ );+ tab.arranged = null;+ tab.arrangedKey = null;+ notifyListeners();+ }+Future<void> assignAgentToPane(int? paneId,String machineId,@@ -16572,6 +16608,9 @@ class AppNotifier extends ChangeNotifier {inputContext,watchOnly: watchOnly,);+ if (existing.session == null && target == activeSwarm) {+ await _attachSession(existing, intent: intent);+ }if (focus && target == activeSwarm) focusPane(existing.id);// A pane a refused share_add left unshared: a person's retry shares it.if (intent == AttachIntent.person) {@@ -17223,6 +17262,7 @@ class AppNotifier extends ChangeNotifier {set zoomedPaneId(int? value) => activeSwarm.zoomedPaneId = value;void toggleZoomPane() {+ if (activeSwarm.isSuperTab) return;final id = focusedPaneId;if (id == null || panes.length < 2) return;zoomedPaneId = zoomedPaneId == id ? null : id;@@ -17458,16 +17498,6 @@ class AppNotifier extends ChangeNotifier {if (tab == null) return;final pane = tab.panes.where((p) => p.id == paneId).firstOrNull;if (pane == null) return;- if (tab.superTabId case final superTabId?) {- final controller = superTabs.peek(superTabId);- if (pane.agentId case final agentId?) {- controller?.hideTerminal(- controller.selectedId,- pane.machineId,- agentId,- );- }- }if (tab.isCompanions || tab.isDevices) {await closeSwarm(tab.id, persist: persist);return;diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 3eebe3b09..6d3008876 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -57,16 +57,6 @@ 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) {@@ -112,7 +102,6 @@ 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>>{};@@ -141,12 +130,7 @@ class SuperTabController extends ChangeNotifier {final group = snapshot?.conversation(conversationId);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),- )+ .where((agent) => group.agentIds.contains(agent.id)).toList();}@@ -156,25 +140,11 @@ class SuperTabController extends ChangeNotifier {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) {if (_disposed || accessRevoked) return;if (agentId != null &&@@ -182,11 +152,9 @@ class SuperTabController extends ChangeNotifier {true) {return;}- if (_terminals[conversationId] == agentId &&- _hiddenTerminals[conversationId] == null) {+ if (_terminals[conversationId] == agentId) {return;}- _hiddenTerminals.remove(conversationId);if (agentId == null) {_terminals.remove(conversationId);} else {@@ -233,10 +201,7 @@ 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/launch.dart b/desktop/lib/super_tabs/launch.dartindex ab182ea40..8a8724125 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -174,6 +174,7 @@ class SuperTabLaunch {'Waiting for the new harness to appear on its machine.',);}+ final project = native.project ?? app.stateOf(machine)?.projectOf(native);saved['command'] ??= {'type': 'agent.add','conversationId': saved['conversationId'],@@ -181,6 +182,11 @@ class SuperTabLaunch {'harnessId': harnessId,'name': saved['lead'] == true ? 'Lead' : native.displayName,'lead': saved['lead'],+ if (saved['lead'] == true && project != null)+ 'project': {+ 'cwd': project.root ?? project.cwd,+ 'repositoryUrl': superTabRepositoryUrl(project.remote),+ },'configuration': {'engine': native.engine ?? '','model': native.modelName,diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex c43ec072e..f50f55473 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -13,7 +13,7 @@ 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 '../shared/widgets/app_select_field.dart';import '../widgets/workspace_subscription_usage.dart';import 'controller.dart';import 'dialog_scope.dart';@@ -125,242 +125,182 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {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']),+ m.nodeOnline != false,).toList();String? machineId =existing?['machineId'] as String? ??+ choices.where((m) => m.isLocalMachine).firstOrNull?.machine.machineId ??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;+ String? setupId;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;- }+ if (busy || machineId == null) return;+ final selected = machineId!;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.',- );+ // Older tabs can record the project already chosen for their lead.+ // No folder is inferred across machines from a matching path.+ if (c.snapshot?.project == null) {+ final lead = c.snapshot?.agents+ .where((a) => c.snapshot!.isLead(a.id))+ .firstOrNull;+ final host = lead == null+ ? null+ : app.stateOf(lead.machineId);+ final native = host?.agents+ .where((a) => a.id == lead?.harnessId)+ .firstOrNull;+ final project = native == null+ ? null+ : host?.projectOf(native);+ if (project != null && c.isOwner) {+ final recorded = await c.command({+ 'type': 'tab.project',+ 'machineId': lead!.machineId,+ 'project': {+ 'cwd': project.root ?? project.cwd,+ 'repositoryUrl': superTabRepositoryUrl(project.remote),+ },+ });+ if (recorded == null) {+ throw SuperTabFailure(+ 'PROJECT_UNAVAILABLE',+ c.operationError ??+ 'Could not read the lead’s project.',+ );+ }+ }}+ setupId ??= superTabOperationId();+ final deadline = DateTime.now().add(const Duration(minutes: 5));+ Map<String, dynamic> prepared;+ while (true) {+ if (!context.mounted || !c.canWrite) return;+ prepared = await app.superTabMachineRequest(selected, {+ 'action': 'prepareContribution',+ 'tabId': c.tabId,+ 'operationId': setupId,+ });+ if (prepared['state'] == 'ready') break;+ if (prepared['state'] != 'preparing') {+ throw const SuperTabFailure(+ 'UPDATE_REQUIRED',+ 'Update Harness on this machine, then try again.',+ );+ }+ if (DateTime.now().isAfter(deadline)) {+ throw const SuperTabFailure(+ 'SETUP_PENDING',+ 'Project setup is still running. Try again to check its progress.',+ );+ }+ await Future<void>.delayed(const Duration(seconds: 1));+ }+ if (!context.mounted || !c.canWrite) return;+ final machine = app.stateOf(selected);final result = c.pendingCommand?['type'] == 'machine.contribute'? await c.retry(): await c.command({'type': 'machine.contribute',- 'machineId': machineId,+ 'machineId': selected,'name': machine!.machine.displayName,- 'cwd': folder,- 'engines': engines.toList()..sort(),- 'maxAgents': limit,+ 'cwd': prepared['cwd'],+ 'engines': prepared['engines'],+ 'maxAgents': prepared['maxAgents'],});if (result == null) {throw SuperTabFailure('CONTRIBUTION_FAILED',- c.operationError ?? 'Could not contribute this machine.',+ c.operationError ?? 'Could not add this machine.',);}- await app.wakeSuperTabHost(machineId!);+ await app.wakeSuperTabHost(selected);if (context.mounted) Navigator.pop(context);} catch (failure) {if (context.mounted) {update(() {busy = false;error = failure.toString();+ if (failure is! SuperTabFailure ||+ failure.code != 'SETUP_PENDING') {+ setupId = null;+ }});}}}return AlertDialog(- title: const Text('Contribute a machine'),+ title: const Text('Add 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: [+ width: 360,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (choices.isEmpty)+ Text(+ 'Connect a computer to Harness first.',+ style: DesktopChrome.text(),+ )+ else+ AbsorbPointer(+ absorbing: busy,+ child: AppSelectField<String>(+ value: machineId!,+ semanticLabel: 'Machine',+ options: [for (final m in choices)- DropdownMenuItem(+ SelectOption(value: m.machine.machineId,- child: Text(m.machine.displayName),+ label: m.isLocalMachine+ ? 'This Mac'+ : 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,+ onChanged: (id) {+ if (busy) return;+ update(() {+ machineId = id;+ setupId = null;+ error = null;+ });+ },),- 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: 16),+ Text(+ 'Let the lead run agents here using this machine’s signed-in accounts.',+ style: DesktopChrome.text(),+ ),+ if (error != null) ...[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!),- ),+ Text(error!, style: DesktopChrome.metadata()),],- ),+ ],),),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',- ),+ onPressed: busy || machineId == null ? null : save,+ child: Text(busy ? 'Preparing…' : 'Add machine'),),],);@@ -414,25 +354,6 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {: '${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@@ -518,9 +439,20 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {final diskFree = value?.projectDiskTotalBytes == null? value?.diskFreeBytes: value?.projectDiskFreeBytes;- final disk = diskTotal == null || diskTotal <= 0 || diskFree == null+ final memoryFree =+ value?.memoryTotalBytes == null || value?.memoryUsedBytes == null? null- : (1 - diskFree / diskTotal) * 100;+ : (value!.memoryTotalBytes! - value.memoryUsedBytes!).clamp(+ 0,+ value.memoryTotalBytes!,+ );+ String available(double? used) =>+ resourcePercent(used == null ? null : (100 - used).clamp(0, 100));+ String compactBytes(num? bytes) =>+ resourceBytes(bytes?.toDouble())+ .replaceAll(' GB', 'G')+ .replaceAll(' TB', 'T')+ .replaceAll(' MB', 'M');return Padding(padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),child: Column(@@ -541,6 +473,9 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {: online? 'Online': 'Offline',+ if (value?.deviceType != null) value!.deviceType!,+ if (value?.chip != null) value!.chip!,+ if (value?.os != null) value!.os!,if (shared?['cwd'] != null) shared!['cwd'] as String,if (allowed != null) 'Engines: ${allowed.join(', ')}','RAM: ${resourceBytes(value?.memoryTotalBytes)}',@@ -595,91 +530,31 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {],),),- 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(),- ),- ],+ child: Text(+ [+ name,+ if (person != null) superTabPersonName(person.email),+ paused+ ? 'Paused'+ : !online+ ? 'Offline'+ : '$running ${running == 1 ? 'agent' : 'agents'}',+ ].join(' '),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(medium: true),),),- 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: 4),+ Tooltip(+ message:+ 'Available capacity\nCPU and GPU: idle percentage at the latest reading\nRAM: ${resourceBytes(memoryFree?.toDouble())} free of ${resourceBytes(value?.memoryTotalBytes)}\nSSD: ${resourceBytes(diskFree)} free of ${resourceBytes(diskTotal)}',+ child: Text(+ 'CPU ${available(value?.cpuPercent)} GPU ${available(value?.busiestGpu?.utilizationPercent)} RAM ${compactBytes(memoryFree)} SSD ${compactBytes(diskFree)}',+ 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()),+ const SizedBox(height: 4),if (usage.accounts.isEmpty)Text('—', style: DesktopChrome.control())else@@ -690,29 +565,20 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {for (final account in usage.accounts)Tooltip(message: account.detail,- child: Column(+ child: Row(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,- ),- ),- ],+ 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()),],),),@@ -732,7 +598,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {children: [Expanded(child: Text(- 'Machines · ${_ids.length}',+ 'Machines',style: DesktopChrome.metadata().copyWith(fontWeight: FontWeight.w600,),@@ -741,7 +607,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {if (c.canWrite && widget.app != null)AppIconButton(icon: AppIcons.plus,- tooltip: 'Contribute a machine',+ tooltip: 'Add machine',onPressed: () => unawaited(_contribute()),),],@@ -753,7 +619,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {child: Padding(padding: const EdgeInsets.all(16),child: Text(- 'Contribute a machine so the lead can start agents.',+ 'Add a machine for the lead to use.',textAlign: TextAlign.center,style: DesktopChrome.metadata(),),diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 1c894209a..5e6b0e568 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -26,9 +26,13 @@ class SuperTabMessageRow extends StatefulWidget {this.grouped = false,this.onReply,this.onOpenAgent,+ this.references = const {},+ this.onOpenGroup,});final SuperTabMessage message;+ final Map<int, String> references;+ final ValueChanged<String>? onOpenGroup;final String author;final SuperTabAgent? agent;final String? machineName;@@ -269,7 +273,11 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {style: DesktopChrome.metadata(),),),- SuperTabMessageText(message.text),+ SuperTabMessageText(+ message.text,+ references: widget.references,+ onOpenGroup: widget.onOpenGroup,+ ),SuperTabPullRequestLinks(message.text),...widget.receipts,],diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dartindex 32b6ff407..3b512e7bb 100644--- a/desktop/lib/super_tabs/message_text.dart+++ b/desktop/lib/super_tabs/message_text.dart@@ -1,5 +1,6 @@import 'package:flutter/material.dart';import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';+import 'package:markdown/markdown.dart' as md;import '../core/open_in_browser.dart';import '../shared/theme/app_theme.dart' as grid;@@ -8,8 +9,15 @@ import '../widgets/desktop_chrome.dart';/// Shared content is selectable, never executable. Markdown images are labels,/// not automatic network requests or reads from a collaborator's local disk.class SuperTabMessageText extends StatelessWidget {- const SuperTabMessageText(this.text, {super.key});+ const SuperTabMessageText(+ this.text, {+ super.key,+ this.references = const {},+ this.onOpenGroup,+ });final String text;+ final Map<int, String> references;+ final ValueChanged<String>? onOpenGroup;static Uri? webLink(String? href) {final uri = href == null ? null : Uri.tryParse(href);@@ -27,8 +35,10 @@ class SuperTabMessageText extends StatelessWidget {final heading = body.copyWith(fontWeight: FontWeight.w600);return MarkdownBody(data: text,- selectable: true,+ selectable: false,softLineBreak: true,+ inlineSyntaxes: [_WorkgroupReference(references)],+ builders: {'pre': _WrappedCode()},styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context)).copyWith(p: body,a: TextStyle(@@ -63,6 +73,7 @@ class SuperTabMessageText extends StatelessWidget {borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),),tableHead: heading,+ tableColumnWidth: const FlexColumnWidth(),tableBody: body,tableBorder: TableBorder.all(color: DesktopChrome.rim),tableCellsPadding: const EdgeInsets.symmetric(@@ -74,6 +85,14 @@ class SuperTabMessageText extends StatelessWidget {),),onTapLink: (_, href, _) {+ final number = href?.startsWith('workgroup:') == true+ ? int.tryParse(href!.substring(10))+ : null;+ final group = references[number];+ if (group != null) {+ onOpenGroup?.call(group);+ return;+ }final uri = webLink(href);if (uri != null) openInBrowser(uri);},@@ -84,3 +103,34 @@ class SuperTabMessageText extends StatelessWidget {);}}++/// Parsed as inline Markdown, so code and fenced blocks remain literal.+class _WorkgroupReference extends md.InlineSyntax {+ _WorkgroupReference(this.references)+ : super(r'(?<![\w/])#([1-9][0-9]*)(?!\w)');+ final Map<int, String> references;+ @override+ bool onMatch(md.InlineParser parser, Match match) {+ final number = int.tryParse(match[1]!);+ if (!references.containsKey(number)) {+ parser.addNode(md.Text(match[0]!));+ return true;+ }+ parser.addNode(+ md.Element.text('a', match[0]!)..attributes['href'] = 'workgroup:$number',+ );+ return true;+ }+}++class _WrappedCode extends MarkdownElementBuilder {+ @override+ Widget? visitText(md.Text text, TextStyle? preferredStyle) => Padding(+ padding: const EdgeInsets.all(12),+ child: Text(+ text.text,+ softWrap: true,+ style: grid.AppType.mono(color: DesktopChrome.foreground, height: 1.5),+ ),+ );+}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 072ec96dc..7c893826d 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -37,6 +37,7 @@ class SuperTabAgent {class SuperTabConversation {SuperTabConversation.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),+ number = (row['number'] as num?)?.toInt(),title = _text(row, 'title'),leadId = row['leadId'] as String?,agentIds = List.unmodifiable((row['agentIds'] as List).cast<String>()),@@ -51,6 +52,8 @@ class SuperTabConversation {? null: Map.unmodifiable(superTabMap(row['assignment']));final String id, title, brief;+ final int? number;+ String get label => number == null ? title : '#$number $title';final String? leadId;final List<String> agentIds;final bool archived;@@ -65,6 +68,9 @@ class SuperTabSnapshot {name = _text(row, 'name'),ownerId = _text(row, 'ownerId'),paused = row['paused'] == true,+ project = row['project'] == null+ ? null+ : Map.unmodifiable(superTabMap(row['project'])),people = _list(row['people'], SuperTabPerson.fromJson),agents = _list(row['agents'], SuperTabAgent.fromJson),machines = _list(@@ -84,6 +90,7 @@ class SuperTabSnapshot {}}final String id, name, ownerId;+ final Map<String, dynamic>? project;final bool paused;final List<SuperTabPerson> people;final List<SuperTabAgent> agents;@@ -206,3 +213,20 @@ class SuperTabMessage {);bool get uncertain => deliveries.any((d) => d['status'] == 'uncertain');}++/// A remote may contain a developer's embedded credential. Never share it.+String? superTabRepositoryUrl(String? remote) {+ if (remote == null || remote.isEmpty) return null;+ if (remote.startsWith('git@') && !remote.contains('://')) return remote;+ final uri = Uri.tryParse(remote);+ if (uri == null ||+ uri.host.isEmpty ||+ !['https', 'http', 'ssh', 'git'].contains(uri.scheme)) {+ return null;+ }+ if (uri.userInfo.isNotEmpty &&+ !(uri.scheme == 'ssh' && uri.userInfo == 'git')) {+ return null;+ }+ return remote;+}diff --git a/desktop/lib/super_tabs/pane.dart b/desktop/lib/super_tabs/pane.dartindex 169813280..d5fd2eeaf 100644--- a/desktop/lib/super_tabs/pane.dart+++ b/desktop/lib/super_tabs/pane.dart@@ -2,28 +2,36 @@ import 'package:flutter/widgets.dart';/// A Super Tab's view of an existing terminal. The renderer and session stay/// shared with ordinary panes; presentation belongs to this placement only.-/// AppNotifier's close policy keeps pane, keyboard and tab dismissal hide-only.+/// Group membership owns the visible panes; individual panes cannot be closed.class SuperPane extends InheritedWidget {const SuperPane({super.key,required this.machineId,required this.harnessId,this.title,+ this.titles = const {},+ this.failures = const {},+ this.onRetry,required super.child,});final String machineId, harnessId;final String? title;+ final Map<(String, String?), String> titles, failures;+ final VoidCallback? onRetry;static SuperPane? maybeOf(BuildContext context) =>context.dependOnInheritedWidgetOfExactType<SuperPane>();String? titleFor(String machine, String harness) =>- machine == machineId && harness == harnessId ? title : null;+ titles[(machine, harness)] ??+ (machine == machineId && harness == harnessId ? title : null);@overridebool updateShouldNotify(SuperPane oldWidget) =>machineId != oldWidget.machineId ||harnessId != oldWidget.harnessId ||- title != oldWidget.title;+ title != oldWidget.title ||+ titles != oldWidget.titles ||+ failures != oldWidget.failures;}diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dartindex cdfb8823d..30b9433eb 100644--- a/desktop/lib/super_tabs/roster.dart+++ b/desktop/lib/super_tabs/roster.dart@@ -207,10 +207,10 @@ class _SuperTabRosterState extends State<SuperTabRoster> {return ListView(padding: const EdgeInsets.only(bottom: 12),children: [- _heading('Leads · ${leads.length}'),+ _heading('Leads'),for (final agent in leads) _agent(agent),_heading(- 'Humans · ${state?.people.length ?? 0}',+ 'Humans',add: c.isOwner ? widget.onInvite : null,tooltip: 'Invite people',),@@ -249,7 +249,13 @@ class _SuperTabRosterState extends State<SuperTabRoster> {),),),- _heading('Agents · ${agents.length}'),+ _heading(+ 'Agents',+ add: c.canWrite && c.selected != null+ ? () => widget.onAddAgent(c.selected!)+ : null,+ tooltip: 'Add agent',+ ),for (final agent in agents) _agent(agent),],);diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 87fdbb040..140978495 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -409,7 +409,7 @@ class _SuperTabViewState extends State<SuperTabView> {for (final group in groups)ListTile(title: Text(- group.title,+ group.label,style: DesktopChrome.control(),),onTap: () =>@@ -463,7 +463,7 @@ class _SuperTabViewState extends State<SuperTabView> {selected: c.selectedId == group.id,selectedTileColor: DesktopChrome.activeSelection,title: Text(- group.title,+ group.label,maxLines: 1,overflow: TextOverflow.ellipsis,style: DesktopChrome.control(@@ -572,20 +572,86 @@ class _SuperTabViewState extends State<SuperTabView> {onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),),Expanded(- child: Text(- group?.title ?? 'Loading conversation…',- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: DesktopChrome.text(medium: true),+ child: Align(+ alignment: Alignment.centerLeft,+ child: group == null+ ? Text('Loading conversation…', style: DesktopChrome.text())+ : PopupMenuButton<String>(+ key: const ValueKey('super-group-options'),+ tooltip: 'Workgroup options',+ position: PopupMenuPosition.under,+ 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 (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',+ ),+ ),+ ],+ ],+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 4,+ vertical: 8,+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Flexible(+ child: Text(+ group.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.text(medium: true),+ ),+ ),+ const SizedBox(width: 6),+ Icon(+ AppIcons.chevronDown,+ size: 16,+ color: DesktopChrome.muted,+ ),+ ],+ ),+ ),+ ),),),- TextButton(+ AppIconButton(key: const ValueKey('super-chat'),- style: TextButton.styleFrom(- foregroundColor: !_terminalsVisible && !_showPullRequests- ? DesktopChrome.accent- : DesktopChrome.muted,- ),+ icon: AppIcons.messageSquareText,+ size: 20,+ tooltip: 'Chat',+ selected: !_terminalsVisible && !_showPullRequests,+ color: !_terminalsVisible && !_showPullRequests+ ? DesktopChrome.accent+ : DesktopChrome.muted,onPressed: () {setState(() => _showPullRequests = false);widget.onCloseTerminal?.call();@@ -593,11 +659,14 @@ class _SuperTabViewState extends State<SuperTabView> {if (mounted) _focus.requestFocus();});},- child: const Text('Chat'),),+ const SizedBox(width: 4),AppIconButton(+ key: const ValueKey('super-terminals'),icon: AppIcons.terminal,+ size: 20,tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',+ selected: _terminalsVisible,color: _terminalsVisible ? DesktopChrome.accent : DesktopChrome.muted,onPressed: group?.agentIds.isNotEmpty == true? () {@@ -606,54 +675,28 @@ class _SuperTabViewState extends State<SuperTabView> {}: null,),- TextButton(- style: TextButton.styleFrom(- foregroundColor: _showPullRequests- ? DesktopChrome.accent- : DesktopChrome.muted,- ),+ const SizedBox(width: 4),+ AppIconButton(+ key: const ValueKey('super-pull-requests'),+ icon: AppIcons.gitPullRequest,+ size: 20,+ tooltip: 'Pull requests',+ selected: !_terminalsVisible && _showPullRequests,+ color: !_terminalsVisible && _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',+ selected: _rosterOpen,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 (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',- ),- ),- ],- ],- ),],),);@@ -778,6 +821,15 @@ class _SuperTabViewState extends State<SuperTabView> {author: message.authorId == c.accountId && !message.fromAgent? 'You': _authorName(message),+ references: {+ for (final g in c.snapshot?.conversations ?? <SuperTabConversation>[])+ if (g.number != null) g.number!: g.id,+ },+ onOpenGroup: (id) {+ setState(() => _showPullRequests = false);+ c.select(id);+ c.selectTerminal(id, null);+ },agent: agent,onOpenAgent: agent == null ? null : () => _openAgent(agent),machineName: agent == null ? null : widget.machineName(agent.machineId),@@ -907,46 +959,48 @@ class _SuperTabViewState extends State<SuperTabView> {}return false;},- child: ListView.builder(- controller: _scroll[c.selectedId],- key: PageStorageKey(- 'super-messages-${c.tabId}-${c.selectedId}',+ child: SelectionArea(+ child: ListView.builder(+ controller: _scroll[c.selectedId],+ key: PageStorageKey(+ 'super-messages-${c.tabId}-${c.selectedId}',+ ),+ padding: const EdgeInsets.symmetric(vertical: 8),+ itemCount: messages.length + 1,+ itemBuilder: (context, index) {+ if (index == 0) {+ return c.hasOlder(c.selectedId)+ ? Align(+ child: TextButton(+ onPressed: () => unawaited(_earlier()),+ child: const Text('Earlier messages'),+ ),+ )+ : const SizedBox.shrink();+ }+ final message = messages[index - 1];+ final previous = index > 1+ ? messages[index - 2]+ : null;+ final time = message.createdAt;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (time != null &&+ !DateUtils.isSameDay(+ time.toLocal(),+ previous?.createdAt?.toLocal(),+ ))+ _date(time),+ _message(+ message,+ grouped.contains(message.id),+ byId,+ ),+ ],+ );+ },),- padding: const EdgeInsets.symmetric(vertical: 8),- itemCount: messages.length + 1,- itemBuilder: (context, index) {- if (index == 0) {- return c.hasOlder(c.selectedId)- ? Align(- child: TextButton(- onPressed: () => unawaited(_earlier()),- child: const Text('Earlier messages'),- ),- )- : const SizedBox.shrink();- }- final message = messages[index - 1];- final previous = index > 1- ? messages[index - 2]- : null;- final time = message.createdAt;- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (time != null &&- !DateUtils.isSameDay(- time.toLocal(),- previous?.createdAt?.toLocal(),- ))- _date(time),- _message(- message,- grouped.contains(message.id),- byId,- ),- ],- );- },),),if (newCount > 0)diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex 9fd2974cd..0da5a5abd 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -41,6 +41,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {(String, String)? _resumeRequest;Future<void> _terminalChange = Future.value();final _nativePanes = <TerminalPane>[];+ final _failures = <(String, String?), String>{};final _nativeHeartbeats = <Timer>[];void _clearNativeContext() {@@ -52,14 +53,14 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {_nativePanes.clear();_readyRequest = null;for (final pane in panes) {- if (pane.inputContext == null && !pane.watchOnly) continue;+ if (pane.inputContext == null && pane.watchOnly) continue;pane.inputContext = null;- pane.watchOnly = false;+ pane.watchOnly = true;final session = pane.session;- session?.stageInputContext(null);+ session?.stageInputContext(null, watchOnly: true);WidgetsBinding.instance.addPostFrameCallback((_) {- if (pane.inputContext == null && !pane.watchOnly) {- unawaited(session?.setInputContext(null));+ if (pane.inputContext == null && pane.watchOnly) {+ unawaited(session?.setInputContext(null, watchOnly: true));}});}@@ -76,12 +77,23 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {final request = (swarmId,controller.selectedId,- agents.isEmpty ? null : agents.map((a) => a.id).join(','),+ agents.isEmpty+ ? null+ : agents+ .map((a) {+ final machine = app.stateOf(a.machineId);+ final native = machine?.agents+ .where((n) => n.id == a.harnessId)+ .firstOrNull;+ return '${a.id}:${native?.isStopped}:${machine?.connectionStatus}:${native != null}';+ })+ .join(','),controller.accountId,controller.canWrite,);if (_terminalRequest == request) return;_clearNativeContext();+ _failures.clear();_terminalRequest = request;final resume = _resumeRequest;_resumeRequest = null;@@ -120,8 +132,18 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}if (current()) {if (tab != null) tab.zoomedPaneId = null;- if (agents.length == 1) {- if (tab?.panes.firstOrNull case final pane?) {+ final focused = agents.where((a) => a.id == resume?.$2).firstOrNull;+ if (focused != null || agents.length == 1) {+ if ((focused == null+ ? tab?.panes.firstOrNull+ : tab?.panes+ .where(+ (p) =>+ p.machineId == focused.machineId &&+ p.agentId == focused.harnessId,+ )+ .firstOrNull)+ case final pane?) {app.focusPane(pane.id);pane.session?.focusInput();}@@ -164,18 +186,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {.where((a) => a.id == agent.harnessId).firstOrNull?.isStopped;- if (stopped == true) {- if (!resume) {- controller.hideTerminal(- conversationId,- agent.machineId,- agent.harnessId,- );- return;- }- // Older idle cleanup may already have stopped a contributed harness.- // Open its saved conversation through the existing resume receipt- // before issuing a native context, so a failed resume leaves none.+ if (stopped == true && resume) {final resumeError = await app.resumeStoppedSession(agent.machineId,agent.harnessId,@@ -185,35 +196,37 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {throw SuperTabFailure('TERMINAL_UNAVAILABLE', resumeError);}}- final issued = await controller.request(- 'POST',- '/api/super-tabs/${controller.tabId}/native',- body: {- 'operationId': superTabOperationId(),- 'conversationId': conversationId,- 'agentId': agent.id,- },- );- if (!current()) return;- inputContext = issued['contextId'] as String?;- if (inputContext == null ||- !RegExp(r'^[A-Za-z0-9_-]{16,160}$').hasMatch(inputContext)) {- throw const SuperTabFailure(- 'NATIVE_UNAVAILABLE',- 'Could not prepare terminal sharing. Try opening it again.',- );- }- final prepared = await app.superTabMachineRequest(agent.machineId, {- 'action': 'prepareNative',- 'tabId': controller.tabId,- 'contextId': inputContext,- });- if (!current()) return;- if (prepared['inputContext'] != inputContext) {- throw const SuperTabFailure(- 'NATIVE_UNAVAILABLE',- 'This machine could not confirm terminal sharing.',+ if (stopped != true || resume) {+ final issued = await controller.request(+ 'POST',+ '/api/super-tabs/${controller.tabId}/native',+ body: {+ 'operationId': superTabOperationId(),+ 'conversationId': conversationId,+ 'agentId': agent.id,+ },);+ if (!current()) return;+ inputContext = issued['contextId'] as String?;+ if (inputContext == null ||+ !RegExp(r'^[A-Za-z0-9_-]{16,160}$').hasMatch(inputContext)) {+ throw const SuperTabFailure(+ 'NATIVE_UNAVAILABLE',+ 'Could not prepare terminal sharing. Try opening it again.',+ );+ }+ final prepared = await app.superTabMachineRequest(agent.machineId, {+ 'action': 'prepareNative',+ 'tabId': controller.tabId,+ 'contextId': inputContext,+ });+ if (!current()) return;+ if (prepared['inputContext'] != inputContext) {+ throw const SuperTabFailure(+ 'NATIVE_UNAVAILABLE',+ 'This machine could not confirm terminal sharing.',+ );+ }}}await app.assignAgentToPane(@@ -256,14 +269,24 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {});} catch (failure) {if (mounted && current()) {- controller.hideTerminal(- conversationId,- agent.machineId,- agent.harnessId,- );- ScaffoldMessenger.of(context).showSnackBar(- SnackBar(content: Text('Terminal sharing paused. $failure')),- );+ _failures[(agent.machineId, agent.harnessId)] =+ 'Terminal sharing paused. $failure';+ final pane = tab.panes+ .where(+ (p) =>+ p.machineId == agent.machineId &&+ p.agentId == agent.harnessId,+ )+ .firstOrNull;+ pane?.session?.stageInputContext(null, watchOnly: true);+ if (pane != null) {+ pane.inputContext = null;+ pane.watchOnly = true;+ unawaited(+ pane.session?.setInputContext(null, watchOnly: true),+ );+ }+ setState(() {});}timer.cancel();} finally {@@ -274,13 +297,9 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}} catch (failure) {if (mounted && current()) {- controller.hideTerminal(- conversationId,- agent.machineId,- agent.harnessId,- );- ScaffoldMessenger.of(context)- .showSnackBar(SnackBar(content: Text(failure.toString())));+ _failures[(agent.machineId, agent.harnessId)] = failure.toString();+ app.reserveSuperTabPane(swarmId, agent.machineId, agent.harnessId);+ setState(() {});}}}@@ -325,14 +344,20 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {final lead = controller.snapshot?.agents.where((a) => controller.snapshot!.isLead(a.id)).firstOrNull;- final terminal = lead == null- ? canvas- : SuperPane(- machineId: lead.machineId,- harnessId: lead.harnessId,- title: 'Lead',- child: canvas,- );+ final terminal = SuperPane(+ machineId: lead?.machineId ?? '',+ harnessId: lead?.harnessId ?? '',+ title: 'Lead',+ titles: {+ for (final a in agents)+ (a.machineId, a.harnessId): controller.snapshot!.agentName(+ a.id,+ ),+ },+ failures: Map.of(_failures),+ onRetry: () => setState(() => _terminalRequest = null),+ child: canvas,+ );return Stack(fit: StackFit.expand,children: [diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex 5e7593023..a2e85a857 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1,3 +1,4 @@+import '../super_tabs/pane.dart';import '../sharing/shared_harness_panel.dart';import 'dart:async';@@ -1547,13 +1548,27 @@ class _PaneContent extends StatelessWidget {TerminalFontScope.watch(context);final machine = notifier.stateOf(pane.machineId);final swarmId = notifier.activeSwarmId;- void close() {+ void closeView() {// A tab switch can precede the frame that replaces this callback. Shared// panes keep their identity, so the pane id alone cannot identify its tab.if (notifier.activeSwarmId != swarmId) return;unawaited(notifier.requestClosePane(pane.id));}+ final superPane = SuperPane.maybeOf(context);+ final VoidCallback? close = superPane == null ? closeView : null;+ final failure = superPane?.failures[(pane.machineId, pane.agentId)];+ if (failure != null) {+ return _PaneStatus(+ title:+ superPane?.titleFor(pane.machineId, pane.agentId ?? '') ?? 'Agent',+ icon: AppIcons.terminal,+ message: failure,+ actionLabel: 'Retry',+ onAction: superPane?.onRetry,+ );+ }+VoidCallback? split(PaneResizeAxis axis) =>swarmMode &&onSplitPane != null &&@@ -1600,7 +1615,10 @@ class _PaneContent extends StatelessWidget {onClose: close,compactHeader: swarmMode,zoomed: notifier.zoomedPaneId == pane.id,- onToggleZoom: swarmMode && (!single || notifier.zoomedPaneId == pane.id)+ onToggleZoom:+ superPane == null &&+ swarmMode &&+ (!single || notifier.zoomedPaneId == pane.id)? () {notifier.focusPane(pane.id);notifier.toggleZoomPane();@@ -1798,8 +1816,13 @@ class _PaneContent extends StatelessWidget {notice = null;}// Joining a shared tab: dimmed until the tab's owner's computer answers.- final joining = wantedAgentId != null &&- sharedPaneChipState(notifier, pane.machineId, wantedAgentId).joining !=+ final joining =+ wantedAgentId != null &&+ sharedPaneChipState(+ notifier,+ pane.machineId,+ wantedAgentId,+ ).joining !=null;final panel = LayoutBuilder(builder: (context, constraints) => TerminalPanel(@@ -1858,7 +1881,9 @@ class _PaneContent extends StatelessWidget {),zoomed: notifier.zoomedPaneId == pane.id,onToggleZoom:- swarmMode && (!single || notifier.zoomedPaneId == pane.id)+ superPane == null &&+ swarmMode &&+ (!single || notifier.zoomedPaneId == pane.id)? () {notifier.focusPane(pane.id);notifier.toggleZoomPane();@@ -2416,7 +2441,7 @@ class _Guide extends StatelessWidget {});final bool single;- final VoidCallback onClose;+ final VoidCallback? onClose;final String title;final Widget? activity;final String compactMessage;diff --git a/desktop/pubspec.lock b/desktop/pubspec.lockindex e28d00089..9ddc06b0c 100644--- a/desktop/pubspec.lock+++ b/desktop/pubspec.lock@@ -376,7 +376,7 @@ packages:source: hostedversion: "3.1.20"markdown:- dependency: transitive+ dependency: "direct main"description:name: markdownsha256: ee85086ad7698b42522c6ad42fe195f1b9898e4d974a1af4576c1a3a176cada9diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yamlindex e9d909534..9262fb199 100644--- a/desktop/pubspec.yaml+++ b/desktop/pubspec.yaml@@ -45,6 +45,7 @@ dependencies:# Selectable agent messages, code and tables. Pure Flutter/Dart; no native# plugin. Super Tab disables automatic images and permits only web links.flutter_markdown_plus: ^1.0.12+ markdown: ^7.3.1dio: ^5.11.0web_socket_channel: ^3.0.3flutter_riverpod: ^2.6.1diff --git a/desktop/test/session_close_test.dart b/desktop/test/session_close_test.dartindex a8ae48a1b..e774b1134 100644--- a/desktop/test/session_close_test.dart+++ b/desktop/test/session_close_test.dart@@ -101,7 +101,7 @@ void main() {for (final wholeTab in [false, true]) {test(- 'closing a Super Tab ${wholeTab ? 'tab' : 'pane'} hides working agents without a stop review',+ 'Super Tab ${wholeTab ? 'tab close hides' : 'pane close preserves'} working agents without a stop review',() async {final tab = app.activeSwarm;app.bindSuperTab(tab.id, 'shared-tab', 'Pilot');@@ -118,7 +118,7 @@ void main() {} else {await app.requestClosePane(pane.id);expect(app.swarms, contains(tab));- expect(tab.panes, isEmpty);+ expect(tab.panes, [pane]);}expect(reviews, 0);expect(connection.closes, isEmpty);diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex faa4ceff6..17b892203 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -1,4 +1,5 @@import 'package:flutter/material.dart';+import 'package:flutter/gestures.dart';import 'package:flutter/services.dart';import 'package:flutter_markdown_plus/flutter_markdown_plus.dart';import 'package:flutter_test/flutter_test.dart';@@ -275,6 +276,43 @@ void main() {},);+ testWidgets(+ 'messages wrap code without nested scrolling and link only known workgroups outside code',+ (tester) async {+ final opened = <String>[];+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SelectionArea(+ child: SizedBox(+ width: 260,+ child: SuperTabMessageText(+ 'See #12 and #99.\n\n`#12`\n\n```txt\n#12 long_code_that_must_wrap_without_a_second_scrollbar_abcdefghijklmnopqrstuvwxyz\n```',+ references: const {12: 'work-id'},+ onOpenGroup: opened.add,+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(find.byType(Scrollable), findsNothing);+ final links = <TextSpan>[];+ for (final text in tester.widgetList<RichText>(find.byType(RichText))) {+ text.text.visitChildren((span) {+ if (span is TextSpan && span.recognizer is TapGestureRecognizer)+ links.add(span);+ return true;+ });+ }+ expect(links.map((s) => s.text), ['#12']);+ (links.single.recognizer as TapGestureRecognizer).onTap!();+ expect(opened, ['work-id']);+ expect(tester.takeException(), isNull);+ },+ );+test('message links permit only explicit http and https destinations', () {for (final href in [null,diff --git a/desktop/test/super_tab_controller_test.dart b/desktop/test/super_tab_controller_test.dartindex caa1ea4d1..7c18a8a67 100644--- a/desktop/test/super_tab_controller_test.dart+++ b/desktop/test/super_tab_controller_test.dart@@ -6,40 +6,43 @@ 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(+ 'group terminals keep every member when selecting one and after reopening',+ () 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.selectTerminal('offline', 'b');+ expect(c.terminalAgents('offline').map((a) => a.id), ['a', 'b']);+ await c.flush();+ c.dispose();+ final restored = server.controller(initial: server.saved);+ await restored.refresh();+ expect(restored.terminalAgents('offline').map((a) => a.id), ['a', '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_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex 4a41e57a0..bd1dab541 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -123,6 +123,9 @@ class SuperTabFixtureConnection extends WsConn {}if (type == 'super_tabs') {if (payload['action'] == 'wake') return {'ok': true};+ if (payload['action'] == 'prepareContribution') {+ return {'ok': true, 'state': 'ready', 'cwd': '/work/project', 'engines': ['claude', 'codex', 'pi'], 'maxAgents': 4};+ }if (payload['action'] == 'prepareNative' ||payload['action'] == 'renewNative') {if (native?['status'] == 'stopped') {diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartnew file mode 100644index 000000000..aba50ee30--- /dev/null+++ b/desktop/test/super_tab_machines_test.dart@@ -0,0 +1,81 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/machines.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/shared/widgets/app_select_field.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;++void main() {+ test('shared repository metadata excludes embedded credentials', () {+ expect(+ superTabRepositoryUrl('https://[email protected]/example/project'),+ isNull,+ );+ expect(+ superTabRepositoryUrl('ssh://git:[email protected]/example/project'),+ isNull,+ );+ expect(+ superTabRepositoryUrl('[email protected]:example/project.git'),+ '[email protected]:example/project.git',+ );+ expect(+ superTabRepositoryUrl('https://github.com/example/project'),+ 'https://github.com/example/project',+ );+ });+ testWidgets(+ 'Add machine has one field and contributes the prepared project and installed engines',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.server.state['project'] = {+ 'machineId': 'm',+ 'cwd': '/work/project',+ 'repositoryUrl': null,+ };+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SizedBox(+ width: 300,+ height: 400,+ child: SuperTabMachines(+ controller: c,+ app: f.app,+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Add machine'));+ await tester.pumpAndSettle();+ expect(find.byType(AppSelectField<String>), findsOneWidget);+ expect(find.text('This Mac'), findsOneWidget);+ expect(find.byType(Checkbox), findsNothing);+ expect(find.text('Choose project folder'), findsNothing);+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));+ await tester.pumpAndSettle();+ expect(find.byType(AlertDialog), findsNothing);+ expect(f.connection.server.posts.single['command'], {+ 'type': 'machine.contribute',+ 'machineId': 'm',+ 'name': f.app.stateOf('m')!.machine.displayName,+ 'cwd': '/work/project',+ 'engines': ['claude', 'codex', 'pi'],+ 'maxAgents': 4,+ });+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );+}diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex b99bed81a..7208b8cc1 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -5,6 +5,7 @@ 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 'package:harness/shared/widgets/app_icon_button.dart';import 'support/super_tab_fixture.dart';@@ -80,7 +81,7 @@ void main() {);await tester.pumpAndSettle();expect(find.byKey(const ValueKey('super-group-offline')), findsNothing);- await tester.tap(find.byTooltip('Conversation options'));+ await tester.tap(find.byTooltip('Workgroup options'));await tester.pumpAndSettle();await tester.tap(find.text('Archived conversations'));await tester.pumpAndSettle();@@ -102,7 +103,7 @@ void main() {.enabled,isFalse,);- await tester.tap(find.byTooltip('Conversation options'));+ await tester.tap(find.byTooltip('Workgroup options'));await tester.pumpAndSettle();await tester.tap(find.text('Reopen conversation'));await tester.pumpAndSettle();@@ -278,7 +279,7 @@ void main() {);await tester.pumpAndSettle();if (rename) {- await tester.tap(find.byTooltip('Conversation options'));+ await tester.tap(find.byTooltip('Workgroup options'));await tester.pumpAndSettle();await tester.tap(find.text('Rename'));} else {@@ -354,7 +355,7 @@ void main() {),);await tester.pumpAndSettle();- expect(find.text('Humans · 20'), findsOneWidget);+ expect(find.text('Humans'), findsOneWidget);final member = find.byKey(const ValueKey('super-member-agent-0'));await tester.scrollUntilVisible(member,@@ -407,10 +408,33 @@ void main() {expect(find.text('Review this result.'), findsNothing);expect(find.byKey(const ValueKey('super-group-lead')), findsOneWidget);expect(find.byType(SuperTabRoster), findsOneWidget);+ expect(+ tester+ .widget<AppIconButton>(+ find.byKey(const ValueKey('super-terminals')),+ )+ .selected,+ isTrue,+ );+ expect(+ tester+ .widget<AppIconButton>(find.byKey(const ValueKey('super-chat')))+ .selected,+ isFalse,+ );+ expect(+ tester+ .widget<AppIconButton>(+ find.byKey(const ValueKey('super-pull-requests')),+ )+ .selected,+ isFalse,+ );+ expect(find.byTooltip('Conversation options'), findsNothing);await tester.binding.setSurfaceSize(const Size(800, 700));await tester.pumpAndSettle();expect(find.text('Native terminal fixture'), findsOneWidget);- await tester.tap(find.text('Chat'));+ await tester.tap(find.byTooltip('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 320fa3038..e8a863671 100644--- a/desktop/test/super_tab_workspace_test.dart+++ b/desktop/test/super_tab_workspace_test.dart@@ -2,19 +2,20 @@ import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/super_tabs/view.dart';+import 'package:harness/super_tabs/pane.dart';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',+ 'group terminals keep all members when opening one and ignore pane close',(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'])+ for (final id in ['a', 'b', 'c', 'd']){'id': id,'name': id,@@ -24,14 +25,17 @@ void main() {'configuration': {'engine': 'codex'},},];- (state['conversations'] as List)[1]['agentIds'] = ['a', 'b'];+ (state['conversations'] as List)[1]['agentIds'] = ['a', 'b', 'c', 'd'];f.app.machineStates['m']!.agents = [- for (final id in ['a', 'b'])+ for (final id in ['a', 'b', 'c', 'd'])Agent.fromJson({'id': 'native-$id','name': id,'engine': 'codex',- 'terminal': {'available': true},+ 'status': ['c', 'd'].contains(id) ? 'stopped' : 'working',+ 'terminal': {+ 'available': !['c', 'd'].contains(id),+ },}),];final c = await f.app.superTabs.open(tabId);@@ -70,7 +74,10 @@ void main() {await tester.pumpAndSettle();await tester.tap(find.text('b needs you').first);await tester.pumpAndSettle();- expect(f.app.activeSwarm.panes.single.agentId, 'native-b');+ expect(+ f.app.activeSwarm.panes.map((p) => p.agentId),+ unorderedEquals(['native-a', 'native-b', 'native-c', 'native-d']),+ );await f.app.handleMachineEventForTest('m', {'type': 'commander_question_close','agentId': 'native-b',@@ -84,14 +91,23 @@ void main() {await tester.pumpAndSettle();expect(f.app.activeSwarm.panes.map((p) => p.agentId),- unorderedEquals(['native-a', 'native-b']),+ unorderedEquals(['native-a', 'native-b', 'native-c', 'native-d']),);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.app.activeSwarm.panes.map((p) => p.agentId),+ unorderedEquals(['native-a', 'native-b', 'native-c', 'native-d']),+ );+ expect(c.terminalAgents('offline').map((a) => a.id), [+ 'a',+ 'b',+ 'c',+ 'd',+ ]);+ expect(f.connection.calls.where((c) => c.$1 == 'agent_resume'), isEmpty);expect(f.connection.calls.where((c) => c.$1 == 'agent_close' || c.$1 == 'agent_create',@@ -169,8 +185,8 @@ void main() {c.selectTerminal('offline', 'worker');await tester.pumpAndSettle();expect(calls.where((call) => call.$1 == 'agent_resume'), isEmpty);- expect(c.terminalAgent('offline'), isNull);- expect(f.app.activeSwarm.panes, isEmpty);+ expect(c.terminalAgent('offline')?.id, 'worker');+ expect(f.app.activeSwarm.panes.single.agentId, 'native-worker');}await openTerminal();expect(calls.where((call) => call.$1 == 'agent_create'), isEmpty);@@ -179,7 +195,7 @@ void main() {hasLength(scenario.viewer ? 0 : 1),);if (scenario.fail) {- expect(c.terminalAgent('offline'), isNull);+ expect(c.terminalAgent('offline')?.id, 'worker');expect(calls.where((call) => call.$2['action'] == 'prepareNative'),isEmpty,@@ -191,7 +207,7 @@ void main() {),isEmpty,);- expect(find.textContaining('did not come back'), findsOneWidget);+ expect(f.app.activeSwarm.panes.single.watchOnly, isTrue);} else {expect(f.app.activeSwarm.panes.single.agentId, 'native-worker');expect(@@ -300,13 +316,13 @@ void main() {await c.refresh();await tester.pumpAndSettle();expect(f.app.activeSwarm.panes.single.watchOnly, isFalse);- // Native pane Close and the narrow Back action have the same personal state.+ // Individual pane close is disabled; membership owns the pane list.await f.app.requestClosePane(f.app.activeSwarm.panes.single.id);await tester.pumpAndSettle();await c.refresh();await tester.pumpAndSettle();- expect(c.terminalAgent('lead'), isNull);- expect(f.app.activeSwarm.panes, isEmpty);+ expect(c.terminalAgent('lead')?.id, 'a');+ expect(f.app.activeSwarm.panes.single.agentId, 'native-a');final scopes = f.connection.calls.where((call) => (call.$2['path'] as String?)?.endsWith('/native') == true,@@ -380,9 +396,18 @@ void main() {f.connection.failNative = true;await tester.pump(const Duration(seconds: 21));await tester.pumpAndSettle();- expect(c.terminalAgent('lead'), isNull);- expect(f.app.activeSwarm.panes, isEmpty);- expect(find.textContaining('Terminal sharing paused'), findsOneWidget);+ expect(c.terminalAgent('lead')?.id, 'a');+ expect(f.app.activeSwarm.panes.single.agentId, 'native-a');+ expect(+ tester.widget<SuperPane>(find.byType(SuperPane)).failures[(+ 'm',+ 'native-a',+ )],+ contains('Terminal sharing paused'),+ );+ expect(f.app.activeSwarm.panes.single.watchOnly, isTrue);+ await tester.tap(find.byTooltip('Chat'));+ await tester.pumpAndSettle();expect(find.byKey(const ValueKey('super-message-composer')),findsOneWidget,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.mdindex 35b2fcce2..6e07f75bc 100644--- 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.md@@ -1,5 +1,23 @@# Super Tab review build — 19 October 2026+## Review polish++The next internal build keeps the approved layout and removes extra controls:++- Chat, terminals and PRs use icon buttons with an explicit selected state. Click the workgroup title for details, rename or archive.+- Workgroups have stable tab-local numbers (`#1`, `#2`, …), shown in navigation and linked in messages. Renaming or archiving a group preserves its number. Lead stays unnumbered.+- The terminal view shows every group member, including stopped or unavailable agents. Clicking a member focuses it within the group. Individual close and zoom controls are absent; changing to Chat does not stop a harness.+- Messages share the conversation's scroll area. Code wraps; paragraphs do not create their own scrolling surfaces.+- The global footer is hidden inside Super Tab. Roster headings are simply Leads, Humans, Agents and Machines. Humans, Agents and Machines each have a `+` for their own action.+- Machine cards use three left-aligned lines: name, owner and active agent count; available CPU/GPU and free RAM/SSD; engine icons and remaining allowance. Details and reset information remain behind the machine/allowance hover or detail view. Unknown readings remain `—`.+- **Add machine** asks only which owned machine to use. Harness reuses the lead's local project or prepares its GitHub repository on another machine, discovers installed engines (including Pi when installed), and sets a resource-based concurrency ceiling. Actual starts still pass capacity admission. It does not install or sign in to engines automatically.++Machine setup uses a polled operation receipt so a slow clone does not block other daemon requests or repeat after a timeout. No agent starts until the owner submits the contribution. Project URLs with embedded credentials are excluded. A project without a clonable repository can be contributed on its existing machine; another machine needs a shared repository first.++Validation for this update includes scoped TypeScript checks, Super Tab unit/widget tests, disposable backend replica-set integration, a two-account machine preparation/execution test using isolated daemon homes, and a native macOS fixture with screenshots of chat, the one-field machine form and four group panes. CI and the official signed internal build identify the final source revision in the PR. The delivery record below describes the preceding build until that next package is installed.++## Preceding installed build+The review build is installed and running on this Mac at:`/Users/ab/Applications/Harness SuperTab Oct19.app`