The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(swarm): a host read checks each machine, share, contributor and Workspace membership once, not once per agent (#2013)
0xken159a32a9b3fcbe
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 92586281f..e107d6bdc 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -2539,6 +2539,70 @@ describe('Lead safety on the host roster', () => {})})+describe('grant checks of the host roster', () => {+ /** A machine of `host`'s shared with the owner and peer, and a Swarm of the owner's with the peer in it, on its own+ * machine so no other test's Swarm shows up in its host reads. */+ async function sharedMachine() {+ const machineId = `grants-${randomUUID()}`+ await db.machine.create({ data: { machineId, userId: host.sub, apiKey: `fixture-${machineId}`, managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })+ await db.machineShare.create({ data: { machineId, ownerId: host.sub, autonomousEnv: 'prod', emails: [owner.email, peer.email] } })+ const tab = (await store.create(owner, randomUUID(), 'Grants')).id+ await invite(tab)+ const add = async (tabId: string, name: string, by: AuthUser, lead = false) => (await run(tabId, { type: 'agent.add', conversationId: 'lead', machineId,+ harnessId: randomUUID(), name, configuration: config, lead }, by)).result.agentId as string+ return { machineId, tab, add }+ }+ /** Each database call a host read makes, as `Model.operation`, through a store on a client that counts them. */+ function counted() {+ const calls: string[] = []+ const client = db.$extends({ query: { $allModels: { async $allOperations({ model, operation, args, query }) {+ calls.push(`${model}.${operation}`)+ return query(args)+ } } } }) as unknown as PrismaClient+ const count = (call: string) => calls.filter(c => c === call).length+ return { store: new SuperTabStore(client), count }+ }+ const agentIds = (rows: Array<{ tabId: string; agent?: { id: string } }>, tab: string) => rows.filter(r => r.tabId === tab && r.agent).map(r => r.agent!.id).sort()++ it('reads the machine, its share, and each contributor and their Workspace membership once per host read, not once per agent', async () => {+ const { machineId, tab, add } = await sharedMachine()+ const agents = [await add(tab, 'Lead', owner, true)]+ for (let i = 0; i < 4; i++) agents.push(await add(tab, `Owner worker ${i}`, owner))+ for (let i = 0; i < 3; i++) agents.push(await add(tab, `Peer worker ${i}`, peer))+ const { store: counting, count } = counted()+ expect(agentIds(await rosterRows(counting, host, machineId), tab)).toEqual(agents.sort())+ // Eight agents of two contributors on one machine: the read's own machine check, one share, two people, two memberships.+ expect({ machines: count('Machine.findFirst'), shares: count('MachineShare.findUnique'), contributors: count('User.findUnique'),+ memberships: count('SwarmWorkspaceMember.findUnique') }).toEqual({ machines: 1, shares: 1, contributors: 2, memberships: 2 })+ })++ it('still drops only the rows of a contributor whose share was revoked', async () => {+ const { machineId, tab, add } = await sharedMachine()+ const mine = [await add(tab, 'Lead', owner, true), await add(tab, 'Owner worker', owner)]+ await add(tab, 'Peer worker 1', peer)+ await add(tab, 'Peer worker 2', peer)+ const before = await db.machineShare.findUniqueOrThrow({ where: { machineId } })+ await db.machineShare.update({ where: { machineId }, data: { emails: [owner.email], grantVersions: nextMachineShareGrants(before, [owner.email], null) } })+ expect(agentIds(await rosterRows(counted().store, host, machineId), tab)).toEqual(mine.sort())+ })++ it('still drops a contributor\'s rows only in the Swarms of the Workspace they left', async () => {+ const { machineId, tab, add } = await sharedMachine()+ const mine = [await add(tab, 'Lead', owner, true), await add(tab, 'Owner worker', owner)]+ await add(tab, 'Peer worker 1', peer)+ await add(tab, 'Peer worker 2', peer)+ // The peer's own Swarm, in the peer's own Workspace, on the same machine.+ const theirs = (await store.create(peer, randomUUID(), 'Peer Swarm')).id+ const peers = [await add(theirs, 'Peer Lead', peer, true), await add(theirs, 'Peer helper', peer)]+ const workspaceId = (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).workspaceId!+ expect((await db.superTab.findUniqueOrThrow({ where: { id: theirs } })).workspaceId).not.toBe(workspaceId)+ await db.swarmWorkspaceMember.update({ where: { id: `${workspaceId}:${peer.sub}` }, data: { removedAt: new Date() } })+ const rows = await rosterRows(counted().store, host, machineId)+ expect(agentIds(rows, tab)).toEqual(mine.sort())+ expect(agentIds(rows, theirs)).toEqual(peers.sort())+ })+})+describe('the Lead reads and types in an agent terminal', () => {async function terminalFixture() {const { tab, lead } = await fixture()diff --git a/backend/src/superTabs/read/host.ts b/backend/src/superTabs/read/host.tsindex aaf97be6d..120bd3fb7 100644--- a/backend/src/superTabs/read/host.ts+++ b/backend/src/superTabs/read/host.ts@@ -10,7 +10,7 @@ import { machineAlive } from '../../lib/prisma.js'import { isTeamSession } from '../../lib/teamSession.js'import { machineBillingAllowsDataPlane } from '../../lib/billingState.js'import { fail, type AgentStart, type SuperTabState } from '../model.js'-import type { SuperTabStore } from '../store.js'+import { GrantReads, type SuperTabStore } from '../store.js'import type { CacheView } from '../cache.js'import { readLastChangedAt, readMachines } from '../cachedReads.js'import * as parts from '../parts/index.js'@@ -55,6 +55,8 @@ export class HostReads {await this.store.hostFor(tx, user, machineId)const owned = await tx.machine.findFirst({ where: { machineId, userId: user.sub, autonomousEnv: user.autonomousEnv, ...machineAlive } })if (!owned || !machineBillingAllowsDataPlane(owned)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)+ // Every agent's grant check of this read shares one read of each machine, share, contributor and Workspace membership.+ const grants = new GrantReads(owned)// Swarms still in one row are migrated when first opened; the job migrates every one before the new release serves.const ids = (await tx.superTab.findMany({ where: { autonomousEnv: user.autonomousEnv, format: 2,OR: [{ machineIds: { has: machineId } }, { cleanupMachineIds: { has: machineId } }] },@@ -75,7 +77,7 @@ export class HostReads {const inputs = await cached.get(tabId, 'host:inputs', 'main', () => this.inputs(tx, tabId))if (!full && held && inputs && held.slice(ROW_HASH) === inputs) { tabs.push({ tabId, lastChangedAt, etag: held, unchanged: true as const }); continue }const state = await this.tabState(tx, cached, tabId, machineId)- const rows = await hostTab(tabId, state, machineId, user, lastChangedAt, await this.lookups(tx, state, teams))+ const rows = await hostTab(tabId, state, machineId, user, lastChangedAt, await this.lookups(tx, state, teams, grants))const etag = rows.etag + (inputs ?? '')// The host already holds these rows: say so instead of sending them again.tabs.push(held?.slice(0, ROW_HASH) === rows.etag ? { tabId, lastChangedAt, etag, unchanged: true as const } : { ...rows, etag })@@ -161,10 +163,10 @@ export class HostReads {.digest('base64url').slice(0, ROW_HASH)}- private async lookups(tx: Transaction, state: SuperTabState, teams: Array<{ machineId: string }>): Promise<HostLookups> {+ private async lookups(tx: Transaction, state: SuperTabState, teams: Array<{ machineId: string }>, grants: GrantReads): Promise<HostLookups> {const people = await tx.user.findMany({ where: { id: { in: state.people.map(p => p.id) }, autonomousEnv: state.environment }, select: { id: true, email: true } })const confidential = await confidentialSessions(tx, state.agents.map(a => a.id), state.id)- return { people, confidential, teams, githubApp: !!this.options.githubApp, agentGrant: target => this.store.agentGrant(tx, state, target) }+ return { people, confidential, teams, githubApp: !!this.options.githubApp, agentGrant: target => this.store.agentGrant(tx, state, target, grants) }}/** Swarms whose record of this machine changed since the cursor and that no longer list it. */diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex a7142f17b..0e888e57f 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -1,6 +1,6 @@import { contributedEngines, expireRemovals, LASTING_TEAM_REFUSALS, machineContribution, machineObservationSchema, machineSlots, machineTeamWork, observedPrivacy, recordAgentPresence, removalPreview, startPreparing, swarmGridRow, teamAccountRequired, teamWorkRefusal, type MachineObservation } from './machines.js'import { createHash } from 'node:crypto'-import type { Prisma, PrismaClient, SuperTabDelivery, SuperTabMessage } from '@prisma/client'+import type { Machine, Prisma, PrismaClient, SuperTabDelivery, SuperTabMessage } from '@prisma/client'import type { AuthUser } from '../lib/ssoAuth.js'import { machineAlive } from '../lib/prisma.js'import { isTeamSession, teamMachine, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../lib/teamSession.js'@@ -278,6 +278,30 @@ export function localPollMemory(now: () => number): PollMemory {const routeDecisionOf = (command: Command): string | undefined => command.type === 'decision.answer' ? undefined: 'decisionId' in command ? command.decisionId : 'routeDecisionId' in command ? command.routeDecisionId : undefined+const machineKey = (environment: string, machineId: string, ownerId: string) => `machine:${environment}:${machineId}:${ownerId}`++/**+ * What agent grant checks read, kept for one request only. A host read checks every agent on its machine, mostly for the+ * same few contributors: without this each agent cost its machine, share, contributor and Workspace membership again+ * (4 point queries per agent on a shared machine, Diego's review 2026-10-28). Never kept past the request, so a revoked+ * share or a Workspace removal drops the rows on the next read, as before.+ */+export class GrantReads {+ private readonly answers = new Map<string, Promise<unknown>>()+ /** `machine`: a live machine the request already read with the grant's own filter (machineAlive), its host's. */+ constructor(machine?: Machine) {+ if (machine) this.answers.set(machineKey(machine.autonomousEnv, machine.machineId, machine.userId), Promise.resolve(machine))+ }++ once<T>(key: string, read: () => Promise<T>): Promise<T> {+ const known = this.answers.get(key) as Promise<T> | undefined+ if (known) return known+ const answer = read()+ this.answers.set(key, answer)+ return answer+ }+}+export class SuperTabStore {readonly native: SuperTabNativeStorereadonly workspaces: SwarmWorkspaces@@ -544,15 +568,17 @@ export class SuperTabStore {/** Shared with the read API (superTabs/read, design section 7.2). *//** Every path that serves an agent's host checks this, so it also holds the Workspace check: the agent acts for its* contributor, who must still be in the Swarm's Workspace. Its host need not be, as it need not be in the Swarm. */- async agentGrant(tx: Transaction, state: SuperTabState, target: Agent): Promise<void> {- await requireWorkspaceAccess(tx, state, target.contributorId)- const machine = await tx.machine.findFirst({ where: { machineId: target.machineId, userId: target.machineOwnerId,- autonomousEnv: state.environment, ...machineAlive } })+ /** `reads`: one request's reads, shared by every agent it checks (GrantReads). */+ async agentGrant(tx: Transaction, state: SuperTabState, target: Agent, reads?: GrantReads): Promise<void> {+ const once = <T>(key: string, read: () => Promise<T>) => reads ? reads.once(key, read) : read()+ await requireWorkspaceAccess(tx, state, target.contributorId, reads)+ const machine = await once(machineKey(state.environment, target.machineId, target.machineOwnerId), () => tx.machine.findFirst({+ where: { machineId: target.machineId, userId: target.machineOwnerId, autonomousEnv: state.environment, ...machineAlive } }))if (!machine || !machineBillingAllowsDataPlane(machine)) fail('HOST_UNAVAILABLE', 'This execution host is unavailable.', 403)if (target.contributorId !== machine.userId) {person(state, target.contributorId)- const contributor = await tx.user.findUnique({ where: { id: target.contributorId }, select: { email: true, autonomousEnv: true } })- const share = await tx.machineShare.findUnique({ where: { machineId: machine.machineId } })+ const contributor = await once(`user:${target.contributorId}`, () => tx.user.findUnique({ where: { id: target.contributorId }, select: { email: true, autonomousEnv: true } }))+ const share = await once(`share:${machine.machineId}`, () => tx.machineShare.findUnique({ where: { machineId: machine.machineId } }))if (!contributor || contributor.autonomousEnv !== state.environment || !share || share.ownerId !== machine.userId ||share.autonomousEnv !== state.environment || !sharedVia(share, contributor.email) ||machineShareGrant(share, contributor.email) !== target.hostGrant) {diff --git a/backend/src/superTabs/workspaceStore.ts b/backend/src/superTabs/workspaceStore.tsindex a3f5d40cf..0192e66db 100644--- a/backend/src/superTabs/workspaceStore.ts+++ b/backend/src/superTabs/workspaceStore.ts@@ -26,14 +26,15 @@ export async function activeMember(tx: Transaction | PrismaClient, workspaceId:const checked = new WeakMap<object, Map<string, boolean>>()/** Whether the person is still in the Swarm's Workspace; a Swarm from before Workspaces passes until the switch is on. Read once- * per person per transaction, which reads one snapshot. */-export async function hasWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string): Promise<boolean> {+ * per person per transaction, which reads one snapshot, or per `request` when its caller names one (a host read's GrantReads). */+export async function hasWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string, request?: object): Promise<boolean> {if (!state.workspaceId) return !workspacesRequired()- // Remembered only within a transaction. A read outside one (the read cache's, cache.ts) runs on the process's own client,- // which lives as long as the process: an answer kept on it would outlive the person's removal.- if (typeof (tx as { $transaction?: unknown }).$transaction === 'function') return !!await activeMember(tx, state.workspaceId, userId)- const answers = checked.get(tx) ?? new Map<string, boolean>()- checked.set(tx, answers)+ // Remembered only within a transaction or the request named. A read outside both (the read cache's, cache.ts) runs on the+ // process's own client, which lives as long as the process: an answer kept on it would outlive the person's removal.+ const scope = request ?? (typeof (tx as { $transaction?: unknown }).$transaction === 'function' ? null : tx)+ if (!scope) return !!await activeMember(tx, state.workspaceId, userId)+ const answers = checked.get(scope) ?? new Map<string, boolean>()+ checked.set(scope, answers)const key = memberId(state.workspaceId, userId)const known = answers.get(key)if (known !== undefined) return known@@ -44,8 +45,8 @@ export async function hasWorkspaceAccess(tx: Transaction, state: Pick<SuperTabSt/** The one Workspace check of every Swarm read and command (design, Audience): the person must still be in the Swarm's Workspace.* Reading the Swarm needs its own membership as well, which the caller checks as before. */-export async function requireWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string): Promise<void> {- if (await hasWorkspaceAccess(tx, state, userId)) return+export async function requireWorkspaceAccess(tx: Transaction, state: Pick<SuperTabState, 'workspaceId'>, userId: string, request?: object): Promise<void> {+ if (await hasWorkspaceAccess(tx, state, userId, request)) returnfail(WORKSPACE_ACCESS_REVOKED, state.workspaceId ? `You are no longer in this Swarm's ${WORKSPACE_LABEL}.` : `This Swarm has no ${WORKSPACE_LABEL} yet.`, 403)}