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
Fix Swarm creation and streamline collaboration controls (#1469)
Dee572b9851c71f
diff --git a/backend/integration/superTabSharing.test.ts b/backend/integration/superTabSharing.test.tsnew file mode 100644index 000000000..2859921b8--- /dev/null+++ b/backend/integration/superTabSharing.test.ts@@ -0,0 +1,188 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import Fastify, { type FastifyInstance } from 'fastify'+import { PrismaClient } from '@prisma/client'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { superTabRoutes } from '../src/routes/superTabs.js'+import { errorHandler } from '../src/middlewares/errorHandler.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import type { GeneralAccess } from '../src/superTabs/sharing.js'++let replica: MongoMemoryReplSet, db: PrismaClient, store: SuperTabStore, app: FastifyInstance+const owner: AuthUser = { sub: '200000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const peer: AuthUser = { sub: '200000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const outsider: AuthUser = { sub: '200000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const subdomain: AuthUser = { sub: '200000000000000000000004', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const accounts = [owner, peer, outsider, subdomain]+const request = (tab: string, path: string, body?: object, user: AuthUser | null = owner, method?: 'GET' | 'POST') =>+ app.inject({ method: method ?? (body ? 'POST' : 'GET'), url: `/api/super-tabs/${tab}/${path}`,+ headers: user ? { authorization: `Bearer ${user.sub}` } : {}, ...(body ? { payload: body } : {}) })+const save = async (tab: string, access: GeneralAccess, rotateLink = false) => {+ const current = await store.sharing(owner, tab)+ return store.saveSharing(owner, tab, { operationId: randomUUID(), revision: current.revision, access, rotateLink })+}+const tokenOf = (details: { joinUrl: string | null }) => new URL(details.joinUrl!).searchParams.get('token')!+const create = async () => (await store.create(owner, randomUUID(), 'Fixture Swarm')).id++beforeAll(async () => {+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })+ const uri = replica.getUri(`swarm_sharing_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ store = new SuperTabStore(db)+ for (const user of accounts) await db.user.create({ data: { id: user.sub, externalId: `sharing-fixture-${user.sub}`,+ email: user.email, autonomousEnv: user.autonomousEnv } })+ app = Fastify()+ app.setErrorHandler(errorHandler)+ // Only SSO is replaced. All routes, authorization, receipts, and Mongo transactions are real.+ app.addHook('onRequest', async (req, reply) => {+ const account = accounts.find(user => `Bearer ${user.sub}` === req.headers.authorization)+ if (!account) return reply.code(401).send({ success: false })+ req.user = account+ })+ await app.register(superTabRoutes, { store })+ await app.ready()+})+afterAll(async () => { await app?.close(); await db?.$disconnect(); await replica?.stop() })++describe('Swarm sharing on the authenticated control API', () => {+ it('stays invite-only by default, requires the owner, and never joins on a read', async () => {+ const tab = await create()+ expect((await request(tab, 'sharing')).json().data).toEqual({ revision: 0,+ access: { mode: 'invited', role: 'collaborator' }, joinUrl: null })+ expect((await request(tab, 'sharing', undefined, null)).statusCode).toBe(401)+ expect((await request(tab, 'sharing', undefined, peer)).statusCode).toBe(403)+ const body = { operationId: randomUUID(), revision: 0, access: { mode: 'link', role: 'collaborator' } }+ expect((await request(tab, 'sharing', body, peer)).statusCode).toBe(403)+ expect((await request(tab, 'sharing', { ...body, access: { mode: 'link', role: 'owner' } })).statusCode).toBe(400)+ expect((await request(tab, 'join/preview', {}, peer)).statusCode).toBe(404)+ expect((await request(tab, 'join', { operationId: randomUUID() }, peer)).statusCode).toBe(404)+ expect((await request(tab, 'join', undefined, peer)).statusCode).toBe(404)+ expect((await store.list(peer)).tabs).toEqual([])+ expect((await store.read(owner, tab)).state.people).toHaveLength(1)+ })++ it('previews and explicitly joins matching domains without exposing a private project', async () => {+ const tab = await create()+ const project = await store.execute(owner, tab, { operationId: randomUUID(),+ command: { type: 'project.create', name: 'Hidden initiative', visibility: 'private', brief: 'Private brief' } })+ const sharing = await request(tab, 'sharing', { operationId: randomUUID(), revision: 0,+ access: { mode: 'domain', domain: ' EXAMPLE.com ', role: 'viewer' } })+ expect(sharing.statusCode).toBe(200)+ expect(sharing.json().data.access.domain).toBe('example.com')+ expect(sharing.json().data.joinUrl).toBe(`harness://swarm/join/${tab}`)+ const before = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ const preview = await request(tab, 'join/preview', {}, peer)+ expect(preview.json().data).toEqual({ id: tab, name: 'Fixture Swarm', role: 'viewer', alreadyMember: false })+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).revision).toBe(before.revision)+ expect((await request(tab, 'join/preview', {}, outsider)).statusCode).toBe(404)+ expect((await request(tab, 'join/preview', {}, subdomain)).statusCode).toBe(404)+ expect((await request(tab, 'join', { operationId: randomUUID(), email: peer.email }, outsider)).statusCode).toBe(400)+ const join = { operationId: randomUUID() }+ const result = await request(tab, 'join', join, peer)+ expect(result.statusCode).toBe(200)+ expect(result.json().data).toMatchObject({ id: tab, role: 'viewer', alreadyMember: false })+ expect((await request(tab, 'join', join, peer)).json().data).toEqual(result.json().data)+ const snapshot = await store.read(peer, tab)+ expect(snapshot.state.projects!.map(p => p.id)).not.toContain(project.result.projectId)+ expect(snapshot.state.sharing).toBeUndefined()+ expect((await request(tab, 'sharing', undefined, peer)).statusCode).toBe(403)+ await expect(store.messages(peer, tab, String(project.result.conversationId), {})).rejects.toMatchObject({ code: 'NOT_FOUND' })+ expect((await store.list(peer)).tabs.map(t => t.id)).toContain(tab)+ await save(tab, { mode: 'invited', role: 'collaborator' })+ expect((await request(tab, 'join', join, peer)).statusCode).toBe(404)+ expect((await store.read(peer, tab)).state.people.find(p => p.id === peer.sub)?.role).toBe('viewer')+ })++ it('rotates and revokes links, encrypts tokens at rest, and never promotes existing members', async () => {+ const tab = await create()+ const invitation = await store.execute(owner, tab, { operationId: randomUUID(),+ command: { type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' } })+ await store.execute(peer, tab, { operationId: randomUUID(), command: { type: 'invite.accept', inviteId: String(invitation.result.inviteId) } })+ const createLink = { operationId: randomUUID(), revision: 0, access: { mode: 'link' as const, role: 'collaborator' as const } }+ const first = await store.saveSharing(owner, tab, createLink), token = tokenOf(first)+ expect(await store.saveSharing(owner, tab, createLink)).toEqual(first)+ expect((await request(tab, 'join/preview', { token }, null)).statusCode).toBe(401)+ expect((await request(tab, 'join/preview', { token })).json().data.role).toBe('owner')+ expect((await request(tab, 'join/preview', { token }, peer)).json().data.role).toBe('viewer')+ expect((await request(tab, 'join', { operationId: randomUUID(), token }, peer)).json().data).toMatchObject({ role: 'viewer', alreadyMember: true })+ const join = { operationId: randomUUID(), token }+ expect((await request(tab, 'join', join, outsider)).json().data.role).toBe('collaborator')+ const stored = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ expect(JSON.stringify(stored)).not.toContain(token)+ expect(JSON.stringify(await db.superTabOperation.findMany({ where: { tabId: tab } }))).not.toContain(token)+ expect((await store.read(owner, tab)).state.sharing).toBeUndefined()+ await store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'tab.rename', name: 'Renamed Swarm' } })+ expect(tokenOf(await store.sharing(owner, tab))).toBe(token)+ const replaced = await save(tab, { mode: 'link', role: 'viewer' }, true)+ expect(tokenOf(replaced)).not.toBe(token)+ expect((await request(tab, 'join/preview', { token }, outsider)).statusCode).toBe(404)+ expect((await request(tab, 'join', join, outsider)).statusCode).toBe(404)+ await expect(store.saveSharing(owner, tab, createLink)).rejects.toMatchObject({ code: 'SHARING_CHANGED' })+ expect((await store.read(outsider, tab)).state.people.find(p => p.id === outsider.sub)?.role).toBe('collaborator')+ await save(tab, { mode: 'invited', role: 'viewer' })+ expect((await request(tab, 'join/preview', { token: tokenOf(replaced) }, outsider)).statusCode).toBe(404)+ })++ it('fences old domain receipts after disabling/re-enabling access and after a member leaves', async () => {+ const tab = await create()+ const access = { mode: 'domain' as const, domain: 'example.com', role: 'collaborator' as const }+ await save(tab, access)+ const join = { operationId: randomUUID() }+ await store.join(peer, tab, join)+ await save(tab, { mode: 'invited', role: 'collaborator' })+ await save(tab, access)+ await expect(store.join(peer, tab, join)).rejects.toMatchObject({ code: 'JOIN_CHANGED' })+ const latest = { operationId: randomUUID() }+ await store.join(peer, tab, latest)+ await store.execute(peer, tab, { operationId: randomUUID(), command: { type: 'member.remove', userId: peer.sub } })+ await expect(store.join(peer, tab, latest)).rejects.toMatchObject({ code: 'JOIN_CHANGED' })+ expect((await store.read(owner, tab)).state.people.some(p => p.id === peer.sub)).toBe(false)+ // A newly confirmed join receives a new membership generation, not any old private grants.+ const rejoin = await store.join(peer, tab, { operationId: randomUUID() })+ expect(rejoin.alreadyMember).toBe(false)+ await expect(store.join(peer, tab, latest)).rejects.toMatchObject({ code: 'JOIN_CHANGED' })+ })++ it('keeps legacy members without a generation stable without restoring them after removal', async () => {+ const tab = await create()+ await save(tab, { mode: 'domain', domain: 'example.com', role: 'collaborator' })+ const row = await db.superTab.findUniqueOrThrow({ where: { id: tab } })+ const state = JSON.parse(JSON.stringify(row.state))+ state.people.push({ id: peer.sub, email: peer.email, role: 'viewer' })+ await db.superTab.update({ where: { id: tab }, data: { state, memberIds: [owner.sub, peer.sub] } })+ const join = { operationId: randomUUID() }+ const result = await store.join(peer, tab, join)+ expect(result).toMatchObject({ role: 'viewer', alreadyMember: true })+ expect(await store.join(peer, tab, join)).toEqual(result)+ await store.execute(owner, tab, { operationId: randomUUID(), command: { type: 'member.remove', userId: peer.sub } })+ await expect(store.join(peer, tab, join)).rejects.toMatchObject({ code: 'JOIN_CHANGED' })+ })++ it('serializes concurrent joins/settings, prevents operation reuse, and isolates account environments', async () => {+ const tab = await create()+ const first = await save(tab, { mode: 'link', role: 'collaborator' }), token = tokenOf(first)+ const join = { operationId: randomUUID(), token }+ const [a, b] = await Promise.all([store.join(peer, tab, join), store.join(peer, tab, join)])+ expect(a).toEqual(b)+ expect((await store.read(owner, tab)).state.people.filter(p => p.id === peer.sub)).toHaveLength(1)+ await expect(store.join({ ...peer, autonomousEnv: 'stag' }, tab, join)).rejects.toMatchObject({ code: 'NOT_FOUND' })+ const updates = [+ { operationId: randomUUID(), revision: first.revision, access: { mode: 'invited' as const, role: 'viewer' as const } },+ { operationId: randomUUID(), revision: first.revision, access: { mode: 'domain' as const, domain: 'example.com', role: 'viewer' as const } },+ ]+ const results = await Promise.allSettled(updates.map(input => store.saveSharing(owner, tab, input)))+ expect(results.filter(result => result.status === 'fulfilled')).toHaveLength(1)+ expect(results.find(result => result.status === 'rejected')).toMatchObject({ reason: { code: 'REVISION_CHANGED' } })+ const accepted = updates[results.findIndex(result => result.status === 'fulfilled')]!+ await expect(store.saveSharing(owner, tab, { ...accepted, revision: 99 })).rejects.toMatchObject({ code: 'OPERATION_REUSED' })+ })+})diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 7f16f6c7a..749b7d417 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -9,6 +9,7 @@ import { SuperTabStore } from '../superTabs/store.js'import { routingPolicySchema } from '../superTabs/routingPolicy.js'import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'import { machineObservationSchema } from '../superTabs/machines.js'+import { joinSwarmSchema, previewJoinSchema, saveSharingSchema } from '../superTabs/sharing.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const tabParams = z.object({ tabId: id })@@ -77,6 +78,19 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suapp.post<{ Body: z.infer<typeof create> }>('/api/super-tabs', { preHandler: validateBody(create) },(req, reply) => respond(reply, () => store.create(req.user!, req.body.operationId, req.body.name, req.body.projectVisibility)))app.get('/api/super-tabs/invitations', (req, reply) => respond(reply, () => store.invitations(req.user!)))+ app.get<{ Params: z.infer<typeof tabParams> }>('/api/super-tabs/:tabId/sharing',+ { preHandler: validateParams(tabParams) },+ (req, reply) => respond(reply, () => store.sharing(req.user!, req.params.tabId)))+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof saveSharingSchema> }>('/api/super-tabs/:tabId/sharing',+ { preHandler: [validateParams(tabParams), validateBody(saveSharingSchema)] },+ (req, reply) => respond(reply, () => store.saveSharing(req.user!, req.params.tabId, req.body)))+ // Preview uses a body so bearer link tokens never enter HTTP access/error logs.+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof previewJoinSchema> }>('/api/super-tabs/:tabId/join/preview',+ { preHandler: [validateParams(tabParams), validateBody(previewJoinSchema)] },+ (req, reply) => respond(reply, () => store.previewJoin(req.user!, req.params.tabId, req.body.token)))+ app.post<{ Params: z.infer<typeof tabParams>; Body: z.infer<typeof joinSwarmSchema> }>('/api/super-tabs/:tabId/join',+ { preHandler: [validateParams(tabParams), validateBody(joinSwarmSchema)] },+ (req, reply) => respond(reply, () => store.join(req.user!, req.params.tabId, req.body)))app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId', { preHandler: validateParams(hostParams) },(req, reply) => respond(reply, () => store.hostTabs(req.user!, req.params.machineId)))app.get<{ Params: z.infer<typeof hostParams> }>('/api/super-tabs/hosts/:machineId/assignments', { preHandler: validateParams(hostParams) },diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 4102f69ea..14e308926 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -104,6 +104,8 @@ export interface SuperTabState {environment: string/** Fields this tab overrides from its owner's account routing policy (routingPolicy.ts). */routingPolicy?: import('./routingPolicy.js').RoutingOverride+ /** Owner-only sharing configuration; visibleState always removes it. */+ sharing?: import('./sharing.js').SwarmSharingpaused: booleanpeople: Person[]agents: Agent[]@@ -196,6 +198,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)+ delete visible.sharingnumberConversations(visible)if (visible.projects) {visible.projects = visible.projects.filter(p => canReadProject(state, actor, p))diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 24d5563b7..15322f55e 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -6,7 +6,7 @@ export interface SwarmProject {name: stringownerId: stringleadConversationId: string- /** Public means every member of this invite-only swarm. */+ /** Public means every member of this swarm, never anonymous internet access. */visibility: ProjectVisibilitymembers: Array<{ id: string; generation: string }>updateMinutes: 1 | 5 | 15 | 30diff --git a/backend/src/superTabs/sharing.test.ts b/backend/src/superTabs/sharing.test.tsnew file mode 100644index 000000000..42ef1feb6--- /dev/null+++ b/backend/src/superTabs/sharing.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest'+import { createSuperTab, visibleState } from './model.js'+import { authenticatedEmail, authorizeSwarmJoin, configureSharing, generalAccessSchema,+ joinSwarmSchema, requireSharingOwner, saveSharingSchema, sharingDetails } from './sharing.js'+import { shouldSkipAuth } from '../middlewares/authMiddleware.js'++const owner = { id: 'owner', email: '[email protected]' }+const tab = () => createSuperTab('tab', 'Fixture Swarm', owner, 'prod')+const linkToken = (state: ReturnType<typeof tab>) => new URL(sharingDetails(state).joinUrl!).searchParams.get('token')!++describe('Swarm sharing policy', () => {+ it('defaults to invited people and keeps every sharing endpoint authenticated', () => {+ expect(sharingDetails(tab())).toEqual({ revision: 0, access: { mode: 'invited', role: 'collaborator' }, joinUrl: null })+ expect(() => authorizeSwarmJoin(tab(), owner.email)).toThrow('unavailable')+ for (const path of ['sharing', 'join', 'join/preview']) expect(shouldSkipAuth(`/api/super-tabs/tab/${path}`)).toBe(false)+ })++ it('accepts an exact normalized email domain, not a subdomain, suffix, address, or caller metadata', () => {+ const state = tab()+ const access = generalAccessSchema.parse({ mode: 'domain', domain: ' Example.COM ', role: 'collaborator' })+ expect(access).toEqual({ mode: 'domain', domain: 'example.com', role: 'collaborator' })+ state.sharing = configureSharing(undefined, access)+ expect(authorizeSwarmJoin(state, ' [email protected] ')).toBe(state.sharing)+ '[email protected]@evil.test', '[email protected]\[email protected]', 'Person <[email protected]>', '', 'not-an-email']) {+ expect(() => authorizeSwarmJoin(state, email)).toThrow('unavailable')+ }+ expect(() => authorizeSwarmJoin(state, owner.email, 'A'.repeat(43))).toThrow('unavailable')+ for (const invalid of ['*.example.com', '@example.com', 'example.com/path', 'example.com.', 'localhost', 'a..example.com']) {+ expect(generalAccessSchema.safeParse({ mode: 'domain', domain: invalid, role: 'viewer' }).success).toBe(false)+ }+ expect(joinSwarmSchema.safeParse({ operationId: 'join', email: '[email protected]' }).success).toBe(false)+ expect(authenticatedEmail('[email protected]')).toBeNull()+ })++ it('restricts grants to viewer or collaborator and link rotation to link access', () => {+ for (const mode of ['invited', 'domain', 'link']) {+ expect(generalAccessSchema.safeParse({ mode, domain: 'example.com', role: 'owner' }).success).toBe(false)+ }+ expect(saveSharingSchema.safeParse({ operationId: 'save', revision: 0,+ access: { mode: 'invited', role: 'viewer' }, rotateLink: true }).success).toBe(false)+ const state = tab()+ state.people.push({ id: 'peer', email: '[email protected]', generation: 'peer', role: 'collaborator' })+ expect(() => requireSharingOwner(state, 'peer')).toThrow('Only the Swarm owner')+ expect(() => requireSharingOwner(state, 'stranger')).toThrow('no longer have access')+ expect(() => requireSharingOwner(state, owner.id)).not.toThrow()+ })++ it('encrypts a strong token for owner retrieval and removes secrets from every shared snapshot', () => {+ const state = tab()+ state.sharing = configureSharing(undefined, { mode: 'link', role: 'viewer' })+ const token = linkToken(state)+ expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/)+ expect(JSON.stringify(state.sharing)).not.toContain(token)+ expect(state.sharing.link?.hash).toMatch(/^[a-f0-9]{64}$/)+ expect(authorizeSwarmJoin(state, '[email protected]', token)).toBe(state.sharing)+ expect(() => authorizeSwarmJoin(state, '[email protected]', token)).toThrow('unavailable')+ for (const bad of [undefined, 'A', `${token}x`, 'A'.repeat(43)]) {+ expect(() => authorizeSwarmJoin(state, owner.email, bad)).toThrow('unavailable')+ }+ expect(visibleState(state, { kind: 'person', userId: owner.id, email: owner.email }).sharing).toBeUndefined()+ state.people.push({ id: 'peer', email: '[email protected]', generation: 'peer', role: 'viewer' })+ expect(visibleState(state, { kind: 'person', userId: 'peer', email: '[email protected]' }).sharing).toBeUndefined()+ expect(sharingDetails(state).joinUrl).toBe(`harness://swarm/join/tab?token=${token}`)+ })++ it('keeps a copied link through a role edit, replaces it explicitly, and erases it when access is closed', () => {+ const state = tab()+ state.sharing = configureSharing(undefined, { mode: 'link', role: 'viewer' })+ const first = state.sharing, token = linkToken(state)+ state.sharing = configureSharing(first, { mode: 'link', role: 'collaborator' })+ expect(linkToken(state)).toBe(token)+ expect(state.sharing.generation).not.toBe(first.generation)+ state.sharing = configureSharing(state.sharing, { mode: 'link', role: 'collaborator' }, true)+ expect(linkToken(state)).not.toBe(token)+ expect(() => authorizeSwarmJoin(state, owner.email, token)).toThrow('unavailable')+ state.sharing = configureSharing(state.sharing, { mode: 'domain', domain: 'example.com', role: 'viewer' })+ expect(state.sharing.link).toBeUndefined()+ expect(sharingDetails(state).joinUrl).toBe('harness://swarm/join/tab')+ state.sharing = configureSharing(state.sharing, { mode: 'invited', role: 'viewer' })+ expect(state.sharing.revision).toBe(5)+ expect(sharingDetails(state).joinUrl).toBeNull()+ expect(() => authorizeSwarmJoin(state, owner.email)).toThrow('unavailable')+ })+})diff --git a/backend/src/superTabs/sharing.ts b/backend/src/superTabs/sharing.tsnew file mode 100644index 000000000..dc3deaf19--- /dev/null+++ b/backend/src/superTabs/sharing.ts@@ -0,0 +1,80 @@+import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'+import { z } from 'zod'+import { decryptMachineCredential, encryptMachineCredential } from '../lib/machineCredential.js'+import { fail, person, type SuperTabState } from './model.js'++const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)+const role = z.enum(['collaborator', 'viewer'])+const domain = z.string().trim().toLowerCase().max(253)+ .regex(/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?$/, 'Enter a domain such as example.com.')+export const generalAccessSchema = z.discriminatedUnion('mode', [+ z.object({ mode: z.literal('invited'), role }).strict(),+ z.object({ mode: z.literal('domain'), role, domain }).strict(),+ z.object({ mode: z.literal('link'), role }).strict(),+])+export const saveSharingSchema = z.object({ operationId: id, revision: z.number().int().nonnegative().safe(),+ access: generalAccessSchema, rotateLink: z.boolean().optional() }).strict()+ .refine(value => !value.rotateLink || value.access.mode === 'link', 'Only a shared link can be replaced.')+export const previewJoinSchema = z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{43}$/).optional() }).strict()+export const joinSwarmSchema = previewJoinSchema.extend({ operationId: id }).strict()+export type GeneralAccess = z.infer<typeof generalAccessSchema>+export type SaveSharing = z.infer<typeof saveSharingSchema>+export type JoinSwarm = z.infer<typeof joinSwarmSchema>++/** Private management state. Never include this in the shared tab snapshot or a command receipt. */+export interface SwarmSharing {+ revision: number+ generation: string+ access: GeneralAccess+ link?: { hash: string; encryptedToken: string }+}++export function requireSharingOwner(state: SuperTabState, userId: string): void {+ person(state, userId)+ if (state.ownerId !== userId) fail('OWNER_REQUIRED', 'Only the Swarm owner can change sharing.', 403)+}++/** Every change fences old join receipts, even if a domain or link is enabled again later. */+export function configureSharing(previous: SwarmSharing | undefined, access: GeneralAccess, rotateLink = false): SwarmSharing {+ let link: SwarmSharing['link']+ if (access.mode === 'link') {+ if (previous?.access.mode === 'link' && previous.link && !rotateLink) link = previous.link+ else {+ const token = randomBytes(32).toString('base64url')+ link = { hash: tokenHash(token), encryptedToken: encryptMachineCredential(token) }+ }+ }+ return { revision: (previous?.revision ?? 0) + 1, generation: randomUUID(), access, ...(link ? { link } : {}) }+}++export function sharingDetails(state: SuperTabState) {+ const sharing = state.sharing+ const access: GeneralAccess = sharing?.access ?? { mode: 'invited', role: 'collaborator' }+ const path = `harness://swarm/join/${encodeURIComponent(state.id)}`+ const joinUrl = access.mode === 'invited' ? null : access.mode === 'domain' ? path+ : sharing?.link ? `${path}?token=${decryptMachineCredential(sharing.link.encryptedToken)}` : null+ return { revision: sharing?.revision ?? 0, access, joinUrl }+}++const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex')++/** Email comes only from the authenticated account, never from a join body or an old roster row. */+export function authenticatedEmail(email: string): string | null {+ const normalized = email.trim().toLowerCase()+ if (!z.email().safeParse(normalized).success || normalized.endsWith('@pending.harness.invalid')) return null+ return normalized+}++export function authorizeSwarmJoin(state: SuperTabState, email: string, token?: string): SwarmSharing {+ const sharing = state.sharing+ const verifiedEmail = authenticatedEmail(email)+ if (!sharing || !verifiedEmail) return fail('JOIN_UNAVAILABLE', 'This Swarm link is unavailable for this account.', 404)+ const access = sharing.access+ if (access.mode === 'domain' && token === undefined && verifiedEmail.split('@')[1] === access.domain) return sharing+ if (access.mode === 'link' && token && sharing.link && /^[A-Za-z0-9_-]{43}$/.test(token)) {+ const expected = Buffer.from(sharing.link.hash, 'hex')+ const actual = Buffer.from(tokenHash(token), 'hex')+ if (expected.length === actual.length && timingSafeEqual(expected, actual)) return sharing+ }+ return fail('JOIN_UNAVAILABLE', 'This Swarm link is unavailable for this account.', 404)+}diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 70f2b9715..93a98f5ad 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -16,6 +16,8 @@ import {} from './model.js'import { closeAssignment, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'+import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,+ saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'type Transaction = Prisma.TransactionClientconst json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue@@ -178,6 +180,80 @@ export class SuperTabStore {})}+ async sharing(user: AuthUser, tabId: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ requireSharingOwner(state, user.sub)+ return sharingDetails(state)+ })+ }++ async saveSharing(user: AuthUser, tabId: string, input: SaveSharing) {+ const request = saveSharingSchema.parse(input)+ return transaction(this.db, async tx => {+ const row = await this.row(tx, user, tabId), state = stateOf(row)+ requireSharingOwner(state, user.sub)+ const receiptId = stableId('swarm-sharing', tabId, user.sub, request.operationId), requestHash = hash(request)+ const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })+ if (prior) {+ if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')+ const result = prior.result as Record<string, unknown>+ if (state.sharing?.generation !== result.generation) fail('SHARING_CHANGED', 'Sharing changed after this request. Reload it and try again.')+ return sharingDetails(state)+ }+ if ((state.sharing?.revision ?? 0) !== request.revision) fail('REVISION_CHANGED', 'Sharing changed elsewhere. Reload it and try again.')+ state.sharing = configureSharing(state.sharing, request.access, request.rotateLink)+ const revision = row.revision + 1+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision, state: json(state) } })+ await tx.superTabOperation.create({ data: { id: receiptId, tabId, actorKey: `person:${user.sub}`, requestHash,+ revision, result: { generation: state.sharing.generation } } })+ return sharingDetails(state)+ })+ }++ /** A signed-in preview contains no projects, people, machines, or conversation data. It never joins. */+ async previewJoin(user: AuthUser, tabId: string, token?: string) {+ return transaction(this.db, async tx => {+ const state = stateOf(await this.row(tx, user, tabId))+ const sharing = authorizeSwarmJoin(state, user.email, token)+ const member = state.people.find(p => p.id === user.sub)+ return { id: tabId, name: state.name, role: member?.role ?? sharing.access.role, alreadyMember: !!member }+ })+ }++ async join(user: AuthUser, tabId: string, input: JoinSwarm) {+ const request = joinSwarmSchema.parse(input)+ return transaction(this.db, async tx => {+ const row = await this.row(tx, user, tabId), state = stateOf(row)+ // Recheck the current grant before an old receipt. Disabling, replacing, or+ // changing access can never revive a removed membership through a retry.+ const sharing = authorizeSwarmJoin(state, user.email, request.token)+ const receiptId = stableId('swarm-join', tabId, user.sub, request.operationId), requestHash = hash(request)+ const prior = await tx.superTabOperation.findUnique({ where: { id: receiptId } })+ let member = state.people.find(p => p.id === user.sub)+ if (prior) {+ if (prior.requestHash !== requestHash) fail('OPERATION_REUSED', 'Use a new operation ID for a different request.')+ const result = prior.result as Record<string, unknown>+ if (result.sharingGeneration !== sharing.generation || !member || (member.generation ?? null) !== result.membershipGeneration) {+ fail('JOIN_CHANGED', 'This join request is no longer current. Open the latest Swarm link again.')+ }+ return { id: tabId, revision: prior.revision, role: member.role, alreadyMember: result.alreadyMember === true }+ }+ const alreadyMember = !!member+ if (!member) {+ member = { id: user.sub, email: authenticatedEmail(user.email)!, role: sharing.access.role, generation: receiptId }+ state.people.push(member)+ }+ // Existing people retain their role and private-project grants. A general+ // access link does not promote a viewer or grant a private project.+ const revision = row.revision + 1+ await tx.superTab.update({ where: { id: tabId, revision: row.revision }, data: { revision, state: json(state), ...indexes(state) } })+ await tx.superTabOperation.create({ data: { id: receiptId, tabId, actorKey: `person:${user.sub}`, requestHash, revision,+ result: { sharingGeneration: sharing.generation, membershipGeneration: member.generation ?? null, alreadyMember } } })+ return { id: tabId, revision, role: member.role, alreadyMember }+ })+ }+async read(user: AuthUser, tabId: string, asAgentId?: string) {return transaction(this.db, async tx => {const row = await this.row(tx, user, tabId)diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 9f687d48e..213c7d684 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,4 +1,4 @@import { defineConfig } from 'vitest/config'-export default defineConfig({ test: { include: ['integration/superTabs.test.ts'], hookTimeout: 120000, testTimeout: 30000,+export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts'], hookTimeout: 120000, testTimeout: 30000,fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/design/terminal-workspace.md b/desktop/design/terminal-workspace.mdindex 870bd5876..2dbdff7a6 100644--- a/desktop/design/terminal-workspace.md+++ b/desktop/design/terminal-workspace.md@@ -34,8 +34,10 @@ Super Tab membership protects an agent from automatic idle and parent cleanup,including while the host is offline and while the Super Tab is paused. Membershiponly in archived conversations does not, and protection lapses after a week without aconfirmed roster (for example after sign-out). If the agent is already stopped,-only **Open terminal** (in Participants or on a message) resumes its saved conversation; a restored-or revisited terminal selection closes instead, so an explicit stop stays stopped.+opening its Swarm pane shows retained terminal output or its saved conversation+when that machine permits history access. Only the pane's explicit **Resume**+action restarts it; navigation and restoration never undo a stop. Swarm membership+does not grant access to machine-wide history.A Lead routes each delegation with `harness super-tab route`. The decision appears in theconversation as one row (who, how — Jev's confidence or the policy order — and why); owners anddiff --git a/desktop/integration_test/super_tab_native_test.dart b/desktop/integration_test/super_tab_native_test.dartindex 457ce9bd7..175e2c80b 100644--- a/desktop/integration_test/super_tab_native_test.dart+++ b/desktop/integration_test/super_tab_native_test.dart@@ -14,6 +14,7 @@ import 'package:harness/super_tabs/workspace.dart';import 'package:harness/widgets/pane_grid.dart';import 'package:harness/widgets/agent_drag.dart';import 'package:harness/widgets/terminal_panel.dart';+import 'package:harness/ws/local_cli_discovery.dart';import '../test/super_tab_launch_test.dart'show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;@@ -42,7 +43,17 @@ void main() {final f = SuperTabLaunchFixture();f.connection.nativeName = 'hi';f.connection.nativeSurface = true;- f.app.machineStates['m']!.terminalCapabilityAvailable = true;+ f.app.machineStates['m']!+ ..terminalCapabilityAvailable = true+ // The fixture serves a local daemon's protocol. A local machine with+ // no endpoint means offline to PaneGrid, even when its registry is set.+ ..localEndpoint = LocalCliEndpoint(+ computerId: 'fixture',+ machineId: 'm',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ );await tester.runAsync(() async {final box = await f.box(engine: 'claude');expect(@@ -273,8 +284,8 @@ void main() {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.+ // Navigation preserves a stopped member. Only an explicit Resume may+ // reopen its exact saved conversation before preparing recording.f.connection.native = {...f.connection.native!,'status': 'stopped',@@ -285,10 +296,20 @@ void main() {await tester.tap(find.byKey(ValueKey('super-member-${c.snapshot!.agents.single.id}')),);+ for (var i = 0; i < 40 && find.text('Resume').evaluate().isEmpty; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(+ f.connection.calls.where((call) => call.$1 == 'agent_resume'),+ isEmpty,+ );+ expect(find.text('Resume'), findsOneWidget);+ await tester.tap(find.text('Resume'));for (var i = 0;i < 120 &&(f.app.activeSwarm.panes.isEmpty ||+ f.app.stateOf('m')!.agents.single.isStopped ||f.app.activeSwarm.panes.single.session?.streamId == null);i++) {diff --git a/desktop/integration_test/swarm_sharing_native_test.dart b/desktop/integration_test/swarm_sharing_native_test.dartnew file mode 100644index 000000000..a971351da--- /dev/null+++ b/desktop/integration_test/swarm_sharing_native_test.dart@@ -0,0 +1,145 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_dialog.dart';+import 'package:harness/super_tabs/join_dialog.dart';+import 'package:harness/super_tabs/join_link.dart';+import 'package:harness/super_tabs/sharing.dart';+import 'package:integration_test/integration_test.dart';+import 'package:window_manager/window_manager.dart';++import '../test/swarm_sharing_test.dart' show SwarmSharingServer;++/// Real macOS controls with synthetic membership and an in-memory server only.+/// This fixture never signs in, calls a production backend or starts an agent.+void main() {+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;+ testWidgets(+ 'native sharing saves access and join requires a separate human action',+ (tester) async {+ await windowManager.ensureInitialized().timeout(+ const Duration(seconds: 10),+ );+ await windowManager+ .setSize(const Size(980, 760))+ .timeout(const Duration(seconds: 10));+ await windowManager.show().timeout(const Duration(seconds: 10));+ await windowManager.focus().timeout(const Duration(seconds: 10));+ final server = SwarmSharingServer();+ final controller = server.controller();+ await controller.refresh();+ final boundary = GlobalKey();+ var joins = 0, opened = false;+ Future<void> shot(String name) async {+ final root = Platform.environment['HARNESS_SWARM_SHARING_NATIVE_SHOTS'];+ if (root == null) return;+ final render =+ boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await render.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(root).create(recursive: true);+ await File('$root/$name.png').writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ }++ Future<void> app(Brightness brightness) async {+ grid.AppTheme.brightness.value = brightness;+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: Builder(+ builder: (context) => Column(+ children: [+ TextButton(+ onPressed: () =>+ showSuperTabSharing(context, controller),+ child: const Text('Share'),+ ),+ TextButton(+ onPressed: () => showAppDialog<void>(+ context: context,+ builder: (_) => SwarmJoinDialog(+ link: SwarmJoinLink.parse(+ server.settings['joinUrl'] as String,+ )!,+ accountEmail: '[email protected]',+ isCurrent: () => true,+ request: (_, path, {body}) async {+ if (path.endsWith('/preview')) {+ return {+ 'id': 'tab',+ 'name': 'Studio',+ 'role': 'collaborator',+ 'alreadyMember': false,+ };+ }+ joins++;+ return {'id': 'tab', 'role': 'collaborator'};+ },+ onJoined: (id, name) {+ opened = id == 'tab' && name == 'Studio';+ },+ ),+ ),+ child: const Text('Open invitation'),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ await app(Brightness.dark);+ await tester.tap(find.text('Share'));+ await tester.pumpAndSettle();+ await shot('dark-invited');+ await tester.tap(find.byKey(const Key('swarm-general-access')));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Anyone with the link').last);+ await tester.pumpAndSettle();+ expect(server.sharingPosts, isEmpty);+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ expect(server.access['mode'], 'link');+ expect(find.byKey(const Key('swarm-copy-link')), findsOneWidget);+ await shot('dark-link');+ await tester.tap(find.text('Done'));+ await tester.pumpAndSettle();+ await app(Brightness.light);+ await tester.tap(find.text('Share'));+ await tester.pumpAndSettle();+ await shot('light-link');+ await tester.tap(find.text('Done'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Open invitation'));+ await tester.pumpAndSettle();+ expect(joins, 0);+ expect(opened, false);+ await shot('join-preview');+ await tester.tap(find.byKey(const Key('swarm-join-confirm')));+ await tester.pumpAndSettle();+ expect(joins, 1);+ expect(opened, true);+ expect(find.byType(SwarmJoinDialog), findsNothing);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ controller.dispose();+ },+ );+}diff --git a/desktop/lib/community/fork_host.dart b/desktop/lib/community/fork_host.dartindex d66df8b10..f46473c0a 100644--- a/desktop/lib/community/fork_host.dart+++ b/desktop/lib/community/fork_host.dart@@ -7,6 +7,7 @@ import '../core/test_run.dart';import '../core/models.dart';import '../notify/system_notifications.dart';import '../state/app_state.dart';+import '../super_tabs/join_link.dart';import 'fork_controller.dart';import 'fork_inbox.dart';import 'fork_project.dart';@@ -14,6 +15,7 @@ import 'fork_project.dart';final communityForkInbox = ForkInbox(HarnessFileStore.shared,claimLink: systemNotifications.openLink,+ onUnhandledLink: swarmJoinInbox.accept,);Future<void>? _inboxReady;diff --git a/desktop/lib/community/fork_inbox.dart b/desktop/lib/community/fork_inbox.dartindex 3dd030e18..93725f5bc 100644--- a/desktop/lib/community/fork_inbox.dart+++ b/desktop/lib/community/fork_inbox.dart@@ -12,6 +12,7 @@ class ForkInbox extends ChangeNotifier {this.store, {this.channel = const MethodChannel('harness/community_links'),this.claimLink,+ this.onUnhandledLink,});final LocalKeyValueStore store;final MethodChannel channel;@@ -20,6 +21,10 @@ class ForkInbox extends ChangeNotifier {/// never queued here. A Windows toast's click arrives this way/// (`SystemNotifications.openLink`).final bool Function(String url)? claimLink;++ /// Hand non-fork links to a typed feature inbox without persisting them here.+ /// Swarm join links may contain bearer tokens and remain in memory only.+ final Future<void> Function(String)? onUnhandledLink;static const storageKey = 'community.forks.v1';final List<ForkLink> pending = [];Future<void> _tail = Future.value();@@ -62,7 +67,11 @@ class ForkInbox extends ChangeNotifier {Future<void> _queue(String url) => _serialize(() async {final link = ForkLink.parse(url);- if (link == null || pending.any((p) => p.key == link.key)) {+ if (link == null) {+ await onUnhandledLink?.call(url);+ return;+ }+ if (pending.any((p) => p.key == link.key)) {return;}if (pending.length >= 20) return;diff --git a/desktop/lib/desktop_workspace.dart b/desktop/lib/desktop_workspace.dartindex 945145954..b24bc6964 100644--- a/desktop/lib/desktop_workspace.dart+++ b/desktop/lib/desktop_workspace.dart@@ -4,13 +4,17 @@ import 'screens/swarm_screen.dart';import 'state/app_state.dart';import 'ws/terminal_transport_plugin.dart';import 'community/fork_host.dart';+import 'super_tabs/join_dialog.dart';/// The signed-in screen of a native build. A browser build compiles/// `web/web_entry.dart` in its place (the conditional import in `main.dart`),/// so native code never reaches `lib/web/`.Widget authenticatedWorkspace(AppNotifier app) => CommunityForkHost(app: app,- child: SwarmScreen(notifier: app),+ child: SwarmJoinHost(+ app: app,+ child: SwarmScreen(notifier: app),+ ),);/// A native build draws nothing around its screens.diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 4aad0cc04..c3b4af503 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -6245,10 +6245,11 @@ class _SwarmScreenState extends State<SwarmScreen> {harnessContext: superTabTarget == null? null: HarnessPickerContext(- title: 'Add agent to ${groupTitle ?? 'conversation'}',+ title:+ 'Add agent to ${contribution?.snapshot?.name ?? app.activeSwarm.name}',description: contributionProject?.isPrivate == true- ? 'Shared with members of ${contributionProject!.name}.'- : 'Shared with everyone in ${app.activeSwarm.name}.',+ ? 'Starts in ${groupTitle ?? 'Lead'}. Only members of ${contributionProject!.name} can access it.'+ : 'Starts in ${groupTitle ?? 'Lead'}.',action: 'Add agent',unavailable: (row) {final shared = app.superTabsdiff --git a/desktop/lib/shared/theme/app_icons.dart b/desktop/lib/shared/theme/app_icons.dartindex c7fcc24a3..a43b666bd 100644--- a/desktop/lib/shared/theme/app_icons.dart+++ b/desktop/lib/shared/theme/app_icons.dart@@ -125,6 +125,7 @@ abstract final class AppIcons {static const messageCircleQuestionMark =LucideIcons.messageCircleQuestionMark400;static const messagesSquare = LucideIcons.messagesSquare400;+ static const messageSquare = LucideIcons.messageSquare400;static const messageSquareText = LucideIcons.messageSquareText400;static const minimize = LucideIcons.minimize400;static const minus = LucideIcons.minus400;diff --git a/desktop/lib/shared/widgets/app_menu.dart b/desktop/lib/shared/widgets/app_menu.dartindex 5106cb80f..823b34e83 100644--- a/desktop/lib/shared/widgets/app_menu.dart+++ b/desktop/lib/shared/widgets/app_menu.dart@@ -81,6 +81,7 @@ class AppMenuItem extends StatefulWidget {this.focusNode,this.metrics = AppMenuRowMetrics.compact,this.textStyle,+ this.expandLabel = false,});/// The leading glyph. Null for a row in a list that PICKS one of several — the@@ -126,6 +127,9 @@ class AppMenuItem extends StatefulWidget {final AppMenuRowMetrics metrics;final TextStyle? textStyle;+ /// Fill a bounded row so its selection check sits at the trailing edge.+ final bool expandLabel;+/// This row is the current choice.////// Marked THREE ways, never by one: an accent wash, a heavier label, and a@@ -211,6 +215,7 @@ class _AppMenuItemState extends State<AppMenuItem> {),const SizedBox(width: 9),Flexible(+ fit: widget.expandLabel ? FlexFit.tight : FlexFit.loose,child: Column(crossAxisAlignment: CrossAxisAlignment.start,mainAxisSize: MainAxisSize.min,diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex b013cc823..f8b96902a 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -1788,19 +1788,53 @@ class AppNotifier extends ChangeNotifier {Map<String, dynamic> payload,) async {final revision = _authRevision;- final result = await _conn(machineId).request(- 'super_tabs',- payload: payload,- timeout: const Duration(seconds: 30),- );+ SuperTabFailure refusal(String code, String? detail, int status) {+ if (!_authWorkCurrent(revision)) {+ return const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');+ }+ final body = payload['body'];+ final command = body is Map ? body['command'] : null;+ if (payload['action'] == 'backend' &&+ command is Map &&+ command['type'] == 'project.create' &&+ code == 'VALIDATION_ERROR' &&+ detail?.contains('command.type') == true &&+ detail?.contains('discriminator') == true) {+ return SuperTabFailure(+ 'UPDATE_REQUIRED',+ 'The Swarm service needs an update before you can create a project. Your draft is saved.',+ statusCode: status,+ );+ }+ return SuperTabFailure(+ code,+ detail ?? 'Could not reach this Swarm.',+ statusCode: status,+ );+ }++ final Map<String, dynamic> result;+ try {+ result = await _conn(machineId).request(+ 'super_tabs',+ payload: payload,+ timeout: const Duration(seconds: 30),+ );+ } on WsRequestFailure catch (failure) {+ throw refusal(+ failure.code,+ failure.detail,+ (failure.payload['status'] as num?)?.toInt() ?? 0,+ );+ }if (!_authWorkCurrent(revision)) {throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');}if (result['error'] != null) {- throw SuperTabFailure(+ throw refusal(result['error'].toString(),- result['detail'] as String? ?? 'Could not reach this Swarm.',- statusCode: (result['status'] as num?)?.toInt() ?? 0,+ result['detail'] as String?,+ (result['status'] as num?)?.toInt() ?? 0,);}return result;diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dartnew file mode 100644index 000000000..5964ec6e7--- /dev/null+++ b/desktop/lib/super_tabs/join_dialog.dart@@ -0,0 +1,274 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/desktop_prompt_surface.dart';+import 'controller.dart';+import 'join_link.dart';++/// The native URL channel queues links before authentication. This host only+/// presents them after sign-in and never joins on the person's behalf.+class SwarmJoinHost extends StatefulWidget {+ const SwarmJoinHost({super.key, required this.app, required this.child});+ final AppNotifier app;+ final Widget child;++ @override+ State<SwarmJoinHost> createState() => _SwarmJoinHostState();+}++class _SwarmJoinHostState extends State<SwarmJoinHost> {+ bool _presenting = false;++ @override+ void initState() {+ super.initState();+ swarmJoinInbox.addListener(_schedule);+ widget.app.addListener(_schedule);+ _schedule();+ }++ void _schedule() {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) unawaited(_next());+ });+ WidgetsBinding.instance.ensureVisualUpdate();+ }++ Future<void> _next() async {+ final app = widget.app;+ final account = app.currentUser;+ if (!mounted ||+ _presenting ||+ swarmJoinInbox.pending.isEmpty ||+ app.status != AppStatus.authenticated ||+ account?.id == null) {+ return;+ }+ final accountId = account!.id!;+ final link = swarmJoinInbox.pending.first;+ bool current() =>+ mounted &&+ app.status == AppStatus.authenticated &&+ app.currentUser?.id == accountId;+ _presenting = true;+ try {+ await showAppDialog<void>(+ context: context,+ builder: (context) => ListenableBuilder(+ listenable: app,+ builder: (context, _) => current()+ ? SwarmJoinDialog(+ link: link,+ accountEmail: account.email,+ request: app.superTabs.map,+ isCurrent: current,+ onJoined: (id, name) {+ if (current()) app.openSuperTab(id, name);+ },+ )+ : AlertDialog(+ content: const Text('Sign in again to open this Swarm link.'),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),+ ),+ ],+ ),+ ),+ );+ } finally {+ swarmJoinInbox.complete(link);+ _presenting = false;+ if (mounted) _schedule();+ }+ }++ @override+ void dispose() {+ swarmJoinInbox.removeListener(_schedule);+ widget.app.removeListener(_schedule);+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => widget.child;+}++class SwarmJoinDialog extends StatefulWidget {+ const SwarmJoinDialog({+ super.key,+ required this.link,+ required this.accountEmail,+ required this.request,+ required this.onJoined,+ required this.isCurrent,+ });+ final SwarmJoinLink link;+ final String accountEmail;+ final SuperTabRequest request;+ final void Function(String id, String name) onJoined;+ final bool Function() isCurrent;++ @override+ State<SwarmJoinDialog> createState() => _SwarmJoinDialogState();+}++class _SwarmJoinDialogState extends State<SwarmJoinDialog> {+ final _operationId = superTabOperationId();+ Map<String, dynamic>? _preview;+ bool _loading = true, _joining = false;+ String? _error;+ String get _path =>+ '/api/super-tabs/${Uri.encodeComponent(widget.link.tabId)}/join';+ Map<String, dynamic> get _token => {+ if (widget.link.token != null) 'token': widget.link.token,+ };+ bool get _current => mounted && widget.isCurrent();++ @override+ void initState() {+ super.initState();+ unawaited(_load());+ }++ Future<void> _load() async {+ if (!_current) return;+ setState(() {+ _loading = true;+ _error = null;+ });+ try {+ // A token belongs in the request body, never an HTTP URL or proxy log.+ final preview = await widget.request(+ 'POST',+ '$_path/preview',+ body: _token,+ );+ if (!_current) return;+ if (preview['id'] != widget.link.tabId ||+ preview['name'] is! String ||+ !const [+ 'owner',+ 'collaborator',+ 'viewer',+ ].contains(preview['role'])) {+ throw const FormatException('Invalid invitation');+ }+ setState(() => _preview = preview);+ } catch (failure) {+ if (_current) setState(() => _error = _errorMessage(failure));+ } finally {+ if (_current) setState(() => _loading = false);+ }+ }++ Future<void> _join() async {+ if (!_current || _joining || _preview == null) return;+ setState(() {+ _joining = true;+ _error = null;+ });+ try {+ if (_preview!['alreadyMember'] != true) {+ final result = await widget.request(+ 'POST',+ _path,+ body: {'operationId': _operationId, ..._token},+ );+ if (!_current) return;+ if (result['id'] != widget.link.tabId) {+ throw const FormatException('Invalid invitation');+ }+ }+ if (!_current) return;+ widget.onJoined(widget.link.tabId, _preview!['name'] as String);+ if (mounted) Navigator.pop(context);+ } catch (failure) {+ if (_current) setState(() => _error = _errorMessage(failure));+ } finally {+ if (_current) setState(() => _joining = false);+ }+ }++ String _errorMessage(Object failure) {+ if (failure is SuperTabFailure) {+ if (const {+ 'FORBIDDEN',+ 'NOT_FOUND',+ 'INVALID_LINK',+ 'LINK_REVOKED',+ 'JOIN_UNAVAILABLE',+ }.contains(failure.code)) {+ return 'This link is unavailable for your account. Ask the owner for an invitation.';+ }+ if (failure.code == 'SIGNED_OUT' || failure.code == 'ACCOUNT_CHANGED') {+ return 'Sign in again to open this Swarm link.';+ }+ }+ return 'Could not open this Swarm. Check your connection and try again.';+ }++ @override+ Widget build(BuildContext context) => DesktopPromptSurface(+ body: DesktopPromptScrollBody(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ DesktopDialogHeader(+ title: _preview?['alreadyMember'] == true+ ? 'Open Swarm'+ : 'Join Swarm',+ padding: EdgeInsets.zero,+ onClose: () => Navigator.pop(context),+ ),+ const SizedBox(height: 16),+ if (_loading)+ const LinearProgressIndicator()+ else if (_preview case final preview?) ...[+ Text(preview['name'] as String, style: DesktopChrome.heading()),+ const SizedBox(height: 8),+ Text(+ preview['alreadyMember'] == true+ ? 'You’re already a member.'+ : preview['role'] == 'viewer'+ ? 'You’ll be able to view shared projects.'+ : 'You’ll be able to collaborate on shared projects.',+ style: DesktopChrome.text(),+ ),+ ],+ const SizedBox(height: 12),+ Text(widget.accountEmail, style: DesktopChrome.metadata()),+ if (_error != null) ...[+ const SizedBox(height: 12),+ Text(_error!, style: DesktopChrome.text()),+ ],+ ],+ ),+ ),+ actions: [+ FilledButton(+ key: const Key('swarm-join-confirm'),+ onPressed: _loading || _joining+ ? null+ : _preview == null+ ? _load+ : _join,+ child: Text(+ _joining+ ? 'Joining…'+ : _preview == null+ ? 'Retry'+ : _preview!['alreadyMember'] == true+ ? 'Open Swarm'+ : 'Join Swarm',+ ),+ ),+ ],+ );+}diff --git a/desktop/lib/super_tabs/join_link.dart b/desktop/lib/super_tabs/join_link.dartnew file mode 100644index 000000000..fd4a47a67--- /dev/null+++ b/desktop/lib/super_tabs/join_link.dart@@ -0,0 +1,70 @@+import 'package:flutter/foundation.dart';++/// A Swarm link identifies membership access, never a machine, path or command.+/// Opening it only queues a preview; the person must sign in and choose Join.+class SwarmJoinLink {+ const SwarmJoinLink(this.tabId, {this.token});++ final String tabId;+ final String? token;+ static final _id = RegExp(r'^[A-Za-z0-9_-]{1,160}$');+ static final _token = RegExp(r'^[A-Za-z0-9_-]{43}$');++ String get url =>+ 'harness://swarm/join/$tabId'+ '${token == null ? '' : '?token=$token'}';++ static SwarmJoinLink? parse(String value) {+ // Match the native URL-open limit, including cold-start delivery.+ if (value.length > 240) return null;+ final uri = Uri.tryParse(value);+ if (uri == null ||+ uri.scheme != 'harness' ||+ uri.host != 'swarm' ||+ uri.hasPort ||+ uri.userInfo.isNotEmpty ||+ uri.hasFragment ||+ uri.pathSegments.length != 2 ||+ uri.pathSegments.first != 'join' ||+ !_id.hasMatch(uri.pathSegments.last)) {+ return null;+ }+ final query = uri.queryParametersAll;+ if (query.isEmpty && !uri.hasQuery) {+ return SwarmJoinLink(uri.pathSegments.last);+ }+ final tokens = query['token'];+ if (query.length != 1 ||+ tokens == null ||+ tokens.length != 1 ||+ !_token.hasMatch(tokens.single)) {+ return null;+ }+ return SwarmJoinLink(uri.pathSegments.last, token: tokens.single);+ }+}++/// Links arriving before sign-in stay in memory, without persisting or logging+/// the bearer token. The native host already queues cold-start URL events.+class SwarmJoinInbox extends ChangeNotifier {+ final List<SwarmJoinLink> _pending = [];+ List<SwarmJoinLink> get pending => List.unmodifiable(_pending);++ Future<void> accept(String value) async {+ final link = SwarmJoinLink.parse(value);+ if (link == null ||+ _pending.length >= 20 ||+ _pending.any((item) => item.url == link.url)) {+ return;+ }+ _pending.add(link);+ notifyListeners();+ }++ void complete(SwarmJoinLink link) {+ _pending.removeWhere((item) => item.url == link.url);+ notifyListeners();+ }+}++final swarmJoinInbox = SwarmJoinInbox();diff --git a/desktop/lib/super_tabs/launch.dart b/desktop/lib/super_tabs/launch.dartindex d640290e0..7bddc4ae7 100644--- a/desktop/lib/super_tabs/launch.dart+++ b/desktop/lib/super_tabs/launch.dart@@ -57,7 +57,7 @@ class SuperTabLaunch {integration = HarnessLaunchIntegration(creationId: saved['creationId'] as String? ?? superTabOperationId(),actionLabel: saved['newProject'] == true- ? 'New project'+ ? 'New Project': saved['lead'] == true? 'New Swarm': 'New Harness',@@ -73,6 +73,20 @@ class SuperTabLaunch {}try {return await launch.prepare(machine, task);+ } on SuperTabFailure catch (failure) {+ // Validation rejects the request before applying it. A lost response+ // stays locked so retrying cannot create a second project or change+ // the visibility of a project that may already exist.+ if (saved['projectPrepared'] != true &&+ const {+ 'VALIDATION_ERROR',+ 'UPDATE_REQUIRED',+ }.contains(failure.code)) {+ saved.remove('creationRequest');+ saved['operationId'] = superTabOperationId();+ await launch.persist();+ }+ rethrow;} finally {integration.projectVisibilityLocked =saved['projectPrepared'] == true ||diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 752f7a34d..2e6457490 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -1,17 +1,19 @@import 'dart:async';import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import '../core/machine_resources.dart';import '../core/models.dart';import '../core/test_run.dart';+import '../shared/theme/app_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_menu.dart';import '../state/app_state.dart';import '../usage/models_menu_controller.dart';import '../widgets/desktop_chrome.dart';import '../widgets/engine_identity.dart';-import '../shared/widgets/app_select_field.dart';import '../widgets/workspace_subscription_usage.dart';import 'controller.dart';import 'dialog_scope.dart';@@ -35,6 +37,176 @@ class SuperTabMachines extends StatefulWidget {State<SuperTabMachines> createState() => _SuperTabMachinesState();}+class _MachineChoice {+ const _MachineChoice({+ required this.id,+ required this.label,+ this.unavailable,+ });++ final String id, label;+ final ({IconData icon, String message})? unavailable;+}++/// Unlike an ordinary choice field, this inventory also explains computers+/// that cannot be selected. Standard menu buttons own their disabled semantics+/// and keyboard traversal; the shared menu theme supplies their appearance.+class _MachinePicker extends StatefulWidget {+ const _MachinePicker({+ required this.value,+ required this.choices,+ required this.busy,+ required this.onChanged,+ });++ final String? value;+ final List<_MachineChoice> choices;+ final bool busy;+ final ValueChanged<String> onChanged;++ @override+ State<_MachinePicker> createState() => _MachinePickerState();+}++class _MachinePickerState extends State<_MachinePicker> {+ final _menu = MenuController();+ final _focus = FocusNode(debugLabel: 'Machine');++ @override+ void dispose() {+ _focus.dispose();+ super.dispose();+ }++ void _open() {+ if (!widget.busy) _menu.open();+ }++ Widget _status(({IconData icon, String message}) status) => Tooltip(+ message: status.message,+ excludeFromSemantics: true,+ child: Icon(status.icon, size: grid.AppControl.iconSize),+ );++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final current = widget.choices+ .where((choice) => choice.id == widget.value)+ .firstOrNull;+ final firstAvailable = widget.choices+ .where((choice) => choice.unavailable == null)+ .firstOrNull;+ final focusId = current?.unavailable == null && current != null+ ? current.id+ : firstAvailable?.id;+ final label = current?.label ?? 'Choose a machine';+ return LayoutBuilder(+ builder: (context, constraints) => MenuAnchor(+ controller: _menu,+ childFocusNode: _focus,+ consumeOutsideTap: true,+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),+ style: grid.AppMenu.style(+ minWidth: constraints.maxWidth,+ maxWidth: constraints.maxWidth,+ ),+ onOpen: () => setState(() {}),+ onClose: () => setState(() {}),+ menuChildren: [+ for (final choice in widget.choices)+ Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),+ child: SizedBox(+ width: constraints.maxWidth - 12,+ child: MenuItemButton(+ key: ValueKey('swarm-machine-option-${choice.id}'),+ autofocus: choice.id == focusId,+ overflowAxis: Axis.vertical,+ semanticsLabel: [+ choice.label,+ ?choice.unavailable?.message,+ ].join(', '),+ style: ButtonStyle(+ side: const WidgetStatePropertyAll(BorderSide.none),+ padding: WidgetStatePropertyAll(+ AppMenuRowMetrics.roomy.padding,+ ),+ ),+ onPressed: widget.busy || choice.unavailable != null+ ? null+ : () => widget.onChanged(choice.id),+ trailingIcon: choice.unavailable != null+ ? _status(choice.unavailable!)+ : choice.id == widget.value+ ? const Icon(+ AppIcons.check,+ size: grid.AppControl.iconSize,+ )+ : null,+ child: Tooltip(+ message: choice.label,+ excludeFromSemantics: true,+ child: Text(+ choice.label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ ),+ ),+ ),+ ],+ builder: (context, menu, _) => CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.arrowDown): _open,+ const SingleActivator(LogicalKeyboardKey.arrowUp): _open,+ },+ child: Semantics(+ label: 'Machine',+ value: [label, ?current?.unavailable?.message].join(', '),+ expanded: menu.isOpen,+ child: TextButton(+ key: const ValueKey('swarm-machine-picker'),+ focusNode: _focus,+ style: TextButton.styleFrom(+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(grid.AppControl.radius),+ ),+ ),+ onPressed: widget.busy+ ? null+ : () => menu.isOpen ? menu.close() : _open(),+ child: ExcludeSemantics(+ child: Row(+ children: [+ Expanded(+ child: Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ ),+ ),+ if (current?.unavailable != null) ...[+ const SizedBox(width: 8),+ _status(current!.unavailable!),+ ],+ const SizedBox(width: 8),+ const Icon(+ AppIcons.chevronDown,+ size: grid.AppControl.iconSize,+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }+}+class _SuperTabMachinesState extends State<SuperTabMachines> {final _samples = <String, (MachineResources, DateTime)>{};ModelsMenuController? _usage;@@ -138,45 +310,33 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {for (final m in c.snapshot?.machines ?? const <Map<String, dynamic>>[])m['machineId'] as String,};- // Only this account's own, reachable computers can be offered — a machine- // already in the tab would duplicate its entry, and one offline or- // unlinked cannot actually be contributed right now. The machine being- // configured is always its own exception: that is the one entry this- // dialog is editing, not adding.- final own = app.machineStates.values- .where((m) => !m.machine.isShared && !m.machine.isSharedMachine)- .toList();- final addable = own- .where(- (m) =>- isExisting(m) ||- (!contributed.contains(m.machine.machineId) &&- !m.needsLink &&- !m.isOffline),- )- .toList();- final alreadyInTab = own- .where(- (m) => !isExisting(m) && contributed.contains(m.machine.machineId),- )- .toList();- final notLinked = own- .where(- (m) =>- !isExisting(m) &&- !contributed.contains(m.machine.machineId) &&- m.needsLink,- )- .toList();- final offline = own- .where(- (m) =>- !isExisting(m) &&- !contributed.contains(m.machine.machineId) &&- !m.needsLink &&- m.isOffline,- )+ // Unavailable computers stay inspectable in the picker, but another+ // account's computers must never be offered for contribution.+ List<MachineState> ownedMachines() => app.machineStates.values+ .where((m) => !m.belongsToOtherAccount).toList();+ ({IconData icon, String message})? unavailable(MachineState m) {+ if (!isExisting(m) && contributed.contains(m.machine.machineId)) {+ return (icon: AppIcons.circleCheck, message: 'Already in this Swarm');+ }+ if (m.needsLink) {+ return (+ icon: AppIcons.unlink,+ message: 'Not linked. Link this computer from Machines.',+ );+ }+ if (m.isOffline) {+ return (+ icon: AppIcons.cloudOff,+ message: 'Offline. Open Harness on this computer to add it.',+ );+ }+ return null;+ }++ bool canSelect(MachineState? m) =>+ m != null && !m.belongsToOtherAccount && unavailable(m) == null;+ final addable = ownedMachines().where(canSelect).toList();String labelFor(MachineState m) => m.isLocalMachine? 'This Mac (${m.machine.displayName})': m.machine.displayName;@@ -191,203 +351,178 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {context: context,builder: (context) => SuperTabDialogScope(controller: c,- child: StatefulBuilder(- builder: (context, update) {- Future<void> save() async {- if (busy || machineId == null) return;- final selected = machineId!;- update(() {- busy = true;- error = null;- });- try {- 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,- 'scope': 'swarm',- 'operationId': setupId,- });- if (prepared['state'] == 'ready' &&- prepared['scope'] == 'swarm') {- break;+ child: ListenableBuilder(+ listenable: app,+ builder: (context, _) => StatefulBuilder(+ builder: (context, update) {+ Future<void> save() async {+ if (busy ||+ !c.canWrite ||+ machineId == null ||+ !canSelect(app.stateOf(machineId!))) {+ return;+ }+ final selected = machineId!;+ update(() {+ busy = true;+ error = null;+ });+ try {+ 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,+ 'scope': 'swarm',+ 'operationId': setupId,+ });+ if (prepared['state'] == 'ready' &&+ prepared['scope'] == 'swarm') {+ 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 (prepared['state'] != 'preparing') {- throw const SuperTabFailure(- 'UPDATE_REQUIRED',- 'Update Harness on this machine, then try again.',+ 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': selected,+ 'name': machine!.machine.displayName,+ 'cwd': prepared['cwd'],+ if (prepared['scope'] != null)+ 'scope': prepared['scope'],+ 'engines': prepared['engines'],+ 'maxAgents': prepared['maxAgents'],+ });+ if (result == null) {+ throw SuperTabFailure(+ 'CONTRIBUTION_FAILED',+ c.operationError ?? 'Could not add this machine.',);}- if (DateTime.now().isAfter(deadline)) {- throw const SuperTabFailure(- 'SETUP_PENDING',- 'Project setup is still running. Try again to check its progress.',- );+ 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;+ }+ });}- 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': selected,- 'name': machine!.machine.displayName,- 'cwd': prepared['cwd'],- if (prepared['scope'] != null)- 'scope': prepared['scope'],- 'engines': prepared['engines'],- 'maxAgents': prepared['maxAgents'],- });- if (result == null) {- throw SuperTabFailure(- 'CONTRIBUTION_FAILED',- c.operationError ?? 'Could not add this machine.',- );- }- 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;- }- });}}- }- final canAdd = addable.isNotEmpty;- // Only in Add mode: Configure already names the one machine it- // edits, so the picker's "already in the tab"/"can't reach it"- // bookkeeping about every OTHER machine is noise there.- final showStatus = !isConfigure;- final singleAlreadyInTab =- !canAdd &&- alreadyInTab.length == 1 &&- notLinked.isEmpty &&- offline.isEmpty;- final String emptyStatement = own.isEmpty- ? 'No computer is connected to this account yet.'- : singleAlreadyInTab- ? '${labelFor(alreadyInTab.single)} is already in this tab.'- : 'No other computer can be added to this tab right now.';- return AlertDialog(- title: Text(isConfigure ? 'Configure machine' : 'Add machine'),- content: SizedBox(- width: 360,- child: Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- if (canAdd)- AbsorbPointer(- absorbing: busy,- child: AppSelectField<String>(- value: machineId!,- semanticLabel: 'Machine',- options: [- for (final m in addable)- SelectOption(- value: m.machine.machineId,+ final own = ownedMachines();+ final canSave =+ machineId != null && canSelect(app.stateOf(machineId!));+ return AlertDialog(+ title: Text(isConfigure ? 'Configure machine' : 'Add machine'),+ content: SizedBox(+ width: 360,+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (own.isNotEmpty)+ _MachinePicker(+ value: machineId,+ busy: busy,+ choices: [+ for (final m in own)+ _MachineChoice(+ id: m.machine.machineId,label: labelFor(m),+ unavailable: unavailable(m),),],onChanged: (id) {- if (busy) return;+ if (busy || !canSelect(app.stateOf(id))) return;update(() {machineId = id;setupId = null;error = null;});},+ )+ else+ Text(+ 'No computer is connected to this account yet.',+ style: DesktopChrome.text(),),- )- else- Text(emptyStatement, style: DesktopChrome.text()),- if (showStatus &&- !singleAlreadyInTab &&- alreadyInTab.isNotEmpty) ...[- const SizedBox(height: 12),- Text(- 'Already in this tab: ${alreadyInTab.map(labelFor).join(', ')}',- style: DesktopChrome.metadata(),- ),- ],- if (showStatus)- for (final m in notLinked) ...[- const SizedBox(height: 4),+ const SizedBox(height: 16),+ if (own.isNotEmpty)Text(- 'Not linked: ${labelFor(m)}. Link it from Machines.',- style: DesktopChrome.metadata(),+ 'Let the lead run agents here using this machine’s signed-in accounts.',+ style: DesktopChrome.text(),+ )+ else ...[+ Text(+ 'To add another computer, install Harness on it and sign in with '+ 'this account, or approve a device with no screen from Machines.',+ style: DesktopChrome.text(),),- ],- if (showStatus)- for (final m in offline) ...[const SizedBox(height: 4),- Text(- 'Offline: ${labelFor(m)}. Start Harness on it to add it.',- style: DesktopChrome.metadata(),+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: () {+ Navigator.pop(context);+ app.requestMachines();+ },+ child: const Text('Open Machines'),+ ),),],- const SizedBox(height: 16),- if (canAdd)- Text(- 'Let the lead run agents here using this machine’s signed-in accounts.',- style: DesktopChrome.text(),- )- else ...[- Text(- 'To add another computer, install Harness on it and sign in with '- 'this account, or approve a device with no screen from Machines.',- style: DesktopChrome.text(),- ),- const SizedBox(height: 4),- Align(- alignment: Alignment.centerLeft,- child: TextButton(- onPressed: () {- Navigator.pop(context);- app.requestMachines();- },- child: const Text('Open Machines'),- ),- ),- ],- if (error != null) ...[- const SizedBox(height: 12),- Text(error!, style: DesktopChrome.metadata()),+ if (error != null) ...[+ const SizedBox(height: 12),+ Text(error!, style: DesktopChrome.metadata()),+ ],],- ],+ ),),- ),- actions: [- if (canAdd)- FilledButton(- onPressed: busy || machineId == null ? null : save,- child: Text(- busy- ? (isConfigure ? 'Saving…' : 'Preparing…')- : (isConfigure ? 'Save' : 'Add machine'),+ actions: [+ if (own.isNotEmpty)+ FilledButton(+ onPressed: busy || !canSave ? null : save,+ child: Text(+ busy+ ? (isConfigure ? 'Saving…' : 'Preparing…')+ : (isConfigure ? 'Save' : 'Add machine'),+ ),+ )+ else+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Close'),),- )- else- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),- ],- );- },+ ],+ );+ },+ ),),),);diff --git a/desktop/lib/super_tabs/pane.dart b/desktop/lib/super_tabs/pane.dartindex 46041b639..739290d85 100644--- a/desktop/lib/super_tabs/pane.dart+++ b/desktop/lib/super_tabs/pane.dart@@ -12,6 +12,7 @@ class SuperPane extends InheritedWidget {this.titles = const {},this.failures = const {},this.onRetry,+ this.onResume,required super.child,});@@ -19,6 +20,7 @@ class SuperPane extends InheritedWidget {final String? title;final Map<(String, String?), String> titles, failures;final VoidCallback? onRetry;+ final void Function(String machineId, String harnessId)? onResume;static SuperPane? maybeOf(BuildContext context) =>context.dependOnInheritedWidgetOfExactType<SuperPane>();@@ -33,5 +35,6 @@ class SuperPane extends InheritedWidget {harnessId != oldWidget.harnessId ||title != oldWidget.title ||titles != oldWidget.titles ||- failures != oldWidget.failures;+ failures != oldWidget.failures ||+ onResume != oldWidget.onResume;}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 3980da2c2..0875f120f 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -198,7 +198,7 @@ class ProjectSidebar extends StatelessWidget {children: [Icon(AppIcons.plus, size: 16),SizedBox(width: 8),- Flexible(child: Text('New project')),+ Flexible(child: Text('New Project')),],),),diff --git a/desktop/lib/super_tabs/project_visibility.dart b/desktop/lib/super_tabs/project_visibility.dartindex 749520854..430b4f848 100644--- a/desktop/lib/super_tabs/project_visibility.dart+++ b/desktop/lib/super_tabs/project_visibility.dart@@ -1,57 +1,99 @@import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_menu.dart';import '../widgets/desktop_chrome.dart';-class ProjectVisibility extends StatelessWidget {+class ProjectVisibility extends StatefulWidget {const ProjectVisibility({super.key,required this.value,required this.onChanged,+ this.disabledReason,});final String value;final ValueChanged<String>? onChanged;+ final String? disabledReason;@override- Widget build(BuildContext context) => MenuAnchor(- menuChildren: [- for (final (id, title, detail) in const [- ('public', 'Public', 'Everyone in this swarm'),- ('private', 'Private', 'Only people you invite to this project'),- ])- MenuItemButton(- onPressed: onChanged == null ? null : () => onChanged!(id),- leadingIcon: Icon(- id == 'private' ? AppIcons.lock : AppIcons.users,- size: 16,- ),- trailingIcon: id == value- ? const Icon(AppIcons.check, size: 16)- : null,- child: Padding(- padding: const EdgeInsets.symmetric(vertical: 4),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Text(title, style: DesktopChrome.control()),- Text(detail, style: DesktopChrome.metadata()),- ],+ State<ProjectVisibility> createState() => _ProjectVisibilityState();+}++class _ProjectVisibilityState extends State<ProjectVisibility> {+ final _menu = MenuController();+ final _focus = FocusNode(debugLabel: 'Project visibility');++ @override+ void dispose() {+ _focus.dispose();+ super.dispose();+ }++ void _open() {+ if (widget.onChanged != null) _menu.open();+ }++ @override+ Widget build(BuildContext context) {+ final width = (MediaQuery.sizeOf(context).width - 32).clamp(0.0, 360.0);+ return MenuAnchor(+ controller: _menu,+ childFocusNode: _focus,+ consumeOutsideTap: true,+ alignmentOffset: Offset(-width, grid.AppControl.menuGap),+ style: grid.AppMenu.style(+ minWidth: width,+ maxWidth: width,+ ).copyWith(alignment: AlignmentDirectional.bottomEnd),+ menuChildren: [+ for (final (id, title, detail) in const [+ ('public', 'Public', 'Everyone in this swarm'),+ ('private', 'Private', 'Only people you invite to this project'),+ ])+ SizedBox(+ width: width,+ child: Tooltip(+ message: detail,+ child: AppMenuItem(+ label: title,+ detail: detail,+ icon: id == 'private' ? AppIcons.lock : AppIcons.users,+ selected: id == widget.value,+ expandLabel: true,+ onPressed: () {+ _menu.close();+ widget.onChanged?.call(id);+ },+ ),),),+ ],+ builder: (context, menu, _) => CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.arrowDown): _open,+ const SingleActivator(LogicalKeyboardKey.arrowUp): _open,+ },+ child: DesktopPill(+ focusNode: _focus,+ label: widget.value == 'private' ? 'Private' : 'Public',+ semanticLabel: 'Project visibility',+ semanticHint: widget.disabledReason,+ icon: widget.value == 'private' ? AppIcons.lock : AppIcons.users,+ menu: true,+ quiet: true,+ textSize: 13,+ tooltip:+ widget.disabledReason ??+ (widget.value == 'private'+ ? 'Only people you invite to this project'+ : 'Everyone in this swarm'),+ onPressed: widget.onChanged == null+ ? null+ : () => menu.isOpen ? menu.close() : _open(),),- ],- builder: (context, menu, _) => DesktopPill(- label: value == 'private' ? 'Private' : 'Public',- semanticLabel: 'Project visibility',- icon: value == 'private' ? AppIcons.lock : AppIcons.users,- capsule: true,- textSize: 13,- tooltip: value == 'private'- ? 'Only invited project members'- : 'Everyone in this swarm',- onPressed: onChanged == null- ? null- : () => menu.isOpen ? menu.close() : menu.open(),- ),- );+ ),+ );+ }}diff --git a/desktop/lib/super_tabs/saved_session.dart b/desktop/lib/super_tabs/saved_session.dartnew file mode 100644index 000000000..373aec530--- /dev/null+++ b/desktop/lib/super_tabs/saved_session.dart@@ -0,0 +1,204 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../shared/theme/app_theme.dart';+import '../shared/widgets/skeleton.dart';+import '../state/app_state.dart';+import '../state/session_tail.dart';+import '../terminal/terminal_text.dart';+import '../widgets/session_tail_view.dart';++/// A stopped agent's saved conversation, without reopening its engine. The+/// ordinary terminal renderer owns any retained buffer and takes precedence.+/// History is an account-owned machine capability, not a Swarm membership grant.+class SuperTabSavedSession extends StatefulWidget {+ const SuperTabSavedSession({+ super.key,+ required this.app,+ required this.machineId,+ required this.harnessId,+ this.onResume,+ });++ final AppNotifier app;+ final String machineId, harnessId;+ final VoidCallback? onResume;++ @override+ State<SuperTabSavedSession> createState() => _SuperTabSavedSessionState();+}++class _SuperTabSavedSessionState extends State<SuperTabSavedSession> {+ final _scroll = ScrollController();+ (String, SessionTailKey)? _identity;+ SessionTails? _tails;++ (String, SessionTailKey)? _authorizedIdentity() {+ final account = widget.app.currentUser?.id;+ final machine = widget.app.stateOf(widget.machineId);+ final agent = machine?.agents+ .where((a) => a.id == widget.harnessId)+ .firstOrNull;+ final session = agent?.sessionId;+ if (account == null ||+ machine == null ||+ machine.belongsToOtherAccount ||+ !widget.app.searchableMachineIds.contains(widget.machineId) ||+ agent?.isStopped != true ||+ session == null ||+ session.isEmpty) {+ return null;+ }+ return (account, (machineId: widget.machineId, sessionId: session));+ }++ @override+ void initState() {+ super.initState();+ widget.app.addListener(_changed);+ _sync();+ }++ @override+ void didUpdateWidget(SuperTabSavedSession oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.app != widget.app) {+ oldWidget.app.removeListener(_changed);+ widget.app.addListener(_changed);+ _tails?.dispose();+ _tails = null;+ _identity = null;+ }+ _sync();+ }++ void _sync() {+ final identity = _authorizedIdentity();+ if (identity == _identity) return;+ _tails?.dispose();+ _tails = null;+ _identity = identity;+ if (identity == null) return;+ // Keep this cache scoped to the exact account and saved session. A late+ // history reply cannot repopulate a cache after sign-out or revoked access.+ final tails = SessionTails((machineId, sessionId, {beforeTurn}) async {+ if (!mounted || _authorizedIdentity() != identity) return null;+ final reply = await widget.app.readSessionTail(+ machineId,+ sessionId,+ beforeTurn: beforeTurn,+ );+ return mounted && _authorizedIdentity() == identity ? reply : null;+ }, capacity: 1);+ _tails = tails;+ tails.addListener(_redraw);+ unawaited(tails.want(identity.$2));+ }++ void _changed() {+ _sync();+ _redraw();+ }++ void _redraw() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ widget.app.removeListener(_changed);+ _tails?.dispose();+ _scroll.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ TerminalFontScope.watch(context);+ final identity = _authorizedIdentity();+ final tails = identity == _identity ? _tails : null;+ final key = identity?.$2;+ final tail = key == null ? null : tails?.read(key);+ final loading =+ tails != null && key != null && tail == null && !tails.unavailable(key);+ final opening = widget.app.pendingAgentRestart(+ widget.machineId,+ widget.harnessId,+ );+ final body = terminalContentStyle(color: AppPalette.textPrimary);+ final muted = terminalContentStyle(color: AppPalette.textSecondary);+ return Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(14, 8, 10, 8),+ child: Row(+ children: [+ Expanded(+ child: Text(+ opening?.busy == true+ ? 'Resuming…'+ : tail != null && tail.rows.isNotEmpty+ ? 'Saved conversation'+ : 'Stopped',+ style: AppType.caption(color: AppPalette.textSecondary),+ ),+ ),+ if (widget.onResume != null)+ TextButton(+ onPressed: opening?.busy == true ? null : widget.onResume,+ child: const Text('Resume'),+ ),+ ],+ ),+ ),+ Expanded(+ child:+ tail != null &&+ tail.rows.isNotEmpty &&+ tails != null &&+ key != null+ ? SelectionArea(+ child: SessionTailView(+ key: ValueKey(identity),+ tail: tail,+ tails: tails,+ tailKey: key,+ controller: _scroll,+ words: const [],+ body: body,+ muted: muted,+ gap: terminalCellSizeOf(context).height,+ padding: const EdgeInsets.fromLTRB(14, 4, 14, 16),+ ),+ )+ : loading+ ? Padding(+ padding: const EdgeInsets.all(14),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ SkeletonText(style: body, widthFactor: .65),+ const SizedBox(height: 12),+ SkeletonText(style: body, widthFactor: .9),+ SkeletonText(style: body, widthFactor: .7),+ ],+ ),+ )+ : Center(+ child: Padding(+ padding: const EdgeInsets.all(20),+ child: Text(+ 'Saved conversation is unavailable on this machine.',+ textAlign: TextAlign.center,+ style: AppType.body(color: AppPalette.textSecondary),+ ),+ ),+ ),+ ),+ ],+ );+ }+}diff --git a/desktop/lib/super_tabs/sharing.dart b/desktop/lib/super_tabs/sharing.dartnew file mode 100644index 000000000..e11fc1e09--- /dev/null+++ b/desktop/lib/super_tabs/sharing.dart@@ -0,0 +1,655 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_icons.dart';+import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_select_field.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/desktop_prompt_surface.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'join_link.dart';+import 'model.dart';++Future<void> showSuperTabSharing(+ BuildContext context,+ SuperTabController controller,+) => showAppDialog<void>(+ context: context,+ builder: (_) => SuperTabDialogScope(+ controller: controller,+ requireWrite: false,+ child: SwarmSharingDialog(controller: controller),+ ),+);++class SwarmSharingDialog extends StatefulWidget {+ const SwarmSharingDialog({super.key, required this.controller});+ final SuperTabController controller;++ @override+ State<SwarmSharingDialog> createState() => _SwarmSharingDialogState();+}++class _SwarmSharingDialogState extends State<SwarmSharingDialog> {+ final _email = TextEditingController();+ final _domain = TextEditingController();+ String _inviteRole = 'collaborator',+ _mode = 'invited',+ _role = 'collaborator';+ bool _loading = true,+ _saving = false,+ _peopleExpanded = false,+ _copied = false;+ String? _sharingError, _emailError;+ Map<String, dynamic>? _settings, _pending;+ Timer? _copyFeedback;+ SuperTabController get c => widget.controller;+ String get _path => '/api/super-tabs/${Uri.encodeComponent(c.tabId)}/sharing';+ bool get _current => mounted && !c.accessRevoked && c.isOwner;+ bool get _busy =>+ _saving || c.saving || c.hasPendingAction || _pending != null;+ Map<String, dynamic> get _access => {+ 'mode': _mode,+ 'role': _role,+ if (_mode == 'domain') 'domain': _domain.text.trim().toLowerCase(),+ };+ bool get _changed {+ if (_settings == null) return false;+ final saved = superTabMap(_settings!['access']);+ return _mode != saved['mode'] ||+ _role != saved['role'] ||+ (_mode == 'domain' && _access['domain'] != saved['domain']);+ }++ bool get _domainValid =>+ _mode != 'domain' ||+ RegExp(r'^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$')+ .hasMatch(_domain.text.trim().toLowerCase());+ String? get _joinUrl {+ final value = _settings?['joinUrl'];+ if (value is! String) return null;+ final link = SwarmJoinLink.parse(value);+ return link?.tabId == c.tabId ? link!.url : null;+ }++ @override+ void initState() {+ super.initState();+ _email.addListener(_edited);+ _domain.addListener(_edited);+ if (c.isOwner) {+ unawaited(_load());+ } else {+ _loading = false;+ _peopleExpanded = true;+ }+ }++ void _edited() {+ if (mounted) setState(() {});+ }++ @override+ void dispose() {+ _copyFeedback?.cancel();+ _email.dispose();+ _domain.dispose();+ super.dispose();+ }++ void _apply(Map<String, dynamic> reply) {+ final access = superTabMap(reply['access']);+ if (reply['revision'] is! num ||+ !const ['invited', 'domain', 'link'].contains(access['mode']) ||+ !const ['collaborator', 'viewer'].contains(access['role']) ||+ (access['mode'] == 'domain' && access['domain'] is! String)) {+ throw const FormatException('Invalid sharing settings');+ }+ _settings = reply;+ _mode = access['mode'] as String;+ _role = access['role'] as String;+ _domain.text = access['domain'] as String? ?? '';+ _copied = false;+ }++ Future<void> _load() async {+ if (!_current) return;+ setState(() {+ _loading = true;+ _sharingError = null;+ });+ try {+ final reply = await c.request('GET', _path);+ if (_current) setState(() => _apply(reply));+ } catch (failure) {+ if (_current) {+ setState(() {+ _sharingError =+ failure is SuperTabFailure && failure.statusCode == 404+ ? 'Sharing links aren’t available on this server yet.'+ : 'Could not load sharing settings. Try again.';+ });+ }+ } finally {+ if (_current) setState(() => _loading = false);+ }+ }++ Future<void> _save({bool rotate = false}) async {+ if (!_current ||+ _saving ||+ c.saving ||+ c.hasPendingAction ||+ _settings == null) {+ return;+ }+ if (_pending == null && !_domainValid) return;+ // Retry the same receipt after an uncertain response, especially for a+ // rotated link. Never create a fresh token merely because its reply was lost.+ _pending ??= {+ 'operationId': superTabOperationId(),+ 'revision': _settings!['revision'],+ 'access': _access,+ if (rotate) 'rotateLink': true,+ };+ setState(() {+ _saving = true;+ _sharingError = null;+ });+ try {+ final reply = await c.request('POST', _path, body: _pending);+ if (!_current) return;+ setState(() {+ _apply(reply);+ _pending = null;+ });+ } catch (failure) {+ if (!_current) return;+ if (failure is SuperTabFailure &&+ failure.statusCode >= 400 &&+ failure.statusCode < 500 &&+ !const {408, 429}.contains(failure.statusCode)) {+ _pending = null;+ if (const {+ 'REVISION_CHANGED',+ 'SHARING_CHANGED',+ }.contains(failure.code)) {+ await _load();+ if (_current) {+ setState(+ () => _sharingError =+ 'Sharing changed. Review the current settings and try again.',+ );+ }+ } else {+ setState(+ () => _sharingError =+ 'Could not change sharing. Check your access and try again.',+ );+ }+ } else {+ setState(+ () => _sharingError =+ 'Could not confirm this change. Retry to check it.',+ );+ }+ } finally {+ if (_current) setState(() => _saving = false);+ }+ }++ Future<void> _invite() async {+ if (!_current || _busy) return;+ final email = _email.text.trim();+ if (!RegExp(r'^[^\s@]+@[^\s@]+\.[^\s@]+$').hasMatch(email)) {+ setState(() => _emailError = 'Enter an email address.');+ return;+ }+ setState(() => _emailError = null);+ final result = await c.command({+ 'type': 'invite.create',+ 'email': email,+ 'role': _inviteRole,+ // Swarm invitations do not depend on the open workgroup or grant private+ // project membership. The backend keeps this legacy landing identifier.+ 'conversationId': 'lead',+ });+ if (result != null && _current) {+ _email.clear();+ setState(() => _peopleExpanded = true);+ }+ }++ Future<void> _copyLink() async {+ final url = _joinUrl;+ if (url == null || _changed || _busy || !_current) return;+ await Clipboard.setData(ClipboardData(text: url));+ if (!_current) return;+ setState(() => _copied = true);+ _copyFeedback?.cancel();+ _copyFeedback = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _copied = false);+ });+ }++ Future<void> _remove(SuperTabPerson person) async {+ final leaving = person.id == c.accountId;+ final confirmed = await showAppDialog<bool>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ requireWrite: false,+ child: AlertDialog(+ title: Text(leaving ? 'Leave Swarm?' : 'Remove ${person.email}?'),+ content: const Text(+ 'Swarm access and agent contributions will be withdrawn. Running harnesses stay on their machines.',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: () => Navigator.pop(context, true),+ child: Text(leaving ? 'Leave' : 'Remove'),+ ),+ ],+ ),+ ),+ );+ if (confirmed != true || !mounted || c.accessRevoked) return;+ final result = await c.command({+ 'type': 'member.remove',+ 'userId': person.id,+ });+ if (result != null && leaving && mounted) Navigator.pop(context);+ }++ Widget _select({+ required Key key,+ required String value,+ required String label,+ required List<SelectOption<String>> options,+ required ValueChanged<String> onChanged,+ bool quiet = false,+ }) {+ final measure = TextPainter(+ text: TextSpan(text: options.first.label, style: DesktopChrome.control()),+ textDirection: Directionality.of(context),+ textScaler: MediaQuery.textScalerOf(context),+ )..layout();+ final width = measure.width + 46;+ measure.dispose();+ return ExcludeFocus(+ excluding: _busy,+ child: IgnorePointer(+ ignoring: _busy,+ child: AppSelectField<String>(+ key: key,+ value: value,+ options: options,+ semanticLabel: label,+ textStyle: DesktopChrome.control(),+ width: quiet ? width : null,+ fillColor: quiet ? Colors.transparent : null,+ selected: quiet ? false : null,+ onChanged: (value) {+ if (!_busy) onChanged(value);+ },+ ),+ ),+ );+ }++ static const _roles = [+ SelectOption(value: 'collaborator', label: 'Can collaborate'),+ SelectOption(value: 'viewer', label: 'Can view'),+ ];++ Widget _people() => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final person in c.snapshot?.people ?? <SuperTabPerson>[])+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(person.email, style: DesktopChrome.text()),+ Text(+ person.role == 'owner'+ ? 'Owner'+ : person.role == 'viewer'+ ? 'Can view'+ : 'Can collaborate',+ style: DesktopChrome.metadata(),+ ),+ ],+ ),+ ),+ if (person.role != 'owner' &&+ (c.isOwner || person.id == c.accountId)) ...[+ const SizedBox(width: 8),+ TextButton(+ onPressed: _busy ? null : () => _remove(person),+ child: Text(person.id == c.accountId ? 'Leave' : 'Remove'),+ ),+ ],+ ],+ ),+ ),+ for (final invite in c.snapshot?.invitations ?? <Map<String, dynamic>>[])+ Padding(+ padding: const EdgeInsets.symmetric(vertical: 8),+ child: Row(+ children: [+ Expanded(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ invite['email'] as String,+ style: DesktopChrome.text(),+ ),+ Text('Invited', style: DesktopChrome.metadata()),+ ],+ ),+ ),+ if (c.isOwner) ...[+ const SizedBox(width: 8),+ TextButton(+ onPressed: _busy+ ? null+ : () => c.command({+ 'type': 'invite.revoke',+ 'inviteId': invite['id'],+ }),+ child: const Text('Revoke'),+ ),+ ],+ ],+ ),+ ),+ ],+ );++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: c,+ builder: (context, _) => Dialog(+ backgroundColor: Colors.transparent,+ elevation: 0,+ shape: DesktopChrome.bareDialogShape,+ child: DesktopDialogSurface(+ child: SizedBox(+ width: 460,+ child: Padding(+ padding: const EdgeInsets.all(24),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ DesktopDialogHeader(+ title: 'Share Swarm',+ padding: EdgeInsets.zero,+ onClose: () => Navigator.pop(context),+ ),+ const SizedBox(height: 16),+ Flexible(+ child: DesktopPromptScrollBody(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (c.isOwner) ...[+ Row(+ children: [+ Expanded(+ child: TextField(+ key: const Key('swarm-invite-email'),+ controller: _email,+ autofocus: true,+ enabled: !_busy,+ keyboardType: TextInputType.emailAddress,+ textInputAction: TextInputAction.send,+ decoration: const InputDecoration(+ hintText: 'Email address',+ ),+ onSubmitted: (_) => _invite(),+ ),+ ),+ const SizedBox(width: 8),+ FilledButton(+ key: const Key('swarm-invite-send'),+ onPressed: _busy || _email.text.trim().isEmpty+ ? null+ : _invite,+ child: const Text('Invite'),+ ),+ ],+ ),+ if (_emailError != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(+ _emailError!,+ style: DesktopChrome.metadata(),+ ),+ ),+ const SizedBox(height: 8),+ Align(+ alignment: Alignment.centerLeft,+ child: _select(+ key: const Key('swarm-invite-role'),+ value: _inviteRole,+ label: 'Invitation access',+ options: _roles,+ quiet: true,+ onChanged: (value) =>+ setState(() => _inviteRole = value),+ ),+ ),+ const SizedBox(height: 24),+ Text(+ 'General access',+ style: DesktopChrome.control(medium: true),+ ),+ const SizedBox(height: 8),+ if (_loading)+ const LinearProgressIndicator()+ else if (_settings != null) ...[+ _select(+ key: const Key('swarm-general-access'),+ value: _mode,+ label: 'General access',+ options: const [+ SelectOption(+ value: 'invited',+ label: 'Invited people',+ ),+ SelectOption(+ value: 'domain',+ label: 'Anyone at a domain',+ ),+ SelectOption(+ value: 'link',+ label: 'Anyone with the link',+ ),+ ],+ onChanged: (value) => setState(() {+ _mode = value;+ _copied = false;+ if (value == 'domain' && _domain.text.isEmpty) {+ final email = c.snapshot!.people+ .where((p) => p.id == c.accountId)+ .firstOrNull+ ?.email;+ if (email != null && email.contains('@')) {+ _domain.text = email.split('@').last;+ }+ }+ }),+ ),+ if (_mode == 'domain') ...[+ const SizedBox(height: 8),+ TextField(+ key: const Key('swarm-sharing-domain'),+ controller: _domain,+ enabled: !_busy,+ keyboardType: TextInputType.url,+ decoration: const InputDecoration(+ hintText: 'example.com',+ ),+ ),+ ],+ if (_mode != 'invited') ...[+ const SizedBox(height: 8),+ Align(+ alignment: Alignment.centerLeft,+ child: _select(+ key: const Key('swarm-sharing-role'),+ value: _role,+ label: 'General access role',+ options: _roles,+ quiet: true,+ onChanged: (value) =>+ setState(() => _role = value),+ ),+ ),+ const SizedBox(height: 8),+ Text(+ 'Private projects stay private.',+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ if (_sharingError != null) ...[+ const SizedBox(height: 8),+ Text(+ _sharingError!,+ style: DesktopChrome.metadata(),+ ),+ if (_settings == null)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: _load,+ child: const Text('Retry'),+ ),+ ),+ ],+ const SizedBox(height: 24),+ ],+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton.icon(+ key: const Key('swarm-sharing-people'),+ style: TextButton.styleFrom(+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+ padding: EdgeInsets.zero,+ ),+ onPressed: () => setState(+ () => _peopleExpanded = !_peopleExpanded,+ ),+ icon: Icon(+ _peopleExpanded+ ? AppIcons.chevronDown+ : AppIcons.chevronRight,+ size: 16,+ ),+ label: const Text('People with access'),+ ),+ ),+ if (_peopleExpanded) _people(),+ if (c.operationError != null)+ Padding(+ padding: const EdgeInsets.only(top: 8),+ child: Text(+ c.operationError!,+ style: DesktopChrome.metadata(),+ ),+ ),+ if (c.hasPendingAction)+ Align(+ alignment: Alignment.centerLeft,+ child: TextButton(+ onPressed: c.saving ? null : c.retry,+ child: const Text('Check pending invitation'),+ ),+ ),+ ],+ ),+ ),+ ),+ const SizedBox(height: 24),+ Wrap(+ alignment: WrapAlignment.spaceBetween,+ crossAxisAlignment: WrapCrossAlignment.center,+ spacing: 8,+ runSpacing: 8,+ children: [+ if (_joinUrl != null)+ TextButton.icon(+ key: const Key('swarm-copy-link'),+ onPressed: _busy || _changed ? null : _copyLink,+ icon: Icon(+ _copied ? AppIcons.check : AppIcons.link2,+ size: 16,+ ),+ label: Text(_copied ? 'Copied' : 'Copy link'),+ )+ else+ const SizedBox.shrink(),+ if (_mode == 'link' && !_changed && _joinUrl != null)+ Tooltip(+ message: 'Replace the link. The previous link will stop working.',+ child: TextButton(+ key: const Key('swarm-reset-link'),+ style: TextButton.styleFrom(+ backgroundColor: Colors.transparent,+ side: BorderSide.none,+ ),+ onPressed: _busy ? null : () => _save(rotate: true),+ child: const Text('Reset link'),+ ),+ ),+ if (_pending != null || _changed)+ FilledButton(+ key: const Key('swarm-sharing-save'),+ onPressed:+ _saving ||+ c.saving ||+ c.hasPendingAction ||+ !_domainValid+ ? null+ : () => _save(),+ child: Text(+ _saving+ ? 'Saving…'+ : _pending != null+ ? 'Retry'+ : 'Save',+ ),+ )+ else+ TextButton(+ onPressed: () => Navigator.pop(context),+ child: const Text('Done'),+ ),+ ],+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 3cda755ae..092cc5864 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -21,6 +21,8 @@ import 'work_details.dart';import 'project_sidebar.dart';import 'project_options.dart';+typedef _ComposerChoice = ({String label, String? detail, VoidCallback choose});+/// The contents of one app tab. Its title stays in the app's existing tab bar./// [terminal] is the existing native pane, with its own controls and input.class SuperTabView extends StatefulWidget {@@ -72,6 +74,8 @@ class _SuperTabViewState extends State<SuperTabView> {final _loadingOlder = <String>{};int _mentionIndex = 0;String? _dismissedMention;+ String? _completionPrefix;+ final _completionKeys = List.generate(6, (_) => GlobalKey());SuperTabController get c => widget.controller;String _agentName(SuperTabAgent agent) =>@@ -89,6 +93,7 @@ class _SuperTabViewState extends State<SuperTabView> {@overridevoid initState() {super.initState();+ _composer.addListener(_composerMoved);c.addListener(_changed);_changed();}@@ -215,9 +220,9 @@ class _SuperTabViewState extends State<SuperTabView> {}Future<void> _send() async {- final mentions = _mentionChoices;- if (mentions.isNotEmpty) {- _chooseMention(mentions[_mentionIndex.clamp(0, mentions.length - 1)]);+ final choices = _completionChoices;+ if (choices.isNotEmpty) {+ choices[_mentionIndex.clamp(0, choices.length - 1)].choose();return;}if (!c.canWrite ||@@ -233,6 +238,138 @@ class _SuperTabViewState extends State<SuperTabView> {if (mounted && result != null) setState(() => _replies.remove(id));}+ void _composerMoved() {+ if (!mounted) return;+ final value = _composer.value;+ final prefix = value.selection.isValid+ ? value.text.substring(0, value.selection.baseOffset)+ : null;+ setState(() {+ if (_completionPrefix != prefix) _mentionIndex = 0;+ _completionPrefix = prefix;+ });+ }++ ({int start, int end, String query})? get _workgroupAtCursor {+ final value = _composer.value;+ if (!value.selection.isValid ||+ !value.selection.isCollapsed ||+ (value.composing.isValid && !value.composing.isCollapsed)) {+ return null;+ }+ final end = value.selection.baseOffset;+ final prefix = value.text.substring(0, end);+ if (prefix == _dismissedMention) return null;+ final match = RegExp(r'(?:^|[\s(])#([^\s#`()]*)$').firstMatch(prefix);+ if (match == null) return null;+ // A reference picker must not interrupt Markdown code or URL fragments.+ String? fence;+ for (final line in prefix.split('\n')) {+ final delimiter = RegExp(r'^ {0,3}(`{3,}|~{3,})').firstMatch(line)?[1];+ if (delimiter == null) continue;+ if (fence == null) {+ fence = delimiter;+ } else if (delimiter[0] == fence[0] && delimiter.length >= fence.length) {+ fence = null;+ }+ }+ if (fence != null) return null;+ int? ticks;+ for (final run in RegExp(+ r'(?<!\\)`+',+ ).allMatches(prefix.split('\n').last)) {+ if (ticks == null) {+ ticks = run[0]!.length;+ } else if (ticks == run[0]!.length) {+ ticks = null;+ }+ }+ if (ticks != null) return null;+ // When editing inside a reference, replace the unfinished token after the+ // caret too, while leaving sentence punctuation and following text intact.+ final continuation = RegExp(r'^[^\s#`()\[\]{},.!?;:]*')+ .firstMatch(value.text.substring(end))![0]!;+ return (+ start: prefix.lastIndexOf('#'),+ end: end + continuation.length,+ query: match[1]!.toLowerCase(),+ );+ }++ List<_ComposerChoice> get _completionChoices {+ if (!c.canWrite || c.selected?.archived != false) return const [];+ final reference = _workgroupAtCursor;+ final snapshot = c.snapshot;+ if (reference != null && snapshot != null) {+ final projectId = c.selected?.projectId;+ final groups = snapshot.conversations+ .where(+ (group) =>+ group.number != null &&+ !snapshot.isProjectLead(group.id) &&+ (group.number.toString().startsWith(reference.query) ||+ group.title.toLowerCase().contains(reference.query)),+ )+ .toList();+ groups.sort((a, b) {+ final active = (a.archived ? 1 : 0).compareTo(b.archived ? 1 : 0);+ if (active != 0) return active;+ final project = (a.projectId == projectId ? 0 : 1).compareTo(+ b.projectId == projectId ? 0 : 1,+ );+ return project != 0 ? project : a.number!.compareTo(b.number!);+ });+ return groups.take(6).map((group) {+ final context = <String>[+ if (group.projectId != projectId)+ snapshot.projectFor(group.id)?.name ?? 'Project',+ if (group.archived) 'Archived',+ ];+ return (+ label: group.label,+ detail: context.isEmpty ? null : context.join(' — '),+ choose: () => _chooseWorkgroup(group),+ );+ }).toList();+ }+ return _mentionChoices+ .map(+ (agent) => (+ label: _agentName(agent),+ detail: '${agent.engine} ${widget.machineName(agent.machineId)}',+ choose: () => _chooseMention(agent),+ ),+ )+ .toList();+ }++ void _chooseWorkgroup(SuperTabConversation group) {+ final at = _workgroupAtCursor;+ if (at == null || group.number == null) return;+ final suffix = _composer.text.substring(at.end);+ final boundary = suffix.startsWith(RegExp(r'[\s)\]}.,!?;:]'));+ final token = '#${group.number}${boundary ? '' : ' '}';+ final text = _composer.text.replaceRange(at.start, at.end, token);+ final caret = at.start + token.length;+ c.setDraft(c.selectedId, text);+ setState(() => _dismissedMention = text.substring(0, caret));+ _composer.value = TextEditingValue(+ text: text,+ selection: TextSelection.collapsed(offset: caret),+ );+ _focus.requestFocus();+ }++ void _moveCompletion(int index) {+ setState(() => _mentionIndex = index);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ final context = _completionKeys[index].currentContext;+ if (mounted && context != null) {+ Scrollable.ensureVisible(context, alignment: .5);+ }+ });+ }+void _closeRoster() {setState(() => _rosterOpen = false);if (!_terminalsVisible) _focus.requestFocus();@@ -530,12 +667,12 @@ class _SuperTabViewState extends State<SuperTabView> {),AppIconButton(key: const ValueKey('super-chat'),- icon: AppIcons.messageSquareText,- size: 20,+ icon: AppIcons.messageSquare,+ size: AppIcons.inlineSize,tooltip: 'Chat',selected: !_terminalsVisible && !_showPullRequests,color: !_terminalsVisible && !_showPullRequests- ? DesktopChrome.accent+ ? DesktopChrome.foreground: DesktopChrome.muted,onPressed: () {setState(() => _showPullRequests = false);@@ -549,11 +686,11 @@ class _SuperTabViewState extends State<SuperTabView> {AppIconButton(key: const ValueKey('super-terminals'),icon: AppIcons.terminal,- size: 20,+ size: AppIcons.inlineSize,tooltip: 'Group terminals (${group?.agentIds.length ?? 0})',selected: _terminalsVisible,color: _terminalsVisible- ? DesktopChrome.accent+ ? DesktopChrome.foreground: DesktopChrome.muted,onPressed: group?.agentIds.isNotEmpty == true? () {@@ -566,11 +703,11 @@ class _SuperTabViewState extends State<SuperTabView> {AppIconButton(key: const ValueKey('super-pull-requests'),icon: AppIcons.gitPullRequest,- size: 20,+ size: AppIcons.inlineSize,tooltip: 'Pull requests',selected: !_terminalsVisible && _showPullRequests,color: !_terminalsVisible && _showPullRequests- ? DesktopChrome.accent+ ? DesktopChrome.foreground: DesktopChrome.muted,onPressed: () {widget.onCloseTerminal?.call();@@ -850,7 +987,7 @@ class _SuperTabViewState extends State<SuperTabView> {? 0: messages.where((message) => message.sequence > newAfter).length;final reply = _replies[c.selectedId];- final mentions = _mentionChoices;+ final choices = _completionChoices;return Column(children: [if (c.error != null)@@ -1049,26 +1186,56 @@ class _SuperTabViewState extends State<SuperTabView> {onTap: () => _openAgent(agent),),),- if (mentions.isNotEmpty)+ if (choices.isNotEmpty)Padding(- padding: const EdgeInsets.symmetric(horizontal: 24),+ padding: const EdgeInsets.fromLTRB(24, 8, 24, 0),child: Material(color: DesktopChrome.surface,- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- for (var i = 0; i < mentions.length; i++)- ListTile(- dense: true,- selected:- i == _mentionIndex.clamp(0, mentions.length - 1),- title: Text(_agentName(mentions[i])),- subtitle: Text(- '${mentions[i].engine} · ${widget.machineName(mentions[i].machineId)}',+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(+ DesktopChrome.controlRadius,+ ),+ side: BorderSide(color: DesktopChrome.rim),+ ),+ clipBehavior: Clip.antiAlias,+ child: ConstrainedBox(+ constraints: BoxConstraints(+ maxHeight: MediaQuery.sizeOf(context).height * .3,+ ),+ child: ListView(+ key: const ValueKey('super-composer-completions'),+ shrinkWrap: true,+ padding: const EdgeInsets.symmetric(vertical: 4),+ children: [+ for (var i = 0; i < choices.length; i++)+ ListTile(+ key: _completionKeys[i],+ dense: true,+ selected:+ i == _mentionIndex.clamp(0, choices.length - 1),+ selectedTileColor: grid.AppSurface.selectedFill,+ selectedColor: DesktopChrome.foreground,+ contentPadding: const EdgeInsets.symmetric(+ horizontal: 16,+ ),+ title: Text(+ choices[i].label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(),+ ),+ subtitle: choices[i].detail == null+ ? null+ : Text(+ choices[i].detail!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ onTap: choices[i].choose,),- onTap: () => _chooseMention(mentions[i]),- ),- ],+ ],+ ),),),),@@ -1080,7 +1247,7 @@ class _SuperTabViewState extends State<SuperTabView> {final composing = _composer.value.composing;if (_focus.hasFocus &&event is KeyDownEvent &&- mentions.isNotEmpty &&+ choices.isNotEmpty &&!keys.isControlPressed &&!keys.isMetaPressed &&!keys.isAltPressed &&@@ -1089,19 +1256,16 @@ class _SuperTabViewState extends State<SuperTabView> {final key = event.logicalKey;if (key == LogicalKeyboardKey.arrowDown ||key == LogicalKeyboardKey.arrowUp) {- setState(- () => _mentionIndex =- (_mentionIndex ++ _moveCompletion(+ (_mentionIndex +(key == LogicalKeyboardKey.arrowDown ? 1 : -1)) %- mentions.length,+ choices.length,);return KeyEventResult.handled;}if (key == LogicalKeyboardKey.tab ||key == LogicalKeyboardKey.enter) {- _chooseMention(- mentions[_mentionIndex.clamp(0, mentions.length - 1)],- );+ choices[_mentionIndex.clamp(0, choices.length - 1)].choose();return KeyEventResult.handled;}if (key == LogicalKeyboardKey.escape) {@@ -1138,7 +1302,7 @@ class _SuperTabViewState extends State<SuperTabView> {child: Padding(padding: const EdgeInsets.fromLTRB(16, 8, 8, 8),child: Row(- crossAxisAlignment: CrossAxisAlignment.end,+ crossAxisAlignment: CrossAxisAlignment.center,children: [Expanded(child: TextField(@@ -1153,9 +1317,13 @@ class _SuperTabViewState extends State<SuperTabView> {: 8,maxLength: 32000,keyboardType: TextInputType.multiline,+ textAlignVertical: TextAlignVertical.center,style: DesktopChrome.text(),decoration: InputDecoration(isDense: true,+ hintStyle: DesktopChrome.text(+ color: DesktopChrome.muted,+ ),contentPadding: const EdgeInsets.symmetric(vertical: 6,),diff --git a/desktop/lib/super_tabs/workspace.dart b/desktop/lib/super_tabs/workspace.dartindex 3bc23a82c..eebde9f3c 100644--- a/desktop/lib/super_tabs/workspace.dart+++ b/desktop/lib/super_tabs/workspace.dart@@ -3,14 +3,13 @@ import 'dart:async';import 'package:flutter/material.dart';import '../shared/widgets/app_dialog.dart';-import '../shared/widgets/app_select_field.dart';import '../state/app_state.dart';import '../state/terminal_pane.dart';-import '../widgets/desktop_chrome.dart';import 'controller.dart';import 'dialog_scope.dart';import 'model.dart';import 'pane.dart';+import 'sharing.dart';import 'view.dart';/// Keeps the app's one native canvas alive in the group's middle area.@@ -37,10 +36,10 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {AppNotifier get app => widget.app;(String, String, String?, String, bool)? _terminalRequest;(String, String, String?, String, bool)? _readyRequest;- // Only Open terminal (Participants or a message) may relaunch a stopped- // member. A restored or revisited selection must not undo `harness close`- // or a person's stop.+ // Navigation never undoes a person's stop. Only the pane's explicit Resume+ // action may restart a saved session, with the Swarm's native context.(String, String)? _resumeRequest;+ (String, String)? _focusRequest;Future<void> _terminalChange = Future.value();final _nativePanes = <TerminalPane>[];final _failures = <(String, String?), String>{};@@ -99,6 +98,8 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {_terminalRequest = request;final resume = _resumeRequest;_resumeRequest = null;+ final focus = _focusRequest;+ _focusRequest = null;bool current() =>mounted &&_terminalRequest == request &&@@ -134,7 +135,7 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}if (current()) {if (tab != null) tab.zoomedPaneId = null;- final focused = agents.where((a) => a.id == resume?.$2).firstOrNull;+ final focused = agents.where((a) => a.id == focus?.$2).firstOrNull;if (focused != null || agents.length == 1) {if ((focused == null? tab?.panes.firstOrNull@@ -310,8 +311,9 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {SuperTabController controller,String tabId,SuperTabAgent agent,- String groupId,- ) {+ String groupId, {+ bool resume = false,+ }) {if (!mounted ||app.activeSwarmId != tabId ||controller.snapshot@@ -323,7 +325,8 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {}controller.select(groupId);_terminalRequest = null;- _resumeRequest = (groupId, agent.id);+ _focusRequest = (groupId, agent.id);+ _resumeRequest = resume ? (groupId, agent.id) : null;controller.selectTerminal(groupId, agent.id);setState(() {});}@@ -441,6 +444,32 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {},failures: Map.of(_failures),onRetry: () => setState(() => _terminalRequest = null),+ onResume: !controller.canWrite+ ? null+ : (machineId, harnessId) {+ if (!controller.canWrite ||+ app.stateOf(machineId)?.belongsToOtherAccount !=+ false) {+ return;+ }+ final agent = controller+ .terminalAgents(controller.selectedId)+ .where(+ (a) =>+ a.machineId == machineId &&+ a.harnessId == harnessId,+ )+ .firstOrNull;+ if (agent != null) {+ _focusAgent(+ controller,+ tab.id,+ agent,+ controller.selectedId,+ resume: true,+ );+ }+ },child: canvas,);return Stack(@@ -490,272 +519,4 @@ class _SuperTabWorkspaceState extends State<SuperTabWorkspace> {Future<void> showSuperTabPeople(BuildContext context,SuperTabController controller,-) => showAppDialog<void>(- context: context,- builder: (_) => SuperTabDialogScope(- controller: controller,- requireWrite: false,- child: _People(controller: controller),- ),-);--class _People extends StatefulWidget {- const _People({required this.controller});- final SuperTabController controller;- @override- State<_People> createState() => _PeopleState();-}--class _PeopleState extends State<_People> {- final _email = TextEditingController();- final _search = TextEditingController();- String _role = 'collaborator';- SuperTabController get c => widget.controller;- @override- void initState() {- super.initState();- _email.addListener(_emailChanged);- }-- void _emailChanged() => setState(() {});- @override- void dispose() {- _email.removeListener(_emailChanged);- _email.dispose();- _search.dispose();- super.dispose();- }-- Future<void> _invite() async {- if (!c.isOwner ||- c.saving ||- c.hasPendingAction ||- _email.text.trim().isEmpty) {- return;- }- final result = await c.command({- 'type': 'invite.create',- 'email': _email.text.trim(),- 'role': _role,- 'conversationId': c.selectedId,- });- if (result != null && mounted) _email.clear();- }-- Future<void> _remove(SuperTabPerson person) async {- final yes = await showAppDialog<bool>(- context: context,- builder: (context) => SuperTabDialogScope(- controller: c,- requireWrite: false,- child: AlertDialog(- title: Text(- person.id == c.accountId- ? 'Leave Swarm?'- : 'Remove ${person.email}?',- ),- content: const Text(- 'Their access and agent contributions will be withdrawn. Running harnesses stay on their machines.',- ),- actions: [- TextButton(- onPressed: () => Navigator.pop(context, false),- child: const Text('Cancel'),- ),- FilledButton(- onPressed: () => Navigator.pop(context, true),- child: Text(person.id == c.accountId ? 'Leave' : 'Remove'),- ),- ],- ),- ),- );- if (yes != true) return;- final result = await c.command({- 'type': 'member.remove',- 'userId': person.id,- });- if (result != null && person.id == c.accountId && mounted) {- Navigator.pop(context);- }- }-- @override- Widget build(BuildContext context) => ListenableBuilder(- listenable: c,- builder: (context, _) {- if (c.accessRevoked) {- return AlertDialog(- content: Text(c.error ?? 'This Swarm is no longer available.'),- actions: [- TextButton(- onPressed: () => Navigator.pop(context),- child: const Text('Close'),- ),- ],- );- }- final query = _search.text.trim().toLowerCase();- final people =- c.snapshot?.people- .where((p) => p.email.toLowerCase().contains(query))- .toList() ??- [];- return Dialog(- backgroundColor: Colors.transparent,- elevation: 0,- shape: DesktopChrome.bareDialogShape,- child: DesktopDialogSurface(- child: SizedBox(- width: 460,- height: 520,- child: Padding(- padding: const EdgeInsets.all(24),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- DesktopDialogHeader(- title: 'People',- padding: EdgeInsets.zero,- onClose: () => Navigator.pop(context),- ),- if (c.isOwner) ...[- const SizedBox(height: 12),- TextField(- controller: _email,- autofocus: true,- decoration: const InputDecoration(- hintText: 'Email address',- ),- onSubmitted: (_) => _invite(),- ),- Row(- children: [- Expanded(- child: ExcludeFocus(- excluding: c.saving || c.hasPendingAction,- child: ExcludeSemantics(- excluding: c.saving || c.hasPendingAction,- child: IgnorePointer(- ignoring: c.saving || c.hasPendingAction,- child: AppSelectField<String>(- value: _role,- semanticLabel: 'Invitation access',- textStyle: DesktopChrome.control(),- options: const [- SelectOption(- value: 'collaborator',- label: 'Can collaborate',- detail: 'Read accessible projects and send messages to their agents.',- ),- SelectOption(- value: 'viewer',- label: 'Can view',- detail: 'Read accessible projects without sending messages or changing work.',- ),- ],- onChanged: (role) {- if (!c.saving && !c.hasPendingAction) {- setState(() => _role = role);- }- },- ),- ),- ),- ),- ),- const SizedBox(width: 12),- FilledButton(- onPressed:- c.saving ||- c.hasPendingAction ||- _email.text.trim().isEmpty- ? null- : _invite,- child: const Text('Invite'),- ),- ],- ),- Text(- 'They’ll find the invitation in Harness Settings → Tab invites.',- style: DesktopChrome.metadata(),- ),- ],- if (c.operationError != null)- Padding(- padding: const EdgeInsets.symmetric(vertical: 8),- child: Text(c.operationError!),- ),- if (c.hasPendingAction)- TextButton(- onPressed: c.saving ? null : c.retry,- child: const Text('Check pending action'),- ),- const SizedBox(height: 12),- TextField(- controller: _search,- decoration: const InputDecoration(- hintText: 'Find a person',- ),- onChanged: (_) => setState(() {}),- ),- const SizedBox(height: 8),- Expanded(- child: ListView(- children: [- for (final person in people)- ListTile(- contentPadding: EdgeInsets.zero,- title: Text(person.email),- subtitle: Text(- person.role == 'owner'- ? 'Owner'- : person.role == 'viewer'- ? 'Viewer'- : 'Collaborator',- style: DesktopChrome.metadata(),- ),- trailing:- person.role != 'owner' &&- (c.isOwner || person.id == c.accountId)- ? TextButton(- onPressed: c.saving- ? null- : () => _remove(person),- child: Text(- person.id == c.accountId- ? 'Leave'- : 'Remove',- ),- )- : null,- ),- for (final invitation- in c.snapshot?.invitations ??- <Map<String, dynamic>>[])- ListTile(- contentPadding: EdgeInsets.zero,- title: Text(invitation['email'] as String),- subtitle: const Text('Invited'),- trailing: TextButton(- onPressed: c.saving- ? null- : () => c.command({- 'type': 'invite.revoke',- 'inviteId': invitation['id'],- }),- child: const Text('Revoke'),- ),- ),- ],- ),- ),- ],- ),- ),- ),- ),- );- },- );-}+) => showSuperTabSharing(context, controller);diff --git a/desktop/lib/widgets/new_harness_form.dart b/desktop/lib/widgets/new_harness_form.dartindex d6c8122ff..09af1ca83 100644--- a/desktop/lib/widgets/new_harness_form.dart+++ b/desktop/lib/widgets/new_harness_form.dart@@ -1,7 +1,5 @@import 'dart:async';-import '../super_tabs/project_visibility.dart';-import 'dart:convert';import 'dart:math' as math;@@ -20,6 +18,7 @@ import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../state/new_harness.dart';import '../state/device_form.dart';+import '../super_tabs/project_visibility.dart';import 'box_chrome.dart' show kTerminalCornerRadius, terminalPaneBorder;import 'dsh_install_panel.dart' show describeInstallFailure;import 'desktop_chrome.dart';@@ -1888,20 +1887,6 @@ class NewHarnessFormState extends State<NewHarnessForm> {),),),- if (box.integration?.projectVisibility case final visibility?)- FocusTraversalOrder(- order: const NumericFocusOrder(3.5),- child: ProjectVisibility(- key: const ValueKey('new-harness-project-visibility'),- value: visibility,- onChanged:- box.locked || box.integration!.projectVisibilityLocked- ? null- : (value) => setState(- () => box.integration!.projectVisibility = value,- ),- ),- ),],),),@@ -1967,37 +1952,49 @@ class NewHarnessFormState extends State<NewHarnessForm> {if (attachments == null) {return Align(alignment: Alignment.centerRight,- child: _desktopLaunchActions(),+ child: _desktopLaunchActions(includeProjectVisibility: true),);}- return Row(- crossAxisAlignment: CrossAxisAlignment.end,- children: [- Expanded(- // Right after the task it sits under, so Start stays last.- child: FocusTraversalOrder(- order: const NumericFocusOrder(4.5),- child: Row(- crossAxisAlignment: CrossAxisAlignment.end,- children: [- NewHarnessAttachButton(- attachments: attachments,- enabled: !box.locked,- ),- const SizedBox(width: 6),- Expanded(- child: NewHarnessAttachmentChips(+ return LayoutBuilder(+ builder: (context, constraints) => Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Expanded(+ // Right after the task it sits under, so Start stays last.+ child: FocusTraversalOrder(+ order: const NumericFocusOrder(4.5),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ NewHarnessAttachButton(attachments: attachments,enabled: !box.locked,),- ),- ],+ const SizedBox(width: 6),+ Expanded(+ child: NewHarnessAttachmentChips(+ attachments: attachments,+ enabled: !box.locked,+ ),+ ),+ ],+ ),),),- ),- const SizedBox(width: 12),- _desktopLaunchActions(),- ],+ const SizedBox(width: 12),+ ConstrainedBox(+ constraints: BoxConstraints(+ // Keep the attachment target reachable when enlarged text+ // makes the action group wrap inside a narrow composer.+ maxWidth: math.max(+ 0,+ constraints.maxWidth - grid.AppControl.height - 6 - 12,+ ),+ ),+ child: _desktopLaunchActions(includeProjectVisibility: true),+ ),+ ],+ ),);}@@ -2253,12 +2250,33 @@ class NewHarnessFormState extends State<NewHarnessForm> {child: const Text('Use the existing folder'),);- Widget _desktopLaunchActions() => Wrap(+ Widget _desktopLaunchActions({bool includeProjectVisibility = false}) => Wrap(spacing: 8,+ runSpacing: 8,+ alignment: WrapAlignment.end,crossAxisAlignment: WrapCrossAlignment.center,children: [if (box.canCancelPending) _cancelPendingButton(),if (box.existingFolder != null) _useExistingFolderButton(),+ if (includeProjectVisibility &&+ box.integration?.projectVisibility != null)+ FocusTraversalOrder(+ order: const NumericFocusOrder(9.95),+ child: ProjectVisibility(+ key: const ValueKey('new-harness-project-visibility'),+ value: box.integration!.projectVisibility!,+ disabledReason: box.integration!.projectVisibilityLocked+ ? 'Project creation has started. Visibility is fixed for this request.'+ : box.locked+ ? 'Finish the current request before changing visibility.'+ : null,+ onChanged: box.locked || box.integration!.projectVisibilityLocked+ ? null+ : (value) => setState(+ () => box.integration!.projectVisibility = value,+ ),+ ),+ ),_desktopStartButton(),],);@@ -2325,7 +2343,7 @@ class NewHarnessFormState extends State<NewHarnessForm> {),const SizedBox(width: 8),],- Text(label),+ Flexible(child: Text(label)),],),),diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dartindex a2e85a857..097d52792 100644--- a/desktop/lib/widgets/pane_grid.dart+++ b/desktop/lib/widgets/pane_grid.dart@@ -1,4 +1,5 @@import '../super_tabs/pane.dart';+import '../super_tabs/saved_session.dart';import '../sharing/shared_harness_panel.dart';import 'dart:async';@@ -1761,12 +1762,28 @@ class _PaneContent extends StatelessWidget {pane.machineId,wantedAgentId!,);+ final resume = superPane?.onResume;+ final canResume = resume != null && !machine.belongsToOtherAccount;notice = terminalNotice(label: opening?.busy == true ? 'Opening' : 'Stopped',icon: AppIcons.terminal,- detail: opening?.result?.error ?? 'Open to continue your saved conversation. Retained output is read only.',- actionLabel: opening?.busy == true ? null : 'Open',- onAction: () => notifier.openSavedPane(pane.id).ignore(),+ detail:+ opening?.result?.error ??+ (superPane != null+ ? 'This agent is stopped. Retained output is read only.'+ : 'Open to continue your saved conversation. Retained output is read only.'),+ actionLabel: opening?.busy == true+ ? null+ : superPane == null+ ? 'Open'+ : canResume+ ? 'Resume'+ : null,+ onAction: superPane == null+ ? () => notifier.openSavedPane(pane.id).ignore()+ : canResume+ ? () => resume(pane.machineId, wantedAgentId)+ : null,banner: true,);} else if (agent != null && agent.launchState == 'held') {@@ -2015,6 +2032,31 @@ class _PaneContent extends StatelessWidget {);}if (agent?.isStopped == true) {+ if (superPane != null) {+ final resume = superPane.onResume;+ return Column(+ children: [+ _PaneHeader(+ title:+ superPane.titleFor(pane.machineId, wantedAgentId) ??+ agentName,+ activity: activityMark,+ ),+ Divider(height: 1, color: AppColors.border),+ Expanded(+ child: SuperTabSavedSession(+ key: ValueKey((pane.machineId, wantedAgentId)),+ app: notifier,+ machineId: pane.machineId,+ harnessId: wantedAgentId,+ onResume: resume != null && !machine.belongsToOtherAccount+ ? () => resume(pane.machineId, wantedAgentId)+ : null,+ ),+ ),+ ],+ );+ }final opening = notifier.pendingAgentRestart(pane.machineId,wantedAgentId,diff --git a/desktop/test/super_tab_completions_test.dart b/desktop/test/super_tab_completions_test.dartnew file mode 100644index 000000000..bcbdf4696--- /dev/null+++ b/desktop/test/super_tab_completions_test.dart@@ -0,0 +1,235 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++void main() {+ final composer = find.byKey(const ValueKey('super-message-composer'));+ final picker = find.byKey(const ValueKey('super-composer-completions'));++ Future<(ConversationServer, SuperTabController)> show(+ WidgetTester tester, {+ Brightness brightness = Brightness.dark,+ double scale = 1,+ }) async {+ final server = ConversationServer();+ (server.state['conversations'] as List)[1]['number'] = 12;+ (server.state['conversations'] as List).addAll(<Map<String, dynamic>>[+ {...conversationFixture('sync', 'Sync reliability'), 'number': 13},+ {+ ...conversationFixture('done', 'Offline prototype'),+ 'number': 2,+ 'archived': true,+ },+ ]);+ final c = server.controller();+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: child!,+ ),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return (server, c);+ }++ testWidgets(+ 'workgroups filter by name and number, insert without sending, then send normally',+ (tester) async {+ final (server, c) = await show(tester);+ await tester.enterText(composer, 'Please review #off');+ await tester.pump();+ expect(+ find.descendant(of: picker, matching: find.text('#12 Offline editing')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: picker,+ matching: find.text('#13 Sync reliability'),+ ),+ findsNothing,+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(c.draft('lead'), 'Please review #12 ');+ expect(server.posts, isEmpty);+ expect(picker, findsNothing);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(+ (server.posts.single['command'] as Map)['text'],+ 'Please review #12',+ );+ await tester.enterText(composer, '#13');+ await tester.pump();+ await tester.tap(+ find.descendant(+ of: picker,+ matching: find.text('#13 Sync reliability'),+ ),+ );+ await tester.pumpAndSettle();+ expect(c.draft('lead'), '#13 ');+ },+ );++ testWidgets('arrow keys and Tab select while Escape dismisses the picker', (+ tester,+ ) async {+ final (server, c) = await show(tester);+ await tester.enterText(composer, '#');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);+ await tester.pumpAndSettle();+ expect(c.draft('lead'), '#13 ');+ expect(server.posts, isEmpty);+ await tester.enterText(composer, '#12');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(picker, findsNothing);+ expect(c.draft('lead'), '#12');+ await tester.pump(const Duration(milliseconds: 250));+ });++ testWidgets(+ 'moving the caret into a reference preserves the following text',+ (tester) async {+ final (server, c) = await show(tester);+ for (final punctuation in ['', ',']) {+ await tester.enterText(+ composer,+ 'Review #offline$punctuation then reply.',+ );+ await tester.pump();+ expect(picker, findsNothing);+ final controller = tester.widget<TextField>(composer).controller!;+ controller.selection = const TextSelection.collapsed(offset: 11);+ await tester.pump();+ expect(picker, findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);+ await tester.pumpAndSettle();+ expect(c.draft('lead'), 'Review #12$punctuation then reply.');+ expect(controller.selection.baseOffset, 10);+ expect(picker, findsNothing);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(+ (server.posts.last['command'] as Map)['text'],+ 'Review #12$punctuation then reply.',+ );+ }+ await tester.pump(const Duration(milliseconds: 250));+ },+ );++ testWidgets('Shift Enter keeps the draft instead of accepting a reference', (+ tester,+ ) async {+ final (server, c) = await show(tester);+ await tester.enterText(composer, '#off');+ await tester.pump();+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);+ await tester.pump(const Duration(milliseconds: 250));+ expect(c.draft('lead'), '#off');+ expect(server.posts, isEmpty);+ // The native text-input client delivers the newline separately from its+ // key event. The completion handler must leave that edit untouched.+ await tester.showKeyboard(composer);+ tester.testTextInput.updateEditingValue(+ const TextEditingValue(+ text: '#off\n',+ selection: TextSelection.collapsed(offset: 5),+ ),+ );+ await tester.pump(const Duration(milliseconds: 250));+ expect(c.draft('lead'), '#off\n');+ expect(server.posts, isEmpty);+ expect(picker, findsNothing);+ });++ testWidgets(+ 'code, URL fragments, IME and selections do not trigger references',+ (tester) async {+ await show(tester);+ for (final text in [+ 'https://example.com/#12',+ '`use #12',+ '```text\n#12',+ '~~~\n#12',+ ]) {+ await tester.enterText(composer, text);+ await tester.pump();+ expect(picker, findsNothing, reason: text);+ }+ final controller = tester.widget<TextField>(composer).controller!;+ controller.value = const TextEditingValue(+ text: '#12',+ selection: TextSelection.collapsed(offset: 3),+ composing: TextRange(start: 1, end: 3),+ );+ await tester.pump();+ expect(picker, findsNothing);+ controller.value = const TextEditingValue(+ text: '#12',+ selection: TextSelection(baseOffset: 0, extentOffset: 3),+ );+ await tester.pump();+ expect(picker, findsNothing);+ await tester.pump(const Duration(milliseconds: 250));+ },+ );++ testWidgets('access revocation removes open suggestions', (tester) async {+ final (_, c) = await show(tester);+ await tester.enterText(composer, '#');+ await tester.pump();+ expect(picker, findsOneWidget);+ c.revokeAccess('Access removed');+ await tester.pumpAndSettle();+ expect(picker, findsNothing);+ expect(tester.widget<TextField>(composer).enabled, isFalse);+ });++ for (final brightness in Brightness.values) {+ testWidgets('reference picker stays bounded at 2x in ${brightness.name}', (+ tester,+ ) async {+ await tester.binding.setSurfaceSize(const Size(660, 480));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await show(tester, brightness: brightness, scale: 2);+ await tester.enterText(composer, '#');+ await tester.pumpAndSettle();+ expect(picker, findsOneWidget);+ expect(tester.takeException(), isNull);+ expect(+ tester.getRect(picker).bottom,+ lessThanOrEqualTo(tester.getRect(composer).top),+ );+ });+ }+}diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dartindex f36cdc306..562834307 100644--- a/desktop/test/super_tab_launch_test.dart+++ b/desktop/test/super_tab_launch_test.dart@@ -37,6 +37,7 @@ class SuperTabFixtureConnection extends WsConn {final joins = <Map<String, dynamic>>[];bool loseCreate = false, loseJoin = false;bool failNative = false;+ WsRequestFailure? backendFailure;bool failResume = false;bool nativeSurface = false;bool failFiles = false, failCreation = false, changeAccountOnUpload = false;@@ -123,6 +124,9 @@ class SuperTabFixtureConnection extends WsConn {};}if (type == 'super_tabs') {+ if (payload['action'] == 'backend' && backendFailure != null) {+ throw backendFailure!;+ }if (payload['action'] == 'wake') return {'ok': true};if (payload['action'] == 'prepareContribution') {return {@@ -392,7 +396,7 @@ void main() {f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');final localId = f.app.activeSwarmId;final box = await f.box(newProject: true);- expect(box.actionLabel, 'New project');+ expect(box.actionLabel, 'New Project');box.integration!.projectVisibility = 'private';expect(await box.create(), NewHarnessOutcome.created, reason: box.error);expect(f.app.swarms, hasLength(1));@@ -418,6 +422,66 @@ void main() {},);+ test(+ 'an unsupported project request keeps its draft and unlocks visibility',+ () async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Company');+ final box = await f.box(newProject: true);+ f.connection.backendFailure = const WsRequestFailure(+ responseType: 'super_tabs_result',+ code: 'VALIDATION_ERROR',+ detail: 'command.type: Invalid discriminator value. Expected machine.contribute',+ payload: {'status': 400},+ );+ final task = box.task;+ expect(await box.create(), NewHarnessOutcome.failed);+ expect(box.error, contains('Swarm service needs an update'));+ expect(box.error, isNot(contains('discriminator')));+ expect(box.task, task);+ expect(box.integration!.projectVisibilityLocked, isFalse);+ expect(f.connection.calls.where((c) => c.$1 == 'agent_create'), isEmpty);++ f.connection.backendFailure = null;+ box.integration!.projectVisibility = 'private';+ expect(await box.create(), NewHarnessOutcome.created, reason: box.error);+ expect(+ f.app.superTabs.peek(tabId)!.snapshot!.projects.last.isPrivate,+ isTrue,+ );+ expect(+ f.connection.calls.where((c) => c.$1 == 'agent_create'),+ hasLength(1),+ );+ },+ );++ test(+ 'Swarm websocket refusals preserve authorization status and detail',+ () async {+ final f = SuperTabLaunchFixture();+ f.connection.backendFailure = const WsRequestFailure(+ responseType: 'super_tabs_result',+ code: 'FORBIDDEN',+ detail: 'You no longer have access to this Swarm.',+ payload: {'status': 403},+ );+ await expectLater(+ f.app.superTabMachineRequest('m', {'action': 'backend'}),+ throwsA(+ isA<SuperTabFailure>()+ .having((e) => e.code, 'code', 'FORBIDDEN')+ .having((e) => e.statusCode, 'status', 403)+ .having(+ (e) => e.message,+ 'message',+ 'You no longer have access to this Swarm.',+ ),+ ),+ );+ },+ );+test('a lost project creation reply keeps its visibility and original receipt',() async {diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dartindex d7ca07112..16cbccf1d 100644--- a/desktop/test/super_tab_machines_test.dart+++ b/desktop/test/super_tab_machines_test.dart@@ -1,20 +1,34 @@+import 'dart:ui' show PointerDeviceKind;+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/state/app_state.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 'package:harness/shared/theme/app_theme.dart' as grid;import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;Future<void> _openAddMachineDialog(WidgetTester tester,SuperTabLaunchFixture f,- dynamic c,-) async {+ dynamic c, {+ Brightness brightness = Brightness.dark,+ double textScale = 1,+}) async {+ final previousBrightness = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previousBrightness);await tester.pumpWidget(MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(textScale)),+ child: child!,+ ),home: Scaffold(body: SizedBox(width: 300,@@ -33,6 +47,9 @@ Future<void> _openAddMachineDialog(await tester.pumpAndSettle();}+final _picker = find.byKey(const ValueKey('swarm-machine-picker'));+Finder _option(String id) => find.byKey(ValueKey('swarm-machine-option-$id'));+void main() {test('shared repository metadata excludes embedded credentials', () {expect(@@ -83,7 +100,7 @@ void main() {await tester.pumpAndSettle();await tester.tap(find.byTooltip('Add machine'));await tester.pumpAndSettle();- expect(find.byType(AppSelectField<String>), findsOneWidget);+ expect(_picker, findsOneWidget);expect(find.text('This Mac (${f.app.stateOf('m')!.machine.displayName})'),findsOneWidget,@@ -142,7 +159,7 @@ void main() {await c.refresh();await _openAddMachineDialog(tester, f, c);- expect(find.byType(AppSelectField<String>), findsOneWidget);+ expect(_picker, findsOneWidget);expect(find.text('This Mac (${f.app.stateOf('m')!.machine.displayName})'),findsOneWidget,@@ -160,7 +177,7 @@ void main() {);testWidgets(- 'Add machine: only This Mac, already in the tab, offers no picker and no Add machine button',+ 'Add machine: already-contributed machines remain visible but cannot be added again',(tester) async {final f = SuperTabLaunchFixture();f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');@@ -171,20 +188,159 @@ void main() {await c.refresh();await _openAddMachineDialog(tester, f, c);- expect(find.byType(AppSelectField<String>), findsNothing);- expect(find.widgetWithText(FilledButton, 'Add machine'), findsNothing);+ expect(_picker, findsOneWidget);+ expect(find.text('Choose a machine'), findsOneWidget);+ expect(+ tester+ .widget<FilledButton>(+ find.widgetWithText(FilledButton, 'Add machine'),+ )+ .onPressed,+ isNull,+ );+ expect(find.textContaining('Already in this tab:'), findsNothing);+ await tester.tap(_picker);+ await tester.pumpAndSettle();+ expect(tester.widget<MenuItemButton>(_option('m')).onPressed, isNull);+ expect(find.byTooltip('Already in this Swarm'), findsOneWidget);+ await tester.tap(_option('m'));+ await tester.pumpAndSettle();+ expect(find.text('Choose a machine'), findsOneWidget);+ expect(f.connection.server.posts, isEmpty);++ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );++ testWidgets(+ 'Add machine: an available owned machine is selected ahead of an already-contributed one',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.server.state['machines'] = [+ {'machineId': 'm', 'contributorId': 'owner'},+ ];+ const other = Machine(+ machineId: 'm2',+ authMode: MachineAuthMode.remote,+ name: 'Other Mac',+ );+ f.app.machines = [...f.app.machines, other];+ f.app.machineStates['m2'] = MachineState(other)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _openAddMachineDialog(tester, f, c);++ expect(_picker, findsOneWidget);+ expect(find.text('Other Mac'), findsOneWidget);expect(- find.text(- 'This Mac (${f.app.stateOf('m')!.machine.displayName}) is already in this tab.',+ find.text('This Mac (${f.app.stateOf('m')!.machine.displayName})'),+ findsNothing,+ );+ expect(find.textContaining('Already in this tab:'), findsNothing);+ final button = tester.widget<FilledButton>(+ find.widgetWithText(FilledButton, 'Add machine'),+ );+ expect(button.onPressed, isNotNull);+ await tester.tap(_picker);+ await tester.pumpAndSettle();+ expect(tester.widget<MenuItemButton>(_option('m')).onPressed, isNull);+ expect(tester.widget<MenuItemButton>(_option('m2')).onPressed, isNotNull);++ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );++ testWidgets(+ 'Add machine: offline and unlinked owned machines are disabled with status tooltips; shared machines stay excluded',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ const offline = Machine(+ machineId: 'm3',+ authMode: MachineAuthMode.remote,+ name: 'macbok test local',+ );+ f.app.machines = [...f.app.machines, offline];+ f.app.machineStates['m3'] = MachineState(offline)+ ..nodeOnline = false+ ..connectionStatus = ConnectionStatus.disconnected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ const unlinked = Machine(+ machineId: 'm4',+ authMode: MachineAuthMode.remote,+ name: 'Studio Mac',+ );+ const sharedHarness = Machine(+ machineId: 'm5',+ authMode: MachineAuthMode.remote,+ name: 'Another account’s harness',+ isShared: true,+ );+ const sharedMachine = Machine(+ machineId: 'm6',+ authMode: MachineAuthMode.remote,+ name: 'Another account’s computer',+ machineShare: MachineShare(+ ownerName: 'Another owner',+ ownerEmail: '[email protected]',+ via: 'email',+ added: true,),+ );+ for (final machine in [unlinked, sharedHarness, sharedMachine]) {+ f.app.machineStates[machine.machineId] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected;+ }+ f.app.machineStates['m4']!.needsLink = true;+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _openAddMachineDialog(tester, f, c);++ expect(_picker, findsOneWidget);+ expect(find.text('macbok test local'), findsNothing);+ expect(find.textContaining('Offline:'), findsNothing);+ expect(find.textContaining('Not linked:'), findsNothing);+ await tester.tap(_picker);+ await tester.pumpAndSettle();+ expect(tester.widget<MenuItemButton>(_option('m3')).onPressed, isNull);+ expect(tester.widget<MenuItemButton>(_option('m4')).onPressed, isNull);+ expect(_option('m5'), findsNothing);+ expect(_option('m6'), findsNothing);+ const offlineHint = 'Offline. Open Harness on this computer to add it.';+ expect(find.byTooltip(offlineHint), findsOneWidget);+ expect(+ find.byTooltip('Not linked. Link this computer from Machines.'),findsOneWidget,);+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);+ await mouse.addPointer(location: Offset.zero);+ await mouse.moveTo(tester.getCenter(find.byTooltip(offlineHint)));+ await tester.pumpAndSettle(const Duration(milliseconds: 800));+ expect(find.text(offlineHint), findsOneWidget);+ await tester.tap(_option('m3'));+ await tester.pumpAndSettle();expect(- find.textContaining('install Harness on it and sign in'),+ find.descendant(+ of: _picker,+ matching: find.text(+ 'This Mac (${f.app.stateOf('m')!.machine.displayName})',+ ),+ ),findsOneWidget,);- expect(find.widgetWithText(TextButton, 'Close'), findsOneWidget);- expect(find.widgetWithText(TextButton, 'Open Machines'), findsOneWidget);+ expect(f.connection.server.posts, isEmpty);+ await mouse.removePointer();await tester.pumpWidget(const SizedBox());await c.flush();@@ -193,75 +349,137 @@ void main() {},);- testWidgets('Add machine: with This Mac already in the tab, the picker offers only another online own '- 'machine, preselected, and keeps Add machine enabled', (tester) async {- final f = SuperTabLaunchFixture();- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');- f.connection.server.state['machines'] = [- {'machineId': 'm', 'contributorId': 'owner'},- ];- const other = Machine(- machineId: 'm2',- authMode: MachineAuthMode.remote,- name: 'Other Mac',- );- f.app.machines = [...f.app.machines, other];- f.app.machineStates['m2'] = MachineState(other)- ..nodeOnline = true- ..connectionStatus = ConnectionStatus.connected- ..agentLoadStatus = AgentLoadStatus.loaded;- final c = await f.app.superTabs.open(tabId);- await c.refresh();- await _openAddMachineDialog(tester, f, c);+ testWidgets(+ 'Machine picker skips unavailable rows with the keyboard and returns focus to the field',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ for (final (id, name, online) in [+ ('m2', 'Offline Mac', false),+ ('m3', 'Studio Mac', true),+ ]) {+ final machine = Machine(+ machineId: id,+ authMode: MachineAuthMode.remote,+ name: name,+ );+ f.app.machineStates[id] = MachineState(machine)+ ..nodeOnline = online+ ..connectionStatus = online+ ? ConnectionStatus.connected+ : ConnectionStatus.disconnected;+ }+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _openAddMachineDialog(tester, f, c);+ await tester.tap(_picker);+ await tester.pumpAndSettle();+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(+ find.descendant(of: _picker, matching: find.text('Studio Mac')),+ findsOneWidget,+ );+ expect(f.connection.server.posts, isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pumpAndSettle();+ expect(_option('m2'), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(AlertDialog), findsOneWidget);+ expect(_option('m2'), findsNothing);+ expect(tester.widget<TextButton>(_picker).focusNode!.hasFocus, isTrue);+ expect(tester.takeException(), isNull);- expect(find.byType(AppSelectField<String>), findsOneWidget);- expect(find.text('Other Mac'), findsOneWidget);- expect(- find.text('This Mac (${f.app.stateOf('m')!.machine.displayName})'),- findsNothing,- );- expect(find.textContaining('Already in this tab:'), findsOneWidget);- final button = tester.widget<FilledButton>(- find.widgetWithText(FilledButton, 'Add machine'),- );- expect(button.onPressed, isNotNull);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );- await tester.pumpWidget(const SizedBox());- await c.flush();- f.app.superTabs.dispose();- await tester.pump();- });+ testWidgets(+ 'A machine that goes offline while the form is open cannot be submitted',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _openAddMachineDialog(tester, f, c);+ f.app.machineStates['m']!.nodeOnline = false;+ await tester.tap(find.widgetWithText(FilledButton, 'Add machine'));+ await tester.pumpAndSettle();+ expect(f.connection.server.posts, isEmpty);+ expect(+ f.connection.calls.where(+ (call) =>+ call.$1 == 'super_tabs' &&+ call.$2['action'] == 'prepareContribution',+ ),+ isEmpty,+ );+ expect(find.byType(AlertDialog), findsOneWidget);- testWidgets('Add machine: an offline own machine is not offered in the picker and is named as offline '- 'with a next step', (tester) async {- final f = SuperTabLaunchFixture();- f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');- const offline = Machine(- machineId: 'm3',- authMode: MachineAuthMode.remote,- name: 'macbok test local',- );- f.app.machines = [...f.app.machines, offline];- f.app.machineStates['m3'] = MachineState(offline)- ..nodeOnline = false- ..connectionStatus = ConnectionStatus.disconnected- ..agentLoadStatus = AgentLoadStatus.loaded;- final c = await f.app.superTabs.open(tabId);- await c.refresh();- await _openAddMachineDialog(tester, f, c);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );- expect(find.byType(AppSelectField<String>), findsOneWidget);- expect(find.text('macbok test local'), findsNothing);- expect(- find.text('Offline: macbok test local. Start Harness on it to add it.'),- findsOneWidget,- );+ for (final brightness in Brightness.values) {+ testWidgets(+ 'Machine picker handles unavailable long names at 2x text in ${brightness.name}',+ (tester) async {+ tester.view.physicalSize = const Size(540, 800);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.app.machineStates['m']!.nodeOnline = false;+ const unlinked = Machine(+ machineId: 'studio',+ authMode: MachineAuthMode.remote,+ name: 'Design Studio’s MacBook Pro with a long custom machine name',+ );+ f.app.machineStates['studio'] = MachineState(unlinked)+ ..nodeOnline = true+ ..needsLink = true;+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await _openAddMachineDialog(+ tester,+ f,+ c,+ brightness: brightness,+ textScale: 2,+ );+ expect(+ tester+ .widget<FilledButton>(+ find.widgetWithText(FilledButton, 'Add machine'),+ )+ .onPressed,+ isNull,+ );+ await tester.tap(_picker);+ await tester.pumpAndSettle();+ expect(tester.widget<MenuItemButton>(_option('m')).onPressed, isNull);+ expect(+ tester.widget<MenuItemButton>(_option('studio')).onPressed,+ isNull,+ );+ expect(tester.takeException(), isNull);- await tester.pumpWidget(const SizedBox());- await c.flush();- f.app.superTabs.dispose();- await tester.pump();- });+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );+ }testWidgets('Configure on a machine card reads as editing: title "Configure machine", button "Save"',diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dartindex c7e603484..b85200987 100644--- a/desktop/test/super_tab_picker_test.dart+++ b/desktop/test/super_tab_picker_test.dart@@ -141,7 +141,7 @@ void main() {);await tester.enterText(input, 'Teammate builder');await tester.pumpAndSettle();- expect(find.text('Add agent to Offline editing'), findsOneWidget);+ expect(find.text('Add agent to Pilot'), findsOneWidget);expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);final results = find.byType(SwarmSearchResults);expect(@@ -183,8 +183,8 @@ void main() {(tester) async {final f = await open(tester);final shared = f.app.activeSwarm;- expect(find.text('Add agent to Offline editing'), findsOneWidget);- expect(find.text('Shared with everyone in Pilot.'), findsOneWidget);+ expect(find.text('Add agent to Pilot'), findsOneWidget);+ expect(find.text('Starts in Offline editing.'), findsOneWidget);expect(find.text('Models'), findsNothing);expect(find.text('Store'), findsNothing);final search = tester@@ -246,7 +246,7 @@ void main() {f.app.superTabs.peek(tabId)!.revokeAccess('Access was removed.');await tester.pumpAndSettle();expect(input, findsNothing);- expect(find.text('Add agent to Offline editing'), findsNothing);+ expect(find.text('Add agent to Pilot'), findsNothing);expect(f.connection.server.posts, isEmpty);expect(tester.takeException(), isNull);await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/super_tab_saved_session_test.dart b/desktop/test/super_tab_saved_session_test.dartnew file mode 100644index 000000000..ebfec53a4--- /dev/null+++ b/desktop/test/super_tab_saved_session_test.dart@@ -0,0 +1,244 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/pane.dart';+import 'package:harness/super_tabs/saved_session.dart';+import 'package:harness/widgets/pane_grid.dart';+import 'package:harness/widgets/session_tail_view.dart';+import 'package:harness/widgets/terminal_panel.dart';+import 'package:harness/ws/ws_conn.dart';++import 'swarm_screen_test.dart' show terminal;+import 'swarm_state_test.dart' show createApp;++class _HistoryConnection extends WsConn {+ _HistoryConnection()+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'm',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ final requests = <(String, Map<String, dynamic>)>[];+ Completer<Map<String, dynamic>>? pending;+ Map<String, dynamic> reply = {+ 'rows': [+ {+ 'turn': 1,+ 'ask': 'Calculate the total',+ 'answer': 'The verified total is 403.',+ },+ ],+ 'total': 1,+ 'hasMore': false,+ };++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ requests.add((type, Map.of(payload)));+ if (type == 'session_tail') return pending?.future ?? reply;+ return {};+ }+}++void main() {+ const stopped = Agent(+ id: 'saved',+ name: 'Multiply',+ engine: 'codex',+ sessionId: 'saved-conversation',+ status: 'stopped',+ terminalAvailable: false,+ );+ late AppNotifier app;+ late _HistoryConnection connection;+ setUp(() {+ connection = _HistoryConnection();+ app = createApp(connectionForTest: (_) => connection, connected: true);+ app.currentUser = const CurrentUserProfile(+ id: 'owner',+ email: '[email protected]',+ );+ app.machineStates['m']!.agents = [stopped];+ addTearDown(app.dispose);+ });++ Future<void> pump(WidgetTester tester, {VoidCallback? resume}) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabSavedSession(+ app: app,+ machineId: 'm',+ harnessId: 'saved',+ onResume: resume,+ ),+ ),+ ),+ );+ await tester.pump();+ }++ testWidgets(+ 'saved output is readable without opening a terminal or restarting an engine',+ (tester) async {+ var resumed = 0;+ await pump(tester, resume: () => resumed++);+ await tester.pumpAndSettle();+ expect(find.text('Saved conversation'), findsOneWidget);+ expect(find.text('The verified total is 403.'), findsOneWidget);+ expect(find.byType(SessionTailView), findsOneWidget);+ expect(connection.requests, hasLength(1));+ expect(connection.requests.single.$1, 'session_tail');+ expect(connection.requests.single.$2, {+ 'sessionId': 'saved-conversation',+ });+ expect(resumed, 0);+ await tester.tap(find.text('Resume'));+ expect(resumed, 1);+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final unavailable in [+ 'observer',+ 'guest',+ 'offline',+ 'unsigned',+ 'no session',+ ]) {+ testWidgets('does not request machine history for $unavailable', (+ tester,+ ) async {+ final machine = app.machineStates['m']!;+ switch (unavailable) {+ case 'observer':+ machine.machine = const Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ isShared: true,+ );+ case 'guest':+ machine.machine = const Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ machineShare: MachineShare(+ ownerName: 'Other',+ ownerEmail: '[email protected]',+ via: 'email',+ added: true,+ ),+ );+ case 'offline':+ machine.connectionStatus = ConnectionStatus.disconnected;+ case 'unsigned':+ app.currentUser = null;+ case 'no session':+ machine.agents = [+ const Agent(+ id: 'saved',+ name: 'Multiply',+ engine: 'codex',+ status: 'stopped',+ ),+ ];+ }+ await pump(tester);+ await tester.pumpAndSettle();+ expect(connection.requests, isEmpty);+ expect(find.byType(SessionTailView), findsNothing);+ expect(+ find.text('Saved conversation is unavailable on this machine.'),+ findsOneWidget,+ );+ expect(find.text('Resume'), findsNothing);+ await tester.pumpWidget(const SizedBox());+ });+ }++ testWidgets(+ 'a missing index is an honest stopped state without an implicit resume',+ (tester) async {+ connection.reply = {'error': 'SESSION_NOT_FOUND'};+ await pump(tester, resume: () {});+ await tester.pumpAndSettle();+ expect(+ find.text('Saved conversation is unavailable on this machine.'),+ findsOneWidget,+ );+ expect(connection.requests.map((call) => call.$1), ['session_tail']);+ expect(find.text('Resume'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets('a late history reply cannot cross an account change', (+ tester,+ ) async {+ connection.pending = Completer();+ await pump(tester);+ expect(connection.requests, hasLength(1));+ app.currentUser = const CurrentUserProfile(+ id: 'different',+ email: '[email protected]',+ );+ app.machineStates['m']!.machine = const Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ isShared: true,+ );+ app.dismissError();+ connection.pending!.complete(connection.reply);+ await tester.pumpAndSettle();+ expect(find.text('The verified total is 403.'), findsNothing);+ expect(find.byType(SessionTailView), findsNothing);+ expect(connection.requests, hasLength(1));+ await tester.pumpWidget(const SizedBox());+ });++ testWidgets(+ 'a Swarm keeps its retained terminal instead of fetching a conversation preview',+ (tester) async {+ final session = terminal('saved', []);+ session.terminal.write('Retained native output\r\n');+ app.adoptSessionForTest(session);+ var resumed = 0;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperPane(+ machineId: 'm',+ harnessId: 'saved',+ title: 'Multiply',+ onResume: (_, _) => resumed++,+ child: PaneGrid(notifier: app, swarmMode: true),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(find.byType(TerminalPanel), findsOneWidget);+ expect(find.byType(SuperTabSavedSession), findsNothing);+ expect(+ connection.requests.where((call) => call.$1 == 'session_tail'),+ isEmpty,+ );+ expect(find.text('Resume'), findsOneWidget);+ await tester.tap(find.text('Resume'));+ expect(resumed, 1);+ expect(app.panes.single.session, same(session));+ await tester.pumpWidget(const SizedBox());+ },+ );+}diff --git a/desktop/test/super_tab_workspace_test.dart b/desktop/test/super_tab_workspace_test.dartindex bebf914ee..4338bcad4 100644--- a/desktop/test/super_tab_workspace_test.dart+++ b/desktop/test/super_tab_workspace_test.dart@@ -4,10 +4,107 @@ 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 'package:harness/widgets/pane_grid.dart';+import 'package:harness/ws/local_cli_discovery.dart';import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;void main() {+ testWidgets(+ 'a stopped native stream keeps its Resume action after a chat round trip',+ (tester) async {+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final f = SuperTabLaunchFixture();+ f.connection.nativeSurface = true;+ f.app.machineStates['m']!+ ..terminalCapabilityAvailable = true+ ..localEndpoint = LocalCliEndpoint(+ computerId: 'fixture',+ machineId: 'm',+ wsUri: Uri.parse('ws://fixture.invalid'),+ protocolVersion: 1,+ terminalProtocolVersion: 3,+ );+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ f.connection.native = {+ 'id': 'native-lead',+ 'name': 'Lead',+ 'engine': 'claude',+ 'terminal': {'available': true},+ };+ f.connection.server.state['agents'] = [+ {+ 'id': 'lead-agent',+ 'name': 'Lead',+ 'machineId': 'm',+ 'harnessId': 'native-lead',+ 'contributorId': 'owner',+ 'configuration': {'engine': 'claude'},+ },+ ];+ (f.connection.server.state['conversations'] as List)[0]['agentIds'] = [+ 'lead-agent',+ ];+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ListenableBuilder(+ listenable: f.app,+ builder: (_, _) => SuperTabWorkspace(+ app: f.app,+ canvas: PaneGrid(notifier: f.app, swarmMode: true),+ onAddAgent: (_) {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ c.selectTerminal('lead', c.snapshot!.agents.single.id);+ for (+ var i = 0;+ i < 40 && f.app.panes.firstOrNull?.session?.streamId == null;+ i+++ ) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(f.app.panes.single.session?.streamId, isNotNull);+ c.selectTerminal('lead', null);+ await tester.pump(const Duration(milliseconds: 100));+ f.connection.native = {+ ...f.connection.native!,+ 'status': 'stopped',+ 'sessionId': 'saved-native',+ 'terminal': {'available': false},+ };+ f.app.machineStates['m']!.agents = [Agent.fromJson(f.connection.native!)];+ tester+ .widget<SuperTabView>(find.byType(SuperTabView))+ .onChooseAgentTerminal!(c.snapshot!.agents.single);+ for (var i = 0; i < 40 && find.text('Resume').evaluate().isEmpty; i++) {+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(+ f.connection.calls.where((call) => call.$1 == 'agent_resume'),+ isEmpty,+ );+ expect(+ find.text('Resume'),+ findsOneWidget,+ reason:+ '${tester.widgetList<Text>(find.byType(Text)).map((text) => text.data).whereType<String>().join("\n")}\n${f.connection.calls}\n${f.app.panes.single.session?.status}',+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ await tester.pump();+ },+ );+testWidgets('group terminals keep all members when opening one and ignore pane close',(tester) async {@@ -193,7 +290,7 @@ void main() {);await tester.pumpAndSettle();final calls = f.connection.calls;- // Participants → Open terminal, the only way to relaunch a stopped member.+ // Opening a pane only navigates. Resume is a separate explicit action.Future<void> openTerminal() async {tester.widget<SuperTabView>(find.byType(SuperTabView))@@ -210,6 +307,14 @@ void main() {expect(f.app.activeSwarm.panes.single.agentId, 'native-worker');}await openTerminal();+ expect(calls.where((call) => call.$1 == 'agent_resume'), isEmpty);+ final superPane = tester.widget<SuperPane>(find.byType(SuperPane));+ if (scenario.viewer) {+ expect(superPane.onResume, isNull);+ } else {+ superPane.onResume!('m', 'native-worker');+ await tester.pumpAndSettle();+ }expect(calls.where((call) => call.$1 == 'agent_create'), isEmpty);expect(calls.where((call) => call.$1 == 'agent_resume'),diff --git a/desktop/test/swarm_creation_form_test.dart b/desktop/test/swarm_creation_form_test.dartnew file mode 100644index 000000000..79a100758--- /dev/null+++ b/desktop/test/swarm_creation_form_test.dart@@ -0,0 +1,275 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/foundation.dart';+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_icons.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/widgets/app_menu.dart';+import 'package:harness/state/harness_attachments.dart';+import 'package:harness/state/harness_launch_integration.dart';+import 'package:harness/state/new_harness.dart';+import 'package:harness/super_tabs/project_visibility.dart';+import 'package:harness/widgets/new_harness_form.dart';++import 'super_tab_launch_test.dart' show SuperTabLaunchFixture;++final _visibility = find.byKey(+ const ValueKey('new-harness-project-visibility'),+);+final _start = find.byKey(const ValueKey('new-harness-field-start'));+final _composer = find.byKey(const ValueKey('new-harness-composer'));++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ final capture = Platform.environment['HARNESS_SWARM_FORM_CAPTURE'];+ final previousShadows = debugDisableShadows;+ setUpAll(() async {+ if (capture == null || !Platform.isMacOS) return;+ final bytes = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(bytes))).load();+ }+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(+ rootBundle.load(+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',+ ),+ ))+ .load();+ });+ tearDownAll(() => debugDisableShadows = previousShadows);++ Future<(NewHarnessController, GlobalKey)> mount(+ WidgetTester tester, {+ Brightness brightness = Brightness.dark,+ double width = 760,+ double textScale = 1,+ bool attachments = true,+ bool visibilityLocked = false,+ bool otherRequest = false,+ }) async {+ final oldBrightness = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = oldBrightness);+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;+ addTearDown(() => debugDefaultTargetPlatformOverride = null);+ if (capture != null) debugDisableShadows = false;+ addTearDown(() => debugDisableShadows = previousShadows);+ tester.view.physicalSize = Size(width, 600);+ tester.view.devicePixelRatio = 1;+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ final f = SuperTabLaunchFixture();+ final files = attachments ? HarnessAttachments() : null;+ final box = NewHarnessController(+ f.app,+ machineId: 'm',+ engine: 'codex',+ folder: '/work/lamp-os',+ attachments: files,+ integration: HarnessLaunchIntegration(+ creationId: 'swarm-form-fixture',+ actionLabel: 'New Project',+ projectVisibility: 'public',+ projectVisibilityLocked: visibilityLocked,+ prepare: (_, task) async => task,+ beforeSubmit: (_, _) async {},+ complete: (_, _) async {},+ ),+ )..linkingProfile = otherRequest;+ addTearDown(box.dispose);+ final boundary = GlobalKey();+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(textScale)),+ child: child!,+ ),+ home: Scaffold(+ body: NewHarnessForm(+ controller: box,+ desktop: true,+ embedded: true,+ onClose: () {},+ onCreated: () {},+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ return (box, boundary);+ }++ Future<void> unmount(WidgetTester tester) async {+ await tester.pumpWidget(const SizedBox());+ debugDefaultTargetPlatformOverride = null;+ debugDisableShadows = previousShadows;+ }++ Future<void> shot(+ WidgetTester tester,+ GlobalKey boundary,+ String name,+ ) async {+ if (capture == null) return;+ await tester.runAsync(+ () => precacheImage(+ const AssetImage('assets/engine-icons/codex.png'),+ tester.element(find.byType(NewHarnessForm)),+ ),+ );+ await tester.pump();+ await tester.runAsync(() async {+ final render =+ boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary;+ final image = await render.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(capture).create(recursive: true);+ await File('$capture/$name.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ for (final brightness in Brightness.values) {+ testWidgets(+ 'New Project keeps visibility beside its action in ${brightness.name}',+ (tester) async {+ final (box, boundary) = await mount(tester, brightness: brightness);+ expect(+ find.descendant(of: _composer, matching: _visibility),+ findsOneWidget,+ );+ expect(+ tester.getRect(_visibility).right,+ lessThan(tester.getRect(_start).left),+ );+ expect(+ tester.getCenter(_visibility).dy,+ closeTo(tester.getCenter(_start).dy, 1),+ );+ expect(find.text('New Project'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('new-harness-attach')),+ findsOneWidget,+ );+ await shot(tester, boundary, 'new-project-${brightness.name}');+ await tester.tap(find.text('Public'));+ await tester.pumpAndSettle();+ expect(find.byType(AppMenuItem), findsNWidgets(2));+ expect(find.text('Everyone in this swarm'), findsOneWidget);+ expect(+ find.text('Only people you invite to this project'),+ findsOneWidget,+ );+ expect(find.byIcon(AppIcons.check), findsOneWidget);+ final publicRow = find.widgetWithText(AppMenuItem, 'Public');+ expect(+ tester.getRect(find.byIcon(AppIcons.check)).right,+ greaterThan(tester.getRect(publicRow).right - 24),+ );+ await shot(+ tester,+ boundary,+ 'new-project-${brightness.name}-visibility',+ );+ await tester.tap(find.text('Private'));+ await tester.pumpAndSettle();+ expect(box.integration!.projectVisibility, 'private');+ expect(find.byType(AppMenuItem), findsNothing);+ expect(find.text('Private'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await unmount(tester);+ },+ );+ }++ testWidgets(+ 'Visibility works without attachments and has keyboard focus continuity',+ (tester) async {+ final (box, _) = await mount(tester, attachments: false);+ await tester.tap(find.text('Public'));+ await tester.pumpAndSettle();+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(AppMenuItem), findsNothing);+ final trigger = find.descendant(+ of: _visibility,+ matching: find.byType(TextButton),+ );+ expect(tester.widget<TextButton>(trigger).focusNode!.hasFocus, isTrue);+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);+ await tester.pumpAndSettle();+ expect(find.byType(AppMenuItem), findsNWidgets(2));+ await tester.tap(find.text('Private'));+ await tester.pumpAndSettle();+ expect(box.integration!.projectVisibility, 'private');+ await unmount(tester);+ },+ );++ for (final otherRequest in [false, true]) {+ testWidgets(+ 'Locked visibility explains its ${otherRequest ? 'current' : 'creation'} request',+ (tester) async {+ await mount(+ tester,+ visibilityLocked: !otherRequest,+ otherRequest: otherRequest,+ );+ final visibility = tester.widget<ProjectVisibility>(_visibility);+ expect(visibility.onChanged, isNull);+ expect(+ find.byTooltip(+ otherRequest+ ? 'Finish the current request before changing visibility.'+ : 'Project creation has started. Visibility is fixed for this request.',+ ),+ findsOneWidget,+ );+ await tester.tap(find.text('Public'));+ await tester.pumpAndSettle();+ expect(find.byType(AppMenuItem), findsNothing);+ await unmount(tester);+ },+ );+ }++ for (final brightness in Brightness.values) {+ testWidgets(+ 'New Project remains usable at 2x text in a compact ${brightness.name} window',+ (tester) async {+ final (_, boundary) = await mount(+ tester,+ brightness: brightness,+ width: 420,+ textScale: 2,+ );+ expect(+ find.descendant(of: _composer, matching: _visibility),+ findsOneWidget,+ );+ expect(+ tester.getRect(_start).right,+ lessThanOrEqualTo(tester.getRect(_composer).right),+ );+ await shot(tester, boundary, 'new-project-${brightness.name}-compact');+ await tester.tap(find.text('Public'));+ await tester.pumpAndSettle();+ expect(find.byType(AppMenuItem), findsNWidgets(2));+ await unmount(tester);+ },+ );+ }+}diff --git a/desktop/test/swarm_sharing_test.dart b/desktop/test/swarm_sharing_test.dartnew file mode 100644index 000000000..c9171e86a--- /dev/null+++ b/desktop/test/swarm_sharing_test.dart@@ -0,0 +1,580 @@+import 'dart:async';+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/community/fork_inbox.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/join_dialog.dart';+import 'package:harness/super_tabs/join_link.dart';+import 'package:harness/super_tabs/sharing.dart';+import 'package:harness/widgets/desktop_chrome.dart';++import 'support/super_tab_fixture.dart';++const _token = '1234567890123456789012345678901234567890123';+const _secondToken = 'abcdefghijabcdefghijabcdefghijabcdefghijabc';+const _link = SwarmJoinLink('tab', token: _token);++class _Store implements LocalKeyValueStore {+ final values = <String, String>{};+ @override+ Future<String?> read(String key) async => values[key];+ @override+ Future<void> write(String key, String value) async => values[key] = value;+ @override+ Future<void> delete(String key) async => values.remove(key);+}++class SwarmSharingServer extends ConversationServer {+ Map<String, dynamic> access = {'mode': 'invited', 'role': 'collaborator'};+ int sharingRevision = 0, sharingReads = 0;+ String token = _token;+ bool loseSharingReply = false, stale = false, failSharingRead = false;+ Completer<void>? hold;+ final sharingPosts = <Map<String, dynamic>>[];+ final sharingReceipts = <String, Map<String, dynamic>>{};++ Map<String, dynamic> get settings => {+ 'revision': sharingRevision,+ 'access': Map<String, dynamic>.from(access),+ 'joinUrl': access['mode'] == 'invited'+ ? null+ : SwarmJoinLink(+ 'tab',+ token: access['mode'] == 'link' ? token : null,+ ).url,+ };++ @override+ Future<Map<String, dynamic>> request(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ if (path.endsWith('/sharing')) {+ await hold?.future;+ if (method == 'GET') {+ sharingReads++;+ if (failSharingRead) {+ throw const SuperTabFailure(+ 'NOT_FOUND',+ 'Not found',+ statusCode: 404,+ );+ }+ return settings;+ }+ sharingPosts.add(Map<String, dynamic>.from(body!));+ final operation = body['operationId'] as String;+ if (sharingReceipts[operation] case final receipt?) return receipt;+ if (stale) {+ throw const SuperTabFailure(+ 'REVISION_CHANGED',+ 'Sharing changed',+ statusCode: 409,+ );+ }+ access = Map<String, dynamic>.from(body['access'] as Map);+ if (body['rotateLink'] == true) token = _secondToken;+ sharingRevision++;+ final result = settings;+ sharingReceipts[operation] = result;+ if (loseSharingReply) throw TimeoutException('lost reply');+ return result;+ }+ final command = body?['command'] as Map?;+ if (command?['type'] == 'invite.create') {+ (state['invitations'] as List).add({+ 'id': 'invitation',+ 'email': command!['email'],+ 'role': command['role'],+ });+ }+ return super.request(method, path, body: body);+ }+}++Future<SuperTabController> _open(+ WidgetTester tester,+ SwarmSharingServer server, {+ String account = 'owner',+ Brightness brightness = Brightness.dark,+ double scale = 1,+ Size size = const Size(900, 700),+ GlobalKey? boundary,+}) async {+ await tester.binding.setSurfaceSize(size);+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final previous = grid.AppTheme.brightness.value;+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = previous);+ final controller = server.controller(account: account);+ await controller.refresh();+ controller.select('offline');+ addTearDown(controller.dispose);+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: child!,+ ),+ home: Scaffold(+ body: Builder(+ builder: (context) => TextButton(+ onPressed: () => showSuperTabSharing(context, controller),+ child: const Text('Share'),+ ),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Share'));+ await tester.pumpAndSettle();+ return controller;+}++Future<void> _choose(WidgetTester tester, String key, String label) async {+ await tester.ensureVisible(find.byKey(Key(key)));+ await tester.tap(find.byKey(Key(key)));+ await tester.pumpAndSettle();+ await tester.tap(find.text(label).last);+ await tester.pumpAndSettle();+}++void main() {+ final capture = Platform.environment['HARNESS_SWARM_SHARING_CAPTURE'];+ setUpAll(() async {+ if (capture == null || !Platform.isMacOS) return;+ final bytes = ByteData.sublistView(+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),+ );+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {+ await (FontLoader(family)..addFont(Future.value(bytes))).load();+ }+ await (FontLoader('packages/lucide_icons_flutter/Lucide400')..addFont(+ rootBundle.load(+ 'packages/lucide_icons_flutter/assets/build_font/LucideVariable-w400.ttf',+ ),+ ))+ .load();+ });++ test('join links accept only a typed domain or bearer invitation', () {+ expect(SwarmJoinLink.parse(_link.url)?.token, _token);+ expect(SwarmJoinLink.parse('harness://swarm/join/tab')?.tabId, 'tab');+ for (final value in [+ 'https://swarm/join/tab',+ 'harness://user@swarm/join/tab',+ 'harness://swarm:42/join/tab',+ 'harness://swarm/join/tab#secret',+ 'harness://swarm/join/tab?',+ 'harness://swarm/join/tab?token=short',+ '${_link.url}&token=$_token',+ '${_link.url}&role=owner',+ 'harness://swarm/join/tab/extra',+ 'harness://swarm/join/%2F',+ 'harness://swarm/join/${'x' * 161}',+ ]) {+ expect(SwarmJoinLink.parse(value), isNull, reason: value);+ }+ });++ testWidgets(+ 'native cold-start links share one channel and never persist join tokens',+ (tester) async {+ final store = _Store(), joins = SwarmJoinInbox();+ const channel = MethodChannel('harness/join-fixture');+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (+ call,+ ) async {+ expect(call.method, 'ready');+ return [+ _link.url,+ 'harness://fork/starter-demo?request=11111111-1111-4111-8111-111111111111',+ ];+ });+ final forks = ForkInbox(+ store,+ channel: channel,+ onUnhandledLink: joins.accept,+ );+ await forks.initialize();+ expect(joins.pending.single.tabId, 'tab');+ expect(forks.pending.single.harnessId, 'starter-demo');+ expect(store.values.values.join(), isNot(contains(_token)));+ await forks.accept(_link.url);+ expect(joins.pending, hasLength(1));+ await forks.accept('harness://swarm/join/tab?token=invalid');+ expect(joins.pending, hasLength(1));+ joins.complete(joins.pending.single);+ expect(joins.pending, isEmpty);+ forks.dispose();+ joins.dispose();+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ channel,+ null,+ );+ },+ );++ testWidgets(+ 'email invitation is Swarm scoped and does not use the open workgroup',+ (tester) async {+ final server = SwarmSharingServer();+ await _open(tester, server);+ expect(+ tester.getSize(find.byType(DesktopDialogSurface)).height,+ lessThan(400),+ );+ expect(find.text('Find a person'), findsNothing);+ expect(find.byKey(const Key('swarm-copy-link')), findsNothing);+ expect(server.sharingPosts, isEmpty);+ await tester.enterText(+ find.byKey(const Key('swarm-invite-email')),+ 'invalid',+ );+ await tester.pump();+ await tester.tap(find.byKey(const Key('swarm-invite-send')));+ await tester.pumpAndSettle();+ expect(find.text('Enter an email address.'), findsOneWidget);+ expect(server.posts, isEmpty);+ await tester.enterText(+ find.byKey(const Key('swarm-invite-email')),+ '[email protected]',+ );+ await _choose(tester, 'swarm-invite-role', 'Can view');+ await tester.tap(find.byKey(const Key('swarm-invite-send')));+ await tester.pumpAndSettle();+ expect(server.posts.single['command'], {+ 'type': 'invite.create',+ 'email': '[email protected]',+ 'role': 'viewer',+ 'conversationId': 'lead',+ });+ expect(find.text('[email protected]'), findsOneWidget);+ expect(find.text('Invited'), findsOneWidget);+ },+ );++ testWidgets(+ 'domain access requires Save; copied link carries no bearer token',+ (tester) async {+ final server = SwarmSharingServer();+ String? copied;+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ (call) async {+ if (call.method == 'Clipboard.setData') {+ copied = (call.arguments as Map)['text'] as String;+ }+ return null;+ },+ );+ await _open(tester, server);+ await _choose(tester, 'swarm-general-access', 'Anyone at a domain');+ expect(server.sharingPosts, isEmpty);+ await tester.enterText(+ find.byKey(const Key('swarm-sharing-domain')),+ 'team.example.com',+ );+ await _choose(tester, 'swarm-sharing-role', 'Can view');+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ expect(server.sharingPosts.single['access'], {+ 'mode': 'domain',+ 'role': 'viewer',+ 'domain': 'team.example.com',+ });+ await tester.tap(find.byKey(const Key('swarm-copy-link')));+ await tester.pumpAndSettle();+ expect(copied, 'harness://swarm/join/tab');+ expect(find.text('Copied'), findsOneWidget);+ await tester.pump(const Duration(seconds: 2));+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(+ SystemChannels.platform,+ null,+ );+ },+ );++ testWidgets(+ 'link rotation retries one receipt and restrictive access removes Copy link',+ (tester) async {+ final server = SwarmSharingServer()+ ..access = {'mode': 'link', 'role': 'collaborator'};+ await _open(tester, server);+ server.loseSharingReply = true;+ await tester.tap(find.byKey(const Key('swarm-reset-link')));+ await tester.pumpAndSettle();+ expect(+ find.text('Could not confirm this change. Retry to check it.'),+ findsOneWidget,+ );+ final first = server.sharingPosts.single;+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ expect(server.sharingPosts.last['operationId'], first['operationId']);+ expect(server.sharingPosts.last['rotateLink'], true);+ expect(server.sharingRevision, 1);+ expect(+ find.text('Could not confirm this change. Retry to check it.'),+ findsNothing,+ );+ server.loseSharingReply = false;+ await _choose(tester, 'swarm-general-access', 'Invited people');+ expect(+ tester+ .widget<TextButton>(find.byKey(const Key('swarm-copy-link')))+ .onPressed,+ isNull,+ );+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ expect(server.access['mode'], 'invited');+ expect(find.byKey(const Key('swarm-copy-link')), findsNothing);+ },+ );++ testWidgets(+ 'a stale access edit reloads instead of overwriting another owner change',+ (tester) async {+ final server = SwarmSharingServer();+ await _open(tester, server);+ await _choose(tester, 'swarm-general-access', 'Anyone with the link');+ server.stale = true;+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ expect(server.sharingReads, 2);+ expect(find.text('Invited people'), findsOneWidget);+ expect(+ find.text(+ 'Sharing changed. Review the current settings and try again.',+ ),+ findsOneWidget,+ );+ },+ );++ testWidgets(+ 'old server leaves email invitations available and explains unavailable links',+ (tester) async {+ final server = SwarmSharingServer()..failSharingRead = true;+ await _open(tester, server);+ expect(+ find.text('Sharing links aren’t available on this server yet.'),+ findsOneWidget,+ );+ await tester.enterText(+ find.byKey(const Key('swarm-invite-email')),+ '[email protected]',+ );+ await tester.pump();+ expect(+ tester+ .widget<FilledButton>(find.byKey(const Key('swarm-invite-send')))+ .onPressed,+ isNotNull,+ );+ },+ );++ testWidgets('viewers can see people but cannot change sharing', (+ tester,+ ) async {+ final server = SwarmSharingServer();+ (server.state['people'] as List).add({+ 'id': 'viewer',+ 'email': '[email protected]',+ 'role': 'viewer',+ });+ await _open(tester, server, account: 'viewer');+ expect(server.sharingReads, 0);+ expect(find.byKey(const Key('swarm-invite-email')), findsNothing);+ expect(find.text('General access'), findsNothing);+ expect(find.text('[email protected]'), findsOneWidget);+ expect(find.text('Leave'), findsOneWidget);+ });++ testWidgets(+ 'revocation removes the captured Share dialog and late settings cannot restore it',+ (tester) async {+ final server = SwarmSharingServer();+ final controller = await _open(tester, server);+ controller.revokeAccess('Removed');+ await tester.pumpAndSettle();+ expect(find.text('This action is no longer available.'), findsOneWidget);+ expect(find.byKey(const Key('swarm-invite-email')), findsNothing);+ expect(find.text('General access'), findsNothing);+ },+ );++ for (final profile in [+ (+ name: 'dark',+ brightness: Brightness.dark,+ scale: 1.0,+ size: const Size(900, 700),+ ),+ (+ name: 'light',+ brightness: Brightness.light,+ scale: 1.0,+ size: const Size(900, 700),+ ),+ (+ name: 'compact',+ brightness: Brightness.dark,+ scale: 2.0,+ size: const Size(600, 600),+ ),+ ]) {+ testWidgets('sharing remains compact and usable in ${profile.name}', (+ tester,+ ) async {+ final server = SwarmSharingServer();+ final boundary = GlobalKey();+ await _open(+ tester,+ server,+ brightness: profile.brightness,+ scale: profile.scale,+ size: profile.size,+ boundary: boundary,+ );+ Future<void> shot(String name) async {+ if (capture == null) return;+ final render =+ boundary.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ await tester.runAsync(() async {+ final image = await render.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(capture).create(recursive: true);+ await File('$capture/${profile.name}-$name.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });+ }++ await shot('invited');+ await _choose(tester, 'swarm-general-access', 'Anyone with the link');+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+ await shot('link');+ await tester.ensureVisible(find.byKey(const Key('swarm-sharing-people')));+ await tester.tap(find.byKey(const Key('swarm-sharing-people')));+ await tester.pumpAndSettle();+ await shot('people');+ expect(tester.takeException(), isNull);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(SwarmSharingDialog), findsNothing);+ });+ }++ testWidgets(+ 'join link previews first; explicit Join retries the same receipt',+ (tester) async {+ final requests = <Map<String, dynamic>>[];+ var refuse = true, opened = false;+ await tester.pumpWidget(+ MaterialApp(+ home: Builder(+ builder: (context) => Scaffold(+ body: TextButton(+ onPressed: () => showDialog<void>(+ context: context,+ builder: (_) => SwarmJoinDialog(+ link: _link,+ accountEmail: '[email protected]',+ isCurrent: () => true,+ onJoined: (id, name) {+ expect(id, 'tab');+ expect(name, 'Team');+ opened = true;+ },+ request: (method, path, {body}) async {+ requests.add({'method': method, 'path': path, ...?body});+ expect(path, isNot(contains(_token)));+ if (path.endsWith('/preview')) {+ return {+ 'id': 'tab',+ 'name': 'Team',+ 'role': 'collaborator',+ 'alreadyMember': false,+ };+ }+ if (refuse) throw TimeoutException('lost reply');+ return {'id': 'tab', 'role': 'collaborator'};+ },+ ),+ ),+ child: const Text('Open link'),+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.text('Open link'));+ await tester.pumpAndSettle();+ expect(requests, hasLength(1));+ expect(requests.single['path'], '/api/super-tabs/tab/join/preview');+ expect(requests.single['token'], _token);+ expect(opened, false);+ await tester.tap(find.byKey(const Key('swarm-join-confirm')));+ await tester.pumpAndSettle();+ expect(opened, false);+ refuse = false;+ await tester.tap(find.byKey(const Key('swarm-join-confirm')));+ await tester.pumpAndSettle();+ expect(requests[2]['operationId'], requests[1]['operationId']);+ expect(opened, true);+ expect(find.byType(SwarmJoinDialog), findsNothing);+ },+ );++ testWidgets('revoked links never offer Join or expose a Swarm name', (+ tester,+ ) async {+ var opened = false;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SwarmJoinDialog(+ link: _link,+ accountEmail: '[email protected]',+ isCurrent: () => true,+ onJoined: (_, _) => opened = true,+ request: (_, _, {body}) async => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'private server text',+ statusCode: 403,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(+ find.text(+ 'This link is unavailable for your account. Ask the owner for an invitation.',+ ),+ findsOneWidget,+ );+ expect(find.text('Retry'), findsOneWidget);+ expect(find.text('private server text'), findsNothing);+ expect(opened, false);+ });+}diff --git a/docs/naming-system.md b/docs/naming-system.mdindex d7204f6ac..0d168c988 100644--- a/docs/naming-system.md+++ b/docs/naming-system.md@@ -53,7 +53,7 @@ and **Browser**. Technical documentation may still call the terminal interface a| **A harness** in the workspace | A running agent session with its own conversation and working context. | Start three Codex harnesses. || **A harness** in the Store | A reusable setup containing agent instructions, tools, and an optional viewer. | Install the Blender harness. || **Tab** | A workspace group of harnesses. | Frontend and Backend tabs. |-| **Swarm** | An invite-only collaborative tab containing projects, people, agents and contributed machines. | Open your company Swarm beside your regular tabs. |+| **Swarm** | A collaborative tab containing projects, people, agents and contributed machines. Invite-only by default; its owner can enable joining by email domain or a shared link. | Open your company Swarm beside your regular tabs. || **Project in a Swarm** | An initiative with its own lead, repository, sharing and workgroups. | Discuss Lamp OS with its lead; expand it to follow a workgroup. || **Workgroup** | A numbered conversation for an independently assignable outcome within a project. | Follow #12 Offline editing. || **Pane** | A visible view of a harness, terminal, or viewer. | Split right; close pane. |@@ -84,8 +84,10 @@ running harness. Adding harnesses to a tab groups them without a separate teamsetup. A **Swarm** occupies one tab in that same tab bar. A person can belong to several Swarms.Its project names open their lead chats; a separate chevron reveals each project's workgroups.People, agents and machines belong to the Swarm. A project's **Public** visibility means everyone-in that Swarm; **Private** means its owner and explicitly invited project members. Swarms themselves-are invite-only. Public communities and a compute marketplace are outside this version.+in that Swarm; **Private** means its owner and explicitly invited project members. Swarms are+invite-only by default. Their owner can allow signed-in people with a chosen email domain or a+shared link to join as viewers or collaborators. Joining a Swarm does not grant access to its+private projects. Public discovery and a compute marketplace are outside this version.Cmd-S opens the existing lead creation form for a new Swarm and its first project; **+ Project**reuses that form inside the current Swarm. Store uses Cmd-Control-S. Existing ordinary tabs keeptheir behavior. The internal `superTab` identifiers, `harness super-tab` protocol and stored account