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 10-29 ad: 4 reviewed PRs (#2169, #2187, #2188, #2088) (#2200)

0xken15a8f9441f4eeb
diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.ts
index 65d43aa2d..c1ddce387 100644
--- a/backend/integration/superTabProfile.test.ts
+++ b/backend/integration/superTabProfile.test.ts
@@ -13,6 +13,7 @@ import { CdnAvatarStore, MemoryAttachmentStore, MemoryAvatarStore } from '../src
import { superTabRoutes } from '../src/routes/superTabs.js'
import { errorHandler } from '../src/middlewares/errorHandler.js'
import type { Command } from '../src/superTabs/commands.js'
+import { usernames } from '../src/superTabs/usernames.js'
// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
let replica: MongoMemoryReplSet
@@ -109,6 +110,52 @@ describe('status line', () => {
})
})
+describe('usernames', () => {
+ const members = async (tab: string, user = owner) =>
+ (await read(tab, user)).body.data.members as Array<{ key: string; data: { username?: string } }>
+
+ it('reaches members through first loads and changes, and nobody outside the Swarm', async () => {
+ const tab = await swarm()
+ const first = await read(tab, peer)
+ await run(tab, { type: 'member.username', username: 'Pilot' })
+ 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.username).toBe('pilot')
+ expect((await members(tab, peer)).find(m => m.key === owner.sub)!.data.username).toBe('pilot')
+ const stranger = await read(tab, outsider)
+ expect(stranger.status).not.toBe(200)
+ expect(stranger.text).not.toContain('pilot')
+ })
+
+ it('lets a viewer choose their own name, and nothing else', async () => {
+ const tab = (await store.create(owner, randomUUID(), 'Office')).id
+ const invitation = await run(tab, { type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
+ await run(tab, { type: 'member.username', username: 'watcher' }, peer)
+ expect((await members(tab)).find(m => m.key === peer.sub)!.data.username).toBe('watcher')
+ await expect(run(tab, { type: 'member.status', status: { text: 'Hi' } }, peer)).rejects.toMatchObject({ code: 'READ_ONLY' })
+ })
+
+ 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.username', username: 'captain' }),
+ run(tab, { type: 'member.username', username: 'captain' }, peer)])
+ expect(results.map(r => r.status).sort()).toEqual(['fulfilled', 'rejected'])
+ expect((results.find(r => r.status === 'rejected') as PromiseRejectedResult).reason).toMatchObject({ code: 'USERNAME_TAKEN' })
+ expect((await members(tab)).filter(m => m.data.username === 'captain')).toHaveLength(1)
+ })
+
+ it('keeps names distinct when someone joins while another person chooses the joiner’s default', async () => {
+ const tab = (await store.create(owner, randomUUID(), 'Office')).id
+ const invitation = await run(tab, { type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ const [chosen] = await Promise.allSettled([run(tab, { type: 'member.username', username: 'peer' }),
+ run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)])
+ const names = usernames((await store.read(owner, tab)).state.people)
+ // Either the choice came first and the joiner is numbered, or the join came first and the choice was refused.
+ expect(names).toEqual(chosen.status === 'fulfilled' ? new Map([[owner.sub, 'peer'], [peer.sub, 'peer2']])
+ : new Map([[owner.sub, 'owner'], [peer.sub, 'peer']]))
+ })
+})
+
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 68c6054f5..922b293bf 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -3149,6 +3149,16 @@ describe('Lead mentions', () => {
expect((await store.messages(owner, tab, group, {})).messages.find(m => m.id === messageId)!.mentions).toEqual([peer.sub])
})
+ it('lists a person’s tag of another person under the author’s username, never their email', async () => {
+ const { tab, group } = await tagged()
+ await run(tab, { type: 'member.username', username: 'boss' })
+ const messageId = (await run(tab, { type: 'message.send', conversationId: group, text: 'Peer, see above.', replyTo: null, recipientIds: [],
+ mentions: [peer.sub] })).result.messageId as string
+ const mention = (await list(tab, peer, 'waiting')).find(m => m.messageId === messageId)
+ expect(mention).toEqual(expect.objectContaining({ leadId: owner.sub, leadName: 'boss', text: 'Peer, see above.' }))
+ expect(JSON.stringify(mention)).not.toContain(owner.email)
+ })
+
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/integration/swarmSweepStarts.test.ts b/backend/integration/swarmSweepStarts.test.ts
new file mode 100644
index 000000000..7edb81208
--- /dev/null
+++ b/backend/integration/swarmSweepStarts.test.ts
@@ -0,0 +1,57 @@
+import { randomUUID } from 'node:crypto'
+import { execFile } from 'node:child_process'
+import { promisify } from 'node:util'
+import { join } from 'node:path'
+import { tmpdir } from 'node:os'
+import { afterAll, beforeAll, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { RETENTION_MS } from '../src/superTabs/parts/types.js'
+import { sweepSwarms } from '../src/superTabs/sweeps.js'
+
+// The hourly sweep removes finished starts 7 days on (sweeps.ts expireStarts). Until 2026-10-29 it also removed every start
+// that had not finished: Prisma sent `finishedAt: { lt }` as $expr, where a null finish time is less than any date. A fresh
+// loopback replica set; never DATABASE_URL.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const NOW = Date.parse('2026-10-29T08:00:00Z')
+const DAY = 86_400_000
+const maker: AuthUser = { sub: randomUUID().replaceAll('-', '').slice(0, 24), email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+let tabId: string
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_sweep_starts_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ await db.user.create({ data: { id: maker.sub, externalId: `fixture-${maker.sub}`, email: maker.email, autonomousEnv: 'prod' } })
+ tabId = (await new SuperTabStore(db, () => NOW).create(maker, randomUUID(), 'Starts')).id
+ const start = (key: string, finishedAt: Date | null) => ({ id: `${tabId}:${key}`, tabId, key, version: 1, changedAt: new Date(NOW - 30 * DAY), ordinal: 1,
+ data: { id: key }, machineId: 'm', conversationId: 'c', agentId: null, deleted: false, finishedAt })
+ await db.swarmStart.createMany({ data: [
+ start('expired', new Date(NOW - RETENTION_MS - DAY)),
+ start('recent', new Date(NOW - DAY)),
+ // Still starting, as parts/write.ts stores it: no finish time yet. Old enough that only its finish time keeps it.
+ ...Array.from({ length: 3 }, (_, i) => start(`running-${i}`, null)),
+ ] })
+ // One stored before the finish time was extracted lacks the field.
+ await db.$runCommandRaw({ insert: 'SwarmStart', documents: [{ _id: `${tabId}:legacy`, tabId, key: 'legacy', version: 1,
+ changedAt: { $date: new Date(NOW - 30 * DAY).toISOString() }, ordinal: 1, data: { id: 'legacy' }, machineId: 'm', conversationId: 'c', deleted: false }] })
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+it('removes only starts that finished more than 7 days ago, never one still starting', async () => {
+ const result = await sweepSwarms(db, NOW)
+ expect(result.startsExpired).toBe(1)
+ const rows = await db.swarmStart.findMany({ where: { tabId }, select: { key: true, deleted: true }, orderBy: { key: 'asc' } })
+ expect(rows.filter(r => r.deleted).map(r => r.key)).toEqual(['expired'])
+ expect(rows.filter(r => !r.deleted).map(r => r.key)).toEqual(['legacy', 'recent', 'running-0', 'running-1', 'running-2'])
+})
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index fabd55dbf..4ac2f0aa5 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -385,6 +385,22 @@ describe('Super Tab collaboration policy', () => {
expect(() => visibleState(f.state, peer)).toThrow('no longer have access')
})
+ // Review of #2188: Desktop adds the accepting computer to the Swarm only when the accept made the person a member. One
+ // who joined by link on another computer while this invitation waited is a member already, and says so.
+ it('says whether the accept made the person a member, and as what', () => {
+ const f = fixture()
+ const invited = f.run({ type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ expect(f.run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer).result)
+ .toEqual({ conversationId: 'lead', alreadyMember: false, role: 'collaborator' })
+ const again = f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' })
+ const late = { kind: 'person' as const, userId: 'late', email: '[email protected]' }
+ // Joined by link elsewhere first, as a viewer: the invitation it still had changes nothing.
+ f.state.people.push({ id: 'late', email: '[email protected]', role: 'viewer', generation: 'link' })
+ expect(f.run({ type: 'invite.accept', inviteId: again.result.inviteId as string }, late).result)
+ .toEqual({ conversationId: 'lead', alreadyMember: true, role: 'viewer' })
+ expect(f.state.people.filter(p => p.id === 'late')).toHaveLength(1)
+ })
+
it('requires the addressed account to accept an unexpired invitation and keeps other invitations private', () => {
const f = fixture()
const invited = f.run({ type: 'invite.create', email: '[email protected]', role: 'collaborator', conversationId: 'lead' })
@@ -2904,17 +2920,17 @@ describe('Lead mentions', () => {
expect(f.run(send('lead', []), as(lead)).messages[0]).not.toHaveProperty('mentions')
})
- it('refuses a person, a non-Lead agent and another project’s Lead', () => {
+ it('refuses a non-Lead agent, another project’s Lead and any tag in the Leads conversation; a person tags (mentions.test.ts)', () => {
const { f, lead, secret } = swarm(), group = f.group(), worker = f.add('worker', 'owner', group)
- expect(() => f.run(send(group, ['peer']))).toThrow('Only a project’s Lead can tag people.')
+ expect(f.run(send(group, ['peer'])).messages[0]!.mentions).toEqual(['peer'])
expect(() => f.run(send(group, ['peer']), as(worker))).toThrow('Only a project’s Lead can tag people.')
expect(() => f.run(send(group, ['owner']), as(secret.lead))).toThrow('This project is unavailable.')
- expect(() => f.run(send(f.state.leadsConversationId!, ['owner']), as(lead))).toThrow('A Lead can tag people only in its own project’s conversations.')
+ expect(() => f.run(send(f.state.leadsConversationId!, ['owner']), as(lead))).toThrow('Nobody is tagged in the Leads conversation.')
})
it('refuses a person who cannot read the conversation or is not in the Swarm', () => {
const { f, secret } = swarm()
- expect(() => f.run(send(secret.conversationId, ['peer']), as(secret.lead))).toThrow('[email protected] cannot read this conversation.')
+ expect(() => f.run(send(secret.conversationId, ['peer']), as(secret.lead))).toThrow('peer cannot read this conversation.')
expect(() => f.run(send(secret.conversationId, ['stranger']), as(secret.lead))).toThrow('Tag a person in this Swarm.')
expect(f.run(send(secret.conversationId, ['owner']), as(secret.lead)).messages[0]!.mentions).toEqual(['owner'])
})
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 48149afec..7cfea2910 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -1,5 +1,6 @@
import { admitMachineStart, cleanupOverdue, downSince, expireRemoval, expireRemovals, failTeamWork, removalEnded, machineContribution, machineOffline, ownedMachine, productManagerOn, projectFolder, projectsOnMachine, requireTeamWork, teamMachineFor, teamAccountPool, teamPoolsOf, teamStartRequest, teamWorkCheck, type ContributedMachine } from './machines.js'
import { assignAgentDisplayNames } from './agentNames.js'
+import { keepUsernames, setUsername } from './usernames.js'
import { z } from 'zod'
import { tokensByModelSchema } from './costs/tokens.js'
import {
@@ -86,7 +87,7 @@ const task = z.object({
export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('machine.contribute'), machineId: id, name: title, cwd: path, scope: z.literal('swarm').optional(), engines: z.array(swarmEngine).min(1).max(2), maxAgents,
- ifMissing: z.literal(true).optional() }).strict(),
+ ifMissing: z.literal(true).optional(), teamAccountOnly: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('machine.pause'), machineId: id, paused: z.boolean() }).strict(),
z.object({ type: z.literal('machine.remove'), machineId: id }).strict(),
z.object({ type: z.literal('machine.cleaned'), machineId: id, removalId: id }).strict(),
@@ -168,6 +169,7 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('member.remove'), userId: id }).strict(),
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('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),
@@ -443,7 +445,8 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if (command.type === 'invite.accept' || command.type === 'agent.sessionClosed' || command.type === 'machine.cleaned') return
// Marking one's own tag done changes only one's own list, so a viewer may do it too.
// Answering a decision asked of oneself changes only that decision, so a viewer may do it too.
- if (command.type === 'mention.done' || command.type === 'decision.answer') return void author(state, actor)
+ // 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)
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
@@ -540,11 +543,15 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
const invite = state.invitations.find(i => i.id === command.inviteId)
if (!invite || invite.email !== actor.email.trim().toLowerCase()) fail('NOT_FOUND', 'This invitation is unavailable.', 404)
if (invite.expiresAt <= context.now) fail('EXPIRED', 'This invitation expired.', 410)
- if (!state.people.some(p => p.id === actor.userId)) {
+ const existing = state.people.find(p => p.id === actor.userId)
+ if (!existing) {
state.people.push({ id: actor.userId, email: invite.email, role: invite.role, generation: invite.id })
}
state.invitations = state.invitations.filter(i => i.id !== invite.id)
result.conversationId = invite.conversationId
+ // As a link join answers (store.ts joinSwarm): Desktop adds the accepting computer only when this made a member.
+ result.alreadyMember = !!existing
+ result.role = existing?.role ?? invite.role
return effects
}
// The host of a removed agent may have left the Swarm with it: the machine owner the request names confirms the close.
@@ -581,7 +588,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
}
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
- const sender = author(state, actor, !leaving && command.type !== 'decision.answer')
+ const sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username')
authorizeCommandAccess(state, actor, command, context)
const rememberAttempt = (group: ReturnType<typeof conversation>) => {
if (group.assignment) effects.previousAttempts.push(structuredClone({ conversationId: group.id,
@@ -1086,6 +1093,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (state.starts?.some(s => s.request.machineId === command.machineId && (!s.harnessId || (s.poolGeneration && !s.poolSettled)) && !s.error)) fail('STARTS_PENDING', 'Reconcile pending starts before changing this contribution.')
// Saving settings sends the whole contribution again; only machine.pause changes its pause (review of #2084).
const paused = mac?.paused ?? state.machines.find(m => m.machineId === command.machineId)?.paused ?? false
+ // Added as its person joined (Desktop's join): teammates' work only through its Harness Team account, for as long as
+ // it stays contributed. Saving its settings sends the contribution without the field, and must not drop the rule.
+ const teamAccountOnly = command.teamAccountOnly || state.machines.find(m => m.machineId === command.machineId)?.teamAccountOnly
state.machines = state.machines.filter(m => m.machineId !== command.machineId)
state.machineCleanups = state.machineCleanups?.filter(c => c.machineId !== command.machineId)
if (!state.machineCleanups?.length) delete state.machineCleanups
@@ -1093,7 +1103,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
state.machines.push({ machineId: command.machineId, name: mac?.name ?? command.name, cwd: command.cwd, engines: [...new Set(command.engines)],
maxAgents: mac?.maxAgents ?? command.maxAgents, ...(command.scope ? { scope: command.scope } : {}),
contributorId: actor.userId, membershipGeneration: contributor.generation, generation: operationId, paused,
- ...(host ? { hostMachineId: host } : {}) })
+ ...(host ? { hostMachineId: host } : {}), ...(teamAccountOnly ? { teamAccountOnly: true as const } : {}) })
// A Mac given other slots or a new name gives its team account the same, and its pause; its own folder, engines and grant stay.
const added = state.machines.at(-1)!
for (const team of teamPoolsOf(state, added)) if (!team.removal) Object.assign(team, { name: added.name, maxAgents: added.maxAgents, paused: added.paused })
@@ -1794,6 +1804,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
case 'member.avatar':
setMemberAvatar(state, actor, command.avatar, context.avatarUpload)
break
+ case 'member.username':
+ setUsername(state, actor, command.username)
+ break
case 'agent.avatar':
setAgentAvatar(state, actor, command.agentId, command.avatar, context.avatarUpload)
break
@@ -2180,6 +2193,7 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (context.registrations) requireSingleRegistration(original, state, context.registrations)
markConfidential(state)
assignAgentDisplayNames(state.agents)
+ keepUsernames(original, state)
// The size limit is per stored part now (parts/commit.ts PART_LIMIT_BYTES); a Swarm as a whole has none.
// Every row this command writes, whatever its words came from: an older message resent, a rule written before this check.
for (const draft of effects.messages) {
diff --git a/backend/src/superTabs/machines.ts b/backend/src/superTabs/machines.ts
index 6af6e084a..5129b90d6 100644
--- a/backend/src/superTabs/machines.ts
+++ b/backend/src/superTabs/machines.ts
@@ -31,6 +31,10 @@ export interface ContributedMachine {
* the host says it cleaned up (machine.cleaned) or REMOVAL_FALLBACK_MS passes. An offline one leaves the list at once and
* its cleanup waits for its host (expireRemovals). Each project's chat hears how it ended (removalEnded). */
removal?: { id: string; state: 'cleaning'; requestedAt: string }
+ /** Added by Desktop as its person joined the Swarm, not lent to teammates by choice: their work runs here only through
+ * its Harness Team account whose privacy check passed, whether or not the Swarm requires that everywhere
+ * (teamWorkRefusal). Kept when the contribution is saved again; gone with the machine. */
+ teamAccountOnly?: true
/** Agent-time Swarm agents here spent on other people's tasks, by leaderboard week, kept by its readings (leaderboard/lent.ts). */
lent?: import('./leaderboard/lent.js').LentWeek[]
}
@@ -226,7 +230,7 @@ export function teamWorkRefusal(pool: ContributedMachine, now: number, teamRow =
// Its last reading stays fresh for a minute, and in that minute it read as taking teammates' work and a Lead's route
// named it (local Team account run, 2026-10-28).
if (pool.hostMachineId && !teamRow) return { code: 'TEAM_ACCOUNT_REQUIRED', reason: `The Harness Team account on ${name} was removed, ${ONLY_OWN}.` }
- if (!teamRow && reading?.sessionKind !== 'team' && !required) return null
+ if (!teamRow && reading?.sessionKind !== 'team' && !required && !pool.teamAccountOnly) return null
if (otherWorkspace) return { code: 'MACHINE_IN_OTHER_WORKSPACE', reason: `The Harness Team account on ${name} also serves another ${WORKSPACE_LABEL}'s Swarms, ${ONLY_OWN} here.` }
if (!reading || now - reading.receivedAt > MACHINE_FRESH_MS) {
// A Mac's team account goes by its Mac's name ("One machine"), and the Mac itself may well be online.
diff --git a/backend/src/superTabs/mentions.test.ts b/backend/src/superTabs/mentions.test.ts
new file mode 100644
index 000000000..f28ac61ce
--- /dev/null
+++ b/backend/src/superTabs/mentions.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor } from './model.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const peer: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'peer', email: '[email protected]' }
+const third: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'third', email: '[email protected]' }
+const configuration = { engine: 'claude', model: null, effort: null, contextWindow: null, engineVersion: null }
+
+function fixture() {
+ let state = createSuperTab('tab', 'Pilot', { id: 'owner', email: owner.email }, 'prod')
+ let next = 0
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}) => {
+ const effects = applyCommand(state, actor, command, { operationId: `op${next++}`, now: 1000,
+ contribution: { machineOwnerId: 'owner', contributorId: actor.kind === 'person' ? actor.userId : 'owner' }, ...context })
+ state = effects.state
+ return effects
+ }
+ for (const who of [peer, third]) {
+ const invited = run({ type: 'invite.create', email: who.email, role: 'collaborator', conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, who)
+ }
+ const app = run({ type: 'project.create', name: 'App', visibility: 'public', brief: '' }).result as { projectId: string; conversationId: string }
+ const worker = run({ type: 'agent.add', conversationId: app.conversationId, harnessId: 'worker', machineId: 'machine', name: 'Worker', lead: false,
+ configuration }).result.agentId as string
+ const group = run({ type: 'conversation.create', projectId: app.projectId, title: 'Copy', brief: '', checks: [] }).result.conversationId as string
+ // A conversation only `peer` reads: their chat with their Buddy.
+ const pmChat = run({ type: 'buddy.chat', projectId: app.projectId }, peer).result.conversationId as string
+ const send = (conversationId: string, mentions: string[], actor: Actor = owner) => run({ type: 'message.send', conversationId,
+ text: 'Please look.', replyTo: null, recipientIds: [], mentions }, actor).messages.at(-1)!
+ return { run, send, app, worker, group, pmChat, get state() { return state } }
+}
+
+describe('people tagging people', () => {
+ it('tags a person who can read the conversation', () => {
+ const f = fixture()
+ expect(f.send(f.group, ['peer', 'third']).mentions).toEqual(['peer', 'third'])
+ expect(f.send(f.group, ['owner'], peer).mentions).toEqual(['owner'])
+ })
+
+ it('drops the author’s own tag', () => {
+ const f = fixture()
+ expect(f.send(f.group, ['owner', 'peer']).mentions).toEqual(['peer'])
+ })
+
+ it('refuses a tag of someone who cannot read the conversation, or is not in the Swarm', () => {
+ const f = fixture()
+ expect(() => f.send(f.pmChat, ['third'], peer)).toThrow(expect.objectContaining({ code: 'INVALID_MENTION' }))
+ expect(() => f.send(f.group, ['stranger'])).toThrow(expect.objectContaining({ code: 'INVALID_MENTION' }))
+ })
+
+ it('refuses tags in the Leads conversation', () => {
+ const f = fixture()
+ const leads = f.state.leadsConversationId!
+ expect(() => f.send(leads, ['peer'])).toThrow(expect.objectContaining({ code: 'MENTION_FORBIDDEN' }))
+ })
+
+ it('still lets only a project’s Lead among agents tag people', () => {
+ const f = fixture()
+ expect(() => f.send(f.app.conversationId, ['peer'], { kind: 'agent', agentId: f.worker, machineOwnerId: 'owner' }))
+ .toThrow(expect.objectContaining({ code: 'MENTION_FORBIDDEN' }))
+ })
+})
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index 3ef56b3b7..43f238326 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -1,4 +1,4 @@
-/** A Lead tags people in its message; each tag waits in the person's Swarm-wide list until they reply in that
+/** A person, or a project's Lead, tags people in a message; each tag waits in the person's Swarm-wide list until they reply in that
* conversation or mark it done. Tags live in SuperTabMention, never in the tab state, so an older backend still
* reads and writes a tab that has them. Called inside SuperTabStore's transactions. */
import { createHash } from 'node:crypto'
@@ -7,6 +7,7 @@ import { ensureIndex } from '../lib/db/indexes.js'
import { fail, isLeads, person, stableId, type Actor, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
import { canReadGroup, groupProject, ledProject, projectOf } from './projects.js'
import { groupsBy } from './parts/indexed.js'
+import { usernameOf } from './usernames.js'
type Tx = Prisma.TransactionClient
export const MAX_MENTIONS = 5
@@ -22,17 +23,21 @@ export async function ensureMentionExpiry(db: PrismaClient): Promise<void> {
await ensureIndex(db, 'SuperTabMention', { key: { createdAt: 1 }, name: 'mention_expiry', expireAfterSeconds: MENTION_EXPIRY_MS / 1000 })
}
-/** Only the project's Lead tags, only in that project's conversations, and only people who can read the conversation. */
+/** A person who can post here tags people; among agents only the project's Lead, in that project's conversations. Never in
+ * the Leads conversation, and only people who can read the conversation. A person's tag of themselves is dropped. */
export function checkMentions(state: SuperTabState, actor: Actor, group: Conversation, personIds: string[]): string[] {
- const ids = [...new Set(personIds)]
+ const ids = [...new Set(personIds)].filter(id => actor.kind !== 'person' || id !== actor.userId)
if (!ids.length) return ids
- const led = actor.kind === 'agent' ? ledProject(state, actor.agentId) : undefined
- if (!led) fail('MENTION_FORBIDDEN', 'Only a project’s Lead can tag people.', 403)
- if (isLeads(group) || groupProject(state, group).id !== led.id) fail('MENTION_FORBIDDEN', 'A Lead can tag people only in its own project’s conversations.', 403)
+ if (isLeads(group)) fail('MENTION_FORBIDDEN', 'Nobody is tagged in the Leads conversation.', 403)
+ if (actor.kind === 'agent') {
+ const led = ledProject(state, actor.agentId)
+ if (!led) fail('MENTION_FORBIDDEN', 'Only a project’s Lead can tag people.', 403)
+ if (groupProject(state, group).id !== led.id) fail('MENTION_FORBIDDEN', 'A Lead can tag people only in its own project’s conversations.', 403)
+ }
for (const id of ids) {
const member = state.people.find(p => p.id === id) ?? fail('INVALID_MENTION', 'Tag a person in this Swarm.', 400)
if (!canReadGroup(state, { kind: 'person', userId: member.id, email: member.email }, group)) {
- fail('INVALID_MENTION', `${member.email} cannot read this conversation.`, 400)
+ fail('INVALID_MENTION', `${usernameOf(state, member.id)} cannot read this conversation.`, 400)
}
}
return ids
@@ -111,10 +116,12 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,
select: { id: true, text: true, author: true } }) : []
return tagged.map(({ row, group }) => {
const message = messages.find(m => m.id === row.messageId)
- const author = message?.author as { name?: string; displayName?: string } | undefined
+ 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'
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: author?.displayName ?? author?.name ?? 'Lead', text: (message?.text ?? '').slice(0, 200),
+ leadId: row.authorAgentId, leadName: authorName, text: (message?.text ?? '').slice(0, 200),
createdAt: row.createdAt, resolvedAt: row.resolvedAt, resolvedBy: row.resolvedBy }
})
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 0117dbf92..7b2c7544f 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -3,6 +3,7 @@ import { lostReasonWithoutMachine } from './lostReason.js'
import type { RouteDecisionEffect } from './routeRecord.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
import { withAvatarView } from './profile.js'
+import { swarmUsernames } from './usernames.js'
import { downSince, expireRemovals, startPreparing } from './machines.js'
import { publicReason, readsRawReason } from './startFailure.js'
import { agentProjectId, agentSetRole, canReadAgent, canReadGroup, canReadProject, groupProject, ledProject, placeRules, projectsOf, sharedWithLeads, skillSetOf, type ProjectVisibility, type SwarmProject } from './projects.js'
@@ -17,6 +18,8 @@ export interface Person {
status?: import('./profile.js').PersonStatus
/** Their own avatar (profile.ts); only Swarm members read it. */
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
}
export interface AgentConfiguration {
engine: string
@@ -628,7 +631,9 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
for (const project of projectsOf(visible)) for (const target of awaitingWorkers(visible, project.id)) target.workDecision = 'awaiting'
for (const project of visible.projects ?? []) project.skillSet = skillSetOf(project)
// An uploaded avatar's stored key stays on the server; readers get a link with each parts read (avatarLinks.ts).
- visible.people = visible.people.map(withAvatarView) as Person[]
+ // Each person as the Swarm names them (usernames.ts), their default included.
+ const names = swarmUsernames(state)
+ visible.people = visible.people.map(p => ({ ...withAvatarView(p), username: names.get(p.id) })) as Person[]
visible.agents = visible.agents.map(withAvatarView) as Agent[]
// On Custom every agent shows the role it runs, null when its kind has none; elsewhere a role id means nothing yet.
for (const target of visible.agents) {
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index 6afe24faa..53d39d7d4 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -57,6 +57,11 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'agent.avatar':
leadCheck(agentProject(command.agentId))
break
+ case 'member.username':
+ // 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()
+ break
case 'project.report': case 'project.repository': case 'project.skills':
leadCheck(command.projectId)
break
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 04220f024..9a7a1a2a8 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -10,6 +10,7 @@ import * as store from '../parts/index.js'
import type { Part, SwarmParts } from '../parts/index.js'
import { canReadGroup } from '../projects.js'
import { withAvatarView } from '../profile.js'
+import { swarmUsernames } from '../usernames.js'
import type { AgentView, Derived, GroupView, HeadView, LivePart, MachineView, MemberView, ProgressView, StartView } from './contract.js'
export interface ReaderParts {
@@ -85,12 +86,15 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:
const head = Object.fromEntries(HEAD_FIELDS.filter(field => visible[field] !== undefined).map(field => [field, visible[field]])) as HeadView
if (head.projects) head.projects = head.projects.map(({ progress: _progress, ...project }) => project)
head.invitations = visible.invitations.filter(i => readable.has(i.conversationId))
- const projects = new Set((visible.projects ?? []).map(p => p.id)), seen = seenMachineIds(visible), buddy = isBuddyReader(state, actor)
+ const projects = new Set((visible.projects ?? []).map(p => p.id)), seen = seenMachineIds(visible), names = swarmUsernames(state)
+ const buddy = isBuddyReader(state, actor)
return {
state,
parts: {
head: envelope(parts.head, head),
- members: parts.members.filter(m => !m.deleted).map(m => envelope(m, withAvatarView(m.data!) as MemberView)),
+ // Each person's username as the Swarm shows it, worked out in join order (the reassembled state's), never the order
+ // member parts happen to load in.
+ members: parts.members.filter(m => !m.deleted).map(m => envelope(m, { ...withAvatarView(m.data!), username: names.get(m.key) } as MemberView)),
agents: visible.agents.map(a => envelope(agentPart(a.id), buddy ? agentWithoutMachine(agentView(state.agents.find(s => s.id === a.id)!))
: agentView(state.agents.find(s => s.id === a.id)!))),
groups: groups.map(g => envelope(groupPart(g.id), groupView(buddy ? groupWithoutMachines(g) : g, seen))),
diff --git a/backend/src/superTabs/sweeps.ts b/backend/src/superTabs/sweeps.ts
index 3e10e5ca8..0f98bc6fc 100644
--- a/backend/src/superTabs/sweeps.ts
+++ b/backend/src/superTabs/sweeps.ts
@@ -87,10 +87,14 @@ async function sleepQuietGroups(db: PrismaClient, now: number): Promise<number>
/** Finished starts are kept 7 days, then removed (spec, Archive); their tombstones go 7 days later (purge index). */
async function expireStarts(db: PrismaClient, now: number): Promise<number> {
- const rows = await db.swarmStart.findMany({ where: { deleted: false, finishedAt: { lt: new Date(now - RETENTION_MS) } }, take: BATCH })
+ // A plain match: Prisma sent `finishedAt: { lt }` as $expr, where a null finish time is less than any date, so every start
+ // still starting was removed too (2026-10-29). Here a start with no finish time never matches.
+ const rows = await db.swarmStart.aggregateRaw({ pipeline: [
+ { $match: { deleted: false, finishedAt: { $lt: { $date: new Date(now - RETENTION_MS).toISOString() } } } }, { $limit: BATCH },
+ { $project: { tabId: 1, key: 1, version: 1, data: 1 } }] }) as unknown as Array<{ tabId: string; key: string; version: number; data: unknown }>
let expired = 0
for (const row of rows) {
- if (await guarded(db, { tabId: row.tabId, op: 'remove', kind: 'start', key: row.key, seen: row.version, data: row.data as unknown as AgentStart })) expired++
+ if (await guarded(db, { tabId: row.tabId, op: 'remove', kind: 'start', key: row.key, seen: Number(row.version), data: row.data as AgentStart })) expired++
}
return expired
}
diff --git a/backend/src/superTabs/teamRouting.test.ts b/backend/src/superTabs/teamRouting.test.ts
index d8457803c..7877542af 100644
--- a/backend/src/superTabs/teamRouting.test.ts
+++ b/backend/src/superTabs/teamRouting.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { applyCommand, commandSchema, type Command, type CommandContext } from './commands.js'
import { admitMachineStart, machineObservationSchema, machineTeamWork, machineSlots, observedPrivacy, PRIVACY_FRESH_MS, removalPreview, teamAccountRequired, teamAccountSwarm, teamWorkRefusal, type ContributedMachine, type MachinePrivacy } from './machines.js'
import { createSuperTab, SuperTabError, visibleState, type Actor, type AgentConfiguration, type AgentStart, type SuperTabState } from './model.js'
import type { RouteDecision } from './routeRecord.js'
@@ -683,3 +683,57 @@ describe('a Team machine serving more than one Workspace', () => {
expect(teamWorkRefusal(f.machine('mate-team'), NOW, true, true, false)).toBeNull()
})
})
+
+// A machine Desktop adds as its person joins a Swarm (Scholes, 2026-10-29): nobody chose to lend it to teammates, so their
+// work reaches it only through its Harness Team account, whose privacy check passed, even while the rule is not
+// required everywhere. Until then it runs only its person's own projects, and never a teammate's agent as that person.
+describe('a machine added as its person joined', () => {
+ beforeEach(() => { delete process.env.SWARM_TEAM_ACCOUNT_REQUIRED })
+ const joined: Extract<Command, { type: 'machine.contribute' }> = { type: 'machine.contribute', machineId: 'joined-mac', name: 'MacBook Air',
+ cwd: '/swarm', scope: 'swarm', engines: ['codex'], maxAgents: 4, teamAccountOnly: true }
+ const contribution = { contribution: { machineOwnerId: 'mate', contributorId: 'mate', hostGrant: null } }
+
+ it('refuses a teammate\'s start on it while it has no Harness Team account, and keeps its person\'s own projects', () => {
+ const f = swarm(), group = f.group(), own = f.group(f.mine, mate)
+ f.run(joined, mate, contribution)
+ f.machine('joined-mac').observation = reading('computer')
+ expect(refusal(() => f.run({ type: 'agent.start', request: f.request(group, 'joined-mac') }, owner, f.pooled('joined-mac'))))
+ .toMatchObject({ code: 'TEAM_ACCOUNT_REQUIRED', status: 403, message: 'MacBook Air has no Harness Team account yet, so it runs only its owner\'s projects.' })
+ expect(f.state.starts ?? []).toEqual([])
+ f.run({ type: 'agent.start', request: f.request(own, 'joined-mac', f.mine) }, mate, f.pooled('joined-mac'))
+ expect(f.state.starts).toHaveLength(1)
+ })
+
+ it('says why in its reading, so routing leaves it out of a teammate\'s project', () => {
+ const f = swarm()
+ f.run(joined, mate, contribution)
+ f.machine('joined-mac').observation = reading('computer')
+ expect(machineTeamWork(f.state, f.machine('joined-mac'), NOW, [])?.code).toBe('TEAM_ACCOUNT_REQUIRED')
+ // An ordinary machine contributed by hand takes it as before while the rule is not required.
+ expect(machineTeamWork(f.state, f.machine('mate-mac'), NOW, [])).toBeNull()
+ })
+
+ it('keeps the rule when its settings are saved again, which sends the contribution without it', () => {
+ const f = swarm()
+ f.run(joined, mate, contribution)
+ const { teamAccountOnly: _rule, ...settings } = joined
+ f.run({ ...settings, maxAgents: 2 }, mate, contribution)
+ expect(f.machine('joined-mac')).toMatchObject({ maxAgents: 2, teamAccountOnly: true })
+ })
+
+ it('admits a teammate\'s work once its Team account\'s privacy check passed', () => {
+ const f = swarm()
+ f.run(joined, mate, contribution)
+ f.machine('joined-mac').observation = reading('team', PASSED)
+ expect(teamWorkRefusal(f.machine('joined-mac'), NOW)).toBeNull()
+ f.machine('joined-mac').observation = reading('team', FAILED)
+ expect(teamWorkRefusal(f.machine('joined-mac'), NOW)?.code).toBe('PRIVACY_CHECK_FAILED')
+ })
+
+ it('is a choice only its person makes: the field is refused on any other command shape', () => {
+ expect(commandSchemaOf(joined).success).toBe(true)
+ expect(commandSchemaOf({ ...joined, teamAccountOnly: false }).success).toBe(false)
+ })
+})
+
+const commandSchemaOf = (command: unknown) => commandSchema.safeParse(command)
diff --git a/backend/src/superTabs/usernames.test.ts b/backend/src/superTabs/usernames.test.ts
new file mode 100644
index 000000000..5d0b22204
--- /dev/null
+++ b/backend/src/superTabs/usernames.test.ts
@@ -0,0 +1,250 @@
+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 { changesFor } from './read/changes.js'
+import { readerView } from './read/views.js'
+import { usernameOf, usernames } from './usernames.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const NOW = Date.parse('2026-10-29T01: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' }>
+
+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)
+ }
+ const name = (id: string) => usernameOf(state, id)
+ return { run, join, name, get state() { return state } }
+}
+
+// The same cases desktop/test/super_tab_usernames_test.dart checks: both sides work out defaults by this one rule.
+describe('default usernames', () => {
+ it('is the lowercased email prefix, numbered by join order when two share one', () => {
+ expect(usernames([
+ { id: 'a', email: '[email protected]' },
+ { id: 'b', email: '[email protected]' },
+ { id: 'c', email: '[email protected]' },
+ { id: 'd', email: '[email protected]' },
+ ])).toEqual(new Map([['a', 'ken'], ['b', 'ken2'], ['c', 'tony'], ['d', 'ken3']]))
+ })
+
+ it('keeps a chosen name and numbers a default around it', () => {
+ expect(usernames([
+ { id: 'a', email: '[email protected]', username: 'ken' },
+ { id: 'b', email: '[email protected]' },
+ { id: 'c', email: '[email protected]' },
+ ])).toEqual(new Map([['a', 'ken'], ['b', 'ken2'], ['c', 'diego']]))
+ })
+
+ it('makes a usable name of a prefix with other characters, or too short', () => {
+ expect(usernames([
+ { id: 'a', email: '[email protected]' },
+ { id: 'b', email: '[email protected]' },
+ { id: 'c', email: '[email protected]' },
+ { id: 'd', email: `${'a'.repeat(40)}@example.com` },
+ ])).toEqual(new Map([['a', 'pham.ngocswarm'], ['b', 'x1'], ['c', 'user'], ['d', 'a'.repeat(30)]]))
+ })
+})
+
+describe('member.username', () => {
+ it('gives the owner and each new person their default without storing one', () => {
+ const f = fixture()
+ f.join(person('peer', '[email protected]'))
+ f.join(person('peer-2', '[email protected]'))
+ expect([f.name('owner'), f.name('peer'), f.name('peer-2')]).toEqual(['ken15', 'peer', 'peer2'])
+ expect(f.state.people.map(p => p.username)).toEqual([undefined, undefined, undefined])
+ })
+
+ it('sets and clears the person’s own name, lowercased and trimmed', () => {
+ const f = fixture()
+ f.run({ type: 'member.username', username: ' River.K ' })
+ expect(f.state.people[0]!.username).toBe('river.k')
+ expect(f.name('owner')).toBe('river.k')
+ f.run({ type: 'member.username', username: null })
+ expect(f.state.people[0]!.username).toBeUndefined()
+ expect(f.name('owner')).toBe('ken15')
+ })
+
+ it('refuses a name another person has, chosen or default, ignoring case', () => {
+ const f = fixture()
+ const peer = person('peer', '[email protected]')
+ f.join(peer)
+ expect(() => f.run({ type: 'member.username', username: 'Peer' })).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN', status: 409 }))
+ f.run({ type: 'member.username', username: 'boss' })
+ expect(() => f.run({ type: 'member.username', username: 'BOSS' }, peer)).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ // Their own current name, default or chosen, is no conflict.
+ f.run({ type: 'member.username', username: 'peer' }, peer)
+ f.run({ type: 'member.username', username: 'boss' })
+ expect([f.name('owner'), f.name('peer')]).toEqual(['boss', 'peer'])
+ })
+
+ it('refuses a name that would take a later default’s number', () => {
+ const f = fixture()
+ f.join(person('ken-a', '[email protected]'))
+ f.join(person('ken-b', '[email protected]'))
+ expect(f.name('ken-b')).toBe('ken2')
+ expect(() => f.run({ type: 'member.username', username: 'ken2' })).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ })
+
+ it('keeps a later person’s numbered name when the name before it is freed by a rename', () => {
+ const f = fixture()
+ f.join(person('ken-a', '[email protected]'))
+ f.join(person('ken-b', '[email protected]'))
+ f.run({ type: 'member.username', username: 'kenny' }, person('ken-a', '[email protected]'))
+ expect([f.name('ken-a'), f.name('ken-b')]).toEqual(['kenny', 'ken2'])
+ expect(f.state.people.find(p => p.id === 'ken-b')!.username).toBe('ken2')
+ // Nobody else's default moved, so nothing else was stored.
+ expect(f.state.people[0]!.username).toBeUndefined()
+ })
+
+ it('keeps a later person’s numbered name when the person before them leaves', () => {
+ const f = fixture()
+ const first = person('ken-a', '[email protected]')
+ f.join(first)
+ f.join(person('ken-b', '[email protected]'))
+ f.run({ type: 'member.remove', userId: 'ken-a' }, first)
+ expect(f.name('ken-b')).toBe('ken2')
+ expect(f.state.people.find(p => p.id === 'ken-b')!.username).toBe('ken2')
+ })
+
+ it('refuses a malformed name', () => {
+ const f = fixture()
+ for (const username of ['k', 'a'.repeat(33), 'ken nguyen', '.ken', 'kén', 'ken@x', '-'] as const) {
+ expect(() => f.run({ type: 'member.username', username }), username).toThrow()
+ }
+ expect(f.state.people[0]!.username).toBeUndefined()
+ })
+
+ it('is every person’s own, a viewer’s too; refused for an agent and anyone outside', () => {
+ const f = fixture()
+ const viewer = person('viewer', '[email protected]')
+ f.join(viewer, 'viewer')
+ f.run({ type: 'member.username', username: 'watcher' }, viewer)
+ expect(f.name('viewer')).toBe('watcher')
+ // A viewer still writes nothing else.
+ expect(() => f.run({ type: 'member.status', status: { text: 'Hi' } }, viewer)).toThrow(expect.objectContaining({ code: 'READ_ONLY' }))
+ expect(() => f.run({ type: 'member.username', username: 'bot' }, { kind: 'agent', agentId: 'a1', machineOwnerId: 'owner' })).toThrow()
+ expect(() => f.run({ type: 'member.username', username: 'stranger' }, person('stranger', '[email protected]'))).toThrow()
+ expect(f.state.people.map(p => p.username)).toEqual([undefined, 'watcher'])
+ })
+
+ it('never gives a person an agent’s name: a default is numbered, a choice refused', () => {
+ 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' } })
+ f.join(person('river', '[email protected]'))
+ expect(f.name('river')).toBe('river2')
+ expect(() => f.run({ type: 'member.username', username: 'RIVER' })).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ // An automatic agent name counts too.
+ const nova = f.run({ type: 'agent.add', conversationId: 'lead', harnessId: 'builder', machineId: 'machine', name: 'Builder', configuration,
+ lead: false }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } }).result.agentId as string
+ const shown = f.state.agents.find(a => a.id === nova)!.displayName!
+ expect(() => f.run({ type: 'member.username', username: shown.toLowerCase() })).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ })
+
+ /** A Swarm with `peer`, a private project's Lead `Hush` that only the owner reads, and the owner's Buddy `Pal`. */
+ function hidden() {
+ const f = fixture()
+ const peer = person('peer', '[email protected]')
+ f.join(peer)
+ const secret = f.run({ type: 'project.create', name: 'Secret', visibility: 'private', brief: '' }).result as { conversationId: string }
+ f.run({ type: 'agent.add', conversationId: secret.conversationId, harnessId: 'hidden', machineId: 'machine', name: 'Hush', configuration,
+ lead: true }, owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ const generation = f.state.people[0]!.generation
+ f.state.agents.push({ id: 'buddy', machineId: 'machine', harnessId: 'buddy-harness', machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: generation, name: 'Pal', configuration, buddyOf: { personId: 'owner', generation } })
+ return { f, peer }
+ }
+
+ it('lets a member take the name of an agent they cannot see, or of a Buddy, and says nothing about it', () => {
+ const { f, peer } = hidden()
+ f.run({ type: 'member.username', username: 'hush' }, peer)
+ expect(f.name('peer')).toBe('hush')
+ f.run({ type: 'member.username', username: 'pal' }, peer)
+ expect(f.name('peer')).toBe('pal')
+ })
+
+ it('refuses the name of a private agent to someone who can see it', () => {
+ const { f } = hidden()
+ expect(() => f.run({ type: 'member.username', username: 'hush' })).toThrow(expect.objectContaining({ code: 'USERNAME_TAKEN' }))
+ })
+
+ it('reads a Swarm whose agent’s project is gone', () => {
+ const f = fixture()
+ f.state.agents.push({ id: 'stray', projectId: 'removed', machineId: 'machine', harnessId: 'h', machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: 'g', name: 'Stray', configuration })
+ expect(f.name('owner')).toBe('ken15')
+ f.run({ type: 'member.username', username: 'stray' })
+ expect(f.name('owner')).toBe('stray')
+ })
+
+ it('does not number a default around an agent some members cannot see, or a Buddy', () => {
+ const { f } = hidden()
+ f.join(person('hush', '[email protected]'))
+ f.join(person('pal', '[email protected]'))
+ expect([f.name('hush'), f.name('pal')]).toEqual(['hush', 'pal'])
+ })
+
+ it('keeps a person’s name when an agent named like them arrives later', () => {
+ const f = fixture()
+ f.join(person('river', '[email protected]'))
+ expect(f.name('river')).toBe('river')
+ f.run({ type: 'agent.add', conversationId: 'lead', harnessId: 'pm', machineId: 'machine', name: 'River', configuration, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ expect(f.name('river')).toBe('river')
+ })
+
+ it('reaches a Buddy as each person’s username, beside its own read limits (#2115)', () => {
+ const f = fixture()
+ f.join(person('peer', '[email protected]'))
+ f.run({ type: 'agent.add', conversationId: 'lead', harnessId: 'pm', machineId: 'machine', name: 'River', configuration, lead: true },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ const generation = f.state.people[0]!.generation
+ f.state.agents.push({ id: 'buddy', projectId: 'lead', machineId: 'machine', harnessId: 'buddy-harness', machineOwnerId: 'owner',
+ contributorId: 'owner', membershipGeneration: generation, name: 'Pal', configuration, buddyOf: { personId: 'owner', generation } })
+ const view = readerView(split(f.state, { tabId: 'tab', version: 1, now: NOW }), { kind: 'agent', agentId: 'buddy', machineOwnerId: 'owner' },
+ NOW, { teamMachines: [] })
+ expect(Object.fromEntries(view.parts.members.map(m => [m.key, m.data.username]))).toEqual({ owner: 'ken15', peer: 'ken' })
+ // Its person's machines stay out of what it reads.
+ expect(view.parts.agents.map(a => a.data.machineId)).not.toContain('machine')
+ })
+
+ it('reaches readers as each person’s username whatever order the members are read in', () => {
+ const f = fixture()
+ f.join(person('earlier', '[email protected]'))
+ f.join(person('rejoined', '[email protected]'))
+ const parts = split(f.state, { tabId: 'tab', version: 1, now: NOW })
+ // Member parts load in no fixed order (parts/load.ts); their ordinals keep the join order.
+ parts.members = [parts.members[0]!, parts.members[2]!, parts.members[1]!]
+ const view = readerView(parts, owner, NOW, { teamMachines: [] })
+ expect(Object.fromEntries(view.parts.members.map(m => [m.key, m.data.username])))
+ .toEqual({ owner: 'ken15', earlier: 'ken', rejoined: 'ken2' })
+ // So do changes, which send the member as the reader's view has it.
+ const changed = changesFor(view, [parts.members.find(m => m.key === 'rejoined')!], owner)
+ expect(changed.members.map(m => ('data' in m ? m.data.username : null))).toEqual(['ken2'])
+ // And a whole-state read.
+ expect(visibleState(f.state, owner, NOW).people.map(p => p.username)).toEqual(['ken15', 'ken', 'ken2'])
+ })
+
+ it('touches every person and the head, so two people choosing one name at once, or a join, retry', () => {
+ const f = fixture()
+ f.join(person('peer', '[email protected]'))
+ const before = f.state
+ const command: Command = { type: 'member.username', username: 'pilot' }
+ const effects = applyCommand(before, owner, command, { now: NOW, operationId: 'op-touch' })
+ expect(touchesFor(command, owner, before, effects)).toEqual(expect.arrayContaining([
+ { kind: 'member', key: 'owner' }, { kind: 'member', key: 'peer' }, { kind: 'head', key: 'head' },
+ ]))
+ })
+})
diff --git a/backend/src/superTabs/usernames.ts b/backend/src/superTabs/usernames.ts
new file mode 100644
index 000000000..c7b1a222f
--- /dev/null
+++ b/backend/src/superTabs/usernames.ts
@@ -0,0 +1,93 @@
+import { assignAgentDisplayNames } from './agentNames.js'
+import { isBuddy } from './buddies.js'
+import { fail, person, type Actor, type Agent, type Person, type SuperTabState } from './model.js'
+import { agentProjectId, canReadAgent, projectsOf } from './projects.js'
+
+/** A username as a person types it: 2 to 32 lowercase letters, digits, `.`, `_` or `-`, starting with a letter or digit. */
+const SHAPE = /^[a-z0-9][a-z0-9._-]{1,31}$/
+/** Room left in a default for its number (`ken` → `ken12`). */
+const DEFAULT_BASE_LENGTH = 30
+
+/** The name a person's email prefix makes: lowercased, only the characters a username takes, never too short. */
+function base(email: string): string {
+ const prefix = email.split('@')[0]!.toLowerCase().replace(/[^a-z0-9._-]/g, '').replace(/^[._-]+/, '').slice(0, DEFAULT_BASE_LENGTH)
+ if (!prefix) return 'user'
+ return prefix.length < 2 ? `${prefix}1` : prefix
+}
+
+/**
+ * Every person's username, by id: the one they chose (or one kept for them), else their email prefix, numbered (`ken2`,
+ * `ken3`) after the names of everyone who joined before them, every chosen name and [agentNames], so nobody is
+ * `@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> {
+ const taken = new Set([...people.flatMap(p => p.username ? [p.username] : []), ...[...agentNames].map(name => name.toLowerCase())])
+ const names = new Map<string, string>()
+ for (const member of people) {
+ if (member.username) {
+ names.set(member.id, member.username)
+ continue
+ }
+ const root = base(member.email)
+ let name = root
+ for (let n = 2; taken.has(name); n++) name = `${root}${n}`
+ taken.add(name)
+ names.set(member.id, name)
+ }
+ return names
+}
+
+/** The names the Swarm shows its agents, as `assignAgentDisplayNames` gives them, without changing [state], for those [counts]
+ * keeps. A Buddy never counts: it is one person's, named for them. */
+function agentNames(state: Pick<SuperTabState, 'agents'>, counts: (agent: Agent) => boolean): string[] {
+ const named = state.agents.map(agent => ({ ...agent }))
+ assignAgentDisplayNames(named)
+ return named.filter(agent => !isBuddy(agent) && counts(agent)).map(agent => agent.displayName ?? agent.name)
+}
+
+/** Agents every member sees, those of shared projects: only these number a default, which every member reads. An agent some
+ * members cannot see never shapes a name they can (review of #2088). */
+const sharedAgentNames = (state: SuperTabState): string[] => agentNames(state, agent => {
+ // An agent of a project that is gone counts for nobody; every read works this out, so it never throws.
+ const project = projectsOf(state).find(p => p.id === agentProjectId(state, agent))
+ return !!project && project.visibility !== 'private'
+})
+
+/** Every person's username in [state], by id. */
+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)
+
+/** `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)
+ // 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.username
+ const name = input.trim().toLowerCase()
+ if (!SHAPE.test(name)) fail('INVALID_USERNAME', 'Use 2 to 32 letters, digits, dots, dashes or underscores, starting with a letter or digit.', 400)
+ // 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)) {
+ 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)
+ }
+ member.username = name
+}
+
+/** A name never changes under anyone, since tags and habits use it: when a command would move someone's default (the name
+ * before it was freed by a rename or a departure, or an agent now has it), they keep the name they had, stored now. */
+export function keepUsernames(before: SuperTabState, after: SuperTabState): void {
+ const was = swarmUsernames(before)
+ // Only defaults: someone who cleared their own chosen name meant to go back to theirs.
+ const defaulted = new Set(before.people.filter(p => !p.username).map(p => p.id))
+ // One at a time: keeping one person's name can move the next default again.
+ for (;;) {
+ const now = swarmUsernames(after)
+ const moved = after.people.find(p => !p.username && defaulted.has(p.id) && now.get(p.id) !== was.get(p.id))
+ if (!moved) return
+ moved.username = was.get(moved.id)!
+ }
+}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 83a89921f..8c64b72fa 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -3,6 +3,6 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({ test: { include: ['integration/superTabs.test.ts', 'integration/superTabSharing.test.ts', 'integration/superTabGithub.test.ts', 'integration/superTabTeam.test.ts', 'integration/superTabWorkspaces.test.ts',
'integration/superTabRead.test.ts', 'integration/superTabReadMarks.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',
'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts',
- 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts',
+ 'integration/superTabIndexes.test.ts', 'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabBuddyProbes.test.ts', 'integration/superTabCosts.test.ts',
'integration/harnessSharesList.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/cacheOn.test-support.ts'],
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.ts
index 9e8c387c1..1b26d8699 100644
--- a/cli/src/gateway/accountHttp.spec.ts
+++ b/cli/src/gateway/accountHttp.spec.ts
@@ -82,6 +82,20 @@ describe('account HTTP in the gateway', () => {
}
})
+ // Scholes 10-29: the banner read "Could not reach the Harness backend (). Check the connection and try again."
+ it.each([
+ ['an empty cause message', Object.assign(new Error('fetch failed'), { cause: { message: '' } }), 'fetch failed'],
+ ['no message at all', new Error(''), null],
+ ['a blank cause and message', Object.assign(new Error(' '), { cause: { message: ' ' } }), null],
+ ])('never shows empty parentheses when the failure has %s', async (_name, failure, reason) => {
+ const { api, request } = setup()
+ request.mockRejectedValueOnce(failure)
+ const answer = await api.backend('GET', '/api/auth/me')
+ expect(answer.body).toMatchObject({ error: { message: reason === null
+ ? 'Could not reach the Harness backend. Check the connection and try again.'
+ : `Could not reach the Harness backend (${reason}). Check the connection and try again.` } })
+ })
+
// Diego 10-29: a body that timed out after the headers, or HTML from a proxy, read as '200 OK, {}'.
it('answers a body that times out after the headers as a timeout, not as an empty success', async () => {
const { api, request } = setup()
diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.ts
index a7078d777..2f2684ab7 100644
--- a/cli/src/gateway/accountHttp.ts
+++ b/cli/src/gateway/accountHttp.ts
@@ -66,7 +66,9 @@ export function createAccountHttp(deps: AccountHttpDeps) {
} catch (error) {
const e = error as Error & { cause?: { message?: string } }
if (timedOut(e)) return timeout()
- return failure(502, 'BACKEND_UNREACHABLE', `Could not reach the Harness backend (${e.cause?.message ?? e.message}). Check the connection and try again.`)
+ // An empty reason is no reason: no parentheses then (Scholes 10-29).
+ const reason = [e.cause?.message, e.message].map(text => text?.trim()).find(Boolean)
+ return failure(502, 'BACKEND_UNREACHABLE', `Could not reach the Harness backend${reason ? ` (${reason})` : ''}. Check the connection and try again.`)
}
// The timeout also covers the body: a success that stalls after the headers, or a proxy's HTML page, is not an empty
// success (Diego 10-29). A refusal keeps its status whatever its body does: 401/403 sign out, 426 asks for an update.
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 5f2947690..5264ea5b7 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -1007,6 +1007,19 @@ describe('the Harness Team account, offered by Desktop on this Mac', () => {
expect(offer).toHaveBeenCalledTimes(2)
})
+ it('tells only Desktop on this Mac why there is no account, asking nothing and starting nothing', async () => {
+ const offer = vi.fn(async () => ({ state: 'started' as const }))
+ const status = vi.fn(async () => ({ state: 'failed' as const, detail: 'launchd would not start it' }))
+ const service = superTabService(fakeCore(), { teamSetup: async () => ({ offer, decline: vi.fn(), status }) })
+ expect(await service.requests.super_tabs({ action: 'teamSetupStatus' }, owner)).toEqual({ ok: true, state: 'failed', detail: 'launchd would not start it' })
+ // Through the relay, or anyone but the owner: the reason can name this Mac's own setup, so it stays on this Mac.
+ for (const asker of [visitor, { local: false, owner: true, accountOwner: true }]) {
+ expect(await service.requests.super_tabs({ action: 'teamSetupStatus' }, asker as never)).toEqual({ error: 'OWNER_REQUIRED' })
+ }
+ expect(status).toHaveBeenCalledOnce()
+ expect(offer).not.toHaveBeenCalled()
+ })
+
it('at app start, answers at once on a Mac that hosts no Swarm work, as no regular user\'s does', async () => {
const offer = vi.fn(async (_reason: string, _shared: () => Promise<boolean>) => ({ state: 'not-shared' as const }))
const make = vi.fn(async () => ({ offer, decline: vi.fn() }))
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index 1d5a84432..b3d26b8c6 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -223,7 +223,7 @@ export interface SuperTabServiceOptions {
/** What reports the Harness Team account's own engines to its owner (team/engines.ts), for a spec. */
teamEngines?: () => Pick<TeamEngineReporter, 'start' | 'stop'>
/** What sets up the Harness Team account when Desktop asks (team/autoSetup.ts), for a spec. */
- teamSetup?: () => Promise<Pick<TeamAutoSetup, 'offer' | 'decline'>>
+ teamSetup?: () => Promise<Pick<TeamAutoSetup, 'offer' | 'decline'> & Partial<Pick<TeamAutoSetup, 'status'>>>
/** Whether this daemon runs team work only (a Harness Team account, `harness team on`), for a spec. */
team?: () => boolean
/** The Harness Team account's own tmux (team/tmux.ts), for a spec. */
@@ -295,7 +295,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
() => readTeamConfig(), options.team ?? (() => readAuthSession()?.kind === 'team'), line => console.log(`[team] ${line}`),
// A team account still on a build that cannot use the relay is updated from here (team/refresh.ts).
(publishedAt) => refreshTeamAccount(realTeamRefreshDeps(core, publishedAt)))))()
- let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'>> | null = null
+ let autoSetup: Promise<Pick<TeamAutoSetup, 'offer' | 'decline'> & Partial<Pick<TeamAutoSetup, 'status'>>> | null = null
// In the Harness Team account: a tmux and a gh of its own when it has none it can run (team/tmux.ts, team/gh.ts). Looked
// at as it connects, and a failed install again half an hour later.
const settled = (outcome: string) => outcome === 'present' || outcome === 'installed' || outcome === 'not-team'
@@ -357,11 +357,17 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
// Harness Team account, behind macOS's own administrator prompt. Never through the relay, with nobody at this Mac.
// `teamSetupCheck` only says whether it is wanted, so Desktop explains it before macOS asks; `teamSetupDecline` is
// that explanation's "Not now". Both are new names, so an older daemon refuses them rather than asking unexplained.
- if (payload.action === 'teamSetup' || payload.action === 'teamSetupCheck' || payload.action === 'teamSetupDecline') {
+ // `teamSetupStatus`: why there is no account yet, for this Mac's own machine row (cancelled, failed and why, running).
+ if (payload.action === 'teamSetup' || payload.action === 'teamSetupCheck' || payload.action === 'teamSetupDecline'
+ || payload.action === 'teamSetupStatus') {
if (!asker.local) return { error: 'OWNER_REQUIRED' }
const setup = () => autoSetup ??= (options.teamSetup ?? (() => realTeamAutoSetup(core.dataDir, line => console.log(`[team] ${line}`))))()
.catch(error => { autoSetup = null; throw error })
if (payload.action === 'teamSetupDecline') { (await setup()).decline(); return { ok: true } }
+ if (payload.action === 'teamSetupStatus') {
+ const made = await setup()
+ return made.status ? { ok: true, ...await made.status() } : { error: 'INVALID_REQUEST' }
+ }
if (!AUTO_SETUP_REASONS.includes(payload.reason as AutoSetupReason)) return { error: 'INVALID_REQUEST' }
// Desktop asks at every launch. A Mac that hosts no Swarm work, as no regular user's does, answers at once:
// nothing read, run or asked of the backend.
diff --git a/cli/src/team/autoSetup.spec.ts b/cli/src/team/autoSetup.spec.ts
index bfe4b4467..1f208161a 100644
--- a/cli/src/team/autoSetup.spec.ts
+++ b/cli/src/team/autoSetup.spec.ts
@@ -102,6 +102,26 @@ describe('the Harness Team account, set up on its own', () => {
expect(unreadable.log.join('\n')).toContain('could not remember')
})
+ it('tells its own Desktop why there is no account: cancelled, failed with the reason, still running, or nothing yet', async () => {
+ const f = fake()
+ expect(await f.auto.status()).toEqual({ state: 'none' })
+ f.setDecision({ state: 'declined', at: 5 })
+ expect(await f.auto.status()).toEqual({ state: 'declined' })
+ f.setDecision({ state: 'failed', at: 5, detail: 'launchd would not start it' })
+ expect(await f.auto.status()).toEqual({ state: 'failed', detail: 'launchd would not start it' })
+ let finish: (value: { code: number; result: Record<string, unknown> | null }) => void = () => {}
+ ;(f.deps.setup as ReturnType<typeof vi.fn>).mockImplementationOnce(() => new Promise((resolve) => { finish = resolve }))
+ await f.auto.offer('manual')
+ expect(await f.auto.status()).toEqual({ state: 'running' })
+ finish({ code: 0, result: { ok: true } })
+ await f.auto.settled()
+ // Made since: whatever was remembered before no longer explains anything.
+ const made = fake({ accountExists: vi.fn(async () => true) })
+ made.setDecision({ state: 'declined', at: 5 })
+ expect(await made.auto.status()).toEqual({ state: 'exists' })
+ expect(made.deps.setup).not.toHaveBeenCalled()
+ })
+
it('on Linux, offers it as on a Mac: wanted at a join, then started; an account there answers exists', async () => {
const linux = fake({ platform: 'linux' })
expect(await linux.auto.offer('join', undefined, true)).toEqual({ state: 'wanted' })
diff --git a/cli/src/team/autoSetup.ts b/cli/src/team/autoSetup.ts
index 926ca9304..26e36bb9b 100644
--- a/cli/src/team/autoSetup.ts
+++ b/cli/src/team/autoSetup.ts
@@ -59,6 +59,9 @@ export const AUTO_SETUP_RETRY_MS = 24 * 60 * 60_000
export type AutoSetupState = 'unsupported' | 'signed-out' | 'dedicated' | 'running' | 'exists' | 'declined' | 'waiting' | 'not-shared'
| 'no-prompt' | 'wanted' | 'started'
+/** What [TeamAutoSetup.status] answers. `detail`: a failed setup's own sentence, at most 300 characters. */
+export interface TeamSetupStatus { state: 'none' | 'running' | 'exists' | 'declined' | 'failed'; detail?: string }
+
/** The moment the person is at this Mac: they joined a Swarm, added this Mac to one, or opened the app (`startup`); or
* they asked for it (`manual`: Desktop's explanation was accepted, or the machine row's Set up button). */
export type AutoSetupReason = 'join' | 'contribute' | 'startup' | 'manual'
@@ -127,6 +130,19 @@ export class TeamAutoSetup {
return 'started'
}
+ /**
+ * Why this Mac has no Harness Team account, for its own Desktop's machine row: the person cancelled (the prompt, "Not
+ * now" or `harness team remove`), setup failed and why, it is running now, or nothing was tried yet. Asks nothing.
+ */
+ async status(): Promise<TeamSetupStatus> {
+ const { deps } = this
+ if (this.running) return { state: 'running' }
+ if (deps.readConfig() || await deps.accountExists(TEAM_USER)) return { state: 'exists' }
+ const decision = deps.readDecision()
+ if (!decision) return { state: 'none' }
+ return { state: decision.state, ...(decision.state === 'failed' && decision.detail ? { detail: decision.detail } : {}) }
+ }
+
/** "Not now" in Desktop's explanation: not offered again on its own, as a cancelled prompt is not. */
decline(): void {
this.deps.writeDecision({ state: 'declined', at: this.deps.now() })
diff --git a/desktop/lib/notify/system_notifications.dart b/desktop/lib/notify/system_notifications.dart
index 349b78092..09422435d 100644
--- a/desktop/lib/notify/system_notifications.dart
+++ b/desktop/lib/notify/system_notifications.dart
@@ -560,9 +560,20 @@ class SystemNotifications {
/// in the Swift code; [postNotice] puts the device's key in the `agentId` slot.
static const deviceNoticeMachine = '@device';
- /// News about the ACCOUNT rather than an agent — a device joined it. The same switch and the same
- /// rules as [post]; a click on it opens that device ([devicePub]) when given, else nothing.
- void postNotice({required String id, required String title, required String body, String? devicePub}) {
+ /// What a Swarm tag's notice puts in the `machineId` slot; the `agentId` slot holds
+ /// `<swarm tab id>/<tag id>` ([mention]), which the click opens (swarm_screen.dart).
+ static const mentionNoticeMachine = '@mention';
+
+ /// News about the ACCOUNT rather than an agent — a device joined it, a person was tagged. The same
+ /// switch and the same rules as [post]; a click on it opens that device ([devicePub]) or that tag
+ /// in its Swarm ([mention]) when given, else nothing.
+ void postNotice({
+ required String id,
+ required String title,
+ required String body,
+ String? devicePub,
+ ({String tabId, String mentionId})? mention,
+ }) {
if (!store.value || !supported) return;
if (permission.value == NotificationPermission.unavailable) return;
_ordered(
@@ -572,8 +583,14 @@ class SystemNotifications {
id: id,
title: title,
body: body,
- machineId: devicePub == null ? '' : deviceNoticeMachine,
- agentId: devicePub ?? '',
+ machineId: mention != null
+ ? mentionNoticeMachine
+ : devicePub == null
+ ? ''
+ : deviceNoticeMachine,
+ agentId: mention != null
+ ? '${mention.tabId}/${mention.mentionId}'
+ : devicePub ?? '',
)
.then((answer) {
if (answer != NotificationPermission.unknown) {
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 30ca2114b..879796937 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -77,10 +77,14 @@ import '../state/harness_launch_integration.dart';
import '../super_tabs/launch.dart';
import '../super_tabs/buddy_chat.dart' show countText;
import '../super_tabs/buddy_chat_shortcut.dart';
+import '../super_tabs/join_machine.dart';
+import '../super_tabs/join_machine_note.dart';
import '../super_tabs/team_account_setup.dart';
import '../super_tabs/workspace.dart';
import '../super_tabs/quick_switcher.dart';
import '../super_tabs/actions.dart';
+import '../super_tabs/controller.dart' show SuperTabController;
+import '../super_tabs/notifications.dart' show SuperTabMentions;
import 'swarm_menu_bus.dart';
import '../state/device_form.dart';
import '../state/device_finder.dart';
@@ -297,6 +301,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
StreamSubscription<void>? _modelsRequests;
StreamSubscription<String>? _superTabClosures;
StreamSubscription<String>? _teamSetupAsks;
+ StreamSubscription<SwarmJoinedMachine>? _joinedMachines;
// The one Swarm notice: whether it exists (queued or shown), whether it
// is on screen, and the closed tab its Reopen restores.
int _superTabNoticeSerial = 0;
@@ -739,6 +744,17 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.systemNotifications.onTap = (machineId, agentId) async {
await revealWindow();
if (!mounted) return;
+ // A tag's notice carries its Swarm tab and tag: the click opens it as the menu bar's row
+ // does, once the tag is still the person's to read.
+ if (machineId == SystemNotifications.mentionNoticeMachine) {
+ final slash = agentId.indexOf('/');
+ if (slash <= 0) return;
+ await _openTagNotice(
+ agentId.substring(0, slash),
+ agentId.substring(slash + 1),
+ );
+ return;
+ }
// A device notice puts its marker where an agent's machine goes and the device's key where the
// agent goes: the click opens that device.
if (machineId == SystemNotifications.deviceNoticeMachine) {
@@ -849,6 +865,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
_teamSetupAsks = app.teamSetupAsks.listen((_) {
if (mounted) unawaited(showTeamAccountSetup(context, app, asked: true));
});
+ // This computer, added to a Swarm as its person joined it (super_tabs/join_machine.dart).
+ _joinedMachines = app.joinedMachines.listen((note) {
+ if (mounted) showJoinedMachineNote(context, app.superTabs.open, note);
+ });
if (!kUnderTest) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
@@ -1004,6 +1024,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_modelsRequests?.cancel();
_superTabClosures?.cancel();
_teamSetupAsks?.cancel();
+ _joinedMachines?.cancel();
_keymap.removeListener(_keymapChanged);
_defaultKeymap.dispose();
grid.AppTheme.palette.removeListener(_paletteChanged);
@@ -7207,6 +7228,38 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
+ /// A click on a tag's system notice: the Swarm it is in, open here or not
+ /// (not loaded yet, its tab closed), opens at the tag. The account must
+ /// still be in that Swarm, and the server must list the tag as the person's
+ /// to answer now, in a read that succeeded; otherwise nothing opens, and a
+ /// Swarm loaded only to check is let go again.
+ Future<void> _openTagNotice(String tabId, String mentionId) async {
+ final name = app.superTabName(tabId);
+ if (name == null) return;
+ final loadedHere = app.superTabs.peek(tabId) == null;
+ // Unless the person went to that Swarm meanwhile: its view holds it now.
+ void letGo() {
+ if (loadedHere && app.activeSwarm.superTabId != tabId) {
+ app.superTabs.release(tabId);
+ }
+ }
+
+ final SuperTabController controller;
+ try {
+ controller = await app.superTabs.open(tabId);
+ } catch (_) {
+ return;
+ }
+ // One read decides and supplies the tag the view opens at.
+ final waiting = await SuperTabMentions.of(controller).waitingNow(mentionId);
+ if (!mounted || !waiting || controller.accessRevoked) return letGo();
+ if (_newHarness?.requestDismiss() == false) return letGo();
+ _closeNewHarness(restoreFocus: false);
+ _closeSearch(restoreFocus: false);
+ app.openSuperTab(tabId, name);
+ controller.openNotice('mention', mentionId);
+ }
+
/// A row of the menu bar's Swarm section: its Swarm tab comes forward and
/// opens the tag or decision there; View all (`all`) opens the Swarm's
/// Notifications page. One no longer listed opens nothing.
diff --git a/desktop/lib/settings/sections/tab_invites_section.dart b/desktop/lib/settings/sections/tab_invites_section.dart
index 474740869..b1b58e1d8 100644
--- a/desktop/lib/settings/sections/tab_invites_section.dart
+++ b/desktop/lib/settings/sections/tab_invites_section.dart
@@ -3,6 +3,8 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../../agent_messages/shared_tab_dialogs.dart';
+import '../../super_tabs/join_machine.dart'
+ show SwarmInviteAccepts, swarmNewMemberRole;
import '../../agent_messages/shared_tab_placement.dart' show shortSharedText;
import '../../agent_messages/shared_tabs.dart';
import '../../agent_messages/update_harness.dart';
@@ -26,6 +28,7 @@ class TabInvitesSection extends StatefulWidget {
class _TabInvitesSectionState extends State<TabInvitesSection> {
List<Map<String, dynamic>> _superInvites = [], _superTabs = [];
String? _superError, _accepting;
+ final _accepts = SwarmInviteAccepts();
bool _loadingSuper = true;
Timer? _refreshTimer;
int _read = 0;
@@ -79,13 +82,20 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
setState(() => _accepting = invite['inviteId'] as String);
try {
final app = widget.notifier;
- final reply = await app.superTabs.map(
- 'POST',
- '/api/super-tabs/${invite['tabId']}/commands',
- body: {
- 'operationId': 'accept-${invite['inviteId']}',
- 'command': {'type': 'invite.accept', 'inviteId': invite['inviteId']},
- },
+ // This attempt's own operation, never one shared with other computers.
+ final reply = await _accepts.accept(
+ invite['inviteId'] as String,
+ (operationId) => app.superTabs.map(
+ 'POST',
+ '/api/super-tabs/${invite['tabId']}/commands',
+ body: {
+ 'operationId': operationId,
+ 'command': {
+ 'type': 'invite.accept',
+ 'inviteId': invite['inviteId'],
+ },
+ },
+ ),
);
final tabId = invite['tabId'] as String;
final controller = await app.superTabs.open(tabId);
@@ -96,6 +106,12 @@ class _TabInvitesSectionState extends State<TabInvitesSection> {
}
if (!mounted) return;
app.openSuperTab(tabId, invite['name'] as String);
+ // Accepted by the person at this computer: it joins the Swarm too, then
+ // the system asks once for the Harness Team account.
+ // Only when this accept made the membership: someone who already joined
+ // by link on another computer shares nothing more.
+ final role = swarmNewMemberRole(result);
+ if (role != null) unawaited(app.addMachineOnJoin(tabId, role: role));
await _refreshSuper();
if (mounted) await Navigator.of(context).maybePop();
} catch (failure) {
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index e6b1d0620..fd19c5845 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -99,6 +99,7 @@ import '../super_tabs/attachment_upload.dart';
import '../super_tabs/avatar_upload.dart';
import '../super_tabs/client.dart';
import '../super_tabs/controller.dart';
+import '../super_tabs/join_machine.dart';
import '../super_tabs/view_store.dart';
import '../super_tabs/notifications.dart' show superTabMentionNotice;
import '../measurement/setup_preference_store.dart';
@@ -1895,6 +1896,12 @@ class AppNotifier extends ChangeNotifier {
/// closure announces its history id so the screen can offer to reopen it.
Stream<String> get superTabClosures => _superTabClosures.stream;
+ /// The name of Swarm [tabId] if this account belongs to it, open here or
+ /// not; null for one it is not in.
+ String? superTabName(String tabId) =>
+ swarms.where((s) => s.superTabId == tabId).firstOrNull?.name ??
+ _superTabNames[tabId];
+
/// Swarms hidden on this computer that the account still belongs to,
/// by name. Saved with the hidden set, so a restart keeps them.
List<({String id, String name})> get closedSuperTabs {
@@ -2169,6 +2176,79 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Why this Mac has no Harness Team account, as its own daemon remembers
+ /// it (cli/src/team/autoSetup.ts `status`): `{state: declined}` after a
+ /// cancel, `{state: failed, detail}`, `running`, `exists` or `none`. Null
+ /// when it cannot say: not this Mac's to set up, or a daemon too old.
+ Future<({String state, String? detail})?> teamSetupStatus() async {
+ final here = _teamAccountHere();
+ if (here == null) return null;
+ try {
+ final answer = await superTabMachineRequest(here, {
+ 'action': 'teamSetupStatus',
+ });
+ final state = answer['state'];
+ if (state is! String) return null;
+ final detail = answer['detail'];
+ return (state: state, detail: detail is String ? detail : null);
+ } catch (_) {
+ return null;
+ }
+ }
+
+ final StreamController<SwarmJoinedMachine> _joinedMachines =
+ StreamController<SwarmJoinedMachine>.broadcast();
+
+ /// This computer, added to a Swarm as its person joined it
+ /// ([addMachineOnJoin]): the screen shows a note, with Pause and Remove.
+ Stream<SwarmJoinedMachine> get joinedMachines => _joinedMachines.stream;
+ final _joinAdding = <String>{};
+
+ /// A Swarm [tabId] just joined at this computer, as [role]: adds this
+ /// computer to it with Add machine's defaults (super_tabs/join_machine.dart),
+ /// then offers the Harness Team account, the one step macOS asks a password
+ /// for. A viewer, someone who was already a member, and a computer that
+ /// cannot make a Team account here are left as they are.
+ Future<void> addMachineOnJoin(
+ String tabId, {
+ required String role,
+ bool alreadyMember = false,
+ }) async {
+ if (alreadyMember || role != 'collaborator') return;
+ final here = _teamAccountHere();
+ final accountId = currentUser?.id;
+ if (here == null || accountId == null || !_joinAdding.add(tabId)) return;
+ bool current() =>
+ !_disposed &&
+ status == AppStatus.authenticated &&
+ currentUser?.id == accountId;
+ try {
+ final c = await superTabs.open(tabId);
+ if (!current()) return;
+ await c.refresh();
+ final note =
+ await SwarmJoinMachine(
+ machineRequest: superTabMachineRequest,
+ readResources: readMachineResources,
+ wake: wakeSuperTabHost,
+ ).add(
+ c,
+ machineId: here,
+ machineName: stateOf(here)?.machine.displayName ?? 'This computer',
+ current: current,
+ );
+ if (note == null || !current()) return;
+ _joinedMachines.add(note);
+ // Joined by the person at this computer: the system asks once for the
+ // Harness Team account (cli/src/team/autoSetup.ts).
+ if (note.added) await offerTeamAccount('join', tabId: tabId);
+ } catch (error) {
+ appLog.info('super-tabs', 'machine not added on join: $error');
+ } finally {
+ _joinAdding.remove(tabId);
+ }
+ }
+
Future<void> wakeSuperTabHost(String machineId) async {
await superTabMachineRequest(machineId, {'action': 'wake'});
// Share derives only the session views authorized by the tab. Its existing
@@ -21974,6 +22054,7 @@ class AppNotifier extends ChangeNotifier {
unawaited(_modelsRequests.close());
unawaited(_superTabClosures.close());
unawaited(_teamSetupAsks.close());
+ unawaited(_joinedMachines.close());
super.dispose();
}
}
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index c0c715689..a89ea12a0 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -101,7 +101,7 @@ class SuperTabAgentInfo {
final person = controller.snapshot?.people
.where((p) => p.id == personId)
.firstOrNull;
- return _known(person == null ? null : superTabPersonName(person.email));
+ return _known(person?.username);
}
String? get questionOwner {
diff --git a/desktop/lib/super_tabs/buddies.dart b/desktop/lib/super_tabs/buddies.dart
index 54f08a21d..773c31fff 100644
--- a/desktop/lib/super_tabs/buddies.dart
+++ b/desktop/lib/super_tabs/buddies.dart
@@ -45,15 +45,13 @@ List<SuperTabProject> buddyProjects(SuperTabController c) => [
if (c.buddy(project.id) == null) project,
];
-/// A person by the name the Swarm shows: their address before the @.
+/// A person by the name the Swarm shows: their username.
String buddyPersonName(SuperTabController c, String personId) {
- final email = c.snapshot?.people
- .where((p) => p.id == personId)
- .firstOrNull
- ?.email;
- return email == null || email.isEmpty
- ? 'its owner'
- : superTabPersonName(email);
+ return c.snapshot?.people
+ .where((p) => p.id == personId)
+ .firstOrNull
+ ?.username ??
+ 'its owner';
}
/// The machine [machineId]'s name as the dialog and the chat show it.
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 2d6262376..a3a0f96e1 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -53,7 +53,8 @@ class SuperTabClient {
final void Function(SuperTabController)? onSelection;
/// A Lead tagged this account in one of its Swarms while the app was open.
- final void Function(SuperTabMention)? onMention;
+ /// A new tag of the reader in Swarm `tabId`.
+ final void Function(String tabId, SuperTabMention mention)? onMention;
/// The waiting tags of a Swarm that is not open changed ([waitingTags]).
final void Function()? onTagCounts;
@@ -651,7 +652,9 @@ class SuperTabClient {
// What discovery already announced is not news when the Swarm opens.
SuperTabMentions.of(controller)
..seen(_tagsSeen.remove(id))
- ..onArrived = onMention;
+ ..onArrived = onMention == null
+ ? null
+ : (mention) => onMention!(id, mention);
if (onNotices case final changed?) {
SuperTabMentions.of(controller).addListener(changed);
SuperTabDecisions.of(controller).addListener(changed);
@@ -715,7 +718,7 @@ class SuperTabClient {
if (seen != null) {
for (final mention in waiting.reversed) {
if (!seen.contains(mention.id)) {
- onMention?.call(mention);
+ onMention?.call(id, mention);
told.add(mention.id);
}
}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index d6eaf6ce3..a0b042774 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -3023,11 +3023,14 @@ class SuperTabController extends ChangeNotifier {
_pending != null) {
return null;
}
+ // A tag the text still says: an agent's is a recipient, a person's a tag.
+ final said = mentions(selectedId).entries
+ .where((entry) => containsMention(text, entry.value))
+ .map((entry) => entry.key);
+ bool isPerson(String id) => snapshot?.people.any((p) => p.id == id) == true;
+ final tagged = said.where(isPerson).toList();
final addressed = recipients.isEmpty
- ? mentions(selectedId).entries
- .where((entry) => containsMention(text, entry.value))
- .map((entry) => entry.key)
- .toList()
+ ? said.where((id) => !isPerson(id)).toList()
: recipients;
if (addressed.any((id) => !selected!.agentIds.contains(id))) {
operationError = 'A mentioned agent is no longer in this conversation. Remove its mention or choose another agent.';
@@ -3045,6 +3048,7 @@ class SuperTabController extends ChangeNotifier {
'text': text,
'replyTo': replyTo,
'recipientIds': addressed,
+ if (tagged.isNotEmpty) 'mentions': tagged,
if (ids.isNotEmpty) 'attachmentIds': ids,
});
// On its way: the message shows in the chat, and the draft is free for
diff --git a/desktop/lib/super_tabs/identity.dart b/desktop/lib/super_tabs/identity.dart
index b4a059c5e..c8379c3e7 100644
--- a/desktop/lib/super_tabs/identity.dart
+++ b/desktop/lib/super_tabs/identity.dart
@@ -30,7 +30,7 @@ class SuperTabAvatar extends StatelessWidget {
this.size = 30,
this.now,
}) : identity = 'person:${person.id}',
- name = superTabPersonName(person.email),
+ name = person.username,
picture = person.avatar,
engine = null,
status = person.status,
diff --git a/desktop/lib/super_tabs/join_dialog.dart b/desktop/lib/super_tabs/join_dialog.dart
index 9d6c88489..f877d54f6 100644
--- a/desktop/lib/super_tabs/join_dialog.dart
+++ b/desktop/lib/super_tabs/join_dialog.dart
@@ -8,6 +8,7 @@ import '../widgets/desktop_chrome.dart';
import '../widgets/desktop_prompt_surface.dart';
import 'controller.dart';
import 'join_link.dart';
+import 'join_machine.dart' show swarmNewMemberRole;
/// The native URL channel queues links before authentication. This host only
/// presents them after sign-in and never joins on the person's behalf.
@@ -69,9 +70,13 @@ class _SwarmJoinHostState extends State<SwarmJoinHost> {
onJoined: (id, name) {
if (!current()) return;
app.openSuperTab(id, name);
- // Joined by the person at this Mac: macOS asks once for
- // the Harness Team account (cli/src/team/autoSetup.ts).
- unawaited(app.offerTeamAccount('join', tabId: id));
+ },
+ // Joined by the person at this computer: it is added to the
+ // Swarm, then the system asks once for the Harness Team
+ // account (super_tabs/join_machine.dart).
+ onNewMember: (id, role) {
+ if (!current()) return;
+ unawaited(app.addMachineOnJoin(id, role: role));
},
)
: AlertDialog(
@@ -111,11 +116,16 @@ class SwarmJoinDialog extends StatefulWidget {
required this.request,
required this.onJoined,
required this.isCurrent,
+ this.onNewMember,
});
final SwarmJoinLink link;
final String accountEmail;
final SuperTabRequest request;
final void Function(String id, String name) onJoined;
+
+ /// After a join that made this account a member, with the role it joined
+ /// as; never for someone who was one already.
+ final void Function(String id, String role)? onNewMember;
final bool Function() isCurrent;
@override
@@ -178,6 +188,7 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {
_error = null;
});
try {
+ String? newRole;
if (_preview!['alreadyMember'] != true) {
final result = await widget.request(
'POST',
@@ -188,9 +199,11 @@ class _SwarmJoinDialogState extends State<SwarmJoinDialog> {
if (result['id'] != widget.link.tabId) {
throw const FormatException('Invalid invitation');
}
+ newRole = swarmNewMemberRole(result);
}
if (!_current) return;
widget.onJoined(widget.link.tabId, _preview!['name'] as String);
+ if (newRole != null) widget.onNewMember?.call(widget.link.tabId, newRole);
if (mounted) Navigator.pop(context);
} catch (failure) {
if (_current) setState(() => _error = _errorMessage(failure));
diff --git a/desktop/lib/super_tabs/join_machine.dart b/desktop/lib/super_tabs/join_machine.dart
new file mode 100644
index 000000000..0df93a8dd
--- /dev/null
+++ b/desktop/lib/super_tabs/join_machine.dart
@@ -0,0 +1,203 @@
+import 'dart:async';
+
+import '../core/machine_resources.dart';
+import 'controller.dart';
+
+/// What one more agent needs to start, the CLI's own figure
+/// (`START_REQUIREMENTS.memoryBytes`, `cli/src/superTabs/capacity.ts`).
+const _agentMemoryBytes = 2 * 1024 * 1024 * 1024;
+
+/// Add machine's starting number of agents: half the machine's memory in
+/// agents, from 1 to 16. Null while its memory is unknown.
+int? superTabSuggestedAgentSlots(MachineResources? resources) {
+ final total = resources?.memoryTotalBytes;
+ if (total == null) return null;
+ return (total / (2 * _agentMemoryBytes)).floor().clamp(1, 16);
+}
+
+/// The role [answer] says this account just became a member as: the
+/// server's own answer to the join that asked, a link join (store.ts
+/// `joinSwarm`) or an invitation's accept (commands.ts `invite.accept`). Null
+/// when the person was a member already, whatever an earlier preview said (they
+/// may have joined on another device meanwhile), or when an older server does
+/// not say: this computer is added only to a membership this request made.
+String? swarmNewMemberRole(Map<String, dynamic> answer) =>
+ answer['alreadyMember'] == false && answer['role'] is String
+ ? answer['role'] as String
+ : null;
+
+/// Accepting a Swarm invitation from this computer. Each attempt has its own
+/// operation, kept only for that attempt's retries (a lost reply is asked
+/// again under it) and dropped once answered: the server replays an
+/// operation's answer to whoever sends it again, so one fixed operation for
+/// an invitation gave a stale accept on another computer the first one's
+/// answer, "not a member before", and shared that computer too (re-check of
+/// #2188).
+class SwarmInviteAccepts {
+ final _attempts = <String, String>{};
+
+ /// Sends [inviteId]'s accept through [send], with this attempt's operation.
+ Future<Map<String, dynamic>> accept(
+ String inviteId,
+ Future<Map<String, dynamic>> Function(String operationId) send,
+ ) async {
+ final operationId = _attempts[inviteId] ??= superTabOperationId();
+ final reply = await send(operationId);
+ _attempts.remove(inviteId);
+ return reply;
+ }
+}
+
+/// The engines a Swarm machine runs (backend `swarmEngine`).
+const _swarmEngines = {'claude', 'codex'};
+
+/// This computer, added to a Swarm by the join that just let its person in
+/// (Scholes, 2026-10-29): what [SwarmJoinMachine.add] did, for the note the
+/// person sees. [problem]: why it was not added, in a sentence for them.
+class SwarmJoinedMachine {
+ const SwarmJoinedMachine({
+ required this.tabId,
+ required this.swarmName,
+ required this.machineId,
+ required this.machineName,
+ this.problem,
+ });
+
+ final String tabId, swarmName, machineId, machineName;
+ final String? problem;
+ bool get added => problem == null;
+}
+
+/// Adds this computer to a Swarm its person just joined, with Add machine's
+/// defaults: the Claude Code and Codex it has, the folder its daemon sets up,
+/// and the number of agents its memory suggests. It is added as
+/// `teamAccountOnly`, so the server sends teammates' work to it only through
+/// its Harness Team account whose privacy check passed (backend
+/// superTabs/machines.ts `teamWorkRefusal`); until then it runs only its
+/// person's own projects.
+///
+/// Only a new collaborator's computer, in a Swarm that uses Harness Team
+/// accounts: a viewer, a computer already in the Swarm and a Swarm whose
+/// server does not try Team accounts yet are left as they are.
+class SwarmJoinMachine {
+ SwarmJoinMachine({
+ required this.machineRequest,
+ required this.readResources,
+ required this.wake,
+ this.pause = const Duration(seconds: 1),
+ this.deadline = const Duration(minutes: 5),
+ });
+
+ /// A `super_tabs` request to this computer's own daemon.
+ final Future<Map<String, dynamic>> Function(
+ String machineId,
+ Map<String, dynamic> payload,
+ )
+ machineRequest;
+ final Future<MachineResources?> Function(String machineId) readResources;
+
+ /// Tells the daemon it is in the Swarm now, so it starts hosting at once.
+ final Future<void> Function(String machineId) wake;
+
+ /// Between two reads of a folder setup still running, and how long the
+ /// whole setup may take, as Add machine waits.
+ final Duration pause, deadline;
+
+ /// Null when nothing was to be done, or the account changed or signed out
+ /// meanwhile ([current] false): nothing is added or said then.
+ Future<SwarmJoinedMachine?> add(
+ SuperTabController c, {
+ required String machineId,
+ required String machineName,
+ required bool Function() current,
+ }) async {
+ final snapshot = c.snapshot;
+ if (snapshot == null || !current()) return null;
+ if (!snapshot.teamAccounts || !c.canWrite) return null;
+ final me = snapshot.people.where((p) => p.id == c.accountId).firstOrNull;
+ if (me?.role != 'collaborator') return null;
+ if (snapshot.machines.any((m) => m['machineId'] == machineId)) return null;
+ SwarmJoinedMachine note([String? problem]) => SwarmJoinedMachine(
+ tabId: c.tabId,
+ swarmName: snapshot.name,
+ machineId: machineId,
+ machineName: machineName,
+ problem: problem,
+ );
+
+ final operationId = superTabOperationId();
+ final until = DateTime.now().add(deadline);
+ Map<String, dynamic> prepared;
+ while (true) {
+ try {
+ prepared = await machineRequest(machineId, {
+ 'action': 'prepareContribution',
+ 'tabId': c.tabId,
+ 'scope': 'swarm',
+ 'operationId': operationId,
+ });
+ } catch (_) {
+ if (!current()) return null;
+ return note(
+ 'Could not reach Harness on this computer. Add it from Machines.',
+ );
+ }
+ if (!current()) return null;
+ if (prepared['state'] == 'ready' && prepared['scope'] == 'swarm') break;
+ if (prepared['state'] != 'preparing') {
+ return note(
+ 'Update Harness on this computer, then add it from Machines.',
+ );
+ }
+ if (DateTime.now().isAfter(until)) {
+ return note(
+ 'Setting up this computer took too long. Add it from Machines.',
+ );
+ }
+ await Future<void>.delayed(pause);
+ }
+ final engines = [
+ for (final engine in prepared['engines'] as List? ?? const [])
+ if (_swarmEngines.contains(engine)) engine as String,
+ ];
+ if (engines.isEmpty) {
+ return note(
+ 'Install Claude Code or Codex on this computer, then add it from Machines.',
+ );
+ }
+ MachineResources? resources;
+ try {
+ resources = await readResources(machineId);
+ } catch (_) {
+ // Its offer below stands in.
+ }
+ final offered = prepared['maxAgents'];
+ final slots =
+ superTabSuggestedAgentSlots(resources) ??
+ (offered is num ? offered.toInt().clamp(1, 1024) : 4);
+ if (!current() || !c.canWrite) return null;
+ final result = await c.command({
+ 'type': 'machine.contribute',
+ 'machineId': machineId,
+ 'name': machineName,
+ 'cwd': prepared['cwd'],
+ 'scope': 'swarm',
+ 'engines': engines,
+ 'maxAgents': slots,
+ 'teamAccountOnly': true,
+ });
+ if (!current()) return null;
+ if (result == null) {
+ return note(
+ c.operationError ??
+ 'Could not add this computer. Add it from Machines.',
+ );
+ }
+ try {
+ await wake(machineId);
+ } catch (_) {
+ // Its daemon finds the Swarm on its next read anyway.
+ }
+ return note();
+ }
+}
diff --git a/desktop/lib/super_tabs/join_machine_note.dart b/desktop/lib/super_tabs/join_machine_note.dart
new file mode 100644
index 000000000..8046febd8
--- /dev/null
+++ b/desktop/lib/super_tabs/join_machine_note.dart
@@ -0,0 +1,119 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../core/runtime_platform.dart';
+import 'controller.dart';
+import 'join_machine.dart';
+
+/// The note after joining a Swarm (Scholes, 2026-10-29): this computer was
+/// added, teammates' agents run here only in Harness Team, never as the
+/// person, and Pause or Remove undo it at once. When it could not be added,
+/// why, and where to add it.
+///
+/// [open]: the Swarm's controller ([SuperTabs.open]), which Pause and Remove
+/// command.
+void showJoinedMachineNote(
+ BuildContext context,
+ Future<SuperTabController> Function(String tabId) open,
+ SwarmJoinedMachine note, {
+ String? operatingSystem,
+}) {
+ final messenger = ScaffoldMessenger.maybeOf(context);
+ if (messenger == null) return;
+ final here = (operatingSystem ?? RuntimePlatform.operatingSystem) == 'macos'
+ ? 'This Mac'
+ : 'This computer';
+ final text = note.added
+ ? '$here was added to ${note.swarmName}. Teammates\' agents run here '
+ 'only in Harness Team, never as you.'
+ : '$here was not added to ${note.swarmName}. ${note.problem}';
+ messenger.showSnackBar(
+ SnackBar(
+ key: const Key('swarm-joined-machine-note'),
+ duration: const Duration(seconds: 12),
+ showCloseIcon: true,
+ content: Row(
+ children: [
+ Expanded(child: Text(text)),
+ if (note.added) ...[
+ const SizedBox(width: 12),
+ _NoteAction(
+ key: const Key('swarm-joined-machine-pause'),
+ label: 'Pause',
+ run: () => _act(open, note, {
+ 'type': 'machine.pause',
+ 'machineId': note.machineId,
+ 'paused': true,
+ }),
+ messenger: messenger,
+ ),
+ _NoteAction(
+ key: const Key('swarm-joined-machine-remove'),
+ label: 'Remove',
+ run: () => _act(open, note, {
+ 'type': 'machine.remove',
+ 'machineId': note.machineId,
+ }),
+ messenger: messenger,
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+}
+
+/// Null when it was done; otherwise the Swarm's own sentence.
+Future<String?> _act(
+ Future<SuperTabController> Function(String tabId) open,
+ SwarmJoinedMachine note,
+ Map<String, dynamic> command,
+) async {
+ try {
+ final c = await open(note.tabId);
+ final result = await c.command(command);
+ return result == null
+ ? c.operationError ?? 'Could not do that. Try again from Machines.'
+ : null;
+ } catch (_) {
+ return 'Could not do that. Try again from Machines.';
+ }
+}
+
+class _NoteAction extends StatefulWidget {
+ const _NoteAction({
+ super.key,
+ required this.label,
+ required this.run,
+ required this.messenger,
+ });
+
+ final String label;
+ final Future<String?> Function() run;
+ final ScaffoldMessengerState messenger;
+
+ @override
+ State<_NoteAction> createState() => _NoteActionState();
+}
+
+class _NoteActionState extends State<_NoteAction> {
+ bool _busy = false;
+
+ Future<void> _press() async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ final failure = await widget.run();
+ if (!widget.messenger.mounted) return;
+ widget.messenger.hideCurrentSnackBar();
+ if (failure != null) {
+ widget.messenger.showSnackBar(SnackBar(content: Text(failure)));
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) => TextButton(
+ onPressed: _busy ? null : () => unawaited(_press()),
+ child: Text(widget.label),
+ );
+}
diff --git a/desktop/lib/super_tabs/jump_to_latest.dart b/desktop/lib/super_tabs/jump_to_latest.dart
new file mode 100644
index 000000000..26d21bbd7
--- /dev/null
+++ b/desktop/lib/super_tabs/jump_to_latest.dart
@@ -0,0 +1,42 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+
+/// Shown at the foot of a message list while it is scrolled away from its
+/// newest message (Scholes, 2026-10-29): "Jump to latest", or the count of
+/// what arrived meanwhile ([count] of them, a floor when [more]). Takes
+/// the reader back to the end.
+class SuperTabJumpToLatest extends StatelessWidget {
+ const SuperTabJumpToLatest({
+ super.key,
+ required this.onPressed,
+ this.count = 0,
+ this.more = false,
+ this.noun = 'message',
+ this.plural = 'messages',
+ });
+
+ final VoidCallback onPressed;
+ final int count;
+
+ /// More came than were read, so [count] is a floor.
+ final bool more;
+ final String noun, plural;
+
+ /// The words on the control: the count wins over the plain jump.
+ static String label(int count, bool more, String noun, String plural) =>
+ count <= 0
+ ? 'Jump to latest'
+ : more
+ ? '$count+ new $plural'
+ : '$count new ${count == 1 ? noun : plural}';
+
+ @override
+ Widget build(BuildContext context) => FilledButton.icon(
+ key: ValueKey(count > 0 ? 'super-new-messages' : 'super-jump-latest'),
+ onPressed: onPressed,
+ icon: const Icon(AppIcons.chevronDown, size: grid.AppDesktop.iconSize),
+ label: Text(label(count, more, noun, plural)),
+ );
+}
diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dart
index d2dd3cbaf..b7e4fb58d 100644
--- a/desktop/lib/super_tabs/leaderboard/person_row.dart
+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart
@@ -27,10 +27,10 @@ TextStyle leaderboardPointsStyle() => grid.AppType.label(
fontFeatures: grid.AppFont.tabularFigures,
);
-/// A person as the leaderboard names them: the board's display name, else the
-/// email's first part, as before the board had names.
+/// A person as the leaderboard names them: their username, as everywhere in
+/// the Swarm (the board's account display name was a long one).
String leaderboardName(SuperTabPerson person, SuperTabPersonScore? score) =>
- score?.displayName ?? superTabPersonName(person.email);
+ person.username;
/// 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.
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 18a8ef237..d940213d5 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -34,6 +34,7 @@ import 'machine_details.dart';
import 'machine_icon.dart';
import 'machine_status.dart';
import 'model.dart';
+import 'join_machine.dart' show superTabSuggestedAgentSlots;
import 'team_account_setup.dart';
import 'section_heading.dart';
@@ -44,10 +45,9 @@ const _agentSlotsMin = 1;
const _agentSlotsMax = 1024;
/// Every machine may offer this many, whatever its RAM, and the suggestion
-/// never starts above [_suggestedSlotsMax]: the CLI's own figures
+/// never starts above 16 (superTabSuggestedAgentSlots): the CLI's own figures
/// (`prepareContribution`, `cli/src/superTabs/contribution.ts`).
const _agentSlotsFloor = 4;
-const _suggestedSlotsMax = 16;
/// What one more agent needs to start, the CLI's own figure
/// (`START_REQUIREMENTS.memoryBytes`, `cli/src/superTabs/capacity.ts`).
@@ -69,14 +69,8 @@ int? _maxAgentSlots(MachineResources? resources) {
);
}
-int? _suggestedAgentSlots(MachineResources? resources) {
- final total = resources?.memoryTotalBytes;
- if (total == null) return null;
- return (total / (2 * _agentMemoryBytes)).floor().clamp(
- _agentSlotsMin,
- _suggestedSlotsMax,
- );
-}
+int? _suggestedAgentSlots(MachineResources? resources) =>
+ superTabSuggestedAgentSlots(resources);
class SuperTabMachines extends StatefulWidget {
const SuperTabMachines({
@@ -1192,6 +1186,12 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
Timer? _timer;
bool _reading = false;
int _revision = 0;
+
+ /// What this Mac's daemon remembers of its Harness Team account setup
+ /// ([AppNotifier.teamSetupStatus]), for its own row's line; null until read
+ /// or when it cannot say.
+ ({String state, String? detail})? _teamSetup;
+ bool _teamSetupReading = false;
SuperTabController get c => widget.controller;
Set<String> get _ids => {
for (final a in c.snapshot?.agents ?? const <SuperTabAgent>[]) a.machineId,
@@ -1209,6 +1209,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
if (!kUnderTest) {
_tick = Timer.periodic(const Duration(seconds: 1), (_) => _changed());
}
+ unawaited(_readTeamSetup());
if ((!kUnderTest || widget.readLocal != null) && widget.app != null) {
_updateUsage();
widget.app!.foreground.addListener(_foreground);
@@ -1220,6 +1221,32 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
if (mounted) setState(() {});
}
+ /// Reads why this Mac has no Harness Team account, only while its person's
+ /// own row offers Set up: asked of this Mac's daemon, never of another's.
+ Future<void> _readTeamSetup() async {
+ final app = widget.app;
+ if (app == null || _teamSetupReading || !app.canSetUpTeamAccount) return;
+ final own = c.snapshot?.machines.any(
+ (m) =>
+ m['contributorId'] == c.accountId &&
+ app.stateOf(m['machineId'] as String)?.isLocalMachine == true &&
+ (m['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED',
+ );
+ if (own != true) {
+ _teamSetup = null;
+ return;
+ }
+ _teamSetupReading = true;
+ try {
+ final read = await app.teamSetupStatus();
+ if (!mounted) return;
+ _teamSetup = read;
+ _changed();
+ } finally {
+ _teamSetupReading = false;
+ }
+ }
+
void _updateUsage() {
if (kUnderTest || widget.app == null) return;
if (!widget.app!.foreground.value) {
@@ -1275,6 +1302,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
_samples.removeWhere((id, _) => !_ids.contains(id));
_awaiting.removeWhere((id) => !_samples.containsKey(id));
+ await _readTeamSetup();
} finally {
_reading = false;
if (mounted && widget.app?.foreground.value == true) {
@@ -1453,7 +1481,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
- ? "${superTabPersonName(person.email)}'s computer"
+ ? "${person.username}'s computer"
: 'Unavailable machine');
final configured = (reading?['engines'] as List?)
?.whereType<String>()
@@ -1598,21 +1626,26 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
}
}
}
- final problem = _teammatesLine(shared, team, contributor);
+ final line = _teammatesLine(shared, team, contributor);
+ final setUpTeam =
+ line != null &&
+ team == null &&
+ (shared?['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED' &&
+ contributor == c.accountId &&
+ app != null &&
+ app.canSetUpTeamAccount &&
+ app.stateOf(id)?.isLocalMachine == true;
+ // Its own person reads why: they cancelled, or setup failed and why.
+ final problem = setUpTeam
+ ? superTabTeamSetupLine(_teamSetup) ?? line
+ : line;
return _MachineView(
apiModels: apiModels,
localModels: localModels,
id: id,
name: name,
problem: problem,
- setUpTeam:
- problem != null &&
- team == null &&
- (shared?['teamWork'] as Map?)?['code'] == 'TEAM_ACCOUNT_REQUIRED' &&
- contributor == c.accountId &&
- app != null &&
- app.canSetUpTeamAccount &&
- app.stateOf(id)?.isLocalMachine == true,
+ setUpTeam: setUpTeam,
owner: person,
contributor: contributor,
shared: shared,
@@ -1632,7 +1665,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 ${superTabPersonName(person.email)}',
+ if (person != null) 'Owned by ${person.username}',
if (paused) 'New work paused',
if (!dim && value?.cpuPercent != null)
'CPU ${available(value!.cpuPercent!)} free',
@@ -1949,7 +1982,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
],
body: SuperTabMachineDetails(
name: name,
- owner: person?.email,
+ owner: person?.username,
status: details,
// Details follow the same freshness rule as the row and its disclosure.
resources: dim ? null : value,
@@ -2043,7 +2076,10 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
child: _MachineLine(
view: view,
onSetUpTeam: view.setUpTeam
- ? () => showTeamAccountSetup(context, widget.app!)
+ ? () async {
+ await showTeamAccountSetup(context, widget.app!);
+ await _readTeamSetup();
+ }
: null,
),
),
@@ -2594,6 +2630,21 @@ String? superTabTeammatesPaused(Object? code) {
return why == null ? null : "Teammates' agents paused: $why";
}
+/// This Mac's own row, for its person, when its daemon remembers why it has no Harness Team account
+/// (cli/src/team/autoSetup.ts `status`); null when it does not, and the Swarm's own line stands.
+String? superTabTeamSetupLine(({String state, String? detail})? setup) {
+ final detail = setup?.detail?.trim().replaceFirst(RegExp(r'[.]+$'), '');
+ final why = switch (setup?.state) {
+ 'declined' => 'setup was cancelled',
+ 'failed' when detail != null && detail.isNotEmpty =>
+ 'setup failed: $detail',
+ 'failed' => 'setup failed',
+ 'running' => 'setting up',
+ _ => null,
+ };
+ return why == null ? null : "Teammates' agents paused: $why";
+}
+
/// One engine's allowance on a machine: its mark and remaining share on the row, its windows on hover.
class _Allowance {
const _Allowance({
@@ -2727,7 +2778,7 @@ class _MachineLine extends StatelessWidget {
Padding(
padding: const EdgeInsets.only(left: 6),
child: Tooltip(
- message: 'Owned by ${superTabPersonName(owner.email)}',
+ message: 'Owned by ${owner.username}',
child: SuperTabAvatar.person(owner, size: 20),
),
),
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index da6da3da5..b91c3baaa 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -34,8 +34,28 @@ class SuperTabPerson {
role = _text(row, 'role'),
generation = row['generation'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
- status = SuperTabPersonStatus.fromJson(row['status']);
+ status = SuperTabPersonStatus.fromJson(row['status']),
+ chosenUsername = row['username'] as String?,
+ username =
+ row['username'] as String? ??
+ superTabDefaultUsername(_text(row, 'email'));
+ SuperTabPerson._named(SuperTabPerson person, this.username)
+ : id = person.id,
+ email = person.email,
+ role = person.role,
+ generation = person.generation,
+ avatar = person.avatar,
+ status = person.status,
+ chosenUsername = person.chosenUsername;
final String id, email, role;
+
+ /// How the Swarm shows and tags them, as the server sends it, worked out in
+ /// its join order. From an older server, their default
+ /// ([superTabUsernames]). Their email is never shown in its place.
+ final String username;
+
+ /// The name the server sent; null from a server without usernames.
+ final String? chosenUsername;
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
@@ -49,6 +69,44 @@ class SuperTabPerson {
bool get canWrite => role == 'owner' || role == 'collaborator';
}
+/// The name an email's prefix makes: lowercased, only the characters a
+/// username takes, never too short. Unnumbered; [superTabUsernames] numbers it.
+String superTabDefaultUsername(String email) {
+ var prefix = email
+ .split('@')
+ .first
+ .toLowerCase()
+ .replaceAll(RegExp(r'[^a-z0-9._-]'), '')
+ .replaceFirst(RegExp(r'^[._-]+'), '');
+ if (prefix.length > 30) prefix = prefix.substring(0, 30);
+ if (prefix.isEmpty) return 'user';
+ return prefix.length < 2 ? '${prefix}1' : prefix;
+}
+
+/// [people], each with their username: the one the server sent, else (an older
+/// server, which sends none) their email prefix numbered (`ken2`) after the
+/// people before them. The server works out names in its own join order and
+/// sends them (backend/src/superTabs/usernames.ts), since members can arrive
+/// in any order.
+List<SuperTabPerson> superTabUsernames(List<SuperTabPerson> people) {
+ final taken = {for (final p in people) ?p.chosenUsername};
+ return [
+ for (final person in people)
+ if (person.chosenUsername != null)
+ person
+ else
+ SuperTabPerson._named(person, () {
+ final root = superTabDefaultUsername(person.email);
+ var name = root;
+ for (var n = 2; taken.contains(name); n++) {
+ name = '$root$n';
+ }
+ taken.add(name);
+ return name;
+ }()),
+ ];
+}
+
class SuperTabAgent {
SuperTabAgent.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
@@ -278,7 +336,7 @@ class SuperTabSnapshot {
project = row['project'] == null
? null
: Map.unmodifiable(superTabMap(row['project'])),
- people = _list(row['people'], SuperTabPerson.fromJson),
+ people = superTabUsernames(_list(row['people'], SuperTabPerson.fromJson)),
agents = _list(row['agents'], SuperTabAgent.fromJson),
machines = _list(
row['machines'] ?? const [],
@@ -303,6 +361,7 @@ class SuperTabSnapshot {
harness: effort,
}),
localModels = SuperTabLocalModels.read(row['localModels']),
+ teamAccounts = row['teamAccounts'] != false,
mentionsWaiting = (row['mentionsWaiting'] as num?)?.toInt() ?? 0,
mentionsDigest = row['mentionsDigest'] as String?,
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
@@ -372,6 +431,9 @@ class SuperTabSnapshot {
/// The reader's tags still waiting for them, Swarm-wide; 0 from a backend
/// before tags (spec 2026-10-24-lead-mentions.md).
+ /// Whether this Swarm's server uses Harness Team accounts: false only where
+ /// it says it does not try them yet (backend read/contract.ts `teamAccounts`).
+ final bool teamAccounts;
final int mentionsWaiting;
/// Which tags wait, as a digest that moves when they change though the
@@ -509,7 +571,8 @@ 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)
- : superTabPersonName(message.authorName);
+ : people.where((p) => p.id == message.authorId).firstOrNull?.username ??
+ superTabPersonName(message.authorName);
}
/// The Swarm's Local models add-on (docs/plans/2026-10-23-swarm-local-models.md): its grid, whether it is on, and what the
diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dart
index 11773067b..241d81c79 100644
--- a/desktop/lib/super_tabs/notifications.dart
+++ b/desktop/lib/super_tabs/notifications.dart
@@ -47,17 +47,19 @@ bool get superTabNoticesInMenuBar =>
/// What tells the person about a new tag outside the window: the operating
/// system, on Desktop only. The web shows only the badge and the list (spec
/// decision 6). The Settings switch for system notifications still applies.
-void Function(SuperTabMention)? superTabMentionNotice(
+/// A click on it opens the tag in its Swarm [tabId], at its message.
+void Function(String tabId, SuperTabMention mention)? superTabMentionNotice(
SystemNotifications system, {
bool web = kIsWeb,
}) => web
? null
- : (mention) => system.postNotice(
+ : (tabId, mention) => system.postNotice(
id: 'harness-mention:${mention.id}',
title: '${mention.leadName} tagged you',
body:
'${mention.projectName} · ${mention.conversationTitle}: '
'${mention.text}',
+ mention: (tabId: tabId, mentionId: mention.id),
);
/// The reader's tags in one Swarm: Waiting and Earlier, read from the backend
@@ -90,6 +92,9 @@ class SuperTabMentions extends ChangeNotifier {
Future<void>? _loading;
// Something changed while a read was under way: read once more after it.
bool _dirty = false;
+ // Reads in the order they were asked, and the latest one shown: an older
+ // answer arriving late never replaces a newer one (review of #2088).
+ int _asked = 0, _shown = 0;
/// Starts from tags already announced elsewhere, so they are not news here.
void seen(Set<String>? ids) {
@@ -155,6 +160,33 @@ class SuperTabMentions extends ChangeNotifier {
}().whenComplete(() => _loading = null);
}
+ /// Whether the server lists [mentionId] among the reader's waiting tags
+ /// now. A read that fails or is refused answers false: what was read before
+ /// never stands in for it. A yes shows that same read as [waiting], so what
+ /// opens the tag reads it from the answer that confirmed it, with no second
+ /// read to decide otherwise.
+ Future<bool> waitingNow(String mentionId) async {
+ final epoch = _epoch, asked = ++_asked;
+ final List<SuperTabMention> fresh;
+ try {
+ fresh = await _list('waiting');
+ } catch (_) {
+ return false;
+ }
+ // Who may read what changed while it was on its way: it says nothing now.
+ // A Swarm just loaded learns its first epoch meanwhile; that is no change.
+ final moved = epoch != null && epoch != _epoch;
+ if (moved || !fresh.any((m) => m.id == mentionId)) return false;
+ // A read asked after this one already shows what is newer.
+ if (asked < _shown) return true;
+ _shown = asked;
+ if (!_sameMentions(waiting, fresh)) {
+ waiting = fresh;
+ notifyListeners();
+ }
+ return true;
+ }
+
Future<List<SuperTabMention>> _list(String state) async {
final Map<String, dynamic> answer;
try {
@@ -171,7 +203,7 @@ class SuperTabMentions extends ChangeNotifier {
}
Future<void> _read() async {
- final epoch = _epoch;
+ final epoch = _epoch, asked = ++_asked;
try {
final [nextWaiting, nextEarlier] = await Future.wait([
_list('waiting'),
@@ -180,6 +212,13 @@ class SuperTabMentions extends ChangeNotifier {
// Read before who may read what changed: the read asked again since
// replaces it.
if (epoch != _epoch) return;
+ // Asked before a read already shown: older news. Read once more, so
+ // both lists and what arrived come from one answer after it.
+ if (asked < _shown) {
+ _dirty = true;
+ return;
+ }
+ _shown = asked;
final same =
error == null &&
_sameMentions(waiting, nextWaiting) &&
@@ -197,7 +236,7 @@ class SuperTabMentions extends ChangeNotifier {
// The same lists again: nothing to show, so nobody is told.
if (same) return;
} catch (_) {
- if (epoch != _epoch) return;
+ if (epoch != _epoch || asked < _shown) return;
error = 'Could not load notifications. Try again.';
}
notifyListeners();
@@ -303,6 +342,22 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
final place = hidden == null || !c.hiddenByBuddies(hidden)
? mention.conversationTitle
: '#${c.snapshot?.projects.where((p) => p.id == mention.projectId).firstOrNull?.name ?? mention.projectName}';
+ // A person who tagged the reader is named as they are now.
+ final person = c.snapshot?.people
+ .where((p) => p.id == mention.leadId)
+ .firstOrNull;
+ final author = person?.username ?? mention.leadName;
+ // Who tagged, a person or a Lead: one face, in one place.
+ final Widget? face = person != null
+ ? SuperTabAvatar.person(person, size: 24)
+ : switch (c.snapshot?.agent(mention.leadId ?? '')) {
+ final lead? => SuperTabAvatar.agent(
+ lead,
+ name: mention.leadName,
+ size: 24,
+ ),
+ null => null,
+ };
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 1),
child: Material(
@@ -319,17 +374,10 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- if (widget.mentions.controller.snapshot?.agent(
- mention.leadId ?? '',
- )
- case final lead?)
+ if (face != null)
Padding(
padding: const EdgeInsets.only(right: 10, top: 2),
- child: SuperTabAvatar.agent(
- lead,
- name: mention.leadName,
- size: 24,
- ),
+ child: face,
),
Expanded(
child: Column(
@@ -339,7 +387,7 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
children: [
Flexible(
child: Text(
- mention.leadName,
+ author,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: DesktopChrome.control(medium: waiting),
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index 23dbff7a8..a70932576 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -316,6 +316,8 @@ class SuperTabParts {
if (_derived['decisionsDigest'] case final String digest) {
state['decisionsDigest'] = digest;
}
+ // Sent only where the server does not try Harness Team accounts yet.
+ if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;
if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);
return state;
}
diff --git a/desktop/lib/super_tabs/profile_actions.dart b/desktop/lib/super_tabs/profile_actions.dart
index aabf73248..30eae066e 100644
--- a/desktop/lib/super_tabs/profile_actions.dart
+++ b/desktop/lib/super_tabs/profile_actions.dart
@@ -20,6 +20,14 @@ extension SuperTabProfileActions on SuperTabController {
},
});
+ /// The reader's own username, trimmed (the server lowercases it), or back
+ /// to their default when null. A taken name comes back in words. A viewer
+ /// may change theirs too, though nothing else.
+ Future<String?> setUsername(String? username) => _profile({
+ 'type': 'member.username',
+ 'username': username?.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].
@@ -70,14 +78,23 @@ extension SuperTabProfileActions on SuperTabController {
return failure;
}
- Future<String?> _profile(Map<String, dynamic> command) async {
- final failure = await _send(command);
+ Future<String?> _profile(
+ Map<String, dynamic> command, {
+ bool viewer = false,
+ }) async {
+ final failure = await _send(command, viewer: viewer);
if (failure == null) await refresh();
return failure;
}
- Future<String?> _send(Map<String, dynamic> command) async {
- if (!canWrite) return _readOnly;
+ Future<String?> _send(
+ Map<String, dynamic> command, {
+ bool viewer = false,
+ }) async {
+ final member =
+ !accessRevoked &&
+ snapshot?.people.any((p) => p.id == accountId) == true;
+ if (!(viewer ? member : canWrite)) return _readOnly;
try {
await request(
'POST',
diff --git a/desktop/lib/super_tabs/profile_sheet.dart b/desktop/lib/super_tabs/profile_sheet.dart
index bff64c8e2..8d550758d 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 'username_editor.dart';
/// Picks one picture from this computer, or null when the person cancels.
Future<Uint8List?> pickSuperTabPicture() async {
@@ -25,7 +26,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 status.
+/// Lead: a picture to pick or upload and, for the reader, a username and a
+/// status.
Future<void> showSuperTabProfile(
BuildContext context,
SuperTabController controller, {
@@ -73,6 +75,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 {
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await c.setUsername(username);
+ if (mounted) setState(() => _busy = false);
+ return error;
+ }
+
Future<void> _upload() async {
final picked = await widget.pickPicture();
if (picked == null) return;
@@ -110,6 +123,14 @@ class _ProfileSheetState extends State<_ProfileSheet> {
children: [
?avatar,
const SizedBox(height: 16),
+ if (agent == null && person != null) ...[
+ SuperTabUsernameEditor(
+ username: person.username,
+ busy: _busy,
+ onSave: _saveUsername,
+ ),
+ const SizedBox(height: 16),
+ ],
Text('Picture', style: DesktopChrome.control(medium: true)),
const SizedBox(height: 8),
Wrap(
diff --git a/desktop/lib/super_tabs/ship_row.dart b/desktop/lib/super_tabs/ship_row.dart
index 3da4dc50f..2ca4ea8bf 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),
- superTabPersonName(requester.email),
+ requester.username,
),
]),
agents('Built by', _ids('builderIds')),
diff --git a/desktop/lib/super_tabs/terminal_unavailable.dart b/desktop/lib/super_tabs/terminal_unavailable.dart
index 5cbc6cada..c87a78b99 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?.email ??
+ snapshot.people.where((p) => p.id == ownerId).firstOrNull?.username ??
'its owner';
final row = snapshot.machines
.where((m) => m['machineId'] == agent.machineId)
diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dart
index 3be84e6dd..bebf7bd06 100644
--- a/desktop/lib/super_tabs/thread_panel.dart
+++ b/desktop/lib/super_tabs/thread_panel.dart
@@ -8,6 +8,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../shared/widgets/app_icon_button.dart';
import '../widgets/desktop_chrome.dart';
import 'controller.dart';
+import 'jump_to_latest.dart';
import 'model.dart';
/// One thread beside the chat (Dee, 2026-10-29): its root, a "N replies"
@@ -39,7 +40,16 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
text: c.threadDraft(widget.root),
);
final _focus = FocusNode();
+ final _scroll = ScrollController();
bool _alsoSend = false;
+ // Whether the list is scrolled away from its newest reply, the replies
+ // there were when the thread opened or was last read to its end (set once
+ // the thread's replies are known), and the latest replies and rows (replies
+ // and those on their way): what came since is the control's count.
+ bool _away = false, _atEnd = false, _baselined = false;
+ int _repliesAtEnd = 0, _replies = 0, _rows = 0, _rowsMeasured = 0;
+ // Each jump to the end supersedes the one before it.
+ int _jumpRequest = 0;
SuperTabController get c => widget.controller;
@@ -47,12 +57,21 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
void initState() {
super.initState();
_focus.requestFocus();
+ _scroll.addListener(_measureAfterFrame);
}
@override
void didUpdateWidget(SuperTabThreadPanel old) {
super.didUpdateWidget(old);
if (old.root != widget.root) {
+ // Another thread starts from its top, with nothing counted.
+ _away = false;
+ _atEnd = false;
+ _baselined = false;
+ _repliesAtEnd = 0;
+ _rowsMeasured = 0;
+ _jumpRequest++;
+ if (_scroll.hasClients) _scroll.jumpTo(0);
// Each thread keeps its own draft.
_composer.text = c.threadDraft(widget.root);
_alsoSend = false;
@@ -61,11 +80,69 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
@override
void dispose() {
+ _jumpRequest++;
+ _scroll.dispose();
_composer.dispose();
_focus.dispose();
super.dispose();
}
+ void _measureAfterFrame() {
+ WidgetsBinding.instance.addPostFrameCallback((_) => _measure());
+ }
+
+ /// A thread read to its end stays there as replies arrive; one read back
+ /// shows Jump to latest, with the count of replies that came meanwhile.
+ void _measure() {
+ if (!mounted || !_scroll.hasClients) return;
+ final position = _scroll.position;
+ if (_rows > _rowsMeasured && _atEnd && position.extentAfter >= 40) {
+ _rowsMeasured = _rows;
+ position.jumpTo(position.maxScrollExtent);
+ }
+ _rowsMeasured = _rows;
+ final away = position.extentAfter >= 40;
+ final atEnd = !away;
+ // What the thread held when it opened is not new; nor is what the reader
+ // has read to its end.
+ final repliesAtEnd = atEnd ? _replies : _repliesAtEnd;
+ if (away == _away && atEnd == _atEnd && repliesAtEnd == _repliesAtEnd) {
+ return;
+ }
+ setState(() {
+ _away = away;
+ _atEnd = atEnd;
+ _repliesAtEnd = repliesAtEnd;
+ });
+ }
+
+ /// Scrolls to the newest reply. A lazy list refines its extent as rows near
+ /// the end are laid out, so one jump can stop above the last reply: jump
+ /// again, a bounded number of times, until nothing is left below.
+ void _jumpToLatest() {
+ final request = ++_jumpRequest;
+ void advance(int attempt) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || request != _jumpRequest || !_scroll.hasClients) return;
+ _scroll.jumpTo(_scroll.position.maxScrollExtent);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || request != _jumpRequest || !_scroll.hasClients) {
+ return;
+ }
+ if (_scroll.position.extentAfter > 1 && attempt < 12) {
+ advance(attempt + 1);
+ } else {
+ _measure();
+ }
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ });
+ WidgetsBinding.instance.scheduleFrame();
+ }
+
+ advance(0);
+ }
+
/// Where "Also send" also puts the reply, as the chat is named.
String get _alsoSendLabel {
final group = c.selected;
@@ -103,6 +180,14 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
.toList();
final count =
c.thread(c.selectedId, widget.root)?.replies ?? replies.length;
+ _replies = count > replies.length ? count : replies.length;
+ _rows = replies.length + pending.length;
+ if (!_baselined &&
+ (c.thread(c.selectedId, widget.root) != null || replies.isNotEmpty)) {
+ _baselined = true;
+ _repliesAtEnd = _replies;
+ }
+ _measureAfterFrame();
return Material(
key: const ValueKey('super-thread-panel'),
color: DesktopChrome.surface,
@@ -139,64 +224,84 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
),
Divider(height: 1, thickness: 1, color: DesktopChrome.rim),
Expanded(
- child: ListView(
- padding: const EdgeInsets.symmetric(
- vertical: grid.AppDesktop.controlGap,
- ),
+ child: Stack(
children: [
- if (root != null) widget.row(root, false),
- if (count > 0)
- Padding(
- key: const ValueKey('super-thread-divider'),
- padding: const EdgeInsets.symmetric(
- horizontal: grid.AppDesktop.groupGap,
- vertical: grid.AppDesktop.controlGap,
- ),
- child: Row(
- children: [
- Text(
- count == 1 ? '1 reply' : '$count replies',
- style: DesktopChrome.metadata(),
+ ListView(
+ controller: _scroll,
+ padding: const EdgeInsets.symmetric(
+ vertical: grid.AppDesktop.controlGap,
+ ),
+ children: [
+ if (root != null) widget.row(root, false),
+ if (count > 0)
+ Padding(
+ key: const ValueKey('super-thread-divider'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.groupGap,
+ vertical: grid.AppDesktop.controlGap,
),
- const SizedBox(width: grid.AppDesktop.controlGap),
- Expanded(
- child: Divider(
- height: 1,
- thickness: 1,
- color: DesktopChrome.rim,
- ),
+ child: Row(
+ children: [
+ Text(
+ count == 1 ? '1 reply' : '$count replies',
+ style: DesktopChrome.metadata(),
+ ),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ Expanded(
+ child: Divider(
+ height: 1,
+ thickness: 1,
+ color: DesktopChrome.rim,
+ ),
+ ),
+ ],
),
- ],
- ),
- ),
- if (c.hasEarlierReplies(widget.root))
- Align(
- alignment: Alignment.centerLeft,
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: grid.AppDesktop.controlGap,
),
- child: TextButton(
- key: const ValueKey('super-thread-earlier'),
- onPressed: c.readingEarlierReplies
- ? null
- : () => unawaited(c.loadThread(earlier: true)),
- child: Text(
- c.readingEarlierReplies
- ? 'Loading earlier replies…'
- : 'Show earlier replies',
+ if (c.hasEarlierReplies(widget.root))
+ Align(
+ alignment: Alignment.centerLeft,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap,
+ ),
+ child: TextButton(
+ key: const ValueKey('super-thread-earlier'),
+ onPressed: c.readingEarlierReplies
+ ? null
+ : () =>
+ unawaited(c.loadThread(earlier: true)),
+ child: Text(
+ c.readingEarlierReplies
+ ? 'Loading earlier replies…'
+ : 'Show earlier replies',
+ ),
+ ),
),
),
+ for (final (index, reply) in replies.indexed)
+ widget.row(
+ reply,
+ index > 0 &&
+ replies[index - 1].authorId == reply.authorId &&
+ replies[index - 1].fromAgent == reply.fromAgent,
+ ),
+ for (final sent in pending) widget.outgoing(sent),
+ ],
+ ),
+ if (_away)
+ Positioned(
+ bottom: grid.AppDesktop.controlGap,
+ left: grid.AppDesktop.controlGap,
+ right: grid.AppDesktop.controlGap,
+ child: Center(
+ child: SuperTabJumpToLatest(
+ onPressed: _jumpToLatest,
+ count: _replies - _repliesAtEnd,
+ noun: 'reply',
+ plural: 'replies',
+ ),
),
),
- for (final (index, reply) in replies.indexed)
- widget.row(
- reply,
- index > 0 &&
- replies[index - 1].authorId == reply.authorId &&
- replies[index - 1].fromAgent == reply.fromAgent,
- ),
- for (final sent in pending) widget.outgoing(sent),
],
),
),
diff --git a/desktop/lib/super_tabs/username_editor.dart b/desktop/lib/super_tabs/username_editor.dart
new file mode 100644
index 000000000..cc42affb3
--- /dev/null
+++ b/desktop/lib/super_tabs/username_editor.dart
@@ -0,0 +1,103 @@
+import 'package:flutter/material.dart';
+
+import '../widgets/desktop_chrome.dart';
+
+/// The reader's username: the field, Save, and why a name was refused (taken,
+/// or not one a username can be), said under the field it is about.
+class SuperTabUsernameEditor extends StatefulWidget {
+ const SuperTabUsernameEditor({
+ super.key,
+ required this.username,
+ required this.busy,
+ required this.onSave,
+ });
+ final String username;
+ final bool busy;
+
+ /// Saves the name; answers why it was refused, or null once saved.
+ final Future<String?> Function(String username) onSave;
+
+ @override
+ State<SuperTabUsernameEditor> createState() => _SuperTabUsernameEditorState();
+}
+
+class _SuperTabUsernameEditorState extends State<SuperTabUsernameEditor> {
+ late final _text = TextEditingController(text: widget.username);
+ String? _error;
+
+ /// The last name saved, until the server's version of it arrives.
+ String? _sent;
+
+ @override
+ void didUpdateWidget(SuperTabUsernameEditor old) {
+ super.didUpdateWidget(old);
+ // A saved name comes back as the server keeps it (lowercased), but never
+ // over a newer edit typed while it was on its way.
+ final typed = _text.text.trim();
+ if (old.username == widget.username) return;
+ if (typed == old.username || typed == _sent) _text.text = widget.username;
+ _sent = null;
+ }
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ bool get _changed {
+ final typed = _text.text.trim();
+ return typed.isNotEmpty && typed != widget.username;
+ }
+
+ Future<void> _save() async {
+ if (widget.busy || !_changed) return;
+ final error = await widget.onSave(_sent = _text.text.trim());
+ if (error != null) _sent = null;
+ if (mounted) setState(() => _error = error);
+ }
+
+ @override
+ Widget build(BuildContext context) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Username', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: TextField(
+ key: const ValueKey('super-username-field'),
+ controller: _text,
+ maxLength: 32,
+ textInputAction: TextInputAction.done,
+ decoration: const InputDecoration(counterText: ''),
+ onChanged: (_) => setState(() => _error = null),
+ onSubmitted: (_) => _save(),
+ ),
+ ),
+ const SizedBox(width: 8),
+ FilledButton(
+ key: const ValueKey('super-username-save'),
+ onPressed: widget.busy || !_changed ? null : _save,
+ child: const Text('Save'),
+ ),
+ ],
+ ),
+ const SizedBox(height: 4),
+ Text(
+ 'How people see and tag you in this Swarm.',
+ 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/view.dart b/desktop/lib/super_tabs/view.dart
index bfe529f66..eaed5600a 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -20,16 +20,17 @@ import '../state/harness_attachments.dart';
import '../state/workspace_chrome.dart';
import 'chat_scroll.dart';
import 'leaderboard/reader.dart';
+import 'jump_to_latest.dart';
import 'unread_line.dart';
import 'roster.dart';
import 'recording_notice.dart';
-import 'identity.dart' show superTabPersonName;
import 'profile_actions.dart';
import 'pull_requests.dart';
import 'composer_newline.dart';
import 'controller.dart';
import 'dialog_scope.dart';
import 'folder_zip.dart';
+import 'identity.dart';
import 'model.dart';
import 'prompt_alerts.dart';
import 'workgroup_name.dart';
@@ -52,7 +53,15 @@ import 'project_options.dart';
import 'pane_layout.dart';
import '../widgets/dial_list_scroll.dart';
-typedef _ComposerChoice = ({String label, String? detail, VoidCallback choose});
+/// A completion row: a workgroup, or someone to tag with their face and
+/// whether they are a person or an agent ([kind]).
+typedef _ComposerChoice = ({
+ String label,
+ String? detail,
+ VoidCallback choose,
+ Widget? leading,
+ String? kind,
+});
/// The contents of one app tab. Its title stays in the app's existing tab bar.
/// [terminal] is the existing native pane, with its own controls and input.
@@ -107,6 +116,8 @@ class _SuperTabViewState extends State<SuperTabView>
final _latest = <String, int>{};
final _following = <String, bool>{};
final _newAfter = <String, int>{};
+ // Conversations whose list is scrolled away from its newest message.
+ final _awayFromEnd = <String>{};
final _unread = SuperTabUnreadLines();
final _replies = <String, SuperTabMessage>{};
String? _selected;
@@ -273,6 +284,7 @@ class _SuperTabViewState extends State<SuperTabView>
if (c.accessRevoked) {
_replies.clear();
_newAfter.clear();
+ _awayFromEnd.clear();
_unread.reset();
}
final visible =
@@ -487,7 +499,8 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
- /// Shows the jump pill while the reader is scrolled away from the line.
+ /// Shows the jump pill while the reader is scrolled away from the line, and
+ /// Jump to latest while the list is away from its newest message.
void _checkUnreadLine() {
final scroll = _scroll[c.selectedId];
var away = false;
@@ -498,7 +511,15 @@ class _SuperTabViewState extends State<SuperTabView>
final top = line == null ? null : _topInList(line);
away = top == null || top < 0 || top > scroll.position.viewportDimension;
}
- if (away == _unread.away || !mounted) return;
+ final id = c.selectedId;
+ final awayFromEnd =
+ scroll != null &&
+ scroll.hasClients &&
+ scroll.position.extentAfter >= 40;
+ if ((away == _unread.away && awayFromEnd == _awayFromEnd.contains(id)) ||
+ !mounted) {
+ return;
+ }
// A list settling its extent moves the position mid-layout: draw the pill
// on the next frame then.
if (SchedulerBinding.instance.schedulerPhase ==
@@ -506,7 +527,14 @@ class _SuperTabViewState extends State<SuperTabView>
WidgetsBinding.instance.addPostFrameCallback((_) => _checkUnreadLine());
return;
}
- setState(() => _unread.away = away);
+ setState(() {
+ _unread.away = away;
+ if (awayFromEnd) {
+ _awayFromEnd.add(id);
+ } else {
+ _awayFromEnd.remove(id);
+ }
+ });
}
/// Esc: everything loaded in the open conversation is read, line and all.
@@ -818,18 +846,12 @@ class _SuperTabViewState extends State<SuperTabView>
label: group.label,
detail: context.isEmpty ? null : context.join(' — '),
choose: () => _chooseWorkgroup(group),
+ leading: null,
+ kind: null,
);
}).toList();
}
- return _mentionChoices
- .map(
- (agent) => (
- label: _agentName(agent),
- detail: '${agent.engine} ${widget.machineName(agent.machineId)}',
- choose: () => _chooseMention(agent),
- ),
- )
- .toList();
+ return _mentionChoices;
}
void _chooseWorkgroup(SuperTabConversation group) {
@@ -896,29 +918,64 @@ class _SuperTabViewState extends State<SuperTabView>
return (start: start, end: end, query: query.toLowerCase());
}
- List<SuperTabAgent> get _mentionChoices {
+ /// Who `@` offers: the people who read this conversation, then its agents,
+ /// filtered by what follows the `@`. Never the reader; nobody is tagged in
+ /// the Leads conversation, so it offers agents alone.
+ List<_ComposerChoice> get _mentionChoices {
final mention = _mentionAtCursor;
- if (mention == null) return const [];
- return c.snapshot?.agents
- .where(
- (agent) =>
- c.selected?.agentIds.contains(agent.id) == true &&
- '${_agentName(agent)} ${agent.engine}'.toLowerCase().contains(
- mention.query,
- ),
- )
- .take(6)
- .toList() ??
- const [];
+ final snapshot = c.snapshot, group = c.selected;
+ if (mention == null || snapshot == null || group == null) return const [];
+ final project = snapshot.projectFor(group.id);
+ bool reads(SuperTabPerson person) => switch (group) {
+ _ when group.kind == 'leads' => false,
+ SuperTabConversation(:final audience?) => audience.contains(person.id),
+ _ when group.buddyOwnerId != null => person.id == group.buddyOwnerId,
+ _ =>
+ project == null ||
+ !project.isPrivate ||
+ project.ownerId == person.id ||
+ project.memberIds.contains(person.id),
+ };
+ final people = snapshot.people.where(
+ (person) =>
+ person.id != c.accountId &&
+ reads(person) &&
+ person.username.contains(mention.query),
+ );
+ final agents = snapshot.agents.where(
+ (agent) =>
+ group.agentIds.contains(agent.id) &&
+ '${_agentName(agent)} ${agent.engine}'.toLowerCase().contains(
+ mention.query,
+ ),
+ );
+ return [
+ for (final person in people)
+ (
+ label: person.username,
+ detail: null,
+ choose: () => _chooseMention(person.id, person.username),
+ leading: SuperTabAvatar.person(person, size: SuperTabAvatar.rowSize),
+ kind: 'person',
+ ),
+ for (final agent in agents)
+ (
+ label: _agentName(agent),
+ detail: '${agent.engine} ${widget.machineName(agent.machineId)}',
+ choose: () => _chooseMention(agent.id, _agentName(agent)),
+ leading: SuperTabAvatar.agent(agent, size: SuperTabAvatar.rowSize),
+ kind: 'agent',
+ ),
+ ].take(_completionKeys.length).toList();
}
- void _chooseMention(SuperTabAgent agent) {
+ void _chooseMention(String id, String name) {
final at = _mentionAtCursor;
if (at == null) return;
- final token = '@${_agentName(agent)}';
+ final token = '@$name';
final text = _composer.text.replaceRange(at.start, at.end, '$token ');
c.setDraft(c.selectedId, text);
- c.mention(c.selectedId, agent.id, token);
+ c.mention(c.selectedId, id, token);
_composer.value = TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: at.start + token.length + 1),
@@ -2258,10 +2315,10 @@ class _SuperTabViewState extends State<SuperTabView>
message: message,
author: _shownAuthor(c, message),
proposalOwner: _proposalOwner(message),
- // A person is named by their address's first part, as people say it.
+ // A person is named by their username, as they are tagged.
mentions: [
for (final id in message.mentions)
- if (_people[id] case final person?) person.email.split('@').first,
+ if (_people[id] case final person?) person.username,
],
references: _references,
onOpenGroup: (id) {
@@ -2306,7 +2363,7 @@ class _SuperTabViewState extends State<SuperTabView>
reactorName: (kind, id) => kind == 'agent'
? c.snapshot?.agentName(id) ?? 'Agent'
: switch (_people[id]) {
- final person? => superTabPersonName(person.email),
+ final person? => person.username,
null => 'Someone',
},
onReact: c.canWrite && c.selected?.archived == false
@@ -2661,6 +2718,8 @@ class _SuperTabViewState extends State<SuperTabView>
: messages.where((message) => message.sequence > newAfter).length;
// More came than were read: the count is a floor.
final moreNew = c.hasNewer(c.selectedId);
+ // Scrolled away from the newest message, or newer pages wait unread.
+ final awayFromEnd = _awayFromEnd.contains(c.selectedId) || moreNew;
final reply = _replies[c.selectedId];
final outgoing = c
.outgoing(c.selectedId)
@@ -2898,7 +2957,7 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
),
- if (newCount > 0 || back)
+ if (newCount > 0 || back || awayFromEnd)
Positioned(
bottom: 12,
left: 20,
@@ -2919,19 +2978,11 @@ class _SuperTabViewState extends State<SuperTabView>
),
label: const Text('Back to reply'),
),
- if (newCount > 0)
- FilledButton.icon(
- key: const ValueKey('super-new-messages'),
+ if (newCount > 0 || awayFromEnd)
+ SuperTabJumpToLatest(
onPressed: _jumpToLatest,
- icon: const Icon(
- AppIcons.chevronDown,
- size: 16,
- ),
- label: Text(
- moreNew
- ? '$newCount+ new messages'
- : '$newCount new ${newCount == 1 ? 'message' : 'messages'}',
- ),
+ count: newCount,
+ more: moreNew,
),
],
),
@@ -3052,6 +3103,13 @@ class _SuperTabViewState extends State<SuperTabView>
contentPadding: const EdgeInsets.symmetric(
horizontal: 16,
),
+ leading: choices[i].leading,
+ trailing: choices[i].kind == null
+ ? null
+ : Text(
+ choices[i].kind!,
+ style: DesktopChrome.metadata(),
+ ),
title: Text(
choices[i].label,
maxLines: 1,
diff --git a/desktop/test/device_viewer_notices_test.dart b/desktop/test/device_viewer_notices_test.dart
index d7c8501ac..f764c7359 100644
--- a/desktop/test/device_viewer_notices_test.dart
+++ b/desktop/test/device_viewer_notices_test.dart
@@ -39,6 +39,7 @@ class _Posts extends SystemNotifications {
required String title,
required String body,
String? devicePub,
+ ({String tabId, String mentionId})? mention,
}) => ids.add(id);
}
diff --git a/desktop/test/notification_link_test.dart b/desktop/test/notification_link_test.dart
index 3e5671d5f..d5c444f5a 100644
--- a/desktop/test/notification_link_test.dart
+++ b/desktop/test/notification_link_test.dart
@@ -28,6 +28,17 @@ void main() {
),
)!;
expect((device.machineId, device.agentId), ('@device', 'pub+k='));
+ // A Swarm tag's toast: its Swarm tab and tag survive the link.
+ final tag = NotificationLink.parse(
+ NotificationLink.build(
+ SystemNotifications.mentionNoticeMachine,
+ '0123456789abcdef01234567/5f0c2a',
+ ),
+ )!;
+ expect((tag.machineId, tag.agentId), (
+ '@mention',
+ '0123456789abcdef01234567/5f0c2a',
+ ));
});
test('the bare link names no agent', () {
diff --git a/desktop/test/super_tab_humans_test.dart b/desktop/test/super_tab_humans_test.dart
index 2cf8fbbd8..049180eec 100644
--- a/desktop/test/super_tab_humans_test.dart
+++ b/desktop/test/super_tab_humans_test.dart
@@ -237,7 +237,7 @@ void main() {
// The line starts where the name does.
expect(
tester.getTopLeft(part('meta', 'peer')).dx,
- tester.getTopLeft(nameIn('peer', 'Dee')).dx,
+ tester.getTopLeft(nameIn('peer', 'dee')).dx,
);
await close(tester, controller);
},
@@ -269,7 +269,7 @@ void main() {
// After the name, before the points.
expect(
tester.getTopLeft(crown('peer')).dx,
- greaterThan(tester.getTopLeft(nameIn('peer', 'Dee')).dx),
+ greaterThan(tester.getTopLeft(nameIn('peer', 'dee')).dx),
);
expect(
tester.getTopRight(crown('peer')).dx,
@@ -456,7 +456,7 @@ void main() {
final waiting = find.byKey(const ValueKey('leaderboard-waiting'));
Finder line(String text) =>
find.descendant(of: waiting, matching: find.text(text));
- expect(line('3 agents are waiting on Ken'), findsOneWidget);
+ expect(line('3 agents are waiting on ken'), findsOneWidget);
expect(line('1 agent is waiting on you'), findsOneWidget);
await close(tester, controller);
});
@@ -521,18 +521,17 @@ void main() {
);
testWidgets(
- "names each person by display name, else their email's first part",
+ 'names each person by their username, never the account display name',
(tester) async {
final controller = await show(tester, humansSwarm());
Finder within(String id, String text) =>
find.descendant(of: person(id), matching: find.text(text));
- expect(nameIn('peer', 'Dee'), findsOneWidget);
- expect(within('owner', 'Ken'), findsOneWidget);
- // A server from before names: the email's first part, as before.
+ expect(nameIn('peer', 'dee'), findsOneWidget);
+ expect(within('owner', 'ken'), findsOneWidget);
expect(within('scholes', 'scholes'), findsOneWidget);
- expect(find.text('dee'), findsNothing);
+ expect(find.text('Dee'), findsNothing);
// On hover the whole name, which a long one needs when it is cut, then the email.
- expect(find.byTooltip('Dee\[email protected]'), findsOneWidget);
+ expect(find.byTooltip('dee\[email protected]'), findsOneWidget);
await close(tester, controller);
},
@@ -615,7 +614,7 @@ void main() {
final dialog = find.byType(SuperTabDetailDialog);
Finder inDialog(String text) =>
find.descendant(of: dialog, matching: find.text(text));
- expect(inDialog('Dee'), findsOneWidget);
+ expect(inDialog('dee'), findsOneWidget);
// Who they are on one line under the name (Ken, 2026-10-28).
expect(inDialog('[email protected] · Can collaborate'), findsOneWidget);
// This week's points in words, and last week's beside them rather than a difference.
diff --git a/desktop/test/super_tab_jump_to_latest_shots_test.dart b/desktop/test/super_tab_jump_to_latest_shots_test.dart
new file mode 100644
index 000000000..da783a2e7
--- /dev/null
+++ b/desktop/test/super_tab_jump_to_latest_shots_test.dart
@@ -0,0 +1,125 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+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_JUMP_SHOTS'];
+
+const _updates = [
+ 'Reading the offline queue before the reconnect.',
+ 'The reconnect keeps every queued edit in order.',
+ 'Two devices editing at once settle on the newest edit.',
+ 'Pushed the branch; the checks are running.',
+];
+
+/// The chat and its thread, both read back from their newest message: each
+/// offers Jump to latest, and the thread counts the reply that came since.
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('screenshots for review (${brightness.name})', (tester) async {
+ final picture = GlobalKey();
+ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ server.append('Should we do thread replies?');
+ for (var i = 1; i <= 24; i++) {
+ server.append('${_updates[i % _updates.length]} ($i)');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ }
+ for (var i = 1; i <= 40; i++) {
+ server.append('${_updates[i % _updates.length]} ($i)');
+ server.messages.last['author'] = {
+ 'kind': 'agent',
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ };
+ }
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(1400, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ 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: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ tester
+ .widget<ScrollView>(
+ find.byKey(const PageStorageKey('super-messages-tab-lead')),
+ )
+ .controller!
+ .jumpTo(0);
+ final thread = tester
+ .widget<ListView>(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-thread-panel')),
+ matching: find.byType(ListView),
+ ),
+ )
+ .controller!;
+ thread.jumpTo(400);
+ await tester.pumpAndSettle();
+ server.append('A late reply, while you were reading back.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ await c.refresh();
+ await tester.pumpAndSettle();
+ expect(find.byKey(const ValueKey('super-jump-latest')), findsOne);
+ expect(find.text('1 new reply'), findsOne);
+
+ if (shots != null) {
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/jump-to-latest-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+ }
+}
diff --git a/desktop/test/super_tab_jump_to_latest_test.dart b/desktop/test/super_tab_jump_to_latest_test.dart
new file mode 100644
index 000000000..60ef55174
--- /dev/null
+++ b/desktop/test/super_tab_jump_to_latest_test.dart
@@ -0,0 +1,304 @@
+import 'package:flutter/material.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/view.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Scrolled away from the newest message, a chat and a thread offer the way
+/// back (Scholes, 2026-10-29): "Jump to latest", or the count of what arrived
+/// meanwhile.
+void main() {
+ const jump = ValueKey('super-jump-latest');
+ const newMessages = ValueKey('super-new-messages');
+ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};
+
+ Future<SuperTabController> show(
+ WidgetTester tester,
+ ConversationServer server,
+ ) async {
+ await tester.binding.setSurfaceSize(const Size(1400, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ addTearDown(c.dispose);
+ return c;
+ }
+
+ ScrollController chatScroll(WidgetTester tester) => tester
+ .widget<ScrollView>(
+ find.byKey(const PageStorageKey('super-messages-tab-lead')),
+ )
+ .controller!;
+
+ Finder panel() => find.byKey(const ValueKey('super-thread-panel'));
+ Finder inPanel(Finder finder) =>
+ find.descendant(of: panel(), matching: finder);
+ ScrollController threadScroll(WidgetTester tester) =>
+ tester.widget<ListView>(inPanel(find.byType(ListView))).controller!;
+
+ ConversationServer chat(int count) {
+ final server = ConversationServer();
+ for (var i = 1; i <= count; i++) {
+ server.append('Update $i: checking the offline queue and reconnect.');
+ }
+ return server;
+ }
+
+ testWidgets('a chat scrolled up offers Jump to latest and the click takes '
+ 'the reader back to the newest message', (tester) async {
+ await show(tester, chat(40));
+ expect(find.byKey(jump), findsNothing);
+ chatScroll(tester).jumpTo(0);
+ await tester.pumpAndSettle();
+ expect(find.byKey(jump), findsOneWidget);
+ expect(
+ find.descendant(
+ of: find.byKey(jump),
+ matching: find.text('Jump to latest'),
+ ),
+ findsOneWidget,
+ );
+
+ await tester.tap(find.byKey(jump));
+ await tester.pumpAndSettle();
+
+ expect(find.byKey(jump), findsNothing);
+ expect(chatScroll(tester).position.extentAfter, lessThan(40));
+ expect(
+ find.text('Update 40: checking the offline queue and reconnect.'),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('new messages arriving meanwhile turn it into one control with '
+ 'their count', (tester) async {
+ final server = chat(40);
+ final c = await show(tester, server);
+ chatScroll(tester).jumpTo(0);
+ await tester.pumpAndSettle();
+ server.append('The reconnect check passed.');
+ server.append('The restart check passed too.');
+ await c.refresh();
+ await tester.pumpAndSettle();
+
+ expect(find.byKey(jump), findsNothing);
+ expect(find.byKey(newMessages), findsOneWidget);
+ expect(find.text('2 new messages'), findsOneWidget);
+
+ await tester.tap(find.byKey(newMessages));
+ await tester.pumpAndSettle();
+ expect(find.byKey(newMessages), findsNothing);
+ expect(find.byKey(jump), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('a reader who scrolls back to the end loses the control '
+ 'without clicking it', (tester) async {
+ await show(tester, chat(40));
+ chatScroll(tester).jumpTo(0);
+ await tester.pumpAndSettle();
+ expect(find.byKey(jump), findsOneWidget);
+ final scroll = chatScroll(tester);
+ scroll.jumpTo(scroll.position.maxScrollExtent);
+ await tester.pumpAndSettle();
+ expect(find.byKey(jump), findsNothing);
+ });
+
+ testWidgets('access removed while scrolled up takes the control and the '
+ 'rows away', (tester) async {
+ final c = await show(tester, chat(40));
+ chatScroll(tester).jumpTo(0);
+ await tester.pumpAndSettle();
+ expect(find.byKey(jump), findsOneWidget);
+
+ c.revokeAccess('Access removed.');
+ await tester.pumpAndSettle();
+
+ expect(find.byKey(jump), findsNothing);
+ expect(find.byKey(newMessages), findsNothing);
+ expect(find.textContaining('Update 1:'), findsNothing);
+ expect(find.text('Conversation unavailable.'), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('a chat that fits the view never offers it', (tester) async {
+ await show(tester, chat(2));
+ expect(find.byKey(jump), findsNothing);
+ expect(find.byKey(newMessages), findsNothing);
+ });
+
+ ConversationServer threadOf(int replies) {
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ server.append('Should we do thread replies?');
+ for (var i = 1; i <= replies; i++) {
+ server.append('Reply $i: a long enough answer to fill the pane.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ }
+ return server;
+ }
+
+ testWidgets('a thread scrolled up offers Jump to latest and the click '
+ 'scrolls it to the newest reply', (tester) async {
+ final c = await show(tester, threadOf(30));
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ expect(panel(), findsOneWidget);
+ // A thread opens at its root, replies below.
+ expect(inPanel(find.byKey(jump)), findsOneWidget);
+
+ await tester.tap(inPanel(find.byKey(jump)));
+ await tester.pumpAndSettle();
+
+ expect(inPanel(find.byKey(jump)), findsNothing);
+ expect(threadScroll(tester).position.extentAfter, lessThan(40));
+ expect(
+ inPanel(find.text('Reply 30: a long enough answer to fill the pane.')),
+ findsOneWidget,
+ );
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a reply that arrives while the thread is read back is counted '
+ 'on the control', (tester) async {
+ final server = threadOf(30);
+ final c = await show(tester, server);
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ threadScroll(tester).jumpTo(300);
+ await tester.pumpAndSettle();
+ server.append('Reply 31: late.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ await c.refresh();
+ await tester.pumpAndSettle();
+
+ expect(inPanel(find.text('1 new reply')), findsOneWidget);
+
+ await tester.tap(inPanel(find.text('1 new reply')));
+ await tester.pumpAndSettle();
+ expect(inPanel(find.text('1 new reply')), findsNothing);
+ expect(inPanel(find.byKey(jump)), findsNothing);
+ expect(inPanel(find.text('Reply 31: late.')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('replies that arrive while the reader stays at the root of a '
+ 'long thread are counted, with no scrolling first', (tester) async {
+ final server = threadOf(30);
+ final c = await show(tester, server);
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ for (final text in ['Reply 31: late.', 'Reply 32: later.']) {
+ server.append(text);
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ await c.refresh();
+ await tester.pumpAndSettle();
+ }
+
+ expect(threadScroll(tester).position.pixels, 0);
+ expect(inPanel(find.text('2 new replies')), findsOneWidget);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('Jump to latest on replies of mixed heights ends on the real '
+ 'last reply', (tester) async {
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'peer',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ server.append('Should we do thread replies?');
+ for (var i = 1; i <= 60; i++) {
+ // Every third reply runs to many lines, the rest to one.
+ final body = i % 3 == 0
+ ? List.filled(90, 'word$i').join(' ')
+ : 'Short reply $i.';
+ server.append('Reply $i: $body');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ }
+ final c = await show(tester, server);
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ expect(inPanel(find.byKey(jump)), findsOneWidget);
+
+ await tester.tap(inPanel(find.byKey(jump)));
+ await tester.pumpAndSettle();
+
+ expect(threadScroll(tester).position.extentAfter, lessThan(1));
+ expect(inPanel(find.textContaining('Reply 60:')), findsOneWidget);
+ expect(inPanel(find.byKey(jump)), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('a reply arriving while the thread is at its end keeps it '
+ 'there with no control', (tester) async {
+ final server = threadOf(30);
+ final c = await show(tester, server);
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ final scroll = threadScroll(tester);
+ scroll.jumpTo(scroll.position.maxScrollExtent);
+ await tester.pumpAndSettle();
+ server.append('Reply 31: late.');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['author'] = peer;
+ await c.refresh();
+ await tester.pumpAndSettle();
+
+ expect(inPanel(find.byKey(jump)), findsNothing);
+ expect(inPanel(find.text('Reply 31: late.')), findsOneWidget);
+ expect(threadScroll(tester).position.extentAfter, lessThan(40));
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets('a thread that fits the pane never offers it', (tester) async {
+ final c = await show(tester, threadOf(2));
+ c.openThread('message-1');
+ await tester.pumpAndSettle();
+ expect(panel(), findsOneWidget);
+ expect(inPanel(find.byKey(jump)), findsNothing);
+ });
+}
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index 588f04561..df2354d2d 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -8,6 +8,7 @@ import 'package:harness/core/first_task.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/core/launch_setup.dart';
+import 'package:harness/notify/system_notifications.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/new_harness.dart';
import 'package:harness/state/harness_attachments.dart';
@@ -382,6 +383,7 @@ class SuperTabLaunchFixture {
bool local = false,
SuperTabFixtureConnection Function(MemoryStore)? connectionFactory,
LocalCliDiscovery? discovery,
+ SystemNotifications? systemNotifications,
Future<String> Function(ProjectFolderRequest request)? prepareFolder,
}) {
connection =
@@ -392,6 +394,7 @@ class SuperTabLaunchFixture {
connectionForTest: (_) => connection,
connected: true,
localCliDiscovery: discovery,
+ systemNotifications: systemNotifications,
prepareFolder: prepareFolder,
);
app.machineStates['m']!
diff --git a/desktop/test/super_tab_members_list_test.dart b/desktop/test/super_tab_members_list_test.dart
index f488baef1..cc09a00ab 100644
--- a/desktop/test/super_tab_members_list_test.dart
+++ b/desktop/test/super_tab_members_list_test.dart
@@ -129,7 +129,8 @@ void main() {
.getTopLeft(
find.descendant(
of: find.byKey(const ValueKey('super-person-peer')),
- matching: find.textContaining('Dee'),
+ // The row names the person by username (dee) or, before usernames, by email prefix (Dee).
+ matching: find.textContaining(RegExp('dee', caseSensitive: false)),
),
)
.dx,
diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dart
index 9a2704786..fba8ca2f9 100644
--- a/desktop/test/super_tab_mentions_test.dart
+++ b/desktop/test/super_tab_mentions_test.dart
@@ -26,6 +26,7 @@ import 'swarm_state_test.dart' show MemoryStore;
/// What would have reached the operating system.
class ShownNotices implements SystemNotifier {
final shown = <({String title, String body})>[];
+ final routes = <(String, String)>[];
@override
bool get supported => true;
@override
@@ -44,6 +45,7 @@ class ShownNotices implements SystemNotifier {
required String agentId,
}) async {
shown.add((title: title, body: body));
+ routes.add((machineId, agentId));
return NotificationPermission.granted;
}
@@ -171,6 +173,48 @@ void main() {
});
});
+ group('a fresh check of one tag', () {
+ Future<(ConversationServer, SuperTabController)> swarm() async {
+ final server = ConversationServer()..tag('message-1');
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ return (server, c);
+ }
+
+ test('says yes from a read that lists it, and shows that read', () async {
+ final (server, c) = await swarm();
+ final tags = SuperTabMentions.of(c);
+ expect(tags.waiting, isEmpty);
+ expect(await tags.waitingNow('mention-1'), isTrue);
+ expect(tags.waiting.map((m) => m.id), ['mention-1']);
+ expect(await tags.waitingNow('gone'), isFalse);
+ });
+
+ test('says no when the read fails, whatever was read before', () async {
+ final (server, c) = await swarm();
+ final tags = SuperTabMentions.of(c);
+ await tags.load();
+ expect(tags.waiting.map((m) => m.id), ['mention-1']);
+ server.failMentions = true;
+ expect(await tags.waitingNow('mention-1'), isFalse);
+ });
+
+ test('says no when who may read what changed while it was read', () async {
+ final (server, c) = await swarm();
+ final tags = SuperTabMentions.of(c);
+ await tags.load();
+ server.holdMentions = Completer<void>();
+ final answer = tags.waitingNow('mention-1');
+ await pumpEventQueue();
+ server.parts.epoch++;
+ await c.refresh();
+ server.holdMentions!.complete();
+ server.holdMentions = null;
+ expect(await answer, isFalse);
+ });
+ });
+
group('notification list', () {
/// [swarm] with a workgroup the reader is tagged in.
ConversationServer taggedInPlans() {
@@ -533,6 +577,38 @@ void main() {
);
});
+ testWidgets('a person’s tag shows their avatar and username', (
+ tester,
+ ) async {
+ final server = ConversationServer()
+ ..append('Ship it?')
+ ..tag('message-1', text: 'Ship it?', leadId: 'dee');
+ server.mentions.last['leadName'] = 'dee';
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {
+ 'id': 'dee',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'username': 'deedee',
+ 'avatar': {'kind': 'preset', 'key': 'fox'},
+ },
+ ];
+ await showView(tester, server);
+ await tester.tap(notificationsEntry());
+ await tester.pumpAndSettle();
+ final row = find.byKey(const ValueKey('super-mention-mention-1'));
+ expect(
+ find.descendant(of: row, matching: find.text('🦊')),
+ findsOneWidget,
+ );
+ // The name they go by now, though they were tagged under another.
+ expect(
+ find.descendant(of: row, matching: find.text('deedee')),
+ findsOneWidget,
+ );
+ });
+
testWidgets('mark done moves the tag to Earlier and clears the count', (
tester,
) async {
@@ -833,12 +909,17 @@ void main() {
expect(superTabMentionNotice(system, web: true), isNull);
final server = ConversationServer()..tag('message-1', text: 'Ship it?');
superTabMentionNotice(system, web: false)!(
+ 'tab-1',
SuperTabMention.fromJson(server.mentions.single),
);
await pumpEventQueue();
expect(notices.shown, [
(title: 'Wren tagged you', body: 'web-project · Lead: Ship it?'),
]);
+ // A click opens that tag in that Swarm (swarm_screen.dart).
+ expect(notices.routes, [
+ (SystemNotifications.mentionNoticeMachine, 'tab-1/mention-1'),
+ ]);
});
test('the client hands each new tag of an open Swarm over', () async {
@@ -849,7 +930,7 @@ void main() {
transport: (method, path, {body}) =>
server.request(method, path, body: body),
discoveryInterval: Duration.zero,
- onMention: (mention) => arrived.add(mention.text),
+ onMention: (tab, mention) => arrived.add('$tab: ${mention.text}'),
);
addTearDown(client.dispose);
client.bind('owner');
@@ -859,7 +940,7 @@ void main() {
server.tag('message-2', text: 'New');
await c.refresh();
await pumpEventQueue();
- expect(arrived, ['New']);
+ expect(arrived, ['tab: New']);
});
test('a Swarm tab not opened yet counts and announces new tags', () async {
@@ -879,7 +960,7 @@ void main() {
: server.request(method, path, body: body),
discoveryInterval: Duration.zero,
onTabs: (_, _) {},
- onMention: (mention) => arrived.add(mention.text),
+ onMention: (tab, mention) => arrived.add('$tab: ${mention.text}'),
onTagCounts: () => counted++,
);
addTearDown(client.dispose);
@@ -891,7 +972,7 @@ void main() {
server.tag('message-2', text: 'New');
await client.refreshTabs();
expect(client.waitingTags('tab'), 2);
- expect(arrived, ['New']);
+ expect(arrived, ['tab: New']);
// Opened, the Swarm's own state counts, and nothing is announced twice.
final c = await client.open('tab');
await c.refresh();
@@ -900,7 +981,7 @@ void main() {
await client.refreshTabs();
expect(server.mentionReads, reads);
expect(client.waitingTags('tab'), 2);
- expect(arrived, ['New']);
+ expect(arrived, ['tab: New']);
});
test(
diff --git a/desktop/test/super_tab_menu_bar_notices_test.dart b/desktop/test/super_tab_menu_bar_notices_test.dart
index 35a4eed9d..805bb6008 100644
--- a/desktop/test/super_tab_menu_bar_notices_test.dart
+++ b/desktop/test/super_tab_menu_bar_notices_test.dart
@@ -4,7 +4,9 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/notify/system_notifications.dart';
import 'package:harness/state/status_menu.dart';
+import 'package:harness/super_tabs/controller.dart' show SuperTabFailure;
import 'package:harness/super_tabs/decisions.dart';
import 'package:harness/super_tabs/notifications.dart';
import 'package:harness/super_tabs/view.dart';
@@ -13,6 +15,7 @@ import 'super_tab_launch_test.dart'
show SuperTabFixtureConnection, SuperTabLaunchFixture, tabId;
import 'support/super_tab_fixture.dart';
import 'swarm_screen_test.dart' show mount;
+import 'swarm_state_test.dart' show MemoryStore;
const otherId = 'fedcba9876543210fedcba98';
@@ -50,6 +53,82 @@ class TwoSwarms extends SuperTabFixtureConnection {
}
}
+/// The fixture's machine, whose Swarm stops answering the person's tag list
+/// when [refusal] is set: refused (403) or failing (503).
+class RefusingTags extends SuperTabFixtureConnection {
+ RefusingTags(super.store) : super(local: true);
+ SuperTabFailure? refusal;
+
+ /// Refuse every tag read after the next successful waiting list (review of
+ /// #2088: permission lost between two reads).
+ bool refuseAfterNextWaiting = false;
+
+ /// The waiting lists the server answered.
+ var waitingReads = 0;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ final path = payload['path'] as String? ?? '';
+ if (refusal case final failure?
+ when type == 'super_tabs' && path.contains('/mentions?')) {
+ throw failure;
+ }
+ final answer = await super.request(
+ type,
+ payload: payload,
+ timeout: timeout,
+ );
+ if (type == 'super_tabs' && path.contains('/mentions?state=waiting')) {
+ waitingReads++;
+ if (refuseAfterNextWaiting) {
+ refuseAfterNextWaiting = false;
+ refusal = const SuperTabFailure(
+ 'FORBIDDEN',
+ 'No longer permitted',
+ statusCode: 403,
+ );
+ }
+ }
+ return answer;
+ }
+}
+
+/// The fixture's machine, holding the answer to the next waiting-tag read
+/// until [releaseOld] completes: an older refresh still on its way (review of
+/// #2088).
+class StaleTagRefresh extends SuperTabFixtureConnection {
+ StaleTagRefresh(super.store) : super(local: true);
+ bool holdNextWaiting = false;
+ Completer<void>? releaseOld;
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async {
+ final hold =
+ holdNextWaiting &&
+ type == 'super_tabs' &&
+ (payload['path'] as String? ?? '').contains('/mentions?state=waiting');
+ if (hold) holdNextWaiting = false;
+ final answer = await super.request(
+ type,
+ payload: payload,
+ timeout: timeout,
+ );
+ if (hold) {
+ releaseOld = Completer<void>();
+ await releaseOld!.future;
+ }
+ return answer;
+ }
+}
+
/// A Swarm open in a tab of [f]'s app, with a tag and a decision waiting.
Future<void> openWithNotices(SuperTabLaunchFixture f) async {
f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');
@@ -63,6 +142,14 @@ Future<void> openWithNotices(SuperTabLaunchFixture f) async {
await SuperTabDecisions.of(c).load();
}
+/// The app's notifications as the macOS runner answers them, on any computer:
+/// a click comes back on `harness/notifications` (Linux CI picks its own
+/// notifier otherwise, which hears no such click).
+SystemNotifications clicks() => SystemNotifications(
+ store: DesktopNotificationStore(storage: MemoryStore()),
+ notifier: MacSystemNotifier(),
+);
+
void main() {
test('the menu bar lists what needs the person in each Swarm: decisions, '
'then tags, with where they were asked', () async {
@@ -346,5 +433,326 @@ void main() {
expect(updates.last['statusMenuSwarmEntries'], isNull);
f.dispose();
}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+
+ /// Mounts [f]'s app with its windows answering, and clicks a tag's system
+ /// notice as the macOS runner sends it back.
+ Future<Future<void> Function(String agentId)> clicker(
+ WidgetTester tester,
+ SuperTabLaunchFixture f,
+ ) async {
+ final messenger = tester.binding.defaultBinaryMessenger;
+ for (final (name, answer) in [
+ ('harness/swarm_tabs', (MethodCall call) async => true),
+ // The click raises the window first; it answers as a shown one.
+ (
+ 'window_manager',
+ (MethodCall call) async =>
+ call.method == 'isMinimized' ? false : null,
+ ),
+ ]) {
+ final channel = MethodChannel(name);
+ messenger.setMockMethodCallHandler(channel, answer);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ }
+ await mount(tester, f.app, nativeTabs: true);
+ await tester.pump();
+ return (agentId) async {
+ messenger.handlePlatformMessage(
+ 'harness/notifications',
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('tapped', {
+ 'machineId': SystemNotifications.mentionNoticeMachine,
+ 'agentId': agentId,
+ }),
+ ),
+ (_) {},
+ );
+ // The Swarm loads and its tags are read from the server first; then
+ // its view reads the tagged message's page.
+ for (var i = 0; i < 6; i++) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 20)),
+ );
+ await tester.pump();
+ }
+ };
+ }
+
+ /// A tag of the person in [server]'s `offline` group, away from the group
+ /// a Swarm opens on: the server's second tag, `mention-2`.
+ void tagInOffline(ConversationServer server) => server
+ ..append('Can you check offline sync?', conversationId: 'offline')
+ ..tag(server.messages.last['id'] as String, conversationId: 'offline');
+
+ testWidgets(
+ 'a click on a tag\'s system notification brings its Swarm tab forward '
+ 'and opens the tagged message',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: TwoSwarms.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ final swarmTab = f.app.activeSwarmId;
+ tagInOffline(f.connection.server);
+ f.app.newSwarm(name: 'Desktop');
+ final click = await clicker(tester, f);
+ final c = f.app.superTabs.peek(tabId)!;
+ // A tag no longer waiting for the person opens nothing.
+ await click('$tabId/gone');
+ expect(f.app.activeSwarmId, isNot(swarmTab));
+ await click('$tabId/mention-2');
+ expect(f.app.activeSwarmId, swarmTab);
+ // Its view takes the request and opens the tagged message's group.
+ expect(c.noticeRequest, isNull);
+ expect(c.selectedId, 'offline');
+ // The read marker's save settles.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testWidgets(
+ 'a click on a tag in a Swarm not loaded yet loads it, checks the tag, '
+ 'and opens it',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: TwoSwarms.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ f.app.newSwarm(name: 'Atlas');
+ f.app.bindSuperTab(f.app.activeSwarmId, otherId, 'Atlas');
+ final atlas = f.app.activeSwarmId;
+ f.app.newSwarm(name: 'Desktop');
+ tagInOffline((f.connection as TwoSwarms).other);
+ expect(f.app.superTabs.peek(otherId), isNull);
+ final click = await clicker(tester, f);
+ await click('$otherId/mention-2');
+ expect(f.app.activeSwarmId, atlas);
+ final c = f.app.superTabs.peek(otherId)!;
+ expect(c.noticeRequest, isNull);
+ expect(c.selectedId, 'offline');
+ // The read marker's save settles.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testWidgets(
+ 'a click on a tag in a closed Swarm tab reopens it at the tag; one no '
+ 'longer waiting reopens nothing',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: TwoSwarms.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ f.app.newSwarm(name: 'Atlas');
+ f.app.bindSuperTab(f.app.activeSwarmId, otherId, 'Atlas');
+ final atlas = f.app.activeSwarmId;
+ await tester.runAsync(() async {
+ await f.app.superTabs.open(otherId);
+ await f.app.requestCloseSwarm(atlas);
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.value();
+ }
+ });
+ expect(f.app.closedSuperTabs.map((t) => t.id), [otherId]);
+ tagInOffline((f.connection as TwoSwarms).other);
+ final before = f.app.activeSwarmId;
+ final click = await clicker(tester, f);
+
+ await click('$otherId/gone');
+ expect(f.app.activeSwarmId, before);
+ expect(f.app.closedSuperTabs.map((t) => t.id), [otherId]);
+ // What was loaded to check is let go again.
+ expect(f.app.superTabs.peek(otherId), isNull);
+
+ await click('$otherId/mention-2');
+ expect(f.app.activeSwarm.superTabId, otherId);
+ expect(f.app.closedSuperTabs, isEmpty);
+ final c = f.app.superTabs.peek(otherId)!;
+ expect(c.noticeRequest, isNull);
+ expect(c.selectedId, 'offline');
+ // The read marker's save settles.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testWidgets(
+ 'a click on a tag in a Swarm this account is not in opens nothing',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: TwoSwarms.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ f.app.newSwarm(name: 'Desktop');
+ final before = f.app.activeSwarmId;
+ final click = await clicker(tester, f);
+ await click('$otherId/mention-1');
+ expect(f.app.activeSwarmId, before);
+ expect(f.app.superTabs.peek(otherId), isNull);
+ // The read marker's save settles.
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ for (final (name, refusal) in [
+ (
+ 'refused',
+ const SuperTabFailure(
+ 'FORBIDDEN',
+ 'No longer permitted',
+ statusCode: 403,
+ ),
+ ),
+ (
+ 'failing',
+ const SuperTabFailure('UNAVAILABLE', 'Try again', statusCode: 503),
+ ),
+ ]) {
+ testWidgets(
+ 'a click whose fresh tag check is $name opens nothing, though the tag '
+ 'waits in what was read before',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: RefusingTags.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ f.app.newSwarm(name: 'Desktop');
+ final before = f.app.activeSwarmId;
+ expect(
+ SuperTabMentions.of(f.app.superTabs.peek(tabId)!).waiting
+ .map((m) => m.id),
+ ['mention-1'],
+ );
+ (f.connection as RefusingTags).refusal = refusal;
+ final click = await clicker(tester, f);
+ await click('$tabId/mention-1');
+ expect(f.app.activeSwarmId, before);
+ expect(f.app.superTabs.peek(tabId)!.noticeRequest, isNull);
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+ }
+
+ testWidgets(
+ 'a click that opens nothing lets go of a Swarm it loaded for a tab not '
+ 'shown yet',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: TwoSwarms.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ f.app.newSwarm(name: 'Atlas');
+ f.app.bindSuperTab(f.app.activeSwarmId, otherId, 'Atlas');
+ f.app.newSwarm(name: 'Desktop');
+ final before = f.app.activeSwarmId;
+ expect(f.app.superTabs.peek(otherId), isNull);
+ final click = await clicker(tester, f);
+ await click('$otherId/gone');
+ expect(f.app.activeSwarmId, before);
+ expect(f.app.superTabs.peek(otherId), isNull);
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testWidgets(
+ 'a click opens from the one read that confirmed the tag: a refusal '
+ 'after it changes nothing, as no second read decides',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: RefusingTags.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ tagInOffline(f.connection.server);
+ final swarmTab = f.app.activeSwarmId;
+ f.app.newSwarm(name: 'Desktop');
+ final click = await clicker(tester, f);
+ final connection = f.connection as RefusingTags;
+ final c = f.app.superTabs.peek(tabId)!;
+ // What was read before does not hold the new tag: only the click's
+ // own read can supply it.
+ expect(SuperTabMentions.of(c).waiting.map((m) => m.id), ['mention-1']);
+ final reads = connection.waitingReads;
+ connection.refuseAfterNextWaiting = true;
+ await click('$tabId/mention-2');
+ expect(connection.waitingReads, reads + 1);
+ expect(f.app.activeSwarmId, swarmTab);
+ expect(c.noticeRequest, isNull);
+ expect(c.selectedId, 'offline');
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
+
+ testWidgets(
+ 'an older tag refresh still on its way cannot replace the read that '
+ 'confirmed the click',
+ (tester) async {
+ final f = SuperTabLaunchFixture(
+ connectionFactory: StaleTagRefresh.new,
+ systemNotifications: clicks(),
+ );
+ await tester.runAsync(() => openWithNotices(f));
+ final swarmTab = f.app.activeSwarmId;
+ f.app.newSwarm(name: 'Desktop');
+ final click = await clicker(tester, f);
+ final connection = f.connection as StaleTagRefresh;
+ final c = f.app.superTabs.peek(tabId)!;
+ final tags = SuperTabMentions.of(c);
+ // A refresh read before the new tag, answering only after the click's.
+ connection.holdNextWaiting = true;
+ final refresh = tags.load();
+ for (var i = 0; i < 8; i++) {
+ await tester.runAsync(() => Future<void>.delayed(Duration.zero));
+ }
+ expect(connection.releaseOld, isNotNull);
+ tagInOffline(connection.server);
+ void releaseStale() {
+ if (tags.waiting.any((m) => m.id == 'mention-2') &&
+ !connection.releaseOld!.isCompleted) {
+ connection.releaseOld!.complete();
+ }
+ }
+
+ tags.addListener(releaseStale);
+ await click('$tabId/mention-2');
+ await tester.runAsync(() => refresh);
+ tags.removeListener(releaseStale);
+ expect(f.app.activeSwarmId, swarmTab);
+ expect(c.noticeRequest, isNull);
+ expect(c.selectedId, 'offline');
+ // The older answer did not take the tag away afterwards either.
+ expect(tags.waiting.map((m) => m.id), contains('mention-2'));
+ await tester.pump(const Duration(seconds: 1));
+ await tester.pumpWidget(const SizedBox());
+ f.dispose();
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),
+ );
});
}
diff --git a/desktop/test/super_tab_person_mentions_test.dart b/desktop/test/super_tab_person_mentions_test.dart
new file mode 100644
index 000000000..b81b9ee0e
--- /dev/null
+++ b/desktop/test/super_tab_person_mentions_test.dart
@@ -0,0 +1,209 @@
+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/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_PERSON_MENTION_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();
+ });
+}
+
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ final picker = find.byKey(const ValueKey('super-composer-completions'));
+
+ ConversationServer swarm() {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'ken', 'email': '[email protected]', 'role': 'collaborator'},
+ {'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['agents'] = [
+ {
+ 'id': 'kestrel',
+ 'name': 'Builder',
+ 'displayName': 'Kestrel',
+ 'machineId': 'host',
+ 'harnessId': 'session',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ for (final group in server.state['conversations'] as List) {
+ (group as Map)['agentIds'] = ['kestrel'];
+ }
+ 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> choices(WidgetTester tester) => [
+ for (final tile in tester.widgetList<ListTile>(
+ find.descendant(of: picker, matching: find.byType(ListTile)),
+ ))
+ (tile.title as Text).data!,
+ ];
+
+ testWidgets('@ offers people first, then agents, filtered as typed', (
+ tester,
+ ) async {
+ await show(tester, swarm());
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Please check @ke');
+ await tester.pumpAndSettle();
+ expect(choices(tester), ['ken15', 'Kestrel']);
+ expect(
+ find.descendant(of: picker, matching: find.text('person')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: picker, matching: find.text('agent')),
+ findsOneWidget,
+ );
+ // Never the reader, never by address.
+ await tester.enterText(composer, 'Please check @');
+ await tester.pumpAndSettle();
+ expect(choices(tester), ['ken15', 'dee', 'Kestrel']);
+ expect(
+ find.descendant(of: picker, matching: find.textContaining('@')),
+ findsNothing,
+ );
+ });
+
+ testWidgets('a chosen person is sent as a tag, not as a recipient', (
+ tester,
+ ) async {
+ final server = swarm();
+ final c = await show(tester, server);
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Please check @ke');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ 'Please check @ken15 ',
+ );
+ expect(c.mentions(c.selectedId), {'ken': '@ken15'});
+ await tester.enterText(composer, 'Please check @ken15 and @Kes');
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ final command = server.posts.last['command'] as Map;
+ expect(command['type'], 'message.send');
+ expect(command['mentions'], ['ken']);
+ expect(command['recipientIds'], ['kestrel']);
+ // The read marker's save settles.
+ await tester.pump(const Duration(seconds: 1));
+ });
+
+ testWidgets('a private chat offers only the people who read it', (
+ tester,
+ ) async {
+ final server = swarm();
+ ((server.state['conversations'] as List)[0] as Map)['audience'] = {
+ 'people': [
+ {'id': 'owner', 'generation': 'fixture'},
+ {'id': 'dee', 'generation': 'fixture'},
+ ],
+ };
+ await show(tester, server);
+ await tester.tap(composer);
+ await tester.enterText(composer, '@');
+ await tester.pumpAndSettle();
+ expect(choices(tester), ['dee', 'Kestrel']);
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('screenshots for review, ${brightness.name}', (tester) async {
+ await tester.binding.setSurfaceSize(const Size(900, 640));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ final server = swarm()
+ ..tag('message-1', text: '@river can you try it?', leadId: 'dee');
+ server.mentions.last['leadName'] = 'dee';
+ final c = await show(tester, server, brightness: brightness);
+ await tester.tap(composer);
+ await tester.enterText(composer, 'Please check @');
+ await tester.pumpAndSettle();
+ await shot(tester, 'picker-all-${brightness.name}');
+ await tester.enterText(composer, 'Please check @ke');
+ await tester.pumpAndSettle();
+ await shot(tester, 'picker-ke-${brightness.name}');
+ await tester.enterText(composer, '');
+ await tester.tap(find.byKey(const ValueKey('super-notifications')));
+ await tester.pumpAndSettle();
+ await shot(tester, 'notification-${brightness.name}');
+ unawaited(
+ showSuperTabProfile(tester.element(find.byType(SuperTabView)), c),
+ );
+ await tester.pumpAndSettle();
+ await shot(tester, 'profile-${brightness.name}');
+ server.refuse = {'code': 'USERNAME_TAKEN', 'message': 'ken15 is taken.'};
+ await tester.enterText(
+ find.byKey(const ValueKey('super-username-field')),
+ 'ken15',
+ );
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('super-username-save')));
+ await tester.pumpAndSettle();
+ expect(find.text('ken15 is taken.'), findsOneWidget);
+ await shot(tester, 'profile-taken-${brightness.name}');
+ }, skip: shots == null);
+ }
+}
diff --git a/desktop/test/super_tab_person_names_test.dart b/desktop/test/super_tab_person_names_test.dart
index e1be5a7bf..24719a3b4 100644
--- a/desktop/test/super_tab_person_names_test.dart
+++ b/desktop/test/super_tab_person_names_test.dart
@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/message_row.dart';
-import 'super_tab_mentions_test.dart' show showView;
+import 'super_tab_mentions_test.dart' show runsOf, showView;
import 'support/super_tab_fixture.dart';
void main() {
@@ -48,4 +48,36 @@ void main() {
expect(find.text('sam'), findsOneWidget);
},
);
+
+ testWidgets('a person who chose a username is shown and tagged by it', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {
+ 'id': 'ivy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'username': 'ivy.k',
+ },
+ ];
+ server.append('Over to @ivy.k for the copy.');
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'ivy',
+ 'name': '[email protected]',
+ };
+ server.messages.last['mentions'] = ['ivy'];
+ await showView(tester, server);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-message-message-1')),
+ matching: find.text('ivy.k'),
+ ),
+ findsOneWidget,
+ );
+ expect(runsOf(tester, '@ivy.k').single?.backgroundColor, isNotNull);
+ expect(find.textContaining('@example.com'), findsNothing);
+ });
}
diff --git a/desktop/test/super_tab_profile_actions_test.dart b/desktop/test/super_tab_profile_actions_test.dart
index be3be219f..bc41ad791 100644
--- a/desktop/test/super_tab_profile_actions_test.dart
+++ b/desktop/test/super_tab_profile_actions_test.dart
@@ -76,6 +76,55 @@ void main() {
expect(c.snapshot!.people.single.status, isNull);
});
+ test('a username is set and cleared as the person’s own', () async {
+ final server = ConversationServer();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(c.snapshot!.people.single.username, 'owner');
+ expect(await c.setUsername(' River '), isNull);
+ expect(lastCommand(server), {
+ 'type': 'member.username',
+ 'username': 'River',
+ });
+ expect(c.snapshot!.people.single.username, 'river');
+ expect(await c.setUsername(null), isNull);
+ expect(lastCommand(server), {'type': 'member.username', 'username': null});
+ expect(c.snapshot!.people.single.username, 'owner');
+ });
+
+ test('a viewer changes their own username, though nothing else', () async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'viewer'},
+ ];
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(await c.setUsername('watcher'), isNull);
+ expect(lastCommand(server), {
+ 'type': 'member.username',
+ 'username': 'watcher',
+ });
+ expect(c.snapshot!.people.single.username, 'watcher');
+ final sent = server.posts.length;
+ expect(
+ await c.setStatus(const SuperTabPersonStatus(text: 'Hi')),
+ isNotNull,
+ );
+ expect(server.posts.length, sent);
+ });
+
+ test('a taken username is refused in words', () async {
+ final server = ConversationServer()
+ ..refuse = {'code': 'USERNAME_TAKEN', 'message': 'dee is taken.'};
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(await c.setUsername('dee'), 'dee is taken.');
+ expect(c.snapshot!.people.single.username, 'owner');
+ });
+
testWidgets('an upload becomes the person’s avatar, a preset an agent’s', (
tester,
) async {
diff --git a/desktop/test/super_tab_profile_sheet_test.dart b/desktop/test/super_tab_profile_sheet_test.dart
index 0cc14ebed..d67e28170 100644
--- a/desktop/test/super_tab_profile_sheet_test.dart
+++ b/desktop/test/super_tab_profile_sheet_test.dart
@@ -1,7 +1,8 @@
-import 'dart:typed_data';
+import 'dart:async';
import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/agent_details.dart';
import 'package:harness/super_tabs/controller.dart';
@@ -156,6 +157,112 @@ void main() {
});
});
+ group('username', () {
+ final field = find.byKey(const ValueKey('super-username-field'));
+ final save = find.byKey(const ValueKey('super-username-save'));
+ String text(WidgetTester tester) =>
+ tester.widget<TextField>(field).controller!.text;
+ bool enabled(WidgetTester tester) =>
+ tester.widget<ButtonStyleButton>(save).onPressed != null;
+
+ testWidgets('shows your name and saves a new one', (tester) async {
+ 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,
+ );
+ // Nothing to save until it changes.
+ expect(enabled(tester), isFalse);
+ await tester.enterText(field, 'River');
+ await tester.pump();
+ expect(enabled(tester), isTrue);
+ await tester.tap(save);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'member.username',
+ 'username': 'River',
+ });
+ expect(c.snapshot!.people.single.username, 'river');
+ expect(text(tester), 'river');
+ expect(enabled(tester), isFalse);
+ });
+
+ testWidgets('Enter in the field saves too', (tester) async {
+ final server = ConversationServer();
+ await openSheet(tester, server);
+ await tester.enterText(field, 'pilot');
+ await tester.testTextInput.receiveAction(TextInputAction.done);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server)['username'], 'pilot');
+ });
+
+ testWidgets(
+ 'a taken name says so under the field and keeps what you typed',
+ (tester) async {
+ final server = ConversationServer();
+ await openSheet(tester, server);
+ server.refuse = {'code': 'USERNAME_TAKEN', 'message': 'dee is taken.'};
+ await tester.enterText(field, 'dee');
+ await tester.pump();
+ await tester.tap(save);
+ await tester.pumpAndSettle();
+ expect(find.text('dee is taken.'), findsOneWidget);
+ expect(text(tester), 'dee');
+ // Above Picture: the reason sits with the field it is about.
+ expect(
+ tester.getTopLeft(find.text('dee is taken.')).dy,
+ lessThan(tester.getTopLeft(find.text('Picture')).dy),
+ );
+ },
+ );
+
+ testWidgets(
+ 'a save that lands keeps what was typed while it was on its way',
+ (tester) async {
+ final server = _GatedUsernameServer();
+ final c = await openSheet(tester, server);
+ await tester.enterText(field, 'river');
+ await tester.pump();
+ await tester.tap(save);
+ await tester.pump();
+ await tester.enterText(field, 'pilot');
+ await tester.pump();
+ server.gate.complete();
+ await tester.pumpAndSettle();
+ expect(c.snapshot!.people.single.username, 'river');
+ expect(text(tester), 'pilot');
+ // The newer name is still there to save.
+ expect(enabled(tester), isTrue);
+ },
+ );
+
+ testWidgets('an empty name cannot be saved', (tester) async {
+ final server = ConversationServer();
+ await openSheet(tester, server);
+ await tester.enterText(field, ' ');
+ await tester.pump();
+ expect(enabled(tester), isFalse);
+ });
+
+ testWidgets('an agent’s sheet has no username', (tester) async {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'agent-1',
+ 'name': 'Kai',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ await openSheet(tester, server, agentId: 'agent-1');
+ expect(field, findsNothing);
+ });
+ });
+
testWidgets('a refusal is shown in the sheet', (tester) async {
final server = ConversationServer();
await openSheet(tester, server);
@@ -215,3 +322,20 @@ void main() {
}
});
}
+
+/// Holds a username save until [gate] completes (review of #2088).
+class _GatedUsernameServer extends ConversationServer {
+ final gate = Completer<void>();
+ @override
+ Future<Map<String, dynamic>> request(
+ String method,
+ String path, {
+ Map<String, dynamic>? body,
+ }) async {
+ if (method == 'POST' &&
+ (body?['command'] as Map?)?['type'] == 'member.username') {
+ await gate.future;
+ }
+ return super.request(method, path, body: body);
+ }
+}
diff --git a/desktop/test/super_tab_reading_client_test.dart b/desktop/test/super_tab_reading_client_test.dart
index 76eebdc61..5d6b01d13 100644
--- a/desktop/test/super_tab_reading_client_test.dart
+++ b/desktop/test/super_tab_reading_client_test.dart
@@ -92,7 +92,7 @@ SuperTabClient _client(
_Backend backend, {
MemoryStore? storage,
SuperTabReading? reading,
- void Function(SuperTabMention)? onMention,
+ void Function(String tabId, SuperTabMention mention)? onMention,
void Function(SuperTabController)? onSnapshot,
}) {
final client = SuperTabClient(
@@ -186,7 +186,7 @@ void main() {
final client = _client(
backend,
reading: reading,
- onMention: (m) => told.add(m.id),
+ onMention: (_, m) => told.add(m.id),
)..bind('owner');
client.show('tab');
client.open('tab');
@@ -215,7 +215,7 @@ void main() {
final client = _client(
backend,
reading: _web,
- onMention: (m) => told.add(m.id),
+ onMention: (_, m) => told.add(m.id),
)..bind('owner');
final other = backend.servers['other']!..append('First.');
other.tag(other.messages.last['id'] as String);
diff --git a/desktop/test/super_tab_team_machine_test.dart b/desktop/test/super_tab_team_machine_test.dart
index 8c560c5e9..5da1eb672 100644
--- a/desktop/test/super_tab_team_machine_test.dart
+++ b/desktop/test/super_tab_team_machine_test.dart
@@ -7,11 +7,32 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/super_tabs/agent_details.dart';
import 'package:harness/super_tabs/machines.dart';
+import 'support/rename_connection.dart';
import 'support/super_tab_fixture.dart';
import 'swarm_state_test.dart' show createApp;
const _offlineAge = 10 * 60 * 1000;
+/// This Mac's daemon, answering what it remembers of its Harness Team account
+/// setup (`teamSetupStatus`); no socket is opened.
+class _TeamDaemon extends RenameConnection {
+ Map<String, dynamic> status = {'ok': true, 'state': 'none'};
+ final asked = <Map<String, dynamic>>[];
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) {
+ if (type == 'super_tabs' && payload['action'] == 'teamSetupStatus') {
+ asked.add(Map.of(payload));
+ return Future.value(status);
+ }
+ return super.request(type, payload: payload, timeout: timeout);
+ }
+}
+
Map<String, dynamic> _pool(
String id, {
String name = 'MacBook Pro',
@@ -296,6 +317,88 @@ void main() {
},
);
+ // Scholes, 2026-10-29: a Mac whose person cancelled the password prompt, or whose setup failed, said only "not set up".
+ testWidgets(
+ 'this Mac\'s row says why it has no Harness Team account, for its person alone, with Set up to try again',
+ (tester) async {
+ final daemon = _TeamDaemon();
+ final app = createApp(connectionForTest: (_) => daemon, connected: true)
+ ..teamAccountHereForTest = true;
+ app.machineStates['m']!.localOnly = true;
+ Future<String?> line(
+ Map<String, dynamic> status, {
+ String account = 'owner',
+ }) async {
+ daemon.status = status;
+ final server = _swarm();
+ server.state['machines'] = [
+ _pool(
+ 'm',
+ contributor: 'owner',
+ teamWork: _refused('TEAM_ACCOUNT_REQUIRED'),
+ ),
+ ];
+ final c = server.controller(account: account);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMachines(
+ controller: c,
+ app: app,
+ onAddAgent: (_) {},
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final text = _problemText(tester, 'm');
+ if (account == 'owner') {
+ expect(
+ find.byKey(const ValueKey('super-machine-team-setup-m')),
+ findsOneWidget,
+ );
+ }
+ await _unmount(tester, c);
+ return text;
+ }
+
+ expect(
+ await line({'ok': true, 'state': 'declined'}),
+ "Teammates' agents paused: setup was cancelled",
+ );
+ expect(
+ await line({
+ 'ok': true,
+ 'state': 'failed',
+ 'detail': 'launchd would not start it.',
+ }),
+ "Teammates' agents paused: setup failed: launchd would not start it",
+ );
+ expect(
+ await line({'ok': true, 'state': 'running'}),
+ "Teammates' agents paused: setting up",
+ );
+ expect(
+ await line({'ok': true, 'state': 'none'}),
+ "Teammates' agents paused: not set up",
+ );
+ // A daemon from before it could say, and one that cannot answer: as before.
+ expect(
+ await line({'error': 'INVALID_REQUEST'}),
+ "Teammates' agents paused: not set up",
+ );
+ // A teammate reads the Mac's own line from the Swarm; this Mac's daemon is never asked for them.
+ final before = daemon.asked.length;
+ expect(
+ await line({'ok': true, 'state': 'declined'}, account: 'peer'),
+ "Teammates' agents paused: not set up",
+ );
+ expect(daemon.asked.length, before);
+ app.dispose();
+ },
+ );
+
// Local Team account run, 2026-10-28: after `harness team remove` its pool stays listed, and the Mac's owner read
// "Harness Team account offline" with no way to set one up again.
testWidgets(
diff --git a/desktop/test/super_tab_teammate_terminal_test.dart b/desktop/test/super_tab_teammate_terminal_test.dart
index 52d7dbde6..61e93a0cb 100644
--- a/desktop/test/super_tab_teammate_terminal_test.dart
+++ b/desktop/test/super_tab_teammate_terminal_test.dart
@@ -275,10 +275,10 @@ void main() {
);
expect(
text,
- 'River runs on $_computer, [email protected]’s computer. Its '
+ 'River runs on $_computer, scholes’s computer. Its '
'terminal is not shared with you yet: Harness there shares it with '
'Swarm members once it is up to date and running. Ask '
- '[email protected] to update and restart Harness, then Retry.',
+ 'scholes to update and restart Harness, then Retry.',
);
expect(text, isNot(contains('must be online')));
});
@@ -294,10 +294,10 @@ void main() {
expect(superTabTerminalPrivate(pm, pm.agent('river')!), isFalse);
expect(
reason(pm, 'river'),
- 'River runs on $_computer, [email protected]’s computer. Its '
+ 'River runs on $_computer, scholes’s computer. Its '
'terminal is not shared with you yet: Harness there shares it with '
'Swarm members once it is up to date and running. Ask '
- '[email protected] to update and restart Harness, then Retry.',
+ 'scholes to update and restart Harness, then Retry.',
);
// Marked confidential by the backend: in a private chat, or a Product Manager before.
final private = reason(
@@ -306,7 +306,7 @@ void main() {
);
expect(
private,
- 'River reads private chats, so only [email protected] can watch '
+ 'River reads private chats, so only scholes can watch '
'its terminal.',
);
// Its computer offline changes nothing: the terminal stays private once it is back.
@@ -326,7 +326,7 @@ void main() {
.millisecondsSinceEpoch;
expect(
reason(snapshot(receivedAt: silent), 'river'),
- 'River runs on $_computer, [email protected]’s computer, which is '
+ 'River runs on $_computer, scholes’s computer, which is '
'offline. Its terminal shows here once that computer is back.',
);
expect(reason(snapshot(), 'river'), contains('which is offline'));
@@ -375,10 +375,7 @@ void main() {
await _settle(tester);
await _shoot(tester, 'teammate-without-invitation');
expect(find.textContaining('must be online'), findsNothing);
- expect(
- find.textContaining('[email protected]’s computer'),
- findsOneWidget,
- );
+ expect(find.textContaining('scholes’s computer'), findsOneWidget);
expect(find.text('Retry'), findsOneWidget);
expect(find.byType(SharedHarnessPanel), findsNothing);
@@ -412,10 +409,7 @@ void main() {
final reads = api.reads;
c.selectTerminal('lead', 'river');
await _settle(tester);
- expect(
- find.textContaining('only [email protected] can watch'),
- findsOneWidget,
- );
+ expect(find.textContaining('only scholes can watch'), findsOneWidget);
expect(find.textContaining('update and restart'), findsNothing);
expect(find.byType(SharedHarnessPanel), findsNothing);
expect(api.reads, reads);
diff --git a/desktop/test/super_tab_usernames_test.dart b/desktop/test/super_tab_usernames_test.dart
new file mode 100644
index 000000000..81222895b
--- /dev/null
+++ b/desktop/test/super_tab_usernames_test.dart
@@ -0,0 +1,132 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/parts.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 'super_tab_parts_test.dart' show recorded;
+
+Map<String, dynamic> _person(String id, String email, [String? username]) => {
+ 'id': id,
+ 'email': email,
+ 'role': 'collaborator',
+ 'username': ?username,
+};
+
+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 [],
+ });
+
+Map<String, String> _names(List<Map<String, dynamic>> people) => {
+ for (final person in _swarm(people).people) person.id: person.username,
+};
+
+void main() {
+ // An older server sends no usernames: Desktop works out defaults by the
+ // rule backend/src/superTabs/usernames.test.ts checks.
+ group('default usernames', () {
+ test('is the lowercased email prefix, numbered by join order', () {
+ expect(
+ _names([
+ _person('a', '[email protected]'),
+ _person('b', '[email protected]'),
+ _person('c', '[email protected]'),
+ _person('d', '[email protected]'),
+ ]),
+ {'a': 'ken', 'b': 'ken2', 'c': 'tony', 'd': 'ken3'},
+ );
+ });
+
+ test('keeps a chosen name and numbers a default around it', () {
+ expect(
+ _names([
+ _person('a', '[email protected]', 'ken'),
+ _person('b', '[email protected]'),
+ _person('c', '[email protected]'),
+ ]),
+ {'a': 'ken', 'b': 'ken2', 'c': 'diego'},
+ );
+ });
+
+ test(
+ 'makes a usable name of a prefix with other characters, or too short',
+ () {
+ expect(
+ _names([
+ _person('a', '[email protected]'),
+ _person('b', '[email protected]'),
+ _person('c', '[email protected]'),
+ _person('d', '${'a' * 40}@example.com'),
+ ]),
+ {'a': 'pham.ngocswarm', 'b': 'x1', 'c': 'user', 'd': 'a' * 30},
+ );
+ },
+ );
+ });
+
+ test('names come from the server, whatever order members arrive in', () {
+ Map<String, dynamic> member(String id, String email, String username) => {
+ 'key': id,
+ 'version': 1,
+ 'changedAt': 1793000000000,
+ 'data': {
+ 'id': id,
+ 'email': email,
+ 'role': 'collaborator',
+ 'generation': 'g',
+ 'username': username,
+ },
+ };
+ final load = recorded('first_load')
+ ..['members'] = [
+ member('6a86', '[email protected]', 'ken15'),
+ // Joined after `earlier`, sent before it (review of #2088).
+ member('rejoined', '[email protected]', 'ken2'),
+ member('earlier', '[email protected]', 'ken'),
+ ];
+ final snapshot = SuperTabSnapshot.fromJson(
+ SuperTabParts.firstLoad(load).state,
+ );
+ expect(
+ {for (final p in snapshot.people) p.id: p.username},
+ {'6a86': 'ken15', 'rejoined': 'ken2', 'earlier': 'ken'},
+ );
+ });
+
+ test('a person’s message is signed with their username, not their email', () {
+ final swarm = _swarm([
+ _person('owner', '[email protected]', 'river'),
+ _person('peer', '[email protected]'),
+ ]);
+ SuperTabMessage from(String id, String email) => SuperTabMessage.fromJson({
+ 'id': 'm-$id',
+ 'conversationId': 'lead',
+ 'text': 'Morning',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': id, 'name': email},
+ });
+ expect(swarm.authorName(from('owner', '[email protected]')), 'river');
+ expect(swarm.authorName(from('peer', '[email protected]')), 'dee');
+ // Someone who left keeps the name their address gives.
+ expect(swarm.authorName(from('gone', '[email protected]')), 'tony');
+ });
+
+ test('the leaderboard names a person by their username', () {
+ final person = _swarm([_person('owner', '[email protected]', 'river')])
+ .people
+ .single;
+ final score = SuperTabPersonScore.fromJson({
+ 'personId': 'owner',
+ 'displayName': 'Ken Nguyen at Autonomous',
+ });
+ expect(leaderboardName(person, score), 'river');
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index bed8922c5..0b1d04450 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -80,6 +80,7 @@ class SwarmPartsBackend {
'otherProjectsWork',
'githubApp',
'readMarks',
+ 'teamAccounts',
}.contains(entry.key))
entry.key: entry.value,
};
@@ -156,6 +157,8 @@ class SwarmPartsBackend {
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
if (state['avatars'] != null) 'avatars': state['avatars'],
+ // Only where the server does not try Team accounts (backend read/views.ts).
+ if (state['teamAccounts'] == false) 'teamAccounts': false,
// The reader's own read marks alone, as backend readMarks.ts sends them.
if ((state['readMarks'] as Map?)?[reader ?? 'owner'] case final Map marks)
'readMarks': Map<String, dynamic>.from(marks),
@@ -609,8 +612,8 @@ class ConversationServer {
};
}
- /// A person's own status or avatar, or an agent's avatar, as the backend
- /// stores it (profile.ts).
+ /// A person's own status, username or avatar, or an agent's avatar, as the
+ /// backend stores it (profile.ts, usernames.ts).
void _profile(Map command, String reader) {
final (key, id) = command['type'] == 'agent.avatar'
? ('agents', command['agentId'])
@@ -633,6 +636,8 @@ class ConversationServer {
...row,
if (command['type'] == 'member.status')
'status': command['status']
+ else if (command['type'] == 'member.username')
+ 'username': (command['username'] as String?)?.toLowerCase()
else
'avatar': command['avatar'] == null
? null
@@ -770,6 +775,7 @@ class ConversationServer {
}
output['messageId'] = 'message-$revision';
} else if (command['type'] == 'member.status' ||
+ command['type'] == 'member.username' ||
command['type'] == 'member.avatar' ||
command['type'] == 'agent.avatar') {
_profile(command, reader ?? 'owner');
diff --git a/desktop/test/swarm_join_machine_test.dart b/desktop/test/swarm_join_machine_test.dart
new file mode 100644
index 000000000..8405bf274
--- /dev/null
+++ b/desktop/test/swarm_join_machine_test.dart
@@ -0,0 +1,477 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/machine_resources.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/join_machine.dart';
+import 'package:harness/super_tabs/join_machine_note.dart';
+import 'package:harness/super_tabs/model.dart';
+
+import 'support/super_tab_fixture.dart';
+
+const _gib = 1024 * 1024 * 1024;
+
+/// This computer's daemon, as the join step asks it: setup of the Swarm's
+/// folder (`prepareContribution`), then a wake once the machine is added.
+class _Daemon {
+ final asked = <Map<String, dynamic>>[];
+ final woken = <String>[];
+
+ /// Answers to `prepareContribution`, in turn; the last one repeats.
+ List<Object> prepared = [
+ {
+ 'ok': true,
+ 'state': 'ready',
+ 'scope': 'swarm',
+ 'cwd': '/Users/mate/Harness/Swarm',
+ 'engines': ['claude', 'codex', 'opencode'],
+ 'maxAgents': 4,
+ 'maxAvailableAgents': 16,
+ },
+ ];
+ MachineResources? resources = const MachineResources(
+ memoryTotalBytes: 32.0 * _gib,
+ );
+
+ Future<Map<String, dynamic>> request(
+ String machineId,
+ Map<String, dynamic> payload,
+ ) async {
+ asked.add({'machineId': machineId, ...payload});
+ final next = prepared.length > 1 ? prepared.removeAt(0) : prepared.first;
+ if (next is Exception) throw next;
+ return Map<String, dynamic>.of(next as Map<String, dynamic>);
+ }
+
+ SwarmJoinMachine adder() => SwarmJoinMachine(
+ machineRequest: request,
+ readResources: (_) async => resources,
+ wake: (id) async => woken.add(id),
+ pause: Duration.zero,
+ deadline: const Duration(milliseconds: 200),
+ );
+}
+
+void main() {
+ late ConversationServer server;
+ late _Daemon daemon;
+
+ /// The Swarm as [person] sees it right after joining with [role].
+ ConversationServer joinedAs(String role, {String person = 'mate'}) {
+ final s = ConversationServer();
+ (s.state['people'] as List).add({
+ 'id': person,
+ 'email': '[email protected]',
+ 'role': role,
+ });
+ return s;
+ }
+
+ List<Map<String, dynamic>> contributions() => [
+ for (final post in server.posts)
+ if ((post['command'] as Map)['type'] == 'machine.contribute')
+ Map<String, dynamic>.from(post['command'] as Map),
+ ];
+
+ setUp(() {
+ server = joinedAs('collaborator');
+ daemon = _Daemon();
+ });
+
+ test('adds this computer with Add machine\'s defaults, only through a Team account for teammates', () async {
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final note = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(note?.added, isTrue);
+ expect(note?.tabId, 'tab');
+ expect(note?.machineId, 'mate-mac');
+ expect(contributions(), [
+ {
+ 'type': 'machine.contribute',
+ 'machineId': 'mate-mac',
+ 'name': 'MacBook Air',
+ 'cwd': '/Users/mate/Harness/Swarm',
+ 'scope': 'swarm',
+ // Only the engines a Swarm runs.
+ 'engines': ['claude', 'codex'],
+ // Half its memory in agents, at most 16: 32 GiB suggests 8.
+ 'maxAgents': 8,
+ 'teamAccountOnly': true,
+ },
+ ]);
+ expect(daemon.asked.single, {
+ 'machineId': 'mate-mac',
+ 'action': 'prepareContribution',
+ 'tabId': 'tab',
+ 'scope': 'swarm',
+ 'operationId': isA<String>(),
+ });
+ expect(daemon.woken, ['mate-mac']);
+ c.dispose();
+ });
+
+ test('waits for the folder setup, then falls back to its offer when memory cannot be read', () async {
+ daemon.resources = null;
+ daemon.prepared = [
+ {'ok': true, 'state': 'preparing'},
+ {'ok': true, 'state': 'preparing'},
+ {...daemon.prepared.single as Map<String, dynamic>, 'maxAgents': 6},
+ ];
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final note = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(note?.added, isTrue);
+ expect(contributions().single['maxAgents'], 6);
+ // One operation for the whole setup, so the daemon answers the same one.
+ expect(daemon.asked.map((a) => a['operationId']).toSet(), hasLength(1));
+ expect(daemon.asked, hasLength(3));
+ c.dispose();
+ });
+
+ test('leaves a viewer, a machine already in the Swarm and a Swarm without Team accounts alone', () async {
+ for (final setup in <void Function()>[
+ () => server = joinedAs('viewer'),
+ () => server.state['machines'] = [
+ {
+ 'machineId': 'mate-mac',
+ 'name': 'MacBook Air',
+ 'contributorId': 'mate',
+ 'engines': ['codex'],
+ 'maxAgents': 2,
+ },
+ ],
+ () => server.state['teamAccounts'] = false,
+ ]) {
+ server = joinedAs('collaborator');
+ daemon = _Daemon();
+ setup();
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final note = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(note, isNull);
+ expect(contributions(), isEmpty);
+ expect(daemon.asked, isEmpty);
+ c.dispose();
+ }
+ });
+
+ test('says why it could not add it: no Claude Code or Codex, Harness too old, or refused', () async {
+ Future<SwarmJoinedMachine?> attempt() async {
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ try {
+ return await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ } finally {
+ c.dispose();
+ }
+ }
+
+ daemon.prepared = [
+ {
+ ...daemon.prepared.single as Map<String, dynamic>,
+ 'engines': ['opencode'],
+ },
+ ];
+ expect(
+ (await attempt())?.problem,
+ 'Install Claude Code or Codex on this computer, then add it from Machines.',
+ );
+ expect(contributions(), isEmpty);
+
+ daemon = _Daemon()
+ ..prepared = [
+ {'ok': true, 'state': 'unknown'},
+ ];
+ expect(
+ (await attempt())?.problem,
+ 'Update Harness on this computer, then add it from Machines.',
+ );
+
+ daemon = _Daemon();
+ server.refuse = {
+ 'code': 'MACHINES_FULL',
+ 'message': 'A Super Tab can have up to 32 contributed machines.',
+ };
+ final refused = await attempt();
+ expect(refused?.added, isFalse);
+ expect(
+ refused?.problem,
+ 'A Super Tab can have up to 32 contributed machines.',
+ );
+ expect(daemon.woken, isEmpty);
+ });
+
+ test('gives up within its deadline when setup never finishes or the daemon cannot be reached', () async {
+ daemon.prepared = [
+ {'ok': true, 'state': 'preparing'},
+ ];
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final slow = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(
+ slow?.problem,
+ 'Setting up this computer took too long. Add it from Machines.',
+ );
+ daemon = _Daemon()..prepared = [Exception('socket closed')];
+ final unreachable = await daemon.adder().add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => true,
+ );
+ expect(
+ unreachable?.problem,
+ 'Could not reach Harness on this computer. Add it from Machines.',
+ );
+ expect(daemon.asked, hasLength(1));
+ expect(contributions(), isEmpty);
+ c.dispose();
+ });
+
+ test('stops, adding nothing and saying nothing, once the account changed or signed out', () async {
+ var current = true;
+ daemon.prepared = [
+ {'ok': true, 'state': 'preparing'},
+ daemon.prepared.single,
+ ];
+ final c = server.controller(account: 'mate');
+ await c.refresh();
+ final adder = SwarmJoinMachine(
+ machineRequest: (id, payload) {
+ current = false;
+ return daemon.request(id, payload);
+ },
+ readResources: (_) async => daemon.resources,
+ wake: (id) async => daemon.woken.add(id),
+ pause: Duration.zero,
+ deadline: const Duration(milliseconds: 200),
+ );
+ final note = await adder.add(
+ c,
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ current: () => current,
+ );
+ expect(note, isNull);
+ expect(contributions(), isEmpty);
+ expect(daemon.asked, hasLength(1));
+ c.dispose();
+ });
+
+ test(
+ 'a snapshot reads whether the Swarm uses Team accounts, absent meaning yes',
+ () {
+ SuperTabSnapshot read(Map<String, dynamic> extra) =>
+ SuperTabSnapshot.fromJson({...server.state, ...extra});
+ expect(read({}).teamAccounts, isTrue);
+ expect(read({'teamAccounts': false}).teamAccounts, isFalse);
+ },
+ );
+
+ // Review of #2188: an invitation accepted on this computer by someone who
+ // joined by link on another one made no membership, and shares nothing.
+ test('a join or accept adds this computer only when the server says it made the membership', () {
+ // An invitation's accept answers as the backend's commands.ts does.
+ expect(
+ swarmNewMemberRole({
+ 'conversationId': 'lead',
+ 'alreadyMember': false,
+ 'role': 'collaborator',
+ }),
+ 'collaborator',
+ );
+ expect(
+ swarmNewMemberRole({
+ 'conversationId': 'lead',
+ 'alreadyMember': true,
+ 'role': 'collaborator',
+ }),
+ isNull,
+ );
+ // A link join, as store.ts answers it.
+ expect(
+ swarmNewMemberRole({
+ 'id': 'tab',
+ 'role': 'viewer',
+ 'alreadyMember': false,
+ }),
+ 'viewer',
+ );
+ // An older server says neither: nothing is added.
+ expect(swarmNewMemberRole({'conversationId': 'lead'}), isNull);
+ expect(swarmNewMemberRole({'alreadyMember': false}), isNull);
+ });
+
+ // Re-check of #2188: every computer sent one fixed operation for an
+ // invitation, so a stale accept on computer B got A's answer back, "not a
+ // member before", and shared B too.
+ test('each computer\'s accept is its own attempt, so a stale one on another computer shares nothing', () async {
+ // The server as store.ts keeps it: an answer per operation, replayed; an
+ // invitation accepted once is gone.
+ final receipts = <String, Map<String, dynamic>>{};
+ var pending = true, loseNextReply = false;
+ Future<Map<String, dynamic>> server(String operationId) async {
+ if (receipts[operationId] case final receipt?) return receipt;
+ if (!pending) {
+ throw const SuperTabFailure(
+ 'NOT_FOUND',
+ 'This invitation is unavailable.',
+ statusCode: 404,
+ );
+ }
+ pending = false;
+ final answer = {
+ 'result': {
+ 'conversationId': 'lead',
+ 'alreadyMember': false,
+ 'role': 'collaborator',
+ },
+ };
+ receipts[operationId] = answer;
+ if (loseNextReply) {
+ loseNextReply = false;
+ throw const SuperTabFailure('NETWORK', 'lost reply');
+ }
+ return answer;
+ }
+
+ final a = SwarmInviteAccepts(), b = SwarmInviteAccepts();
+ // A's reply is lost; its retry is the same attempt and gets its answer.
+ loseNextReply = true;
+ await expectLater(a.accept('i1', server), throwsA(isA<SuperTabFailure>()));
+ final accepted = await a.accept('i1', server);
+ expect(swarmNewMemberRole(superTabMap(accepted['result'])), 'collaborator');
+ // B still shows the invitation and accepts it: refused, nothing to add.
+ await expectLater(
+ b.accept('i1', server),
+ throwsA(
+ isA<SuperTabFailure>().having((f) => f.code, 'code', 'NOT_FOUND'),
+ ),
+ );
+ expect(receipts, hasLength(1));
+ });
+
+ group('the note after joining', noteTests);
+}
+
+void noteTests() {
+ late ConversationServer server;
+ setUp(() => server = ConversationServer());
+
+ Future<SuperTabController> mount(
+ WidgetTester tester,
+ SwarmJoinedMachine note,
+ ) async {
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showJoinedMachineNote(
+ context,
+ (_) async => c,
+ note,
+ operatingSystem: 'macos',
+ ),
+ child: const Text('show'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('show'));
+ await tester.pumpAndSettle();
+ return c;
+ }
+
+ const added = SwarmJoinedMachine(
+ tabId: 'tab',
+ swarmName: 'Pilot',
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ );
+
+ testWidgets('says this Mac was added, and Pause pauses it', (tester) async {
+ final c = await mount(tester, added);
+ expect(
+ find.text(
+ 'This Mac was added to Pilot. Teammates\' agents run here only in '
+ 'Harness Team, never as you.',
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(find.byKey(const Key('swarm-joined-machine-pause')));
+ await tester.pumpAndSettle();
+ expect(server.posts.map((p) => p['command']), [
+ {'type': 'machine.pause', 'machineId': 'mate-mac', 'paused': true},
+ ]);
+ expect(find.byKey(const Key('swarm-joined-machine-note')), findsNothing);
+ c.dispose();
+ });
+
+ testWidgets('Remove removes it; a refusal says why', (tester) async {
+ server.refuse = {
+ 'code': 'FORBIDDEN',
+ 'message': 'Only its owner can remove it.',
+ };
+ final c = await mount(tester, added);
+ await tester.tap(find.byKey(const Key('swarm-joined-machine-remove')));
+ await tester.pumpAndSettle();
+ expect(server.posts.map((p) => p['command']), [
+ {'type': 'machine.remove', 'machineId': 'mate-mac'},
+ ]);
+ expect(find.text('Only its owner can remove it.'), findsOneWidget);
+ c.dispose();
+ });
+
+ testWidgets('a computer that was not added says why, with nothing to undo', (
+ tester,
+ ) async {
+ final c = await mount(
+ tester,
+ const SwarmJoinedMachine(
+ tabId: 'tab',
+ swarmName: 'Pilot',
+ machineId: 'mate-mac',
+ machineName: 'MacBook Air',
+ problem: 'Install Claude Code or Codex on this computer, then add it from Machines.',
+ ),
+ );
+ expect(
+ find.text(
+ 'This Mac was not added to Pilot. Install Claude Code or Codex on this '
+ 'computer, then add it from Machines.',
+ ),
+ findsOneWidget,
+ );
+ expect(find.byKey(const Key('swarm-joined-machine-pause')), findsNothing);
+ expect(find.byKey(const Key('swarm-joined-machine-remove')), findsNothing);
+ c.dispose();
+ });
+}
diff --git a/desktop/test/swarm_sharing_test.dart b/desktop/test/swarm_sharing_test.dart
index 9cd2e83c2..d8b4a2c70 100644
--- a/desktop/test/swarm_sharing_test.dart
+++ b/desktop/test/swarm_sharing_test.dart
@@ -722,4 +722,75 @@ void main() {
expect(find.text('private server text'), findsNothing);
expect(opened, false);
});
+
+ // Scholes, 2026-10-29: joining adds this computer, so only a join that made
+ // the person a member says so, with the role; someone already in it, never.
+ testWidgets('tells only a new member\'s join, with its role', (tester) async {
+ Future<List<String>> join(
+ Map<String, dynamic> preview, {
+ Map<String, dynamic>? joined,
+ }) async {
+ final told = <String>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () => showDialog<void>(
+ context: context,
+ builder: (_) => SwarmJoinDialog(
+ link: _link,
+ accountEmail: '[email protected]',
+ isCurrent: () => true,
+ onJoined: (_, _) {},
+ onNewMember: (id, role) => told.add('$id:$role'),
+ request: (_, path, {body}) async =>
+ path.endsWith('/preview')
+ ? {'id': _link.tabId, 'name': 'Pilot', ...preview}
+ : {'id': _link.tabId, ...?joined},
+ ),
+ ),
+ child: const Text('open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('open'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const Key('swarm-join-confirm')));
+ await tester.pumpAndSettle();
+ return told;
+ }
+
+ expect(
+ await join(
+ {'role': 'collaborator'},
+ joined: {'role': 'collaborator', 'alreadyMember': false},
+ ),
+ ['${_link.tabId}:collaborator'],
+ );
+ expect(
+ await join(
+ {'role': 'viewer'},
+ joined: {'role': 'viewer', 'alreadyMember': false},
+ ),
+ ['${_link.tabId}:viewer'],
+ );
+ expect(
+ await join({'role': 'collaborator', 'alreadyMember': true}),
+ isEmpty,
+ );
+ // Review of #2188: the preview said not a member, but the person joined on
+ // another device while it was open. The join's own answer decides.
+ expect(
+ await join(
+ {'role': 'collaborator'},
+ joined: {'role': 'collaborator', 'alreadyMember': true},
+ ),
+ isEmpty,
+ );
+ // A server that does not say: nothing is added.
+ expect(await join({'role': 'collaborator'}), isEmpty);
+ });
}
diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dart
index 74e72f97e..ee91e950e 100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@ -5,6 +5,7 @@ import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/project_folder.dart';
import 'package:harness/measurement/product_measurement.dart';
+import 'package:harness/notify/system_notifications.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/pane_layout_store.dart';
import 'package:harness/state/pane_preset.dart';
@@ -41,6 +42,7 @@ class _PreparingApp extends AppNotifier {
super.connectionForTest,
super.localCliDiscovery,
super.productMeasurement,
+ super.systemNotifications,
super.paneLayoutStore,
});
final Future<String> Function(ProjectFolderRequest request) prepare;
@@ -60,6 +62,7 @@ AppNotifier createApp({
ProductMeasurement? productMeasurement,
LocalCliDiscovery? localCliDiscovery,
Future<String> Function(ProjectFolderRequest request)? prepareFolder,
+ SystemNotifications? systemNotifications,
}) {
final app =
(prepareFolder == null
@@ -70,6 +73,7 @@ AppNotifier createApp({
connectionForTest: connectionForTest,
localCliDiscovery: localCliDiscovery,
productMeasurement: productMeasurement,
+ systemNotifications: systemNotifications,
paneLayoutStore: store == null
? null
: PaneLayoutStore(storage: store),
@@ -82,6 +86,7 @@ AppNotifier createApp({
connectionForTest: connectionForTest,
localCliDiscovery: localCliDiscovery,
productMeasurement: productMeasurement,
+ systemNotifications: systemNotifications,
paneLayoutStore: store == null
? null
: PaneLayoutStore(storage: store),
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 9272af3bc..877a71f8a 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -39,11 +39,17 @@ class SuperTabPerson {
role = _text(row, 'role'),
generation = row['generation'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
- status = SuperTabPersonStatus.fromJson(row['status']);
+ status = SuperTabPersonStatus.fromJson(row['status']),
+ chosenUsername = row['username'] as String?;
final String id, email, role;
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
+ /// The username the person chose (desktop usernames); null for a default.
+ /// The phone still names people by their email prefix until it takes
+ /// usernames too.
+ final String? chosenUsername;
+
/// Their status while it lasts.
SuperTabPersonStatus? statusAt(DateTime now) =>
status?.shownAt(now) == true ? status : null;
@@ -336,6 +342,7 @@ class SuperTabSnapshot {
mentionsDigest = row['mentionsDigest'] as String?,
decisionsWaiting = (row['decisionsWaiting'] as num?)?.toInt() ?? 0,
decisionsDigest = row['decisionsDigest'] as String?,
+ teamAccounts = row['teamAccounts'] != false,
readMarks = Map.unmodifiable({
if (row['readMarks'] case final Map marks)
for (final MapEntry(:key, :value) in marks.entries)
@@ -413,6 +420,10 @@ class SuperTabSnapshot {
/// count may not; null from a backend before it (superTabs/decisions.ts).
final String? decisionsDigest;
+ /// False only where the server does not try Harness Team accounts yet
+ /// (backend read/contract.ts `teamAccounts`), as on the desktop.
+ final bool teamAccounts;
+
/// The reader's own read marks kept on the server (backend readMarks.ts): the newest message sequence read, by
/// conversation, on any of their devices. Never another person's.
final Map<String, int> readMarks;
diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dart
index 23dbff7a8..a70932576 100644
--- a/mobile/lib/swarm/parts.dart
+++ b/mobile/lib/swarm/parts.dart
@@ -316,6 +316,8 @@ class SuperTabParts {
if (_derived['decisionsDigest'] case final String digest) {
state['decisionsDigest'] = digest;
}
+ // Sent only where the server does not try Harness Team accounts yet.
+ if (_derived['teamAccounts'] == false) state['teamAccounts'] = false;
if (_readMarks.isNotEmpty) state['readMarks'] = Map.of(_readMarks);
return state;
}