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-03 b2002: #2721 (#2823)

0xken15780877f4fd2a
diff --git a/backend/integration/superTabTagsClear.test.ts b/backend/integration/superTabTagsClear.test.ts
new file mode 100644
index 000000000..937bce51b
--- /dev/null
+++ b/backend/integration/superTabTagsClear.test.ts
@@ -0,0 +1,237 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import Fastify, { type FastifyInstance } from 'fastify'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import { migrateSwarm } from '../src/superTabs/migration/migrate.js'
+import * as parts from '../src/superTabs/parts/index.js'
+import { swarmTransaction } from '../src/superTabs/cache.js'
+import { guardedWrite } from '../src/superTabs/parts/write.js'
+import { SwarmReads } from '../src/superTabs/read/service.js'
+import { HostReads } from '../src/superTabs/read/host.js'
+import { buddyChatId } from '../src/superTabs/buddies.js'
+import { stableId, type Author, type Conversation, type SuperTabState } from '../src/superTabs/model.js'
+import { writeLegacySwarm } from '../scripts/swarm-parts/legacy.js'
+import { NOW, outsider as outsiderActor, owner as ownerActor, peer as peerActor, swarm } from '../src/superTabs/read/fixture.test-support.js'
+import { resolveByAnswer } from '../src/superTabs/mentions.js'
+import { plan, profiled } from './plans.test-support.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let app: FastifyInstance
+let store: SuperTabStore
+const user = (actor: { userId: string; email: string }): AuthUser => ({ sub: actor.userId, email: actor.email, autonomousEnv: 'prod', role: 'user' })
+const [owner, peer, outsider] = [ownerActor, peerActor, outsiderActor].map(user) as [AuthUser, AuthUser, AuthUser]
+const signedIn = (authorization: string | undefined) => [owner, peer, outsider].find(u => `Bearer ${u.sub}` === authorization)
+const MIGRATED = NOW - 60_000
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_tags_clear_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ for (const each of [owner, peer, outsider]) await db.user.create({ data: { id: each.sub, externalId: `fixture-${each.sub}`, email: each.email, autonomousEnv: 'prod' } })
+ // The owner's own machine runs the Swarm's agents, so the owner may write as them.
+ await db.machine.create({ data: { machineId: 'host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ store = new SuperTabStore(db)
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ app.addHook('onRequest', async (request, reply) => {
+ const found = signedIn(request.headers.authorization)
+ if (!found) return reply.code(401).send({ success: false })
+ request.user = found
+ })
+ await app.register(superTabRoutes, { store, github: null, reads: new SwarmReads(store), hosts: new HostReads(store) })
+ await app.ready()
+})
+afterAll(async () => {
+ await app?.close()
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+/** A Swarm in parts: the first project (a PM, the chat "Web" with a worker) and peer's Buddy chat in it. */
+async function scene() {
+ const s = swarm(MIGRATED)
+ s.join(peerActor)
+ s.join(outsiderActor)
+ const pm = s.add('pm-harness', 'lead', true, ownerActor, 'host', owner.sub)
+ const web = s.group('Web')
+ const worker = s.add('worker-harness', web, false, ownerActor, 'host', owner.sub)
+ s.run({ type: 'work.assign', conversationId: web, agentId: worker })
+ let buddyId = s.group('Peer\'s Buddy')
+ s.edit(state => {
+ const generation = state.people.find(p => p.id === peer.sub)!.generation
+ const chat = state.conversations.find(c => c.id === buddyId)!
+ buddyId = buddyChatId(chat.projectId ?? 'lead', { id: peer.sub, generation })
+ Object.assign(chat, { id: buddyId, kind: 'buddy', leadId: null, agentIds: [], audience: { people: [{ id: peer.sub, generation }] } })
+ })
+ const tabId = `tab-${randomUUID()}`
+ await writeLegacySwarm(db, { state: { ...structuredClone(s.state), id: tabId } as SuperTabState, revision: 3 })
+ const report = await migrateSwarm(db, tabId, { now: () => MIGRATED })
+ if (!report.ok) throw new Error(report.error)
+ return { tabId, web, pm, worker, buddyId }
+}
+
+const agentAuthor = (id: string): Author => ({ kind: 'agent', id, name: id, membershipGeneration: 'fixture' })
+const personAuthor = (u: AuthUser): Author => ({ kind: 'person', id: u.sub, name: u.email, membershipGeneration: 'fixture' })
+
+/** Stores a message as the store stores one (numbered after the chat's newest) and, when it tags, the tag; answers its id. */
+async function say(tabId: string, conversationId: string, author: Author, opts: { thread?: string; alsoInChat?: boolean; tags?: AuthUser[] } = {}) {
+ const id = `m-${randomUUID()}`
+ await swarmTransaction(db, async tx => {
+ const current = (await parts.loadActive(tx, tabId, { groupIds: [conversationId] })).groups.find(g => g.key === conversationId)!
+ const data = structuredClone(current.data!) as Conversation
+ const sequence = (data.messageSeq ?? 0) + 1
+ data.messageSeq = data.lastMessageSequence = sequence
+ if (!opts.thread || opts.alsoInChat) data.lastMainSequence = sequence
+ await tx.superTabMessage.create({ data: { id, tabId, conversationId, sequence, author: author as never, text: 'Please look.', thread: opts.thread ?? id,
+ ...(opts.alsoInChat ? { alsoInChat: true } : {}), recipientIds: [], mentions: (opts.tags ?? []).map(t => t.sub), createdAt: new Date() } })
+ await guardedWrite(tx, tabId, { op: 'update', kind: 'group', key: conversationId, seen: current.version, data }, Date.now())
+ for (const tagged of opts.tags ?? []) {
+ await tx.superTabMention.create({ data: { id: stableId(tabId, id, tagged.sub), tabId, personId: tagged.sub, projectId: 'lead', conversationId,
+ messageId: id, authorAgentId: author.id, createdAt: new Date(), resolvedAt: null, resolvedBy: null } })
+ }
+ })
+ return id
+}
+const tagFor = (messageId: string, who: AuthUser) => db.superTabMention.findFirstOrThrow({ where: { messageId, personId: who.sub } })
+const listed = async (tabId: string, as: AuthUser) => {
+ const response = await app.inject({ method: 'GET', url: `/api/super-tabs/${tabId}/mentions?state=waiting`, headers: { authorization: `Bearer ${as.sub}` } })
+ expect(response.statusCode).toBe(200)
+ return (response.json().data.mentions as Array<{ messageId: string }>).map(m => m.messageId)
+}
+const post = async (url: string, as: AuthUser, payload: object) => {
+ const response = await app.inject({ method: 'POST', url, headers: { authorization: `Bearer ${as.sub}` }, payload })
+ expect(response.statusCode).toBe(200)
+}
+const sequenceOf = async (id: string) => (await db.superTabMessage.findUniqueOrThrow({ where: { id } })).sequence
+const markChat = async (s: { tabId: string; web: string }, sequence: number, as: AuthUser) => post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, as, { sequence })
+const markThread = async (s: { tabId: string; web: string }, root: string, sequence: number, as: AuthUser) =>
+ post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/threads/${root}/read`, as, { sequence })
+
+describe('reading clears tags', () => {
+ it('reading the chat past a tag resolves it as read', async () => {
+ const s = await scene()
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] })
+ expect(await listed(s.tabId, peer)).toEqual([tag])
+ await markChat(s, await sequenceOf(tag), peer)
+ expect(await listed(s.tabId, peer)).toEqual([])
+ expect((await tagFor(tag, peer)).resolvedBy).toBe('read')
+ })
+
+ // ENGINEERING §4: a read mark is on the request path. The tags it passes are resolved in one write, never one per tag.
+ it('a mark past thirty tags resolves them in one write', async () => {
+ const s = await scene()
+ const tags: string[] = []
+ for (let i = 0; i < 30; i++) tags.push(await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] }))
+ const newest = await sequenceOf(tags.at(-1)!)
+ const entries = await profiled(db, () => markChat(s, newest, peer))
+ expect(await listed(s.tabId, peer)).toEqual([])
+ expect(await Promise.all(tags.map(async tag => (await tagFor(tag, peer)).resolvedBy))).toEqual(tags.map(() => 'read'))
+ expect(entries.filter(e => e.ns.endsWith('.SuperTabMention') && e.op === 'update')).toHaveLength(1)
+ })
+
+ it('a mark before the tag leaves it waiting', async () => {
+ const s = await scene()
+ await say(s.tabId, s.web, personAuthor(owner))
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] })
+ await markChat(s, (await sequenceOf(tag)) - 1, peer)
+ expect(await listed(s.tabId, peer)).toEqual([tag])
+ })
+
+ it('a chat mark does not clear a tag in a thread reply; its thread mark does', async () => {
+ const s = await scene()
+ const root = await say(s.tabId, s.web, personAuthor(owner))
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { thread: root, tags: [peer] })
+ await markChat(s, await sequenceOf(tag), peer)
+ expect(await listed(s.tabId, peer)).toEqual([tag])
+ await markThread(s, root, await sequenceOf(tag), peer)
+ expect(await listed(s.tabId, peer)).toEqual([])
+ expect((await tagFor(tag, peer)).resolvedBy).toBe('read')
+ })
+
+ it('a reply also sent to the chat clears by the chat mark', async () => {
+ const s = await scene()
+ const root = await say(s.tabId, s.web, personAuthor(owner))
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { thread: root, alsoInChat: true, tags: [peer] })
+ await markChat(s, await sequenceOf(tag), peer)
+ expect(await listed(s.tabId, peer)).toEqual([])
+ expect((await tagFor(tag, peer)).resolvedBy).toBe('read')
+ })
+
+ it('a failed tag resolve still stores and answers the read mark', async () => {
+ const s = await scene()
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] })
+ const sequence = await sequenceOf(tag)
+ const real = db.superTabMention.findMany.bind(db.superTabMention) as (args: { select?: object }) => Promise<unknown>
+ // Only resolveRead's capped read (the first, before the answer is built) fails.
+ const spy = vi.spyOn(db.superTabMention, 'findMany').mockImplementation(((args: { select?: object }) => Object.keys(args.select ?? {}).join() === 'id,messageId' ? Promise.reject(new Error('boom')) : real(args)) as never)
+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, headers: { authorization: `Bearer ${peer.sub}` }, payload: { sequence } })
+ spy.mockRestore()
+ expect(response.statusCode).toBe(200)
+ expect(response.json().data.sequence).toBe(sequence)
+ })
+
+ it('another person\'s read leaves my tag', async () => {
+ const s = await scene()
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] })
+ await markChat(s, await sequenceOf(tag), owner)
+ expect(await listed(s.tabId, peer)).toEqual([tag])
+ })
+})
+
+describe('answering clears tags', () => {
+ const sendTo = (s: { tabId: string }, conversationId: string, as: AuthUser) => store.execute(as, s.tabId, { operationId: randomUUID(),
+ command: { type: 'message.send', conversationId, text: 'Go ahead.', replyTo: null, recipientIds: [] } })
+
+ it('posting in my Buddy chat clears the PM\'s tag in a task chat', async () => {
+ const s = await scene()
+ const tag = await say(s.tabId, s.web, agentAuthor(s.pm), { tags: [peer] })
+ await sendTo(s, s.buddyId, peer)
+ expect(await listed(s.tabId, peer)).toEqual([])
+ expect((await tagFor(tag, peer)).resolvedBy).toBe('answer')
+ })
+
+ // ENGINEERING §4: a person's post runs this in its message.send. The tags are found by the person's own index; the agent that
+ // made each is in no index, so they are read once, never once per agent answered.
+ it('answering five agents reads the person\'s tags once, and resolves only those five agents\' waiting tags', async () => {
+ const tabId = `tab-${randomUUID()}`, now = Date.now()
+ const agents = Array.from({ length: 10 }, (_, i) => `agent-${i}`)
+ // 200 tags of one person, 20 by each agent; one in four already resolved.
+ const tags = Array.from({ length: 200 }, (_, i) => ({ id: `${tabId}-tag-${i}`, tabId, personId: peer.sub, projectId: 'lead', conversationId: 'lead',
+ messageId: `m-${i}`, authorAgentId: agents[i % 10]!, createdAt: new Date(now - 60_000 - i * 1000),
+ resolvedAt: i % 4 === 0 ? new Date(now - 30_000) : null, resolvedBy: i % 4 === 0 ? 'read' : null }))
+ await db.superTabMention.createMany({ data: tags })
+ const answered = agents.slice(0, 5)
+ const entries = await profiled(db, () => resolveByAnswer(db as never, tabId, peer.sub, answered, now))
+ const ops = entries.filter(e => e.ns.endsWith('.SuperTabMention')), examined = ops.reduce((sum, e) => sum + (e.docsExamined ?? 0), 0)
+ const expected = tags.filter(tag => answered.includes(tag.authorAgentId) && !tag.resolvedAt).map(tag => tag.id).sort()
+ const after = await db.superTabMention.findMany({ where: { tabId }, select: { id: true, resolvedBy: true } })
+ expect(after.filter(row => row.resolvedBy === 'answer').map(row => row.id).sort()).toEqual(expected)
+ expect(after.filter(row => row.resolvedBy === 'read')).toHaveLength(50)
+ expect(after.filter(row => !row.resolvedBy)).toHaveLength(150 - expected.length)
+ // Each of the person's tags once, then the resolved ones in one write by their ids.
+ expect(examined, `examined ${examined} for ${tags.length} tags, ${expected.length} resolved: ${JSON.stringify(plan(ops).slice(0, 3))}`).toBeLessThanOrEqual(tags.length + expected.length)
+ expect(ops.filter(e => e.op === 'update')).toHaveLength(1)
+ })
+
+ it('a tag by another agent stays', async () => {
+ const s = await scene()
+ const tag = await say(s.tabId, s.web, agentAuthor(s.worker), { tags: [peer] })
+ await sendTo(s, s.buddyId, peer)
+ expect(await listed(s.tabId, peer)).toEqual([tag])
+ })
+})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 4c4444f5b..20e4cdee3 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -4117,7 +4117,7 @@ describe('Lead mentions', () => {
it('resolves on the person’s later post in that conversation, not on anyone else’s', async () => {
const { tab, group } = await tagged()
await run(tab, { type: 'message.send', conversationId: group, text: 'Owner chimes in.', replyTo: null, recipientIds: [] })
- await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Elsewhere.', replyTo: null, recipientIds: [] }, peer)
+ // A post elsewhere to the Lead who tagged them answers it too (superTabTagsClear.test.ts): not one here.
expect(await list(tab, peer, 'waiting')).toHaveLength(1)
await run(tab, { type: 'message.send', conversationId: group, text: 'Looks good.', replyTo: null, recipientIds: [] }, peer)
expect(await list(tab, peer, 'waiting')).toEqual([])
diff --git a/backend/src/superTabs/mentions.test.ts b/backend/src/superTabs/mentions.test.ts
index 28cbe6b3e..b78642344 100644
--- a/backend/src/superTabs/mentions.test.ts
+++ b/backend/src/superTabs/mentions.test.ts
@@ -2,7 +2,8 @@ import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { storeOldLeads } from './leads.test-support.js'
import { applyCommand, type Command, type CommandContext } from './commands.js'
-import { checkMentions, MAX_MENTIONS, tagTokens } from './mentions.js'
+import { answeredAgents, checkMentions, MAX_MENTIONS, tagTokens } from './mentions.js'
+import { openSwarmBuddyChat } from './buddies.js'
import { createSuperTab, type Actor } from './model.js'
const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
@@ -98,6 +99,39 @@ describe('people tagging people', () => {
})
})
+describe('answeredAgents', () => {
+ const post = (f: ReturnType<typeof fixture>, conversationId: string, recipientIds: string[], actor: Extract<Actor, { kind: 'person' }> = owner) => {
+ const draft = f.run({ type: 'message.send', conversationId, text: 'Done.', replyTo: null, recipientIds, mentions: [] }, actor).messages.find(m => !m.source)!
+ return answeredAgents(f.state, actor, f.state.conversations.find(c => c.id === conversationId)!, draft.recipients)
+ }
+
+ it('a plain post in a project chat answers its coordinator', () => {
+ const f = fixture()
+ expect(post(f, f.app.conversationId, [])).toEqual([f.lead])
+ })
+
+ it('a post addressed to another agent leaves the PM\'s tags', () => {
+ const f = fixture()
+ expect(answeredAgents(f.state, owner, f.state.conversations.find(c => c.id === f.app.conversationId)!, [f.worker])).toEqual([f.worker])
+ })
+
+ it('the Swarm Buddy chat clears coordinators of readable projects only', () => {
+ const f = fixture()
+ const secret = f.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).result as { projectId: string; conversationId: string }
+ const secretLead = f.run({ type: 'agent.add', conversationId: secret.conversationId, harnessId: 'secret-lead', machineId: 'machine', name: 'Secret Lead', lead: true,
+ configuration }).result.agentId as string
+ const chat = openSwarmBuddyChat(f.state, f.state.people.find(p => p.id === 'peer')!)
+ const answered = answeredAgents(f.state, peer, chat, [])
+ expect(answered).toContain(f.lead)
+ expect(answered).not.toContain(secretLead)
+ })
+
+ it('a project Buddy chat answers its Buddy and that project\'s coordinator', () => {
+ const f = fixture()
+ expect(answeredAgents(f.state, peer, f.state.conversations.find(c => c.id === f.pmChat)!, [f.worker])).toEqual([f.worker, f.lead])
+ })
+})
+
const shared = JSON.parse(readFileSync(new URL('./tagFixture.json', import.meta.url), 'utf8')) as { cases: Array<{ text: string; tags: string[] }> }
describe('tags in the text', () => {
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index d9cce251c..3630f065e 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -5,8 +5,8 @@ import { createHash } from 'node:crypto'
import type { Prisma, PrismaClient } from '@prisma/client'
import { ensureIndex } from '../lib/db/indexes.js'
import { activeWork, agentOnly, fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-import { canReadGroup, groupProject, projectAgent, projectOf } from './projects.js'
-import { isSwarmBuddyChat } from './buddies.js'
+import { canReadGroup, canReadProject, groupProject, projectAgent, projectOf, projectsOf } from './projects.js'
+import { isBuddyChat, isSwarmBuddyChat } from './buddies.js'
import { groupsBy, readBy } from './parts/indexed.js'
import { deliveredCopies } from './pageReads.js'
import { usernameOf } from './usernames.js'
@@ -156,6 +156,55 @@ export async function resolveByReply(tx: Tx, tabId: string, conversationId: stri
data: { resolvedAt: new Date(now), resolvedBy: 'reply' } })
}
+/** A read mark moved to [sequence] resolves the person's waiting tags it passes: in the chat (threadId null) those shown there, in a
+ * thread those shown only in it (threadsOf, as Desktop's mentionUnread reads them). Most marks find no tag and stop after one read.
+ * A held tag (holdUntil) resolved before its time is never listed, as in resolveByReply (intended). */
+export async function resolveRead(db: Tx | PrismaClient, input: { tabId: string; personId: string; conversationId: string; threadId: string | null;
+ sequence: number; now: number }): Promise<number> {
+ const { tabId, personId, conversationId, threadId, sequence, now } = input, tx = db as Tx
+ const rows = await tx.superTabMention.findMany({ where: { tabId, personId, conversationId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS) }, ...waiting },
+ select: { id: true, messageId: true }, orderBy: { createdAt: 'desc' }, take: 500 })
+ if (!rows.length) return 0
+ // By id through its index (parts/indexed.ts), never a Prisma `in` on a hot collection (hotFilters.test.ts).
+ const messages = (await readBy(tx, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: [...new Set(rows.map(r => r.messageId))] }, tabId,
+ sequence: { $lte: sequence } } }, { $project: { conversationId: 1, thread: 1, alsoInChat: 1 } }]))
+ .map(m => ({ id: m._id as string, conversationId: m.conversationId as string, thread: (m.thread as string | undefined) ?? null,
+ alsoInChat: (m.alsoInChat as boolean | undefined) ?? null }))
+ const threads = await threadsOf(tx, tabId, messages)
+ const passed = new Set(messages.filter(m => (threads.get(m.id) ?? null) === threadId).map(m => m.id))
+ return resolveIds(tx, tabId, personId, rows.filter(r => passed.has(r.messageId)).map(r => r.id), 'read', now)
+}
+
+/** Resolves these waiting tags of the person in one write, by their ids (at most the 500 a read takes): raw, since Prisma sends
+ * an `in` on this hot collection as $expr (hotFilters.test.ts). `resolvedAt: null` matches an unset one too. Answers how many. */
+async function resolveIds(tx: Tx, tabId: string, personId: string, ids: string[], by: 'read' | 'answer', now: number): Promise<number> {
+ if (!ids.length) return 0
+ const answer = await tx.$runCommandRaw({ update: 'SuperTabMention', updates: [{ q: { _id: { $in: ids }, tabId, personId, resolvedAt: null },
+ u: { $set: { resolvedAt: { $date: new Date(now).toISOString() }, resolvedBy: by } }, multi: true }] }) as { nModified?: number; writeErrors?: unknown[] }
+ if (answer.writeErrors?.length) throw new Error('The database refused some tag resolves')
+ return answer.nModified ?? 0
+}
+
+/** The agents a person's post answers: its recipients, and in their own Buddy chat also the coordinator of each project the Buddy
+ * relays to (every project they read for the Swarm chat, the chat's own for a project chat). */
+export function answeredAgents(state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, group: Conversation, recipients: readonly string[]): string[] {
+ const coordinators = !isBuddyChat(group) || !group.audience?.people.some(p => p.id === actor.userId) ? []
+ : (isSwarmBuddyChat(group) ? projectsOf(state).filter(p => canReadProject(state, actor, p)) : [projectOf(state, group.projectId ?? 'lead')])
+ .map(p => state.conversations.find(c => c.id === p.leadConversationId)?.leadId)
+ return [...new Set([...recipients.filter(id => state.agents.some(a => a.id === id)), ...coordinators.filter((id): id is string => !!id)])]
+}
+
+/** A post to an agent answers every tag that agent made for the person, in any conversation. A held tag (holdUntil) resolved
+ * before its time is never listed, as in resolveByReply (intended). The agent that made a tag is in no index: the person's
+ * waiting tags are read once by theirs, as resolveRead reads them, and the agents' resolved in one write. */
+export async function resolveByAnswer(tx: Tx, tabId: string, personId: string, agentIds: readonly string[], now: number): Promise<void> {
+ if (!agentIds.length) return
+ const answered = new Set(agentIds)
+ const rows = await tx.superTabMention.findMany({ where: { tabId, personId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS), lte: new Date(now) }, ...waiting },
+ select: { id: true, authorAgentId: true }, orderBy: { createdAt: 'desc' }, take: 500 })
+ await resolveIds(tx, tabId, personId, rows.filter(row => answered.has(row.authorAgentId)).map(row => row.id), 'answer', now)
+}
+
/** A worker took the group: its held tags are over. A listed one moves to Earlier; one not yet listed is dropped, as if never
* made. Run before [dropHeldTags] of the same command, which would drop the listed ones too. */
export async function resolveWhenWorked(tx: Tx, tabId: string, conversationId: string, now: number): Promise<void> {
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index d0943be09..8f88bbe6d 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -7,7 +7,8 @@ import type { PrismaClient } from '@prisma/client'
import type { AuthUser } from '../../lib/ssoAuth.js'
import { isTeamSession, TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE } from '../../lib/teamSession.js'
import { agentOnly, author, fail, groupForBuddy, isLeads, seenMachineIds, stableId, SuperTabError, visibleState, type Actor, type AgentStart, type SuperTabState } from '../model.js'
-import { mentionsDigest, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'
+import { logger } from '../../utils/logger.js'
+import { mentionsDigest, resolveRead, swarmsWithTags, waitingMentions, waitingTagConversations } from '../mentions.js'
import { decisionsWaiting } from '../decisions.js'
import { readMarks, readThreadMarks, writeThreadFollow, writeThreadMark } from '../readMarks.js'
import { activityDigest, listActivity, markActivityRead, markActivityThreadRead, type ActivityItem } from '../activity.js'
@@ -225,6 +226,13 @@ export class SwarmReads {
})
}
+ /** The stored mark is the answer: a failed tag resolve is only logged, since the client never resends a mark at or below it. */
+ private async resolveTags(input: Parameters<typeof resolveRead>[1]): Promise<void> {
+ try { await resolveRead(this.db, input) } catch (error) {
+ logger.warn('[swarm-read] tags not resolved', { tabId: input.tabId, conversationId: input.conversationId, error: error instanceof Error ? error.message : String(error) })
+ }
+ }
+
/** Moves the person's read mark in a conversation they can read forward, never past its newest message (readMarks.ts). Only a
* person reading as themselves has marks: an agent, or a Team session, is refused before anything is written. Reading the
* chat never reads a reply only in a thread: first, each such thread of theirs between the old mark and the new one with no
@@ -233,7 +241,9 @@ export class SwarmReads {
if (isTeamSession(user)) fail(TEAM_SESSION_LIMITED, TEAM_SESSION_MESSAGE, 403)
const { group, state } = await this.readGroup(user, tabId, conversationId)
const next = Math.min(sequence, group.data!.lastMessageSequence), now = this.now()
- return { sequence: await moveChatMark(this.db, { tabId, state, personId: user.sub, conversationId, next, now }) }
+ const stored = await moveChatMark(this.db, { tabId, state, personId: user.sub, conversationId, next, now })
+ await this.resolveTags({ tabId, personId: user.sub, conversationId, threadId: null, sequence: stored, now })
+ return { sequence: stored }
}
/** Moves the person's mark of thread `threadId` in a conversation they can read forward, never past the conversation's
@@ -247,6 +257,7 @@ export class SwarmReads {
const stored = await writeThreadMark(this.db, { tabId, personId: user.sub, conversationId, threadId, sequence: Math.min(sequence, newest), now })
// The thread's replies the mark passes are read in Activity too (activity.ts).
await markActivityThreadRead(this.db, { tabId, personId: user.sub, conversationId, threadId, sequence: stored, now })
+ await this.resolveTags({ tabId, personId: user.sub, conversationId, threadId, sequence: stored, now })
return { sequence: stored }
}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 6d1755b4b..ddd2d9848 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -82,7 +82,7 @@ import { costRows, failedStarts, summarizeCosts } from './costs/read.js'
import { APPROVE, approvedLine, localDate, MAX_PROPOSALS, proposalQuestion, proposalTitle, REASK_DAYS, reflectionMessageId, routingReflection, type Proposal, type ReflectionInput } from './costs/reflection.js'
import { readEvidence, recordEvidence } from './evidence/store.js'
import { closeAssignment, closeUnassignedStart, LIST_SIZE, newestConversations, newestDecisions, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
-import { dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'
+import { answeredAgents, dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByAnswer, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'
import { answerable, askDecisions, MAX_OPEN_DECISIONS, REFLECTION_DECISION, reflectionDecisions, expireReflections, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingConversations, waitingFor, waitingInProject, withdrawIn, workEnded, workOver, writeDecisions } from './decisions.js'
import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'
import { recordMessageRead, type MessageReadKey } from './messageReadStats.js'
@@ -1831,6 +1831,12 @@ export class SuperTabStore {
await this.writeMessages(tx, tabId, effects.state, effects.messages, sequences)
if (effects.lateDeliveries?.length) await this.writeLateDeliveries(tx, tabId, effects.state, effects.lateDeliveries)
if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)
+ // Answering an agent settles its tags in other conversations too (mentions.ts answeredAgents).
+ if (command.type === 'message.send' && actor.kind === 'person' && !isTeamSession(user)) {
+ const sent = effects.messages.filter(m => m.conversationId === command.conversationId && m.author.kind === 'person' && m.author.id === actor.userId && !m.source)
+ await resolveByAnswer(tx, tabId, actor.userId, answeredAgents(effects.state, actor, effects.state.conversations.find(c => c.id === command.conversationId)!,
+ sent.flatMap(m => m.recipients)), context.now)
+ }
if (command.type === 'work.assign') await resolveWhenWorked(tx, tabId, command.conversationId, context.now)
// The Lead acting on a group ends the tags it held back about it (mentions.ts), before this command's own are written.
const ledId = 'conversationId' in command ? command.conversationId : command.type === 'agent.start' ? command.request.conversationId : undefined
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 8b263fc84..27dcd7b6b 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/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/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.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/swarmAgentTombstones.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['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/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['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/core/api.ts b/cli/src/core/api.ts
index a6d923318..42b308cc8 100644
--- a/cli/src/core/api.ts
+++ b/cli/src/core/api.ts
@@ -234,7 +234,7 @@ export interface CoreApi {
/** Deliver text into a live agent under a delivery id of the caller's own, as the Wi-Fi device, Agent
* Messages and the orchestrator deliver their turns: one path for the three. What becomes of it is heard through
* `onDelivery`, under the same id. */
- deliver(agentId: string, text: string, deliveryId: string): void
+ deliver(agentId: string, text: string, deliveryId: string, options?: DeliveryOptions): void
/** Take back a delivery not yet being written: true when it was, and it never will be; false for one
* the agent's pane is already taking. Answered at once, as the orchestrator reads it in
* line: in a service's own process the core is asked and the answer cannot wait, so it is false there,
@@ -567,6 +567,11 @@ export const ACCOUNT_BACKEND_OFF: Pick<CoreApi['account'], 'backend' | 'identity
/** Where a service that was never told runs this daemon from: the installed CLI, on no port it knows. */
export const DAEMON_UNKNOWN: DaemonAddress = { command: 'harness', port: 0, machineId: () => '', autonomousEnv: 'prod' }
+/** How a delivery is told apart: `answersQuestion` marks a person's Swarm message, which closes the question it answers
+ * in a Claude pane (core/input.ts `beforeTeamWrite`);
+ * `writtenAt` is when it was written (ms), as only a question open since then is its to close. */
+export interface DeliveryOptions { answersQuestion?: true; writtenAt?: number }
+
/** What became of a delivered turn (`turns.deliver`), as the core's input says it: `queued`, written
* (`delivered`), its turn `started`, `rejected` with why, or `unknown`. `sessionId` is the agent it was
* delivered to, as the delivery named it. */
diff --git a/cli/src/core/deliveries.spec.ts b/cli/src/core/deliveries.spec.ts
index 81fc5f62c..560e84f51 100644
--- a/cli/src/core/deliveries.spec.ts
+++ b/cli/src/core/deliveries.spec.ts
@@ -34,6 +34,19 @@ describe('delivered turns', () => {
expect(deliveries.answer('worker', 'deliver', { deliveryId: id, agentId: 'a', text: 'x' })).toEqual({})
})
+ it('remembers a delivery that answers a question until it settles', () => {
+ const { deliveries } = setup()
+ deliveries.turns.deliver('a', 'x', 'p1', { answersQuestion: true, writtenAt: 5 })
+ deliveries.turns.deliver('a', 'x', 'p2')
+ expect(deliveries.answer('orchestrator', 'deliver', { deliveryId: 'p3', agentId: 'a', text: 'x', answersQuestion: true, writtenAt: 7 })).toEqual({})
+ expect(['p1', 'p2', 'p3'].map(deliveries.answersQuestion)).toEqual([{ writtenAt: 5 }, null, { writtenAt: 7 }])
+ expect(deliveries.answer('orchestrator', 'deliver', { deliveryId: 'p4', agentId: 'a', text: 'x', answersQuestion: true, writtenAt: 'soon' })).toEqual({})
+ expect(deliveries.answersQuestion('p4')).toEqual({})
+ deliveries.settled(event('p1', 'delivered'))
+ deliveries.settled(event('p3', 'rejected'))
+ expect(['p1', 'p3'].map(deliveries.answersQuestion)).toEqual([null, null])
+ })
+
it('cannot grant, cancel or submit another service namespace or unbounded permissions', async () => {
const { deliveries, deps } = setup()
const id = 'team:service:other:one'
diff --git a/cli/src/core/deliveries.ts b/cli/src/core/deliveries.ts
index 5c9781150..f40f7027c 100644
--- a/cli/src/core/deliveries.ts
+++ b/cli/src/core/deliveries.ts
@@ -80,7 +80,11 @@ export function createDeliveries(deps: DeliveriesDeps) {
settled({ deliveryId, sessionId: taken.agentId, state: 'rejected', reason: 'cancelled' })
return true
}
+ /** Deliveries from a person's message, which close a question open on the pane, until they settle. */
+ const answering = new Map<string, { writtenAt?: number }>()
+ const answers = (writtenAt: unknown) => Number.isFinite(writtenAt) ? { writtenAt: writtenAt as number } : {}
const settled = (event: TurnDelivery): void => {
+ if (event.state !== 'queued') answering.delete(event.deliveryId)
for (const listener of listeners) {
try { listener(event) } catch (error) {
log(`[deliveries] a listener failed on ${event.deliveryId.slice(0, 40)} · ${error instanceof Error ? error.message : String(error)}`)
@@ -91,7 +95,10 @@ export function createDeliveries(deps: DeliveriesDeps) {
}
const turns: Pick<CoreApi['turns'], 'deliver' | 'cancelDelivery' | 'onDelivery' | 'leaseDeliveries'> = {
- deliver: (agentId, content, deliveryId) => submit(agentId, content, deliveryId),
+ deliver: (agentId, content, deliveryId, options) => {
+ if (options?.answersQuestion) answering.set(deliveryId, answers(options.writtenAt))
+ submit(agentId, content, deliveryId)
+ },
cancelDelivery: (deliveryId) => cancel(deliveryId),
onDelivery: (listener) => {
listeners.add(listener)
@@ -112,6 +119,9 @@ export function createDeliveries(deps: DeliveriesDeps) {
return (leases.get(service)?.get(deliveryId) ?? 0) > now()
},
+ /** The delivery, when it is unsettled and came from a person's message (`DeliveryOptions.answersQuestion`), else null. */
+ answersQuestion: (deliveryId: string): { writtenAt?: number } | null => answering.get(deliveryId) ?? null,
+
/** The core's input says what became of a delivery: every listener here hears it, each guarded, and the
* process that made it is told. A listener that throws costs that listener the event, never the input
* that said it or another listener. */
@@ -140,6 +150,7 @@ export function createDeliveries(deps: DeliveriesDeps) {
makers.delete(deliveryId)
makers.set(deliveryId, service)
if (makers.size > KEPT_DELIVERERS) makers.delete(makers.keys().next().value!)
+ if (payload.answersQuestion === true) answering.set(deliveryId, answers(payload.writtenAt))
submit(agentId, payload.text, deliveryId)
return {}
},
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index 8b3bc51db..8ef8c4053 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -157,6 +157,137 @@ describe('the session input controller\'s dependencies', () => {
expect(sessionInputDeps({ ...given, moveGate }, () => lock([])).moveGate).toBe(moveGate)
})
+ describe('a person\'s Swarm message closes the question it answers', () => {
+ const QUESTION = fixture('question-tabs.txt')
+ const OTHER_QUESTION = QUESTION.replace('Which colors do you like?', 'Which size do you like?')
+ const ID = 'team:service:superTabs:answer'
+ type Over = { answers?: { writtenAt?: number } | null; pending?: { openedAt: number; text: string } | null; engine?: 'a1' | 'cx'; held?: boolean }
+ /** The pane shows `first` until a key is pressed, then `after`; a question was opened at 1000, the message written at 2000. */
+ const asking = (first: string, after: string, over: Over = {}) => {
+ const t = deps({
+ answersQuestion: () => over.answers === undefined ? { writtenAt: 2000 } : over.answers,
+ pendingQuestion: () => over.pending === undefined ? { openedAt: 1000, text: 'q' } : over.pending,
+ controlHeld: () => over.held === true,
+ })
+ const wired = sessionInputDeps(t.deps, () => lock(t.calls))
+ t.setPane(first)
+ vi.mocked(t.deps.terminal.keyTerminalAction).mockImplementation(async (id, key) => { t.calls.push(`key ${id} ${key}`); t.setPane(after); return ok })
+ return { t, wired, session: agents.get(over.engine ?? 'a1')! }
+ }
+ const keys = (calls: string[]) => calls.filter((c) => c.startsWith('key '))
+
+ it('presses Escape once and delivers when the question closes', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE)
+ expect(await wired.beforeTeamWrite!(session, ID)).toBeNull()
+ expect(keys(t.calls)).toEqual(['key a1 Escape'])
+ expect(t.calls).toContain('lock a1')
+ })
+ // An answer typed at the terminal replaces the free-text row's placeholder: Escape would end the question and lose it.
+ describe.each([
+ ['a single-select question', fixture('question-single.txt'), 'Type something.', 'Iced tea, no sugar'],
+ ['a multi-select question', QUESTION, '[ ] Type something', '[ ] Teal, please'],
+ ])('in %s', (_, empty, placeholder, answer) => {
+ it('presses Escape while its free-text row is empty', async () => {
+ const { t, wired, session } = asking(empty, READY_PANE)
+ expect(await wired.beforeTeamWrite!(session, ID)).toBeNull()
+ expect(keys(t.calls)).toEqual(['key a1 Escape'])
+ })
+ it('holds, pressing no Escape, while its free-text row holds a typed answer', async () => {
+ const typed = empty.replace(placeholder, answer)
+ expect(typed).not.toBe(empty)
+ const { t, wired, session } = asking(typed, READY_PANE)
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ })
+ it('never presses Escape on a permission prompt', async () => {
+ const { t, wired, session } = asking(CLAUDE_PERMISSION, READY_PANE)
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('leaves an agent\'s message waiting', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE, { answers: null })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('leaves another engine waiting', async () => {
+ const { t, wired, session } = asking(fixture('question-codex.txt'), READY_PANE, { engine: 'cx' })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('holds when Escape was not sent, or the delivery or the pane is unknown', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE)
+ vi.mocked(t.deps.terminal.keyTerminalAction).mockResolvedValueOnce({ state: 'failed', dispatch: 'not_started', reason: 'gone' })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(await wired.beforeTeamWrite!(session)).toBe('team_waiting_user')
+ t.setPane(null)
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_unavailable')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('still holds when the question stays after Escape', async () => {
+ vi.useFakeTimers()
+ try {
+ const { t, wired, session } = asking(QUESTION, QUESTION)
+ const held = wired.beforeTeamWrite!(session, ID)
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(await held).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual(['key a1 Escape'])
+ } finally { vi.useRealTimers() }
+ })
+ it('does not press Escape when the question was answered before the lock', async () => {
+ const { t, session } = asking(QUESTION, READY_PANE)
+ // The writer lock is busy while the question is answered elsewhere: the pane is clear by the time it is ours.
+ const late: Pick<AutonomousDeviceInput, 'legacyWrite'> = { legacyWrite: async (_id, write) => { t.setPane(READY_PANE); return write() } }
+ const wiredLate = sessionInputDeps(t.deps, () => late)
+ expect(await wiredLate.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('does not press Escape for another question than the one first read', async () => {
+ const { t, session } = asking(QUESTION, READY_PANE)
+ const late: Pick<AutonomousDeviceInput, 'legacyWrite'> = { legacyWrite: async (_id, write) => { t.setPane(OTHER_QUESTION); return write() } }
+ expect(await sessionInputDeps(t.deps, () => late).beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('does not press Escape without a pending AskUserQuestion record', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE, { pending: null })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('does not press Escape while an answer holds the terminal', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE, { held: true })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('does not press Escape for a delivery the core may no longer write', async () => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE)
+ t.deps.deliveries.canWrite = () => false
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it.each([
+ ['before the question opened', { writtenAt: 500 }],
+ ['at an unknown time', {}],
+ ])('does not press Escape for a message written %s', async (_, answers) => {
+ const { t, wired, session } = asking(QUESTION, READY_PANE, { answers })
+ expect(await wired.beforeTeamWrite!(session, ID)).toBe('team_waiting_user')
+ expect(keys(t.calls)).toEqual([])
+ })
+ it('waits for the redraw after Escape and delivers once the question is gone', async () => {
+ vi.useFakeTimers()
+ try {
+ const { t, wired, session } = asking(QUESTION, QUESTION)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let reads = 0
+ vi.mocked(t.deps.terminal.captureTerminal).mockImplementation(async () => (++reads > 4 ? READY_PANE : QUESTION))
+ const result = wired.beforeTeamWrite!(session, ID)
+ await vi.advanceTimersByTimeAsync(3000)
+ expect(await result).toBeNull()
+ expect(keys(t.calls)).toEqual(['key a1 Escape'])
+ expect(warn.mock.calls.some(([line]) => String(line).includes('question closed for a person\'s message'))).toBe(true)
+ } finally { vi.useRealTimers() }
+ })
+ })
+
it('tells the device of a delivery first, then its caller; its caller alone without a device', () => {
const one = deps()
sessionInputDeps(one.deps, () => lock([])).onDelivery!(delivery('d1'))
@@ -488,6 +619,17 @@ describe('createInput', () => {
release!()
})
+ it('presses no Escape while a question is being answered through the controller', async () => {
+ const run = deps({ answersQuestion: () => ({ writtenAt: 2000 }), pendingQuestion: () => ({ openedAt: 1000, text: 'q' }) })
+ run.setPane(fixture('question-tabs.txt'))
+ const inputs = createInput(run.deps)
+ const release = inputs.acquireTerminalControl('a1', { forAnswer: true })!
+ const given = (controller: object) => (controller as unknown as { deps: Record<string, (...args: unknown[]) => unknown> }).deps
+ expect(await given(inputs.input).beforeTeamWrite(agents.get('a1'), 'team:service:superTabs:x')).toBe('team_waiting_user')
+ expect(run.calls.filter((c) => c.startsWith('key '))).toEqual([])
+ release()
+ })
+
it('takes control of a pane only when both the queue and the terminal grant it, and gives both back', () => {
const run = deps()
const inputs = createInput(run.deps)
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 2649765e6..3292931be 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -67,6 +67,13 @@ export interface InputDeps {
/** Whether a typed delivery's maker queues it in the engine's own input while the agent works (the Swarm's chat,
* superTabs/inCore/deliveries.ts), where the engine takes that; absent, every typed delivery waits for idle. */
typesWhileBusy?: (deliveryId: string) => boolean
+ /** Whether a delivery is a person's Swarm message, which closes a question open in a Claude pane (core/deliveries.ts), and when
+ * it was written (ms); null for any other. */
+ answersQuestion?: (deliveryId: string) => { writtenAt?: number } | null
+ /** The AskUserQuestion the core knows is open for a session, and when it opened (core/questions.ts); none, no Escape. */
+ pendingQuestion?: (sessionId: string) => { openedAt: number; text: string } | null
+ /** Whether an answer holds the agent's pane (`SessionInputController.acquireControl`): no Escape while it does. */
+ controlHeld?: (agentId: string) => boolean
/** An agent whose turns keep ending at once has its automatic writes held a while (turns/shortTurnGuard.ts). */
shortTurns?: Pick<ShortTurnGuard, 'holding'>
}
@@ -131,6 +138,8 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminal
/** How long the check before a message's Enter asks again after a read that says nothing: 3 s. */
const ENTER_CHECK_TRIES = 12
const ENTER_CHECK_RETRY_MS = 250
+/** How often the pane is read after Escape, for the question to go: 2 s. */
+const QUESTION_CLOSE_TRIES = 8
/** The bottom of a capture for the log: escape sequences and odd spaces kept visible (JSON), secrets redacted,
* each row cut, so a composer the reader missed can be read back from the log. */
@@ -143,6 +152,15 @@ export function heldScreen(capture: string | null): string {
const HELD_SCREEN_ROWS = 15
const HELD_SCREEN_ROW_CHARS = 400
+/** The question a reading shows, to tell it from another. */
+const questionOf = (screen: ScreenReading | null): string | undefined =>
+ JSON.stringify(screen?.question)
+
+/** Whether a question's free-text row still shows its placeholder. Text typed into it replaces the placeholder, and Escape
+ * would end the question and lose it. A reading with no free-text row holds too: it cannot tell that row empty. */
+const freeTextEmpty = (screen: ScreenReading | null): boolean =>
+ screen?.question?.kind === 'question' && !!screen.question.typeRow
+
/** What `SessionInputController` is given: every write takes the device's pane lock first. */
export function sessionInputDeps(
deps: InputDeps,
@@ -172,7 +190,38 @@ export function sessionInputDeps(
if (deps.shortTurns?.holding(session.sessionId)) return 'team_waiting_control'
const capture = await captureTerminal(session.agentId)
const screen = await deps.readScreen(session, capture)
- return deliveryHold(session, screen, capture, deliveryId)
+ const hold = deliveryHold(session, screen, capture, deliveryId)
+ // A person's answer closes the question it answers: one Escape, then the pane is read again and held as ever if
+ // the question stays. Never a permission prompt, an agent's message, another engine, a question the core does not
+ // know of, one that opened after the message was written, or one with an answer typed into its free-text row.
+ const answers = deliveryId ? deps.answersQuestion?.(deliveryId) : null
+ const pending = deps.pendingQuestion?.(session.sessionId)
+ if (screen?.messageHold !== 'question_open' || session.engine !== 'claude' || !deliveryId || !answers || !pending
+ || answers.writtenAt === undefined || answers.writtenAt < pending.openedAt || !freeTextEmpty(screen)) return hold
+ const first = questionOf(screen)
+ // Under the pane's lock, which may have waited: the question is read again, and is still the one first read, still
+ // pending, unanswered by hand and wanted by its maker.
+ const pressed = await deviceInput().legacyWrite(session.agentId, async () => {
+ const again = await deps.readScreen(session, await captureTerminal(session.agentId))
+ if (again?.messageHold !== 'question_open' || questionOf(again) !== first || !freeTextEmpty(again)
+ || !deps.pendingQuestion?.(session.sessionId) || deps.controlHeld?.(session.agentId) || !deliveries.canWrite(deliveryId)) {
+ return terminalActionNotStarted('question_changed')
+ }
+ return keyTerminalAction(session.agentId, 'Escape')
+ })
+ if (pressed.state !== 'succeeded') return hold
+ // Claude redraws a moment after the key.
+ for (let tries = 1; tries <= QUESTION_CLOSE_TRIES; tries++) {
+ await new Promise((settle) => setTimeout(settle, ENTER_CHECK_RETRY_MS))
+ const after = await captureTerminal(session.agentId)
+ const next = await deps.readScreen(session, after)
+ if (next && next.messageHold !== 'question_open') {
+ console.warn(`[inject] ${sid(session.sessionId)} question closed for a person's message`)
+ return deliveryHold(session, next, after, deliveryId)
+ }
+ }
+ console.warn(`[inject] ${sid(session.sessionId)} question closed for a person's message: Escape sent, question still open`)
+ return hold
},
validateRuntime: validateTerminal,
// Typed into the pane as it stands, a draft or a running turn included, under the pane's write lock.
@@ -239,7 +288,7 @@ export function deviceInputDeps(
export function createInput(deps: InputDeps) {
const { resolve, terminal: { pinTerminalControl } } = deps
- const input: SessionInputController = new SessionInputController(sessionInputDeps(deps, () => deviceInput))
+ const input: SessionInputController = new SessionInputController(sessionInputDeps({ ...deps, controlHeld: (agentId) => input.controlHeld(agentId) }, () => deviceInput))
const deviceInput: AutonomousDeviceInput = new AutonomousDeviceInput(deviceInputDeps(deps, () => input))
const acquireTerminalControl = (id: string, opts?: { forAnswer?: boolean }): (() => void) | null => {
const agentId = resolve(id)?.agentId ?? id
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 7d767ec8b..4584e520c 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1371,6 +1371,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {
shortTurns,
// The Swarm's chat is queued in the engine's own input while an agent works (superTabs/inCore/deliveries.ts).
...(swarm ? { typesWhileBusy: swarm.typesWhileBusy } : {}),
+ answersQuestion: deliveries.answersQuestion,
+ // Built further down: read when a person's message meets an open question, never now.
+ pendingQuestion: (sessionId) => asking.pendingQuestion(sessionId),
readScreen: screens.read,
submission: submissions,
resolve: (id) => registry.resolve(id),
diff --git a/cli/src/core/questions.spec.ts b/cli/src/core/questions.spec.ts
index 6beae3e0b..214d0c553 100644
--- a/cli/src/core/questions.spec.ts
+++ b/cli/src/core/questions.spec.ts
@@ -39,6 +39,18 @@ const waiting = (sessionId: string, agentId = sessionId) => ({
describe('questions', () => {
afterEach(() => vi.restoreAllMocks())
+ it('knows the AskUserQuestion open for a session, and since when; not a permission prompt, not one answered', () => {
+ vi.spyOn(Date, 'now').mockReturnValue(1234)
+ const { asking } = setup()
+ const watcher = given(asking.questionWatcher)
+ watcher.onQuestion('s1', 'r1', [{ q: 'Ship it?', options: [] }])
+ expect(asking.pendingQuestion('s1')).toEqual({ openedAt: 1234, text: 'Ship it?' })
+ watcher.onQuestionGone('s1', 'r1')
+ expect(asking.pendingQuestion('s1')).toBeNull()
+ watcher.onQuestion('s1', 'r2', [], { permission: {}, dialog: 'Run printf hi?' })
+ expect(asking.pendingQuestion('s1')).toBeNull()
+ })
+
it('drives the pane through the terminal it was given, holding it for the whole answer', () => {
const { deps, asking } = setup()
const controller = given(asking.questions)
diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.ts
index 96eeb40a6..df8dacd77 100644
--- a/cli/src/core/questions.ts
+++ b/cli/src/core/questions.ts
@@ -71,6 +71,10 @@ export function createQuestions({
}
// What is still being asked, by session — handed to a window that connects later (openQuestions below).
const openQuestions = new Map<string, Record<string, unknown>>()
+ // The AskUserQuestions open by session, and when each was seen open: what lets the input close one for a person's message
+ // (core/input.ts `beforeTeamWrite`). A permission prompt is not one.
+ const pending = new Map<string, { openedAt: number; text: string }>()
+ const pendingQuestion = (sessionId: string): { openedAt: number; text: string } | null => pending.get(sessionId) ?? null
// The same, of the questions this module asked, for an app away from this desk that connects later: the
// cloud agents' questions share `openQuestions` (core/agents/cloud.ts) and never go over the relay.
const askedRemotely = new Map<string, Frame>()
@@ -89,6 +93,7 @@ export function createQuestions({
onQuestion: (sessionId, requestId, shaped, detail) => {
deviceInput.setUserAction(agentIdFor(sessionId), true)
questions.remember(requestId, sessionId)
+ if (!detail?.permission) pending.set(sessionId, { openedAt: Date.now(), text: shaped[0]?.q ?? '' })
showAwaitingAnswer(sessionId)
const asked = {
type: 'commander_question',
@@ -123,6 +128,7 @@ export function createQuestions({
// disagree about whether a question is still open.
onQuestionGone: (sessionId, requestId) => {
heard?.('answered', sessionId, requestId)
+ pending.delete(sessionId)
deviceInput.setUserAction(agentIdFor(sessionId), false)
const closed = {
type: 'commander_question_close',
@@ -153,7 +159,7 @@ export function createQuestions({
clients.sendRemote({ type: 'commander_questions_open', payload: { requestIds } })
}
const questionResponse = createQuestionResponse(answer)
- return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, monitorActivity, hearQuestions, questionWatcher, reannounceRemote }
+ return { questions, showAwaitingAnswer, answer, questionResponse, openQuestions, pendingQuestion, monitorActivity, hearQuestions, questionWatcher, reannounceRemote }
}
/**
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index 5d4514a74..a32d691b8 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -1423,10 +1423,12 @@ describe('SessionInputController', () => {
const release = controller.acquireControl('s1')
expect(release).toBeTypeOf('function')
expect(controller.acquireControl('s1')).toBeNull()
+ expect(controller.controlHeld('s1')).toBe(true)
controller.submit('s1', 'wait behind control')
expect(injected).toEqual([])
release?.()
+ expect(controller.controlHeld('s1')).toBe(false)
await vi.waitFor(() => expect(injected).toEqual(['wait behind control']))
controller.forget('s1')
})
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index d21dd39bb..bbd28ca08 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -439,6 +439,11 @@ export class SessionInputController {
}
}
+ /** Whether a caller holds this pane (`acquireControl`): a question being answered, a sequence of keys. */
+ controlHeld(sessionId: string): boolean {
+ return this.states.get(sessionId)?.controlLocked === true
+ }
+
onTurnStarted(sessionId: string, userMessage: string): void {
const state = this.state(sessionId)
const session = this.controlSession(sessionId)
diff --git a/cli/src/services/turnsLink.spec.ts b/cli/src/services/turnsLink.spec.ts
index 59779f19d..c458374b0 100644
--- a/cli/src/services/turnsLink.spec.ts
+++ b/cli/src/services/turnsLink.spec.ts
@@ -23,6 +23,20 @@ describe('delivered turns from a service in its own process', () => {
expect(heard).toEqual([])
})
+ it('sends answersQuestion with the delivery', async () => {
+ const query = vi.fn(async () => ({}))
+ const link = turnsLink(query)
+ link.turns.deliver('agent-1', 'hello', 'd1', { answersQuestion: true, writtenAt: 42 })
+ link.turns.deliver('agent-1', 'hello', 'd2')
+ link.turns.deliver('agent-1', 'hello', 'd3', { answersQuestion: true })
+ await flush()
+ expect(query.mock.calls).toEqual([
+ ['deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd1', answersQuestion: true, writtenAt: 42 }],
+ ['deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd2' }],
+ ['deliver', { agentId: 'agent-1', text: 'hello', deliveryId: 'd3', answersQuestion: true, writtenAt: undefined }],
+ ])
+ })
+
it('reads a cancel the core could not make, or never answered, as not taken back', async () => {
expect(await turnsLink(async () => ({ cancelled: false })).cancel('d1')).toBe(false)
expect(await turnsLink(async () => { throw new Error('gone') }).cancel('d1')).toBe(false)
diff --git a/cli/src/services/turnsLink.ts b/cli/src/services/turnsLink.ts
index 1f378f0e9..438bc6e01 100644
--- a/cli/src/services/turnsLink.ts
+++ b/cli/src/services/turnsLink.ts
@@ -41,8 +41,8 @@ export function turnsLink(query: (query: string, payload: Payload) => Promise<Pa
const cancel = async (deliveryId: string): Promise<boolean> =>
(await query('cancel_delivery', { deliveryId }).catch((): Payload => ({}))).cancelled === true
const turns: DeliveryTurns = {
- deliver: (agentId, text, deliveryId) => {
- void query('deliver', { agentId, text, deliveryId }).then(
+ deliver: (agentId, text, deliveryId, options) => {
+ void query('deliver', { agentId, text, deliveryId, ...(options?.answersQuestion ? { answersQuestion: true, writtenAt: options.writtenAt } : {}) }).then(
(answer) => { if (typeof answer.error === 'string') tell({ deliveryId, sessionId: agentId, state: 'rejected', reason: answer.error }) },
() => tell({ deliveryId, sessionId: agentId, state: 'unknown', reason: 'The core did not confirm this delivery.' }),
)
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index be68a9562..e3ec61b06 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -820,6 +820,27 @@ describe('Super Tab native delivery handoff', () => {
expect(prompt).not.toContain('email addresses')
expect(prompt).not.toContain('Report exact revisions')
})
+ it('only the machine\'s own person\'s message may close its question', async () => {
+ const signedIn = (t: ReturnType<typeof setup>, accountId: string | null) =>
+ vi.mocked(t.core.account.identity).mockResolvedValue(accountId ? { accountId, email: `${accountId}@example.com` } : null)
+ const person = { kind: 'person', id: 'p1', name: '[email protected]' }
+ const own = setup({ author: person, text: 'Yes', createdAt: '2026-11-03T05:00:00.000Z' })
+ signedIn(own, 'p1')
+ await own.open().tick()
+ expect(vi.mocked(own.core.turns.deliver).mock.calls[0]![3]).toEqual({ answersQuestion: true, writtenAt: Date.parse('2026-11-03T05:00:00.000Z') })
+ const other = setup({ author: person, text: 'Yes', createdAt: '2026-11-03T05:00:00.000Z' })
+ signedIn(other, 'p2')
+ await other.open().tick()
+ expect(vi.mocked(other.core.turns.deliver).mock.calls[0]![3]).toBeUndefined()
+ const out = setup({ author: person, text: 'Yes' })
+ signedIn(out, null)
+ await out.open().tick()
+ expect(vi.mocked(out.core.turns.deliver).mock.calls[0]![3]).toBeUndefined()
+ const agent = setup({ author: { kind: 'agent', id: 'p1', name: 'Builder' }, text: 'Done' })
+ signedIn(agent, 'p1')
+ await agent.open().tick()
+ expect(vi.mocked(agent.core.turns.deliver).mock.calls[0]![3]).toBeUndefined()
+ })
// Final review: with no --to a reply reaches the coordinator (or, from the coordinator, the task's assignee), so an Engineer
// answering a Reviewer reached the PM, and the PM answering an agent that was not the assignee reached no one.
it('names an agent author with --to in the reply line, and no one for a person', async () => {
@@ -5073,7 +5094,8 @@ describe('a delivery held by a busy pane', () => {
expect(t.saved().entries).toEqual({})
await seconds(t, host, 5)
expect(writes(t)).toBe(122)
- })
+ // 120 simulated ticks: about 2 s here, past the 5 s default on a loaded CI runner.
+ }, 20_000)
it('a cancel pushed while held stops the retry', async () => {
const t = setup(), host = t.open()
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 664fee51b..413520879 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -1916,8 +1916,14 @@ export class SuperTabHost {
const attached = [files.text, sent?.links.length ? ARTIFACT_LINKS(sent.links) : '', elsewhere.length ? LINKS_ELSEWHERE(elsewhere) : '',
approving ? APPROVALS(approving.judged) : '']
.filter(Boolean).join('\n\n')
+ // A person's message closes the question it answers, only the one of this machine's own signed-in account, and only a
+ // question opened after it was written (core/input.ts `beforeTeamWrite`).
+ const answers = fromPerson && !['agent-only', 'native'].includes(String(object(message.source).kind))
+ && !!object(message.author).id && (await this.core.account.identity().catch(() => null))?.accountId === String(object(message.author).id)
+ const writtenAt = typeof message.createdAt === 'string' ? Date.parse(message.createdAt) : NaN
this.core.turns.deliver(entry.harnessId, this.prompt(entry, message, attached, command, quote ?? '', result.buddyNews === true, context,
- result.otherAccount === true), id)
+ result.otherAccount === true), id,
+ ...(answers ? [{ answersQuestion: true as const, ...(Number.isFinite(writtenAt) ? { writtenAt } : {}) }] : []))
return false
}
diff --git a/desktop/lib/state/status_menu.dart b/desktop/lib/state/status_menu.dart
index 57212a5aa..b99ba797b 100644
--- a/desktop/lib/state/status_menu.dart
+++ b/desktop/lib/state/status_menu.dart
@@ -1,4 +1,5 @@
import '../notify/alert_sounds.dart';
+import '../super_tabs/activity.dart';
import '../super_tabs/decisions.dart';
import '../super_tabs/notifications.dart';
import 'app_state.dart';
@@ -196,8 +197,8 @@ void clearStatusMenuNotifications(AppNotifier app, List receipts) {
}
/// The menu bar's Swarm section: in each open Swarm tab, the decisions asked
-/// of this account, then the tags waiting for it, newest first in each, as its
-/// Notifications page lists them. Only from conversations it can read now,
+/// of this account, then the tags waiting for it and not read past, newest
+/// first in each, as Activity lists them. Only from conversations it can read now,
/// none from a Swarm it lost, none signed out: the lists are what was read
/// last, and access can leave before they are read again. Choosing one opens
/// it there (`SuperTabController.openNotice`).
@@ -250,8 +251,10 @@ List<Map<String, Object?>> statusMenuSwarmEntries(AppNotifier app) {
),
);
}
+ final activity = SuperTabActivity.of(controller);
for (final m in SuperTabMentions.of(controller).waiting) {
- if (!readable(m.conversationId)) continue;
+ // Read past, it leaves here as it leaves Activity.
+ if (!readable(m.conversationId) || !activity.mentionUnread(m)) continue;
rows.add(
row(
'mention',
diff --git a/desktop/test/super_tab_menu_bar_notices_test.dart b/desktop/test/super_tab_menu_bar_notices_test.dart
index 06e5bb74e..999180fab 100644
--- a/desktop/test/super_tab_menu_bar_notices_test.dart
+++ b/desktop/test/super_tab_menu_bar_notices_test.dart
@@ -173,6 +173,22 @@ void main() {
expect(rows.last['id'], 'mention-1');
});
+ test('a tag read past leaves the menu bar\'s Swarm rows', () async {
+ final f = SuperTabLaunchFixture(local: true);
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
+ final c = await f.app.superTabs.open(tabId);
+ f.connection.server.tag('message-1', messageSequence: 5);
+ Future<List<Object?>> kinds(int mark) async {
+ f.connection.server.markReadElsewhere('lead', mark);
+ await c.refresh();
+ await SuperTabMentions.of(c).load();
+ return [for (final r in statusMenuSwarmEntries(f.app)) r['kind']];
+ }
+
+ expect(await kinds(4), ['mention']);
+ expect(await kinds(5), isEmpty);
+ });
+
group('a conversation the person can no longer read', () {
/// A tag and a decision in "Offline editing", then that conversation
/// leaves what this account reads.
diff --git a/docs/plans/2026-11-03-notices-clear-on-answer-plan.md b/docs/plans/2026-11-03-notices-clear-on-answer-plan.md
new file mode 100644
index 000000000..e99e34918
--- /dev/null
+++ b/docs/plans/2026-11-03-notices-clear-on-answer-plan.md
@@ -0,0 +1,129 @@
+# Notices Clear On Read And Answer Implementation Plan
+
+> **How this plan runs:** by this project's instructions: one Engineer implements it task by task, test first (each failing test committed before its code), and the review step on the pull request is the one independent review. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A Swarm tag or an agent's open question stops being a notification once its person reads it or answers the agent, wherever they do it.
+
+**Architecture:** The server resolves tags on two new events (a read mark passing the tag; a post that answers the tag's agent), so every client agrees. Desktop's menu bar applies Activity's read rule locally, and the open thread marks nothing read while hidden. The CLI host closes a Claude Code question with Escape when a person's Swarm message for that agent arrives, so the message is delivered as the answer.
+
+**Tech Stack:** TypeScript + Prisma/Mongo (backend), Dart/Flutter (Desktop), TypeScript (CLI daemon); vitest, flutter test.
+
+**Spec:** `docs/specs/2026-11-03-notices-clear-on-answer.md`
+
+## Global Constraints
+
+- `resolvedBy` values: `'read'` for a read mark, `'answer'` for a post to the tag's agent. Existing `'reply'`, `'done'`, `'worker'` unchanged.
+- Only the acting person's own tags (`personId = user.sub`); a Team session is refused before any write, as today.
+- Escape is pressed only for engine `claude`, only on `messageHold === 'question_open'`, only for a delivery from a person; never on `permission_open`.
+- Read rule (the same as `activity.dart mentionUnread`): a tag on a message shown in the chat goes by the chat mark; a tag on a reply shown only in its thread (`threadsOf` gives it a thread) goes by that thread's mark.
+- No phone or web change. No firmware change.
+- Base: `origin/main` b8a64b53e or later, worktree `.claude/worktrees/noticlear`, branch `feat/noti-clear-on-answer`.
+
+## Review Focus
+
+1. A tag in a thread reply that was also sent to the chat (`alsoInChat`) resolves by the chat mark, not only the thread mark: Task 1 test "a reply also sent to the chat clears by the chat mark".
+2. A post in a project chat that `@`-addresses a worker does not clear the PM's tags unless the PM is also a recipient: Task 2 test "a post addressed to another agent leaves the PM's tags".
+3. A person's own Buddy chat clears tags only from coordinators of projects they can read: Task 2 test "the Swarm Buddy chat clears coordinators of readable projects only".
+4. A question still on screen after Escape (a second dialog, an engine that ignores it) is withheld as today, never typed into: Task 5 test "still holds when the question stays after Escape".
+5. The thread pane becoming visible again marks the replies that came while it was hidden, once: Task 4 test "marks the hidden replies when the pane shows again".
+
+---
+
+### Task 1: Reading past a tag resolves it (backend)
+
+**Files:**
+- Modify: `backend/src/superTabs/mentions.ts` (add `resolveRead`; reuse the private `threadsOf`, :313)
+- Modify: `backend/src/superTabs/read/service.ts:232-252` (`markRead`, `markThreadRead`)
+- Create: `backend/integration/superTabTagsClear.test.ts` (fixture as in `integration/superTabReadMarks.test.ts`)
+- Modify: `backend/vitest.super-tabs.config.ts` (include the new file)
+
+**Interfaces:**
+- Produces: `resolveRead(db: Prisma.TransactionClient | PrismaClient, input: { tabId: string; personId: string; conversationId: string; threadId: string | null; sequence: number; now: number }): Promise<number>` — the count it resolved.
+
+- [ ] **Step 1: Write the failing tests** in `superTabTagsClear.test.ts`, `describe('reading clears tags')`:
+ - "reading the chat past a tag resolves it as read": an agent's chat message tags the peer at sequence n; the peer's `POST …/conversations/:id/read` with n. Expect the peer's `mentions?open=true` read to lack it, its row `resolvedBy === 'read'`, and `mentionsWaiting` 0.
+ - "a mark before the tag leaves it waiting": mark n-1 → still listed.
+ - "a chat mark does not clear a tag in a thread reply; its thread mark does": tag in a reply (not `alsoInChat`) to a root; chat mark past it → listed; `POST …/threads/:root/read` past it → resolved `'read'`.
+ - "a reply also sent to the chat clears by the chat mark".
+ - "another person's read leaves my tag": the owner reads the chat past it → the peer's tag still listed.
+- [ ] **Step 2: Run** `cd backend && npm run test:super-tabs -- integration/superTabTagsClear.test.ts` — Expected: FAIL (tags stay listed).
+- [ ] **Step 3: Implement `resolveRead`**: read the person's waiting rows in that conversation (`tagRows`-style indexed filter plus `conversationId`), stop if none; read their messages (`id, sequence, thread, alsoInChat, conversationId`); `threadsOf` gives each reply's thread; resolve (`updateMany` with `waiting`, `resolvedAt: now`, `resolvedBy: 'read'`) the rows whose message sequence ≤ `sequence` and whose thread equals `threadId` (null meaning: no thread from `threadsOf`). Call it in `markRead` with the stored chat sequence and `threadId: null`, and in `markThreadRead` with the stored thread sequence and `threadId`.
+- [ ] **Step 4: Run** the same command — Expected: PASS. Then `cd backend && npx vitest run src/superTabs/mentions.test.ts src/superTabs/read` — Expected: PASS.
+- [ ] **Step 5: Commit** `feat(swarm): reading past a tag resolves it`.
+
+### Task 2: A post that answers an agent resolves that agent's tags (backend)
+
+**Files:**
+- Modify: `backend/src/superTabs/mentions.ts` (add `answeredAgents`, `resolveByAnswer`)
+- Modify: `backend/src/superTabs/store.ts:1765` (call after `resolveByReply`)
+- Test: `backend/src/superTabs/mentions.test.ts` (pure), `backend/integration/superTabTagsClear.test.ts` (stored)
+
+**Interfaces:**
+- Produces: `answeredAgents(state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, group: Conversation, recipients: readonly string[]): string[]` — the recipients that are agents in `state.agents`; plus, when `group` is the actor's own Buddy chat, the coordinator (`leadId` of the project's lead conversation) of each project the Buddy speaks for: every project the actor can read (`canReadProject`) for the Swarm Buddy chat (`isSwarmBuddyChat`), the chat's own project for a project Buddy chat. Deduplicated.
+- Produces: `resolveByAnswer(tx: Tx, tabId: string, personId: string, agentIds: readonly string[], now: number): Promise<void>` — `updateMany` of the person's waiting tags with `authorAgentId` in `agentIds` and `createdAt ≤ now`, `resolvedBy: 'answer'`; no-op for an empty list.
+
+- [ ] **Step 1: Write the failing tests.**
+ - `mentions.test.ts` `describe('answeredAgents')`: "a plain post in a project chat answers its coordinator" (recipients from `applyCommand` message.send's draft); "a post addressed to another agent leaves the PM's tags" (`recipientIds: [worker]` → `[worker]` only); "the Swarm Buddy chat clears coordinators of readable projects only" (a private project the peer cannot read is left out); "a project Buddy chat answers its Buddy and that project's coordinator".
+ - `superTabTagsClear.test.ts` `describe('answering clears tags')`: "posting in my Buddy chat clears the PM's tag in a task chat" (PM tags the peer in a task conversation; the peer posts in their Buddy chat → tag resolved `'answer'`); "a tag by another agent stays".
+- [ ] **Step 2: Run** `cd backend && npx vitest run src/superTabs/mentions.test.ts` and the integration command from Task 1 — Expected: FAIL (`answeredAgents` not exported; tag still listed).
+- [ ] **Step 3: Implement** both functions; in `store.ts` after `resolveByReply`, for `message.send` by a person: find the posted draft in `effects.messages` (`id === effects.result.messageId`), and call `resolveByAnswer(tx, tabId, actor.userId, answeredAgents(effects.state, actor, group, draft.recipients), context.now)`.
+- [ ] **Step 4: Run** both commands — Expected: PASS. Then `cd backend && npm run test:super-tabs` — Expected: PASS.
+- [ ] **Step 5: Commit** `feat(swarm): a post that answers an agent clears its tags`.
+
+### Task 3: The menu bar lists only tags not read past (Desktop)
+
+**Files:**
+- Modify: `desktop/lib/state/status_menu.dart:252-264` (`statusMenuSwarmEntries`)
+- Test: `desktop/test/super_tab_menu_bar_notices_test.dart`
+
+**Interfaces:**
+- Consumes: `SuperTabActivity.of(controller).mentionUnread(SuperTabMention)` (`activity.dart:174`).
+
+- [ ] **Step 1: Write the failing test** "a tag read past leaves the menu bar's Swarm rows": a controller with a waiting tag at sequence 5 and chat read mark 5 → `statusMenuSwarmEntries(app)` has no `mention` row; mark 4 → it has one.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_menu_bar_notices_test.dart` — Expected: FAIL.
+- [ ] **Step 3: Implement**: skip a waiting tag when `!SuperTabActivity.of(controller).mentionUnread(m)`.
+- [ ] **Step 4: Run** the same command and `flutter test test/status_menu_test.dart` — Expected: PASS.
+- [ ] **Step 5: Commit** `fix(desktop): the menu bar drops a tag once it is read`.
+
+### Task 4: A hidden thread pane marks nothing read (Desktop, #15)
+
+> Dropped: main fixed this in #2711 (`threadPaneHidden`) while this branch was open.
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart:862-877, 1436-1445` (`threadPaneVisible`, `_seeThread`)
+- Modify: `desktop/lib/super_tabs/view.dart:266-277, 777` (set and clear the callback)
+- Test: `desktop/test/super_tab_thread_tags_test.dart`
+
+**Interfaces:**
+- Produces: `bool Function()? threadPaneVisible` on `SuperTabController`; null (no view) counts as visible, as today.
+
+- [ ] **Step 1: Write the failing tests**: "a reply to the open thread is not marked read while the pane is hidden" (open a thread, `threadPaneShown()`, set `threadPaneVisible = () => false`, a poll page brings a reply with its `threads` summary → no `POST …/threads/<root>/read`); "marks the hidden replies when the pane shows again" (then visible and `threadPaneShown()` → exactly one mark at the reply's sequence).
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_thread_tags_test.dart` — Expected: FAIL (a mark is posted while hidden).
+- [ ] **Step 3: Implement**: at the top of `_seeThread`, if `threadPaneVisible?.call() == false`, set `_threadUnshown = true` and return; the view sets `c.threadPaneVisible = () => _viewIsVisible` in `initState` (beside `chatShown`) and clears it in `dispose`. The existing `threadPaneShown()` call in `_readVisibleTailAfterFrame` (view.dart:513-517) catches up when it shows.
+- [ ] **Step 4: Run** the same command and `flutter test test/super_tab_controller_test.dart test/super_tab_threads_test.dart` — Expected: PASS.
+- [ ] **Step 5: Commit** `fix(desktop): a thread hidden behind another app marks nothing read`.
+
+### Task 5: A person's Swarm message closes the question it answers (CLI)
+
+**Files:**
+- Modify: `cli/src/core/api.ts:237` (`deliver` options), `cli/src/services/turnsLink.ts:44-45` (send them), `cli/src/core/deliveries.ts` (`answer('deliver')` keeps them; `answersQuestion`), `cli/src/core/main.ts:1373` (wire into input deps), `cli/src/core/input.ts:69, 165-171` (`answersQuestion` dep; `beforeTeamWrite`), `cli/src/superTabs/host.ts:1919` (pass it for a person's message)
+- Test: `cli/src/core/input.spec.ts`, `cli/src/core/deliveries.spec.ts`, `cli/src/services/turnsLink.spec.ts`, `cli/src/superTabs/host.spec.ts`
+
+**Interfaces:**
+- Produces: `export interface DeliveryOptions { answersQuestion?: true }` in `core/api.ts`; `deliver(agentId: string, text: string, deliveryId: string, options?: DeliveryOptions): void`.
+- Produces: `answersQuestion(deliveryId: string): boolean` from `core/deliveries.ts` (true while that delivery is unsettled and was sent with the option); `InputDeps.answersQuestion?: (deliveryId: string) => boolean`.
+
+- [ ] **Step 1: Write the failing tests.**
+ - `input.spec.ts`: "a person's Swarm message closes a Claude question and is delivered" (screen `messageHold: 'question_open'`, `answersQuestion` true, engine `claude`; after one `Escape` key the next read has no hold → `beforeTeamWrite` returns null and `sendKey` saw `Escape` once); "never presses Escape on a permission prompt" (`permission_open` → `team_waiting_user`, no key); "an agent's message still waits" (`answersQuestion` false → hold, no key); "another engine still waits" (`codex`); "still holds when the question stays after Escape" (second read still `question_open` → `team_waiting_user`, one key only).
+ - `deliveries.spec.ts`: "remembers a delivery that answers a question until it settles".
+ - `turnsLink.spec.ts`: "sends answersQuestion with the delivery".
+ - `host.spec.ts`: "a person's message is delivered as answering a question, an agent's is not".
+- [ ] **Step 2: Run** `cd cli && npx vitest run src/core/input.spec.ts src/core/deliveries.spec.ts src/services/turnsLink.spec.ts src/superTabs/host.spec.ts` — Expected: FAIL.
+- [ ] **Step 3: Implement**: the host passes `{ answersQuestion: true }` when `object(message.author).kind === 'person'` and the turn is not Buddy news, `agent-only` or `native`; `turnsLink` adds it to the `deliver` query; `core/deliveries.ts` keeps the ids in a Set dropped in `settled`; in `beforeTeamWrite`, when the reading's `messageHold === 'question_open'`, `session.engine === 'claude'` and `deps.answersQuestion?.(deliveryId)`, press `Escape` through `deviceInput().legacyWrite(… keyTerminalAction(id, 'Escape'))`, log `[inject] <sid> question closed for a person's message`, capture and read again, and return `deliveryHold` of the new reading.
+- [ ] **Step 4: Run** the same command — Expected: PASS. Then `cd cli && npm run test:core && npm run test:harnessd` — Expected: PASS.
+- [ ] **Step 5: Commit** `feat(cli): a person's Swarm message closes the question it answers`.
+
+### Task 6: Pull request
+
+- [ ] Push `feat/noti-clear-on-answer`, open a PR to `main` with the spec link, what each task changes, and the tests run (backend super-tabs suite, Desktop files above on macOS, CLI `test:core` and `test:harnessd`). Mark it ready so `ci/required` runs.
+- [ ] Send the PR to Diego's Buddy for the PM to merge (`buddy_post.py`, English): "Please merge PR #N with make merge-pr once ci/required is green; fix any conflict with main and merge. Name diego as the requester."
diff --git a/docs/specs/2026-11-03-notices-clear-on-answer.md b/docs/specs/2026-11-03-notices-clear-on-answer.md
new file mode 100644
index 000000000..9df76538d
--- /dev/null
+++ b/docs/specs/2026-11-03-notices-clear-on-answer.md
@@ -0,0 +1,116 @@
+# Notices clear when you read or answer (Diego, 2026-11-03)
+
+## What Diego asked
+
+1. When a person settles something by chatting with the PM or the Buddy directly, not through the notification UI, the
+ notification list still clears.
+2. When a person opens a thread and reads it, its notifications clear by themselves.
+
+Both apply to the two kinds of rows in the menu bar list:
+
+- **Swarm tags** ("Orion tagged you"): `SuperTabMention` rows on the server, listed by Desktop's menu bar, Activity's
+ Needs you, the phone and every badge.
+- **Ready questions** ("Harness Swarm lead coordination – What do you want to do?"): an agent's open terminal question
+ (Claude Code's AskUserQuestion) on this Mac, a `blockedAgents` entry in Desktop.
+
+Choices Diego made: both kinds clear; a post to an agent clears **every** open tag that agent made for that person in the
+Swarm.
+
+## How it works today (main b8a64b53e)
+
+- A tag resolves only when the tagged person posts in the **same conversation** (`mentions.ts resolveByReply`, called from
+ `store.ts:1765`) or presses Done (`mention.done`). Reading resolves nothing.
+- Activity hides a tag read past its message (`activity.dart mentionUnread`: the chat mark, or the thread mark for a thread
+ reply), but the menu bar lists every unresolved tag (`status_menu.dart:253`), and the phone and the badges count the
+ server's unresolved ones (`mentionsWaiting`). Four surfaces, two rules.
+- While an agent's pane shows a question, a Swarm message to it is withheld (`teamHold` → `team_waiting_user`,
+ `core/input.ts deliveryHold`). The person's answer in the chat never reaches the agent, and the Ready row stays.
+ Diego's daemon logged `withheld: team_waiting_user` every 1-2 s for both Lead coordination sessions on 2026-11-03.
+- A thread left open beside the chat marks its replies read while the app is hidden (issue sent 2026-11-03 as #15:
+ `controller.dart _seeThread` gates only on a restored thread). With reading now resolving tags, this would clear tags
+ nobody saw, so it is fixed here too.
+
+## Behaviour
+
+### Reading clears a tag (server)
+
+When a person's read mark moves past a tag's message, that tag resolves with `resolvedBy: 'read'`:
+
+- a tag on a message shown in the chat (a top-level message, a thread root, or a reply also sent to the chat) resolves when
+ the **chat** mark reaches its sequence (`markRead`);
+- a tag on a thread reply shown only in its thread resolves when that **thread's** mark reaches its sequence
+ (`markThreadRead`).
+
+This is the rule Desktop's `mentionUnread` already uses, so Activity, the menu bar, the phone and the badges agree.
+
+Mark all read (Desktop, phone) moves every chat mark to its newest message, so it resolves every tag those marks pass, as
+Slack's does. Desktop's Undo still works: it holds the marks back until its time is up (controller.dart `markAllRead`),
+so nothing is resolved before then. A tag held for a task's
+no-worker grace (`holdUntil`) that is read or answered before its time is never listed, as a reply already does today.
+
+### Answering an agent clears its tags (server)
+
+When a person posts (`message.send`), besides today's same-conversation rule, every open tag of theirs in the Swarm made by
+an agent the post **answers** resolves with `resolvedBy: 'answer'`. The post answers:
+
+- each agent among the post's recipients (who it was addressed to, the coordinator a plain post in a project chat reaches,
+ the Buddy or session a Buddy-chat post reaches);
+- in the person's own Buddy chat, also the coordinator of each project the Buddy speaks for: every project they can read
+ for the one Swarm Buddy chat, the chat's own project for a project Buddy chat. The Buddy relays to those PMs, so talking
+ to the Buddy is talking to them.
+
+Tags made by people, and by agents the post does not answer, stay.
+
+### The menu bar lists what Activity lists (Desktop)
+
+The menu bar's Swarm rows leave out a tag read past (`mentionUnread`), as Activity does, so a read clears its row at once,
+before the server's next answer.
+
+### A person's message closes the question it answers (CLI)
+
+When a Swarm message from **the machine's own person** is due for a Claude Code session whose pane shows a question, the
+host presses Escape once, waits for the pane to redraw, and delivers the message if nothing else holds it. Claude Code
+ends the question as declined and the message arrives as the answer; the daemon's `question_close` drops the Ready row
+everywhere.
+
+Escape is pressed only when all of these hold, checked again under the pane's writer lock just before the key:
+
+- the pane reads `question_open` and shows the same question as the reading that decided it;
+- the core holds a pending AskUserQuestion record for that agent (not only the screen heuristic);
+- the message was written after that question opened (a message from before it answers something else);
+- the core may still write the delivery (`canWrite`), and no question answer (dial, card, phone) holds the terminal;
+- the question's free-text row holds no typed answer.
+
+Never for a permission prompt (`permission_open`), never for a message from an agent or from another person of the Swarm
+(they keep waiting, as today), never for another engine (Codex and the others keep waiting).
+
+### A hidden thread pane marks nothing read (Desktop, #15)
+
+The open thread's read mark moves only while its pane is on screen, so reading cannot clear a tag nobody saw. This landed
+on main separately (#2711, `threadPaneHidden`), which this work relies on.
+
+## Design
+
+- **Growth:** no new rows. Two more ways to set `resolvedAt` on existing `SuperTabMention` rows, which the 30-day TTL
+ index already deletes.
+- **Concurrency:** each resolve is one `updateMany` on the person's own rows: right after the read-mark write (`markRead`,
+ `markThreadRead`, not in its transaction) or inside the command transaction (`message.send`). Resolving is idempotent:
+ `waiting` in the filter.
+- **Read cost:** a read-mark write reads the person's waiting tags in that one conversation (indexed by tabId, personId,
+ createdAt, capped at 500 as `tagRows`) and their messages by id; most marks find none and stop after the first read. A post
+ adds one `updateMany` keyed by the person and the answered agent ids.
+- **Scale:** at 10x tags per person the first read is still one indexed page; the warning metric is the existing
+ `mentionsWaiting` read time.
+- **Compatibility:** `resolvedBy` is a free string; Desktop and the phone only test it for null, so `'read'` and `'answer'`
+ show as answered in old clients. An old Desktop still lists read tags in its menu bar until the server resolves them,
+ which it now does on the read. An old daemon keeps withholding; nothing breaks.
+- **Migration + rollback:** none. Rolling back stops new resolves; resolved rows stay resolved.
+- **Audience:** the server resolves only the acting person's own tags (`personId = user.sub`); a Team session has no marks
+ and is refused as today.
+- **Identity:** the person's own account, never the machine owner's.
+- **Failure:** a resolve after a read mark is best-effort: a failure is logged as a warning and the mark still answers
+ (the tag stays waiting until a later mark passes it, and the new Desktop menu bar already hides it). A resolve in a post
+ fails the command with its other writes. Escape is logged either way (`question closed for a person's message` or
+ `Escape sent, question still open`); if the pane still holds after it, the delivery is withheld as today and retried.
+ A Team session resolves nothing, by read or by post.
+- **Platforms:** server for every client; Desktop macOS/Linux/Windows menu bar; the CLI change is engine `claude` only.