Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge batch 11-03 b2200: #2797 #2794 #2783 #2836 #2838 (#2839)

0xken15b5b3c63fad5a
diff --git a/.github/workflows/backend-cache.yml b/.github/workflows/backend-cache.yml
index b67242c87..e3e73cf81 100644
--- a/.github/workflows/backend-cache.yml
+++ b/.github/workflows/backend-cache.yml
@@ -19,6 +19,7 @@ concurrency:
jobs:
mongod:
+ if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
timeout-minutes: 10
defaults:
diff --git a/AGENTS.md b/AGENTS.md
index 43b72083a..be453231e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,3 +1,15 @@
+# Product
+
+Every change serves one positioning, written in [PRODUCT.md](PRODUCT.md#what-harness-is): tell the PM what you
+want, and your crew ships it; Ken's router fits every agent to a machine with the resources its job needs; every lab
+in one crew, on the team's own machines, reviewed and tested before merge.
+
+- Build only what your task asks. An idea beyond it goes to the project's PM as a proposal (outside a Swarm, to the
+ maintainers).
+- The PM owns the product. Fixes to what ships, security fixes and anything that makes the crew faster or more
+ reliable are a yes at once. New features and growing scope are a no unless they strengthen the positioning. Fewer
+ things, made with purpose.
+
# Development and release work
Read [ENGINEERING.md](ENGINEERING.md) before changing code: every change meets its standards. What Harness must
diff --git a/PRODUCT.md b/PRODUCT.md
index 2e8a4d617..1ac680e67 100644
--- a/PRODUCT.md
+++ b/PRODUCT.md
@@ -23,6 +23,15 @@ agents from every lab on them, with work verified before it ships.**
- **People bring the capacity; the Product Manager decides what it builds.** Everyone in a Swarm can bring a machine
or a subscription, and it joins one pool used before anyone waits.
+**Positioning** (Dee, 2026-11-03). A new feature or more scope strengthens one of these, or it is not built; fixes to
+what ships, security and anything that makes the crew faster are a yes at once:
+
+- **Tell the PM what you want, and your crew ships it.**
+- **Ken's router fits every agent to a machine with the resources its job needs**: the CPU, memory, disk, tools,
+ devices and quota, so dozens of agents run at once through CI, end-to-end tests and VMs without choking. Tokens are
+ the least of the bottlenecks.
+- **Every lab in one crew, on the team's own machines, reviewed and tested before merge.**
+
## Who it is for
In this order:
diff --git a/backend/integration/superTabActivity.test.ts b/backend/integration/superTabActivity.test.ts
index 37306cd44..1b982852d 100644
--- a/backend/integration/superTabActivity.test.ts
+++ b/backend/integration/superTabActivity.test.ts
@@ -123,6 +123,9 @@ describe('Activity: replies to a person\'s messages', () => {
expect(list.map(i => [i.kind, i.messageId, i.text, i.actor.kind])).toEqual([['reply', agentReply, 'Worker answers', 'agent'], ['reply', reply, 'Peer answers', 'person']])
expect(list[1]).toMatchObject({ conversationId: s.web, conversationTitle: 'Web', threadId: root, actor: { id: peer.sub, name: expect.any(String) }, read: false, emoji: null })
expect(list[0].actor.name).toBe('worker-harness')
+ // A person by the name they set (personNames.ts), else their username.
+ await run(s.tabId, { type: 'member.name', name: 'Peer Person' }, peer)
+ expect((await items(s.tabId)).find(i => i.messageId === reply).actor.name).toBe('Peer Person')
expect(typeof list[0].messageSequence).toBe('number')
// Nothing for the person who replied, and nothing for a reply in one's own thread.
expect(await items(s.tabId, peer)).toEqual([])
diff --git a/backend/integration/superTabNoticeDigest.test.ts b/backend/integration/superTabNoticeDigest.test.ts
index ab81ce12d..5f2dd14ba 100644
--- a/backend/integration/superTabNoticeDigest.test.ts
+++ b/backend/integration/superTabNoticeDigest.test.ts
@@ -713,3 +713,95 @@ describe('with the update request', () => {
expect((await deliveryOf(id, f.lead)).status).toBe('digested')
})
})
+
+// Two more kinds (docs/plans/2026-11-02-pm-digest-more-kinds-design.md): the coordinator's own skills notices, and usage-limit or
+// failing-model alerts. Each was delivered at once until then. A step's Stuck still is: a person must act on it (review of #2797).
+describe('a step\'s Stuck, skills notices and quiet alerts', () => {
+ /** A review step of the task, assigned to a Reviewer on the worker's machine. */
+ async function stepOf(f: Awaited<ReturnType<typeof swarm>>) {
+ const step = String((await f.execute({ type: 'conversation.create', title: 'Review: Ship the parser', brief: 'Review it', checks: [],
+ reviewOf: f.group })).result.conversationId)
+ const reviewer = await f.add(step, 'test-host', 'Reviewer')
+ const assignmentId = String((await f.execute({ type: 'work.assign', conversationId: step, agentId: reviewer })).result.assignmentId)
+ const status = (s: 'blocked' | 'needs_human') => f.execute({ type: 'work.status', conversationId: step, assignmentId, status: s, result: 'Changes needed' }, host, reviewer)
+ return { step, reviewer, status }
+ }
+ /** The alert rows about [agentId] the coordinator was sent, oldest first. */
+ const alertsTo = async (f: Awaited<ReturnType<typeof swarm>>, alert: string) => {
+ const rows = (await db.superTabMessage.findMany({ where: { tabId: f.tab }, orderBy: { sequence: 'asc' } }))
+ .filter(m => kindOf(m) === 'terminal-alert' && (m.source as { alert?: string }).alert === alert)
+ const sent = []
+ for (const m of rows) if (await db.superTabDelivery.findUnique({ where: { id: stableId(m.id, f.lead) } })) sent.push(m.id)
+ return sent
+ }
+ const alert = (f: Awaited<ReturnType<typeof swarm>>, active: boolean) =>
+ f.execute({ type: 'agent.alert', agentId: f.worker, alert: 'limit', active }, host, f.worker)
+
+ it('a step\'s Stuck goes at once to the coordinator and to the task\'s owner: a person must act on it (review of #2797)', async () => {
+ const f = await swarm()
+ const s = await stepOf(f)
+ await s.status('blocked')
+ const row = await statusRow(f.tab, s.step, 'Stuck')
+ expect((await deliveryOf(row.id, f.lead)).status).toBe('queued')
+ expect((await deliveryOf(row.id, f.worker)).status).toBe('queued')
+ })
+
+ it('a step\'s Stuck goes at once to the coordinator when no owner of its task is told (review of the more-kinds branch)', async () => {
+ const f = await swarm()
+ const orphan = String((await f.execute({ type: 'conversation.create', title: 'Nobody holds this', brief: 'Unassigned', checks: [] })).result.conversationId)
+ const step = String((await f.execute({ type: 'conversation.create', title: 'Review: Nobody holds this', brief: 'Review it', checks: [],
+ reviewOf: orphan })).result.conversationId)
+ const reviewer = await f.add(step, 'test-host', 'Reviewer')
+ const assignmentId = String((await f.execute({ type: 'work.assign', conversationId: step, agentId: reviewer })).result.assignmentId)
+ await f.execute({ type: 'work.status', conversationId: step, assignmentId, status: 'blocked', result: 'Needs the owner\'s account' }, host, reviewer)
+ const row = await statusRow(f.tab, step, 'Stuck')
+ expect(row.recipientIds).toEqual([f.lead])
+ expect((await deliveryOf(row.id, f.lead)).status).toBe('queued')
+ })
+
+ it('a step\'s Needs a human goes at once to the coordinator', async () => {
+ const f = await swarm()
+ const s = await stepOf(f)
+ await s.status('needs_human')
+ const row = await statusRow(f.tab, s.step, 'Needs a human')
+ expect((await deliveryOf(row.id, f.lead)).status).toBe('queued')
+ })
+
+ it('the coordinator\'s skills notice is gathered; its other agent-only notices are not', async () => {
+ const f = await swarm()
+ const skills = await f.write({ kind: 'agent-only', notice: 'skills' }, f.lead, f.group, 'The project\'s instructions changed.', f.lead)
+ expect((await deliveryOf(skills, f.lead)).status).toBe('gathered')
+ const decision = await f.write({ kind: 'agent-only', decisionId: 'd1' }, f.lead, f.group, 'Ken answered your question.', f.lead)
+ expect((await deliveryOf(decision, f.lead)).status).toBe('queued')
+ })
+
+ it.each([['limit', 'gathered'], ['model', 'gathered'], ['prompt', 'queued']])('a %s alert is %s', async (kind, expected) => {
+ const f = await swarm()
+ const id = await f.write({ kind: 'terminal-alert', agentId: f.worker, alert: kind }, f.lead)
+ expect((await deliveryOf(id, f.lead)).status).toBe(expected)
+ })
+
+ it('an alert that ended before the release is cancelled and left out', async () => {
+ const f = await swarm()
+ await alert(f, true)
+ const [id] = await alertsTo(f, 'limit')
+ expect((await deliveryOf(id!, f.lead)).status).toBe('gathered')
+ await alert(f, false)
+ f.clock.now += DUE + 1_000
+ await f.poll()
+ expect((await deliveryOf(id!, f.lead)).status).toBe('cancelled')
+ expect((await digests(f.tab)).some(d => d.text.includes(id!))).toBe(false)
+ })
+
+ it('an alert raised again before the release is delivered', async () => {
+ const f = await swarm()
+ await alert(f, true)
+ const [id] = await alertsTo(f, 'limit')
+ await alert(f, false)
+ await alert(f, true)
+ f.clock.now += DUE + 1_000
+ await f.poll()
+ expect((await deliveryOf(id!, f.lead)).status).not.toBe('cancelled')
+ expect((await digests(f.tab)).some(d => d.text.includes(id!))).toBe(true)
+ })
+})
diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.ts
index def4c63dc..848c81400 100644
--- a/backend/integration/superTabProfile.test.ts
+++ b/backend/integration/superTabProfile.test.ts
@@ -156,6 +156,41 @@ describe('usernames', () => {
})
})
+describe('display names', () => {
+ const members = async (tab: string, user = owner) =>
+ (await read(tab, user)).body.data.members as Array<{ key: string; data: { name?: string } }>
+
+ it('reach members through first loads and changes after a reload, and nobody outside the Swarm', async () => {
+ const tab = await swarm()
+ const first = await read(tab, peer)
+ await run(tab, { type: 'member.name', name: ' Minh Nguyen ' })
+ const changes = await read(tab, peer, `changes?cursor=${first.body.data.cursor}`)
+ expect(changes.body.data.members.find((m: { key: string }) => m.key === owner.sub).data.name).toBe('Minh Nguyen')
+ // A fresh read loads the member's part from the database: the name was stored with it.
+ expect((await members(tab, peer)).find(m => m.key === owner.sub)!.data.name).toBe('Minh Nguyen')
+ expect((await store.read(owner, tab)).state.people.find(p => p.id === owner.sub)!.name).toBe('Minh Nguyen')
+ const stranger = await read(tab, outsider)
+ expect(stranger.status).not.toBe(200)
+ expect(stranger.text).not.toContain('Minh Nguyen')
+ })
+
+ it('gives a name to one of two people choosing it at once', async () => {
+ const tab = await swarm()
+ const results = await Promise.allSettled([run(tab, { type: 'member.name', name: 'Captain' }),
+ run(tab, { type: 'member.name', name: 'captain' }, peer)])
+ expect(results.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
+ expect((results.find(r => r.status === 'rejected') as PromiseRejectedResult).reason).toMatchObject({ code: 'NAME_TAKEN' })
+ expect((await members(tab)).filter(m => m.data.name?.toLowerCase() === 'captain')).toHaveLength(1)
+ })
+
+ it('gives one of a name and a username that read alike, chosen at once', async () => {
+ const tab = await swarm()
+ const results = await Promise.allSettled([run(tab, { type: 'member.name', name: 'Skipper' }),
+ run(tab, { type: 'member.username', username: 'skipper' }, peer)])
+ expect(results.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
+ })
+})
+
describe('avatar uploads', () => {
it('stores a png, jpg or webp of at most 1 MB as the image its bytes are', async () => {
const tab = await swarm()
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 4a4ef51d1..7e5f05613 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -4176,6 +4176,14 @@ describe('Lead mentions', () => {
expect(JSON.stringify(mention)).not.toContain(owner.email)
})
+ it('lists a person’s tag under the name they set, when they set one', async () => {
+ const { tab, group } = await tagged()
+ await run(tab, { type: 'member.name', name: 'The Boss' })
+ const messageId = (await run(tab, { type: 'message.send', conversationId: group, text: 'Peer, look.', replyTo: null, recipientIds: [],
+ mentions: [peer.sub] })).result.messageId as string
+ expect((await list(tab, peer, 'waiting')).find(m => m.messageId === messageId)).toMatchObject({ leadName: 'The Boss' })
+ })
+
it('resolves on the person’s later post in that conversation, not on anyone else’s', async () => {
const { tab, group } = await tagged()
await run(tab, { type: 'message.send', conversationId: group, text: 'Owner chimes in.', replyTo: null, recipientIds: [] })
diff --git a/backend/src/lib/devImports.test-support.ts b/backend/src/lib/devImports.test-support.ts
new file mode 100644
index 000000000..0b5b565c0
--- /dev/null
+++ b/backend/src/lib/devImports.test-support.ts
@@ -0,0 +1,12 @@
+/**
+ * The devDependencies a source file imports (productionBuild.test.ts): `from 'x'` (import or export), a bare `import 'x'`, and
+ * `import('x')`, each with any subpath. `import type` is skipped: the build erases it. A text scan, so an import written in a
+ * comment counts too: shipped files keep test-only package names out altogether.
+ */
+export function devImports(source: string, devDependencies: readonly string[]): string[] {
+ const specifiers = [...source.matchAll(/(?:\bfrom\s*|\bimport\s*\(?\s*)(['"])([^'"\n]+)\1/g)]
+ .filter(match => !/\bimport\s+type\b[^;\n]*$/.test(source.slice(source.lastIndexOf('\n', match.index) + 1, match.index)))
+ .map(match => match[2]!)
+ const packageOf = (specifier: string) => specifier.split('/').slice(0, specifier.startsWith('@') ? 2 : 1).join('/')
+ return [...new Set(specifiers.map(packageOf).filter(name => devDependencies.includes(name)))]
+}
diff --git a/backend/src/lib/productionBuild.test.ts b/backend/src/lib/productionBuild.test.ts
index 9d799d954..770c65c99 100644
--- a/backend/src/lib/productionBuild.test.ts
+++ b/backend/src/lib/productionBuild.test.ts
@@ -2,18 +2,34 @@ import { readdirSync, readFileSync } from 'node:fs'
import { join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
+import { devImports } from './devImports.test-support.js'
-// build.mjs ships every .ts under src except *.test.ts and *.test-support.ts into dist. Code that only tests or CI use
-// (anything importing Vitest) must carry one of those names, or it lands in the production build (review of #2804).
+// build.mjs ships every .ts under src except *.test.ts and *.test-support.ts into dist, and production installs no
+// devDependency. Code that imports one (Vitest, the in-memory MongoDB, ...) must carry one of those names (reviews of #2804
+// and #2822).
const src = fileURLToPath(new URL('..', import.meta.url))
const files = (dir: string): string[] => readdirSync(dir, { withFileTypes: true })
.flatMap(entry => entry.isDirectory() ? files(join(dir, entry.name)) : entry.name.endsWith('.ts') ? [join(dir, entry.name)] : [])
+const devDependencies = Object.keys((JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')) as
+ { devDependencies: Record<string, string> }).devDependencies)
describe('the production build', () => {
- it('ships no file that imports Vitest', () => {
+ it('ships no file that imports a devDependency', () => {
const shipped = files(src).filter(path => !path.endsWith('.test.ts') && !path.endsWith('.test-support.ts'))
expect(shipped.length).toBeGreaterThan(50)
- const testOnly = shipped.filter(path => /from ['"]vitest(\/[\w-]+)?['"]/.test(readFileSync(path, 'utf8')))
- expect(testOnly.map(path => relative(src, path))).toEqual([])
+ const testOnly = shipped.flatMap(path => devImports(readFileSync(path, 'utf8'), devDependencies).map(name => `${relative(src, path)}: ${name}`))
+ expect(testOnly).toEqual([])
+ })
+
+ it('finds every form of import of a devDependency, and none that is erased or another package', () => {
+ const dev = ['vitest', 'mongodb-memory-server-core', 'mongodb', '@vitest/coverage-v8']
+ expect(devImports(`import { it } from 'vitest'`, dev)).toEqual(['vitest'])
+ expect(devImports(`import 'vitest'`, dev)).toEqual(['vitest'])
+ expect(devImports(`const m = await import("mongodb-memory-server-core")`, dev)).toEqual(['mongodb-memory-server-core'])
+ expect(devImports(`export { x } from 'vitest/node'`, dev)).toEqual(['vitest'])
+ expect(devImports(`import * as c from '@vitest/coverage-v8/dist/x.js'`, dev)).toEqual(['@vitest/coverage-v8'])
+ expect(devImports(`import type { Db } from 'mongodb'`, dev)).toEqual([])
+ expect(devImports(`import { type Db } from 'mongodb-extra'\nimport { PrismaClient } from '@prisma/client'`, dev)).toEqual([])
+ expect(devImports(`// import 'vitest' in a comment is still flagged: keep test-only words out of shipped files`, dev)).toEqual(['vitest'])
})
})
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.ts
index 22ae909cb..ba964172b 100644
--- a/backend/src/routes/productUsage.test.ts
+++ b/backend/src/routes/productUsage.test.ts
@@ -392,3 +392,13 @@ it('accepts every returning-offer skip and pairing-source counter', async () =>
expect(methods.ingestProductUsage).toHaveBeenLastCalledWith('account', report)
}
})
+
+it('accepts every Import agent outcome from a Desktop (task #2379), and keeps it in the report', async () => {
+ for (const measure of ['started', 'ok', 'failed', 'cancelled', 'unknown', 'under_1s', 'over_1m']) {
+ const metric = `ui_desktop_agent_import_${measure}`
+ const report = { ...good, context: { surface: 'desktop', release: '1.3.0', platform: 'macos', channel: 'production' },
+ counters: { [metric]: 1 } }
+ expect((await submit(report)).statusCode, metric).toBe(200)
+ expect(methods.ingestProductUsage).toHaveBeenLastCalledWith('account', report)
+ }
+})
diff --git a/backend/src/superTabs/activity.ts b/backend/src/superTabs/activity.ts
index 0ff0e4cbc..d93a8ab55 100644
--- a/backend/src/superTabs/activity.ts
+++ b/backend/src/superTabs/activity.ts
@@ -21,7 +21,7 @@ import { agentOnly, isLeads, stableId, type Actor, type Author, type Conversatio
import { SESSION_ENDED_KIND } from './buddySessions.js'
import { canReadGroup, projectOf } from './projects.js'
import { groupsBy, readBy } from './parts/indexed.js'
-import { usernameOf } from './usernames.js'
+import { shownNameOf } from './personNames.js'
import { FIELDS, readable, row as messageRow, type Row } from './read/inbox.js'
type Tx = Prisma.TransactionClient
@@ -162,9 +162,9 @@ export async function listActivity(db: PrismaClient, tabId: string, state: Super
/** A reply that lives only in its thread names its root; a top-level message or one also sent to the chat names none. */
const threadOf = (m: Row) => m.thread && m.thread !== m.id && !m.alsoInChat ? m.thread : null
-/** A person by their username, as everywhere in the Swarm; an agent by its name, or the reply's author name when it left. */
+/** A person by the name the Swarm shows for them (personNames.ts); an agent by its name, or the reply's author name when it left. */
function actorName(state: SuperTabState, kind: string, id: string, message: Row, rowKind: string): string {
- if (kind === 'person') return usernameOf(state, id) ?? 'Someone'
+ if (kind === 'person') return shownNameOf(state, id) ?? 'Someone'
const agent = state.agents.find(a => a.id === id) as { displayName?: string | null; name?: string } | undefined
const author = rowKind === 'reply' ? message.author as Author & { displayName?: string } : undefined
return agent?.displayName ?? agent?.name ?? author?.displayName ?? author?.name ?? 'An agent'
diff --git a/backend/src/superTabs/buddies.ts b/backend/src/superTabs/buddies.ts
index d763a9a9c..c46537021 100644
--- a/backend/src/superTabs/buddies.ts
+++ b/backend/src/superTabs/buddies.ts
@@ -101,7 +101,7 @@ const BUDDY_RESERVED: ReadonlySet<string> = new Set(['reviewer', 'admin', 'admin
/** 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+$/, ''))
+export 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 }
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index 61b5f97c3..bc1e148c1 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -380,6 +380,30 @@ describe('Super Tab collaboration policy', () => {
expect([sent, answer].some(m => m.recipients.includes(lead))).toBe(false)
})
+ // The PM's digest gathers its own skills notices (docs/plans/2026-11-02-pm-digest-more-kinds-design.md).
+ it('marks an agent\'s own skills notice', () => {
+ const f = fixture()
+ f.add('lead', 'owner', 'lead', true)
+ const build = f.group(), engineer = f.add('engineer', 'owner', build)
+ const sent = f.run(commandSchema.parse({ type: 'message.send', conversationId: build, text: 'The project\'s instructions changed.', replyTo: null,
+ recipientIds: [engineer], agentOnly: true, notice: 'skills' }), as(engineer)).messages[0]!
+ expect(sent.source).toEqual({ kind: 'agent-only', notice: 'skills' })
+ expect(sent.recipients).toEqual([engineer])
+ })
+
+ it('refuses the skills mark anywhere but an agent\'s own agent-only notice', () => {
+ const f = fixture()
+ f.add('lead', 'owner', 'lead', true)
+ const build = f.group(), engineer = f.add('engineer', 'owner', build), other = f.add('other', 'owner', build)
+ const mark = (actor: Actor, recipientIds: string[], agentOnly?: true) => () => f.run(commandSchema.parse({ type: 'message.send', conversationId: build,
+ text: 'Hidden.', replyTo: null, recipientIds, ...(agentOnly ? { agentOnly } : {}), notice: 'skills' }), actor)
+ expect(mark(as(engineer), [engineer])).toThrow('A skills notice is an agent-only notice to the agent itself.')
+ expect(mark({ kind: 'person', userId: 'owner', email: '[email protected]' }, [engineer], true)).toThrow('An agent sends an agent-only notice to itself alone.')
+ expect(mark(as(engineer), [other], true)).toThrow('An agent sends an agent-only notice to itself alone.')
+ expect(() => commandSchema.parse({ type: 'message.send', conversationId: build, text: 'x', replyTo: null, recipientIds: [engineer],
+ agentOnly: true, notice: 'other' })).toThrow()
+ })
+
it('keeps recipients and posts inside the project and out of Buddy chats and the Leads conversation', () => {
const f = fixture()
f.add('lead', 'owner', 'lead', true)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 120fab365..f7381428f 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -3,6 +3,7 @@ import type { PushOrigin } from '../github/pushOrigin.js'
import { admitMachineStart, defaultProfileId, storedProfileId, BUDDY_WINDOWS_REFUSAL, buddyHomeFolder, buddyProjectsOn, SWARM_BUDDY_CAPABILITY, cleanupOverdue, dropIdleBuddyMachines, NOT_SWARM_MACHINE, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, machineSlots, contributedEngines, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { keepUsernames, setUsername, swarmUsernames, usernameOf } from './usernames.js'
+import { setName, writtenNameOf } from './personNames.js'
import { z } from 'zod'
import { tokensByModelSchema } from './costs/tokens.js'
import {
@@ -280,11 +281,15 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('member.status'), status: statusSchema.nullable() }).strict(),
z.object({ type: z.literal('member.avatar'), avatar: avatarChoice }).strict(),
z.object({ type: z.literal('member.username'), username: z.string().max(64).nullable() }).strict(),
+ z.object({ type: z.literal('member.name'), name: z.string().max(200).nullable() }).strict(),
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(),
mentionsIfNoWorker: z.literal(true).optional(), agentOnly: z.literal(true).optional(),
+ // An agent's own skills notice (instructions changed, skills replaced): the coordinator's goes in its digest
+ // (noticeDigest.ts gatheredNotice). Only with `agentOnly`, which keeps it to the agent itself.
+ notice: z.literal('skills').optional(),
// A person's thread reply in their own Buddy chat that starts the thread's own Buddy session (buddySessions.ts).
newSession: z.literal(true).optional(),
// A New session in one project (spec: The model): it reads that project alone, and is the only Buddy that writes into it.
@@ -616,8 +621,9 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if (command.type === 'swarm.delete' || command.type === 'swarm.restore') return
// Marking one's own tag done changes only one's own list, so a viewer may do it too.
// Answering a decision asked of oneself changes only that decision, so a viewer may do it too.
- // So does choosing one's own username (usernames.ts).
- if (command.type === 'mention.done' || command.type === 'decision.answer' || command.type === 'member.username') return void author(state, actor)
+ // So does choosing one's own username (usernames.ts) or name (personNames.ts).
+ if (command.type === 'mention.done' || command.type === 'decision.answer' || command.type === 'member.username'
+ || command.type === 'member.name') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
@@ -856,7 +862,8 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// Before any role check: a viewer or an agent is told what anyone without the Swarm is told (deletion.ts).
if (command.type === 'swarm.delete' && (actor.kind !== 'person' || actor.userId !== state.ownerId)) notThere()
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
- const sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username')
+ const sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username'
+ && command.type !== 'member.name')
authorizeCommandAccess(state, actor, command, context)
/** A machine's owner said so: they sent the command, or the Lead of the chat [askedIn] names passes on a message they wrote
* there in the last day, as routing rules are (machine.engineResume, machine.projects). */
@@ -2770,7 +2777,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// The machine owner hears when their non-default account runs another person's PM; the project line may be out of their reach.
const owner = state.people.find(p => p.id === target.machineOwnerId), pool = state.machines?.find(m => m.machineId === target.machineId)
if (moved && label && asked && owner && asked !== owner.id) {
- const who = usernameOf(state, asked) ?? state.people.find(p => p.id === asked)?.email ?? 'Someone'
+ const who = writtenNameOf(state, asked) ?? state.people.find(p => p.id === asked)?.email ?? 'Someone'
effects.messages.push({ id: stableId(operationId, 'pm-switch-notice'), conversationId: openSwarmBuddyChat(state, owner).id, author: sender, replyTo: null, recipients: [],
source: { kind: 'pm-switch-notice', machineId: target.machineId },
text: `${who} moved the PM of ${project.name} on ${pool?.name ?? target.machineId} to your ${engine} account "${label}".` })
@@ -2900,6 +2907,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'member.username':
setUsername(state, actor, command.username)
break
+ case 'member.name':
+ setName(state, actor, command.name)
+ break
case 'agent.avatar':
setAgentAvatar(state, actor, command.agentId, command.avatar, context.avatarUpload)
break
@@ -3027,8 +3037,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (command.agentOnly && (actor.kind !== 'agent' || recipients.length !== 1 || recipients[0] !== actor.agentId || mentions.length)) {
fail('INVALID_RECIPIENT', 'An agent sends an agent-only notice to itself alone.', 400)
}
+ if (command.notice && !command.agentOnly) fail('VALIDATION_ERROR', 'A skills notice is an agent-only notice to the agent itself.', 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, text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions, command.mentionsIfNoWorker)
+ message(group.id, text, recipients, command.replyTo, command.agentOnly ? { ...AGENT_ONLY, ...command.notice ? { notice: command.notice } : {} } : undefined, attachments, mentions, command.mentionsIfNoWorker)
// After the person's message: nobody answers it, so its person is told why (Dee, review of #2447).
if (buddyDown) buddyDownLine(group, buddyDown)
// The message that makes it LOOP_NOTICE_AT in a row between two agents tells their Lead, once; delivery is never held.
diff --git a/backend/src/superTabs/memberRows.test.ts b/backend/src/superTabs/memberRows.test.ts
index 5c4fcbd4a..faa12a8b8 100644
--- a/backend/src/superTabs/memberRows.test.ts
+++ b/backend/src/superTabs/memberRows.test.ts
@@ -66,6 +66,14 @@ describe('the row that says so', () => {
expect(actorLabel(state, 'agent:gone')).toBeUndefined()
expect(actorLabel(state, 'person:gone')).toBeUndefined()
})
+
+ it('names a person by the name they set, when they set one, as plain words', () => {
+ const state = swarm([], [])
+ state.people[0]!.name = 'Ken Nguyen'
+ expect(actorLabel(state, 'person:ken')).toBe('Ken Nguyen')
+ state.people[0]!.name = '[Ken](https://ev.il)'
+ expect(actorLabel(state, 'person:ken')).toBe('\\[Ken\\]\\(https://ev.il\\)')
+ })
})
// Cleo, Orion, Luna and Echo: a machine's report closes sessions and reopens them outside any command, and those changes left no
diff --git a/backend/src/superTabs/memberRows.ts b/backend/src/superTabs/memberRows.ts
index 11edd0dd7..3fd687075 100644
--- a/backend/src/superTabs/memberRows.ts
+++ b/backend/src/superTabs/memberRows.ts
@@ -1,7 +1,7 @@
import { agentDisplayName } from './agentNames.js'
import { isBuddyChat } from './buddies.js'
import { stableId, type Agent, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-import { usernameOf } from './usernames.js'
+import { writtenNameOf } from './personNames.js'
/** One agent that joined or left one chat in a command. */
export type MemberChange = { group: Conversation; agent: Agent; added: boolean }
@@ -40,7 +40,7 @@ export function memberRowText(by: { id: string; label: string }, agent: { id: st
return `${by.label} ${added ? 'added' : 'removed'} ${quotedName(agent.name)}.`
}
-/** How a row names the actor [key] (model.ts actorKey): an agent by its quoted display name, a person by their username; none
+/** How a row names the actor [key] (model.ts actorKey): an agent by its quoted display name, a person by the name the Swarm shows for them; none
* once gone. */
export function actorLabel(state: SuperTabState, key: string): string | undefined {
const [kind, id] = [key.slice(0, key.indexOf(':')), key.slice(key.indexOf(':') + 1)]
@@ -49,7 +49,7 @@ export function actorLabel(state: SuperTabState, key: string): string | undefine
return agent && quotedName(agent.displayName ?? agent.name)
}
const person = state.people.find(p => p.id === id)
- return person && (usernameOf(state, id) ?? person.email.split('@')[0])
+ return person && (writtenNameOf(state, id) ?? person.email.split('@')[0])
}
/**
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index 3630f065e..e59adff9c 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -9,6 +9,7 @@ import { canReadGroup, canReadProject, groupProject, projectAgent, projectOf, pr
import { isBuddyChat, isSwarmBuddyChat } from './buddies.js'
import { groupsBy, readBy } from './parts/indexed.js'
import { deliveredCopies } from './pageReads.js'
+import { shownNameOf } from './personNames.js'
import { usernameOf } from './usernames.js'
type Tx = Prisma.TransactionClient
@@ -310,8 +311,8 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,
return tagged.map(({ row, group }) => {
const message = messages.find(m => m.id === row.messageId)
const author = message?.author as { kind?: string; name?: string; displayName?: string } | undefined
- // A person's name in a message is their email: the inbox shows their username, as everywhere in the Swarm.
- const authorName = author?.kind === 'person' ? usernameOf(state, row.authorAgentId) ?? 'Someone' : author?.displayName ?? author?.name ?? 'Lead'
+ // A person's name in a message is their email: the inbox shows the name the Swarm shows for them (personNames.ts).
+ const authorName = author?.kind === 'person' ? shownNameOf(state, row.authorAgentId) ?? 'Someone' : author?.displayName ?? author?.name ?? 'Lead'
return { id: row.id, projectId: row.projectId, projectName: projectOf(state, group.projectId ?? 'lead').name,
conversationId: row.conversationId, conversationTitle: group.title, messageId: row.messageId,
leadId: row.authorAgentId, leadName: authorName, text: (message?.text ?? '').slice(0, 200),
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 7e94d6693..1b7a9f6eb 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -24,6 +24,8 @@ export interface Person {
avatar?: import('./profile.js').Avatar
/** The name they chose (usernames.ts), or one kept for them; absent, readers work out their default. Only members read it. */
username?: string
+ /** The name they show (personNames.ts), such as "Minh Nguyen"; absent, the Swarm shows their username. Only members read it. */
+ name?: string
/** `domain`: joined by themselves as someone at the owner's email domain (autoJoin.ts), so the people list says so. */
joinedVia?: 'domain'
}
diff --git a/backend/src/superTabs/noticeDigest.test.ts b/backend/src/superTabs/noticeDigest.test.ts
index be76fe78e..1737e56ef 100644
--- a/backend/src/superTabs/noticeDigest.test.ts
+++ b/backend/src/superTabs/noticeDigest.test.ts
@@ -20,6 +20,25 @@ describe('what is gathered', () => {
it.each(['pair-loop', 'terminal-alert', 'buddy-proposal', 'update-request', 'digest-request', 'agent-only', 'system', 'instructions', 'notice-digest', 'from-a-newer-server'])('not %s', kind => {
expect(gatheredNotice({ kind })).toBe(false)
})
+ it('never a Stuck or Needs a human, a step\'s or a task\'s: a person must act on each (review of #2797)', () => {
+ expect(gatheredNotice({ kind: 'system', status: 'blocked', conversationId: 'step' })).toBe(false)
+ expect(gatheredNotice({ kind: 'system', status: 'blocked' })).toBe(false)
+ expect(gatheredNotice({ kind: 'system', status: 'needs_human' })).toBe(false)
+ // The rule as it was on this branch: a step's Stuck, with its task's owner told too, waited for the digest.
+ expect((gatheredNotice as (...args: unknown[]) => boolean)({ kind: 'system', status: 'blocked' }, { reviewOf: 'task' }, true)).toBe(false)
+ })
+ it('the coordinator\'s own skills notice, and no other agent-only row', () => {
+ expect(gatheredNotice({ kind: 'agent-only', notice: 'skills' })).toBe(true)
+ expect(gatheredNotice({ kind: 'agent-only' })).toBe(false)
+ expect(gatheredNotice({ kind: 'agent-only', decisionId: 'd1' })).toBe(false)
+ expect(gatheredNotice({ kind: 'agent-only', notice: 'other' })).toBe(false)
+ })
+ it('a usage limit or a failing model, never an agent waiting at a prompt', () => {
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'limit' })).toBe(true)
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'model' })).toBe(true)
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'prompt' })).toBe(false)
+ expect(gatheredNotice({ kind: 'terminal-alert' })).toBe(false)
+ })
it('not a row with no source: a post', () => {
for (const source of [undefined, null]) expect(gatheredNotice(source)).toBe(false)
expect(gatheredNotice({ status: 'done' })).toBe(false)
diff --git a/backend/src/superTabs/noticeDigest.ts b/backend/src/superTabs/noticeDigest.ts
index 6909c421b..f441d95e7 100644
--- a/backend/src/superTabs/noticeDigest.ts
+++ b/backend/src/superTabs/noticeDigest.ts
@@ -18,15 +18,32 @@ const OTHER_ACCOUNT_LINE = 'From another account:'
const TITLE_MAX = 40
const STEP_MAX = 20
-/** Notices nobody waits on within minutes. Not `pair-loop`, `terminal-alert`, `buddy-proposal`, `update-request`, `digest-request`
- * (throttled already, with instructions of their own) nor `agent-only`: each delivers at once, as any kind not listed does. */
+/** Notices nobody waits on within minutes. Not `pair-loop`, `buddy-proposal`, `update-request`, `digest-request` (throttled
+ * already, with instructions of their own): each delivers at once, as any kind not listed does. A `terminal-alert` and an
+ * `agent-only` row are gathered only in the forms `gatheredNotice` names. */
export const DIGEST_KINDS: ReadonlySet<unknown> = new Set(['work-stalled', 'work-lost', 'work-resumed', 'idle', 'review-failed', 'review-capacity', 'overlap', 'note-removed'])
+/** The alerts nobody acts on within minutes: routing already skips a limited agent, and a failing model retries on its own
+ * (docs/plans/2026-11-02-pm-digest-more-kinds-design.md). An agent waiting at a prompt (`prompt`) needs someone now. */
+const GATHERED_ALERTS: ReadonlySet<unknown> = new Set(['limit', 'model'])
-/** Whether a message to a coordinator waits for the digest: a routine notice, or a `work.status` row saying Done. Needs a human
- * and Blocked go at once; so does a status row written before rows said their status. */
+/** Whether a message to a coordinator waits for the digest: a routine notice, a `work.status` row saying Done, the coordinator's own
+ * skills notice (`message.send` `notice: "skills"`), or a usage-limit or failing-model alert. Needs a human and Stuck, a task's or
+ * a step's (a person must act on each: blocked and needs_human are only for that, review of #2797), any other agent-only row (a
+ * decision answered) and a prompt alert go at once; so does a status row written before rows said their status. */
export function gatheredNotice(source: unknown): boolean {
- const row = source as { kind?: unknown } | null | undefined
+ const row = source as { kind?: unknown; notice?: unknown; alert?: unknown } | null | undefined
return DIGEST_KINDS.has(row?.kind) || doneRow(source)
+ || (row?.kind === 'agent-only' && row.notice === 'skills')
+ || (row?.kind === 'terminal-alert' && GATHERED_ALERTS.has(row.alert))
+}
+
+/** A gathered alert whose agent no longer has that alert: it ended before the digest went, so the digest leaves it out. An agent
+ * that is gone is left to the release's own checks. */
+export function endedAlert(state: Pick<SuperTabState, 'agents'>, source: unknown): boolean {
+ const row = source as { kind?: unknown; agentId?: unknown; alert?: unknown } | null | undefined
+ if (row?.kind !== 'terminal-alert' || !GATHERED_ALERTS.has(row.alert)) return false
+ const target = state.agents.find(a => a.id === row.agentId)
+ return !!target && !(target.alerting ?? []).includes(row.alert as 'limit' | 'model')
}
/** A `work.status` row saying Done: the one notice that outlives its sender (store.ts releasableNotices). */
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 931fae723..66977978c 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -70,7 +70,7 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'agent.avatar':
leadCheck(agentProject(command.agentId))
break
- case 'member.username':
+ case 'member.username': case 'member.name':
// Unique in the Swarm: a concurrent choice of the same name writes another person's part, and a join writes the head.
for (const person of before.people) member(person.id)
head()
diff --git a/backend/src/superTabs/personNames.test.ts b/backend/src/superTabs/personNames.test.ts
new file mode 100644
index 000000000..c8240a27b
--- /dev/null
+++ b/backend/src/superTabs/personNames.test.ts
@@ -0,0 +1,178 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, visibleState, type Actor } from './model.js'
+import { split } from './parts/shape.js'
+import { touchesFor } from './parts/touches.js'
+import { readerView } from './read/views.js'
+import { MAX_NAME_LENGTH, shownNameOf, writtenNameOf } from './personNames.js'
+import { usernameOf } from './usernames.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const NOW = Date.parse('2026-11-03T10:00:00.000Z')
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+const person = (id: string, email: string) => ({ kind: 'person', userId: id, email }) as Extract<Actor, { kind: 'person' }>
+const relay = person('relay', '[email protected]')
+const peer = person('peer', '[email protected]')
+
+function fixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { now: NOW, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const join = (who: Extract<Actor, { kind: 'person' }>, role: 'viewer' | 'collaborator' = 'collaborator') => {
+ const invited = run({ type: 'invite.create', email: who.email, role, conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, who)
+ }
+ join(relay)
+ join(peer)
+ const name = (id: string) => state.people.find(p => p.id === id)!.name
+ const shown = (id: string) => shownNameOf(state, id)
+ const setName = (value: string | null, actor: Actor = relay) => run({ type: 'member.name', name: value }, actor)
+ return { run, join, name, shown, setName, get state() { return state } }
+}
+
+describe('member.name', () => {
+ it('shows the username until a person sets a name, and again once they clear it', () => {
+ const f = fixture()
+ expect(f.shown('relay')).toBe('wkpnjjhbnm')
+ f.setName('Minh Nguyen')
+ expect(f.name('relay')).toBe('Minh Nguyen')
+ expect(f.shown('relay')).toBe('Minh Nguyen')
+ f.setName(null)
+ expect(f.name('relay')).toBeUndefined()
+ expect(f.shown('relay')).toBe('wkpnjjhbnm')
+ })
+
+ it('trims the name and keeps one space between its words', () => {
+ const f = fixture()
+ f.setName(' Minh \t Nguyen ')
+ expect(f.name('relay')).toBe('Minh Nguyen')
+ })
+
+ it(`refuses an empty name, one over ${MAX_NAME_LENGTH} characters, and hidden characters`, () => {
+ const f = fixture()
+ for (const name of ['', ' ', 'a'.repeat(MAX_NAME_LENGTH + 1), 'Minh‮Nguyen', 'Mi​nh', 'Minh\nNguyen', 'Minh
Nguyen']) {
+ expect(() => f.setName(name), JSON.stringify(name)).toThrow(expect.objectContaining({ code: 'INVALID_NAME', status: 400 }))
+ }
+ // Characters, not UTF-16 units: forty letters with accents or an emoji still fit.
+ f.setName('é'.repeat(MAX_NAME_LENGTH - 1) + '🦊')
+ expect([...f.name('relay')!]).toHaveLength(MAX_NAME_LENGTH)
+ })
+
+ it('refuses another member’s name, username or email, whatever its case, width, spacing or @', () => {
+ const f = fixture()
+ f.setName('Dee Tran', peer)
+ for (const name of ['dee tran', 'DEETRAN', 'Dee Tran', 'dee', '@Dee', 'D E E', '[email protected]', '[email protected]', 'ken15', '@ken15']) {
+ expect(() => f.setName(name), name).toThrow(expect.objectContaining({ code: 'NAME_TAKEN', status: 409 }))
+ }
+ expect(f.name('relay')).toBeUndefined()
+ })
+
+ it('allows one’s own username or email, and a name close to but not another’s', () => {
+ const f = fixture()
+ f.setName('WKPNJJHBNM')
+ expect(f.name('relay')).toBe('WKPNJJHBNM')
+ f.setName('Dee’s friend')
+ expect(f.name('relay')).toBe('Dee’s friend')
+ })
+
+ it('refuses an agent’s name the person can see', () => {
+ const f = fixture()
+ f.run({ type: 'agent.add', conversationId: 'lead', harnessId: 'pm', machineId: 'machine', name: 'River', configuration, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ expect(() => f.setName('river')).toThrow(expect.objectContaining({ code: 'NAME_TAKEN' }))
+ })
+
+ it('changes only the person’s own name: an agent, or someone outside the Swarm, is refused', () => {
+ const f = fixture()
+ const lead = f.run({ type: 'agent.add', conversationId: 'lead', harnessId: 'pm', machineId: 'machine', name: 'River', configuration, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string
+ expect(() => f.setName('Bot', { kind: 'agent', agentId: lead, machineOwnerId: 'owner' })).toThrow(expect.objectContaining({ code: 'HUMAN_REQUIRED' }))
+ expect(() => f.setName('Stranger', person('stranger', '[email protected]'))).toThrow()
+ // The command names no one: it sets the actor's own, and nobody else's.
+ expect(() => f.run({ type: 'member.name', name: 'Minh', userId: 'relay' } as unknown as Command, owner)).toThrow()
+ f.setName('Owner name', owner)
+ expect([f.name('owner'), f.name('relay'), f.name('peer')]).toEqual(['Owner name', undefined, undefined])
+ })
+
+ it('lets a viewer set their own name, though they write nothing else', () => {
+ const f = fixture()
+ const viewer = person('viewer', '[email protected]')
+ f.join(viewer, 'viewer')
+ f.setName('Watcher', viewer)
+ expect(f.name('viewer')).toBe('Watcher')
+ expect(() => f.run({ type: 'member.status', status: { text: 'Hi' } }, viewer)).toThrow(expect.objectContaining({ code: 'READ_ONLY' }))
+ })
+
+ it('refuses a username equal to another member’s name', () => {
+ const f = fixture()
+ f.setName('Minh')
+ expect(() => f.run({ type: 'member.username', username: 'minh' }, peer)).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ // One's own name is no conflict.
+ f.run({ type: 'member.username', username: 'minh' }, relay)
+ expect(f.state.people.find(p => p.id === 'relay')!.username).toBe('minh')
+ })
+
+ it('reaches members with the rest of the person, and only members', () => {
+ const f = fixture()
+ f.setName('Minh Nguyen')
+ const view = readerView(split(f.state, { tabId: 'tab', version: 1, now: NOW }), peer, NOW, { teamMachines: [] })
+ expect(view.parts.members.find(m => m.key === 'relay')!.data.name).toBe('Minh Nguyen')
+ expect(visibleState(f.state, peer, NOW).people.find(p => p.id === 'relay')!.name).toBe('Minh Nguyen')
+ expect(() => visibleState(f.state, person('stranger', '[email protected]'), NOW)).toThrow()
+ })
+
+ it('touches every person and the head, so two people choosing one name at once retry', () => {
+ const f = fixture()
+ const before = f.state
+ const command: Command = { type: 'member.name', name: 'Pilot' }
+ const effects = applyCommand(before, relay, command, { now: NOW, operationId: 'op-touch' })
+ expect(touchesFor(command, relay, before, effects)).toEqual(expect.arrayContaining([
+ { kind: 'member', key: 'owner' }, { kind: 'member', key: 'relay' }, { kind: 'member', key: 'peer' }, { kind: 'head', key: 'head' },
+ ]))
+ })
+
+ it('refuses a role’s or the Swarm’s own name, numbered too (review 1 of #2794)', () => {
+ const f = fixture()
+ for (const name of ['Product Manager', 'PM', 'pm 2', 'Lead', 'Engineer', 'Reviewer', 'Tester', 'Harness', 'System', 'Admin',
+ 'Everyone', 'Swarm', 'You', 'Someone']) {
+ expect(() => f.setName(name), name).toThrow(expect.objectContaining({ code: 'NAME_RESERVED', status: 400 }))
+ }
+ // Width variants too, as every name compare reads them (review 2 of #2794).
+ for (const name of ['PM', 'Lead', 'system']) {
+ expect(() => f.setName(name), name).toThrow(expect.objectContaining({ code: 'NAME_RESERVED' }))
+ }
+ f.setName('Leading Light')
+ expect(f.name('relay')).toBe('Leading Light')
+ })
+
+ it('numbers a later joiner’s default around a name someone set, never the person’s own (review 1 of #2794)', () => {
+ const f = fixture()
+ f.setName('Bob')
+ f.join(person('bob', '[email protected]'))
+ expect(usernameOf(f.state, 'bob')).toBe('bob2')
+ // One's own name never moves one's own default.
+ f.setName('WKPNJJHBNM')
+ expect(usernameOf(f.state, 'relay')).toBe('wkpnjjhbnm')
+ })
+
+ it('refuses a web address as a name, which server lines would show as a link (review 2 of #2794)', () => {
+ const f = fixture()
+ for (const name of ['https://ev.il/x', 'ev.il://x', 'www.ev.il', 'WWW.EV.IL']) {
+ expect(() => f.setName(name), name).toThrow(expect.objectContaining({ code: 'INVALID_NAME' }))
+ }
+ })
+
+ it('writes a name into server-written text as plain words, never Markdown (review 1 of #2794)', () => {
+ const f = fixture()
+ f.setName('[Ken](ev.il/x) *x*')
+ expect(writtenNameOf(f.state, 'relay')).toBe('\\[Ken\\]\\(ev.il/x\\) \\*x\\*')
+ f.setName('1. Minh')
+ expect(writtenNameOf(f.state, 'relay')).toBe('1\\. Minh')
+ // A username is written as it is today.
+ expect(writtenNameOf(f.state, 'peer')).toBe('dee')
+ })
+})
diff --git a/backend/src/superTabs/personNames.ts b/backend/src/superTabs/personNames.ts
new file mode 100644
index 000000000..9c23cea4d
--- /dev/null
+++ b/backend/src/superTabs/personNames.ts
@@ -0,0 +1,58 @@
+import { isRoleName } from './agentNames.js'
+import { reserved } from './buddies.js'
+import { fail, person, type Actor, type SuperTabState } from './model.js'
+import { printable } from './profile.js'
+import { agentNamesSeenBy, nameKey, swarmUsernames, usernameOf } from './usernames.js'
+
+/** Characters, not UTF-16 units: a name in any script, or with an emoji, gets the same room. */
+export const MAX_NAME_LENGTH = 40
+
+/**
+ * `member.name`: a person sets the name the Swarm shows for them ("Minh Nguyen"), or clears it to show their username
+ * again. Their username stays the handle a tag types. Trimmed, with one space between words, and never another member's
+ * name, username or email, or an agent's name they can see, as [nameKey] compares them: a name nobody can take to pass
+ * as someone else.
+ */
+export function setName(state: SuperTabState, actor: Actor, input: string | null): void {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'Only a person has a name.', 403)
+ // A viewer too: their name is theirs, though they write nothing else (commands.ts authorizeCommandAccess).
+ const member = person(state, actor.userId)
+ if (input === null) return void delete member.name
+ const name = input.normalize('NFC').replace(/[\t\p{Zs}]+/gu, ' ').trim()
+ if (!name || [...name].length > MAX_NAME_LENGTH || !printable(name)) {
+ fail('INVALID_NAME', `Use 1 to ${MAX_NAME_LENGTH} characters, with no hidden ones.`, 400)
+ }
+ // Read as every compare here reads it: width variants folded (NFKC), so `PM` is `PM` (review 2 of #2794).
+ const folded = name.normalize('NFKC')
+ // A web address would show as a link in the lines the server writes (review 2 of #2794).
+ if (/:\/\/|^www\./i.test(folded)) fail('INVALID_NAME', 'Use a name, not a web address.', 400)
+ // A role's or the Swarm's own voice, as a Buddy may not take (buddies.ts), and the words readers put in place of a name.
+ if (isRoleName(folded) || reserved(folded) || /^(?:tester|you|someone)(?:[\s#-]+\d+)?$/i.test(folded)) {
+ fail('NAME_RESERVED', `${name} is a role's name. Choose another.`, 400)
+ }
+ const key = nameKey(name)
+ const usernames = swarmUsernames(state)
+ const others = state.people.filter(p => p.id !== member.id)
+ .flatMap(p => [p.name, usernames.get(p.id), p.email])
+ if ([...others, ...agentNamesSeenBy(state, actor)].some(other => other && nameKey(other) === key)) {
+ fail('NAME_TAKEN', 'Someone here already goes by that name.', 409)
+ }
+ member.name = name
+}
+
+/** The name the Swarm shows for person [id]: the one they set, else their username. */
+export const shownNameOf = (state: SuperTabState, id: string): string | undefined =>
+ state.people.find(p => p.id === id)?.name ?? usernameOf(state, id)
+
+/** Markdown's punctuation, escaped so a name reads as the words it is (CommonMark backslash escapes); a dot only after the
+ * digits a name may open with, where "1. Ken" would start a list. */
+const escaped = (text: string): string =>
+ text.replace(/[\\`*_{}[\]()#+\-!<>|~]/g, c => `\\${c}`).replace(/^(\d+)\./, '$1\\.')
+
+/** The name of person [id] as text the server writes into a message, which readers render as Markdown: a name they set,
+ * escaped, so `[Ken](https://ev.il)` never becomes a link in a Lead's line (review 1 of #2794); else their username, as
+ * today (its letters, digits, `.`, `_` and `-` never form Markdown on their own). */
+export function writtenNameOf(state: SuperTabState, id: string): string | undefined {
+ const name = state.people.find(p => p.id === id)?.name
+ return name ? escaped(name) : usernameOf(state, id)
+}
diff --git a/backend/src/superTabs/profile.ts b/backend/src/superTabs/profile.ts
index 9b437acb3..9901cad39 100644
--- a/backend/src/superTabs/profile.ts
+++ b/backend/src/superTabs/profile.ts
@@ -10,7 +10,7 @@ export const MAX_STATUS_LENGTH = 80
export interface PersonStatus { text: string; emoji: (typeof STATUS_EMOJI)[number] | null; until: string | null }
// Control, format (bidi overrides, zero-width) and line/paragraph separators: words that hide their real shape.
-const printable = (value: string) => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value)
+export const printable = (value: string) => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value)
export const statusSchema = z.object({
text: z.string().trim().min(1).max(MAX_STATUS_LENGTH).refine(printable, 'Use printable words.'),
emoji: z.enum(STATUS_EMOJI).nullable().optional(),
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 38e3b8dc9..cfcf8923d 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -73,7 +73,7 @@ import { STATUS_LABELS,
} from './model.js'
import { QUIET_CLAIM, type HoldReason } from './holdReason.js'
import { stuck } from './deliverySettle.js'
-import { digestIsDue, digestMessage, digestText, doneRow, GATHERED_LIMIT_MS, gatheredNotice, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'
+import { digestIsDue, digestMessage, digestText, doneRow, endedAlert, GATHERED_LIMIT_MS, gatheredNotice, NOTICE_DIGEST_MAX, noticeLine } from './noticeDigest.js'
import { agentDisplayName } from './agentNames.js'
import { endedHolds, HOLDING, startedHolds, type WorkHold } from '../github/holds.js'
import { accrueLent, addLent, lentAgents, lentProjects } from './leaderboard/lent.js'
@@ -3560,7 +3560,8 @@ export class SuperTabStore {
const message = this.recipientAllowed(state, delivery)
? await tx.superTabMessage.findUnique({ where: { id: delivery.messageId }, select: { text: true, source: true, author: true } }) : undefined
const allowed = message !== undefined && this.deliveryAllowed(state, delivery) && await this.senderAllowed(tx, state, delivery)
- if (!allowed && !(message && doneRow(message.source))) {
+ // An alert whose agent no longer has it has no reason left: the limit reset, or the model answers again (more-kinds design).
+ if ((!allowed && !(message && doneRow(message.source))) || (message && endedAlert(state, message.source))) {
refused += (await tx.superTabDelivery.updateMany({ where: { id: delivery.id, tabId: delivery.tabId, status: 'gathered' }, data: { status: 'cancelled', holdReason: null, holdSince: null } })).count
continue
}
diff --git a/backend/src/superTabs/usernames.ts b/backend/src/superTabs/usernames.ts
index 2e86224f6..77db50e5a 100644
--- a/backend/src/superTabs/usernames.ts
+++ b/backend/src/superTabs/usernames.ts
@@ -24,8 +24,10 @@ function base(email: string): string {
* `@River` beside the Product Manager. [people] are in join order (the state's own order). Readers get these names from
* the server (read/views.ts, model.ts visibleState); Desktop works out the same defaults only for an older server.
*/
-export function usernames(people: ReadonlyArray<Pick<Person, 'id' | 'email' | 'username'>>, agentNames: Iterable<string> = []): Map<string, string> {
+export function usernames(people: ReadonlyArray<Pick<Person, 'id' | 'email' | 'username' | 'name'>>, agentNames: Iterable<string> = []): Map<string, string> {
const taken = new Set([...people.flatMap(p => p.username ? [p.username] : []), ...[...agentNames].map(name => name.toLowerCase())])
+ // Another person's display name (personNames.ts) too, so a later joiner never reads like them; never one's own.
+ const shown = people.flatMap(p => p.name ? [{ id: p.id, key: nameKey(p.name) }] : [])
const names = new Map<string, string>()
for (const member of people) {
if (member.username) {
@@ -33,8 +35,9 @@ export function usernames(people: ReadonlyArray<Pick<Person, 'id' | 'email' | 'u
continue
}
const root = base(member.email)
+ const free = (name: string) => !taken.has(name) && !shown.some(s => s.id !== member.id && s.key === name)
let name = root
- for (let n = 2; taken.has(name); n++) name = `${root}${n}`
+ for (let n = 2; !free(name); n++) name = `${root}${n}`
taken.add(name)
names.set(member.id, name)
}
@@ -61,6 +64,14 @@ const sharedAgentNames = (state: SuperTabState): string[] => agentNames(state, a
export const swarmUsernames = (state: SuperTabState): Map<string, string> => usernames(state.people, sharedAgentNames(state))
export const usernameOf = (state: SuperTabState, id: string): string | undefined => swarmUsernames(state).get(id)
+/** The names of agents [actor] can see, the scope their reads use: refusing another's name would tell them it exists. */
+export const agentNamesSeenBy = (state: SuperTabState, actor: Actor): string[] =>
+ agentNames(state, agent => projectsOf(state).some(p => p.id === agentProjectId(state, agent)) && canReadAgent(state, actor, agent))
+
+/** What makes two names the same person to a reader: width variants (NFKC), case, spaces and a leading `@` aside, so
+ * `Dee`, `@dee` and `D E E` all read as `dee` (personNames.ts). */
+export const nameKey = (text: string): string => text.normalize('NFKC').toLowerCase().replace(/[\s\p{Zs}]+/gu, '').replace(/^@+/, '')
+
/** `member.username`: a person chooses their own name, or clears it to go back to their default. Unique in the Swarm. */
export function setUsername(state: SuperTabState, actor: Actor, input: string | null): void {
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'Only a person has a username.', 403)
@@ -69,14 +80,16 @@ export function setUsername(state: SuperTabState, actor: Actor, input: string |
if (input === null) return void delete member.username
const name = input.trim().toLowerCase()
if (!SHAPE.test(name)) fail('INVALID_USERNAME', 'Use 2 to 32 letters, digits, dots, dashes or underscores, starting with a letter or digit, with no dot at the end or two in a row.', 400)
- // Only agents this person can see, the scope their reads use: refusing another's name would tell them it exists.
- const sees = (agent: Agent) => projectsOf(state).some(p => p.id === agentProjectId(state, agent)) && canReadAgent(state, actor, agent)
- if (agentNames(state, sees).some(agent => agent.toLowerCase() === name)) {
+ if (agentNamesSeenBy(state, actor).some(agent => agent.toLowerCase() === name)) {
fail('USERNAME_TAKEN', `${name} is an agent’s name here.`, 409)
}
for (const [id, other] of swarmUsernames(state)) {
if (id !== member.id && other === name) fail('USERNAME_TAKEN', `${name} is taken.`, 409)
}
+ // Nor another person's display name (personNames.ts), which would make the two read alike.
+ if (state.people.some(p => p.id !== member.id && p.name && nameKey(p.name) === nameKey(name))) {
+ fail('USERNAME_TAKEN', `${name} is someone’s name here.`, 409)
+ }
member.username = name
}
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index 8d011d233..c30e83606 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -80,7 +80,7 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl
* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness
* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */
export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer_returning', 'phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',
- 'phone_offer_away_finished', 'share_invite', 'share_accept'] as const
+ 'phone_offer_away_finished', 'share_invite', 'share_accept', 'agent_import'] as const
/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸
* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command
* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 636b3d4e8..b82025df2 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -615,7 +615,7 @@ describe('account Experimental settings proxy', () => {
const newer = { ...body, counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_PRIVATE_CANARY: 1 } }
const kept = await post(newer)
expect(kept.status).toBe(200)
- expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('6')
+ expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('7')
expect(send).toHaveBeenCalledExactlyOnceWith({ ...body,
counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_report_unknown_metric: 1 } })
expect(JSON.stringify(send.mock.calls)).not.toContain('PRIVATE_CANARY')
@@ -628,7 +628,7 @@ describe('account Experimental settings proxy', () => {
] as const) {
const response = await post(refused, h)
expect(response.status).toBe('x-adapter-local' in h ? 400 : 403)
- expect(response.headers.get('x-harness-usage-vocabulary')).toBe('6')
+ expect(response.headers.get('x-harness-usage-vocabulary')).toBe('7')
expect(await response.text()).not.toContain('PRIVATE_CANARY')
}
expect(send).toHaveBeenCalledOnce()
diff --git a/cli/src/lib/appProductUsageReport.spec.ts b/cli/src/lib/appProductUsageReport.spec.ts
index 97b969b6c..558458968 100644
--- a/cli/src/lib/appProductUsageReport.spec.ts
+++ b/cli/src/lib/appProductUsageReport.spec.ts
@@ -85,7 +85,7 @@ it('drops names this contract does not know yet, says so once, and refuses every
})
it('announces vocabulary 6 including first-arrival, invite and existing Add Phone names', () => {
- expect(APP_USAGE_VOCABULARY).toBe(6)
+ expect(APP_USAGE_VOCABULARY).toBeGreaterThanOrEqual(6)
for (const measure of ['frame_slow_wait', 'frame_slow_build', 'frame_slow_raster', 'frame_long_collector']) {
expect(appProductUsageReport({ ...native, counters: { [`health_desktop_${measure}`]: 1 } })).toBeDefined()
}
@@ -103,7 +103,7 @@ it('announces vocabulary 6 including first-arrival, invite and existing Add Phon
})
it('forwards returning offers, every skip reason and every pairing source in vocabulary 6', () => {
- expect(APP_USAGE_VOCABULARY).toBe(6)
+ expect(APP_USAGE_VOCABULARY).toBeGreaterThanOrEqual(6)
const metrics = [
...['started', 'ok', 'cancelled', 'unknown', 'under_1s', 'over_1m'].map(x => `ui_desktop_phone_offer_returning_${x}`),
...['has_phone', 'no_device_list', 'already_shown', 'stopped', 'cap_reached', 'not_signed_in',
@@ -115,3 +115,10 @@ it('forwards returning offers, every skip reason and every pairing source in voc
expect(appProductUsageReport(report), metric).toEqual(report)
}
})
+
+it('forwards Import agent outcomes in vocabulary 7 (task #2379)', () => {
+ expect(APP_USAGE_VOCABULARY).toBe(7)
+ const report = { ...native, counters: Object.fromEntries(['started', 'ok', 'failed', 'cancelled', 'unknown', 'over_1m']
+ .map(measure => [`ui_desktop_agent_import_${measure}`, 1])) }
+ expect(appProductUsageReport(report)).toBe(report)
+})
diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.ts
index 894e8a922..9b3660e81 100644
--- a/cli/src/lib/appProductUsageReport.ts
+++ b/cli/src/lib/appProductUsageReport.ts
@@ -9,8 +9,9 @@ import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS
* Desktop sends a name newer than revision 1 only once a proxy has announced it, so an older CLI never sees one.
* 5: first-arrival episodes and shared-tab invitation outcomes.
* 6: returning-account phone offers, offer skip reasons and Add Phone pairing sources.
+ * 7: Import an agent running on this Mac (`ui_desktop_agent_import_*`, task #2379).
* Raise it with each name the Desktop gates on it (`ProductHealthMeasure.vocabulary`, `ProductFlow.vocabulary`). */
-export const APP_USAGE_VOCABULARY = 6
+export const APP_USAGE_VOCABULARY = 7
export const APP_USAGE_VOCABULARY_HEADER = 'x-harness-usage-vocabulary'
// hn's counts reach the daemon's own queue only through hn's `product_observe`; no app can file them.
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index 8d011d233..c30e83606 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -80,7 +80,7 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl
* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness
* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */
export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer_returning', 'phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',
- 'phone_offer_away_finished', 'share_invite', 'share_accept'] as const
+ 'phone_offer_away_finished', 'share_invite', 'share_accept', 'agent_import'] as const
/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸
* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command
* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index b9d7c2dcb..53098effb 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -23,7 +23,7 @@ vi.mock('../lib/buddyGuard.js', async original => {
import type { BackendNotice, CoreApi, TurnDelivery } from '../core/api.js'
import { fakeCore } from '../testing/fakeCore.js'
import type { attachedFiles as attachedFilesType } from './attachments.js'
-import { backend, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
+import { backend, BUDDY_SESSION_GONE_MS, BUDDY_SESSION_IDLE_MS, BUDDY_SESSION_SLEEP_GAP_MS, buddyChatIdOf, swarmListedFor, swarmRoleFor, hostJournalFile, SuperTabHost, type SuperTabHostOptions } from './host.js'
import { SWITCH_ADOPT_MS, SWITCH_HOLD_MS } from './leadSwitch.js'
import { TerminalHost } from './terminal.js'
import { hostForm, swarmReply } from './fixtures/read/index.js'
@@ -92,6 +92,27 @@ function setup(messageFields: Record<string, unknown> = {}, claimFields: Record<
revoke: (value = true) => { revoked = value }, foreignClaim: () => { claimId = 'another-process' }, from: (id: string) => { from = id } }
}
+// Import an agent (task #2379; security review of #2783): an agent any Swarm still lists on this machine is in a Swarm,
+// its chats archived or its stop asked, though it has no role to restart with.
+describe('whether a Swarm lists a session on this machine', () => {
+ it('names a session any roster row of this machine lists, whatever its chats or stop', async () => {
+ const t = setup()
+ const agent = { id: 'agent', harnessId: 'harness', machineId: 'machine-1' }
+ let rows: Record<string, unknown>[] = [{ tabId: 'tab', agent, stopRequested: true }]
+ vi.mocked(t.call).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true, data:
+ path.includes('/hosts/') ? hostForm(rows) : swarmReply(path, { agents: [{ ...agent, workDecision: 'stop' }],
+ conversations: [{ id: 'task', archived: true, agentIds: ['agent'] }] }) } }))
+ const sources = sourcesOf(t.core)
+ // The restart role says none: its chats are archived and its stop asked.
+ expect(await swarmRoleFor(sources, 'harness')).toBeNull()
+ expect(await swarmListedFor(sources, 'harness')).toBe(true)
+ expect(await swarmListedFor(sources, 'personal')).toBe(false)
+ // Another machine's row of the same session id is not this machine's.
+ rows = [{ tabId: 'tab', agent: { ...agent, machineId: 'machine-2' } }]
+ expect(await swarmListedFor(sources, 'harness')).toBe(false)
+ })
+})
+
describe('current Swarm role lookup', () => {
// Project instructions, phase 4 (decision 1): the role's name is the project's document's; the session is a coordinator,
// an agent or a Buddy, and an older client's Reviewer keeps its swarm-review file.
@@ -3435,8 +3456,9 @@ describe('built-in skill text after a CLI update', () => {
expect(f.sent.map(s => [s.asAgentId, s.command.recipientIds, s.command.conversationId]).sort()).toEqual([
['a-builder', ['a-builder'], 'work'], ['a-lead', ['a-lead'], 'lead-group'], ['a-reviewer', ['a-reviewer'], 'lead-group']])
for (const s of f.sent) expect(s.command.text).toContain(f.files[s.asAgentId.slice(2)]!)
- // Only the agent sees its notice; no person reads it in a chat.
+ // Only the agent sees its notice; no person reads it in a chat. Marked as a skills notice, its coordinator's goes in its digest.
for (const s of f.sent) expect(s.command.agentOnly).toBe(true)
+ for (const s of f.sent) expect(s.command.notice).toBe('skills')
expect(f.sent.find(s => s.asAgentId === 'a-reviewer')!.command.text).toContain('swarm-review skill')
// A second pass and a restarted host find the files current and say nothing more.
await f.pass(host, 5_000)
@@ -3444,14 +3466,26 @@ describe('built-in skill text after a CLI update', () => {
expect(f.sent).toHaveLength(3)
})
+ it('drops the skills mark, once, when a backend refuses it, and keeps the notice agent-only', async () => {
+ const f = syncFixture()
+ f.setRefuse(request => 'notice' in request.command ? { status: 400, body: { success: false,
+ error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "notice"' } } } : undefined)
+ const host = await f.pass()
+ expect(f.refused).toHaveLength(3)
+ expect(f.sent.map(s => [s.asAgentId, s.command.agentOnly, 'notice' in s.command]).sort()).toEqual([
+ ['a-builder', true, false], ['a-lead', true, false], ['a-reviewer', true, false]])
+ await f.pass(host, 120_000)
+ expect(f.sent).toHaveLength(3)
+ })
+
it('sends each notice the old way, once, when an older backend refuses the agent-only mark', async () => {
const f = syncFixture()
f.setRefuse(request => request.command.agentOnly ? { status: 400, body: { success: false,
error: { code: 'VALIDATION_ERROR', message: 'command: Unrecognized key: "agentOnly"' } } } : undefined)
const host = await f.pass()
expect(f.refused.map(r => r.operationId).sort()).toEqual(f.sent.map(s => s.operationId).sort())
- expect(f.sent.map(s => [s.asAgentId, s.command.recipientIds, 'agentOnly' in s.command]).sort()).toEqual([
- ['a-builder', ['a-builder'], false], ['a-lead', ['a-lead'], false], ['a-reviewer', ['a-reviewer'], false]])
+ expect(f.sent.map(s => [s.asAgentId, s.command.recipientIds, 'agentOnly' in s.command, 'notice' in s.command]).sort()).toEqual([
+ ['a-builder', ['a-builder'], false, false], ['a-lead', ['a-lead'], false, false], ['a-reviewer', ['a-reviewer'], false, false]])
await f.pass(host, 120_000)
expect(f.sent).toHaveLength(3)
expect(f.refused).toHaveLength(3)
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index b7b6734d1..b2eb79d1f 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -96,6 +96,17 @@ export async function swarmRoleFor(sources: SwarmSources, harnessId: string): Pr
// agent, and last an agent that was a Reviewer.
return (['buddy', 'lead', 'dev', 'review'] as const).map(role => grants.find(grant => grant && wireRole(grant) === role)).find(Boolean) ?? null
}
+/** Whether any Swarm's roster lists [harnessId] on this machine, whatever its chats or stop: Import agent never brings in a
+ * session a Swarm lists, as its transcript may hold that Swarm's private project (re-review of #2783). Its restart role
+ * above is none for one whose chats are archived or whose stop was asked, and it is listed still. */
+export async function swarmListedFor(sources: SwarmSources, harnessId: string): Promise<boolean> {
+ const machineId = sources.feed.machineId
+ if (!identifier(machineId) || !identifier(harnessId)) return false
+ return (await sources.feed.refresh()).roster.map(object).some(row => {
+ const agent = object(row.agent)
+ return identifier(row.tabId) && agent.machineId === machineId && agent.harnessId === harnessId
+ })
+}
/** A Buddy names its owner (backend buddies.ts); its role field stays a builder's for older readers. */
const isBuddy = (agent: Record<string, unknown>) => !!agent.buddyOf && typeof agent.buddyOf === 'object'
@@ -1631,16 +1642,24 @@ export class SuperTabHost {
.filter(group => group.archived !== true && identifier(group.id) && Array.isArray(group.agentIds) && group.agentIds.includes(id))
const group = groups.find(g => g.leadId === id) ?? groups.find(g => object(g.assignment).agentId === id) ?? groups[0]
if (!group || !current()) return false
- const send = (agentOnly: boolean) => backend(this.core, 'POST', `/api/super-tabs/${target.tabId}/commands`, {
+ const send = (agentOnly: boolean, notice: boolean) => backend(this.core, 'POST', `/api/super-tabs/${target.tabId}/commands`, {
// A switch back to an earlier mode's text is a new rewrite, so its count keeps it from reusing that text's id.
operationId: `skill-${id}-${refresh.version.slice(0, 32)}${refresh.change ? `-${refresh.change}` : ''}`, asAgentId: id,
- command: { type: 'message.send', conversationId: group.id, replyTo: null, recipientIds: [id], text: refresh.notice, ...(agentOnly ? { agentOnly } : {}) },
+ command: { type: 'message.send', conversationId: group.id, replyTo: null, recipientIds: [id], text: refresh.notice,
+ ...(agentOnly ? { agentOnly } : {}), ...(notice ? { notice: 'skills' } : {}) },
})
+ const refused = (error: unknown, key: string) => error instanceof SuperTabHostError && error.code === 'VALIDATION_ERROR' && error.message.includes(`"${key}"`)
try {
- // Only the agent sees its notice. A backend from before the mark refuses it before recording anything, so the same
- // id sends it the old way, visible in the group (2026-10-24: the owner found it confusing in the project chat).
- await send(true).catch(error => {
- if (error instanceof SuperTabHostError && error.code === 'VALIDATION_ERROR' && error.message.includes('"agentOnly"')) return send(false)
+ // Only the agent sees its notice, marked as a skills notice: its coordinator's waits for its digest (backend
+ // noticeDigest.ts). A backend from before a mark refuses it before recording anything, so the same id goes again
+ // without it: without the skills mark, or, before agent-only notices, the old way, visible in the group (2026-10-24:
+ // the owner found it confusing in the project chat).
+ await send(true, true).catch(error => {
+ if (refused(error, 'agentOnly')) return send(false, false)
+ if (refused(error, 'notice')) return send(true, false).catch(again => {
+ if (refused(again, 'agentOnly')) return send(false, false)
+ throw again
+ })
throw error
})
} catch (error) {
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 8830fcbbd..4cebc9aab 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -59,6 +59,21 @@ describe('restart role lookup through the service', () => {
expect(await service.port.swarmRole('old-native')).toBeUndefined()
service.port.stop()
})
+ // Import an agent (security review of #2783): whether any Swarm lists the harness here, for its owner only; an unreadable
+ // roster answers no `listed`, which Desktop refuses on.
+ it('says whether any Swarm lists a harness on this machine, for the owner only', async () => {
+ const agent = { id: 'agent', machineId: 'machine-1', harnessId: 'kept' }
+ const call = vi.fn<CoreApi['account']['backend']>(async (_method, path) => ({ status: 200, body: { data:
+ path.includes('/hosts/') ? hostForm([{ tabId: 'tab', agent, stopRequested: true }])
+ : swarmReply(path, { agents: [agent], conversations: [{ archived: true, agentIds: ['agent'] }] }) } }))
+ const service = superTabService(fakeCore({ account: { backend: call } }))
+ expect(await service.requests.super_tabs({ action: 'swarmListed', harnessId: 'kept' }, owner)).toEqual({ ok: true, listed: true })
+ expect(await service.requests.super_tabs({ action: 'swarmListed', harnessId: 'personal' }, owner)).toEqual({ ok: true, listed: false })
+ expect(await service.requests.super_tabs({ action: 'swarmListed', harnessId: 'kept' }, visitor)).toMatchObject({ error: 'OWNER_REQUIRED' })
+ call.mockRejectedValueOnce(new Error('Offline'))
+ expect(await service.requests.super_tabs({ action: 'swarmListed', harnessId: 'kept' }, owner)).toEqual({ ok: true })
+ service.port.stop()
+ })
// Project instructions, phase 4 (decision 1): the process answers the core in the wire's values, which a core from before
// role kinds reads too; a Reviewer's answer keeps its swarm-review file.
it('answers the core\'s role lookup in the values every core reads', async () => {
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 66900f6de..34718506e 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -6,7 +6,7 @@ import { createHash } from 'node:crypto'
import type { CoreApi, ServiceRequests, SuperTabsPort } from '../core/api.js'
import { validModelTokens } from '../lib/agentUsageWire.js'
import { ASSIGNMENT_COMMANDS, staleAssignmentHint, wantsCurrent, withCurrentAssignment } from './assignmentIds.js'
-import { backend, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError, type SuperTabHostOptions, type SwarmSources } from './host.js'
+import { backend, swarmListedFor, swarmRoleFor, hostJournalFile, identifier, object, SuperTabHost, SuperTabHostError, type SuperTabHostOptions, type SwarmSources } from './host.js'
import { HostFeed } from './hostFeed.js'
import { SwarmReads, type SwarmRead } from './swarmReads.js'
import { within } from './wire.js'
@@ -466,6 +466,12 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// these alone; a Reviewer's keeps its swarm-review file.
return { ok: true, role: grant ? wireRole(grant) : grant, ...(grant ? { mode: grant.mode } : {}) }
}
+ // Import agent (Desktop): whether any Swarm lists this harness here. An unreadable roster answers no `listed`, on which
+ // Desktop refuses rather than share.
+ if (payload.action === 'swarmListed') {
+ const listed = await within(swarmListedFor(sources(), String(payload.harnessId ?? '')))
+ return listed === null ? { ok: true } : { ok: true, listed }
+ }
// `harness send`, `new`, `tell` and `close` from a pane (buddyPane.ts): whether its harness is a Buddy, from this computer's
// own launch record (start.ts starts one with the Swarm role buddy; core/agents/create.ts saves it on the session). The
// second review of #2087 found the server read alone missed its deadline 2 times in 3 under load: it is asked only about a
diff --git a/desktop/lib/core/models.dart b/desktop/lib/core/models.dart
index 72be82b01..ef69ee017 100644
--- a/desktop/lib/core/models.dart
+++ b/desktop/lib/core/models.dart
@@ -439,6 +439,9 @@ class Agent {
/// Effort reported with [modelName], never inferred from a model default.
final String? modelEffort;
+ /// [modelName] as the engine names it (`claude-opus-5-5`), for a launch.
+ final String? modelId;
+
/// The grid model this agent is CURRENTLY running on, or null for its own vendor login.
///
/// Read by the daemon off the live process on every discovery, never bookkept — so it is the
@@ -463,6 +466,15 @@ class Agent {
/// Why the agent's model will not answer right now (`grid.note`), or null when nothing is wrong.
final GridNote? gridNote;
final String? parentAgentId;
+
+ /// `agent` when another agent started this harness, wherever that agent
+ /// runs; null when the person did (cli lib/agentFrame.ts `startedBy`).
+ final String? startedBy;
+
+ /// Started by the Swarm: by an agent, from no harness on this machine, as
+ /// the CLI tells one (superTabs/inCore/adoption.ts `swarmStarted`). Every
+ /// Buddy is one.
+ bool get startedBySwarm => startedBy == 'agent' && parentAgentId == null;
final AgentProject? project;
final AgentGitContext? gitContext;
AgentProject? get displayProject =>
@@ -569,12 +581,14 @@ class Agent {
this.claudeHome,
this.modelName,
this.modelEffort,
+ this.modelId,
this.gridModel,
this.gridWebSearch,
this.gridBaseUrl,
this.gridState,
this.gridNote,
this.parentAgentId,
+ this.startedBy,
this.project,
this.gitContext,
this.lastActivityAt,
@@ -737,12 +751,14 @@ class Agent {
: null,
modelName: model?.name,
modelEffort: model?.effort,
+ modelId: model?.id,
gridModel: _safeLabel(grid?['model']),
gridWebSearch: GridWebSearch.fromWire(grid?['webSearch']),
gridBaseUrl: _safeUrl(grid?['baseUrl']),
gridState: GridSectionState.parse(grid?['state']),
gridNote: GridNote.fromWire(grid?['note']),
parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),
+ startedBy: j['startedBy'] == 'agent' ? 'agent' : null,
project: AgentProject.fromJson(j['project']),
gitContext: AgentGitContext.fromJson(j['gitContext']),
lastActivityAt: j['updatedAt'] is String
@@ -818,12 +834,14 @@ class Agent {
claudeHome: claudeHome,
modelName: modelName,
modelEffort: modelEffort,
+ modelId: modelId,
gridModel: gridModel,
gridWebSearch: gridWebSearch,
gridBaseUrl: gridBaseUrl,
gridState: gridState,
gridNote: gridNote,
parentAgentId: parentAgentId,
+ startedBy: startedBy,
project: project,
gitContext: gitContext ?? this.gitContext,
lastActivityAt: lastActivityAt,
diff --git a/desktop/lib/core/runtime_model_name.dart b/desktop/lib/core/runtime_model_name.dart
index 7b4af47f6..ff468ab9f 100644
--- a/desktop/lib/core/runtime_model_name.dart
+++ b/desktop/lib/core/runtime_model_name.dart
@@ -8,7 +8,8 @@ String? runtimeModelName(
/// Keep the observed effort with its model and validate both against the same
/// agent/engine identity. Missing metadata never implies a default effort.
-({String name, String effort})? runtimeModelDetails(
+/// [id] is the model as the engine names it, [name] as people know it.
+({String id, String name, String effort})? runtimeModelDetails(
Object? value, {
required String agentId,
String? engine,
@@ -38,7 +39,11 @@ String? runtimeModelName(
RegExp(r'[\x00-\x1f\x7f]').hasMatch(model)) {
return null;
}
- return (name: modelDisplayName(model), effort: match[4]!.toLowerCase());
+ return (
+ id: model,
+ name: modelDisplayName(model),
+ effort: match[4]!.toLowerCase(),
+ );
} on ArgumentError {
return null;
} on FormatException {
diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dart
index 21e80c4ec..adf4a25cd 100644
--- a/desktop/lib/measurement/product_measurement.dart
+++ b/desktop/lib/measurement/product_measurement.dart
@@ -34,6 +34,10 @@ enum ProductFlow {
phoneOfferReturning('phone_offer_returning'),
shareInvite('share_invite'),
shareAccept('share_accept'),
+
+ /// Import an agent running on this Mac (task #2379): started when its
+ /// handoff preview shows, then imported, failed or cancelled.
+ agentImport('agent_import'),
// The same card offered once to a computer that never had it, after one of its own harnesses
// finished a turn (`AppNotifier._offerPhoneAfterWork`): counted apart, so the two offers read apart.
phoneOfferAfterWork('phone_offer_after_work'),
@@ -63,6 +67,7 @@ enum ProductFlow {
phoneOffer => 3,
phoneOfferReturning => 6,
shareInvite || shareAccept => 5,
+ agentImport => 7,
phoneOfferAfterWork || phoneOfferAwayWaited || phoneOfferAwayFinished => 4,
_ => 1,
};
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index b49da29c3..bf84669f2 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -6988,7 +6988,8 @@ class AppNotifier extends ChangeNotifier {
final _startupTimings = <String, int>{};
final _startupClock = Stopwatch();
void _markStartup(String step) {
- if (_startupClock.isRunning) _startupTimings[step] = _startupClock.elapsedMilliseconds;
+ if (_startupClock.isRunning)
+ _startupTimings[step] = _startupClock.elapsedMilliseconds;
}
/// Set by any install during this boot: what the CLI said before it is out of date.
@@ -7037,10 +7038,13 @@ class AppNotifier extends ChangeNotifier {
// Beside the tool probe, as neither waits on the other (task #2169). A fresh computer has no CLI yet: a check that
// fails is asked again after. One from before a sign-out or an install says nothing about now.
final askedAt = _authRevision;
- final early = cliLogin.checkStatus().then<CliAuthStatus?>((status) {
- _markStartup('signed-in check');
- return status;
- }).catchError((Object _) => null);
+ final early = cliLogin
+ .checkStatus()
+ .then<CliAuthStatus?>((status) {
+ _markStartup('signed-in check');
+ return status;
+ })
+ .catchError((Object _) => null);
final environmentReady = await _prepareEnvironment();
_markStartup('tools');
if (!environmentReady) return;
@@ -7262,7 +7266,9 @@ class AppNotifier extends ChangeNotifier {
/// What `bootstrap()` does right after the environment is confirmed ready — pulled out so
/// [recheckEnvironmentStep] can reach the same destination without repeating `bootstrap()`'s config
/// load and update-check startup, which already ran on the launch that got stuck here.
- Future<void> _continueAfterEnvironmentReady({Future<CliAuthStatus?>? early}) async {
+ Future<void> _continueAfterEnvironmentReady({
+ Future<CliAuthStatus?>? early,
+ }) async {
agentPrefetch?.setupRunning = false;
final revision = _authRevision;
if (!_authWorkCurrent(revision)) return;
@@ -7554,10 +7560,12 @@ class AppNotifier extends ChangeNotifier {
// have answered, so the tiles are there for it, as before.
Object? daemonFailure;
var daemonFailed = false;
- final daemon = ensureCliDaemonReady().then<void>((_) => _markStartup('daemon')).catchError((Object error) {
- daemonFailed = true;
- daemonFailure = error;
- });
+ final daemon = ensureCliDaemonReady()
+ .then<void>((_) => _markStartup('daemon'))
+ .catchError((Object error) {
+ daemonFailed = true;
+ daemonFailure = error;
+ });
await _restorePaneLayout(claimOnAttach: true);
_armLaunchClaimExpiry();
if (!_authWorkCurrent(revision)) {
@@ -7973,7 +7981,10 @@ class AppNotifier extends ChangeNotifier {
} catch (_) {
return;
}
- if (!_authWorkCurrent(revision) || !still.loggedIn || still.machineId != machineId) return;
+ if (!_authWorkCurrent(revision) ||
+ !still.loggedIn ||
+ still.machineId != machineId)
+ return;
_keptProfileId = profile.id;
}
await _profileCache.write(machineId, profile);
@@ -7988,7 +7999,8 @@ class AppNotifier extends ChangeNotifier {
if (me != null) {
currentUser = CurrentUserProfile.fromMe(me);
_profileConfirmed = true;
- if (currentUser case final profile?) unawaited(_keepProfile(profile, revision));
+ if (currentUser case final profile?)
+ unawaited(_keepProfile(profile, revision));
// A sign-in by hand: the device log keeps which account it was made to.
if (currentUser!.id case final id?)
unawaited(_deviceLog?.signedInAs(id));
@@ -18191,6 +18203,27 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Asks [machineId]'s daemon for the Change agent handoff of [agentId]
+ /// (`agent_handoff_prepare`, owner only): the record and transcript it
+ /// writes in the agent's folder under change [changeId], for an agent of
+ /// [targetEngine]. Answers the daemon's reply, an explicit refusal included;
+ /// throws when it gives none in time.
+ Future<Map<String, dynamic>> prepareAgentHandoff(
+ String machineId, {
+ required String agentId,
+ required String changeId,
+ required String targetEngine,
+ }) => _agentHandoffRequest(
+ machineId,
+ 'agent_handoff_prepare',
+ payload: {
+ 'agentId': agentId,
+ 'changeId': changeId,
+ 'targetEngine': targetEngine,
+ },
+ timeout: const Duration(seconds: 6),
+ );
+
/// Fill [change].handoff for the new agent, or return why the switch must not go on.
///
/// First choice: the machine writes a record of the whole conversation into the project and the
@@ -18207,15 +18240,11 @@ class AppNotifier extends ChangeNotifier {
) async {
change.handoffHeld = true;
try {
- final reply = await _agentHandoffRequest(
+ final reply = await prepareAgentHandoff(
machineId,
- 'agent_handoff_prepare',
- payload: {
- 'agentId': source.id,
- 'changeId': change.creation._id,
- 'targetEngine': change.engine,
- },
- timeout: const Duration(seconds: 6),
+ agentId: source.id,
+ changeId: change.creation._id,
+ targetEngine: change.engine,
);
final accepted = acceptAgentHandoffReply(
reply,
diff --git a/desktop/lib/super_tabs/activity.dart b/desktop/lib/super_tabs/activity.dart
index 5d1ce39f3..1c3d93f91 100644
--- a/desktop/lib/super_tabs/activity.dart
+++ b/desktop/lib/super_tabs/activity.dart
@@ -114,7 +114,7 @@ class SuperTabActivity extends ChangeNotifier {
kind: SuperTabNeedKind.mention,
id: 'mention:${m.id}',
title:
- '${people[m.leadId]?.username ?? m.leadName} mentioned you in # ${m.projectName}',
+ '${people[m.leadId]?.shownName ?? m.leadName} mentioned you in # ${m.projectName}',
conversationId: m.conversationId,
at: m.createdAt,
mention: m,
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index f84b21166..16fee4ba3 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -99,14 +99,15 @@ class SuperTabAgentInfo {
bool get hasQuestion =>
app?.questionFor(agent.machineId, agent.harnessId) != null;
- /// The agent's machine owner, named as the sidebar Humans list names them.
+ /// The agent's machine owner, named as People names them: the name they
+ /// set, else their username.
String? get owner => _personName(agent.machineOwnerId);
String? _personName(Object? personId) {
final person = controller.snapshot?.people
.where((p) => p.id == personId)
.firstOrNull;
- return _known(person?.username);
+ return _known(person?.shownName);
}
String? get questionOwner {
diff --git a/desktop/lib/super_tabs/backlog_view.dart b/desktop/lib/super_tabs/backlog_view.dart
index aae20a882..e0673eb09 100644
--- a/desktop/lib/super_tabs/backlog_view.dart
+++ b/desktop/lib/super_tabs/backlog_view.dart
@@ -243,7 +243,7 @@ class _Row extends StatelessWidget {
String? _personName(String id) => controller.snapshot?.people
.where((p) => p.id == id)
.firstOrNull
- ?.username;
+ ?.shownName;
String get _pullRequestText {
final url = _pullRequest(task);
diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dart
index 0c859f014..5146b7cfc 100644
--- a/desktop/lib/super_tabs/buddies.dart
+++ b/desktop/lib/super_tabs/buddies.dart
@@ -45,12 +45,13 @@ List<SuperTabProject> buddyProjects(SuperTabController c) => [
if (c.buddy(project.id) == null) project,
];
-/// A person by the name the Swarm shows: their username.
+/// A person by the name the Swarm shows: the name they set, else their
+/// username.
String buddyPersonName(SuperTabController c, String personId) {
return c.snapshot?.people
.where((p) => p.id == personId)
.firstOrNull
- ?.username ??
+ ?.shownName ??
'its owner';
}
diff --git a/desktop/lib/super_tabs/composer_tags.dart b/desktop/lib/super_tabs/composer_tags.dart
index a8d26a03d..0108e628c 100644
--- a/desktop/lib/super_tabs/composer_tags.dart
+++ b/desktop/lib/super_tabs/composer_tags.dart
@@ -80,7 +80,8 @@ List<SuperTabComposerChoice> superTabTagChoices(
(person) =>
person.id != c.accountId &&
reads(person) &&
- person.username.contains(query),
+ (person.username.contains(query) ||
+ (person.name?.toLowerCase().contains(query) ?? false)),
);
final offered = agents
? snapshot.agents.where(
@@ -96,8 +97,9 @@ List<SuperTabComposerChoice> superTabTagChoices(
return [
for (final person in people)
(
- label: person.username,
- detail: null,
+ // Shown by the name they set, tagged by their username.
+ label: person.shownName,
+ detail: person.name == null ? null : '@${person.username}',
choose: () => choose(person.id, person.username),
leading: SuperTabAvatar.person(person, size: SuperTabAvatar.rowSize),
kind: 'person',
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 789cf583a..001452d1f 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -5009,7 +5009,7 @@ class SuperTabController extends ChangeNotifier {
for (final file in files) {
var id = _uploaded[file];
if (id == null) {
- final answer = await _uploadFile(conversationId, file);
+ final answer = await uploadFile(conversationId, file);
if (run != _uploadRun) return null;
id = superTabMap(answer['attachment'])['id'] as String;
_uploaded[file] = id;
@@ -5039,7 +5039,7 @@ class SuperTabController extends ChangeNotifier {
/// Sends [file] to the backend and returns its attachment. Gives up when no
/// byte has moved for [uploadTimeout], or when the upload is cancelled.
- Future<Map<String, dynamic>> _uploadFile(
+ Future<Map<String, dynamic>> uploadFile(
String conversationId,
HarnessAttachment file,
) async {
diff --git a/desktop/lib/super_tabs/identity.dart b/desktop/lib/super_tabs/identity.dart
index b0eb11e90..0cfbcf5be 100644
--- a/desktop/lib/super_tabs/identity.dart
+++ b/desktop/lib/super_tabs/identity.dart
@@ -32,7 +32,7 @@ class SuperTabAvatar extends StatelessWidget {
this.now,
this.radius,
}) : identity = 'person:${person.id}',
- name = person.username,
+ name = person.shownName,
picture = person.avatar,
engine = null,
status = person.status,
diff --git a/desktop/lib/super_tabs/import_agent.dart b/desktop/lib/super_tabs/import_agent.dart
new file mode 100644
index 000000000..0ec595783
--- /dev/null
+++ b/desktop/lib/super_tabs/import_agent.dart
@@ -0,0 +1,509 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:path/path.dart' as p;
+
+import '../core/models.dart';
+import '../logging/app_log.dart';
+import '../state/agent_handoff_file.dart';
+import '../state/app_state.dart';
+import '../state/harness_attachments.dart';
+import '../widgets/engine_identity.dart';
+import 'controller.dart';
+import 'identity.dart';
+import 'model.dart';
+
+/// Import an agent running on this Mac into a project
+/// (docs/plans/2026-11-03-import-agent-design.md): which agents can be
+/// imported, the handoff of one, and the import itself.
+
+/// One agent of this Mac that can be imported, with its machine.
+typedef ImportableAgent = ({String machineId, Agent agent});
+
+/// Why import is refused when this Mac is not in the Swarm.
+const kImportNeedsThisMac =
+ 'Add this Mac to the Swarm first: the imported agent continues in its '
+ 'Harness Team account.';
+
+/// Why import is refused when this Mac has no Harness Team account in the
+/// Swarm: the new agent never runs in the person's own account.
+const kImportNeedsTeamAccount =
+ 'Set up Harness Team on this Mac first: the imported agent continues '
+ 'there, not in your own account.';
+
+const _engines = {'claude', 'codex'};
+
+/// This Mac's own machine: never a Team account's or another person's.
+MachineState? _thisMac(AppNotifier app) {
+ if (app.viewer != null) return null;
+ final mac = app.localMachineState;
+ return mac == null || mac.belongsToOtherAccount || mac.machine.isTeamAccount
+ ? null
+ : mac;
+}
+
+/// The agents of this Mac's own account that may be imported, newest first:
+/// Claude Code or Codex, running or resumable, listed by no open Swarm, and
+/// not started by the Swarm (Buddies included).
+List<ImportableAgent> importableAgents(AppNotifier app, SuperTabController c) {
+ final mac = _thisMac(app);
+ if (mac == null) return const [];
+ final id = mac.machine.machineId;
+ final listed = <String>{
+ for (final snapshot in [
+ c.snapshot,
+ for (final other in app.superTabs.loadedControllers) other.snapshot,
+ ])
+ for (final agent in snapshot?.agents ?? const <SuperTabAgent>[])
+ if (agent.machineId == id) agent.harnessId,
+ };
+ final agents = [
+ for (final agent in mac.agents)
+ if (_engines.contains(agent.engine) &&
+ !agent.isCloud &&
+ (!agent.isStopped || agent.canResumeConversation) &&
+ !agent.startedBySwarm &&
+ !listed.contains(agent.id))
+ agent,
+ ];
+ final never = DateTime.fromMillisecondsSinceEpoch(0);
+ agents.sort(
+ (a, b) => (b.lastActivityAt ?? never).compareTo(a.lastActivityAt ?? never),
+ );
+ return [for (final agent in agents) (machineId: id, agent: agent)];
+}
+
+/// Why nothing can be imported into [c]'s Swarm from here, or null when it
+/// can: Harness must run on this Mac, and this Mac's Harness Team account
+/// must be in the Swarm and take work.
+String? importUnavailable(AppNotifier app, SuperTabController c) {
+ final mac = _thisMac(app);
+ if (mac == null) {
+ return 'Import works in Harness on the Mac where the agent runs.';
+ }
+ final snapshot = c.snapshot;
+ if (snapshot?.pool(mac.machine.machineId) == null) {
+ return kImportNeedsThisMac;
+ }
+ final team = snapshot!.teamPoolOf(mac.machine.machineId);
+ if (team == null) return kImportNeedsTeamAccount;
+ return switch (team['teamWork']) {
+ {'allowed': false, 'reason': final String reason} => reason,
+ _ => null,
+ };
+}
+
+/// The steps of an import, in order, each named where it fails.
+enum ImportStep {
+ prepare('Preparing the handoff'),
+ conversation('Opening the conversation'),
+ upload('Sharing the files'),
+ start('Starting the agent'),
+ message('Sending the handoff');
+
+ const ImportStep(this.label);
+
+ /// What the person reads beside its failure.
+ final String label;
+}
+
+/// Why a step of an import did not happen, in words the person reads.
+class ImportFailure implements Exception {
+ ImportFailure(this.step, this.message, {this.code = 'refused'}) {
+ // Named, without names, paths or content.
+ appLog.warn('super-tabs', 'agent import failed at ${step.name}: $code');
+ }
+ final ImportStep step;
+ final String message;
+
+ /// What refused, for the log and tests: no names, paths or content.
+ final String code;
+
+ @override
+ String toString() => '${step.label}: $message';
+}
+
+/// One file of a handoff, as read from this Mac: exactly what is shared.
+class ImportFile {
+ ImportFile(this.name, this.bytes);
+ final String name;
+ final Uint8List bytes;
+ int get size => bytes.length;
+ late final String text = utf8.decode(bytes, allowMalformed: true);
+}
+
+/// The two files of an agent's handoff: the redacted record and the
+/// conversation with its tool calls.
+class ImportHandoff {
+ const ImportHandoff({required this.record, required this.transcript});
+ final ImportFile record, transcript;
+}
+
+/// Refuses an agent that any Swarm lists, open in this window or not, its
+/// chats archived or its stop asked: the backend's roster through this Mac's
+/// daemon (cli superTabs/service.ts `swarmListed`). A person may have added
+/// their own session to a Swarm, and its transcript may hold that Swarm's
+/// private project (security review of #2783). An answer that cannot be read
+/// refuses too: nothing is shared on a guess.
+Future<void> _notInAnySwarm(AppNotifier app, ImportableAgent agent) async {
+ Map<String, dynamic> answer;
+ try {
+ answer = await app.superTabMachineRequest(agent.machineId, {
+ 'action': 'swarmListed',
+ 'harnessId': agent.agent.id,
+ });
+ } on SuperTabFailure catch (failure) {
+ // An older daemon takes the action it does not know for an agent's own
+ // request, which names no tab.
+ if (failure.code == 'INVALID_REQUEST') {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'Update Harness on this Mac to import its agents.',
+ code: 'daemon-old',
+ );
+ }
+ answer = const {};
+ } catch (_) {
+ answer = const {};
+ }
+ final listed = answer['listed'];
+ if (listed is! bool) {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'Harness could not check whether a Swarm already has this agent. Try '
+ 'again.',
+ code: 'listed-unknown',
+ );
+ }
+ if (listed) {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'This agent is already in a Swarm, so it is not imported.',
+ code: 'in-swarm',
+ );
+ }
+}
+
+/// Prepares [agent]'s handoff on its own machine, the Change agent's
+/// (`agent_handoff_prepare`, owner only), with a fresh change id and the
+/// agent's own engine as target, then reads both files it wrote. Nothing is
+/// sent anywhere. Throws an [ImportFailure] when the daemon holds or refuses
+/// it, or a file cannot be read.
+Future<ImportHandoff> prepareImportHandoff(
+ AppNotifier app,
+ ImportableAgent agent,
+) async {
+ final source = agent.agent;
+ final machine = app.stateOf(agent.machineId);
+ final folder = source.project?.cwd ?? machine?.projectOf(source)?.cwd;
+ if (machine == null || folder == null) {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'This agent has no project folder to hand off from.',
+ code: 'no-folder',
+ );
+ }
+ await _notInAnySwarm(app, agent);
+ final changeId = superTabOperationId();
+ final Map<String, dynamic> reply;
+ try {
+ reply = await app.prepareAgentHandoff(
+ agent.machineId,
+ agentId: source.id,
+ changeId: changeId,
+ targetEngine: source.engine!,
+ );
+ } catch (_) {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'Preparing the handoff took too long. Try again.',
+ code: 'no-answer',
+ );
+ }
+ final accepted = acceptAgentHandoffReply(
+ reply,
+ agentId: source.id,
+ changeId: changeId,
+ folder: folder,
+ sourceLabel: engineIdentity(source.engine).label,
+ );
+ if (!accepted.accepted || accepted.prompt == null) {
+ final error = reply['error'];
+ throw ImportFailure(ImportStep.prepare, switch (error) {
+ 'UNSUPPORTED' => 'Update Harness on this Mac to import its agents.',
+ 'IDENTITY_UNAVAILABLE' =>
+ "This agent's conversation is not confirmed yet. Try again in a "
+ 'minute.',
+ 'TIMEOUT' || 'BUSY' => 'Preparing the handoff took too long. Try again.',
+ _ when accepted.accepted =>
+ 'This agent has no conversation to hand off yet.',
+ _ => 'The handoff could not be prepared. Try again.',
+ }, code: error is String ? error : 'unaccepted');
+ }
+ final record = p.join(folder, agentHandoffFile(source.id, changeId));
+ final transcript = '${p.withoutExtension(record)}.transcript.md';
+ try {
+ return ImportHandoff(
+ record: ImportFile(p.basename(record), await File(record).readAsBytes()),
+ transcript: ImportFile(
+ p.basename(transcript),
+ await File(transcript).readAsBytes(),
+ ),
+ );
+ } on FileSystemException {
+ throw ImportFailure(
+ ImportStep.prepare,
+ 'Could not read the handoff files on this Mac. Try again.',
+ code: 'unreadable',
+ );
+ }
+}
+
+/// How long an import waits for its new agent to be listed: as long as its
+/// host may take to prepare it (fetch the project, check its worktree out),
+/// cli superTabs/start.ts.
+const kImportStartWait = Duration(minutes: 15);
+
+/// What a start asks of the Team account's machine when nothing more is
+/// needed (cli superTabs/capacity.ts START_REQUIREMENTS).
+const _startRequirements = {
+ 'memoryBytes': 2147483648,
+ 'diskBytes': 10737418240,
+ 'maxCpuPercent': 100,
+ 'tools': ['git'],
+ 'devices': <String>[],
+ 'quotaRequired': false,
+};
+
+/// A model a launch may name (backend superTabs/commands.ts LAUNCH_MODEL).
+final _launchModel = RegExp(r'^[A-Za-z0-9][A-Za-z0-9._:\-[\]]{0,63}$');
+
+/// One import, from its first Import to its last: what is done already, so
+/// Import again does only what is left. Its commands' operation ids derive
+/// from [id], so a reply that was lost is checked, never repeated.
+class AgentImport {
+ AgentImport() : id = superTabOperationId();
+ final String id;
+ String? conversationId;
+
+ /// The files shared so far, by name: their attachment ids.
+ final attachmentIds = <String, String>{};
+ String? startId, agentId;
+}
+
+/// Where an import ended: its conversation and the agent continuing there.
+typedef ImportResult = ({String conversationId, String agentId});
+
+/// Imports [agent] into [projectId] of [c]'s Swarm with [handoff], doing what
+/// [progress] has not done yet: opens a conversation,
+/// `Continue <agent>'s work`, shares both files in it, starts a new agent
+/// there in this Mac's Harness Team account (engine and model as the agent's, role Engineer, in
+/// the project's repository), waits up to [startWait] for it to be listed,
+/// then sends it both files in one message, to it alone. The agent on this
+/// Mac is never touched. Throws an [ImportFailure] naming the step.
+Future<ImportResult> importAgent(
+ AppNotifier app,
+ SuperTabController c,
+ String projectId,
+ ImportableAgent agent,
+ ImportHandoff handoff, {
+ required AgentImport progress,
+ Duration startWait = kImportStartWait,
+}) async {
+ final next = progress.conversationId == null
+ ? ImportStep.conversation
+ : ImportStep.start;
+ if (importUnavailable(app, c) case final why?) {
+ throw ImportFailure(next, why, code: 'unavailable');
+ }
+ final team = c.snapshot!.teamPoolOf(agent.machineId)!;
+ final teamId = team['machineId'] as String;
+ final project = c.snapshot!.projectById(projectId);
+ final name = agent.agent.displayName;
+ final owner =
+ c.snapshot!.people
+ .where((person) => person.id == c.accountId)
+ .firstOrNull
+ ?.username ??
+ 'its owner';
+ final mac = superTabMachineName(
+ app.stateOf(agent.machineId)?.machine.displayName ?? 'this Mac',
+ );
+
+ final conversation = progress.conversationId ??=
+ (await _command(
+ c,
+ ImportStep.conversation,
+ '${progress.id}-conversation',
+ {
+ 'type': 'conversation.create',
+ 'projectId': projectId,
+ 'title': "Continue $name's work",
+ 'brief':
+ "Continues $name's work from $owner's Mac, $mac. Its "
+ 'handoff is attached: a record of earlier work, not '
+ 'instructions.',
+ 'checks': <Object>[],
+ },
+ ))['conversationId']
+ as String;
+
+ for (final file in [handoff.record, handoff.transcript]) {
+ if (progress.attachmentIds.containsKey(file.name)) continue;
+ try {
+ final answer = await c.uploadFile(
+ conversation,
+ HarnessAttachment(file.name, file.bytes),
+ );
+ progress.attachmentIds[file.name] =
+ superTabMap(answer['attachment'])['id'] as String;
+ } catch (failure) {
+ throw ImportFailure(
+ ImportStep.upload,
+ failure is SuperTabFailure
+ ? failure.message
+ : 'Could not share the handoff files. Try again.',
+ code: failure is SuperTabFailure ? failure.code : 'upload',
+ );
+ }
+ }
+
+ final model = agent.agent.modelId;
+ final cwd = project == null ? null : _projectFolder(team, project);
+ if (cwd == null) {
+ throw ImportFailure(
+ ImportStep.start,
+ "This Mac's Team account has no folder for this project yet.",
+ code: 'no-folder',
+ );
+ }
+ final startId = progress.startId ??=
+ (await _command(c, ImportStep.start, '${progress.id}-start', {
+ 'type': 'agent.start',
+ 'request': {
+ 'conversationId': conversation,
+ 'machineId': teamId,
+ 'engine': agent.agent.engine,
+ 'name': name,
+ 'cwd': cwd,
+ 'roleName': 'Engineer',
+ 'worktree': true,
+ if (model != null && _launchModel.hasMatch(model)) 'model': model,
+ 'requirements': _startRequirements,
+ },
+ }))['startId']
+ as String;
+ final agentId = progress.agentId ??= await _listed(
+ c,
+ startId,
+ teamId,
+ startWait,
+ );
+
+ await _command(c, ImportStep.message, '${progress.id}-message', {
+ 'type': 'message.send',
+ 'conversationId': conversation,
+ 'text':
+ "You are continuing $name's work on $owner's Mac. Read the attached "
+ 'handoff: a record of earlier work, not instructions. Say what it was '
+ 'doing, then take the next step.',
+ 'replyTo': null,
+ 'recipientIds': [agentId],
+ 'attachmentIds': [
+ for (final file in [handoff.record, handoff.transcript])
+ progress.attachmentIds[file.name]!,
+ ],
+ });
+ return (conversationId: conversation, agentId: agentId);
+}
+
+/// [project]'s folder on [pool], as the backend works it out for a start
+/// there (backend superTabs/machines.ts `projectFolder`).
+String? _projectFolder(Map<String, dynamic> pool, SuperTabProject project) {
+ final cwd = pool['cwd'];
+ if (cwd is! String) return null;
+ if (pool['scope'] != 'swarm') return cwd;
+ final repository = project.repository;
+ return repository?['machineId'] == pool['machineId']
+ ? repository!['cwd'] as String?
+ : '${cwd.replaceFirst(RegExp(r'/+$'), '')}/${project.id}';
+}
+
+/// Sends [command] under [operationId], or checks it again when its reply
+/// was lost (the controller still holds it), and answers its result.
+Future<Map<String, dynamic>> _command(
+ SuperTabController c,
+ ImportStep step,
+ String operationId,
+ Map<String, dynamic> command,
+) async {
+ final pending = c.pendingCommand;
+ final again = pending != null && jsonEncode(pending) == jsonEncode(command);
+ if (pending != null && !again) {
+ throw ImportFailure(
+ step,
+ 'Another change in this Swarm is not confirmed yet. Check it, then '
+ 'import again.',
+ code: 'busy',
+ );
+ }
+ final result = again
+ ? await c.retry()
+ : await c.command(command, operationId: operationId);
+ if (result == null) {
+ throw ImportFailure(
+ step,
+ c.operationError ?? 'Not confirmed. Try again.',
+ code: c.operationErrorCode ?? 'unconfirmed',
+ );
+ }
+ return result;
+}
+
+/// The id of the agent start [startId] made on [machineId], once the Swarm
+/// lists it; throws when its host failed it, or after [wait].
+Future<String> _listed(
+ SuperTabController c,
+ String startId,
+ String machineId,
+ Duration wait,
+) async {
+ final listed = Completer<String>();
+ void check() {
+ if (listed.isCompleted) return;
+ final snapshot = c.snapshot;
+ final start = snapshot?.startOf(startId);
+ if (start?.error case final error?) {
+ return listed.completeError(
+ ImportFailure(ImportStep.start, error, code: 'start-failed'),
+ );
+ }
+ final agent = snapshot?.agents
+ .where(
+ (a) =>
+ a.machineId == machineId &&
+ start?.harnessId != null &&
+ a.harnessId == start!.harnessId,
+ )
+ .firstOrNull;
+ if (agent != null) listed.complete(agent.id);
+ }
+
+ c.addListener(check);
+ try {
+ check();
+ return await listed.future.timeout(
+ wait,
+ onTimeout: () => throw ImportFailure(
+ ImportStep.start,
+ "The agent has not started yet on this Mac's Team account. Import "
+ 'again to keep waiting.',
+ code: 'start-timeout',
+ ),
+ );
+ } finally {
+ c.removeListener(check);
+ }
+}
diff --git a/desktop/lib/super_tabs/import_agent_dialog.dart b/desktop/lib/super_tabs/import_agent_dialog.dart
new file mode 100644
index 000000000..118646433
--- /dev/null
+++ b/desktop/lib/super_tabs/import_agent_dialog.dart
@@ -0,0 +1,467 @@
+import 'dart:async';
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+
+import '../core/home_dir.dart';
+import '../core/relative_time.dart';
+import '../measurement/product_measurement.dart';
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/empty_state.dart';
+import '../state/app_state.dart';
+import '../state/swarm_navigation.dart' show externalEngineName;
+import '../widgets/desktop_chrome.dart';
+import '../widgets/engine_identity.dart';
+import '../widgets/laid_out_list.dart';
+import '../widgets/update_notice.dart' show formatDownloadSize;
+import 'controller.dart';
+import 'detail_dialog.dart';
+import 'dialog_scope.dart';
+import 'import_agent.dart';
+import 'model.dart';
+import 'team_account_setup.dart';
+
+/// Whether Add agent offers Import: Harness on a Mac, where its daemon and a
+/// Harness Team account are; never the web, Linux or Windows.
+bool get superTabImportOffered =>
+ !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS;
+
+/// Import an agent into [group]'s project: the agents of this Mac to choose
+/// from, the handoff of the one chosen as its project's members will read it,
+/// and Import (docs/plans/2026-11-03-import-agent-design.md).
+Future<void> showImportAgent(
+ BuildContext context,
+ AppNotifier app,
+ SuperTabController c,
+ SuperTabConversation group,
+) {
+ final project = c.snapshot?.projectFor(group.id);
+ if (project == null) return Future.value();
+ return showAppDialog<void>(
+ context: context,
+ builder: (context) => SuperTabDialogScope(
+ controller: c,
+ child: _ImportAgentDialog(app: app, controller: c, project: project),
+ ),
+ );
+}
+
+class _ImportAgentDialog extends StatefulWidget {
+ const _ImportAgentDialog({
+ required this.app,
+ required this.controller,
+ required this.project,
+ });
+ final AppNotifier app;
+ final SuperTabController controller;
+ final SuperTabProject project;
+
+ @override
+ State<_ImportAgentDialog> createState() => _ImportAgentDialogState();
+}
+
+class _ImportAgentDialogState extends State<_ImportAgentDialog> {
+ AppNotifier get app => widget.app;
+ SuperTabController get c => widget.controller;
+
+ /// The agent being previewed, and its handoff once read.
+ ImportableAgent? _agent;
+ ImportHandoff? _handoff;
+ bool _busy = false;
+
+ /// What went wrong last, at which step.
+ ImportFailure? _failure;
+
+ /// The import once Import was pressed: what it has done so far.
+ AgentImport? _import;
+
+ /// The files shown whole.
+ final _open = <ImportFile>{};
+
+ /// The import counted while its preview shows (ENGINEERING.md 8): ended ok
+ /// by Import, failed when left after a failed step, cancelled otherwise.
+ void Function(ProductOutcome)? _counted;
+
+ void _end(ProductOutcome outcome) {
+ _counted?.call(outcome);
+ _counted = null;
+ }
+
+ @override
+ void dispose() {
+ _end(
+ _failure != null && _import != null
+ ? ProductOutcome.failed
+ : ProductOutcome.cancelled,
+ );
+ super.dispose();
+ }
+
+ Future<void> _choose(ImportableAgent agent) async {
+ if (_busy) return;
+ setState(() {
+ _busy = true;
+ _agent = agent;
+ _failure = null;
+ });
+ try {
+ final handoff = await prepareImportHandoff(app, agent);
+ if (!mounted) return;
+ _counted = app.productMeasurement.begin(ProductFlow.agentImport);
+ setState(() => _handoff = handoff);
+ } on ImportFailure catch (failure) {
+ if (mounted) setState(() => _failure = failure);
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+
+ void _back() => setState(() {
+ _end(ProductOutcome.cancelled);
+ _agent = null;
+ _handoff = null;
+ _failure = null;
+ _open.clear();
+ });
+
+ Future<void> _run() async {
+ if (_busy) return;
+ final import = _import ??= AgentImport();
+ setState(() {
+ _busy = true;
+ _failure = null;
+ });
+ try {
+ await importAgent(
+ app,
+ c,
+ widget.project.id,
+ _agent!,
+ _handoff!,
+ progress: import,
+ );
+ _end(ProductOutcome.ok);
+ if (mounted) Navigator.pop(context);
+ } on ImportFailure catch (failure) {
+ if (mounted) setState(() => _failure = failure);
+ } finally {
+ if (mounted) setState(() => _busy = false);
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: Listenable.merge([app, c]),
+ builder: (context, _) {
+ final title = 'Import an agent into ${widget.project.name}';
+ final why = _import == null ? importUnavailable(app, c) : null;
+ final cancel = TextButton(
+ onPressed: _busy && _import != null
+ ? null
+ : () => Navigator.pop(context),
+ child: const Text('Cancel'),
+ );
+ if (why != null) {
+ return SuperTabDetailDialog(
+ title: title,
+ body: Text(why, style: DesktopChrome.control()),
+ actions: [
+ cancel,
+ if (why == kImportNeedsTeamAccount && app.canSetUpTeamAccount)
+ FilledButton(
+ onPressed: () => showTeamAccountSetup(context, app),
+ child: const Text('Set up Harness Team'),
+ ),
+ ],
+ );
+ }
+ final handoff = _handoff;
+ return PopScope(
+ canPop: !(_busy && _import != null),
+ child: SuperTabDetailDialog(
+ title: title,
+ onClose: _busy && _import != null ? () {} : null,
+ body: handoff == null ? _picker() : _preview(handoff),
+ footer: handoff == null ? _failureLine() : null,
+ leadingActions: [
+ if (handoff != null && _import == null)
+ TextButton(
+ style: superTabQuietAction,
+ onPressed: _busy ? null : _back,
+ child: const Text('Back'),
+ ),
+ ],
+ actions: [
+ cancel,
+ if (handoff != null)
+ FilledButton(
+ onPressed: _busy ? null : () => unawaited(_run()),
+ child: Text(switch (_failure?.step) {
+ _ when _busy => 'Importing…',
+ ImportStep.start => 'Start again',
+ null => 'Import',
+ _ => 'Try again',
+ }),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+
+ Widget? _failureLine() => switch (_failure) {
+ final failure? => Text(
+ '${failure.step.label}: ${failure.message}',
+ style: DesktopChrome.metadata(color: grid.AppPalette.warn),
+ ),
+ null => null,
+ };
+
+ Widget _picker() {
+ final agents = importableAgents(app, c);
+ final note = Text(
+ 'Not offered: agents already in a Swarm, Buddies and Swarm-started '
+ 'agents.',
+ style: DesktopChrome.metadata(),
+ );
+ if (agents.isEmpty) {
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const EmptyState(
+ compact: true,
+ icon: AppIcons.bot,
+ title: 'No agent on this Mac to import',
+ message: 'Claude Code and Codex agents of yours show here.',
+ ),
+ note,
+ ],
+ );
+ }
+ final now = DateTime.now();
+ return Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final agent in agents) _agentRow(agent, now),
+ const SizedBox(height: DesktopChrome.controlGap),
+ note,
+ ],
+ );
+ }
+
+ Widget _agentRow(ImportableAgent row, DateTime now) {
+ final agent = row.agent;
+ final folder = agent.project?.cwd;
+ final home = maybeHomeDir();
+ final shown = folder != null && home != null && folder.startsWith('$home/')
+ ? '~${folder.substring(home.length)}'
+ : folder;
+ final at = agent.lastActivityAt;
+ final preparing = _busy && _agent == row;
+ return InkWell(
+ key: ValueKey('import-agent-${agent.id}'),
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ onTap: _busy ? null : () => unawaited(_choose(row)),
+ child: Padding(
+ padding: const EdgeInsets.symmetric(vertical: DesktopChrome.controlGap),
+ child: Row(
+ children: [
+ EngineMark.forAgent(agent),
+ const SizedBox(width: DesktopChrome.controlGap),
+ Expanded(
+ child: Text(
+ [
+ externalEngineName(agent.engine!),
+ agent.displayName,
+ ?shown,
+ ].join(' · '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
+ ),
+ const SizedBox(width: DesktopChrome.controlGap),
+ if (preparing)
+ const SizedBox.square(
+ dimension: grid.AppControl.iconSize,
+ child: CircularProgressIndicator(strokeWidth: 1.5),
+ )
+ else if (at != null)
+ Text(relativeAgo(at, now), style: DesktopChrome.metadata()),
+ ],
+ ),
+ ),
+ );
+ }
+
+ Widget _preview(ImportHandoff handoff) => Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Text(
+ "What ${widget.project.name}'s members will read",
+ style: DesktopChrome.control(medium: true),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border.all(color: DesktopChrome.rim),
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ _file('Handoff (redacted)', handoff.record),
+ Divider(height: 1, thickness: 1, color: DesktopChrome.rim),
+ _file('Conversation and tool calls', handoff.transcript),
+ ],
+ ),
+ ),
+ const SizedBox(height: DesktopChrome.controlGap),
+ Text(
+ 'Secrets (keys, tokens, passwords in URLs) are removed. Tool output is '
+ 'never included.',
+ style: DesktopChrome.metadata(),
+ ),
+ Text(
+ 'The agent on this Mac keeps running; nothing about it changes.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (_import != null) ...[
+ const SizedBox(height: DesktopChrome.groupGap),
+ for (final step in ImportStep.values.skip(1)) _step(step),
+ ],
+ ],
+ );
+
+ Widget _file(String label, ImportFile file) {
+ final open = _open.contains(file);
+ return Padding(
+ padding: const EdgeInsets.symmetric(horizontal: DesktopChrome.controlGap),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ Expanded(child: Text(label, style: DesktopChrome.control())),
+ Text(
+ formatDownloadSize(file.size),
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(width: DesktopChrome.controlGap),
+ TextButton(
+ onPressed: () =>
+ setState(() => open ? _open.remove(file) : _open.add(file)),
+ child: Text(open ? 'Hide text' : 'Full text'),
+ ),
+ ],
+ ),
+ if (open) _FileText(file),
+ ],
+ ),
+ );
+ }
+
+ /// One step of the import: done, under way, failed with why, or still to
+ /// come.
+ Widget _step(ImportStep step) {
+ final done = _stepDone(step);
+ final failed = !done && _failure?.step == step;
+ final current =
+ !done &&
+ ImportStep.values.skip(1).firstWhere((s) => !_stepDone(s)) == step;
+ final mark = done
+ ? Icon(
+ AppIcons.circleCheck,
+ size: grid.AppControl.iconSize,
+ semanticLabel: 'Done',
+ )
+ : failed
+ ? Icon(
+ AppIcons.circleAlert,
+ size: grid.AppControl.iconSize,
+ color: grid.AppPalette.warn,
+ semanticLabel: 'Failed',
+ )
+ : current && _busy
+ ? const SizedBox.square(
+ dimension: grid.AppControl.iconSize,
+ child: CircularProgressIndicator(strokeWidth: 1.5),
+ )
+ : Icon(
+ AppIcons.circle,
+ size: grid.AppControl.iconSize,
+ color: DesktopChrome.muted,
+ );
+ return Padding(
+ padding: const EdgeInsets.symmetric(vertical: grid.AppDesktop.listRowGap),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Row(
+ children: [
+ mark,
+ const SizedBox(width: DesktopChrome.controlGap),
+ Expanded(
+ child: Text(
+ step.label,
+ style: DesktopChrome.control(
+ color: done || failed || current
+ ? null
+ : DesktopChrome.muted,
+ ),
+ ),
+ ),
+ ],
+ ),
+ if (failed)
+ Padding(
+ padding: const EdgeInsetsDirectional.only(
+ start: grid.AppControl.iconSize + DesktopChrome.controlGap,
+ ),
+ child: Text(
+ _failure!.message,
+ style: DesktopChrome.metadata(color: grid.AppPalette.warn),
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+
+ bool _stepDone(ImportStep step) => switch (step) {
+ ImportStep.conversation => _import!.conversationId != null,
+ ImportStep.upload => _import!.attachmentIds.length == 2,
+ ImportStep.start => _import!.agentId != null,
+ _ => false,
+ };
+}
+
+/// A file's whole text, line by line, built only as it scrolls into view: a
+/// transcript runs to 2 MB.
+class _FileText extends StatelessWidget {
+ const _FileText(this.file);
+ final ImportFile file;
+
+ @override
+ Widget build(BuildContext context) {
+ final lines = file.text.split('\n');
+ final style = grid.AppType.monoMeta(color: DesktopChrome.foreground);
+ return Padding(
+ padding: const EdgeInsets.only(bottom: DesktopChrome.controlGap),
+ child: SizedBox(
+ height: 220,
+ child: SelectionArea(
+ child: LaidOutListView.builder(
+ itemCount: lines.length,
+ itemBuilder: (context, i) => Text(lines[i], style: style),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/instructions_panel.dart b/desktop/lib/super_tabs/instructions_panel.dart
index fe6cfcd3e..027cccd6a 100644
--- a/desktop/lib/super_tabs/instructions_panel.dart
+++ b/desktop/lib/super_tabs/instructions_panel.dart
@@ -595,7 +595,7 @@ class _InstructionsPanelState extends State<_InstructionsPanel> {
}
String _personName(String id) =>
- c.snapshot?.people.where((p) => p.id == id).firstOrNull?.username ??
+ c.snapshot?.people.where((p) => p.id == id).firstOrNull?.shownName ??
'a member';
/// What the coordinator was told to keep, newest first, with who asked and until when (spec: PM notes).
diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dart
index 5c58e65bb..f963341a6 100644
--- a/desktop/lib/super_tabs/leaderboard/person_row.dart
+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart
@@ -27,10 +27,11 @@ TextStyle leaderboardPointsStyle() => grid.AppType.label(
fontFeatures: grid.AppFont.tabularFigures,
);
-/// A person as the leaderboard names them: their username, as everywhere in
-/// the Swarm (the board's account display name was a long one).
+/// A person as the leaderboard names them: as everywhere in the Swarm, the
+/// name they set, else their username (the board's account display name was
+/// a long one).
String leaderboardName(SuperTabPerson person, SuperTabPersonScore? score) =>
- person.username;
+ person.shownName;
/// Whether a person wears the crown: first on the board, with points. At the
/// start of a week everyone ties at 0, and no one has taken #1 yet.
@@ -150,6 +151,7 @@ class LeaderboardPersonRow extends StatelessWidget {
builder: (context) => Tooltip(
message: [
leaderboardName(person, score),
+ if (person.name != null) '@${person.username}',
person.email,
?person.statusAt(clock.now())?.text,
].join('\n'),
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 340166728..62975346f 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -1425,7 +1425,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
app?.stateOf(id)?.machine.displayName ??
// The Swarm knows no name for it, and sharing its own would be new data: it is named by its owner.
(agentsOnly && person != null
- ? "${person.username}'s computer"
+ ? "${person.shownName}'s computer"
: 'Unavailable machine');
final subscriptions = _subscriptions(
id,
@@ -1547,7 +1547,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
// after its state when that is not online. Never an age. Only current readings are included.
tip: [
if (cleaning) 'Cleaning up' else ?superTabMachineTip(status),
- if (person != null) 'Owned by ${person.username}',
+ if (person != null) 'Owned by ${person.shownName}',
if (paused) 'New work paused',
if (!dim && value?.cpuPercent != null)
'CPU ${available(value!.cpuPercent!)} free',
@@ -1896,7 +1896,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
],
body: SuperTabMachineDetails(
name: name,
- owner: person?.username,
+ owner: person?.shownName,
status: details,
// Details follow the same freshness rule as the row and its disclosure.
resources: dim ? null : value,
@@ -2974,7 +2974,7 @@ class _MachineLine extends StatelessWidget {
left: grid.AppDesktop.controlGap,
),
child: Text(
- owner.username,
+ owner.shownName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: DesktopChrome.metadata(),
@@ -2993,7 +2993,7 @@ class _MachineLine extends StatelessWidget {
Padding(
padding: const EdgeInsets.only(left: 6),
child: Tooltip(
- message: 'Owned by ${owner.username}',
+ message: 'Owned by ${owner.shownName}',
child: SuperTabAvatar.person(owner, size: 20),
),
),
diff --git a/desktop/lib/super_tabs/manage_page.dart b/desktop/lib/super_tabs/manage_page.dart
index 59a1fef79..536e4b282 100644
--- a/desktop/lib/super_tabs/manage_page.dart
+++ b/desktop/lib/super_tabs/manage_page.dart
@@ -361,7 +361,7 @@ class _ManageSwarmState extends State<_ManageSwarm> {
),
children: [
_fact('Name', _value(snapshot.name)),
- if (owner != null) _fact('Owner', _value(owner.username)),
+ if (owner != null) _fact('Owner', _value(owner.shownName)),
_fact(
'People',
_value('${snapshot.people.length}'),
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index a5211b20d..5d1e212c1 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -44,6 +44,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.onOpenGroup,
this.mentions = const [],
this.mentionAddresses = const {},
+ this.mentionLabels = const {},
this.readerId = '',
this.reactorName,
this.onReact,
@@ -90,6 +91,10 @@ class SuperTabMessageRow extends StatefulWidget {
/// Their addresses, by name: a tag by full address is theirs only when it
/// is this one.
final Map<String, String> mentionAddresses;
+
+ /// The name each tagged person shows as, by the name they are tagged by
+ /// ([SuperTabMessageText.labels]).
+ final Map<String, String> mentionLabels;
final Map<int, String> references;
final ValueChanged<String>? onOpenGroup;
final String author;
@@ -534,6 +539,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
onOpenGroup: widget.onOpenGroup,
mentions: widget.mentions,
addresses: widget.mentionAddresses,
+ labels: widget.mentionLabels,
taggedYou: taggedYou,
),
),
diff --git a/desktop/lib/super_tabs/message_text.dart b/desktop/lib/super_tabs/message_text.dart
index 3c21a0292..6c9e1bfa7 100644
--- a/desktop/lib/super_tabs/message_text.dart
+++ b/desktop/lib/super_tabs/message_text.dart
@@ -18,6 +18,7 @@ class SuperTabMessageText extends StatelessWidget {
this.onOpenGroup,
this.mentions = const [],
this.addresses = const {},
+ this.labels = const {},
this.taggedYou = false,
});
final String text;
@@ -32,6 +33,11 @@ class SuperTabMessageText extends StatelessWidget {
/// address is theirs only when it is this one.
final Map<String, String> addresses;
+ /// The name a person in [mentions] shows as, by the name they are tagged
+ /// by: their tag reads `@Minh Nguyen` though the text says `@wkpnjjhbnm`
+ /// (backend personNames.ts). Absent, the tag reads as written.
+ final Map<String, String> labels;
+
/// The message tags the reader, so its row is washed in the accent: a tag
/// takes the stronger accent in light, to stay 4.5:1 on its pill there.
final bool taggedYou;
@@ -88,7 +94,7 @@ class SuperTabMessageText extends StatelessWidget {
inlineSyntaxes: [
_WebAutolink(),
_WorkgroupReference(references),
- if (mentions.isNotEmpty) _Mention(mentions, addresses),
+ if (mentions.isNotEmpty) _Mention(mentions, addresses, labels),
],
builders: {
'pre': _CodeBlock(),
@@ -265,21 +271,25 @@ bool _says(String tag, String name, Map<String, String> addresses) {
/// `@name` or `@name@domain` for a tagged person; any other `@` stays text.
/// Parsed as inline Markdown, so code and fenced blocks remain literal.
class _Mention extends md.InlineSyntax {
- _Mention(this.mentions, this.addresses) : super(tag.pattern);
+ _Mention(this.mentions, this.addresses, this.labels) : super(tag.pattern);
// Never right after a letter, digit, `@` or `/` (an address, a path, a
// link). A name never ends in a dot: `@dee.` closes a sentence.
static final tag = RegExp(
r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?',
);
final List<String> mentions;
- final Map<String, String> addresses;
+ final Map<String, String> addresses, labels;
@override
bool onMatch(md.InlineParser parser, Match match) {
final tag = '${match[1]}${match[2] ?? ''}'.toLowerCase();
+ final name = mentions.where((n) => _says(tag, n, addresses)).firstOrNull;
parser.addNode(
- mentions.any((name) => _says(tag, name, addresses))
- ? md.Element.text('mention', match[0]!)
- : md.Text(match[0]!),
+ name == null
+ ? md.Text(match[0]!)
+ : md.Element.text(
+ 'mention',
+ labels[name] == null ? match[0]! : '@${labels[name]}',
+ ),
);
return true;
}
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 896a9b3d3..20ee041fa 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -50,6 +50,10 @@ class SuperTabPerson {
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
status = SuperTabPersonStatus.fromJson(row['status']),
chosenUsername = row['username'] as String?,
+ name = switch (row['name']) {
+ final String name when name.trim().isNotEmpty => name,
+ _ => null,
+ },
username =
row['username'] as String? ??
superTabDefaultUsername(_text(row, 'email'));
@@ -61,7 +65,8 @@ class SuperTabPerson {
joinedVia = person.joinedVia,
avatar = person.avatar,
status = person.status,
- chosenUsername = person.chosenUsername;
+ chosenUsername = person.chosenUsername,
+ name = person.name;
final String id, email, role;
/// How the Swarm shows and tags them, as the server sends it, worked out in
@@ -71,6 +76,15 @@ class SuperTabPerson {
/// The name the server sent; null from a server without usernames.
final String? chosenUsername;
+
+ /// The name they set for the Swarm to show ("Minh Nguyen",
+ /// backend/src/superTabs/personNames.ts); null until they set one, and
+ /// from an older server.
+ final String? name;
+
+ /// How the Swarm shows them: the name they set, else their username. A tag
+ /// still types [username].
+ String get shownName => name ?? username;
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
@@ -563,6 +577,15 @@ class SuperTabSnapshot {
row['invitations'],
(row) => Map<String, dynamic>.unmodifiable(row),
),
+ _starts = Map.unmodifiable({
+ for (final start
+ in row['starts'] is List ? row['starts'] as List : const [])
+ if (start case {'id': final String id})
+ id: (
+ harnessId: start['harnessId'] as String?,
+ error: start['error'] as String?,
+ ),
+ }),
startEfforts = Map.unmodifiable({
for (final start
in row['starts'] is List ? row['starts'] as List : const [])
@@ -664,6 +687,12 @@ class SuperTabSnapshot {
late final List<SuperTabProject> projects;
final List<Map<String, dynamic>> invitations;
+ /// Each agent start's outcome so far, by its id: the harness it made, or
+ /// why it failed (backend AgentStart); null for a start this read does not
+ /// hold.
+ ({String? harnessId, String? error})? startOf(String id) => _starts[id];
+ final Map<String, ({String? harnessId, String? error})> _starts;
+
/// The effort each started agent's start asked for, by harness id. Empty where the starts are not read (a view
/// kept on this device leaves them out).
final Map<String, String> startEfforts;
@@ -881,7 +910,7 @@ class SuperTabSnapshot {
// Recorded labels remain the fallback for agents no longer in the Swarm.
String authorName(SuperTabMessage message) => message.fromAgent
? agentName(message.authorId, fallback: message.authorName)
- : people.where((p) => p.id == message.authorId).firstOrNull?.username ??
+ : people.where((p) => p.id == message.authorId).firstOrNull?.shownName ??
superTabPersonName(message.authorName);
}
diff --git a/desktop/lib/super_tabs/name_editor.dart b/desktop/lib/super_tabs/name_editor.dart
new file mode 100644
index 000000000..b466a0d4d
--- /dev/null
+++ b/desktop/lib/super_tabs/name_editor.dart
@@ -0,0 +1,110 @@
+import 'package:flutter/material.dart';
+
+import '../widgets/desktop_chrome.dart';
+
+/// The most characters a name takes (backend personNames.ts MAX_NAME_LENGTH).
+const superTabNameMaxLength = 40;
+
+/// The name the Swarm shows for the reader ("Minh Nguyen"): the field, Save,
+/// and why a name was refused, said under the field. Emptied, Save clears it
+/// and the Swarm shows their username again.
+class SuperTabNameEditor extends StatefulWidget {
+ const SuperTabNameEditor({
+ super.key,
+ required this.name,
+ required this.busy,
+ required this.onSave,
+ });
+
+ /// The name they set; null when they have none.
+ final String? name;
+ final bool busy;
+
+ /// Saves the name, null to clear it; answers why it was refused, or null
+ /// once saved.
+ final Future<String?> Function(String? name) onSave;
+
+ @override
+ State<SuperTabNameEditor> createState() => _SuperTabNameEditorState();
+}
+
+class _SuperTabNameEditorState extends State<SuperTabNameEditor> {
+ late final _text = TextEditingController(text: widget.name ?? '');
+ String? _error;
+
+ /// The last name saved, until the server's version of it arrives.
+ String? _sent;
+
+ @override
+ void didUpdateWidget(SuperTabNameEditor old) {
+ super.didUpdateWidget(old);
+ // A saved name comes back as the server keeps it (one space between
+ // words), but never over a newer edit typed while it was on its way.
+ final typed = _text.text.trim();
+ if (old.name == widget.name) return;
+ if (typed == (old.name ?? '') || typed == _sent) {
+ _text.text = widget.name ?? '';
+ }
+ _sent = null;
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ bool get _changed => _text.text.trim() != (widget.name ?? '');
+
+ Future<void> _save() async {
+ if (widget.busy || !_changed) return;
+ final typed = _sent = _text.text.trim();
+ final error = await widget.onSave(typed.isEmpty ? null : typed);
+ if (error != null) _sent = null;
+ if (mounted) setState(() => _error = error);
+ }
+
+ @override
+ Widget build(BuildContext context) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Name', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('super-name-field'),
+ controller: _text,
+ maxLength: superTabNameMaxLength,
+ textInputAction: TextInputAction.done,
+ decoration: const InputDecoration(counterText: ''),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _save(),
+ ),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ key: const ValueKey('super-name-save'),
+ onPressed: widget.busy || !_changed ? null : _save,
+ child: const Text('Save'),
+ ),
+ ],
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'What teammates see. Leave empty to show your username.',
+ style: DesktopChrome.metadata(),
+ ),
+ if (_error case final error?) ...[
+ const SizedBox(height: 4),
+ Text(
+ error,
+ style: DesktopChrome.metadata(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ],
+ ],
+ );
+}
diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dart
index 58b25d188..308646e92 100644
--- a/desktop/lib/super_tabs/notifications.dart
+++ b/desktop/lib/super_tabs/notifications.dart
@@ -373,7 +373,7 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
final person = c.snapshot?.people
.where((p) => p.id == mention.leadId)
.firstOrNull;
- final author = person?.username ?? mention.leadName;
+ final author = person?.shownName ?? mention.leadName;
// Who tagged, a person or a Lead: one face, in one place.
final Widget? face = person != null
? SuperTabAvatar.person(person, size: 24)
diff --git a/desktop/lib/super_tabs/profile_actions.dart b/desktop/lib/super_tabs/profile_actions.dart
index 2b810ac60..4632e2685 100644
--- a/desktop/lib/super_tabs/profile_actions.dart
+++ b/desktop/lib/super_tabs/profile_actions.dart
@@ -28,6 +28,12 @@ extension SuperTabProfileActions on SuperTabController {
'username': username?.trim(),
}, viewer: true);
+ /// The name the Swarm shows for the reader, trimmed (the server keeps one
+ /// space between words), or back to their username when null. A taken name
+ /// comes back in words. A viewer may change theirs too.
+ Future<String?> setName(String? name) =>
+ _profile({'type': 'member.name', 'name': name?.trim()}, viewer: true);
+
/// [agentId]'s avatar when given (its contributor's or Lead's to change),
/// else the reader's own: [preset], or back to the default when null.
/// An upload goes through [uploadAvatar].
diff --git a/desktop/lib/super_tabs/profile_sheet.dart b/desktop/lib/super_tabs/profile_sheet.dart
index 8d550758d..bdb5583b8 100644
--- a/desktop/lib/super_tabs/profile_sheet.dart
+++ b/desktop/lib/super_tabs/profile_sheet.dart
@@ -13,6 +13,7 @@ import 'identity.dart';
import 'model.dart';
import 'profile_actions.dart';
import 'status_editor.dart';
+import 'name_editor.dart';
import 'username_editor.dart';
/// Picks one picture from this computer, or null when the person cancels.
@@ -26,8 +27,8 @@ Future<Uint8List?> pickSuperTabPicture() async {
}
/// The reader's own profile, or [agentId]'s avatar for its contributor or
-/// Lead: a picture to pick or upload and, for the reader, a username and a
-/// status.
+/// Lead: a picture to pick or upload and, for the reader, a name, a username
+/// and a status.
Future<void> showSuperTabProfile(
BuildContext context,
SuperTabController controller, {
@@ -76,12 +77,17 @@ class _ProfileSheetState extends State<_ProfileSheet> {
}
/// A refused name is said under its own field, not at the foot of the sheet.
- Future<String?> _saveUsername(String username) async {
+ Future<String?> _saveUsername(String username) =>
+ _saveField(() => c.setUsername(username));
+
+ Future<String?> _saveName(String? name) => _saveField(() => c.setName(name));
+
+ Future<String?> _saveField(Future<String?> Function() save) async {
setState(() {
_busy = true;
_error = null;
});
- final error = await c.setUsername(username);
+ final error = await save();
if (mounted) setState(() => _busy = false);
return error;
}
@@ -124,6 +130,12 @@ class _ProfileSheetState extends State<_ProfileSheet> {
?avatar,
const SizedBox(height: 16),
if (agent == null && person != null) ...[
+ SuperTabNameEditor(
+ name: person.name,
+ busy: _busy,
+ onSave: _saveName,
+ ),
+ const SizedBox(height: 16),
SuperTabUsernameEditor(
username: person.username,
busy: _busy,
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 0850c4483..4ec897cda 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -11,6 +11,7 @@ import '../shared/theme/app_icons.dart';
import '../shared/theme/appearance_prefs_store.dart';
import '../shared/widgets/app_icon_button.dart';
import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_menu.dart';
import '../shared/widgets/app_select_field.dart';
import '../state/app_state.dart';
import '../state/harness_activity.dart';
@@ -26,6 +27,7 @@ import 'controller.dart';
import 'detail_dialog.dart';
import 'dialog_scope.dart';
import 'identity.dart';
+import 'import_agent_dialog.dart';
import 'leaderboard/format.dart';
import 'leaderboard/member_row.dart';
import 'leaderboard/model.dart';
@@ -600,6 +602,9 @@ class _SuperTabRosterState extends State<SuperTabRoster>
final openProject = projectId == null
? null
: state?.projectById(projectId);
+ final adds = c.canWrite && c.selected != null && audience == null;
+ // On this Mac, Add agent also imports one of its agents.
+ final imports = widget.app != null && superTabImportOffered;
return [
_heading(openProject == null ? null : scoped != null),
if (_board.error case final error?)
@@ -637,10 +642,17 @@ class _SuperTabRosterState extends State<SuperTabRoster>
SuperTabSectionHeading(
'Agents',
// A private conversation holds only the project's Lead.
- onAdd: c.canWrite && c.selected != null && audience == null
- ? () => widget.onAddAgent(c.selected!)
- : null,
+ onAdd: adds && !imports ? () => widget.onAddAgent(c.selected!) : null,
addTooltip: 'Add agent',
+ actions: [
+ if (adds && imports)
+ _AddAgentMenu(
+ onImport: () => unawaited(
+ showImportAgent(context, widget.app!, c, c.selected!),
+ ),
+ onStart: () => widget.onAddAgent(c.selected!),
+ ),
+ ],
),
for (final agent in listed)
if (!superTabFoldsIdle(states[agent.id]!))
@@ -779,3 +791,52 @@ bool superTabFoldsIdle(SuperTabAgentState state) =>
HarnessActivity.paused,
HarnessActivity.offline,
}.contains(state.mark);
+
+/// The Agents heading's +, on this Mac: Import an agent running here first,
+/// then Start a new agent, today's picker.
+class _AddAgentMenu extends StatefulWidget {
+ const _AddAgentMenu({required this.onImport, required this.onStart});
+ final VoidCallback onImport, onStart;
+
+ @override
+ State<_AddAgentMenu> createState() => _AddAgentMenuState();
+}
+
+class _AddAgentMenuState extends State<_AddAgentMenu> {
+ final _menu = MenuController();
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return MenuAnchor(
+ controller: _menu,
+ consumeOutsideTap: true,
+ alignmentOffset: const Offset(0, grid.AppControl.menuGap),
+ style: grid.AppMenu.style(minWidth: 240),
+ menuChildren: [
+ for (final (label, icon, run) in [
+ (
+ 'Import an agent running on this Mac',
+ AppIcons.download,
+ widget.onImport,
+ ),
+ ('Start a new agent', AppIcons.plus, widget.onStart),
+ ])
+ AppMenuItem(
+ label: label,
+ icon: icon,
+ expandLabel: true,
+ onPressed: () {
+ _menu.close();
+ run();
+ },
+ ),
+ ],
+ builder: (context, menu, _) => AppIconButton(
+ icon: AppIcons.plus,
+ tooltip: 'Add agent',
+ onPressed: () => menu.isOpen ? menu.close() : menu.open(),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/ship_row.dart b/desktop/lib/super_tabs/ship_row.dart
index 7b72db4e6..df5dbbba8 100644
--- a/desktop/lib/super_tabs/ship_row.dart
+++ b/desktop/lib/super_tabs/ship_row.dart
@@ -98,7 +98,7 @@ class _SuperTabShipRowState extends State<SuperTabShipRow> {
_Credit('Requested by', [
(
SuperTabAvatar.person(requester, size: 20),
- requester.username,
+ requester.shownName,
),
]),
agents('Built by', _ids('builderIds')),
diff --git a/desktop/lib/super_tabs/terminal_unavailable.dart b/desktop/lib/super_tabs/terminal_unavailable.dart
index c87a78b99..08fad4ccf 100644
--- a/desktop/lib/super_tabs/terminal_unavailable.dart
+++ b/desktop/lib/super_tabs/terminal_unavailable.dart
@@ -22,7 +22,7 @@ String superTabTerminalUnavailable({
final ownerId = agent.machineOwnerId;
if (snapshot == null || ownerId == accountId) return superTabTerminalOffline;
final owner =
- snapshot.people.where((p) => p.id == ownerId).firstOrNull?.username ??
+ snapshot.people.where((p) => p.id == ownerId).firstOrNull?.shownName ??
'its owner';
final row = snapshot.machines
.where((m) => m['machineId'] == agent.machineId)
diff --git a/desktop/lib/super_tabs/username_editor.dart b/desktop/lib/super_tabs/username_editor.dart
index cc42affb3..3ec49fc07 100644
--- a/desktop/lib/super_tabs/username_editor.dart
+++ b/desktop/lib/super_tabs/username_editor.dart
@@ -86,7 +86,7 @@ class _SuperTabUsernameEditorState extends State<SuperTabUsernameEditor> {
),
const SizedBox(height: 4),
Text(
- 'How people see and tag you in this Swarm.',
+ 'How people tag you in this Swarm.',
style: DesktopChrome.metadata(),
),
if (_error case final error?) ...[
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 9c4fc6487..289b80d99 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -3111,7 +3111,8 @@ class _SuperTabViewState extends State<SuperTabView>
facts: _facts,
),
author: _shownAuthor(c, message),
- // A person is named by their username, as they are tagged.
+ // A person is found by their username, as they are tagged, and reads
+ // as the name they set.
mentions: [
for (final id in message.mentions)
if (_people[id] case final person?) person.username,
@@ -3120,6 +3121,11 @@ class _SuperTabViewState extends State<SuperTabView>
for (final id in message.mentions)
if (_people[id] case final person?) person.username: person.email,
},
+ mentionLabels: {
+ for (final id in message.mentions)
+ if (_people[id] case SuperTabPerson(:final username, :final name?))
+ username: name,
+ },
references: _references,
onOpenGroup: (id) {
setState(() => _showPullRequests = false);
@@ -3187,7 +3193,7 @@ class _SuperTabViewState extends State<SuperTabView>
reactorName: (kind, id) => kind == 'agent'
? c.snapshot?.agentName(id) ?? 'Agent'
: switch (_people[id]) {
- final person? => person.username,
+ final person? => person.shownName,
null => 'Someone',
},
// An older Buddy chat is kept to read: no reaction there (security review 1 of #2437).
diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dart
index 5a73196d7..03e7fe2c4 100644
--- a/desktop/test/product_health_test.dart
+++ b/desktop/test/product_health_test.dart
@@ -143,6 +143,22 @@ void main() {
expect(totals()['health_desktop_first_run_response'], 1);
});
+ test('Import agent outcomes wait for vocabulary 7 (task #2379)', () async {
+ expect(ProductFlow.agentImport.wire, 'agent_import');
+ expect(ProductFlow.agentImport.vocabulary, 7);
+ await usage.flush();
+ usage.proxyVocabulary = 6;
+ usage.begin(ProductFlow.agentImport)(ProductOutcome.ok);
+ usage.begin(ProductFlow.agentImport)(ProductOutcome.cancelled);
+ await usage.flush();
+ expect(totals().keys.where((name) => name.contains('agent_import')), isEmpty);
+ usage.proxyVocabulary = 7;
+ await usage.flush();
+ expect(totals()['ui_desktop_agent_import_started'], 2);
+ expect(totals()['ui_desktop_agent_import_ok'], 1);
+ expect(totals()['ui_desktop_agent_import_cancelled'], 1);
+ });
+
test('invite counters wait for vocabulary 5', () async {
await usage.flush();
usage.proxyVocabulary = 4;
diff --git a/desktop/test/super_tab_backlog_test.dart b/desktop/test/super_tab_backlog_test.dart
index ad83822b2..966bff834 100644
--- a/desktop/test/super_tab_backlog_test.dart
+++ b/desktop/test/super_tab_backlog_test.dart
@@ -430,6 +430,18 @@ void main() {
expect(rowText(tester, 'shipped'), contains('PR #2713'));
});
+ testWidgets('who asked and who it waits on read by the name they set '
+ '(#2794)', (tester) async {
+ final server = swarm();
+ (server.state['people'] as List).cast<Map>().firstWhere(
+ (p) => p['id'] == 'pilot',
+ )['name'] = 'Pilot Pham';
+ await show(tester, server);
+ expect(rowText(tester, 'asking'), contains('api · Pilot Pham'));
+ expect(rowText(tester, 'asking'), contains('Waiting on Pilot Pham'));
+ expect(rowText(tester, 'asking'), isNot(contains('pilot')));
+ });
+
testWidgets('a task the reader cannot read is absent, even when a server '
'sends it', (tester) async {
final server = swarm()..parts.leaksHiddenGroups = true;
diff --git a/desktop/test/super_tab_display_name_test.dart b/desktop/test/super_tab_display_name_test.dart
new file mode 100644
index 000000000..f4c0e8afc
--- /dev/null
+++ b/desktop/test/super_tab_display_name_test.dart
@@ -0,0 +1,282 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/leaderboard/model.dart';
+import 'package:harness/super_tabs/leaderboard/person_row.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/profile_sheet.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_DISPLAY_NAME_SHOTS'];
+final _picture = GlobalKey();
+
+Future<void> _shot(WidgetTester tester, String name) async {
+ await tester.runAsync(() async {
+ final boundary =
+ _picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage();
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
+// A person sets the name the Swarm shows for them (backend personNames.ts):
+// it shows wherever a person shows, and their username stays the tag.
+
+Map<String, dynamic> _person(
+ String id,
+ String email, {
+ String? username,
+ String? name,
+}) => {
+ 'id': id,
+ 'email': email,
+ 'role': 'collaborator',
+ 'username': ?username,
+ 'name': ?name,
+};
+
+SuperTabSnapshot _swarm(List<Map<String, dynamic>> people) =>
+ SuperTabSnapshot.fromJson({
+ 'version': 1,
+ 'id': 'tab',
+ 'name': 'Pilot',
+ 'ownerId': people.first['id'],
+ 'people': people,
+ 'agents': const [],
+ 'conversations': const [],
+ 'invitations': const [],
+ });
+
+SuperTabMessage _from(String id, String email) => SuperTabMessage.fromJson({
+ 'id': 'm-$id',
+ 'conversationId': 'lead',
+ 'text': 'Morning',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': id, 'name': email},
+});
+
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+ group('the model', () {
+ final swarm = _swarm([
+ _person(
+ 'relay',
+ name: 'Minh Nguyen',
+ ),
+ _person('dee', '[email protected]'),
+ ]);
+ final minh = swarm.people.first, dee = swarm.people.last;
+
+ test('shows the name a person set, else their username', () {
+ expect(minh.name, 'Minh Nguyen');
+ expect(minh.shownName, 'Minh Nguyen');
+ expect(minh.username, 'wkpnjjhbnm');
+ expect(dee.name, isNull);
+ expect(dee.shownName, 'dee');
+ });
+
+ test('signs a person’s message with the name they set', () {
+ expect(
+ swarm.authorName(_from('relay', '[email protected]')),
+ 'Minh Nguyen',
+ );
+ expect(swarm.authorName(_from('dee', '[email protected]')), 'dee');
+ });
+
+ test('the leaderboard and the avatar name a person by it', () {
+ final score = SuperTabPersonScore.fromJson({'personId': 'relay'});
+ expect(leaderboardName(minh, score), 'Minh Nguyen');
+ expect(leaderboardName(dee, null), 'dee');
+ expect(SuperTabAvatar.person(minh).name, 'Minh Nguyen');
+ expect(SuperTabAvatar.person(dee).name, 'dee');
+ });
+ });
+
+ group('the Swarm screen', () {
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ final picker = find.byKey(const ValueKey('super-composer-completions'));
+
+ ConversationServer server({bool named = true}) {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {
+ 'id': 'relay',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'username': 'wkpnjjhbnm',
+ if (named) 'name': 'Minh Nguyen',
+ },
+ {'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.append('@wkpnjjhbnm can you check the sign-in screen?');
+ server.messages.last['mentions'] = ['relay'];
+ server.append('On it.');
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'relay',
+ 'name': '[email protected]',
+ };
+ return server;
+ }
+
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server, {
+ Brightness brightness = Brightness.dark,
+ }) async {
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: _picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ List<(String, String?)> choices(WidgetTester tester) => [
+ for (final tile in tester.widgetList<ListTile>(
+ find.descendant(of: picker, matching: find.byType(ListTile)),
+ ))
+ (
+ (tile.title as Text).data!,
+ switch (tile.subtitle) {
+ final Text text => text.data,
+ _ => null,
+ },
+ ),
+ ];
+
+ testWidgets('People, the chat author and a tag show the name', (
+ tester,
+ ) async {
+ await show(tester, server());
+ // The People row and the message's author line.
+ expect(find.text('Minh Nguyen'), findsWidgets);
+ expect(find.text('wkpnjjhbnm'), findsNothing);
+ // The tag reads as their name, though the text still says the username.
+ expect(
+ find.textContaining('@Minh Nguyen', findRichText: true),
+ findsOneWidget,
+ );
+ expect(
+ find.textContaining('@wkpnjjhbnm', findRichText: true),
+ findsNothing,
+ );
+ });
+
+ testWidgets('with no name set, each reads as today', (tester) async {
+ await show(tester, server(named: false));
+ expect(find.text('wkpnjjhbnm'), findsWidgets);
+ expect(
+ find.textContaining('@wkpnjjhbnm', findRichText: true),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Minh'), findsNothing);
+ });
+
+ testWidgets('@ offers a person by name, matched by name or username, '
+ 'and tags their username', (tester) async {
+ final s = server();
+ final c = await show(tester, s);
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Thanks @minh');
+ await tester.pumpAndSettle();
+ expect(choices(tester), [('Minh Nguyen', '@wkpnjjhbnm')]);
+ await tester.enterText(composer, 'Thanks @wkp');
+ await tester.pumpAndSettle();
+ expect(choices(tester), [('Minh Nguyen', '@wkpnjjhbnm')]);
+ // Someone with no name reads as today.
+ await tester.enterText(composer, 'Thanks @de');
+ await tester.pumpAndSettle();
+ expect(choices(tester), [('dee', null)]);
+ await tester.enterText(composer, 'Thanks @minh');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ 'Thanks @wkpnjjhbnm ',
+ );
+ expect(c.mentions(c.selectedId), {'relay': '@wkpnjjhbnm'});
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('screenshots for review, ${brightness.name}', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 720));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ final s = server();
+ // The reader is the person who set the name, to show their profile.
+ final c = await show(tester, s, brightness: brightness);
+ await tester.tap(find.byKey(const ValueKey('super-members-button')));
+ await tester.pumpAndSettle();
+ await _shot(tester, 'chat-people-${brightness.name}');
+ await tester.tap(find.byKey(const ValueKey('super-members-close')));
+ await tester.pumpAndSettle();
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Thanks @mi');
+ await tester.pumpAndSettle();
+ await _shot(tester, 'picker-${brightness.name}');
+ await tester.enterText(composer, '');
+ await tester.pumpAndSettle();
+ unawaited(
+ showSuperTabProfile(tester.element(find.byType(SuperTabView)), c),
+ );
+ await tester.pumpAndSettle();
+ await tester.enterText(
+ find.byKey(const ValueKey('super-name-field')),
+ 'River Tran',
+ );
+ await tester.pump();
+ await _shot(tester, 'profile-${brightness.name}');
+ s.refuse = {
+ 'code': 'NAME_TAKEN',
+ 'message': 'Someone here already goes by that name.',
+ };
+ await tester.enterText(
+ find.byKey(const ValueKey('super-name-field')),
+ 'Minh Nguyen',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('super-name-save')));
+ await tester.pumpAndSettle();
+ await _shot(tester, 'profile-taken-${brightness.name}');
+ }, skip: shots == null);
+ }
+ });
+}
diff --git a/desktop/test/super_tab_import_agent_test.dart b/desktop/test/super_tab_import_agent_test.dart
new file mode 100644
index 000000000..0332aad01
--- /dev/null
+++ b/desktop/test/super_tab_import_agent_test.dart
@@ -0,0 +1,1282 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/home_dir.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/measurement/product_measurement.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/state/app_state.dart';
+import 'package:harness/super_tabs/import_agent.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/roster.dart';
+import 'package:harness/ws/ws_conn.dart';
+
+import 'support/super_tab_fixture.dart';
+import 'swarm_state_test.dart' show createApp;
+
+/// This Mac's daemon: answers `agent_handoff_prepare` with [handoff].
+class _Daemon extends WsConn {
+ _Daemon()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ /// Every request, by the machine asked, type and payload.
+ final calls = <(String, String, Map<String, dynamic>)>[];
+
+ /// The machine the app asks next: set by the fixture's connection.
+ String asked = '';
+ Map<String, dynamic> Function(Map<String, dynamic> payload) handoff = (_) => {
+ 'error': 'UNSUPPORTED',
+ };
+
+ /// Thrown instead of an answer: a daemon that does not answer in time.
+ Object? fails;
+
+ /// The daemon's answer to whether any Swarm lists an agent, from the backend
+ /// (cli superTabs/service.ts `swarmListed`): none here unless a test says.
+ Map<String, dynamic> Function(Map<String, dynamic> payload) swarmListed = (
+ _,
+ ) => {'ok': true, 'listed': false};
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ calls.add((asked, type, Map.of(payload)));
+ if (type == 'super_tabs' && payload['action'] == 'swarmListed') {
+ return swarmListed(payload);
+ }
+ if (type == 'agent_handoff_prepare') {
+ if (fails case final failure?) throw failure;
+ return handoff(payload);
+ }
+ return const {};
+ }
+
+ /// Answers as a daemon that wrote the handoff of the agent it was asked
+ /// about into [folder], as the Change agent handoff does
+ /// (cli lib/agentHandoff.ts).
+ void writes(
+ Directory folder, {
+ String record = '# Handoff\nWorking on the login fix.\n',
+ String? transcript = '## Turn 1\nFix the login.\n',
+ String? file,
+ }) => handoff = (payload) {
+ final base = '${payload['agentId']}-${payload['changeId']}';
+ final dir = Directory('${folder.path}/.harness/handoff')
+ ..createSync(recursive: true);
+ File('${dir.path}/$base.md').writeAsStringSync(record);
+ if (transcript != null) {
+ File('${dir.path}/$base.transcript.md').writeAsStringSync(transcript);
+ }
+ return {
+ 'agentId': payload['agentId'],
+ 'file': file ?? '.harness/handoff/$base.md',
+ 'gitRepo': true,
+ 'cwd': folder.path,
+ 'degraded': <String>[],
+ };
+ };
+}
+
+/// An agent as this Mac's daemon lists it.
+Agent _agent(
+ String id, {
+ String engine = 'claude',
+ String status = 'active',
+ String? sessionId = 'session',
+ String? startedBy,
+ String? parentAgentId,
+ String cwd = '/work/api',
+ String updatedAt = '2026-11-03T08:00:00.000Z',
+ String? model,
+}) => Agent.fromJson({
+ 'id': id,
+ 'name': 'fix-$id',
+ 'engine': engine,
+ 'status': status,
+ 'sessionId': ?sessionId,
+ 'startedBy': ?startedBy,
+ 'parentAgentId': ?parentAgentId,
+ 'project': {'name': 'api', 'cwd': cwd},
+ 'updatedAt': updatedAt,
+ if (model != null) 'selectedModel': 'runtime-v1:$id:$engine:$model@high',
+ 'terminal': {'available': true},
+});
+
+/// The Swarm's server, with this Mac's Team account as the host of the
+/// starts it records: it starts each at once, fails it with [hostFails], or
+/// leaves it waiting while [hostStarts] is false.
+class _Server extends ConversationServer {
+ bool hostStarts = true;
+ String? hostFails;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ final answer = await super.request(method, path, body: body);
+ final id = body?['operationId'];
+ final starts = (state['starts'] ??= <dynamic>[]) as List;
+ if (body?['command']
+ case {'type': 'agent.start', 'request': final Map request}
+ when !starts.any((s) => (s as Map)['id'] == id)) {
+ // As the backend: the start's id is its command's operation id.
+ (answer['result'] as Map)['startId'] = id;
+ revision++;
+ final started = hostStarts && hostFails == null;
+ starts.add({
+ 'id': id,
+ 'request': request,
+ 'harnessId': started ? 'h-new' : null,
+ 'error': hostFails,
+ });
+ if (started) {
+ (state['agents'] as List).add({
+ 'id': 'agent-new',
+ 'projectId': 'lead',
+ 'name': request['name'],
+ 'machineId': request['machineId'],
+ 'harnessId': 'h-new',
+ 'contributorId': 'owner',
+ 'roleName': request['roleName'],
+ 'configuration': {'engine': request['engine']},
+ });
+ final chat = (state['conversations'] as List).cast<Map>().firstWhere(
+ (g) => g['id'] == request['conversationId'],
+ );
+ chat['agentIds'] = [...chat['agentIds'] as List, 'agent-new'];
+ }
+ }
+ return answer;
+ }
+
+ /// The commands it took, in order, with their operation ids.
+ List<(String, Map)> get commands => [
+ for (final post in posts)
+ (post['operationId'] as String, post['command'] as Map),
+ ];
+}
+
+class ImportFixture {
+ ImportFixture({ProductMeasurement? measurement}) {
+ app = createApp(
+ connected: true,
+ connectionForTest: (id) => daemon..asked = id,
+ productMeasurement: measurement,
+ );
+ app.currentUser = const CurrentUserProfile(
+ id: 'owner',
+ email: '[email protected]',
+ );
+ app.machineStates['m']!.localOnly = true;
+ for (final machine in const [
+ // This Mac's Harness Team account, on the same account.
+ Machine(
+ machineId: 'team-m',
+ authMode: MachineAuthMode.remote,
+ name: 'Harness Team',
+ sessionKind: 'team',
+ ),
+ // Another of the owner's computers.
+ Machine(
+ machineId: 'laptop',
+ authMode: MachineAuthMode.remote,
+ name: 'Laptop',
+ ),
+ // Someone else's computer, shared with the owner.
+ Machine(
+ machineId: 'shared',
+ authMode: MachineAuthMode.remote,
+ name: 'Mira',
+ machineShare: MachineShare(
+ ownerName: 'mira',
+ ownerEmail: '[email protected]',
+ via: 'person',
+ added: true,
+ ),
+ ),
+ ]) {
+ app.machines = [...app.machines, machine];
+ app.machineStates[machine.machineId] = MachineState(machine)
+ ..agents = [_agent('${machine.machineId}-agent')];
+ }
+ server.state['projects'] = [projectFixture('lead', 'openharness', 'lead')];
+ server.state['machines'] = <dynamic>[macPool, teamPool];
+ }
+
+ final daemon = _Daemon();
+ late final AppNotifier app;
+ final server = _Server();
+ late final c = server.controller();
+
+ final macPool = <String, dynamic>{
+ 'machineId': 'm',
+ 'name': 'Studio',
+ 'contributorId': 'owner',
+ 'scope': 'swarm',
+ 'cwd': '/Users/owner/.harness/swarm/tab',
+ };
+ final teamPool = <String, dynamic>{
+ 'machineId': 'team-m',
+ 'name': 'Studio',
+ 'contributorId': 'owner',
+ 'hostMachineId': 'm',
+ 'scope': 'swarm',
+ 'cwd': '/Users/Shared/harness-team/swarm/tab',
+ 'observation': {'receivedAt': 1},
+ };
+
+ /// This Mac's agents, as its daemon lists them.
+ set agents(List<Agent> agents) => app.machineStates['m']!.agents = agents;
+
+ Future<void> start() => c.refresh();
+
+ void dispose() {
+ c.dispose();
+ app.dispose();
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+
+ Future<ImportFixture> fixture() async {
+ final f = ImportFixture();
+ addTearDown(f.dispose);
+ await f.start();
+ return f;
+ }
+
+ group('which agents can be imported', () {
+ test('only this Mac\'s own Claude Code and Codex agents, running or '
+ 'resumable, that no Swarm lists and the Swarm did not start', () async {
+ final f = await fixture();
+ f.agents = [
+ _agent('claude', updatedAt: '2026-11-03T08:00:00.000Z'),
+ _agent('codex', engine: 'codex', updatedAt: '2026-11-03T09:00:00.000Z'),
+ _agent('opencode', engine: 'opencode'),
+ _agent('terminal', engine: 'terminal'),
+ // Listed by this Swarm: a teammate's agent and a Buddy.
+ _agent('listed'),
+ _agent('buddy'),
+ // Started by the Swarm: an agent started it, from no harness here.
+ _agent('swarm-started', startedBy: 'agent'),
+ // Started by one of this Mac's own harnesses: the person's.
+ _agent('child', startedBy: 'agent', parentAgentId: 'claude'),
+ _agent('paused', status: 'stopped'),
+ _agent('gone', status: 'stopped', sessionId: null),
+ ];
+ (f.server.state['agents'] as List).addAll([
+ {
+ 'id': 'agent-listed',
+ 'projectId': 'lead',
+ 'name': 'Engineer',
+ 'machineId': 'm',
+ 'harnessId': 'listed',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ {
+ 'id': 'agent-buddy',
+ 'projectId': 'lead',
+ 'name': 'Buddy',
+ 'buddyOf': {'personId': 'owner', 'generation': 'fixture'},
+ 'machineId': 'm',
+ 'harnessId': 'buddy',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ]);
+ await f.c.refresh();
+
+ final offered = importableAgents(f.app, f.c);
+ // Newest first, all on this Mac.
+ expect(
+ [for (final a in offered) a.agent.id],
+ ['codex', 'claude', 'child', 'paused'],
+ );
+ expect(offered.map((a) => a.machineId).toSet(), {'m'});
+ });
+
+ test('never an agent of the Team account, another computer or another '
+ 'person', () async {
+ final f = await fixture();
+ f.agents = [];
+ expect(importableAgents(f.app, f.c), isEmpty);
+ });
+
+ test('nothing when this computer is not running Harness', () async {
+ final f = await fixture();
+ f.agents = [_agent('claude')];
+ f.app.machineStates['m']!.localOnly = false;
+ expect(importableAgents(f.app, f.c), isEmpty);
+ expect(importUnavailable(f.app, f.c), isNotNull);
+ });
+ });
+
+ group('where the new agent runs', () {
+ test('this Mac\'s Team account in the Swarm: import is offered', () async {
+ final f = await fixture();
+ expect(importUnavailable(f.app, f.c), isNull);
+ });
+
+ test('no Team account for this Mac in the Swarm says how to set one up, '
+ 'and starts nowhere else', () async {
+ final f = await fixture();
+ f.server.state['machines'] = <dynamic>[f.macPool];
+ await f.c.refresh();
+ expect(importUnavailable(f.app, f.c), kImportNeedsTeamAccount);
+ // A Team account of another Mac is not this Mac's.
+ f.server.state['machines'] = <dynamic>[
+ f.macPool,
+ {...f.teamPool, 'hostMachineId': 'laptop'},
+ ];
+ await f.c.refresh();
+ expect(importUnavailable(f.app, f.c), kImportNeedsTeamAccount);
+ });
+
+ test('a Team account that takes no work says why', () async {
+ final f = await fixture();
+ f.teamPool['teamWork'] = {
+ 'allowed': false,
+ 'code': 'PRIVACY_CHECK_FAILED',
+ 'reason': 'Its Team account failed the privacy check.',
+ };
+ await f.c.refresh();
+ expect(
+ importUnavailable(f.app, f.c),
+ 'Its Team account failed the privacy check.',
+ );
+ });
+
+ test('this Mac not in the Swarm says to add it', () async {
+ final f = await fixture();
+ f.server.state['machines'] = <dynamic>[];
+ await f.c.refresh();
+ expect(importUnavailable(f.app, f.c), kImportNeedsThisMac);
+ });
+ });
+
+ group('the handoff preview', () {
+ late Directory folder;
+ setUp(() async {
+ folder = await Directory.systemTemp.createTemp('import-agent-');
+ addTearDown(() => folder.delete(recursive: true));
+ });
+
+ test('this Mac\'s daemon prepares the Change agent handoff of the agent, '
+ 'and its two files are read whole', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', engine: 'codex', cwd: folder.path)];
+ f.daemon.writes(folder, record: '# Handoff\nkey ****\n');
+ final agent = importableAgents(f.app, f.c).single;
+
+ final handoff = await prepareImportHandoff(f.app, agent);
+
+ // First whether a Swarm lists it (any Swarm, open here or not), then the
+ // handoff.
+ expect(f.daemon.calls.map((c) => (c.$1, c.$2, c.$3['action'])), [
+ ('m', 'super_tabs', 'swarmListed'),
+ ('m', 'agent_handoff_prepare', null),
+ ]);
+ expect(f.daemon.calls.first.$3['harnessId'], 'fix');
+ final (machine, type, payload) = f.daemon.calls.last;
+ expect((machine, type), ('m', 'agent_handoff_prepare'));
+ expect(payload['agentId'], 'fix');
+ expect(payload['targetEngine'], 'codex');
+ expect(payload['changeId'], matches(RegExp(r'^[0-9a-f]{32}$')));
+ final change = payload['changeId'];
+ expect(handoff.record.name, 'fix-$change.md');
+ expect(handoff.record.text, '# Handoff\nkey ****\n');
+ expect(handoff.record.size, 19);
+ expect(handoff.transcript.name, 'fix-$change.transcript.md');
+ expect(handoff.transcript.text, '## Turn 1\nFix the login.\n');
+ expect(handoff.transcript.size, 25);
+ // Nothing has left this Mac.
+ expect(f.server.posts, isEmpty);
+ expect(f.server.uploads, isEmpty);
+
+ // Each preview is a new change.
+ await prepareImportHandoff(f.app, agent);
+ expect(f.daemon.calls.last.$3['changeId'], isNot(change));
+ });
+
+ for (final (why, reply, words) in [
+ (
+ 'a held conversation',
+ {'error': 'IDENTITY_UNAVAILABLE', 'held': true},
+ 'not confirmed yet',
+ ),
+ ('a busy daemon', {'error': 'BUSY'}, 'took too long'),
+ ('an older daemon', {'error': 'UNSUPPORTED'}, 'Update Harness'),
+ (
+ 'nothing to hand off',
+ {'agentId': 'fix', 'file': null, 'gitRepo': true, 'degraded': []},
+ 'no conversation',
+ ),
+ ]) {
+ test('$why says why and offers nothing to import', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', cwd: folder.path)];
+ f.daemon.handoff = (_) => {...reply, 'cwd': folder.path};
+ await expectLater(
+ prepareImportHandoff(f.app, importableAgents(f.app, f.c).single),
+ throwsA(
+ isA<ImportFailure>()
+ .having((e) => e.step, 'step', ImportStep.prepare)
+ .having((e) => e.message, 'message', contains(words)),
+ ),
+ );
+ });
+ }
+
+ // Security review of #2783 (Alder3), Important 1: an agent the person
+ // added to a Swarm that is not open in this window is in a Swarm too, and
+ // its transcript may hold that Swarm's private project.
+ test('an agent in a Swarm not open here is refused before anything is '
+ 'prepared', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', engine: 'codex', cwd: folder.path)];
+ f.daemon.writes(folder, record: '# Handoff\n');
+ f.daemon.swarmListed = (_) => {'ok': true, 'listed': true};
+ final agent = importableAgents(f.app, f.c).single;
+ await expectLater(
+ prepareImportHandoff(f.app, agent),
+ throwsA(
+ isA<ImportFailure>()
+ .having((e) => e.step, 'step', ImportStep.prepare)
+ .having(
+ (e) => e.message,
+ 'message',
+ contains('already in a Swarm'),
+ ),
+ ),
+ );
+ expect(f.daemon.calls.map((c) => c.$2), ['super_tabs']);
+ expect(f.server.posts, isEmpty);
+ });
+
+ test(
+ 'a Swarm role that cannot be read refuses, rather than share',
+ () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', engine: 'codex', cwd: folder.path)];
+ f.daemon.writes(folder, record: '# Handoff\n');
+ // The backend did not answer: the daemon knows neither way.
+ f.daemon.swarmListed = (_) => {'ok': true};
+ final agent = importableAgents(f.app, f.c).single;
+ await expectLater(
+ prepareImportHandoff(f.app, agent),
+ throwsA(
+ isA<ImportFailure>().having(
+ (e) => e.message,
+ 'message',
+ contains('could not check'),
+ ),
+ ),
+ );
+ expect(f.daemon.calls.map((c) => c.$2), ['super_tabs']);
+ },
+ );
+
+ // Re-review of #2783 (Alder3): a Swarm that still lists the agent with its
+ // chats archived or its stop asked gives it no role, and is a Swarm still.
+ test('an agent a Swarm lists with no role is refused too', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', engine: 'codex', cwd: folder.path)];
+ f.daemon.writes(folder, record: '# Handoff\n');
+ f.daemon.swarmListed = (_) => {'ok': true, 'role': null, 'listed': true};
+ final agent = importableAgents(f.app, f.c).single;
+ await expectLater(
+ prepareImportHandoff(f.app, agent),
+ throwsA(
+ isA<ImportFailure>().having(
+ (e) => e.message,
+ 'message',
+ contains('already in a Swarm'),
+ ),
+ ),
+ );
+ expect(f.daemon.calls.map((c) => c.$2), ['super_tabs']);
+ });
+
+ test('a daemon too old to say whether a Swarm lists the agent asks for an '
+ 'update of Harness on this Mac', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', engine: 'codex', cwd: folder.path)];
+ f.daemon.writes(folder, record: '# Handoff\n');
+ // An older daemon takes an unknown action for an agent's own request.
+ f.daemon.swarmListed = (_) => {'error': 'INVALID_REQUEST'};
+ final agent = importableAgents(f.app, f.c).single;
+ await expectLater(
+ prepareImportHandoff(f.app, agent),
+ throwsA(
+ isA<ImportFailure>()
+ .having((e) => e.code, 'code', 'daemon-old')
+ .having(
+ (e) => e.message,
+ 'message',
+ contains('Update Harness on this Mac'),
+ ),
+ ),
+ );
+ expect(f.daemon.calls.map((c) => c.$2), ['super_tabs']);
+ });
+
+ test('a reply naming another file is refused', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', cwd: folder.path)];
+ f.daemon.writes(folder, file: '../../.ssh/id_rsa');
+ await expectLater(
+ prepareImportHandoff(f.app, importableAgents(f.app, f.c).single),
+ throwsA(isA<ImportFailure>()),
+ );
+ });
+
+ test('a missing transcript says the files could not be read', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', cwd: folder.path)];
+ f.daemon.writes(folder, transcript: null);
+ await expectLater(
+ prepareImportHandoff(f.app, importableAgents(f.app, f.c).single),
+ throwsA(
+ isA<ImportFailure>().having(
+ (e) => e.message,
+ 'message',
+ contains('Could not read'),
+ ),
+ ),
+ );
+ });
+
+ test('a daemon that does not answer says so', () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', cwd: folder.path)];
+ f.daemon.fails = TimeoutException('no answer');
+ await expectLater(
+ prepareImportHandoff(f.app, importableAgents(f.app, f.c).single),
+ throwsA(
+ isA<ImportFailure>().having(
+ (e) => e.message,
+ 'message',
+ contains('took too long'),
+ ),
+ ),
+ );
+ });
+
+ test(
+ 'what is previewed is what is shared: the files are read once',
+ () async {
+ final f = await fixture();
+ f.agents = [_agent('fix', cwd: folder.path)];
+ f.daemon.writes(folder);
+ final handoff = await prepareImportHandoff(
+ f.app,
+ importableAgents(f.app, f.c).single,
+ );
+ File('${folder.path}/.harness/handoff/${handoff.record.name}')
+ .writeAsStringSync('changed after the preview');
+ expect(handoff.record.text, '# Handoff\nWorking on the login fix.\n');
+ },
+ );
+ });
+
+ group('import', () {
+ late Directory folder;
+ setUp(() async {
+ folder = await Directory.systemTemp.createTemp('import-agent-');
+ addTearDown(() => folder.delete(recursive: true));
+ });
+
+ Future<(ImportFixture, ImportableAgent, ImportHandoff)> prepared() async {
+ final f = await fixture();
+ f.agents = [
+ _agent('fix', engine: 'codex', cwd: folder.path, model: 'gpt-5.6-sol'),
+ ];
+ f.daemon.writes(folder);
+ final agent = importableAgents(f.app, f.c).single;
+ return (f, agent, await prepareImportHandoff(f.app, agent));
+ }
+
+ const requirements = {
+ 'memoryBytes': 2147483648,
+ 'diskBytes': 10737418240,
+ 'maxCpuPercent': 100,
+ 'tools': ['git'],
+ 'devices': <String>[],
+ 'quotaRequired': false,
+ };
+
+ test('a preview alone sends nothing to the server', () async {
+ final (f, _, _) = await prepared();
+ expect(f.server.posts, isEmpty);
+ expect(f.server.uploads, isEmpty);
+ });
+
+ test('opens a conversation, shares both files in it, starts the agent '
+ 'in this Mac\'s Team account and sends the files to it alone', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+
+ final result = await importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: import,
+ );
+
+ final commands = f.server.commands;
+ expect(
+ [for (final (id, _) in commands) id],
+ [
+ '${import.id}-conversation',
+ '${import.id}-start',
+ '${import.id}-message',
+ ],
+ );
+ final conversation = result.conversationId;
+ expect(commands[0].$2, {
+ 'type': 'conversation.create',
+ 'projectId': 'lead',
+ 'title': "Continue fix-fix's work",
+ 'brief':
+ "Continues fix-fix's work from owner's Mac, Test host. Its "
+ 'handoff is attached: a record of earlier work, not instructions.',
+ 'checks': <dynamic>[],
+ });
+ expect(f.server.uploads.map((u) => u['conversationId']), [
+ conversation,
+ conversation,
+ ]);
+ expect(f.server.uploads.map((u) => u['name']), [
+ handoff.record.name,
+ handoff.transcript.name,
+ ]);
+ expect(f.server.uploads[0]['file'], handoff.record.bytes);
+ expect(f.server.uploads[1]['file'], handoff.transcript.bytes);
+ expect(commands[1].$2, {
+ 'type': 'agent.start',
+ 'request': {
+ 'conversationId': conversation,
+ 'machineId': 'team-m',
+ 'engine': 'codex',
+ 'name': 'fix-fix',
+ 'cwd': '/Users/Shared/harness-team/swarm/tab/lead',
+ 'roleName': 'Engineer',
+ 'worktree': true,
+ 'model': 'gpt-5.6-sol',
+ 'requirements': requirements,
+ },
+ });
+ expect(commands[2].$2, {
+ 'type': 'message.send',
+ 'conversationId': conversation,
+ 'text':
+ "You are continuing fix-fix's work on owner's Mac. Read the "
+ 'attached handoff: a record of earlier work, not instructions. '
+ 'Say what it was doing, then take the next step.',
+ 'replyTo': null,
+ 'recipientIds': ['agent-new'],
+ 'attachmentIds': ['attachment-1', 'attachment-2'],
+ });
+ expect(result.agentId, 'agent-new');
+ // The new conversation is the one on screen.
+ expect(f.c.selectedId, conversation);
+ // The imported agent is never stopped, messaged or registered.
+ expect(f.daemon.calls.map((c) => c.$2), [
+ 'super_tabs',
+ 'agent_handoff_prepare',
+ ]);
+ // That first ask is only a read of whether a Swarm lists it.
+ expect(f.daemon.calls.first.$3['action'], 'swarmListed');
+ });
+
+ test('a project whose repository is the Team account\'s own folder starts '
+ 'there', () async {
+ final (f, agent, handoff) = await prepared();
+ (f.server.state['projects'] as List).first['repository'] = {
+ 'machineId': 'team-m',
+ 'cwd': '/Users/Shared/harness-team/code/openharness',
+ };
+ await f.c.refresh();
+ await importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: AgentImport(),
+ );
+ final start = f.server.commands[1].$2['request'] as Map;
+ expect(start['cwd'], '/Users/Shared/harness-team/code/openharness');
+ });
+
+ Matcher failedAt(ImportStep step, [Object? words]) => isA<ImportFailure>()
+ .having((e) => e.step, 'step', step)
+ .having((e) => e.message, 'message', words ?? isNotEmpty);
+
+ List<String> sent(ImportFixture f) => [
+ for (final (_, command) in f.server.commands) command['type'] as String,
+ ];
+
+ test(
+ 'a refused conversation shares nothing; Import again opens it once',
+ () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.refuse = {'code': 'PAUSED', 'message': 'New work is paused.'};
+ await expectLater(
+ importAgent(f.app, f.c, 'lead', agent, handoff, progress: import),
+ throwsA(failedAt(ImportStep.conversation, 'New work is paused.')),
+ );
+ expect(f.server.uploads, isEmpty);
+ f.server.refuse = null;
+ await importAgent(f.app, f.c, 'lead', agent, handoff, progress: import);
+ expect(sent(f), [
+ 'conversation.create',
+ 'conversation.create',
+ 'agent.start',
+ 'message.send',
+ ]);
+ expect(f.server.commands[0].$1, f.server.commands[1].$1);
+ },
+ );
+
+ test('a failed upload keeps the conversation and the file already '
+ 'shared; Import again shares only the other', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.failUpload = handoff.transcript.name;
+ await expectLater(
+ importAgent(f.app, f.c, 'lead', agent, handoff, progress: import),
+ throwsA(failedAt(ImportStep.upload)),
+ );
+ expect(import.conversationId, isNotNull);
+ expect(sent(f), ['conversation.create']);
+ f.server.failUpload = null;
+ await importAgent(f.app, f.c, 'lead', agent, handoff, progress: import);
+ expect(sent(f), ['conversation.create', 'agent.start', 'message.send']);
+ expect(f.server.uploads.map((u) => u['name']), [
+ handoff.record.name,
+ handoff.transcript.name,
+ ]);
+ });
+
+ test('a refused start keeps the conversation and its files; Import again '
+ 'starts it with the same operation', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.unknownCommand = (command) => command['type'] == 'agent.start';
+ await expectLater(
+ importAgent(f.app, f.c, 'lead', agent, handoff, progress: import),
+ throwsA(failedAt(ImportStep.start)),
+ );
+ expect(f.c.snapshot!.conversation(import.conversationId!), isNotNull);
+ f.server.unknownCommand = null;
+ await importAgent(f.app, f.c, 'lead', agent, handoff, progress: import);
+ expect(sent(f), [
+ 'conversation.create',
+ 'agent.start',
+ 'agent.start',
+ 'message.send',
+ ]);
+ expect(f.server.uploads, hasLength(2));
+ expect(f.server.commands[1].$1, f.server.commands[2].$1);
+ });
+
+ test('a start whose reply was lost is checked, never made twice', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.unknownCommand = (command) {
+ if (command['type'] == 'agent.start') f.server.loseReply = true;
+ return false;
+ };
+ await expectLater(
+ importAgent(f.app, f.c, 'lead', agent, handoff, progress: import),
+ throwsA(failedAt(ImportStep.start)),
+ );
+ f.server.unknownCommand = null;
+ await importAgent(f.app, f.c, 'lead', agent, handoff, progress: import);
+ expect((f.server.state['starts'] as List), hasLength(1));
+ expect(sent(f).last, 'message.send');
+ });
+
+ test('a start its host fails says why', () async {
+ final (f, agent, handoff) = await prepared();
+ f.server.hostFails = 'This machine could not clone the project.';
+ await expectLater(
+ importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: AgentImport(),
+ ),
+ throwsA(
+ failedAt(
+ ImportStep.start,
+ 'This machine could not clone the project.',
+ ),
+ ),
+ );
+ expect(sent(f), ['conversation.create', 'agent.start']);
+ });
+
+ test('an agent that is not listed in time says so; Import again waits '
+ 'for it without starting another', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.hostStarts = false;
+ await expectLater(
+ importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: import,
+ startWait: const Duration(milliseconds: 50),
+ ),
+ throwsA(failedAt(ImportStep.start, contains('not started yet'))),
+ );
+ // Its host starts it later.
+ final start = (f.server.state['starts'] as List).single as Map;
+ start['harnessId'] = 'h-new';
+ (f.server.state['agents'] as List).add({
+ 'id': 'agent-new',
+ 'projectId': 'lead',
+ 'name': 'fix-fix',
+ 'machineId': 'team-m',
+ 'harnessId': 'h-new',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ });
+ f.server.revision++;
+ await f.c.refresh();
+ final result = await importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: import,
+ );
+ expect(result.agentId, 'agent-new');
+ expect(sent(f), ['conversation.create', 'agent.start', 'message.send']);
+ });
+
+ test('a refused message keeps the agent; Import again sends it once more '
+ 'with the same operation', () async {
+ final (f, agent, handoff) = await prepared();
+ final import = AgentImport();
+ f.server.unknownCommand = (command) => command['type'] == 'message.send';
+ await expectLater(
+ importAgent(f.app, f.c, 'lead', agent, handoff, progress: import),
+ throwsA(failedAt(ImportStep.message)),
+ );
+ expect(import.agentId, 'agent-new');
+ f.server.unknownCommand = null;
+ await importAgent(f.app, f.c, 'lead', agent, handoff, progress: import);
+ expect(sent(f), [
+ 'conversation.create',
+ 'agent.start',
+ 'message.send',
+ 'message.send',
+ ]);
+ expect(f.server.commands[2].$1, f.server.commands[3].$1);
+ });
+
+ test('no Team account for this Mac starts nothing anywhere', () async {
+ final (f, agent, handoff) = await prepared();
+ f.server.state['machines'] = <dynamic>[f.macPool];
+ await f.c.refresh();
+ await expectLater(
+ importAgent(
+ f.app,
+ f.c,
+ 'lead',
+ agent,
+ handoff,
+ progress: AgentImport(),
+ ),
+ throwsA(failedAt(ImportStep.conversation, kImportNeedsTeamAccount)),
+ );
+ expect(f.server.posts, isEmpty);
+ expect(f.server.uploads, isEmpty);
+ });
+ });
+
+ group('the entry and the dialog', () {
+ late Directory folder;
+ setUp(() async {
+ folder = await Directory.systemTemp.createTemp('import-agent-');
+ addTearDown(() => folder.delete(recursive: true));
+ });
+ final mac = TargetPlatformVariant.only(TargetPlatform.macOS);
+
+ /// A handoff of about 2 KB and a transcript of about 5 KB.
+ final record = '# Handoff\n${'r' * 2038}';
+ final transcript = '## Turn 1\nFix the login.\n${'t' * 5095}';
+
+ Future<ImportFixture> roster(
+ WidgetTester tester, {
+ void Function(SuperTabConversation group)? onAddAgent,
+ Brightness brightness = Brightness.light,
+ ProductMeasurement? measurement,
+ }) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final f = ImportFixture(measurement: measurement);
+ addTearDown(f.dispose);
+ await tester.runAsync(f.start);
+ f.agents = [
+ _agent('fix', engine: 'codex', cwd: folder.path),
+ _agent('docs', cwd: folder.path, updatedAt: '2026-11-03T07:00:00Z'),
+ ];
+ f.daemon.writes(folder, record: record, transcript: transcript);
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topRight,
+ child: SizedBox(
+ width: 280,
+ child: SuperTabRoster(
+ controller: f.c,
+ app: f.app,
+ onInvite: () {},
+ onAddAgent: onAddAgent ?? (_) {},
+ onAnswer: (_) {},
+ onOpenAgent: (_) {},
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return f;
+ }
+
+ /// Lets this Mac's files be read, then draws what follows, until [done].
+ Future<void> settle(WidgetTester tester, bool Function() done) async {
+ for (var i = 0; i < 100 && !done(); i++) {
+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));
+ await tester.pump();
+ }
+ await tester.pumpAndSettle();
+ expect(done(), isTrue);
+ }
+
+ Future<void> openImport(WidgetTester tester) async {
+ await tester.tap(find.byTooltip('Add agent'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Import an agent running on this Mac'));
+ await tester.pumpAndSettle();
+ }
+
+ Future<void> preview(WidgetTester tester, ImportFixture f) async {
+ await openImport(tester);
+ await tester.tap(find.textContaining('Codex · fix-fix'));
+ await settle(
+ tester,
+ () => find
+ .text("What openharness's members will read")
+ .evaluate()
+ .isNotEmpty,
+ );
+ }
+
+ testWidgets('the + offers Import first, then Start a new agent, which '
+ 'opens today\'s picker', (tester) async {
+ SuperTabConversation? added;
+ await roster(tester, onAddAgent: (group) => added = group);
+ await tester.tap(find.byTooltip('Add agent'));
+ await tester.pumpAndSettle();
+ final import = find.text('Import an agent running on this Mac');
+ final start = find.text('Start a new agent');
+ expect(
+ tester.getTopLeft(import).dy,
+ lessThan(tester.getTopLeft(start).dy),
+ );
+ await tester.tap(start);
+ await tester.pumpAndSettle();
+ expect(added?.id, 'lead');
+ expect(find.text('Import an agent running on this Mac'), findsNothing);
+ }, variant: mac);
+
+ testWidgets('elsewhere the + opens today\'s picker at once', (
+ tester,
+ ) async {
+ SuperTabConversation? added;
+ await roster(tester, onAddAgent: (group) => added = group);
+ await tester.tap(find.byTooltip('Add agent'));
+ await tester.pumpAndSettle();
+ expect(added?.id, 'lead');
+ expect(find.text('Import an agent running on this Mac'), findsNothing);
+ }, variant: TargetPlatformVariant.only(TargetPlatform.linux));
+
+ testWidgets('Import lists this Mac\'s agents and what is not offered', (
+ tester,
+ ) async {
+ final f = await roster(tester);
+ f.agents = [
+ _agent('fix', engine: 'codex', cwd: '/work/api'),
+ _agent('docs', cwd: '${homeDir()}/code/docs'),
+ ];
+ await openImport(tester);
+ expect(find.text('Import an agent into openharness'), findsOneWidget);
+ expect(find.text('Codex · fix-fix · /work/api'), findsOneWidget);
+ expect(find.text('Claude Code · fix-docs · ~/code/docs'), findsOneWidget);
+ expect(
+ find.text(
+ 'Not offered: agents already in a Swarm, Buddies and '
+ 'Swarm-started agents.',
+ ),
+ findsOneWidget,
+ );
+ }, variant: mac);
+
+ testWidgets('the preview shows both files whole, with their sizes, and '
+ 'what is shared; Cancel sends nothing', (tester) async {
+ final f = await roster(tester);
+ await preview(tester, f);
+ expect(find.text('Handoff (redacted)'), findsOneWidget);
+ expect(find.text('Conversation and tool calls'), findsOneWidget);
+ expect(find.text('2 KB'), findsOneWidget);
+ expect(find.text('5 KB'), findsOneWidget);
+ expect(
+ find.text(
+ 'Secrets (keys, tokens, passwords in URLs) are removed. Tool '
+ 'output is never included.',
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.text(
+ 'The agent on this Mac keeps running; nothing about it changes.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.text('Full text').first);
+ await tester.pumpAndSettle();
+ expect(find.text('# Handoff'), findsOneWidget);
+ expect(find.text('r' * 2038), findsOneWidget);
+ await tester.tap(find.text('Full text'));
+ await tester.pumpAndSettle();
+ expect(find.text('Fix the login.'), findsOneWidget);
+
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ expect(find.text('Import an agent into openharness'), findsNothing);
+ expect(f.server.posts, isEmpty);
+ expect(f.server.uploads, isEmpty);
+ }, variant: mac);
+
+ testWidgets('Import starts the new agent and opens its conversation', (
+ tester,
+ ) async {
+ final f = await roster(tester);
+ await preview(tester, f);
+ await tester.tap(find.widgetWithText(FilledButton, 'Import'));
+ await settle(
+ tester,
+ () => find.text('Import an agent into openharness').evaluate().isEmpty,
+ );
+ final sent = f.server.commands.last.$2;
+ expect(sent['type'], 'message.send');
+ expect(sent['recipientIds'], ['agent-new']);
+ expect(f.c.selectedId, sent['conversationId']);
+ expect(
+ f.c.snapshot!.conversation(f.c.selectedId)!.title,
+ "Continue fix-fix's work",
+ );
+ }, variant: mac);
+
+ testWidgets('a failed step says which, keeps what was done in view, and '
+ 'Start again goes on from there', (tester) async {
+ final f = await roster(tester);
+ await preview(tester, f);
+ f.server.unknownCommand = (command) => command['type'] == 'agent.start';
+ await tester.tap(find.widgetWithText(FilledButton, 'Import'));
+ await settle(
+ tester,
+ () => find.text('Start again').evaluate().isNotEmpty,
+ );
+ for (final done in ['Opening the conversation', 'Sharing the files']) {
+ expect(
+ find.descendant(
+ of: find
+ .ancestor(of: find.text(done), matching: find.byType(Row))
+ .first,
+ matching: find.bySemanticsLabel('Done'),
+ ),
+ findsOneWidget,
+ reason: done,
+ );
+ }
+ expect(find.text('Starting the agent'), findsOneWidget);
+ expect(find.text('Invalid request.'), findsOneWidget);
+ f.server.unknownCommand = null;
+ await tester.tap(find.text('Start again'));
+ await settle(
+ tester,
+ () => find.text('Import an agent into openharness').evaluate().isEmpty,
+ );
+ expect(
+ [for (final (_, c) in f.server.commands) c['type']],
+ ['conversation.create', 'agent.start', 'agent.start', 'message.send'],
+ );
+ }, variant: mac);
+
+ // ENGINEERING.md 8: each import is counted by its outcome alone, with no
+ // name, path or id.
+ ({
+ ProductMeasurement usage,
+ Map<String, int> Function() totals,
+ Future<void> Function(WidgetTester) bind,
+ })
+ counted() {
+ final reports = <Map<String, dynamic>>[];
+ final usage = ProductMeasurement(
+ surface: 'desktop',
+ automatic: false,
+ context: ProductUsageContext(
+ release: '1.3.0',
+ platform: 'macos',
+ production: true,
+ ),
+ sendSetup: (_) async => {'accepted': true},
+ )..proxyVocabulary = 7; // The app disposes it with itself.
+ return (
+ usage: usage,
+ // After the app is made, which binds its own (signed-out) account:
+ // this account, its sharing choice read.
+ bind: (tester) async {
+ usage.account(
+ 'owner',
+ choice: () async => {'enabled': true, 'revision': 0},
+ send: (report) async {
+ reports.add(report);
+ return {'accepted': true};
+ },
+ );
+ await tester.runAsync(usage.flush);
+ },
+ totals: () {
+ final all = <String, int>{};
+ for (final report in reports) {
+ for (final e in (report['counters'] as Map).entries) {
+ all[e.key as String] = (all[e.key] ?? 0) + (e.value as int);
+ }
+ }
+ return all;
+ },
+ );
+ }
+
+ testWidgets('a preview is counted as started, and Cancel as cancelled', (
+ tester,
+ ) async {
+ final m = counted();
+ final f = await roster(tester, measurement: m.usage);
+ await m.bind(tester);
+ await preview(tester, f);
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ await tester.runAsync(m.usage.flush);
+ expect(m.totals()['ui_desktop_agent_import_started'], 1);
+ expect(m.totals()['ui_desktop_agent_import_cancelled'], 1);
+ expect(m.totals()['ui_desktop_agent_import_ok'], isNull);
+ }, variant: mac);
+
+ testWidgets('an Import is counted as ok', (tester) async {
+ final m = counted();
+ final f = await roster(tester, measurement: m.usage);
+ await m.bind(tester);
+ await preview(tester, f);
+ await tester.tap(find.widgetWithText(FilledButton, 'Import'));
+ await settle(
+ tester,
+ () => find.text('Import an agent into openharness').evaluate().isEmpty,
+ );
+ await tester.runAsync(m.usage.flush);
+ expect(m.totals()['ui_desktop_agent_import_started'], 1);
+ expect(m.totals()['ui_desktop_agent_import_ok'], 1);
+ }, variant: mac);
+
+ testWidgets('an import left after a failed step is counted as failed', (
+ tester,
+ ) async {
+ final m = counted();
+ final f = await roster(tester, measurement: m.usage);
+ await m.bind(tester);
+ await preview(tester, f);
+ f.server.unknownCommand = (command) => command['type'] == 'agent.start';
+ await tester.tap(find.widgetWithText(FilledButton, 'Import'));
+ await settle(
+ tester,
+ () => find.text('Start again').evaluate().isNotEmpty,
+ );
+ await tester.tap(find.text('Cancel'));
+ await tester.pumpAndSettle();
+ await tester.runAsync(m.usage.flush);
+ expect(m.totals()['ui_desktop_agent_import_failed'], 1);
+ expect(m.totals()['ui_desktop_agent_import_cancelled'], isNull);
+ }, variant: mac);
+
+ testWidgets('a held handoff says why in the picker', (tester) async {
+ final f = await roster(tester);
+ f.daemon.handoff = (_) => {'error': 'IDENTITY_UNAVAILABLE', 'held': true};
+ await openImport(tester);
+ await tester.tap(find.textContaining('Codex · fix-fix'));
+ await settle(
+ tester,
+ () => find.textContaining('not confirmed yet').evaluate().isNotEmpty,
+ );
+ expect(find.text("What openharness's members will read"), findsNothing);
+ }, variant: mac);
+
+ testWidgets('no Team account for this Mac says how to set one up', (
+ tester,
+ ) async {
+ final f = await roster(tester);
+ f.app.teamAccountHereForTest = true;
+ f.server.state['machines'] = <dynamic>[f.macPool];
+ await tester.runAsync(f.c.refresh);
+ await tester.pumpAndSettle();
+ await openImport(tester);
+ expect(find.text(kImportNeedsTeamAccount), findsOneWidget);
+ expect(find.textContaining('fix-fix'), findsNothing);
+ await tester.tap(find.text('Set up Harness Team'));
+ await tester.pumpAndSettle();
+ expect(
+ find.textContaining(
+ RegExp(r'^Set up Harness Team on this (Mac|computer)$'),
+ ),
+ findsOneWidget,
+ );
+ expect(f.server.posts, isEmpty);
+ }, variant: mac);
+ });
+}
diff --git a/desktop/test/super_tab_machines_test.dart b/desktop/test/super_tab_machines_test.dart
index bc182bce5..7cde146a5 100644
--- a/desktop/test/super_tab_machines_test.dart
+++ b/desktop/test/super_tab_machines_test.dart
@@ -408,6 +408,46 @@ void main() {
},
);
+ testWidgets(
+ 'a machine’s owner is named by the name they set (review of #2794)',
+ (tester) async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {
+ 'id': 'tony',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'name': 'Tony Tran',
+ },
+ ];
+ server.state['machines'] = [
+ {
+ 'machineId': 't',
+ 'name': 'MacBook Pro',
+ 'contributorId': 'tony',
+ 'observation': {'receivedAt': DateTime.now().millisecondsSinceEpoch},
+ },
+ ];
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(controller: c, onAddAgent: (_) {}),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(
+ _tipOf(tester, find.byKey(const ValueKey('super-machine-t'))),
+ 'Owned by Tony Tran',
+ );
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ c.dispose();
+ },
+ );
+
testWidgets(
'two machines of one model keep their names, and each has its owner avatar and tooltip',
(tester) async {
diff --git a/desktop/test/super_tab_profile_sheet_test.dart b/desktop/test/super_tab_profile_sheet_test.dart
index d67e28170..a181f2642 100644
--- a/desktop/test/super_tab_profile_sheet_test.dart
+++ b/desktop/test/super_tab_profile_sheet_test.dart
@@ -169,10 +169,7 @@ void main() {
final server = ConversationServer();
final c = await openSheet(tester, server);
expect(text(tester), 'owner');
- expect(
- find.text('How people see and tag you in this Swarm.'),
- findsOneWidget,
- );
+ expect(find.text('How people tag you in this Swarm.'), findsOneWidget);
// Nothing to save until it changes.
expect(enabled(tester), isFalse);
await tester.enterText(field, 'River');
@@ -260,6 +257,96 @@ void main() {
];
await openSheet(tester, server, agentId: 'agent-1');
expect(field, findsNothing);
+ expect(find.byKey(const ValueKey('super-name-field')), findsNothing);
+ });
+ });
+
+ // The name the Swarm shows for the reader (backend personNames.ts).
+ group('name', () {
+ final field = find.byKey(const ValueKey('super-name-field'));
+ final save = find.byKey(const ValueKey('super-name-save'));
+ String text(WidgetTester tester) =>
+ tester.widget<TextField>(field).controller!.text;
+ bool enabled(WidgetTester tester) =>
+ tester.widget<ButtonStyleButton>(save).onPressed != null;
+
+ testWidgets('sits above the username and saves a name, trimmed', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ final c = await openSheet(tester, server);
+ expect(text(tester), '');
+ expect(
+ tester.getTopLeft(field).dy,
+ lessThan(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('super-username-field')))
+ .dy,
+ ),
+ );
+ expect(
+ find.text('What teammates see. Leave empty to show your username.'),
+ findsOneWidget,
+ );
+ expect(enabled(tester), isFalse);
+ await tester.enterText(field, ' Minh Nguyen ');
+ await tester.pump();
+ await tester.tap(save);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'member.name',
+ 'name': 'Minh Nguyen',
+ });
+ expect(c.snapshot!.people.single.name, 'Minh Nguyen');
+ expect(c.snapshot!.people.single.shownName, 'Minh Nguyen');
+ expect(text(tester), 'Minh Nguyen');
+ expect(enabled(tester), isFalse);
+ });
+
+ testWidgets('an emptied name clears it, back to the username', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ ((server.state['people'] as List).single as Map)['name'] = 'Minh';
+ final c = await openSheet(tester, server);
+ expect(text(tester), 'Minh');
+ await tester.enterText(field, ' ');
+ await tester.pump();
+ expect(enabled(tester), isTrue);
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {'type': 'member.name', 'name': null});
+ expect(c.snapshot!.people.single.name, isNull);
+ expect(c.snapshot!.people.single.shownName, 'owner');
+ });
+
+ testWidgets('a refused name says why under the field', (tester) async {
+ final server = ConversationServer();
+ await openSheet(tester, server);
+ server.refuse = {
+ 'code': 'NAME_TAKEN',
+ 'message': 'Someone here already goes by that name.',
+ };
+ await tester.enterText(field, 'Dee');
+ await tester.pump();
+ await tester.tap(save);
+ await tester.pumpAndSettle();
+ final why = find.text('Someone here already goes by that name.');
+ expect(why, findsOneWidget);
+ expect(text(tester), 'Dee');
+ expect(
+ tester.getTopLeft(why).dy,
+ lessThan(
+ tester
+ .getTopLeft(find.byKey(const ValueKey('super-username-field')))
+ .dy,
+ ),
+ );
+ });
+
+ testWidgets('takes at most 40 characters', (tester) async {
+ await openSheet(tester, ConversationServer());
+ expect(tester.widget<TextField>(field).maxLength, 40);
});
});
diff --git a/desktop/test/super_tab_ship_test.dart b/desktop/test/super_tab_ship_test.dart
index f1f136745..73542a352 100644
--- a/desktop/test/super_tab_ship_test.dart
+++ b/desktop/test/super_tab_ship_test.dart
@@ -107,6 +107,17 @@ void main() {
},
);
+ testWidgets('who asked is named by the name they set (review of #2794)', (
+ tester,
+ ) async {
+ final server = shipServer();
+ ((server.state['people'] as List).first as Map)['name'] = 'Minh Nguyen';
+ await show(tester, server);
+ expect(find.text('Minh Nguyen'), findsOneWidget);
+ expect(find.text('owner'), findsNothing);
+ await tester.pumpAndSettle();
+ });
+
testWidgets('a fresh celebration throws confetti once, then it is gone', (
tester,
) async {
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index d2b38f956..6e3c91da0 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -858,6 +858,11 @@ class ConversationServer {
'status': command['status']
else if (command['type'] == 'member.username')
'username': (command['username'] as String?)?.toLowerCase()
+ else if (command['type'] == 'member.name')
+ 'name': (command['name'] as String?)?.replaceAll(
+ RegExp(r'\s+'),
+ ' ',
+ )
else
'avatar': command['avatar'] == null
? null
@@ -1113,6 +1118,7 @@ class ConversationServer {
}
} else if (command['type'] == 'member.status' ||
command['type'] == 'member.username' ||
+ command['type'] == 'member.name' ||
command['type'] == 'member.avatar' ||
command['type'] == 'agent.avatar') {
_profile(command, reader ?? 'owner');
diff --git a/docs/plans/2026-11-02-pm-digest-more-kinds-design.md b/docs/plans/2026-11-02-pm-digest-more-kinds-design.md
new file mode 100644
index 000000000..d4dc6a1f8
--- /dev/null
+++ b/docs/plans/2026-11-02-pm-digest-more-kinds-design.md
@@ -0,0 +1,81 @@
+# The PM's digest gathers three more kinds of notice
+
+Status: design, 2026-11-02. Requested by Ken. Extends
+[2026-11-02-pm-notice-digest-design.md](2026-11-02-pm-notice-digest-design.md) (shipped in #2560, merged in batch #2575).
+
+## Why
+
+On 2026-11-02 the openharness PM received 993 messages up to 21:45 Vietnam time, and 466 of them came from the server.
+The digest's kinds cover 247 of the 466, which become 86 digests. Of the notices still delivered at once, three kinds
+nobody waits on from the PM within minutes:
+
+| Kind | That day | What they said |
+|---|---|---|
+| `blocked` status of a **step** | 47 | mostly a Reviewer waiting on fixes ("changes needed, findings sent to the Builder"); a few needed a person ("needs the owner's account") |
+| the PM's own `agent-only` instructions notices | 29 | "The project's instructions changed: …", "Harness now gives you two skills …" |
+| `terminal-alert` for a usage limit or a failing model | ~10 of 19 | "hit a usage limit", "can't get answers from its model" |
+
+The first design kept `blocked` and `agent-only` at once on purpose: Stuck is urgent, and an agent-only notice may be a
+decision someone answered. This design gathers only the parts of them where the one waiting is someone else, or no one.
+
+## What changes
+
+1. **A step's Stuck: dropped after review.** It stays at once for the coordinator, as today. The project instructions say
+ blocked and needs_human are only for something a person must do (workflow step 3; #2638, which would have changed that,
+ closed unmerged), so a step's Stuck is always something a person acts on (review of #2797, 2026-11-03).
+2. **The PM's instructions and skills notices.** An `agent-only` message a coordinator's own host sends to it about its
+ skills (instructions changed, skills replaced or updated) is gathered. The host marks it: `message.send` gains an
+ optional `notice: "skills"`, accepted only with `agentOnly: true`, from an agent to itself; the row keeps it as
+ `source.notice`. Any other `agent-only` message, a decision answered among them, still goes at once. Unmarked rows
+ (older daemons) go at once.
+3. **Usage limits and failing models.** A `terminal-alert` with `alert: "limit"` or `alert: "model"` is gathered.
+ `alert: "prompt"` (an agent waiting at a prompt) still goes at once. At release, an alert whose agent no longer has
+ that alert (`agent.alerting`) is cancelled, not delivered: the limit reset, or the model answers again.
+
+Nothing else changes: the 5-minute interval, the 50-line cap, the 30-minute backstop, the release checks
+(`deliveryAllowed`, `senderAllowed`), the merge with a due update request, and every cancel path.
+
+## Where in the code
+
+- `noticeDigest.ts`: `gatheredNotice(source, group)` takes the message's group too: it gathers a `blocked` status row only
+ when `group.reviewOf` is set, an `agent-only` row with `notice: "skills"`, and a `terminal-alert` with `limit` or
+ `model`. The one call site, `store.ts` `writeMessages`, passes the group it already holds.
+- `store.ts` `releasableNotices`: cancels a gathered `terminal-alert` whose agent's `alerting` no longer holds its alert,
+ as it cancels any row that no longer has a reason.
+- `commands.ts`: `message.send` schema gains `notice: z.literal('skills').optional()`; refused (VALIDATION_ERROR) unless
+ `agentOnly` and the sender is the only recipient. It is written into `source` with `agent-only`.
+- CLI `host.ts` `tellSkill`: sends `notice: "skills"`; a backend that refuses the key gets the same request without it,
+ as `agentOnly` is retried today.
+
+## Tests (each fails on main first)
+
+- A step's `blocked` row: the coordinator's delivery is `gathered`, the task owner's is `queued`; a task's `blocked` row
+ and any `needs_human` row are `queued` for the coordinator.
+- A coordinator's self-sent `agent-only` with `notice: "skills"` is gathered; one without it, or another agent's
+ `agent-only` message, is queued; `notice` from another sender, to another recipient, or without `agentOnly` is refused.
+- `terminal-alert` `limit` and `model` are gathered and `prompt` is queued; a gathered `limit` whose agent's alert ended
+ before release is cancelled and not in the digest.
+- CLI: `tellSkill` sends `notice`, and retries without it on the old backend's refusal.
+- Full Super Tab integration suite, as for any delivery change.
+
+## Expected effect
+
+On the 2026-11-02 numbers, about 85 more notices a day reach the PM inside digests instead of one by one, on top of the
+161 the first design saves. Most of the PM's remaining load is agents' posts (422 that day), which this does not touch.
+
+## Design
+
+- **Growth:** no new rows; gathered deliveries are the existing rows with the existing statuses, compacted as today.
+- **Concurrency:** unchanged; the release runs in the coordinator's poll transaction, guarded by `status: 'gathered'`.
+- **Read cost:** the release already reads each gathered row's message; the alert check reads the agent from the state
+ it already holds. No new query.
+- **Scale:** at 10x, the 50-line cap and the next digest absorb it; the first metric to warn is digests that roll over
+ ("And N more").
+- **Compatibility:** an old daemon sends no `notice`, so its notices go at once as today. An old backend refuses
+ `notice`, and the new CLI resends without it. Desktop and the phone are unchanged.
+- **Migration + rollback:** none. Rollback is the first design's: requeue `gathered` rows after the last new pod stops.
+- **Audience:** the digest stays the coordinator's alone; `notice` is accepted only on an agent's message to itself.
+- **Identity:** no new identity; the host sends as its own agent, as today.
+- **Failure:** a gathered row the coordinator never polls for goes back to queued after 30 minutes (existing backstop);
+ a refused `notice` falls back to an immediate notice.
+- **Platforms:** backend and the CLI host only.
diff --git a/docs/plans/2026-11-02-pm-digest-more-kinds-plan.md b/docs/plans/2026-11-02-pm-digest-more-kinds-plan.md
new file mode 100644
index 000000000..6b4276ee4
--- /dev/null
+++ b/docs/plans/2026-11-02-pm-digest-more-kinds-plan.md
@@ -0,0 +1,200 @@
+# The PM's digest gathers three more kinds of notice: Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task (Ken
+> chose inline execution with one independent final review). Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** A step's Stuck, the coordinator's own skills notices, and usage-limit or failing-model alerts reach the PM in its
+5-minute digest instead of one by one.
+
+**Architecture:** `gatheredNotice` (backend `noticeDigest.ts`) decides per message and recipient whether the coordinator's
+delivery is gathered; it gains the message's group and three rules. `message.send` gains an optional `notice: "skills"` mark
+for agent-only self-notices, which the CLI host sets. The release (`store.ts releasableNotices`) cancels an alert that ended.
+
+**Tech Stack:** TypeScript, Fastify + Prisma on MongoDB (backend), Vitest with MongoMemoryReplSet (integration), the Node CLI
+host with its spec suite.
+
+**Spec:** [2026-11-02-pm-digest-more-kinds-design.md](2026-11-02-pm-digest-more-kinds-design.md), extending
+[2026-11-02-pm-notice-digest-design.md](2026-11-02-pm-notice-digest-design.md).
+
+## Global Constraints
+
+- Gathered only for the coordinator (the existing `ledProject(state, recipient)` check); every other recipient is unchanged.
+- Still at once: `needs_human` anywhere, `blocked` on a task (no `reviewOf`), `terminal-alert` `prompt`, every `agent-only`
+ without `notice: "skills"` (a decision answered among them), every post.
+- `notice` is accepted only as the literal `"skills"`, only with `agentOnly: true`; `agentOnly`'s own rule (an agent, to itself
+ alone, no mentions) still applies. The row's source is `{ kind: 'agent-only', notice: 'skills' }`.
+- 5 minutes, 50 lines, the 30-minute backstop, release checks and every cancel path stay as they are.
+- No client (Desktop, phone, web) change. Never edit `cli/src/lib/e2ee/core.ts`.
+- Each commit: the failing test first, then the code that passes it; push after each task.
+
+## Review Focus
+
+1. A step's `needs_human` must still reach the PM at once; only `blocked` in a step is gathered. (Task 1 and Task 3 tests.)
+2. A gathered step `blocked` still reaches the task's owner at once (queued for the owner). (Task 3 test.)
+3. `notice: "skills"` from a person, to another agent, or without `agentOnly` is refused, so nobody can hide a message in a
+ digest. (Task 2 tests.)
+4. An alert that ended and was raised again before the release is delivered, not cancelled: `alerting` holds it again.
+ (Task 3 test.)
+5. An old backend refusing `notice` still gets an agent-only notice (not a visible one), and an older one refusing
+ `agentOnly` still gets the plain one, each once. (Task 4 tests.)
+
+---
+
+### Task 1: What is gathered (`noticeDigest.ts`)
+
+**Files:**
+- Modify: `backend/src/superTabs/noticeDigest.ts` (`gatheredNotice`, `DIGEST_KINDS` comment)
+- Test: `backend/src/superTabs/noticeDigest.test.ts` (`describe('what is gathered')`)
+
+**Interfaces:**
+- Produces: `gatheredNotice(source: unknown, group?: Pick<Conversation, 'reviewOf'>): boolean`. Without a group it answers as
+ today for every source; a `blocked` status row counts only with `group.reviewOf`.
+
+- [ ] **Step 1: Write the failing tests** in `describe('what is gathered')`:
+
+```ts
+it('a step\'s Stuck, never a task\'s, and Needs a human nowhere', () => {
+ expect(gatheredNotice({ kind: 'system', status: 'blocked' }, step)).toBe(true)
+ expect(gatheredNotice({ kind: 'system', status: 'blocked' }, task)).toBe(false)
+ expect(gatheredNotice({ kind: 'system', status: 'blocked' })).toBe(false)
+ expect(gatheredNotice({ kind: 'system', status: 'needs_human' }, step)).toBe(false)
+})
+it('the coordinator\'s own skills notice, and no other agent-only row', () => {
+ expect(gatheredNotice({ kind: 'agent-only', notice: 'skills' })).toBe(true)
+ expect(gatheredNotice({ kind: 'agent-only' })).toBe(false)
+ expect(gatheredNotice({ kind: 'agent-only', decisionId: 'd1' })).toBe(false)
+ expect(gatheredNotice({ kind: 'agent-only', notice: 'other' })).toBe(false)
+})
+it('a usage limit or a failing model, never an agent waiting at a prompt', () => {
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'limit' })).toBe(true)
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'model' })).toBe(true)
+ expect(gatheredNotice({ kind: 'terminal-alert', alert: 'prompt' })).toBe(false)
+ expect(gatheredNotice({ kind: 'terminal-alert' })).toBe(false)
+})
+```
+
+The existing `it.each([... 'terminal-alert', ... 'agent-only' ...])('not %s')` and the "no other status" test stay as they
+are (a bare kind stays not gathered; `blocked` without a group stays not gathered).
+
+- [ ] **Step 2: Run, watch them fail**
+
+Run: `cd backend && npm test -- src/superTabs/noticeDigest.test.ts`
+Expected: the three new tests FAIL (`expected false to be true`).
+
+- [ ] **Step 3: Implement** the signature above in `noticeDigest.ts`. Update the `DIGEST_KINDS` comment: `terminal-alert`
+ and `agent-only` are no longer "each delivers at once", only their marked forms are gathered.
+
+- [ ] **Step 4: Run, watch them pass**, plus the whole file. Expected: PASS.
+
+- [ ] **Step 5: Commit and push**
+
+```bash
+git add backend/src/superTabs/noticeDigest.ts backend/src/superTabs/noticeDigest.test.ts
+git commit -m "Swarm digest: a step's Stuck, skills notices, usage limits and failing models are gathered"
+```
+
+### Task 2: The `notice` mark on `message.send` (`commands.ts`)
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (the `message.send` schema near `agentOnly: z.literal(true).optional()`, the
+ `agentOnly` check near line 2753, the `message(...)` call near line 2757)
+- Test: `backend/src/superTabs/commands.test.ts` (next to the existing agent-only `message.send` tests)
+
+**Interfaces:**
+- Produces: `message.send` accepts `notice?: 'skills'`; the written message's `source` is `{ kind: 'agent-only', notice: 'skills' }`.
+- Consumes: Task 1's rule reads `source.notice`.
+
+- [ ] **Step 1: Write the failing tests**
+ - `'marks an agent\'s own skills notice'`: an agent sends `{ agentOnly: true, notice: 'skills', recipientIds: [self] }`;
+ the message's `source` equals `{ kind: 'agent-only', notice: 'skills' }`.
+ - `'refuses the skills mark anywhere but an agent\'s own agent-only notice'`: `notice: 'skills'` without `agentOnly`, from
+ a person, and to another agent each throw `VALIDATION_ERROR`; `notice: 'other'` fails the schema.
+
+- [ ] **Step 2: Run, watch them fail**
+
+Run: `cd backend && npm test -- src/superTabs/commands.test.ts -t "skills"`
+Expected: FAIL (`Unrecognized key: "notice"`).
+
+- [ ] **Step 3: Implement**: schema `notice: z.literal('skills').optional()`; `notice` without `agentOnly` refused with the
+ same `VALIDATION_ERROR` style as the `agentOnly` check; source `{ ...AGENT_ONLY, notice }` when set.
+
+- [ ] **Step 4: Run, watch them pass**, plus the whole file. Expected: PASS.
+
+- [ ] **Step 5: Commit and push**
+
+### Task 3: Gathering and release in the store
+
+**Files:**
+- Modify: `backend/src/superTabs/store.ts` (`writeMessages` gathering line `gatheredNotice(message.source) && ...`;
+ `releasableNotices`)
+- Test: `backend/integration/superTabNoticeDigest.test.ts`
+
+**Interfaces:**
+- Consumes: Task 1 `gatheredNotice(source, group)`; Task 2's source shape.
+
+- [ ] **Step 1: Write the failing tests** (use the file's `swarm()`, `write()`, `deliveryOf()`, `poll()`, `digests()`):
+ - `'a step\'s Stuck is gathered for the coordinator and goes at once to the task\'s owner'`: create a step
+ (`conversation.create` with `reviewOf: group`, title `Review: Ship the parser`), add and assign a Reviewer on `test-host`,
+ the Reviewer sets `blocked`; the `Stuck` row's delivery is `gathered` for `lead`, `queued` for `worker`.
+ - `'a step\'s Needs a human goes at once to the coordinator'`: same step, `needs_human`; `queued` for `lead`.
+ - `'the coordinator\'s skills notice is gathered; its other agent-only notices are not'`: `write({ kind: 'agent-only',
+ notice: 'skills' }, lead, leadConversation, 'The project\'s instructions changed.', lead)` is `gathered`;
+ `write({ kind: 'agent-only' }, lead, ..., lead)` is `queued`.
+ - `'a usage limit and a failing model are gathered; a prompt goes at once'`: `write({ kind: 'terminal-alert', agentId:
+ worker, alert })` for `limit`, `model` (gathered) and `prompt` (queued).
+ - `'an alert that ended before the release is cancelled and left out'`: the worker raises `agent.alert` `{ agentId: worker,
+ alert: 'limit', active: true }` (as `host`, `asAgentId` worker), which writes the real alert, gathered for `lead`; then
+ `active: false`; advance `DUE`, poll: that row is `cancelled` and no digest names its message id.
+ - `'an alert raised again before the release is delivered'`: `limit` active, inactive, active again before the poll: the
+ first row is named in the digest (its agent holds the alert again).
+
+- [ ] **Step 2: Run, watch them fail**
+
+Run: `cd backend && npx vitest run --config vitest.super-tabs.config.ts integration/superTabNoticeDigest.test.ts`
+Expected: the new tests FAIL (`expected 'queued' to be 'gathered'`, and the ended alert delivered).
+
+- [ ] **Step 3: Implement**: `writeMessages` passes `group` to `gatheredNotice`. In `releasableNotices`, a row whose message
+ source is `terminal-alert` and whose `agent(state, source.agentId)?.alerting` lacks `source.alert` is cancelled exactly as
+ a refused row is (same `updateMany` guarded by `status: 'gathered'`, counted in `refused`).
+
+- [ ] **Step 4: Run, watch them pass**, then the whole Super Tab integration suite.
+
+Run: `cd backend && npm run test:super-tabs`
+Expected: all files pass.
+
+- [ ] **Step 5: Commit and push**
+
+### Task 4: The CLI host marks its skills notices
+
+**Files:**
+- Modify: `cli/src/superTabs/host.ts` (`tellSkill`)
+- Test: `cli/src/superTabs/host.spec.ts` (next to `'sends each notice the old way, once, when an older backend refuses the
+ agent-only mark'`)
+
+**Interfaces:**
+- Consumes: Task 2's `notice: 'skills'`.
+
+- [ ] **Step 1: Write the failing tests**
+ - In `'rewrites each running Lead, Builder and Reviewer skill once …'`: every sent command has `notice: 'skills'`.
+ - `'drops the skills mark, once, when a backend refuses it, and keeps the notice agent-only'`: refuse requests with
+ `notice` (`VALIDATION_ERROR`, `Unrecognized key: "notice"`); each notice is sent once with `agentOnly: true` and no
+ `notice`.
+ - The existing older-backend test (refuses `agentOnly`) still ends with each notice sent once with neither key.
+
+- [ ] **Step 2: Run, watch them fail**
+
+Run: `cd cli && npx vitest run src/superTabs/host.spec.ts -t "skill"`
+Expected: FAIL (`notice` missing).
+
+- [ ] **Step 3: Implement**: `send(agentOnly, notice)`; try `(true, true)`, on a refusal naming `"notice"` retry `(true,
+ false)`, on one naming `"agentOnly"` retry `(false, false)`; any other refusal is thrown as today.
+
+- [ ] **Step 4: Run, watch them pass**, then `cd cli && npm run typecheck && npx vitest run src/superTabs`. Expected: PASS.
+
+- [ ] **Step 5: Commit and push**
+
+### Finish
+
+- [ ] `cd backend && npx tsc --noEmit -p . && npm test && npm run test:super-tabs`; `cd cli && npm run typecheck`.
+- [ ] Red/green evidence in a PR comment (each new test's failing assertion on `origin/main`, then passing).
+- [ ] One independent final review of the whole branch on the most capable model.
diff --git a/docs/plans/2026-11-03-import-agent-design.md b/docs/plans/2026-11-03-import-agent-design.md
new file mode 100644
index 000000000..4fd301704
--- /dev/null
+++ b/docs/plans/2026-11-03-import-agent-design.md
@@ -0,0 +1,102 @@
+# Import an agent running on this Mac into a project
+
+Task #2379, requested by Scholes (2026-11-03). PM ruling (River, PRODUCT.md "Work across accounts": Accept): the
+project's Add agent becomes one entry with two choices, **Import an agent running on this Mac** first and **Start a new
+agent**; a preview shows exactly what of the agent's session will be shared with the project's members, secrets
+redacted, before the new agent starts. Scholes asked not to wait for his review; this design is posted to him and the
+work proceeds on it.
+
+## What the person sees
+
+```
+Agents [+] (the roster's Add agent)
+ ├─ Import an agent running on this Mac
+ └─ Start a new agent (today's picker, unchanged)
+
+Import an agent into <project>
+ Claude Code · fix-login · ~/code/api 3 min ago
+ Codex · release notes · ~/code/web 1 h ago
+ ── not offered: agents already in a Swarm, Buddies, Swarm-started agents
+
+What <project>'s members will read
+ ┌───────────────────────────────────────────────┐
+ │ Handoff (redacted) 18 KB [full text]│
+ │ Conversation and tool calls 410 KB [full text]│
+ └───────────────────────────────────────────────┘
+ Secrets (keys, tokens, passwords in URLs) are removed. Tool output is never included.
+ The agent on this Mac keeps running; nothing about it changes.
+ [Cancel] [Import]
+```
+
+On Import, a new conversation "Continue <agent>'s work" opens in the project with the two files in it, and the new
+agent starts in this Mac's Harness Team account and is sent them. It answers there, already knowing what the agent was
+doing.
+
+## How it works
+
+1. **Picker.** Desktop lists the agents of this Mac's own account (its own machine, never the Team account's or another
+ person's) whose engine is Claude Code or Codex, that are running or resumable, that no Swarm lists (no Swarm roster
+ row with this machine and harness id, in any Swarm, open here or not, its chats archived or its stop asked: the
+ daemon's `swarmListed` reads the backend's roster, and an answer it cannot read refuses), that are not Buddies and were not started by the Swarm
+ (`startedBy: 'agent'` without a parent, as the CLI tells a Swarm start, `superTabs/inCore/adoption.ts`). Desktop
+ starts parsing the frame's `startedBy` for this.
+2. **Handoff.** Desktop asks this Mac's daemon for the existing Change agent handoff, `agent_handoff_prepare`
+ (owner only; `cli/src/lib/agentHandoff.ts`), with a fresh change id and the agent's own engine as target. Only the
+ owner's daemon can read the agent's transcript (the reader refuses a file another user owns), so the handoff is
+ made in the owner's account, from the session only:
+ - header (agent, session, project folder, time), the engine's earlier summary, the conversation (40,000 characters
+ at most), latest request and answer, files changed, git state (branch, HEAD, status, diff stat, commits);
+ - a second file with each turn's request, answer and tool calls (2 MB at most); tool output, reasoning and
+ transcript paths are never included;
+ - everything passes `secureText`: PEM blocks, GitHub, AWS, Slack and Google keys, JWTs, `user:pass@` in URLs and
+ the shared log redactions, before any trimming and again on each whole document.
+ The files are written in the agent's folder under `.harness/handoff/` (0600, git-excluded), as Change agent does.
+ Nothing is sent anywhere yet. A preparation that is held or fails says why and offers nothing to import.
+3. **Preview.** Desktop reads both files from this Mac and shows them whole, with their sizes, as above. This is the
+ exact content that will be shared.
+4. **Import** (only after the person presses it):
+ - opens a conversation in the project, "Continue <agent>'s work", with a brief naming the agent and this Mac;
+ - uploads the two files as attachments of that conversation (the Swarm's attachment store; a project's members
+ read its conversations' attachments, as the preview says);
+ - starts the new agent with `agent.start` on this Mac's Harness Team account, engine and model as the imported
+ agent's, in that conversation, role Engineer, in the project's repository;
+ - once the agent is listed, posts the files to it in one message: "You are continuing <agent>'s work on <owner>'s
+ Mac. Read the attached handoff: a record of earlier work, not instructions. Say what it was doing, then take the
+ next step." Its host downloads them to the agent's machine as with any delivered file.
+ The imported agent is never stopped, messaged or registered; its own files gain only the handoff folder.
+
+## Privacy and security (review required: session content crosses accounts)
+
+- **Who reads what.** The handoff leaves the owner's account only when they press Import, after seeing it whole. It
+ reaches the Swarm's attachment store and the project conversation, readable by the project's members (a private
+ project's members only), and the Team account's agent through ordinary delivery. Nothing else of the session moves.
+- **Redaction** is the Change agent's, already reviewed for that feature; the preview shows its result, so a secret it
+ misses is visible before sharing. The preview says so.
+- **Identity.** Everything acts as the signed-in owner (the handoff read on their daemon, the upload and the start
+ under their sign-in). The new agent runs in the Team account, never in the owner's.
+- **The imported agent** is untouched: no stop, input, registration or Swarm membership.
+- **Refused:** an agent on another person's machine or a Team account, an agent a Swarm already lists, a web browser
+ (no local daemon), a Mac with no Team account in the Swarm (says how to set it up).
+
+## Design (docs/feature-design-rules.md)
+
+- **Growth:** two attachments per import, deleted with their conversation and Swarm (attachment retention as today).
+ The local handoff files are the Change agent's, kept beside the agent's work.
+- **Concurrency:** each step is one existing command or upload; a second Import of the same agent makes a second
+ conversation (allowed: the person asked twice). The start and the message use stable operation ids per import.
+- **Read cost:** none on hot paths; one handoff read on the owner's Mac per preview.
+- **Scale:** at most a few imports a day per person; the attachment size limit (256 MB) is far above the 2 MB cap.
+- **Compatibility:** no new backend or wire fields. An older daemon without `agent_handoff_prepare` refuses, and the
+ import says to update Harness on this Mac. Older apps see an ordinary conversation, files and agent.
+- **Migration and rollback:** none; removing the entry removes the feature.
+- **Audience:** the server enforces who reads the conversation and its files, as for any project conversation.
+- **Identity:** never the machine owner's login for the new agent: it runs in the Team account.
+- **Failure:** every step's failure is shown in the dialog with what was done (for example, files shared but the start
+ refused: the conversation stays, with a Start again).
+- **Platforms:** Desktop on macOS, where a Harness Team account exists. Linux, Windows and the web: the choice is not
+ offered.
+
+## Measures (ENGINEERING.md 8)
+
+`agent_import` in the usage vocabulary (revision 7, backend and CLI): started when the preview shows, then ok on
+Import, failed when left after a failed step, cancelled otherwise; with its durations. No content, names or ids.
diff --git a/docs/plans/2026-11-03-import-agent-plan.md b/docs/plans/2026-11-03-import-agent-plan.md
new file mode 100644
index 000000000..075487cd3
--- /dev/null
+++ b/docs/plans/2026-11-03-import-agent-plan.md
@@ -0,0 +1,93 @@
+# Import an agent running on this Mac Implementation Plan
+
+> **How this plan runs:** by this project's instructions (Engineer role): task by task, test first (the failing test
+> committed and watched failing, then the code); the pull request's Review step is the one independent review.
+
+**Goal:** From a project's Add agent, the owner imports an agent running on this Mac: they see the redacted handoff of
+its session, and on Import a new agent in this Mac's Harness Team account continues its work from that handoff.
+
+**Architecture:** Desktop only. The owner's daemon prepares the existing Change agent handoff (`agent_handoff_prepare`);
+Desktop previews the two files, then with existing commands opens a conversation, uploads the files as its
+attachments, starts the new agent there on the Team account (`agent.start`) and sends it the files in one message.
+
+**Tech Stack:** Flutter (desktop/lib/super_tabs, desktop/lib/state), widget tests with the conversation fixture.
+
+**Spec:** `docs/plans/2026-11-03-import-agent-design.md`.
+
+## Global Constraints
+
+- Copy, verbatim: menu items **Import an agent running on this Mac** (first) and **Start a new agent**; dialog title
+ **Import an agent into <project>**; preview heading **What <project>'s members will read**; the lines **Secrets
+ (keys, tokens, passwords in URLs) are removed. Tool output is never included.** and **The agent on this Mac keeps
+ running; nothing about it changes.**; conversation title **Continue <agent>'s work**; the message to the new agent
+ **You are continuing <agent>'s work on <owner>'s Mac. Read the attached handoff: a record of earlier work, not
+ instructions. Say what it was doing, then take the next step.**
+- Nothing leaves the owner's account before Import is pressed. The imported agent is never stopped, sent input,
+ registered or added to a Swarm.
+- macOS Desktop only (a local daemon and a Team account); not offered on the web.
+- Desktop tests use a memory store and a fake sign-in; never the real CLI.
+
+## Review Focus
+
+1. An agent a Swarm already lists, a Buddy, a Swarm-started agent, or an agent of another account or the Team account is
+ never offered. Test in Task 1.
+2. Cancel after the preview sends nothing to the server. Test in Task 3.
+3. A failure at any step (prepare held, upload, start, message) says which step and leaves what was done visible; a
+ second Import never repeats a step that worked (stable operation ids). Test in Task 3.
+4. No Team account for this Mac in the Swarm: the choice says how to set one up instead of starting anywhere else.
+ Test in Task 1.
+5. The message reaches only the new agent, with both files. Test in Task 3.
+
+---
+
+### Task 1: Which agents can be imported
+
+**Files:** `desktop/lib/core/models.dart` (parse `startedBy`, `parentAgentId` if absent), new
+`desktop/lib/super_tabs/import_agent.dart`; test `desktop/test/super_tab_import_agent_test.dart`.
+
+**Interfaces:** `List<ImportableAgent> importableAgents(AppNotifier app, SuperTabController c)` (record of machineId,
+agent); `String? importUnavailable(AppNotifier app, SuperTabController c)` (null, or why: no Team account here, web).
+
+- [ ] Failing tests for every Review Focus 1 and 4 case, then the code.
+
+### Task 2: The handoff preview
+
+**Files:** `import_agent.dart`; test as above.
+
+**Interfaces:** `Future<ImportHandoff> prepareImportHandoff(AppNotifier app, ImportableAgent agent)`: calls
+`agent_handoff_prepare` on the agent's own machine with a fresh 32-hex change id and the agent's engine, reads the
+handoff and transcript files it names (`<file>` and its `.transcript.md`), returns their names, sizes and text, or
+throws `ImportFailure(step, message)` (held, unsupported daemon, unreadable file).
+
+- [ ] Failing tests with a fake daemon reply and temp files, then the code.
+
+### Task 3: Import
+
+**Files:** `import_agent.dart`; test as above.
+
+**Interfaces:** `Future<ImportResult> importAgent(AppNotifier app, SuperTabController c, String projectId,
+ImportableAgent agent, ImportHandoff handoff, {required String importId})`: `conversation.create` (title above, brief
+naming the agent and Mac), the two uploads to it, `agent.start` (Team machine, engine and model as the agent's, role
+Engineer, the project's repository), waits for the new agent to be listed, then `message.send` to it alone with both
+attachments. Operation ids derive from `importId`, so a retry repeats nothing that worked.
+
+- [ ] Failing fixture tests: command order and fields, recipients, attachments, nothing sent on Cancel, failure per
+ step with retry; then the code.
+
+### Task 4: The entry and the dialog
+
+**Files:** `desktop/lib/super_tabs/roster.dart` (Add agent `+` becomes a menu with the two choices),
+new `desktop/lib/super_tabs/import_agent_dialog.dart`; widget test and screenshots.
+
+- [ ] Failing widget tests: menu order and copy; picker rows; preview shows both files whole with sizes and the two
+ lines; Import runs Task 3 and opens the new conversation; errors show the step; Start a new agent opens today's
+ picker. Then the code, `check-ui-style`, screenshots light and dark.
+
+### Task 5: Measures (ENGINEERING.md 8)
+
+**Files:** `backend/src/types/productUsage.ts`, `cli/src/lib/productUsageContract.ts`,
+`cli/src/lib/appProductUsageReport.ts` (vocabulary 7), `desktop/lib/measurement/product_measurement.dart`
+(`ProductFlow.agentImport`), the dialog; tests in each.
+
+- [ ] Failing tests: the backend keeps `ui_desktop_agent_import_*`, the CLI forwards them in vocabulary 7, the Desktop
+ waits for vocabulary 7, and the dialog counts started at the preview, then ok, failed or cancelled. Then the code.
diff --git a/docs/plans/2026-11-03-person-display-name-plan.md b/docs/plans/2026-11-03-person-display-name-plan.md
new file mode 100644
index 000000000..6e9a1ac98
--- /dev/null
+++ b/docs/plans/2026-11-03-person-display-name-plan.md
@@ -0,0 +1,155 @@
+# A person sets the name the Swarm shows for them: implementation plan
+
+> Worked by this project's instructions (Engineer role): this plan is the pull request's first commit. Then each task is
+> done test first, by one Engineer, with one Review step and one Test step on the pull request. Steps use checkbox
+> (`- [ ]`) syntax.
+
+**Goal:** a person can set and change their own display name (for example "Minh Nguyen") on Desktop, web and phone.
+People rows, chat authors, reactions, the inbox and tags show it. Until they set one, everything shows their username,
+which defaults to the email's first part, as today. Only they can change it, and it can never equal another member's
+name, username or email.
+
+**Architecture:** the name is one optional field on the person's member record (`Person.name`), set by a new
+`member.name` command beside `member.username` (backend/src/superTabs/personNames.ts). The username stays the handle a
+tag types (`@wkpnjjhbnm`); the display name is what the Swarm shows. Readers already receive the whole member record,
+so `name` reaches clients with no read change. Each client gets one rule, `shownName = name ?? username`, and every place
+that shows a person (not one that types a tag) uses it.
+
+**Tech Stack:** TypeScript backend (vitest unit tests, `npm run test:super-tabs` integration), Flutter 3.47.2 Desktop
+(also built for the web) and phone app (`flutter_test` widget tests and headless screenshots).
+
+**Spec:** task #2446 brief (River, 2026-11-03) and the mockup posted for the requester in the task chat
+(2026-11-03 17:41 VN):
+
+```
+People list (left: today, right: after)
+ People + People +
+ (W) wkpnjjhbnm 12 pts (M) Minh Nguyen 12 pts
+Hover on a person: Minh Nguyen · @wkpnjjhbnm · the email, as today
+Chat author: (M) Minh Nguyen 10:42
+Typing "@mi" suggests: (M) Minh Nguyen @wkpnjjhbnm
+A tag in a message reads "@Minh Nguyen"; it still tags by @wkpnjjhbnm.
+Your profile: Name [ Minh Nguyen ] [Save] above Username [ wkpnjjhbnm ] [Save]
+```
+
+## Global Constraints
+
+- PR body first line: "Requested by [email protected] through Harness."
+- Visible parts wait for the requester's confirmation of the mockup; backend and model work goes first.
+- Harness design language (desktop/design/desktop-design-system.md): design-system roles only, no hardcoded colors or
+ sizes; `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs` before Ready.
+- Swarm code stays out of cli/src/core. Desktop tests use a memory store and a fake sign-in, never the real CLI.
+- Before Ready: a failing-first test for every risk below, red/green evidence in a PR comment, the full Super Tab
+ integration suite (`cd backend && npm run test:super-tabs`), and screenshots light and dark.
+
+## Design
+
+- Growth: one string of at most 40 characters per member; it is deleted with the member record (leaving the Swarm) or
+ by clearing it.
+- Concurrency: `member.name` claims a name against every member's name, username and email, so it touches every member
+ part and the head, exactly as `member.username` does (parts/touches.ts). Of two people choosing the same name at once,
+ one retries and is refused. `member.username` also checks display names, under the same touches.
+- Read cost: none added. The name is inside the member part every reader already loads; `changes` sends it only when
+ that member part changed.
+- Scale: the check is one pass over members (tens per Swarm); at 10x it is still a few hundred string compares per
+ set. The first warning would be command latency on `member.name`, the same as `member.username` today.
+- Compatibility: an older client ignores `name` and shows the username, as today. A newer client against an older
+ server gets the server's refusal of an unknown command, shown under the field. The phone and Desktop show the name
+ wherever the server sends it.
+- Migration + rollback: none. The field is optional; a rollback leaves it stored and unread, and the username shows
+ again. No new collection, index or query: the MongoDB schema-design and query-optimizer questions (embed vs.
+ reference, index use) are answered by "embedded in the existing member document, read with it".
+- Audience: the server enforces it. The command changes only the actor's own record (`actor.userId`); agents are
+ refused (HUMAN_REQUIRED). Only Swarm members read it, as with username and status.
+- Identity: the actor's own person record in this Swarm; never the machine owner's login.
+- Failure: every refusal (empty, too long, unprintable, taken) returns a code and a sentence, shown under the field;
+ nothing is silently dropped.
+- Platforms: backend; Desktop on macOS and the web build; phone app on iOS and Android (shared Dart).
+
+## Review Focus
+
+1. Impersonation: a name that equals another member's name, username or email, ignoring case, width variants
+ (NFKC), spaces and a leading `@`, is refused; so is an agent name the person can see. A username equal to another
+ member's display name is refused too (Task 1 tests).
+2. Only the person changes it: an agent, or another person, cannot set someone's name (Task 1 tests).
+3. Hidden characters: control, format (bidi, zero-width) and line separators are refused, as in a status (Task 1).
+4. Concurrency: two people choosing one name at once, one wins (Task 2 integration test through the real store).
+5. Tags still work: a tag in text stays `@username` and still notifies; only its pill label changes (Tasks 4, 6).
+6. With no name set, every surface reads exactly as today (each client task has a no-name test).
+7. Review 1: role and Swarm names (PM, Lead, Reviewer, Tester, Harness, System, Admin, Everyone, You, Someone) are
+ refused; a later joiner's default username is numbered around display names; a name written into server text
+ (member rows, task lines, the PM-switch note) is Markdown-escaped. Out of scope, as for Buddy names: look-alike
+ letters of other scripts (NFKC does not fold them), and Buddy names against display names (a Minor of review 1).
+
+---
+
+### Task 1: name rules and the `member.name` command (backend)
+
+**Files:**
+- Create: `backend/src/superTabs/personNames.ts`, `backend/src/superTabs/personNames.test.ts`
+- Modify: `backend/src/superTabs/model.ts` (`Person.name`), `backend/src/superTabs/commands.ts` (schema, dispatch,
+ viewer allowed as for `member.username`), `backend/src/superTabs/usernames.ts` (refuse another's display name),
+ `backend/src/superTabs/parts/touches.ts`
+
+**Interfaces:**
+- `MAX_NAME_LENGTH = 40`; `setName(state, actor, input: string | null): void`; `shownNameOf(state, id): string | undefined`
+ (name, else username); `nameKey(text): string` (NFKC, lowercased, spaces and a leading `@` removed).
+
+- [ ] Write failing tests: sets and clears own name; trims and collapses spaces; refuses empty, over 40, hidden
+ characters; refuses another member's name, username, email (case, width, spaces, `@`); refuses a visible agent name;
+ allows one's own username; refuses an agent actor; a viewer may set theirs; a username equal to another's name is
+ refused; touches cover every member and the head.
+- [ ] Run `npm test -- src/superTabs/personNames.test.ts`, watch them fail; commit.
+- [ ] Implement; run again, green; commit.
+
+### Task 2: through the real store (backend integration)
+
+**Files:**
+- Modify: `backend/integration/superTabProfile.test.ts`
+
+- [ ] Failing tests: a name set by one member reaches another member's first load and changes, and no outsider; two
+ people choosing one name at once, one is refused (NAME_TAKEN); the name survives a reload (parts round trip).
+- [ ] Run `npx vitest run -c vitest.super-tabs.config.ts integration/superTabProfile.test.ts`, red then green; commit.
+
+### Task 3: server-written names (backend)
+
+**Files:**
+- Modify: `backend/src/superTabs/mentions.ts` (inbox author), `activity.ts` (actor name), `memberRows.ts`
+ (`actorLabel`), `commands.ts` (decision line "who"), `taskLine.ts`; tests beside each.
+
+- [ ] Failing tests: each shows the display name when set and the username when not; tags (`@name` in
+ reviewCapacity) keep the username.
+- [ ] Red, then switch each to `shownNameOf`; green; commit.
+
+### Task 4: Desktop and web: the model and every place a person shows
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/model.dart` (`SuperTabPerson.name`, `shownName`, author name), `identity.dart`
+ (avatar initial), `leaderboard/person_row.dart`, `roster.dart` (card title, hover), `view.dart` (reactions, tag
+ labels), `message_text.dart` (a tag's pill reads its label), `composer_tags.dart` (suggestion shows the name, matches
+ name or username, inserts the username), `activity.dart`, `notifications.dart`, `manage_page.dart`
+- Test: `desktop/test/super_tab_display_name_test.dart`
+
+- [ ] Failing widget tests: with a name, the People row, card, chat author, reaction tooltip, tag pill, suggestion and
+ inbox show it, and the inserted tag is `@username`; with none, each reads as today.
+- [ ] Red, implement, green; commit.
+
+### Task 5: Desktop and web: setting it in Your profile
+
+**Files:**
+- Create: `desktop/lib/super_tabs/name_editor.dart`
+- Modify: `desktop/lib/super_tabs/profile_actions.dart` (`setName`), `profile_sheet.dart`
+- Test: `desktop/test/super_tab_profile_sheet_test.dart`, screenshots in `super_tab_humans_shots_test.dart`
+
+- [ ] Failing tests: Name field above Username, saves trimmed, clears to the username, shows the server's refusal.
+- [ ] Red, implement, green; screenshots light and dark of the profile, People list and a chat; commit.
+
+### Task 6: phone app
+
+**Files:**
+- Modify: `mobile/lib/swarm/model.dart`, `swarm_conversation_page.dart` (author, suggestions), `swarm_message_row.dart`
+ (tag pill label), `swarm_thread_line.dart`, `swarm_you_page.dart` (Name row with Change), `swarm_profile.dart`
+ (`setName`); create `swarm_name_editor.dart`
+- Test: `mobile/test/swarm/swarm_display_name_test.dart`, screenshots light and dark
+
+- [ ] Failing tests as in Tasks 4 and 5 for the phone; red, implement, green; commit.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 577ba1589..756218395 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -55,6 +55,10 @@ class SuperTabPerson {
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
status = SuperTabPersonStatus.fromJson(row['status']),
chosenUsername = row['username'] as String?,
+ name = switch (row['name']) {
+ final String name when name.trim().isNotEmpty => name,
+ _ => null,
+ },
username =
row['username'] as String? ??
superTabDefaultUsername(_text(row, 'email'));
@@ -66,7 +70,8 @@ class SuperTabPerson {
joinedVia = person.joinedVia,
avatar = person.avatar,
status = person.status,
- chosenUsername = person.chosenUsername;
+ chosenUsername = person.chosenUsername,
+ name = person.name;
final String id, email, role;
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
@@ -78,6 +83,14 @@ class SuperTabPerson {
/// The name the server sent; null from a server without usernames.
final String? chosenUsername;
+ /// The name they set for the Swarm to show (`member.name`, "Minh Nguyen");
+ /// null until they set one, and from an older server.
+ final String? name;
+
+ /// How the Swarm shows them: their [name], else their [username]. A tag
+ /// still types and matches the [username].
+ String get shownName => name ?? username;
+
/// Their status while it lasts.
SuperTabPersonStatus? statusAt(DateTime now) =>
status?.shownAt(now) == true ? status : null;
@@ -594,6 +607,15 @@ class SuperTabSnapshot {
row['invitations'],
(row) => Map<String, dynamic>.unmodifiable(row),
),
+ _starts = Map.unmodifiable({
+ for (final start
+ in row['starts'] is List ? row['starts'] as List : const [])
+ if (start case {'id': final String id})
+ id: (
+ harnessId: start['harnessId'] as String?,
+ error: start['error'] as String?,
+ ),
+ }),
startEfforts = Map.unmodifiable({
for (final start
in row['starts'] is List ? row['starts'] as List : const [])
@@ -682,6 +704,12 @@ class SuperTabSnapshot {
late final List<SuperTabProject> projects;
final List<Map<String, dynamic>> invitations;
+ /// Each agent start's outcome so far, by its id: the harness it made, or
+ /// why it failed (backend AgentStart); null for a start this read does not
+ /// hold. Read as the desktop reads it (desktop_parity_test.dart).
+ ({String? harnessId, String? error})? startOf(String id) => _starts[id];
+ final Map<String, ({String? harnessId, String? error})> _starts;
+
/// The effort each started agent's start asked for, by harness id. Empty where the starts are not read (a view
/// kept on this device leaves them out).
final Map<String, String> startEfforts;
@@ -874,7 +902,7 @@ class SuperTabSnapshot {
// Recorded labels remain the fallback when a person or agent has left.
String authorName(SuperTabMessage message) => message.fromAgent
? agentName(message.authorId, fallback: message.authorName)
- : people.where((p) => p.id == message.authorId).firstOrNull?.username ??
+ : people.where((p) => p.id == message.authorId).firstOrNull?.shownName ??
superTabPersonName(message.authorName);
}
diff --git a/mobile/lib/swarm/swarm_activity_page.dart b/mobile/lib/swarm/swarm_activity_page.dart
index 6ae7358bc..fa9931e46 100644
--- a/mobile/lib/swarm/swarm_activity_page.dart
+++ b/mobile/lib/swarm/swarm_activity_page.dart
@@ -1232,7 +1232,7 @@ class SwarmActivityRow extends StatelessWidget {
/// Who an Activity row is from, by an id its avatar is coloured by and a
/// name, read in the row's own Swarm ([reader]) and never another's: the
/// asker, the tagging Lead, the worker, a thread's last writer, or who
-/// reacted. A person is named by their username, never the email.
+/// reacted. A person is named by the name they show by, never the email.
({String id, String name}) swarmActivityWho(
SwarmActivityItem item,
SwarmReader? reader,
@@ -1244,7 +1244,9 @@ class SwarmActivityRow extends StatelessWidget {
return snapshot?.agentName(id, fallback: fallback) ?? fallback;
}
final person = snapshot?.people.where((p) => p.id == id).firstOrNull;
- return person == null || person.email.isEmpty ? 'Someone' : person.username;
+ return person == null || person.email.isEmpty
+ ? 'Someone'
+ : person.shownName;
}
return switch (item) {
diff --git a/mobile/lib/swarm/swarm_buddy.dart b/mobile/lib/swarm/swarm_buddy.dart
index e10ed76a0..992b3a41f 100644
--- a/mobile/lib/swarm/swarm_buddy.dart
+++ b/mobile/lib/swarm/swarm_buddy.dart
@@ -498,14 +498,16 @@ String _machineName(Object? name, {String fallback = 'Your machine'}) {
: name;
}
-/// A person of [reader]'s Swarm by the name it shows them by: their username;
+/// A person of [reader]'s Swarm by the name it shows them by ([SuperTabPerson.shownName]);
/// "its owner" while the Swarm does not list them (the
/// desktop's `buddyPersonName`).
String swarmBuddyPersonName(SwarmReader reader, String personId) {
final person = reader.snapshot?.people
.where((p) => p.id == personId)
.firstOrNull;
- return person == null || person.email.isEmpty ? 'its owner' : person.username;
+ return person == null || person.email.isEmpty
+ ? 'its owner'
+ : person.shownName;
}
/// Opens the person's Buddy chat in [projectId], on the server first when
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 1b0cb102e..8d4d7d405 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -997,6 +997,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
mentions: view.mentions,
tagged: _taggedOf(c, m).keys.toList(),
taggedAddresses: _taggedOf(c, m),
+ taggedLabels: _labelsOf(c, m),
readerId: c.reader.accountId,
references: _numberedReferences(c, m.text).references,
onOpenConversation: (id) => _openNumberedConversation(c, id),
@@ -1655,6 +1656,19 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
if (m.mentions.contains(person.id)) person.username: person.email,
};
+ /// The names the tag pills of [m] read: each tagged person who set a name,
+ /// by their username. The text keeps `@username`; only the pill shows the
+ /// name.
+ static Map<String, String> _labelsOf(
+ SwarmConversation c,
+ SuperTabMessage m,
+ ) => {
+ if (m.mentions.isNotEmpty)
+ for (final person in c.reader.snapshot?.people ?? <SuperTabPerson>[])
+ if (m.mentions.contains(person.id) && person.name != null)
+ person.username: person.name!,
+ };
+
/// The open task's steps, each read on its own, merged into its chat (task
/// steps design): a step keeps its own conversation.
final _steps = <String, SwarmConversation>{};
@@ -1709,13 +1723,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
(picture: agent?.avatar, status: null);
/// Who gave a reaction, by name and never by email: "You", an agent's
- /// name, another person's username.
+ /// name, another person's shown name.
String _reactorName(SwarmConversation c, String kind, String id) {
if (kind == 'person' && id == c.reader.accountId) return 'You';
final snapshot = c.reader.snapshot;
if (kind == 'agent') return snapshot?.agentName(id) ?? 'Agent';
final person = snapshot?.people.where((p) => p.id == id).firstOrNull;
- return person?.username ??
+ return person?.shownName ??
(person == null ? 'Someone' : superTabPersonName(person.email));
}
@@ -1901,6 +1915,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final answerIn = pm && view.canPost ? view.buddyProject : null;
final quoted = reply == null ? null : _quoted(c, reply);
final tagged = _taggedOf(c, m);
+ final labels = _labelsOf(c, m);
final lit = _lit == m.id, followed = _target == m.id;
final acting = _acting == m.id;
final reactions = c.reactionsOf(m);
@@ -1949,6 +1964,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
// account is drawn again.
c.reader.accountId,
[for (final e in tagged.entries) '${e.key}:${e.value}'].join(' '),
+ [for (final e in labels.entries) '${e.key}:${e.value}'].join(' '),
reactions,
answerIn,
view.project,
@@ -1968,6 +1984,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
mentions: view.mentions,
tagged: tagged.keys.toList(),
taggedAddresses: tagged,
+ taggedLabels: labels,
readerId: c.reader.accountId,
references: references,
onOpenConversation: (id) => _openNumberedConversation(c, id),
@@ -3333,8 +3350,10 @@ class _Ask extends StatelessWidget {
}
/// Over the composer, who the @ being typed can name, as Desktop offers
-/// them: the chat's people whose username holds what follows it, then its
-/// agents whose name starts with it, each with its role and what it is doing.
+/// them: the chat's people whose username or shown name holds what follows
+/// it (each by the name they show by, `@username` beside one who set a name;
+/// a pick still puts in `@username`), then its agents whose name starts with
+/// it, each with its role and what it is doing.
class _MentionPicker extends StatelessWidget {
const _MentionPicker({
required this.people,
@@ -3362,7 +3381,9 @@ class _MentionPicker extends StatelessWidget {
final prefix = query.toLowerCase();
final shownPeople = [
for (final person in people)
- if (person.username.contains(prefix)) person,
+ if (person.username.toLowerCase().contains(prefix) ||
+ (person.name?.toLowerCase().contains(prefix) ?? false))
+ person,
];
final shown = [
for (final agent in agents)
@@ -3395,7 +3416,9 @@ class _MentionPicker extends StatelessWidget {
for (final person in shownPeople)
TtyTap(
key: ValueKey('swarm-pick-person-${person.id}'),
- semanticsLabel: person.username,
+ semanticsLabel: person.name == null
+ ? person.username
+ : '${person.name}, @${person.username}',
minHeight: 52,
onTap: () => onPick(person.id),
child: Padding(
@@ -3405,18 +3428,42 @@ class _MentionPicker extends StatelessWidget {
child: Row(
children: [
SwarmChatAvatar(
- name: person.username,
+ name: person.shownName,
id: person.id,
agent: false,
picture: person.avatar,
),
const SizedBox(width: 10),
Expanded(
- child: Text(
- person.username,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: swarmChatText(16, weight: FontWeight.w500),
+ child: Row(
+ children: [
+ Flexible(
+ child: Text(
+ person.shownName,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(
+ 16,
+ weight: FontWeight.w500,
+ ),
+ ),
+ ),
+ // The handle a tag types, beside a name.
+ if (person.name != null) ...[
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text(
+ '@${person.username}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: swarmChatText(
+ 13,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ ],
+ ],
),
),
],
diff --git a/mobile/lib/swarm/swarm_home_view.dart b/mobile/lib/swarm/swarm_home_view.dart
index e71cb381b..ad1ae7379 100644
--- a/mobile/lib/swarm/swarm_home_view.dart
+++ b/mobile/lib/swarm/swarm_home_view.dart
@@ -37,6 +37,7 @@ SwarmHomeSwarm swarmHomeSwarm(
'id': p.id,
'email': '',
'username': ?p.chosenUsername,
+ 'name': ?p.name,
'role': p.role,
'avatar': ?_preset(p.avatar),
},
diff --git a/mobile/lib/swarm/swarm_instructions_page.dart b/mobile/lib/swarm/swarm_instructions_page.dart
index ca8e4d34a..875790448 100644
--- a/mobile/lib/swarm/swarm_instructions_page.dart
+++ b/mobile/lib/swarm/swarm_instructions_page.dart
@@ -71,12 +71,12 @@ class _SwarmInstructionsPageState extends State<SwarmInstructionsPage> {
.where((p) => p.id == widget.projectId)
.firstOrNull;
- /// A member's username from the reader's snapshot, else "a member".
+ /// A member's shown name from the reader's snapshot, else "a member".
String _personName(String id) =>
widget.reader.snapshot?.people
.where((p) => p.id == id)
.firstOrNull
- ?.username ??
+ ?.shownName ??
'a member';
/// Whether the person may delete a note: as Desktop, one who can write in the
diff --git a/mobile/lib/swarm/swarm_leaderboard.dart b/mobile/lib/swarm/swarm_leaderboard.dart
index e7d9fabb4..d997d9bb1 100644
--- a/mobile/lib/swarm/swarm_leaderboard.dart
+++ b/mobile/lib/swarm/swarm_leaderboard.dart
@@ -60,7 +60,8 @@ List<SwarmProjectHuman> swarmProjectHumans(
for (final person in swarmProjectPeople(snapshot, project))
(
person: person,
- name: scores[person.id]?.displayName ?? person.username,
+ // The name they set for this Swarm wins over their account's.
+ name: person.name ?? scores[person.id]?.displayName ?? person.username,
score: scores[person.id],
own: person.id == viewer,
),
@@ -551,7 +552,7 @@ class _SwarmLeaderboardPageState extends State<SwarmLeaderboardPage> {
SuperTabPerson? personOf(String id) =>
people.where((p) => p.id == id).firstOrNull;
String nameOf(SwarmScore score) => switch (personOf(score.personId)) {
- final person? => score.displayName ?? person.username,
+ final person? => person.name ?? score.displayName ?? person.username,
null => 'Former member',
};
final week = _shownLabel(reader, current);
diff --git a/mobile/lib/swarm/swarm_machines.dart b/mobile/lib/swarm/swarm_machines.dart
index 53260f455..7aa8b2bf2 100644
--- a/mobile/lib/swarm/swarm_machines.dart
+++ b/mobile/lib/swarm/swarm_machines.dart
@@ -143,7 +143,7 @@ class _SwarmMachinesSectionState extends State<SwarmMachinesSection> {
const SizedBox(width: AppSpace.s),
SwarmAvatar(
id: owner.id,
- name: owner.username,
+ name: owner.shownName,
picture: owner.avatar,
size: AppIconSize.standalone,
),
@@ -270,7 +270,7 @@ class SwarmMachineSheet extends StatelessWidget {
),
_detail('Status', view.status),
if (view.owner case final owner?)
- _detail('Owner', owner.username),
+ _detail('Owner', owner.shownName),
_heading('Hardware'),
if (view.dim)
_detail('Readings', 'Current readings unavailable')
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 66a814f2b..9444e900a 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -258,6 +258,7 @@ class SwarmMessageRow extends StatelessWidget {
required this.mentions,
this.tagged = const [],
this.taggedAddresses = const {},
+ this.taggedLabels = const {},
this.readerId = '',
required this.grouped,
required this.lit,
@@ -299,6 +300,10 @@ class SwarmMessageRow extends StatelessWidget {
/// it is this one.
final Map<String, String> taggedAddresses;
+ /// What a tagged person's pill reads, by username: the name they set. The
+ /// text keeps `@username`; one with no name here reads as it is written.
+ final Map<String, String> taggedLabels;
+
/// Who reads it: a message that tags them stands out.
final String readerId;
final bool grouped, lit, actions;
@@ -429,6 +434,7 @@ class SwarmMessageRow extends StatelessWidget {
references: references,
tagged: tagged,
addresses: taggedAddresses,
+ labels: taggedLabels,
onTap: onTap,
onOpenConversation: onOpenConversation,
),
diff --git a/mobile/lib/swarm/swarm_message_text.dart b/mobile/lib/swarm/swarm_message_text.dart
index a8bd1606a..d22572c29 100644
--- a/mobile/lib/swarm/swarm_message_text.dart
+++ b/mobile/lib/swarm/swarm_message_text.dart
@@ -21,6 +21,7 @@ class SwarmMessageText extends StatelessWidget {
this.references = const {},
this.tagged = const [],
this.addresses = const {},
+ this.labels = const {},
this.onTap,
this.onOpenConversation,
});
@@ -30,6 +31,10 @@ class SwarmMessageText extends StatelessWidget {
final Map<int, String> references;
final List<String> tagged;
final Map<String, String> addresses;
+
+ /// What a tagged person's pill reads, by username: `@` and the name they
+ /// set, while the text keeps `@username`.
+ final Map<String, String> labels;
final VoidCallback? onTap;
final ValueChanged<String>? onOpenConversation;
@@ -61,7 +66,7 @@ class SwarmMessageText extends StatelessWidget {
inlineSyntaxes: [
_WebAutolink(),
_ConversationReference(references),
- _SwarmMention(names, addresses),
+ _SwarmMention(names, addresses, labels),
],
builders: {'mention': _SwarmMentionBuilder()},
styleSheet: MarkdownStyleSheet.fromTheme(Theme.of(context))
@@ -184,25 +189,30 @@ class _ConversationReference extends md.InlineSyntax {
}
class _SwarmMention extends md.InlineSyntax {
- _SwarmMention(this.names, this.addresses)
+ _SwarmMention(this.names, this.addresses, this.labels)
: super(r'(?<![\w@/])@([\w+-]+(?:\.[\w+-]+)*)(@[\w-]+(?:\.[\w-]+)+)?');
final List<String> names;
final Map<String, String> addresses;
+ final Map<String, String> labels;
@override
bool onMatch(md.InlineParser parser, Match match) {
final name = match[1]!.toLowerCase();
final domain = match[2]?.toLowerCase();
- final tagged = names.any((candidate) {
+ final tagged = names.where((candidate) {
final key = candidate.toLowerCase();
final email = addresses[candidate]?.toLowerCase();
if (domain == null) return key == name;
if (email != null) return '$name$domain' == email;
return key == name;
- });
+ }).firstOrNull;
+ // A person who set a name reads by it; the tag stays theirs by username.
+ final label = tagged == null ? null : labels[tagged];
parser.addNode(
- tagged ? md.Element.text('mention', match[0]!) : md.Text(match[0]!),
+ tagged == null
+ ? md.Text(match[0]!)
+ : md.Element.text('mention', label == null ? match[0]! : '@$label'),
);
return true;
}
diff --git a/mobile/lib/swarm/swarm_name_editor.dart b/mobile/lib/swarm/swarm_name_editor.dart
new file mode 100644
index 000000000..db65f9b5b
--- /dev/null
+++ b/mobile/lib/swarm/swarm_name_editor.dart
@@ -0,0 +1,155 @@
+import 'package:flutter/material.dart';
+
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'swarm_style.dart';
+
+/// The name the Swarm shows for the reader ("Minh Nguyen"): the field, Save,
+/// and why a name was refused (taken, or not one a name can be), said under
+/// the field — beside [SwarmUsernameEditor], whose username stays the handle
+/// a tag types. Emptied, Save clears it, and the username shows again.
+class SwarmNameEditor extends StatefulWidget {
+ const SwarmNameEditor({
+ super.key,
+ required this.name,
+ required this.enabled,
+ required this.busy,
+ required this.onSave,
+ });
+
+ /// The name they set; null while they show by their username.
+ final String? name;
+
+ /// The person may change it now: off while another change is saving, and
+ /// for a reader who is no longer in the Swarm.
+ final bool enabled;
+
+ /// This field's own Save is on its way.
+ final bool busy;
+
+ /// Saves the name, null to clear it; answers why it was refused, or null
+ /// once saved.
+ final Future<String?> Function(String? name) onSave;
+
+ /// The server's limit (backend/src/superTabs/personNames.ts).
+ static const maxLength = 40;
+
+ @override
+ State<SwarmNameEditor> createState() => _SwarmNameEditorState();
+}
+
+class _SwarmNameEditorState extends State<SwarmNameEditor> {
+ late final _text = TextEditingController(text: widget.name ?? '');
+ String? _error;
+
+ /// The last name saved ('' for a clear), until the server's version of it
+ /// arrives.
+ String? _sent;
+
+ @override
+ void didUpdateWidget(SwarmNameEditor old) {
+ super.didUpdateWidget(old);
+ // A saved name comes back as the server keeps it (one space between
+ // words), but never over a newer edit typed while it was on its way.
+ final typed = _text.text.trim();
+ if (old.name == widget.name) return;
+ if (typed == (old.name ?? '') || typed == _sent) {
+ _text.text = widget.name ?? '';
+ }
+ _sent = null;
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ bool get _changed => _text.text.trim() != (widget.name ?? '');
+
+ bool get _can => widget.enabled && !widget.busy && _changed;
+
+ Future<void> _save() async {
+ if (!_can) return;
+ final typed = _sent = _text.text.trim();
+ final error = await widget.onSave(typed.isEmpty ? null : typed);
+ if (error != null) _sent = null;
+ // Closed, or the Swarm replaced, meanwhile: the answer is for nobody here.
+ if (mounted) setState(() => _error = error);
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ const SwarmCaption('Name'),
+ Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('swarm-name-field'),
+ controller: _text,
+ enabled: widget.enabled,
+ maxLength: SwarmNameEditor.maxLength,
+ textCapitalization: TextCapitalization.words,
+ textInputAction: TextInputAction.done,
+ style: AppType.body(color: AppPalette.textPrimary),
+ decoration: InputDecoration(
+ counterText: '',
+ filled: true,
+ fillColor: AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(AppControl.radius),
+ borderSide: BorderSide.none,
+ ),
+ ),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _save(),
+ ),
+ ),
+ const SizedBox(width: AppSpace.s),
+ SwarmButton(
+ key: const ValueKey('swarm-name-save'),
+ label: 'Save',
+ style: SwarmButtonStyle.fill,
+ busy: widget.busy,
+ busyLabel: 'Saving…',
+ onPressed: _can ? _save : null,
+ ),
+ ],
+ ),
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.xs,
+ AppSpace.xs,
+ 0,
+ ),
+ child: Text(
+ 'Leave empty to show your username.',
+ style: AppType.caption(color: AppPalette.textSecondary),
+ ),
+ ),
+ if (_error case final error?)
+ Padding(
+ padding: const EdgeInsets.fromLTRB(
+ AppSpace.xs,
+ AppSpace.xs,
+ AppSpace.xs,
+ 0,
+ ),
+ child: Text(
+ error,
+ key: const ValueKey('swarm-name-error'),
+ style: AppType.caption(color: AppColors.danger),
+ ),
+ ),
+ ],
+ );
+ }
+}
diff --git a/mobile/lib/swarm/swarm_profile.dart b/mobile/lib/swarm/swarm_profile.dart
index b4be0b217..e7a7b0548 100644
--- a/mobile/lib/swarm/swarm_profile.dart
+++ b/mobile/lib/swarm/swarm_profile.dart
@@ -90,6 +90,13 @@ class SwarmProfile {
'username': username?.trim(),
}, viewer: true);
+ /// The name the Swarm shows for the reader ("Minh Nguyen"), trimmed, or
+ /// back to their username when null (the server's `member.name`); a viewer
+ /// sets theirs too. A refused or taken name comes back in the server's
+ /// words.
+ Future<String?> setName(String? name) =>
+ _send({'type': 'member.name', 'name': name?.trim()}, viewer: true);
+
/// [preset], or back to the initial when null.
Future<String?> setAvatar(SuperTabPresetAvatar? preset) => _send({
'type': 'member.avatar',
diff --git a/mobile/lib/swarm/swarm_profile_sheet.dart b/mobile/lib/swarm/swarm_profile_sheet.dart
index 205409373..1c3b39c07 100644
--- a/mobile/lib/swarm/swarm_profile_sheet.dart
+++ b/mobile/lib/swarm/swarm_profile_sheet.dart
@@ -19,6 +19,7 @@ import 'swarm_profile.dart';
import 'swarm_reader.dart';
import 'swarm_session.dart';
import 'swarm_style.dart';
+import 'swarm_name_editor.dart';
import 'swarm_username_editor.dart';
/// One photo from the person's library, or null when they back out. Asked
@@ -50,7 +51,7 @@ Future<Uint8List?> readPickedSwarmPhoto(XFile? picked) async {
}
/// The person's own profile in the Swarm [swarmId], in a sheet over the
-/// page: their username, a built-in picture or a photo of theirs, and a
+/// page: their name and username, a built-in picture or a photo of theirs, and a
/// status that clears when they say — the desktop's profile (`profile_sheet.dart`) in the
/// phone's own way.
Future<void> showSwarmProfile(
@@ -116,6 +117,9 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
/// The username's own Save is on its way: [_busy] says it for the rest.
bool _naming = false;
+
+ /// The name's own Save is on its way, as [_naming] for the username.
+ bool _titling = false;
String? _error;
@override
@@ -149,6 +153,17 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
return error;
}
+ /// A refused name is said under its own field, as a username's is.
+ Future<String?> _saveName(SwarmProfile profile, String? name) async {
+ setState(() {
+ _busy = _titling = true;
+ _error = null;
+ });
+ final error = await profile.setName(name);
+ if (mounted) setState(() => _busy = _titling = false);
+ return error;
+ }
+
Future<void> _photo(SwarmProfile profile) async {
final Uint8List? picked;
try {
@@ -279,7 +294,7 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
SuperTabPersonStatus? status,
SwarmProfile profile,
) {
- final name = me.username;
+ final name = me.shownName;
final edit = profile.canEdit && !_busy;
final current = me.avatar;
final text = _text.text.trim();
@@ -330,6 +345,13 @@ class _SwarmProfileSheetState extends State<SwarmProfileSheet> {
// A viewer's name is theirs too, though they change nothing else.
// One field per reader: an answer sent under another account or
// Swarm never lands in this one.
+ SwarmNameEditor(
+ key: ValueKey((profile.reader, 'name')),
+ name: me.name,
+ enabled: profile.canRename && (!_busy || _titling),
+ busy: _titling,
+ onSave: (name) => _saveName(profile, name),
+ ),
SwarmUsernameEditor(
key: ObjectKey(profile.reader),
username: me.username,
@@ -701,7 +723,7 @@ class SwarmPersonSheet extends StatelessWidget {
Widget _sheet(BuildContext context, SwarmReader reader) {
final person = reader.snapshot?.person(personId);
final mine = personId == reader.accountId;
- final name = person == null ? 'Someone' : person.username;
+ final name = person == null ? 'Someone' : person.shownName;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -760,6 +782,16 @@ class SwarmPersonSheet extends StatelessWidget {
),
],
const SizedBox(height: 4),
+ // The handle a tag types, under a name they set.
+ if (person.name != null)
+ Text(
+ '@${person.username}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ ),
+ ),
Text(
person.email,
maxLines: 1,
diff --git a/mobile/lib/swarm/swarm_ship_row.dart b/mobile/lib/swarm/swarm_ship_row.dart
index 5f818fe35..4e3f47455 100644
--- a/mobile/lib/swarm/swarm_ship_row.dart
+++ b/mobile/lib/swarm/swarm_ship_row.dart
@@ -200,7 +200,7 @@ class _SwarmShipRowState extends State<SwarmShipRow> {
];
final credits = [
if (requester != null)
- ('Requested by', [(requester.id, requester.username)]),
+ ('Requested by', [(requester.id, requester.shownName)]),
('Built by', agents(ship.builderIds)),
('Reviewed by', agents(ship.reviewerIds)),
].where((credit) => credit.$2.isNotEmpty).toList();
diff --git a/mobile/lib/swarm/swarm_task_status.dart b/mobile/lib/swarm/swarm_task_status.dart
index 7bdb8257d..39a2fe730 100644
--- a/mobile/lib/swarm/swarm_task_status.dart
+++ b/mobile/lib/swarm/swarm_task_status.dart
@@ -19,7 +19,7 @@ String? Function(String personId) swarmTaskPersonName(
) =>
(personId) =>
switch (snapshot.people.where((p) => p.id == personId).firstOrNull) {
- final person? when person.email.isNotEmpty => person.username,
+ final person? when person.email.isNotEmpty => person.shownName,
_ => null,
};
diff --git a/mobile/lib/swarm/swarm_thread_line.dart b/mobile/lib/swarm/swarm_thread_line.dart
index e0edfdbe9..14f700c6c 100644
--- a/mobile/lib/swarm/swarm_thread_line.dart
+++ b/mobile/lib/swarm/swarm_thread_line.dart
@@ -30,7 +30,7 @@ typedef SwarmThreadFace = ({
});
/// The newest reply authors of [thread] as [snapshot] names and dresses them:
-/// an agent by the Swarm's name for it, a person by their username,
+/// an agent by the Swarm's name for it, a person by the name they show by,
/// part, as the chat names a message's author. The project's coordinator
/// wears manager blue here as on its own messages, whatever its role is
/// called.
@@ -61,7 +61,7 @@ List<SwarmThreadFace> swarmThreadFaces(
snapshot?.people
.where((p) => p.id == id)
.firstOrNull
- ?.username ??
+ ?.shownName ??
superTabPersonName(author['name'] as String? ?? ''),
id: id,
agent: false,
diff --git a/mobile/lib/swarm/swarm_you_page.dart b/mobile/lib/swarm/swarm_you_page.dart
index a57217c31..ef8b67ae1 100644
--- a/mobile/lib/swarm/swarm_you_page.dart
+++ b/mobile/lib/swarm/swarm_you_page.dart
@@ -85,7 +85,7 @@ class SwarmYouButton extends StatelessWidget {
final session = SwarmScope.of(context);
Widget face() {
final me = swarmYouOf(session).me;
- final name = me == null || me.email.isEmpty ? 'You' : me.username;
+ final name = me == null || me.email.isEmpty ? 'You' : me.shownName;
final status = me?.statusAt(clock.now())?.label;
return Semantics(
button: true,
@@ -126,7 +126,7 @@ class SwarmYouButton extends StatelessWidget {
/// You, as Tony's prototype C4 draws it (2026-10-30), opened from the avatar
/// on Home and Activity since it stopped being a tab (2026-11-03):
/// who they are in the Swarm Home shows — their face, their name and that
-/// Swarm — then their status and their username, each with Change for their
+/// Swarm — then their status, their name and their username, each with Change for their
/// profile, where it is set ([showSwarmProfile]); Your models, with how many of their own machines'
/// models the Swarms can use now, and Your devices, with how many of their
/// own computers are online; and Settings. Only what is theirs counts: not a
@@ -223,6 +223,20 @@ class SwarmYouPage extends StatelessWidget {
),
],
),
+ const SwarmCaption('Name'),
+ SwarmGroup(
+ children: [
+ SwarmRow(
+ key: const ValueKey('swarm-you-name'),
+ leading: const SwarmRowGlyph(LucideIcons.user300),
+ // How the Swarm shows them, the username until they set one;
+ // nothing of a Swarm before it is read, or once it is taken away.
+ title: me == null ? 'Name' : me.name ?? 'Add your name',
+ trailing: profile == null ? null : const _Change(),
+ onTap: profile,
+ ),
+ ],
+ ),
const SwarmCaption('Username'),
SwarmGroup(
children: [
@@ -334,7 +348,7 @@ class _Me extends StatelessWidget {
AppTheme.watch(context);
final me = this.me;
// A Home kept for a cold start holds no email.
- final name = me == null || me.email.isEmpty ? 'You' : me.username;
+ final name = me == null || me.email.isEmpty ? 'You' : me.shownName;
return Padding(
padding: const EdgeInsets.fromLTRB(
AppSpace.xs,
diff --git a/mobile/test/phone/phone_shell_swarm_home_test.dart b/mobile/test/phone/phone_shell_swarm_home_test.dart
index 92b76b7a5..682fb5b32 100644
--- a/mobile/test/phone/phone_shell_swarm_home_test.dart
+++ b/mobile/test/phone/phone_shell_swarm_home_test.dart
@@ -60,6 +60,9 @@ void main() {
/// Row [row] of You, tapped.
Future<void> youTo(WidgetTester tester, String row) async {
await openYou(tester);
+ // You scrolls: on the test's short screen its last rows sit below.
+ await tester.ensureVisible(key(row));
+ await tester.pump();
await tester.tap(key(row));
await frames(tester);
}
diff --git a/mobile/test/swarm/swarm_display_name_shots_test.dart b/mobile/test/swarm/swarm_display_name_shots_test.dart
new file mode 100644
index 000000000..71b650050
--- /dev/null
+++ b/mobile/test/swarm/swarm_display_name_shots_test.dart
@@ -0,0 +1,223 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_you_page.dart';
+import 'package:harness_mobile/terminal/terminal_font_store.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of the name a person sets (plan
+/// 2026-11-03-person-display-name, Task 6): You with a Name row above
+/// Username, and a chat whose author and tag read by that name beside one
+/// who set none. On a 390-point
+/// phone in both phone themes, from made-up data only, to the folder
+/// `SWARM_DISPLAY_NAME_SHOTS` names.
+final shots = Platform.environment['SWARM_DISPLAY_NAME_SHOTS'];
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in {
+ '.AppleSystemUIFont',
+ 'Roboto',
+ AppFont.sans,
+ ...AppFont.sansFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ final terminal = terminalFontStore.value;
+ for (final family in {
+ '.AppleSystemUIFontMonospaced',
+ 'monospace',
+ AppFont.mono,
+ ...AppFont.monoFallback,
+ terminal.fontFamily,
+ ...terminal.fontFamilyFallback,
+ }) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+ final mine = {
+ ...person(me),
+ 'email': '[email protected]',
+ 'username': 'tony',
+ 'name': 'Tony Tran',
+ };
+ final ken = {
+ ...person('ken', role: 'collaborator'),
+ 'username': 'wkpnjjhbnm',
+ 'name': 'Minh Nguyen',
+ };
+
+ FakeSwarm backend() {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Fix login',
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: 'working',
+ lastMessageSequence: 2,
+ ),
+ ],
+ ),
+ 'members': [
+ part(me, 1, mine),
+ part('ken', 1, ken),
+ // One who set no name reads by username, as today.
+ part('dee', 1, person('dee', role: 'collaborator')),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ Map<String, dynamic> said(
+ String id,
+ int sequence,
+ String author,
+ String text, {
+ List<String> mentions = const [],
+ }) => {
+ 'id': id,
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': sequence,
+ 'mentions': mentions,
+ 'author': {'kind': 'person', 'id': author, 'name': '[email protected]'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(
+ 2026,
+ 11,
+ 3,
+ 3,
+ 40 + sequence,
+ ).toIso8601String(),
+ };
+ fake.routes[messages] = (_) => {
+ 'messages': [
+ said(
+ 'm2',
+ 2,
+ 'dee',
+ 'Thanks @wkpnjjhbnm, I will check it on the phone.',
+ mentions: ['ken'],
+ ),
+ said('m1', 1, 'ken', 'The login fix is ready for a look.'),
+ ],
+ 'next': null,
+ 'threads': <Object>[],
+ };
+ return fake;
+ }
+
+ testWidgets('You with a name, and a chat by a named author, in both '
+ 'phone themes', (tester) async {
+ addTearDown(tester.view.reset);
+ debugDisableShadows = false;
+ tester.view.padding = const FakeViewPadding(top: 47 * 3, bottom: 34 * 3);
+ addTearDown(tester.view.resetPadding);
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ const size = Size(390, 844);
+ tester.view
+ ..physicalSize = size * 3
+ ..devicePixelRatio = 3;
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ for (final (shot, page) in [
+ ('you', const SwarmYouPage() as Widget),
+ (
+ 'chat',
+ const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ ]) {
+ final fake = backend();
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => me,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: page,
+ ),
+ ),
+ );
+ await host.session!.inbox.refresh();
+ await tester.pumpAndSettle();
+ if (shot == 'you') {
+ expect(find.text('Tony Tran'), findsWidgets);
+ } else {
+ expect(find.text('Minh Nguyen'), findsWidgets);
+ }
+ if (shots != null) {
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await File('$shots/display-name-390-$shot-${brightness.name}.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ }
+ }
+ debugDisableShadows = true;
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_display_name_test.dart b/mobile/test/swarm/swarm_display_name_test.dart
new file mode 100644
index 000000000..16d2f3e63
--- /dev/null
+++ b/mobile/test/swarm/swarm_display_name_test.dart
@@ -0,0 +1,539 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/shared/theme/app_theme.dart'
+ show AppPalette, AppSurface;
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/parts.dart';
+import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
+import 'package:harness_mobile/swarm/swarm_face.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_style.dart';
+import 'package:harness_mobile/swarm/swarm_thread_line.dart';
+import 'package:harness_mobile/swarm/swarm_you_page.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// The name a person sets for the Swarm to show (plan
+/// 2026-11-03-person-display-name, Task 6): wherever the phone shows a person
+/// it reads `name ?? username`; wherever a tag is typed or matched it keeps
+/// `@username`. With no name set, every place reads exactly as before.
+void main() {
+ // Ken set a name; Dee keeps the username her email makes.
+ final ken = {
+ ...person('ken', role: 'collaborator'),
+ 'username': 'kenji',
+ 'name': 'Minh Nguyen',
+ };
+ final dee = person('dee', role: 'collaborator');
+
+ group('the model', () {
+ SuperTabPerson member(Map<String, dynamic> row) =>
+ SuperTabPerson.fromJson(row);
+
+ test('reads the name, and shows it over the username', () {
+ final person = member(ken);
+ expect(person.name, 'Minh Nguyen');
+ expect(person.username, 'kenji');
+ expect(person.shownName, 'Minh Nguyen');
+ });
+
+ test('without one, shows the username, as today', () {
+ final person = member(dee);
+ expect(person.name, isNull);
+ expect(person.shownName, 'dee');
+ });
+
+ test('a name stays with the default username an older server leaves to '
+ 'the phone', () {
+ final [named] = superTabUsernames([
+ member({...person('p1'), 'name': 'Minh Nguyen'}),
+ ]);
+ expect(named.username, 'p1');
+ expect(named.name, 'Minh Nguyen');
+ expect(named.shownName, 'Minh Nguyen');
+ });
+ });
+
+ SuperTabSnapshot snapshotOf(List<Map<String, dynamic>> members) {
+ final load = firstLoad();
+ for (final m in members) {
+ (load['members'] as List).add(part(m['id'] as String, 1, m));
+ }
+ return SuperTabSnapshot.fromJson(SuperTabParts.firstLoad(load).state);
+ }
+
+ SuperTabMessage byPerson(String id) => SuperTabMessage.fromJson({
+ 'id': 'm-$id',
+ 'conversationId': 'g1',
+ 'text': 'hello',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': id, 'name': '[email protected]'},
+ 'createdAt': DateTime.utc(2026, 11, 3, 9).toIso8601String(),
+ });
+
+ test('a chat author reads by their name; one without, by username', () {
+ final snapshot = snapshotOf([ken, dee]);
+ expect(snapshot.authorName(byPerson('ken')), 'Minh Nguyen');
+ expect(snapshot.authorName(byPerson('dee')), 'dee');
+ });
+
+ test('a thread\'s reply line names its people by name, else username', () {
+ final thread = SuperTabThread.fromJson({
+ 'id': 'm1',
+ 'replies': 2,
+ 'lastSequence': 3,
+ 'authors': [
+ {'kind': 'person', 'id': 'ken', 'name': '[email protected]'},
+ {'kind': 'person', 'id': 'dee', 'name': '[email protected]'},
+ ],
+ 'people': ['ken', 'dee'],
+ });
+ final faces = swarmThreadFaces(snapshotOf([ken, dee]), thread);
+ expect([for (final face in faces) face.name], ['Minh Nguyen', 'dee']);
+ });
+
+ group('the chat', () {
+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';
+ const commands = '/api/super-tabs/$tab/commands';
+
+ FakeSwarm backend(List<Map<String, dynamic>> page) {
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [
+ groupData(
+ 'g1',
+ title: 'Fix login',
+ agentIds: ['agent-lead', 'agent-builder'],
+ status: 'working',
+ lastMessageSequence: page.length,
+ ),
+ ],
+ ),
+ 'members': [
+ for (final member in [person(me), ken, dee])
+ part(member['id'] as String, 1, member),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
+ changes(cursor: 'c2');
+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes[messages] = (_) => {
+ 'messages': page.reversed.toList(),
+ 'next': null,
+ 'threads': <Object>[],
+ };
+ fake.routes[commands] = (_) => {'result': <String, dynamic>{}};
+ return fake;
+ }
+
+ Map<String, dynamic> said(
+ String id,
+ int sequence,
+ String author,
+ String text, {
+ List<String> mentions = const [],
+ }) => {
+ 'id': id,
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': sequence,
+ 'mentions': mentions,
+ 'author': {'kind': 'person', 'id': author, 'name': '[email protected]'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 11, 3, 1, sequence).toIso8601String(),
+ };
+
+ Future<FakeSwarm> pump(
+ WidgetTester tester,
+ List<Map<String, dynamic>> page,
+ ) async {
+ tester.view.devicePixelRatio = 3;
+ tester.view.physicalSize = const Size(393 * 3, 852 * 3);
+ addTearDown(tester.view.reset);
+ final fake = backend(page);
+ final account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: const SwarmConversationPage(swarmId: tab, conversationId: 'g1'),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return fake;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Finder inside(String k, Finder matching) =>
+ find.descendant(of: key(k), matching: matching);
+
+ /// The texts drawn as tag pills inside [k], in order.
+ List<String> pills(WidgetTester tester, String k) => [
+ for (final rich in tester.widgetList<RichText>(
+ inside(k, find.byType(RichText)),
+ ))
+ ..._pills(rich.text, null),
+ ];
+
+ testWidgets('an author shows by their name; one without, by username', (
+ tester,
+ ) async {
+ await pump(tester, [
+ said('m1', 1, 'ken', 'on it'),
+ said('m2', 2, 'dee', 'thanks'),
+ ]);
+ expect(inside('swarm-message-m1', find.text('Minh Nguyen')), findsOne);
+ expect(inside('swarm-message-m1', find.text('kenji')), findsNothing);
+ // The face's initial comes from the name too.
+ final face = tester.widget<SwarmChatAvatar>(
+ inside('swarm-message-m1', find.byType(SwarmChatAvatar)),
+ );
+ expect(face.name, 'Minh Nguyen');
+ expect(inside('swarm-message-m2', find.text('dee')), findsOne);
+ });
+
+ testWidgets('a tag reads as the name it shows, and as the username for '
+ 'one without; the text keeps @username', (tester) async {
+ await pump(tester, [
+ said(
+ 'm1',
+ 1,
+ 'dee',
+ 'ask @kenji and @dee to look',
+ mentions: ['ken', 'dee'],
+ ),
+ ]);
+ expect(pills(tester, 'swarm-message-m1'), ['@Minh Nguyen', '@dee']);
+ });
+
+ testWidgets('@ suggests a named person by their name with @username '
+ 'beside it, found by either, and puts in @username', (tester) async {
+ final fake = await pump(tester, [said('m1', 1, 'dee', 'hi')]);
+ final field = find.descendant(
+ of: key('swarm-field'),
+ matching: find.byType(TextField),
+ );
+ Future<void> type(String text) async {
+ await tester.enterText(field, text);
+ await tester.pump();
+ }
+
+ await type('@');
+ expect(
+ inside('swarm-pick-person-ken', find.text('Minh Nguyen')),
+ findsOne,
+ );
+ expect(inside('swarm-pick-person-ken', find.text('@kenji')), findsOne);
+ // One without a name reads as today: the username alone.
+ expect(inside('swarm-pick-person-dee', find.text('dee')), findsOne);
+ expect(inside('swarm-pick-person-dee', find.text('@dee')), findsNothing);
+
+ // By the name, any case, and by the username.
+ await type('ask @MINH');
+ expect(key('swarm-pick-person-ken'), findsOneWidget);
+ expect(key('swarm-pick-person-dee'), findsNothing);
+ await type('ask @nguy');
+ expect(key('swarm-pick-person-ken'), findsOneWidget);
+ await type('ask @kenj');
+ expect(key('swarm-pick-person-ken'), findsOneWidget);
+ expect(key('swarm-pick-person-dee'), findsNothing);
+
+ await type('ask @minh');
+ await tester.tap(key('swarm-pick-person-ken'));
+ await tester.pump();
+ expect(tester.widget<TextField>(field).controller!.text, 'ask @kenji ');
+
+ await type('ask @kenji to look');
+ await tester.tap(key('swarm-send'));
+ await tester.pumpAndSettle();
+ expect(fake.commands.single['text'], 'ask @kenji to look');
+ expect(fake.commands.single['mentions'], ['ken']);
+ });
+ });
+
+ group('You and the Name editor', () {
+ late FakeSwarm swarm;
+ late Map<String, dynamic> mine;
+ late SwarmHost host;
+
+ /// What the next command answers instead of the server's rules, once.
+ FutureOr<Object?> Function()? answer;
+
+ // The backend's rules (backend/src/superTabs/personNames.ts), in short.
+ Object? setName(Map<String, dynamic> command) {
+ final input = command['name'] as String?;
+ if (input == null) {
+ mine = {...mine}..remove('name');
+ return {'ok': true};
+ }
+ final name = input.replaceAll(RegExp(r'\s+'), ' ').trim();
+ if (name.isEmpty || name.runes.length > 40) {
+ throw const SuperTabFailure(
+ 'INVALID_NAME',
+ 'Use 1 to 40 characters, with no hidden ones.',
+ statusCode: 400,
+ );
+ }
+ if (name.toLowerCase() == 'dee') {
+ throw const SuperTabFailure(
+ 'NAME_TAKEN',
+ 'Someone here already goes by that name.',
+ statusCode: 409,
+ );
+ }
+ mine = {...mine, 'name': name};
+ return {'ok': true};
+ }
+
+ Future<void> pump(WidgetTester tester, {String? name}) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ answer = null;
+ swarm = FakeSwarm();
+ mine = {
+ ...person(me),
+ 'email': '[email protected]',
+ 'username': 'tony',
+ 'name': ?name,
+ };
+ var version = 1;
+ swarm.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'Autonomous', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ swarm.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(),
+ 'members': [part(me, version, mine), part('dee', 1, dee)],
+ };
+ swarm.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c${++version}'),
+ 'members': [part(me, version, mine)],
+ };
+ swarm.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ swarm.routes['/api/super-tabs/$tab/commands'] = (body) {
+ final command = body!['command'] as Map<String, dynamic>;
+ if (answer case final once?) {
+ answer = null;
+ return once();
+ }
+ return switch (command['type']) {
+ 'member.name' => setName(command),
+ _ => {'ok': true},
+ };
+ };
+ final account = ValueNotifier<String?>(me);
+ host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: swarm.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) =>
+ SwarmScope(notifier: host, child: child!),
+ home: const SwarmYouPage(),
+ ),
+ );
+ unawaited(host.session!.inbox.refresh());
+ await tester.pumpAndSettle();
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+ Finder inside(String k, Finder matching) =>
+ find.descendant(of: key(k), matching: matching);
+ TextField field(WidgetTester tester) =>
+ tester.widget<TextField>(key('swarm-name-field'));
+ bool saveOn(WidgetTester tester) =>
+ tester.widget<SwarmButton>(key('swarm-name-save')).onPressed != null;
+ String? shownError() => key('swarm-name-error').evaluate().isEmpty
+ ? null
+ : (key('swarm-name-error').evaluate().single.widget as Text).data;
+ SuperTabPerson? stored() =>
+ host.session!.inbox.reader(tab)!.snapshot!.person(me);
+ List<Map<String, dynamic>> named() => [
+ for (final c in swarm.commands)
+ if (c['type'] == 'member.name') c,
+ ];
+
+ Future<void> settle(WidgetTester tester) async {
+ for (var i = 0; i < 10; i++) {
+ await tester.pump(const Duration(milliseconds: 50));
+ }
+ }
+
+ Future<void> openProfile(WidgetTester tester) async {
+ await tester.tap(key('swarm-you-name'));
+ await tester.pumpAndSettle();
+ expect(key('swarm-name-field'), findsOneWidget);
+ }
+
+ Future<void> type(WidgetTester tester, String text) async {
+ await tester.enterText(key('swarm-name-field'), text);
+ await tester.pump();
+ }
+
+ Future<void> save(WidgetTester tester) async {
+ await tester.ensureVisible(key('swarm-name-save'));
+ await tester.tap(key('swarm-name-save'));
+ await settle(tester);
+ }
+
+ testWidgets('with a name: You heads with it, a Name row above Username '
+ 'shows it with Change, and Username keeps the handle', (tester) async {
+ await pump(tester, name: 'Minh Nguyen');
+ expect(inside('swarm-you-me', find.text('Minh Nguyen')), findsOne);
+ expect(inside('swarm-you-name', find.text('Minh Nguyen')), findsOne);
+ expect(inside('swarm-you-name', find.text('Change')), findsOne);
+ expect(inside('swarm-you-username', find.text('tony')), findsOne);
+ expect(
+ tester.getTopLeft(key('swarm-you-name')).dy,
+ lessThan(tester.getTopLeft(key('swarm-you-username')).dy),
+ );
+ });
+
+ testWidgets('with none: You heads with the username, as today', (
+ tester,
+ ) async {
+ await pump(tester);
+ expect(inside('swarm-you-me', find.text('tony')), findsOne);
+ expect(inside('swarm-you-username', find.text('tony')), findsOne);
+ expect(inside('swarm-you-name', find.text('Change')), findsOne);
+ });
+
+ testWidgets('the Name field sits above Username, and a name saves '
+ 'trimmed and shows at once', (tester) async {
+ await pump(tester);
+ await openProfile(tester);
+ expect(field(tester).controller!.text, '');
+ expect(
+ tester.getTopLeft(key('swarm-name-field')).dy,
+ lessThan(tester.getTopLeft(key('swarm-username-field')).dy),
+ );
+ expect(find.text('Leave empty to show your username.'), findsOne);
+ // Nothing changed, nothing to save.
+ expect(saveOn(tester), isFalse);
+
+ await type(tester, ' Minh Nguyen ');
+ expect(saveOn(tester), isTrue);
+ await save(tester);
+
+ expect(named(), [
+ {'type': 'member.name', 'name': 'Minh Nguyen'},
+ ]);
+ expect(shownError(), isNull);
+ expect(field(tester).controller!.text, 'Minh Nguyen');
+ expect(stored()!.name, 'Minh Nguyen');
+ await tester.tap(key('swarm-profile-close'));
+ await tester.pumpAndSettle();
+ expect(inside('swarm-you-me', find.text('Minh Nguyen')), findsOne);
+ expect(inside('swarm-you-name', find.text('Minh Nguyen')), findsOne);
+ });
+
+ testWidgets('an emptied field clears it with null, and the username '
+ 'shows again', (tester) async {
+ await pump(tester, name: 'Minh Nguyen');
+ await openProfile(tester);
+ expect(field(tester).controller!.text, 'Minh Nguyen');
+
+ await type(tester, ' ');
+ expect(saveOn(tester), isTrue);
+ await save(tester);
+
+ expect(named(), [
+ {'type': 'member.name', 'name': null},
+ ]);
+ expect(shownError(), isNull);
+ expect(stored()!.name, isNull);
+ await tester.tap(key('swarm-profile-close'));
+ await tester.pumpAndSettle();
+ expect(inside('swarm-you-me', find.text('tony')), findsOne);
+ });
+
+ testWidgets('a name the server refuses says why under its field, and '
+ 'nothing changes', (tester) async {
+ await pump(tester, name: 'Minh Nguyen');
+ await openProfile(tester);
+ await type(tester, 'Dee');
+ await save(tester);
+
+ expect(shownError(), 'Someone here already goes by that name.');
+ expect(key('swarm-profile-error'), findsNothing);
+ expect(key('swarm-username-error'), findsNothing);
+ expect(field(tester).controller!.text, 'Dee');
+ expect(stored()!.name, 'Minh Nguyen');
+ // Typing again clears it.
+ await type(tester, 'Minh');
+ expect(shownError(), isNull);
+ });
+
+ testWidgets('a call lost on the way says so and never stays Saving', (
+ tester,
+ ) async {
+ await pump(tester);
+ await openProfile(tester);
+ answer = () => throw TimeoutException('no answer');
+ await type(tester, 'Minh');
+ await save(tester);
+ expect(shownError(), 'Could not reach this Swarm. Try again.');
+ expect(find.text('Saving…'), findsNothing);
+ expect(saveOn(tester), isTrue);
+ });
+ });
+}
+
+Iterable<String> _pills(InlineSpan span, TextStyle? inherited) sync* {
+ if (span is! TextSpan) return;
+ final style = inherited?.merge(span.style) ?? span.style;
+ if (span.text case final text?
+ when style?.backgroundColor == AppSurface.accentWash &&
+ style?.color == AppPalette.accentOnSurface) {
+ yield text;
+ }
+ for (final child in span.children ?? const <InlineSpan>[]) {
+ yield* _pills(child, style);
+ }
+}
diff --git a/scripts/tests/test_ci_plan.py b/scripts/tests/test_ci_plan.py
index 87ffd7d91..f70fec206 100644
--- a/scripts/tests/test_ci_plan.py
+++ b/scripts/tests/test_ci_plan.py
@@ -65,6 +65,8 @@ class SelectionTests(unittest.TestCase):
saver = (workflows / "backend-cache.yml").read_text()
self.assertRegex(saver, r"(?ms)^on:.*^ push:\n branches: \[main\]")
self.assertIn("actions/cache/save@", saver)
+ # A manual run from another branch would save a cache only that branch reads (review of #2822).
+ self.assertRegex(saver, r"(?m)^ mongod:\n if: github\.ref == 'refs/heads/main'$")
self.assertIn(f"key: {key}", saver)
self.assertIn("path: /tmp/harness-super-tab-mongodb-binaries", job)
self.assertIn("path: /tmp/harness-super-tab-mongodb-binaries", saver)