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
Swarm: one not-available answer for every access failure; web sign-out clears that account's drafts (#2333)
0xken15c02efefc8cda
diff --git a/backend/integration/superTabInbox.test.ts b/backend/integration/superTabInbox.test.tsindex 903d7eb59..431a9ee33 100644--- a/backend/integration/superTabInbox.test.ts+++ b/backend/integration/superTabInbox.test.ts@@ -295,7 +295,8 @@ describe('a person\'s inbox: unread threads and each chat\'s latest message', ()const removed = await inbox(s.tabId, peer)// Refused as the messages read refuses them, not answered as a member with nothing to read.const page = await get(`/api/super-tabs/${s.tabId}/conversations/${s.web}/messages`, peer)- expect(page.status).toBe(403)+ // As for a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE).+ expect(page.status).toBe(404)expect({ status: removed.status, code: removed.body.error?.code }).toEqual({ status: page.status, code: page.body.error?.code })expect(removed.body.data).toBeUndefined()expect(JSON.stringify(removed.body)).not.toMatch(/Web|Buddy|Leads/)diff --git a/backend/integration/superTabNotAvailable.test.ts b/backend/integration/superTabNotAvailable.test.tsnew file mode 100644index 000000000..88b214e38--- /dev/null+++ b/backend/integration/superTabNotAvailable.test.ts@@ -0,0 +1,185 @@+import { randomUUID } from 'node:crypto'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import { join } from 'node:path'+import { tmpdir } from 'node:os'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import Fastify, { type FastifyInstance } from 'fastify'+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'+import { PrismaClient } from '@prisma/client'+import type { AuthUser } from '../src/lib/ssoAuth.js'+import { SuperTabStore } from '../src/superTabs/store.js'+import { MemoryAttachmentStore, MemoryAvatarStore } from '../src/superTabs/attachments.js'+import type { Command } from '../src/superTabs/commands.js'+import { SwarmReads } from '../src/superTabs/read/service.js'+import { errorHandler } from '../src/middlewares/errorHandler.js'+import { NOT_AVAILABLE, NOT_AVAILABLE_ROUTES, superTabRoutes } from '../src/routes/superTabs.js'++// The person routes through the real store and read service (Huy, 10-30, the follow-up of #2306): a Swarm, chat, project,+// decision, file or link the caller cannot reach gets one answer, whether it is missing, refused, revoked or in another+// project. Each case is compared byte for byte, status and body, so no route can tell them apart.+let replica: MongoMemoryReplSet+let db: PrismaClient+let app: FastifyInstance+let store: SuperTabStore+const user = (n: number, name: string): AuthUser => ({ sub: `40000000000000000000000${n}`, email: `${name}@example.com`, autonomousEnv: 'prod', role: 'user' })+const owner = user(1, 'owner'), member = user(2, 'member'), outsider = user(3, 'outsider'), removed = user(4, 'removed')+const users = new Map([owner, member, outsider, removed].map(u => [u.sub, u]))++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_not_available_test_${randomUUID().replaceAll('-', '_')}`)+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,+ })+ db = new PrismaClient({ datasources: { db: { url: uri } } })+ for (const u of users.values()) await db.user.create({ data: { id: u.sub, externalId: `fixture-${u.sub}`, email: u.email, autonomousEnv: u.autonomousEnv } })+ store = new SuperTabStore(db, () => Date.now(), { store: new MemoryAttachmentStore(), prefix: 'super-tabs', publicBase: 'https://cdn.example.test',+ avatars: new MemoryAvatarStore('https://avatars.example.test') })+ app = Fastify()+ app.setErrorHandler(errorHandler)+ app.addHook('onRequest', async request => { request.user = users.get(String(request.headers['x-user'])) as never })+ await app.register(superTabRoutes, { store, reads: new SwarmReads(store), github: null, hosts: {} as never, signIn: null,+ approvals: { approved: async () => false, approvedProjects: async () => [] } as never })+ await app.ready()+})+afterAll(async () => {+ await app?.close()+ await db?.$disconnect()+ await replica?.stop()+})++/** A Swarm with a member, a person who was a member and was removed, and a private project the member is not in. */+async function swarm() {+ const tab = (await store.create(owner, randomUUID(), 'Not available', 'public')).id+ const execute = (command: Command, as = owner) => store.execute(as, tab, { operationId: randomUUID(), command })+ for (const u of [member, removed]) {+ const invitation = await execute({ type: 'invite.create', email: u.email, role: 'collaborator', conversationId: 'lead' })+ await execute({ type: 'invite.accept', inviteId: invitation.result.inviteId as string }, u)+ }+ await execute({ type: 'member.remove', userId: removed.sub })+ const project = await execute({ type: 'project.create', name: 'Private', visibility: 'private', brief: '' })+ return { tab, privateProject: String(project.result.projectId), privateChat: String(project.result.conversationId) }+}++const MISSING = 'ffffffffffffffffffffffff'+const boundary = 'not-available-boundary'+const form = (parts: string[]) => `${parts.join('')}--${boundary}--\r\n`+const field = (name: string, value: string) => `--${boundary}\r\nContent-Disposition: form-data; name="${name}"\r\n\r\n${value}\r\n`+const file = (name: string, type: string, body: string) =>+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: ${type}\r\n\r\n${body}\r\n`++/** One call of each person route, about Swarm `tab`, its conversation `chat` and project `project`. */+function calls(tab: string, chat: string, project: string) {+ const op = () => randomUUID()+ const json = (method: 'GET' | 'POST', route: string, url: string, payload?: object) => ({ method, route, url, payload, headers: {} })+ const multipart = (route: string, url: string, payload: string) =>+ ({ method: 'POST' as const, route, url, payload, headers: { 'content-type': `multipart/form-data; boundary=${boundary}` } })+ const t = `/api/super-tabs/${tab}`+ return [+ json('GET', 'GET /api/super-tabs/:tabId/parts', `${t}/parts`),+ json('GET', 'GET /api/super-tabs/:tabId/parts', `${t}/parts?asAgentId=${MISSING}`),+ json('GET', 'GET /api/super-tabs/:tabId/changes', `${t}/changes?cursor=abc`),+ json('GET', 'GET /api/super-tabs/:tabId/inbox', `${t}/inbox`),+ json('POST', 'POST /api/super-tabs/:tabId/commands', `${t}/commands`,+ { operationId: op(), command: { type: 'message.send', conversationId: chat, text: 'hello', replyTo: null, recipientIds: [] } }),+ json('GET', 'GET /api/super-tabs/:tabId/mentions', `${t}/mentions?state=waiting`),+ json('GET', 'GET /api/super-tabs/:tabId/decisions', `${t}/decisions?state=open`),+ json('GET', 'GET /api/super-tabs/:tabId/leaderboard', `${t}/leaderboard?projectId=${project}`),+ json('GET', 'GET /api/super-tabs/:tabId/sharing', `${t}/sharing`),+ json('POST', 'POST /api/super-tabs/:tabId/sharing', `${t}/sharing`, { operationId: op(), revision: 0, access: { mode: 'link', role: 'viewer' } }),+ json('GET', 'GET /api/super-tabs/:tabId/routing-policy', `${t}/routing-policy`),+ json('GET', 'GET /api/super-tabs/:tabId/groups', `${t}/groups?dormant=1&projectId=${project}`),+ json('GET', 'GET /api/super-tabs/:tabId/groups/:conversationId', `${t}/groups/${chat}`),+ json('POST', 'POST /api/super-tabs/:tabId/join', `${t}/join`, { operationId: op(), token: 'a'.repeat(43) }),+ json('POST', 'POST /api/super-tabs/:tabId/join/preview', `${t}/join/preview`, { token: 'a'.repeat(43) }),+ json('POST', 'POST /api/super-tabs/:tabId/native', `${t}/native`, { operationId: op(), conversationId: chat, agentId: MISSING }),+ json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', `${t}/conversations/${chat}/messages`),+ json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up', `${t}/conversations/${chat}/catch-up?after=0`),+ json('POST', 'POST /api/super-tabs/:tabId/conversations/:conversationId/read', `${t}/conversations/${chat}/read`, { sequence: 1 }),+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/github', `${t}/projects/${project}/github`),+ json('POST', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve', `${t}/projects/${project}/github/approve`, { scope: 'project' }),+ json('GET', 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', `${t}/projects/${project}/roles/${MISSING}`),+ json('GET', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId', `${t}/route-decisions/${MISSING}`),+ json('GET', 'GET /api/super-tabs/:tabId/machines/:machineId/removal', `${t}/machines/${MISSING}/removal`),+ multipart('POST /api/super-tabs/:tabId/attachments', `${t}/attachments`, form([field('conversationId', chat), file('notes.txt', 'text/plain', 'hello')])),+ multipart('POST /api/super-tabs/:tabId/avatars', `${t}/avatars`, form([file('me.png', 'image/png', 'not a png')])),+ json('POST', 'POST /api/super-tabs/:tabId/workspace-visibility', `${t}/workspace-visibility`, { visibility: 'workspace' }),+ json('POST', 'POST /api/super-tabs/:tabId/workspace-join', `${t}/workspace-join`, { operationId: op() }),+ json('GET', 'GET /api/super-tabs/:tabId/costs', `${t}/costs`),+ json('GET', 'GET /api/super-tabs/:tabId/route-decisions', `${t}/route-decisions`),+ json('GET', 'GET /api/super-tabs/:tabId/starts/:startId', `${t}/starts/${MISSING}`),+ json('GET', 'GET /api/super-tabs/:tabId/conversations/:conversationId/attempts', `${t}/conversations/${chat}/attempts`),+ json('GET', 'GET /api/super-tabs/:tabId/terminal/:requestId', `${t}/terminal/${MISSING}`),+ json('GET', 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries', `${t}/agents/${MISSING}/deliveries`),+ json('GET', 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId', `${t}/agents/${MISSING}/deliveries/${MISSING}`),+ json('POST', 'POST /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId', `${t}/agents/${MISSING}/deliveries/${MISSING}`,+ { type: 'claim', claimId: op() }),+ json('GET', 'GET /api/super-tabs/:tabId/native/:contextId', `${t}/native/${MISSING}`),+ json('POST', 'POST /api/super-tabs/:tabId/native/:contextId', `${t}/native/${MISSING}`,+ { turnId: op(), kind: 'prompt', previousEventId: null, text: 'hello', truncated: false, interrupted: false }),+ json('POST', 'POST /api/super-tabs/:tabId/github-token', `${t}/github-token`, { machineId: MISSING }),+ json('POST', 'POST /api/super-tabs/:tabId/machines/:machineId', `${t}/machines/${MISSING}`, { generation: 'g1',+ resources: { cpuPercent: 1, memoryTotalBytes: 1e9, memoryUsedBytes: 1e8, diskFreeBytes: 1e9, diskTotalBytes: 2e9, projectDiskFreeBytes: 1e9,+ deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null },+ quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] }),+ json('POST', 'POST /api/super-tabs/:tabId/stopped', `${t}/stopped`, { assignmentId: MISSING, receipt: 'stopped' }),+ ]+}++type Call = ReturnType<typeof calls>[number]+const answer = async (call: Call, as: AuthUser) => {+ const res = await app.inject({ method: call.method, url: call.url, headers: { ...call.headers, 'x-user': as.sub },+ payload: call.payload as never })+ return { status: res.statusCode, body: res.body }+}+const NOT_AVAILABLE_BODY = JSON.stringify({ success: false, error: { code: NOT_AVAILABLE.code, message: NOT_AVAILABLE.message } })++describe('a Swarm the caller cannot reach, on every person route', () => {+ it('answers one not-available answer: a Swarm that does not exist, one never joined, one left, read with a made-up agent id too', async () => {+ const f = await swarm()+ const real = calls(f.tab, 'lead', 'lead'), missing = calls(MISSING, 'lead', 'lead')+ // Every person route is called here, so a route added to the list without a test fails.+ expect(new Set(real.map(c => c.route))).toEqual(NOT_AVAILABLE_ROUTES)+ for (const [i, call] of real.entries()) {+ const cases = { missing: await answer(missing[i]!, outsider), refused: await answer(call, outsider), revoked: await answer(call, removed) }+ // Approving needs the server's GitHub App, which this server has not: it says so to everyone, before any Swarm is read.+ // So does a GitHub token, which needs the same app.+ const expected = /\/github\/approve$|\/github-token$/.test(call.route) ? cases.missing : { status: 404, body: NOT_AVAILABLE_BODY }+ for (const [name, got] of Object.entries(cases)) expect.soft(got, `${name}: ${call.url}`).toEqual(expected)+ }+ })++ it('answers a member alike for a private project\'s chat and project as for ones that do not exist, naming neither', async () => {+ const f = await swarm()+ const hidden = calls(f.tab, f.privateChat, f.privateProject), missing = calls(f.tab, MISSING, MISSING)+ const about = /chat|project-|conversation|Private/+ // The routes that name a chat or a project; the others answer the member normally.+ const named = hidden.filter(c => c.url.includes(f.privateChat) || c.url.includes(f.privateProject)+ || JSON.stringify(c.payload ?? '').includes(f.privateChat) || String(c.payload ?? '').includes(f.privateChat))+ expect(named.map(c => c.route)).toEqual(expect.arrayContaining(['POST /api/super-tabs/:tabId/commands', 'GET /api/super-tabs/:tabId/groups/:conversationId',+ 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', 'POST /api/super-tabs/:tabId/attachments',+ 'GET /api/super-tabs/:tabId/projects/:projectId/github', 'GET /api/super-tabs/:tabId/leaderboard']))+ // Checked before the chat: a terminal opens for one agent (made up here), and approving needs the server's GitHub App.+ const before = ['POST /api/super-tabs/:tabId/native', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve']+ for (const call of named) {+ const got = await answer(call, member), absent = await answer(missing[hidden.indexOf(call)]!, member)+ expect(got, call.url).toEqual(absent)+ if (before.includes(call.route)) continue+ expect(got.status, call.url).toBe(404)+ expect(got.body, call.url).toBe(NOT_AVAILABLE_BODY)+ expect(JSON.parse(got.body).error.message).not.toMatch(about)+ }+ })++ it('still reads for a member, and keeps a role refusal\'s own words inside a Swarm they read', async () => {+ const f = await swarm()+ expect((await answer(calls(f.tab, 'lead', 'lead')[0]!, member)).status).toBe(200)+ // Only the owner changes sharing: the member reads this Swarm, so being told why tells them nothing new.+ const sharing = calls(f.tab, 'lead', 'lead').find(c => c.route === 'POST /api/super-tabs/:tabId/sharing')!+ const refused = await answer(sharing, member)+ expect(refused.status).toBe(403)+ expect(JSON.parse(refused.body).error.code).toBe('OWNER_REQUIRED')+ })+})diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.tsindex ae2507058..1b554d0ac 100644--- a/backend/integration/superTabProfile.test.ts+++ b/backend/integration/superTabProfile.test.ts@@ -186,7 +186,8 @@ describe('avatar uploads', () => {it('is refused outside the Swarm and for a viewer', async () => {const tab = await swarm()- expect((await upload(tab, image(64), 'me.png', 'image/png', outsider)).status).toBe(403)+ // Outside it, refused as a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE).+ expect(await upload(tab, image(64), 'me.png', 'image/png', outsider)).toMatchObject({ status: 404, code: 'NOT_FOUND' })const viewing = (await store.create(owner, randomUUID(), 'Read only')).idconst invitation = await run(viewing, { type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' })await run(viewing, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)diff --git a/backend/integration/superTabSharing.test.ts b/backend/integration/superTabSharing.test.tsindex 2b5b71516..f420040e5 100644--- a/backend/integration/superTabSharing.test.ts+++ b/backend/integration/superTabSharing.test.ts@@ -78,9 +78,10 @@ describe('Swarm sharing on the authenticated control API', () => {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)+ // Someone outside the Swarm is answered as for one that does not exist (routes/superTabs.ts NOT_AVAILABLE).+ expect((await request(tab, 'sharing', undefined, peer)).statusCode).toBe(404)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, peer)).statusCode).toBe(404)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)diff --git a/backend/integration/superTabWorkspaces.test.ts b/backend/integration/superTabWorkspaces.test.tsindex 65ae1e74b..0d25ed736 100644--- a/backend/integration/superTabWorkspaces.test.ts+++ b/backend/integration/superTabWorkspaces.test.ts@@ -7,7 +7,7 @@ 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 { NOT_AVAILABLE, 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'@@ -97,14 +97,15 @@ describe('the Workspace check on every Swarm read and command', () => {await db.swarmWorkspaceRemoval.create({ data: { id: `${removed.id}:${removed.generation}`, workspaceId: workspace!.id, userId: peer.sub, email: peer.email,generation: removed.generation, autonomousEnv: 'prod', removedAt: new Date(), removedBy: owner.sub, finishedAt: null } })+ // Every Swarm route answers as for a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE).for (const url of reads) {const reply = await call('GET', url, peer)- expect(reply.statusCode, url).toBe(403)- expect(JSON.stringify(reply.json()), url).toContain('WORKSPACE_ACCESS_REVOKED')+ expect(reply.statusCode, url).toBe(NOT_AVAILABLE.status)+ expect(reply.json().error.code, url).toBe(NOT_AVAILABLE.code)}const send = await call('POST', `/api/super-tabs/${tab}/commands`, peer,{ operationId: randomUUID(), command: { type: 'message.send', conversationId: 'lead', text: 'still here?', replyTo: null, recipientIds: [] } })- expect(send.statusCode).toBe(403)+ expect(send.statusCode).toBe(NOT_AVAILABLE.status)expect((await listed(peer)).map(r => r.id)).not.toContain(tab)// The Swarm's own people are untouched.expect((await call('GET', `/api/super-tabs/${tab}/parts`, owner)).statusCode).toBe(200)@@ -117,7 +118,7 @@ describe('the Workspace check on every Swarm read and command', () => {it('keeps a person of one Workspace out of another Workspace\'s Swarm', async () => {const theirs = await create(other, 'Elsewhere')const reply = await call('GET', `/api/super-tabs/${theirs}/parts`, owner)- expect(reply.statusCode).toBe(403)+ expect(reply.json().error).toEqual({ code: NOT_AVAILABLE.code, message: NOT_AVAILABLE.message })expect(JSON.stringify(reply.json())).not.toContain('Elsewhere')expect((await workspacesOf(owner)).flatMap(o => o.swarms.map(s => s.id))).not.toContain(theirs)})@@ -184,14 +185,16 @@ describe('Swarms open to the Workspace', () => {const names = async (who: AuthUser) => (await workspacesOf(who)).find(o => o.id === workspaceId)?.swarms.map(s => s.id) ?? []expect(await names(member)).not.toContain(tab)expect(await names(admin)).toContain(tab)- expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, member, { operationId: randomUUID() })).statusCode).toBe(403)- expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, member, { visibility: 'workspace' })).statusCode).toBe(403)+ // Not open to them yet, and not theirs to open: refused as a Swarm that does not exist, as their Workspace list says.+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, member, { operationId: randomUUID() })).statusCode).toBe(NOT_AVAILABLE.status)+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, member, { visibility: 'workspace' })).statusCode).toBe(NOT_AVAILABLE.status)expect((await call('POST', `/api/super-tabs/${tab}/workspace-visibility`, owner, { visibility: 'workspace' })).statusCode).toBe(200)expect(await names(member)).toContain(tab)const joinedOf = async (who: AuthUser) => (await workspacesOf(who)).find(o => o.id === workspaceId)!.swarms.find(s => s.id === tab)!.memberexpect([await joinedOf(member), await joinedOf(owner)]).toEqual([false, true])expect(await names(peer)).not.toContain(tab)- expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, peer, { operationId: randomUUID() })).statusCode).toBe(403)+ // A guest is never shown it, and is refused it as a Swarm that does not exist.+ expect((await call('POST', `/api/super-tabs/${tab}/workspace-join`, peer, { operationId: randomUUID() })).statusCode).toBe(NOT_AVAILABLE.status)const joined = await call('POST', `/api/super-tabs/${tab}/workspace-join`, member, { operationId: randomUUID() })expect(joined.statusCode).toBe(200)expect(joined.json().data.role).toBe('collaborator')@@ -221,7 +224,7 @@ describe('removing someone from a Workspace', () => {expect(removed.statusCode).toBe(200)for (const tab of [a, b]) {expect(await swarmPeople(tab)).not.toContain(member.sub)- expect((await call('GET', `/api/super-tabs/${tab}/parts`, member)).statusCode).toBe(403)+ expect((await call('GET', `/api/super-tabs/${tab}/parts`, member)).statusCode).toBe(NOT_AVAILABLE.status)}expect((await workspacesOf(member)).map(o => o.id)).not.toContain(workspaceId)expect((await call('GET', `/api/super-tabs/${elsewhere}/parts`, member)).statusCode).toBe(200)@@ -244,7 +247,7 @@ describe('removing someone from a Workspace', () => {const token = new URL(saved.joinUrl!).searchParams.get('token')!expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/members/${peer.sub}/remove`, owner, {})).statusCode).toBe(200)const again = await call('POST', `/api/super-tabs/${tab}/join`, peer, { operationId: randomUUID(), token })- expect(again.statusCode).toBe(403)+ expect(again.json().error).toEqual({ code: NOT_AVAILABLE.code, message: NOT_AVAILABLE.message })expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/invitations`, owner, { email: peer.email, role: 'guest' })).statusCode).toBe(200)expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, peer, {})).statusCode).toBe(200)expect((await call('POST', `/api/super-tabs/${tab}/join`, peer, { operationId: randomUUID(), token })).statusCode).toBe(200)@@ -303,7 +306,7 @@ describe('the migration of today\'s Swarms into Workspaces, and its undo', () =>expect(peerWorkspaces.map(o => [o.id, o.role, o.swarms.map(s => s.id)])).toEqual([[ownerWorkspace!.id, 'guest', [first]]])// Nobody gains or loses access.expect((await call('GET', `/api/super-tabs/${first}/parts`, legacyPeer)).statusCode).toBe(200)- expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyPeer)).statusCode).toBe(403)+ expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyPeer)).statusCode).toBe(NOT_AVAILABLE.status)expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)).json().data.members).toEqual(before.json().data.members)expect((await call('GET', `/api/super-tabs/${second}/parts`, legacyOwner)).json().data.head.data.workspaceId).toBe(ownerWorkspace!.id)@@ -323,8 +326,8 @@ describe('the migration of today\'s Swarms into Workspaces, and its undo', () =>process.env.SWARM_WORKSPACES_REQUIRED = '1'try {const reply = await call('GET', `/api/super-tabs/${tab}/parts`, legacyOwner)- expect(reply.statusCode).toBe(403)- expect(JSON.stringify(reply.json())).toContain('WORKSPACE_ACCESS_REVOKED')+ expect(reply.statusCode).toBe(NOT_AVAILABLE.status)+ expect(reply.json().error.code).toBe(NOT_AVAILABLE.code)expect((await listed(legacyOwner)).map(r => r.id)).not.toContain(tab)} finally { delete process.env.SWARM_WORKSPACES_REQUIRED }await migrateWorkspaces(db, { apply: true })@@ -381,8 +384,8 @@ describe('a removal whose Swarm cleanup failed', () => {expect((await call('POST', `/api/super-tabs/workspaces/${workspaceId}/accept`, member, {})).statusCode).toBe(200)expect((await workspacesOf(member)).map(o => o.id)).toContain(workspaceId)expect(await swarmPeople(privateTab)).not.toContain(member.sub)- expect((await call('GET', `/api/super-tabs/${privateTab}/parts`, member)).statusCode).toBe(403)- expect((await call('POST', `/api/super-tabs/${privateTab}/commands`, member, { operationId, command })).statusCode).toBe(403)+ expect((await call('GET', `/api/super-tabs/${privateTab}/parts`, member)).statusCode).toBe(NOT_AVAILABLE.status)+ expect((await call('POST', `/api/super-tabs/${privateTab}/commands`, member, { operationId, command })).statusCode).toBe(NOT_AVAILABLE.status)})it('keeps the person out while the earlier removal cannot finish', async () => {diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 9084b26b5..21b5055b8 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -1089,11 +1089,13 @@ describe('Super Tabs on a real Mongo replica set', () => {const group = (await run(tab, { type: 'conversation.create', title: 'Other work', brief: '', checks: [] })).result.conversationId as stringexpect((await store.messages(host, tab, group, { messageId: question }, lead)).messages).toEqual([])expect((await app.inject({ url: `/api/super-tabs/${tab}/conversations/lead/messages?messageId=${question}`,- headers: { authorization: `Bearer ${peer.sub}` } })).statusCode).toBe(403)+ headers: { authorization: `Bearer ${peer.sub}` } })).statusCode).toBe(404)await run(tab, { type: 'project.delete', projectId: 'lead' })+ // Its project gone, the host runs none of the Swarm's agents and is not in it: answered as for a Swarm that does not+ // exist (routes/superTabs.ts NOT_AVAILABLE); the store still says the agent is unavailable.const removed = await app.inject({ url, headers })- expect(removed.statusCode).toBe(409)- expect(removed.json().error.code).toBe('AGENT_UNAVAILABLE')+ expect(removed.statusCode).toBe(404)+ expect(removed.json().error.code).toBe('NOT_FOUND')})it('records native turns once, in order, with verified source metadata and no input echo', async () => {@@ -1906,7 +1908,8 @@ describe('Super Tabs on a real Mongo replica set', () => {const group = (await run(two.tab, { type: 'conversation.create', title: 'Other work', brief: '', checks: [] })).result.conversationId as stringconst read = (tab: string, conversation: string, user: AuthUser, query = '') =>app.inject({ url: `/api/super-tabs/${tab}/conversations/${conversation}/attempts${query}`, headers: { authorization: `Bearer ${user.sub}` } })- expect((await read(one.tab, 'lead', peer)).statusCode).toBe(403)+ // A non-member is answered as for a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE).+ expect((await read(one.tab, 'lead', peer)).statusCode).toBe(404)expect((await read(one.tab, group, owner)).statusCode).toBe(404)expect((await read(two.tab, group, owner)).statusCode).toBe(200)expect((await read(one.tab, 'lead', host, `?asAgentId=${two.lead}`)).statusCode).not.toBe(200)diff --git a/backend/src/routes/superTabs.test.ts b/backend/src/routes/superTabs.test.tsindex ddb47336f..9e4e40890 100644--- a/backend/src/routes/superTabs.test.ts+++ b/backend/src/routes/superTabs.test.ts@@ -50,7 +50,9 @@ import { registerAuthMiddleware } from '../middlewares/authMiddleware.js'import { redeemHandoff, startHandoff } from '../lib/harnessSession.js'import type { AuthUser } from '../lib/ssoAuth.js'import { SuperTabError } from '../superTabs/model.js'-import { HOT_BODY_LIMIT, superTabRoutes } from './superTabs.js'+import { HOT_BODY_LIMIT, NOT_AVAILABLE, superTabRoutes } from './superTabs.js'+import { logger } from '../utils/logger.js'+import { WORKSPACE_ACCESS_REVOKED } from '../superTabs/workspaceStore.js'describe('Super Tab route failures', () => {let app: FastifyInstance@@ -98,6 +100,60 @@ describe('Super Tab route failures', () => {})})+// One answer for anything the caller cannot reach, on the routes a person's app calls (Huy, 10-30): the route only maps the+// store's refusal, so a fake store throws each kind. integration/superTabNotAvailable.test.ts runs the real store.+describe('the person routes\' one not-available answer', () => {+ let app: FastifyInstance+ let thrown: unknown+ const throwing = async () => { throw thrown }+ beforeEach(async () => {+ app = Fastify()+ app.setErrorHandler(errorHandler)+ app.addHook('onRequest', async request => { request.user = { sub: 'u1', email: '[email protected]', autonomousEnv: 'prod', role: 'user' } as never })+ const store = { hostGrids: throwing, messages: throwing, execute: throwing }+ await app.register(superTabRoutes, { store: store as never, github: null, reads: { firstLoad: throwing } as never, hosts: {} as never })+ await app.ready()+ })+ afterEach(async () => { await app.close(); vi.restoreAllMocks() })+ const body = JSON.stringify({ success: false, error: { code: NOT_AVAILABLE.code, message: NOT_AVAILABLE.message } })+ const ask = (url: string, method: 'GET' | 'POST' = 'GET') => app.inject({ method, url,+ payload: method === 'POST' ? { operationId: 'op-1', command: { type: 'message.send', conversationId: 'c1', text: 'hi', replyTo: null, recipientIds: [] } } : undefined })++ it('answers missing, not a member, out of the Workspace and a refused link alike, and logs which it was', async () => {+ const warn = vi.spyOn(logger, 'warn')+ const refusals = [new SuperTabError('NOT_FOUND', 'This Super Tab is unavailable.', 404),+ new SuperTabError('FORBIDDEN', 'You no longer have access to this Super Tab.', 403, true),+ new SuperTabError(WORKSPACE_ACCESS_REVOKED, 'You are no longer in this Swarm\'s Workspace.', 403),+ new SuperTabError('JOIN_UNAVAILABLE', 'This Swarm link is unavailable for this account.', 404),+ new SuperTabError('NOT_FOUND', 'This conversation is unavailable.', 404)]+ for (const refusal of refusals) {+ thrown = refusal+ for (const [url, method] of [['/api/super-tabs/tab-1/parts'], ['/api/super-tabs/tab-1/conversations/c1/messages'], ['/api/super-tabs/tab-1/commands', 'POST']] as const) {+ const res = await ask(url, method)+ expect({ status: res.statusCode, body: res.body }, `${refusal.code} ${url}`).toEqual({ status: 404, body })+ }+ expect(warn).toHaveBeenCalledWith('Swarm not available to the caller', expect.objectContaining({ code: refusal.code, reason: refusal.message }))+ }+ })++ it('keeps a role refusal inside a Swarm the caller reads, and a FORBIDDEN that is not about reaching it', async () => {+ for (const refusal of [new SuperTabError('READ_ONLY', 'You have read-only access to this Super Tab.', 403),+ new SuperTabError('FORBIDDEN', 'Only the owner can remove another person.', 403)]) {+ thrown = refusal+ const res = await ask('/api/super-tabs/tab-1/commands', 'POST')+ expect(res.statusCode).toBe(403)+ expect(res.json().error).toEqual({ code: refusal.code, message: refusal.message })+ }+ })++ it('leaves the routes a machine\'s host calls as they were', async () => {+ thrown = new SuperTabError('FORBIDDEN', 'You no longer have access to this Super Tab.', 403, true)+ const res = await ask('/api/super-tabs/grids')+ expect(res.statusCode).toBe(403)+ expect(res.json().error.message).toBe('You no longer have access to this Super Tab.')+ })+})+describe('Super Tab body limits (roadmap 2.8)', () => {let app: FastifyInstancelet reached: string[]diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex bc0a86ca2..a494dfc2b 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -30,6 +30,7 @@ import { UPDATE_REQUIRED } from '../superTabs/read/contract.js'import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'import type { AuthUser } from '../lib/ssoAuth.js'import { DEFAULT_DAYS, MAX_DAYS } from '../superTabs/costs/read.js'+import { WORKSPACE_ACCESS_REVOKED } from '../superTabs/workspaceStore.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)const tabParams = z.object({ tabId: id })@@ -111,9 +112,51 @@ const githubToken = z.object({ machineId: id }).strict()const githubStartToken = z.object({ always: z.boolean().optional() }).strict()+/**+ * The routes about one Swarm that a sign-in may call: the web with the browser's own sign-in (desktop+ * super_tabs/backend_transport.dart), Desktop and the phone through their machine, and a machine's host and its agents.+ * On these, a Swarm, chat, message, project, decision, start, delivery, file or link the caller cannot reach gets one+ * answer, whether it is missing, refused, revoked, outside its Workspace or in another project, so the answer never says+ * which. The server log keeps the specific reason. Role refusals inside a Swarm the caller reads (read-only,+ * owner-only) keep their own words: they tell nothing the caller cannot already see. Hosts read 403 and 404 alike as+ * access lost (cli superTabs/machines.ts, swarmReads.ts).+ */+export const NOT_AVAILABLE_ROUTES: ReadonlySet<string> = new Set([+ 'GET /api/super-tabs/:tabId/parts', 'GET /api/super-tabs/:tabId/changes', 'GET /api/super-tabs/:tabId/inbox', 'POST /api/super-tabs/:tabId/commands',+ 'GET /api/super-tabs/:tabId/mentions', 'GET /api/super-tabs/:tabId/decisions', 'GET /api/super-tabs/:tabId/leaderboard',+ 'GET /api/super-tabs/:tabId/sharing', 'POST /api/super-tabs/:tabId/sharing', 'GET /api/super-tabs/:tabId/routing-policy',+ 'GET /api/super-tabs/:tabId/groups', 'GET /api/super-tabs/:tabId/groups/:conversationId',+ 'POST /api/super-tabs/:tabId/join', 'POST /api/super-tabs/:tabId/join/preview', 'POST /api/super-tabs/:tabId/native',+ 'GET /api/super-tabs/:tabId/conversations/:conversationId/messages', 'GET /api/super-tabs/:tabId/conversations/:conversationId/catch-up',+ 'POST /api/super-tabs/:tabId/conversations/:conversationId/read',+ 'GET /api/super-tabs/:tabId/projects/:projectId/github', 'POST /api/super-tabs/:tabId/projects/:projectId/github/approve',+ 'GET /api/super-tabs/:tabId/projects/:projectId/roles/:roleId', 'GET /api/super-tabs/:tabId/route-decisions/:decisionId',+ 'GET /api/super-tabs/:tabId/machines/:machineId/removal',+ 'POST /api/super-tabs/:tabId/attachments', 'POST /api/super-tabs/:tabId/avatars',+ // Reached by any sign-in too (review of #2333): Workspace settings, costs, routing and the host's own reads.+ 'POST /api/super-tabs/:tabId/workspace-visibility', 'POST /api/super-tabs/:tabId/workspace-join', 'GET /api/super-tabs/:tabId/costs',+ 'GET /api/super-tabs/:tabId/route-decisions', 'GET /api/super-tabs/:tabId/starts/:startId',+ 'GET /api/super-tabs/:tabId/conversations/:conversationId/attempts', 'GET /api/super-tabs/:tabId/terminal/:requestId',+ 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries', 'GET /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',+ 'POST /api/super-tabs/:tabId/agents/:agentId/deliveries/:deliveryId',+ 'GET /api/super-tabs/:tabId/native/:contextId', 'POST /api/super-tabs/:tabId/native/:contextId', 'POST /api/super-tabs/:tabId/github-token',+ 'POST /api/super-tabs/:tabId/machines/:machineId', 'POST /api/super-tabs/:tabId/stopped',+])+/** The one answer on those routes for anything the caller cannot reach. 404 with the code every client already+ * reads as gone (Desktop and the phone: FORBIDDEN or NOT_FOUND; the CLI: 403 or 404). */+export const NOT_AVAILABLE = { code: 'NOT_FOUND', message: 'This is not available to you. It may have been removed, or your access changed.', status: 404 } as const+const UNREACHABLE_CODES: ReadonlySet<string> = new Set(['NOT_FOUND', 'JOIN_UNAVAILABLE', WORKSPACE_ACCESS_REVOKED])+const unreachable = (error: SuperTabError) => error.unreachable || UNREACHABLE_CODES.has(error.code)+async function respond(reply: FastifyReply, action: () => Promise<unknown>) {try { sendSuccess(reply, await action()) } catch (error) {if (error instanceof GitHubAppError) return sendError(reply, error.message, error.code, error.status, error.details)+ const { request } = reply+ if (error instanceof SuperTabError && unreachable(error) && NOT_AVAILABLE_ROUTES.has(`${request.method} ${request.routeOptions.url}`)) {+ logger.warn('Swarm not available to the caller', { code: error.code, statusCode: error.status, reason: error.message,+ path: request.url, method: request.method })+ return sendError(reply, NOT_AVAILABLE.message, NOT_AVAILABLE.code, NOT_AVAILABLE.status)+ }// A Swarm refusal, a busy Swarm (503 with Retry-After), an expired transaction or a duplicate key: the shared// error handler answers each deliberately, and every other failure stays a 500 with its stack logged.throw errordiff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex ade4b72bf..12340ddb5 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -479,7 +479,9 @@ export interface CommandEffects {decisionAnswer?: import('./decisions.js').DecisionAnswer}export class SuperTabError extends Error {- constructor(readonly code: string, message: string, readonly status = 409) {+ /** `unreachable`: the caller cannot reach this Swarm at all (not, or no longer, a member). The person routes answer it as+ * they answer a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE), so the answer never says which. */+ constructor(readonly code: string, message: string, readonly status = 409, readonly unreachable = false) {super(message)this.name = 'SuperTabError'}@@ -528,7 +530,9 @@ export function reviewing(state: SuperTabState, agentId: string): boolean {}export function person(state: SuperTabState, id: string): Person {- return state.people.find(p => p.id === id) ?? fail('FORBIDDEN', 'You no longer have access to this Super Tab.', 403)+ const found = state.people.find(p => p.id === id)+ if (!found) throw new SuperTabError('FORBIDDEN', 'You no longer have access to this Super Tab.', 403, true)+ return found}export function agent(state: SuperTabState, id: string): Agent {const found = state.agents.find(a => a.id === id) ?? fail('AGENT_UNAVAILABLE', 'This agent is no longer in the Super Tab.')diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex c2efbfcf7..1b591c4cc 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -436,6 +436,30 @@ const authorForBuddy = <T extends Pick<Author, 'kind' | 'membershipGeneration'>author?.kind === 'agent' && author.membershipGeneration ? { ...author, membershipGeneration: '' } : authorconst [UNPURGED_HEAD, UNPURGED_TAIL] = unpurgedNotice('\0').split('\0') as [string, string]+/** Someone with no part in this Swarm: not in it, hosting none of its agents, contributing none of its machines and running+ * none of its work. A refusal to them is answered as for a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE):+ * its words would say the Swarm is there. Anyone with a part keeps them. */+function stranger(state: SuperTabState, userId: string): boolean {+ return !state.people.some(p => p.id === userId) && !state.agents.some(a => a.machineOwnerId === userId)+ && !(state.machines ?? []).some(m => m.contributorId === userId)+ && !state.conversations.some(c => c.assignment?.execution.machineOwnerId === userId)+}+async function strangerRefusal<T>(state: SuperTabState, userId: string, check: () => T | Promise<T>): Promise<T> {+ try { return await check() } catch (error) {+ if (error instanceof SuperTabError && stranger(state, userId)) throw new SuperTabError(error.code, error.message, error.status, true)+ throw error+ }+}++/** A Workspace refusal to someone not in the Swarm (a Workspace admin need not be): the routes answer it as for a Swarm that+ * does not exist (routes/superTabs.ts NOT_AVAILABLE), since its words would say the Swarm is there. Its members keep them. */+async function outsiderRefusal(state: SuperTabState, userId: string, check: () => Promise<void>): Promise<void> {+ try { await check() } catch (error) {+ if (error instanceof SuperTabError && !state.people.some(p => p.id === userId)) throw new SuperTabError(error.code, error.message, error.status, true)+ throw error+ }+}+export class SuperTabStore {readonly native: SuperTabNativeStorereadonly workspaces: SwarmWorkspaces@@ -744,8 +768,12 @@ export class SuperTabStore {if (!workspaceLeave) await requireWorkspaceAccess(tx, state, user.sub)return { kind: 'person', userId: user.sub, email: user.email }}- const target = agent(state, agentId)- if (target.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)+ // A stranger learns nothing of the Swarm from an agent id, real, made up or another Swarm's.+ const target = await strangerRefusal(state, user.sub, () => {+ const found = agent(state, agentId)+ if (found.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can speak as this agent.', 403)+ return found+ })// ...and as an agent only one running on its own machine, never the person's agents elsewhere.if (team !== null && target.machineId !== team) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)const reads = new GrantReads()@@ -856,9 +884,11 @@ export class SuperTabStore {this.personOnly(user)return transaction(this.db, async tx => {const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)- if (!state.workspaceId) fail('WORKSPACE_REQUIRED', `This Swarm has no ${WORKSPACE_LABEL} yet.`, 409)- const own = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })- if (!(state.ownerId === user.sub && own && !own.removedAt && own.role !== 'guest')) await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.manage')+ await outsiderRefusal(state, user.sub, async () => {+ if (!state.workspaceId) fail('WORKSPACE_REQUIRED', `This Swarm has no ${WORKSPACE_LABEL} yet.`, 409)+ const own = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })+ if (!(state.ownerId === user.sub && own && !own.removedAt && own.role !== 'guest')) await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.manage')+ })state.workspaceVisibility = visibilityawait this.save(tx, loaded, state, clock.next(), [{ kind: 'head', key: 'head' }])return { id: tabId, workspaceVisibility: visibility }@@ -870,8 +900,10 @@ export class SuperTabStore {this.personOnly(user)return transaction(this.db, async tx => {const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)- if (!state.workspaceId || state.workspaceVisibility !== 'workspace') fail('FORBIDDEN', 'This Swarm is not open to its Workspace.', 403)- await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.joinOpen')+ await outsiderRefusal(state, user.sub, async () => {+ if (!state.workspaceId || state.workspaceVisibility !== 'workspace') fail('FORBIDDEN', 'This Swarm is not open to its Workspace.', 403)+ await requireWorkspaceRole(tx, state.workspaceId, user.sub, 'swarm.joinOpen')+ })const existing = state.people.find(p => p.id === user.sub)if (existing) return { id: tabId, role: existing.role, alreadyMember: true }const member = { id: user.sub, email: authenticatedEmail(user.email)!, role: 'collaborator' as const, generation: stableId('workspace-join', tabId, user.sub, operationId) }@@ -2309,8 +2341,11 @@ export class SuperTabStore {// Only the conversations its checks read (parts/load.ts loadObserved): the whole Swarm was ~1.1 MB a report (#876).const loaded = loadedFrom(await this.row(tx, user, tabId), await loadObserved(tx, tabId, machineId)), state = structuredClone(loaded.state)await this.hostFor(tx, user, machineId, owned, state)- const pool = machineContribution(state, machineId)- if (!pool || pool.contributorId !== user.sub || pool.generation !== observation.generation) fail('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403)+ const pool = await strangerRefusal(state, user.sub, () => {+ const found = machineContribution(state, machineId)+ if (!found || found.contributorId !== user.sub || found.generation !== observation.generation) fail('CONTRIBUTION_REVOKED', 'Read the current machine contribution.', 403)+ return found+ })if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)const now = this.now()// A machine that went silent while cleaning takes the fallback before this fresh reading can bring it back: its records@@ -2902,8 +2937,11 @@ export class SuperTabStore {const loaded = await this.load(tx, user, tabId), state = structuredClone(loaded.state)const before = { agents: state.agents, conversations: structuredClone(state.conversations) }const group = state.conversations.find(c => c.assignment?.id === assignmentId)- const assignment = group?.assignment- if (!assignment || assignment.execution.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can confirm this stop.', 403)+ const assignment = await strangerRefusal(state, user.sub, () => {+ const found = group?.assignment+ if (!found || found.execution.machineOwnerId !== user.sub) fail('FORBIDDEN', 'Only the execution host can confirm this stop.', 403)+ return found+ })const execution = assignment.executionawait this.hostFor(tx, user, execution.machineId)const machine = await tx.machine.findFirst({ where: { machineId: execution.machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex 942dfc3a5..191475b98 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -4,7 +4,7 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts','integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts','integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts','integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts',- 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts',+ 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts','integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts','integration/superTabEvidence.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })diff --git a/desktop/lib/core/harness_file_store_web.dart b/desktop/lib/core/harness_file_store_web.dartindex a70d247c8..76451363d 100644--- a/desktop/lib/core/harness_file_store_web.dart+++ b/desktop/lib/core/harness_file_store_web.dart@@ -7,7 +7,10 @@ import 'local_key_value_store.dart';/// Sign-in, machine identity, links, and preferences persist on this origin./// OAuth transactions stay tab-local in DirectLogin. Storage failures propagate.class HarnessFileStore- implements BatchLocalKeyValueStore, SynchronizedLocalKeyValueStore {+ implements+ BatchLocalKeyValueStore,+ SynchronizedLocalKeyValueStore,+ KeyListingLocalKeyValueStore {static final HarnessFileStore shared = HarnessFileStore();static const _prefix = 'harness.web.v1.';static const _migrated = '${_prefix}persistent_credentials';@@ -55,6 +58,17 @@ class HarnessFileStore};}+ @override+ Future<List<String>> keys() async {+ await _ready();+ final local = web.window.localStorage;+ return [+ for (var i = 0; i < local.length; i++)+ if (local.key(i) case final key? when key.startsWith(_prefix))+ key.substring(_prefix.length),+ ];+ }+@overrideFuture<void> write(String key, String value) async {await _ready();diff --git a/desktop/lib/core/local_key_value_store.dart b/desktop/lib/core/local_key_value_store.dartindex 33bf961ca..5f380c108 100644--- a/desktop/lib/core/local_key_value_store.dart+++ b/desktop/lib/core/local_key_value_store.dart@@ -12,6 +12,13 @@ abstract interface class BatchLocalKeyValueStore implements LocalKeyValueStore {Future<Map<String, String?>> readMany(Iterable<String> keys);}+/// Stores that can name every key they hold (the browser's), so all of one+/// account's keys can go at sign-out ([forgetSwarmAccount]).+abstract interface class KeyListingLocalKeyValueStore+ implements LocalKeyValueStore {+ Future<List<String>> keys();+}+/// A store shared by independent runtimes, such as browser tabs.abstract interface class SynchronizedLocalKeyValueStoreimplements LocalKeyValueStore {diff --git a/desktop/lib/super_tabs/account_keys.dart b/desktop/lib/super_tabs/account_keys.dartnew file mode 100644index 000000000..e9fe1e472--- /dev/null+++ b/desktop/lib/super_tabs/account_keys.dart@@ -0,0 +1,110 @@+import 'dart:convert';++import '../core/local_key_value_store.dart';++/// The account a Swarm key in the client's storage belongs to, or null for a+/// key that is no account's. What the web keeps of an account beside its+/// saved views (docs/specs/2026-10-30-web-swarm-direct.md, Caching):+/// - `super_tab.<account>.<swarm>`: unsent drafts, selection, what is open;+/// - `super_tab.launch.<account>.<tab>.<conversation>`: an unsent New Harness+/// or New Project;+/// - `super_tab.hidden.<account>`: the Swarms hidden on this browser;+/// - `super_tab.personal.<account>`: the Swarm last chosen in the switcher.+/// The saved views' own keys (`super_tab.view…`, `super_tab.saved_by`) are+/// [SuperTabSavedViews]', which forgets them itself.+String? swarmKeyAccount(String key) {+ if (!key.startsWith('super_tab.')) return null;+ final parts = key.substring('super_tab.'.length).split('.');+ return switch (parts) {+ ['launch', final account, _, ...] => account,+ ['hidden' || 'personal', final account] => account,+ ['view' || 'views' || 'saved_by' || 'signed_out', ...] => null,+ [final account, _] => account,+ _ => null,+ };+}++/// The accounts signed out on this browser whose keys are swept again at each+/// sign-in or reload: another page of this browser may still have written one+/// of theirs after the sign-out swept them (it reloads, but not at once).+const signedOutAccountsKey = 'super_tab.signed_out';++/// How many signed-out accounts a browser remembers: the oldest goes first.+const maxSignedOutAccounts = 16;++/// Signing out on the web: every key of each account signed out on this+/// browser goes, [leaving] (the account signing out now, if any) with them,+/// and [bound] (the one signed in now) is no longer one of them. Another+/// account's keys stay. Under the browser's lock, so two pages never rewrite+/// the list over each other.+Future<void> forgetSwarmAccounts(+ LocalKeyValueStore storage, {+ required String? bound,+ String? leaving,+}) => storage.synchronized(signedOutAccountsKey, () async {+ final out = await _signedOut(storage);+ if (leaving != null && leaving != bound) {+ out+ ..remove(leaving)+ ..add(leaving);+ }+ if (bound != null) out.remove(bound);+ while (out.length > maxSignedOutAccounts) {+ out.removeAt(0);+ }+ if (out.isNotEmpty && storage is KeyListingLocalKeyValueStore) {+ for (final key in await storage.keys()) {+ if (out.contains(swarmKeyAccount(key))) await storage.delete(key);+ }+ }+ if (out.isEmpty) {+ await storage.delete(signedOutAccountsKey);+ } else {+ await storage.write(signedOutAccountsKey, jsonEncode(out));+ }+});++Future<List<String>> _signedOut(LocalKeyValueStore storage) async {+ try {+ final raw = await storage.read(signedOutAccountsKey);+ if (raw == null) return [];+ return (jsonDecode(raw) as List).whereType<String>().toList();+ } catch (_) {+ return [];+ }+}++/// The client's storage on the web: a write for an account that is not the+/// one signed in on this page is dropped, so a draft, a hidden Swarm, a+/// launch or a switcher pick saved after sign-out (a timer, a flush, a reply+/// landing late) writes nothing. Reads and deletes go through.+class SwarmAccountStorage+ implements BatchLocalKeyValueStore, SynchronizedLocalKeyValueStore {+ SwarmAccountStorage(this.inner, {required this.writes});++ final LocalKeyValueStore inner;++ /// Whether a key of this account may be written now.+ final bool Function(String account) writes;++ @override+ Future<String?> read(String key) => inner.read(key);++ @override+ Future<Map<String, String?>> readMany(Iterable<String> keys) =>+ inner.readMany(keys);++ @override+ Future<void> write(String key, String value) {+ final account = swarmKeyAccount(key);+ if (account != null && !writes(account)) return Future.value();+ return inner.write(key, value);+ }++ @override+ Future<void> delete(String key) => inner.delete(key);++ @override+ Future<T> synchronized<T>(String scope, Future<T> Function() action) =>+ inner.synchronized(scope, action);+}diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dartindex acf872d0f..e7a17904a 100644--- a/desktop/lib/super_tabs/client.dart+++ b/desktop/lib/super_tabs/client.dart@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';import 'package:flutter/foundation.dart';import '../core/local_key_value_store.dart';+import 'account_keys.dart';import 'attachment_upload.dart';import 'avatar_upload.dart';import 'controller.dart';@@ -28,7 +29,7 @@ typedef SuperTabListing = ({String id, String name});class SuperTabClient {SuperTabClient({required this.transport,- required this.storage,+ required LocalKeyValueStore storage,LocalKeyValueStore? viewStorage,this.onSnapshot,this.onTabs,@@ -39,9 +40,19 @@ class SuperTabClient {this.upload = refuseUpload,this.avatarUpload = refuseAvatarUpload,this.discoveryInterval = const Duration(seconds: 15),- }) : viewStorage = viewStorage ?? storage;+ }) : _storage = storage,+ viewStorage = viewStorage ?? storage;final SuperTabTransport transport;- final LocalKeyValueStore storage;+ final LocalKeyValueStore _storage;++ /// Where Swarm drafts, launches, hidden Swarms and the switcher's pick are+ /// kept, per account. On the web a write for an account that is not signed+ /// in on this page is dropped ([SwarmAccountStorage]): one landing after a+ /// sign-out would put back what it cleared.+ late final LocalKeyValueStore storage = SwarmAccountStorage(+ _storage,+ writes: (account) => !_forgetsWebOnly || account == _account,+ );/// Where each Swarm's saved view is kept ([SuperTabSavedViews]): a few/// hundred KB each, so Desktop keeps them out of [storage]'s small file.@@ -109,6 +120,9 @@ class SuperTabClient {// The account bound before the host said views are kept, at boot. With// none bound yet, the bind that follows claims.if (claims && _account != null) _claimViews();+ // A page that starts signed out still sweeps what another page wrote of+ // an account after it signed out.+ if (claims && _account == null) _forgetSignedOut();for (final controller in _loaded.values) {controller.reading = value;}@@ -150,8 +164,30 @@ class SuperTabClient {unawaited(_views.claim(_account, leaving: leaving).catchError((Object _) {}),);+ _forgetSignedOut(leaving: leaving);+ }++ /// The web's sign-out: the drafts, launches, hidden Swarms and switcher+ /// pick of the account leaving go, and those of any account signed out on+ /// this browser that another page wrote after ([forgetSwarmAccounts]).+ /// The account signed in now, and any other, keep theirs. Desktop keeps+ /// each account's, as before.+ void _forgetSignedOut({String? leaving}) {+ if (!_forgetsWebOnly) return;+ final bound = _account;+ _forgetting = _forgetting+ .then(+ (_) => forgetSwarmAccounts(_storage, bound: bound, leaving: leaving),+ )+ .catchError((Object _) {});}+ Future<void> _forgetting = Future.value();++ /// The last sign-out's clearing, for tests and Settings.+ @visibleForTesting+ Future<void> get forgotten => _forgetting;+/// Moves each time a Swarm's view is kept on this device: Settings' Clear/// now stops saying Cleared once one is kept again.ValueListenable<int> get viewsKept => _viewsKept;diff --git a/desktop/test/super_tab_web_sign_out_test.dart b/desktop/test/super_tab_web_sign_out_test.dartnew file mode 100644index 000000000..100fdfd48--- /dev/null+++ b/desktop/test/super_tab_web_sign_out_test.dart@@ -0,0 +1,218 @@+import 'dart:async';++import 'package:fake_async/fake_async.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/super_tabs/account_keys.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/reading.dart';++import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show MemoryStore;++// Signing out on the web clears what the browser keeps of that account's+// Swarms beside its saved views (Huy, 10-30, the follow-up of #2306): its+// drafts, launches, hidden Swarms and switcher pick. Another account's stay,+// and a save that lands after the sign-out writes nothing.++/// The browser's storage: it can list its keys.+class _BrowserStore extends MemoryStore+ implements KeyListingLocalKeyValueStore {+ @override+ Future<List<String>> keys() async => values.keys.toList();+}++const _web = SuperTabReading(+ quietPoll: Duration(seconds: 15),+ pausesAway: true,+ readsOnConnect: true,+ connectGrace: Duration(seconds: 10),+ messagesWithState: true,+ drawsSaved: true,+);++/// What an account keeps here beside its saved views.+Map<String, String> _kept(String account) => {+ 'super_tab.$account.tab': '{"drafts":{"lead":"half a sentence"}}',+ 'super_tab.launch.$account.desk.lead': '{"phase":"draft"}',+ 'super_tab.hidden.$account': '["other"]',+ 'super_tab.personal.$account': 'tab',+};++Future<Object?> _transport(+ ConversationServer server,+ String method,+ String path, {+ Map<String, dynamic>? body,+}) async {+ if (Uri.parse(path).path == '/api/super-tabs/list') {+ return {+ 'tabs': [+ {'id': 'tab', 'name': 'Pilot'},+ ],+ 'next': null,+ };+ }+ return server.request(method, path, body: body);+}++SuperTabClient _client(+ LocalKeyValueStore store, {+ SuperTabReading reading = _web,+ ConversationServer? server,+}) {+ final backend = server ?? ConversationServer();+ return SuperTabClient(+ transport: (method, path, {body}) =>+ _transport(backend, method, path, body: body),+ storage: store,+ discoveryInterval: Duration.zero,+ )..reading = reading;+}++Iterable<String> _swarmKeys(MemoryStore store, String account) =>+ store.values.keys.where((key) => swarmKeyAccount(key) == account);++void main() {+ test('names whose each Swarm key is, and no one for the saved views', () {+ expect(swarmKeyAccount('super_tab.owner.tab'), 'owner');+ expect(swarmKeyAccount('super_tab.launch.owner.desk.lead'), 'owner');+ expect(swarmKeyAccount('super_tab.hidden.owner'), 'owner');+ expect(swarmKeyAccount('super_tab.personal.owner'), 'owner');+ for (final key in [+ 'super_tab.view.owner.tab',+ 'super_tab.views.owner',+ 'super_tab.saved_by',+ signedOutAccountsKey,+ 'super_tab.owner',+ 'harness.other',+ 'theme',+ ]) {+ expect(swarmKeyAccount(key), isNull, reason: key);+ }+ });++ test('signing out clears that account\'s drafts, launches, hidden Swarms '+ 'and pick, and keeps another account\'s', () async {+ final store = _BrowserStore()+ ..values.addAll(_kept('owner'))+ ..values.addAll(_kept('other'))+ ..values['theme'] = 'dark';+ final client = _client(store);+ addTearDown(client.dispose);+ client.bind('owner');+ await client.forgotten;+ expect(_swarmKeys(store, 'owner'), hasLength(4));++ client.bind(null);+ await client.forgotten;+ expect(_swarmKeys(store, 'owner'), isEmpty);+ expect(+ Map.fromEntries(+ _swarmKeys(store, 'other').map((k) => MapEntry(k, store.values[k])),+ ),+ _kept('other'),+ );+ expect(store.values['theme'], 'dark');+ });++ test(+ 'switching accounts clears the one leaving and keeps the one coming',+ () async {+ final store = _BrowserStore()+ ..values.addAll(_kept('owner'))+ ..values.addAll(_kept('other'));+ final client = _client(store);+ addTearDown(client.dispose);+ client.bind('owner');+ client.bind('other');+ await client.forgotten;+ expect(_swarmKeys(store, 'owner'), isEmpty);+ expect(_swarmKeys(store, 'other'), hasLength(4));+ },+ );++ test('a draft saved after the sign-out writes nothing: its timer, the '+ 'close\'s flush, a hidden Swarm and a launch or pick saved late', () {+ fakeAsync((async) {+ final store = _BrowserStore();+ final client = _client(store, server: ConversationServer()..append('Hi'));+ addTearDown(client.dispose);+ client+ ..bind('owner')+ ..show('tab');+ SuperTabController? c;+ client.open('tab').then((opened) => c = opened);+ async.elapse(const Duration(seconds: 1));+ expect(c, isNotNull);+ // Typed just before signing out: the 200 ms save is still waiting.+ c!.setDraft('lead', 'half a sentence');+ final hiding = client.setTabVisible('tab', false);+ client.bind(null);+ async.elapse(const Duration(seconds: 1));+ unawaited(hiding);+ // A launch form and the switcher answer after the sign-out.+ unawaited(client.storage.write('super_tab.launch.owner.desk.lead', '{}'));+ unawaited(client.storage.write('super_tab.personal.owner', 'tab'));+ async.elapse(const Duration(seconds: 1));+ expect(_swarmKeys(store, 'owner'), isEmpty);+ });+ });++ test('a key another page wrote after the sign-out goes at the next sign-in '+ 'or reload, and comes back once that account signs in again', () async {+ final store = _BrowserStore();+ final client = _client(store);+ addTearDown(client.dispose);+ client.bind('owner');+ client.bind(null);+ await client.forgotten;+ // Another page of this browser had not reloaded yet.+ store.values.addAll(_kept('owner'));+ final reload = _client(store);+ addTearDown(reload.dispose);+ reload.bind('other');+ await reload.forgotten;+ expect(_swarmKeys(store, 'owner'), isEmpty);++ // Signed in again: theirs to keep from now on.+ reload.bind('owner');+ await reload.forgotten;+ await reload.storage.write('super_tab.personal.owner', 'tab');+ expect(store.values['super_tab.personal.owner'], 'tab');+ reload.bind('owner2');+ await reload.forgotten;+ final again = _client(store);+ addTearDown(again.dispose);+ again.bind('owner');+ await again.forgotten;+ await again.storage.write('super_tab.hidden.owner', '[]');+ expect(store.values['super_tab.hidden.owner'], '[]');+ });++ test('remembers a bounded number of accounts signed out here', () async {+ final store = _BrowserStore();+ for (var i = 0; i < maxSignedOutAccounts + 4; i++) {+ await forgetSwarmAccounts(store, bound: null, leaving: 'a$i');+ }+ final kept = store.values[signedOutAccountsKey]!;+ expect(kept, isNot(contains('"a0"')));+ expect(kept, contains('"a${maxSignedOutAccounts + 3}"'));+ });++ test(+ 'Desktop keeps each account\'s drafts when it signs out, as before',+ () async {+ final store = _BrowserStore()..values.addAll(_kept('owner'));+ final client = _client(store, reading: SuperTabReading.desktop);+ addTearDown(client.dispose);+ client.bind('owner');+ client.bind(null);+ await client.forgotten;+ await client.storage.write('super_tab.personal.owner', 'other');+ expect(_swarmKeys(store, 'owner'), hasLength(4));+ expect(store.values['super_tab.personal.owner'], 'other');+ },+ );+}diff --git a/desktop/test/swarm_view_files_test.dart b/desktop/test/swarm_view_files_test.dartindex c5574eccb..289578bd1 100644--- a/desktop/test/swarm_view_files_test.dart+++ b/desktop/test/swarm_view_files_test.dart@@ -12,6 +12,7 @@ import 'package:harness/core/harness_file_store.dart';import 'package:harness/logging/app_log.dart';import 'package:harness/state/app_state.dart';import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/super_tabs/account_keys.dart';import 'package:harness/super_tabs/saved_view.dart';import 'super_tab_saved_view_test.dart' show savedViewForTest;@@ -118,7 +119,12 @@ void main() {);addTearDown(real.dispose);expect(real.localStore, same(HarnessFileStore.shared));- expect(real.superTabs.storage, same(HarnessFileStore.shared));+ // The settings store, behind the web's guard on a signed-out account's+ // writes (super_tabs/account_keys.dart).+ expect(+ (real.superTabs.storage as SwarmAccountStorage).inner,+ same(HarnessFileStore.shared),+ );expect(real.superTabs.viewStorage, isNot(same(HarnessFileStore.shared)));expect(real.superTabs.viewStorage, isNot(isA<HarnessFileStore>()));});diff --git a/desktop/test/web/swarm_sign_out_browser_test.dart b/desktop/test/web/swarm_sign_out_browser_test.dartnew file mode 100644index 000000000..e395f7c12--- /dev/null+++ b/desktop/test/web/swarm_sign_out_browser_test.dart@@ -0,0 +1,95 @@+@TestOn('browser')+library;++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/harness_file_store.dart';+import 'package:harness/super_tabs/client.dart';+import 'package:harness/super_tabs/reading.dart';+import 'package:web/web.dart' as web;++// The web's sign-out in a real browser's storage (the follow-up of #2306):+// what the page keeps of an account's Swarms goes from localStorage, another+// account's and the page's own settings stay.+void main() {+ const prefix = 'harness.web.v1.';+ const reading = SuperTabReading(+ quietPoll: Duration(seconds: 15),+ pausesAway: true,+ readsOnConnect: true,+ connectGrace: Duration(seconds: 10),+ messagesWithState: true,+ drawsSaved: true,+ );+ final clients = <SuperTabClient>[];+ SuperTabClient client() {+ final made = SuperTabClient(+ transport: (method, path, {body}) async => throw UnimplementedError(),+ storage: HarnessFileStore(),+ discoveryInterval: Duration.zero,+ )..reading = reading;+ clients.add(made);+ return made;+ }++ Iterable<String> stored() sync* {+ final local = web.window.localStorage;+ for (var i = 0; i < local.length; i++) {+ yield local.key(i)!;+ }+ }++ setUp(() {+ // Flutter's isolated test origin; never the user's browser profile.+ web.window.localStorage.clear();+ });+ tearDown(() {+ for (final made in clients) {+ made.dispose();+ }+ clients.clear();+ web.window.localStorage.clear();+ });++ test('signing out removes that account\'s Swarm keys from localStorage, '+ 'and keeps another account\'s and the page\'s own', () async {+ final page = client()..bind('owner');+ await page.forgotten;+ for (final key in [+ 'super_tab.owner.tab',+ 'super_tab.launch.owner.desk.lead',+ 'super_tab.hidden.owner',+ 'super_tab.personal.owner',+ ]) {+ await page.storage.write(key, '{}');+ }+ web.window.localStorage+ ..setItem('${prefix}super_tab.other.tab', '{}')+ ..setItem('${prefix}theme_mode', 'dark');+ expect(stored().where((k) => k.contains('.owner')), hasLength(4));++ page.bind(null);+ await page.forgotten;+ expect(stored().where((k) => k.contains('.owner')), isEmpty);+ expect(+ web.window.localStorage.getItem('${prefix}super_tab.other.tab'),+ '{}',+ );+ expect(web.window.localStorage.getItem('${prefix}theme_mode'), 'dark');++ // A late save from this page after the sign-out is dropped.+ await page.storage.write('super_tab.owner.tab', '{"drafts":{}}');+ expect(+ web.window.localStorage.getItem('${prefix}super_tab.owner.tab'),+ isNull,+ );++ // Another page wrote one before it reloaded: the next page's start sweeps it.+ web.window.localStorage.setItem('${prefix}super_tab.owner.tab', '{}');+ final next = client()..bind(null);+ await next.forgotten;+ expect(+ web.window.localStorage.getItem('${prefix}super_tab.owner.tab'),+ isNull,+ );+ });+}diff --git a/docs/specs/2026-10-30-web-swarm-direct.md b/docs/specs/2026-10-30-web-swarm-direct.mdindex e117e4a2d..8eedb4acd 100644--- a/docs/specs/2026-10-30-web-swarm-direct.md+++ b/docs/specs/2026-10-30-web-swarm-direct.md@@ -83,14 +83,16 @@ browser coming back online, not on a machine connecting. The machine-connect tri### Caching and offline-Unchanged in kind, with one gap left for a follow-up (below). The web's saved Swarm views (`SuperTabSavedViews`, browser storage) are already claimed per+Unchanged in kind. The web's saved Swarm views (`SuperTabSavedViews`, browser storage) are already claimed peraccount, forgotten when another account signs in on that browser or the account leaves, and cleared by Settings ▸Account ▸ Clear now. In-memory state is per account generation (`SuperTabClient.request` drops answers that landafter an account change; `superTabMachineRequest` the same by `_authRevision`). Offline: reads fail with the networktext above and retry on the existing poll; posts stay in the composer with their operation id, as now.-What a sign-out on the web leaves in browser storage today (each keyed by account, so another account signing in never-reads them through the app, but they stay on a shared browser). Follow-up: clear them on a web sign-out.+What else the web keeps of an account in browser storage, each keyed by account. A web sign-out (or another account+signing in) removes the leaving account's, and leaves any other account's (`super_tabs/account_keys.dart`). A write for an+account no longer signed in on that page is dropped, so a draft saved late cannot put one back; one another page wrote+before it reloaded is swept at the next sign-in or page start (`super_tab.signed_out`, at most 16 accounts).- `super_tab.<account>.<swarm>`: each Swarm's unsent composer drafts per conversation, its selection and what is expanded;- `super_tab.launch.<account>.<tab>.<conversation>`: an unsent New Harness or New Project draft;- `super_tab.hidden.<account>`: the Swarms hidden on this browser;@@ -150,8 +152,10 @@ sign-out on shared machines), no critical or important findings; their minor oneor the Team account's. Missing or expired sign-in: the backend answers 401, and the app's existing sign-in flowtakes over. Nothing falls back to a machine.9. **Failure:** backend unreachable → "Could not reach Harness. Check your connection." with a bounded retry on the- existing poll (no stuck Loading). Access lost (403/404) → the existing `accessRevoked` path clears the view, as- today. Account changed mid-request → the answer is dropped (`ACCOUNT_CHANGED`). A machine-only action whose machine+ existing poll (no stuck Loading). Access lost → the existing `accessRevoked` path clears the view, as+ today. On the routes a person's app calls, anything the caller cannot reach (missing, never joined, removed, outside+ the Workspace, a refused link, another project's chat) answers one 404 with one body (`routes/superTabs.ts`+ `NOT_AVAILABLE`), so the answer never says which; the server log keeps the reason. Account changed mid-request → the answer is dropped (`ACCOUNT_CHANGED`). A machine-only action whose machinecannot answer → the specific text in the table above. 426 → "Update Harness".10. **Platforms:** web on desktop and phone browsers changes. Native macOS, Windows and Linux are unchanged (localdaemon). The phone app is unchanged (still relays) and is a follow-up.