The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 10-30 al: 3 reviewed PRs (#2191, #2094, #2122) (#2251)
0xken15e0d00d72b320
diff --git a/backend/integration/superTabBuddies.test.ts b/backend/integration/superTabBuddies.test.tsindex 0668e81dd..4e36ac1c1 100644--- a/backend/integration/superTabBuddies.test.ts+++ b/backend/integration/superTabBuddies.test.ts@@ -423,6 +423,103 @@ describe('a person\'s Buddy chat before any Buddy, and the PM\'s private lines (})})+describe('naming a Buddy through the store (Diego, 10-29)', () => {+ const rename = (f: Awaited<ReturnType<typeof swarm>>, chat: string, name: string | null, user = peer, asAgentId?: string) =>+ f.execute({ type: 'buddy.rename', conversationId: chat, name }, user, asAgentId)+ const shown = async (f: Awaited<ReturnType<typeof swarm>>, user: AuthUser, agentId: string) =>+ (await f.store.read(user, f.tab)).state.agents.find(a => a.id === agentId)?.displayName++ it('is its owner\'s, and everyone in the Swarm reads the new name, on its roster row and as its messages\' sender', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ await rename(f, chat, 'Sparky')+ expect(await shown(f, owner, agentId)).toBe('Sparky')+ expect(await shown(f, peer, agentId)).toBe('Sparky')+ expect((await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === chat)).toMatchObject({ title: 'Sparky', buddyName: 'Sparky' })+ const said = await f.execute({ type: 'message.send', conversationId: chat, text: 'Hi', replyTo: null, recipientIds: [] }, peer, agentId)+ const row = await db.superTabMessage.findFirstOrThrow({ where: { tabId: f.tab, id: String(said.result.messageId) } })+ expect(row.author).toMatchObject({ id: agentId, displayName: 'Sparky' })+ })++ it('is refused for the Swarm owner, the PM and the Buddy itself', async () => {+ const f = await swarm()+ const { chat, agentId } = await buddy(f)+ await expect(rename(f, chat, 'Mine now', owner)).rejects.toThrow('unavailable')+ await expect(rename(f, chat, 'Mine now', owner, f.lead)).rejects.toThrow()+ await expect(rename(f, chat, 'Mine now', peer, agentId)).rejects.toThrow('A Buddy only talks with its owner')+ expect(await shown(f, owner, agentId)).toBe('peer\'s Buddy')+ })++ it('renamed while it starts, it joins and says it is ready under the new name', async () => {+ const f = await swarm()+ const added = await f.execute({ type: 'buddy.create', projectId: 'lead', machineId: 'peer-mac', engine: 'claude' }, peer)+ const startId = String(added.result.startId), chat = String(added.result.conversationId)+ await rename(f, chat, 'Later')+ const host = (command: Command) => f.execute(command, peer, undefined, 'peer-mac')+ await host({ type: 'agent.startDispatch', startId })+ const agentId = String((await host({ type: 'agent.started', startId, harnessId: randomUUID(), configuration: config })).result.agentId)+ await host({ type: 'agent.startSettled', startId, warning: null })+ expect(await shown(f, owner, agentId)).toBe('Later')+ expect((await f.store.messages(peer, f.tab, chat, {})).messages.map(m => m.text)).toEqual(['Later is ready. Tell it what you have in mind.'])+ })++ it('refuses a name chosen in another person\'s Buddy chat that went quiet', async () => {+ const f = await swarm()+ const theirs = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, owner)).result.conversationId)+ await rename(f, theirs, 'Fern', owner)+ await db.swarmGroup.updateMany({ where: { tabId: f.tab, key: theirs }, data: { dormant: true } })+ const mine = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, peer)).result.conversationId)+ await expect(rename(f, mine, 'fern')).rejects.toThrow('taken')+ await rename(f, mine, 'Fennel')+ })++ it('refuses the name of an agent still starting (review of #2094)', async () => {+ const f = await swarm()+ await f.execute({ type: 'agent.start', request: { conversationId: 'lead', machineId: 'peer-mac', engine: 'claude', name: 'Sparky', cwd: '/swarm/lead',+ worktree: true, requirements: { memoryBytes: 0, diskBytes: 0, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false } } } as Command, peer)+ const mine = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, peer)).result.conversationId)+ await expect(rename(f, mine, 'sparky')).rejects.toThrow('taken')+ })++ it('two people naming their Buddies alike at the same moment, on two servers: one wins, the other is refused (review of #2094)', async () => {+ const f = await swarm()+ const ours = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, peer)).result.conversationId)+ const theirs = String((await f.execute({ type: 'buddy.chat', projectId: 'lead' }, owner)).result.conversationId)+ // A barrier before each first write: both renames have read the names in use (and found Sparky free) before either+ // writes. Attempts after a conflict pass it at once.+ let arrived = 0, release!: () => void+ const bothRead = new Promise<void>(resolve => { release = resolve })+ const barrier = () => { if (++arrived === 2) release(); return bothRead }+ const [one, two] = [0, 1].map(() => new SuperTabStore(beforeFirstWrite(db, barrier), () => Date.now()))+ const settled = await Promise.allSettled([+ one!.execute(peer, f.tab, { operationId: randomUUID(), command: { type: 'buddy.rename', conversationId: ours, name: 'Sparky' } }),+ two!.execute(owner, f.tab, { operationId: randomUUID(), command: { type: 'buddy.rename', conversationId: theirs, name: 'Sparky' } }),+ ])+ expect(arrived).toBeGreaterThanOrEqual(2)+ expect(settled.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])+ expect(String((settled.find(r => r.status === 'rejected') as PromiseRejectedResult).reason)).toContain('taken')+ const named = await db.swarmGroup.findMany({ where: { tabId: f.tab, key: { in: [ours, theirs] } }, select: { data: true } })+ expect(named.filter(g => (g.data as { buddyName?: string }).buddyName === 'Sparky')).toHaveLength(1)+ })++ it('goes back to the default when cleared, and is kept when the Buddy is removed and added again', async () => {+ const f = await swarm()+ const first = await buddy(f)+ await rename(f, first.chat, 'Sparky')+ await rename(f, first.chat, null)+ expect(await shown(f, owner, first.agentId)).toBe('peer\'s Buddy')+ await rename(f, first.chat, 'Sparky')+ await f.execute({ type: 'buddy.remove', projectId: 'lead' }, peer)+ // Another store reads it back from the database: the name lives on the chat, not in a cache.+ const store = new SuperTabStore(db, () => Date.now())+ const again = await buddy({ ...f, store, execute: (command, user = owner, asAgentId, hostMachineId) =>+ store.execute(user, f.tab, { operationId: randomUUID(), command }, asAgentId, hostMachineId) })+ expect(again.chat).toBe(first.chat)+ expect(await shown(f, owner, again.agentId)).toBe('Sparky')+ expect((await f.store.messages(peer, f.tab, again.chat, {})).messages.map(m => m.text)).toContain('Sparky is ready. Tell it what you have in mind.')+ })+})+describe('a Buddy hears how its person\'s requests go, unasked (Diego, 10-29)', () => {/** peer's Buddy and its proposal in the project chat, sent on peer's ask. */async function proposed() {diff --git a/backend/integration/superTabGroupPlans.test.ts b/backend/integration/superTabGroupPlans.test.tsindex 56347fbe5..1978bc49b 100644--- a/backend/integration/superTabGroupPlans.test.ts+++ b/backend/integration/superTabGroupPlans.test.ts@@ -7,7 +7,8 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient, type Prisma } from '@prisma/client'import type { AuthUser } from '../src/lib/ssoAuth.js'-import { SuperTabStore, transaction } from '../src/superTabs/store.js'+import { buddyNames, SuperTabStore, transaction } from '../src/superTabs/store.js'+import { buddyChatId } from '../src/superTabs/buddies.js'import { migrateSwarm } from '../src/superTabs/migration/migrate.js'import { HostReads } from '../src/superTabs/read/host.js'import { DIRECT, readLight } from '../src/superTabs/cachedReads.js'@@ -240,6 +241,24 @@ describe('hot SwarmGroup reads name their index and read only what they return (})// Folded from #1964: a later page started at no bound, so each page read every newer quiet conversation again.+ it('a Buddy rename or add reads the names chosen in the Swarm\'s Buddy chats by key, quiet ones included, and nothing else (review of #2094)', async () => {+ const state = parts.reassemble(await db.$transaction(tx => parts.loadActive(tx, s.tabId)))+ const me = state.people.find(p => p.id === owner.sub)!+ const { id: _id, ...row } = (await db.swarmGroup.findFirst({ where: { tabId: s.tabId, key: s.done } }))!+ const key = buddyChatId(s.other, me)+ await db.swarmGroup.create({ data: { ...row, id: `${s.tabId}:${key}`, key, kind: 'buddy', projectId: s.other, dormant: true,+ data: { ...row.data as object, id: key, kind: 'buddy', projectId: s.other, title: 'Fern', buddyName: 'Fern' } } })+ let names: unknown+ // The other tests count this Swarm's quiet conversations: the chat goes once read.+ const reads = await profiled(async () => { names = await db.$transaction(tx => buddyNames(tx, s.tabId, state)) })+ .finally(() => db.swarmGroup.delete({ where: { id: `${s.tabId}:${key}` } }))+ expect(names).toEqual([{ conversationId: key, name: 'Fern' }])+ expect(reads).toHaveLength(1)+ expect(reads[0]!.plans.join(), JSON.stringify(reads)).toContain('tabId: 1, key: 1')+ expectIndexed(reads)+ expectOnlyReturned(reads)+ })+it('each page of a project\'s quiet conversations reads the 50 it returns, newest activity first', async () => {const order = [...s.quietLead].sort((a, b) => b.lastActivityAt.getTime() - a.lastActivityAt.getTime() || (a.key < b.key ? 1 : -1))const pages: string[][] = []diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex fea613058..930becb1c 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -3362,6 +3362,97 @@ describe('Lead mentions', () => {expect(indexes.cursor.firstBatch).toContainEqual(expect.objectContaining({ key: { createdAt: 1 }, expireAfterSeconds: MENTION_EXPIRY_MS / 1000 }))})+ describe('a tag held for a task with no worker', () => {+ const MINUTE = 60_000+ /** The Lead's notice that a failed start left a task with no worker, tagging the requester only if that lasts. */+ async function held() {+ const { tab, lead } = await fixture()+ await invite(tab)+ const group = (await run(tab, { type: 'conversation.create', title: 'Welcome copy', brief: 'Write the welcome copy',+ checks: [{ description: 'Copy reads well', independent: false }] })).result.conversationId as string+ await run(tab, { type: 'conversation.agent', conversationId: group, agentId: lead, present: true, lead: true })+ const messageId = (await run(tab, { type: 'message.send', conversationId: group, text: 'Builder could not start on the Studio.', replyTo: null,+ recipientIds: [], mentions: [peer.sub], mentionsIfNoWorker: true } as Command, host, lead)).result.messageId as string+ return { tab, lead, group, messageId }+ }+ /** A store whose clock is [minutes] on. */+ const after = (minutes: number) => new SuperTabStore(db, () => Date.now() + minutes * MINUTE)+ const waitingAt = async (tab: string, minutes: number) => (await after(minutes).mentions(peer, tab, 'waiting')).mentions+ const countAt = async (tab: string, minutes: number) => (await waiting(tab, peer, after(minutes))).mentionsWaiting+ const assignAt = async (tab: string, group: string, lead: string, minutes: number) => String((await after(minutes).execute(owner, tab,+ { operationId: randomUUID(), command: { type: 'work.assign', conversationId: group, agentId: lead } })).result.assignmentId)++ it('does not tag the requester at once, and tags them once the group has had no worker for 20 minutes', async () => {+ const { tab, group, messageId } = await held()+ expect(await waitingAt(tab, 0)).toEqual([])+ expect(await countAt(tab, 0)).toBe(0)+ expect(await countAt(tab, 19)).toBe(0)+ expect(await waitingAt(tab, 21)).toEqual([expect.objectContaining({ conversationId: group, messageId, resolvedBy: null })])+ expect(await countAt(tab, 21)).toBe(1)+ expect((await store.messages(owner, tab, group, {})).messages.find(m => m.id === messageId)!.mentions).toEqual([peer.sub])+ })++ it('never tags them when the Lead acted on the group after the notice', async () => {+ const { tab, lead, group } = await held()+ await run(tab, { type: 'message.send', conversationId: group, text: 'Starting it on another machine.', replyTo: null, recipientIds: [] }, host, lead)+ expect(await waitingAt(tab, 21)).toEqual([])+ expect(await countAt(tab, 21)).toBe(0)+ })++ it('never tags them when a worker was assigned within the 20 minutes', async () => {+ const { tab, lead, group } = await held()+ await assignAt(tab, group, lead, 5)+ expect(await waitingAt(tab, 21)).toEqual([])+ expect(await (await after(21).mentions(peer, tab, 'earlier')).mentions).toEqual([])+ })++ it('clears a shown tag the moment a worker is assigned, and does not bring it back when that work ends', async () => {+ const { tab, lead, group, messageId } = await held()+ expect(await countAt(tab, 21)).toBe(1)+ const assignmentId = await assignAt(tab, group, lead, 22)+ expect(await waitingAt(tab, 22)).toEqual([])+ expect(await countAt(tab, 22)).toBe(0)+ expect((await after(22).mentions(peer, tab, 'earlier')).mentions).toEqual([expect.objectContaining({ messageId, resolvedBy: 'worker' })])+ await after(23).execute(owner, tab, { operationId: randomUUID(), command: { type: 'work.cancel', conversationId: group, assignmentId, reason: 'Not needed' } })+ expect(await waitingAt(tab, 24)).toEqual([])+ })++ const earlierAt = async (tab: string, minutes: number) => (await after(minutes).mentions(peer, tab, 'earlier')).mentions+ const as = (minutes: number, user: AuthUser, tab: string, command: Command, agent?: string) =>+ after(minutes).execute(user, tab, { operationId: randomUUID(), command }, agent)+ const post = (group: string): Command => ({ type: 'message.send', conversationId: group, text: 'On it.', replyTo: null, recipientIds: [] })++ it('keeps a tag the Lead acted on out of Waiting and Earlier, also when a worker is assigned or the requester replies later', async () => {+ const { tab, lead, group } = await held()+ await as(5, host, tab, post(group), lead)+ await assignAt(tab, group, lead, 22)+ expect(await waitingAt(tab, 22)).toEqual([])+ expect(await earlierAt(tab, 22)).toEqual([])+ const again = await held()+ await as(5, host, again.tab, post(again.group), again.lead)+ await as(25, peer, again.tab, post(again.group))+ expect(await waitingAt(again.tab, 25)).toEqual([])+ expect(await earlierAt(again.tab, 25)).toEqual([])+ })++ it('moves a listed tag to Earlier when the requester replies after minute 20, and never lists one answered before', async () => {+ const late = await held()+ await as(25, peer, late.tab, post(late.group))+ expect(await waitingAt(late.tab, 25)).toEqual([])+ expect(await earlierAt(late.tab, 25)).toEqual([expect.objectContaining({ messageId: late.messageId, resolvedBy: 'reply' })])+ const early = await held()+ await as(10, peer, early.tab, post(early.group))+ expect(await waitingAt(early.tab, 25)).toEqual([])+ expect(await earlierAt(early.tab, 25)).toEqual([])+ })++ it('keeps a tag out of the lists when its group has no worker but was archived', async () => {+ const { tab, group } = await held()+ await run(tab, { type: 'conversation.archive', conversationId: group, archived: true } as Command)+ expect(await waitingAt(tab, 21)).toEqual([])+ })+ })+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 storedState(tab)diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex f27529564..9776002d8 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1120,8 +1120,10 @@ model SuperTabMention {authorAgentId StringcreatedAt DateTimeresolvedAt DateTime?- /// reply | done+ /// reply | done | workerresolvedBy String?+ /// A tag the Lead made about a task with no worker: not listed before this time (superTabs/mentions.ts). Unset on every other tag.+ holdUntil DateTime?@@index([tabId, personId, createdAt])@@index([tabId, conversationId, personId])diff --git a/backend/src/superTabs/agentNames.ts b/backend/src/superTabs/agentNames.tsindex 587ce5582..8605efcfd 100644--- a/backend/src/superTabs/agentNames.ts+++ b/backend/src/superTabs/agentNames.ts@@ -10,6 +10,8 @@ const names = ['Hugo', 'Indigo', 'Jasper', 'Lark', 'Milo', 'Nico', 'Quinn', 'River',]const defaults = /^(?:lead|builder|agent|new agent|product manager|engineer|pm|dev)(?:[\s#-]+\d+)?$/i+/** A role's name, never a member's: an agent named so is given a member name instead (assignAgentDisplayNames). */+export const isRoleName = (name: string): boolean => defaults.test(name.trim())const automatic = /^(?:claude|codex|pi|agent)-\d{4}-\d{2}-\d{2}(?:[-T].*)?$/ifunction chosen(agent: NamedAgent): string | undefined {diff --git a/backend/src/superTabs/buddies.test.ts b/backend/src/superTabs/buddies.test.tsindex 3465c4fbf..7db3c7483 100644--- a/backend/src/superTabs/buddies.test.ts+++ b/backend/src/superTabs/buddies.test.ts@@ -7,6 +7,7 @@ import { createSuperTab, visibleState, type Actor, type Conversation } from './mimport { canReadGroup, canWatchAgent, isConfidential, readsRecordsIn } from './projects.js'import { CLOSED_CHAT_ANSWERED_NOTICE } from './decisions.js'import { buddyChatId } from './buddies.js'+import { isRoleName } from './agentNames.js'import { sweepLiveness } from './liveness.js'import { hostTab } from './read/hostRows.js'import { groupView } from './read/views.js'@@ -799,3 +800,149 @@ describe('where a Buddy runs (Ken\'s ruling, 10-28)', () => {}})})++describe('naming a Buddy (Diego, 10-29)', () => {+ const host = { contribution: { machineOwnerId: 'peer', contributorId: 'peer' } }+ /** fresh() with peer's Buddy added in App, and started unless [start] is false. */+ function named(start = true) {+ const f = fresh()+ const added = addBuddy(f, peer, f.app.projectId)+ const startId = added.result.startId as string, chat = added.result.conversationId as string+ const agentId = start ? f.run({ type: 'agent.started', startId, harnessId: 'native', configuration }, peer, host).result.agentId as string : ''+ const rename = (name: string | null, actor: Actor = peer, conversationId = chat) => f.run({ type: 'buddy.rename', conversationId, name }, actor)+ return { f, chat, startId, agentId, rename }+ }+ const shown = (f: ReturnType<typeof setup>, reader: Actor, agentId: string) => visibleState(f.state, reader).agents.find(a => a.id === agentId)?.displayName++ it('is its owner\'s: everyone in the Swarm then sees the new name, and their chat takes it as its title', () => {+ const { f, chat, agentId, rename } = named()+ rename(' Sparky ')+ for (const reader of [peer, owner, agentActor(f.pm)]) expect(shown(f, reader, agentId)).toBe('Sparky')+ expect(group(f, chat)).toMatchObject({ title: 'Sparky', buddyName: 'Sparky' })+ })++ it('is refused for anyone else, the Swarm owner and the PM too, and changes nothing', () => {+ const { f, chat, agentId, rename } = named()+ expect(() => rename('Mine now', owner)).toThrow('unavailable')+ expect(() => rename('Mine now', agentActor(f.pm))).toThrow()+ expect(() => rename('Mine now', agentActor(agentId))).toThrow()+ expect(shown(f, owner, agentId)).toBe('peer\'s Buddy')+ expect(group(f, chat).buddyName).toBeUndefined()+ })++ it('renames only a Buddy: a project chat or a workgroup is refused', () => {+ const { f, rename } = named()+ expect(() => rename('Sparky', peer, f.app.conversationId)).toThrow('Buddy chat')+ expect(() => rename('Sparky', owner, f.group)).toThrow('Buddy chat')+ expect(group(f, f.group).title).toBe('Offline')+ })++ it('goes back to the default when cleared, empty or null', () => {+ const { f, chat, agentId, rename } = named()+ for (const cleared of [null, ' ']) {+ rename('Sparky')+ rename(cleared)+ expect(shown(f, owner, agentId)).toBe('peer\'s Buddy')+ expect(group(f, chat).title).toBe('peer\'s Buddy')+ expect(group(f, chat).buddyName).toBeUndefined()+ }+ })++ it('is kept when the Buddy is removed and added again', () => {+ const { f, chat, rename } = named()+ rename('Sparky')+ f.run({ type: 'buddy.remove', projectId: f.app.projectId }, peer)+ const again = addBuddy(f, peer, f.app.projectId)+ expect(f.state.starts!.find(s => s.id === again.result.startId)!.request.name).toBe('Sparky')+ const agentId = f.run({ type: 'agent.started', startId: again.result.startId as string, harnessId: 'native-2', configuration }, peer, host).result.agentId as string+ const settled = f.run({ type: 'agent.startSettled', startId: again.result.startId as string, warning: null }, peer, host)+ expect(shown(f, owner, agentId)).toBe('Sparky')+ expect(settled.messages.map(m => [m.conversationId, m.text])).toEqual([[chat, 'Sparky is ready. Tell it what you have in mind.']])+ })++ it('may be chosen before any Buddy runs, and while one is starting', () => {+ const f = fresh()+ const chat = f.run({ type: 'buddy.chat', projectId: f.app.projectId }, peer).result.conversationId as string+ f.run({ type: 'buddy.rename', conversationId: chat, name: 'Early' }, peer)+ const added = addBuddy(f, peer, f.app.projectId)+ expect(f.state.starts!.find(s => s.id === added.result.startId)!.request.name).toBe('Early')+ f.run({ type: 'buddy.rename', conversationId: chat, name: 'Later' }, peer)+ expect(f.state.starts!.find(s => s.id === added.result.startId)!.request.name).toBe('Later')+ })++ it('takes a name like a username: 2 to 32 letters, digits, spaces and . _ - \', never a role or someone else\'s name', () => {+ const { f, agentId, rename } = named()+ for (const name of ['Sparky', 'R2-D2', 'Nguyễn\'s pal', 'peer\'s Buddy', 'x'.repeat(32), 'Bé Na']) {+ rename(name)+ expect(shown(f, owner, agentId)).toBe(name)+ }+ for (const name of ['a', 'x'.repeat(33), '.dot', 'evilname', 'tab\there', 'two spaces', 'emoji 🎉', 'semi;colon']) {+ expect(() => rename(name)).toThrow('Use 2 to 32')+ }+ const pmName = shown(f, owner, f.pm)!+ for (const name of ['Lead', 'pm', 'Product Manager', 'Engineer', pmName, pmName.toUpperCase(), 'owner']) {+ expect(() => rename(name)).toThrow(/taken|role/)+ }+ expect(shown(f, owner, agentId)).toBe('Bé Na')+ })++ it('refuses invisible characters, and compares and counts names after NFKC (review of #2094)', () => {+ const { f, agentId, rename } = named()+ const pmName = shown(f, owner, f.pm)!+ for (const name of [`${pmName}\uFE0F`, 'Lead\uFE0F', '\u3164\u3164', 'Sp\u200Barky', 'Sparky\u00AD']) expect(() => rename(name)).toThrow()+ // Fullwidth letters are the same name after NFKC: a role, or the PM's name.+ expect(() => rename('Lead')).toThrow('role')+ expect(() => rename([...pmName].map(ch => String.fromCodePoint(ch.codePointAt(0)! + 0xFEE0)).join(''))).toThrow('taken')+ // The ligature ffi is three letters after NFKC: 31 + 3 is too long, while 29 + 3 fits.+ expect(() => rename(`${'x'.repeat(31)}ffi`)).toThrow('Use 2 to 32')+ rename(`${'x'.repeat(29)}ffi`)+ expect(shown(f, owner, agentId)).toBe(`${'x'.repeat(29)}ffi`)+ rename('Sparky')+ expect(shown(f, owner, agentId)).toBe('Sparky')+ })++ it('refuses another person\'s default Buddy name and a name chosen in another Buddy chat, quiet ones included', () => {+ const { f, rename } = named()+ expect(() => rename('owner\'s Buddy')).toThrow('taken')+ const theirs = f.run({ type: 'buddy.chat', projectId: f.web.projectId }, owner).result.conversationId as string+ f.run({ type: 'buddy.rename', conversationId: theirs, name: 'Moss' }, owner)+ expect(() => rename('moss')).toThrow('taken')+ // A chat the command did not load (gone quiet) is named by the store.+ const quiet = { buddyNames: [{ conversationId: 'quiet-chat', name: 'Fern' }] }+ expect(() => f.run({ type: 'buddy.rename', conversationId: buddyChatId(f.app.projectId, { id: 'peer', generation: 'first' }), name: 'FERN' }, peer, quiet)).toThrow('taken')+ // Its own chosen name, also listed by the store, is no clash with itself.+ rename('Sparky')+ f.run({ type: 'buddy.rename', conversationId: buddyChatId(f.app.projectId, { id: 'peer', generation: 'first' }), name: 'Sparky' }, peer, { buddyNames: [{ conversationId: buddyChatId(f.app.projectId, { id: 'peer', generation: 'first' }), name: 'Sparky' }] })+ })++ it('reserves Buddy-only names such as Reviewer, without making them roles for other agents', () => {+ const { rename } = named()+ for (const name of ['Reviewer', 'reviewer', 'Admin', 'System', 'Reviewer 2', 'reviewer-3', 'System 4']) expect(() => rename(name)).toThrow(/role|reserved/)+ expect(isRoleName('Reviewer')).toBe(false)+ })++ it('falls back to the default when its chosen name was taken by the time a Buddy is added again', () => {+ const { f, chat, rename } = named()+ rename('Sparky')+ f.run({ type: 'buddy.remove', projectId: f.app.projectId }, peer)+ f.state.agents.push({ id: 'later', projectId: f.web.projectId, machineId: 'machine', harnessId: 'later-harness', machineOwnerId: 'host',+ contributorId: 'owner', membershipGeneration: 'test', name: 'Sparky', configuration })+ const again = addBuddy(f, peer, f.app.projectId)+ expect(f.state.starts!.find(s => s.id === again.result.startId)!.request.name).toBe('peer\'s Buddy')+ expect(group(f, chat)).toMatchObject({ title: 'peer\'s Buddy' })+ expect(group(f, chat).buddyName).toBeUndefined()+ // Nothing fails silently: its owner reads why in their chat, and how to name it again.+ expect(again.messages.map(m => [m.conversationId, m.text, m.recipients])).toEqual([[chat,+ 'Sparky is taken now; your Buddy starts as peer\'s Buddy. Rename it from the ⋮ menu.', []]])+ })++ it('also falls back when another Buddy chat, quiet or loaded, chose the name meanwhile', () => {+ const { f, chat, rename } = named()+ rename('Sparky')+ f.run({ type: 'buddy.remove', projectId: f.app.projectId }, peer)+ const again = f.run({ type: 'buddy.create', projectId: f.app.projectId, machineId: 'peer-mac', engine: 'claude' }, peer,+ { contribution: { machineOwnerId: 'peer', contributorId: 'peer' }, buddyNames: [{ conversationId: 'quiet-chat', name: 'sparky' }] })+ expect(f.state.starts!.find(s => s.id === again.result.startId)!.request.name).toBe('peer\'s Buddy')+ expect(group(f, chat).buddyName).toBeUndefined()+ })+})diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.tsindex c4c5a68e2..796081a18 100644--- a/backend/src/superTabs/buddies.ts+++ b/backend/src/superTabs/buddies.ts@@ -2,7 +2,8 @@* read. When they ask, it posts one proposal in the project chat on their behalf; the PM assigns the work as usual. A Buddy* reads what its person reads of its project but no private conversation (Ken, 10-29), and does nothing but post in its* chat and propose. On in every Swarm: Buddies replaced Chat with PM (Ken, 10-29). */-import { fail, nextConversationNumber, stableId, type Actor, type Agent, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'+import { agentDisplayName, isRoleName } from './agentNames.js'+import { fail, nextConversationNumber, person, stableId, type Actor, type Agent, type AgentStartRequest, type Conversation, type Person, type SuperTabState } from './model.js'export const isBuddy = (target: Pick<Agent, 'buddyOf'>): boolean => !!target.buddyOfexport const isBuddyChat = (group: Pick<Conversation, 'kind'>): boolean => group.kind === 'buddy'@@ -43,7 +44,7 @@ export function openBuddyChat(state: SuperTabState, projectId: string, owner: Peif (!chat) {const number = nextConversationNumber(state)state.groupCounter = number- chat = { id, kind: 'buddy', ...(state.projects ? { projectId } : {}), number, title: `${owner.email.split('@')[0]}'s Buddy`, leadId: null,+ chat = { id, kind: 'buddy', ...(state.projects ? { projectId } : {}), number, title: defaultBuddyName(owner), leadId: null,agentIds: [], archived: false, brief: '', checks: [], assignment: null, lastMessageSequence: 0,audience: { people: [{ id: owner.id, generation: owner.generation }] } }state.conversations.push(chat)@@ -52,6 +53,83 @@ export function openBuddyChat(state: SuperTabState, projectId: string, owner: Pereturn chat}+/** What a Buddy is called until its owner names it: "ken's Buddy". */+export const defaultBuddyName = (owner: Pick<Person, 'email'>): string => `${owner.email.split('@')[0]}'s Buddy`++/** A Buddy's name as its owner may choose it, sized like a username (usernames are 2 to 32 characters, starting with a+ * letter or digit) but a display name: letters of any case and language, digits, single spaces, `.`, `_`, `-` and+ * apostrophes, as the default "ken's Buddy" has. Checked after NFKC, which also makes it the name kept; nothing that hides+ * its shape (controls, bidi overrides, and every default-ignorable such as U+FE0F or a Hangul filler: review of #2094). */+const BUDDY_NAME = /^[\p{L}\p{N}](?:[\p{L}\p{M}\p{N}._'\u2019-]| (?! ))*$/u+const INVISIBLE = /\p{Default_Ignorable_Code_Point}/u+const BUDDY_NAME_LENGTH = { min: 2, max: 32 }+/** Names only a Buddy is refused, beside roles (agentNames.ts isRoleName, which also picks automatic agent names and so+ * stays as it is): the Reviewer and the Swarm's own voices. Compared as `nameKey`s. */+const BUDDY_RESERVED: ReadonlySet<string> = new Set(['reviewer', 'admin', 'administrator', 'system', 'swarm', 'harness', 'everyone'])+/** A name as names are compared: NFKC, lowercased. Look-alike letters of other scripts are out of scope (review of #2094). */+const nameKey = (name: string): string => name.normalize('NFKC').toLowerCase()+/** Whether [name] is a reserved one, numbered too ("Reviewer 2", "system-3"), as the role check reads "Lead 2". */+const reserved = (name: string): boolean => BUDDY_RESERVED.has(nameKey(name).replace(/[\s#-]+\d+$/, ''))++/** A name chosen in a Buddy chat, as the store reads every Buddy chat's, quiet ones included (store.ts buddyNames). */+export interface ChosenBuddyName { conversationId: string; name: string }++/** Whether [name] for [chat]'s Buddy is someone else's: another agent's name (the PM's included) or one still starting, a+ * person's, another person's default Buddy name, or a name chosen in another Buddy chat, loaded or listed by the store in+ * [chosen]. Two commands claiming a name never both pass: each touches the head part (parts/touches.ts). */+function nameTaken(state: SuperTabState, chat: Conversation, name: string, chosen: readonly ChosenBuddyName[]): boolean {+ const owner = chat.audience?.people[0]?.id+ const others = [+ ...state.agents.filter(a => !chat.agentIds.includes(a.id)).map(a => agentDisplayName(state.agents, a.id) ?? a.name),+ // An agent still starting has its name already (review of #2094): its own Buddy's start excepted.+ ...(state.starts ?? []).filter(st => !st.harnessId && !st.error && st.request.conversationId !== chat.id).map(st => st.request.name),+ ...state.people.map(p => p.email.split('@')[0]!),+ ...state.people.filter(p => p.id !== owner).map(defaultBuddyName),+ ...state.conversations.filter(c => isBuddyChat(c) && c.id !== chat.id && c.buddyName).map(c => c.buddyName!),+ ...chosen.filter(c => c.conversationId !== chat.id).map(c => c.name),+ ]+ const key = nameKey(name)+ return others.some(other => nameKey(other) === key)+}++/** `buddy.rename`: a person names their own Buddy, from its chat, or clears the name for the default (Diego, 10-29). Only+ * the chat's owner may; the Swarm owner and every agent are refused, and so is any chat that is not a Buddy chat. The name+ * is kept on the chat, so a Buddy added again takes it (chosenBuddyName), and is shown at once by a running or starting one. */+export function renameBuddy(state: SuperTabState, actor: Actor, chat: Conversation, input: string | null, chosen: readonly ChosenBuddyName[] = []): void {+ if (actor.kind !== 'person') fail('BUDDY_PERSON', 'A person names their own Buddy.', 403)+ if (!isBuddyChat(chat)) fail('BUDDY_CHAT', 'Name a Buddy from your Buddy chat.', 400)+ const owner = person(state, actor.userId)+ if (!chat.audience?.people.some(p => p.id === owner.id && p.generation === owner.generation)) fail('NOT_FOUND', 'This conversation is unavailable.', 404)+ const name = input?.normalize('NFKC').trim() || null+ if (name) {+ const length = [...name].length+ if (length < BUDDY_NAME_LENGTH.min || length > BUDDY_NAME_LENGTH.max || INVISIBLE.test(name) || !BUDDY_NAME.test(name)) {+ fail('INVALID_BUDDY_NAME', 'Use 2 to 32 letters, digits, single spaces, dots, dashes, underscores or apostrophes, starting with a letter or digit.', 400)+ }+ if (isRoleName(name) || reserved(name)) fail('BUDDY_NAME_ROLE', `${name} is a role's name. Choose another.`, 400)+ if (nameTaken(state, chat, name, chosen)) fail('BUDDY_NAME_TAKEN', `${name} is taken in this Swarm. Choose another.`, 409)+ chat.buddyName = name+ } else {+ delete chat.buddyName+ }+ const shown = name ?? defaultBuddyName(owner)+ chat.title = shown+ for (const buddy of state.agents) if (isBuddy(buddy) && chat.agentIds.includes(buddy.id)) buddy.displayName = shown+ for (const start of state.starts ?? []) if (start.request.conversationId === chat.id && !start.error && !start.poolSettled) start.request.name = shown+}++/** The name [owner]'s Buddy added in [chat] starts with: the one chosen there, unless someone took it since (a new agent, a+ * person who joined, another Buddy chat), when the chat goes back to the default rather than show two Buddies alike, and+ * `notice` is the line that tells its owner so in their chat: nothing changes without saying (review of #2094). */+export function chosenBuddyName(state: SuperTabState, chat: Conversation, owner: Person, chosen: readonly ChosenBuddyName[] = []): { name: string; notice?: string } {+ const was = chat.buddyName+ if (!was) return { name: defaultBuddyName(owner) }+ if (!nameTaken(state, chat, was, chosen)) return { name: was }+ delete chat.buddyName+ chat.title = defaultBuddyName(owner)+ return { name: chat.title, notice: `${was} is taken now; your Buddy starts as ${chat.title}. Rename it from the ⋮ menu.` }+}+/** What a Buddy asks of its machine: it reads and talks, so the usual agent's share with git to read the project. */export const BUDDY_REQUIREMENTS: AgentStartRequest['requirements'] = { memoryBytes: 2 * 1024 ** 3, diskBytes: 1024 ** 3, maxCpuPercent: 85,tools: ['git'], devices: [], quotaRequired: false }diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 7c268716b..6fd5b9c4c 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -3134,6 +3134,15 @@ describe('Lead mentions', () => {expect(f.run(send(secret.conversationId, ['owner']), as(secret.lead)).messages[0]!.mentions).toEqual(['owner'])})+ it('holds a tag for a notice that says a task has no worker, and only a tag can be held', () => {+ const { f, lead } = swarm(), group = f.group()+ const held = (mentions: string[]): Command => ({ ...send(group, mentions), mentionsIfNoWorker: true } as Command)+ expect(f.run(held(['peer']), as(lead)).messages[0]).toMatchObject({ mentions: ['peer'], holdMentions: true })+ expect(f.run(send(group, ['peer']), as(lead)).messages[0]).not.toHaveProperty('holdMentions')+ expect(() => f.run(held([]), as(lead))).toThrow('Hold a tag only for a message that tags someone.')+ expect(commandSchema.safeParse({ ...send(group, ['peer']), mentionsIfNoWorker: false }).success).toBe(false)+ })+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)@@ -3229,7 +3238,9 @@ describe('credentials in Swarm chat', () => {expect(route).toMatchObject({ decision: { assessment: { why: `needs ${CREDENTIAL_MARKER}` }, excluded: [{ reason: `asked for ${CREDENTIAL_MARKER}` }] } })const owns = withoutCredentials({ type: 'work.define', conversationId: 'g', checks: [], task: { goal: 'g', changes: 'c', constraints: 'n', owns: ['src', github] } } as unknown as Command, removed)expect(owns).toMatchObject({ task: { owns: ['src', CREDENTIAL_MARKER] } })- expect(removed).toEqual(['github', 'github', 'jwt', 'github', 'github'])+ const rename = withoutCredentials({ type: 'buddy.rename', conversationId: 'chat', name: github } as Command, removed)+ expect(rename).toMatchObject({ name: CREDENTIAL_MARKER })+ expect(removed).toEqual(['github', 'github', 'jwt', 'github', 'github', 'github'])// Commands with no words of their own are passed through untouched.const pause: Command = { type: 'tab.pause', paused: true }expect(withoutCredentials(pause, removed)).toBe(pause)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex 748ab6a1e..91678288c 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -34,7 +34,7 @@ import { openReview, openReviewOf, projectPullRequest, verdictPending } from './import { carryOver, cheapAttempt, GRID_START_FAILED, REVIEW_FAILED, stepUp, stepUpRefusal } from './stepUp.js'import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, isConfidential, markConfidential, onTeamAccount, requireSingleRegistration, 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'-import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, PROPOSAL_ASK_MS, proposalText, requireBuddyCommand } from './buddies.js'+import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, PROPOSAL_ASK_MS, proposalText, renameBuddy, requireBuddyCommand } from './buddies.js'import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'import { LEAD_NAME, leadJoined, leadStartFailed, leadStarting, placeLead } from './leadStart.js'@@ -150,6 +150,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('buddy.remove'), projectId: id }).strict(),// A person's own Buddy chat in a project, opened before any Buddy is (buddies.ts openBuddyChat).z.object({ type: z.literal('buddy.chat'), projectId: id }).strict(),+ // A person names their own Buddy from its chat, or clears the name with null (buddies.ts renameBuddy).+ z.object({ type: z.literal('buddy.rename'), conversationId: id, name: z.string().max(200).nullable() }).strict(),// The PM's private line to one person, in their Buddy chat of its project: Buddies replaced Chat with PM (Ken, 10-29).z.object({ type: z.literal('person.tell'), personId: id, text: z.string().trim().min(1).max(32_000) }).strict(),// A person's own Buddy in a project, on a machine of the Swarm (buddies.ts).@@ -182,7 +184,8 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('agent.avatar'), agentId: id, avatar: avatarChoice }).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),- alsoSend: z.literal(true).optional(), attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(), agentOnly: z.literal(true).optional() }).strict(),+ alsoSend: z.literal(true).optional(), attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(),+ mentionsIfNoWorker: z.literal(true).optional(), agentOnly: z.literal(true).optional() }).strict(),z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean() }).strict(),z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),@@ -232,6 +235,7 @@ const WORDS: Partial<Record<Command['type'], readonly string[]>> = {'agent.startSettled': ['warning'],'conversation.create': ['title', 'brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'checks[].description'],'conversation.rename': ['title'],+ 'buddy.rename': ['name'],'work.define': ['brief', 'task.goal', 'task.changes', 'task.constraints', 'task.owns[]', 'checks[].description'],'work.assign': ['overrideReason'],'work.status': ['result'],@@ -296,6 +300,9 @@ export interface CommandContext {agentOnly?: true }/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */openTags?: Array<{ messageId: string; createdAt: number }>+ /** For `buddy.rename` and `buddy.create`: the names chosen in this Swarm's Buddy chats, quiet ones included, read by the+ * store (buddies.ts chosenBuddyName): a command loads only the chats it names. */+ buddyNames?: import('./buddies.js').ChosenBuddyName[]/** The proposal a new group names as its origin (conversation.create proposalMessageId), loaded from this tab by the store. */proposal?: { id: string; conversationId: string; author: Author; source: Record<string, unknown> | null }/** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. */@@ -610,9 +617,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commabrief: 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[], mentions?: string[]) => {+ attachments?: Attachment[], mentions?: string[], holdMentions?: true) => {effects.messages.push({ id: operationId, conversationId, author: sender, text: body, replyTo, recipients, ...(source ? { source } : {}),- ...(attachments?.length ? { attachments } : {}), ...(mentions?.length ? { mentions } : {}) })+ ...(attachments?.length ? { attachments } : {}), ...(mentions?.length ? { mentions } : {}), ...(holdMentions ? { holdMentions } : {}) })result.messageId = operationId}/** The project Lead's own route, start, assignment or post on a task, with its time (liveness.ts reads it). It rides on the@@ -1545,6 +1552,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaresult.conversationId = openBuddyChat(state, readProject(state, actor, command.projectId).id, person(state, actor.userId)).idbreak}+ case 'buddy.rename':+ renameBuddy(state, actor, readConversation(state, actor, command.conversationId), command.name, context.buddyNames)+ breakcase 'person.tell': {const project = actor.kind === 'agent' ? ledProject(state, actor.agentId) : undefinedif (!project) fail('TELL_FORBIDDEN', 'Only a project\'s Lead sends a person a private line, in its own project.', 403)@@ -1589,10 +1599,11 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma// A slot for each of its person's Buddies there, one per project: it takes nothing else.if (pool.buddyOnly) pool.maxAgents = machineSlots(state, pool) + 1const contributor = person(state, grant.contributorId)- openBuddyChat(state, project.id, me)+ const chat = openBuddyChat(state, project.id, me)+ const named = chosenBuddyName(state, chat, me, context.buddyNames)// Never moved to the Mac's Team account, as a teammate's project otherwise is (machines.ts teamStartRequest).const request: AgentStartRequest = { conversationId: chatId, machineId: pool.machineId, engine: command.engine,- ...(command.model ? { model: command.model } : {}), name: `${who}'s Buddy`, cwd: projectFolder(pool, project), worktree: true,+ ...(command.model ? { model: command.model } : {}), name: named.name, cwd: projectFolder(pool, project), worktree: true,requirements: BUDDY_REQUIREMENTS, buddyOf: { personId: me.id, generation: me.generation } }const admitted = admitMachineStart(state, request, context.now, undefined, context.teamMachines, context.otherWorkspaceMachines)!state.starts ??= []@@ -1600,6 +1611,8 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commastate.starts.push({ poolGeneration: admitted.generation, id: operationId, creationId: `super-${operationId}`, actorKey: actorKey(actor),contributorId: contributor.id, membershipGeneration: contributor.generation, machineOwnerId: grant.machineOwnerId,hostGrant: grant.hostGrant ?? null, request, harnessId: null, dispatched: false, error: null, requestedAt: context.now })+ // Its chosen name was taken since: its owner reads so in their chat, to nobody else (buddies.ts chosenBuddyName).+ if (named.notice) message(chatId, named.notice, [], null, SYSTEM_ROW)result.startId = operationIdresult.conversationId = chatIdbreak@@ -1929,6 +1942,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaconst 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.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)}@@ -1967,7 +1981,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commafail('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)+ message(group.id, command.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 : nulldiff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.tsindex f45feff0a..b761daf0f 100644--- a/backend/src/superTabs/mentions.ts+++ b/backend/src/superTabs/mentions.ts@@ -4,7 +4,7 @@import { createHash } from 'node:crypto'import type { Prisma, PrismaClient } from '@prisma/client'import { ensureIndex } from '../lib/db/indexes.js'-import { fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'+import { activeWork, fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'import { canReadGroup, groupProject, ledProject, projectOf } from './projects.js'import { groupsBy } from './parts/indexed.js'import { usernameOf } from './usernames.js'@@ -13,6 +13,10 @@ type Tx = Prisma.TransactionClientexport 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+/** A Lead's tag about a task with no worker (message.send mentionsIfNoWorker) is listed only after this long, and only if the+ * group still has no worker and the Lead has done nothing for it since: the Lead sees a failed start first and usually+ * restarts the task within minutes, so a person tagged at once got a notice they could do nothing about (Dee, 2026-10-29). */+export const NO_WORKER_GRACE_MS = 20 * 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. */@@ -47,7 +51,7 @@ export async function writeMentions(tx: Tx, tabId: string, state: SuperTabState,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,+ createdAt: new Date(now), resolvedAt: null, resolvedBy: null, ...(message.holdMentions ? { holdUntil: new Date(now + NO_WORKER_GRACE_MS) } : {}),})))if (data.length) await tx.superTabMention.createMany({ data })}@@ -58,6 +62,28 @@ export async function resolveByReply(tx: Tx, tabId: string, conversationId: stridata: { resolvedAt: new Date(now), resolvedBy: 'reply' } })}+/** A worker took the group: its held tags are over. A listed one moves to Earlier; one not yet listed is dropped, as if never+ * made. Run before [dropHeldTags] of the same command, which would drop the listed ones too. */+export async function resolveWhenWorked(tx: Tx, tabId: string, conversationId: string, now: number): Promise<void> {+ const held = { tabId, conversationId, holdUntil: { isSet: true as const }, ...waiting }+ await tx.superTabMention.updateMany({ where: { ...held, holdUntil: { lte: new Date(now) } }, data: { resolvedAt: new Date(now), resolvedBy: 'worker' } })+ await tx.superTabMention.deleteMany({ where: held })+}++/** The group's Lead acted on it (leadAction in the state): the held tags made before that are dropped for good, listed or not.+ * Dropped, not resolved, so a later reply or assignment cannot bring one back in Earlier. */+export async function dropHeldTags(tx: Tx, tabId: string, conversationId: string, now: number): Promise<void> {+ await tx.superTabMention.deleteMany({ where: { tabId, conversationId, holdUntil: { isSet: true }, createdAt: { lt: new Date(now) }, ...waiting } })+}++/** Whether a tag is listed: a held one only once its time has come, while its group still has no worker; one answered before+ * it came up was never listed. */+function listed(row: { resolvedAt: Date | null; holdUntil?: Date | null }, group: Conversation, now: number): boolean {+ if (!row.holdUntil) return true+ if (row.resolvedAt) return row.resolvedAt >= row.holdUntil+ return now >= row.holdUntil.getTime() && !group.archived && !activeWork(group)+}+/** The tags a person's post in this conversation is about to answer (resolveByReply), for the leaderboard's credit* (leaderboard/record.ts recordPost): only which message and when. */export async function openTags(tx: Tx, tabId: string, conversationId: string, personId: string, now: number): Promise<Array<{ messageId: string; createdAt: number }>> {@@ -93,7 +119,7 @@ async function readable(tx: Tx, tabId: string, state: SuperTabState, actor: Extr}return rows.flatMap(row => {const group = groups.get(row.conversationId)- return group && !isLeads(group) && canReadGroup(state, actor, group) ? [{ row, group }] : []+ return group && !isLeads(group) && canReadGroup(state, actor, group) && listed(row, group, now) ? [{ row, group }] : []})}diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex c7643996f..d61a0764b 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -248,6 +248,9 @@ export interface Conversation {reactionSeq?: number/** A Buddy chat's owner messages its Buddy already proposed for (buddies.ts): each asks once. */proposals?: string[]+ /** The name a Buddy chat's owner chose for their Buddy (buddies.ts renameBuddy): kept here, which outlives the Buddy, so+ * one added again takes it. Absent: the default, "<person>'s Buddy". */+ buddyName?: string/** The person who asked for this work: whoever opened it, or the person its Lead named (leaderboard/record.ts). */requesterId?: string/** What the leaderboard counts here (leaderboard/record.ts); bookkeeping readers never get whole. */@@ -383,6 +386,8 @@ export interface MessageDraft {attachments?: import('./attachments.js').Attachment[]/** People a Lead tagged (mentions.ts). */mentions?: string[]+ /** Its tags wait until the group has had no worker and no Lead action for a while (mentions.ts NO_WORKER_GRACE_MS). */+ holdMentions?: true/** The root of the thread this reply is in; absent on a top-level message, which is its own thread (writeMessages). */thread?: string/** A thread reply also shown in the conversation's main stream. */diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex 7717c8b8c..1a6f1db80 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -13,7 +13,7 @@ const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [], cards: {},messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,- requesterId: 'p', ledger: {}, proposals: [], liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },+ requesterId: 'p', ledger: {}, proposals: [], buddyName: 'Sparky', liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },stepUp: { attempt: 2, floor: 2, reason: 'r', at: 1, carry: '' },}diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex e3c42eb74..e61c85a20 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status','assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction', 'stepUp',+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'cards', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'buddyName', 'liveness', 'leadAction', 'stepUp','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf', 'assignment.reviewFoundAt'],} as constconst LIGHT_GROUP = {diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.tsindex 700523945..5dd6bdc96 100644--- a/backend/src/superTabs/parts/touches.ts+++ b/backend/src/superTabs/parts/touches.ts@@ -61,6 +61,8 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatecase 'buddy.create':// It may record a Buddy-only machine, or count on one that a concurrent removal of its last Buddy ends.slots(command.machineId)+ // Its name is claimed against every other name in the Swarm, as buddy.rename's is (below).+ head()breakcase 'agent.avatar':leadCheck(agentProject(command.agentId))@@ -70,6 +72,12 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabStatefor (const person of before.people) member(person.id)head()break+ // A Buddy's name is claimed against every other name in the Swarm, some of them in chats a command does not load: the+ // head guards the claim, as agent.start and agent.add touch it, so of two claims at once one retries and is refused+ // (review of #2094).+ case 'buddy.rename':+ head()+ breakcase 'project.report': case 'project.repository': case 'project.skills':leadCheck(command.projectId)breakdiff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex 88ab69e93..e62f9dc5e 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -21,7 +21,7 @@ import { randomBytes } from 'node:crypto'import type { Readable } from 'node:stream'import { logger } from '../utils/logger.js'import { retryTransient } from './retry.js'-import { buddyChatId } from './buddies.js'+import { buddyChatId, type ChosenBuddyName } from './buddies.js'import { canReadAgent, canReadGroup, canWatchAgent, groupProject, ledProject, onTeamAccount, projectOf, projectsOf, agentProjectId, readConversation, roleVersion, skillModeOf, type ProjectVisibility } from './projects.js'import { bindSession, makeProjectPrivate } from './sessionScope.js'import { isBuddy, isBuddyReader, refuseBuddyRouting, routingRow } from './buddies.js'@@ -56,7 +56,7 @@ import { mayDrive, TERMINAL_ANSWER_MS, TERMINAL_EXPIRY_MS, TERMINAL_PICKUP_MS, Timport { costRows, summarizeCosts } from './costs/read.js'import { recordEvidence } from './evidence/store.js'import { closeAssignment, closeUnassignedStart, readDecision, recentDecisions, recordAttempts, timedDecisionOf, writeRouteEffects } from './routeDecisions.js'-import { listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, writeMentions } from './mentions.js'+import { dropHeldTags, listMentions, markDone, mentionsWaiting, openTags, readMention, resolveByReply, resolveWhenWorked, writeMentions } from './mentions.js'import { answerable, fullFor, listDecisions, type DecisionList, readAskedDecision, recordAnswer, repeatOf, waitingFor, waitingIn, waitingInProject, writeDecisions } from './decisions.js'import { CATCH_UP_SCAN, catchUpSummary, type CatchUp } from './catchUp.js'import { DEFAULT_ROUTING_POLICY, effectivePolicy, routingPolicySchema, type RoutingPolicy } from './routingPolicy.js'@@ -1141,6 +1141,7 @@ export class SuperTabStore {if (error instanceof SuperTabError && ['HOST_UNAVAILABLE', 'HOST_REQUIRED'].includes(error.code)) fail('BUDDY_OWN_MACHINE', BUDDY_OWN_MACHINE_REFUSAL, 403)throw error})+ if (command.type === 'buddy.rename' || command.type === 'buddy.create') context.buddyNames = await buddyNames(tx, tabId, original)if (command.type === 'agent.started' || command.type === 'agent.startDispatch') {const start = original.starts?.find(s => s.id === command.startId) ?? fail('NOT_FOUND', 'This agent start is unavailable.', 404)context.contribution = await this.contribution(tx, original, actor, start.request, true)@@ -1415,6 +1416,11 @@ export class SuperTabStore {await recordEvidence(tx, tabId, original, effects.state, context.now)await this.writeMessages(tx, tabId, effects.state, effects.messages, sequences)if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)+ if (command.type === 'work.assign') await resolveWhenWorked(tx, tabId, command.conversationId, context.now)+ // The Lead acting on a group ends the tags it held back about it (mentions.ts), before this command's own are written.+ const ledId = 'conversationId' in command ? command.conversationId : command.type === 'agent.start' ? command.request.conversationId : undefined+ const leadAt = (state: SuperTabState) => state.conversations.find(c => c.id === ledId)?.leadAction?.at+ if (ledId && leadAt(effects.state) !== undefined && leadAt(effects.state) !== leadAt(original)) await dropHeldTags(tx, tabId, ledId, 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 (command.type === 'message.react') await this.writeReaction(tx, tabId, actor, command)@@ -2712,3 +2718,17 @@ export class SuperTabStore {return done}}++/** The names chosen in [state]'s Buddy chats, quiet ones included (buddies.ts chosenBuddyName). A chat's id is fixed per+ * project and person (buddyChatId), so they are read by key, naming the unique index (parts/indexed.ts groupsBy), the name+ * alone: a few short strings per person and project, and only for a rename or an add. `$gt: ''` keeps the non-empty strings+ * (a `$type` match reads as a tagged value to Prisma's raw replies). */+export async function buddyNames(tx: Transaction, tabId: string, state: SuperTabState): Promise<ChosenBuddyName[]> {+ const keys = projectsOf(state).flatMap(project => state.people.map(person => buddyChatId(project.id, person)))+ if (!keys.length) return []+ const rows = await groupsBy(tx, 'key', [+ { $match: { tabId, key: { $in: keys }, deleted: false, 'data.buddyName': { $gt: '' } } },+ { $project: { _id: 0, key: 1, name: '$data.buddyName' } },+ ]) as Array<{ key: string; name: string }>+ return rows.map(row => ({ conversationId: row.key, name: row.name }))+}diff --git a/cli/e2e/superTabStartBlocked.e2e.ts b/cli/e2e/superTabStartBlocked.e2e.tsnew file mode 100644index 000000000..6660e02ed--- /dev/null+++ b/cli/e2e/superTabStartBlocked.e2e.ts@@ -0,0 +1,96 @@+/** A Lead's routed start that the machine's host fails, with no other machine to try, on the real native protocol: a private+ * daemon, tmux and data dir, a fake Claude engine and the fake backend. The group is told the task has no worker, and its+ * requester is tagged only if the task still has none after a while (backend mentions.ts), which this checks by the+ * command the backend would receive. Database behaviour is covered by the backend's tests. */+import { createHash } from 'node:crypto'+import { mkdirSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { superTabCommand } from '../src/superTabs/command.js'+import { LocalClient } from './harness/client.js'+import { IsolatedDaemon } from './harness/daemon.js'+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'+import { overOldRoutes } from './harness/swarmReads.js'++const ME: FakeMachine = { machineId: 'd7'.repeat(16), computerId: 'e2e-super-tab-blocked-computer', name: 'Fixture Mac', token: 'e2e-super-tab-blocked-token' }+const TAB = 'blocked-tab'+let daemon: IsolatedDaemon | undefined, backend: FakeBackend | undefined+const clients: LocalClient[] = []+afterEach(async () => {+ clients.splice(0).forEach(client => client.close())+ await daemon?.close(); daemon = undefined+ await backend?.close(); backend = undefined+})++it('tells the group a failed start left no worker, and tags the requester only on hold', async () => {+ const relay = await FakeBackend.start(); backend = relay; relay.addMachine(ME)+ const d = await IsolatedDaemon.create({ submissionGate: true, env: {+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId, ANTHROPIC_API_KEY: 'fixture-not-a-credential',+ } }); daemon = d+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token,+ autonomousEnv: 'prod', computerId: ME.computerId, machineId: ME.machineId,+ expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',+ }), { mode: 0o600 })+ onTestFailed(() => console.log(d.log().split('\n').slice(-160).join('\n')))+ await d.start()+ const client = await LocalClient.connect(d, { machineId: ME.machineId }); clients.push(client)+ const cwd = join(d.projectsDir, 'project'); mkdirSync(cwd, { recursive: true })+ const made = await client.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(made.error, JSON.stringify(made)).toBeUndefined()+ const leadId = createHash('sha256').update(JSON.stringify([ME.machineId, made.agent.id])).digest('hex').slice(0, 24)+ const agents = [{ id: leadId, name: 'Lead', machineId: ME.machineId, harnessId: made.agent.id, configuration: { engine: 'claude', model: 'opus', effort: 'high' } }]+ const conversations = [{ id: 'g1', title: 'API', projectId: 'p1', leadId, agentIds: [leadId], archived: false, brief: 'Add the endpoint.',+ checks: [{ description: 'Tests pass' }], assignment: null, requesterId: 'person-1' }]+ const candidate = { id: 'c0', kind: 'new', machineId: ME.machineId, engine: 'claude', model: 'opus', effort: 'high', quality: 3, cost: 10,+ title: 'Builder · Claude opus high', label: 'Fixture Mac' }+ const decision = { id: 'd-1', conversationId: 'g1', outcome: 'failed', final: null, override: null,+ record: { assessment: { difficulty: 'medium', risk: 'low', why: 'Fixture.', size: 'medium' }, candidates: [candidate], excluded: [],+ floor: 2, notes: false, pick: 'c0', via: 'order', p: null, belowFloor: false, why: 'Policy order.' } }+ const starts = new Map<string, Record<string, any>>()+ const commands: Array<Record<string, any>> = []+ relay.superTabs = overOldRoutes(async (method, raw, body) => {+ const url = new URL(raw, relay.httpUrl), path = url.pathname+ if (path === `/api/super-tabs/${TAB}` && method === 'GET') return { data: { revision: commands.length, state: { id: TAB, agents, conversations,+ projects: [{ id: 'p1', name: 'API', ownerId: 'owner-1', repository: { machineId: ME.machineId, cwd } }],+ machines: [{ machineId: ME.machineId, name: ME.name, scope: 'swarm', cwd }], rules: [],+ people: [{ id: 'person-1', email: '[email protected]', role: 'collaborator' }] } } }+ if (path === `/api/super-tabs/hosts/${ME.machineId}`) return { data: agents.map(agent => ({ tabId: TAB, agent, lead: true, leadsConversationId: null, observers: [] })) }+ if (path === `/api/super-tabs/hosts/${ME.machineId}/pools` || path === `/api/super-tabs/hosts/${ME.machineId}/assignments`) return { data: [] }+ if (path === `/api/super-tabs/${TAB}/route-decisions/d-1`) return { data: decision }+ if (path.startsWith(`/api/super-tabs/${TAB}/starts/`)) {+ const start = starts.get(path.split('/').at(-1)!)+ // The machine's host fails the queued start in preparation, the second time the Lead looks.+ if (start && start.read) start.error = 'The Harness GitHub App token is not in the form GitHub gives.'+ if (start) start.read = true+ return { data: start }+ }+ if (path === `/api/super-tabs/${TAB}/commands`) {+ const command = body.command+ commands.push(body)+ if (command.type === 'agent.start') {+ const startId = `start-${body.operationId}`+ starts.set(startId, { id: startId, creationId: `super-${startId}`, poolGeneration: 'pool', routeDecisionId: command.routeDecisionId,+ request: command.request, dispatched: false, harnessId: null, error: null })+ return { data: { result: { startId } } }+ }+ if (command.type === 'agent.startFailed') starts.get(String(command.startId))!.error = command.error+ return { data: { result: { messageId: body.operationId } } }+ }+ throw new Error(`Unexpected request ${method} ${raw}`)+ })+ const where = { port: d.port, dataDir: d.dataDir, machineId: ME.machineId, harnessPane: true }+ let answer: Record<string, any> = {}+ const code = await superTabCommand(['--tab', TAB, '--agent', leadId, 'start', 'first-start', JSON.stringify({ conversationId: 'g1',+ machineId: ME.machineId, engine: 'claude', model: 'opus', effort: 'high', name: 'Builder', cwd, worktree: false,+ requirements: { memoryBytes: 0, diskBytes: 1, maxCpuPercent: 100, tools: [], devices: [], quotaRequired: false }, routeDecisionId: 'd-1' })],+ { where: () => where, print: text => { answer = JSON.parse(text) } })+ expect(answer, JSON.stringify(answer)).toMatchObject({ error: 'START_BLOCKED', startId: 'start-first-start' })+ expect(code).not.toBe(0)+ const notices = commands.filter(c => c.command.type === 'message.send')+ expect(notices).toHaveLength(1)+ expect(notices[0]!.command).toMatchObject({ conversationId: 'g1', mentions: ['person-1'], mentionsIfNoWorker: true, recipientIds: [],+ text: 'Builder could not start on Fixture Mac, and no other machine allowed for this task could take it. This task has no worker. '+ + 'Fix that machine or add another one, then ask the Lead to start it again.' })+ // Nothing but the notice and the failed start went to the backend for it: no second start.+ expect(commands.filter(c => c.command.type === 'agent.start')).toHaveLength(1)+})diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex a900e8219..b1a75f7d1 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -62,7 +62,7 @@ const HELP = {release: 'When a Builder finishes, decide reuse, keep or stop; prefer stop unless more work is coming soon. Reuse assigns new work; agent.release records keep or requests stop. Wait for the execution host to confirm a stop. A person can withdraw a stuck stop; the session cannot receive new work in that Swarm. Its native capacity stays reserved until its host confirms stopping. Other Swarms wait up to two minutes for an in-flight close, then may reuse it.',resume: 'resume START_ID: finish a pending start without creating another agent.',// Buddies (backend superTabs/buddies.ts): a person adds and removes their own; the Buddy proposes only when they ask.- buddies: 'Buddies, in every Swarm: each person has a Buddy chat per project that only they and their Buddy read (buddy.chat with projectId opens it before any Buddy), may add their own Buddy there (buddy.create with projectId, machineId of a Swarm machine, engine claude or codex) and remove it (buddy.remove with projectId). It brainstorms with them in that chat, and the PM\'s private lines to them land there too. propose OPERATION_ID JSON [--attach PATH]...: a Buddy only, when its owner asks: {"conversationId":"its chat","ownerMessageId":"their message asking","goal":"...","scope":"...","priority":"low|normal|high","attachmentIds":["a file its owner sent in its chat"]}. --attach adds a file inside its own folder; up to 5 files in all, 10 MB each. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',+ buddies: 'Buddies, in every Swarm: each person has a Buddy chat per project that only they and their Buddy read (buddy.chat with projectId opens it before any Buddy), may add their own Buddy there (buddy.create with projectId, machineId of a Swarm machine, engine claude or codex), remove it (buddy.remove with projectId), and name it (buddy.rename with conversationId of their Buddy chat and name, or null for the default name). It brainstorms with them in that chat, and the PM\'s private lines to them land there too. propose OPERATION_ID JSON [--attach PATH]...: a Buddy only, when its owner asks: {"conversationId":"its chat","ownerMessageId":"their message asking","goal":"...","scope":"...","priority":"low|normal|high","attachmentIds":["a file its owner sent in its chat"]}. --attach adds a file inside its own folder; up to 5 files in all, 10 MB each. The Swarm posts it in the project chat to the PM, marked as on the owner\'s behalf. A Buddy is never assigned work.',// A person's own command, for the machines they added; an agent's terminal is refused (command.ts), so no agent raises its// own machine's room (Lead, 2026-10-28).setAgents: 'set-agents MACHINE_ID COUNT: for a machine\'s owner, from their own terminal, not an agent\'s: how many Swarm agents may run on that machine at once. Each agent still needs free memory when it starts. A machine may offer one agent for every 2 GB of its memory, and at least 4; a larger number is refused.',diff --git a/cli/src/superTabs/start.spec.ts b/cli/src/superTabs/start.spec.tsindex 91f5b2045..df3371a8c 100644--- a/cli/src/superTabs/start.spec.ts+++ b/cli/src/superTabs/start.spec.ts@@ -1204,13 +1204,13 @@ describe('a Lead\'s start that fails before its agent exists', () => {expect(b.commands.slice(before).map(c => c.operationId)).toEqual(b.commands.slice(before - 2, before).map(c => c.operationId))})- it('with no other machine, tells the group and its requester that the task has no worker, without the raw error', async () => {+ it('with no other machine, tells the group, and its requester only if the task still has no worker, without the raw error', async () => {const b = backend({ candidates: [candidate('c0', 'mac-one'), candidate('c1', 'mac-one', 'member')] })const result = await b.lead(b.first)expect(b.of('agent.start')).toHaveLength(1)const [notice] = b.of('message.send')- expect(notice).toMatchObject({ conversationId: 'group', mentions: ['person-1'], recipientIds: [],- text: 'Builder could not start on Mac One, and no other machine allowed for this task could take it. This task has no worker until that machine is fixed or another one is added.' })+ expect(notice).toMatchObject({ conversationId: 'group', mentions: ['person-1'], mentionsIfNoWorker: true, recipientIds: [],+ text: 'Builder could not start on Mac One, and no other machine allowed for this task could take it. This task has no worker. Fix that machine or add another one, then ask the Lead to start it again.' })expect(String(notice!.text)).not.toContain('token')expect(result).toMatchObject({ error: 'START_BLOCKED', startId: 'first-start', detail: expect.stringContaining(TOKEN) })})@@ -1221,7 +1221,7 @@ describe('a Lead\'s start that fails before its agent exists', () => {const b = backend({ candidates: [candidate('c0', 'mac-one')], error: reason })expect(await b.lead(b.first)).toMatchObject({ error: 'START_BLOCKED', detail: expect.stringContaining(reason) })expect(b.of('message.send')).toMatchObject([{ text: 'Builder could not start on Mac One: not enough free memory (1.8 GiB free, 2 GiB needed), '- + 'and no other machine allowed for this task could take it. This task has no worker until memory frees up on that machine or another one is added.' }])+ + 'and no other machine allowed for this task could take it. This task has no worker. Free up memory on that machine or add another one, then ask the Lead to start it again.' }])})it('reports instead of trying a third machine when the retry fails as well', async () => {@@ -1246,15 +1246,15 @@ describe('a Lead\'s start that fails before its agent exists', () => {expect(b.of('agent.start')).toHaveLength(1)})- const STAYS = 'Builder could not start. This task needs a particular machine or device, so it was not moved to another machine. It has no worker until a machine that has what it needs can start it.'- it('keeps a task that requires its machine or device where it is, and tells the group and its requester', async () => {+ const STAYS = 'Builder could not start. This task needs a particular machine or device, so it was not moved to another machine. It has no worker. Make a machine that has what it needs available, then ask the Lead to start it again.'+ it('keeps a task that requires its machine or device where it is, and tells the group, and its requester only if it still has no worker', async () => {// As each Lead reads it: a machine it sees, one it does not (only counted), a device.for (const requires of [{ machines: ['mac-one'] }, { machines: [], unseenMachines: 1 }, { devices: ['/dev/cu.round'] }]) {const b = backend({ requires })expect(await b.lead(b.first)).toMatchObject({ error: 'START_BLOCKED', startId: 'first-start', detail: expect.stringContaining(TOKEN) })expect(b.of('route.record')).toEqual([])expect(b.of('agent.start')).toHaveLength(1)- expect(b.of('message.send')).toMatchObject([{ conversationId: 'group', mentions: ['person-1'], recipientIds: [], text: STAYS }])+ expect(b.of('message.send')).toMatchObject([{ conversationId: 'group', mentions: ['person-1'], mentionsIfNoWorker: true, recipientIds: [], text: STAYS }])// A group reader may not see the machine (backend model.ts withSeenRequirement): the post names none, nor the raw error.for (const hidden of ['mac-one', 'Mac One', TOKEN, 'token']) expect(String(b.of('message.send')[0]!.text)).not.toContain(hidden)}diff --git a/cli/src/superTabs/start.ts b/cli/src/superTabs/start.tsindex 8ec409f44..37dfdb73a 100644--- a/cli/src/superTabs/start.ts+++ b/cli/src/superTabs/start.ts@@ -159,21 +159,24 @@ async function startElsewhere(input: Json, failed: Json, scoped: ScopedRequest,const machineName = (id: unknown) => text(machines.find(m => m.machineId === id)?.name) ?? 'its machine'const blocked = async (on: Json, required = false): Promise<Json> => {const requester = identifier(group?.requesterId) ? [group.requesterId] : []+ // This Lead is told by the result below and usually starts the task again within minutes. The requester is tagged only if+ // the task still has no worker after a while and the Lead has done nothing for it (backend mentions.ts): tagged at once,+ // Dee got two notices he could not act on for a task that had a worker soon after (2026-10-29).// People read why in the failure row the backend wrote; this one says only what it means, never the raw error. A task's// requirement names no machine at all: the one it failed on is a required one, which a reader may not see (backend// model.ts TaskRequirement; review of #1847). A memory shortage is named, with only the numbers members see in the Machines// view: "until that machine is fixed" sent people looking for a fault on Ken's MacBook Pro (2026-10-28).const short = memoryShortIn(on.error)requireSuccess(await scoped({ action: 'command', operationId: derived('start-blocked', String(on.id)), command: { type: 'message.send',- conversationId: request.conversationId, replyTo: null, recipientIds: [], ...(requester.length ? { mentions: requester } : {}),+ conversationId: request.conversationId, replyTo: null, recipientIds: [], ...(requester.length ? { mentions: requester, mentionsIfNoWorker: true } : {}),text: required? `${String(request.name)} could not start. This task needs a particular machine or device, so it was not moved to another machine. `- + 'It has no worker until a machine that has what it needs can start it.'+ + 'It has no worker. Make a machine that has what it needs available, then ask the Lead to start it again.': short? `${String(request.name)} could not start on ${machineName(object(on.request).machineId)}: not enough free memory (${short.free} free, ${short.needed} needed), `- + 'and no other machine allowed for this task could take it. This task has no worker until memory frees up on that machine or another one is added.'+ + 'and no other machine allowed for this task could take it. This task has no worker. Free up memory on that machine or add another one, then ask the Lead to start it again.': `${String(request.name)} could not start on ${machineName(object(on.request).machineId)}, and no other machine allowed for this task could take it. `- + 'This task has no worker until that machine is fixed or another one is added.' } }))+ + 'This task has no worker. Fix that machine or add another one, then ask the Lead to start it again.' } }))return { error: 'START_BLOCKED', startId: on.id, detail: `${String(on.error)} ${required? 'This task requires its machine or device, so it was not moved; the group was told.': 'No other machine allowed for this task could start it; the group was told.'}` }diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dartindex 8bda1d034..1690b2a29 100644--- a/desktop/lib/super_tabs/buddies.dart+++ b/desktop/lib/super_tabs/buddies.dart@@ -361,6 +361,134 @@ Future<void> confirmRemoveBuddy(if (remove == true) await c.removeBuddy(projectId);}+/// What the reader's Buddy is called until they name it, as the backend+/// names it: "ken's Buddy".+String buddyDefaultName(SuperTabController c) {+ final email = c.snapshot?.people+ .where((p) => p.id == c.accountId)+ .firstOrNull+ ?.email;+ return "${(email ?? '').split('@').first}'s Buddy";+}++/// Rename the reader's Buddy in [projectId] (mockup confirmed by Diego,+/// 10-29): the name everyone in the Swarm sees; empty goes back to+/// [buddyDefaultName]. The backend checks the name and says why it refuses.+Future<void> showRenameBuddy(+ BuildContext context,+ SuperTabController c,+ String projectId,+) => showAppDialog<void>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ projectId: projectId,+ child: _RenameBuddyDialog(controller: c, projectId: projectId),+ ),+);++class _RenameBuddyDialog extends StatefulWidget {+ const _RenameBuddyDialog({required this.controller, required this.projectId});+ final SuperTabController controller;+ final String projectId;++ @override+ State<_RenameBuddyDialog> createState() => _RenameBuddyDialogState();+}++class _RenameBuddyDialogState extends State<_RenameBuddyDialog> {+ SuperTabController get c => widget.controller;++ /// The backend's limit: a longer name is refused there anyway.+ static const _maxLength = 32;+ late final _name = TextEditingController(+ text: c.buddyChat(widget.projectId)?.buddyName ?? '',+ );+ bool _busy = false;+ String? _error;++ @override+ void dispose() {+ _name.dispose();+ super.dispose();+ }++ Future<void> _submit() async {+ if (_busy) return;+ setState(() {+ _busy = true;+ _error = null;+ });+ final renamed = await c.renameBuddy(widget.projectId, _name.text);+ if (!mounted) return;+ if (renamed) {+ Navigator.pop(context);+ return;+ }+ setState(() {+ _busy = false;+ _error = c.operationError ?? 'Could not rename the Buddy. Try again.';+ });+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final fallback = buddyDefaultName(c);+ return AlertDialog(+ title: const Text('Rename your Buddy'),+ content: SizedBox(+ width: 440,+ // Scrolls in a short window or at large text, as Add a Buddy does.+ child: SingleChildScrollView(+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(+ 'Everyone in this Swarm sees this name.',+ style: DesktopChrome.text(),+ ),+ const SizedBox(height: 12),+ TextField(+ key: const ValueKey('super-buddy-name'),+ controller: _name,+ autofocus: true,+ enabled: !_busy,+ maxLength: _maxLength,+ decoration: InputDecoration(+ hintText: fallback,+ counterText: '',+ ),+ onSubmitted: (_) => _submit(),+ ),+ const SizedBox(height: 4),+ Text(+ 'Leave it empty to go back to "$fallback".',+ style: DesktopChrome.control(color: DesktopChrome.muted),+ ),+ if (_error case final error?) ...[+ const SizedBox(height: 12),+ Text(error, style: DesktopChrome.control()),+ ],+ ],+ ),+ ),+ ),+ actions: [+ TextButton(+ onPressed: _busy ? null : () => Navigator.pop(context),+ child: const Text('Cancel'),+ ),+ FilledButton(+ onPressed: _busy ? null : _submit,+ child: Text(_busy ? 'Saving…' : 'Save'),+ ),+ ],+ );+ }+}+/// Under a Buddy chat's header: what it runs on and who else can see its/// terminal, and, while it is down, a way to start it again. Before its/// agent is there, how its start is going (backend: the start carries thediff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 880d0cf2a..d18e7bc45 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -1,8 +1,10 @@import 'dart:async';import 'dart:collection';+import 'dart:convert';import 'dart:math';import 'package:clock/clock.dart';+import 'package:cryptography/dart.dart' show DartSha256;import 'package:dio/dio.dart' show CancelToken, DioException, DioExceptionType;import 'package:flutter/foundation.dart';@@ -37,6 +39,28 @@ String superTabOperationId() {).join();}+/// The id the backend gives the message a person sends with receipt+/// [operationId]: `stableId(state.id, actorKey(actor), operationId)`, the+/// first 24 hex of sha256 over the JSON of those parts (backend+/// superTabs/commands.ts `message.send`, model.ts `stableId`).+String superTabMessageId({+ required String tabId,+ required String accountId,+ required String operationId,+}) => const DartSha256()+ .hashSync(+ utf8.encode(jsonEncode([tabId, 'person:$accountId', operationId])),+ )+ .bytes+ .map((b) => b.toRadixString(16).padLeft(2, '0'))+ .join()+ .substring(0, 24);++/// Saved for a text still queued when the window closed. Older versions read+/// and show it; this one knows it by [_unsentKey] and shows Not sent alone.+const _unsentReason = 'Not sent before this window closed.';+const _unsentKey = 'unsent';+class SuperTabFailure implements Exception {const SuperTabFailure(this.code, this.message, {this.statusCode = 0});final String code, message;@@ -51,6 +75,9 @@ enum SuperTabOutgoingState {/// On its way, or accepted and not read back yet.sending,+ /// Accepted by the server, while its transcript refresh is still pending.+ confirmed,+/// Sent with no answer: it may or may not have arrived. Retry checks and/// sends it once.unconfirmed,@@ -67,6 +94,12 @@ typedef _Refused = ({String error,});+typedef _QueuedSend = ({+ String operationId,+ Map<String, dynamic> command,+ Completer<Map<String, dynamic>?> result,+});+/// A message the reader sent that the transcript does not hold yet.class SuperTabOutgoing {const SuperTabOutgoing({@@ -78,6 +111,7 @@ class SuperTabOutgoing {this.thread,this.alsoSend = false,this.error,+ this.confirmedAt,});final String conversationId, text;@@ -95,6 +129,7 @@ class SuperTabOutgoing {/// Why it was refused, as the backend said it.final String? error;+ final String? confirmedAt;}/// Personal navigation/drafts live on this client. Membership, work and messages@@ -127,6 +162,8 @@ class SuperTabController extends ChangeNotifier {SuperTabReading reading = const SuperTabReading(),}) : _policy = reading {if (initial['tabId'] == tabId && initial['accountId'] == accountId) {+ final order = initial['sendOrder'];+ if (order is List) _sendOrder.addAll(order.whereType<String>());_savedSelection = initial['selectedId'] is String;expandedProjects.addAll((initial['expandedProjects'] as List? ?? const []).whereType<String>(),@@ -201,7 +238,7 @@ class SuperTabController extends ChangeNotifier {in superTabMap(row['mentions']).entries)if (token is String) agent: token,},- error: row['error'] as String,+ error: row[_unsentKey] == true ? '' : row['error'] as String,),];if (kept.isNotEmpty) _refused[key] = kept;@@ -525,9 +562,57 @@ class SuperTabController extends ChangeNotifier {int stateReads = 0;Future<void> _persisting = Future.value();Map<String, dynamic>? _pending;+ final _queuedSends = <_QueuedSend>[];+ bool _drainingSends = false;++ /// Who holds [saving] now: a send gives it up at its answer, so the next+ /// one may take it while the first still reads.+ Object? _lane;+ final _sendAcknowledgements = <String, Completer<void>>{};+ final _sendOrder = <String>[];++ /// Text can queue behind another text send; other actions and attachments+ /// retain their existing single-action flow.+ bool get canQueueText =>+ !_disposed &&+ canWrite &&+ !uploading &&+ (_pending == null ||+ (saving && pendingCommand?['type'] == 'message.send'));/// Sends the backend took, by message id, until the transcript holds them.final _sent = <String, Map<String, dynamic>>{};+ final _sendIdentities =+ <String, ({String operationId, String conversationId})>{};++ /// A local row keeps its identity even if the service assigns a different id.+ String messageIdentity(String id) =>+ _sendIdentities[id]?.operationId ?? _onTheirWay[id] ?? id;++ /// The messages on their way, by the id the backend gives each, so one a+ /// read brings before its answer is the same message (and the same row).+ Map<String, String> get _onTheirWay {+ final receipts = [+ if (pendingCommand?['type'] == 'message.send')+ _pending!['operationId'] as String,+ for (final queued in _queuedSends) queued.operationId,+ ];+ if (!listEquals(receipts, _onTheirWayFor)) {+ _onTheirWayFor = receipts;+ _onTheirWayIds = {+ for (final receipt in receipts) _messageIdOf(receipt): receipt,+ };+ }+ return _onTheirWayIds;+ }++ List<String> _onTheirWayFor = const [];+ Map<String, String> _onTheirWayIds = const {};+ String _messageIdOf(String receipt) => superTabMessageId(+ tabId: tabId,+ accountId: accountId,+ operationId: receipt,+ );/// The tags of each message on its way, by operation id, for a refusal to/// give back.@@ -1743,7 +1828,15 @@ class SuperTabController extends ChangeNotifier {_quoting.clear();_forgetThreads();_sent.clear();+ _sendIdentities.clear();+ _pending = null;+ _sendingMentions.clear();_refused.clear();+ _sendOrder.clear();+ for (final queued in _queuedSends) {+ queued.result.complete(null);+ }+ _queuedSends.clear();_poll?.cancel();_changed();}@@ -1773,22 +1866,46 @@ class SuperTabController extends ChangeNotifier {_threadSeen.entries.skip(max(0, _threadSeen.length - 500)),),if (_pending != null) 'pending': _pending,- if (_refused.isNotEmpty)+ if (_sendOrder.isNotEmpty) 'sendOrder': List<String>.of(_sendOrder),+ if (_refused.isNotEmpty || _queuedSends.isNotEmpty)'refused': {- for (final MapEntry(:key, :value) in _refused.entries)+ for (final key in {+ ..._refused.keys,+ ..._queuedSends.map((q) => q.command['conversationId'] as String),+ })key: [- for (final refused in value)+ for (final refused in _refused[key] ?? const <_Refused>[]){'operationId': refused.operationId,'command': refused.command,'mentions': refused.mentions,- 'error': refused.error,+ 'error': refused.error.isEmpty ? _unsentReason : refused.error,+ if (refused.error.isEmpty) _unsentKey: true,},+ // Persist unsent queue entries in the existing recovery format:+ // older clients also retain their text and require explicit Retry.+ for (final queued in _queuedSends)+ if (queued.command['conversationId'] == key)+ {+ 'operationId': queued.operationId,+ 'command': queued.command,+ 'mentions': _sendingMentions[queued.operationId] ?? const {},+ 'error': _unsentReason,+ _unsentKey: true,+ },],},};Future<void> _persist() {+ final active = {+ if (_pending != null) _pending!['operationId'],+ ..._sent.keys,+ for (final refused in _refused.values)+ ...refused.map((r) => r.operationId),+ ..._queuedSends.map((q) => q.operationId),+ };+ _sendOrder.removeWhere((id) => !active.contains(id));// Serial writes prevent an older autosave from restoring a resolved receipt.final next = _persisting.catchError((Object _) {})@@ -1834,6 +1951,9 @@ class SuperTabController extends ChangeNotifier {/// hold yet, oldest first.List<SuperTabOutgoing> outgoing(String id) {final held = {for (final m in _messages[id] ?? const []) m.id};+ // The receipts of what is on its way that a read already brought.+ final onTheirWay = _onTheirWay;+ final arrived = {for (final messageId in held) ?onTheirWay[messageId]};SuperTabOutgoing of(Map<String, dynamic> command,SuperTabOutgoingState state, {@@ -1848,27 +1968,33 @@ class SuperTabController extends ChangeNotifier {state: state,operationId: operationId,error: error,+ confirmedAt: command['confirmedAt'] as String?,);final pending = _pending,command = pending == null? const <String, dynamic>{}: superTabMap(pending['command']);- return [+ final rows = <SuperTabOutgoing>[for (final refused in _refused[id] ?? const <_Refused>[])of(refused.command,SuperTabOutgoingState.refused,operationId: refused.operationId,- error: refused.error,+ // Left unsent at close: Not sent says it all.+ error: refused.error.isEmpty ? null : refused.error,),for (final MapEntry(key: messageId, value: sent) in _sent.entries)if (sent['conversationId'] == id && !held.contains(messageId))- of(sent, SuperTabOutgoingState.sending),- // The backend names a person's message by its send's operation id, so- // one read back while its answer was lost is not shown twice.+ of(+ sent,+ SuperTabOutgoingState.confirmed,+ operationId: messageIdentity(messageId),+ ),+ // The backend names a person's message by a hash of its send's+ // receipt, so one read back before its answer is not shown twice.if (command['type'] == 'message.send' &&command['conversationId'] == id &&- !held.contains(pending!['operationId']))+ !arrived.contains(pending!['operationId']))of(command,saving@@ -1876,7 +2002,19 @@ class SuperTabController extends ChangeNotifier {: SuperTabOutgoingState.unconfirmed,operationId: pending['operationId'] as String?,),+ for (final queued in _queuedSends)+ if (queued.command['conversationId'] == id &&+ !arrived.contains(queued.operationId))+ of(+ queued.command,+ SuperTabOutgoingState.sending,+ operationId: queued.operationId,+ ),];+ int order(SuperTabOutgoing row) =>+ _sendOrder.indexOf(row.operationId ?? '');+ rows.sort((a, b) => order(a).compareTo(order(b)));+ return rows;}/// Sends failed [message] again: one with no answer under its own receipt@@ -1910,6 +2048,7 @@ class SuperTabController extends ChangeNotifier {_sendingMentions.remove(_pending!['operationId']);_pending = null;}+ _sendOrder.remove(message.operationId);operationError = null;operationErrorCode = null;unawaited(@@ -2039,6 +2178,21 @@ class SuperTabController extends ChangeNotifier {Future<bool> removeBuddy(String projectId) async =>await command({'type': 'buddy.remove', 'projectId': projectId}) != null;+ /// Names the reader's Buddy in [projectId] from its chat, or clears the+ /// name for the default when [name] is empty. Everyone in the Swarm sees it.+ /// False when refused: [operationError] says why.+ Future<bool> renameBuddy(String projectId, String name) async {+ final chat = buddyChat(projectId);+ if (chat == null) return false;+ final trimmed = name.trim();+ return await command({+ 'type': 'buddy.rename',+ 'conversationId': chat.id,+ 'name': trimmed.isEmpty ? null : trimmed,+ }) !=+ null;+ }+/// Whether [group] is out of the app: there is no private channel to the/// PM (Ken, 10-29), so no private chat but a Buddy chat is listed or opened,/// the reader's old Chat with PM that an older server still sends included.@@ -3120,6 +3274,7 @@ class SuperTabController extends ChangeNotifier {return null;}saving = true;+ final lane = _lane = Object();operationError = null;operationErrorCode = null;operationNotice = null;@@ -3127,9 +3282,9 @@ class SuperTabController extends ChangeNotifier {try {// The receipt ID reaches durable local storage before the request can reach the server.await _persist();- if (_disposed) return null;+ if (_disposed || accessRevoked) return null;final answer = await request('POST', '$_path/commands', body: pending);- if (_disposed) return null;+ if (_disposed || accessRevoked) return null;final result = superTabMap(answer['result']);final command = superTabMap(pending['command']);final notice = result['credentialNotice'];@@ -3137,11 +3292,18 @@ class SuperTabController extends ChangeNotifier {if (command['type'] == 'message.send') {final id = command['conversationId'] as String;_sendingMentions.remove(pending['operationId']);- // Shown as sending until the transcript holds it, so it never leaves+ // Kept confirmed until the transcript holds it, so it never leaves// the chat between the answer and the read that brings it.- _sent[result['messageId'] as String? ??- pending['operationId'] as String] =- command;+ final messageId =+ result['messageId'] as String? ?? pending['operationId'] as String;+ _sendIdentities[messageId] = (+ operationId: pending['operationId'] as String,+ conversationId: id,+ );+ _sent[messageId] = {+ ...command,+ 'confirmedAt': clock.now().toUtc().toIso8601String(),+ };if (_drafts[id]?.trim() == command['text']) {_drafts.remove(id);_mentions.remove(id);@@ -3167,17 +3329,25 @@ class SuperTabController extends ChangeNotifier {_moveView(to: result['conversationId'] as String);}_pending = null;+ _changed();try {await _persist();} catch (_) {_pending = pending;rethrow;}+ if (command['type'] == 'message.send') {+ // A refresh is read-only work. It must not hold the send lane after+ // the command and its durable receipt have both been confirmed.+ _release(lane);+ _sendAcknowledgements[pending['operationId']]?.complete();+ _changed();+ }// What the command wrote is in the next change read.await refresh();return result;} catch (failure) {- if (!_disposed && _isUpdateRequired(failure)) {+ if (!_disposed && !accessRevoked && _isUpdateRequired(failure)) {_requireUpdate();_failOperation(updateMessage,@@ -3192,7 +3362,7 @@ class SuperTabController extends ChangeNotifier {} catch (_) {_pending = pending;}- } else if (!_disposed) {+ } else if (!_disposed && !accessRevoked) {_failOperation(failure is SuperTabFailure? failure.message@@ -3225,11 +3395,52 @@ class SuperTabController extends ChangeNotifier {}return null;} finally {- saving = false;+ _release(lane);_changed();+ if (_pending == null) {+ unawaited(_drainSends());+ } else if (identical(_pending, pending) &&+ !_drainingSends &&+ !_disposed &&+ !accessRevoked &&+ _queuedSends.isNotEmpty) {+ // A send the queue did not start (a file, a Retry) ended unsure: what+ // waits behind it is kept to send again, as the queue's own does.+ _refuseQueued();+ unawaited(+ _persist().catchError((Object _) {+ error = 'Could not save these messages on this computer.';+ _changed();+ }),+ );+ }}}+ static String _excerpt(String text) {+ final line = text.trim().replaceAll(RegExp(r'\s+'), ' ');+ return line.length <= 80 ? line : '${line.substring(0, 79)}…';+ }++ /// Gives up [saving] if [lane] still holds it.+ void _release(Object lane) {+ if (!identical(_lane, lane)) return;+ _lane = null;+ saving = false;+ }++ /// Keeps every queued text for Retry: an earlier one needs confirmation.+ void _refuseQueued() {+ for (final queued in _queuedSends) {+ _refuse({+ 'operationId': queued.operationId,+ 'command': queued.command,+ }, 'An earlier message needs confirmation.');+ if (!queued.result.isCompleted) queued.result.complete(null);+ }+ _queuedSends.clear();+ }+/// Keeps a refused [pending] message, with its tags, for Retry.void _refuse(Map<String, dynamic> pending, String error) {final command = superTabMap(pending['command']);@@ -3259,6 +3470,15 @@ class SuperTabController extends ChangeNotifier {void _dropShownSends(String id) {final held = {for (final m in _messages[id] ?? const []) m.id};_sent.removeWhere((messageId, _) => held.contains(messageId));+ _sendOrder.removeWhere(+ (operationId) => held.any((id) => messageIdentity(id) == operationId),+ );+ _sendIdentities.removeWhere(+ (messageId, identity) =>+ identity.conversationId == id &&+ !held.contains(messageId) &&+ !_sent.containsKey(messageId),+ );}bool _maySend(Map<String, dynamic> command) =>@@ -3282,8 +3502,7 @@ class SuperTabController extends ChangeNotifier {selected!.archived ||!canWrite ||uploading ||- saving ||- _pending != null) {+ ((saving || _pending != null) && (files.isNotEmpty || !canQueueText))) {return null;}// A tag the text still says: an agent's is a recipient, a person's a tag.@@ -3304,6 +3523,32 @@ class SuperTabController extends ChangeNotifier {return null;}final conversationId = selectedId;+ if (files.isEmpty) {+ final operationId = superTabOperationId();+ _sendOrder.add(operationId);+ final result = Completer<Map<String, dynamic>?>();+ _sendingMentions[operationId] = Map.of(+ _mentions[conversationId] ?? const {},+ );+ _queuedSends.add((+ operationId: operationId,+ command: {+ 'type': 'message.send',+ 'conversationId': conversationId,+ 'text': text,+ 'replyTo': replyTo,+ 'recipientIds': addressed,+ if (tagged.isNotEmpty) 'mentions': tagged,+ },+ result: result,+ ));+ _drafts.remove(conversationId);+ _mentions.remove(conversationId);+ onSending?.call();+ _changed();+ unawaited(_drainSends());+ return result.future;+ }final ids = await _uploadAll(conversationId,attachments(conversationId),@@ -3312,7 +3557,10 @@ class SuperTabController extends ChangeNotifier {if (ids == null) return null;final before = _pending;final tags = Map<String, String>.of(_mentions[conversationId] ?? const {});- final sending = command({+ // In the order it was sent, as text is.+ final operationId = superTabOperationId();+ _sendOrder.add(operationId);+ final sending = command(operationId: operationId, {'type': 'message.send','conversationId': conversationId,'text': text,@@ -3347,6 +3595,76 @@ class SuperTabController extends ChangeNotifier {}}+ Future<void> _drainSends() async {+ if (_drainingSends || saving || _pending != null || _disposed) return;+ _drainingSends = true;+ final gone = <String>[];+ try {+ while (_queuedSends.isNotEmpty && !_disposed && !accessRevoked) {+ final queued = _queuedSends.removeAt(0);+ final id = queued.command['conversationId'] as String;+ final group = snapshot?.conversation(id);+ if (group == null && canWrite) {+ // Its conversation is gone: no chat can show it, so it is dropped+ // and the sender told.+ _sendingMentions.remove(queued.operationId);+ _sendOrder.remove(queued.operationId);+ gone.add(queued.command['text'] as String? ?? '');+ queued.result.complete(null);+ await _persist();+ } else if (canWrite && group != null && !group.archived) {+ _pending = {+ 'operationId': queued.operationId,+ 'command': queued.command,+ };+ final advance = Completer<void>();+ _sendAcknowledgements[queued.operationId] = advance;+ unawaited(+ retry().then((result) {+ if (!queued.result.isCompleted) queued.result.complete(result);+ if (!advance.isCompleted) advance.complete();+ _sendAcknowledgements.remove(queued.operationId);+ }),+ );+ await advance.future;+ } else {+ _refuse({+ 'operationId': queued.operationId,+ 'command': queued.command,+ }, 'This conversation is no longer writable.');+ queued.result.complete(null);+ await _persist();+ }+ if (_pending != null) break;+ }+ if (gone.isNotEmpty && !_disposed && !accessRevoked) {+ operationNotice = gone.length == 1+ ? 'Not sent: “${_excerpt(gone.single)}”. Its conversation is no longer available.'+ : 'Not sent: ${gone.length} messages. Their conversation is no longer available.';+ }+ // An uncertain send keeps its receipt for Retry. Later messages have+ // not reached the server and remain explicitly retryable, not lost.+ if (!_disposed && !accessRevoked && _queuedSends.isNotEmpty) {+ _refuseQueued();+ await _persist();+ }+ } catch (_) {+ // The queue remains in the recovery state when a local write fails.+ error = 'Could not save these messages on this computer.';+ for (final queued in _queuedSends) {+ _refuse({+ 'operationId': queued.operationId,+ 'command': queued.command,+ }, 'Could not save this message on this computer.');+ if (!queued.result.isCompleted) queued.result.complete(null);+ }+ _queuedSends.clear();+ } finally {+ _drainingSends = false;+ _changed();+ }+ }+/// Uploads each of [files] that has not gone up yet and returns their ids,/// or null with [operationError] set when one could not. The draft and the/// files stay where they are.@@ -3465,6 +3783,10 @@ class SuperTabController extends ChangeNotifier {@overridevoid dispose() {_disposed = true;+ for (final queued in _queuedSends) {+ queued.result.complete(null);+ }+ _queuedSends.clear();_serverMarks.dispose();_poll?.cancel();_toldRead?.cancel();diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dartindex ecda57464..34d1e6838 100644--- a/desktop/lib/super_tabs/message_receipt.dart+++ b/desktop/lib/super_tabs/message_receipt.dart@@ -304,8 +304,21 @@ class SuperTabOutgoingReceipt extends StatelessWidget {required this.message,required this.onDelete,this.onRetry,+ this.inline = false,});final SuperTabOutgoing message;+ final bool inline;++ Widget _line(List<Widget> parts) => inline+ ? Semantics(+ liveRegion: true,+ child: Wrap(+ spacing: grid.AppDesktop.controlGap,+ crossAxisAlignment: WrapCrossAlignment.center,+ children: parts,+ ),+ )+ : _receiptLine(parts);/// Null while it cannot be done now, as during another send.final VoidCallback? onRetry;@@ -315,15 +328,15 @@ class SuperTabOutgoingReceipt extends StatelessWidget {Widget build(BuildContext context) {if (message.state == SuperTabOutgoingState.sending) {final style = superTabReceiptStyle(DesktopChrome.muted);- return _receiptLine([- _sendingMark(context, DesktopChrome.muted),+ return _line([+ if (!inline) _sendingMark(context, DesktopChrome.muted),Text('Sending…', style: style),]);}final color = Theme.of(context).colorScheme.error;final style = superTabReceiptStyle(color);final refused = message.state == SuperTabOutgoingState.refused;- return _receiptLine([+ return _line([Icon(AppIcons.triangleAlert, size: 14, color: color),Text('Not sent', style: style),if (refused && message.error != null) ...[diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex 4bc07440d..b0a85cf65 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -46,6 +46,8 @@ class SuperTabMessageRow extends StatefulWidget {this.reactorName,this.onReact,this.proposalOwner,+ this.headerStatus,+ this.dimmed = false,this.thread,this.threadUnread = false,this.onOpenThread,@@ -95,6 +97,10 @@ class SuperTabMessageRow extends StatefulWidget {final ValueChanged<BuildContext>? onOpenReply;final VoidCallback onReturnToComposer;final List<Widget> receipts;+ final Widget? headerStatus;++ /// Its text and files are faint while it sends; its status line is not.+ final bool dimmed;/// The reader, whose own reactions are marked; [reactorName] names the/// others. Without [onReact] the counts only show.@@ -353,7 +359,11 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {size: 14,),),- if (message.createdAt case final time?)+ if (widget.headerStatus+ case final status?)+ status+ else if (message.createdAt+ case final time?)Tooltip(message: MaterialLocalizations.of(context,@@ -442,24 +452,30 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),),if (message.text.isNotEmpty)- ConstrainedBox(- constraints: const BoxConstraints(- maxWidth: 960,- ),- child: SuperTabMessageText(- message.text,- references: widget.references,- onOpenGroup: widget.onOpenGroup,- mentions: widget.mentions,+ Opacity(+ opacity: widget.dimmed ? 0.6 : 1,+ child: ConstrainedBox(+ constraints: const BoxConstraints(+ maxWidth: 960,+ ),+ child: SuperTabMessageText(+ message.text,+ references: widget.references,+ onOpenGroup: widget.onOpenGroup,+ mentions: widget.mentions,+ ),),),if (message.attachments.isNotEmpty)- Padding(- padding: EdgeInsets.only(- top: message.text.isEmpty ? 0 : 8,- ),- child: SuperTabAttachments(- message.attachments,+ Opacity(+ opacity: widget.dimmed ? 0.6 : 1,+ child: Padding(+ padding: EdgeInsets.only(+ top: message.text.isEmpty ? 0 : 8,+ ),+ child: SuperTabAttachments(+ message.attachments,+ ),),),widget.card ??diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex dd9500a43..79fce26c1 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -196,6 +196,7 @@ class SuperTabConversation {row['projectId'] as String? ?? (row['kind'] == 'leads' ? '' : 'lead'),kind = row['kind'] as String?,buddyOwnerId = row['buddyOwnerId'] as String?,+ buddyName = row['buddyName'] as String?,number = (row['number'] as num?)?.toInt(),title = _text(row, 'title'),leadId = row['leadId'] as String?,@@ -247,6 +248,10 @@ class SuperTabConversation {/// The person a Buddy chat belongs to; only they read it.final String? buddyOwnerId;++ /// The name a Buddy chat's person chose for their Buddy, kept while no+ /// Buddy runs; null for the default (backend buddies.ts renameBuddy).+ final String? buddyName;final SuperTabTask? task;final int? number;String get label => number == null ? title : '#$number $title';diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 78d7b6896..91bb59a42 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -578,10 +578,11 @@ class ProjectSidebar extends StatelessWidget {final project = reading.project;final chat = reading.buddyChat;final agent = controller.buddy(project.id);- // With no Buddy running it reads as plain "Buddy" (its chat's title names- // the owner, which the reader is).+ // With no Buddy running it reads as the name the reader chose for it, or+ // plain "Buddy" (its chat's default title names the owner, which the+ // reader is): one name everywhere is the point of renaming (Lead, 10-29).final name = agent == null- ? 'Buddy'+ ? chat?.buddyName ?? 'Buddy': snapshot.agentName(agent.id, fallback: agent.name);return SuperTabBuddyRow(key: ValueKey('super-buddy-${project.id}'),diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 370323e0e..a8a5ba177 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -325,8 +325,10 @@ class _SuperTabViewState extends State<SuperTabView>_unread.forget(_selected);_scrollRequest++;_jumpingToEnd = false;- // A search or a way back belongs to the conversation it started in.- _jumpRequest++;+ // A search or a way back belongs to the conversation it started in. The+ // first conversation shown ends nothing: a tag opened as the view+ // appears is still being found while it is adopted.+ if (_selected != null) _jumpRequest++;_finding = null;_back = null;if (_anchors.remove(id) case final anchor?) {@@ -629,9 +631,9 @@ class _SuperTabViewState extends State<SuperTabView>if (!c.canWrite ||c.selected == null ||c.selected!.archived ||- c.saving ||c.uploading ||- c.hasPendingAction ||+ ((c.saving || c.hasPendingAction) &&+ (!_files.isEmpty || !c.canQueueText)) ||(_composer.text.trim().isEmpty && _files.isEmpty)) {return;}@@ -1552,9 +1554,19 @@ class _SuperTabViewState extends State<SuperTabView>/// list stays.Future<void> _openMention(SuperTabMention mention) async {final id = mention.conversationId;- if (c.snapshot?.conversation(id) == null) return;+ final request = ++_jumpRequest;+ // A closed or quiet conversation is asked for by id, as a message link does: the tag of a task with no worker is in one,+ // and a row that did nothing left the reader not knowing why it was there.+ final readable =+ c.snapshot?.conversation(id) != null || await c.loadGroup(id);+ if (!mounted || request != _jumpRequest || c.accessRevoked) return;+ if (!readable || c.snapshot?.conversation(id) == null) {+ ScaffoldMessenger.maybeOf(context)+ ?.showSnackBar(const SnackBar(content: Text('Message unavailable')));+ return;+ }final message = await _findMessage(id, mention.messageId);- if (!mounted) return;+ if (!mounted || request != _jumpRequest) return;if (message == null) {ScaffoldMessenger.maybeOf(context)?.showSnackBar(SnackBar(@@ -1806,14 +1818,14 @@ class _SuperTabViewState extends State<SuperTabView>bool _isBuddyChat(SuperTabConversation group) =>c.buddyChat(group.projectId)?.id == group.id;- /// The name of the reader's Buddy that [group] is the chat with, or- /// "your Buddy" while it has none (removed, or starting). Null when [group]- /// is no Buddy chat of the reader's.+ /// The name of the reader's Buddy that [group] is the chat with: the name+ /// they chose while it has none (removed, or starting), else "your Buddy".+ /// Null when [group] is no Buddy chat of the reader's.String? _buddyName(SuperTabConversation? group) {if (group == null || !_isBuddyChat(group)) return null;final agent = c.buddy(group.projectId);return agent == null- ? 'your Buddy'+ ? group.buddyName ?? 'your Buddy': c.snapshot!.agentName(agent.id, fallback: agent.name);}@@ -1836,7 +1848,7 @@ class _SuperTabViewState extends State<SuperTabView>? '# $kProductManagersChannel': _buddyName(group) == null? null- : c.buddy(group.projectId) == null+ : c.buddy(group.projectId) == null && group.buddyName == null? 'Your Buddy': '${_buddyName(group)} · Your Buddy';if (name == null) return SuperTabWorkgroupName(group!, style: style);@@ -2118,9 +2130,14 @@ class _SuperTabViewState extends State<SuperTabView>if (editable && project?.ownerId == c.accountId)item('Delete Project', () => _groupAction('delete', group)),] else if (_isBuddyChat(group)) ...[- // A Buddy chat is the reader's own: the Buddy itself to remove.- // Nothing to rename or archive, and no way to a Chat with PM (Ken,- // 10-28).+ // A Buddy chat is the reader's own: the Buddy itself to name, any+ // time, and to remove. Nothing to archive, and no way to a Chat with+ // PM (Ken, 10-28).+ if (editable)+ item(+ 'Rename Buddy…',+ () => unawaited(showRenameBuddy(context, c, group.projectId)),+ ),if (editable && c.buddy(group.projectId) != null)item('Remove Buddy',@@ -2200,65 +2217,77 @@ class _SuperTabViewState extends State<SuperTabView>?.showSnackBar(SnackBar(content: Text(failure)));}- /// [sent], drawn as the reader's own message will be once the transcript- /// holds it, with where it stands under it.- Widget _outgoingRow(- SuperTabOutgoing sent,- List<SuperTabMessage> messages,- Map<String, SuperTabMessage> byId,- ) {+ SuperTabMessage _outgoingMessage(SuperTabOutgoing sent) {final id = sent.conversationId;final person = c.snapshot?.people.where((p) => p.id == c.accountId).firstOrNull;- final message = SuperTabMessage.fromJson({- 'id': 'outgoing',+ return SuperTabMessage.fromJson({+ 'id': sent.operationId ?? 'outgoing','conversationId': id,'text': sent.text,'replyTo': sent.replyTo,'sequence': 0,- 'createdAt': DateTime.now().toUtc().toIso8601String(),+ 'createdAt': sent.confirmedAt ?? DateTime.now().toUtc().toIso8601String(),+ // As the backend writes the sender (model.ts author()), so the row+ // groups the same before and after it is confirmed.'author': {'kind': 'person','id': c.accountId,'name': person?.email ?? '',+ 'membershipGeneration': ?person?.generation,},});+ }++ /// Uses the transcript's own row identity before and after acknowledgement.+ Widget _outgoingRow(+ SuperTabOutgoing sent,+ Map<String, SuperTabMessage> byId, {+ required bool grouped,+ }) {+ final message = _outgoingMessage(sent);+ final person = c.snapshot?.people+ .where((p) => p.id == c.accountId)+ .firstOrNull;final reply = byId[sent.replyTo];return KeyedSubtree(key: const ValueKey('super-outgoing'),child: SuperTabMessageRow(message: message,+ dimmed: sent.state == SuperTabOutgoingState.sending,author: _shownAuthor(c, message),proposalOwner: _proposalOwner(message),person: person,- grouped: SuperTabMessageRow.groupsWith(message, messages.lastOrNull),+ grouped: grouped,reply: reply,replyAuthor: reply == null ? null : _shownAuthor(c, reply),onReturnToComposer: _focus.requestFocus,readerId: c.accountId,- receipts: [- SuperTabOutgoingReceipt(- message: sent,- // A refused message goes again only when nothing else is on- // its way.- onRetry:- c.saving ||- (sent.state == SuperTabOutgoingState.refused &&- c.hasPendingAction)- ? null- : () {- unawaited(c.retryOutgoing(sent));- _focus.requestFocus();- },- // The click lands in the transcript; typing goes on in the- // composer, as after Reply.- onDelete: () {- c.discardOutgoing(sent);- _focus.requestFocus();- },- ),- ],+ headerStatus: sent.state == SuperTabOutgoingState.confirmed+ ? null+ : SuperTabOutgoingReceipt(+ inline: true,+ message: sent,+ // A refused message goes again only when nothing else is on+ // its way.+ onRetry:+ c.saving ||+ (sent.state == SuperTabOutgoingState.refused &&+ c.hasPendingAction)+ ? null+ : () {+ unawaited(c.retryOutgoing(sent));+ _focus.requestFocus();+ },+ // The click lands in the transcript; typing goes on in the+ // composer, as after Reply.+ onDelete: () {+ c.discardOutgoing(sent);+ _focus.requestFocus();+ },+ ),+ receipts: const [],),);}@@ -2447,7 +2476,8 @@ class _SuperTabViewState extends State<SuperTabView>root: open.root,row: (message, grouped) =>_message(message, grouped, byId, inThread: true),- outgoing: (sent) => _outgoingRow(sent, rows, byId),+ // The thread panel groups its own rows; one on its way keeps its name.+ outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),);}@@ -2688,17 +2718,37 @@ class _SuperTabViewState extends State<SuperTabView>.reversed.where(c.isOwn).firstOrNull;- final messages = _shownMessages(c.selectedId);+ final actualMessages = _shownMessages(c.selectedId);+ // A thread's reply sends in its thread; only what shows here is pending here.+ final outgoing = c+ .outgoing(c.selectedId)+ .where((sent) => sent.inMainStream)+ .toList();+ final pendingById = {for (final sent in outgoing) sent.operationId: sent};+ final messages = [...actualMessages, ...outgoing.map(_outgoingMessage)];final entries = superTabTranscriptEntries(messages);final byId = {for (final message in messages) message.id: message};final rowIndex = {for (final (index, entry) in entries.indexed)- _rowKey(entry.message.id): index,+ _rowKey(c.messageIdentity(entry.message.id)): index,};// A row stays the same row as pages arrive above it, state and all.int? rowOf(Key key) => key is ValueKey<String> ? rowIndex[key.value] : null;- final split = _splitAt(c.selectedId, entries);- final grouped = _joined(messages, _split[c.selectedId]);+ final split = _splitAt(+ c.selectedId,+ superTabTranscriptEntries(actualMessages),+ );+ // Rows on their way group by the same rule, so a quick line keeps the+ // shape it will have once confirmed; one Not sent keeps its name and+ // actions.+ final grouped = _joined(messages, _split[c.selectedId])+ ..removeWhere(+ (id) => switch (pendingById[id]?.state) {+ SuperTabOutgoingState.refused ||+ SuperTabOutgoingState.unconfirmed => true,+ _ => false,+ },+ );Widget row(int index) {final entry = entries[index];final message = entry.message;@@ -2708,7 +2758,7 @@ class _SuperTabViewState extends State<SuperTabView>final previous = index > 0 ? entries[index - 1].message : null;final time = message.createdAt;return Column(- key: ValueKey(_rowKey(message.id)),+ key: ValueKey(_rowKey(c.messageIdentity(message.id))),crossAxisAlignment: CrossAxisAlignment.stretch,children: [if (time != null &&@@ -2737,7 +2787,13 @@ class _SuperTabViewState extends State<SuperTabView>key: message.id == _target ? _targetKey : null,child: SuperTabMessageHighlight(on: message.id == _lit,- child: entry.interruptions > 0+ child: pendingById.containsKey(message.id)+ ? _outgoingRow(+ pendingById[message.id]!,+ byId,+ grouped: grouped.contains(message.id),+ )+ : entry.interruptions > 0? SuperTabRecordingNotice(key: ValueKey('super-message-${message.id}'),author: _shownAuthor(c, message),@@ -2768,16 +2824,13 @@ class _SuperTabViewState extends State<SuperTabView>// Scrolled away from the newest message, or newer pages wait unread.final awayFromEnd = _awayFromEnd.contains(c.selectedId) || moreNew;final reply = _replies[c.selectedId];- final outgoing = c- .outgoing(c.selectedId)- .where((sent) => sent.inMainStream)- .toList();// A failed message says so in its own row, with what can be done. Only// this conversation's own error is said there; another's never hides it.final composerError = c.composerError(c.selectedId);final errorInRow = outgoing.any((sent) => switch (sent.state) {- SuperTabOutgoingState.sending => false,+ SuperTabOutgoingState.sending ||+ SuperTabOutgoingState.confirmed => false,SuperTabOutgoingState.unconfirmed => c.hasPendingAction,SuperTabOutgoingState.refused =>composerError != null && sent.error == composerError,@@ -2869,7 +2922,9 @@ class _SuperTabViewState extends State<SuperTabView>_readEarlierNearTop(id, event.metrics);}if (atEnd) {- final sequence = messages.lastOrNull?.sequence ?? 0;+ // A row still sending has no place in the transcript.+ final sequence =+ actualMessages.lastOrNull?.sequence ?? 0;WidgetsBinding.instance.addPostFrameCallback((_) {if (mounted && c.selectedId == id) {_readToEnd(id, sequence);@@ -2924,17 +2979,8 @@ class _SuperTabViewState extends State<SuperTabView>sliver: SliverList(delegate: SliverChildBuilderDelegate(// Messages on their way end the list.- (context, index) =>- index < entries.length - split- ? row(split + index)- : _outgoingRow(- outgoing[index -- (entries.length - split)],- messages,- byId,- ),- childCount:- entries.length - split + outgoing.length,+ (context, index) => row(split + index),+ childCount: entries.length - split,findChildIndexCallback: (key) =>switch (rowOf(key)) {final i? when i >= split => i - split,@@ -3047,10 +3093,7 @@ class _SuperTabViewState extends State<SuperTabView>child: Row(children: [Expanded(- child: Text(- composerError,- style: DesktopChrome.control(),- ),+ child: Text(composerError, style: DesktopChrome.control()),),if (c.hasPendingAction)TextButton(@@ -3391,8 +3434,10 @@ class _SuperTabViewState extends State<SuperTabView>color: DesktopChrome.accent,onPressed:writable &&- !busy &&- !c.hasPendingAction &&+ !c.uploading &&+ ((!busy && !c.hasPendingAction) ||+ (_files.isEmpty &&+ c.canQueueText)) &&(_composer.text.trim().isNotEmpty ||diff --git a/desktop/test/super_tab_buddies_shots_test.dart b/desktop/test/super_tab_buddies_shots_test.dartindex 4937cf8d5..b8a7453a8 100644--- a/desktop/test/super_tab_buddies_shots_test.dart+++ b/desktop/test/super_tab_buddies_shots_test.dart@@ -128,6 +128,24 @@ void main() {await c.select('buddy-peer-lead');await capture('chat');+ // Rename Buddy (Diego, 10-29): the ⋮ menu, the dialog, then the header.+ await tester.tap(find.byTooltip('Buddy options'));+ await tester.pumpAndSettle();+ await captureWindow(+ tester,+ shots,+ 'buddy-rename-menu-${brightness.name}',+ );+ await tester.tap(find.text('Rename Buddy…'));+ await tester.pumpAndSettle();+ await tester.enterText(+ find.byKey(const ValueKey('super-buddy-name')),+ 'Sparky',+ );+ await tester.pumpAndSettle();+ await captureWindow(tester, shots, 'buddy-rename-${brightness.name}');+ await tester.tap(find.text('Save'));+ await capture('renamed');await c.select('buddy-peer-web');await capture('offline');await c.select('lead');diff --git a/desktop/test/super_tab_buddies_test.dart b/desktop/test/super_tab_buddies_test.dartindex 8923d6c31..86c99e90c 100644--- a/desktop/test/super_tab_buddies_test.dart+++ b/desktop/test/super_tab_buddies_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';@@ -155,6 +157,61 @@ void main() {expect(c.buddyChat('lead'), isNotNull);});+ test(+ 'renaming the Buddy sends its chat and the name, and the Swarm shows it',+ () async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = server.controller(account: 'peer');+ addTearDown(c.dispose);+ await c.refresh();++ expect(await c.renameBuddy('lead', ' Sparky '), isTrue);++ expect(commands(server, 'buddy.rename'), [+ {+ 'type': 'buddy.rename',+ 'conversationId': 'buddy-peer-lead',+ 'name': 'Sparky',+ },+ ]);+ expect(c.snapshot!.agentName('wren'), 'Sparky');+ expect(c.buddyChat('lead')?.buddyName, 'Sparky');+ },+ );++ test('clearing the name sends none, for the default', () async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = server.controller(account: 'peer');+ addTearDown(c.dispose);+ await c.refresh();+ await c.renameBuddy('lead', 'Sparky');++ expect(await c.renameBuddy('lead', ' '), isTrue);++ expect(commands(server, 'buddy.rename').last['name'], isNull);+ expect(c.snapshot!.agentName('wren'), "ken.tran's Buddy");+ expect(c.buddyChat('lead')?.buddyName, isNull);+ });++ test('a refused rename says why and keeps the name', () async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = server.controller(account: 'peer');+ addTearDown(c.dispose);+ await c.refresh();+ server.refuse = {+ 'code': 'BUDDY_NAME_TAKEN',+ 'message': 'Lead is taken in this Swarm. Choose another.',+ };++ expect(await c.renameBuddy('lead', 'Lead'), isFalse);++ expect(c.operationError, 'Lead is taken in this Swarm. Choose another.');+ expect(c.snapshot!.agentName('wren'), 'Wren');+ });+test('the shortcut opens the Buddy chat and never creates a private conversation', () async {final server = buddySwarm();giveBuddy(server);@@ -472,6 +529,38 @@ void main() {},);+ testWidgets(+ 'a removed Buddy with a chosen name keeps it in the sidebar and its chat\'s header',+ (tester) async {+ final server = buddySwarm();+ giveBuddy(server);+ (server.state['agents'] as List).removeWhere(+ (a) => (a as Map)['id'] == 'wren',+ );+ final chat = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'buddy-peer-lead');+ chat+ ..['buddyName'] = 'Sparky'+ ..['title'] = 'Sparky';+ final c = await show(tester, server);+ expect(+ find.descendant(of: buddyEntry, matching: find.text('Sparky')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: buddyEntry, matching: find.text('Buddy')),+ findsNothing,+ );+ await tester.tap(buddyEntry);+ await tester.pumpAndSettle();++ expect(find.text('Sparky · Your Buddy'), findsOneWidget);+ expect(find.text('Message Sparky'), findsOneWidget);+ await close(tester, c);+ },+ );+testWidgets('a Buddy whose session is down says offline', (tester) async {final server = buddySwarm();giveBuddy(server);@@ -1040,6 +1129,180 @@ void main() {);});+ group('Rename Buddy (mockup confirmed by Diego, 10-29)', () {+ Future<void> openRename(WidgetTester tester) async {+ await tester.tap(buddyEntry);+ await tester.pumpAndSettle();+ await tester.tap(find.byTooltip('Buddy options'));+ await tester.pumpAndSettle();+ await tester.tap(find.text('Rename Buddy…'));+ await tester.pumpAndSettle();+ }++ final nameField = find.byKey(const ValueKey('super-buddy-name'));++ testWidgets('names the Buddy for everyone, and its header shows it', (+ tester,+ ) async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = await show(tester, server);+ await openRename(tester);++ expect(find.text('Rename your Buddy'), findsOneWidget);+ expect(+ find.text('Everyone in this Swarm sees this name.'),+ findsOneWidget,+ );+ await tester.enterText(nameField, 'Sparky');+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();++ expect(commands(server, 'buddy.rename'), [+ {+ 'type': 'buddy.rename',+ 'conversationId': 'buddy-peer-lead',+ 'name': 'Sparky',+ },+ ]);+ expect(find.text('Rename your Buddy'), findsNothing);+ expect(find.text('Sparky · Your Buddy'), findsOneWidget);+ await close(tester, c);+ });++ testWidgets(+ 'starts from the chosen name; empty goes back to the default, as it says',+ (tester) async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = await show(tester, server);+ await c.renameBuddy('lead', 'Sparky');+ await openRename(tester);++ expect(+ tester.widget<TextField>(nameField).controller!.text,+ 'Sparky',+ );+ expect(+ find.text('Leave it empty to go back to "ken.tran\'s Buddy".'),+ findsOneWidget,+ );+ await tester.enterText(nameField, '');+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();++ expect(commands(server, 'buddy.rename').last['name'], isNull);+ expect(find.text("ken.tran's Buddy · Your Buddy"), findsOneWidget);+ await close(tester, c);+ },+ );++ testWidgets('a refusal shows in the dialog, which keeps the name typed', (+ tester,+ ) async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = await show(tester, server);+ await openRename(tester);+ server.refuse = {+ 'code': 'BUDDY_NAME_TAKEN',+ 'message': 'Lead is taken in this Swarm. Choose another.',+ };+ await tester.enterText(nameField, 'Lead');+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();++ expect(+ find.descendant(+ of: find.byType(AlertDialog),+ matching: find.text('Lead is taken in this Swarm. Choose another.'),+ ),+ findsOneWidget,+ );+ expect(tester.widget<TextField>(nameField).controller!.text, 'Lead');+ expect(find.text('Wren · Your Buddy'), findsOneWidget);+ server.refuse = null;+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ await close(tester, c);+ });++ testWidgets(+ 'says Saving… while the server answers, and takes no second Save',+ (tester) async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = await show(tester, server);+ await openRename(tester);+ await tester.enterText(nameField, 'Sparky');+ final hold = server.holdCommands = Completer<void>();+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pump();++ expect(find.widgetWithText(FilledButton, 'Saving…'), findsOneWidget);+ await tester.tap(find.widgetWithText(FilledButton, 'Saving…'));+ await tester.pump();+ expect(commands(server, 'buddy.rename'), hasLength(1));+ hold.complete();+ server.holdCommands = null;+ await tester.pumpAndSettle();+ expect(find.text('Rename your Buddy'), findsNothing);+ await close(tester, c);+ },+ );++ testWidgets('scrolls in a short window, as Add a Buddy does', (+ tester,+ ) async {+ final server = buddySwarm();+ giveBuddy(server);+ final c = await show(tester, server);+ await openRename(tester);+ server.refuse = {+ 'code': 'BUDDY_NAME_TAKEN',+ 'message': 'Lead is taken in this Swarm. Choose another.',+ };+ await tester.enterText(nameField, 'Lead');+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();+ server.refuse = null;+ await tester.binding.setSurfaceSize(const Size(1280, 330));+ await tester.pumpAndSettle();++ // Nothing overflows: the dialog's content scrolls instead.+ expect(tester.takeException(), isNull);+ final dialog = find.byType(AlertDialog);+ await tester.dragUntilVisible(+ find.descendant(+ of: dialog,+ matching: find.text('Lead is taken in this Swarm. Choose another.'),+ ),+ find.descendant(of: dialog, matching: find.byType(Scrollable)).first,+ const Offset(0, -40),+ );+ await tester.binding.setSurfaceSize(const Size(1280, 800));+ await tester.tap(find.widgetWithText(TextButton, 'Cancel'));+ await tester.pumpAndSettle();+ await close(tester, c);+ });++ testWidgets('is offered before any Buddy runs', (tester) async {+ final server = buddySwarm();+ giveBuddy(server);+ (server.state['agents'] as List).removeWhere(+ (a) => (a as Map)['id'] == 'wren',+ );+ final c = await show(tester, server);+ await openRename(tester);+ await tester.enterText(nameField, 'Early');+ await tester.tap(find.widgetWithText(FilledButton, 'Save'));+ await tester.pumpAndSettle();++ expect(find.text('Early · Your Buddy'), findsOneWidget);+ await close(tester, c);+ });+ });+testWidgets('the Buddy chat lists only its person and its Buddy, and offers no Add agent',(tester) async {diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartindex 7af8cdc45..a79a21d1b 100644--- a/desktop/test/super_tab_mentions_test.dart+++ b/desktop/test/super_tab_mentions_test.dart@@ -632,6 +632,48 @@ void main() {);});+ // A task with no worker is a quiet conversation: the state does not hold it until it is asked for (Dee, 2026-10-29).+ testWidgets(+ 'a tag in a closed conversation loads it and opens at its message',+ (tester) async {+ final server = ConversationServer();+ server.state['conversations'] = [+ ...server.state['conversations'] as List,+ {...conversationFixture('group', 'Release'), 'archived': true},+ ];+ server.append('Builder could not start.', conversationId: 'group');+ server.tag(+ 'message-1',+ conversationId: 'group',+ text: 'Builder could not start.',+ );+ final c = await showView(tester, server);+ expect(c.snapshot?.conversation('group'), isNull);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));+ await tester.pumpAndSettle();+ expect(c.selectedId, 'group');+ expect(find.text('Builder could not start.'), findsWidgets);+ // The read mark of the opened conversation saves a moment later.+ await tester.pump(const Duration(seconds: 1));+ },+ );++ testWidgets('a tag in a conversation the reader cannot read says so', (+ tester,+ ) async {+ final server = ConversationServer()+ ..tag('message-9', conversationId: 'private-chat', text: 'Hidden');+ final c = await showView(tester, server);+ await tester.tap(notificationsEntry());+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));+ await tester.pumpAndSettle();+ expect(find.text('Message unavailable'), findsOneWidget);+ expect(c.selectedId, isNot('private-chat'));+ });+testWidgets('a tag too far back says so and stays on the list', (tester,) async {diff --git a/desktop/test/super_tab_outgoing_rows_test.dart b/desktop/test/super_tab_outgoing_rows_test.dartnew file mode 100644index 000000000..bf5f4f8fb--- /dev/null+++ b/desktop/test/super_tab_outgoing_rows_test.dart@@ -0,0 +1,223 @@+// The rows of what the reader sends before the transcript holds it: grouped+// as confirmed rows are, dimmed only in their text, and never counted as the+// end of what was read.+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_receipt.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++void main() {+ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};++ /// A controller over [server] whose command POSTs wait for [hold] while it+ /// is set; each message the server writes is dated now, as the backend's.+ SuperTabController controller(+ ConversationServer server, {+ Completer<void>? Function()? hold,+ }) => SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: server.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST' && path.endsWith('/commands')) {+ await hold?.call()?.future;+ final reply = await server.request(method, path, body: body);+ server.messages.lastOrNull?['createdAt'] = DateTime.now()+ .toUtc()+ .toIso8601String();+ return reply;+ }+ return server.request(method, path, body: body);+ },+ );++ Future<void> show(WidgetTester tester, SuperTabController c) async {+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ final composer = find.byKey(const ValueKey('super-message-composer'));+ Future<void> type(WidgetTester tester, String text) async {+ await tester.enterText(composer, text);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 50));+ }++ Finder rowOf(String text) => find.ancestor(+ of: find.text(text),+ matching: find.byType(SuperTabMessageRow),+ );+ bool grouped(WidgetTester tester, String text) =>+ tester.widget<SuperTabMessageRow>(rowOf(text)).grouped;+ Finder dimmed(Finder of) => find.ancestor(+ of: of,+ matching: find.byWidgetPredicate((w) => w is Opacity && w.opacity < 1),+ );++ testWidgets('a quick line under my own line joins it while it sends and '+ 'after, at one height apart from its delivery line', (tester) async {+ final server = ConversationServer()..append('Earlier line');+ server.messages.last['createdAt'] = DateTime.now()+ .toUtc()+ .toIso8601String();+ final post = Completer<void>();+ final c = controller(server, hold: () => post);+ await show(tester, c);++ await type(tester, 'Quick follow-up');+ expect(grouped(tester, 'Quick follow-up'), isTrue);+ final height = tester.getSize(rowOf('Quick follow-up')).height;++ post.complete();+ await tester.pumpAndSettle();+ expect(c.outgoing('lead'), isEmpty);+ expect(grouped(tester, 'Quick follow-up'), isTrue);+ // The confirmed latest line of mine adds its delivery line below; the+ // line itself, with no avatar or name, keeps the height it had.+ final receipt = tester.getSize(find.byType(SuperTabMessageReceipt)).height;+ expect(tester.getSize(rowOf('Quick follow-up')).height - receipt, height);+ await close(tester, c);+ });++ testWidgets('a quick line that was not sent keeps its name and actions', (+ tester,+ ) async {+ final server = ConversationServer()..append('Earlier line');+ server.messages.last['createdAt'] = DateTime.now()+ .toUtc()+ .toIso8601String();+ final c = controller(server);+ await show(tester, c);+ server.reject = true;+ await type(tester, 'Refused follow-up');+ await tester.pumpAndSettle();+ expect(grouped(tester, 'Refused follow-up'), isFalse);+ expect(+ find.descendant(+ of: rowOf('Refused follow-up'),+ matching: find.text('Retry'),+ ),+ findsOneWidget,+ );+ await close(tester, c);+ });++ testWidgets('while a line sends only its text is dimmed; Sending… stays '+ 'readable', (tester) async {+ final post = Completer<void>();+ final c = controller(ConversationServer(), hold: () => post);+ await show(tester, c);+ await type(tester, 'On its way');+ expect(find.text('Sending…'), findsOneWidget);+ expect(dimmed(find.text('On its way')), findsOneWidget);+ expect(dimmed(find.text('Sending…')), findsNothing);+ post.complete();+ await tester.pumpAndSettle();+ await close(tester, c);+ });++ testWidgets('scrolling to the end reads through the last message, not a '+ 'line still sending', (tester) async {+ final server = ConversationServer();+ for (var i = 1; i <= 40; i++) {+ server.append('Update $i: checking the offline queue and reconnect.');+ }+ final post = Completer<void>();+ final c = controller(server, hold: () => post);+ await show(tester, c);+ await type(tester, 'Still sending');+ final scroll = tester+ .widget<ScrollView>(+ find.byKey(const PageStorageKey('super-messages-tab-lead')),+ )+ .controller!;+ scroll.jumpTo(0);+ await tester.pump(const Duration(milliseconds: 50));+ server.append('From a teammate');+ server.messages.last['author'] = peer;+ await c.refresh();+ await tester.pump(const Duration(milliseconds: 50));+ expect(c.unreadCount(c.selected!), 1);++ // A lazy list refines its extent as rows near the end are laid out.+ for (var i = 0; i < 8 && scroll.position.extentAfter > 1; i++) {+ scroll.jumpTo(scroll.position.maxScrollExtent);+ await tester.pump(const Duration(milliseconds: 50));+ }+ expect(scroll.position.extentAfter, lessThan(40));+ await tester.pump(const Duration(seconds: 5));+ expect(c.unreadCount(c.selected!), 0);+ post.complete();+ await tester.pumpAndSettle();+ await close(tester, c);+ });++ testWidgets('text left unsent when the window closed reads Not sent · '+ 'Retry · Delete', (tester) async {+ final server = ConversationServer();+ final gate = Completer<void>();+ final first = controller(server, hold: () => gate);+ await first.refresh();+ first.setDraft('lead', 'First');+ unawaited(first.send());+ first.setDraft('lead', 'Second');+ unawaited(first.send());+ await first.flush();+ first.dispose();+ final restored = server.controller(initial: server.saved);+ final unsent = restored+ .outgoing('lead')+ .firstWhere((m) => m.text == 'Second');+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabOutgoingReceipt(+ message: unsent,+ onRetry: () {},+ onDelete: () {},+ ),+ ),+ ),+ );+ expect(find.text('Not sent'), findsOneWidget);+ expect(find.text('Retry'), findsOneWidget);+ expect(find.text('Delete'), findsOneWidget);+ expect(find.textContaining('before this window closed'), findsNothing);+ gate.complete();+ await tester.pumpWidget(const SizedBox());+ restored.dispose();+ });+}diff --git a/desktop/test/super_tab_outgoing_shots_test.dart b/desktop/test/super_tab_outgoing_shots_test.dartindex 4d8914bc8..5ac7e2ac6 100644--- a/desktop/test/super_tab_outgoing_shots_test.dart+++ b/desktop/test/super_tab_outgoing_shots_test.dart@@ -89,6 +89,10 @@ void main() {await send('@Builder check the arm64 build');await tester.pumpAndSettle();await shot('refused');+ server.reject = false;+ await tester.tap(find.text('Retry'));+ await tester.pumpAndSettle();+ await shot('confirmed');await tester.pumpWidget(const SizedBox());await c.flush();}, skip: shots == null);diff --git a/desktop/test/super_tab_outgoing_test.dart b/desktop/test/super_tab_outgoing_test.dartindex 9e9c90b89..50a903611 100644--- a/desktop/test/super_tab_outgoing_test.dart+++ b/desktop/test/super_tab_outgoing_test.dart@@ -1,11 +1,290 @@import 'dart:async';+import 'dart:typed_data';import 'package:flutter_test/flutter_test.dart';+import 'package:harness/state/harness_attachments.dart';import 'package:harness/super_tabs/controller.dart';import 'support/super_tab_fixture.dart';void main() {+ test(+ 'an older refresh cannot unlock a newer POST or retry it twice',+ () async {+ final s = ConversationServer();+ final second = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST' &&+ (body!['command'] as Map)['text'] == 'Second') {+ await second.future;+ }+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ c.setDraft('lead', 'First');+ final one = c.send();+ c.setDraft('lead', 'Second');+ final two = c.send();+ await one;+ expect(c.saving, isTrue);+ expect(await c.retry(), isNull);+ second.complete();+ await two;+ expect(s.posts, hasLength(2));+ await c.flush();+ c.dispose();+ },+ );+ test('revocation drops queued text and cannot dispatch it later', () async {+ final s = ConversationServer();+ final gate = Completer<void>();+ final dispatched = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST') {+ dispatched.complete();+ await gate.future;+ }+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ c.setDraft('lead', 'First');+ final one = c.send();+ c.setDraft('lead', 'Second');+ final two = c.send();+ expect(c.outgoing('lead'), hasLength(2));+ await dispatched.future;+ c.revokeAccess('Access removed.');+ gate.complete();+ await Future.wait([one, two]);+ expect(c.outgoing('lead'), isEmpty);+ expect(s.posts, hasLength(1));+ c.dispose();+ });+ test(+ 'queued sends retain their project, workgroup and own Buddy destinations',+ () async {+ final s = ConversationServer();+ final gate = Completer<void>();+ var hold = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST' && hold) await gate.future;+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ await c.addBuddy(projectId: 'lead', machineId: 'mac', engine: 'claude');+ hold = true;+ final sends = <Future<Map<String, dynamic>?>>[];+ for (final id in ['lead', 'offline', 'buddy-owner-lead']) {+ expect(await c.select(id), isTrue);+ c.setDraft(id, 'Message for $id');+ sends.add(c.send());+ expect(c.outgoing(id).single.text, 'Message for $id');+ }+ gate.complete();+ await Future.wait(sends);+ final posts = s.posts+ .map((p) => p['command'] as Map)+ .where((p) => p['type'] == 'message.send');+ expect(posts.map((p) => p['conversationId']), [+ 'lead',+ 'offline',+ 'buddy-owner-lead',+ ]);+ await c.flush();+ c.dispose();+ },+ );+ test('a slow refresh never delays the next queued POST', () async {+ final s = ConversationServer();+ final reads = Completer<void>();+ var holdReads = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'GET' && holdReads) {+ final captured = await s.request(method, path, body: body);+ await reads.future;+ return captured;+ }+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ holdReads = true;+ c.setDraft('lead', 'First');+ final one = c.send();+ c.setDraft('lead', 'Second');+ final two = c.send();+ await Future<void>.delayed(Duration.zero);+ expect(s.posts.map((p) => (p['command'] as Map)['text']), [+ 'First',+ 'Second',+ ]);+ reads.complete();+ await Future.wait([one, two]);+ expect(c.messages('lead').map((m) => m.text), ['First', 'Second']);+ await c.flush();+ c.dispose();+ });+ test('queued text survives closing and can never cross accounts', () async {+ final s = ConversationServer();+ final gate = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST') await gate.future;+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ c.setDraft('lead', 'First');+ final one = c.send();+ c.setDraft('lead', 'Second');+ final two = c.send();+ await c.flush();+ final saved = s.saved!;+ c.dispose();+ gate.complete();+ await Future.wait([one, two]);+ final restored = s.controller(initial: saved);+ await restored.refresh();+ expect(restored.outgoing('lead').map((m) => m.text), ['First', 'Second']);+ expect(+ s.posts,+ hasLength(1),+ reason: 'Only the request already dispatched before close can finish; restoration sends nothing.',+ );+ final other = SuperTabController(+ tabId: 'tab',+ accountId: 'someone-else',+ request: s.request,+ save: s.save,+ initial: saved,+ pollInterval: Duration.zero,+ );+ expect(other.outgoing('lead'), isEmpty);+ restored.dispose();+ other.dispose();+ });+ test(+ 'acknowledged text confirms before the following refresh finishes',+ () async {+ final s = ConversationServer();+ final reads = Completer<void>();+ var holdReads = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'GET' && holdReads) await reads.future;+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ holdReads = true;+ c.setDraft('lead', 'Confirmed already');+ final sent = c.send();+ await Future<void>.delayed(Duration.zero);+ expect(c.outgoing('lead').single.state.name, 'confirmed');+ reads.complete();+ await sent;+ expect(c.outgoing('lead'), isEmpty);+ expect(c.messages('lead').map((m) => m.text), ['Confirmed already']);+ await c.flush();+ c.dispose();+ },+ );+ test(+ 'an uncertain first send keeps later text retryable in typed order',+ () async {+ final server = ConversationServer()..loseReply = true;+ final gate = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: server.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST') await gate.future;+ return server.request(method, path, body: body);+ },+ );+ await c.refresh();+ c.setDraft('lead', 'First');+ final one = c.send();+ c.setDraft('lead', 'Second');+ final two = c.send();+ gate.complete();+ await Future.wait([one, two]);+ expect(server.posts, hasLength(1));+ expect(c.outgoing('lead').map((m) => m.text), ['First', 'Second']);+ expect(c.outgoing('lead').map((m) => m.state), [+ SuperTabOutgoingState.unconfirmed,+ SuperTabOutgoingState.refused,+ ]);+ await c.flush();+ c.dispose();+ },+ );+ test('rapid text sends show immediately and post in typed order', () async {+ final server = ConversationServer();+ final first = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: server.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST' && server.posts.isEmpty) await first.future;+ return server.request(method, path, body: body);+ },+ );+ await c.refresh();+ c.setDraft('lead', 'First');+ final one = c.send();+ await Future<void>.delayed(Duration.zero);+ c.setDraft('lead', 'Second');+ final two = c.send();+ await Future<void>.delayed(Duration.zero);+ expect(c.outgoing('lead').map((m) => m.text), ['First', 'Second']);+ expect(c.draft('lead'), isEmpty);+ first.complete();+ await Future.wait([one, two]);+ expect(server.posts.map((p) => (p['command'] as Map)['text']), [+ 'First',+ 'Second',+ ]);+ expect(c.messages('lead').map((m) => m.text), ['First', 'Second']);+ await c.flush();+ c.dispose();+ });+/// A controller whose sends wait for [hold] while it is set.({SuperTabController controller, ConversationServer server}) open({Completer<void>? Function()? hold,@@ -65,7 +344,9 @@ void main() {// The send lands; the read after it does not.server.failReads = true;await controller.send();- expect(outgoing(controller), [('Ship it', SuperTabOutgoingState.sending)]);+ expect(outgoing(controller), [+ ('Ship it', SuperTabOutgoingState.confirmed),+ ]);expect(controller.messages('lead'), isEmpty);server.failReads = false;@@ -101,14 +382,13 @@ void main() {test('an unconfirmed message the transcript already holds is not shown ''twice', () async {final (:controller, :server) = open(- server: ConversationServer()..loseReply = true,+ server: ConversationServer()+ ..loseReply = true+ ..hashedIds = true,);await controller.refresh();controller.setDraft('lead', 'Once only');await controller.send();- // The backend names a person's message by the send's operation id.- final sent = server.messages.single;- sent['id'] = server.posts.single['operationId'];await controller.refresh();expect(controller.messages('lead').map((m) => m.text), ['Once only']);expect(outgoing(controller), isEmpty);@@ -243,4 +523,295 @@ void main() {reopened.discardOutgoing(reopened.outgoing('lead').single);expect(outgoing(reopened), isEmpty);});++ /// A controller over [server] whose requests go through [request] first.+ SuperTabController over(+ ConversationServer server,+ Future<Map<String, dynamic>> Function(+ String method,+ String path,+ Map<String, dynamic>? body,+ )+ request, {+ Map<String, dynamic>? initial,+ }) {+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: server.save,+ upload: server.upload,+ initial: initial ?? const {},+ pollInterval: Duration.zero,+ request: (method, path, {body}) => request(method, path, body),+ );+ addTearDown(() async {+ await c.flush();+ c.dispose();+ });+ return c;+ }++ bool isCommand(String method, String path) =>+ method == 'POST' && path.endsWith('/commands');+ final file = HarnessAttachment('build.log', Uint8List.fromList([1, 2, 3]));++ test('text queued behind an attachment send whose answer is lost is Not '+ 'sent with Retry, not Sending forever', () async {+ final server = ConversationServer();+ final answer = Completer<void>();+ final c = over(server, (method, path, body) async {+ if (isCommand(method, path) &&+ (body!['command'] as Map)['attachmentIds'] != null) {+ await answer.future;+ throw StateError('Connection lost');+ }+ return server.request(method, path, body: body);+ });+ await c.refresh();+ c.attachments('lead').add([file]);+ c.setDraft('lead', 'With the log');+ final withFile = c.send();+ await pumpEventQueue();+ expect(c.saving, isTrue);+ // The file stays in its own box until the answer; text typed in another+ // chat meanwhile queues behind it.+ expect(await c.select('offline'), isTrue);+ c.setDraft('offline', 'Typed after it');+ unawaited(c.send());+ List<(String, SuperTabOutgoingState)> offline() => [+ for (final m in c.outgoing('offline')) (m.text, m.state),+ ];+ expect(offline(), [('Typed after it', SuperTabOutgoingState.sending)]);+ answer.complete();+ await withFile;+ await pumpEventQueue();+ expect(outgoing(c), [('With the log', SuperTabOutgoingState.unconfirmed)]);+ expect(offline(), [('Typed after it', SuperTabOutgoingState.refused)]);+ expect(+ server.posts.where(+ (p) => (p['command'] as Map)['text'] == 'Typed after it',+ ),+ isEmpty,+ );+ });++ test('text queued behind a Retry whose answer is lost is Not sent with '+ 'Retry, not Sending forever', () async {+ final server = ConversationServer()..reject = true;+ final answer = Completer<void>();+ var loseRetry = false;+ final c = over(server, (method, path, body) async {+ if (isCommand(method, path) && loseRetry) {+ loseRetry = false;+ await answer.future;+ throw StateError('Connection lost');+ }+ return server.request(method, path, body: body);+ });+ await c.refresh();+ c.setDraft('lead', 'First');+ await c.send();+ server.reject = false;+ loseRetry = true;+ final retrying = c.retryOutgoing(c.outgoing('lead').single);+ await pumpEventQueue();+ c.setDraft('lead', 'Second');+ unawaited(c.send());+ expect(outgoing(c).last, ('Second', SuperTabOutgoingState.sending));+ answer.complete();+ await retrying;+ await pumpEventQueue();+ expect(outgoing(c), [+ ('First', SuperTabOutgoingState.unconfirmed),+ ('Second', SuperTabOutgoingState.refused),+ ]);+ // Delete frees the lane: the next text goes out at once.+ c.discardOutgoing(c.outgoing('lead').first);+ c.setDraft('lead', 'Third');+ await c.send();+ expect(server.messages.map((m) => m['text']), contains('Third'));+ });++ test('the app names a sent message as the server does', () {+ // Pinned to backend/src/superTabs/commands.ts `message.send`:+ // `const operationId = stableId(state.id, actorKey(actor), context.operationId)`+ // and `result.messageId = operationId`, with `stableId` in model.ts.+ // Value from Node: stableId('tab', 'person:owner', 'op-1').+ expect(+ superTabMessageId(tabId: 'tab', accountId: 'owner', operationId: 'op-1'),+ 'a0960dce4aca9b3328df941b',+ );+ });++ test('a refresh that lands before the acknowledgement shows the message '+ 'once, in the same row', () async {+ final server = ConversationServer()..hashedIds = true;+ final answer = Completer<void>();+ final c = over(server, (method, path, body) async {+ final reply = await server.request(method, path, body: body);+ if (isCommand(method, path)) await answer.future;+ return reply;+ });+ await c.refresh();+ c.setDraft('lead', 'Once');+ final sent = c.send();+ await pumpEventQueue();+ final receipt = c.outgoing('lead').single.operationId;+ expect(server.messages, hasLength(1));+ await c.refresh();+ expect(c.messages('lead').map((m) => m.text), ['Once']);+ expect(c.outgoing('lead'), isEmpty);+ expect(c.messageIdentity(c.messages('lead').single.id), receipt);+ answer.complete();+ await sent;+ expect(c.messages('lead').map((m) => m.text), ['Once']);+ expect(c.outgoing('lead'), isEmpty);+ });++ test('an attachment send keeps its place after earlier text', () async {+ final server = ConversationServer();+ final c = over(+ server,+ (method, path, body) => server.request(method, path, body: body),+ );+ await c.refresh();+ // The first is taken; the read after it does not land.+ server.failReads = true;+ c.setDraft('lead', 'First');+ await c.send();+ server.reject = true;+ c.attachments('lead').add([file]);+ c.setDraft('lead', 'Second, with the log');+ await c.send();+ expect(outgoing(c), [+ ('First', SuperTabOutgoingState.confirmed),+ ('Second, with the log', SuperTabOutgoingState.refused),+ ]);+ });++ test('text left unsent when the window closed reads Not sent alone, and '+ 'older app versions still read its reason', () async {+ final server = ConversationServer();+ final gate = Completer<void>();+ final c = over(server, (method, path, body) async {+ if (isCommand(method, path)) await gate.future;+ return server.request(method, path, body: body);+ });+ await c.refresh();+ c.setDraft('lead', 'First');+ unawaited(c.send());+ c.setDraft('lead', 'Second');+ unawaited(c.send());+ await c.flush();+ final saved = server.saved!;+ final kept = ((saved['refused'] as Map)['lead'] as List).single as Map;+ expect(kept['error'], 'Not sent before this window closed.');+ final restored = over(+ server,+ (method, path, body) => server.request(method, path, body: body),+ initial: saved,+ );+ final unsent = restored+ .outgoing('lead')+ .firstWhere((m) => m.text == 'Second');+ expect(unsent.state, SuperTabOutgoingState.refused);+ expect(unsent.error, isNull);+ await restored.flush();+ final again = ((server.saved!['refused'] as Map)['lead'] as List).single;+ expect((again as Map)['error'], 'Not sent before this window closed.');+ gate.complete();+ });++ test('a finished send leaves the busy flag to the action that holds the '+ 'lane now', () async {+ final server = ConversationServer();+ final reads = Completer<void>();+ final saving = Completer<void>();+ var holdSave = false;+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ pollInterval: Duration.zero,+ save: (value) async {+ if (holdSave) await saving.future;+ return server.save(value);+ },+ request: (method, path, {body}) async {+ final reply = await server.request(method, path, body: body);+ if (isCommand(method, path) &&+ (body!['command'] as Map)['type'] == 'member.status') {+ holdSave = true;+ }+ return reply;+ },+ );+ addTearDown(c.dispose);+ await c.refresh();+ server.holdReads = reads;+ c.setDraft('lead', 'First');+ final first = c.send();+ await pumpEventQueue();+ expect(c.saving, isFalse, reason: 'Acknowledged; its read is held.');+ final status = c.command({+ 'type': 'member.status',+ 'status': {'text': 'Reviewing', 'emoji': null},+ });+ await pumpEventQueue();+ expect(c.saving, isTrue);+ server.holdReads = null;+ reads.complete();+ await first;+ expect(+ c.saving,+ isTrue,+ reason: 'The status change still holds the lane while it saves.',+ );+ saving.complete();+ await status;+ expect(c.saving, isFalse);+ });++ test(+ 'queued text for a conversation that is gone is dropped with a notice',+ () async {+ final server = ConversationServer();+ final answer = Completer<void>();+ final c = over(server, (method, path, body) async {+ if (isCommand(method, path) &&+ (body!['command'] as Map)['text'] == 'First') {+ await answer.future;+ }+ return server.request(method, path, body: body);+ });+ await c.refresh();+ c.setDraft('lead', 'First');+ final first = c.send();+ await pumpEventQueue();+ expect(await c.select('offline'), isTrue);+ c.setDraft('offline', 'For the closed one');+ unawaited(c.send());+ (server.state['conversations'] as List).removeWhere(+ (g) => (g as Map)['id'] == 'offline',+ );+ server.revision++;+ await c.refresh();+ expect(c.snapshot!.conversation('offline'), isNull);+ answer.complete();+ await first;+ await pumpEventQueue();+ expect(c.outgoing('offline'), isEmpty);+ expect(+ c.operationNotice,+ 'Not sent: “For the closed one”. Its conversation is no longer available.',+ );+ await c.flush();+ expect((server.saved!['refused'] as Map?)?['offline'], isNull);+ expect(+ server.posts.where(+ (p) => (p['command'] as Map)['conversationId'] == 'offline',+ ),+ isEmpty,+ );+ },+ );}diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex 294911928..69dad3c05 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -1,8 +1,12 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_row.dart';import 'package:harness/super_tabs/view.dart';import 'package:harness/super_tabs/roster.dart';import 'package:harness/shared/widgets/app_icon_button.dart';@@ -10,6 +14,68 @@ import 'package:harness/shared/widgets/app_icon_button.dart';import 'support/super_tab_fixture.dart';void main() {+ testWidgets('rapid pending rows have independent identity and dimmed text', (+ tester,+ ) async {+ final s = ConversationServer();+ final post = Completer<void>();+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ save: s.save,+ pollInterval: Duration.zero,+ request: (method, path, {body}) async {+ if (method == 'POST') await post.future;+ return s.request(method, path, body: body);+ },+ );+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ final composer = find.byKey(const ValueKey('super-message-composer'));+ for (final text in ['First quick send', 'Second quick send']) {+ await tester.enterText(composer, text);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ }+ expect(tester.takeException(), isNull);+ expect(find.byType(SuperTabMessageRow), findsNWidgets(2));+ final firstId = c.outgoing(c.selectedId).first.operationId!;+ final stableRow = find.byKey(ValueKey('super-row-$firstId'));+ expect(stableRow, findsOneWidget);+ final before = tester.element(stableRow);+ final beforeHeight = tester.getSize(stableRow).height;+ final dimmed = find.ancestor(+ of: find.text('First quick send'),+ matching: find.byWidgetPredicate((w) => w is Opacity && w.opacity < 1),+ );+ expect(dimmed, findsOneWidget);+ post.complete();+ await tester.pumpAndSettle();+ expect(find.byType(SuperTabMessageRow), findsNWidgets(2));+ expect(identical(before, tester.element(stableRow)), isTrue);+ expect(+ tester.getSize(stableRow).height,+ beforeHeight,+ reason: 'Replacing Sending with confirmation must not resize the row.',+ );+ expect(dimmed, findsNothing);+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });testWidgets('native observations keep their agent author and show source and truncation clearly',(tester) async {diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex b82b352f2..eb0c0e0e8 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -3,6 +3,7 @@ import 'dart:convert';import 'dart:math';import 'dart:typed_data';+import 'package:cryptography/dart.dart' show DartSha256;import 'package:dio/dio.dart' show CancelToken;import 'package:harness/super_tabs/attachment_upload.dart';import 'package:harness/super_tabs/buddies.dart' show kBuddyEngineRefusals;@@ -383,6 +384,15 @@ const superTabUpdateRequired = SuperTabFailure(statusCode: 426,);+/// The backend's `stableId(...parts)`: the first 24 hex of+/// sha256(JSON.stringify(parts)) (backend/src/superTabs/model.ts).+String _backendId(List<String> parts) => const DartSha256()+ .hashSync(utf8.encode(jsonEncode(parts)))+ .bytes+ .map((b) => b.toRadixString(16).padLeft(2, '0'))+ .join()+ .substring(0, 24);+class ConversationServer {int revision = 0;@@ -400,6 +410,11 @@ class ConversationServer {void Function(String path)? onRead;bool loseReply = false, reject = false, failSave = false, failReads = false;+ /// Names a person's message as the backend does: a hash of the Swarm, the+ /// sender and the send's receipt id (backend model.ts `stableId`, used by+ /// `message.send` in commands.ts), not `message-N`.+ bool hashedIds = false;+/// Conversations whose single-message reads (`?messageId=`) the backend/// refuses, as it does for one the reader may not read.final forbidMessageReads = <String>{};@@ -412,6 +427,9 @@ class ConversationServer {// Makes every command answer with this refusal: {code, message}, with// [refuseStatus] as its HTTP status.Map<String, String>? refuse;+ // While set, every command waits for it before it answers: a slow server.+ Completer<void>? holdCommands;+int refuseStatus = 409;/// How many re-sends of an operation already answered lose their reply@@ -770,6 +788,7 @@ class ConversationServer {}if (method == 'POST') {posts.add(Map<String, dynamic>.from(body!));+ if (holdCommands case final hold?) await hold.future;if (reject) {throw const SuperTabFailure('INVALID_RECIPIENT',@@ -823,7 +842,18 @@ class ConversationServer {messages.last['thread'] = root;if (command['alsoSend'] == true) messages.last['alsoInChat'] = true;}- output['messageId'] = 'message-$revision';+ if (hashedIds) {+ final id = _backendId([+ state['id'] as String,+ 'person:${reader ?? 'owner'}',+ operationId,+ ]);+ if (messages.last['thread'] == messages.last['id']) {+ messages.last['thread'] = id;+ }+ messages.last['id'] = id;+ }+ output['messageId'] = messages.last['id'];} else if (command['type'] == 'member.status' ||command['type'] == 'member.username' ||command['type'] == 'member.avatar' ||@@ -974,6 +1004,46 @@ class ConversationServer {});}output['conversationId'] = chatId;+ } else if (command['type'] == 'buddy.rename') {+ // As the backend's: the reader's own Buddy chat keeps the name, or+ // drops it for the default, and its Buddy shows it at once.+ final person = reader ?? 'owner';+ final chat = (state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .where(+ (g) =>+ g['id'] == command['conversationId'] &&+ g['kind'] == 'buddy' &&+ g['buddyOwnerId'] == person,+ )+ .firstOrNull;+ if (chat == null) {+ throw const SuperTabFailure(+ 'NOT_FOUND',+ 'This conversation is unavailable.',+ statusCode: 404,+ );+ }+ revision++;+ final owner = (state['people'] as List? ?? const [])+ .cast<Map>()+ .where((p) => p['id'] == person)+ .firstOrNull;+ final name = command['name'] as String?;+ final shown =+ name ??+ "${(owner?['email'] as String? ?? person).split('@').first}'s Buddy";+ if (name == null) {+ chat.remove('buddyName');+ } else {+ chat['buddyName'] = name;+ }+ chat['title'] = shown;+ for (final agent in (state['agents'] as List).cast<Map>()) {+ if ((chat['agentIds'] as List).contains(agent['id'])) {+ agent['displayName'] = shown;+ }+ }} else if (command['type'] == 'buddy.remove') {revision++;final person = reader ?? 'owner';diff --git a/desktop/tool/swarm_latency_probe_test.dart b/desktop/tool/swarm_latency_probe_test.dartnew file mode 100644index 000000000..662ccdf78--- /dev/null+++ b/desktop/tool/swarm_latency_probe_test.dart@@ -0,0 +1,109 @@+// Diagnostic only: synthetic transport gates, never the real CLI or account.+import 'dart:async';+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/view.dart';++import '../test/support/super_tab_fixture.dart';++void main() {+ testWidgets('baseline send frames and transport boundaries', (tester) async {+ final server = ConversationServer();+ final post = Completer<void>();+ final reads = Completer<void>();+ var gated = false;+ final clock = Stopwatch()..start();+ final events = <Map<String, Object>>[];+ void record(String event) =>+ events.add({'event': event, 'us': clock.elapsedMicroseconds});+ final c = SuperTabController(+ tabId: 'tab',+ accountId: 'owner',+ pollInterval: Duration.zero,+ save: (value) async {+ record('save');+ await server.save(value);+ },+ request: (method, path, {body}) async {+ if (gated) {+ record('$method start');+ await (method == 'POST' ? post.future : reads.future);+ }+ final result = await server.request(method, path, body: body);+ if (gated) record('$method complete');+ return result;+ },+ );+ record('open start');+ await c.refresh();+ record('open read complete');+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Test Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ record('open settled');+ record('switch start');+ await c.select('offline');+ await tester.pump();+ record('switch first frame');+ await tester.pumpAndSettle();+ final field = find.byKey(const ValueKey('super-message-composer'));+ record('typing start');+ await tester.enterText(field, 'Latency probe');+ await tester.pump();+ record('typing frame');+ gated = true;+ record('enter');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump(const Duration(microseconds: 16667));+ record('first frame');+ expect(find.text('Latency probe'), findsWidgets);+ expect(c.outgoing(c.selectedId), hasLength(1));+ record('ack release');+ post.complete();+ await tester.pump();+ record('ack frame');+ final savingAfterAck = c.saving;+ final outgoingAfterAck = c.outgoing(c.selectedId).length;+ final statesAfterAck = c+ .outgoing(c.selectedId)+ .map((m) => m.state.name)+ .toList();+ await tester.enterText(field, 'Second probe');+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ final queued = c.outgoing(c.selectedId).length;+ record('refresh release');+ reads.complete();+ await tester.pumpAndSettle();+ record('confirmed frame');+ debugPrint(+ jsonEncode({+ 'events': events,+ 'savingAfterAck': savingAfterAck,+ 'outgoingAfterAck': outgoingAfterAck,+ 'statesAfterAck': statesAfterAck,+ 'outgoingAfterSecondSend': queued,+ 'posted': server.posts.length,+ 'secondDraft': c.draft(c.selectedId),+ }),+ );+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ });+}diff --git a/docs/naming-system.md b/docs/naming-system.mdindex dec63b497..95415c93e 100644--- a/docs/naming-system.md+++ b/docs/naming-system.md@@ -113,7 +113,9 @@ hides them. Workgroups are shown by their number in grey with no **#**and then their title (`12 Offline editing`), aligned with the project name. An expanded projectwithout workgroups says **No workgroups yet**. An open channel's heading reads as its row(`# openharness`). **Buddies** holds the person's **Buddy chat** for each project, from the-start, listed by their Buddy's name and avatar, or **Buddy** while none runs; the product+start, listed by their Buddy's name and avatar, or while none runs by the name they chose for it,+else **Buddy**; its ⋮ menu offers+**Rename Buddy…**, and the name its person chooses is the one everyone sees; the productmanager's private lines to them land there. Opening one highlights only that row and leaves theprojects as they were. The project's name is in grey brackets when the Swarm has several(`Wren (web-2)`); new lines show the name in bold, with no count. Hovering saysdiff --git a/docs/swarms.md b/docs/swarms.mdindex bd11e40dd..1ece74fe3 100644--- a/docs/swarms.md+++ b/docs/swarms.md@@ -306,6 +306,17 @@ Buddies are on in every Swarm; there is no setting. They replaced Chat with PM (full permissions, and its relaunches keep the mode it was started with: remove it and add a Claude Code Buddy. Astart the server recorded before the refusal, run by a Harness from 10-29 on, starts in Codex's read-only sandboxwith approvals sent to the person, and a Codex too old for that mode stays stopped rather than starting without it.+- A Buddy is called "<person>'s Buddy" until its owner names it: **Rename Buddy…** in the Buddy chat's ⋮ menu+ (`buddy.rename` with the Buddy chat's id, and `null` for the default), at any time, even before a Buddy runs.+ Everyone in the Swarm sees the new name on its roster row and as its messages' sender. Only the chat's owner may+ rename it, not the Swarm's owner or any agent, and no other agent can be renamed this way. A name is 2 to 32+ letters, digits, single spaces, dots, dashes, underscores or apostrophes, starting with a letter or digit, counted and+ compared after Unicode NFKC, with no invisible characters (such as U+FE0F). It is never a role ("Lead", "PM") or a+ name kept for the Swarm ("Reviewer", "System"), nor, ignoring case, another agent's name, a person's, another person's+ default Buddy name or a name chosen in another Buddy chat. It is kept on the Buddy chat, so removing the Buddy and+ adding it again keeps it, unless someone has taken it since, when the Buddy starts with the default name instead. A+ person who leaves and joins again starts with a new chat and the default name. Look-alike letters from other+ scripts are not compared.- Nobody else is ever added to a Buddy chat, the Swarm's owner and the product manager included.- A proposal is sent only for its owner's own message in their Buddy chat that asked for it: their newest message there,or one from the last hour, and only once for each such message. The server writes the "on behalf of" label, so a Buddy cannot leave it out or change it.diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex ef7593207..80264a842 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -149,6 +149,7 @@ class SuperTabConversation {row['projectId'] as String? ?? (row['kind'] == 'leads' ? '' : 'lead'),kind = row['kind'] as String?,buddyOwnerId = row['buddyOwnerId'] as String?,+ buddyName = row['buddyName'] as String?,number = (row['number'] as num?)?.toInt(),title = _text(row, 'title'),leadId = row['leadId'] as String?,@@ -207,6 +208,10 @@ class SuperTabConversation {/// The person a Buddy chat belongs to; only they read it.final String? buddyOwnerId;++ /// The name a Buddy chat's person chose for their Buddy, kept while no+ /// Buddy runs; null for the default (backend buddies.ts renameBuddy).+ final String? buddyName;final SuperTabTask? task;final int? number;String get label => number == null ? title : '#$number $title';diff --git a/mobile/lib/swarm/swarm_need_rows.dart b/mobile/lib/swarm/swarm_need_rows.dartindex aa1d3ed34..d23079b6e 100644--- a/mobile/lib/swarm/swarm_need_rows.dart+++ b/mobile/lib/swarm/swarm_need_rows.dart@@ -178,7 +178,7 @@ class SwarmNeedLine extends StatelessWidget {const _titleHeight = 1.3;/// An open need: its glyph in the warning colour, who asks and where — a tap-/// there opens where it was asked, when [onOpen] is given — then [body] and+/// there or on [body] opens where it was asked, when [onOpen] is given — then [body] and/// [actions].class _NeedCard extends StatelessWidget {const _NeedCard({@@ -214,6 +214,10 @@ class _NeedCard extends StatelessWidget {),style: AppType.label(color: AppPalette.textPrimary, height: _titleHeight),);+ final bodyText = Text.rich(+ _mentions(body),+ style: AppType.body(color: AppPalette.textPrimary, height: 1.4),+ );return Padding(padding: const EdgeInsets.all(AppSpace.l),child: Row(@@ -246,13 +250,15 @@ class _NeedCard extends StatelessWidget {header,if (body.isNotEmpty) ...[const SizedBox(height: 6),- Text.rich(- _mentions(body),- style: AppType.body(- color: AppPalette.textPrimary,- height: 1.4,- ),- ),+ if (onOpen case final open?)+ GestureDetector(+ key: ValueKey('swarm-need-body-${need.key}'),+ behavior: HitTestBehavior.opaque,+ onTap: open,+ child: bodyText,+ )+ else+ bodyText,],const SizedBox(height: 14),actions,diff --git a/mobile/test/swarm/swarm_buddy_name_model_test.dart b/mobile/test/swarm/swarm_buddy_name_model_test.dartnew file mode 100644index 000000000..cd9e6f8c1--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_name_model_test.dart@@ -0,0 +1,25 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++import 'swarm_fixture.dart';++/// A Buddy chat carries the name its person chose for their Buddy, kept while+/// no Buddy runs, as the desktop's model does (desktop_parity_test).+void main() {+ test('a Buddy chat keeps the name its person chose', () {+ final chat = SuperTabConversation.fromJson({+ ...buddyChatData('c1', agentIds: const []),+ 'buddyName': 'Sparky',+ });++ expect(chat.buddyName, 'Sparky');+ });++ test('a chat with no chosen name, as from an older backend, has none', () {+ final chat = SuperTabConversation.fromJson(+ buddyChatData('c1', agentIds: const []),+ );++ expect(chat.buddyName, isNull);+ });+}diff --git a/mobile/test/swarm/swarm_screens_test.dart b/mobile/test/swarm/swarm_screens_test.dartindex 5f359cd56..51680991f 100644--- a/mobile/test/swarm/swarm_screens_test.dart+++ b/mobile/test/swarm/swarm_screens_test.dart@@ -439,6 +439,21 @@ void main() {expect(find.text('Which name should the flag have?'), findsOneWidget);});+ testWidgets('a tag opens the conversation from its text too', (+ tester,+ ) async {+ await pump(tester, backend(), const SwarmNeedsPage());+ await tester.tap(key('swarm-need-row-mention:m1'));+ await tester.pumpAndSettle();++ await tester.tap(+ find.textContaining('Can you check the copy?', findRichText: true),+ );+ await tester.pumpAndSettle();++ expect(find.byType(SwarmConversationPage), findsOneWidget);+ });+testWidgets('with Swarm off, says where to turn it on', (tester) async {await pump(tester, backend(), const SwarmPage(), on: false);