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
Merge batch 11-03 bt: #2713 #2714 (#2736)
0xken15d33f1e278607
diff --git a/backend/integration/superTabAutoJoin.test.ts b/backend/integration/superTabAutoJoin.test.tsnew file mode 100644index 000000000..4f837c0cd--- /dev/null+++ b/backend/integration/superTabAutoJoin.test.ts@@ -0,0 +1,475 @@+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, beforeEach, describe, expect, it, vi } 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'+import * as parts from '../src/superTabs/parts/index.js'+import type { SuperTabState } from '../src/superTabs/model.js'+import { addMember, memberId } from '../src/superTabs/workspaceStore.js'++// Ken's spec docs/specs/2026-11-03-swarm-domain-auto-join.md, "Tests that fail first": people at the owner's own email domain+// join a Swarm whose owner turned "Add them automatically" on, on their own list read; nobody at a public domain ever does.++let replica: MongoMemoryReplSet, db: PrismaClient, store: SuperTabStore, app: FastifyInstance, uri: string+/** The store's clock: tests move it past the 2-minute try window. */+let clock = Date.now()++const account = (n: number, email: string): AuthUser => ({ sub: `3000000000000000000000${n.toString(16).padStart(2, '0')}`, email, autonomousEnv: 'prod', role: 'user' })+const ken = account(1, '[email protected]'), x = account(2, '[email protected]'), gmailOwner = account(3, '[email protected]'), xGmail = account(4, '[email protected]')+const relay = account(5, '[email protected]'), partner = account(6, '[email protected]')+const accounts = [ken, x, gmailOwner, xGmail, relay, partner]++/** A Swarm's whole state as its parts hold it. */+async function storedState(tab: string): Promise<SuperTabState> {+ return parts.reassemble(await db.$transaction(tx => parts.loadAll(tx, tab)))+}+/** Replaces a Swarm's parts with `state`, as an older release would have left them. */+async function saveState(tab: string, state: SuperTabState) {+ await db.$transaction(async tx => {+ const current = await parts.loadAll(tx, tab)+ const version = Math.max(current.head.version, ...[...current.members, ...current.agents, ...current.groups, ...current.machines,+ ...current.starts, ...current.progress].map(p => p.version)) + 1+ for (const model of [tx.swarmHead, tx.swarmMember, tx.swarmAgent, tx.swarmGroup, tx.swarmMachine, tx.swarmStart, tx.swarmProgress] as unknown as+ Array<{ deleteMany(args: unknown): Promise<unknown> }>) await model.deleteMany({ where: { tabId: tab } })+ await parts.insertParts(tx, { ...parts.split(state, { tabId: tab, version, now: Date.now(), visibilityEpoch: current.visibilityEpoch }),+ sequenceBase: current.sequenceBase })+ })+}+/** The owner the helpers act as by default: ken, or the owner of the test's own company (org). */+let current = ken+let nextAccount = 0x40+/** A company of its own for one test, so Swarms of other tests at the same domain never fill its try of ten: its owner becomes+ * the helpers' default, and each name is a person at its domain. */+const org = async (label: string, names: string[]): Promise<Record<string, AuthUser>> => {+ const make = async (name: string) => {+ const user = account(nextAccount++, `${name}@${label}.com`)+ accounts.push(user)+ await db.user.create({ data: { id: user.sub, externalId: `auto-join-fixture-${user.sub}`, email: user.email, autonomousEnv: user.autonomousEnv } })+ return user+ }+ current = await make('owner')+ const people: Record<string, AuthUser> = {}+ for (const name of names) people[name] = await make(name)+ return people+}+const request = (path: string, body?: object, user: AuthUser = current, method?: 'GET' | 'POST') =>+ app.inject({ method: method ?? (body ? 'POST' : 'GET'), url: `/api/super-tabs/${path}`,+ headers: { authorization: `Bearer ${user.sub}` }, ...(body ? { payload: body } : {}) })+/** Saves sharing as `owner` through the API, at the current revision. */+const save = async (tab: string, access: GeneralAccess | Record<string, unknown>, owner: AuthUser = current) => {+ const current = await store.sharing(owner, tab)+ return request(`${tab}/sharing`, { operationId: randomUUID(), revision: current.revision, access }, owner)+}+const create = async (owner: AuthUser = current, name = 'Acme Swarm') => (await store.create(owner, randomUUID(), name)).id+const later = () => { clock += 121_000 }+const turnOn = (tab: string, role: 'collaborator' | 'viewer' = 'collaborator', owner: AuthUser = current) =>+ save(tab, { mode: 'domain', domain: owner.email.split('@')[1]!, role, autoJoin: true }, owner)+const personIn = async (tab: string, user: AuthUser) => (await storedState(tab)).people.find(p => p.id === user.sub)+const workspaceRole = async (tab: string, user: AuthUser) => {+ const { workspaceId } = await storedState(tab)+ return (await db.swarmWorkspaceMember.findUnique({ where: { id: memberId(workspaceId!, user.sub) } }))?.role+}+const listed = async (user: AuthUser) => (await request('list', undefined, user)).json().data.tabs.map((tab: { id: string }) => tab.id) as string[]++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' } })+ uri = replica.getUri(`swarm_auto_join_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, () => clock)+ for (const user of accounts) await db.user.create({ data: { id: user.sub, externalId: `auto-join-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 header = req.headers.authorization ?? ''+ const user = accounts.find(a => header === `Bearer ${a.sub}`)+ const team = accounts.find(a => header === `Bearer team:${a.sub}`)+ if (!user && !team) return reply.code(401).send({ success: false })+ req.user = user ?? { ...team!, harnessSessionKind: 'team', harnessComputerId: 'computer-1' }+ })+ await app.register(superTabRoutes, { store })+ await app.ready()+})+afterAll(async () => { await app?.close(); await db?.$disconnect(); await replica?.stop() })++describe('Domain checks on save and join', () => {+ beforeEach(() => { current = ken })+ it('refuses a public domain on save', async () => {+ const own = await create(gmailOwner)+ const refused = await save(own, { mode: 'domain', domain: 'gmail.com', role: 'collaborator' }, gmailOwner)+ expect(refused.statusCode).toBe(400)+ expect(refused.json().error.code).toBe('PUBLIC_DOMAIN')+ const tab = await create()+ const outlook = await save(tab, { mode: 'domain', domain: 'outlook.com', role: 'collaborator' })+ expect(outlook.json().error.code).toBe('PUBLIC_DOMAIN')+ })++ it('refuses auto-join at a domain that is not the owner\'s, and keeps a partner share without it', async () => {+ const tab = await create()+ const refused = await save(tab, { mode: 'domain', domain: 'partner.com', role: 'collaborator', autoJoin: true })+ expect(refused.statusCode).toBe(400)+ expect(refused.json().error.code).toBe('DOMAIN_NOT_YOURS')+ const accepted = await save(tab, { mode: 'domain', domain: 'partner.com', role: 'collaborator' })+ expect(accepted.statusCode).toBe(200)+ expect(accepted.json().data.access).toEqual({ mode: 'domain', domain: 'partner.com', role: 'collaborator', autoJoin: false })+ const joined = await request(`${tab}/join`, { operationId: randomUUID() }, partner)+ expect(joined.statusCode).toBe(200)+ expect(joined.json().data).toMatchObject({ id: tab, role: 'collaborator', alreadyMember: false })+ })++ it('keeps autoJoin when a save leaves it out, turns it off with false, and clears it with another mode', async () => {+ const tab = await create()+ const on = await save(tab, { mode: 'domain', domain: 'acme.com', role: 'collaborator', autoJoin: true })+ expect(on.json().data.access.autoJoin).toBe(true)+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDomain).toBe('acme.com')+ // An older Desktop saves without the field: it never turns auto-join off by accident.+ const kept = await save(tab, { mode: 'domain', domain: 'acme.com', role: 'viewer' })+ expect(kept.json().data.access).toEqual({ mode: 'domain', domain: 'acme.com', role: 'viewer', autoJoin: true })+ const off = await save(tab, { mode: 'domain', domain: 'acme.com', role: 'viewer', autoJoin: false })+ expect(off.json().data.access.autoJoin).toBe(false)+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDomain).toBeNull()+ await save(tab, { mode: 'domain', domain: 'acme.com', role: 'viewer', autoJoin: true })+ const link = await save(tab, { mode: 'link', role: 'viewer' })+ expect(link.json().data.access).toEqual({ mode: 'link', role: 'viewer' })+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDomain).toBeNull()+ const back = await save(tab, { mode: 'domain', domain: 'acme.com', role: 'viewer' })+ expect(back.json().data.access.autoJoin).toBe(false)+ })++ it('drops a kept autoJoin when an older app saves another domain, instead of refusing it', async () => {+ const tab = await create()+ await save(tab, { mode: 'domain', domain: 'acme.com', role: 'collaborator', autoJoin: true })+ const moved = await save(tab, { mode: 'domain', domain: 'partner.com', role: 'collaborator' })+ expect(moved.statusCode).toBe(200)+ expect(moved.json().data.access.autoJoin).toBe(false)+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDomain).toBeNull()+ })++ it('answers JOIN_UNAVAILABLE for an old share at a public domain, and shows it turned off', async () => {+ const tab = await create()+ await save(tab, { mode: 'domain', domain: 'acme.com', role: 'collaborator' })+ const state = await storedState(tab)+ state.sharing!.access = { mode: 'domain', domain: 'gmail.com', role: 'collaborator' }+ await saveState(tab, state)+ // The route answers a non-member's refusal as for a Swarm that does not exist (routes/superTabs.ts NOT_AVAILABLE).+ expect((await request(`${tab}/join`, { operationId: randomUUID() }, xGmail)).statusCode).toBe(404)+ await expect(store.join(xGmail, tab, { operationId: randomUUID() })).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })+ expect((await request(`${tab}/join/preview`, {}, xGmail)).statusCode).toBe(404)+ const details = (await request(`${tab}/sharing`)).json().data+ expect(details.access).toEqual({ mode: 'invited', role: 'collaborator' })+ expect(details.turnedOffDomain).toBe('gmail.com')+ expect(details.joinUrl).toBeNull()+ })++ it('tells the Share dialog the owner\'s own domain and whether anyone can have an address there', async () => {+ const tab = await create()+ expect((await request(`${tab}/sharing`)).json().data).toMatchObject({ ownDomain: 'acme.com', ownDomainPublic: false, autoJoinFull: false })+ const own = await create(gmailOwner)+ expect((await request(`${own}/sharing`, undefined, gmailOwner)).json().data).toMatchObject({ ownDomain: 'gmail.com', ownDomainPublic: true })+ })+})++describe('Joining by domain on the person\'s own list read', () => {+ it('joins [email protected] to the acme Swarm with auto-join on, as a Workspace guest, with the role the owner picked', async () => {+ const { x } = await org('one', ['x'])+ const on = await create(), linkOnly = await create(), invited = await create()+ await turnOn(on, 'viewer')+ await save(linkOnly, { mode: 'domain', domain: current.email.split('@')[1]!, role: 'collaborator' })+ const tabs = await listed(x)+ expect(tabs).toContain(on)+ expect(tabs).not.toContain(linkOnly)+ expect(tabs).not.toContain(invited)+ expect(await personIn(on, x)).toMatchObject({ role: 'viewer', joinedVia: 'domain', email: x.email })+ expect(await workspaceRole(on, x)).toBe('guest')+ expect(await personIn(linkOnly, x)).toBeUndefined()+ })++ it('joins nobody at a public domain', async () => {+ const own = await create(gmailOwner)+ // Even a share an older release saved at gmail.com with auto-join on lets nobody in.+ const state = await storedState(own)+ state.sharing = { revision: 1, generation: 'old', access: { mode: 'domain', domain: 'gmail.com', role: 'collaborator', autoJoin: true } }+ await saveState(own, state)+ await db.superTab.update({ where: { id: own }, data: { autoJoinDomain: 'gmail.com' } })+ expect(await listed(xGmail)).toEqual([])+ expect(await listed(relay)).toEqual([])+ expect(await personIn(own, xGmail)).toBeUndefined()+ })++ it('joins through the Workspaces list too', async () => {+ const { y } = await org('two', ['y'])+ const tab = await create()+ await turnOn(tab)+ expect((await request('workspaces', undefined, y)).statusCode).toBe(200)+ expect(await personIn(tab, y)).toMatchObject({ role: 'collaborator', joinedVia: 'domain' })+ })++ it('keeps the role of someone already a member of the Workspace', async () => {+ const { z } = await org('three', ['z'])+ const tab = await create()+ await turnOn(tab)+ const { workspaceId } = await storedState(tab)+ await db.$transaction(tx => addMember(tx, workspaceId!, { id: z.sub, email: z.email }, 'member', current.sub, randomUUID()))+ expect(await listed(z)).toContain(tab)+ expect(await workspaceRole(tab, z)).toBe('member')+ })++ it('joins ten Swarms per try, and the rest after two minutes', async () => {+ const { b1 } = await org('beta', ['b1'])+ const tabs: string[] = []+ for (let i = 0; i < 11; i++) { const tab = await create(current, `Beta ${i}`); await turnOn(tab); tabs.push(tab) }+ expect((await listed(b1)).filter(id => tabs.includes(id))).toHaveLength(10)+ expect((await listed(b1)).filter(id => tabs.includes(id))).toHaveLength(10)+ later()+ expect((await listed(b1)).filter(id => tabs.includes(id)).sort()).toEqual([...tabs].sort())+ })++ it('never joins from a team session', async () => {+ const { t } = await org('four', ['t'])+ const tab = await create()+ await turnOn(tab)+ const team = await app.inject({ method: 'GET', url: '/api/super-tabs/list', headers: { authorization: `Bearer team:${t.sub}` } })+ expect(team.statusCode).toBe(403)+ expect((await app.inject({ method: 'GET', url: '/api/super-tabs/workspaces', headers: { authorization: `Bearer team:${t.sub}` } })).statusCode).toBe(403)+ expect(await personIn(tab, t)).toBeUndefined()+ })++ it('writes no membership after turning auto-join off commits', async () => {+ for (let i = 0; i < 4; i++) {+ const { w, v } = await org(`five${i}`, ['w', 'v'])+ const tab = await create()+ await turnOn(tab)+ const revision = (await store.sharing(current, tab)).revision+ const off = { operationId: randomUUID(), revision, access: { mode: 'domain' as const, domain: current.email.split('@')[1]!, role: 'collaborator' as const, autoJoin: false } }+ await Promise.all([store.saveSharing(current, tab, off), store.autoJoinSwarm(w, tab).catch(() => 'conflict')])+ const parts = await db.$transaction(tx => import('../src/superTabs/parts/index.js').then(p => p.loadAll(tx, tab)))+ const joined = parts.members.find(m => m.key === w.sub && !m.deleted)+ // Joined only before the turn-off: the turn-off's head write is then the later one.+ if (joined) expect(joined.changedAt).toBeLessThan(parts.head.changedAt)+ expect(await store.autoJoinSwarm(v, tab)).toBe('skipped')+ expect(await personIn(tab, v)).toBeUndefined()+ }+ })++ it('stops at 200 people, and tells the owner', async () => {+ const { u } = await org('six', ['u'])+ const tab = await create()+ await turnOn(tab)+ const state = await storedState(tab)+ for (let i = state.people.length; i < 200; i++) state.people.push({ id: `filler${i}`, email: `filler${i}@acme.com`, role: 'viewer', generation: `g${i}` })+ await saveState(tab, state)+ expect(await listed(u)).not.toContain(tab)+ expect(await personIn(tab, u)).toBeUndefined()+ expect((await request(`${tab}/sharing`)).json().data.autoJoinFull).toBe(true)+ })++ it('joins nobody to a deleted Swarm', async () => {+ const { d1 } = await org('seven', ['d1'])+ const tab = await create(current, 'Doomed')+ await turnOn(tab)+ await store.execute(current, tab, { operationId: randomUUID(), command: { type: 'swarm.delete', name: 'Doomed' } })+ expect((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDomain).toBeNull()+ expect(await store.autoJoinSwarm(d1, tab)).toBe('skipped')+ await listed(d1)+ expect(await personIn(tab, d1)).toBeUndefined()+ })++ it('makes one membership when two reads of the same person race', async () => {+ const { s1 } = await org('eight', ['s1'])+ const tab = await create()+ await turnOn(tab)+ const outcomes = await Promise.all([store.autoJoinSwarm(s1, tab), store.autoJoinSwarm(s1, tab)])+ expect(outcomes.sort()).toEqual(['joined', 'skipped'])+ expect((await storedState(tab)).people.filter(p => p.id === s1.sub)).toHaveLength(1)+ })+})++describe('Leaving is final for auto-join', () => {+ const declinedOf = async (tab: string) => (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).autoJoinDeclined+ const leave = (user: AuthUser, tab: string, by: AuthUser = user) =>+ store.execute(by, tab, { operationId: randomUUID(), command: { type: 'member.remove', userId: user.sub } })++ it('does not pull back someone who left', async () => {+ const { leaver } = await org('nine', ['leaver'])+ const tab = await create()+ await turnOn(tab)+ expect(await listed(leaver)).toContain(tab)+ await leave(leaver, tab)+ expect(await declinedOf(tab)).toContain(leaver.sub)+ later()+ expect(await listed(leaver)).not.toContain(tab)+ expect(await personIn(tab, leaver)).toBeUndefined()+ })++ it('does not pull back someone the owner removed, and keeps that across turning auto-join off and on', async () => {+ const { removed } = await org('ten', ['removed'])+ const tab = await create()+ await turnOn(tab)+ await listed(removed)+ await leave(removed, tab, current)+ await save(tab, { mode: 'invited', role: 'collaborator' })+ await turnOn(tab)+ expect(await declinedOf(tab)).toContain(removed.sub)+ later()+ expect(await listed(removed)).not.toContain(tab)+ })++ it('lets someone come back on purpose by an accepted invitation, which clears the decline', async () => {+ const { invitee } = await org('eleven', ['invitee'])+ const tab = await create()+ await turnOn(tab)+ await listed(invitee)+ await leave(invitee, tab)+ const invite = await store.execute(current, tab, { operationId: randomUUID(),+ command: { type: 'invite.create', email: invitee.email, role: 'viewer', conversationId: 'lead' } })+ await store.execute(invitee, tab, { operationId: randomUUID(), command: { type: 'invite.accept', inviteId: String(invite.result.inviteId) } })+ expect(await declinedOf(tab)).not.toContain(invitee.sub)+ expect(await personIn(tab, invitee)).toMatchObject({ role: 'viewer' })+ expect((await personIn(tab, invitee))!.joinedVia).toBeUndefined()+ })++ it('lets someone come back on purpose by a shared link, which clears the decline', async () => {+ const { linked } = await org('twelve', ['linked'])+ const tab = await create()+ await turnOn(tab)+ await listed(linked)+ await leave(linked, tab)+ const link = (await save(tab, { mode: 'link', role: 'collaborator' })).json().data+ const token = new URL(link.joinUrl).searchParams.get('token')!+ expect((await request(`${tab}/join`, { operationId: randomUUID(), token }, linked)).statusCode).toBe(200)+ expect(await declinedOf(tab)).not.toContain(linked.sub)+ expect((await personIn(tab, linked))!.joinedVia).toBeUndefined()+ })++ // Security review 1 of #2714: the domain's own join link needs no token, so it must not undo a leave or a removal.+ it('keeps someone who left or was removed out of the domain link too', async () => {+ const { gone, ousted } = await org('seventeen', ['gone', 'ousted'])+ const tab = await create()+ await turnOn(tab)+ await listed(gone)+ await listed(ousted)+ await leave(gone, tab)+ await leave(ousted, tab, current)+ for (const user of [gone, ousted]) {+ expect((await request(`${tab}/join/preview`, {}, user)).statusCode).toBe(404)+ expect((await request(`${tab}/join`, { operationId: randomUUID() }, user)).statusCode).toBe(404)+ await expect(store.join(user, tab, { operationId: randomUUID() })).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })+ expect(await personIn(tab, user)).toBeUndefined()+ expect(await declinedOf(tab)).toContain(user.sub)+ }+ // The same holds once the owner turns auto-join off: the domain link alone never undoes a leave or a removal.+ await save(tab, { mode: 'domain', domain: current.email.split('@')[1]!, role: 'collaborator', autoJoin: false })+ await expect(store.join(ousted, tab, { operationId: randomUUID() })).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })+ })++ it('declines someone the Workspace removed instead of joining them, and does not try that Swarm again', async () => {+ const { banned } = await org('thirteen', ['banned'])+ const tab = await create()+ await turnOn(tab)+ const { workspaceId } = await storedState(tab)+ await db.swarmWorkspaceMember.create({ data: { id: memberId(workspaceId!, banned.sub), workspaceId: workspaceId!, userId: banned.sub, email: banned.email,+ role: 'guest', generation: 'old', addedBy: current.sub, addedAt: new Date(), removedAt: new Date(), removedBy: current.sub, purgeAt: null } })+ expect(await listed(banned)).not.toContain(tab)+ expect(await personIn(tab, banned)).toBeUndefined()+ expect(await declinedOf(tab)).toContain(banned.sub)+ const tried = vi.spyOn(store, 'autoJoinSwarm')+ later()+ await listed(banned)+ expect(tried.mock.calls.filter(([, id]) => id === tab)).toEqual([])+ tried.mockRestore()+ })++ it('declines someone who joined by domain and was then removed from the Workspace', async () => {+ const { wsGone } = await org('fourteen', ['wsGone'])+ const tab = await create()+ await turnOn(tab)+ await listed(wsGone)+ const { workspaceId } = await storedState(tab)+ await store.workspaces.remove(current, workspaceId!, wsGone.sub)+ expect(await personIn(tab, wsGone)).toBeUndefined()+ expect(await declinedOf(tab)).toContain(wsGone.sub)+ })+})++describe('A Workspace removal is final for auto-join', () => {+ // Security review 2 of #2714: the Workspace's own record of a removal is purged after 30 days (sweeps.ts), so auto-join keeps+ // its own, on the Workspace, until the person is added back on purpose.+ it('never pulls back someone the Workspace removed, after the removal record is purged, until a Workspace invitation', async () => {+ const { fired } = await org('eighteen', ['fired'])+ const first = await create()+ await turnOn(first)+ expect(await listed(fired)).toContain(first)+ const { workspaceId } = await storedState(first)+ await store.workspaces.remove(current, workspaceId!, fired.sub)+ // What the purge leaves: no member row and no removal row.+ await db.swarmWorkspaceMember.deleteMany({ where: { workspaceId: workspaceId!, userId: fired.sub } })+ await db.swarmWorkspaceRemoval.deleteMany({ where: { workspaceId: workspaceId!, userId: fired.sub } })+ const later_ = await create()+ await turnOn(later_)+ later()+ expect(await listed(fired)).not.toContain(later_)+ expect(await personIn(later_, fired)).toBeUndefined()+ expect((await db.superTab.findUniqueOrThrow({ where: { id: later_ } })).autoJoinDeclined).toContain(fired.sub)+ // Invited back to the Workspace on purpose: auto-join may add them again.+ await store.workspaces.invite(current, workspaceId!, fired.email, 'member')+ await store.workspaces.accept(fired, workspaceId!)+ const third = await create()+ await turnOn(third)+ later()+ expect(await listed(fired)).toContain(third)+ })+})++describe('What readers see', () => {+ it('tells every member auto-join is on, marks who came by domain, and never shows the declines or the sharing', async () => {+ const { joiner, leaver } = await org('fifteen', ['joiner', 'leaver'])+ const tab = await create()+ await turnOn(tab)+ await listed(joiner)+ await listed(leaver)+ await store.execute(leaver, tab, { operationId: randomUUID(), command: { type: 'member.remove', userId: leaver.sub } })+ const first = (await request(`${tab}/parts`, undefined, joiner)).json().data+ expect(first.head.data.autoJoin).toBe(true)+ expect(first.members.find((m: { key: string }) => m.key === joiner.sub).data.joinedVia).toBe('domain')+ expect(first.members.find((m: { key: string }) => m.key === current.sub).data.joinedVia).toBeUndefined()+ expect(first.head.data.autoJoinDeclined).toBeUndefined()+ expect(first.head.data.sharing).toBeUndefined()+ expect(JSON.stringify(first)).not.toContain(leaver.sub)+ expect((await store.read(joiner, tab)).state).toMatchObject({ autoJoin: true })+ expect((await store.read(joiner, tab)).state.autoJoinDeclined).toBeUndefined()+ await save(tab, { mode: 'domain', domain: current.email.split('@')[1]!, role: 'collaborator', autoJoin: false })+ expect((await request(`${tab}/parts`, undefined, joiner)).json().data.head.data.autoJoin).toBeUndefined()+ })+})++describe('The pre-merge production query', () => {+ it('lists the Swarms whose saved domain share is at a public domain, and no other', async () => {+ await org('sixteen', [])+ const broken = await create(), fine = await create()+ await save(fine, { mode: 'domain', domain: 'partner.com', role: 'collaborator' })+ await save(broken, { mode: 'domain', domain: 'partner.com', role: 'collaborator' })+ const state = await storedState(broken)+ state.sharing!.access = { mode: 'domain', domain: 'yahoo.com', role: 'collaborator' }+ await saveState(broken, state)+ const { stdout } = await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/tsx'), ['scripts/swarm-auto-join/public-domain-shares.ts'],+ { env: { ...process.env, DATABASE_URL: uri }, timeout: 60000 })+ const listed = JSON.parse(stdout) as { count: number; swarms: Array<{ id: string; domain: string; deleted: boolean }> }+ expect(listed.swarms).toContainEqual({ id: broken, domain: 'yahoo.com', deleted: false })+ expect(listed.swarms.map(swarm => swarm.id)).not.toContain(fine)+ expect(listed.count).toBe(listed.swarms.length)+ })+})diff --git a/backend/integration/superTabGithub.test.ts b/backend/integration/superTabGithub.test.tsindex faeb602d1..52daccdcb 100644--- a/backend/integration/superTabGithub.test.ts+++ b/backend/integration/superTabGithub.test.ts@@ -16,6 +16,7 @@ import type { Command } from '../src/superTabs/commands.js'import { GitHubTokens, MemoryTokenCache } from '../src/github/tokens.js'import { fakeApp, fakeGitHub, throwawayKey } from '../src/github/fakeGitHub.js'import { poolRows } from './hostRows.test-support.js'+import { logger } from '../src/utils/logger.js'// The Harness GitHub App's token endpoint on the real control API: a fresh loopback MongoDB and a fake GitHub. This suite// never reads DATABASE_URL, an existing database or github.com.@@ -50,11 +51,13 @@ afterAll(async () => {})/** One control API with the app configured against a fresh fake GitHub, its store revoking as tasks end. */-async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?: GitHubSignIn | null } = {}) {- const github = fakeGitHub({ publicKey: key.publicKey, appId: '424242' })- github.installed.set('example/app', 91)+async function fresh(options: { github?: boolean; approveAll?: boolean; signIn?: GitHubSignIn | null; now?: () => number+ /** Another server's GitHub, shared: a second control API on the same database and GitHub, with its own caches. */+ shared?: ReturnType<typeof fakeGitHub> } = {}) {+ const github = options.shared ?? fakeGitHub({ publicKey: key.publicKey, appId: '424242' })+ if (!options.shared) github.installed.set('example/app', 91)const log = { warn: vi.fn() }- const tokens = new GitHubTokens(fakeApp(key.privateKey, github), new MemoryTokenCache(), { log, secret: randomBytes(32) })+ const tokens = new GitHubTokens(fakeApp(key.privateKey, github, { now: options.now }), new MemoryTokenCache(), { log, secret: randomBytes(32) })const releases: Promise<void>[] = []const store = new SuperTabStore(db, Date.now, null, { workEnded: (tab, ended) => { releases.push(tokens.release(tab, ended)) },workStarted: (tab, started) => { releases.push(tokens.resume(tab, started)) } })@@ -684,3 +687,120 @@ describe('the CI load', () => {expect((await load(off, other.tab, 'lead')).json().data).toEqual({ state: 'unavailable' })})})++// Task #2316 (Dee, 2026-11-03): after lampos's repository was allowed, "Set up GitHub for teammates" stayed on everyone's+// computer for up to 5 minutes. Each project's GitHub revision moves in the Swarm state, so members' apps read again.+describe('the GitHub revision', () => {+ const signIn = { authorizeUrl: (state: string) => `https://github.test/login/oauth/authorize?state=${state}`,+ permission: async () => ({ login: 'olive', push: true }) } as unknown as GitHubSignIn+ /** A Swarm whose project and Docs are on example/app, and Other on example/other. */+ async function swarm(env: Env) {+ const { tab } = await working(env)+ const project = async (name: string, repositoryUrl: string) => {+ const made = (await env.run(tab, { type: 'project.create', name, visibility: 'public', brief: '' } as Command)).result+ await env.run(tab, { type: 'agent.add', conversationId: made.conversationId, machineId: 'owner-mac', harnessId: randomUUID(), name: 'Lead',+ configuration: config, lead: true, project: { cwd: `/work/${name}`, repositoryUrl } } as Command)+ return String(made.projectId)+ }+ return { tab, docs: await project('Docs', 'https://github.com/Example/App'), other: await project('Other', 'https://github.com/example/other.git') }+ }+ const revisions = async (env: Env, tab: string) =>+ Object.fromEntries(((await env.store.read(owner, tab)).state.projects ?? []).map(p => [p.id, p.githubRevision ?? 0]))+ const allow = async (env: Env, tab: string, projectId: string, scope: 'project' | 'swarm') => {+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/${projectId}/github/approve`,+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope } })+ const state = new URL((asked.json().data as { authorizeUrl: string }).authorizeUrl).searchParams.get('state')!+ return { state, page: await env.app.inject({ method: 'GET', url: `/api/github/callback?code=c&state=${encodeURIComponent(state)}` }) }+ }+ const check = (env: Env, tab: string, projectId: string, refresh = true, record = true) => env.app.inject({ method: 'GET',+ url: `/api/super-tabs/${tab}/projects/${projectId}/github${refresh ? `?refresh=1${record ? '' : '&record=0'}` : ''}`,+ headers: { authorization: `Bearer ${owner.sub}` } })++ it('moves every project on the repository when someone allows it, and a swarm-wide approval moves them all', async () => {+ teamAccounts()+ const env = await fresh({ approveAll: false, signIn })+ const { tab, docs, other } = await swarm(env)+ const before = await revisions(env, tab)+ expect((await allow(env, tab, 'lead', 'project')).page.statusCode).toBe(200)+ const once = await revisions(env, tab)+ expect(once).toEqual({ ...before, lead: before.lead! + 1, [docs]: before[docs]! + 1 })+ expect((await allow(env, tab, docs, 'swarm')).page.statusCode).toBe(200)+ expect(await revisions(env, tab)).toEqual({ lead: once.lead! + 1, [docs]: once[docs]! + 1, [other]: before[other] })+ })++ it('a dialog read that finds the app installed now moves it once; the same answer again moves nothing', async () => {+ teamAccounts()+ let at = Date.now()+ const env = await fresh({ approveAll: false, signIn, now: () => at })+ const { tab, docs } = await swarm(env)+ env.github.installed.delete('example/app')+ expect((await check(env, tab, 'lead')).json().data).toMatchObject({ state: 'not-installed' })+ const missing = await revisions(env, tab)+ // Installed on GitHub's own site; the dialog asks again (at most every 15 s per repository).+ env.github.installed.set('example/app', 91)+ at += 16_000+ expect((await check(env, tab, 'lead')).json().data).toMatchObject({ state: 'not-approved' })+ const found = await revisions(env, tab)+ expect(found.lead).toBe(missing.lead! + 1)+ expect(found[docs]).toBe(missing[docs])+ at += 16_000+ expect((await check(env, tab, 'lead')).json().data).toMatchObject({ state: 'not-approved' })+ expect(await revisions(env, tab)).toEqual(found)+ // A read that does not ask GitHub again records nothing: another server's cache may be older.+ expect((await check(env, tab, docs, false)).json().data).toMatchObject({ state: 'not-approved' })+ expect(await revisions(env, tab)).toEqual(found)+ })++ // Review of #2713: every member's app reads again when the revision moves, and those reads land on servers whose caches+ // differ (an installation is kept 10 minutes, "not installed" 1 minute). Had they recorded what they found, two servers+ // would move the revision back and forth, each move making every app read again.+ it('a read that follows a revision move records nothing, whatever answer it gets; a person\'s check still does', async () => {+ teamAccounts()+ const one = await fresh({ approveAll: false, signIn })+ const two = await fresh({ approveAll: false, signIn, shared: one.github })+ const { tab } = await swarm(one)+ expect((await check(one, tab, 'lead')).json().data).toMatchObject({ state: 'not-approved' })+ const seen = await revisions(one, tab)+ // Removed from the repository: the first server still keeps the installation (10 minutes), the second asks GitHub.+ one.github.installed.delete('example/app')+ for (const [server, state] of [[one, 'not-approved'], [two, 'not-installed'], [one, 'not-approved'], [two, 'not-installed']] as const) {+ expect((await check(server, tab, 'lead', true, false)).json().data).toMatchObject({ state })+ expect(await revisions(one, tab)).toEqual(seen)+ }+ // A person checks again: that records the answer, once.+ expect((await check(two, tab, 'lead')).json().data).toMatchObject({ state: 'not-installed' })+ expect((await revisions(one, tab)).lead).toBe(seen.lead! + 1)+ })++ it('GitHub sending a person back after installing forgets the cache and moves every project on the repository', async () => {+ teamAccounts()+ const env = await fresh({ approveAll: false, signIn })+ const { tab, docs, other } = await swarm(env)+ env.github.installed.delete('example/app')+ expect((await check(env, tab, 'lead', false)).json().data).toMatchObject({ state: 'not-installed' })+ const before = await revisions(env, tab)+ env.github.installed.set('example/app', 91)+ const asked = await env.app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/projects/lead/github/approve`,+ headers: { authorization: `Bearer ${owner.sub}` }, payload: { scope: 'project' } })+ const state = new URL((asked.json().data as { authorizeUrl: string }).authorizeUrl).searchParams.get('state')!+ const installed = await env.app.inject({ method: 'GET', url: `/api/github/callback?installation_id=9&setup_action=install&state=${encodeURIComponent(state)}` })+ expect(installed.body).toContain('Harness is installed')+ expect(await revisions(env, tab)).toEqual({ lead: before.lead! + 1, [docs]: before[docs]! + 1, [other]: before[other] })+ // Read without asking again: the cache was forgotten, so it is installed now.+ expect((await check(env, tab, 'lead', false)).json().data).toMatchObject({ state: 'not-approved' })+ })++ it('an approval whose move fails still says it is allowed, and says why in the log', async () => {+ teamAccounts()+ const env = await fresh({ approveAll: false, signIn })+ const { tab } = await swarm(env)+ const warn = vi.spyOn(logger, 'warn')+ onTestFinished(() => { warn.mockRestore() })+ vi.spyOn(env.store, 'githubChanged').mockRejectedValueOnce(new Error('write conflict'))+ const { page } = await allow(env, tab, 'lead', 'project')+ expect(page.statusCode).toBe(200)+ expect(page.body).toContain('example/app is allowed')+ expect(warn).toHaveBeenCalledWith('[github] access change not recorded', expect.objectContaining({ tabId: tab, error: 'Error: write conflict' }))+ expect(env.approved).toHaveLength(1)+ })+})diff --git a/backend/integration/superTabNamedReads.test.ts b/backend/integration/superTabNamedReads.test.tsindex ea140c545..84afda732 100644--- a/backend/integration/superTabNamedReads.test.ts+++ b/backend/integration/superTabNamedReads.test.ts@@ -80,7 +80,9 @@ describe('a person\'s Swarm list', () => {mine.sort()})- const memberReads = (entries: Awaited<ReturnType<typeof profiled>>) => reads(entries, 'SuperTab', ['memberIds'])+ /** The auto-join read (superTabs/autoJoin.ts) also names memberIds, as `$ne`: it is checked on its own below. */+ const isAutoJoin = (row: ReturnType<typeof reads>[number]) => JSON.stringify(row.command ?? {}).includes('autoJoinDomain')+ const memberReads = (entries: Awaited<ReturnType<typeof profiled>>) => reads(entries, 'SuperTab', ['memberIds']).filter(row => !isAutoJoin(row))const bounded = (rows: ReturnType<typeof memberReads>, returned: number) => {expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)expect(rows[0]!.nreturned).toBe(returned)@@ -95,6 +97,11 @@ describe('a person\'s Swarm list', () => {expect(listed!.tabs.map(t => t.id)).toEqual(mine)expect(listed!.next).toBeNull()bounded(memberReads(entries), mine.length)+ // Before it, the person's try for Swarms of their domain: one read on its own index, which finds none and examines none.+ const autoJoins = reads(entries, 'SuperTab', ['memberIds']).filter(isAutoJoin)+ expect(autoJoins, JSON.stringify(plan(autoJoins))).toHaveLength(1)+ expect(autoJoins[0]!.docsExamined).toBe(0)+ expect(autoJoins[0]!.command?.hint).toEqual({ autonomousEnv: 1, autoJoinDomain: 1 })})it('the store\'s list and its later page read the same way', async () => {diff --git a/backend/integration/superTabSharing.test.ts b/backend/integration/superTabSharing.test.tsindex f420040e5..5dd360eef 100644--- a/backend/integration/superTabSharing.test.ts+++ b/backend/integration/superTabSharing.test.ts@@ -76,7 +76,7 @@ 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 })+ access: { mode: 'invited', role: 'collaborator' }, joinUrl: null, ownDomain: 'example.com', ownDomainPublic: false, autoJoinFull: false })expect((await request(tab, 'sharing', undefined, null)).statusCode).toBe(401)// 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)@@ -164,11 +164,17 @@ describe('Swarm sharing on the authenticated control API', () => {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' })+ // Who left or was removed is refused before any old receipt: the domain link alone never brings them back.+ await expect(store.join(peer, tab, latest)).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })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)+ // Someone who left comes back only on purpose, by an invitation or a shared link, never by the domain link alone+ // (spec 2026-11-03, Trust 4). Back by invitation, they get a new membership generation, not any old private grants.+ await expect(store.join(peer, tab, { operationId: randomUUID() })).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })+ const invitation = await store.execute(owner, tab, { operationId: randomUUID(),+ command: { type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' } })+ const rejoin = await store.execute(peer, tab, { operationId: randomUUID(), command: { type: 'invite.accept', inviteId: String(invitation.result.inviteId) } })+ expect(rejoin.result.alreadyMember).toBe(false)+ expect((await store.join(peer, tab, { operationId: randomUUID() })).alreadyMember).toBe(true)await expect(store.join(peer, tab, latest)).rejects.toMatchObject({ code: 'JOIN_CHANGED' })})@@ -184,7 +190,8 @@ describe('Swarm sharing on the authenticated control API', () => {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' })+ // Who left or was removed is refused before any old receipt: the domain link alone never brings them back.+ await expect(store.join(peer, tab, join)).rejects.toMatchObject({ code: 'JOIN_UNAVAILABLE' })})it('serializes concurrent joins/settings, prevents operation reuse, and isolates account environments', async () => {diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex aff873d9d..b05d8bf04 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1032,6 +1032,11 @@ model SuperTab {autonomousEnv StringmemberIds String[]invitedEmails String[]+ /// The domain whose people join this Swarm by themselves while its owner has auto-join on (superTabs/autoJoin.ts); absent+ /// otherwise. Derived from the head's sharing in every commit (parts/commit.ts indexesOf).+ autoJoinDomain String?+ /// People who left or were removed: auto-join never adds them again. Cleared by an invitation accepted or a link join.+ autoJoinDeclined String[]machineIds String[]/// Machines whose host still has to clean up after their removal: read apart from the 100-Swarm host poll.cleanupMachineIds String[] @default([])@@ -1066,6 +1071,8 @@ model SuperTab {/// A machine's Swarms, newest first: the host poll's lookup, once a second per host (superTabs/swarmRows.ts machineSwarms).@@index([autonomousEnv, machineIds, updatedAt])@@index([autonomousEnv, cleanupMachineIds, updatedAt])+ /// The Swarms a person at a domain joins by themselves: one read per person at most every 2 minutes (superTabs/autoJoin.ts).+ @@index([autonomousEnv, autoJoinDomain])}// A terminal retains its history when removed from a roster. These bindings@@ -1688,6 +1695,9 @@ model SwarmWorkspace {createdAt DateTime @default(now())deletedAt DateTime?purgeAt DateTime?+ /// People this Workspace removed, whom Swarm auto-join never adds again (superTabs/autoJoin.ts). Kept past the purge of their+ /// member row; cleared when they are added back on purpose (workspaceStore.ts addMember).+ autoJoinDeclined String[]/// Removed rows go at purgeAt (superTabs/sweeps.ts ensurePartExpiry). Declared so db push keeps the index; the worker sets its expiry.@@index([purgeAt], map: "workspace_purge")diff --git a/backend/scripts/swarm-auto-join/public-domain-shares.ts b/backend/scripts/swarm-auto-join/public-domain-shares.tsnew file mode 100644index 000000000..3b10ffc3c--- /dev/null+++ b/backend/scripts/swarm-auto-join/public-domain-shares.ts@@ -0,0 +1,28 @@+// Swarm auto-join (docs/specs/2026-11-03-swarm-domain-auto-join.md, "Old Swarm settings that break the new rules"): from this+// release a saved "Anyone at a domain" share at a domain anyone can have an address at (gmail.com, ...) stops answering joins.+// This lists those Swarms before the merge, so their owners can be told. Read-only: two aggregations, no write.+// The PM runs it with the read-only production login, never an Engineer:+// cd backend && DATABASE_URL="$(read-only URL from its environment file)" npx tsx scripts/swarm-auto-join/public-domain-shares.ts+// It prints the count and the Swarm ids (with each one's domain and whether it is deleted) as JSON, nothing else.+import { PrismaClient } from '@prisma/client'+import { isPublicEmailDomain } from '../../src/lib/publicEmailDomains.js'++interface Share { tabId: string; domain: string }++const db = new PrismaClient()+try {+ // Swarms in parts keep sharing in their head part; a Swarm still in one row keeps it in the row's state.+ const heads = await db.swarmHead.aggregateRaw({ pipeline: [+ { $match: { deleted: false, 'data.sharing.access.mode': 'domain' } },+ { $project: { _id: 0, tabId: 1, domain: '$data.sharing.access.domain' } }] }) as unknown as Share[]+ const rows = await db.superTab.aggregateRaw({ pipeline: [+ { $match: { format: { $ne: 2 }, 'state.sharing.access.mode': 'domain' } },+ { $project: { _id: 0, tabId: '$_id', domain: '$state.sharing.access.domain' } }] }) as unknown as Share[]+ const broken = [...heads, ...rows].filter(share => isPublicEmailDomain(String(share.domain ?? '')))+ const deleted = new Set((await db.superTab.findMany({ where: { id: { in: broken.map(share => share.tabId) }, deletedAt: { not: null } }, select: { id: true } }))+ .map(row => row.id))+ const swarms = broken.map(share => ({ id: share.tabId, domain: share.domain, deleted: deleted.has(share.tabId) })).sort((a, b) => a.id < b.id ? -1 : 1)+ console.log(JSON.stringify({ count: swarms.length, swarms }, null, 2))+} finally {+ await db.$disconnect()+}diff --git a/backend/src/lib/publicEmailDomains.test.ts b/backend/src/lib/publicEmailDomains.test.tsnew file mode 100644index 000000000..24c7125fa--- /dev/null+++ b/backend/src/lib/publicEmailDomains.test.ts@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest'+import { emailDomain, isPublicEmailDomain } from './publicEmailDomains.js'++describe('public email domains', () => {+ // Swarm auto-join (docs/specs/2026-11-03-swarm-domain-auto-join.md, Trust 5): free providers common in Vietnam and Asia.+ it('counts the free providers common in Vietnam and Asia as public', () => {+ for (const domain of ['zing.vn', 'vnn.vn', 'hn.vnn.vn', 'hcm.vnn.vn', 'fpt.vn', 'rediffmail.com', 'yahoo.co.in', 'yahoo.com.sg',+ 'foxmail.com', 'sohu.com', 'aliyun.com', '139.com', 'nate.com', 'docomo.ne.jp']) {+ expect(isPublicEmailDomain(domain), domain).toBe(true)+ }+ })++ it('keeps company domains, including a company sharing a provider\'s name, open to sharing', () => {+ for (const domain of ['acme.com', 'autonomous.ai', 'fpt.com.vn', 'viettel.com.vn']) expect(isPublicEmailDomain(domain), domain).toBe(false)+ expect(isPublicEmailDomain(null)).toBe(true)+ expect(emailDomain('[email protected]')).toBe('acme.com')+ })+})diff --git a/backend/src/lib/publicEmailDomains.ts b/backend/src/lib/publicEmailDomains.tsindex 9b351805f..2a275ee96 100644--- a/backend/src/lib/publicEmailDomains.ts+++ b/backend/src/lib/publicEmailDomains.ts@@ -20,6 +20,13 @@ const PUBLIC_EMAIL_DOMAINS = new Set(['zoho.com', 'zohomail.com', 'yandex.com', 'yandex.ru', 'mail.ru', 'inbox.ru', 'list.ru', 'bk.ru','tutanota.com', 'tuta.io', 'fastmail.com', 'hey.com', 'duck.com','qq.com', '163.com', '126.com', 'yeah.net', 'sina.com', 'naver.com', 'daum.net', 'hanmail.net',+ // Free and ISP mail common in Vietnam and Asia (Swarm auto-join lets in anyone at a domain: spec 2026-11-03, Trust 5).+ // Only consumer domains: a company's own (fpt.com.vn, viettel.com.vn) stays a company's.+ 'zing.vn', 'vnn.vn', 'hn.vnn.vn', 'hcm.vnn.vn', 'fpt.vn',+ 'rediffmail.com', 'yahoo.co.in', 'yahoo.in', 'yahoo.com.sg', 'yahoo.com.my', 'yahoo.co.id', 'yahoo.com.ph', 'yahoo.co.th',+ 'yahoo.com.hk', 'yahoo.com.tw', 'yahoo.com.au', 'yahoo.co.kr', 'hotmail.co.jp', 'outlook.jp', 'live.jp',+ 'foxmail.com', 'sohu.com', 'sina.cn', 'aliyun.com', '139.com', '189.cn', '21cn.com', 'tom.com', 'vip.qq.com', 'vip.163.com',+ 'nate.com', 'kakao.com', 'nifty.com', 'excite.co.jp', 'docomo.ne.jp', 'ezweb.ne.jp', 'au.com', 'softbank.ne.jp', 'i.softbank.jp','pending.harness.invalid',])diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 3f88e2582..e1517d652 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -11,6 +11,7 @@ import { PERIODS } from '../superTabs/leaderboard/rolling.js'import { fail, SuperTabError } from '../superTabs/model.js'import { SuperTabStore } from '../superTabs/store.js'import { redisPollMemory } from '../superTabs/pollMemory.js'+import { redisAutoJoinMemory } from '../superTabs/autoJoin.js'import { redisReportMemory } from '../superTabs/machineReports.js'import { routingPolicySaveSchema } from '../superTabs/routingPolicy.js'import { nativeEventSchema, openNativeSchema } from '../superTabs/native.js'@@ -114,7 +115,8 @@ const hostParams = z.object({ machineId: id })const hostStartParams = hostParams.extend({ tabId: id, startId: id })const machineParams = hostParams.extend({ tabId: id })const projectParams = tabParams.extend({ projectId: id })-const refreshQuery = z.object({ refresh: z.literal('1').optional() })+// `record=0`: an app reading again because the project's GitHub revision moved, not a person checking; it records nothing.+const refreshQuery = z.object({ refresh: z.literal('1').optional(), record: z.literal('0').optional() })const approveBody = z.object({ scope: z.enum(['project', 'swarm']) }).strict()// What GitHub sends back: a sign-in's code and our state, and after an installation its id and action.const callbackQuery = z.object({ code: z.string().max(512).optional(), state: z.string().max(4096).optional(), error: z.string().max(128).optional(),@@ -237,6 +239,8 @@ async function productionStore(github: GitHubTokens | null): Promise<SuperTabSto// Every server answers the quiet delivery poll from any server's full one, and tells the agent's machine of new work// through whichever server holds its daemon socket (stability roadmap 2.4). Both only ever drop, never fail, on Redis.polls: redisPollMemory(bus.pub),+ // Each person is tried for joining by domain once per 2 minutes across every server (superTabs/autoJoin.ts).+ autoJoins: redisAutoJoinMemory(bus.pub),// What each machine's full report saw, so its heartbeats skip the Swarm load, and one sweep clock per Swarm (DB 2.5).reports: redisReportMemory(bus.pub),deliveriesWaiting: announceSwarmDeliveries, terminalWaiting: announceSwarmTerminal,@@ -274,6 +278,11 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Suconst store = options.store ?? await productionStore(github)const reads = options.reads ?? new SwarmReads(store, { githubApp: !!github })const hosts = options.hosts ?? new HostReads(store, { githubApp: !!github, teamAccountsIdle: !github })+ // Members' apps read a project's GitHub access again when its revision moves (projects.ts githubRevision). A move that+ // fails is logged and changes no answer: the apps then read again within 5 minutes, as before.+ const recorded = (tabId: string, move: () => Promise<unknown>) => move().catch(error => {+ logger.warn('[github] access change not recorded', { tabId, error: String(error) })+ })app.get('/api/super-tabs/grids', (req, reply) => respond(reply, () => store.hostGrids(req.user!)))// Each row says whether this server has the Harness GitHub App, so the host knows to ask for a start's token below.app.get('/api/super-tabs/hosts/:machineId/pools', updateRequired)@@ -317,7 +326,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su{ preHandler: [validateParams(projectParams), validateQuery(refreshQuery)] },(req, reply) => respond(reply, async () => {const project = await store.projectRepository(req.user!, req.params.tabId, req.params.projectId)- return projectGitHubAccess(github?.app ?? null, project.repositoryUrl, { canApprove: !!signIn,+ const access = await projectGitHubAccess(github?.app ?? null, project.repositoryUrl, { canApprove: !!signIn,approved: async repository => !project.approvalRequired || approvals.approved(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository),approvedFor: async repository => {const ids = await approvals.approvedProjects(req.user!.autonomousEnv, req.params.tabId, repository)@@ -325,6 +334,11 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su},you: repository => approvals.reader(req.user!.autonomousEnv, req.params.tabId, req.params.projectId, repository, req.user!.sub) },req.query.refresh === '1')+ // Only a person's check records what it found (opening GitHub access, Check again): every app reads again when the+ // revision moves, on servers whose caches differ, and recording those reads would move it back and forth (review of+ // #2713). A read without `refresh` may answer from an older cache, so it records nothing either.+ if (req.query.refresh === '1' && req.query.record !== '0') await recorded(req.params.tabId, () => store.githubSeen(req.params.tabId, req.params.projectId, access.state))+ return access}))// The jobs running and waiting on a project's GitHub Actions, for the route (github/ciLoad.ts): counts only, read through// the app, by a person or an agent who may read the project. Only for a repository someone who can push to it approved for@@ -361,6 +375,11 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su// (local Team account run, 2026-10-28).if (req.query.error) return page('Sign-in was cancelled', 'Nothing was allowed. Go back to Harness and choose Continue in GitHub to try again.')if (!req.query.code || !signIn || !named) {+ // Installed just now: this server stops keeping "not installed", and members' apps read again (task #2316).+ if (named && github) {+ github.app.forget(named)+ await recorded(request.tabId, () => store.githubChanged(request.tabId, request.repository))+ }return page('Harness is installed', 'Go back to Harness and choose Continue in GitHub, so this project can use it.')}const seen = await signIn.permission(req.query.code, named).catch(() => null)@@ -371,6 +390,7 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Sureturn page(`You can't push to ${named.fullName}`, 'So you can\'t allow it. Ask someone who can push to it to open the project in Harness and choose Set up GitHub for teammates.', 403)}await approvals.approve(request, seen.login)+ await recorded(request.tabId, () => store.githubChanged(request.tabId, request.repository))// Named, so the person knows which project it was for (local Team account run, 2026-10-28: 'This project can now use it').const where = request.scope === 'swarm' ? 'every project in this Swarm': await store.projectNameFor(request.userId, request.autonomousEnv as AuthUser['autonomousEnv'], request.tabId, request.projectId).catch(() => null) ?? 'this project'diff --git a/backend/src/superTabs/autoJoin.test.ts b/backend/src/superTabs/autoJoin.test.tsnew file mode 100644index 000000000..ae3020be8--- /dev/null+++ b/backend/src/superTabs/autoJoin.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it, vi } from 'vitest'+import type { AuthUser } from '../lib/ssoAuth.js'+import { AUTO_JOIN_EVERY_MS, AUTO_JOIN_LIMIT, autoJoin, localAutoJoinMemory, redisAutoJoinMemory, type AutoJoinDeps } from './autoJoin.js'++const x: AuthUser = { sub: 'x', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }+const deps = (over: Partial<AutoJoinDeps> = {}): AutoJoinDeps => ({+ memory: { claim: vi.fn(async () => true) },+ find: vi.fn(async () => ['a', 'b']),+ join: vi.fn(async () => 'joined' as const),+ ...over,+})++describe('autoJoin', () => {+ it('finds the Swarms of the person\'s own domain, ten at most, and joins each as the person', async () => {+ const d = deps()+ expect(await autoJoin(d, x)).toEqual(['a', 'b'])+ expect(d.find).toHaveBeenCalledWith(x, 'acme.com', AUTO_JOIN_LIMIT)+ expect(AUTO_JOIN_LIMIT).toBe(10)+ expect(d.join).toHaveBeenCalledWith(x, 'a')+ expect(d.memory.claim).toHaveBeenCalledWith('prod:x')+ })++ it('reads nothing when the person was tried in the last two minutes', async () => {+ const d = deps({ memory: { claim: async () => false } })+ expect(await autoJoin(d, x)).toEqual([])+ expect(d.find).not.toHaveBeenCalled()+ })++ it('still tries when the memory is down', async () => {+ const d = deps({ memory: { claim: async () => { throw new Error('redis down') } } })+ expect(await autoJoin(d, x)).toEqual(['a', 'b'])+ })++ it('skips a public domain, an address with no domain and a team session before any read', async () => {+ for (const user of [{ ...x, email: '[email protected]' }, { ...x, email: '[email protected]' }, { ...x, email: 'nobody' },+ { ...x, harnessSessionKind: 'team' as const }]) {+ const d = deps()+ expect(await autoJoin(d, user)).toEqual([])+ expect(d.memory.claim).not.toHaveBeenCalled()+ expect(d.find).not.toHaveBeenCalled()+ }+ })++ it('answers with the Swarms that did join when one join fails or is skipped', async () => {+ const d = deps({ find: async () => ['a', 'b', 'c', 'd'], join: vi.fn(async (_user: AuthUser, tab: string) => {+ if (tab === 'b') throw new Error('conflict')+ return tab === 'c' ? 'skipped' as const : tab === 'd' ? 'declined' as const : 'joined' as const+ }) })+ expect(await autoJoin(d, x)).toEqual(['a'])+ expect(d.join).toHaveBeenCalledTimes(4)+ })++ it('never throws when the read fails', async () => {+ expect(await autoJoin(deps({ find: async () => { throw new Error('mongo down') } }), x)).toEqual([])+ })+})++describe('auto-join memories', () => {+ it('claims a person once per two minutes in one server', async () => {+ let now = 1_000+ const memory = localAutoJoinMemory(() => now)+ expect(await memory.claim('k')).toBe(true)+ expect(await memory.claim('k')).toBe(false)+ now += AUTO_JOIN_EVERY_MS+ expect(await memory.claim('k')).toBe(true)+ expect(AUTO_JOIN_EVERY_MS).toBe(120_000)+ })++ it('claims with one SET NX PX in Redis, shared by every server', async () => {+ const set = vi.fn(async () => 'OK' as string | null)+ const memory = redisAutoJoinMemory({ set })+ expect(await memory.claim('prod:x')).toBe(true)+ expect(set).toHaveBeenCalledWith('swarm:auto-join:prod:x', '1', 'PX', 120_000, 'NX')+ set.mockResolvedValueOnce(null)+ expect(await memory.claim('prod:x')).toBe(false)+ })+})diff --git a/backend/src/superTabs/autoJoin.ts b/backend/src/superTabs/autoJoin.tsnew file mode 100644index 000000000..82b3f2393--- /dev/null+++ b/backend/src/superTabs/autoJoin.ts@@ -0,0 +1,80 @@+/**+ * People at the owner's email domain join a Swarm by themselves (docs/specs/2026-11-03-swarm-domain-auto-join.md). The join is+ * a pull on the person's own list read: no invitation, link or click. It acts as the joining person alone, never the owner.+ */+import type { AuthUser } from '../lib/ssoAuth.js'+import { emailDomain, isPublicEmailDomain } from '../lib/publicEmailDomains.js'+import { isTeamSession } from '../lib/teamSession.js'+import { logger } from '../utils/logger.js'++/** How often one person is tried: list reads are polled every few seconds, so a join can take up to this long (spec, my call). */+export const AUTO_JOIN_EVERY_MS = 120_000+/** Swarms joined per try; more are joined on later tries. */+export const AUTO_JOIN_LIMIT = 10++/** What one Swarm's try came to (SuperTabStore.autoJoinSwarm): joined now; nothing to do (off, full, a member, declined+ * already, or gone); or declined now because the Workspace removed the person. */+export type AutoJoinOutcome = 'joined' | 'skipped' | 'declined'++/** When each person was last tried, shared by every server. `claim` is true when the person may be tried now, and marks them+ * tried for AUTO_JOIN_EVERY_MS before any read. It may throw: the person is then tried anyway, as other poll memories do. */+export interface AutoJoinMemory { claim(key: string): Promise<boolean> }++export interface AutoJoinDeps {+ memory: AutoJoinMemory+ /** Up to `limit` Swarms of `domain` with auto-join on that the person is not in and never declined: one indexed read. */+ find(user: AuthUser, domain: string, limit: number): Promise<string[]>+ /** Joins the person to one Swarm in its own transaction, rechecking everything there. */+ join(user: AuthUser, tabId: string): Promise<AutoJoinOutcome>+}++/** Joins `user` to the Swarms of their own email domain whose owners turned auto-join on. Never throws: a list read answers+ * anyway. Returns the Swarms joined now. */+export async function autoJoin(deps: AutoJoinDeps, user: AuthUser): Promise<string[]> {+ const domain = emailDomain(user.email)+ if (!domain || isPublicEmailDomain(domain) || isTeamSession(user)) return []+ const due = await deps.memory.claim(`${user.autonomousEnv}:${user.sub}`).catch(error => {+ logger.warn('[super-tab] auto-join memory unavailable', { error: error instanceof Error ? error.message : String(error) })+ return true+ })+ if (!due) return []+ let tabIds: string[]+ try {+ tabIds = await deps.find(user, domain, AUTO_JOIN_LIMIT)+ } catch (error) {+ logger.warn('[super-tab] auto-join read failed', { userId: user.sub, error: error instanceof Error ? error.message : String(error) })+ return []+ }+ const joined: string[] = []+ for (const tabId of tabIds) {+ try {+ if (await deps.join(user, tabId) === 'joined') joined.push(tabId)+ } catch (error) {+ // Tried again once the person's 2-minute mark expires.+ logger.warn('[super-tab] auto-join failed', { tabId, userId: user.sub, error: error instanceof Error ? error.message : String(error) })+ }+ }+ return joined+}++/** One server's own memory. */+export function localAutoJoinMemory(now: () => number): AutoJoinMemory {+ const tried = new Map<string, number>()+ return {+ async claim(key) {+ const at = now()+ if ((tried.get(key) ?? -Infinity) > at - AUTO_JOIN_EVERY_MS) return false+ tried.set(key, at)+ if (tried.size > 10_000) for (const [k, when] of tried) if (when <= at - AUTO_JOIN_EVERY_MS) tried.delete(k)+ return true+ },+ }+}++/** The Redis command the memory needs: the bus' fail-fast connection (lib/bus.ts `pub`) in production. */+export interface AutoJoinRedis { set(key: string, value: string, px: 'PX', ms: number, nx: 'NX'): Promise<string | null> }++/** Every server's memory: one `SET NX PX`, which claims and marks the person in one step. */+export function redisAutoJoinMemory(redis: AutoJoinRedis): AutoJoinMemory {+ return { claim: async key => await redis.set(`swarm:auto-join:${key}`, '1', 'PX', AUTO_JOIN_EVERY_MS, 'NX') === 'OK' }+}diff --git a/backend/src/superTabs/autoJoinDomain.ts b/backend/src/superTabs/autoJoinDomain.tsnew file mode 100644index 000000000..327e80a11--- /dev/null+++ b/backend/src/superTabs/autoJoinDomain.ts@@ -0,0 +1,12 @@+import { isPublicEmailDomain } from '../lib/publicEmailDomains.js'+import type { SuperTabState } from './model.js'++// Kept apart from sharing.ts, whose link tokens load the server's settings: the Swarm model and every commit read this, and+// importing them must not load the environment (integration/workerIndexPlans.test.ts points the app's database first).++/** The domain whose people join this Swarm by themselves, while its owner has that on; null otherwise. A saved domain anyone+ * can have an address at never counts, whatever an older release saved. */+export function autoJoinOn(state: Pick<SuperTabState, 'sharing' | 'deletion'>): string | null {+ const access = state.sharing?.access+ return !state.deletion && access?.mode === 'domain' && access.autoJoin === true && !isPublicEmailDomain(access.domain) ? access.domain : null+}diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 55095d852..82dbf756b 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -42,6 +42,7 @@ import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema,import { switchExpired } from './tidy.js'import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'import { recordClosing } from './closedAgents.js'+import { declinedWith, declinedWithout } from './sharing.js'import { actorLabel, memberChanges, memberRowText, quotedName } from './memberRows.js'import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'@@ -782,6 +783,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,state.people.push({ id: actor.userId, email: invite.email, role: invite.role, generation: invite.id })}state.invitations = state.invitations.filter(i => i.id !== invite.id)+ // Back on purpose: auto-join may add them again if they leave and the owner invites them once more (spec, Leaving is final).+ if (state.autoJoinDeclined?.includes(actor.userId)) state.autoJoinDeclined = declinedWithout(state, actor.userId)result.conversationId = invite.conversationId// As a link join answers (store.ts joinSwarm): Desktop adds the accepting computer only when this made a member.result.alreadyMember = !!existing@@ -2733,6 +2736,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,}state.people = state.people.filter(p => p.id !== member.id)state.invitations = state.invitations.filter(i => i.email !== member.email)+ // Leaving, or being removed, is final for auto-join: only an invitation or a link brings them back (spec 2026-11-03).+ state.autoJoinDeclined = declinedWith(state, member.id)result.removedUserId = member.idbreak}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex d2db9ed4d..be2e025eb 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -1,5 +1,6 @@import { createHash } from 'node:crypto'import { cloneData } from './cloneData.js'+import { autoJoinOn } from './autoJoinDomain.js'import { lostReasonWithoutMachine } from './lostReason.js'import type { RouteDecisionEffect } from './routeRecord.js'import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'@@ -22,6 +23,8 @@ export interface Person {avatar?: import('./profile.js').Avatar/** The name they chose (usernames.ts), or one kept for them; absent, readers work out their default. Only members read it. */username?: string+ /** `domain`: joined by themselves as someone at the owner's email domain (autoJoin.ts), so the people list says so. */+ joinedVia?: 'domain'}export interface AgentConfiguration {engine: string@@ -433,6 +436,11 @@ export interface SuperTabState {rules?: import('./rules.js').SwarmRule[]/** Owner-only sharing configuration; visibleState always removes it. */sharing?: import('./sharing.js').SwarmSharing+ /** People who left or were removed, whom auto-join never adds again (autoJoin.ts); visibleState always removes it. */+ autoJoinDeclined?: string[]+ /** Only in what a reader gets (visibleState), never stored: people at the owner's domain join by themselves, so the leave+ * dialog says someone who leaves is not added back. */+ autoJoin?: truepaused: boolean/** Its owner deleted it (deletion.ts): nobody reads or writes it, its row lists no member, and its owner may restore it until* `purgeAt` (ISO times). Absent on a live Swarm. */@@ -814,9 +822,10 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(// and closing sessions (only that machine's host roster lists them: read/hostRows.ts; a removed private agent's session is// not every member's), and overlap alerts. Nor a dormant conversation: it is read on demand, never in a whole-Swarm read// (spec, Archive); a command may still load one.- const { sharing: _sharing, harnessReservations: _reservations, releasedHarnesses: _released, overlapAlerts: _alerts, closingSessions: _closing,+ const { sharing: _sharing, autoJoinDeclined: _declined, harnessReservations: _reservations, releasedHarnesses: _released, overlapAlerts: _alerts, closingSessions: _closing,removedSessions: _removed, ...kept } = stateconst visible = cloneData({ ...kept, conversations: state.conversations.filter(c => !c.dormant) })+ if (autoJoinOn(state)) visible.autoJoin = true// A Buddy-only machine is no machine of the Swarm to anyone, its own person included (machines.ts buddyOnly): their Buddy// shows as a Buddy, and their machine stays theirs. Machines, status and the leaderboard's lent hours all read this.if (visible.machines) visible.machines = visible.machines.filter(m => !m.buddyOnly)diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex dd534808d..89136d6dc 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -1,5 +1,6 @@import type { Prisma } from '@prisma/client'import { agentOnly, conversation, fail, isLeads, type AgentStart, type MessageDraft, type SuperTabState } from '../model.js'+import { autoJoinOn } from '../autoJoinDomain.js'import { split } from './shape.js'import { guardedWrite, PartConflict, type HeadColumns, type HostColumns, type PartWrite } from './write.js'import type { GroupData, MachineData, Part, PartKind, SwarmParts } from './types.js'@@ -83,6 +84,8 @@ export function indexesOf(state: SuperTabState) {...(state.closingSessions ?? []).map(c => c.machineId), ...(state.machineCleanups ?? []).map(c => c.machineId)])],cleanupMachineIds: [...new Set([...(state.machines ?? []).flatMap(m => m.removal ? [m.machineId] : []),...(state.machineCleanups ?? []).map(c => c.machineId)])],+ // Who joins by domain (autoJoin.ts): a deleted Swarm, or one whose owner turned it off, is found by nobody.+ autoJoinDomain: autoJoinOn(state), autoJoinDeclined: state.autoJoinDeclined ?? [],}}diff --git a/backend/src/superTabs/parts/indexed.ts b/backend/src/superTabs/parts/indexed.tsindex 5c93f1659..ea2ff3572 100644--- a/backend/src/superTabs/parts/indexed.ts+++ b/backend/src/superTabs/parts/indexed.ts@@ -45,6 +45,8 @@ export const NAMED_INDEX = {workspace: { autonomousEnv: 1, workspaceId: 1 },/** Deleted Swarms by purge time (deletion.ts): the purge sweep. */purge: { purgeAt: 1 },+ /** The Swarms people at a domain join by themselves (autoJoin.ts): one read per person at most every 2 minutes. */+ autoJoin: { autonomousEnv: 1, autoJoinDomain: 1 },},/** Each part kind's changes since a cursor; machines also by when they were last read. */SwarmHead: { changes: { tabId: 1, changedAt: 1 } },diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.tsindex 31346c7e2..f01a1fa47 100644--- a/backend/src/superTabs/projects.ts+++ b/backend/src/superTabs/projects.ts@@ -66,10 +66,20 @@ export interface SwarmProject {instructionsHash?: string/** Moves on each note the coordinator keeps or a member removes (instructions.ts), so an open panel knows to read them. */notesRevision?: number+ /** Moves when its repository's GitHub access may have changed: someone allowed it, GitHub sent someone back after+ * installing the app, or a check that asked GitHub again found a different answer (store.ts githubChanged, githubSeen).+ * Members' apps read the access again when it moves rather than keeping it 5 minutes (task #2316, Dee 2026-11-03). */+ githubRevision?: number+ /** What the last check that asked GitHub again found (github/projectAccess.ts), so only a different answer moves it. */+ githubSeen?: GitHubSeen/** What its coordinator is called; reads give "Product Manager" when absent (instructions.ts coordinatorNameOf). */coordinatorName?: string}+/** The GitHub access states a check records (github/projectAccess.ts): the others are no answer from GitHub. */+export const GITHUB_SEEN = ['not-installed', 'not-approved', 'covered'] as const+export type GitHubSeen = typeof GITHUB_SEEN[number]+/** A project's status card: its text, when (ISO time) and by which agent it was written. */export interface ProjectStatus { text: string; at: string; by: string }export const PROJECT_STATUS_MAX = 2_000diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.tsindex 00d6f8d27..ca23f11cf 100644--- a/backend/src/superTabs/read/contract.ts+++ b/backend/src/superTabs/read/contract.ts@@ -22,9 +22,11 @@ export type PartChange<T> = LivePart<T> | Tombstoneexport type GroupChange = LivePart<GroupView> | Tombstone | DormantStub/** The head as a reader sees it: no sharing, overlap alerts, retired number or parked groups; projects, rules and- * invitations filtered (invitations only for the Swarm owner). */+ * invitations filtered (invitations only for the Swarm owner). `autoJoin`: people at the owner's domain join by themselves+ * (autoJoin.ts), from the sharing the head holds; who declined is never sent. */export type HeadView = Pick<SuperTabState, 'version' | 'id' | 'name' | 'project' | 'projects' | 'leadsConversationId' | 'ownerId'- | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility' | 'buddies' | 'removedMachines'>+ | 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels' | 'workspaceId' | 'workspaceVisibility' | 'buddies' | 'removedMachines'+ | 'autoJoin'>/** A member's avatar says only `{ kind: 'upload' }` for an upload: its link comes signed in `derived.avatars`. */export type MemberView = Omit<Person, 'avatar'> & { avatar?: import('../profile.js').AvatarView }/** The stored agent. Time-based and cross-part values (`downSince`, `limitedUntil`, an awaiting decision, the customdiff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex ac84b360b..d0943be09 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -367,6 +367,8 @@ export class SwarmReads {async list(user: AuthUser, after?: string, withMentions = false): Promise<SwarmList> {if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)+ // People at the owner's domain join Swarms with auto-join on by themselves, before the first page is read (autoJoin.ts).+ if (!after) await this.store.autoJoin(user)const rows = await memberSwarms(this.db, user.autonomousEnv, user.sub, { after, limit: 101 })// A Swarm of a Workspace the person is no longer in is not theirs to list, even before their removal from it has run.const workspaceIds = [...new Set(rows.flatMap(r => r.workspaceId ? [r.workspaceId] : []))]diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.tsindex 4cd245ec9..0543412ed 100644--- a/backend/src/superTabs/read/views.ts+++ b/backend/src/superTabs/read/views.ts@@ -53,7 +53,7 @@ export interface ReadExtras {}const HEAD_FIELDS = ['version', 'id', 'name', 'project', 'projects', 'leadsConversationId', 'ownerId', 'environment',- 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility', 'buddies', 'removedMachines'] as const+ 'routingPolicy', 'rules', 'paused', 'invitations', 'localModels', 'workspaceId', 'workspaceVisibility', 'buddies', 'removedMachines', 'autoJoin'] as constexport const envelope = <T>(part: Pick<Part, 'key' | 'version' | 'changedAt'>, data: T): LivePart<T> =>({ key: part.key, version: part.version, changedAt: part.changedAt, data })diff --git a/backend/src/superTabs/sharing.test.ts b/backend/src/superTabs/sharing.test.tsindex 42ef1feb6..2b9091157 100644--- a/backend/src/superTabs/sharing.test.ts+++ b/backend/src/superTabs/sharing.test.ts@@ -6,11 +6,12 @@ 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')!+const linkToken = (state: ReturnType<typeof tab>) => new URL(sharingDetails(state, owner.email).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(sharingDetails(tab(), owner.email)).toEqual({ revision: 0, access: { mode: 'invited', role: 'collaborator' }, joinUrl: null,+ ownDomain: 'example.com', ownDomainPublic: false, autoJoinFull: false })expect(() => authorizeSwarmJoin(tab(), owner.email)).toThrow('unavailable')for (const path of ['sharing', 'join', 'join/preview']) expect(shouldSkipAuth(`/api/super-tabs/tab/${path}`)).toBe(false)})@@ -61,7 +62,7 @@ describe('Swarm sharing policy', () => {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}`)+ expect(sharingDetails(state, owner.email).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', () => {@@ -76,10 +77,10 @@ describe('Swarm sharing policy', () => {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')+ expect(sharingDetails(state, owner.email).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(sharingDetails(state, owner.email).joinUrl).toBeNull()expect(() => authorizeSwarmJoin(state, owner.email)).toThrow('unavailable')})})diff --git a/backend/src/superTabs/sharing.ts b/backend/src/superTabs/sharing.tsindex dc3deaf19..de69b1edf 100644--- a/backend/src/superTabs/sharing.ts+++ b/backend/src/superTabs/sharing.ts@@ -1,6 +1,10 @@import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto'import { z } from 'zod'import { decryptMachineCredential, encryptMachineCredential } from '../lib/machineCredential.js'+import { emailDomain, isPublicEmailDomain } from '../lib/publicEmailDomains.js'+import { autoJoinOn } from './autoJoinDomain.js'++export { autoJoinOn }import { fail, person, type SuperTabState } from './model.js'const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)@@ -9,7 +13,9 @@ 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(),+ // `autoJoin`: people at the domain join with no link or click, on their own list read (autoJoin.ts). Only at the saving+ // owner's own domain. Left out of a save, the saved value is kept (an older Desktop never turns it off by saving).+ z.object({ mode: z.literal('domain'), role, domain, autoJoin: z.boolean().optional() }).strict(),z.object({ mode: z.literal('link'), role }).strict(),])export const saveSharingSchema = z.object({ operationId: id, revision: z.number().int().nonnegative().safe(),@@ -34,8 +40,24 @@ export function requireSharingOwner(state: SuperTabState, userId: string): voidif (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 {+/** Every change fences old join receipts, even if a domain or link is enabled again later. `ownerEmail` is the saving owner's+ * own account email: a domain anyone can have an address at is refused, and auto-join is only ever at the owner's own domain.+ * The stored access holds `autoJoin` only while it is on. */+export function configureSharing(previous: SwarmSharing | undefined, input: GeneralAccess, rotateLink = false, ownerEmail?: string): SwarmSharing {+ let access: GeneralAccess = input+ if (input.mode === 'domain') {+ if (isPublicEmailDomain(input.domain)) {+ fail('PUBLIC_DOMAIN', `Anyone can make an address at ${input.domain}. Invite people or share a link instead.`, 400)+ }+ const own = ownerEmail === undefined ? null : emailDomain(ownerEmail)+ if (input.autoJoin === true && input.domain !== own) {+ fail('DOMAIN_NOT_YOURS', `Automatic joins work only at your own email domain${own ? `, ${own}` : ''}.`, 400)+ }+ // Absent keeps the saved value, for the same domain and only while it is still the owner's own.+ const kept = previous?.access.mode === 'domain' && previous.access.domain === input.domain && previous.access.autoJoin === true && input.domain === own+ const { autoJoin: _autoJoin, ...rest } = input+ access = (input.autoJoin ?? kept) ? { ...rest, autoJoin: true } : rest+ }let link: SwarmSharing['link']if (access.mode === 'link') {if (previous?.access.mode === 'link' && previous.link && !rotateLink) link = previous.link@@ -47,13 +69,37 @@ export function configureSharing(previous: SwarmSharing | undefined, access: Genreturn { revision: (previous?.revision ?? 0) + 1, generation: randomUUID(), access, ...(link ? { link } : {}) }}-export function sharingDetails(state: SuperTabState) {+/** The most people a Swarm takes by auto-join: the most a private project can name (project.sharing). Invitations and links+ * still work past it. */+export const AUTO_JOIN_CAP = 200+++/** The people auto-join never adds again, with `userId` added: someone who left or was removed (spec, Leaving is final). Kept+ * sorted, so the same people always write the same row. */+export function declinedWith(state: Pick<SuperTabState, 'autoJoinDeclined'>, userId: string): string[] {+ return [...new Set([...state.autoJoinDeclined ?? [], userId])].sort()+}++/** Without `userId`: they came back on purpose, by an invitation or a link. Undefined when nobody is left. */+export function declinedWithout(state: Pick<SuperTabState, 'autoJoinDeclined'>, userId: string): string[] | undefined {+ const rest = (state.autoJoinDeclined ?? []).filter(id => id !== userId)+ return rest.length ? rest : undefined+}++/** What the owner's Share dialog shows. `ownerEmail` is the reading owner's account email. A saved share at a domain anyone can+ * have an address at, which this release no longer answers, shows as invite-only with the domain it turned off. */+export function sharingDetails(state: SuperTabState, ownerEmail: string) {const sharing = state.sharing- const access: GeneralAccess = sharing?.access ?? { mode: 'invited', role: 'collaborator' }+ const saved: GeneralAccess = sharing?.access ?? { mode: 'invited', role: 'collaborator' }+ const turnedOff = saved.mode === 'domain' && isPublicEmailDomain(saved.domain) ? saved.domain : undefined+ const access: GeneralAccess = turnedOff ? { mode: 'invited', role: saved.role }+ : saved.mode === 'domain' ? { ...saved, autoJoin: saved.autoJoin === true } : savedconst 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 ownDomain = emailDomain(ownerEmail)+ return { revision: sharing?.revision ?? 0, access, joinUrl, ownDomain, ownDomainPublic: isPublicEmailDomain(ownDomain),+ autoJoinFull: !!autoJoinOn(state) && state.people.length >= AUTO_JOIN_CAP, ...(turnedOff ? { turnedOffDomain: turnedOff } : {}) }}const tokenHash = (token: string) => createHash('sha256').update(token).digest('hex')@@ -65,12 +111,16 @@ export function authenticatedEmail(email: string): string | null {return normalized}-export function authorizeSwarmJoin(state: SuperTabState, email: string, token?: string): SwarmSharing {+/** `userId`: the joining person. Someone who left or was removed (autoJoinDeclined) comes back only on purpose, by an+ * invitation or a shared link's token, never by the domain's own join link, which needs none (spec 2026-11-03, Trust 4). */+export function authorizeSwarmJoin(state: SuperTabState, email: string, token?: string, userId?: string): SwarmSharing {const sharing = state.sharingconst 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+ // A domain anyone can have an address at lets nobody in, even one saved before this was refused (spec, Trust 2).+ if (access.mode === 'domain' && token === undefined && !isPublicEmailDomain(access.domain) && verifiedEmail.split('@')[1] === access.domain &&+ !(userId !== undefined && state.autoJoinDeclined?.includes(userId))) return sharingif (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')diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 1e47f8f7d..edef3b137 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -31,7 +31,7 @@ import { noteClaim, recordDeliveryCall } from '../lib/deliveryCalls.js'import { retryTransient } from './retry.js'import { recordReload } from './retryStats.js'import { buddyChatId, swarmBuddyChatId, type ChosenBuddyName } from './buddies.js'-import { accountOf, wordsOf, buddyPerson, canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey } from './projects.js'+import { accountOf, wordsOf, buddyPerson, canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, readProject, skillModeOf, startProject, type ProjectVisibility, sessionKey, GITHUB_SEEN, type GitHubSeen, type SwarmProject } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { SESSION_ENDED_KIND, sessionContext, sessionReadsRow, type ContextRow } from './buddySessions.js'import { isBuddy, isBuddyChat, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'@@ -51,7 +51,7 @@ import { judgedMachines, loseTasks, nextLossAt, sweepForLead, sweepLiveness, SWEimport { archivable, archiveLine, idleNotices, reviewClosable, reviewCloseLine, reviewPullRequests } from './tidy.js'import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachineParts, loadObserved, reassemble, split, type GroupData, type HeadData, type MachineData, type Part, type SwarmParts } from './parts/index.js'import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'-import { memberSwarms } from './swarmRows.js'+import { autoJoinSwarms, memberSwarms } from './swarmRows.js'import { commitParts, indexesOf, numberMessages, type Touch, type Written } from './parts/commit.js'import { loadDeliveryParts, ms } from './parts/light.js'import { endSteps, stepEndedRows, stepsOf } from './steps.js'@@ -62,7 +62,7 @@ import { freeze, readStamps, stampOwed, swarmReadCache, swarmTransaction, type Cimport { countReport, DEADLINE_CAP_MS, localReportMemory, RECORD_TTL_MS, type ReportMemory, type ReportRecord } from './machineReports.js'import { DIRECT, readLastChangedAt, readParts, type ReadNamed } from './cachedReads.js'import { revokeNativeContexts, SuperTabNativeStore } from './native.js'-import { activeMember, addMember, hasWorkspaceAccess, listWorkspaces, memberId, WORKSPACE_ACCESS_REVOKED, workspaceForNewSwarm, requireWorkspaceAccess, requireWorkspaceRole, SwarmWorkspaces } from './workspaceStore.js'+import { activeMember, addMember, autoJoinDeclinedBy, hasWorkspaceAccess, listWorkspaces, memberId, WORKSPACE_ACCESS_REVOKED, workspaceForNewSwarm, requireWorkspaceAccess, requireWorkspaceRole, SwarmWorkspaces } from './workspaceStore.js'import { WORKSPACE_LABEL, type WorkspaceRole } from './workspaces.js'import { STATUS_LABELS,activeWork, actorKey, agent, agentOnly, appendPullRequestUrls, author, conversation, createSuperTab, fail, person, stableId, visibleState, finishWorker,@@ -88,7 +88,9 @@ import { DEFAULT_ROUTING_POLICY, type RoutingPolicy } from './routingPolicy.js'import { catalogRead } from './catalog.js'import { invitedSwarms } from './invitedSwarms.js'import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,- saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'+ saveSharingSchema, sharingDetails, autoJoinOn, AUTO_JOIN_CAP, declinedWith, declinedWithout, type JoinSwarm, type SaveSharing } from './sharing.js'+import { autoJoin, localAutoJoinMemory, type AutoJoinMemory, type AutoJoinOutcome } from './autoJoin.js'+import { emailDomain } from '../lib/publicEmailDomains.js'type Transaction = Prisma.TransactionClienttype ReactCommand = Extract<Command, { type: 'message.react' }>@@ -329,6 +331,9 @@ export interface SuperTabStoreHooks {/** What each machine's full report saw, for its next reports, and each Swarm's sweep clock, shared by every server (Redis* in production, machineReports.ts). Left out, this server remembers alone. */reports?: ReportMemory+ /** When each person was last tried for joining by domain (autoJoin.ts), shared by every server (Redis in production). Left+ * out, this server remembers alone. */+ autoJoins?: AutoJoinMemory/** A delivery now waits for this agent, committed: its machine's daemon socket tells its host to read it at once* (lib/swarmDeliveryPushes.ts). Called after the write commits; it must not throw. */deliveriesWaiting?: (waiting: DeliveriesWaiting) => void@@ -550,6 +555,7 @@ export class SuperTabStore {private readonly attachments: Attachments | null = null, private readonly hooks: SuperTabStoreHooks = {}) {this.fileLinks = attachments ? new FileLinks(attachments.store, attachments.publicBase, attachments.prefix) : nullthis.polls = hooks.polls ?? localPollMemory(now)+ this.autoJoins = hooks.autoJoins ?? localAutoJoinMemory(now)this.reports = hooks.reports ?? localReportMemory(now)this.native = new SuperTabNativeStore({transaction: body => transaction(db, body),@@ -1032,9 +1038,57 @@ export class SuperTabStore {async workspaceList(user: AuthUser) {this.personOnly(user)+ // As the Swarm list does: a Swarm the person joins by domain is in the Workspace they see in this answer.+ await this.autoJoin(user)return { workspaces: await listWorkspaces(this.db, user) }}+ /** Joins the person to the Swarms of their own email domain with auto-join on, at most every 2 minutes (autoJoin.ts). Run at+ * the start of the list reads apps poll. Never throws. */+ async autoJoin(user: AuthUser): Promise<string[]> {+ return autoJoin({ memory: this.autoJoins, find: (person, domain, limit) => autoJoinSwarms(this.db, person.autonomousEnv, domain, person.sub, limit),+ join: (person, tabId) => this.autoJoinSwarm(person, tabId) }, user)+ }++ /** Joins `user` to Swarm [tabId] as someone at its owner's domain, by themselves (spec 2026-11-03). Everything the read found+ * is checked again in this transaction: auto-join still on at the person's domain, not a member, never declined, under 200+ * people. The join relies on the sharing the head holds, so turning auto-join off at once conflicts with it. Someone the+ * Workspace removed is declined instead, in its own write, so no later read finds this Swarm for them. */+ async autoJoinSwarm(user: AuthUser, tabId: string): Promise<AutoJoinOutcome> {+ this.personOnly(user)+ const outcome = await transaction(this.db, async tx => {+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)+ const domain = autoJoinOn(state), email = authenticatedEmail(user.email)+ if (!domain || !email || emailDomain(email) !== domain || state.people.some(p => p.id === user.sub) ||+ state.autoJoinDeclined?.includes(user.sub) || state.people.length >= AUTO_JOIN_CAP) return 'skipped' as const+ const stamp = clock.next(), generation = stableId('auto-join', tabId, user.sub, String(stamp))+ if (state.workspaceId) {+ // As a link join: a guest of the Workspace, never higher; someone active there keeps their role (addMember).+ const prior = await tx.swarmWorkspaceMember.findUnique({ where: { id: memberId(state.workspaceId, user.sub) } })+ // Removed from the Workspace: its row says so until purged, and the Workspace's own decline after that.+ if (prior?.removedAt || (!prior && await autoJoinDeclinedBy(tx, state.workspaceId, user.sub))) return 'revoked' as const+ await addMember(tx, state.workspaceId, { id: user.sub, email }, 'guest', state.ownerId, generation)+ }+ state.people.push({ id: user.sub, email, role: state.sharing!.access.role, generation, joinedVia: 'domain' })+ await this.save(tx, loaded, state, stamp, [{ kind: 'head', key: 'head' }])+ // People per Swarm is what warns first at scale (spec, Design 4).+ logger.info('[super-tab] auto-join', { tabId, userId: user.sub, people: state.people.length })+ return 'joined' as const+ }).catch(error => {+ // A Swarm deleted since the read is found by nobody.+ if (error instanceof SuperTabError && error.code === 'NOT_FOUND') return 'skipped' as const+ throw error+ })+ if (outcome !== 'revoked') return outcome+ await transaction(this.db, async tx => {+ const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)+ if (state.autoJoinDeclined?.includes(user.sub) || state.people.some(p => p.id === user.sub)) return+ state.autoJoinDeclined = declinedWith(state, user.sub)+ await this.save(tx, loaded, state, clock.next())+ })+ return 'declined'+ }+/** Opens a Swarm to its Workspace's members, or closes it again: its owner (not a guest) or the Workspace's owners and admins,* who need not be in the Swarm. Closing it leaves everyone who joined. */async setWorkspaceVisibility(user: AuthUser, tabId: string, visibility: 'invite-only' | 'workspace') {@@ -1096,7 +1150,7 @@ export class SuperTabStore {return transaction(this.db, async tx => {const { state } = await this.load(tx, user, tabId)requireSharingOwner(state, user.sub)- return sharingDetails(state)+ return sharingDetails(state, user.email)})}@@ -1112,14 +1166,14 @@ export class SuperTabStore {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)+ return sharingDetails(state, user.email)}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)+ state.sharing = configureSharing(state.sharing, request.access, request.rotateLink, user.email)const stamp = clock.next(), { written } = await this.save(tx, loaded, state, stamp, [{ kind: 'member', key: user.sub }])await tx.superTabOperation.create({ data: { id: receiptId, tabId, actorKey: `person:${user.sub}`, requestHash,revision: 0, parts: json(receiptParts(written, stamp)), result: { generation: state.sharing.generation } } })- return sharingDetails(state)+ return sharingDetails(state, user.email)})}@@ -1128,7 +1182,7 @@ export class SuperTabStore {this.personOnly(user)return transaction(this.db, async tx => {const { state } = await this.load(tx, user, tabId)- const sharing = authorizeSwarmJoin(state, user.email, token)+ const sharing = authorizeSwarmJoin(state, user.email, token, user.sub)const member = state.people.find(p => p.id === user.sub)return { id: tabId, name: state.name, role: member?.role ?? sharing.access.role, alreadyMember: !!member }})@@ -1141,7 +1195,7 @@ export class SuperTabStore {const loaded = await this.load(tx, user, tabId), state = cloneData(loaded.state)// 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 sharing = authorizeSwarmJoin(state, user.email, request.token, user.sub)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)@@ -1165,6 +1219,8 @@ export class SuperTabStore {member = { id: user.sub, email: authenticatedEmail(user.email)!, role: sharing.access.role, generation: receiptId }state.people.push(member)}+ // A join by link or domain link is coming back on purpose: it clears a decline (spec 2026-11-03, Leaving is final).+ if (state.autoJoinDeclined?.includes(user.sub)) state.autoJoinDeclined = declinedWithout(state, user.sub)// Existing people retain their role and private-project grants. A general// access link does not promote a viewer or grant a private project.// The join relied on the sharing generation the head holds: a concurrent sharing change conflicts with it.@@ -2881,6 +2937,41 @@ export class SuperTabStore {try { return (await this.projectRepository({ sub: userId, email: person.email, role: 'user', autonomousEnv }, tabId, projectId)).name } catch { return null }}+ /** Moves the GitHub revision of every project of [tabId] on [repository] (owner/name, any case): someone allowed it, or+ * GitHub sent someone back after installing the app there, so members' apps read its access again (projects.ts+ * githubRevision). A deleted or missing Swarm moves nothing. */+ async githubChanged(tabId: string, repository: string): Promise<void> {+ const key = repository.toLowerCase()+ await this.moveGitHub(tabId, project => githubRepository(project.repository?.repositoryUrl ?? '')?.fullName.toLowerCase() === key)+ }++ /** Records what a check that asked GitHub again found for [projectId], moving its GitHub revision when that differs+ * from the last one recorded. States that are no answer from GitHub record nothing. Whether it moved. */+ async githubSeen(tabId: string, projectId: string, state: string): Promise<boolean> {+ if (!(GITHUB_SEEN as readonly string[]).includes(state)) return false+ const seen = state as GitHubSeen+ return this.moveGitHub(tabId, project => project.id === projectId && project.githubSeen !== seen, project => { project.githubSeen = seen })+ }++ /** One state write moving the GitHub revision of the projects [moves] picks, re-read in its transaction; none picked+ * writes nothing. */+ private async moveGitHub(tabId: string, moves: (project: SwarmProject) => boolean, also?: (project: SwarmProject) => void): Promise<boolean> {+ return transaction(this.db, async tx => {+ const row = await tx.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })+ if (!row || row.deletedAt) return false+ const loaded = await loadRow(tx, requireParts(row), {})+ const state = cloneData(loaded.state)+ const moved = (state.projects ?? []).filter(moves)+ if (!moved.length) return false+ for (const project of moved) {+ project.githubRevision = (project.githubRevision ?? 0) + 1+ also?.(project)+ }+ await this.save(tx, loaded, state, clock.next(), [{ kind: 'head', key: 'head' }])+ return true+ })+ }+async machineRemoval(user: AuthUser, tabId: string, machineId: string) {return transaction(this.db, async tx => {const { state } = await this.load(tx, user, tabId)@@ -3244,6 +3335,7 @@ export class SuperTabStore {/** When each caller's full delivery poll last succeeded for an agent: key is tab, agent and caller. */private readonly polls: PollMemory+ private readonly autoJoins: AutoJoinMemory/*** Every running agent's host polls this each second. With nothing waiting and the full poll (which loads the Swarm anddiff --git a/backend/src/superTabs/swarmRows.ts b/backend/src/superTabs/swarmRows.tsindex 94178ea88..1d32f6f3f 100644--- a/backend/src/superTabs/swarmRows.ts+++ b/backend/src/superTabs/swarmRows.ts@@ -43,3 +43,12 @@ export async function swarmsIn(db: Transaction, autonomousEnv: string, ids: striif (!ids.length) return []return (await readBy(db, 'SuperTab', 'id', [{ $match: { _id: { $in: ids }, autonomousEnv } }, { $project: { _id: 1 } }])).map(row => row._id as string)}++/** Up to `limit` live Swarms people at `domain` join by themselves (autoJoin.ts) that `userId` is not in and never declined: one+ * read on the auto-join index, which usually matches nothing. The two `$ne` are checked on the few rows of the domain. */+export async function autoJoinSwarms(db: Transaction, autonomousEnv: string, domain: string, userId: string, limit: number): Promise<string[]> {+ const rows = await readBy(db, 'SuperTab', 'autoJoin', [+ { $match: { autonomousEnv, autoJoinDomain: domain, deletedAt: null, memberIds: { $ne: userId }, autoJoinDeclined: { $ne: userId } } },+ { $limit: limit }, { $project: { _id: 1 } }])+ return rows.map(row => row._id as string)+}diff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex 2dc7f5e0f..a21c6bdb3 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -68,6 +68,8 @@ export async function addMember(tx: Transaction, workspaceId: string, person: {checked.get(tx)?.delete(id)const prior = await tx.swarmWorkspaceMember.findUnique({ where: { id } })if (prior && !prior.removedAt) return prior+ // Added back: by an invitation, a link or an open Swarm, never by auto-join, which refuses anyone declined here first.+ await clearAutoJoinDecline(tx, workspaceId, person.id)if (await tx.swarmWorkspaceRemoval.count({ where: { workspaceId, userId: person.id, finishedAt: null } })) {fail('REMOVAL_PENDING', `An earlier removal from this ${WORKSPACE_LABEL} is still taking them out of its Swarms. Try again in a few minutes.`, 409)}@@ -77,6 +79,19 @@ export async function addMember(tx: Transaction, workspaceId: string, person: {: tx.swarmWorkspaceMember.create({ data: { id, workspaceId, userId: person.id, ...data } })}+/** Whether this Workspace removed `userId`: auto-join never adds them to its Swarms. Unlike the member row, never purged. */+export async function autoJoinDeclinedBy(tx: Transaction, workspaceId: string, userId: string): Promise<boolean> {+ const workspace = await tx.swarmWorkspace.findUnique({ where: { id: workspaceId }, select: { autoJoinDeclined: true } })+ return !!workspace?.autoJoinDeclined.includes(userId)+}++async function clearAutoJoinDecline(tx: Transaction, workspaceId: string, userId: string): Promise<void> {+ const workspace = await tx.swarmWorkspace.findUnique({ where: { id: workspaceId }, select: { autoJoinDeclined: true } })+ if (workspace?.autoJoinDeclined.includes(userId)) {+ await tx.swarmWorkspace.update({ where: { id: workspaceId }, data: { autoJoinDeclined: workspace.autoJoinDeclined.filter(id => id !== userId) } })+ }+}+/** The Workspace a Swarm is created in: the one named, where the person may create Swarms, or else their own, made now. */export async function workspaceForNewSwarm(tx: Transaction, user: AuthUser, swarmName: string, generation: string, workspaceId?: string): Promise<string> {if (workspaceId) {@@ -286,6 +301,9 @@ export class SwarmWorkspaces {const now = new Date(this.deps.now())await tx.swarmWorkspaceMember.update({ where: { id: target.id }, data: { removedAt: now, removedBy: user.sub,purgeAt: new Date(now.getTime() + WORKSPACE_PURGE_MS), version: { increment: 1 } } })+ // Swarm auto-join never adds them back, even after this row is purged (spec 2026-11-03; security review 2 of #2714).+ const declined = (await tx.swarmWorkspace.findUnique({ where: { id: workspaceId }, select: { autoJoinDeclined: true } }))?.autoJoinDeclined ?? []+ if (!declined.includes(userId)) await tx.swarmWorkspace.update({ where: { id: workspaceId }, data: { autoJoinDeclined: [...declined, userId].sort() } })// The removal stays open until the person has left every Swarm of the Workspace, whatever happens to their row after.return tx.swarmWorkspaceRemoval.create({ data: { id: `${target.id}:${target.generation}`, workspaceId, userId, email: target.email,generation: target.generation, autonomousEnv: workspace.autonomousEnv, removedAt: now, removedBy: user.sub, finishedAt: null, purgeAt: null } })diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.tsindex ee852b029..2542fcaae 100644--- a/backend/vitest.super-tabs.config.ts+++ b/backend/vitest.super-tabs.config.ts@@ -1,6 +1,6 @@import { defineConfig } from 'vitest/config'-export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',+export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabAutoJoin.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts','integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabInbox.test.ts', 'integration/superTabFollowedThreads.test.ts', 'integration/superTabActivity.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/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts',diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 6d398ae8b..cea87d45f 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1252,31 +1252,55 @@ class SuperTabController extends ChangeNotifier {/// rebuild either.final Map<String, DateTime> _githubAsked = {};+ /// The project's GitHub revision each read was asked at ([SuperTabProject.githubRevision]): another one in the+ /// Swarm read means the access may have changed, so it is read again at once (task #2316).+ final Map<String, int> _githubRevisionAsked = {};+/// Whether teammates' agents can push to [projectId]'s repository, as last read; null before a read, or from a/// server too old to say.SuperTabProjectGitHub? githubAccessOf(String projectId) =>_github[projectId]?.value;- /// Reads [projectId]'s GitHub access, at most every 5 minutes; [refresh]: a person checks again (the server asks- /// GitHub at once, at most every 15 seconds per repository). An older server has no such read: nothing is shown.+ /// Reads [projectId]'s GitHub access, at most every 5 minutes unless the project's GitHub revision moved since the+ /// last read (someone allowed its repository or installed the app: read again at once); [refresh]: a person checks+ /// again (the server asks GitHub at once, at most every 15 seconds per repository, and records the answer). A moved+ /// revision asks GitHub again too, since another server may still keep "not installed", but records nothing. An+ /// older server has no such read: nothing is shown.Future<void> readGitHubAccess(String projectId, {bool refresh = false,}) async {+ final revision =+ snapshot?.projects+ .where((p) => p.id == projectId)+ .firstOrNull+ ?.githubRevision ??+ 0;+ final readAt = _githubRevisionAsked[projectId];+ // Read again because the revision moved: asks GitHub again, but records nothing (`record=0`), so servers whose caches+ // differ cannot move it back and forth (review of #2713). A person's own check records.+ final moved = !refresh && readAt != null && readAt != revision;final asked = _githubAsked[projectId];if (_disposed ||accessRevoked ||(!refresh &&+ !moved &&asked != null &&clock.now().difference(asked) < const Duration(minutes: 5))) {return;}+ // A read already out finishes first; the revision it was asked at still differs, so the next call reads again.if (!_githubReading.add(projectId)) return;_githubAsked[projectId] = clock.now();+ _githubRevisionAsked[projectId] = revision;try {final answer = await request('GET',- '$_path/projects/${Uri.encodeComponent(projectId)}/github${refresh ? '?refresh=1' : ''}',+ '$_path/projects/${Uri.encodeComponent(projectId)}/github${refresh+ ? '?refresh=1'+ : moved+ ? '?refresh=1&record=0'+ : ''}',);_github[projectId] = (value: SuperTabProjectGitHub.fromJson(answer),diff --git a/desktop/lib/super_tabs/manage_page.dart b/desktop/lib/super_tabs/manage_page.dartindex 24a7d6b0d..eba4e4235 100644--- a/desktop/lib/super_tabs/manage_page.dart+++ b/desktop/lib/super_tabs/manage_page.dart@@ -289,8 +289,9 @@ class _ManageSwarmState extends State<_ManageSwarm> {requireWrite: false,child: AlertDialog(title: const Text('Leave Swarm?'),- content: const Text(+ content: superTabLeaveWords('Swarm access and agent contributions will be withdrawn.',+ autoJoin: c.snapshot?.autoJoin == true,),actions: [TextButton(diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex 0973d864e..ca801e593 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -46,6 +46,7 @@ class SuperTabPerson {email = _text(row, 'email'),role = _text(row, 'role'),generation = row['generation'] as String?,+ joinedVia = row['joinedVia'] as String?,avatar = SuperTabAvatarPicture.fromJson(row['avatar']),status = SuperTabPersonStatus.fromJson(row['status']),chosenUsername = row['username'] as String?,@@ -57,6 +58,7 @@ class SuperTabPerson {email = person.email,role = person.role,generation = person.generation,+ joinedVia = person.joinedVia,avatar = person.avatar,status = person.status,chosenUsername = person.chosenUsername;@@ -79,6 +81,10 @@ class SuperTabPerson {/// This membership: a new one each time the person joins the Swarm. Null/// from a backend that does not send it.final String? generation;++ /// How they joined: `domain` when they were added automatically for their+ /// email's domain. Null otherwise and from an older server.+ final String? joinedVia;bool get canWrite => role == 'owner' || role == 'collaborator';}@@ -457,6 +463,7 @@ class SuperTabProject {instructionsRevision =(row['instructionsRevision'] as num?)?.toInt() ?? 0,notesRevision = (row['notesRevision'] as num?)?.toInt() ?? 0,+ githubRevision = (row['githubRevision'] as num?)?.toInt() ?? 0,isPrivate = row['visibility'] == 'private',memberIds = [for (final member in row['members'] as List? ?? const [])@@ -476,6 +483,10 @@ class SuperTabProject {final String? coordinatorName;final int instructionsRevision, notesRevision;+ /// Moves when its repository's GitHub access may have changed (someone allowed it, or the app was installed): the+ /// app reads that access again at once rather than keeping it 5 minutes. 0 from a backend before it (task #2316).+ final int githubRevision;+/// Whether the backend keeps an instruction document for it.bool get hasInstructions => coordinatorName != null;final bool isPrivate;@@ -564,6 +575,7 @@ class SuperTabSnapshot {threadSessions = row['threadSessions'] == true,sessionsFromChat = row['sessionsFromChat'] == true,swarmBuddy = row['swarmBuddy'] == true,+ autoJoin = row['autoJoin'] == true,mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,mentionsDigest = row['mentionsDigest'] as String?,decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,@@ -679,6 +691,10 @@ class SuperTabSnapshot {/// session in a project. False from an older one, whose Buddies are per/// project.final bool swarmBuddy;++ /// People at the owner's email domain are added automatically (head+ /// `autoJoin`, every member reads it): someone who leaves is not added back.+ final bool autoJoin;final int mentionsWaiting;/// Which tags wait, as a digest that moves when they change though thediff --git a/desktop/lib/super_tabs/project_github.dart b/desktop/lib/super_tabs/project_github.dartindex ea0cb14ea..8c08d7049 100644--- a/desktop/lib/super_tabs/project_github.dart+++ b/desktop/lib/super_tabs/project_github.dart@@ -79,7 +79,8 @@ String _names(List<String> names) => names.length < 2: '${names.sublist(0, names.length - 1).join(', ')} and ${names.last}';/// The project's GitHub access in full, with what to do about it: Project details' row, and the dialog the sidebar line-/// opens ([dialog]). Read when shown; [SuperTabController.readGitHubAccess] keeps it at most 5 minutes.+/// opens ([dialog]). Asks GitHub again when shown, so a setup done on GitHub's own site is picked up by whoever opens+/// it, and through the project's GitHub revision by everyone else (task #2316).class ProjectGitHubAccess extends StatefulWidget {const ProjectGitHubAccess({super.key,@@ -128,7 +129,7 @@ class _ProjectGitHubAccessState extends State<ProjectGitHubAccess>void initState() {super.initState();WidgetsBinding.instance.addObserver(this);- widget.controller.readGitHubAccess(widget.projectId);+ widget.controller.readGitHubAccess(widget.projectId, refresh: true);}@overridediff --git a/desktop/lib/super_tabs/sharing.dart b/desktop/lib/super_tabs/sharing.dartindex f28f90baf..e5ae4aea5 100644--- a/desktop/lib/super_tabs/sharing.dart+++ b/desktop/lib/super_tabs/sharing.dart@@ -43,6 +43,10 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {_saving = false,_peopleExpanded = false,_copied = false;++ /// With `domain`: the owner's own domain rather than a typed one, and+ /// whether people there are added automatically.+ bool _own = false, _autoJoin = false;String? _sharingError, _emailError;Map<String, dynamic>? _settings, _pending;Timer? _copyFeedback;@@ -51,23 +55,42 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {bool get _current => mounted && !c.accessRevoked && c.isOwner;bool get _busy =>_saving || c.saving || c.hasPendingAction || _pending != null;++ /// The owner's own email domain, as the server read it; null from an older+ /// server, which takes only a typed domain and knows no automatic joins.+ String? get _ownDomain => switch (_settings?['ownDomain']) {+ final String domain when domain.isNotEmpty => domain,+ _ => null,+ };++ /// The owner's domain is one anyone can make an address at (gmail.com):+ /// nobody is let in by it.+ bool get _ownPublic => _settings?['ownDomainPublic'] == true;+ bool get _ownUsable => _ownDomain != null && !_ownPublic;+ String get _typedDomain => _domain.text.trim().toLowerCase();Map<String, dynamic> get _access => {'mode': _mode,'role': _role,- if (_mode == 'domain') 'domain': _domain.text.trim().toLowerCase(),+ if (_mode == 'domain') 'domain': _own ? _ownDomain : _typedDomain,+ // Sent every time, so turning it off is never left to the saved value.+ if (_mode == 'domain' && _ownDomain != null) 'autoJoin': _own && _autoJoin,};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']);+ (_mode == 'domain' && _access['domain'] != saved['domain']) ||+ (_mode == 'domain' &&+ _ownDomain != null &&+ _access['autoJoin'] != (saved['autoJoin'] == true));}bool get _domainValid =>_mode != 'domain' ||+ _own ||RegExp(r'^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$')- .hasMatch(_domain.text.trim().toLowerCase());+ .hasMatch(_typedDomain);String? get _joinUrl {final value = _settings?['joinUrl'];if (value is! String) return null;@@ -111,7 +134,10 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {_settings = reply;_mode = access['mode'] as String;_role = access['role'] as String;- _domain.text = access['domain'] as String? ?? '';+ final domain = access['domain'] as String? ?? '';+ _own = _mode == 'domain' && _ownUsable && domain == _ownDomain;+ _autoJoin = _own && access['autoJoin'] == true;+ _domain.text = _own ? '' : domain;_copied = false;}@@ -245,8 +271,9 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {requireWrite: false,child: AlertDialog(title: Text(leaving ? 'Leave Swarm?' : 'Remove ${person.email}?'),- content: const Text(+ content: superTabLeaveWords('Swarm access and agent contributions will be withdrawn. Running harnesses stay on their machines.',+ autoJoin: leaving && c.snapshot?.autoJoin == true,),actions: [TextButton(@@ -382,6 +409,12 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {: 'Can collaborate',style: DesktopChrome.metadata(),),+ if (person.joinedVia == 'domain' &&+ person.email.contains('@'))+ Text(+ 'Joined with @${person.email.split('@').last}',+ style: DesktopChrome.metadata(),+ ),],),),@@ -439,6 +472,69 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {],);+ /// Under Invited people: a share the server turned off, and Everyone at a+ /// public domain shown unavailable.+ List<Widget> _invitedNotes() => [+ if (_settings?['turnedOffDomain'] case final String domain) ...[+ const SizedBox(height: 8),+ Text(+ 'Sharing with @$domain was turned off: anyone can make an address there.',+ style: DesktopChrome.metadata(),+ ),+ ],+ if (_ownPublic && _ownDomain != null) ...[+ const SizedBox(height: 8),+ Text(+ 'Everyone at @$_ownDomain',+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ Text(+ 'Not available for @$_ownDomain: anyone can make an address there. Invite people or share a link.',+ style: DesktopChrome.metadata(),+ ),+ ],+ ];++ /// Add them automatically: only at the owner's own domain.+ List<Widget> _autoJoinChoice() {+ final own = _ownDomain!, typed = _typedDomain;+ return [+ const SizedBox(height: 8),+ CheckboxListTile(+ key: const Key('swarm-sharing-auto-join'),+ dense: true,+ contentPadding: EdgeInsets.zero,+ controlAffinity: ListTileControlAffinity.leading,+ title: Text(+ 'Add them automatically',+ style: DesktopChrome.control(+ color: _own ? null : DesktopChrome.muted,+ ),+ ),+ subtitle: _own+ ? Text(+ 'Anyone who signs in with an @$own email joins this Swarm. You can remove anyone.',+ style: DesktopChrome.metadata(),+ )+ : typed.isEmpty+ ? null+ : Text(+ 'Automatic joins work only for @$own, your own domain. People at $typed join with the link.',+ style: DesktopChrome.metadata(),+ ),+ value: _own && _autoJoin,+ onChanged: !_own || _busy+ ? null+ : (value) => setState(() => _autoJoin = value == true),+ ),+ if (_own && _autoJoin && _settings?['autoJoinFull'] == true)+ Text(+ 'Automatic joins stopped: this Swarm has 200 people.',+ style: DesktopChrome.metadata(),+ ),+ ];+ }+@overrideWidget build(BuildContext context) => ListenableBuilder(listenable: c,@@ -488,30 +584,65 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {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 (_ownDomain case final own?)+ _select(+ key: const Key('swarm-general-access'),+ value: _mode != 'domain'+ ? _mode+ : _own+ ? 'own'+ : 'other',+ label: 'General access',+ options: [+ const SelectOption(+ value: 'invited',+ label: 'Invited people',+ ),+ // No row that does nothing: at a public domain the+ // choice is shown unavailable below instead.+ if (!_ownPublic)+ SelectOption(value: 'own', label: 'Everyone at @$own'),+ const SelectOption(value: 'other', label: 'Other domain…'),+ const SelectOption(+ value: 'link',+ label: 'Anyone with the link',+ ),+ ],+ onChanged: (value) => setState(() {+ _mode = const {'own', 'other'}.contains(value)+ ? 'domain'+ : value;+ _own = value == 'own';+ if (!_own) _autoJoin = false;+ _copied = false;+ }),+ )+ else+ _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') ...[+ }),+ ),+ if (_mode == 'invited') ..._invitedNotes(),+ if (_mode == 'domain' && !_own) ...[const SizedBox(height: 8),TextField(key: const Key('swarm-sharing-domain'),@@ -534,6 +665,7 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {onChanged: (value) => setState(() => _role = value),),),+ if (_mode == 'domain' && _ownUsable) ..._autoJoinChoice(),const SizedBox(height: 8),Text('Private projects stay private.',@@ -633,3 +765,19 @@ class _SwarmSharingDialogState extends State<SwarmSharingDialog> {),);}++/// A leave or remove confirmation's words. Leaving a Swarm that adds people+/// at its owner's domain automatically also says the person is not added back.+Widget superTabLeaveWords(String words, {required bool autoJoin}) => autoJoin+ ? Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(words),+ const SizedBox(height: 8),+ const Text(+ "You won't be added back automatically. Ask the owner to invite you if you want to return.",+ ),+ ],+ )+ : Text(words);diff --git a/desktop/test/super_tab_project_github_test.dart b/desktop/test/super_tab_project_github_test.dartindex 2e802f455..fcd97f851 100644--- a/desktop/test/super_tab_project_github_test.dart+++ b/desktop/test/super_tab_project_github_test.dart@@ -144,6 +144,126 @@ void main() {},);+ // Task #2316 (Dee, 2026-11-03): after lampos's repository was allowed, the line stayed on everyone's computer for up to+ // 5 minutes. The backend moves the project's GitHub revision; the app reads again when it moves.+ group('the project\'s GitHub revision', () {+ /// The fixture's project with its GitHub revision at [revision], then a Swarm read.+ Future<void> moved(SuperTabController c, int revision) async {+ final projects = server.state['projects'] ??= <dynamic>[+ projectFixture('lead', server.state['name'] as String, 'lead'),+ ];+ ((projects as List).first as Map)['githubRevision'] = revision;+ server.revision++;+ await c.refresh();+ }++ testWidgets(+ 'the sidebar line clears when it moves, without waiting 5 minutes',+ (tester) async {+ answer = {+ 'state': 'not-approved',+ 'repository': 'acme/app',+ 'canApprove': true,+ };+ final c = await mount(+ tester,+ (c, p) => ProjectGitHubLine(controller: c, project: p),+ );+ expect(find.text('Set up GitHub for teammates'), findsOneWidget);+ expect(asked, hasLength(1));+ answer = {'state': 'covered', 'repository': 'acme/app'};+ await moved(c, 1);+ await tester.pumpAndSettle();+ expect(find.text('Set up GitHub for teammates'), findsNothing);+ // Asks GitHub again: another server may still keep "not installed". It records nothing, so servers whose+ // caches differ cannot move the revision back and forth (review of #2713).+ expect(asked, hasLength(2));+ expect(asked.last, endsWith('/github?refresh=1&record=0'));+ c.dispose();+ },+ );++ testWidgets('a read that does not move it keeps the 5-minute keep', (+ tester,+ ) async {+ final c = await mount(+ tester,+ (c, p) => ProjectGitHubLine(controller: c, project: p),+ );+ expect(asked, hasLength(1));+ await moved(c, 0);+ await tester.pumpAndSettle();+ expect(asked, hasLength(1));+ c.dispose();+ });++ test(+ 'a read in flight when it moves is read again once it lands',+ () async {+ final c = controllerFor();+ await c.refresh();+ final project = c.snapshot!.projects.first;+ hold = Completer<void>();+ final first = c.readGitHubAccess(project.id);+ await moved(c, 1);+ // Asked while the first read is still out: that one answers for the revision before.+ unawaited(c.readGitHubAccess(project.id));+ hold!.complete();+ await first;+ hold = null;+ await c.readGitHubAccess(project.id);+ expect(asked, hasLength(2));+ expect(asked.last, endsWith('/github?refresh=1&record=0'));+ await c.readGitHubAccess(project.id);+ expect(asked, hasLength(2));+ c.dispose();+ },+ );+ });++ // Review of #2713: a person's own check records what GitHub says, even right after the revision moved.+ test(+ 'a person checking again records the answer, even after a revision move',+ () async {+ final c = controllerFor();+ await c.refresh();+ final project = c.snapshot!.projects.first;+ await c.readGitHubAccess(project.id);+ final projects = server.state['projects'] ??= <dynamic>[+ projectFixture('lead', server.state['name'] as String, 'lead'),+ ];+ ((projects as List).first as Map)['githubRevision'] = 1;+ server.revision++;+ await c.refresh();+ await c.readGitHubAccess(project.id, refresh: true);+ expect(asked.last, endsWith('/github?refresh=1'));+ c.dispose();+ },+ );++ // Task #2316: a setup done on GitHub's own site is picked up when anyone opens the dialog or Project details.+ testWidgets(+ 'opening GitHub access asks GitHub again, even within 5 minutes',+ (tester) async {+ final c = controllerFor();+ await c.refresh();+ final project = c.snapshot!.projects.first;+ await c.readGitHubAccess(project.id);+ expect(asked, hasLength(1));+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: ProjectGitHubAccess(controller: c, projectId: project.id),+ ),+ ),+ );+ await tester.pumpAndSettle();+ expect(asked, hasLength(2));+ expect(asked.last, endsWith('/github?refresh=1'));+ c.dispose();+ },+ );+testWidgets('nothing is asked or shown in a Swarm of one, or when covered', (tester,) async {diff --git a/desktop/test/super_tab_sharing_auto_join_test.dart b/desktop/test/super_tab_sharing_auto_join_test.dartnew file mode 100644index 000000000..bf3c537da--- /dev/null+++ b/desktop/test/super_tab_sharing_auto_join_test.dart@@ -0,0 +1,381 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/manage_page.dart';+import 'package:harness/super_tabs/sharing.dart';+import 'package:harness/widgets/desktop_chrome.dart';++import 'swarm_sharing_test.dart' show SwarmSharingServer;+import 'swarm_state_test.dart' show createApp;++/// People at the owner's email domain join a Swarm by themselves+/// (docs/specs/2026-11-03-swarm-domain-auto-join.md, "Copy and screens").+class AutoJoinServer extends SwarmSharingServer {+ AutoJoinServer({+ this.ownDomain = 'acme.com',+ this.ownDomainPublic = false,+ this.autoJoinFull = false,+ this.turnedOffDomain,+ }) {+ final people = state['people'] as List;+ (people.first as Map)['email'] = 'ken@$ownDomain';+ }++ String ownDomain;+ bool ownDomainPublic, autoJoinFull;+ String? turnedOffDomain;++ @override+ Map<String, dynamic> get settings => {+ ...super.settings,+ 'ownDomain': ownDomain,+ 'ownDomainPublic': ownDomainPublic,+ 'autoJoinFull': autoJoinFull,+ 'turnedOffDomain': ?turnedOffDomain,+ };+}++const _help =+ 'Anyone who signs in with an @acme.com email joins this Swarm. You can remove anyone.';+const _partner =+ 'Automatic joins work only for @acme.com, your own domain. People at partner.com join with the link.';+const _public =+ 'Not available for @gmail.com: anyone can make an address there. Invite people or share a link.';+const _full = 'Automatic joins stopped: this Swarm has 200 people.';+const _turnedOff =+ 'Sharing with @gmail.com was turned off: anyone can make an address there.';+const _notBack =+ "You won't be added back automatically. Ask the owner to invite you if you want to return.";++Future<SuperTabController> _open(+ WidgetTester tester,+ SwarmSharingServer server, {+ String account = 'owner',+}) async {+ await tester.binding.setSurfaceSize(const Size(900, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final controller = server.controller(account: account);+ await controller.refresh();+ controller.select('offline');+ addTearDown(controller.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ 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();+}++Finder get _autoJoin => find.byKey(const Key('swarm-sharing-auto-join'));++CheckboxListTile _toggle(WidgetTester tester) =>+ tester.widget<CheckboxListTile>(_autoJoin);++Color? _titleColor(WidgetTester tester) =>+ tester.widget<Text>(find.text('Add them automatically')).style?.color;++Future<void> _save(WidgetTester tester) async {+ await tester.tap(find.byKey(const Key('swarm-sharing-save')));+ await tester.pumpAndSettle();+}++void main() {+ group('Share dialog, owner [email protected]', () {+ testWidgets(+ 'Everyone at @acme.com replaces a typed domain; turning auto-join on saves it',+ (tester) async {+ final server = AutoJoinServer();+ await _open(tester, server);+ await tester.tap(find.byKey(const Key('swarm-general-access')));+ await tester.pumpAndSettle();+ expect(find.text('Anyone at a domain'), findsNothing);+ expect(find.text('Other domain…'), findsOneWidget);+ await tester.tap(find.text('Everyone at @acme.com').last);+ await tester.pumpAndSettle();+ expect(find.byKey(const Key('swarm-sharing-domain')), findsNothing);+ expect(find.text('Add them automatically'), findsOneWidget);+ expect(find.text(_help), findsOneWidget);+ expect(find.text('Private projects stay private.'), findsOneWidget);+ // The owner turns it on by hand.+ expect(_toggle(tester).value, isFalse);+ expect(_toggle(tester).onChanged, isNotNull);+ expect(_titleColor(tester), isNot(DesktopChrome.muted));+ await tester.tap(_autoJoin);+ await tester.pumpAndSettle();+ expect(_toggle(tester).value, isTrue);+ await _save(tester);+ expect(server.sharingPosts.single['access'], {+ 'mode': 'domain',+ 'role': 'collaborator',+ 'domain': 'acme.com',+ 'autoJoin': true,+ });+ expect(find.text('Everyone at @acme.com'), findsOneWidget);+ expect(_toggle(tester).value, isTrue);+ expect(find.byKey(const Key('swarm-sharing-save')), findsNothing);+ },+ );++ testWidgets('a saved auto-join shows on; turning it off saves false', (+ tester,+ ) async {+ final server = AutoJoinServer()+ ..access = {+ 'mode': 'domain',+ 'role': 'viewer',+ 'domain': 'acme.com',+ 'autoJoin': true,+ };+ await _open(tester, server);+ expect(find.text('Everyone at @acme.com'), findsOneWidget);+ expect(_toggle(tester).value, isTrue);+ expect(find.byKey(const Key('swarm-sharing-save')), findsNothing);+ expect(find.text(_full), findsNothing);+ await tester.tap(_autoJoin);+ await tester.pumpAndSettle();+ await _save(tester);+ expect(server.sharingPosts.single['access'], {+ 'mode': 'domain',+ 'role': 'viewer',+ 'domain': 'acme.com',+ 'autoJoin': false,+ });+ expect(_toggle(tester).value, isFalse);+ });++ testWidgets(+ 'Other domain… keeps the typed field and disables auto-join with the partner copy',+ (tester) async {+ final server = AutoJoinServer();+ await _open(tester, server);+ await _choose(tester, 'swarm-general-access', 'Other domain…');+ final field = find.byKey(const Key('swarm-sharing-domain'));+ expect(field, findsOneWidget);+ await tester.enterText(field, 'partner.com');+ await tester.pumpAndSettle();+ expect(_toggle(tester).onChanged, isNull);+ // Reads as unavailable, not only its box.+ expect(_titleColor(tester), DesktopChrome.muted);+ expect(_toggle(tester).value, isFalse);+ expect(find.text(_partner), findsOneWidget);+ expect(find.text(_help), findsNothing);+ await _save(tester);+ expect(server.sharingPosts.single['access'], {+ 'mode': 'domain',+ 'role': 'collaborator',+ 'domain': 'partner.com',+ 'autoJoin': false,+ });+ // The saved partner share opens as Other domain… again.+ expect(find.text('Other domain…'), findsOneWidget);+ expect(tester.widget<TextField>(field).controller!.text, 'partner.com');+ },+ );++ testWidgets('an owner at a public domain cannot pick Everyone at it', (+ tester,+ ) async {+ final server = AutoJoinServer(+ ownDomain: 'gmail.com',+ ownDomainPublic: true,+ );+ await _open(tester, server);+ expect(find.text(_public), findsOneWidget);+ expect(find.text('Everyone at @gmail.com'), findsOneWidget);+ await tester.tap(find.text('Everyone at @gmail.com'));+ await tester.pumpAndSettle();+ expect(find.byKey(const Key('swarm-sharing-save')), findsNothing);+ await tester.tap(find.byKey(const Key('swarm-general-access')));+ await tester.pumpAndSettle();+ // In the open menu only the shown, unavailable one: no row to pick.+ expect(find.text('Everyone at @gmail.com'), findsOneWidget);+ expect(find.text('Other domain…'), findsOneWidget);+ await tester.tap(find.text('Invited people').last);+ await tester.pumpAndSettle();+ expect(_autoJoin, findsNothing);+ expect(server.sharingPosts, isEmpty);+ });++ testWidgets('a full Swarm says automatic joins stopped', (tester) async {+ final server = AutoJoinServer(autoJoinFull: true)+ ..access = {+ 'mode': 'domain',+ 'role': 'collaborator',+ 'domain': 'acme.com',+ 'autoJoin': true,+ };+ await _open(tester, server);+ expect(find.text(_full), findsOneWidget);+ });++ testWidgets('a share at a public domain that was turned off says so', (+ tester,+ ) async {+ final server = AutoJoinServer(turnedOffDomain: 'gmail.com');+ await _open(tester, server);+ expect(find.text('Invited people'), findsOneWidget);+ expect(find.text(_turnedOff), findsOneWidget);+ await _choose(tester, 'swarm-general-access', 'Anyone with the link');+ expect(find.text(_turnedOff), findsNothing);+ });++ testWidgets('an older server keeps the typed domain and no toggle', (+ tester,+ ) async {+ final server = SwarmSharingServer();+ await _open(tester, server);+ await _choose(tester, 'swarm-general-access', 'Anyone at a domain');+ expect(find.byKey(const Key('swarm-sharing-domain')), findsOneWidget);+ expect(_autoJoin, findsNothing);+ await _save(tester);+ expect(+ (server.sharingPosts.single['access'] as Map).containsKey('autoJoin'),+ isFalse,+ );+ });+ });++ group('People list', () {+ testWidgets('a person who came by domain says Joined with @their domain', (+ tester,+ ) async {+ final server = AutoJoinServer();+ (server.state['people'] as List)+ ..add({+ 'id': 'lan',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'joinedVia': 'domain',+ })+ ..add({'id': 'leo', 'email': '[email protected]', 'role': 'viewer'});+ await _open(tester, server);+ await tester.tap(find.byKey(const Key('swarm-sharing-people')));+ await tester.pumpAndSettle();+ expect(find.text('Joined with @acme.com'), findsOneWidget);+ expect(find.textContaining('Joined with'), findsOneWidget);+ });+ });++ group('Leave dialogs', () {+ Future<void> leaveFromSharing(+ WidgetTester tester, {+ required bool on,+ }) async {+ final server = AutoJoinServer();+ if (on) server.state['autoJoin'] = true;+ (server.state['people'] as List).add({+ 'id': 'lan',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'joinedVia': 'domain',+ });+ await _open(tester, server, account: 'lan');+ await tester.tap(find.widgetWithText(TextButton, 'Leave'));+ await tester.pumpAndSettle();+ expect(find.text('Leave Swarm?'), findsOneWidget);+ }++ testWidgets('Share dialog: leaving a Swarm with auto-join on warns', (+ tester,+ ) async {+ await leaveFromSharing(tester, on: true);+ expect(find.text(_notBack), findsOneWidget);+ });++ testWidgets('Share dialog: without auto-join, no warning', (tester) async {+ await leaveFromSharing(tester, on: false);+ expect(find.text(_notBack), findsNothing);+ });++ testWidgets('the owner removing someone sees no auto-join warning', (+ tester,+ ) async {+ final server = AutoJoinServer()..state['autoJoin'] = true;+ (server.state['people'] as List).add({+ 'id': 'lan',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ await _open(tester, server);+ await tester.tap(find.byKey(const Key('swarm-sharing-people')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(TextButton, 'Remove'));+ await tester.pumpAndSettle();+ expect(find.text('Remove [email protected]?'), findsOneWidget);+ expect(find.text(_notBack), findsNothing);+ });++ Future<void> leaveFromManage(+ WidgetTester tester, {+ required bool on,+ }) async {+ final server = AutoJoinServer();+ if (on) server.state['autoJoin'] = true;+ (server.state['people'] as List).add({+ 'id': 'member',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'generation': 'g',+ });+ final c = server.controller(account: 'member');+ await c.refresh();+ final AppNotifier app = createApp();+ addTearDown(app.dispose);+ await tester.binding.setSurfaceSize(const Size(800, 700));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabManagePage(+ controller: c,+ app: app,+ tab: SuperTabManageTab.swarm,+ onAddAgent: (_) {},+ ),+ ),+ ),+ );+ await tester.pump();+ addTearDown(() async {+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ });+ await tester.tap(find.byKey(const ValueKey('super-manage-leave')));+ await tester.pumpAndSettle();+ expect(find.text('Leave Swarm?'), findsOneWidget);+ }++ testWidgets('Manage: leaving a Swarm with auto-join on warns', (+ tester,+ ) async {+ await leaveFromManage(tester, on: true);+ expect(find.text(_notBack), findsOneWidget);+ });++ testWidgets('Manage: without auto-join, no warning', (tester) async {+ await leaveFromManage(tester, on: false);+ expect(find.text(_notBack), findsNothing);+ });+ });+}diff --git a/docs/plans/2026-11-03-github-access-revision-plan.md b/docs/plans/2026-11-03-github-access-revision-plan.mdnew file mode 100644index 000000000..f3e8778f8--- /dev/null+++ b/docs/plans/2026-11-03-github-access-revision-plan.md@@ -0,0 +1,136 @@+# GitHub access clears within one Swarm refresh: implementation plan++> Worked by this project's instructions (Engineer role): this plan is the pull request's first commit, then each task+> test first, one Engineer, one Review step on the pull request. Steps use checkbox (`- [ ]`) syntax.++**Goal:** after someone allows a repository for a project, every member's Desktop drops "Set up GitHub for teammates"+within one Swarm refresh (seconds), and an install done on GitHub's own site is picked up for everyone once anyone opens+the setup dialog or Project details.++**Architecture:** each Swarm project gets a GitHub revision in its Swarm state (`githubRevision`, as `notesRevision`+for notes). The backend moves it when an approval is written, when GitHub sends a person back after installing, and+when a dialog read asking GitHub again (`refresh=1`) finds a different state from the one it last recorded+(`githubSeen`). That state write reaches every member through the Swarm read they already poll. Desktop keeps the+revision it read GitHub access at. When the revision changes, it reads again at once with `refresh=1`, without waiting+out the 5-minute keep, which stays as the fallback.++**Tech Stack:** backend TypeScript (Fastify, Prisma on MongoDB, vitest integration suite on a loopback MongoDB and+`fakeGitHub`); Desktop Flutter 3.47.2 (`flutter_test` with `ConversationServer` fixture).++**Spec:** task #2316 brief (Lead, 2026-11-03 11:51 VN), "Set up GitHub for teammates" clears on every computer within+seconds of allowing it (Dee).++## Global Constraints++- PR body first line: "Requested by [email protected] through Harness."+- Approvals decide who can push through the app; this changes only when apps re-read, never who is allowed.+- Before Ready: a test that fails without the fix for every risk named here, red/green evidence in a PR comment, and the+ full Super Tab integration suite for the backend change.+- Never run a test that signs the Mac out of the real CLI (Desktop tests use a memory store and a fake sign-in).+- Swarm code stays out of cli/src/core. Stop only processes you started, by id. Temp files only in mktemp -d folders.+- The 5-minute re-read stays as the fallback (`readGitHubAccess`).++## Design++- Growth: one counter and one state word per project, inside the project's own record; they go when the project or+ Swarm is deleted. Nothing new is stored per read or per person.+- Concurrency: each move is one Swarm state transaction on the head part (where projects live), as every command is;+ a concurrent writer retries. A dialog read writes only when the state it found differs from `githubSeen`, re-checked+ inside the transaction.+- Read cost: the revision rides in the Swarm read clients already make. A client re-reads GitHub access only for the+ project whose revision moved. The backend asks GitHub again at most every 15 s per repository per server+ (`GitHubApp.forget`).+- Scale 10x: each move is one head write plus one GitHub access read per member watching the line. The first metric+ to warn is GitHub API calls of the app's installation (rate limit) from `refresh=1` reads; these are bounded per+ repository by the 15 s forget limit.+- Compatibility: older clients ignore the new fields and keep the 5-minute re-read. New clients reading an older+ backend see revision 0 that never moves, so they behave as today.+- Migration + rollback: none. The fields are optional. Rolling back leaves them in the state, unread.+- Audience: the fields are part of the project as `visibleState` already filters it (readers of the project). The+ GitHub access route checks the reader as before, and the move needs no reader beyond a person the route already let in.+- Identity: N/A because nothing here acts on GitHub as anyone; the read uses the app as before.+- Failure: a move that fails is logged (`[github] access change not recorded`). The approval page still says it was+ allowed and the GitHub read still answers. Clients then fall back to the 5-minute re-read.+- Platforms: Desktop shows the line (project_github.dart). Web and the phone app do not show it (checked:+ no "Set up GitHub for teammates" in web/ or mobile/), so they need no change.++## Review Focus++1. Two servers with different "not installed" caches: a refresh read on a stale server must not keep moving the+ revision back and forth. Only `refresh=1` reads record a state, and `forget` runs first. Test: a second refresh read+ finding the same state moves nothing (Task 1).+2. A swarm-wide approval (`scope: swarm`) must move every project on that repository, not just the one asked from+ (Task 1 test).+3. A failed move must not turn an allowed repository's page into an error (Task 1 test: the approval page is still+ 200 when the move throws).+4. A read already in flight when the revision moves must be read again once it lands, not lost (Task 2 test).+5. A project whose revision never moves (an older backend) keeps the 5-minute keep exactly (Task 2 test).++---++### Task 1: backend moves a project's GitHub revision++**Files:**+- Modify: `backend/src/superTabs/projects.ts` (SwarmProject fields)+- Modify: `backend/src/superTabs/store.ts` (two methods near `projectRepository`)+- Modify: `backend/src/routes/superTabs.ts` (callback and GitHub access route)+- Test: `backend/integration/superTabGithub.test.ts`++**Interfaces:**+- Produces: `SwarmProject.githubRevision?: number`, `SwarmProject.githubSeen?: 'not-installed' | 'not-approved' | 'covered'`.+- Produces: `SuperTabStore.githubChanged(tabId: string, repository: string): Promise<void>` moves `githubRevision` of+ every project of the Swarm whose repository is that GitHub repository (owner/name, any case or `.git`). It does nothing+ for a deleted or missing Swarm.+- Produces: `SuperTabStore.githubSeen(tabId: string, projectId: string, state: ProjectGitHubAccess['state']): Promise<boolean>`+ records the state and moves the revision when it differs from `githubSeen`. It returns whether it moved. It ignores any state other than the+ three above.++- [ ] **Step 1: write the failing tests** in a new `describe('the GitHub revision')`:+ - `moves every project on the repository when someone allows it, and a swarm-wide approval moves them all`: two+ projects on example/app plus one on example/other. A project-scope approval through the callback moves both on+ example/app by 1 and leaves example/other at its revision. A swarm-scope approval moves both again.+ - `a dialog read that finds the app installed now moves it once; the same answer again moves nothing`: delete+ example/app from `github.installed`, read `?refresh=1`, which records `not-installed` and moves the revision. Install it, then+ read `?refresh=1`: the revision moves again. Read `?refresh=1` again: no move. Read without refresh after an+ uninstall: no move.+ - `GitHub sending a person back after installing forgets the cache and moves it`: callback with `installation_id` and+ no code moves the revision.+ - `an approval whose move fails still says it is allowed`: `store.githubChanged` stubbed to throw; the page is 200,+ "example/app is allowed", and `log.warn` was called.+ - Revisions read with `store.load(tx, owner, tab)` in a transaction.+- [ ] **Step 2: run them and see them fail** (`cd backend && npx vitest run integration/superTabGithub.test.ts -t+ "GitHub revision"`): fails with "githubChanged is not a function" or revision undefined.+- [ ] **Step 3: implement.** Store methods load the row as `postReflection` does (no reader), use `cloneData`, change the+ matched projects, and `save` with a head touch. Route: after `approvals.approve` call `store.githubChanged`, catching and+ logging a failure. In the no-code callback, call `github.app.forget(named)` and then `store.githubChanged`. In the GitHub access+ route, when `refresh=1`, call `store.githubSeen` with the answer's state (caught and logged).+- [ ] **Step 4: run them and see them pass**, plus `npm test -- src/github` and the GitHub integration file.+- [ ] **Step 5: commit** test first, then code.++### Task 2: Desktop re-reads GitHub access when the revision moves++**Files:**+- Modify: `desktop/lib/super_tabs/model.dart` (`SuperTabProject.githubRevision`)+- Modify: `desktop/lib/super_tabs/controller.dart` (`readGitHubAccess`)+- Modify: `desktop/lib/super_tabs/project_github.dart` (dialog and Project details read with refresh)+- Test: `desktop/test/super_tab_project_github_test.dart`++**Interfaces:**+- Consumes: the project row's `githubRevision` (Task 1).+- Produces: `SuperTabProject.githubRevision` (int, 0 when absent).++- [ ] **Step 1: write the failing tests:**+ - `the sidebar line clears when the project's GitHub revision moves, without waiting 5 minutes`: the line is shown for+ `not-approved`. The answer becomes `covered` and the fixture's project `githubRevision` becomes 1. After `c.refresh()`+ and a pump, the line is gone and the last GitHub read asked `?refresh=1`.+ - `a revision that does not move keeps the 5-minute keep`: a refresh with the same revision asks nothing.+ - `a read in flight when the revision moves is read again after it lands`: a held read with the revision moving+ during it reads once more.+ - `opening the setup dialog asks GitHub again`: a read within 5 minutes still asks `?refresh=1` when the dialog opens.+- [ ] **Step 2: run them and see them fail** (`flutter test test/super_tab_project_github_test.dart`).+- [ ] **Step 3: implement.** `readGitHubAccess` records the snapshot revision it asked at (`_githubRevisionAsked`).+ A different revision now passes the keep and reads with `refresh=1`. `ProjectGitHubAccess.initState` reads with+ `refresh: true`.+- [ ] **Step 4: run them and see them pass**, plus every `super_tab*` test that names `readGitHubAccess`,+ `githubAccessOf` or `ProjectGitHubAccess`, and `check-ui-style`.+- [ ] **Step 5: commit** test first, then code.diff --git a/docs/plans/2026-11-03-swarm-domain-auto-join-plan.md b/docs/plans/2026-11-03-swarm-domain-auto-join-plan.mdnew file mode 100644index 000000000..5a8bc0647--- /dev/null+++ b/docs/plans/2026-11-03-swarm-domain-auto-join-plan.md@@ -0,0 +1,208 @@+# Swarm domain auto-join Implementation Plan++> **How this plan runs:** by this project's instructions (Engineer role): the Engineer implements it task by task, test+> first (failing test committed, watched failing, then the code), and the pull request's Review step is the one+> independent review. Tasks 1–5 (backend) and Task 6 (Desktop) share no files; Task 6 runs in parallel by its own+> subagent against the API contract below. Steps use checkbox (`- [ ]`) syntax.++**Goal:** A person signed in at the owner's email domain is joined, with no click, to every Swarm whose owner turned on+"Add them automatically"; nobody at a public domain ever is; a person who left is never pulled back.++**Architecture:** The setting lives in `state.sharing.access` (head part). Two derived columns on the `SuperTab` row,+`autoJoinDomain` and `autoJoinDeclined`, come from `indexesOf(state)` (parts/commit.ts), so they are written in the same+guarded row update as `memberIds` by every commit that changes them; one named index `[autonomousEnv, autoJoinDomain]`+serves the pull. `autoJoin(user)` (superTabs/autoJoin.ts) runs before both list reads, at most once per person per+2 minutes (Redis `SET NX PX`), and joins each match through `SuperTabStore.autoJoinSwarm`, one transaction per Swarm,+as the person.++**Tech Stack:** Fastify + Prisma (MongoDB) + Redis (ioredis) backend, vitest integration suite on mongodb-memory-server;+Flutter Desktop with widget tests.++**Spec:** `docs/specs/2026-11-03-swarm-domain-auto-join.md`++## Global Constraints++- Error codes: `PUBLIC_DOMAIN` (400) on save at a public domain; `DOMAIN_NOT_YOURS` (400) only when `autoJoin: true`+ names a domain other than the saving owner's `emailDomain(AuthUser.email)`; a link/domain join at a public domain+ answers `JOIN_UNAVAILABLE` (404) as any unavailable join does.+- `autoJoin` absent in a save keeps the saved value (same domain); `false` turns it off; any mode other than `domain`+ clears it.+- Try each person at most every **2 minutes** (`AUTO_JOIN_EVERY_MS = 120_000`), key written before trying; Redis down+ means try. **Limit 10** Swarms per try. **Cap 200** people per Swarm.+- Auto-join gives Workspace role **guest** (an active Workspace member keeps theirs) and the Swarm role the owner picked;+ marks `joinedVia: 'domain'` on the person. A team session never joins.+- Desktop copy, verbatim (owner `[email protected]`): option **"Everyone at @acme.com"**, **"Other domain…"**, toggle+ **"Add them automatically"** with **"Anyone who signs in with an @acme.com email joins this Swarm. You can remove+ anyone."**; **"Automatic joins work only for @acme.com, your own domain. People at partner.com join with the link."**;+ **"Not available for @gmail.com: anyone can make an address there. Invite people or share a link."**;+ **"Joined with @acme.com"**; **"Sharing with @gmail.com was turned off: anyone can make an address there."**;+ **"Automatic joins stopped: this Swarm has 200 people."**; leave dialog **"You won't be added back automatically. Ask+ the owner to invite you if you want to return."**+- No feature switch. Swarm code stays out of `cli/src/core`. Desktop tests never sign the real CLI out (memory store,+ fake sign-in).++## API contract (backend ↔ Desktop)++- `GET/POST /api/super-tabs/:tabId/sharing` answer+ `{ revision, access, joinUrl, ownDomain: string|null, ownDomainPublic: boolean, autoJoinFull: boolean, turnedOffDomain?: string }`.+ `access` for `domain` is `{ mode: 'domain', role, domain, autoJoin: boolean }`. A saved share at a public domain+ answers `access: { mode: 'invited', role }` with `turnedOffDomain: '<domain>'`.+- The save body's `access` for `domain` takes optional `autoJoin: boolean`.+- Swarm read: the head part's data carries `autoJoin: true` while auto-join is on (any member reads it); each member part+ may carry `joinedVia: 'domain'`.++## Review Focus++1. An old Desktop saves `domain` sharing for a *different* domain with no `autoJoin` field → auto-join turns off (the+ saved value is kept only for the same domain), never `DOMAIN_NOT_YOURS`. Test in Task 2.+2. The owner's email moved to another domain and they save with the field absent → kept value is dropped (auto-join only+ at the saver's own domain), no refusal. Test in Task 2.+3. A deleted Swarm with auto-join on → nobody joins (`autoJoinDomain` cleared on deletion). Test in Task 3.+4. A person auto-joined, then removed from the Workspace (the Workspace removal leaves each Swarm via `member.remove`)+ → declined, never rejoined. Test in Task 4.+5. Two list reads of the same person race on one Swarm → one membership, no error to either read. Test in Task 3.++---++### Task 1: Spec and plan (this commit)++- [x] Commit `docs/specs/2026-11-03-swarm-domain-auto-join.md` (with the "What exists today" fix) and this plan.++### Task 2: Domain checks and the `autoJoin` setting on save and join++**Files:**+- Modify: `backend/src/superTabs/sharing.ts` (schema, `configureSharing`, `sharingDetails`, `authorizeSwarmJoin`)+- Modify: `backend/src/superTabs/store.ts` (`sharing`, `saveSharing`: pass the user)+- Modify: `backend/src/lib/publicEmailDomains.ts` (add VN/Asian free providers)+- Test: `backend/integration/superTabAutoJoin.test.ts` (new), `backend/src/lib/publicEmailDomains.test.ts` if present++**Interfaces:**+- Produces: `generalAccessSchema` `domain` gains `autoJoin: z.boolean().optional()`;+ `configureSharing(previous, access, rotateLink, ownerEmail: string): SwarmSharing` (stored `access.autoJoin` only when+ true); `sharingDetails(state, ownerEmail: string)` returns the contract shape above;+ `autoJoinOn(state): string | null` (the domain while `mode==='domain' && autoJoin && !isPublicEmailDomain(domain)`).++- [ ] **Step 1: Write the failing tests** in `superTabAutoJoin.test.ts` (fixture as `superTabSharing.test.ts`; accounts at+ `acme.com`, `partner.com`, `gmail.com`):+ - `refuses a public domain on save`: gmail owner saves `{mode:'domain',domain:'gmail.com'}` → 400 `PUBLIC_DOMAIN`;+ acme owner saving `domain: 'outlook.com'` → `PUBLIC_DOMAIN`.+ - `refuses auto-join at another domain`: acme owner `{domain:'partner.com', autoJoin:true}` → 400 `DOMAIN_NOT_YOURS`;+ `{domain:'partner.com'}` → 200, `access.autoJoin === false`, and a `partner.com` person's `POST join` → 200.+ - `keeps, turns off and clears autoJoin`: save `{domain:'acme.com', autoJoin:true}`; save `{domain:'acme.com',+ role:'viewer'}` → `autoJoin` still true; save `autoJoin:false` → false; on again, then `{mode:'link'}` → details+ have no `autoJoin`, row `autoJoinDomain === null`; back to `domain` with no field → false. Review Focus 1 and 2.+ - `turns off an old public-domain share`: write `state.sharing.access = {mode:'domain',domain:'gmail.com'}` directly+ (saveState) → a gmail person's `POST join` → 404 `JOIN_UNAVAILABLE`; owner's `GET sharing` →+ `access.mode === 'invited'`, `turnedOffDomain === 'gmail.com'`.+ - `tells the dialog the owner's domain`: acme owner `ownDomain 'acme.com', ownDomainPublic false`; gmail owner+ `ownDomainPublic true`.+- [ ] **Step 2:** Run `cd backend && NODE_ENV=test HARNESS_CREDENTIAL_ENCRYPTION_KEY=<package.json key> npx vitest run -c vitest.super-tabs.config.ts integration/superTabAutoJoin.test.ts` → FAIL (no codes, no fields).+- [ ] **Step 3:** Implement. Save: `PUBLIC_DOMAIN` before `DOMAIN_NOT_YOURS`; kept value = previous `autoJoin` when+ previous was `domain` at the same domain and that domain is the saver's own. Join: `authorizeSwarmJoin` refuses a+ public `access.domain`. Public list adds: free consumer providers common in Vietnam and Asia+ (Zing, VNN, FPT mail, Rediff and others; the exact list is in the commit).+- [ ] **Step 4:** Re-run → PASS; run `integration/superTabSharing.test.ts` → still PASS.+- [ ] **Step 5:** Commit test, then code.++### Task 3: Row fields, index and the pull join on list reads++**Files:**+- Modify: `backend/prisma/schema.prisma` (`SuperTab.autoJoinDomain String?`, `autoJoinDeclined String[]`,+ `@@index([autonomousEnv, autoJoinDomain])`)+- Modify: `backend/src/superTabs/parts/commit.ts` (`indexesOf`), `backend/src/superTabs/parts/indexed.ts`+ (`NAMED_INDEX.SuperTab.autoJoin`), `backend/src/superTabs/model.ts` (`Person.joinedVia?: 'domain'`,+ `SuperTabState.autoJoinDeclined?: string[]`, stripped in `visibleState`)+- Create: `backend/src/superTabs/autoJoin.ts`+- Modify: `backend/src/superTabs/store.ts` (`autoJoinSwarm`, `workspaceList`, hook `autoJoins`),+ `backend/src/superTabs/read/service.ts` (`list`), `backend/src/routes/superTabs.ts` (Redis memory wiring)+- Test: `backend/integration/superTabAutoJoin.test.ts`, `backend/src/superTabs/autoJoin.test.ts`++**Interfaces:**+- Produces (autoJoin.ts): `AUTO_JOIN_EVERY_MS = 120_000`, `AUTO_JOIN_LIMIT = 10`, `AUTO_JOIN_CAP = 200`;+ `interface AutoJoinMemory { claim(key: string): Promise<boolean> }`; `redisAutoJoinMemory(redis)` (`SET+ swarm:auto-join:<env>:<sub> 1 PX 120000 NX`); `localAutoJoinMemory(now)`;+ `autoJoin(store: SuperTabStore, user: AuthUser): Promise<string[]>` (joined tab ids; never throws).+- Produces (store.ts): `autoJoinSwarm(user, tabId): Promise<'joined' | 'skipped' | 'declined'>` — in one transaction:+ sharing still on at the person's domain, person not declined and not a member, `people.length < 200`; Workspace guest+ (an active member keeps theirs; `WORKSPACE_ACCESS_REVOKED` → `'declined'` written in its own transaction); person+ pushed with the sharing role, `joinedVia: 'domain'`, a fresh generation; touches the head. Logs+ `[super-tab] auto-join` with `tabId`, `userId`, `people`.+- `indexesOf(state)` adds `autoJoinDomain: deletion ? null : autoJoinOn(state)`,+ `autoJoinDeclined: state.autoJoinDeclined ?? []`.++- [ ] **Step 1: Write the failing tests:**+ - `joins [email protected] to auto-join Swarms on /list`: three acme Swarms (auto-join on as viewer; domain without+ auto-join; invite-only) → `GET /list` as `[email protected]` lists only the first; its member part has `role 'viewer'`,+ `joinedVia 'domain'`; `swarmWorkspaceMember` role `guest`.+ - `joins nobody at a public domain`: `[email protected]`, `[email protected]` → nothing joined, no Swarm read.+ - `joins through /workspaces too`.+ - `keeps an existing Workspace member's role`: person already `member` of the owner's Workspace → joined, still+ `member`.+ - `ten per try`: 11 Swarms waiting → first read joins 10; within 2 minutes no try; after the clock passes 2 minutes+ the 11th joins.+ - `team session never joins`: list as `harnessSessionKind: 'team'` → 403 and no membership.+ - `turning auto-join off racing a join`: run `saveSharing(autoJoin:false)` and `autoJoinSwarm` concurrently N times →+ whenever the save committed first, no membership; never a member after a later off with joinedAt after it.+ - `stops at 200 people`: Swarm with 200 people → skipped; `sharing` answers `autoJoinFull: true`.+ - `deleted Swarm joins nobody` (Review Focus 3); `two racing reads, one membership` (Review Focus 5).+ - Unit (`autoJoin.test.ts`): memory `claim` false → no query; memory throws → tries; one Swarm's join throws → the+ others still join and `autoJoin` resolves.+- [ ] **Step 2:** Run → FAIL.+- [ ] **Step 3:** Implement as the Interfaces say. The pull: `readBy(db, 'SuperTab', 'autoJoin', [{ $match: {+ autonomousEnv, autoJoinDomain: domain, deletedAt: null, memberIds: { $ne: sub }, autoJoinDeclined: { $ne: sub } } },+ { $limit: 10 }, { $project: { _id: 1 } }])` — a raw pipeline, so no Prisma `has`/`in` filter and no new+ `hotFilters.allowed.json` entry (that list may only shrink). `SwarmReads.list` calls it only without `after`, after+ its team-session refusal.+- [ ] **Step 4:** Re-run → PASS; `npm test -- src/superTabs/hotFilters.test.ts src/superTabs/parts` → PASS.+- [ ] **Step 5:** Commit test, then code.++### Task 4: Leaving is final; re-invite and link join clear it++**Files:**+- Modify: `backend/src/superTabs/commands.ts` (`member.remove`, `invite.accept`), `backend/src/superTabs/store.ts`+ (`join` clears the decline)+- Test: `backend/integration/superTabAutoJoin.test.ts`++- [ ] **Step 1: Write the failing tests:** leave, advance 2 min, read → not rejoined, row `autoJoinDeclined` holds them;+ removed by the owner → same; invited again and accepted → `autoJoinDeclined` no longer holds them; link join after+ leaving → cleared; removed from the Workspace (`WORKSPACE_ACCESS_REVOKED`) → not joined, declined, next read after+ 2 min queries nothing for that Swarm; auto-joined then Workspace-removed → declined (Review Focus 4); declines kept+ across auto-join off and on.+- [ ] **Step 2:** Run → FAIL.+- [ ] **Step 3:** `member.remove` adds `member.id` to `state.autoJoinDeclined` (set, kept sorted for stable writes);+ `invite.accept` and a `join` remove the person.+- [ ] **Step 4:** Re-run → PASS.+- [ ] **Step 5:** Commit test, then code.++### Task 5: Readers see `autoJoin` and `joinedVia`; pre-merge prod query++**Files:**+- Modify: `backend/src/superTabs/read/views.ts`, `backend/src/superTabs/read/contract.ts` (`HeadView.autoJoin?: true`)+- Create: `backend/scripts/publicDomainShares.ts` (read-only: count and ids of Swarms whose saved `domain` share is at+ a public domain; the PM runs it with the read-only login)+- Test: `backend/integration/superTabAutoJoin.test.ts`++- [ ] **Step 1: Failing test:** a member's first-load read has head `autoJoin: true` while on, absent when off; the+ joined person's member part has `joinedVia: 'domain'`; the head never carries `autoJoinDeclined` or `sharing`.+- [ ] **Step 2–5:** run → FAIL, implement, PASS, commit. Then the full Super Tab integration suite+ (`npm run test:super-tabs`) and `npm test`, `npm run typecheck`.++### Task 6: Desktop Share dialog and leave dialogs (parallel subagent)++**Files:**+- Modify: `desktop/lib/super_tabs/sharing.dart`, `desktop/lib/super_tabs/manage_page.dart` (leave dialog line), the+ Desktop model if members/head need the two fields+- Test: `desktop/test/super_tab_sharing_auto_join_test.dart` (new) and existing sharing tests++**Interfaces:** consumes the API contract above.++- [ ] **Step 1: Failing widget tests:** owner `[email protected]` sees "Everyone at @acme.com" with "Add them automatically"+ and its help line; saving sends `{mode:'domain',domain:'acme.com',autoJoin:true}`; "Other domain…" shows the typed+ field and disables the toggle with the partner copy; `ownDomainPublic` owner sees the option disabled with the gmail+ copy; `turnedOffDomain` shows "Invited people" and the turned-off note; `autoJoinFull` shows the 200 copy; a member+ with `joinedVia: 'domain'` shows "Joined with @acme.com"; both leave dialogs add the line when the head has+ `autoJoin: true`, and not otherwise.+- [ ] **Step 2:** `flutter test <file>` → FAIL.+- [ ] **Step 3:** Implement with the existing `AppSelectField`/dialog widgets (Harness design language, no new styles).+- [ ] **Step 4:** PASS; run the Desktop sharing/manage tests, `check-ui-style`, `laid_out_list_test`, `flutter analyze`.+- [ ] **Step 5:** Commit test, then code; golden-free screenshots of the dialog states for the PR.diff --git a/docs/specs/2026-11-03-swarm-domain-auto-join.md b/docs/specs/2026-11-03-swarm-domain-auto-join.mdnew file mode 100644index 000000000..34cd4d8aa--- /dev/null+++ b/docs/specs/2026-11-03-swarm-domain-auto-join.md@@ -0,0 +1,243 @@+# People at the owner's email domain join a Swarm by themselves++Status: spec for Ken's confirmation · 2026-11-03 · requested by Ken.+Builds on Swarm sharing (`backend/src/superTabs/sharing.ts`, `desktop/lib/super_tabs/sharing.dart`) and Workspaces+(`docs/plans/2026-10-27-swarm-workspaces.md`).++## Why++Ken: someone who signs in with their company email should land in the company's Swarms without an invitation, the way+Slack lets "anyone with an @acme.com email" into a workspace. Slack still asks for one click ("Workspaces you can+join"); Ken wants no click at all.++Ken's decisions (2026-11-03):++- **Per Swarm, owner's choice.** A person joins only the Swarms whose owner turned it on, not every Swarm of the company.+- **No click.** The Swarm is simply in their sidebar the next time their app reads its list.+- **The account's email is the only trust signal**, for Google, Apple and emailed-code sign-in alike, as the SSO gives+ it. No Google-only limit and no DNS proof of the domain: people must be able to use it (Ken, after River's review:+ "lam phai user xai dc"). The SSO profile carries no verified flag; asking the SSO owner to confirm every path checks+ the mailbox is a follow-up, not a blocker.+- **Workspace role: Guest** (River's review, 2026-11-03). Most Swarms live in their owner's personal Workspace; Member+ would also open the owner's other Workspace-open Swarms, the Workspace people list and Swarm creation there. Inside+ the Swarm a guest works as any member with the Swarm role the owner picked. A Workspace-level switch later can give+ Member.++Done when: a person who signs in as `[email protected]` finds every acme Swarm with auto-join on in their list, with no+invitation, link or click; nobody at a public email domain is ever let in by domain; a person who left is not pulled+back; old apps see the joined Swarm; two independent security reviews passed; merged.++## Goals, non-goals, anti-goals++- **Goal:** zero-step join for colleagues, turned on per Swarm by its owner in the Share dialog that exists today.+- **Non-goal:** one switch for a whole company or Workspace (no client has Workspace screens yet). The pull join, the+ domain rules and the declines below are what a Workspace-level switch would reuse later.+- **Non-goal:** removing people whose company account was closed. The backend is not told (see Known limits).+- **Anti-goal:** a stranger gets in because a domain looked like a company's. That is a failure even if everything else+ works.+- **Anti-goal:** someone who left keeps reappearing in the Swarm.++## What exists today (main 8c3469058)++- **Swarm sharing** (`sharing.ts`): General access is `invited`, `domain` (`{ role, domain }`) or `link`. With `domain`,+ anyone signed in at that domain **who has the link** `harness://swarm/join/<id>` joins with `POST+ /api/super-tabs/:tabId/join` (`store.join`). That join adds them to the Swarm's Workspace as **guest**+ (`store.ts:1135`), refuses someone the Workspace removed (`WORKSPACE_ACCESS_REVOKED`), and keeps an existing member's+ role.+- The sharing setting lives in the head part's JSON (`state.sharing`). It cannot be queried by domain.+- Nothing checks the domain. The owner types it (`sharing.dart`, prefilled from their own email). `gmail.com` or another+ company's domain is accepted. Machine sharing already refuses both (`routes/machineShares.ts:132`,+ `isPublicEmailDomain`).+- **Sign-in** goes through Autonomous SSO (`lib/sso.ts`) with Google, Apple or an emailed code. The backend gets the SSO+ profile's email (`AuthUser.email`), with no verified flag (see Known limits). It gets no Google `hd` claim and does not know which method was used.+- **Public domains**: `lib/publicEmailDomains.ts`, a hand-kept list, already holding Apple's private relay+ (`privaterelay.appleid.com`) and `pending.harness.invalid`.+- **Lists** a client reads: `GET /api/super-tabs/list` (`SwarmReads.list` in `read/service.ts`, polled every few+ seconds; Swarms whose `SuperTab.memberIds` hold the person) and `GET /api/super-tabs/workspaces` (`listWorkspaces`).+ Desktop, phone and CLI read the first.+- **Leaving / removal**: the `member.remove` command, of oneself or by the owner (`commands.ts:2710`).++## Trust++| Sign-in | Email the backend sees | Joins by domain |+|---|---|---|+| Google, company account at acme.com | `[email protected]` | yes |+| Google, personal Gmail | `[email protected]` | no: public domain |+| Apple, real email shared | `[email protected]` | yes |+| Apple, Hide My Email | `…@privaterelay.appleid.com` | no: public domain. Needs an invitation |+| Emailed code | `[email protected]` | yes |++A verified email proves the person reads that mailbox, not that the domain is a company's. The remaining risk is a free+mail provider missing from the public list. It is held by:++1. **Auto-join only at the owner's own domain.** The server takes it from the saving owner's `AuthUser.email`; turning+ auto-join on for any other domain is refused (`DOMAIN_NOT_YOURS`, 400). A `domain` share without auto-join (link+ needed) keeps any non-public domain, so sharing with a partner's domain keeps working as today.+2. **Never a public domain** (`PUBLIC_DOMAIN`, 400), checked on save and again on every join (`authorizeSwarmJoin`), so a+ domain added to the list later stops working at once.+3. **The owner turns it on by hand**, with plain words (Copy).+4. **The owner sees who came by domain** and can remove them; a removed person does not come back by domain.+5. **The public list grows** in the same PR by the free providers common in Vietnam and Asia (for example Zing, VNN,+ FPT mail, Rediff). The builder picks the exact list.++## The model++### Setting++- `GeneralAccess` `domain` gains `autoJoin?: boolean` (`sharing.ts`). Saved with the existing `POST+ /api/super-tabs/:tabId/sharing`, owner only, as today.+- Absent in a save means **keep the saved value**; only `false` turns it off. An older Desktop that saves sharing+ without the field therefore never turns it off by accident. Any mode other than `domain` clears it.+- Turning it off stops new joins. People who already joined stay.+- `sharingDetails` returns `autoJoin` so the dialog shows it.++### Index on the Swarm row++Two new fields on `SuperTab`, written in the same transaction as the sharing save (and kept by `commitParts` like+`memberIds`):++- `autoJoinDomain String?`: the domain while `mode === 'domain' && autoJoin`, otherwise absent.+- `autoJoinDeclined String[]`: user ids who must not be joined again (below).+- Index `[autonomousEnv, autoJoinDomain]`, registered in `hotFilters.allowed.json`.++The builder may instead keep these in a separate collection if the row layout argues for it; the query shape must stay+a single indexed read.++### When the join happens: on the person's own list read++`autoJoin(user)` (new, `superTabs/autoJoin.ts`) runs at the start of the list read clients poll every few seconds,+`SwarmReads.list` (`superTabs/read/service.ts`, first page only, no `after`), and of `workspaceList`, before the list is+built. Because that read is a poll, a person is tried at most once every **2 minutes** (a per-user Redis key with that+TTL, written before trying; Redis down means try, as other poll memories do). A join can therefore take up to 2 minutes+after the owner turns it on (my call).++1. `domain = emailDomain(user.email)`. Stop when it is none or public, or the session is a team session.+2. One indexed read: `SuperTab` where `autonomousEnv`, `autoJoinDomain = domain`, not deleted, `memberIds` does not hold+ `user.sub`, `autoJoinDeclined` does not hold `user.sub`; limit 10. More are joined on later reads.+3. For each, the existing join path with `{ operationId: stableId('auto-join', tabId, user.sub) }`. In that path, for an+ auto-join:+ - The Workspace role given is **guest**, as a link join gives. Someone already active in the Workspace keeps the role+ they have.+ - Someone the Workspace removed (`WORKSPACE_ACCESS_REVOKED`) is added to `autoJoinDeclined` instead, in its own small+ write, so the read stops finding the Swarm.+ - The Swarm role is the sharing role the owner picked (Can collaborate / Can view). An existing member keeps theirs.+ - The new person is marked `joinedVia: 'domain'` in `state.people`.+4. Each join is its own transaction. A failure is logged with `tabId` and `userId` and skipped; the list is answered+ anyway, including the Swarms that did join, and the rest are tried after the 2-minute key expires.+5. **Cap: 200 people per Swarm** (my call), the most a private project can name (`project.sharing` `memberIds` max 200).+ A Swarm at 200 is skipped by auto-join; invitations and links still work. The Share dialog shows+ **"Automatic joins stopped: this Swarm has 200 people."**++The person is joined as themselves (their own `AuthUser`), never by the owner or a machine.++### Leaving is final for auto-join++- `member.remove` (leaving, or removed by the owner) adds the person's id to `autoJoinDeclined` of that Swarm.+- An invitation accepted (`invite.accept`) or a link join removes it, so the person can come back on purpose.+- The list is kept across turning auto-join off and on; it goes with the Swarm.++### Old Swarm settings that break the new rules++A saved `domain` share at a public domain stops answering joins from this release. A share at a partner's domain is+unchanged. Before merging, a read-only prod query lists them (count and Swarm ids, in the PR); their owners are told. The+Share dialog shows such a Swarm as "Invited people" with a one-line note (Copy).++## Copy and screens (Desktop Share dialog, `desktop/lib/super_tabs/sharing.dart`)++Owner `[email protected]`:++```+General access+[ Everyone at @acme.com ▾ ] ← was "Anyone at a domain" + a typed domain+[ Can collaborate ▾ ]++[■] Add them automatically+ Anyone who signs in with an @acme.com email joins+ this Swarm. You can remove anyone.+Private projects stay private.+```++- The option names the owner's domain by default. **Other domain…** keeps today's typed field for a partner; with a+ typed domain the auto-join toggle is disabled with **"Automatic joins work only for @acme.com, your own domain.+ People at partner.com join with the link."**+- Owner at a public domain: the option is shown disabled, with+ **"Not available for @gmail.com: anyone can make an address there. Invite people or share a link."**+- People list: under each person who came by domain, a quiet **"Joined with @acme.com"**.+- Old setting that broke the rules: **"Sharing with @gmail.com was turned off: anyone can make an address there."**+- Leave dialog, in a Swarm with auto-join on (the member read carries `autoJoin: true` for this): add+ **"You won't be added back automatically. Ask the owner to invite you if you want to return."**+- The person who joins sees no notice: the Swarm is in their sidebar.++Phone: nothing to build; the joined Swarm appears in Swarm Home through its list read. CLI: nothing to build; `harness+super-tab` list reads trigger the join too. Web: no Share dialog today; nothing to build.++## Design (docs/feature-design-rules.md)++1. **Growth.** `autoJoinDomain` is one field per Swarm, cleared with the setting. `autoJoinDeclined` grows by one id per+ person who left or was removed, shrinks on a re-invite, and goes with the Swarm's purge. A Swarm with 1,000 leaves+ holds about 25 KB on its row; review if a row passes 1,000 entries.+2. **Concurrency.** Each join is today's join transaction on the Swarm head, so a join racing a sharing change or a+ removal conflicts and retries, as today. Two list reads of the same person racing use the same stable operation id;+ the second finds the member and writes nothing. A decline write and a join of the same person race on the same row:+ the join reads `autoJoinDeclined` inside its transaction and stops if it is there.+3. **Read cost.** Per first-page list poll: one Redis get. At most every 2 minutes per person: one indexed read that+ usually matches nothing (no `$or`, no scan). Public domains skip both. Writes happen only when there is someone to+ join.+4. **Scale.** Today: about 6 people per Swarm. At 10x, 60. A company Swarm with auto-join could reach every employee:+ the metric that warns first is people per Swarm (every read and fan-out of that Swarm grows with it). Log it on each+ auto-join; review when one Swarm passes 100.+5. **Compatibility.** Joins happen on the server in reads every app already makes, so old Desktop, phone and CLI see the+ Swarm. An old Desktop cannot turn auto-join on and, by the "absent keeps" rule, cannot turn it off by saving. An old+ Desktop that types a public domain, or turns nothing on, gets the server's refusal message, which it already shows.+6. **Migration and rollback.** No data migration: new fields default to absent. Rollback to an older backend ignores the+ fields; joined people stay ordinary members; domain shares at a public domain start answering again (the+ pre-merge list says which).+7. **Audience.** Server-enforced: the domain comes from the owner's token, the join from the joiner's token; the public+ list is checked on save and on join; reading a Swarm still needs its membership; private projects stay private.+8. **Identity.** Every join acts as the joining person. Nothing acts as the owner.+9. **Failure.** A join that fails is logged with ids and tried again on the next read, while the list is still answered.+ Refused saves say why (`PUBLIC_DOMAIN`, `DOMAIN_NOT_YOURS`). A share turned off by the new rules says so in the dialog.+10. **Platforms.** Backend does the work; Desktop changes the Share dialog and the leave dialog; phone, CLI and web need+ nothing.++## Known limits++- A person who leaves the company stays in the Swarm until the owner removes them: the SSO does not say when a company+ account is closed. They can no longer sign in once their company deletes the account.+- A person whose email changes to another domain keeps what they joined, and joins the new domain's Swarms only once+ their token carries the new email.+- The owner's own domain is read at save time. If the owner's email later changes domain, the saved domain stays until+ the owner saves sharing again.++- An account whose SSO email was never checked against its mailbox could claim a company address and be joined. The+ owner sees "Joined with @acme.com" and removes them; the SSO owner is asked to confirm every sign-in path verifies+ the email (follow-up).++## Release gates (River's review)++- **Two independent security reviews**, since this changes who can reach a Swarm.+- **Ken's go before the backend release**: the release builds the new `[autonomousEnv, autoJoinDomain]` index on the+ production `SuperTab` collection.++## Build order (reviewable PRs)++1. Backend: the domain checks on save and join, `autoJoin` in sharing, the row fields and index, `autoJoin(user)` on+ both list reads, Workspace guest role for auto-joins, `joinedVia`, declines on `member.remove` and their removal on+ re-invite or link join, public list additions, the pre-merge prod query. Integration tests below.+2. Desktop: Share dialog option and toggle, disabled state, "Joined with" label, leave dialog line.++## Tests that fail first++- `[email protected]` reads `/list` → is a member of the acme Swarm with auto-join on (Workspace **guest**, Swarm role the owner+ picked, `joinedVia: 'domain'`); not of an acme Swarm with `domain` sharing but auto-join off; not of an invite-only one.+- `[email protected]`, `…@privaterelay.appleid.com`: nothing joined. A gmail owner saving `domain` → `PUBLIC_DOMAIN`; an acme+ owner turning auto-join on for `partner.com` → `DOMAIN_NOT_YOURS`; saving `partner.com` without auto-join → accepted, link join works.+- A saved share at `gmail.com` (written directly) → link join answers `JOIN_UNAVAILABLE`.+- Leave, read again → not rejoined. Removed by the owner, read again → not rejoined. Invited again and accepted →+ `autoJoinDeclined` no longer holds them.+- Removed from the Workspace → not joined, added to `autoJoinDeclined`, next read does not try again.+- Someone already a Workspace member → joined to the Swarm, stays member.+- Saving sharing without `autoJoin` keeps it on; `false` turns it off; mode `link` clears it and `autoJoinDomain`.+- Turning auto-join off racing a join → no membership written after the turn-off commits.+- 11 Swarms waiting → 10 joined on the first read, the 11th on the next.+- Team session list read → no join.