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): the decisions badge counts exactly what the reader can open, reading ids only (#1825)
0xken15714cafea6896
diff --git a/backend/integration/superTabRead.test.ts b/backend/integration/superTabRead.test.tsindex d9aff4fce..fd8606de1 100644--- a/backend/integration/superTabRead.test.ts+++ b/backend/integration/superTabRead.test.ts@@ -15,6 +15,7 @@ import * as parts from '../src/superTabs/parts/index.js'import { guardedWrite } from '../src/superTabs/parts/write.js'import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import { SwarmReads } from '../src/superTabs/read/service.js'+import { decisionsWaiting } from '../src/superTabs/decisions.js'import { HostReads } from '../src/superTabs/read/host.js'import type { Conversation, SuperTabState } from '../src/superTabs/model.js'import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'@@ -748,6 +749,42 @@ describe('decisions asked of one person (v2)', () => {expect((await get(`/api/super-tabs/${s.tabId}/parts`, owner)).body.data.derived.decisionsDigest).toBe(left.decisionsDigest)})+ it('counts every open decision the reader can open, past 200, reading only which ones and where', async () => {+ const s = await scene()+ clock = Date.now()+ // 150 in finished work gone quiet, which the peer still reads; then 100 newer in a conversation they have left, quiet too:+ // both are read for their access fields alone, and the left one is filtered on those.+ await writeGroup(s.tabId, s.web, Date.now(), group => { group.archived = true; group.dormant = true })+ await writeGroup(s.tabId, s.privateId, Date.now(), group => { group.audience = { people: [] }; group.dormant = true })+ const asked = (conversationId: string, n: number, from: number) => Array.from({ length: n }, (_, i) => ({ id: `${conversationId}-${i}`,+ tabId: s.tabId, batchId: `${conversationId}-batch`, projectId: 'lead', conversationId, assignmentId: null, personId: peer.sub,+ askerAgentId: s.lead, question: `Question ${i}?`, options: ['Yes', 'No'], recommended: 0, unblocks: 'The release', createdAt: new Date(from + i) }))+ await db.superTabDecision.createMany({ data: [...asked(s.web, 150, NOW), ...asked(s.privateId, 100, NOW + 1000)] })+ expect((await get(`/api/super-tabs/${s.tabId}/parts`, peer)).body.data.derived.decisionsWaiting).toBe(150)++ const reads: unknown[] = [], whole: string[] = [], quiet: Array<{ key: string; data: Record<string, unknown> }> = []+ const counted = db.$extends({ query: {+ superTabDecision: { async findMany({ args, query }) { reads.push(args); return query(args) } },+ swarmGroup: {+ async findMany({ args, query }) { const rows = await query(args); whole.push(...rows.map(row => row.key)); return rows },+ async aggregateRaw({ args, query }) { const rows = await query(args); quiet.push(...rows as unknown as typeof quiet); return rows },+ },+ } })+ const waiting = await counted.$transaction(async tx => {+ const state = parts.reassemble(await parts.loadActive(tx, s.tabId))+ whole.length = 0+ return decisionsWaiting(tx, s.tabId, state, { kind: 'person', userId: peer.sub, email: peer.email })+ })+ expect(waiting.count).toBe(150)+ // Neither what they ask nor a cap; and each quiet conversation's access fields, not its whole record.+ expect(reads).toEqual([expect.objectContaining({ select: { id: true, conversationId: true } })])+ expect(reads[0]).not.toHaveProperty('take')+ expect(whole).toEqual([])+ expect(quiet.map(row => row.key).sort()).toEqual([s.web, s.privateId].sort())+ for (const row of quiet) expect(['id', 'kind', 'projectId', 'audience']).toEqual(expect.arrayContaining(Object.keys(row.data)))+ expect(quiet.find(row => row.key === s.privateId)!.data).toEqual({ id: s.privateId, projectId: 'lead', audience: { people: [] } })+ })+it('keeps one answer when two arrive at once, returns the same receipt for a retried answer, and refuses a person removed from the Swarm', async () => {const s = await scene()clock = Date.now()diff --git a/backend/src/superTabs/decisions.ts b/backend/src/superTabs/decisions.tsindex 07b87008a..5cd203f2a 100644--- a/backend/src/superTabs/decisions.ts+++ b/backend/src/superTabs/decisions.ts@@ -121,28 +121,39 @@ function readerWhere(state: SuperTabState, actor: Actor): Prisma.SuperTabDecisioreturn { OR: [{ askerAgentId: actor.agentId }, ...led ? [{ projectId: led.id }] : []] }}+/** What an access check reads of a conversation (projects.ts canReadGroup). */+const ACCESS_FIELDS = ['id', 'kind', 'projectId', 'audience'] as const+/** The conversations [ids] names: those the read loaded, and the rest (quiet, archived, or left out of a light read) read- * here, so a decision in one still counts. A deleted conversation is none. */-async function conversationsOf(tx: Tx, tabId: string, state: SuperTabState, ids: string[]): Promise<Map<string, Conversation>> {- const found = new Map(state.conversations.filter(c => ids.includes(c.id)).map(c => [c.id, c]))- const missing = [...new Set(ids.filter(id => !found.has(id)))]- if (missing.length) {- for (const row of await tx.swarmGroup.findMany({ where: { tabId, key: { in: missing }, deleted: false }, select: { key: true, data: true } })) {- found.set(row.key, row.data as unknown as Conversation)- }- }+ * here, so a decision in one still counts. With [only], the rest bring only those fields. A deleted conversation is none. */+async function conversationsOf(tx: Tx, tabId: string, state: SuperTabState, ids: string[],+ only?: readonly string[]): Promise<Map<string, Conversation>> {+ const named = new Set(ids)+ const found = new Map(state.conversations.filter(c => named.has(c.id)).map(c => [c.id, c]))+ const missing = [...named].filter(id => !found.has(id))+ if (!missing.length) return found+ const rows = only+ ? await tx.swarmGroup.aggregateRaw({ pipeline: [{ $match: { tabId, deleted: false, key: { $in: missing } } },+ { $project: { _id: 0, key: 1, ...Object.fromEntries(only.map(field => [`data.${field}`, 1])) } }] }) as unknown as Array<{ key: string; data: unknown }>+ : await tx.swarmGroup.findMany({ where: { tabId, key: { in: missing }, deleted: false }, select: { key: true, data: true } })+ for (const row of rows) found.set(row.key, row.data as Conversation)return found}+/** Checked at every read, for agents too: a reader who can no longer read the conversation no longer reads its decisions. */+const readableIn = (state: SuperTabState, actor: Actor, groups: Map<string, Conversation>, conversationId: string) => {+ const group = groups.get(conversationId)+ return group && canReadGroup(state, actor, group) ? group : undefined+}+/** ponytail: capped at 200 per state, newest first; page it if a reader ever has more. */async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Actor, open: boolean) {const rows = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), open ? waiting : { answeredAt: { not: null } }] },orderBy: { createdAt: 'desc' }, take: 200 })const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId))return rows.flatMap(row => {- const group = groups.get(row.conversationId)- // Checked at every read, for agents too: a reader who can no longer read the conversation no longer reads its decisions.- return group && canReadGroup(state, actor, group) ? [{ row, group }] : []+ const group = readableIn(state, actor, groups, row.conversationId)+ return group ? [{ row, group }] : []})}@@ -155,10 +166,14 @@ export async function waitingInProject(tx: Tx, tabId: string, projectId: string)}/** A person's open decisions: how many, and a digest of which. A client reads its list again when the digest moves, as- * when one is answered elsewhere and another asked, which leaves the count alone (review of #1820). Never what they ask. */+ * when one is answered elsewhere and another asked, which leaves the count alone (review of #1820). Read on every poll, so+ * only each one's id and conversation, and each quiet conversation's access fields: never what they ask, nor a brief. Not+ * capped: a cap counted rows the reader cannot open and left out ones they can, so the badge undercounted. */export async function decisionsWaiting(tx: Tx, tabId: string, state: SuperTabState,actor: Extract<Actor, { kind: 'person' }>): Promise<{ count: number; digest: string }> {- const ids = (await readable(tx, tabId, state, actor, true)).map(({ row }) => row.id).sort()+ const rows = await tx.superTabDecision.findMany({ where: { tabId, AND: [readerWhere(state, actor), waiting] }, select: { id: true, conversationId: true } })+ const groups = await conversationsOf(tx, tabId, state, rows.map(r => r.conversationId), ACCESS_FIELDS)+ const ids = rows.filter(row => readableIn(state, actor, groups, row.conversationId)).map(row => row.id).sort()return { count: ids.length, digest: createHash('sha256').update(ids.join('\n')).digest('base64url').slice(0, 16) }}