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.

Backend: a Lead tags people in its messages (#1678)

0xken154040d881f8ce
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 417dbd808..e0c761256 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -17,6 +17,7 @@ import { nextMachineShareGrants } from '../src/lib/machineSharePolicy.js'
import { DEFAULT_ROUTING_POLICY } from '../src/superTabs/routingPolicy.js'
import { stableId, type SuperTabState } from '../src/superTabs/model.js'
import { ensureTerminalExpiry, TERMINAL_EXPIRY_MS } from '../src/superTabs/terminal.js'
+import { ensureMentionExpiry, MENTION_EXPIRY_MS } from '../src/superTabs/mentions.js'
// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
let replica: MongoMemoryReplSet
@@ -2606,3 +2607,103 @@ describe('machine removal', () => {
expect(((await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state as unknown as SuperTabState).machineCleanups).toBeUndefined()
})
})
+
+describe('Lead mentions', () => {
+ const DAY = 24 * 60 * 60_000
+ async function tagged(role: 'collaborator' | 'viewer' = 'collaborator') {
+ const { tab, lead } = await fixture()
+ await invite(tab, role)
+ const group = (await run(tab, { type: 'conversation.create', title: 'Copy review', brief: '', checks: [] })).result.conversationId as string
+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })
+ const text = `Please confirm the welcome copy. ${'x'.repeat(300)}`
+ const messageId = (await run(tab, { type: 'message.send', conversationId: group, text, replyTo: null, recipientIds: [], mentions: [peer.sub] },
+ host, lead)).result.messageId as string
+ return { tab, lead, group, text, messageId }
+ }
+ const list = async (tab: string, user: AuthUser, state: 'waiting' | 'earlier') => {
+ const response = await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/mentions?state=${state}`, headers: { authorization: `Bearer ${user.sub}` } })
+ expect(response.statusCode, response.body).toBe(200)
+ return response.json().data.mentions as Array<Record<string, unknown>>
+ }
+ const waiting = async (tab: string, user: AuthUser, reader = store) => (await reader.read(user, tab)).state as SuperTabState & { mentionsWaiting?: number }
+
+ it('lists a tag only for the tagged person, with the message, and counts it on their state alone', async () => {
+ const { tab, lead, group, text, messageId } = await tagged()
+ const [mention, ...rest] = await list(tab, peer, 'waiting')
+ expect(rest).toEqual([])
+ expect(mention).toEqual({ id: expect.any(String), projectId: 'lead', projectName: 'Pilot', conversationId: group, conversationTitle: 'Copy review',
+ messageId, leadName: expect.any(String), text: text.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null })
+ expect(mention!.leadName).toBe((await waiting(tab, owner)).agents.find(a => a.id === lead)!.displayName)
+ expect(await list(tab, owner, 'waiting')).toEqual([])
+ expect(await list(tab, peer, 'earlier')).toEqual([])
+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(1)
+ expect((await waiting(tab, owner)).mentionsWaiting).toBe(0)
+ expect((await store.read(host, tab, lead)).state).not.toHaveProperty('mentionsWaiting')
+ expect((await store.messages(owner, tab, group, {})).messages.find(m => m.id === messageId)!.mentions).toEqual([peer.sub])
+ })
+
+ 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)
+ 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([])
+ expect(await list(tab, peer, 'earlier')).toEqual([expect.objectContaining({ resolvedBy: 'reply', resolvedAt: expect.any(String) })])
+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(0)
+ })
+
+ it('resolves on the person’s reply inside a thread', async () => {
+ const { tab, group, messageId } = await tagged()
+ await run(tab, { type: 'message.send', conversationId: group, text: 'Confirmed.', replyTo: messageId, recipientIds: [] }, peer)
+ expect(await list(tab, peer, 'waiting')).toEqual([])
+ expect(await list(tab, peer, 'earlier')).toEqual([expect.objectContaining({ messageId, resolvedBy: 'reply' })])
+ })
+
+ it('lets a tagged viewer mark it done', async () => {
+ const { tab } = await tagged('viewer')
+ const [mention] = await list(tab, peer, 'waiting')
+ await run(tab, { type: 'mention.done', mentionId: mention!.id as string }, peer)
+ expect(await list(tab, peer, 'earlier')).toEqual([expect.objectContaining({ id: mention!.id, resolvedBy: 'done' })])
+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(0)
+ })
+
+ it('resolves when the person marks it done, and nobody else can', async () => {
+ const { tab } = await tagged()
+ const [mention] = await list(tab, peer, 'waiting')
+ const done: Command = { type: 'mention.done', mentionId: mention!.id as string }
+ await expect(run(tab, done)).rejects.toThrow('This mention is unavailable.')
+ const operationId = randomUUID()
+ await run(tab, done, peer, undefined, operationId)
+ await run(tab, done, peer, undefined, operationId)
+ expect(await list(tab, peer, 'waiting')).toEqual([])
+ expect(await list(tab, peer, 'earlier')).toEqual([expect.objectContaining({ id: mention!.id, resolvedBy: 'done' })])
+ })
+
+ it('drops a tag 30 days after it was made and from a conversation the person can no longer read', async () => {
+ const { tab } = await tagged()
+ const later = new SuperTabStore(db, () => Date.now() + 30 * DAY + 1000)
+ expect((await waiting(tab, peer, later)).mentionsWaiting).toBe(0)
+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(1)
+ await run(tab, { type: 'project.sharing', projectId: 'lead', visibility: 'private', memberIds: [] })
+ expect(await list(tab, peer, 'waiting')).toEqual([])
+ expect((await waiting(tab, peer)).mentionsWaiting).toBe(0)
+ await ensureMentionExpiry(db)
+ const indexes = await db.$runCommandRaw({ listIndexes: 'SuperTabMention' }) as { cursor: { firstBatch: Array<{ key: object; expireAfterSeconds?: number }> } }
+ expect(indexes.cursor.firstBatch).toContainEqual(expect.objectContaining({ key: { createdAt: 1 }, expireAfterSeconds: MENTION_EXPIRY_MS / 1000 }))
+ })
+
+ it('keeps the stored tab and older messages as the previous backend reads and writes them', async () => {
+ const { tab, group } = await tagged()
+ const stored = (await db.superTab.findUniqueOrThrow({ where: { id: tab } })).state
+ expect(JSON.stringify(stored)).not.toMatch(/mention/i)
+ // A message the previous backend wrote has no mentions field; its next post omits mentions too.
+ await db.$runCommandRaw({ insert: 'SuperTabMessage', documents: [{ _id: 'old-backend-row', tabId: tab, conversationId: group, sequence: 1,
+ author: { kind: 'person', id: owner.sub, name: owner.email, membershipGeneration: tab }, text: 'Written before mentions.',
+ replyTo: null, recipientIds: [], createdAt: { $date: new Date().toISOString() } }] })
+ await run(tab, { type: 'message.send', conversationId: group, text: 'Old shape.', replyTo: null, recipientIds: [] })
+ const rows = (await store.messages(owner, tab, group, {})).messages
+ expect(rows.find(m => m.id === 'old-backend-row')!.mentions).toEqual([])
+ expect(rows.at(-1)!.mentions).toEqual([])
+ })
+})
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index 9ccf172bd..ee7ad78ee 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1032,11 +1032,32 @@ model SuperTabMessage {
attachments Json?
replyTo String?
recipientIds String[]
+ /// People a Lead tagged (superTabs/mentions.ts); absent on older rows.
+ mentions String[]
createdAt DateTime @default(now())
@@index([tabId, conversationId, sequence])
}
+/// A Lead's tag of a person, waiting until they reply in that conversation or mark it done (superTabs/mentions.ts).
+/// Kept out of the tab state so an older backend still reads it; removed 30 days after createdAt by a TTL index.
+model SuperTabMention {
+ id String @id @map("_id")
+ tabId String
+ personId String
+ projectId String
+ conversationId String
+ messageId String
+ authorAgentId String
+ createdAt DateTime
+ resolvedAt DateTime?
+ /// reply | done
+ resolvedBy String?
+
+ @@index([tabId, personId, createdAt])
+ @@index([tabId, conversationId, personId])
+}
+
/// One uploaded file, which one message of the actor that uploaded it can send once.
model SuperTabAttachment {
id String @id @map("_id")
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index c1edf8e42..fb137535b 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -40,6 +40,7 @@ const deliveryAction = z.discriminatedUnion('type', [
z.object({ type: z.literal('ack'), claimId: id, receipt: z.string().min(1).max(2000), uncertain: z.boolean() }).strict(),
z.object({ type: z.literal('hold'), claimId: id, reason: holdReason }).strict(),
])
+const mentionQuery = z.object({ state: z.enum(['waiting', 'earlier']) }).strict()
const savePolicy = z.object({ revision: z.number().int().nonnegative().safe(), policy: routingPolicySchema }).strict()
const stop = z.object({ assignmentId: id, receipt: z.string().min(1).max(2000) }).strict()
@@ -151,6 +152,9 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
return uploaded ?? fail('INVALID_ATTACHMENT', 'Attach one file.', 400)
}))
})
+ app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof mentionQuery> }>('/api/super-tabs/:tabId/mentions',
+ { preHandler: [validateParams(tabParams), validateQuery(mentionQuery)] },
+ (req, reply) => respond(reply, () => store.mentions(req.user!, req.params.tabId, req.query.state)))
app.get<{ Params: z.infer<typeof startParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/starts/:startId',
{ preHandler: [validateParams(startParams), validateQuery(agentQuery)] },
(req, reply) => respond(reply, () => store.start(req.user!, req.params.tabId, req.params.startId, req.query.asAgentId)))
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index ce1fb4382..170126c04 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -2055,3 +2055,52 @@ describe('the Local models add-on', () => {
expect(effectivePolicy(saved, { localModels: { quality: 2, enabled: true } }).policy.localModels).toEqual({ quality: 2, enabled: true })
})
})
+
+describe('Lead mentions', () => {
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const send = (conversationId: string, mentions: string[]): Command => ({ type: 'message.send', conversationId, text: 'Please confirm the copy.',
+ replyTo: null, recipientIds: [], mentions })
+ const swarm = () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)
+ f.invite()
+ const created = f.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: 'Secret' }).result as { projectId: string; conversationId: string }
+ return { f, lead, secret: { ...created, lead: f.add('secret-lead', 'owner', created.conversationId, true) } }
+ }
+
+ it('lets a project Lead tag readers in its own project and puts them on the message once', () => {
+ const { f, lead } = swarm(), group = f.group()
+ expect(f.run(send(group, ['peer', 'owner', 'peer']), as(lead)).messages[0]!.mentions).toEqual(['peer', 'owner'])
+ expect(f.run(send('lead', []), as(lead)).messages[0]).not.toHaveProperty('mentions')
+ })
+
+ it('refuses a person, a non-Lead agent and another project’s Lead', () => {
+ const { f, lead, secret } = swarm(), group = f.group(), worker = f.add('worker', 'owner', group)
+ expect(() => f.run(send(group, ['peer']))).toThrow('Only a project’s Lead can tag people.')
+ expect(() => f.run(send(group, ['peer']), as(worker))).toThrow('Only a project’s Lead can tag people.')
+ expect(() => f.run(send(group, ['owner']), as(secret.lead))).toThrow('This project is unavailable.')
+ expect(() => f.run(send(f.state.leadsConversationId!, ['owner']), as(lead))).toThrow('A Lead can tag people only in its own project’s conversations.')
+ })
+
+ it('refuses a person who cannot read the conversation or is not in the Swarm', () => {
+ const { f, secret } = swarm()
+ expect(() => f.run(send(secret.conversationId, ['peer']), as(secret.lead))).toThrow('[email protected] cannot read this conversation.')
+ expect(() => f.run(send(secret.conversationId, ['stranger']), as(secret.lead))).toThrow('Tag a person in this Swarm.')
+ expect(f.run(send(secret.conversationId, ['owner']), as(secret.lead)).messages[0]!.mentions).toEqual(['owner'])
+ })
+
+ it('tags at most five people', () => {
+ expect(commandSchema.safeParse(send('lead', ['a', 'b', 'c', 'd', 'e'])).success).toBe(true)
+ expect(commandSchema.safeParse(send('lead', ['a', 'b', 'c', 'd', 'e', 'f'])).success).toBe(false)
+ })
+
+ it('lets only the tagged person mark a mention done, a viewer included', () => {
+ const f = fixture(), lead = f.add('lead', 'owner', 'lead', true)
+ f.invite('viewer')
+ const mention = { id: 'mention-1', personId: 'peer', conversationId: 'lead' }
+ const done: Command = { type: 'mention.done', mentionId: 'mention-1' }
+ expect(f.run(done, peer, { mention }).result).toEqual({ mentionId: 'mention-1' })
+ expect(() => f.run(done, owner, { mention })).toThrow('This mention is unavailable.')
+ expect(() => f.run(done, peer)).toThrow('This mention is unavailable.')
+ expect(() => f.run(done, as(lead), { mention })).toThrow('This mention is unavailable.')
+ })
+})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index bf9dd91dd..cc411a4cf 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -11,6 +11,7 @@ import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type Rou
import { routingOverrideSchema } from './routingPolicy.js'
import { agentTarget, askedInSchema, broken, MAX_RULES, RULE_MESSAGE_MS, ruleSchema, ruleTextSchema, startTarget, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
+import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'
import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, type TerminalRequest } from './terminal.js'
import { agentKind, agentProjectId, agentSetRole, deleteProject, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
@@ -112,7 +113,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('member.remove'), userId: id }).strict(),
// Text may be empty when the message carries files; applyCommand checks that one of them is there.
z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),
- attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional() }).strict(),
+ attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional() }).strict(),
+ z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),
z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),
z.object({ type: z.literal('work.define'), conversationId: id, brief: text.optional(), task: task.optional(), checks: z.array(check).min(1).max(40) }).strict()
.refine(c => c.task !== undefined || c.brief !== undefined, 'Provide a task or brief.')
@@ -163,6 +165,8 @@ export interface CommandContext {
abandonedStartIds?: string[]
/** The request an `agent.screenResult` / `agent.inputResult` answers, read from SuperTabTerminalRequest by the store. */
terminalRequest?: TerminalRequest
+ /** The mention `mention.done` names, read from SuperTabMention by the store. */
+ mention?: MentionTarget
}
/** Messages in a row between the Lead and its worker after which the Lead's message is no longer delivered automatically. */
@@ -269,6 +273,8 @@ function dropClosing(state: SuperTabState, keep: (request: NonNullable<SuperTabS
* access after the person has been removed from a private project. */
export function authorizeCommandAccess(state: SuperTabState, actor: Actor, command: Command, context: Partial<CommandContext> = {}) {
if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return
+ // Marking one's own tag done changes only one's own list, so a viewer may do it too.
+ if (command.type === 'mention.done') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
// An invitation's group is only where the person lands, and invite.create replaces a deleted one (inviteLanding).
@@ -357,6 +363,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
return effects
}
+ if (command.type === 'mention.done') {
+ author(state, actor)
+ if (actor.kind !== 'person' || context.mention?.id !== command.mentionId || context.mention.personId !== actor.userId) {
+ fail('NOT_FOUND', 'This mention is unavailable.', 404)
+ }
+ result.mentionId = command.mentionId
+ return effects
+ }
+
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving)
authorizeCommandAccess(state, actor, command, context)
@@ -365,9 +380,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
brief: group.brief, checks: group.checks, assignment: group.assignment }))
}
const message = (conversationId: string, body: string, recipients: string[] = [], replyTo: string | null = null, source?: Record<string, unknown>,
- attachments?: Attachment[]) => {
+ attachments?: Attachment[], mentions?: string[]) => {
effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),
- ...(attachments?.length ? { attachments } : {}) })
+ ...(attachments?.length ? { attachments } : {}), ...(mentions?.length ? { mentions } : {}) })
result.messageId = operationId
}
/** An agent starts or assigns only what the route chose; a person may still do either by hand. */
@@ -1176,6 +1191,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const ids = [...new Set(command.attachmentIds ?? [])]
const attachments = ids.map(id => context.attachments?.find(a => a.id === id) ?? fail('ATTACHMENT_UNAVAILABLE', 'Upload this file again before sending it.', 400))
if (!command.text && !attachments.length) fail('TEXT_REQUIRED', 'Write a message or attach a file.', 400)
+ const mentions = checkMentions(state, actor, group, command.mentions ?? [])
if (command.replyTo && (!context.reply || context.reply.id !== command.replyTo || context.reply.conversationId !== group.id)) {
fail('INVALID_REPLY', 'Reply to a message in this conversation.', 400)
}
@@ -1201,7 +1217,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!group.agentIds.includes(id)) fail('INVALID_RECIPIENT', 'Choose an agent in this conversation.', 400)
}
// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.
- message(group.id, command.text, recipients, command.replyTo, undefined, attachments)
+ message(group.id, command.text, recipients, command.replyTo, undefined, attachments, mentions)
break
}
case 'delivery.resolve': {
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
new file mode 100644
index 000000000..8b2f02224
--- /dev/null
+++ b/backend/src/superTabs/mentions.ts
@@ -0,0 +1,92 @@
+/** A Lead tags people in its message; each tag waits in the person's Swarm-wide list until they reply in that
+ * conversation or mark it done. Tags live in SuperTabMention, never in the tab state, so an older backend still
+ * reads and writes a tab that has them. Called inside SuperTabStore's transactions. */
+import type { Prisma, PrismaClient } from '@prisma/client'
+import { fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
+import { canReadProject, groupProject, ledProject, projectOf } from './projects.js'
+
+type Tx = Prisma.TransactionClient
+export const MAX_MENTIONS = 5
+/** A tag drops off the list this long after it was made: refused on read, and removed by a TTL index. */
+export const MENTION_EXPIRY_MS = 30 * 24 * 60 * 60_000
+/** The mention `mention.done` names, read from this tab by the store. */
+export interface MentionTarget { id: string; personId: string; conversationId: string }
+/** Mongo omits unset fields, so `resolvedAt: null` alone would miss a row written without it. */
+const waiting: Prisma.SuperTabMentionWhereInput = { OR: [{ resolvedAt: null }, { resolvedAt: { isSet: false } }] }
+
+/** Run by the singleton worker at startup, like the terminal answer expiry. */
+export async function ensureMentionExpiry(db: PrismaClient): Promise<void> {
+ await db.$runCommandRaw({ createIndexes: 'SuperTabMention', indexes: [{ key: { createdAt: 1 }, name: 'mention_expiry',
+ expireAfterSeconds: MENTION_EXPIRY_MS / 1000 }] })
+}
+
+/** Only the project's Lead tags, only in that project's conversations, and only people who can read the conversation. */
+export function checkMentions(state: SuperTabState, actor: Actor, group: Conversation, personIds: string[]): string[] {
+ const ids = [...new Set(personIds)]
+ if (!ids.length) return ids
+ const led = actor.kind === 'agent' ? ledProject(state, actor.agentId) : undefined
+ if (!led) fail('MENTION_FORBIDDEN', 'Only a project’s Lead can tag people.', 403)
+ if (isLeads(group) || groupProject(state, group).id !== led.id) fail('MENTION_FORBIDDEN', 'A Lead can tag people only in its own project’s conversations.', 403)
+ for (const id of ids) {
+ const member = state.people.find(p => p.id === id) ?? fail('INVALID_MENTION', 'Tag a person in this Swarm.', 400)
+ if (!canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, led)) {
+ fail('INVALID_MENTION', `${member.email} cannot read this conversation.`, 400)
+ }
+ }
+ return ids
+}
+
+export async function writeMentions(tx: Tx, tabId: string, state: SuperTabState, messages: MessageDraft[], now: number): Promise<void> {
+ const data = messages.flatMap(message => (message.mentions ?? []).map(personId => ({
+ id: stableId(tabId, message.id, personId), tabId, personId, projectId: state.conversations.find(c => c.id === message.conversationId)!.projectId ?? 'lead',
+ conversationId: message.conversationId, messageId: message.id, authorAgentId: message.author.id,
+ createdAt: new Date(now), resolvedAt: null, resolvedBy: null,
+ })))
+ if (data.length) await tx.superTabMention.createMany({ data })
+}
+
+/** Any post by the tagged person in that conversation answers every earlier tag there, in a thread or not. */
+export async function resolveByReply(tx: Tx, tabId: string, conversationId: string, personId: string, now: number): Promise<void> {
+ await tx.superTabMention.updateMany({ where: { tabId, conversationId, personId, createdAt: { lte: new Date(now) }, ...waiting },
+ data: { resolvedAt: new Date(now), resolvedBy: 'reply' } })
+}
+
+export async function readMention(tx: Tx, tabId: string, id: string): Promise<MentionTarget | undefined> {
+ return await tx.superTabMention.findFirst({ where: { id, tabId }, select: { id: true, personId: true, conversationId: true } }) ?? undefined
+}
+
+/** Marking an answered tag done again keeps how it was answered. */
+export async function markDone(tx: Tx, tabId: string, id: string, personId: string, now: number): Promise<void> {
+ await tx.superTabMention.updateMany({ where: { id, tabId, personId, ...waiting }, data: { resolvedAt: new Date(now), resolvedBy: 'done' } })
+}
+
+/** The person's own unexpired tags in conversations they can still read, newest first. The badge counts this same list.
+ * ponytail: capped at 500 per state; page it if a person ever gets more in 30 days. */
+async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {
+ person(state, actor.userId)
+ const rows = await tx.superTabMention.findMany({ where: { tabId, personId: actor.userId, createdAt: { gt: new Date(now - MENTION_EXPIRY_MS) },
+ ...(open ? waiting : { resolvedAt: { not: null } }) }, orderBy: { createdAt: 'desc' }, take: 500 })
+ return rows.filter(row => {
+ const group = state.conversations.find(c => c.id === row.conversationId)
+ return !!group && !isLeads(group) && canReadProject(state, actor, projectOf(state, group.projectId ?? 'lead'))
+ })
+}
+
+export async function mentionsWaiting(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number): Promise<number> {
+ return (await readable(tx, tabId, state, actor, now, true)).length
+}
+
+export async function listMentions(tx: Tx, tabId: string, state: SuperTabState, actor: Extract<Actor, { kind: 'person' }>, now: number, open: boolean) {
+ const rows = await readable(tx, tabId, state, actor, now, open)
+ const messages = rows.length ? await tx.superTabMessage.findMany({ where: { tabId, id: { in: rows.map(r => r.messageId) } },
+ select: { id: true, text: true, author: true } }) : []
+ return rows.map(row => {
+ const group = state.conversations.find(c => c.id === row.conversationId)!
+ const message = messages.find(m => m.id === row.messageId)
+ const author = message?.author as { name?: string; displayName?: string } | undefined
+ return { id: row.id, projectId: row.projectId, projectName: projectOf(state, group.projectId ?? 'lead').name,
+ conversationId: row.conversationId, conversationTitle: group.title, messageId: row.messageId,
+ leadName: author?.displayName ?? author?.name ?? 'Lead', text: (message?.text ?? '').slice(0, 200),
+ createdAt: row.createdAt, resolvedAt: row.resolvedAt, resolvedBy: row.resolvedBy }
+ })
+}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0e62d8246..c5738f0a8 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -229,6 +229,8 @@ export interface MessageDraft {
/** Structured row kind for clients; `native` is written by native.ts, `route`/`route-override` by commands. */
source?: Record<string, unknown>
attachments?: import('./attachments.js').Attachment[]
+ /** People a Lead tagged (mentions.ts). */
+ mentions?: string[]
}
export interface CommandEffects {
state: SuperTabState
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index f40e590d9..69531c9fd 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -21,6 +21,7 @@ import {
import { holdNoticeText, type HoldReason } from './holdNotice.js'
import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, type TerminalEffect } from './terminal.js'
import { closeAssignment, closeUnassignedStart, readDecision, recentRoutes, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'
+import { listMentions, markDone, mentionsWaiting, readMention, resolveByReply, writeMentions } from './mentions.js'
import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'
import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSchema, requireSharingOwner,
saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'
@@ -331,7 +332,8 @@ export class SuperTabStore {
await tx.superTab.updateMany({ where: { id: tabId, revision: row.revision }, data: { state: json(state) } })
}
const visible = visibleState(state, actor, this.now())
- return { revision: row.revision, state: { ...visible, machines: visible.machines?.map(pool => ({
+ const mentions = actor.kind === 'person' ? { mentionsWaiting: await mentionsWaiting(tx, tabId, state, actor, this.now()) } : {}
+ return { revision: row.revision, state: { ...visible, ...mentions, machines: visible.machines?.map(pool => ({
...pool, availableSlots: Math.max(0, pool.maxAgents - machineSlots(state, state.machines!.find(m => m.machineId === pool.machineId)!)),
})) } }
})
@@ -464,6 +466,7 @@ export class SuperTabStore {
context.confirmedStopped = !!proof && !!execution && proof.machineId === execution.machineId &&
proof.harnessId === execution.harnessId && proof.machineOwnerId === execution.machineOwnerId
}
+ if (command.type === 'mention.done') context.mention = await readMention(tx, tabId, command.mentionId)
if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)
if (command.type === 'route.record') context.recentRoutes = await recentRoutes(tx, tabId, context.now)
if (command.type === 'agent.screen' || command.type === 'agent.input') {
@@ -629,6 +632,9 @@ export class SuperTabStore {
await closeAssignment(tx, tabId, command.assignmentId, command.status, context.now)
}
await this.writeMessages(tx, tabId, effects.state, effects.messages, revision)
+ if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)
+ await writeMentions(tx, tabId, effects.state, effects.messages, context.now)
+ if (command.type === 'mention.done') await markDone(tx, tabId, command.mentionId, context.mention!.personId, context.now)
if (context.attachments?.length) {
// Conflicts with a concurrent send of the same file: only one message can take it.
const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: { in: context.attachments.map(a => a.id) }, ...unused },
@@ -867,7 +873,7 @@ export class SuperTabStore {
await tx.superTabMessage.create({ data: { id: message.id, tabId, conversationId: message.conversationId,
sequence: revision, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),
...(message.attachments ? { attachments: json(message.attachments) } : {}),
- text: message.text, replyTo: message.replyTo, recipientIds: message.recipients } })
+ text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [] } })
for (const recipient of message.recipients) {
const target = agent(state, recipient)
const group = conversation(state, message.conversationId)
@@ -897,7 +903,15 @@ export class SuperTabStore {
const deliveries = page.length ? await tx.superTabDelivery.findMany({ where: { tabId, messageId: { in: page.map(m => m.id) } },
select: { id: true, messageId: true, agentId: true, status: true, receipt: true,
holdReason: true, holdSince: true, deliveredAt: true, answeredAt: true, createdAt: true, updatedAt: true } }) : []
- return { messages: page.map(m => ({ ...m, deliveries: deliveries.filter(d => d.messageId === m.id) })), next, revision: row.revision }
+ return { messages: page.map(m => ({ ...m, mentions: m.mentions ?? [], deliveries: deliveries.filter(d => d.messageId === m.id) })), next, revision: row.revision }
+ })
+ }
+
+ /** The caller's own tags in this Swarm, newest first: still waiting, or answered and marked done. */
+ async mentions(user: AuthUser, tabId: string, state: 'waiting' | 'earlier') {
+ return transaction(this.db, async tx => {
+ const row = await this.row(tx, user, tabId)
+ return { mentions: await listMentions(tx, tabId, stateOf(row), { kind: 'person', userId: user.sub, email: user.email }, this.now(), state === 'waiting') }
})
}
diff --git a/backend/src/worker.ts b/backend/src/worker.ts
index 069f4728b..f27bcb9a7 100644
--- a/backend/src/worker.ts
+++ b/backend/src/worker.ts
@@ -16,6 +16,7 @@ import { ensurePlans } from './lib/db/seed.js'
import { prisma } from './lib/prisma.js'
import { ensureProductUsageExpiry } from './lib/productUsage.js'
import { ensureTerminalExpiry } from './superTabs/terminal.js'
+import { ensureMentionExpiry } from './superTabs/mentions.js'
import { machineBillingWorkerService } from './services/MachineBillingWorkerService.js'
import { productUsagePeopleRollupService } from './services/ProductUsagePeopleRollupService.js'
import { logger } from './utils/logger.js'
@@ -32,6 +33,7 @@ async function start(): Promise<void> {
ensureSchema()
await ensureProductUsageExpiry()
await ensureTerminalExpiry(prisma)
+ await ensureMentionExpiry(prisma)
// AFTER the push: it creates the new collections + their unique indexes, and the copy uses $merge
// so those indexes survive. Copying first would leave the unique index build to fail silently.
await migrateMachineRename()