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.

Tags are words in the sentence, and a message that tags you stands out (#2287)

0xken15bca1540822c4
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 930becb1c..2e565fbcc 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -3222,7 +3222,8 @@ describe('Lead mentions', () => {
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, leadId: lead, leadName: expect.any(String), text: text.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null })
+ // The picked tag the text did not say opens it, as the server stores it (mentions.ts withTags).
+ messageId, leadId: lead, leadName: expect.any(String), text: `@peer ${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([])
@@ -3283,7 +3284,7 @@ describe('Lead mentions', () => {
const messageId = (await run(tab, { type: 'message.send', conversationId: group, text: 'Peer, see above.', replyTo: null, recipientIds: [],
mentions: [peer.sub] })).result.messageId as string
const mention = (await list(tab, peer, 'waiting')).find(m => m.messageId === messageId)
- expect(mention).toEqual(expect.objectContaining({ leadId: owner.sub, leadName: 'boss', text: 'Peer, see above.' }))
+ expect(mention).toEqual(expect.objectContaining({ leadId: owner.sub, leadName: 'boss', text: '@peer Peer, see above.' }))
expect(JSON.stringify(mention)).not.toContain(owner.email)
})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 1d3eb5474..db1b92957 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,6 +1,6 @@
import { admitMachineStart, BUDDY_WINDOWS_REFUSAL, cleanupOverdue, dropIdleBuddyMachines, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, machineSlots, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
-import { keepUsernames, setUsername } from './usernames.js'
+import { keepUsernames, setUsername, swarmUsernames } from './usernames.js'
import { z } from 'zod'
import { tokensByModelSchema } from './costs/tokens.js'
import {
@@ -13,7 +13,7 @@ import { routeRecordSchema, routeTitle, startedAs, type RouteCandidate, type Rou
import { DEFAULT_ROUTING_POLICY, routingOverrideSaveSchema, type RoutingPolicy } from './routingPolicy.js'
import { agentTarget, askedInSchema, broken, MAX_RULES, reviewRefusal, RULE_MESSAGE_MS, SAME_ENGINE, sameEngineReview, ruleSchema, ruleTextSchema, startTarget, unmet, type RunTarget } from './rules.js'
import { MAX_ATTACHMENTS, type Attachment } from './attachments.js'
-import { checkMentions, MAX_MENTIONS, type MentionTarget } from './mentions.js'
+import { checkMentions, MAX_MENTIONS, namedIn, textTags, withTags, type MentionTarget } from './mentions.js'
import { answerDecision, askDecisions, checkAsker, decisionChoices, decisionQuestion, MAX_OPEN_DECISIONS, MAX_QUESTIONS, type DecisionTarget } from './decisions.js'
import { TERMINAL_KEYS, terminalAlert, terminalRequest, terminalResult, toLead, type TerminalRequest } from './terminal.js'
import { leadNoticeRows, loseTasks, recordTaskState, renewLease, renewOwnTask, restartQuietTime, reviewFoundProblems, waitingForReview } from './liveness.js'
@@ -1943,7 +1943,16 @@ 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 ?? [])
+ // The text is where tags live, as people tag in chat: each name it says tags that person, if they may read here. A tag
+ // picked in an older client (or the CLI's --mention) that the text does not say is written into it, so every client
+ // shows the same words. Only from the command, so a retry writes the same text.
+ const picked = checkMentions(state, actor, group, command.mentions ?? [])
+ // Every username is worked out at once, and only for a post that names or picks someone.
+ const names = picked.length || command.text.includes('@') ? swarmUsernames(state) : new Map<string, string>()
+ const named = namedIn(state, command.text, names)
+ const text = withTags(picked.filter(id => !named.includes(id)).map(id => `@${names.get(id)}`), command.text)
+ // A tag would tell a person about an agent-only notice they cannot see.
+ const mentions = [...new Set([...picked, ...command.agentOnly ? [] : textTags(state, actor, group, named)])].slice(0, MAX_MENTIONS)
if (command.mentionsIfNoWorker && !mentions.length) fail('INVALID_MENTION', 'Hold a tag only for a message that tags someone.', 400)
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)
@@ -1983,12 +1992,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
fail('INVALID_RECIPIENT', 'An agent sends an agent-only notice to itself alone.', 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, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions, command.mentionsIfNoWorker)
+ message(group.id, text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions, command.mentionsIfNoWorker)
// A reply joins its message's thread, always at the root, so threads never nest. A reply to a notice only its
// recipients read (the Lead answering a stalled alert) stays in the chat: people open a thread from its root.
const thread = command.replyTo && !context.reply?.agentOnly ? context.reply?.thread : null
if (thread) Object.assign(effects.messages.at(-1)!, { thread, ...(command.alsoSend ? { alsoInChat: true } : {}) })
- recordPost(state, group, actor, { replyTo: command.replyTo, text: command.text, reply: context.reply, openTags: context.openTags }, context.now)
+ recordPost(state, group, actor, { replyTo: command.replyTo, text, reply: context.reply, openTags: context.openTags }, context.now)
if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)
leadActed(group.id, 'post')
break
diff --git a/backend/src/superTabs/mentions.test.ts b/backend/src/superTabs/mentions.test.ts
index f28ac61ce..91ab5636d 100644
--- a/backend/src/superTabs/mentions.test.ts
+++ b/backend/src/superTabs/mentions.test.ts
@@ -1,5 +1,7 @@
+import { readFileSync } from 'node:fs'
import { describe, expect, it } from 'vitest'
import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { MAX_MENTIONS, tagTokens } from './mentions.js'
import { createSuperTab, type Actor } from './model.js'
const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
@@ -21,6 +23,8 @@ function fixture() {
run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, who)
}
const app = run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const lead = run({ type: 'agent.add', conversationId: app.conversationId, harnessId: 'lead', machineId: 'machine', name: 'Lead', lead: true,
+ configuration }).result.agentId as string
const worker = run({ type: 'agent.add', conversationId: app.conversationId, harnessId: 'worker', machineId: 'machine', name: 'Worker', lead: false,
configuration }).result.agentId as string
const group = run({ type: 'conversation.create', projectId: app.projectId, title: 'Copy', brief: '', checks: [] }).result.conversationId as string
@@ -28,7 +32,10 @@ function fixture() {
const pmChat = run({ type: 'buddy.chat', projectId: app.projectId }, peer).result.conversationId as string
const send = (conversationId: string, mentions: string[], actor: Actor = owner) => run({ type: 'message.send', conversationId,
text: 'Please look.', replyTo: null, recipientIds: [], mentions }, actor).messages.at(-1)!
- return { run, send, app, worker, group, pmChat, get state() { return state } }
+ /** A post that tags only by what its text says, as people type in chat. */
+ const say = (conversationId: string, text: string, actor: Actor = owner, mentions?: string[]) => run({ type: 'message.send', conversationId,
+ text, replyTo: null, recipientIds: [], ...(mentions ? { mentions } : {}) }, actor).messages.at(-1)!
+ return { run, send, say, app, lead, worker, group, pmChat, get state() { return state } }
}
describe('people tagging people', () => {
@@ -61,3 +68,112 @@ describe('people tagging people', () => {
.toThrow(expect.objectContaining({ code: 'MENTION_FORBIDDEN' }))
})
})
+
+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', () => {
+ it.each(shared.cases)('finds the tags in $text', ({ text, tags }) => {
+ expect(tagTokens(text)).toEqual(tags)
+ })
+
+ it('reads a 32,000-character text of unclosed link brackets in linear time', () => {
+ // Each `](` without a `)` once scanned to the end: about 200 ms per send at the limit.
+ const started = performance.now()
+ expect(tagTokens(`${']('.repeat(15_995)}@dee.`)).toEqual(['dee'])
+ expect(performance.now() - started).toBeLessThan(50)
+ })
+
+ it('tags each person the text names, by username in any case or by full address', () => {
+ const f = fixture()
+ const said = f.say(f.group, '@peer can you free some memory? @Third.')
+ expect(said.mentions).toEqual(['peer', 'third'])
+ expect(said.text).toBe('@peer can you free some memory? @Third.')
+ expect(f.say(f.group, 'Ask @[email protected] today').mentions).toEqual(['peer'])
+ })
+
+ it('never tags a name in code, a link or an email address', () => {
+ const f = fixture()
+ for (const text of ['run `@peer` here', '```\n@peer\n```', 'mail [email protected]', 'see https://example.com/@peer']) {
+ expect(f.say(f.group, text).mentions ?? [], text).toEqual([])
+ }
+ })
+
+ it('leaves an unknown name, or a person who cannot read the chat, as plain text without an error', () => {
+ const f = fixture()
+ const outsider = f.say(f.pmChat, '@third and @nobody, look', peer)
+ expect(outsider.mentions ?? []).toEqual([])
+ expect(outsider.text).toBe('@third and @nobody, look')
+ })
+
+ it('drops the author naming themselves', () => {
+ const f = fixture()
+ expect(f.say(f.group, '@owner and @peer').mentions).toEqual(['peer'])
+ })
+
+ it('tags from a Lead’s text in its own project, and from no other agent', () => {
+ const f = fixture()
+ const lead = { kind: 'agent' as const, agentId: f.lead, machineOwnerId: 'owner' }
+ expect(f.say(f.app.conversationId, '@peer please confirm', lead).mentions).toEqual(['peer'])
+ const worker = f.say(f.app.conversationId, '@peer please confirm', { kind: 'agent', agentId: f.worker, machineOwnerId: 'owner' })
+ expect(worker.mentions ?? []).toEqual([])
+ expect(worker.text).toBe('@peer please confirm')
+ })
+
+ it('tags nobody from the text of a Leads conversation post or an agent-only notice', () => {
+ const f = fixture()
+ expect(f.say(f.state.leadsConversationId!, '@peer look').mentions ?? []).toEqual([])
+ const notice = f.run({ type: 'message.send', conversationId: f.app.conversationId, text: '@peer is away', replyTo: null,
+ recipientIds: [f.lead], agentOnly: true }, { kind: 'agent', agentId: f.lead, machineOwnerId: 'owner' }).messages.at(-1)!
+ expect(notice.mentions ?? []).toEqual([])
+ })
+
+ it('keeps at most MAX_MENTIONS tags, the picked ones first', () => {
+ const f = fixture()
+ for (const name of ['p4', 'p5', 'p6', 'p7']) {
+ const invited = f.run({ type: 'invite.create', email: `${name}@example.com`, role: 'collaborator', conversationId: 'lead' })
+ f.run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, { kind: 'person', userId: name, email: `${name}@example.com` })
+ }
+ const many = f.say(f.group, '@p4 @p5 @p6 @p7 @third', owner, ['peer'])
+ expect(many.mentions).toEqual(['peer', 'p4', 'p5', 'p6', 'p7'].slice(0, MAX_MENTIONS))
+ })
+})
+
+describe('a picked tag the text does not say', () => {
+ it('opens the first line of the stored text, once', () => {
+ const f = fixture()
+ const sent = f.send(f.group, ['peer', 'third'])
+ expect(sent.text).toBe('@peer @third Please look.')
+ expect(sent.mentions).toEqual(['peer', 'third'])
+ })
+
+ it('gets a line of its own when the text opens with a block', () => {
+ const f = fixture()
+ expect(f.say(f.group, '- one\n- two', owner, ['peer']).text).toBe('@peer\n\n- one\n- two')
+ expect(f.say(f.group, '\n\nShipped:\n- Desktop', owner, ['peer']).text).toBe('@peer Shipped:\n- Desktop')
+ })
+
+ it('is not added again when the text already names them, in any case, with a dot or by address', () => {
+ const f = fixture()
+ for (const text of ['Ask @Peer.', 'cc @[email protected]', '@peer: done']) {
+ expect(f.say(f.group, text, owner, ['peer']).text).toBe(text)
+ }
+ // A name inside code is not a tag, so the tag still opens the line.
+ expect(f.say(f.group, 'run `@peer`', owner, ['peer']).text).toBe('@peer run `@peer`')
+ })
+
+ it('is written the same way when the command is retried', () => {
+ const command = { type: 'message.send' as const, conversationId: '', text: 'Please look.', replyTo: null, recipientIds: [], mentions: ['peer'] }
+ const first = fixture(), again = fixture()
+ expect(first.run({ ...command, conversationId: first.group }).messages.at(-1)!.text)
+ .toBe(again.run({ ...command, conversationId: again.group }).messages.at(-1)!.text)
+ // A client that sends back the text the server wrote does not get the tag twice.
+ expect(first.say(first.group, '@peer Please look.', owner, ['peer']).text).toBe('@peer Please look.')
+ })
+
+ it('is the whole text of a post that is only files', () => {
+ const f = fixture()
+ const sent = f.run({ type: 'message.send', conversationId: f.group, text: '', replyTo: null, recipientIds: [], mentions: ['peer'],
+ attachmentIds: ['file'] }, owner, { attachments: [{ id: 'file', name: 'a.png', url: 'https://cdn.example.com/a.png', size: 1, mime: 'image/png' }] }).messages.at(-1)!
+ expect(sent.text).toBe('@peer')
+ })
+})
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index b761daf0f..93b28ab37 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -27,6 +27,93 @@ export async function ensureMentionExpiry(db: PrismaClient): Promise<void> {
await ensureIndex(db, 'SuperTabMention', { key: { createdAt: 1 }, name: 'mention_expiry', expireAfterSeconds: MENTION_EXPIRY_MS / 1000 })
}
+/** `@name` or `@name@domain`, as people tag in chat. Never right after a letter, digit, `@` or `/` (an address, a path, a
+ * link), and a name never ends in a dot: `@dee.` closes a sentence. Desktop (message_text.dart) and the phone
+ * (swarm_message_row.dart) use this same pattern; tagFixture.json is the table all three pass. */
+const TAG = /(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?/g
+const FENCE = /^ {0,3}(`{3,}|~{3,})/
+const blank = (part: string) => part.replace(/[^\n]/g, ' ')
+
+/** [text] with what is never a tag blanked out, as Markdown renders it: fenced and indented code, code spans, bare links and
+ * link destinations. */
+function prose(text: string): string {
+ const lines = text.split('\n')
+ let fence: string | null = null
+ let indented = false
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i]!
+ if (fence) {
+ const close = FENCE.exec(line)
+ if (close && close[1]![0] === fence[0] && close[1]!.length >= fence.length && !line.slice(close[0].length).trim()) fence = null
+ lines[i] = blank(line)
+ continue
+ }
+ const open = FENCE.exec(line)
+ if (open && !(open[1]![0] === '`' && line.slice(open[0].length).includes('`'))) {
+ fence = open[1]!
+ lines[i] = blank(line)
+ indented = false
+ continue
+ }
+ // Indented code starts after a blank line (or the first line) and runs while its lines stay indented.
+ const startsCode: boolean = /^( {4}|\t)/.test(line) && line.trim() !== '' && (indented || i === 0 || !lines[i - 1]!.trim())
+ indented = startsCode || (indented && !line.trim())
+ if (startsCode) lines[i] = blank(line)
+ }
+ return lines.join('\n')
+ .replace(/(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g, blank)
+ .replace(/\]\([^)\]]*\)/g, blank)
+ .replace(/\b(?:https?:\/\/|www\.)\S+/gi, blank)
+}
+
+/** The tags [text] holds, in order: each name as written after its `@`, lowercased, a full address with its domain. */
+export function tagTokens(text: string): string[] {
+ return [...prose(text).matchAll(TAG)].map(match => `${match[1]}${match[2] ?? ''}`.toLowerCase())
+}
+
+/** The people [text] names, in order, once each: `@username` in any case, or `@` and their full address. [names] is the
+ * Swarm's usernames by person (usernames.ts swarmUsernames). */
+export function namedIn(state: SuperTabState, text: string, names: ReadonlyMap<string, string>): string[] {
+ const tokens = tagTokens(text)
+ if (!tokens.length) return []
+ const byName = new Map([...names].map(([id, name]) => [name.toLowerCase(), id]))
+ const ids = tokens.flatMap(token => {
+ const id = token.includes('@') ? state.people.find(p => p.email.toLowerCase() === token)?.id : byName.get(token)
+ return id && state.people.some(p => p.id === id) ? [id] : []
+ })
+ return [...new Set(ids)]
+}
+
+/** [tags] on the first line of [text], as a person types them in chat. Only text that opens with a block (a list, heading,
+ * quote, table, code, divider or link definition) keeps them on a line of their own, so that block still renders. The same
+ * rule as Desktop's SuperTabMessageText.withTags, which shows an older message's unsaid tags. */
+export function withTags(tags: string[], text: string): string {
+ if (!tags.length) return text
+ const body = text.replace(/^(?:[ \t]*\n)+/, '')
+ if (!body) return tags.join(' ')
+ return OPENS_BLOCK.test(body) ? `${tags.join(' ')}\n\n${body}` : `${tags.join(' ')} ${body}`
+}
+const OPENS_BLOCK = new RegExp('^(?: {4}|\\t| {0,3}(?:[-*+](?:[ \\t\\n]|$)|#{1,6}(?:[ \\t\\n]|$)|>'
+ + '|\\d{1,9}[.)](?:[ \\t\\n]|$)|```|~~~|\\||\\[[^\\]\\n]+\\]:'
+ + '|(?:(?:\\*[ \\t]*){3,}|(?:-[ \\t]*){3,}|(?:_[ \\t]*){3,})(?:\\n|$)))')
+
+/** Whether [actor] may tag people in [group]: a person who can post there; among agents only the project's Lead, in its own
+ * project's conversations; nobody in the Leads conversation. */
+function mayTag(state: SuperTabState, actor: Actor, group: Conversation): boolean {
+ if (isLeads(group)) return false
+ if (actor.kind !== 'agent') return true
+ const led = ledProject(state, actor.agentId)
+ return !!led && groupProject(state, group).id === led.id
+}
+
+/** The people [named] by a post's text whom it tags: only when [actor] may tag here, only people who can read [group], never
+ * the author. Anyone else stays plain text: a name in a sentence is never an error. */
+export function textTags(state: SuperTabState, actor: Actor, group: Conversation, named: string[]): string[] {
+ if (!mayTag(state, actor, group)) return []
+ return named.filter(id => (actor.kind !== 'person' || id !== actor.userId) && state.people.some(p => p.id === id
+ && canReadGroup(state, { kind: 'person', userId: p.id, email: p.email }, group)))
+}
+
/** A person who can post here tags people; among agents only the project's Lead, in that project's conversations. Never in
* the Leads conversation, and only people who can read the conversation. A person's tag of themselves is dropped. */
export function checkMentions(state: SuperTabState, actor: Actor, group: Conversation, personIds: string[]): string[] {
diff --git a/backend/src/superTabs/tagFixture.json b/backend/src/superTabs/tagFixture.json
new file mode 100644
index 000000000..e1292a29b
--- /dev/null
+++ b/backend/src/superTabs/tagFixture.json
@@ -0,0 +1,30 @@
+{
+ "about": "Which words in a chat message are tags. One table for the backend (src/superTabs/mentions.ts), Desktop (desktop/lib/super_tabs/message_text.dart) and the phone (mobile/lib/swarm/swarm_message_row.dart); the three copies must stay byte-identical (scripts/tests/test_tag_fixture_copies.py). Each case lists its tags in order, lowercased, as written after the @ without closing punctuation. names are every name the cases use, so a word that is not a tag is not one only because of where it stands.",
+ "names": ["dee", "ken", "tony", "diego", "dee.ken", "b", "github"],
+ "cases": [
+ { "text": "@diego can you free some memory on your Pro-10? Reviews are waiting on it.", "tags": ["diego"] },
+ { "text": "Thanks @Dee", "tags": ["dee"] },
+ { "text": "Ask @dee.", "tags": ["dee"] },
+ { "text": "@dee, @ken and @tony: please look", "tags": ["dee", "ken", "tony"] },
+ { "text": "(@dee) said so", "tags": ["dee"] },
+ { "text": "It is @dee's turn", "tags": ["dee"] },
+ { "text": "Ask @dee.ken today", "tags": ["dee.ken"] },
+ { "text": "Ask @[email protected] today", "tags": ["[email protected]"] },
+ { "text": "Ask @[email protected].", "tags": ["[email protected]"] },
+ { "text": "> @dee quoted", "tags": ["dee"] },
+ { "text": "- @dee in a list", "tags": ["dee"] },
+ { "text": "Mail [email protected] or [email protected]", "tags": [] },
+ { "text": "git clone [email protected]:autonomous-ai/openharness.git", "tags": [] },
+ { "text": "@@dee and x@dee", "tags": [] },
+ { "text": "an @ alone, and @ dee", "tags": [] },
+ { "text": "run `@dee` here, then @ken", "tags": ["ken"] },
+ { "text": "run ``a `@dee` b`` here", "tags": [] },
+ { "text": "```\n@dee\n```\nthen @ken", "tags": ["ken"] },
+ { "text": "~~~sh\necho @dee\n~~~\nthen @ken", "tags": ["ken"] },
+ { "text": "```\n@dee never closed", "tags": [] },
+ { "text": "Run this:\n\n @dee indented\n\nthen @ken", "tags": ["ken"] },
+ { "text": "See https://github.com/@dee/repo and www.example.com/@ken", "tags": [] },
+ { "text": "See example.com/@dee", "tags": [] },
+ { "text": "[profile](https://example.com/@dee) by @ken", "tags": ["ken"] }
+ ]
+}
diff --git a/backend/src/superTabs/usernames.test.ts b/backend/src/superTabs/usernames.test.ts
index 5d0b22204..c88c3b269 100644
--- a/backend/src/superTabs/usernames.test.ts
+++ b/backend/src/superTabs/usernames.test.ts
@@ -108,6 +108,15 @@ describe('member.username', () => {
expect(f.state.people[0]!.username).toBeUndefined()
})
+ it('refuses a name that cannot be tagged in text: a dot at its end or two in a row', () => {
+ const f = fixture()
+ for (const username of ['ken.', 'ken..nguyen']) {
+ expect(() => f.run({ type: 'member.username', username }), username).toThrow(expect.objectContaining({ code: 'INVALID_USERNAME' }))
+ }
+ f.run({ type: 'member.username', username: 'ken.nguyen' })
+ expect(f.state.people[0]!.username).toBe('ken.nguyen')
+ })
+
it('keeps a later person’s numbered name when the person before them leaves', () => {
const f = fixture()
const first = person('ken-a', '[email protected]')
diff --git a/backend/src/superTabs/usernames.ts b/backend/src/superTabs/usernames.ts
index c7b1a222f..37fadd33e 100644
--- a/backend/src/superTabs/usernames.ts
+++ b/backend/src/superTabs/usernames.ts
@@ -3,8 +3,9 @@ import { isBuddy } from './buddies.js'
import { fail, person, type Actor, type Agent, type Person, type SuperTabState } from './model.js'
import { agentProjectId, canReadAgent, projectsOf } from './projects.js'
-/** A username as a person types it: 2 to 32 lowercase letters, digits, `.`, `_` or `-`, starting with a letter or digit. */
-const SHAPE = /^[a-z0-9][a-z0-9._-]{1,31}$/
+/** A username as a person types it: 2 to 32 lowercase letters, digits, `.`, `_` or `-`, starting with a letter or digit. Never
+ * a dot at its end or two in a row, so `@name` in a message tags them (mentions.ts: `@dee.` closes a sentence). */
+const SHAPE = /^[a-z0-9](?:[a-z0-9_-]|\.(?!\.)){0,30}[a-z0-9_-]$/
/** Room left in a default for its number (`ken` → `ken12`). */
const DEFAULT_BASE_LENGTH = 30
@@ -65,7 +66,7 @@ export function setUsername(state: SuperTabState, actor: Actor, input: string |
const member = person(state, actor.userId)
if (input === null) return void delete member.username
const name = input.trim().toLowerCase()
- if (!SHAPE.test(name)) fail('INVALID_USERNAME', 'Use 2 to 32 letters, digits, dots, dashes or underscores, starting with a letter or digit.', 400)
+ if (!SHAPE.test(name)) fail('INVALID_USERNAME', 'Use 2 to 32 letters, digits, dots, dashes or underscores, starting with a letter or digit, with no dot at the end or two in a row.', 400)
// Only agents this person can see, the scope their reads use: refusing another's name would tell them it exists.
const sees = (agent: Agent) => projectsOf(state).some(p => p.id === agentProjectId(state, agent)) && canReadAgent(state, actor, agent)
if (agentNames(state, sees).some(agent => agent.toLowerCase() === name)) {
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 075da49f6..b92741428 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1158,6 +1158,8 @@ describe('mentions on a post', () => {
const lead = await help(t, { tabId: 'tab', agentId: t.agentId })
expect(lead.post).toContain(`post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... ${mention}:`)
expect(lead.post).toContain('--mention tags a person, by the id or email shown in status (up to 5), when you need them to act or decide; it shows in their notifications.')
+ // The server reads tags from the text too (backend mentions.ts).
+ expect(lead.post).toContain('An @username or @email in TEXT tags that person as well, outside code and links.')
expect(await help(t, { tabId: 'tab', harnessId: 'native' })).toEqual(lead)
// A former Lead still named on an older work group is not one, as in status.
swarm(t, 'new-lead')
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index e30bbe549..0ecdff4f4 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -115,7 +115,7 @@ const list = (value: unknown) => Array.isArray(value) ? value.map(object) : []
const answerOf = (read: SwarmRead) => ({ lastChangedAt: read.lastChangedAt, state: read.state, ...(read.githubApp ? { githubApp: true } : {}) })
const OFF_ROSTER = 'This agent is not on this machine\'s Swarm roster right now. That can mean this machine has no access to it, or its billing does not allow it. Check how this machine is shared.'
/** Only a project's Lead may tag people (spec 2026-10-24-lead-mentions), so only a Lead's help offers it. */
-const LEAD_HELP = { ...HELP, post: `post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]...: ${POST_HELP} --mention tags a person, by the id or email shown in status (up to 5), when you need them to act or decide; it shows in their notifications.`,
+const LEAD_HELP = { ...HELP, post: `post GROUP TEXT OPERATION_ID [--reply-to MESSAGE_ID] [--attach PATH]... [--mention PERSON]...: ${POST_HELP} --mention tags a person, by the id or email shown in status (up to 5), when you need them to act or decide; it shows in their notifications. An @username or @email in TEXT tags that person as well, outside code and links.`,
// Advisory (docs/plans/2026-10-27-swarm-scheduler.md): a plan for every open group at once, which the route still decides.
plan: 'plan [JSON]: the best plan for all your open groups at once, from the scheduler on this machine (Python 3 and OR-Tools; without them it says how to install, and routing works as before). Per group: the machine, engine, model and effort, start order and expected finish, with the finish time and cost against routing one group at a time. JSON (optional): {"groups":{"GROUP":{"difficulty":"low|medium|high","risk":"low|medium|high","size":"small|medium|large","kind":"optional word","after":["GROUP"]}}}; a group you do not assess is planned at medium and listed as an estimate. It keeps the owner\'s hard rules and a review\'s other model family, and records nothing: follow it in order by routing each group and starting the plan\'s pick with overrideReason "scheduler plan".',
// Only a project's Lead asks a batch: up to 10 questions for one person, in one of its project's conversations.
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 8bc901574..fb396cdc7 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -42,6 +42,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.references = const {},
this.onOpenGroup,
this.mentions = const [],
+ this.mentionAddresses = const {},
this.readerId = '',
this.reactorName,
this.onReact,
@@ -81,6 +82,10 @@ class SuperTabMessageRow extends StatefulWidget {
/// The names of the people [message] tags.
final List<String> mentions;
+
+ /// Their addresses, by name: a tag by full address is theirs only when it
+ /// is this one.
+ final Map<String, String> mentionAddresses;
final Map<int, String> references;
final ValueChanged<String>? onOpenGroup;
final String author;
@@ -252,6 +257,11 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
grid.AppTheme.watch(context);
final message = widget.message;
final active = _hovered || _focused;
+ // A message that tags the reader stands out, as Slack marks one that
+ // names you: an accent bar on its edge over a wash of the accent.
+ final taggedYou =
+ widget.readerId.isNotEmpty &&
+ message.mentions.contains(widget.readerId);
final authorStyle = DesktopChrome.text(medium: true)
.copyWith(fontWeight: FontWeight.w600);
// A phone's author is a finger tall, 44 over its 20 px line. The gap
@@ -297,8 +307,17 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
container: true,
label: widget.grouped ? widget.author : null,
child: DecoratedBox(
+ key: taggedYou
+ ? ValueKey('super-tagged-you-${message.id}')
+ : null,
decoration: BoxDecoration(
- color: active ? grid.AppSurface.hoverFill : Colors.transparent,
+ color: taggedYou
+ ? (active
+ ? grid.AppSurface.accentWashHover
+ : grid.AppSurface.accentWash)
+ : active
+ ? grid.AppSurface.hoverFill
+ : Colors.transparent,
border: Border.all(
color: _focus.hasPrimaryFocus
? DesktopChrome.focusRing
@@ -468,6 +487,8 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
references: widget.references,
onOpenGroup: widget.onOpenGroup,
mentions: widget.mentions,
+ addresses: widget.mentionAddresses,
+ taggedYou: taggedYou,
),
),
),
@@ -577,6 +598,17 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
),
),
),
+ if (taggedYou)
+ Positioned(
+ left: 0,
+ top: 0,
+ bottom: 0,
+ child: ColoredBox(
+ key: ValueKey('super-tagged-bar-${message.id}'),
+ color: grid.AppPalette.accentOnSurface,
+ child: const SizedBox(width: 3),
+ ),
+ ),
],
),
),
diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dart
index d01b528bd..d8a4031c6 100644
--- a/desktop/lib/super_tabs/message_text.dart
+++ b/desktop/lib/super_tabs/message_text.dart
@@ -17,6 +17,8 @@ class SuperTabMessageText extends StatelessWidget {
this.references = const {},
this.onOpenGroup,
this.mentions = const [],
+ this.addresses = const {},
+ this.taggedYou = false,
});
final String text;
final Map<int, String> references;
@@ -26,6 +28,14 @@ class SuperTabMessageText extends StatelessWidget {
/// the text says it; one the text does not say opens its first line.
final List<String> mentions;
+ /// The address of each person in [mentions], by name: a tag by full
+ /// address is theirs only when it is this one.
+ final Map<String, String> addresses;
+
+ /// The message tags the reader, so its row is washed in the accent: a tag
+ /// takes the stronger accent in light, to stay 4.5:1 on its pill there.
+ final bool taggedYou;
+
static Uri? webLink(String? href) {
final uri = href == null ? null : Uri.tryParse(href);
return uri != null &&
@@ -47,6 +57,15 @@ class SuperTabMessageText extends StatelessWidget {
: '${tags.join(' ')} $body';
}
+ /// The tags [text] holds, in order: each name as written after its `@`,
+ /// lowercased, a full address with its domain. Not in code or a link. The
+ /// backend reads a message's tags by this same rule (superTabs/mentions.ts);
+ /// test/fixtures/tag_fixture.json is the table both pass.
+ static List<String> tagsIn(String text) => [
+ for (final match in _Mention.tag.allMatches(_prose(text)))
+ '${match[1]}${match[2] ?? ''}'.toLowerCase(),
+ ];
+
static final _opensBlock = RegExp(
r'^(?: {4}|\t| {0,3}(?:[-*+](?:[ \t\n]|$)|#{1,6}(?:[ \t\n]|$)|>'
r'|\d{1,9}[.)](?:[ \t\n]|$)|```|~~~|\||\[[^\]\n]+\]:'
@@ -56,10 +75,11 @@ class SuperTabMessageText extends StatelessWidget {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
+ // Read only for a message that tags someone: most tag nobody.
+ final said = mentions.isEmpty ? const <String>[] : tagsIn(text);
final unsaid = [
for (final name in mentions)
- if (!_Mention.tag.allMatches(text).any((m) => _Mention.names(m, name)))
- '@$name',
+ if (!said.any((tag) => _says(tag, name, addresses))) '@$name',
];
return MarkdownBody(
data: withTags(unsaid, text),
@@ -68,9 +88,19 @@ class SuperTabMessageText extends StatelessWidget {
inlineSyntaxes: [
_WebAutolink(),
_WorkgroupReference(references),
- if (mentions.isNotEmpty) _Mention(mentions),
+ if (mentions.isNotEmpty) _Mention(mentions, addresses),
],
- builders: {'pre': _CodeBlock(), 'mention': _MentionName()},
+ builders: {
+ 'pre': _CodeBlock(),
+ 'mention': _MentionName(
+ taggedYou
+ ? grid.AppTheme.pick(
+ grid.AppCard.accentStrong,
+ grid.AppPalette.accentOnSurface,
+ )
+ : grid.AppPalette.accentOnSurface,
+ ),
+ },
paddingBuilders: {'a': _CompactLinkLabel()},
styleSheet: desktopMarkdownStyleSheet(context),
onTapLink: (_, href, _) {
@@ -169,21 +199,85 @@ class _WorkgroupReference extends md.InlineSyntax {
}
}
+final _fence = RegExp(r'^ {0,3}(`{3,}|~{3,})');
+final _codeSpan = RegExp(r'(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)');
+final _linkTarget = RegExp(r'\]\([^)\]]*\)');
+final _bareLink = RegExp(r'\b(?:https?://|www\.)\S+', caseSensitive: false);
+String _blank(Match match) => match[0]!.replaceAll(RegExp(r'[^\n]'), ' ');
+
+/// [text] with what is never a tag blanked out, as Markdown renders it: fenced
+/// and indented code, code spans, bare links and link destinations.
+String _prose(String text) {
+ final lines = text.split('\n');
+ String? fence;
+ var indented = false;
+ for (var i = 0; i < lines.length; i++) {
+ final line = lines[i];
+ final blank = line.replaceAll(RegExp(r'[^\n]'), ' ');
+ if (fence != null) {
+ final close = _fence.firstMatch(line);
+ if (close != null &&
+ close[1]![0] == fence[0] &&
+ close[1]!.length >= fence.length &&
+ line.substring(close[0]!.length).trim().isEmpty) {
+ fence = null;
+ }
+ lines[i] = blank;
+ continue;
+ }
+ final open = _fence.firstMatch(line);
+ if (open != null &&
+ !(open[1]![0] == '`' &&
+ line.substring(open[0]!.length).contains('`'))) {
+ fence = open[1];
+ lines[i] = blank;
+ indented = false;
+ continue;
+ }
+ // Indented code starts after a blank line (or the first line) and runs
+ // while its lines stay indented.
+ final startsCode =
+ RegExp(r'^( {4}|\t)').hasMatch(line) &&
+ line.trim().isNotEmpty &&
+ (indented || i == 0 || lines[i - 1].trim().isEmpty);
+ indented = startsCode || (indented && line.trim().isEmpty);
+ if (startsCode) lines[i] = blank;
+ }
+ return lines
+ .join('\n')
+ .replaceAllMapped(_codeSpan, _blank)
+ .replaceAllMapped(_linkTarget, _blank)
+ .replaceAllMapped(_bareLink, _blank);
+}
+
+/// Whether [tag] (as [SuperTabMessageText.tagsIn] gives it) names [name]: by
+/// the name, or by full address, which must be theirs when it is known (the
+/// backend matches an address to a person's email, mentions.ts namedIn).
+bool _says(String tag, String name, Map<String, String> addresses) {
+ final at = tag.indexOf('@');
+ if (at < 0) return tag == name.toLowerCase();
+ final address = addresses[name];
+ return address == null
+ ? tag.substring(0, at) == name.toLowerCase()
+ : tag == address.toLowerCase();
+}
+
/// `@name` or `@name@domain` for a tagged person; any other `@` stays text.
/// Parsed as inline Markdown, so code and fenced blocks remain literal.
class _Mention extends md.InlineSyntax {
- _Mention(this.mentions) : super(tag.pattern);
- // A name never ends in a dot: `@dee.` closes a sentence.
+ _Mention(this.mentions, this.addresses) : super(tag.pattern);
+ // Never right after a letter, digit, `@` or `/` (an address, a path, a
+ // link). A name never ends in a dot: `@dee.` closes a sentence.
static final tag = RegExp(
- r'(?<![\w@])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',
+ r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',
);
- static bool names(Match match, String name) =>
- match[1]!.toLowerCase() == name.toLowerCase();
final List<String> mentions;
+ final Map<String, String> addresses;
@override
bool onMatch(md.InlineParser parser, Match match) {
+ final tag = '${match[1]}${match[2] ?? ''}'.toLowerCase();
parser.addNode(
- mentions.any((name) => names(match, name))
+ mentions.any((name) => _says(tag, name, addresses))
? md.Element.text('mention', match[0]!)
: md.Text(match[0]!),
);
@@ -192,6 +286,8 @@ class _Mention extends md.InlineSyntax {
}
class _MentionName extends MarkdownElementBuilder {
+ _MentionName(this.ink);
+ final Color ink;
@override
Widget? visitElementAfterWithContext(
BuildContext context,
@@ -202,7 +298,7 @@ class _MentionName extends MarkdownElementBuilder {
TextSpan(
text: element.textContent,
style: (parentStyle ?? const TextStyle()).copyWith(
- color: grid.AppPalette.accentOnSurface,
+ color: ink,
backgroundColor: grid.AppSurface.accentWash,
fontWeight: FontWeight.w600,
),
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index afda03dc3..49022c944 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -2469,6 +2469,10 @@ class _SuperTabViewState extends State<SuperTabView>
for (final id in message.mentions)
if (_people[id] case final person?) person.username,
],
+ mentionAddresses: {
+ for (final id in message.mentions)
+ if (_people[id] case final person?) person.username: person.email,
+ },
references: _references,
onOpenGroup: (id) {
setState(() => _showPullRequests = false);
diff --git a/desktop/test/fixtures/tag_fixture.json b/desktop/test/fixtures/tag_fixture.json
new file mode 100644
index 000000000..e1292a29b
--- /dev/null
+++ b/desktop/test/fixtures/tag_fixture.json
@@ -0,0 +1,30 @@
+{
+ "about": "Which words in a chat message are tags. One table for the backend (src/superTabs/mentions.ts), Desktop (desktop/lib/super_tabs/message_text.dart) and the phone (mobile/lib/swarm/swarm_message_row.dart); the three copies must stay byte-identical (scripts/tests/test_tag_fixture_copies.py). Each case lists its tags in order, lowercased, as written after the @ without closing punctuation. names are every name the cases use, so a word that is not a tag is not one only because of where it stands.",
+ "names": ["dee", "ken", "tony", "diego", "dee.ken", "b", "github"],
+ "cases": [
+ { "text": "@diego can you free some memory on your Pro-10? Reviews are waiting on it.", "tags": ["diego"] },
+ { "text": "Thanks @Dee", "tags": ["dee"] },
+ { "text": "Ask @dee.", "tags": ["dee"] },
+ { "text": "@dee, @ken and @tony: please look", "tags": ["dee", "ken", "tony"] },
+ { "text": "(@dee) said so", "tags": ["dee"] },
+ { "text": "It is @dee's turn", "tags": ["dee"] },
+ { "text": "Ask @dee.ken today", "tags": ["dee.ken"] },
+ { "text": "Ask @[email protected] today", "tags": ["[email protected]"] },
+ { "text": "Ask @[email protected].", "tags": ["[email protected]"] },
+ { "text": "> @dee quoted", "tags": ["dee"] },
+ { "text": "- @dee in a list", "tags": ["dee"] },
+ { "text": "Mail [email protected] or [email protected]", "tags": [] },
+ { "text": "git clone [email protected]:autonomous-ai/openharness.git", "tags": [] },
+ { "text": "@@dee and x@dee", "tags": [] },
+ { "text": "an @ alone, and @ dee", "tags": [] },
+ { "text": "run `@dee` here, then @ken", "tags": ["ken"] },
+ { "text": "run ``a `@dee` b`` here", "tags": [] },
+ { "text": "```\n@dee\n```\nthen @ken", "tags": ["ken"] },
+ { "text": "~~~sh\necho @dee\n~~~\nthen @ken", "tags": ["ken"] },
+ { "text": "```\n@dee never closed", "tags": [] },
+ { "text": "Run this:\n\n @dee indented\n\nthen @ken", "tags": ["ken"] },
+ { "text": "See https://github.com/@dee/repo and www.example.com/@ken", "tags": [] },
+ { "text": "See example.com/@dee", "tags": [] },
+ { "text": "[profile](https://example.com/@dee) by @ken", "tags": ["ken"] }
+ ]
+}
diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dart
index b2bb38435..ecc4c442f 100644
--- a/desktop/test/super_tab_mentions_test.dart
+++ b/desktop/test/super_tab_mentions_test.dart
@@ -1,5 +1,7 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
+import 'dart:math' as math;
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
@@ -83,15 +85,20 @@ Future<void> shot(WidgetTester tester, String name) async {
Future<SuperTabController> showView(
WidgetTester tester,
- ConversationServer server,
-) async {
+ ConversationServer server, {
+ String account = 'owner',
+ Brightness brightness = Brightness.dark,
+}) async {
await tester.binding.setSurfaceSize(const Size(1200, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
- final c = server.controller();
+ final before = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = before);
+ final c = server.controller(account: account);
await c.refresh();
await tester.pumpWidget(
MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
+ theme: grid.buildAppTheme(brightness: brightness),
builder: (context, child) => RepaintBoundary(key: _picture, child: child),
home: Scaffold(
body: SuperTabView(
@@ -114,6 +121,65 @@ String minutesAgo(int minutes) => DateTime.now()
.subtract(Duration(minutes: minutes))
.toIso8601String();
+/// The texts painted as tags, in order.
+List<String> tagRuns(WidgetTester tester) => [
+ for (final (text, _) in tagStyles(tester)) text,
+];
+
+/// Each tag painted, with its ink.
+List<(String, Color?)> tagStyles(WidgetTester tester) => [
+ for (final rich in tester.widgetList<RichText>(find.byType(RichText)))
+ ..._tagRuns(rich.text, null),
+];
+
+Iterable<(String, Color?)> _tagRuns(
+ InlineSpan span,
+ TextStyle? inherited,
+) sync* {
+ if (span is! TextSpan) return;
+ final style = inherited?.merge(span.style) ?? span.style;
+ if (span.text case final text?
+ when style?.backgroundColor == grid.AppSurface.accentWash &&
+ style?.fontWeight == FontWeight.w600) {
+ yield (text, style?.color);
+ }
+ for (final child in span.children ?? const <InlineSpan>[]) {
+ yield* _tagRuns(child, style);
+ }
+}
+
+/// WCAG contrast of [a] on [b].
+double contrast(Color a, Color b) {
+ final (x, y) = (a.computeLuminance(), b.computeLuminance());
+ return (math.max(x, y) + 0.05) / (math.min(x, y) + 0.05);
+}
+
+/// The table of tags and non-tags the backend and the phone pass too.
+final tagTable = jsonDecode(
+ File('test/fixtures/tag_fixture.json').readAsStringSync(),
+) as Map<String, dynamic>;
+
+/// A Swarm with diego and ken in it, and two messages from its owner: one
+/// that tags diego, one that tags nobody.
+ConversationServer taggedChat() {
+ final server = ConversationServer();
+ for (final name in ['diego', 'ken']) {
+ (server.state['people'] as List).add({
+ 'id': name,
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'username': name,
+ });
+ }
+ server
+ ..append(
+ '@diego can you free some memory on your Pro-10? Reviews are waiting on it.',
+ )
+ ..append('Thanks, the review queue is moving again.');
+ server.messages.first['mentions'] = ['diego'];
+ return server;
+}
+
/// The styles of every run of [text] painted in the tree.
List<TextStyle?> runsOf(WidgetTester tester, String text) => [
for (final rich in tester.widgetList<RichText>(find.byType(RichText)))
@@ -133,13 +199,19 @@ Iterable<TextStyle?> _runs(
}
}
-Future<void> showText(WidgetTester tester, String text, List<String> names) =>
- tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(body: SuperTabMessageText(text, mentions: names)),
- ),
- );
+Future<void> showText(
+ WidgetTester tester,
+ String text,
+ List<String> names, {
+ Map<String, String> addresses = const {},
+}) => tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabMessageText(text, mentions: names, addresses: addresses),
+ ),
+ ),
+);
Finder notificationsEntry() =>
find.byKey(const ValueKey('super-notifications'));
@@ -991,6 +1063,140 @@ void main() {
expect(runsOf(tester, 'ping @dee'), isNotEmpty);
});
+ for (final row in (tagTable['cases'] as List).cast<Map>()) {
+ testWidgets('finds the tags in ${jsonEncode(row['text'])}', (
+ tester,
+ ) async {
+ final names = (tagTable['names'] as List).cast<String>();
+ final tags = (row['tags'] as List).cast<String>();
+ await showText(tester, row['text'] as String, names);
+ // A tagged name the text does not say opens it (withTags), so each
+ // name the table has no tag for in this text is shown first.
+ final said = {for (final tag in tags) tag.split('@').first};
+ expect(
+ [for (final tag in tagRuns(tester)) tag.substring(1).toLowerCase()],
+ [
+ for (final name in names)
+ if (!said.contains(name)) name,
+ ...tags,
+ ],
+ );
+ });
+ }
+
+ test('reads a 32,000-character text of unclosed link brackets in '
+ 'linear time', () {
+ // Each `](` without a `)` once scanned to the end: about 3 s to draw.
+ final watch = Stopwatch()..start();
+ expect(SuperTabMessageText.tagsIn('${'](' * 15995}@dee.'), ['dee']);
+ expect(watch.elapsedMilliseconds, lessThan(50));
+ });
+
+ testWidgets('a tag by its full address is said, and is its pill', (
+ tester,
+ ) async {
+ await showText(
+ tester,
+ ['diego'],
+ addresses: {'diego': '[email protected]'},
+ );
+ expect(
+ find.text('@[email protected] look', findRichText: true),
+ findsOneWidget,
+ );
+ expect(tagRuns(tester), ['@[email protected]']);
+ });
+
+ testWidgets('another address is no tag of them', (tester) async {
+ await showText(
+ tester,
+ ['diego'],
+ addresses: {'diego': '[email protected]'},
+ );
+ expect(
+ find.text('@diego @[email protected] look', findRichText: true),
+ findsOneWidget,
+ );
+ expect(tagRuns(tester), ['@diego']);
+ });
+
+ testWidgets('the conversation knows the address of each person tagged', (
+ tester,
+ ) async {
+ final server = taggedChat();
+ (server.state['people'] as List).cast<Map>().firstWhere(
+ (p) => p['id'] == 'diego',
+ )['email'] = '[email protected]';
+ server.messages.first['text'] = '@[email protected] can you look?';
+ await showView(tester, server, account: 'ken');
+ expect(
+ find.text('@[email protected] can you look?', findRichText: true),
+ findsOneWidget,
+ );
+ expect(tagRuns(tester), ['@[email protected]']);
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('a message that tags you stands out, for you alone '
+ '(${brightness.name})', (tester) async {
+ Finder tagged(String id) =>
+ find.byKey(ValueKey('super-tagged-you-$id'));
+ final server = taggedChat();
+ await showView(
+ tester,
+ server,
+ account: 'diego',
+ brightness: brightness,
+ );
+ await shot(tester, 'tagged-you-${brightness.name}');
+ expect(tagged('message-1'), findsOneWidget);
+ expect(tagged('message-2'), findsNothing);
+ final row = tester.widget<DecoratedBox>(tagged('message-1'));
+ expect(
+ (row.decoration as BoxDecoration).color,
+ grid.AppSurface.accentWash,
+ );
+ final bar = tester.getSize(
+ find.byKey(const ValueKey('super-tagged-bar-message-1')),
+ );
+ expect(bar.width, 3);
+ expect(bar.height, greaterThan(20));
+ expect(
+ tester
+ .widget<ColoredBox>(
+ find.byKey(const ValueKey('super-tagged-bar-message-1')),
+ )
+ .color,
+ grid.AppPalette.accentOnSurface,
+ );
+ // The tag in the text stays its pill, its ink readable on the pill
+ // over the wash (WCAG AA for text, 4.5:1).
+ final (tag, ink) = tagStyles(tester).single;
+ expect(tag, '@diego');
+ final behind = Color.alphaBlend(
+ grid.AppSurface.accentWash,
+ Color.alphaBlend(
+ grid.AppSurface.accentWash,
+ grid.AppTheme.surfacePalette.background,
+ ),
+ );
+ expect(contrast(ink!, behind), greaterThanOrEqualTo(4.5));
+
+ // The same message, read by someone else: plain.
+ await showView(tester, server, account: 'ken', brightness: brightness);
+ await shot(tester, 'tagged-other-${brightness.name}');
+ expect(tagged('message-1'), findsNothing);
+ // A tag in a message that is not yours keeps the pill it had.
+ expect(tagStyles(tester).single.$2, grid.AppPalette.accentOnSurface);
+ expect(
+ find.byKey(const ValueKey('super-tagged-bar-message-1')),
+ findsNothing,
+ );
+ });
+ }
+
testWidgets('the conversation highlights the people a message tags', (
tester,
) async {
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index b5ec77928..48351a4af 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -726,6 +726,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
look: _lookOf(c, m),
role: m.fromAgent && !pm ? view.roles[m.authorId] : null,
mentions: view.mentions,
+ tagged: _taggedOf(c, m).keys.toList(),
+ taggedAddresses: _taggedOf(c, m),
+ readerId: c.reader.accountId,
grouped: grouped,
lit: false,
quote: null,
@@ -1156,6 +1159,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
/// [m]'s author by name; in the person's own Buddy chat the PM's private
/// lines read as lines to them, "River (PM) → you": the PM writes there but
/// cannot read it (#2090).
+ /// The people [m] tags: each one's address by their username, as the
+ /// server names them; an older server's member without one goes by their
+ /// email's name.
+ static Map<String, String> _taggedOf(
+ SwarmConversation c,
+ SuperTabMessage m,
+ ) => {
+ if (m.mentions.isNotEmpty)
+ for (final person in c.reader.snapshot?.people ?? <SuperTabPerson>[])
+ if (m.mentions.contains(person.id))
+ person.chosenUsername ?? person.email.split('@').first: person.email,
+ };
+
String _nameOf(SwarmConversation c, SuperTabMessage m) {
final name = c.reader.snapshot?.authorName(m) ?? m.authorName;
return swarmIsPmLine(c.reader, m) ? '$name (PM) → you' : name;
@@ -1348,6 +1364,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
// project chat, where everyone reads it (Tony, mockup A, 10-29).
final answerIn = pm && view.canPost ? view.buddyProject : null;
final quoted = reply == null ? null : _quoted(c, reply);
+ final tagged = _taggedOf(c, m);
final lit = _lit == m.id, followed = _target == m.id;
final acting = _acting == m.id;
final reactions = c.reactionsOf(m);
@@ -1373,6 +1390,10 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
quoted,
view.canPost,
view.mentions,
+ // The highlight follows the reader: a row kept for another
+ // account is drawn again.
+ c.reader.accountId,
+ [for (final e in tagged.entries) '${e.key}:${e.value}'].join(' '),
reactions,
answerIn,
view.project,
@@ -1389,6 +1410,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
look: look,
role: role,
mentions: view.mentions,
+ tagged: tagged.keys.toList(),
+ taggedAddresses: tagged,
+ readerId: c.reader.accountId,
grouped: grouped,
lit: lit,
followed: followed,
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 73f371cdf..21687d44c 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -57,51 +57,145 @@ Color swarmChatHair(Tty tty) => tty.text.withValues(alpha: 0.12);
Color swarmChatCard(Tty tty) =>
Color.alphaBlend(tty.text.withValues(alpha: 0.05), tty.ground);
-/// The names an @mention in a message is marked for, as the desktop and the
-/// prototype mark them: the pattern that finds them is made once for every
-/// message drawn with them.
+/// `@name` or `@name@domain`, as people tag in chat. Never right after a
+/// letter, digit, `@` or `/` (an address, a path, a link), and a name never
+/// ends in a dot: `@dee.` closes a sentence. The backend and the desktop read
+/// tags by this same rule; test/fixtures/tag_fixture.json is the table all
+/// three pass.
+final _tag = RegExp(
+ r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',
+);
+final _oneWord = RegExp(r'^[\w+-]+(?:\.[\w+-]+)*$');
+final _fence = RegExp(r'^ {0,3}(`{3,}|~{3,})');
+final _codeSpan = RegExp(r'(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)');
+final _linkTarget = RegExp(r'\]\([^)\]]*\)');
+final _bareLink = RegExp(r'\b(?:https?://|www\.)\S+', caseSensitive: false);
+String _blank(String text) => text.replaceAll(RegExp(r'[^\n]'), ' ');
+
+/// [text] with what is never a tag blanked out, each character kept in its
+/// place: fenced and indented code, code spans, bare links and link
+/// destinations.
+String _prose(String text) {
+ final lines = text.split('\n');
+ String? fence;
+ var indented = false;
+ for (var i = 0; i < lines.length; i++) {
+ final line = lines[i];
+ if (fence != null) {
+ final close = _fence.firstMatch(line);
+ if (close != null &&
+ close[1]![0] == fence[0] &&
+ close[1]!.length >= fence.length &&
+ line.substring(close[0]!.length).trim().isEmpty) {
+ fence = null;
+ }
+ lines[i] = _blank(line);
+ continue;
+ }
+ final open = _fence.firstMatch(line);
+ if (open != null &&
+ !(open[1]![0] == '`' &&
+ line.substring(open[0]!.length).contains('`'))) {
+ fence = open[1];
+ lines[i] = _blank(line);
+ indented = false;
+ continue;
+ }
+ // Indented code starts after a blank line (or the first line) and runs
+ // while its lines stay indented.
+ final startsCode =
+ RegExp(r'^( {4}|\t)').hasMatch(line) &&
+ line.trim().isNotEmpty &&
+ (indented || i == 0 || lines[i - 1].trim().isEmpty);
+ indented = startsCode || (indented && line.trim().isEmpty);
+ if (startsCode) lines[i] = _blank(line);
+ }
+ String blanked(Match m) => _blank(m[0]!);
+ return lines
+ .join('\n')
+ .replaceAllMapped(_codeSpan, blanked)
+ .replaceAllMapped(_linkTarget, blanked)
+ .replaceAllMapped(_bareLink, blanked);
+}
+
+/// The names an @mention in a message is marked for, as the desktop marks
+/// them: the chat's agents here, and per message the people it tags. A name
+/// of one word is marked where the shared tag rule finds it; an agent's name
+/// of several words by the pattern made once for every message drawn with it.
class SwarmMentions {
SwarmMentions(List<String> names)
: names = List.unmodifiable(names),
- _pattern = names.isEmpty
+ _words = {
+ for (final name in names)
+ if (_oneWord.hasMatch(name)) name.toLowerCase(),
+ },
+ _pattern = names.every(_oneWord.hasMatch)
? null
: RegExp(
- // Longest first, so "@Nova2" is not read as "@Nova".
- '(?<![\\w@])@(?:${([...names]..sort((a, b) => b.length.compareTo(a.length))).map(RegExp.escape).join('|')})(?![\\w])',
+ // Longest first, so "@Nova 2" is not read as "@Nova".
+ '(?<![\\w@/])@(?:${([for (final name in names)
+ if (!_oneWord.hasMatch(name)) name]..sort((a, b) => b.length.compareTo(a.length))).map(RegExp.escape).join('|')})(?![\\w])',
caseSensitive: false,
);
final List<String> names;
+ final Set<String> _words;
final RegExp? _pattern;
- /// [text] with each @mention of one of [names] marked.
- TextSpan span(String text, TextStyle style) {
- final pattern = _pattern;
- if (pattern == null || !text.contains('@')) {
+ /// [text] with each @mention of one of [names] or [tagged] marked. A tag by
+ /// full address is a tagged person's only when it is their address in
+ /// [addresses] (by username), as the backend matches it to their email.
+ TextSpan span(
+ String text,
+ TextStyle style, {
+ Iterable<String> tagged = const [],
+ Map<String, String> addresses = const {},
+ }) {
+ if (!text.contains('@') || (names.isEmpty && tagged.isEmpty)) {
return TextSpan(text: text, style: style);
}
- return TextSpan(style: style, children: _marked(text, pattern));
+ final words = {..._words, for (final name in tagged) name.toLowerCase()};
+ final known = {
+ for (final MapEntry(:key, :value) in addresses.entries)
+ key.toLowerCase(): value.toLowerCase(),
+ };
+ bool marks(Match match) {
+ final name = match[1]!.toLowerCase();
+ if (match[2] == null) return words.contains(name);
+ if (known.containsValue('$name${match[2]!.toLowerCase()}')) return true;
+ return words.contains(name) && !known.containsKey(name);
+ }
+
+ final prose = _prose(text);
+ final ranges = [
+ for (final match in _tag.allMatches(prose))
+ if (marks(match)) (match.start, match.end),
+ if (_pattern case final pattern?)
+ for (final match in pattern.allMatches(prose)) (match.start, match.end),
+ ]..sort((a, b) => a.$1.compareTo(b.$1));
+ if (ranges.isEmpty) return TextSpan(text: text, style: style);
+ return TextSpan(style: style, children: _marked(text, ranges));
}
}
-List<InlineSpan> _marked(String text, RegExp pattern) {
+List<InlineSpan> _marked(String text, List<(int, int)> marks) {
final spans = <InlineSpan>[];
var at = 0;
- for (final match in pattern.allMatches(text)) {
- if (match.start > at) {
- spans.add(TextSpan(text: text.substring(at, match.start)));
- }
+ for (final (start, end) in marks) {
+ if (start < at) continue;
+ if (start > at) spans.add(TextSpan(text: text.substring(at, start)));
spans.add(
TextSpan(
- text: match[0],
+ text: text.substring(start, end),
+ // The desktop's tag pill (message_text.dart).
style: TextStyle(
color: AppPalette.accentOnSurface,
- backgroundColor: AppPalette.accentOnSurface.withValues(alpha: 0.13),
- fontWeight: FontWeight.w500,
+ backgroundColor: AppSurface.accentWash,
+ fontWeight: FontWeight.w600,
),
),
);
- at = match.end;
+ at = end;
}
if (at < text.length) spans.add(TextSpan(text: text.substring(at)));
return spans;
@@ -193,6 +287,9 @@ class SwarmMessageRow extends StatelessWidget {
required this.look,
required this.role,
required this.mentions,
+ this.tagged = const [],
+ this.taggedAddresses = const {},
+ this.readerId = '',
required this.grouped,
required this.lit,
this.followed = false,
@@ -217,6 +314,17 @@ class SwarmMessageRow extends StatelessWidget {
final String? role;
final SwarmMentions mentions;
+
+ /// The usernames of the people [message] tags: each reads as a pill where
+ /// the text says it.
+ final List<String> tagged;
+
+ /// Their addresses, by username: a tag by full address is theirs only when
+ /// it is this one.
+ final Map<String, String> taggedAddresses;
+
+ /// Who reads it: a message that tags them stands out.
+ final String readerId;
final bool grouped, lit, actions;
/// The row a quote led to: lit, then fading. Only it animates — a fade on
@@ -313,7 +421,12 @@ class SwarmMessageRow extends StatelessWidget {
child: SizedBox(
width: double.infinity,
child: Text.rich(
- mentions.span(part.text, swarmChatText(16, height: 1.42)),
+ mentions.span(
+ part.text,
+ swarmChatText(16, height: 1.42),
+ tagged: tagged,
+ addresses: taggedAddresses,
+ ),
),
),
),
@@ -367,7 +480,31 @@ class SwarmMessageRow extends StatelessWidget {
onLongPress: onLongPress,
child: frame,
);
- if (!followed) return Padding(key: key, padding: padding, child: held);
+ // A message that tags the reader stands out, as Slack marks one that
+ // names you: an accent bar on its edge over a wash of the accent. The
+ // bar is drawn over the row, so nothing in it moves.
+ final taggedYou =
+ readerId.isNotEmpty && message.mentions.contains(readerId);
+ final bar = taggedYou
+ ? BoxDecoration(
+ border: Border(
+ left: BorderSide(color: AppPalette.accentOnSurface, width: 3),
+ ),
+ )
+ : null;
+ if (!followed) {
+ if (!taggedYou) return Padding(key: key, padding: padding, child: held);
+ return KeyedSubtree(
+ key: key,
+ child: Container(
+ key: ValueKey('swarm-tagged-you-${message.id}'),
+ padding: padding,
+ decoration: BoxDecoration(color: AppSurface.accentWash),
+ foregroundDecoration: bar,
+ child: held,
+ ),
+ );
+ }
return AnimatedContainer(
key: key,
duration: const Duration(milliseconds: 600),
@@ -376,9 +513,12 @@ class SwarmMessageRow extends StatelessWidget {
decoration: BoxDecoration(
color: lit
? AppPalette.accentOnSurface.withValues(alpha: 0.16)
+ : taggedYou
+ ? AppSurface.accentWash
: Colors.transparent,
borderRadius: BorderRadius.circular(AppControl.rowRadius),
),
+ foregroundDecoration: bar,
child: held,
);
}
diff --git a/mobile/test/fixtures/tag_fixture.json b/mobile/test/fixtures/tag_fixture.json
new file mode 100644
index 000000000..e1292a29b
--- /dev/null
+++ b/mobile/test/fixtures/tag_fixture.json
@@ -0,0 +1,30 @@
+{
+ "about": "Which words in a chat message are tags. One table for the backend (src/superTabs/mentions.ts), Desktop (desktop/lib/super_tabs/message_text.dart) and the phone (mobile/lib/swarm/swarm_message_row.dart); the three copies must stay byte-identical (scripts/tests/test_tag_fixture_copies.py). Each case lists its tags in order, lowercased, as written after the @ without closing punctuation. names are every name the cases use, so a word that is not a tag is not one only because of where it stands.",
+ "names": ["dee", "ken", "tony", "diego", "dee.ken", "b", "github"],
+ "cases": [
+ { "text": "@diego can you free some memory on your Pro-10? Reviews are waiting on it.", "tags": ["diego"] },
+ { "text": "Thanks @Dee", "tags": ["dee"] },
+ { "text": "Ask @dee.", "tags": ["dee"] },
+ { "text": "@dee, @ken and @tony: please look", "tags": ["dee", "ken", "tony"] },
+ { "text": "(@dee) said so", "tags": ["dee"] },
+ { "text": "It is @dee's turn", "tags": ["dee"] },
+ { "text": "Ask @dee.ken today", "tags": ["dee.ken"] },
+ { "text": "Ask @[email protected] today", "tags": ["[email protected]"] },
+ { "text": "Ask @[email protected].", "tags": ["[email protected]"] },
+ { "text": "> @dee quoted", "tags": ["dee"] },
+ { "text": "- @dee in a list", "tags": ["dee"] },
+ { "text": "Mail [email protected] or [email protected]", "tags": [] },
+ { "text": "git clone [email protected]:autonomous-ai/openharness.git", "tags": [] },
+ { "text": "@@dee and x@dee", "tags": [] },
+ { "text": "an @ alone, and @ dee", "tags": [] },
+ { "text": "run `@dee` here, then @ken", "tags": ["ken"] },
+ { "text": "run ``a `@dee` b`` here", "tags": [] },
+ { "text": "```\n@dee\n```\nthen @ken", "tags": ["ken"] },
+ { "text": "~~~sh\necho @dee\n~~~\nthen @ken", "tags": ["ken"] },
+ { "text": "```\n@dee never closed", "tags": [] },
+ { "text": "Run this:\n\n @dee indented\n\nthen @ken", "tags": ["ken"] },
+ { "text": "See https://github.com/@dee/repo and www.example.com/@ken", "tags": [] },
+ { "text": "See example.com/@dee", "tags": [] },
+ { "text": "[profile](https://example.com/@dee) by @ken", "tags": ["ken"] }
+ ]
+}
diff --git a/mobile/test/swarm/swarm_tags_test.dart b/mobile/test/swarm/swarm_tags_test.dart
new file mode 100644
index 000000000..5324e70fe
--- /dev/null
+++ b/mobile/test/swarm/swarm_tags_test.dart
@@ -0,0 +1,419 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Tags are words in the sentence, as people tag in Slack (Dee, 10-30): the
+/// phone pills the same words the backend and Desktop read as tags, and a
+/// message that tags the reader stands out, for that reader alone.
+final shots = Platform.environment['SWARM_TAG_SHOTS'];
+
+/// The table of tags and non-tags the backend and Desktop pass too.
+final table = jsonDecode(
+ File('test/fixtures/tag_fixture.json').readAsStringSync(),
+) as Map<String, dynamic>;
+
+/// The texts painted as tag pills, in order.
+List<String> pills(WidgetTester tester) => [
+ for (final rich in tester.widgetList<RichText>(find.byType(RichText)))
+ ..._pills(rich.text, null),
+];
+
+Iterable<String> _pills(InlineSpan span, TextStyle? inherited) sync* {
+ if (span is! TextSpan) return;
+ final style = inherited?.merge(span.style) ?? span.style;
+ if (span.text case final text?
+ when style?.backgroundColor == AppSurface.accentWash &&
+ style?.color == AppPalette.accentOnSurface) {
+ yield text;
+ }
+ for (final child in span.children ?? const <InlineSpan>[]) {
+ yield* _pills(child, style);
+ }
+}
+
+Future<void> showRow(
+ WidgetTester tester,
+ String text, {
+ List<String> tagged = const [],
+ Map<String, String> addresses = const {},
+ List<String> mentions = const [],
+ String readerId = '',
+}) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final message = SuperTabMessage.fromJson({
+ 'id': 'm1',
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': 1,
+ 'mentions': mentions,
+ 'author': {'kind': 'person', 'id': me, 'name': 'owner'},
+ 'createdAt': DateTime.utc(2026, 10, 30, 9, 8).toIso8601String(),
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: ListView(
+ children: [
+ SwarmMessageRow(
+ message: message,
+ name: 'owner',
+ look: (picture: null, status: null),
+ role: null,
+ mentions: SwarmMentions(const []),
+ tagged: tagged,
+ taggedAddresses: addresses,
+ readerId: readerId,
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: false,
+ onTap: () {},
+ onReply: null,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+}
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ group('the shared table', () {
+ for (final row in (table['cases'] as List).cast<Map>()) {
+ testWidgets('finds the tags in ${jsonEncode(row['text'])}', (
+ tester,
+ ) async {
+ await showRow(
+ tester,
+ row['text'] as String,
+ tagged: (table['names'] as List).cast<String>(),
+ );
+ expect([
+ for (final pill in pills(tester)) pill.substring(1).toLowerCase(),
+ ], row['tags']);
+ });
+ }
+ });
+
+ testWidgets('a person\'s tag is the Desktop pill', (tester) async {
+ await showRow(tester, '@diego can you look?', tagged: ['diego']);
+ final pill = tester
+ .widgetList<RichText>(find.byType(RichText))
+ .expand((rich) => _styled(rich.text, null))
+ .firstWhere((run) => run.$1 == '@diego')
+ .$2;
+ expect(pill?.color, AppPalette.accentOnSurface);
+ expect(pill?.backgroundColor, AppSurface.accentWash);
+ expect(pill?.fontWeight, FontWeight.w600);
+ });
+
+ test('reads a 32,000-character text of unclosed link brackets in '
+ 'linear time', () {
+ // Each `](` without a `)` once scanned to the end: about 2.9 s to draw.
+ final watch = Stopwatch()..start();
+ final span = SwarmMentions(const [])
+ .span('${'](' * 15995}@dee.', const TextStyle(), tagged: ['dee']);
+ expect(watch.elapsedMilliseconds, lessThan(50));
+ expect(
+ [
+ for (final child in span.children!)
+ if ((child as TextSpan).style?.backgroundColor != null) child.text,
+ ],
+ ['@dee'],
+ );
+ });
+
+ testWidgets('a tag by its full address is its pill', (tester) async {
+ await showRow(
+ tester,
+ tagged: ['diego'],
+ addresses: {'diego': '[email protected]'},
+ );
+ expect(pills(tester), ['@[email protected]']);
+ });
+
+ testWidgets('another address is no tag of them', (tester) async {
+ await showRow(
+ tester,
+ tagged: ['diego'],
+ addresses: {'diego': '[email protected]'},
+ );
+ expect(pills(tester), isEmpty);
+ });
+
+ testWidgets('a name the message does not tag is no pill', (tester) async {
+ await showRow(tester, '@diego and @ken, look', tagged: ['diego']);
+ expect(pills(tester), ['@diego']);
+ });
+
+ testWidgets('a long tagged name wraps at 390 points', (tester) async {
+ final name = 'a-very-long-username-${'x' * 60}';
+ await showRow(
+ tester,
+ '@$name can you free some memory on your Pro-10?',
+ tagged: [name],
+ mentions: ['someone'],
+ readerId: 'someone',
+ );
+ expect(tester.takeException(), isNull);
+ expect(pills(tester), ['@$name']);
+ for (final rich in find.byType(RichText).evaluate()) {
+ expect(rich.size!.width, lessThanOrEqualTo(390));
+ }
+ });
+
+ testWidgets('the chat knows the address of each person tagged', (
+ tester,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await showChat(
+ tester,
+ reader: 'ken',
+ brightness: Brightness.light,
+ diegoEmail: '[email protected]',
+ text: '@[email protected] can you look? Reviews are waiting on it.',
+ );
+ expect(pills(tester), ['@[email protected]']);
+ await closeChat(tester);
+ });
+
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ testWidgets('a message that tags you stands out, for you alone '
+ '(${palette.brightness.name})', (tester) async {
+ final before = (AppTheme.palette.value, AppTheme.brightness.value);
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = palette.brightness;
+ addTearDown(() {
+ AppTheme.palette.value = before.$1;
+ AppTheme.brightness.value = before.$2;
+ });
+ await tester.binding.setSurfaceSize(const Size(390, 844));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ Finder tagged(String id) => find.byKey(ValueKey('swarm-tagged-you-$id'));
+
+ await showChat(tester, reader: 'diego', brightness: palette.brightness);
+ await shot(tester, 'phone-tagged-you-${palette.brightness.name}');
+ expect(tagged('m1'), findsOneWidget);
+ expect(tagged('m2'), findsNothing);
+ final row = tester.widget<Container>(tagged('m1'));
+ expect((row.decoration! as BoxDecoration).color, AppSurface.accentWash);
+ final bar =
+ (row.foregroundDecoration! as BoxDecoration).border! as Border;
+ expect(bar.left.width, 3);
+ expect(bar.left.color, AppPalette.accentOnSurface);
+ expect(pills(tester), contains('@diego'));
+ // The tag's ink stays readable on its pill over the wash (WCAG AA for
+ // text, 4.5:1), on the chat's own ground.
+ final ground = Theme.of(tester.element(tagged('m1')))
+ .scaffoldBackgroundColor;
+ final behind = Color.alphaBlend(
+ AppSurface.accentWash,
+ Color.alphaBlend(AppSurface.accentWash, ground),
+ );
+ final ink = AppPalette.accentOnSurface;
+ final (x, y) = (ink.computeLuminance(), behind.computeLuminance());
+ expect(
+ (math.max(x, y) + 0.05) / (math.min(x, y) + 0.05),
+ greaterThanOrEqualTo(4.5),
+ );
+
+ // The same message, read by someone else: plain, its tag still a pill.
+ await showChat(tester, reader: 'ken', brightness: palette.brightness);
+ await shot(tester, 'phone-tagged-other-${palette.brightness.name}');
+ expect(tagged('m1'), findsNothing);
+ expect(pills(tester), contains('@diego'));
+ await closeChat(tester);
+ });
+ }
+}
+
+Iterable<(String, TextStyle?)> _styled(
+ InlineSpan span,
+ TextStyle? inherited,
+) sync* {
+ if (span is! TextSpan) return;
+ final style = inherited?.merge(span.style) ?? span.style;
+ if (span.text case final text?) yield (text, style);
+ for (final child in span.children ?? const <InlineSpan>[]) {
+ yield* _styled(child, style);
+ }
+}
+
+final _boundary = GlobalKey();
+SwarmHost? _host;
+
+/// Closes the chat and ends its host's timers.
+Future<void> closeChat(WidgetTester tester) async {
+ await tester.pumpWidget(const SizedBox());
+ _host?.dispose();
+ _host = null;
+ await tester.pump(const Duration(minutes: 1));
+}
+
+Future<void> shot(WidgetTester tester, String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final image =
+ await (_boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+/// The project chat as [reader] reads it: the owner's message that tags
+/// diego, then one that tags nobody.
+Future<void> showChat(
+ WidgetTester tester, {
+ required String reader,
+ required Brightness brightness,
+ String diegoEmail = '[email protected]',
+ String text =
+ '@diego can you free some memory on your Pro-10? '
+ 'Reviews are waiting on it.',
+}) async {
+ if (_host != null) await closeChat(tester);
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+ Map<String, dynamic> member(String id, String role) => {
+ ...person(id, role: role),
+ 'username': id == me ? 'owner' : id,
+ if (id == 'diego') 'email': diegoEmail,
+ };
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'OpenHarness', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Pilot',
+ agentIds: ['agent-lead'],
+ lastMessageSequence: 2,
+ ),
+ ],
+ ),
+ 'members': [
+ part(me, 1, member(me, 'owner')),
+ part('diego', 1, member('diego', 'collaborator')),
+ part('ken', 1, member('ken', 'collaborator')),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes[messages] = (_) => {
+ 'messages': [
+ {
+ 'id': 'm1',
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': 1,
+ 'mentions': ['diego'],
+ 'author': {'kind': 'person', 'id': me, 'name': 'owner'},
+ 'createdAt': DateTime.utc(2026, 10, 30, 9, 8).toIso8601String(),
+ },
+ {
+ 'id': 'm2',
+ 'conversationId': 'g1',
+ 'text': 'Thanks, the review queue is moving again.',
+ 'sequence': 2,
+ 'author': {'kind': 'person', 'id': me, 'name': 'owner'},
+ 'createdAt': DateTime.utc(2026, 10, 30, 9, 12).toIso8601String(),
+ },
+ ],
+ 'next': null,
+ };
+ final host = SwarmHost(
+ accountId: () => reader,
+ account: ValueNotifier<String?>(reader),
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ _host = host;
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: _boundary,
+ child: MaterialApp(
+ key: ValueKey('chat-$reader-$brightness'),
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ ),
+ );
+ for (var i = 0; i < 40; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 10)),
+ );
+ await tester.pump();
+ if (find
+ .textContaining('Reviews are waiting', findRichText: true)
+ .evaluate()
+ .isNotEmpty) {
+ break;
+ }
+ }
+}
diff --git a/scripts/tests/test_tag_fixture_copies.py b/scripts/tests/test_tag_fixture_copies.py
new file mode 100644
index 000000000..450ecccee
--- /dev/null
+++ b/scripts/tests/test_tag_fixture_copies.py
@@ -0,0 +1,39 @@
+"""The backend, Desktop and the phone read chat tags by one rule, tested against one table kept in three copies (each
+component's CI checks out only its own folder). The copies must stay byte-identical."""
+from pathlib import Path
+import subprocess
+import unittest
+
+ROOT = Path(__file__).resolve().parents[2]
+COPIES = ("backend/src/superTabs/tagFixture.json", "desktop/test/fixtures/tag_fixture.json", "mobile/test/fixtures/tag_fixture.json")
+
+
+def blob_ids(root, paths):
+ """Each path's git object id at HEAD: equal ids are equal bytes. Process checks check out only scripts, but the
+ commit's trees are there, so this needs none of the files on disk."""
+ out = subprocess.check_output(["git", "ls-tree", "-z", "HEAD", "--", *paths], cwd=root, timeout=15).decode()
+ ids = {}
+ for entry in filter(None, out.split("\0")):
+ meta, path = entry.split("\t", 1)
+ ids[path] = meta.split()[2]
+ return ids
+
+
+def disk_ids(root, paths):
+ """The same ids for the files as they are on disk, uncommitted edits included, when all of them are checked out."""
+ files = [root / path for path in paths]
+ if not all(f.is_file() for f in files):
+ return None
+ out = subprocess.check_output(["git", "hash-object", "--", *map(str, files)], cwd=root, timeout=15).decode()
+ return dict(zip(paths, out.split()))
+
+
+class TagFixtureCopies(unittest.TestCase):
+ def test_the_three_copies_are_identical(self):
+ ids = disk_ids(ROOT, COPIES) or blob_ids(ROOT, COPIES)
+ self.assertEqual(sorted(ids), sorted(COPIES), "a copy of the tag table is missing")
+ self.assertEqual(len(set(ids.values())), 1, f"the tag table copies differ: {ids}; copy {COPIES[0]} over the others")
+
+
+if __name__ == "__main__":
+ unittest.main()