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
Batch I: #2022 #2060 (#2061)
0xken157441acd2221e
diff --git a/backend/integration/harnessSharesList.test.ts b/backend/integration/harnessSharesList.test.tsindex d482372df..a6202f4e7 100644--- a/backend/integration/harnessSharesList.test.ts+++ b/backend/integration/harnessSharesList.test.ts@@ -16,10 +16,17 @@ import { poolRows } from './hostRows.test-support.js'// The harness shares list (routes/harnessShares.ts) against a Swarm-sized database. Prod 2026-10-28: CLI daemons' list calls// took half the backend's busy time in spike minutes (p95 13.4 s), each share loading its whole Swarm to check it. Every// permission read here is real; Redis is replaced by "every machine is running".-const shared = vi.hoisted(() => ({ db: null as unknown as PrismaClient }))+const shared = vi.hoisted(() => ({ db: null as unknown as PrismaClient, busyTabs: new Set<string>() }))vi.mock('../src/lib/prisma.js', async original => ({ ...await original<typeof import('../src/lib/prisma.js')>(), get prisma() { return shared.db } }))vi.mock('../src/lib/bus.js', async original => ({ ...await original<typeof import('../src/lib/bus.js')>(),getAgentPresenceMany: async (ids: string[]) => new Map(ids.map(id => [id, 'running'])) }))+// A Swarm named in `busyTabs` answers its cached reads as a Swarm under a lock answers them: busy (retry.ts).+vi.mock('../src/superTabs/cachedReads.js', async original => {+ const real = await original<typeof import('../src/superTabs/cachedReads.js')>()+ const { fail } = await import('../src/superTabs/model.js')+ return { ...real, readParts: (...args: Parameters<typeof real.readParts>) => shared.busyTabs.has(args[2])+ ? fail('SWARM_BUSY', 'This Swarm is busy. Try again in a moment.', 503) : real.readParts(...args) }+})const { harnessShareRoutes } = await import('../src/routes/harnessShares.js')const { SuperTabStore } = await import('../src/superTabs/store.js')@@ -211,11 +218,11 @@ describe('the harness shares list as permissions change', () => {const shares: Record<string, { name: string; to: AuthUser }> = {}/** Adds agent `name` to `conversationId` on the host's machine through the owner's grant, and shares it with both members. *//** Shares session `harnessId` on `machine`, as `claimedOwner` names it, with both members, under agent name `name`. */- const shareWithBoth = async (name: string, machine: string, harnessId: string, claimedOwner: AuthUser) => {+ const shareWithBoth = async (name: string, machine: string, harnessId: string, claimedOwner: AuthUser, superTabId: string | null = tab) => {for (const to of [a, b]) {const id = randomUUID()shares[id] = { name, to }- await db.harnessShare.create({ data: { id, superTabId: tab, ownerId: claimedOwner.sub, machineId: machine, agentId: harnessId,+ await db.harnessShare.create({ data: { id, superTabId, ownerId: claimedOwner.sub, machineId: machine, agentId: harnessId,recipientEmail: to.email, autonomousEnv: 'prod', name, ownerPublicKey: 'fixture-key', expiresAt: new Date(Date.now() + 86_400_000), revokedAt: null } })}}@@ -241,7 +248,7 @@ describe('the harness shares list as permissions change', () => {expect((await store.openableShares(as, rows)).map(share => share.id).sort(), `${as.email}: the store's batch and each share alone`).toEqual([...alone].sort())return mine.filter(id => listed.has(id)).map(id => shares[id]!.name).sort().join('')}- return { tab, run, agents, sees, shared, shareWithBoth, n }+ return { tab, run, agents, sees, shared, shareWithBoth, n, shares }}/** Marks agent `agentId` of this Swarm confidential in another Swarm too, as a registration there would have left it. */@@ -359,4 +366,41 @@ describe('the harness shares list as permissions change', () => {await shareWithBoth('B', 'a-mac', harnessId, a)expect([await sees(a), await sees(b)]).toEqual(['BXYZ', 'XYZ'])})++ /** Another Swarm of the owner whose Lead L runs on the owner's machine, with L's part written before the confidential mark+ * existed (projects.ts markConfidential): the list learns L is confidential only by reading that Swarm. */+ async function otherSwarmWithUnmarkedLead(n: number) {+ const other = (await store.create(owner, randomUUID(), `Other ${n}`)).id+ const harnessId = `perm-${n}-L`+ const lead = (await store.execute(owner, other, { operationId: randomUUID(), command: { type: 'agent.add', conversationId: 'lead',+ machineId: 'own-host', harnessId, name: 'Lead', configuration: AGENT_CONFIGURATION, lead: true } })).result.agentId as string+ const part = await database.db.swarmAgent.findFirstOrThrow({ where: { tabId: other, key: lead } })+ const { confidential: _mark, ...unmarked } = part.data as Record<string, unknown>+ await database.db.swarmAgent.update({ where: { id: part.id }, data: { data: unmarked as object } })+ return { other, harnessId }+ }++ it('hides a Lead of another Swarm whose part was never marked, read from that Swarm', async () => {+ const { n, sees, shareWithBoth } = await swarmWithShares()+ const { harnessId } = await otherSwarmWithUnmarkedLead(n)+ await shareWithBoth('L', 'own-host', harnessId, owner, null)+ expect([await sees(a), await sees(b)]).toEqual(['XYZ', 'XYZ'])+ })++ it('hides only the shares a busy other Swarm would answer for, and lists the rest', async () => {+ const { tab, n, agents, shareWithBoth, shares } = await swarmWithShares()+ const { other, harnessId } = await otherSwarmWithUnmarkedLead(n)+ await shareWithBoth('L', 'own-host', harnessId, owner, null)+ // X is registered in the other Swarm too, unmarked, as a part written before the mark would be: only that Swarm can say.+ const { id, ...x } = await database.db.swarmAgent.findFirstOrThrow({ where: { tabId: tab, key: agents.X! } })+ const { confidential: _mark, ...unmarked } = x.data as Record<string, unknown>+ await database.db.swarmAgent.create({ data: { ...x, id: `elsewhere-${id}`, tabId: other, data: unmarked as object } })+ // Each share asked alone would throw while that Swarm is busy (mayOpenShare), so this Swarm's shares are named by hand.+ const names = async (as: AuthUser) => listedIds(await list(as)).filter(id => shares[id]?.to === as).map(id => shares[id]!.name).sort().join('')+ expect([await names(a), await names(b)]).toEqual(['XYZ', 'XYZ'])+ shared.busyTabs.add(other)+ try {+ expect([await names(b), await names(a)]).toEqual(['YZ', 'YZ'])+ } finally { shared.busyTabs.delete(other) }+ })})diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.tsindex 6b2a184bd..07457deb0 100644--- a/backend/integration/superTabIndexes.test.ts+++ b/backend/integration/superTabIndexes.test.ts@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'-import { pageDeliveries, pageReactions } from '../src/superTabs/pageReads.js'+import { inConversationOrder, pageDeliveries, pageReactions } from '../src/superTabs/pageReads.js'import { recentDecisions } from '../src/superTabs/routeDecisions.js'import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'import { revokeNativeContexts } from '../src/superTabs/native.js'@@ -129,6 +129,35 @@ describe('message page reads', () => {})})+describe('the delivery poll order', () => {+ const at = new Date(T0), later = new Date(T0 + 1000)+ const row = (messageId: string, conversationId: string, createdAt = at) => ({ messageId, conversationId, createdAt })+ beforeAll(async () => {+ await db.superTabMessage.createMany({ data: [['O-c1-1', 'c1', 1], ['O-c1-2', 'c1', 2], ['O-c1-3', 'c1', 3], ['O-c1-4', 'c1', 4],+ ['O-c2-7', 'c2', 7], ['O-c2-8', 'c2', 8]].map(([id, conversationId, sequence]) => ({ id: id as string, tabId: 'O',+ conversationId: conversationId as string, sequence: sequence as number, author: { kind: 'person', id: 'owner' }, text: 'm', recipientIds: ['agent-0'] })) })+ })++ it('puts each conversation\'s tied rows in sequence order in that conversation\'s places, reading only the tied messages by id', async () => {+ const read = [row('O-c1-3', 'c1'), row('O-c2-8', 'c2'), row('O-c1-1', 'c1'), row('O-c1-4', 'c1', later), row('O-c2-7', 'c2'), row('O-c1-2', 'c1')]+ const [rows, profile] = await profiled('SuperTabMessage', () => inConversationOrder(db, 'O', read))+ expect(rows.map(r => r.messageId)).toEqual(['O-c1-1', 'O-c2-7', 'O-c1-2', 'O-c1-4', 'O-c2-8', 'O-c1-3'])+ expect(profile).toEqual({ plans: ['IXSCAN { _id: 1 }'], docsExamined: 5, returned: 5 })+ })++ it('reads nothing when no conversation has two rows at one time', async () => {+ const read = [row('O-c1-2', 'c1'), row('O-c2-7', 'c2'), row('O-c1-1', 'c1', later)]+ const [rows, profile] = await profiled('SuperTabMessage', () => inConversationOrder(db, 'O', read))+ expect(rows).toEqual(read)+ expect(profile).toEqual({ plans: [], docsExamined: 0, returned: 0 })+ })++ it('never orders by another Swarm\'s messages: rows whose messages it does not find keep their places', async () => {+ const read = [row('O-c1-2', 'c1'), row('O-c1-1', 'c1')]+ expect((await inConversationOrder(db, 'B', read)).map(r => r.messageId)).toEqual(['O-c1-2', 'O-c1-1'])+ })+})+describe('the delivery pass', () => {it('reads the open deliveries through the status index, examining only those it judges, with their dates as Dates', async () => {const open = ['queued', 'claimed', 'uncertain'].map((status, i) => ({ _id: `A-open-${i}`, tabId: 'A', conversationId: 'g1', messageId: 'A-m900',diff --git a/backend/integration/superTabLiveness.test.ts b/backend/integration/superTabLiveness.test.tsindex 641338248..03bfdc1c3 100644--- a/backend/integration/superTabLiveness.test.ts+++ b/backend/integration/superTabLiveness.test.ts@@ -811,6 +811,43 @@ describe('the delivery poll of an agent with nothing waiting', () => {// Hosts read an idle agent's deliveries only every 30 s once the server pushes (stability roadmap 2.4): each new one is// announced to the machine its agent runs on, once its write commits, so the host reads it at once.describe('the push for a new delivery', () => {+ it('keeps several messages batched for one recipient in conversation order, including equal timestamps', async () => {+ const f = await swarm()+ const assignments: string[] = []+ for (const title of ['Parser', 'Renderer', 'Exporter']) {+ const group = String((await f.execute({ type: 'conversation.create', title, brief: 'Build it',+ checks: [{ description: 'Built', independent: false }] })).result.conversationId)+ // Without the Lead in these groups, each loss is delivered in the same project chat.+ await f.execute({ type: 'conversation.agent', conversationId: group, agentId: f.lead, present: false, lead: false })+ const worker = await f.add(group, 'test-host', randomUUID(), title)+ assignments.push(String((await f.execute({ type: 'work.assign', conversationId: group, agentId: worker })).result.assignmentId))+ }+ f.clock.now += 6 * MINUTE+ // Each loss notice is named by its task and the time of the loss (this poll).+ const expectedIds = assignments.map(assignment => stableId(stableId('work-lost', assignment, String(f.clock.now)), 'lead'))+ // One poll expires all three assignments and inserts their messages/deliveries together.+ const first = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))+ expect(first).toHaveLength(3)+ expect(new Set(first.map(row => row.messageId))).toEqual(new Set(expectedIds))+ expect(new Set(first.map(row => row.createdAt.getTime())).size).toBe(1)+ const page = (await f.timed.messages(owner, f.tab, 'lead', {})).messages.filter(row => expectedIds.includes(row.id))+ expect(page).toHaveLength(3)+ expect(page[1]!.sequence).toBe(page[0]!.sequence + 1)+ expect(page[2]!.sequence).toBe(page[1]!.sequence + 1)+ expect(first.map(row => row.messageId)).toEqual(page.map(row => row.id))++ // Make the tie explicit, and store the rows later sequence first so insertion order cannot stand in for it, then read again.+ const tiedAt = new Date('2026-10-28T00:00:00.000Z')+ const stored = await db.superTabDelivery.findMany({ where: { tabId: f.tab, messageId: { in: expectedIds } } })+ await db.superTabDelivery.deleteMany({ where: { tabId: f.tab, messageId: { in: expectedIds } } })+ for (const id of [...page.map(row => row.id)].reverse()) {+ await db.superTabDelivery.create({ data: { ...stored.find(row => row.messageId === id)!, createdAt: tiedAt } })+ }+ const again = (await f.timed.deliveries(host, f.tab, f.lead)).filter(row => expectedIds.includes(row.messageId))+ expect(again.map(row => row.createdAt)).toEqual([tiedAt, tiedAt, tiedAt])+ expect(again.map(row => row.messageId)).toEqual(page.map(row => row.id))+ })+const announcing = () => {const waiting: Array<{ machineId: string; tabId: string; agentId: string }> = []return { waiting, hooks: { deliveriesWaiting: (w: { machineId: string; tabId: string; agentId: string }) => { waiting.push(w) } } }diff --git a/backend/src/middlewares/errorHandler.ts b/backend/src/middlewares/errorHandler.tsindex a404ee698..146fc833b 100644--- a/backend/src/middlewares/errorHandler.ts+++ b/backend/src/middlewares/errorHandler.ts@@ -3,9 +3,9 @@ import { AppError, ValidationError } from '../errors/index.js'import { sendError } from '../utils/response.js'import { logger } from '../utils/logger.js'import { SuperTabError } from '../superTabs/model.js'+import { RETRYABLE_SWARM_CODES } from '../superTabs/retry.js'/** The Swarm 503s that waiting fixes. Others (no attachment store, no picture uploads) are this server's setup. */-const RETRYABLE_SWARM_CODES = new Set(['SWARM_BUSY', 'SWARM_MIGRATING'])/** How long a busy answer asks the caller to wait: just past the Swarm transaction's longest backoff (1.5 s). */const BUSY_RETRY_AFTER_SECONDS = 2diff --git a/backend/src/superTabs/confidential.ts b/backend/src/superTabs/confidential.tsindex c34793e46..2c91e8493 100644--- a/backend/src/superTabs/confidential.ts+++ b/backend/src/superTabs/confidential.ts@@ -1,5 +1,6 @@import type { Prisma } from '@prisma/client'-import type { Agent, SuperTabState } from './model.js'+import { SuperTabError, type Agent, type SuperTabState } from './model.js'+import { RETRYABLE_SWARM_CODES } from './retry.js'import { loadActive, reassemble } from './parts/index.js'import { confidentialSession, sessionKey, type OtherRegistrations } from './projects.js'import { bindSession, sessionRecordId } from './sessionScope.js'@@ -14,9 +15,11 @@ type Transaction = Prisma.TransactionClient* Swarm's readers while it is that Swarm's current Lead (projects.ts watchClosed), which is why a Swarm asks about the others.*//** `stateOf` gives a Swarm's active parts with these agents' groups, as loadActive in `tx` does; a read outside a transaction may- * give the read cache's (cachedReads.ts readParts gives the same parts), uncopied, as nothing here changes it. */+ * give the read cache's (cachedReads.ts readParts gives the same parts), uncopied, as nothing here changes it. With `busyClosed`,+ * a Swarm too busy to read (retry.ts) closes the sessions asked of it, as unknown, and is named to it; without, its answer throws. */export async function confidentialSessions(tx: Transaction, agentIds: string[], exceptTabId?: string,- stateOf: (tabId: string, agentIds: string[]) => Promise<SuperTabState> = async (tabId, ids) => reassemble(await loadActive(tx, tabId, { agentIds: ids }))): Promise<Set<string>> {+ stateOf: (tabId: string, agentIds: string[]) => Promise<SuperTabState> = async (tabId, ids) => reassemble(await loadActive(tx, tabId, { agentIds: ids })),+ busyClosed?: (tabId: string) => void): Promise<Set<string>> {const found = new Set<string>()if (!agentIds.length) return found// One $in scan of the key index, and only the mark: Prisma's `in` is planned as one index scan per id, and `data` is the whole agent.@@ -32,7 +35,15 @@ export async function confidentialSessions(tx: Transaction, agentIds: string[],for (const [tabId, keys] of unmarked) {const pending = keys.filter(key => !found.has(key))if (!pending.length) continue- const state = await stateOf(tabId, pending)+ let state: SuperTabState+ try {+ state = await stateOf(tabId, pending)+ } catch (error) {+ if (!busyClosed || !(error instanceof SuperTabError) || !RETRYABLE_SWARM_CODES.has(error.code)) throw error+ for (const key of pending) found.add(key)+ busyClosed(tabId)+ continue+ }for (const target of state.agents) if (pending.includes(target.id) && confidentialSession(state, target)) found.add(target.id)}return founddiff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex 463ce6c58..deb376b7c 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -28,3 +28,30 @@ export async function pageDeliveries(tx: Transaction, tabId: string, messageIds:receipt: (row.receipt ?? null) as string | null, holdReason: (row.holdReason ?? null) as string | null, holdSince: date(row.holdSince),deliveredAt: date(row.deliveredAt), answeredAt: date(row.answeredAt), createdAt: date(row.createdAt)!, updatedAt: date(row.updatedAt)! }))}++/** An agent's open deliveries, read by creation time, with each conversation's tied rows put in its message order. One+ * write's deliveries share a creation time, and Mongo breaks that tie by insertion order alone. Each conversation keeps its+ * places among the others; only tied rows have their messages' sequences read. */+export async function inConversationOrder<T extends Pick<SuperTabDelivery, 'conversationId' | 'messageId' | 'createdAt'>>(+ tx: Transaction, tabId: string, rows: T[]): Promise<T[]> {+ const ties = new Map<string, number[]>()+ rows.forEach((row, index) => {+ const key = `${row.conversationId}\0${row.createdAt.getTime()}`+ ties.set(key, [...ties.get(key) ?? [], index])+ })+ const tied = [...ties.values()].filter(places => places.length > 1)+ if (!tied.length) return rows+ // Matched by id alone: with tabId in the match, the planner can cover it from the tabId+conversationId+sequence index+ // and walk every message key of the Swarm. The Swarm is checked here instead.+ const found = await tx.superTabMessage.aggregateRaw({ pipeline: [+ { $match: { _id: { $in: tied.flat().map(index => rows[index]!.messageId) } } }, { $project: { tabId: 1, sequence: 1 } }] }) as+ unknown as Array<{ _id: string; tabId: string; sequence: number }>+ const sequence = new Map(found.filter(message => message.tabId === tabId).map(message => [message._id, message.sequence]))+ const ordered = [...rows]+ for (const places of tied) {+ const group = places.map(index => rows[index]!)+ .sort((a, b) => (sequence.get(a.messageId) ?? Infinity) - (sequence.get(b.messageId) ?? Infinity))+ places.forEach((index, at) => { ordered[index] = group[at]! })+ }+ return ordered+}diff --git a/backend/src/superTabs/retry.ts b/backend/src/superTabs/retry.tsindex bcf6682c9..c210da1f7 100644--- a/backend/src/superTabs/retry.ts+++ b/backend/src/superTabs/retry.ts@@ -1,5 +1,8 @@import { fail } from './model.js'+/** A Swarm's answers that say "try again" rather than "no": busy after its retries, or moving to its new store. */+export const RETRYABLE_SWARM_CODES: ReadonlySet<string> = new Set(['SWARM_BUSY', 'SWARM_MIGRATING'])+const TRANSACTION_ATTEMPTS = 8const EXPIRED_TRANSACTION_ATTEMPTS = 2const TRANSACTION_BACKOFF_MS = 50diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex e0a590991..01d87f3bd 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -11,7 +11,7 @@ import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMITimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { pageDeliveries, pageReactions } from './pageReads.js'+import { inConversationOrder, pageDeliveries, pageReactions } from './pageReads.js'import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl, trimPrefix,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'import { randomBytes } from 'node:crypto'@@ -288,6 +288,10 @@ export class GrantReads {}}+/** Another Swarm too busy to say whether a shared session is confidential there: the list hides those shares and lists the rest,+ * as a busy load of a share's own Swarm hides its shares (Lead, review of #1973), rather than failing every share. */+const busyListing = (tabId: string) => logger.warn('[super-tab] shares list: a busy Swarm hid the shares it could not answer for', { tabId })+export class SuperTabStore {readonly native: SuperTabNativeStorereadonly workspaces: SwarmWorkspaces@@ -1980,7 +1984,8 @@ export class SuperTabStore {async openableShares<T extends { superTabId: string | null; machineId: string; agentId: string; ownerId: string }>(user: AuthUser, shares: T[]): Promise<T[]> {const key = (share: T) => stableId(share.machineId, share.agentId)// An ordinary share: never of a session confidential in any Swarm, but for its machine's person.- const anywhere = await confidentialSessions(this.db, shares.filter(s => !s.superTabId && user.sub !== s.ownerId).map(key), undefined, this.cachedState)+ const anywhere = await confidentialSessions(this.db, shares.filter(s => !s.superTabId && user.sub !== s.ownerId).map(key), undefined, this.cachedState,+ busyListing)const byTab = new Map<string, T[]>()for (const share of shares) if (share.superTabId) byTab.set(share.superTabId, [...byTab.get(share.superTabId) ?? [], share])const observable = new Set<T>()@@ -2011,7 +2016,7 @@ export class SuperTabStore {}const targets = shares.map(share => state.agents.find(a => a.machineId === share.machineId && a.harnessId === share.agentId && a.machineOwnerId === share.ownerId))// Confidential in another Swarm closes it here too; in this one, its current Lead stays open to readers (projects.ts watchClosed).- const elsewhere = await confidentialSessions(this.db, targets.flatMap(t => t ? [t.id] : []), tabId, this.cachedState)+ const elsewhere = await confidentialSessions(this.db, targets.flatMap(t => t ? [t.id] : []), tabId, this.cachedState, busyListing)const allowed: T[] = []for (const [i, share] of shares.entries()) {const target = targets[i]@@ -2139,8 +2144,8 @@ export class SuperTabStore {await this.save(tx, loaded, state, clock.next(), [...judgedMachines(loaded.state, state, written), ...stoppedMachines(state, idle),...woken ? [{ kind: 'agent' as const, key: agentId }] : []])await this.writeMessages(tx, tabId, state, written, sequences, true)- const rows = await tx.superTabDelivery.findMany({ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } },- orderBy: { createdAt: 'asc' }, take: 100 })+ const rows = await inConversationOrder(tx, tabId, await tx.superTabDelivery.findMany({+ where: { tabId, agentId, status: { in: [...OPEN_DELIVERY] } }, orderBy: { createdAt: 'asc' }, take: 100 }))const allowed: SuperTabDelivery[] = []for (const delivery of rows) {if (this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)) allowed.push(delivery)