Skip to content

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.

Merge batch 11-05 i1540: #3100 (#3127)

0xken15c18e7ebb60d3
diff --git a/backend/integration/superTabComputerMoves.test.ts b/backend/integration/superTabComputerMoves.test.ts
new file mode 100644
index 000000000..6985aadef
--- /dev/null
+++ b/backend/integration/superTabComputerMoves.test.ts
@@ -0,0 +1,220 @@
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import type { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { cleanUpComputers, otherAccountsOnComputer, teamCleanupPending } from '../src/superTabs/computerMoves.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { localReportMemory } from '../src/superTabs/machineReports.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { planDatabase, plan, profiled, reads } from './plans.test-support.js'
+
+// One computer, signed in as kelvin, then as ttkhoahcmus (Scholes, #3122): each account has its own machine row for it, joined
+// only by the computer's id. A fresh loopback replica set, created here.
+const COMPUTER = 'c'.repeat(32), OTHER = 'd'.repeat(32)
+const kelvin = '500000000000000000000001', tt = '500000000000000000000002', other = '500000000000000000000003'
+const user = (sub: string, email: string): AuthUser => ({ sub, email, autonomousEnv: 'prod', role: 'user' })
+const owner = user('500000000000000000000009', '[email protected]'), kelvinUser = user(kelvin, '[email protected]'), ttUser = user(tt, '[email protected]')
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+/** Each machine's key in its account's device key log (lib/deviceKeyLog.ts): one key per computer, whatever account it signs
+ * in to, so a computer's machines of two accounts hold the same one (e2ee/store.ts identity.json). */
+const keys: Array<{ userId: string; machineId: string; pub: string }> = [
+ { userId: kelvin, machineId: 'kelvin-mac', pub: 'pub-computer' }, { userId: tt, machineId: 'tt-mac', pub: 'pub-computer' },
+ { userId: kelvin, machineId: 'kelvin-old', pub: 'pub-duplicated' }, { userId: tt, machineId: 'tt-new', pub: 'pub-duplicated' },
+]
+
+beforeAll(async () => {
+ ({ replica, db } = await planDatabase('computer_moves'))
+ const machine = (machineId: string, userId: string, computerId: string, extra: Record<string, unknown> = {}) => db.machine.create({ data: {
+ machineId, userId, computerId, sessionKind: 'computer', apiKey: `fixture-${machineId}`, managerId: '', autonomousEnv: 'prod', authMode: 'remote', ...extra } })
+ await machine('kelvin-mac', kelvin, COMPUTER)
+ await machine('tt-mac', tt, COMPUTER)
+ // Not another account's sign-in on this computer: a Team row, a deleted row, another environment's, another computer's.
+ await machine('kelvin-team', kelvin, COMPUTER, { sessionKind: 'team', hostMachineId: 'kelvin-mac' })
+ await machine('other-deleted', other, COMPUTER, { deletedAt: new Date() })
+ await machine('other-stag', other, COMPUTER, { autonomousEnv: 'stag' })
+ await machine('other-elsewhere', other, OTHER)
+ // Many other computers' rows, which a read not bounded by the computer would examine too.
+ for (let i = 0; i < 40; i++) await machine(`filler-${i}`, other, i.toString(16).padStart(32, '0'))
+ for (const person of [owner, kelvinUser, ttUser]) {
+ await db.user.create({ data: { id: person.sub, externalId: `fixture-${person.sub}`, email: person.email, autonomousEnv: 'prod' } })
+ }
+ const memory = localReportMemory(Date.now)
+ store = new SuperTabStore(db, Date.now, null, { reports: { get: (t, m) => memory.get(t, m), set: (t, m, r) => memory.set(t, m, r), sweepDue: async () => false },
+ machineKeys: async userIds => new Map(userIds.map(id => [id, keys.filter(k => k.userId === id).map(k => ({ ...k, kind: 'machine' as const }))])) })
+}, 300_000)
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe("a computer's other accounts", () => {
+ it('are the live rows of other accounts signed in on it before, never the owner\'s own, a Team row, or another computer\'s', async () => {
+ expect(await otherAccountsOnComputer(db, { computerId: COMPUTER, ownerId: tt, autonomousEnv: 'prod' }))
+ .toEqual([{ machineId: 'kelvin-mac', userId: kelvin }])
+ expect(await otherAccountsOnComputer(db, { computerId: COMPUTER, ownerId: kelvin, autonomousEnv: 'prod' }))
+ .toEqual([{ machineId: 'tt-mac', userId: tt }])
+ })
+
+ it('are read from the index on the computer id', async () => {
+ const entries = await profiled(db, () => otherAccountsOnComputer(db, { computerId: COMPUTER, ownerId: tt, autonomousEnv: 'prod' }))
+ const rows = reads(entries, 'machines', ['computerId'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ computerId: 1, userId: 1 \}/)
+ // Only this computer's six rows, not the 41 others.
+ expect(rows[0]!.docsExamined, JSON.stringify(plan(rows))).toBeLessThanOrEqual(6)
+ })
+})
+
+describe('a computer signed in as another account', () => {
+ const run = (tab: string, command: Command, as: AuthUser = owner) => store.execute(as, tab, { operationId: randomUUID(), command })
+ /** A Swarm with kelvin and ttkhoahcmus in it, and kelvin's Mac added, which reports nothing since he signed out of it. */
+ async function swarm() {
+ const tab = (await store.create(owner, randomUUID(), 'Machines')).id
+ for (const person of [kelvinUser, ttUser]) {
+ const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
+ }
+ await run(tab, { type: 'machine.contribute', machineId: 'kelvin-mac', name: 'MacBooks-MacBook-Pro-7', cwd: '/work', scope: 'swarm', engines: ['claude'],
+ maxAgents: 2, teamAccountOnly: true }, kelvinUser)
+ return tab
+ }
+ const machinesIn = async (tab: string) => (await store.read(owner, tab)).state.machines!.map(m => ({ machineId: m.machineId, contributorId: m.contributorId,
+ previousOwner: m.previousOwner?.personId }))
+
+ it("moves its entry in every Swarm to the new account, once", async () => {
+ const tabs = [await swarm(), await swarm()]
+ expect(await store.computerSignedIn({ machineId: 'tt-mac', ownerId: tt, computerId: COMPUTER, autonomousEnv: 'prod' })).toEqual(
+ expect.arrayContaining(tabs.map(tabId => ({ tabId, from: 'kelvin-mac', fromOwner: kelvin, to: 'tt-mac', toOwner: tt }))))
+ for (const tab of tabs) expect(await machinesIn(tab)).toEqual([{ machineId: 'tt-mac', contributorId: tt, previousOwner: kelvin }])
+ expect(await store.computerSignedIn({ machineId: 'tt-mac', ownerId: tt, computerId: COMPUTER, autonomousEnv: 'prod' })).toEqual([])
+ for (const tab of tabs) expect(await machinesIn(tab)).toEqual([{ machineId: 'tt-mac', contributorId: tt, previousOwner: kelvin }])
+ })
+
+ it('moves nothing for a computer id the signed-in machine does not have', async () => {
+ const tab = await swarm()
+ expect(await store.computerSignedIn({ machineId: 'tt-mac', ownerId: tt, computerId: OTHER, autonomousEnv: 'prod' })).toEqual([])
+ expect(await store.computerSignedIn({ machineId: 'other-elsewhere', ownerId: other, computerId: COMPUTER, autonomousEnv: 'prod' })).toEqual([])
+ expect(await machinesIn(tab)).toEqual([{ machineId: 'kelvin-mac', contributorId: kelvin, previousOwner: undefined }])
+ })
+
+ // Security review 1 of #3100: the computer id is self-declared. Someone who learned it, signed in to their own account
+ // anywhere, must not take that computer's entry while it sleeps: only the computer's own key, which its sign-in to the new
+ // account registered in that account's log, proves it is the same computer.
+ it("moves nothing for an account that claims a computer's id without that computer's key", async () => {
+ const VICTIM = 'b'.repeat(32)
+ await db.machine.create({ data: { machineId: 'kelvin-victim', userId: kelvin, computerId: VICTIM, sessionKind: 'computer', apiKey: 'fixture-kelvin-victim',
+ managerId: '', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machine.create({ data: { machineId: 'forged-mac', userId: tt, computerId: VICTIM, sessionKind: 'computer', apiKey: 'fixture-forged-mac',
+ managerId: '', autonomousEnv: 'prod', authMode: 'remote' } })
+ keys.push({ userId: kelvin, machineId: 'kelvin-victim', pub: 'pub-victim' }, { userId: tt, machineId: 'forged-mac', pub: 'pub-forger' })
+ const tab = (await store.create(owner, randomUUID(), 'Forged')).id
+ for (const person of [kelvinUser, ttUser]) {
+ const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
+ }
+ await run(tab, { type: 'machine.contribute', machineId: 'kelvin-victim', name: 'Victim Mac', cwd: '/work', scope: 'swarm', engines: ['claude'],
+ maxAgents: 2, teamAccountOnly: true }, kelvinUser)
+ expect(await store.computerSignedIn({ machineId: 'forged-mac', ownerId: tt, computerId: VICTIM, autonomousEnv: 'prod' })).toEqual([])
+ // Nor with no key at all: a machine that never registered one proves nothing.
+ keys.splice(keys.findIndex(k => k.machineId === 'forged-mac'), 1)
+ expect(await store.computerSignedIn({ machineId: 'forged-mac', ownerId: tt, computerId: VICTIM, autonomousEnv: 'prod' })).toEqual([])
+ expect(await machinesIn(tab)).toEqual([{ machineId: 'kelvin-victim', contributorId: kelvin, previousOwner: undefined }])
+ })
+
+ it('cannot be asked for by a person', async () => {
+ const tab = await swarm()
+ await expect(run(tab, { type: 'machine.moved', machineId: 'kelvin-mac' }, kelvinUser)).rejects.toThrow()
+ await expect(run(tab, { type: 'machine.moved', machineId: 'kelvin-mac' }, ttUser)).rejects.toThrow()
+ expect(await machinesIn(tab)).toEqual([{ machineId: 'kelvin-mac', contributorId: kelvin, previousOwner: undefined }])
+ })
+})
+
+describe('the one-time cleanup of computers listed under two accounts', () => {
+ const run = (tab: string, command: Command, as: AuthUser = owner) => store.execute(as, tab, { operationId: randomUUID(), command })
+ const DUPLICATED = 'e'.repeat(32)
+ const machinesIn = async (tab: string) => (await store.read(owner, tab)).state.machines!.map(m => `${m.machineId}:${m.contributorId}`).sort()
+
+ it('leaves each computer listed once, under the account seen last, writes nothing on a dry run, and moves nothing the second time', async () => {
+ // The reported Mac: added by kelvin, then by ttkhoahcmus once they signed in on it, so both are listed (Scholes, 11-05).
+ const at = (minutes: number) => new Date(Date.now() - minutes * 60_000)
+ for (const [machineId, userId, seen] of [['kelvin-old', kelvin, at(50)], ['tt-new', tt, at(1)]] as const) {
+ await db.machine.create({ data: { machineId, userId, computerId: DUPLICATED, sessionKind: 'computer', apiKey: `fixture-${machineId}`, managerId: '',
+ autonomousEnv: 'prod', authMode: 'remote', lastSeenAt: seen } })
+ }
+ const tab = (await store.create(owner, randomUUID(), 'Duplicates')).id
+ for (const person of [kelvinUser, ttUser]) {
+ const invitation = await run(tab, { type: 'invite.create', email: person.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, person)
+ }
+ const add = (machineId: string, as: AuthUser) => run(tab, { type: 'machine.contribute', machineId, name: 'MacBooks-MacBook-Pro-7', cwd: '/work',
+ scope: 'swarm', engines: ['claude'], maxAgents: 2, teamAccountOnly: true }, as)
+ await add('kelvin-old', kelvinUser)
+ await add('tt-new', ttUser)
+
+ // Security review 2 of #3100: what Ken's go covers is exactly what the write changes. A computer shared by two accounts whose
+ // machine key does not match is found, and moved neither in the dry run nor in the write.
+ await db.machine.update({ where: { machineId: 'forged-mac' }, data: { lastSeenAt: new Date() } })
+ const moved = { tabId: tab, from: 'kelvin-old', fromOwner: kelvin, to: 'tt-new', toOwner: tt }
+ const dry = await cleanUpComputers(db, store, 'prod', { write: false })
+ expect(dry.computers).toContainEqual({ signedIn: { machineId: 'tt-new', ownerId: tt }, others: ['kelvin-old'] })
+ expect(dry.computers.some(c => c.signedIn.machineId === 'forged-mac')).toBe(true)
+ expect(dry.moves).toEqual([moved])
+ expect(await machinesIn(tab)).toEqual([`kelvin-old:${kelvin}`, `tt-new:${tt}`])
+
+ expect((await cleanUpComputers(db, store, 'prod', { write: true })).moves).toEqual([moved])
+ expect(await machinesIn(tab)).toEqual([`tt-new:${tt}`])
+ const again = await cleanUpComputers(db, store, 'prod', { write: true })
+ expect(again.moves).toEqual([])
+ expect(await machinesIn(tab)).toEqual([`tt-new:${tt}`])
+ })
+})
+
+describe("a Mac whose owner's Team account is about to join", () => {
+ const run = (tab: string, command: Command, as: AuthUser = owner) => store.execute(as, tab, { operationId: randomUUID(), command })
+ it('reads joining, not "not set up", until its Team account is listed, from an indexed read of the owners\' Team machines', async () => {
+ const tab = (await store.create(owner, randomUUID(), 'Joining')).id
+ const invitation = await run(tab, { type: 'invite.create', email: kelvinUser.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, kelvinUser)
+ await db.machine.create({ data: { machineId: 'kelvin-joining', userId: kelvin, computerId: 'f'.repeat(32), sessionKind: 'computer',
+ apiKey: 'fixture-kelvin-joining', managerId: '', autonomousEnv: 'prod', authMode: 'remote' } })
+ await db.machine.create({ data: { machineId: 'kelvin-joining-team', userId: kelvin, computerId: 'a'.repeat(31) + 'f', sessionKind: 'team',
+ hostMachineId: 'kelvin-joining', apiKey: 'fixture-kelvin-joining-team', managerId: '', autonomousEnv: 'prod', authMode: 'remote' } })
+ await run(tab, { type: 'machine.contribute', machineId: 'kelvin-joining', name: 'MacBooks-MacBook-Pro-7', cwd: '/work', scope: 'swarm',
+ engines: ['claude'], maxAgents: 2, teamAccountOnly: true }, kelvinUser)
+ await store.observeMachine(kelvinUser, tab, 'kelvin-joining', { generation: (await store.read(kelvinUser, tab)).state.machines![0]!.generation,
+ resources: { cpuPercent: 10, memoryTotalBytes: 32e9, memoryUsedBytes: 4e9, diskFreeBytes: 120e9, diskTotalBytes: 500e9, projectDiskFreeBytes: 120e9,
+ deviceType: 'Laptop', chip: 'Fixture', os: 'macOS', gpuPercent: null }, quotas: [], tools: {}, runningHarnessIds: [], stoppedHarnessIds: [] })
+ const teamWork = async () => ((await store.read(kelvinUser, tab)).state.machines!.find(m => m.machineId === 'kelvin-joining') as { teamWork?: { code?: string } })
+ .teamWork?.code
+ expect(await teamWork()).toBe('TEAM_ACCOUNT_JOINING')
+ const { state } = await store.readLoad(kelvinUser, tab)
+ const entries = await profiled(db, () => store.joiningTeams(db, state))
+ const rows = reads(entries, 'machines', ['hostMachineId'])
+ expect(rows, JSON.stringify(plan(rows))).toHaveLength(1)
+ expect(rows[0]!.planSummary, JSON.stringify(plan(rows))).toMatch(/IXSCAN \{ userId: 1/)
+ })
+})
+
+describe("a Harness Team account's previous account's Swarm cleanup", () => {
+ it('is pending while a Swarm lists its Team machine for cleanup, read from the computer and cleanup indexes', async () => {
+ const TEAM_COMPUTER = '9'.repeat(32)
+ await db.machine.create({ data: { machineId: 'kelvin-team-c', userId: kelvin, computerId: TEAM_COMPUTER, sessionKind: 'team', hostMachineId: 'kelvin-mac',
+ apiKey: 'fixture-kelvin-team-c', managerId: '', autonomousEnv: 'prod', authMode: 'remote' } })
+ const tab = (await store.create(owner, randomUUID(), 'Cleanup')).id
+ // What a commit writes for a Swarm whose machineCleanups name that machine (parts/commit.ts): the index the read uses.
+ await db.superTab.update({ where: { id: tab }, data: { cleanupMachineIds: ['kelvin-team-c'] } })
+ expect(await teamCleanupPending(db, { computerId: TEAM_COMPUTER, userId: tt })).toBe(true)
+ // Its own account signing in again (a plain repair) waits on nothing of its own.
+ expect(await teamCleanupPending(db, { computerId: TEAM_COMPUTER, userId: kelvin })).toBe(false)
+ const entries = await profiled(db, () => teamCleanupPending(db, { computerId: TEAM_COMPUTER, userId: tt }))
+ const machines = reads(entries, 'machines', ['computerId'])
+ expect(machines[0]!.planSummary, JSON.stringify(plan(machines))).toMatch(/IXSCAN \{ computerId: 1, userId: 1 \}/)
+ const swarms = reads(entries, 'SuperTab', ['cleanupMachineIds'])
+ expect(swarms[0]!.planSummary, JSON.stringify(plan(swarms))).toMatch(/IXSCAN \{ autonomousEnv: 1, cleanupMachineIds: 1/)
+ await db.superTab.update({ where: { id: tab }, data: { cleanupMachineIds: [] } })
+ expect(await teamCleanupPending(db, { computerId: TEAM_COMPUTER, userId: tt })).toBe(false)
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 5c36a4513..9a24bace8 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -295,6 +295,9 @@ model Machine {
@@index([userId])
@@index([userId, computerId])
+ /// A computer's rows of every account (superTabs/computerMoves.ts otherAccountsOnComputer): another account's sign-in there
+ /// moves the computer's Swarm entries to it (#3122).
+ @@index([computerId, userId])
@@index([managerId, billingStatus])
@@index([billingStatus, externalSubscriptionStatus, externalSubscriptionEndAt])
@@map("machines")
diff --git a/backend/scripts/swarm-computer-moves/run.ts b/backend/scripts/swarm-computer-moves/run.ts
new file mode 100644
index 000000000..d42f61ba8
--- /dev/null
+++ b/backend/scripts/swarm-computer-moves/run.ts
@@ -0,0 +1,28 @@
+// One row per computer (#3122): computers listed in Swarms under two accounts before a sign-in moved them. From this release a
+// sign-in moves the computer's entries by itself (superTabs/computerMoves.ts); this moves the ones listed twice already, once.
+// Dry run by default: it writes nothing and prints each computer shared by two accounts, and every move the write would make
+// (Swarm, old entry and owner, new entry and owner), decided exactly as the write decides. `--write` prints the moves it made:
+// what Ken's go covered, and what each old owner can add back with Add machine.
+// It reads every machine row that has a computer id, once, on the (computerId, userId) index: check that read's plan and the
+// collection's size on the read-only login (dry run) before the go.
+// Rows count as one computer by their computer id alone, which is self-declared: a pinned ADAPTER_COMPUTER_ID shared by
+// containers under different accounts reads as one computer here. The write moves an entry only where both accounts' logs
+// hold the same machine key for it (computerMoves.ts sameComputerKey), so those containers are listed and left alone.
+// cd backend && DATABASE_URL="$(read-only URL from its environment file)" npx tsx scripts/swarm-computer-moves/run.ts
+// `--write` is a production write: run it only in the backend release Ken says go for, with the release's own login.
+// cd backend && npx tsx scripts/swarm-computer-moves/run.ts --write
+// Safe to run twice: an entry moved is gone. It prints JSON only, machine and account ids, never an email or a name. What it
+// moved can be added back by its owner (Add machine).
+import { PrismaClient } from '@prisma/client'
+import { SuperTabStore } from '../../src/superTabs/store.js'
+import { cleanUpComputers } from '../../src/superTabs/computerMoves.js'
+
+const write = process.argv.includes('--write')
+const env = process.argv.find(arg => arg.startsWith('--env='))?.slice('--env='.length) ?? 'prod'
+const db = new PrismaClient()
+try {
+ const result = await cleanUpComputers(db, new SuperTabStore(db), env, { write })
+ console.log(JSON.stringify({ write, env, ...result }, null, 2))
+} finally {
+ await db.$disconnect()
+}
diff --git a/backend/src/lib/adapterWs.ts b/backend/src/lib/adapterWs.ts
index 94911f80f..201048254 100644
--- a/backend/src/lib/adapterWs.ts
+++ b/backend/src/lib/adapterWs.ts
@@ -71,6 +71,7 @@ import { ShortTurnGuard } from './shortTurnGuard.js'
import { markCpuKind } from './selfProfile.js'
import { createConnectionRoutes } from './terminalRoute.js'
import { recordRelay } from './relayStats.js'
+import { computerSignedIn } from '../superTabs/computerMoves.js'
const wss = createWss(WS_LIMITS.adapter, { echoFirstProtocol: true })
@@ -224,6 +225,12 @@ export function handleAdapterUpgrade(req: IncomingMessage, socket: Duplex, head:
if (!(await claimMachineOwner(machineId, computerId, PRESENCE_TTL_SEC))) { denyBusy(); return }
const row = machine
wss.handleUpgrade(req, socket, head, (ws) => void attachAdapter(ws, row, label, computerId, clientVersion, countryCode, user.harnessSessionId, team))
+ // A computer is signed in as one account at a time: Swarm entries of the account signed in here before move to this one
+ // (superTabs/computerMoves.ts, #3122). Never awaited: the connect does not wait on Swarms.
+ if (!team) {
+ void computerSignedIn({ machineId, ownerId: user.sub, computerId, autonomousEnv: user.autonomousEnv })
+ .catch(error => logger.warn('[swarm] computer move failed', { machineId, error: String(error) }))
+ }
})().catch((err) => {
if (err instanceof AppError) {
// 403 is the revoked-machine answer from `resolveOrCreateForComputer`, 429 its new-id rate limit
diff --git a/backend/src/lib/harnessSession.test.ts b/backend/src/lib/harnessSession.test.ts
index 8fc0b4b3c..fb479a1f9 100644
--- a/backend/src/lib/harnessSession.test.ts
+++ b/backend/src/lib/harnessSession.test.ts
@@ -70,8 +70,10 @@ const fakes = vi.hoisted(() => {
const transaction = vi.fn(async (body: (tx: unknown) => Promise<unknown>) => body({ harnessSession, machine }))
const publishDown = vi.fn(async () => 1)
const activeMachineKeys = vi.fn(async (_userId: string): Promise<Array<{ pub: string; machineId: string; kind: string }>> => [])
+ // Whether another account's Harness Team machine on the redeeming computer still has a Swarm cleanup (superTabs/computerMoves.ts).
+ const teamCleanupPending = vi.fn(async (_db: unknown, _of: { computerId: string; userId: string }) => false)
return {
- redis, ttls, sessions, users, machines, pub, harnessSession, machine, transaction, publishDown, activeMachineKeys,
+ redis, ttls, sessions, users, machines, pub, harnessSession, machine, transaction, publishDown, activeMachineKeys, teamCleanupPending,
setFailRedis: (v: boolean) => { failRedis = v },
get: vi.fn(async (id: string) => users.get(id) ?? null),
findByEmail: vi.fn(),
@@ -80,6 +82,7 @@ const fakes = vi.hoisted(() => {
vi.mock('./bus.js', () => ({ pub: fakes.pub, publishDown: fakes.publishDown }))
vi.mock('./deviceKeyLog.js', () => ({ activeMachineKeys: fakes.activeMachineKeys }))
+vi.mock('../superTabs/computerMoves.js', () => ({ teamCleanupPending: fakes.teamCleanupPending }))
vi.mock('./prisma.js', () => ({
prisma: { harnessSession: fakes.harnessSession, machine: fakes.machine, $transaction: fakes.transaction },
machineAlive: { OR: [{ deletedAt: null }, { deletedAt: { isSet: false } }] },
@@ -282,6 +285,16 @@ describe('scan to sign in — the routes', () => {
token === 'sso-token' ? signedIn : authenticateAccessToken(token, env, opts))
})
+ it("answers a team sign-in refused for another account's pending Swarm cleanup in words its person can act on", async () => {
+ fakes.teamCleanupPending.mockResolvedValueOnce(true)
+ const { code } = await startHandoff(USER.id, 'team')
+ const redeemed = await app.inject({ method: 'POST', url: '/api/auth/handoff/redeem',
+ payload: { code, label: 'Mac · Team', computerId: 'ab12cd34ef56ab12cd34ef56ab12cd34' } })
+ expect(redeemed.statusCode).toBe(409)
+ expect(redeemed.json().error).toMatchObject({ code: 'TEAM_CLEANUP_PENDING' })
+ expect(JSON.stringify(redeemed.json())).toContain('Try Repair again in a few minutes')
+ })
+
it('the computer mints a code, the phone redeems it, refreshes, and signs out', async () => {
const minted = await app.inject({ method: 'POST', url: '/api/auth/handoff', headers: { authorization: 'Bearer sso-token' } })
expect(minted.statusCode).toBe(200)
@@ -388,6 +401,19 @@ describe('team sessions — minting and redeeming', () => {
expect(fakes.sessions).toHaveLength(0)
})
+ // Security review 2 of #3100: after a computer moved to another account, Repair signs its Harness Team account in for the
+ // new one. The old account's Team machine still has its Swarm folders to delete, and only its own sign-in can: replaced
+ // first, that cleanup could never finish, and the old Swarms' checkouts would stay where the new account's work runs.
+ it("a team code is refused while another account's Team machine on that computer still has a Swarm cleanup to do", async () => {
+ fakes.teamCleanupPending.mockResolvedValueOnce(true)
+ const { code } = await startHandoff(USER.id, 'team')
+ await expect(redeemHandoff(code, 'x', COMPUTER)).rejects.toThrow('still being cleaned up')
+ expect(fakes.teamCleanupPending).toHaveBeenCalledWith(expect.anything(), { computerId: COMPUTER, userId: USER.id })
+ expect(fakes.sessions).toHaveLength(0)
+ const again = await startHandoff(USER.id, 'team')
+ expect(await redeemHandoff(again.code, 'x', COMPUTER)).not.toBeNull()
+ })
+
it('a team code never binds to a computer the account already runs with a normal sign-in', async () => {
fakes.machines.push({ userId: USER.id, computerId: COMPUTER, machineId: 'owner-mac', sessionKind: 'computer' })
fakes.machines.push({ userId: USER.id, computerId: OTHER_COMPUTER, machineId: 'legacy', sessionKind: null })
diff --git a/backend/src/lib/harnessSession.ts b/backend/src/lib/harnessSession.ts
index 632da0d0c..58ce7f706 100644
--- a/backend/src/lib/harnessSession.ts
+++ b/backend/src/lib/harnessSession.ts
@@ -1,4 +1,5 @@
import { randomInt } from 'node:crypto'
+import { teamCleanupPending } from '../superTabs/computerMoves.js'
import { pub, publishDown } from './bus.js'
import type { Prisma } from '@prisma/client'
import { machineAlive, prisma } from './prisma.js'
@@ -130,6 +131,15 @@ function handoffOf(held: unknown): { userId: string; kind: HandoffKind; convert?
} catch { return null }
}
+/** A team sign-in for another account while the previous account's Swarm work in that Harness Team account is still being
+ * deleted (superTabs/computerMoves.ts teamCleanupPending): what its person reads, and does. */
+export class TeamCleanupPending extends Error {
+ readonly code = 'TEAM_CLEANUP_PENDING'
+ constructor() {
+ super("The previous account's Swarm work in Harness Team on this computer is still being cleaned up, so it was not signed in for you yet. Try Repair again in a few minutes.")
+ }
+}
+
/**
* Spend [code] and sign [label]'s device in as the account that minted it, as the kind it was minted
* for. A team code also needs the redeeming daemon's [computerId], which its session is bound to. Null
@@ -151,6 +161,8 @@ export async function redeemHandoff(code: string, label: string, computerId?: st
// The computer that asked to become a team machine, and no other.
if (handoff.convert) return handoff.convert === computer ? convertComputer(handoff.userId, label || 'Team', computer) : null
if (await computerHeldByAnotherSignIn(handoff.userId, computer)) return null
+ // Another account's Team machine here still has Swarm folders to delete, which only its own sign-in can (#3122).
+ if (await teamCleanupPending(prisma, { computerId: computer, userId: handoff.userId })) throw new TeamCleanupPending()
// A repair run signs the same team account in again: its machine already exists and records its Mac now. A new one
// records it when it registers (MachineService.resolveForTeamComputer), from the session made here.
if (handoff.host) {
diff --git a/backend/src/lib/teamSessionSockets.test.ts b/backend/src/lib/teamSessionSockets.test.ts
index 68baba073..4dd500172 100644
--- a/backend/src/lib/teamSessionSockets.test.ts
+++ b/backend/src/lib/teamSessionSockets.test.ts
@@ -9,7 +9,7 @@ const m = vi.hoisted(() => ({
machineService: { resolveOrCreateForComputer: vi.fn(), resolveForTeamComputer: vi.fn() },
machineUpdate: vi.fn(), machineFindUnique: vi.fn(), userFindUnique: vi.fn(),
claim: vi.fn(), release: vi.fn(), publishUp: vi.fn(), publishPair: vi.fn(), terminalDown: vi.fn(),
- pushes: vi.fn(), appendKey: vi.fn(), nodeRole: vi.fn(), recordTurn: vi.fn(),
+ pushes: vi.fn(), appendKey: vi.fn(), nodeRole: vi.fn(), recordTurn: vi.fn(), computerSignedIn: vi.fn(),
}))
vi.mock('./ssoAuth.js', async original => ({ ...await original<typeof import('./ssoAuth.js')>(), authenticateAccessToken: m.auth }))
vi.mock('./wsServer.js', async original => ({ ...await original<typeof import('./wsServer.js')>(), createWss: () => ({ handleUpgrade: m.upgrade }) }))
@@ -23,6 +23,7 @@ vi.mock('./bus.js', () => ({
publishTerminalUp: vi.fn(), subscribeTerminalDown: m.terminalDown, setMachineAppState: vi.fn(), clearMachineAppState: vi.fn(),
}))
vi.mock('./adapterAccountPushes.js', () => ({ relayAccountPushes: m.pushes }))
+vi.mock('../superTabs/computerMoves.js', () => ({ computerSignedIn: m.computerSignedIn }))
vi.mock('./deviceKeyLog.js', () => ({ appendDeviceKey: m.appendKey, touchDeviceKey: vi.fn() }))
vi.mock('./nodeRole.js', () => ({ attachNodeRole: m.nodeRole, PRESENCE_TTL_SEC: 30 }))
// The real hub starts its heartbeat timers on import; these tests never attach a hub client, so it is a stub with none.
@@ -77,6 +78,7 @@ beforeEach(() => {
m.appendKey.mockResolvedValue({ ok: true, head: { seq: 1, hash: 'h' } })
m.nodeRole.mockResolvedValue({ touch: vi.fn(), detach: vi.fn(async () => {}) })
m.recordTurn.mockResolvedValue(undefined)
+ m.computerSignedIn.mockResolvedValue(undefined)
m.machineService.resolveForTeamComputer.mockResolvedValue({ machine: teamMac, created: false })
m.upgrade.mockReset()
m.machineService.resolveOrCreateForComputer.mockResolvedValue({ machine: ownerMac, created: false })
@@ -110,6 +112,16 @@ describe('the machine socket and a team session', () => {
expect(m.upgrade).toHaveBeenCalledTimes(1)
})
+ it("tells the Swarms of a normal sign-in on its computer, which moves the computer's entries there, never of a team session's (#3122)", async () => {
+ m.auth.mockResolvedValue(owner)
+ handleAdapterUpgrade(adapter(OWNER_COMPUTER) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.computerSignedIn).toHaveBeenCalledWith({ machineId: 'owner-mac', ownerId: 'owner', computerId: OWNER_COMPUTER, autonomousEnv: 'prod' })
+ m.computerSignedIn.mockClear()
+ m.auth.mockResolvedValue(team)
+ handleAdapterUpgrade(adapter(TEAM_COMPUTER) as never, raw() as never, Buffer.alloc(0)); await flush()
+ expect(m.computerSignedIn).not.toHaveBeenCalled()
+ })
+
it('tells the turn tracking a team session\'s turn from a normal sign-in\'s', async () => {
const turnOn = async (user: AuthUser, computer: string) => {
m.auth.mockResolvedValue(user)
diff --git a/backend/src/routes/auth.ts b/backend/src/routes/auth.ts
index 50e7d351d..6f71f26c0 100644
--- a/backend/src/routes/auth.ts
+++ b/backend/src/routes/auth.ts
@@ -24,7 +24,7 @@ import {
} from '../lib/sso.js'
import { parseAutonomousEnvironment, type AutonomousEnvironment } from '../lib/autonomousEnvironment.js'
import { isHarnessRefreshToken } from '../lib/harnessTokenFormat.js'
-import { createSsoSession, redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff, type HarnessTokens } from '../lib/harnessSession.js'
+import { createSsoSession, redeemHandoff, refreshHarnessSession, revokeHarnessSession, startHandoff, TeamCleanupPending, type HarnessTokens } from '../lib/harnessSession.js'
import { parseSsoSessionRequest, type SsoGrant, type SsoSessionRequest } from '../lib/ssoSession.js'
import { normalizeSignInAttribution, type SignInAttribution } from '../lib/signInAttribution.js'
import { createHash } from 'node:crypto'
@@ -409,6 +409,7 @@ export async function authRoutes(app: FastifyInstance): Promise<void> {
logger.info('handoff redeemed', { label })
return sendSuccess(reply, tokens)
} catch (e) {
+ if (e instanceof TeamCleanupPending) return sendError(reply, e.message, e.code, 409)
logger.error('handoff redeem failed', e)
return sendError(reply, 'Authentication service unavailable', 'AUTH_SERVICE_UNAVAILABLE', 503)
}
diff --git a/backend/src/routes/control.test.ts b/backend/src/routes/control.test.ts
index d93b21084..96059091f 100644
--- a/backend/src/routes/control.test.ts
+++ b/backend/src/routes/control.test.ts
@@ -34,6 +34,8 @@ const fakes = vi.hoisted(() => {
machine: {
findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => where.computerId === 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
? [{ machineId: 'team-mac', userId: 'owner', computerId: where.computerId, billingStatus: 'not_required', sessionKind: 'team' }] : []),
+ // Other accounts' Team machines on the redeeming computer (superTabs/computerMoves.ts teamCleanupPending): none here.
+ aggregateRaw: vi.fn(async () => []),
},
},
user: { id: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' },
diff --git a/backend/src/routes/superTabs.test.ts b/backend/src/routes/superTabs.test.ts
index 3e09a637b..ea4fd67a2 100644
--- a/backend/src/routes/superTabs.test.ts
+++ b/backend/src/routes/superTabs.test.ts
@@ -33,6 +33,8 @@ const fakes = vi.hoisted(() => {
machine: {
findMany: vi.fn(async ({ where }: { where: Record<string, unknown> }) => where.computerId === 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
? [{ machineId: 'team-mac', userId: 'owner', computerId: where.computerId, billingStatus: 'not_required', sessionKind: 'team' }] : []),
+ // Other accounts' Team machines on the redeeming computer (superTabs/computerMoves.ts teamCleanupPending): none here.
+ aggregateRaw: vi.fn(async () => []),
},
},
user: { id: 'owner', email: '[email protected]', role: 'user', autonomousEnv: 'prod' },
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 0c8bccd97..a98de5497 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -44,6 +44,7 @@ import { DEFAULT_DAYS, MAX_DAYS } from '../superTabs/costs/read.js'
import { WORKSPACE_ACCESS_REVOKED } from '../superTabs/workspaceStore.js'
import { markNothingNew } from '../lib/routeLatency.js'
import { onMachineRenamed } from '../superTabs/machineRenames.js'
+import { onComputerSignedIn } from '../superTabs/computerMoves.js'
/** Runs a poll and marks its reply nothing-new for `route latency` when `empty` says so (spec 2026-11-02 poll cost, Part 0). */
const noting = <T>(req: FastifyRequest, run: () => Promise<T>, empty: (result: T) => boolean) => async (): Promise<T> => {
@@ -312,6 +313,8 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
const store = options.store ?? await productionStore(github)
// A rename in Machines reaches the Swarms the machine is in at once (MachineService.rename).
onMachineRenamed(rename => store.machineRenamed(rename))
+ // Another account's sign-in on a computer moves the computer's Swarm entries to it (computerMoves.ts).
+ onComputerSignedIn(signIn => store.computerSignedIn(signIn))
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
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1c53d3c67..474a5ecda 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,7 @@
import { applyPushOrigin, failPushUnknown, failTeamWritten, hasStep, mainAccountMembers, markTeamWritten, mayName, requireNameable, requireTeamWrittenAccount, requireTeamWrittenMachine, TEAM_WRITTEN_REASON, TEAM_WRITTEN_STOP, teamWrittenTask } from './teamWritten.js'
import type { PushOrigin } from '../github/pushOrigin.js'
import { admitByRoom, admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, refusesWindowsBuddy, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, machineLimitReached, MACHINE_LIMIT_MESSAGE, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, movedToTeamAccount, type ContributedMachine } from './machines.js'
+import { movableEntry } from './computerMoves.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { addedAgentName, renameAgentTo } from './agentRename.js'
import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
@@ -25,7 +26,7 @@ import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQues
import { leadOf, TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest, workedAgain } from './terminal.js'
import { changesRequested, engineerAnswered, leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, revisionReady, toldEngineer, waitingForReview } from './liveness.js'
import { DELETED_SWARM_COMMANDS, isPersonalSwarm, notThere, SWARM_DELETE_GRACE_MS } from './deletion.js'
-import { ABANDONED, askedModel, coordinatorCopy, failureNotice, failureRecipients, MACHINE_REMOVED, publicReason } from './startFailure.js'
+import { ABANDONED, askedModel, coordinatorCopy, failureNotice, failureRecipients, MACHINE_MOVED, MACHINE_REMOVED, publicReason } from './startFailure.js'
import { noteStartFailed, noteStartSucceeded, resumeEngine } from './engineHealth.js'
import { reviewCapacityNotice } from './reviewCapacity.js'
import { digestStartsAfter, knownTimeZone } from './digest.js'
@@ -170,6 +171,8 @@ export const commandSchema = z.discriminatedUnion('type', [
// With ifMissing: not if its person took it out (Swarm removedMachines). A Personal Swarm's own sync sends it (#2181).
unlessRemoved: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),
+ // The store's alone (context.computerMove): another account signed in on the computer [machineId] is on (#3122).
+ z.object({ type: z.literal('machine.moved'), machineId: id }).strict(),
z.object({ type: z.literal('machine.engineResume'), machineId: id, engine: z.string().regex(/^[a-z][a-z0-9_-]{0,79}$/), askedIn: askedInSchema.optional() }).strict(),
// The projects that may use a machine; null: every project (Tony, 11-03).
z.object({ type: z.literal('machine.projects'), machineId: id, projectIds: z.array(id).min(1).max(64).nullable(), askedIn: askedInSchema.optional() }).strict(),
@@ -475,6 +478,9 @@ export interface CommandContext {
/** The machines of this Swarm's pending cleanups whose machine account is deleted, read by the store: no host will ever
* confirm those cleanups (Ken's remote-deepseek and WIN-DELL, 2026-10-28), so they go. */
deletedMachineIds?: string[]
+ /** For `machine.moved`: the machine of the account signed in now on the computer the command's machine is on, read by the
+ * store from their account rows (store.ts computerSignedIn), never from a request. `name`: its account row's name, if any. */
+ computerMove?: { to: { machineId: string; ownerId: string; name: string | null } }
/** Read from host ownership/access records by the store, never copied from the request. */
contribution?: { machineOwnerId: string; contributorId: string; hostGrant?: string | null
/** The name the machine's owner gave it, from its account row (machines.ts accountMachineName); absent when it has none. */
@@ -1463,7 +1469,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
* like one agent, its pending starts fail, routing rules lose it, and a contributed machine stays paused and cleaning
* until its host deletes the Swarm's folders there — or leaves at once when that host is offline
* (spec 2026-10-23-remove-machine.md). */
- const removeMachine = (machineId: string, pool: ContributedMachine | undefined, members: Agent[], how: (machine: string) => string, lead = false) => {
+ /** [keepFolders]: the machine's folders stay with the computer (machine.moved), so it leaves the list at once with no cleanup. */
+ const removeMachine = (machineId: string, pool: ContributedMachine | undefined, members: Agent[], how: (machine: string) => string, lead = false,
+ keepFolders = false) => {
// Its row in each group names them, so no member row repeats it.
for (const member of members) announcedRemovals.add(member.id)
const pending = state.starts?.filter(s => s.request.machineId === machineId && !s.harnessId && !s.error) ?? []
@@ -1507,7 +1515,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
// Its host is offline and cannot acknowledge, so the fallback applies at once: the machine leaves the list
// now and its cleanup waits for its next connection (spec 2026-10-23-remove-machine.md).
- if (pool?.removal && machineOffline(pool, context.now)) expireRemoval(state, pool)
+ if (pool && keepFolders) state.machines = state.machines!.filter(m => m !== pool)
+ else if (pool?.removal && machineOffline(pool, context.now)) expireRemoval(state, pool)
return removed
}
@@ -2053,6 +2062,53 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
}
break
}
+ case 'machine.moved': {
+ // A computer is signed in as one account at a time (Scholes, #3122): the store found another account's sign-in on the
+ // computer of this entry and runs this as the entry's owner. Nothing here is the request's: the store read the computer's
+ // accounts from their rows. An entry still reporting is left (two live accounts on one computer id are no switch).
+ const move = context.computerMove
+ if (!move || actor.kind !== 'person') fail('FORBIDDEN', 'Harness moves a computer to the account signed in on it.', 403)
+ const pool = movableEntry(state, command.machineId, actor.userId, move.to, context.now)
+ if (!pool) break
+ const teams = teamPoolsOf(state, pool).filter(m => !m.removal)
+ const here = new Set([pool.machineId, ...teams.map(t => t.machineId)])
+ // Its host is gone, so a start it launched never arrives: each fails now, launched or not.
+ for (const start of state.starts?.filter(s => here.has(s.request.machineId) && !s.harnessId && !s.error) ?? []) {
+ start.error = MACHINE_MOVED
+ effects.messages.push({ id: stableId(operationId, 'start', start.id), conversationId: start.request.conversationId, author: sender,
+ text: `${start.request.name} will not start: its machine is signed in to another account now.`, replyTo: null, recipients: [], source: SYSTEM_ROW })
+ }
+ const leaving = state.agents.filter(a => here.has(a.machineId))
+ const how = (machine: string) => `${machine} is signed in to another account now, so it left the Swarm under its old account`
+ // The old account's agents stop first, Product Managers too: they ran under a login this computer no longer has.
+ removeMachine(pool.machineId, pool, leaving, how, true, true)
+ // Its Team account's host still runs as the old account: it deletes its own folders, and the entry leaves the list now.
+ for (const team of teams) {
+ removeMachine(team.machineId, team, [], how, true)
+ if (state.machines?.includes(team)) expireRemoval(state, team)
+ }
+ const newOwner = state.people.find(p => p.id === move.to.ownerId)
+ const until = new Date(context.now).toISOString()
+ const existing = state.machines?.find(m => m.machineId === move.to.machineId && !m.removal)
+ if (existing) existing.previousOwner = { personId: pool.contributorId, until }
+ else if (newOwner && !existing && !state.machines?.some(m => m.machineId === move.to.machineId)
+ && !state.removedMachines?.some(r => r.machineId === move.to.machineId) && !machineLimitReached(state, newOwner.id)) {
+ // The computer's own settings move with it; what was granted to or recorded for its old owner does not. Teammates' work
+ // runs here only through a Team account of the new owner's, as when a person's join adds their computer.
+ ;(state.machines ??= []).push({ machineId: move.to.machineId, name: move.to.name ?? pool.name, cwd: pool.cwd, engines: [...pool.engines],
+ maxAgents: pool.maxAgents, ...(pool.agents ? { agents: pool.agents } : {}), ...(pool.scope ? { scope: pool.scope } : {}),
+ contributorId: newOwner.id, membershipGeneration: newOwner.generation, generation: operationId, paused: pool.paused,
+ teamAccountOnly: true, previousOwner: { personId: pool.contributorId, until } })
+ }
+ const names = leaving.map(a => a.displayName ?? a.name)
+ const join = names.length > 1 ? `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` : names[0]
+ const signedIn = newOwner ? `signed in as ${usernameOf(state, newOwner.id) ?? 'another account'}` : 'signed in to another account'
+ effects.messages.push({ id: stableId(operationId, 'computer-moved'), conversationId: openSwarmBuddyChat(state, person(state, pool.contributorId)).id,
+ author: sender, replyTo: null, recipients: [], source: { kind: 'computer-moved', machineId: pool.machineId },
+ text: `Your ${pool.name} is ${signedIn} now, so it left this Swarm under your account${join ? `, and ${join} with it` : ''}.` })
+ result.moved = true
+ break
+ }
case 'localModels.set': {
// An add-on the owner turns on: its grid is theirs, and nothing calls grid until they do.
if (actor.kind !== 'person' || actor.userId !== state.ownerId) fail('OWNER_REQUIRED', 'Only the Swarm owner turns Local models on or off.', 403)
diff --git a/backend/src/superTabs/computerMoves.test.ts b/backend/src/superTabs/computerMoves.test.ts
new file mode 100644
index 000000000..b77544720
--- /dev/null
+++ b/backend/src/superTabs/computerMoves.test.ts
@@ -0,0 +1,182 @@
+// A computer is signed in as one account at a time (Scholes, #3122: MacBooks-MacBook-Pro-7 showed as kelvin's, as
+// ttkhoahcmus's and as kelvin's Team account at once). When another account signs in there, the store finds the computer's
+// entry of the old account in each Swarm (store.ts computerSignedIn) and moves it: one entry, the new account's.
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor } from './model.js'
+import { swarmBuddyChatId } from './buddies.js'
+import { joiningTeamMacs, machineTeamWork, type ContributedMachine } from './machines.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const kelvin: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'kelvin', email: '[email protected]' }
+const tt: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'tt', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+const NOW = 10_000_000
+const reading = (receivedAt: number): NonNullable<ContributedMachine['observation']> => ({ generation: 'g1', receivedAt, sessionKind: 'computer',
+ resources: { cpuPercent: null, memoryTotalBytes: null, memoryUsedBytes: null, diskFreeBytes: null, diskTotalBytes: null, projectDiskFreeBytes: null,
+ deviceType: null, chip: null, os: null, gpuPercent: null }, tools: {}, quotas: [], runningHarnessIds: [], stoppedHarnessIds: [] })
+const own = (userId: string) => ({ machineOwnerId: userId, contributorId: userId, hostGrant: null })
+/** What the store read from the account rows: ttkhoahcmus's machine on the computer kelvin's entry is on. */
+const moveTo = (to = { machineId: 'tt-mac', ownerId: 'tt', name: 'MacBooks-MacBook-Pro-7' }): Partial<CommandContext> => ({ computerMove: { to } })
+const MOVED: Command = { type: 'machine.moved', machineId: 'kelvin-mac' }
+
+/** A Swarm where kelvin's Mac is in, offline since he signed out of it, with its Team account live, and ttkhoahcmus a member. */
+function setup({ ttMember = true, kelvinOnline = false } = {}) {
+ let state = createSuperTab('swarm', 'Team', { id: 'owner', email: owner.email }, 'test')
+ state.people.push({ id: 'kelvin', email: kelvin.email, role: 'collaborator', generation: 'kelvin-gen' })
+ if (ttMember) state.people.push({ id: 'tt', email: tt.email, role: 'collaborator', generation: 'tt-gen' })
+ let next = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { operationId: `op${next++}`, now: NOW,
+ contribution: own(actor.kind === 'person' ? actor.userId : 'owner'), ...context })
+ state = effects.state
+ return effects
+ }
+ const kelvinMac: ContributedMachine = { machineId: 'kelvin-mac', name: 'MacBooks-MacBook-Pro-7', contributorId: 'kelvin', membershipGeneration: 'kelvin-gen',
+ generation: 'g0', cwd: '/Users/mac/harness-swarm', scope: 'swarm', engines: ['claude', 'codex'], maxAgents: 3, agents: 'atMost', paused: true,
+ observation: reading(kelvinOnline ? NOW - 1000 : NOW - 3_000_000), teamAccountOnly: true, projects: ['lead'],
+ ownAccountChoice: { allowed: true, by: 'kelvin', at: '2026-11-04T00:00:00.000Z' }, othersToldWeek: 1,
+ lent: [{ week: 1, ms: 5000 }] as unknown as ContributedMachine['lent'], engineFailures: { codex: 1 } }
+ const kelvinTeam: ContributedMachine = { machineId: 'kelvin-team', name: 'MacBooks-MacBook-Pro-7', contributorId: 'kelvin', membershipGeneration: 'kelvin-gen',
+ generation: 'g0', cwd: '/Users/harness-team/harness-swarm', scope: 'swarm', engines: ['claude'], maxAgents: 3, paused: true,
+ observation: { ...reading(NOW - 1000), sessionKind: 'team' }, hostMachineId: 'kelvin-mac' }
+ state.machines = [kelvinMac, kelvinTeam]
+ const group = run({ type: 'conversation.create', projectId: 'lead', title: 'Offline edits', brief: 'Save edits.', checks: [] }).result.conversationId as string
+ const builder = run({ type: 'agent.add', conversationId: group, harnessId: 'h-builder', machineId: 'kelvin-mac', name: 'Birch3', configuration, lead: false },
+ kelvin, { contribution: own('kelvin') }).result.agentId as string
+ const teamAgent = run({ type: 'agent.add', conversationId: group, harnessId: 'h-team', machineId: 'kelvin-team', name: 'Fern', configuration, lead: false },
+ kelvin, { contribution: { ...own('kelvin'), hostMachineId: 'kelvin-mac' } }).result.agentId as string
+ return { run, group, builder, teamAgent, get state() { return state } }
+}
+const entries = (f: ReturnType<typeof setup>) => f.state.machines!.filter(m => !m.removal).map(m => m.machineId)
+
+describe("another account's sign-in on a computer", () => {
+ it('leaves exactly one entry, under the new account, with a note of who it was before', () => {
+ const f = setup()
+ f.run(MOVED, kelvin, moveTo())
+ expect(entries(f)).toEqual(['tt-mac'])
+ const moved = f.state.machines!.find(m => m.machineId === 'tt-mac')!
+ expect(moved).toMatchObject({ contributorId: 'tt', membershipGeneration: 'tt-gen', name: 'MacBooks-MacBook-Pro-7',
+ cwd: '/Users/mac/harness-swarm', engines: ['claude', 'codex'], maxAgents: 3, agents: 'atMost', paused: true, scope: 'swarm',
+ teamAccountOnly: true, previousOwner: { personId: 'kelvin', until: new Date(NOW).toISOString() } })
+ })
+
+ it("carries none of the old owner's grants or records", () => {
+ const f = setup()
+ f.run(MOVED, kelvin, moveTo())
+ const moved = f.state.machines!.find(m => m.machineId === 'tt-mac')!
+ for (const key of ['projects', 'ownAccountChoice', 'othersToldWeek', 'lent', 'lentDays', 'engineFailures', 'engineSuspensions', 'observation', 'hostMachineId']) {
+ expect(moved, key).not.toHaveProperty(key)
+ }
+ })
+
+ it("stops the old account's agents first, there and on its Team account, and tells their groups and the old owner", () => {
+ const f = setup()
+ const effects = f.run(MOVED, kelvin, moveTo())
+ expect(f.state.agents.map(a => a.id)).not.toContain(f.builder)
+ expect(f.state.agents.map(a => a.id)).not.toContain(f.teamAgent)
+ expect(effects.cancelledAgents).toEqual(expect.arrayContaining([f.builder, f.teamAgent]))
+ expect(effects.messages.find(m => m.conversationId === f.group)?.text).toContain('MacBooks-MacBook-Pro-7 is signed in to another account now')
+ const told = effects.messages.filter(m => m.conversationId === swarmBuddyChatId(f.state.people.find(p => p.id === 'kelvin')!))
+ expect(told).toHaveLength(1)
+ expect(told[0]!.text).toBe('Your MacBooks-MacBook-Pro-7 is signed in as ttkhoahcmus now, so it left this Swarm under your account, and Birch3 and Fern with it.')
+ })
+
+ it('cleans up after the Team account, whose host still runs, and leaves the computer\'s folders to the new account', () => {
+ const f = setup()
+ f.run(MOVED, kelvin, moveTo())
+ expect(f.state.machineCleanups?.map(c => c.machineId)).toEqual(['kelvin-team'])
+ expect(f.state.removedMachines ?? []).toEqual([])
+ })
+
+ it('fails the starts still waiting on the old account\'s machine', () => {
+ const f = setup()
+ f.state.starts = [{ id: 's1', request: { machineId: 'kelvin-mac', conversationId: f.group, name: 'Holly' }, dispatched: true } as never]
+ f.run(MOVED, kelvin, moveTo())
+ expect(f.state.starts![0]!.error).toBeTruthy()
+ })
+
+ it('keeps the new account\'s own entry and settings when it is already in the Swarm, adding only the note', () => {
+ const f = setup()
+ f.state.machines!.push({ machineId: 'tt-mac', name: 'MacBooks-MacBook-Pro-7', contributorId: 'tt', membershipGeneration: 'tt-gen', generation: 'g1',
+ cwd: '/Users/mac/harness-swarm', engines: ['claude'], maxAgents: 1, paused: false, observation: reading(NOW - 1000) })
+ f.run(MOVED, kelvin, moveTo())
+ expect(entries(f)).toEqual(['tt-mac'])
+ expect(f.state.machines!.find(m => m.machineId === 'tt-mac')).toMatchObject({ maxAgents: 1, paused: false, previousOwner: { personId: 'kelvin' } })
+ })
+
+ it('only takes the old entry out when the new account is not in the Swarm, and names no one to the old owner', () => {
+ const f = setup({ ttMember: false })
+ const effects = f.run(MOVED, kelvin, moveTo())
+ expect(entries(f)).toEqual([])
+ const told = effects.messages.filter(m => m.conversationId === swarmBuddyChatId(f.state.people.find(p => p.id === 'kelvin')!))
+ expect(told[0]!.text).toBe('Your MacBooks-MacBook-Pro-7 is signed in to another account now, so it left this Swarm under your account, and Birch3 and Fern with it.')
+ })
+
+ it('does not add the new account\'s machine where its person took it out', () => {
+ const f = setup()
+ f.state.removedMachines = [{ machineId: 'tt-mac', contributorId: 'tt' }]
+ f.run(MOVED, kelvin, moveTo())
+ expect(entries(f)).toEqual([])
+ })
+
+ it('moves nothing while the old entry still reports: two live accounts on one computer id are no switch', () => {
+ const f = setup({ kelvinOnline: true })
+ const before = structuredClone(f.state.machines)
+ f.run(MOVED, kelvin, moveTo())
+ expect(f.state.machines).toEqual(before)
+ expect(f.state.agents.map(a => a.id)).toContain(f.builder)
+ })
+
+ it('is refused unless the store read the move itself', () => {
+ const f = setup()
+ expect(() => f.run(MOVED, kelvin)).toThrow()
+ expect(() => f.run(MOVED, tt)).toThrow()
+ expect(entries(f)).toEqual(['kelvin-mac', 'kelvin-team'])
+ })
+
+ it('changes nothing the second time', () => {
+ const f = setup()
+ f.run(MOVED, kelvin, moveTo())
+ const after = structuredClone(f.state)
+ const again = f.run(MOVED, kelvin, moveTo())
+ expect(f.state.machines).toEqual(after.machines)
+ expect(again.messages).toEqual([])
+ })
+})
+
+// Scholes, 11-05: kelvin added his Mac, Set up showed for a couple of seconds and went away. His Harness Team account was on
+// that Mac already, and joined the Swarm moments after the Mac did; until then the Mac read "not set up".
+describe('a Mac whose own Harness Team account has not joined the Swarm yet', () => {
+ const mac = (f: ReturnType<typeof setup>) => {
+ f.state.machines = f.state.machines!.filter(m => m.machineId === 'kelvin-mac')
+ const pool = f.state.machines[0]!
+ pool.observation = reading(NOW - 1000)
+ // Teammates' work only through its Team account, as Add machine leaves it.
+ delete pool.ownAccountChoice
+ return pool
+ }
+ const row = (userId: string, hostMachineId: string, machineId = 'kelvin-team') => ({ machineId, userId, hostMachineId })
+
+ it('is joining while its owner has a Team account on it that the Swarm does not list', () => {
+ const f = setup()
+ const pool = mac(f)
+ expect(joiningTeamMacs(f.state, [row('kelvin', 'kelvin-mac')])).toEqual(['kelvin-mac'])
+ expect(machineTeamWork(f.state, pool, NOW, [], [], ['kelvin-mac'])?.code).toBe('TEAM_ACCOUNT_JOINING')
+ expect(machineTeamWork(f.state, pool, NOW, [], [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ })
+
+ it("is not joining with another account's Team account on it, one listed already, or no room for it", () => {
+ const f = setup()
+ mac(f)
+ // The Team account of the computer's previous account names that account's machine, never this one.
+ expect(joiningTeamMacs(f.state, [row('tt', 'kelvin-mac')])).toEqual([])
+ expect(joiningTeamMacs(f.state, [row('kelvin', 'another-mac')])).toEqual([])
+ const listed = setup()
+ expect(joiningTeamMacs(listed.state, [row('kelvin', 'kelvin-mac')])).toEqual([])
+ const cleaning = setup()
+ mac(cleaning)
+ cleaning.state.machineCleanups = [{ machineId: 'kelvin-team', removalId: 'r', machineOwnerId: 'kelvin' }]
+ expect(joiningTeamMacs(cleaning.state, [row('kelvin', 'kelvin-mac')])).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/computerMoves.ts b/backend/src/superTabs/computerMoves.ts
new file mode 100644
index 000000000..d75bbe4a8
--- /dev/null
+++ b/backend/src/superTabs/computerMoves.ts
@@ -0,0 +1,127 @@
+/**
+ * A computer is signed in as one account at a time (Scholes, #3122): when another account signs in there, the computer's
+ * entry in each Swarm moves to it. Account rows are per account and computer (MachineService.resolveOrCreateForComputer),
+ * joined only by `Machine.computerId`, the id minted once in the computer's own `~/.harness/computer-id`.
+ */
+import type { Prisma } from '@prisma/client'
+import { readBy } from './parts/indexed.js'
+import { machineOffline, type ContributedMachine } from './machines.js'
+import type { SuperTabState } from './model.js'
+
+type Reader = Pick<Prisma.TransactionClient, 'machine'>
+
+/**
+ * The live rows of other accounts signed in on [computerId] before, never [ownerId]'s own or a Harness Team sign-in's.
+ * A plain `$match` on the (computerId, userId) index: Prisma sends `not` and the deletedAt OR as $expr, which no index bounds.
+ */
+export async function otherAccountsOnComputer(db: Reader, { computerId, ownerId, autonomousEnv }: { computerId: string; ownerId: string; autonomousEnv: string }):
+ Promise<Array<{ machineId: string; userId: string }>> {
+ const rows = await db.machine.aggregateRaw({ pipeline: [
+ { $match: { computerId, userId: { $ne: ownerId }, autonomousEnv, authMode: 'remote', sessionKind: { $ne: 'team' }, deletedAt: null } },
+ { $sort: { userId: 1 } }, { $limit: 16 }, { $project: { _id: 0, machineId: 1, userId: 1 } }],
+ options: { hint: { computerId: 1, userId: 1 } } }) as unknown as Array<{ machineId: string; userId: string }>
+ return rows.map(row => ({ machineId: row.machineId, userId: row.userId }))
+}
+
+/** One entry a computer's sign-in moves (or, in a dry run, would): in Swarm [tabId], [fromOwner]'s machine [from] to
+ * [toOwner]'s [to]. Ids only, so the cleanup's output names what Ken's go covers and what each owner may add back. */
+export interface ComputerMove { tabId: string; from: string; fromOwner: string; to: string; toOwner: string }
+
+/**
+ * The entry of [ownerId]'s machine [machineId] that a sign-in of [to] on the same computer moves, or none: the computer's own
+ * entry (not a Team account's), not being removed, still [ownerId]'s, and not reporting, since two live accounts on one
+ * computer id are no switch. machine.moved and the cleanup's dry run both decide by it.
+ */
+export function movableEntry(state: SuperTabState, machineId: string, ownerId: string, to: { machineId: string; ownerId: string }, now: number):
+ ContributedMachine | undefined {
+ const pool = state.machines?.find(m => m.machineId === machineId && !m.hostMachineId && !m.removal)
+ if (!pool || pool.contributorId !== ownerId || ownerId === to.ownerId || machineId === to.machineId || !machineOffline(pool, now)) return undefined
+ return pool
+}
+
+/** Each account's active device keys (lib/deviceKeyLog.ts activeMachineKeysOf): only `machine` keys are read here. */
+export type MachineKeys = (userIds: string[]) => Promise<Map<string, ReadonlyArray<{ pub: string; kind: string; machineId: string }>>>
+
+/**
+ * Whether [from] and [to] are machines of one computer: each account's log holds the same machine key for its machine. The
+ * key is the computer's (cli e2ee/store.ts identity.json, never touched by a sign-in), and every add is signed by the key
+ * itself for that one account (deviceLogCore.ts), so only a holder of its private key can list it under a second account.
+ * The computer id alone is self-declared (security review 1 of #3100). A machine with no key proves nothing.
+ */
+export async function sameComputerKey(keys: MachineKeys, from: { userId: string; machineId: string }, to: { userId: string; machineId: string }):
+ Promise<boolean> {
+ const held = await keys([from.userId, to.userId])
+ const of = (side: { userId: string; machineId: string }) => held.get(side.userId)?.find(k => k.kind === 'machine' && k.machineId === side.machineId)?.pub
+ const pub = of(from)
+ return !!pub && pub === of(to)
+}
+
+/** An account's ordinary sign-in connecting from a computer (lib/adapterWs.ts): never a Harness Team session's. */
+export interface ComputerSignIn { machineId: string; ownerId: string; computerId: string; autonomousEnv: string }
+
+type Listener = (signIn: ComputerSignIn) => Promise<unknown>
+let listener: Listener | null = null
+
+/** The Swarm routes' store takes sign-ins from here (routes/superTabs.ts), so the adapter socket loads no Swarm code. */
+export function onComputerSignedIn(next: Listener | null): void {
+ listener = next
+}
+
+/** Tells the Swarms an entry of this computer's previous account is in. Never fails the connect: a Swarm missed is logged, and
+ * the next connect tries again. Nothing to do when no Swarm routes run here. */
+export async function computerSignedIn(signIn: ComputerSignIn): Promise<void> {
+ await listener?.(signIn)
+}
+
+/**
+ * Whether another account's Harness Team machine on [computerId] (a Team account's own computer id) still has its folders to
+ * delete in a Swarm: a computer moved to [userId] left that Team machine's cleanup (commands.ts machine.moved), and only its
+ * own sign-in can run it (security review 2 of #3100). Signed in for [userId] first, it never would, and the old Swarms'
+ * checkouts would stay where [userId]'s teammates' work runs. Two indexed reads: the computer's Team rows, then the Swarms'
+ * cleanup index.
+ */
+export async function teamCleanupPending(db: Reader & Pick<Prisma.TransactionClient, 'superTab'>, { computerId, userId }: { computerId: string; userId: string }):
+ Promise<boolean> {
+ const teams = await db.machine.aggregateRaw({ pipeline: [
+ { $match: { computerId, userId: { $ne: userId }, authMode: 'remote', sessionKind: 'team', deletedAt: null } },
+ { $limit: 16 }, { $project: { _id: 0, machineId: 1, autonomousEnv: 1 } }],
+ options: { hint: { computerId: 1, userId: 1 } } }) as unknown as Array<{ machineId: string; autonomousEnv: string }>
+ for (const autonomousEnv of new Set(teams.map(t => t.autonomousEnv))) {
+ const ids = teams.filter(t => t.autonomousEnv === autonomousEnv).map(t => t.machineId)
+ const swarms = await readBy(db as Prisma.TransactionClient, 'SuperTab', 'cleanup', [
+ { $match: { autonomousEnv, cleanupMachineIds: { $in: ids } } }, { $limit: 1 }, { $project: { _id: 1 } }])
+ if (swarms.length) return true
+ }
+ return false
+}
+
+/** What the one-time cleanup found: each computer with live rows of two or more accounts, the one seen last, and the others. */
+export interface CleanUp { computers: Array<{ signedIn: { machineId: string; ownerId: string }; others: string[] }>; moves: ComputerMove[] }
+
+/**
+ * The one-time cleanup of computers listed under two accounts before moves existed (Scholes, 11-05: MacBooks-MacBook-Pro-7 three
+ * times): the account seen last on each is the one signed in there, and its sign-in moves the others' entries as a connect does
+ * (store.ts computerSignedIn). A computer whose last two accounts were seen at the same moment, or never, is left. With [write]
+ * false it writes nothing and lists the moves the write would make, decided the same way. Safe to run again: an entry moved
+ * is gone, and nothing else is written.
+ */
+export async function cleanUpComputers(db: Reader, store: { computerSignedIn(signIn: ComputerSignIn, options: { write: boolean }): Promise<ComputerMove[]> },
+ autonomousEnv: string,
+ { write }: { write: boolean }): Promise<CleanUp> {
+ const groups = await db.machine.aggregateRaw({ pipeline: [
+ { $match: { computerId: { $type: 'string' }, autonomousEnv, authMode: 'remote', sessionKind: { $ne: 'team' }, deletedAt: null } },
+ { $group: { _id: '$computerId', accounts: { $addToSet: '$userId' }, rows: { $push: { machineId: '$machineId', userId: '$userId', seen: '$lastSeenAt' } } } },
+ { $match: { 'accounts.1': { $exists: true } } }],
+ options: { hint: { computerId: 1, userId: 1 } } }) as unknown as Array<{ _id: string; rows: Array<{ machineId: string; userId: string; seen?: { $date: string } | null }> }>
+ const result: CleanUp = { computers: [], moves: [] }
+ for (const group of groups) {
+ const seen = (row: (typeof group.rows)[number]) => row.seen ? Date.parse(row.seen.$date) : 0
+ const [last, next] = [...group.rows].sort((a, b) => seen(b) - seen(a))
+ if (!last || !seen(last) || (next && seen(next) === seen(last))) continue
+ result.computers.push({ signedIn: { machineId: last.machineId, ownerId: last.userId },
+ others: group.rows.filter(row => row.userId !== last.userId).map(row => row.machineId) })
+ // The dry run decides as the write does, so what it lists is what the write moves.
+ result.moves.push(...await store.computerSignedIn({ machineId: last.machineId, ownerId: last.userId, computerId: group._id, autonomousEnv }, { write }))
+ }
+ return result
+}
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index a8e37fff7..ec1099e1e 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -56,6 +56,9 @@ export interface ContributedMachine {
* Manager candidate, serves no local models, and no reader sees it (model.ts visibleState). It goes with its last Buddy
* (commands.ts dropIdleBuddyMachines), or becomes an ordinary machine when its person adds it with Add machine. */
buddyOnly?: true
+ /** Who had this computer's entry before the account signed in on it now (commands.ts machine.moved, #3122), and until when:
+ * Machines says "Was kelvin until 5 Nov". Only the last one; gone with the entry. */
+ previousOwner?: { personId: string; until: string }
/** Agent-time Swarm agents here spent on other people's tasks, by leaderboard week, kept by its readings (leaderboard/lent.ts). */
lent?: import('./leaderboard/lent.js').LentWeek[]
/** The same by day, for the board's rolling periods. Only the leaderboard read gets it (model.ts visibleState). */
@@ -299,7 +302,7 @@ export function observedPrivacy(previous: StoredPrivacy | undefined, reported: M
}
export type TeamWorkCode = 'TEAM_WRITTEN_WORK' | 'MACHINE_OFFLINE' | 'TEAM_ACCOUNT_REQUIRED' | 'PRIVACY_UNCHECKED' | 'PRIVACY_CHECK_FAILED' | 'PRIVACY_CHECK_STALE'
- | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS' | 'ACCESS_MISSING'
+ | 'MACHINE_IN_OTHER_WORKSPACE' | 'NOT_SWARM_MACHINE' | 'MACHINE_PROJECTS' | 'ACCESS_MISSING' | 'TEAM_ACCOUNT_JOINING'
export interface TeamWorkRefusal { code: TeamWorkCode; reason: string }
/** Refusals that hold until a person acts on the machine; a stale check or an offline machine may pass again by itself. */
export const LASTING_TEAM_REFUSALS: readonly string[] = ['TEAM_ACCOUNT_REQUIRED', 'PRIVACY_UNCHECKED', 'PRIVACY_CHECK_FAILED', 'MACHINE_IN_OTHER_WORKSPACE']
@@ -459,12 +462,33 @@ export function teamPoolOf(state: SuperTabState, pool: ContributedMachine, live?
* (2026-10-28). Any other machine, and a Mac without one, reads as itself.
*/
export function machineTeamWork(state: SuperTabState, pool: ContributedMachine, now: number, teamMachines: readonly string[],
- otherWorkspaceMachines: readonly string[] = []): TeamWorkRefusal | null {
+ otherWorkspaceMachines: readonly string[] = [], joiningTeams: readonly string[] = []): TeamWorkRefusal | null {
// Its owner lets teammates' work run in their own account: starts stay on the Mac, so the Mac itself is what routing reads
// (security review 2 of #2981).
const team = !pool.hostMachineId && !ownAccountWork(pool) ? teamPoolOf(state, pool, teamMachines) : undefined
const subject = team ?? pool
- return teamWorkRefusal(subject, now, teamMachines.includes(subject.machineId), teamAccountRequired(), otherWorkspaceMachines.includes(subject.machineId))
+ const refusal = teamWorkRefusal(subject, now, teamMachines.includes(subject.machineId), teamAccountRequired(), otherWorkspaceMachines.includes(subject.machineId))
+ // Its owner's Team account is on it and joins on the Mac's next poll (read/hostRows.ts joinTeam): not "not set up" meanwhile,
+ // which offered Set up for those seconds (Scholes, 11-05).
+ if (refusal?.code === 'TEAM_ACCOUNT_REQUIRED' && !team && joiningTeams.includes(pool.machineId)) {
+ return { code: 'TEAM_ACCOUNT_JOINING', reason: `The Harness Team account on ${pool.name} is joining this Swarm, ${ONLY_OWN} until it has.` }
+ }
+ return refusal
+}
+
+/** A Harness Team machine of an account (its account row): the Mac it lives on. */
+export interface TeamMachineRow { machineId: string; userId: string; hostMachineId: string }
+
+/**
+ * The Macs of the Swarm whose owner has a Harness Team account on it that the Swarm does not list yet, and room for it: the
+ * ones its host adds on its next poll (read/hostRows.ts joinTeam), from [teams], those owners' Team machines. A Team account
+ * of another account names that account's own Mac, never this one (#3122).
+ */
+export function joiningTeamMacs(state: SuperTabState, teams: readonly TeamMachineRow[]): string[] {
+ const listed = (machineId: string) => state.machines?.some(m => m.machineId === machineId) || state.machineCleanups?.some(c => c.machineId === machineId)
+ return (state.machines ?? []).filter(mac => !mac.hostMachineId && !mac.removal && !mac.buddyOnly && mac.scope === 'swarm'
+ && teams.some(t => t.hostMachineId === mac.machineId && t.userId === mac.contributorId && !listed(t.machineId))
+ && machineRoom(state, mac.contributorId, { team: true }) > 0).map(mac => mac.machineId)
}
/** The projects with work on [machineId]: its agents' and its pending starts'. */
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 4dc8b2eff..4240b3698 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -628,6 +628,8 @@ export const NOTICE_READERS = {
'note-removed': 'recipients',
'project-report': 'people', route: 'people', 'route-override': 'people', 'buddy-proposal': 'people', 'buddy-proposal-sent': 'people', 'buddy-session-ended': 'people',
'decision-delegated': 'people', 'machine-removed': 'people', ship: 'people',
+ // A computer signed in as another account now, told to its old owner in their Buddy chat (commands.ts machine.moved, #3122).
+ 'computer-moved': 'people',
// "<machine> left the Swarm: ..." in every project chat, no longer written (anh Dee, 11-04, #2742): the rows stored before are
// read by nobody (they have no recipients), and a project chat ending in one is served as read (read/servedTops.ts).
'machine-left': 'agent',
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 4c4e67321..4759d5003 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -51,7 +51,7 @@ interface Read { parts: SwarmParts; actor: Actor; view: ReaderView; lastChangedA
export const GROUP_ROWS_BYTES = 8 * 1024 * 1024
/** How long one Swarm's machine lookups below are reused: machines report every 15 s anyway (Diego's review, item 5, 2026-10-28). */
const MACHINE_READS_MS = 15_000
-type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[], machineVersions: Record<string, string>]
+type MachineReads = [teamMachines: string[], otherWorkspaceMachines: string[], machineVersions: Record<string, string>, joiningTeams: string[]]
/** The conversations the reader can read now, a dormant one read by id included. */
function readableGroups(read: Read): Set<string> {
@@ -578,13 +578,13 @@ export class SwarmReads {
const loaded = await loader(cached, tabId, opts)
const state = parts.reassemble(loaded, { share: true })
const actor = await this.store.actor(tx, user, state, asAgentId)
- const [[teamMachines, otherWorkspaceMachines, machineVersions], counts, newest] = await Promise.all([
+ const [[teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams], counts, newest] = await Promise.all([
this.machineLookups(state),
actor.kind === 'person' ? Promise.all([waitingMentions(tx, tabId, state, actor, t0), decisionsWaiting(tx, tabId, state, actor),
activityDigest(tx, tabId, actor.userId, t0), remindersDigest(tx, tabId, actor.userId)]) : undefined,
readLastChangedAt(tx, cached, tabId),
])
- const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, teamAccountsIdle: this.store.teamAccountsIdle,
+ const view = readerView(loaded, actor, t0, { teamMachines, otherWorkspaceMachines, machineVersions, joiningTeams, teamAccountsIdle: this.store.teamAccountsIdle,
...(counts ? { mentionsWaiting: counts[0].count, mentionsDigest: counts[0].digest, decisionsWaiting: counts[1].count,
decisionsDigest: counts[1].digest, activityDigest: counts[2], remindersDigest: counts[3] } : {}) }, state)
// People count a chat unread by its newest main row; agents keep no read marks.
@@ -596,7 +596,7 @@ export class SwarmReads {
* same answer for every reader, whose view hides what it may not see, so one lookup serves every read of the Swarm for
* MACHINE_READS_MS. Commands that admit work still look up afresh (store.ts executeOnce). Outside any transaction, as every read is. */
private machineLookups(state: SuperTabState): Promise<MachineReads> {
- if (!state.machines?.length) return Promise.resolve([[], [], {}])
+ if (!state.machines?.length) return Promise.resolve([[], [], {}, []])
const now = this.now()
const key = JSON.stringify([state.id, state.environment, state.workspaceId ?? null, state.machines.map(m => m.machineId).sort()])
const kept = this.machineReads.get(key)
@@ -605,8 +605,9 @@ export class SwarmReads {
if (now >= entry.at && now - entry.at < MACHINE_READS_MS) break
this.machineReads.delete(old)
}
- const entry = { at: now, read: Promise.all([this.store.machineFacts(this.db, state), this.store.otherWorkspaceMachines(this.db, state)])
- .then(([facts, other]): MachineReads => [facts.team, other, facts.versions]) }
+ const entry = { at: now, read: Promise.all([this.store.machineFacts(this.db, state), this.store.otherWorkspaceMachines(this.db, state),
+ this.store.joiningTeams(this.db, state)])
+ .then(([facts, other, joining]): MachineReads => [facts.team, other, facts.versions, joining]) }
this.machineReads.delete(key)
this.machineReads.set(key, entry)
// A failed lookup is never reused.
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 05cd90fd1..6682dcbb8 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -40,6 +40,8 @@ export interface ReadExtras {
teamAccountsIdle?: boolean
/** Each contributed machine's CLI version as its daemon last connected (store.ts machineFacts). */
machineVersions?: Record<string, string>
+ /** Macs whose owner's Harness Team account on them is not listed yet (store.ts joiningTeams). */
+ joiningTeams?: string[]
/** A person's open mentions, counted by the store. */
mentionsWaiting?: number
/** Which ones they are, as a digest (mentions.ts). */
@@ -134,7 +136,7 @@ function derive(state: SuperTabState, visible: SuperTabState, actor: Actor, now:
const slots = slotCounter(state)
const machine = (pool: ContributedMachine) => {
const stored = state.machines!.find(m => m.machineId === pool.machineId)!
- const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [])
+ const refusal = machineTeamWork(state, stored, now, extras.teamMachines, extras.otherWorkspaceMachines ?? [], extras.joiningTeams ?? [])
const version = extras.machineVersions?.[pool.machineId]
const suspended = suspendedEngines(stored, now)
return [pool.machineId, { availableSlots: availableSlots(state, stored, slots(stored)),
diff --git a/backend/src/superTabs/startFailure.ts b/backend/src/superTabs/startFailure.ts
index 7f977d409..36de97d94 100644
--- a/backend/src/superTabs/startFailure.ts
+++ b/backend/src/superTabs/startFailure.ts
@@ -28,6 +28,8 @@ const TIMEOUTS: Array<[string, string]> = [[TIMED_OUT_SUFFIX, TIMED_OUT],
[STOPPED_REPORTING_SUFFIX, 'Its machine stopped reporting while preparing it.']]
/** Reasons the server writes itself, which name nothing (commands.ts removeMachine and machine.contribute). */
export const MACHINE_REMOVED = 'Its machine was removed from the Swarm.'
+/** Its machine's computer is signed in to another account now (commands.ts machine.moved, #3122). */
+export const MACHINE_MOVED = 'Its machine is signed in to another account now.'
export const ABANDONED = 'Abandoned before it started.'
/** A Team account's host refusing a Codex Product Manager it cannot sign in (cli superTabs/start.ts): it names nothing of the
* machine but its lack of the owner's relay, which its project reads (security re-check 3 of #2089). */
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 86eff0398..da4ca3b35 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -2,7 +2,7 @@ import { refusalLogFields, type DeclaredClient } from './refusalLog.js'
import { writeReactionActivity, writeReplyActivity } from './activity.js'
import { phoneNotices, type ReplyRow, type TagRow } from '../push/notices.js'
import type { PhoneNotice } from '../push/sender.js'
-import { accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'
+import { joiningTeamMacs, type TeamMachineRow, accountMachineName, availableSlots, expireRemovals, followAccountName, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, slotCounter, machineTeamWork, preparableStart, readingOnly, refusableStart, recordAgentPresence, renamedBy, removalPreview, startPreparing, storedObservation, swarmGridRow, teamAccountRequired, teamWorkRefusal, ownAccountWork, ownAccountNote, type MachineObservation } from './machines.js'
import { expireAccess } from './machineAccess.js'
import { authorForAgent, lazyUsernames, namesPerson, rowForAgent, shownNameOf } from './personNames.js'
import { readingClearsSuspensions, suspendedEngines } from './engineHealth.js'
@@ -33,7 +33,7 @@ import { closeProposal, databaseProposalReads, openProposalRows, openProposals,
import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, directUploads, errorCode, EXPIRED_UPLOAD, HOURLY_UPLOAD_BYTES, HOURLY_UPLOADS, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, MAX_FORM_ATTACHMENT_BYTES, objectKeyFor, peekType, PENDING_UPLOAD_PURPOSE, publicUrl, TOO_LARGE_MESSAGE, trimPrefix, typeFromHead, UPLOAD_LINK_MS,
type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'
import { FileLinks } from './fileLinks.js'
-import { randomBytes } from 'node:crypto'
+import { randomBytes, randomUUID } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
import { noteClaim, recordDeliveryCall } from '../lib/deliveryCalls.js'
@@ -65,6 +65,8 @@ import { clock, insertParts, loadActive, loadGroups, loadLightGroups, loadMachin
import { groupsBy, listingDrops, quietSince, readBy, withoutHints } from './parts/indexed.js'
import { autoJoinSwarms, machineSwarms, memberSwarms } from './swarmRows.js'
import type { MachineRename } from './machineRenames.js'
+import { movableEntry, otherAccountsOnComputer, sameComputerKey, type ComputerMove, type ComputerSignIn, type MachineKeys } from './computerMoves.js'
+import { activeMachineKeysOf } from '../lib/deviceKeyLog.js'
import { commitParts, indexesOf, machineContentChanged, numberMessages, type Touch, type Written } from './parts/commit.js'
import { loadDeliveryParts, ms } from './parts/light.js'
import { endSteps, ownerOf, stepEndedRows, stepsOf } from './steps.js'
@@ -339,6 +341,9 @@ async function abandonedStarts(tx: Transaction, tabId: string, state: SuperTabSt
}
export interface SuperTabStoreHooks {
+ /** Accounts' active machine keys, for a computer's move to the account signed in on it (computerMoves.ts sameComputerKey).
+ * Without it, their device key logs (lib/deviceKeyLog.ts). */
+ machineKeys?: MachineKeys
/** The client for reads that tolerate a few seconds of lag (lib/prisma.ts prismaSecondary, task #2970): older history
* pages and the costs report. Without it they read the store's own client. */
replica?: PrismaClient
@@ -624,6 +629,7 @@ export class SuperTabStore {
this.polls = hooks.polls ?? localPollMemory(now)
this.autoJoins = hooks.autoJoins ?? localAutoJoinMemory(now)
this.reports = hooks.reports ?? localReportMemory(now)
+ this.machineKeys = hooks.machineKeys ?? activeMachineKeysOf
this.native = new SuperTabNativeStore({
transaction: body => transaction(db, body),
load: (tx, user, tabId, groupIds) => this.load(tx, user, tabId, { groupIds }),
@@ -713,7 +719,7 @@ export class SuperTabStore {
if (target && target.machineId !== team && !onTeamAccount(state, target)) refuse(target)
}
switch (command.type) {
- case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.engineResume': case 'machine.projects':
+ case 'machine.contribute': case 'machine.pause': case 'machine.remove': case 'machine.moved': case 'machine.engineResume': case 'machine.projects':
case 'machine.ownAccountWork': case 'machine.access': return refuse()
case 'machine.cleaned': case 'tab.project': case 'agent.add':
if (command.machineId !== team) refuse()
@@ -776,6 +782,19 @@ export class SuperTabStore {
versions: Object.fromEntries(rows.flatMap(r => r.clientVersion ? [[r.machineId, r.clientVersion] as const] : [])) }
}
+ /** The Swarm's Macs whose owner's Harness Team account on it is not listed yet (machines.ts joiningTeamMacs): they read
+ * joining, not "not set up" (#3122). One read of those owners' Team machines on their account index; none with no Mac. */
+ async joiningTeams(tx: Transaction, state: SuperTabState): Promise<string[]> {
+ const macs = (state.machines ?? []).filter(m => !m.hostMachineId && !m.removal && !m.buddyOnly)
+ if (!macs.length) return []
+ const teams = await tx.machine.aggregateRaw({ pipeline: [
+ { $match: { userId: { $in: [...new Set(macs.map(m => m.contributorId))] }, sessionKind: 'team', hostMachineId: { $in: macs.map(m => m.machineId) },
+ autonomousEnv: state.environment, deletedAt: null } },
+ { $limit: 200 }, { $project: { _id: 0, machineId: 1, userId: 1, hostMachineId: 1 } }],
+ options: { hint: { userId: 1 } } }) as unknown as TeamMachineRow[]
+ return joiningTeamMacs(state, teams)
+ }
+
/** This Swarm's contributed machines that are also contributed to a Swarm of another Workspace: their Harness Team account
* takes no teammate's work here (machines.ts teamWorkRefusal). One indexed read of the machines' parts, one of rows. */
async otherWorkspaceMachines(tx: Transaction, state: SuperTabState): Promise<string[]> {
@@ -942,7 +961,7 @@ export class SuperTabStore {
// that read by dormant would not do: its index has no dormant, so it examines them all, and removals need them (design D8).
if ((command.type === 'agent.input' || command.type === 'agent.alert' || command.type === 'agent.rebind') && !ledProject(state, command.agentId)) agentIds.push(command.agentId)
if (command.type === 'agent.remove') startAgentIds.push(command.agentId)
- if (command.type === 'machine.remove') {
+ if (command.type === 'machine.remove' || command.type === 'machine.moved') {
const pool = state.machines?.find(m => m.machineId === command.machineId)
const machines = new Set([command.machineId, ...(pool ? state.machines!.filter(m => m.hostMachineId === pool.machineId).map(m => m.machineId) : [])])
agentIds.push(...state.agents.filter(a => machines.has(a.machineId)).map(a => a.id))
@@ -1316,12 +1335,13 @@ export class SuperTabStore {
const facts = visible.machines?.length ? await this.machineFacts(tx, state) : { team: [], versions: {} as Record<string, string> }
const teamMachines = facts.team
const otherWorkspace = visible.machines?.length ? await this.otherWorkspaceMachines(tx, state) : []
+ const joining = visible.machines?.length ? await this.joiningTeams(tx, state) : []
const slots = slotCounter(state)
return { lastChangedAt: await readLastChangedAt(tx, view, tabId) ?? 0, state: { ...visible, ...mentions, machines: visible.machines?.map(pool => {
const stored = state.machines!.find(m => m.machineId === pool.machineId)!
// Whether it takes teammates' projects now, and if not why (machines.ts teamWorkRefusal): what routing leaves it
// out for, and what Desktop can show on the machine.
- const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace)
+ const refusal = machineTeamWork(state, stored, now, teamMachines, otherWorkspace, joining)
const suspended = suspendedEngines(stored, now)
return { ...pool, availableSlots: availableSlots(state, stored, slots(stored)),
teamWork: refusal ? { allowed: false as const, ...refusal } : { allowed: true as const,
@@ -1379,7 +1399,7 @@ export class SuperTabStore {
if (!autonomousEnv || !person) { result.skipped++; continue }
const user: AuthUser = { sub: row.personId, email: person.email, autonomousEnv, role: 'user' }
await this.executeOnce(user, row.tabId, { operationId: `overdue-decision-${row.id}`, command: { type: 'decision.answer', decisionId: row.id, delegate: true } },
- undefined, undefined, false, true)
+ undefined, undefined, false, { overdue: true })
result.answered++
} catch (error) {
const code = error instanceof SuperTabError ? error.code : 'unknown'
@@ -1481,8 +1501,10 @@ export class SuperTabStore {
}
}
+ /** [only]: what the store alone may give a command: `overdue` for decision.answer (leaveOverdueDecisions), `movedTo` for
+ * machine.moved (computerSignedIn). */
private async executeOnce(user: AuthUser, tabId: string, input: { operationId: string; command: Command }, asAgentId?: string, hostMachineId?: string,
- workspaceLeave = false, overdue = false) {
+ workspaceLeave = false, only: { overdue?: boolean; movedTo?: { machineId: string; ownerId: string } } = {}) {
const { operationId, command } = operationSchema.parse(input)
const pushOrigin = await this.pushOriginFor(user, tabId, command)
let ended: WorkHold[] = [], started: WorkHold[] = []
@@ -1582,7 +1604,10 @@ export class SuperTabStore {
}
if (command.type !== 'invite.accept' && command.type !== 'agent.sessionClosed' && command.type !== 'machine.cleaned') author(original, actor)
const context: CommandContext = { operationId, now: this.now(), ...(leavingDeleted ? { workspaceLeave: true as const } : {}),
- ...(overdue && command.type === 'decision.answer' ? { overdue: true as const } : {}) }
+ ...(only.overdue && command.type === 'decision.answer' ? { overdue: true as const } : {}) }
+ if (command.type === 'machine.moved' && only.movedTo && actor.kind === 'person') {
+ context.computerMove = await this.computerMove(tx, original, actor.userId, command.machineId, only.movedTo)
+ }
if (command.type === 'swarm.restore' && original.deletion && original.workspaceId) {
const lost: string[] = []
for (const person of original.people) if (!await hasWorkspaceAccess(tx, original, person.id)) lost.push(person.id)
@@ -1942,7 +1967,7 @@ export class SuperTabStore {
if (start?.routeDecisionId) await closeUnassignedStart(tx, tabId, start.routeDecisionId, start.id, 'failed', context.now)
}
// Starts a removed machine failed, whether its owner removed it or left the Swarm with it, release their route holds.
- if (command.type === 'machine.remove' || command.type === 'member.remove' || command.type === 'swarm.delete') {
+ if (command.type === 'machine.remove' || command.type === 'machine.moved' || command.type === 'member.remove' || command.type === 'swarm.delete') {
for (const start of original.starts ?? []) {
if (!start.routeDecisionId || start.harnessId || start.error) continue
if (effects.state.starts?.find(s => s.id === start.id)?.error) {
@@ -3397,6 +3422,7 @@ export class SuperTabStore {
}
private readonly reports: ReportMemory
+ private readonly machineKeys: MachineKeys
/** The caller's own account row for the machine and the host checks that need no Swarm: once per report call, which a
* batch of readings shares (DB 2.5). */
@@ -4324,6 +4350,63 @@ export class SuperTabStore {
return renamed
}
+ /**
+ * Another account's sign-in on a computer (computerMoves.ts, #3122): each Swarm with an entry of the computer's previous
+ * accounts moves it to [signIn]'s machine, by the store-only machine.moved run as that entry's owner. One Swarm at a time;
+ * one that fails is logged and left to the next connect. With [write] false (the cleanup's dry run) nothing is written, and
+ * each entry is decided as machine.moved decides (computerMoves.ts movableEntry). The moves made, or that would be.
+ */
+ async computerSignedIn(signIn: ComputerSignIn, { write = true }: { write?: boolean } = {}): Promise<ComputerMove[]> {
+ const others = await otherAccountsOnComputer(this.db, signIn)
+ if (!others.length) return []
+ const to = await this.db.machine.findFirst({ where: { machineId: signIn.machineId, userId: signIn.ownerId, autonomousEnv: signIn.autonomousEnv, ...machineAlive },
+ select: { computerId: true, sessionKind: true } })
+ if (to?.computerId !== signIn.computerId || to.sessionKind === 'team') return []
+ const moves: ComputerMove[] = []
+ for (const from of others) {
+ // Only the computer's own key proves it is the same computer; machine.moved checks again in its transaction.
+ if (!await sameComputerKey(this.machineKeys, from, { userId: signIn.ownerId, machineId: signIn.machineId })) {
+ logger.warn('[swarm] a sign-in names a computer another account is on, without that computer\'s machine key: nothing moved',
+ { machineId: signIn.machineId, otherMachineId: from.machineId })
+ continue
+ }
+ const person = await this.db.user.findUnique({ where: { id: from.userId }, select: { email: true } })
+ if (!person) continue
+ const user: AuthUser = { sub: from.userId, email: person.email, autonomousEnv: signIn.autonomousEnv as AuthUser['autonomousEnv'], role: 'user' }
+ const move = { from: from.machineId, fromOwner: from.userId, to: signIn.machineId, toOwner: signIn.ownerId }
+ for (const tabId of await machineSwarms(this.db, signIn.autonomousEnv, from.machineId, MACHINE_RENAME_SWARMS)) {
+ try {
+ if (!write) {
+ const swarm = await this.db.superTab.findUnique({ where: { id: tabId }, select: SWARM_ROW })
+ if (!swarm || swarm.deletedAt) continue
+ const { state } = await loadRow(this.db as unknown as Transaction, requireParts(swarm))
+ if (movableEntry(state, from.machineId, from.userId, { machineId: signIn.machineId, ownerId: signIn.ownerId }, this.now())) moves.push({ tabId, ...move })
+ continue
+ }
+ const done = await this.executeOnce(user, tabId, { operationId: `computer-move-${randomUUID()}`, command: { type: 'machine.moved', machineId: from.machineId } },
+ undefined, undefined, false, { movedTo: { machineId: signIn.machineId, ownerId: signIn.ownerId } })
+ if (done.result.moved) moves.push({ tabId, ...move })
+ } catch (error) {
+ logger.warn('[swarm] a computer move did not reach a Swarm', { tabId, machineId: from.machineId, code: error instanceof SuperTabError ? error.code : 'unknown' })
+ }
+ }
+ }
+ return moves
+ }
+
+ /** The move [ownerId]'s entry [machineId] makes to [to], read from both account rows in this transaction: the same computer,
+ * two accounts, neither a Team sign-in. None otherwise, which machine.moved refuses. */
+ private async computerMove(tx: Transaction, state: SuperTabState, ownerId: string, machineId: string, to: { machineId: string; ownerId: string }):
+ Promise<CommandContext['computerMove']> {
+ if (ownerId === to.ownerId) return undefined
+ const row = (id: string, userId: string) => tx.machine.findFirst({ where: { machineId: id, userId, autonomousEnv: state.environment, ...machineAlive },
+ select: { computerId: true, sessionKind: true, name: true } })
+ const [from, next] = await Promise.all([row(machineId, ownerId), row(to.machineId, to.ownerId)])
+ if (!from?.computerId || from.computerId !== next?.computerId || from.sessionKind === 'team' || next.sessionKind === 'team') return undefined
+ if (!await sameComputerKey(this.machineKeys, { userId: ownerId, machineId }, { userId: to.ownerId, machineId: to.machineId })) return undefined
+ return { to: { ...to, name: accountMachineName(next) } }
+ }
+
/**
* What GitHub says of [watch], a pull request linked to the task [groupId] (pullRequestEvents.ts): each event its Engineer
* was not told yet goes to it as a message in the task, and every event is recorded there, in one write, so a retry or a
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index a4e4a328c..253ad6ed2 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -8,5 +8,5 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/overdueDecisions.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabPmSchedule.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
- 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
+ 'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabComputerMoves.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts', 'integration/superTabRequestReads.test.ts', 'integration/superTabVoiceMessages.test.ts', 'integration/superTabProjectChatWorkers.test.ts', 'integration/prismaQueryTiming.test.ts', 'integration/secondaryReads.test.ts', 'integration/pushDevices.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 8ee6d2786..214d1f4b5 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1209,7 +1209,7 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
const make = vi.fn(async () => ({ offer, decline: vi.fn() }))
const service = superTabService(fakeCore(), { teamSetup: make })
expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, owner)).toEqual({ ok: true, state: 'started' })
- expect(offer).toHaveBeenCalledWith('join', expect.any(Function), false)
+ expect(offer).toHaveBeenCalledWith('join', expect.any(Function), false, { signInAgain: false })
for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {
expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'join' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
}
@@ -1221,6 +1221,20 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
expect(offer).toHaveBeenCalledTimes(2)
})
+ it("signs the account in again only when the person's own Set up asks, where it serves another account (#3122)", async () => {
+ const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'started' as const }))
+ const service = superTabService(fakeCore(), { teamSetup: vi.fn(async () => ({ offer, decline: vi.fn() })) })
+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', signInAgain: true }, owner)
+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: true })
+ // Only Set up itself: a check, an automatic moment or anything but true signs nothing in again.
+ await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'manual', signInAgain: true }, owner)
+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), true, { signInAgain: false })
+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'join', signInAgain: true }, owner)
+ expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), false, { signInAgain: false })
+ await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual', signInAgain: 'yes' }, owner)
+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false })
+ })
+
it('tells only Desktop on this Mac why there is no account, asking nothing and starting nothing', async () => {
const offer = vi.fn(async () => ({ state: 'started' as const }))
const status = vi.fn(async () => ({ state: 'failed' as const, detail: 'launchd would not start it' }))
@@ -1245,7 +1259,7 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
mkdirSync(dirname(hostJournalFile(dataDir, 'machine-1')), { recursive: true })
writeFileSync(hostJournalFile(dataDir, 'machine-1'), '{}')
await service.requests.super_tabs({ action: 'teamSetup', reason: 'startup' }, owner)
- expect(offer).toHaveBeenCalledWith('startup', expect.any(Function), false)
+ expect(offer).toHaveBeenCalledWith('startup', expect.any(Function), false, { signInAgain: false })
})
it('says whether it is wanted without asking macOS, runs it when the person asks, and remembers "Not now"', async () => {
@@ -1253,9 +1267,9 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
const decline = vi.fn()
const service = superTabService(fakeCore(), { teamSetup: async () => ({ offer, decline }) })
expect(await service.requests.super_tabs({ action: 'teamSetupCheck', reason: 'join' }, owner)).toEqual({ ok: true, state: 'wanted' })
- expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), true)
+ expect(offer).toHaveBeenLastCalledWith('join', expect.any(Function), true, { signInAgain: false })
expect(await service.requests.super_tabs({ action: 'teamSetup', reason: 'manual' }, owner)).toEqual({ ok: true, state: 'started' })
- expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false)
+ expect(offer).toHaveBeenLastCalledWith('manual', expect.any(Function), false, { signInAgain: false })
expect(await service.requests.super_tabs({ action: 'teamSetupDecline' }, owner)).toEqual({ ok: true })
expect(decline).toHaveBeenCalledOnce()
for (const action of ['teamSetupCheck', 'teamSetupDecline']) {
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 05b6c507c..302130283 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -470,8 +470,11 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// Desktop names no Swarm and is offered as before.
if ((payload.reason === 'join' || payload.reason === 'contribute') && identifier(payload.tabId)
&& !await teamAccountsIn(sources(), payload.tabId)) return { ok: true, state: 'not-used' }
+ // `signInAgain`: Set up on a row the Swarm says has no Team account while this Mac has one, so it serves another account
+ // (#3122). Only the person's own Set up: a check or an automatic moment signs nothing in again.
+ const signInAgain = payload.action === 'teamSetup' && payload.reason === 'manual' && payload.signInAgain === true
return { ok: true, ...await (await setup()).offer(payload.reason as AutoSetupReason, () => sharedSwarm(sources()),
- payload.action === 'teamSetupCheck') }
+ payload.action === 'teamSetupCheck', { signInAgain }) }
}
if (payload.action === 'swarmRole') {
const grant = await port.swarmRole(String(payload.harnessId ?? ''))
diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.ts
index 8cfb8dcbd..4580a2f60 100644
--- a/cli/src/team/autoSetup.spec.ts
+++ b/cli/src/team/autoSetup.spec.ts
@@ -310,6 +310,18 @@ describe('a half-finished setup is repaired, not taken for done (#2765, Darren-M
expect((await both.auto.status()).detail).toBe('the team daemon is not running, and its privacy check has not passed')
})
+ it("with every part in place, signs the account in again for this Mac's account when Set up asks, where it serves another (#3122)", async () => {
+ const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
+ expect(await f.auto.offer('manual', async () => true, false, { signInAgain: true })).toEqual({ state: 'started' })
+ await f.auto.settled()
+ expect(f.deps.setup).toHaveBeenCalledWith(expect.any(Function), { signInAgain: true })
+ // Never on its own: an automatic moment, or Desktop's explanation, asks for no password.
+ const quiet = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
+ expect(await quiet.auto.offer('join', async () => true, false, { signInAgain: true })).toEqual({ state: 'exists' })
+ expect(await quiet.auto.offer('manual', async () => true, true, { signInAgain: true })).toEqual({ state: 'wanted' })
+ expect(quiet.deps.setup).not.toHaveBeenCalled()
+ })
+
it('with every part in place it is done: exists, and nothing runs', async () => {
const f = fake({ accountExists: vi.fn(async () => true), missing: async () => [] } as Partial<AutoSetupDeps>)
expect(await f.auto.offer('manual')).toEqual({ state: 'exists' })
diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.ts
index 50792a4a8..ce3078504 100644
--- a/cli/src/team/autoSetup.ts
+++ b/cli/src/team/autoSetup.ts
@@ -90,7 +90,7 @@ export interface AutoSetupDeps {
writeDecision(decision: TeamSetupDecision): void
/** `harness team setup --json`, as this account: its exit code and the JSON it answered (null when it said none).
* [progress] hears each step as it goes. */
- setup(progress?: (step: string) => void): Promise<{ code: number; result: Record<string, unknown> | null }>
+ setup(progress?: (step: string) => void, options?: { signInAgain?: boolean }): Promise<{ code: number; result: Record<string, unknown> | null }>
now(): number
log(line: string): void
/** Linux: whether the administrator prompt can be shown from here (pkexec and a desktop session, ./admin.ts
@@ -114,16 +114,19 @@ export class TeamAutoSetup {
* Starts the setup when it is wanted, and answers at once with why it did or did not; the prompt is macOS's. At `startup`
* it is wanted only while [sharedSwarm] says this Mac is in a Swarm with other people in it (false when it cannot say).
* With [check] it starts nothing and answers `wanted` instead, for Desktop to explain the account first.
+ * With [signInAgain] the person's own Set up signs an existing account in again for the account signed in here: the Swarm
+ * found it serving another account of this computer (#3122), which no part of it shows.
*/
- async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false, check = false): Promise<{ state: AutoSetupState }> {
- const state = await this.decide(reason, sharedSwarm, check)
+ async offer(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean> = async () => false, check = false,
+ { signInAgain = false }: { signInAgain?: boolean } = {}): Promise<{ state: AutoSetupState }> {
+ const state = await this.decide(reason, sharedSwarm, check, signInAgain)
// Every answer is said, not only a setup that starts: Macs in a Swarm went without the prompt and nothing on them said
// why (2026-10-27). A check that finds it wanted starts nothing: that is Desktop's question, not an answer.
if (state !== 'started' && state !== 'wanted') this.deps.log(`the Harness Team account was not offered (${reason}): ${state}`)
return { state }
}
- private async decide(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean>, check: boolean): Promise<AutoSetupState> {
+ private async decide(reason: AutoSetupReason, sharedSwarm: () => Promise<boolean>, check: boolean, signInAgain: boolean): Promise<AutoSetupState> {
const { deps } = this
// A Mac, a Linux and a Windows computer (docs/superpowers/plans/2026-10-28-harness-team-account-windows.md).
if (!teamLayout(deps.platform)) return 'unsupported'
@@ -134,7 +137,8 @@ export class TeamAutoSetup {
if (deps.readConfig() || await deps.accountExists(TEAM_USER)) {
// Done only when every part is there (#2765: an account with no daemon answered "already set up", and nothing
// repaired it). A part missing is repaired only when the person asks (Set up): no password is asked for on its own.
- if (!(await this.missing()).length) return 'exists'
+ const again = reason === 'manual' && signInAgain
+ if (!(await this.missing()).length && !again) return 'exists'
if (reason !== 'manual') return 'incomplete'
} else if (reason !== 'manual') {
const decision = deps.readDecision()
@@ -148,7 +152,7 @@ export class TeamAutoSetup {
if (deps.platform === 'linux' && deps.canPrompt && !deps.canPrompt()) return 'no-prompt'
if (check) return 'wanted'
if (this.running) return 'running'
- this.running = this.run().finally(() => { this.running = null })
+ this.running = this.run(reason === 'manual' && signInAgain).finally(() => { this.running = null })
return 'started'
}
@@ -184,7 +188,7 @@ export class TeamAutoSetup {
/** Waits for a setup this started, for a spec. */
settled(): Promise<void> { return this.running ?? Promise.resolve() }
- private async run(): Promise<void> {
+ private async run(signInAgain: boolean): Promise<void> {
const { deps } = this
deps.log(deps.platform === 'win32' ? 'setting up the Harness Team account: Windows asks for permission (User Account Control)'
: `setting up the Harness Team account: ${deps.platform === 'darwin' ? 'macOS' : 'the system'} asks for an administrator password`)
@@ -192,7 +196,7 @@ export class TeamAutoSetup {
this.step = null
let outcome: { code: number; result: Record<string, unknown> | null }
try {
- outcome = await deps.setup((step) => { this.step = step })
+ outcome = await deps.setup((step) => { this.step = step }, ...signInAgain ? [{ signInAgain: true }] : [])
} catch (error) {
outcome = { code: 1, result: { ok: false, code: 'SETUP_FAILED', message: error instanceof Error ? error.message : String(error) } }
}
@@ -266,11 +270,11 @@ export async function realTeamAutoSetup(dataDir: string, log: (line: string) =>
},
readDecision: () => readTeamSetupDecision(file),
writeDecision: (decision) => writeTeamSetupDecision(file, decision),
- setup: async (progress) => {
+ setup: async (progress, options) => {
const [{ teamCommand }, { teamCommandDeps }] = await Promise.all([import('./command.js'), import('./deps.js')])
const lines: string[] = []
const refuse = async (): Promise<never> => { throw new Error('setup does not restart the daemon') }
- const code = await teamCommand(['setup', '--json'], { ...teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }),
+ const code = await teamCommand(['setup', '--json', ...options?.signInAgain ? ['--sign-in-again'] : []], { ...teamCommandDeps({ stopDaemon: refuse, startDaemon: refuse }),
out: (line) => lines.push(line), err: (line) => lines.push(line), interactive: false, ...(progress ? { progress } : {}) })
const last = [...lines].reverse().find((line) => line.startsWith('{'))
let result: Record<string, unknown> | null = null
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index c01053bc3..d6029573c 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -2627,14 +2627,17 @@ class AppNotifier extends ChangeNotifier {
/// Starts the Harness Team account's setup on this Mac, the person having
/// asked: macOS's administrator prompt follows. Answers the daemon's state
/// (`started`, `exists`, `running`, ...), or `update` from a daemon too old
- /// to set it up from here.
- Future<String> setUpTeamAccount() async {
+ /// to set it up from here. With [signInAgain], an account already here is
+ /// signed in again for this account: the Swarm found it serving another
+ /// account of this computer (#3122).
+ Future<String> setUpTeamAccount({bool signInAgain = false}) async {
final here = _teamAccountHere();
if (here == null) return 'unsupported';
try {
final answer = await superTabMachineRequest(here, {
'action': 'teamSetup',
'reason': 'manual',
+ if (signInAgain) 'signInAgain': true,
});
return answer['state']?.toString() ?? 'started';
} on SuperTabFailure catch (failure) {
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index c1fca5b95..942911de3 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -1555,6 +1555,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
id: id,
name: name,
problem: problem,
+ history: superTabMachineHistory(shared, snapshot.people),
setUpTeam: setUpTeam,
setUpTeamLabel: superTabTeamSetupAction(_teamSetup),
owner: person,
@@ -2214,6 +2215,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
missing: _teamSetup?.state == 'incomplete'
? _teamSetup?.detail ?? ''
: null,
+ signInAgain: _teamSetup?.state == 'exists',
);
await _readTeamSetup();
}
@@ -2241,6 +2243,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
view.cleaning
? 'Cleaning up'
: superTabMachineStateLabel(view.status),
+ ?view.history,
?view.problem,
if (view.tip.isNotEmpty) view.tip,
].join(', '),
@@ -2829,6 +2832,7 @@ class _MachineView {
required this.subscriptionsAside,
required this.tip,
this.problem,
+ this.history,
this.setUpTeam = false,
this.setUpTeamLabel = 'Set up',
this.apiModels = const [],
@@ -2849,6 +2853,9 @@ class _MachineView {
/// Its one line when teammates' agents cannot run there ([superTabTeammatesPaused]); null otherwise.
final String? problem;
+
+ /// Who had this computer's row before (superTabMachineHistory); null for a row never moved.
+ final String? history;
final SuperTabPerson? owner;
final String? contributor;
final Map<String, dynamic>? shared;
@@ -2913,6 +2920,8 @@ String? superTabTeammatesPaused(Object? code) {
final why = switch (code) {
'MACHINE_OFFLINE' => 'Harness Team account offline',
'TEAM_ACCOUNT_REQUIRED' => 'not set up',
+ // Its owner's Harness Team account is on it and joins on the Mac's next poll (backend machines.ts, #3122).
+ 'TEAM_ACCOUNT_JOINING' => 'Harness Team is joining',
'PRIVACY_UNCHECKED' => 'privacy not checked yet',
'PRIVACY_CHECK_FAILED' => 'privacy check failed',
'PRIVACY_CHECK_STALE' => 'privacy check out of date',
@@ -2935,15 +2944,43 @@ String? superTabTeamSetupLine(({String state, String? detail})? setup) {
'incomplete' when detail != null && detail.isNotEmpty =>
'Harness Team is not finished ($detail)',
'incomplete' => 'Harness Team is not finished',
+ // The Swarm has no Team account for this row while this Mac has one: it serves another account of this computer,
+ // the one signed in here before (#3122).
+ 'exists' => 'Harness Team on this computer works for another account',
_ => null,
};
return why == null ? null : "Teammates' agents paused: $why";
}
-/// The row's button for this Mac's own setup: Repair when the account is there but a part of it is not (#2765), else
-/// Set up.
+/// The row's button for this Mac's own setup: Repair when the account is there but a part of it is not (#2765), or it
+/// works for another account (#3122), else Set up.
String superTabTeamSetupAction(({String state, String? detail})? setup) =>
- setup?.state == 'incomplete' ? 'Repair' : 'Set up';
+ setup?.state == 'incomplete' || setup?.state == 'exists'
+ ? 'Repair'
+ : 'Set up';
+
+/// Who had this computer's row before the account signed in on it now, and until when: "Was kelvin until 5 Nov"
+/// (backend machines.ts previousOwner, #3122). Null for a row never moved, or one whose person is not in the Swarm.
+String? superTabMachineHistory(
+ Map<String, dynamic>? pool,
+ List<SuperTabPerson> people, {
+ DateTime? now,
+}) {
+ final previous = pool?['previousOwner'];
+ if (previous is! Map) return null;
+ final person = people.where((p) => p.id == previous['personId']).firstOrNull;
+ final until = DateTime.tryParse(previous['until']?.toString() ?? '');
+ if (person == null || until == null) return null;
+ const months = [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', //
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
+ ];
+ final local = until.toLocal();
+ final year = local.year == (now ?? DateTime.now()).year
+ ? ''
+ : ' ${local.year}';
+ return 'Was ${person.shownName} until ${local.day} ${months[local.month - 1]}$year';
+}
/// One engine's allowance on a machine: its mark and remaining share on the row, its windows on hover.
class _Allowance {
@@ -3142,21 +3179,30 @@ class _MachineLine extends StatelessWidget {
child: text,
)
: text;
- final problem = view.problem;
- if (problem == null) return title;
+ final problem = view.problem, history = view.history;
+ if (problem == null && history == null) return title;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
title,
- Text(
- problem,
- key: ValueKey('super-machine-problem-${view.id}'),
- maxLines: 2,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.metadata(),
- ),
- if (onSetUpTeam != null)
+ if (history != null)
+ Text(
+ history,
+ key: ValueKey('super-machine-history-${view.id}'),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ if (problem != null)
+ Text(
+ problem,
+ key: ValueKey('super-machine-problem-${view.id}'),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(),
+ ),
+ if (problem != null && onSetUpTeam != null)
TextButton(
key: ValueKey('super-machine-team-setup-${view.id}'),
onPressed: onSetUpTeam,
diff --git a/desktop/lib/super_tabs/team_account_setup.dart b/desktop/lib/super_tabs/team_account_setup.dart
index ee4860567..3db79cea0 100644
--- a/desktop/lib/super_tabs/team_account_setup.dart
+++ b/desktop/lib/super_tabs/team_account_setup.dart
@@ -22,13 +22,15 @@ Future<void> showTeamAccountSetup(
bool asked = false,
String? operatingSystem,
String? missing,
+ bool signInAgain = false,
}) => showAppDialog<void>(
context: context,
barrierDismissible: false,
builder: (context) => _TeamAccountSetup(
app: app,
asked: asked,
- missing: missing,
+ missing: signInAgain ? 'it is signed in for another account' : missing,
+ signInAgain: signInAgain,
words: _Words.of(operatingSystem ?? RuntimePlatform.operatingSystem),
),
);
@@ -264,12 +266,16 @@ class _TeamAccountSetup extends StatefulWidget {
required this.asked,
required this.words,
this.missing,
+ this.signInAgain = false,
});
final AppNotifier app;
final bool asked;
final _Words words;
+ /// The account is there, signed in for another account of this computer (#3122): Repair signs it in for this one.
+ final bool signInAgain;
+
/// The account is there and these parts are not (cli/src/team/autoSetup.ts `missingDetail`, #2765): the dialog
/// repairs instead of setting up. Empty for a part it could not name.
final String? missing;
@@ -289,7 +295,9 @@ class _TeamAccountSetupState extends State<_TeamAccountSetup> {
final words = widget.words;
String outcome;
try {
- outcome = switch (await widget.app.setUpTeamAccount()) {
+ outcome = switch (await widget.app.setUpTeamAccount(
+ signInAgain: widget.signInAgain,
+ )) {
'started' || 'running' => words.started,
'exists' => words.exists,
'update' => words.update,
diff --git a/desktop/test/super_tab_computer_move_shots_test.dart b/desktop/test/super_tab_computer_move_shots_test.dart
new file mode 100644
index 000000000..11584be81
--- /dev/null
+++ b/desktop/test/super_tab_computer_move_shots_test.dart
@@ -0,0 +1,101 @@
+// Task #3122 (Scholes, 11-05): a computer moved from kelvin's account, whose Harness Team account still works for him, for
+// the pull request's pictures. Writes nothing unless COMPUTER_MOVE_SHOTS names a folder.
+import 'dart:io';
+
+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/super_tabs/machines.dart';
+
+import 'support/capture.dart';
+import 'support/rename_connection.dart';
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show createApp;
+
+final shots = Platform.environment['COMPUTER_MOVE_SHOTS'];
+
+class _TeamDaemon extends RenameConnection {
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
+ return Future.value({'ok': true, 'state': 'exists'});
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+
+ for (final brightness in Brightness.values) {
+ testWidgets('a moved computer\'s row in ${brightness.name}', (
+ tester,
+ ) async {
+ if (shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ tester.view.devicePixelRatio = 2;
+ tester.view.physicalSize = const Size(1240, 520);
+ addTearDown(tester.view.reset);
+ final daemon = _TeamDaemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'kelvin',
+ 'email': '[email protected]',
+ 'username': 'kelvin',
+ 'role': 'collaborator',
+ });
+ server.state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'MacBooks-MacBook-Pro-7',
+ 'contributorId': 'owner',
+ 'scope': 'swarm',
+ 'cwd': '/swarm',
+ 'engines': ['claude', 'codex'],
+ 'maxAgents': 4,
+ 'paused': false,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+ 'teamWork': {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_REQUIRED',
+ 'reason': 'Refused.',
+ },
+ 'previousOwner': {
+ 'personId': 'kelvin',
+ 'until': DateTime(
+ DateTime.now().year,
+ 11,
+ 5,
+ 12,
+ ).toUtc().toIso8601String(),
+ },
+ },
+ ];
+ final c = server.controller(account: 'owner');
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData(brightness: brightness),
+ home: Scaffold(
+ body: SuperTabMachines(controller: c, app: app, onAddAgent: (_) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'computer-move-${brightness.name}');
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ app.dispose();
+ });
+ }
+}
diff --git a/desktop/test/super_tab_computer_move_test.dart b/desktop/test/super_tab_computer_move_test.dart
new file mode 100644
index 000000000..bbd4c1fb2
--- /dev/null
+++ b/desktop/test/super_tab_computer_move_test.dart
@@ -0,0 +1,209 @@
+// One row per computer (#3122, Scholes 11-05): a computer signed in as another account shows once, under that account,
+// saying who it was before. Its Harness Team account may still serve the old account: the Swarm then says it has none,
+// while this Mac's daemon says it exists. The row says so in plain words, and Repair signs it in again for this account.
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/machines.dart';
+
+import 'support/rename_connection.dart';
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show createApp;
+
+/// This Mac's daemon: what it says of its Harness Team account, and every setup it is asked for.
+class _TeamDaemon extends RenameConnection {
+ Map<String, dynamic> status = {'ok': true, 'state': 'exists'};
+ final setups = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
+ return Future.value(status);
+ }
+ if (type == 'super_tabs' && payload['action'] == 'teamSetup') {
+ setups.add(Map.of(payload));
+ status = {'ok': true, 'state': 'running'};
+ return Future.value({'ok': true, 'state': 'started'});
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
+Map<String, dynamic> _pool({
+ Map<String, dynamic>? teamWork,
+ Map<String, dynamic>? previousOwner,
+}) => {
+ 'machineId': 'm',
+ 'name': 'MacBooks-MacBook-Pro-7',
+ 'contributorId': 'owner',
+ 'scope': 'swarm',
+ 'cwd': '/swarm',
+ 'engines': ['codex'],
+ 'maxAgents': 4,
+ 'paused': false,
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+ 'teamWork': teamWork ?? {'allowed': true},
+ 'previousOwner': ?previousOwner,
+};
+
+/// The owner's Swarm with kelvin, a teammate, who had this computer before.
+ConversationServer _swarm(Map<String, dynamic> pool) {
+ final server = ConversationServer();
+ (server.state['people'] as List).add({
+ 'id': 'kelvin',
+ 'email': '[email protected]',
+ 'username': 'kelvin',
+ 'role': 'collaborator',
+ });
+ server.state['machines'] = [pool];
+ return server;
+}
+
+Future<dynamic> _mount(
+ WidgetTester tester,
+ ConversationServer server, {
+ dynamic app,
+}) async {
+ final c = server.controller(account: 'owner');
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(controller: c, app: app, onAddAgent: (_) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<void> _unmount(WidgetTester tester, dynamic c) async {
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+}
+
+String? _text(WidgetTester tester, String key) {
+ final found = find.byKey(ValueKey(key));
+ return found.evaluate().isEmpty ? null : tester.widget<Text>(found).data;
+}
+
+void main() {
+ testWidgets(
+ 'a computer moved from another account says who had it, and until when',
+ (tester) async {
+ final until = DateTime(DateTime.now().year, 11, 5, 12);
+ final c = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ previousOwner: {
+ 'personId': 'kelvin',
+ 'until': until.toUtc().toIso8601String(),
+ },
+ ),
+ ),
+ );
+ expect(
+ _text(tester, 'super-machine-history-m'),
+ 'Was kelvin until 5 Nov',
+ );
+ await _unmount(tester, c);
+ // Never moved: nothing said.
+ final plain = await _mount(tester, _swarm(_pool()));
+ expect(_text(tester, 'super-machine-history-m'), isNull);
+ await _unmount(tester, plain);
+ },
+ );
+
+ testWidgets(
+ 'a Harness Team account serving another account reads so on this Mac\'s row, and Repair signs it in again for this account',
+ (tester) async {
+ final daemon = _TeamDaemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ final c = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_REQUIRED',
+ 'reason': 'Refused.',
+ },
+ ),
+ ),
+ app: app,
+ );
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team on this computer works for another account",
+ );
+ final repair = find.byKey(const ValueKey('super-machine-team-setup-m'));
+ expect(
+ find.descendant(of: repair, matching: find.text('Repair')),
+ findsOneWidget,
+ );
+
+ await tester.tap(repair);
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('team-account-setup-continue')));
+ await tester.pumpAndSettle();
+ expect(daemon.setups, [
+ {'action': 'teamSetup', 'reason': 'manual', 'signInAgain': true},
+ ]);
+ // Once the dialog closes, the row reads the daemon again: the setup is running now.
+ await tester.tap(find.byKey(const Key('team-account-setup-done')));
+ await tester.pumpAndSettle();
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: setting up",
+ );
+ await _unmount(tester, c);
+ app.dispose();
+ },
+ );
+
+ // Scholes, 11-05: right after Add machine the row read "not set up" with Set up for a few seconds, until the Mac's own
+ // Harness Team account joined the Swarm.
+ testWidgets('a Mac whose Harness Team account is joining says so, with no Set up', (
+ tester,
+ ) async {
+ final daemon = _TeamDaemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ final c = await _mount(
+ tester,
+ _swarm(
+ _pool(
+ teamWork: {
+ 'allowed': false,
+ 'code': 'TEAM_ACCOUNT_JOINING',
+ 'reason': 'Joining.',
+ },
+ ),
+ ),
+ app: app,
+ );
+ expect(
+ _text(tester, 'super-machine-problem-m'),
+ "Teammates' agents paused: Harness Team is joining",
+ );
+ expect(
+ find.byKey(const ValueKey('super-machine-team-setup-m')),
+ findsNothing,
+ );
+ await _unmount(tester, c);
+ app.dispose();
+ });
+
+ test("the row's button reads Repair for an account already here, Set up otherwise", () {
+ expect(superTabTeamSetupAction((state: 'exists', detail: null)), 'Repair');
+ expect(superTabTeamSetupAction((state: 'none', detail: null)), 'Set up');
+ });
+}
diff --git a/docs/plans/2026-11-05-one-row-per-computer-plan.md b/docs/plans/2026-11-05-one-row-per-computer-plan.md
new file mode 100644
index 000000000..5772c7771
--- /dev/null
+++ b/docs/plans/2026-11-05-one-row-per-computer-plan.md
@@ -0,0 +1,141 @@
+# One row per computer — Plan
+
+Written by the writing-plans skill's format; implemented by its Engineer task by task, test first (project instructions,
+Engineer). No Execution Handoff.
+
+**Goal:** A computer shows once in a Swarm's Machines, under the account signed in on it now. When another account signs
+in there, the computer's entry moves to that account: the old account's entry, its agents and its Team entry leave, the old
+owner is told, and the new entry says "Was kelvin until 5 Nov". Existing duplicates are cleaned once. A Mac whose Harness
+Team account still serves the old account says so, and Set up repairs it.
+
+**Architecture:** Account rows (`Machine`) are per account and computer (`MachineService.resolveOrCreateForComputer`); the
+computer is `Machine.computerId`, a random id minted once in `~/.harness/computer-id` and stamped on every connect
+(`lib/adapterWs.ts`). A connect that is not a Team session tells the Swarm code, as a rename does (`machineRenames.ts`
+→ `store.machineRenamed`): new `computerMoves.ts` → `store.computerSignedIn`. The store finds the other accounts' live rows
+on that computer (new index), the Swarms each is in (`machineSwarms`), and in each runs the store-only command
+`machine.moved` as that entry's old owner, with `context.computerMove` it read itself. The one-time cleanup runs the same
+store call for the newest-connected row of every computer that has rows of two or more accounts.
+The Team half: Desktop's row already gets `TEAM_ACCOUNT_REQUIRED` from the server for the new account's Mac while the
+local daemon answers `exists` (its Team account serves the old account). That pair now reads "Harness Team on this Mac
+works for another account" with Repair, which runs `harness team setup --json --sign-in-again` behind the system's
+administrator prompt: the Team account signs in for the account here, the old Team sign-in is ended, and the row updates
+when its new Team entry reports.
+
+**Tech Stack:** Fastify backend, Prisma on MongoDB, vitest; Flutter Desktop (widget tests, memory store, fake sign-in);
+CLI TypeScript (node:test specs).
+
+**Spec:** Task #3122 (Scholes, 11-05; #3118 folded in).
+
+## Global Constraints
+
+- One way: the move reuses the removal of agents and Team entries `machine.remove` does (`removeMachine` in
+ commands.ts), never a second copy of it.
+- Nothing from a client decides a move: which entries share a computer, who owns each and whether one is online are
+ read by the store from account rows and the Swarm's own readings. `machine.moved` sent by a client is refused.
+- An entry with a fresh reading is never moved (two live accounts on one computer id is no switch).
+- Nothing granted to the old owner carries over: projects, own-account choice, Lent ledger, engine failures, the week
+ told, shares (per machine id already). The new entry is Team-account-only (teammates' work only through a Team account
+ whose privacy check passed), as Desktop's join adds a computer.
+- A moved entry records no removal of the person's (`removedMachines`) and no folder cleanup for the old host: the
+ computer and its Swarm folders stay; the new account's host serves them.
+- Production write: the cleanup script is dry-run by default; `--write` only in the release Ken says go for.
+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in; nothing signs the Mac out.
+
+## Review Focus (two security reviews)
+
+- Who can take over a computer's entry: nobody by its id. The computer id is self-declared, so a move also needs both
+ accounts' device key logs to hold the same machine key for their machines (computerMoves.ts sameComputerKey): the
+ key is the computer's own (`identity.json`, untouched by sign-ins) and every add is self-signed for one account, so
+ only a holder of its private key can list it under a second one (security review 1 of #3100).
+- Whether the old owner's agents, Team entry, grants or Team sign-in survive a switch.
+- That `machine.moved` cannot be sent from outside the store.
+
+## Design (feature design rules)
+
+- **Growth:** `previousOwner` is one `{ personId, until }` per entry, replaced by the next move, gone with the entry. The
+ new index has one key per account row, deleted with it.
+- **Concurrency:** one Swarm transaction per move, through `executeOnce` (revision check and retry), as renames go one
+ Swarm at a time.
+- **Read cost:** a connect reads one indexed query (`machines` by `computerId`); only when another account's row is
+ there, the Swarm index by machine id (`machineSwarms`, capped at 500); only those Swarms load.
+- **Scale (10x):** rows per computer stay a handful. First warning: the per-Swarm failure log line
+ (`[swarm] a computer move did not reach a Swarm`), and connect time, which does not wait for the move.
+- **Compatibility:** `previousOwner` is a new optional field; older clients ignore it. Older Desktops still show one
+ row once the move happens. `--sign-in-again` exists in released CLIs; an older daemon ignores Desktop's new
+ `signInAgain` flag and answers `exists` as today, so its dialog says "already set up" until the CLI updates.
+- **Migration + rollback:** the index is created by `db push` in the release; rolling back leaves an unused index
+ (harmless) or drops it. The cleanup prints every entry it moves as JSON; rollback is the owner's Add machine, or
+ restoring those entries from that output.
+- **Audience:** the server derives every fact; only the store sets `context.computerMove`.
+- **Identity:** each account's work runs only under its own login; the moved entry is the new account's own machine.
+- **Failure:** a Swarm that fails is logged and retried by the next connect; groups whose agents left say so; the old
+ owner is told; a Repair that fails says why on the row.
+- **Platforms:** backend (Linux); Desktop on macOS (row, Repair); CLI on macOS, Linux and Windows (Team sign-in again).
+
+## Tasks
+
+### 1. Index and lookup of a computer's other accounts
+**Files:** `backend/prisma/schema.prisma`, `backend/src/superTabs/computerMoves.ts` (new), its test, integration plan
+test.
+**Interfaces:** `otherAccountsOnComputer(db, { computerId, ownerId, autonomousEnv }) → Array<{ machineId, userId }>`
+(live, remote, not Team rows).
+- [ ] Failing test: rows of another account on the same computer are found; the owner's own, Team rows, deleted rows,
+ other computers and other environments are not.
+- [ ] Code + `@@index([computerId])`; integration test reads the plan: IXSCAN on it.
+
+### 2. `machine.moved`: one Swarm's entry moves (backend commands)
+**Files:** `backend/src/superTabs/commands.ts`, `machines.ts` (`previousOwner` on `ContributedMachine`),
+`computerMoves.test.ts`.
+- [ ] Failing tests:
+ - another account's sign-in leaves exactly one entry, the new account's, with `previousOwner` naming the old owner and
+ the time; its name, folder, engines, slots and pause carried; Team-account-only;
+ - the old owner's agents on it and on its Team entry are removed, their groups told, a task with no agent says so, a
+ pending start fails; the old owner gets one line in their Buddy chat;
+ - none of the old owner's grants carry over (projects, own-account choice, Lent, told week);
+ - an entry with a fresh reading is not moved; an entry being removed is not moved;
+ - a new account that is not in the Swarm: the old entry goes, nothing is added; a machine the new account took out
+ (`removedMachines`) is not added; the per-person machine limit holds;
+ - sent by a client (no store context), it is refused; run twice, the second changes nothing.
+- [ ] Code: the command, reusing `removeMachine` (no cleanup record, no `removedMachines`).
+
+### 3. Connect tells the Swarms (backend store + adapter)
+**Files:** `backend/src/superTabs/computerMoves.ts`, `store.ts` (`computerSignedIn`), `routes/superTabs.ts`
+(listener), `lib/adapterWs.ts` (one call after the connect write, not awaited, never for a Team session).
+- [ ] Failing test (store, memory DB): kelvin's entry in two Swarms, ttkhoahcmus connects on the same computer → each
+ Swarm has one entry, ttkhoahcmus's, and kelvin is told in each; a second connect changes nothing.
+- [ ] Code.
+
+### 4. One-time cleanup of existing duplicates
+**Files:** `backend/scripts/swarm-computer-moves/run.ts` (new), its test.
+- [ ] Failing test: a Swarm with the three entries of the reported Mac (kelvin, ttkhoahcmus, kelvin's Team entry) ends
+ with ttkhoahcmus's alone; run again, nothing changes; dry run writes nothing.
+- [ ] Code: computers with rows of two or more accounts (aggregation on the new index), newest `lastSeenAt` wins,
+ `store.computerSignedIn` for it.
+
+### 5. Desktop: history note, and a Team account serving another account
+**Files:** `desktop/lib/super_tabs/machines.dart`, `desktop/lib/super_tabs/model.dart` if needed, tests in
+`desktop/test/super_tab_team_machine_test.dart` and a machines row test.
+- [ ] Failing widget tests: a row with `previousOwner` says "Was kelvin until 5 Nov"; a row the server marks
+ `TEAM_ACCOUNT_REQUIRED` whose daemon says `exists` reads "Teammates' agents paused: Harness Team on this Mac works for
+ another account" with Repair; Repair asks the daemon to sign the Team account in again; after it the row reads the new
+ status.
+- [ ] Code. Light and dark screenshots for the pull request.
+
+### 6. CLI: Set up signs the Team account in again when asked
+**Files:** `cli/src/superTabs/service.ts` (`teamSetup` action takes `signInAgain`), `cli/src/team/autoSetup.ts`
+(`offer` runs setup with `--sign-in-again` when the account exists), specs.
+- [ ] Failing spec: a manual offer with `signInAgain` on an existing account runs `team setup --json --sign-in-again`
+ and answers `started`; without it, `exists` as today.
+- [ ] Code.
+
+### 7. Old account's sessions on the computer — open, not in this pull request
+- [x] Checked: another account's `harness login --force` stops the daemon, and the new daemon's Swarm host polls and
+ serves only its own machine id (`host-<machineId>.json`), so no work reaches the old account's sessions and the Swarm
+ has removed their agents (task 2). Not verified: whether their processes stay up idle until the computer restarts.
+ Stopping another machine id's sessions from the new host reaches into the daemon's session ownership; proposed to the
+ PM as a follow-up rather than built here.
+
+## Evidence for the pull request
+
+Red/green per task in a pull request comment; backend unit suite in CI; CLI team specs and Desktop widget tests on macOS
+run locally; screenshots of the changed rows in light and dark.