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.

Swarm: avatars, status, reactions and the ship moment (#1766)

Jacob Phamd5ca22d7d0c8
diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.ts
new file mode 100644
index 000000000..e29a9ec7c
--- /dev/null
+++ b/backend/integration/superTabProfile.test.ts
@@ -0,0 +1,330 @@
+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, describe, expect, it } from 'vitest'
+import { MongoMemoryReplSet } from 'mongodb-memory-server-core'
+import { PrismaClient } from '@prisma/client'
+import Fastify, { type FastifyInstance } from 'fastify'
+import type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { MemoryAttachmentStore, MemoryAvatarStore } from '../src/superTabs/attachments.js'
+import { superTabRoutes } from '../src/routes/superTabs.js'
+import { errorHandler } from '../src/middlewares/errorHandler.js'
+import type { Command } from '../src/superTabs/commands.js'
+
+// A fresh loopback replica set, created here. This suite never reads DATABASE_URL or an existing database.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+let store: SuperTabStore
+let app: FastifyInstance
+const files = new MemoryAttachmentStore()
+const pictures = new MemoryAvatarStore('https://avatars.example.test')
+const owner: AuthUser = { sub: '200000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const peer: AuthUser = { sub: '200000000000000000000002', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const outsider: AuthUser = { sub: '200000000000000000000003', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const run = (tab: string, command: Command, user = owner, asAgentId?: string, operationId = randomUUID()) =>
+ store.execute(user, tab, { operationId, command }, asAgentId)
+const read = async (tab: string, user: AuthUser, path = 'parts') => {
+ const response = await app.inject({ method: 'GET', url: `/api/super-tabs/${tab}/${path}`, headers: { authorization: `Bearer ${user.sub}` } })
+ return { status: response.statusCode, body: response.json(), text: response.body }
+}
+type Uploaded = { id: string }
+const upload = async (tab: string, bytes: Uint8Array, name = 'me.png', mime = 'image/png', user = owner, asAgentId?: string) => {
+ const form = new FormData()
+ form.append('file', new Blob([bytes], { type: mime }), name)
+ const encoded = new Request('http://upload.test', { method: 'POST', body: form })
+ const response = await app.inject({ method: 'POST', url: `/api/super-tabs/${tab}/avatars${asAgentId ? `?asAgentId=${asAgentId}` : ''}`,
+ headers: { authorization: `Bearer ${user.sub}`, 'content-type': encoded.headers.get('content-type')! }, payload: Buffer.from(await encoded.arrayBuffer()) })
+ const body = response.json()
+ return { status: response.statusCode, code: body.error?.code ?? body.code, avatar: body.data?.avatar as Uploaded }
+}
+const PNG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+const image = (size: number, head: number[] = PNG) => { const bytes = new Uint8Array(size).map((_, i) => i % 251); bytes.set(head); return bytes }
+const stored = async (id: string) => pictures.objects.get((await db.superTabAttachment.findUniqueOrThrow({ where: { id } })).objectKey)
+async function swarm() {
+ const tab = (await store.create(owner, randomUUID(), 'Office')).id
+ const invitation = await run(tab, { type: 'invite.create', email: peer.email, role: 'collaborator', conversationId: 'lead' })
+ await run(tab, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
+ return tab
+}
+
+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(`super_tab_profile_${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 } } })
+ store = new SuperTabStore(db, Date.now, { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test', avatars: pictures })
+ for (const user of [owner, peer, outsider]) await db.user.create({ data: { id: user.sub, externalId: `fixture-${user.sub}`,
+ email: user.email, autonomousEnv: user.autonomousEnv } })
+ // The owner's own machine runs the agents, so acting as one needs no machine share.
+ await db.machine.create({ data: { machineId: 'host', userId: owner.sub, apiKey: 'fixture-only', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+ app = Fastify()
+ app.setErrorHandler(errorHandler)
+ // External SSO is replaced with fixture accounts; every permission and transaction below is real.
+ app.addHook('onRequest', async (request, reply) => {
+ const user = [owner, peer, outsider].find(u => `Bearer ${u.sub}` === request.headers.authorization)
+ if (!user) return reply.code(401).send({ success: false })
+ request.user = user
+ })
+ await app.register(superTabRoutes, { store, github: null })
+ await app.ready()
+})
+afterAll(async () => {
+ await app?.close()
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+describe('status line', () => {
+ it('reaches members through first loads and changes, and nobody outside the Swarm', async () => {
+ const tab = await swarm()
+ const first = await read(tab, peer)
+ expect(first.status).toBe(200)
+ await run(tab, { type: 'member.status', status: { text: 'Heads down', emoji: '🎯' } })
+ 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.status)
+ .toEqual({ text: 'Heads down', emoji: '🎯', until: null })
+ expect((await read(tab, peer)).body.data.members.find((m: { key: string }) => m.key === owner.sub).data.status.text).toBe('Heads down')
+ const stranger = await read(tab, outsider)
+ expect(stranger.status).not.toBe(200)
+ expect(stranger.text).not.toContain('Heads down')
+ await run(tab, { type: 'member.status', status: null })
+ expect((await read(tab, peer)).body.data.members.find((m: { key: string }) => m.key === owner.sub).data.status).toBeUndefined()
+ })
+
+ it('answers a retried operation once, and a second writer does not undo the first', async () => {
+ const tab = await swarm()
+ const operationId = randomUUID()
+ const command: Command = { type: 'member.status', status: { text: 'Coffee', emoji: '☕' } }
+ await Promise.all([run(tab, command, owner, undefined, operationId), run(tab, command, owner, undefined, operationId),
+ run(tab, { type: 'member.status', status: { text: 'Reviewing' } }, peer)])
+ const members = (await read(tab, owner)).body.data.members as Array<{ key: string; data: { status?: { text: string } } }>
+ expect(members.find(m => m.key === owner.sub)!.data.status!.text).toBe('Coffee')
+ expect(members.find(m => m.key === peer.sub)!.data.status!.text).toBe('Reviewing')
+ })
+})
+
+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()
+ const png = await upload(tab, image(1024 * 1024))
+ expect(png.status).toBe(200)
+ // No link comes back: a picture is only ever reached through a member read's signed link.
+ expect(png.avatar).toEqual({ id: expect.any(String) })
+ expect(await stored(png.avatar.id)).toMatchObject({ contentType: 'image/png' })
+ // A .png that is really a JPEG still shows, as what it is.
+ const jpeg = await upload(tab, image(2048, [0xff, 0xd8, 0xff]), 'me.png', 'image/png', peer)
+ expect(jpeg.status).toBe(200)
+ expect(await stored(jpeg.avatar.id)).toMatchObject({ contentType: 'image/jpeg' })
+ const webp = await upload(tab, image(64, [...Buffer.from('RIFF'), 0, 0, 0, 0, ...Buffer.from('WEBP')]), 'me.webp', 'image/webp')
+ expect(webp.status).toBe(200)
+ })
+
+ it('refuses a file over 1 MB, a gif, and a page or script that says it is an image', async () => {
+ const tab = await swarm()
+ const before = pictures.objects.size
+ expect(await upload(tab, image(1024 * 1024 + 1))).toMatchObject({ status: 413, code: 'AVATAR_TOO_LARGE' })
+ expect(await upload(tab, image(64, [...Buffer.from('GIF89a')]), 'me.gif', 'image/gif')).toMatchObject({ status: 415, code: 'AVATAR_TYPE' })
+ expect(await upload(tab, new TextEncoder().encode('<html><script>alert(1)</script></html>'), 'me.png', 'image/png'))
+ .toMatchObject({ status: 415, code: 'AVATAR_TYPE' })
+ expect(await upload(tab, new TextEncoder().encode('<svg xmlns="http://www.w3.org/2000/svg"/>'), 'me.svg', 'image/svg+xml'))
+ .toMatchObject({ status: 415, code: 'AVATAR_TYPE' })
+ expect(pictures.objects.size).toBe(before)
+ })
+
+ it('is refused outside the Swarm and for a viewer', async () => {
+ const tab = await swarm()
+ expect((await upload(tab, image(64), 'me.png', 'image/png', outsider)).status).toBe(403)
+ const viewing = (await store.create(owner, randomUUID(), 'Read only')).id
+ const invitation = await run(viewing, { type: 'invite.create', email: peer.email, role: 'viewer', conversationId: 'lead' })
+ await run(viewing, { type: 'invite.accept', inviteId: invitation.result.inviteId as string }, peer)
+ expect(await upload(viewing, image(64), 'me.png', 'image/png', peer)).toMatchObject({ status: 403, code: 'READ_ONLY' })
+ })
+
+ it('is never sendable as a chat file', async () => {
+ const tab = await swarm()
+ const { avatar } = await upload(tab, image(64))
+ await expect(run(tab, { type: 'message.send', conversationId: 'lead', text: '', replyTo: null, recipientIds: [], attachmentIds: [avatar.id] }))
+ .rejects.toMatchObject({ code: 'ATTACHMENT_UNAVAILABLE' })
+ })
+})
+
+describe('setting avatars', () => {
+ const HOUR = 3_600_000
+ const avatarOf = async (tab: string, key: string) =>
+ ((await read(tab, peer)).body.data.members as Array<{ key: string; data: { avatar?: unknown } }>).find(m => m.key === key)!.data.avatar
+ const linkFor = async (tab: string, reader: AuthUser, who: string) =>
+ ((await read(tab, reader)).body.data.derived?.avatars ?? {})[who] as string | undefined
+
+ it('puts the person’s own upload on their member record, once', async () => {
+ const tab = await swarm()
+ const { avatar } = await upload(tab, image(64))
+ await run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: avatar.id } })
+ expect(await avatarOf(tab, owner.sub)).toEqual({ kind: 'upload' })
+ await expect(run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: avatar.id } })).rejects.toMatchObject({ code: 'AVATAR_UNAVAILABLE' })
+ })
+
+ it('reaches members only through a signed link that stops opening within an hour', async () => {
+ const tab = await swarm()
+ const { avatar } = await upload(tab, image(64))
+ await run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: avatar.id } })
+ const first = await read(tab, peer)
+ // The record says only that there is a picture; the bucket opens nothing without a signature, its path alone included.
+ expect(first.body.data.members.find((m: { key: string }) => m.key === owner.sub).data.avatar).toEqual({ kind: 'upload' })
+ const objectKey = (await db.superTabAttachment.findUniqueOrThrow({ where: { id: avatar.id } })).objectKey
+ expect(pictures.open(`https://avatars.example.test/${objectKey}`, Date.now())).toBeNull()
+ const link = await linkFor(tab, peer, `person:${owner.sub}`)
+ expect(link).toMatch(/^https:\/\/avatars\.example\.test\//)
+ expect(pictures.open(link!, Date.now())).toEqual(Buffer.from(image(64)))
+ // The same link for a while, so a picture is not fetched again on every poll.
+ expect(await linkFor(tab, peer, `person:${owner.sub}`)).toBe(link)
+ // A copied link stops opening once it is over.
+ expect(pictures.open(link!, Date.now() + HOUR + 1)).toBeNull()
+ const changes = await read(tab, peer, `changes?cursor=${first.body.data.cursor}`)
+ expect(changes.body.data.derived.avatars[`person:${owner.sub}`]).toBe(link)
+ })
+
+ it('gives no link to someone outside the Swarm or removed from it', async () => {
+ const tab = await swarm()
+ const { avatar } = await upload(tab, image(64))
+ await run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: avatar.id } })
+ const kept = await linkFor(tab, peer, `person:${owner.sub}`)
+ const stranger = await read(tab, outsider)
+ expect(stranger.status).not.toBe(200)
+ expect(stranger.text).not.toContain('avatars.example.test')
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ const removed = await read(tab, peer)
+ expect(removed.status).not.toBe(200)
+ expect(removed.text).not.toContain('avatars.example.test')
+ // What they kept stops opening within the hour.
+ expect(pictures.open(kept!, Date.now() + HOUR + 1)).toBeNull()
+ })
+
+ it('refuses someone else’s upload and a chat file', async () => {
+ const tab = await swarm()
+ const theirs = (await upload(tab, image(64), 'me.png', 'image/png', peer)).avatar
+ await expect(run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: theirs.id } })).rejects.toMatchObject({ code: 'AVATAR_UNAVAILABLE' })
+ const chat = await store.upload(owner, tab, 'lead', { name: 'shot.png', mime: 'image/png', body: (await import('node:stream')).Readable.from([Buffer.from(image(64))]) })
+ await expect(run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: chat.attachment.id } })).rejects.toMatchObject({ code: 'AVATAR_UNAVAILABLE' })
+ expect(await avatarOf(tab, owner.sub)).toBeUndefined()
+ })
+
+ it('lets only one of two commands racing for the same upload take it', async () => {
+ const tab = await swarm()
+ const { avatar } = await upload(tab, image(64))
+ const results = await Promise.allSettled([1, 2].map(() => run(tab, { type: 'member.avatar', avatar: { kind: 'upload', id: avatar.id } })))
+ expect(results.filter(r => r.status === 'fulfilled')).toHaveLength(1)
+ expect(await db.superTabAttachment.findUnique({ where: { id: avatar.id } })).toMatchObject({ usedBy: expect.any(String) })
+ })
+
+ it('without a private avatar bucket, refuses uploads and still takes presets', async () => {
+ const plain = new SuperTabStore(db, Date.now, { store: files, prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })
+ const tab = (await plain.create(owner, randomUUID(), 'No bucket')).id
+ const { Readable } = await import('node:stream')
+ await expect(plain.uploadAvatar(owner, tab, { body: Readable.from([Buffer.from(image(64))]) })).rejects.toMatchObject({ code: 'AVATARS_UNAVAILABLE', status: 503 })
+ await plain.execute(owner, tab, { operationId: randomUUID(), command: { type: 'member.avatar', avatar: { kind: 'preset', key: 'fox' } } })
+ })
+})
+
+describe('reactions', () => {
+ const post = async (tab: string, text = 'Shipped the fix') =>
+ (await run(tab, { type: 'message.send', conversationId: 'lead', text, replyTo: null, recipientIds: [] })).result.messageId as string
+ const react = (tab: string, messageId: string, on: boolean, user = owner, emoji: 'tada' | 'heart' = 'tada', operationId = randomUUID()) =>
+ run(tab, { type: 'message.react', conversationId: 'lead', messageId, emoji, on }, user, undefined, operationId)
+ const page = async (tab: string, user = owner) =>
+ (await read(tab, user, 'conversations/lead/messages')).body.data.messages as Array<{ id: string; reactions: Array<{ emoji: string; count: number }> }>
+ const countsOf = async (tab: string, messageId: string, user = owner) => (await page(tab, user)).find(m => m.id === messageId)!.reactions
+
+ it('adds and removes idempotently, and bumps the group only on a change', async () => {
+ const tab = await swarm()
+ const messageId = await post(tab)
+ const seq = async () => ((await read(tab, owner)).body.data.groups as Array<{ key: string; data: { reactionSeq?: number } }>)
+ .find(g => g.key === 'lead')!.data.reactionSeq ?? 0
+ expect((await react(tab, messageId, true)).result).toMatchObject({ changed: true })
+ expect((await react(tab, messageId, true)).result).toMatchObject({ changed: false })
+ expect(await countsOf(tab, messageId)).toEqual([{ emoji: 'tada', count: 1, by: [{ kind: 'person', id: owner.sub }] }])
+ expect(await seq()).toBe(1)
+ await react(tab, messageId, false)
+ expect((await react(tab, messageId, false)).result).toMatchObject({ changed: false })
+ expect(await countsOf(tab, messageId)).toEqual([])
+ expect(await seq()).toBe(2)
+ })
+
+ it('keeps one row when the same reaction arrives twice at once, and counts two reactors racing', async () => {
+ const tab = await swarm()
+ const messageId = await post(tab)
+ await Promise.all([react(tab, messageId, true), react(tab, messageId, true), react(tab, messageId, true, peer)])
+ expect(await countsOf(tab, messageId)).toMatchObject([{ emoji: 'tada', count: 2 }])
+ expect(await db.superTabReaction.count({ where: { tabId: tab, messageId } })).toBe(2)
+ })
+
+ it('answers a retried operation with its first result', async () => {
+ const tab = await swarm()
+ const messageId = await post(tab)
+ const operationId = randomUUID()
+ const first = await react(tab, messageId, true, owner, 'tada', operationId)
+ expect((await react(tab, messageId, true, owner, 'tada', operationId)).result).toEqual(first.result)
+ })
+
+ it('drops a member who left from the counts, and refuses a reader outside the Swarm', async () => {
+ const tab = await swarm()
+ const messageId = await post(tab)
+ await react(tab, messageId, true, peer, 'heart')
+ await react(tab, messageId, true, owner, 'heart')
+ await run(tab, { type: 'member.remove', userId: peer.sub })
+ expect(await countsOf(tab, messageId)).toEqual([{ emoji: 'heart', count: 1, by: [{ kind: 'person', id: owner.sub }] }])
+ await expect(react(tab, messageId, true, outsider)).rejects.toMatchObject({ status: 403 })
+ await expect(react(tab, messageId, true, peer)).rejects.toMatchObject({ status: 403 })
+ })
+
+ it('tells a poll for new messages that reactions changed, so it reads the page again', async () => {
+ const tab = await swarm()
+ const messageId = await post(tab)
+ const poll = async () => (await read(tab, peer, 'conversations/lead/messages?after=1000000')).body.data as { messages: unknown[]; reactionSeq: number }
+ expect(await poll()).toEqual({ messages: [], next: null, reactionSeq: 0 })
+ await react(tab, messageId, true)
+ expect((await poll()).reactionSeq).toBe(1)
+ })
+
+ it('refuses a message from another conversation or another Swarm', async () => {
+ const tab = await swarm()
+ const other = await swarm()
+ const elsewhere = await post(other)
+ await expect(react(tab, elsewhere, true)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ const group = (await run(tab, { type: 'conversation.create', title: 'Side', brief: 'Side work.', checks: [] })).result.conversationId as string
+ const side = (await run(tab, { type: 'message.send', conversationId: group, text: 'here', replyTo: null, recipientIds: [] })).result.messageId as string
+ await expect(react(tab, side, true)).rejects.toMatchObject({ code: 'NOT_FOUND' })
+ })
+})
+
+describe('the ship moment', () => {
+ const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ it('posts one celebration in the project chat when linked work is Done, waking nobody', async () => {
+ const tab = await swarm()
+ await run(tab, { type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId: randomUUID(), name: 'River', configuration: config, lead: true })
+ const group = (await run(tab, { type: 'conversation.create', title: 'Avatars', brief: 'Add avatars.',
+ checks: [{ description: 'Tests pass', independent: false }] })).result.conversationId as string
+ const builder = (await run(tab, { type: 'agent.add', conversationId: group, machineId: 'host', harnessId: randomUUID(), name: 'Kai',
+ configuration: config, lead: false })).result.agentId as string
+ await run(tab, { type: 'work.assign', conversationId: group, agentId: builder })
+ const state = (await store.read(owner, tab)).state
+ const work = state.conversations.find(c => c.id === group)!
+ await run(tab, { type: 'work.check', conversationId: group, assignmentId: work.assignment!.id, checkId: work.checks[0]!.id, passed: true,
+ evidence: 'npm test: 12 passed' }, owner, builder)
+ const operationId = randomUUID()
+ const done: Command = { type: 'work.status', conversationId: group, assignmentId: work.assignment!.id, status: 'done',
+ result: 'Merged https://github.com/example/app/pull/7' }
+ await run(tab, done, owner, builder, operationId)
+ await run(tab, done, owner, builder, operationId)
+ const rows = await db.superTabMessage.findMany({ where: { tabId: tab, conversationId: 'lead' } })
+ const ships = rows.filter(m => (m.source as { kind?: string } | null)?.kind === 'ship')
+ expect(ships).toHaveLength(1)
+ expect(ships[0]).toMatchObject({ text: '🎉 Shipped: Avatars, requested by owner, built by Kai. https://github.com/example/app/pull/7', recipientIds: [] })
+ expect(await db.superTabDelivery.count({ where: { tabId: tab, messageId: ships[0]!.id } })).toBe(0)
+ })
+})
diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.ts
index 7465d7dd8..05f4cce1c 100644
--- a/backend/integration/superTabs.test.ts
+++ b/backend/integration/superTabs.test.ts
@@ -2696,7 +2696,7 @@ describe('Lead mentions', () => {
const [mention, ...rest] = await list(tab, peer, 'waiting')
expect(rest).toEqual([])
expect(mention).toEqual({ id: expect.any(String), projectId: 'lead', projectName: 'Pilot', conversationId: group, conversationTitle: 'Copy review',
- messageId, leadName: expect.any(String), text: text.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null })
+ messageId, leadId: lead, leadName: expect.any(String), text: text.slice(0, 200), createdAt: expect.any(String), resolvedAt: null, resolvedBy: null })
expect(mention!.leadName).toBe((await waiting(tab, owner)).agents.find(a => a.id === lead)!.displayName)
expect(await list(tab, owner, 'waiting')).toEqual([])
expect(await list(tab, peer, 'earlier')).toEqual([])
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index d0c90f1fd..654fcc427 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -1078,6 +1078,22 @@ model SuperTabMention {
@@index([tabId, conversationId, personId])
}
+/// One reactor's emoji on one message (superTabs/reactions.ts). The id is derived from all four, so adding the same
+/// reaction twice keeps one row; message pages count them.
+model SuperTabReaction {
+ id String @id @map("_id")
+ tabId String
+ conversationId String
+ messageId String
+ /// person | agent
+ actorKind String
+ actorId String
+ emoji String
+ createdAt DateTime @default(now())
+
+ @@index([tabId, messageId])
+}
+
/// A question to one person, with options and a recommendation (backend/src/superTabs/decisions.ts). Kept out of the tab
/// state, as mentions are: an asking agent and the asked person read it, and the person answers it once.
model SuperTabDecision {
@@ -1116,6 +1132,8 @@ model SuperTabAttachment {
size Int
objectKey String
usedBy String?
+ /// `avatar` for a profile picture (superTabs/profile.ts), which no message sends; absent on a chat file.
+ purpose String?
createdAt DateTime @default(now())
@@index([tabId, actorKey, createdAt])
diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts
index 99fcfde83..1f3659c95 100644
--- a/backend/src/config/env.ts
+++ b/backend/src/config/env.ts
@@ -235,6 +235,8 @@ const envSchema = z.object({
SUPER_TAB_ATTACHMENTS_PREFIX: z.string().default('super-tabs'),
// Where clients read the files. https:// in production (superTabs/attachments.ts refuses anything else at startup).
SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: z.string().url().default('https://cdn.harness.autonomous.ai'),
+ // A private bucket (no public read) for Swarm avatars, served only through signed links. Unset: avatar uploads are off.
+ SUPER_TAB_AVATARS_BUCKET: z.string().default(''),
// The Harness GitHub App (github/app.ts, docs/swarm-github-app.md): a Swarm agent doing a task pushes and opens pull
// requests with a one-hour token for its project's repository alone. Both empty: off, and POST
diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.ts
index 9756bd2a0..20c4c7da8 100644
--- a/backend/src/routes/superTabs.ts
+++ b/backend/src/routes/superTabs.ts
@@ -3,7 +3,7 @@ import { z } from 'zod'
import { prisma } from '../lib/prisma.js'
import { env } from '../config/env.js'
import multipart from '@fastify/multipart'
-import { attachmentsFromEnv, MAX_ATTACHMENT_BYTES } from '../superTabs/attachments.js'
+import { attachmentsFromEnv, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES } from '../superTabs/attachments.js'
import { validateBody, validateParams, validateQuery } from '../middlewares/validation.js'
import { sendError, sendSuccess } from '../utils/response.js'
import { operationSchema } from '../superTabs/commands.js'
@@ -243,6 +243,27 @@ export async function superTabRoutes(app: FastifyInstance, options: { store?: Su
return uploaded ?? fail('INVALID_ATTACHMENT', 'Attach one file.', 400)
}))
})
+ // An avatar picture (superTabs/profile.ts) comes the same way, alone in its form; the command that sets it names whose it is.
+ await app.register(async scope => {
+ await scope.register(multipart, { limits: { fileSize: MAX_AVATAR_BYTES + 1, files: 1, fields: 0, parts: 1 } })
+ scope.post<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof agentQuery> }>('/api/super-tabs/:tabId/avatars',
+ { preHandler: [validateParams(tabParams), validateQuery(agentQuery)] }, (req, reply) => respond(reply, async () => {
+ let uploaded: unknown = null, stored: unknown = null
+ try {
+ for await (const part of req.parts()) {
+ if (part.type === 'field' || uploaded) { if (part.type === 'file') part.file.resume(); fail('INVALID_AVATAR', 'Send one picture.', 400) }
+ try { uploaded = await store.uploadAvatar(req.user!, req.params.tabId, { body: part.file }, req.query.asAgentId) }
+ catch (error) { stored = error; throw error } finally { part.file.resume() }
+ }
+ } catch (error) {
+ const code = error && typeof error === 'object' && 'code' in error ? error.code : null
+ if (code === 'FST_REQ_FILE_TOO_LARGE') fail('AVATAR_TOO_LARGE', 'An avatar can be at most 1 MB.', 413)
+ if (error instanceof SuperTabError || (error === stored && !(code && String(code).startsWith('FST_')))) throw error
+ fail('INVALID_AVATAR', 'Send a multipart form with one picture.', 400)
+ }
+ return uploaded ?? fail('INVALID_AVATAR', 'Send one picture.', 400)
+ }))
+ })
app.get<{ Params: z.infer<typeof tabParams>; Querystring: z.infer<typeof mentionQuery> }>('/api/super-tabs/:tabId/mentions',
{ preHandler: [validateParams(tabParams), validateQuery(mentionQuery)] },
(req, reply) => respond(reply, () => store.mentions(req.user!, req.params.tabId, req.query.state)))
diff --git a/backend/src/superTabs/attachments.test.ts b/backend/src/superTabs/attachments.test.ts
index a002c72cb..6e0754d3e 100644
--- a/backend/src/superTabs/attachments.test.ts
+++ b/backend/src/superTabs/attachments.test.ts
@@ -1,14 +1,14 @@
import { generateKeyPairSync } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { Readable } from 'node:stream'
-import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, imageTypeOf, GcsAttachmentStore, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom } from './attachments.js'
+import { AttachmentTooLarge, attachmentName, attachmentsFromEnv, checkedType, imageTypeOf, GcsAttachmentStore, GcsAvatarStore, MemoryAttachmentStore, objectKeyFor, served, serviceAccountFrom } from './attachments.js'
const { privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 })
const key = { type: 'service_account', project_id: 'harness-test', client_email: '[email protected]',
private_key: privateKey.export({ type: 'pkcs8', format: 'pem' }).toString() }
const encoded = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('base64')
-const env = (credentials: string, bucket = 'attachments') => ({ NODE_ENV: 'test', SUPER_TAB_ATTACHMENTS_BUCKET: bucket, SUPER_TAB_ATTACHMENTS_CREDENTIALS: credentials,
- SUPER_TAB_ATTACHMENTS_PREFIX: 'super-tabs', SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'https://cdn.example.test' })
+const env = (credentials: string, bucket = 'attachments', avatars = '') => ({ NODE_ENV: 'test', SUPER_TAB_ATTACHMENTS_BUCKET: bucket, SUPER_TAB_ATTACHMENTS_CREDENTIALS: credentials,
+ SUPER_TAB_ATTACHMENTS_PREFIX: 'super-tabs', SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: 'https://cdn.example.test', SUPER_TAB_AVATARS_BUCKET: avatars })
describe('attachment bucket credentials', () => {
it('decodes a base64 service account key, also wrapped over lines', () => {
@@ -50,6 +50,21 @@ describe('attachment bucket credentials', () => {
expect(attachmentsFromEnv({ ...env(''), NODE_ENV: 'production' })?.publicBase).toBe('https://cdn.example.test')
})
+ it('keeps avatars off without a private bucket, and never in the public one', () => {
+ expect(attachmentsFromEnv(env(encoded(key)))?.avatars).toBeNull()
+ expect(attachmentsFromEnv(env(encoded(key), 'attachments', 'avatars'))?.avatars).toBeInstanceOf(GcsAvatarStore)
+ })
+
+ it('signs an avatar link with the configured key, for a limited time, without a network call', async () => {
+ const avatars = attachmentsFromEnv(env(encoded(key), 'attachments', 'avatars'))!.avatars!
+ const expires = Date.now() + 3_600_000
+ const link = new URL(await avatars.signedUrl('super-tabs/tab/0123/avatar', expires))
+ expect(link.host).toBe('storage.googleapis.com')
+ expect(link.pathname).toBe('/avatars/super-tabs/tab/0123/avatar')
+ expect(link.searchParams.get('X-Goog-Credential')).toContain(key.client_email)
+ expect(Number(link.searchParams.get('X-Goog-Expires'))).toBeLessThanOrEqual(3600)
+ })
+
it('builds the storage client from the configured key, without a network call', async () => {
const store = attachmentsFromEnv(env(encoded(key)))!.store as GcsAttachmentStore
const bucket = await (store as unknown as { files(): Promise<import('@google-cloud/storage').Bucket> }).files()
diff --git a/backend/src/superTabs/attachments.ts b/backend/src/superTabs/attachments.ts
index 545621da8..da61e52ba 100644
--- a/backend/src/superTabs/attachments.ts
+++ b/backend/src/superTabs/attachments.ts
@@ -1,4 +1,4 @@
-import { randomBytes } from 'node:crypto'
+import { createHmac, randomBytes } from 'node:crypto'
import { Readable, Transform, Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { z } from 'zod'
@@ -8,13 +8,18 @@ export interface Attachment { id: string; name: string; mime: string; size: numb
export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
export const MAX_ATTACHMENTS = 10
+/** An avatar is a small picture: Desktop resizes it before upload, and the backend still holds it to this. */
+export const MAX_AVATAR_BYTES = 1024 * 1024
+export const AVATAR_TYPES: ReadonlySet<string> = new Set(['image/png', 'image/jpeg', 'image/webp'])
+/** The `purpose` of an avatar upload (schema.prisma SuperTabAttachment): never sendable as a chat file. */
+export const AVATAR_PURPOSE = 'avatar'
// Control, format (bidi overrides, zero-width) and line/paragraph separators: a name that hides its real shape.
export const attachmentName = z.string().trim().min(1).max(255).refine(value => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value), 'Use a printable file name.')
export const attachmentMime = z.string().trim().toLowerCase().max(200).regex(/^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/)
export class AttachmentTooLarge extends Error {
- constructor() { super(`A file can be at most ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB.`) }
+ constructor(cap = MAX_ATTACHMENT_BYTES) { super(`A file can be at most ${cap / 1024 / 1024} MB.`) }
}
/** The bucket behind the CDN. Tests and the local rig use the in-memory store below. */
@@ -22,7 +27,13 @@ export interface AttachmentStore {
/** Streams `body` into the object and answers its size. Past `cap` bytes it throws AttachmentTooLarge and leaves no object. */
put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number): Promise<number>
}
-export interface Attachments { store: AttachmentStore; prefix: string; publicBase: string }
+/** The private bucket avatars are kept in: nobody reads an object without a link the server signed (avatarLinks.ts). */
+export interface AvatarStore extends AttachmentStore {
+ /** A link that opens [objectKey] until [expiresAt] (epoch ms), and never after. */
+ signedUrl(objectKey: string, expiresAt: number): Promise<string>
+}
+/** `avatars`: the private avatar bucket; without one, avatar uploads are refused and presets still work. */
+export interface Attachments { store: AttachmentStore; prefix: string; publicBase: string; avatars?: AvatarStore | null }
/** Anyone holding a link can open the file, so the key carries 128 random bits; the name segment is for people. */
export function objectKeyFor(prefix: string, tabId: string, name: string): string {
@@ -51,11 +62,9 @@ export function imageTypeOf(head: Buffer): string | null {
return null
}
-/** A file that claims to be an image is served as one only when its first bytes agree, and then as what they say: a
- * renamed page or script never opens inline, and a .png that is really a JPEG still shows. `body` is handed back with
- * those bytes in front, so the store still reads the whole file as a stream. */
-export async function checkedType(mime: string, body: Readable): Promise<{ mime: string; body: Readable }> {
- if (!INLINE.has(mime)) return { mime, body }
+/** The raster type `body`'s first bytes are, or null, and `body` handed back with those bytes in front, so the store
+ * still reads the whole file as a stream. */
+export async function peekType(body: Readable): Promise<{ type: string | null; body: Readable }> {
// One iterator for the whole read: leaving a `for await` early would destroy the request stream.
const source = body[Symbol.asyncIterator]()
const parts: Buffer[] = []
@@ -74,7 +83,15 @@ export async function checkedType(mime: string, body: Readable): Promise<{ mime:
yield Buffer.from(next.value)
}
}
- return { mime: imageTypeOf(head) ?? 'application/octet-stream', body: Readable.from(rest()) }
+ return { type: imageTypeOf(head), body: Readable.from(rest()) }
+}
+
+/** A file that claims to be an image is served as one only when its first bytes agree, and then as what they say: a
+ * renamed page or script never opens inline, and a .png that is really a JPEG still shows. */
+export async function checkedType(mime: string, body: Readable): Promise<{ mime: string; body: Readable }> {
+ if (!INLINE.has(mime)) return { mime, body }
+ const peeked = await peekType(body)
+ return { mime: peeked.type ?? 'application/octet-stream', body: peeked.body }
}
/** Counts what passes and fails the stream past `cap`, so a writer never commits more. */
@@ -82,7 +99,7 @@ async function capped(body: Readable, cap: number, sink: Writable): Promise<numb
let size = 0
await pipeline(body, new Transform({ transform(chunk: Buffer, _encoding, done) {
size += chunk.byteLength
- done(size > cap ? new AttachmentTooLarge() : null, chunk)
+ done(size > cap ? new AttachmentTooLarge(cap) : null, chunk)
} }), sink)
return size
}
@@ -108,9 +125,10 @@ export function serviceAccountFrom(raw: string): ServiceAccount | null {
export class GcsAttachmentStore implements AttachmentStore {
private bucket: Promise<import('@google-cloud/storage').Bucket> | null = null
- constructor(private readonly name: string, private readonly account: ServiceAccount | null = null) {}
+ constructor(private readonly name: string, private readonly account: ServiceAccount | null = null,
+ private readonly cacheControl = 'public, max-age=31536000, immutable') {}
// Loaded on first use, so a backend without a bucket never loads the client.
- private files() {
+ protected files() {
this.bucket ??= import('@google-cloud/storage').then(({ Storage }) => new Storage(this.account ?? undefined).bucket(this.name))
return this.bucket
}
@@ -118,11 +136,20 @@ export class GcsAttachmentStore implements AttachmentStore {
const { contentType, contentDisposition } = served(file.name, file.mime)
// One request, not a resumable session: a failed or refused stream aborts it and no object is written.
const sink = (await this.files()).file(objectKey).createWriteStream({ resumable: false, contentType,
- metadata: { contentDisposition, cacheControl: 'public, max-age=31536000, immutable' } })
+ metadata: { contentDisposition, cacheControl: this.cacheControl } })
return capped(body, cap, sink)
}
}
+/** Avatars in a bucket that grants nobody read access: each read hands out V4 signed links instead (avatarLinks.ts). */
+export class GcsAvatarStore extends GcsAttachmentStore implements AvatarStore {
+ constructor(name: string, account: ServiceAccount | null = null) { super(name, account, 'private, max-age=3600') }
+ async signedUrl(objectKey: string, expiresAt: number) {
+ const [url] = await (await this.files()).file(objectKey).getSignedUrl({ version: 'v4', action: 'read', expires: expiresAt })
+ return url
+ }
+}
+
export class MemoryAttachmentStore implements AttachmentStore {
readonly objects = new Map<string, { bytes: Buffer; contentType: string; contentDisposition: string }>()
async put(objectKey: string, file: { name: string; mime: string }, body: Readable, cap: number) {
@@ -133,8 +160,26 @@ export class MemoryAttachmentStore implements AttachmentStore {
}
}
+/** Avatars for tests and the local rig: links carry their expiry and an HMAC of it, and `open` honours both as the bucket would. */
+export class MemoryAvatarStore extends MemoryAttachmentStore implements AvatarStore {
+ private readonly secret = randomBytes(32)
+ constructor(private readonly base: string) { super() }
+ private sign(objectKey: string, expiresAt: number) {
+ return createHmac('sha256', this.secret).update(`${objectKey}\n${expiresAt}`).digest('hex')
+ }
+ async signedUrl(objectKey: string, expiresAt: number) {
+ return `${this.base}/${objectKey}?expires=${expiresAt}&signature=${this.sign(objectKey, expiresAt)}`
+ }
+ /** What the bucket answers [url] at [now]: the bytes, or null once the link is over or was not signed here. */
+ open(url: string, now: number): Buffer | null {
+ const link = new URL(url), objectKey = decodeURIComponent(link.pathname.slice(1)), expiresAt = Number(link.searchParams.get('expires'))
+ if (!(expiresAt > now) || link.searchParams.get('signature') !== this.sign(objectKey, expiresAt)) return null
+ return this.objects.get(objectKey)?.bytes ?? null
+ }
+}
+
export function attachmentsFromEnv(env: { NODE_ENV: string; SUPER_TAB_ATTACHMENTS_BUCKET: string; SUPER_TAB_ATTACHMENTS_CREDENTIALS: string;
- SUPER_TAB_ATTACHMENTS_PREFIX: string; SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: string }): Attachments | null {
+ SUPER_TAB_ATTACHMENTS_PREFIX: string; SUPER_TAB_ATTACHMENTS_PUBLIC_BASE: string; SUPER_TAB_AVATARS_BUCKET: string }): Attachments | null {
// Every message carries these links and every agent's computer downloads from them: in production only over HTTPS.
// A local or test run may serve them from a plain loopback server.
if (env.NODE_ENV === 'production' && new URL(env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE).protocol !== 'https:') {
@@ -143,6 +188,8 @@ export function attachmentsFromEnv(env: { NODE_ENV: string; SUPER_TAB_ATTACHMENT
// Read even without a bucket, so a broken key fails the deploy that set it rather than the one that adds the bucket.
const account = serviceAccountFrom(env.SUPER_TAB_ATTACHMENTS_CREDENTIALS)
if (!env.SUPER_TAB_ATTACHMENTS_BUCKET) return null
+ // Avatars are member-only, so never the public attachments bucket: without a private one, uploads stay off.
return { store: new GcsAttachmentStore(env.SUPER_TAB_ATTACHMENTS_BUCKET, account), prefix: env.SUPER_TAB_ATTACHMENTS_PREFIX,
- publicBase: env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE }
+ publicBase: env.SUPER_TAB_ATTACHMENTS_PUBLIC_BASE,
+ avatars: env.SUPER_TAB_AVATARS_BUCKET ? new GcsAvatarStore(env.SUPER_TAB_AVATARS_BUCKET, account) : null }
}
diff --git a/backend/src/superTabs/avatarLinks.ts b/backend/src/superTabs/avatarLinks.ts
new file mode 100644
index 000000000..decf6d699
--- /dev/null
+++ b/backend/src/superTabs/avatarLinks.ts
@@ -0,0 +1,34 @@
+import type { AvatarStore } from './attachments.js'
+import type { Avatar } from './profile.js'
+import type { SuperTabState } from './model.js'
+
+/** A link is the same through each half hour, so a picture is fetched once in it rather than on every poll, and lasts an
+ * hour from that half hour's start: a copied link stops opening within an hour, and a member removed gets no new one. */
+export const AVATAR_LINK_WINDOW_MS = 30 * 60_000
+export const AVATAR_LINK_TTL_MS = 60 * 60_000
+export const avatarLinkExpiry = (now: number) => Math.floor(now / AVATAR_LINK_WINDOW_MS) * AVATAR_LINK_WINDOW_MS + AVATAR_LINK_TTL_MS
+
+/** Signs at most once per picture and window: signing may call the cloud (IAM signBlob) without a key of our own. */
+export class AvatarLinks {
+ private readonly signed = new Map<string, string>()
+ constructor(private readonly bucket: AvatarStore) {}
+
+ /** A member read's links, by `person:<id>` and `agent:<id>`, for the people and agents it can see that have uploads. */
+ async forReader(state: Pick<SuperTabState, 'people'>, agents: Array<{ id: string; avatar?: Avatar }>, now: number): Promise<Record<string, string>> {
+ const expiresAt = avatarLinkExpiry(now)
+ const holders = [...state.people.map(p => [`person:${p.id}`, p.avatar] as const), ...agents.map(a => [`agent:${a.id}`, a.avatar] as const)]
+ const links = await Promise.all(holders.flatMap(([who, avatar]) =>
+ avatar?.kind === 'upload' ? [this.link(avatar.key, expiresAt).then(url => [who, url] as const)] : []))
+ return Object.fromEntries(links)
+ }
+
+ private async link(objectKey: string, expiresAt: number): Promise<string> {
+ const cached = this.signed.get(`${objectKey}@${expiresAt}`)
+ if (cached) return cached
+ const url = await this.bucket.signedUrl(objectKey, expiresAt)
+ // Links of past windows are never asked again.
+ for (const key of this.signed.keys()) if (!key.endsWith(`@${expiresAt}`)) this.signed.delete(key)
+ this.signed.set(`${objectKey}@${expiresAt}`, url)
+ return url
+ }
+}
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 54b3edf69..f81992d49 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -20,6 +20,9 @@ import { credentialResult, redactCredentials, type CredentialKind } from './cred
import { dirtyGroups, reportGroups, summarize } from './projectUpdates.js'
import { LEDGER_WEEKS, PULL_REQUEST_URL, recordAnswer, recordAsked, recordMerged, recordReview, recordRun, recordStatus } from './leaderboard/record.js'
import { WEEK_MS } from './leaderboard/week.js'
+import { react, reactionSchema, type ReactionTarget } from './reactions.js'
+import { shipNotice, shippedAt } from './ship.js'
+import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'
import { agentKind, agentProjectId, audienceOf, agentSetRole, canReadProject, deleteProject, markConfidential, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectMembers, projectOf, projectRules, projectsOf, readAgent, readConversation, readProject, roleVersion, sameProject, sharedWithLeads, SKILL_SET_NAMES, skillSetOf, type ProjectRole, type RoleKind, type SwarmProject } from './projects.js'
const id = z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/)
@@ -136,10 +139,14 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('invite.revoke'), inviteId: id }).strict(),
z.object({ type: z.literal('invite.accept'), inviteId: id }).strict(),
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('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),
attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(), agentOnly: z.literal(true).optional() }).strict(),
z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),
+ z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean() }).strict(),
z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),
z.object({ type: z.literal('decision.answer'), decisionId: id, choice: z.number().int().min(0), note: z.string().trim().min(1).max(2000).optional() }).strict(),
z.object({ type: z.literal('delivery.resolve'), deliveryId: id, resolution: z.enum(['received', 'resend', 'cancel']) }).strict(),
@@ -175,6 +182,7 @@ export const operationSchema = z.object({ operationId: id, command: commandSchem
* chat row is redacted (terminal.ts). Not a role's skill text, which only its project's owner, Lead and hosts read. */
const WORDS: Partial<Record<Command['type'], readonly string[]>> = {
'message.send': ['text'],
+ 'member.status': ['status.text'],
'agent.add': ['name', 'initialMessage'],
'agent.start': ['request.name', 'overrideReason'],
'agent.startFailed': ['error'],
@@ -244,6 +252,10 @@ export interface CommandContext {
delivery?: { id: string; conversationId: string; agentId: string; messageId: string; text: string; attachments?: Attachment[] }
/** The files `message.send` names, each checked by the store: uploaded by this actor to this conversation, and unused. */
attachments?: Attachment[]
+ /** The avatar upload `member.avatar` or `agent.avatar` names, checked by the store the same way (profile.ts). */
+ avatarUpload?: AvatarUpload
+ /** The message `message.react` names, read by the store (reactions.ts). */
+ reaction?: ReactionTarget
/** Route decisions this tab recorded in the last hour, counted by the store. */
/** The decision a command names, read from SuperTabRouteDecision by the store. */
routeDecision?: RouteDecision
@@ -1479,6 +1491,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
owner(state, actor)
state.invitations = state.invitations.filter(i => i.id !== command.inviteId)
break
+ case 'member.status':
+ setStatus(state, actor, command.status, context.now)
+ break
+ case 'message.react':
+ result.changed = react(postable(state, actor, command.conversationId), command.messageId, command.on, context.reaction)
+ break
+ case 'member.avatar':
+ setMemberAvatar(state, actor, command.avatar, context.avatarUpload)
+ break
+ case 'agent.avatar':
+ setAgentAvatar(state, actor, command.agentId, command.avatar, context.avatarUpload)
+ break
case 'member.remove': {
if (actor.kind !== 'person' || (actor.userId !== state.ownerId && actor.userId !== command.userId)) {
fail('FORBIDDEN', 'Only the owner can remove another person.', 403)
@@ -1734,6 +1758,12 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
(actor.kind !== 'agent' || id !== actor.agentId) && state.agents.some(a => a.id === id && agentRole(a) === 'reviewer' && a.workDecision !== 'stop'))
const asked = command.ask ? `\n\nAsked ${person(state, command.ask.personId).email}.` : ''
message(group.id, `${label}${command.result ? `\n\n${command.result}` : ''}${asked}`, [...(tellLead ? [lead] : []), ...reviewers], null, SYSTEM_ROW)
+ // Shipped before this command: the leaderboard marks this Done as shipped just above (recordStatus).
+ if (command.status === 'done' && shippedAt(conversation(original, group.id)) == null) {
+ appendPullRequestUrls(group, [command.result, ...group.checks.map(check => check.evidence)])
+ const shipped = shipNotice(state, group, sender, operationId)
+ if (shipped) effects.messages.push(shipped)
+ }
}
if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)
break
diff --git a/backend/src/superTabs/mentions.ts b/backend/src/superTabs/mentions.ts
index 8df0db9b8..2f0d46f52 100644
--- a/backend/src/superTabs/mentions.ts
+++ b/backend/src/superTabs/mentions.ts
@@ -94,7 +94,7 @@ export async function listMentions(tx: Tx, tabId: string, state: SuperTabState,
const author = message?.author as { name?: string; displayName?: string } | undefined
return { id: row.id, projectId: row.projectId, projectName: projectOf(state, group.projectId ?? 'lead').name,
conversationId: row.conversationId, conversationTitle: group.title, messageId: row.messageId,
- leadName: author?.displayName ?? author?.name ?? 'Lead', text: (message?.text ?? '').slice(0, 200),
+ leadId: row.authorAgentId, leadName: author?.displayName ?? author?.name ?? 'Lead', text: (message?.text ?? '').slice(0, 200),
createdAt: row.createdAt, resolvedAt: row.resolvedAt, resolvedBy: row.resolvedBy }
})
}
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 7337c996b..d0ddec7d1 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -1,12 +1,22 @@
import { createHash } from 'node:crypto'
import type { RouteDecisionEffect } from './routeRecord.js'
import { agentDisplayName, assignAgentDisplayNames } from './agentNames.js'
+import { withAvatarView } from './profile.js'
import { downSince, expireRemovals } 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'
export type Role = 'owner' | 'collaborator' | 'viewer'
-export interface Person { id: string; email: string; role: Role; generation: string }
+export interface Person {
+ id: string
+ email: string
+ role: Role
+ generation: string
+ /** Their own short status (profile.ts); only Swarm members read it. */
+ status?: import('./profile.js').PersonStatus
+ /** Their own avatar (profile.ts); only Swarm members read it. */
+ avatar?: import('./profile.js').Avatar
+}
export interface AgentConfiguration {
engine: string
model: string | null
@@ -62,6 +72,8 @@ export interface Agent {
/** Set once its session is a Lead or in a private conversation, and kept until the session leaves: nobody but its
* machine's person watches it (projects.ts canWatchAgent). */
confidential?: true
+ /** Set by its contributor or its project's Lead (profile.ts); absent shows the pattern Desktop draws from its name. */
+ avatar?: import('./profile.js').Avatar
}
export type AgentRole = 'builder' | 'reviewer'
export const agentRole = (agent: Pick<Agent, 'role'>): AgentRole => agent.role ?? 'builder'
@@ -192,6 +204,8 @@ export interface Conversation {
/** The last attempt here that was lost: its agent's status and checks for it are refused, even after reassignment. Where it
* ran (machine and engine) stays too, so routing the work again avoids that account even once its agent is gone. */
lostAttempt?: { id: string; agentId: string; machineId?: string; engine?: string }
+ /** Counts reaction changes here (reactions.ts), so readers see a new reaction on an older message. */
+ reactionSeq?: number
/** The person who asked for this work: whoever opened it, or the person its Lead named (leaderboard/record.ts). */
requesterId?: string
/** What the leaderboard counts here (leaderboard/record.ts); bookkeeping readers never get whole. */
@@ -533,6 +547,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 signed link with each parts read (avatarLinks.ts).
+ visible.people = visible.people.map(withAvatarView) 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) {
const home = projectsOf(state).find(p => p.id === agentProjectId(state, target))
diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.ts
index d2476a3c0..084349b92 100644
--- a/backend/src/superTabs/parts/light.test.ts
+++ b/backend/src/superTabs/parts/light.test.ts
@@ -12,7 +12,7 @@ const assignment: Required<Assignment> = {
const conversation: Required<Conversation> = {
id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',
task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, pullRequestUrls: [],
- messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' },
+ messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,
requesterId: 'p', ledger: {},
}
diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.ts
index 54b97b7e5..68f0eec23 100644
--- a/backend/src/superTabs/parts/light.ts
+++ b/backend/src/superTabs/parts/light.ts
@@ -26,7 +26,7 @@ export const GROUP_FIELDS = {
always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status',
'assignment.lost'],
whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],
- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger',
+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq',
'assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt'],
} as const
const LIGHT_GROUP = {
diff --git a/backend/src/superTabs/parts/touches.test.ts b/backend/src/superTabs/parts/touches.test.ts
index 2209bb9da..790389a39 100644
--- a/backend/src/superTabs/parts/touches.test.ts
+++ b/backend/src/superTabs/parts/touches.test.ts
@@ -38,6 +38,13 @@ describe('the parts a command touches (design section 1.2, column T)', () => {
expect(has(f.run({ type: 'message.send', conversationId: a.id, text: 'Hi', replyTo: null, recipientIds: [] }, f.agentActor(a.worker)).touches, 'agent', a.worker)).toBe(true)
})
+ it('makes a Lead\'s change to an agent\'s avatar meet on the Lead conversation its check reads', () => {
+ const f = swarm(), a = f.group('A')
+ const { touches } = f.run({ type: 'agent.avatar', agentId: a.worker, avatar: { kind: 'preset', key: 'owl' } }, f.agentActor(f.lead))
+ expect(has(touches, 'group', 'lead')).toBe(true)
+ expect(has(touches, 'agent', a.worker)).toBe(true)
+ })
+
it('leaves a post\'s recipients alone, so workers posting to their Lead in different groups never meet on the Lead', () => {
const f = swarm(), a = f.group('A')
const { effects, touches } = f.run({ type: 'message.send', conversationId: a.id, text: 'Report', replyTo: null, recipientIds: [] }, f.agentActor(a.worker))
diff --git a/backend/src/superTabs/parts/touches.ts b/backend/src/superTabs/parts/touches.ts
index f40a56b12..48579621d 100644
--- a/backend/src/superTabs/parts/touches.ts
+++ b/backend/src/superTabs/parts/touches.ts
@@ -54,6 +54,9 @@ export function touchesFor(command: Command, actor: Actor, before: SuperTabState
case 'machine.contribute':
if (!before.machines?.some(m => m.machineId === command.machineId)) head()
break
+ case 'agent.avatar':
+ leadCheck(agentProject(command.agentId))
+ break
case 'project.report': case 'project.repository': case 'project.skills':
leadCheck(command.projectId)
break
diff --git a/backend/src/superTabs/profile.test.ts b/backend/src/superTabs/profile.test.ts
new file mode 100644
index 000000000..43f13dca5
--- /dev/null
+++ b/backend/src/superTabs/profile.test.ts
@@ -0,0 +1,123 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, visibleState, 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 stranger: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'stranger', email: '[email protected]' }
+const NOW = Date.parse('2026-10-27T09:00:00.000Z')
+
+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 invite = (role: 'viewer' | 'collaborator' = 'collaborator') => {
+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ }
+ const member = (id: string) => state.people.find(p => p.id === id)
+ return { run, invite, member, get state() { return state } }
+}
+
+describe('status line', () => {
+ it('sets and clears the person’s own status', () => {
+ const f = fixture()
+ f.run({ type: 'member.status', status: { text: ' Out until 2pm ', emoji: '🌴', until: '2026-10-27T14:00:00.000Z' } })
+ expect(f.member('owner')!.status).toEqual({ text: 'Out until 2pm', emoji: '🌴', until: '2026-10-27T14:00:00.000Z' })
+ f.run({ type: 'member.status', status: { text: 'Focus' } })
+ expect(f.member('owner')!.status).toEqual({ text: 'Focus', emoji: null, until: null })
+ f.run({ type: 'member.status', status: null })
+ expect(f.member('owner')!.status).toBeUndefined()
+ })
+
+ it('refuses a status that is too long, unprintable, already over or set as an agent', () => {
+ const f = fixture()
+ expect(() => f.run({ type: 'member.status', status: { text: 'x'.repeat(81) } })).toThrow()
+ expect(() => f.run({ type: 'member.status', status: { text: 'Focus‮' } })).toThrow()
+ expect(() => f.run({ type: 'member.status', status: { text: 'Lunch', emoji: '💣' } } as unknown as Command)).toThrow()
+ expect(() => f.run({ type: 'member.status', status: { text: 'Lunch', until: '2026-10-27T08:59:59.000Z' } }))
+ .toThrow(expect.objectContaining({ code: 'STATUS_EXPIRED' }))
+ expect(() => f.run({ type: 'member.status', status: { text: 'Lunch' } }, { kind: 'agent', agentId: 'a1', machineOwnerId: 'owner' })).toThrow()
+ expect(f.member('owner')!.status).toBeUndefined()
+ })
+
+ it('keeps a credential out of the status', () => {
+ const f = fixture()
+ const effects = f.run({ type: 'member.status', status: { text: 'key ghp_R4nd0mT0k3nV4lu3Xq9Lp2Zs8Wd5Yb7Hc1Jk6Mn' } })
+ expect(f.member('owner')!.status!.text).not.toContain('ghp_R4nd0m')
+ expect(effects.result.credentialsRemoved).toBeTruthy()
+ })
+
+ it('is refused for a viewer and read only by members', () => {
+ const f = fixture()
+ f.invite('viewer')
+ expect(() => f.run({ type: 'member.status', status: { text: 'Coffee', emoji: '☕' } }, peer))
+ .toThrow(expect.objectContaining({ code: 'READ_ONLY' }))
+ f.run({ type: 'member.status', status: { text: 'Coffee', emoji: '☕' } })
+ expect(visibleState(f.state, peer).people.find(p => p.id === 'owner')!.status!.text).toBe('Coffee')
+ expect(() => visibleState(f.state, stranger)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ })
+})
+
+describe('avatars', () => {
+ const upload = { id: 'u1', key: 'avatars/tab/0123abcd/avatar' }
+ const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+ const agentFixture = () => {
+ const f = fixture()
+ f.invite()
+ const add = (harnessId: string, contributor: Extract<Actor, { kind: 'person' }>, lead = false) =>
+ f.run({ type: 'agent.add', conversationId: 'lead', machineId: 'host', harnessId, name: harnessId, configuration: config, lead }, contributor,
+ { contribution: { machineOwnerId: 'host-owner', contributorId: contributor.userId } }).result.agentId as string
+ const lead = add('lead-h', owner, true)
+ const worker = add('worker-h', peer)
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ return Object.assign(f, { lead, worker, as })
+ }
+
+ it('lets a person pick a preset, use their upload, and clear it', () => {
+ const f = fixture()
+ f.run({ type: 'member.avatar', avatar: { kind: 'preset', key: 'fox' } })
+ expect(f.member('owner')!.avatar).toEqual({ kind: 'preset', key: 'fox' })
+ f.run({ type: 'member.avatar', avatar: { kind: 'upload', id: 'u1' } }, owner, { avatarUpload: upload })
+ expect(f.member('owner')!.avatar).toEqual({ kind: 'upload', key: upload.key })
+ f.run({ type: 'member.avatar', avatar: null })
+ expect(f.member('owner')!.avatar).toBeUndefined()
+ })
+
+ it('refuses an upload the store did not find for this actor, and an unknown preset', () => {
+ const f = fixture()
+ expect(() => f.run({ type: 'member.avatar', avatar: { kind: 'upload', id: 'u1' } })).toThrow(expect.objectContaining({ code: 'AVATAR_UNAVAILABLE' }))
+ expect(() => f.run({ type: 'member.avatar', avatar: { kind: 'preset', key: 'https://evil.example/x.png' } } as unknown as Command)).toThrow()
+ expect(f.member('owner')!.avatar).toBeUndefined()
+ })
+
+ it('lets the project’s Lead or the agent’s contributor change an agent’s avatar, nobody else', () => {
+ const f = agentFixture()
+ const avatarOf = (id: string) => f.state.agents.find(a => a.id === id)!.avatar
+ f.run({ type: 'agent.avatar', agentId: f.worker, avatar: { kind: 'preset', key: 'owl' } }, f.as(f.lead))
+ expect(avatarOf(f.worker)).toEqual({ kind: 'preset', key: 'owl' })
+ f.run({ type: 'agent.avatar', agentId: f.worker, avatar: { kind: 'upload', id: 'u1' } }, peer, { avatarUpload: upload })
+ expect(avatarOf(f.worker)).toEqual({ kind: 'upload', key: upload.key })
+ expect(() => f.run({ type: 'agent.avatar', agentId: f.lead, avatar: { kind: 'preset', key: 'cat' } }, peer))
+ .toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(() => f.run({ type: 'agent.avatar', agentId: f.worker, avatar: { kind: 'preset', key: 'cat' } }, f.as(f.worker)))
+ .toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ f.run({ type: 'agent.avatar', agentId: f.worker, avatar: null }, f.as(f.lead))
+ expect(avatarOf(f.worker)).toBeUndefined()
+ })
+
+ it('shows avatars to members only', () => {
+ const f = agentFixture()
+ f.run({ type: 'member.avatar', avatar: { kind: 'upload', id: 'u1' } }, owner, { avatarUpload: upload })
+ f.run({ type: 'agent.avatar', agentId: f.worker, avatar: { kind: 'upload', id: 'u1' } }, peer, { avatarUpload: upload })
+ const seen = visibleState(f.state, peer)
+ // Readers learn there is a picture; its stored key stays on the server, and a link comes only signed (avatarLinks.ts).
+ expect(seen.people.find(p => p.id === 'owner')!.avatar).toEqual({ kind: 'upload' })
+ expect(seen.agents.find(a => a.id === f.worker)!.avatar).toEqual({ kind: 'upload' })
+ expect(() => visibleState(f.state, stranger)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ })
+})
diff --git a/backend/src/superTabs/profile.ts b/backend/src/superTabs/profile.ts
new file mode 100644
index 000000000..a1be7d554
--- /dev/null
+++ b/backend/src/superTabs/profile.ts
@@ -0,0 +1,73 @@
+import { z } from 'zod'
+import { agent, fail, person, type Actor, type SuperTabState } from './model.js'
+import { agentProjectId, ledProject } from './projects.js'
+
+/** The emoji a status may wear. Desktop offers each with its words (focus, coffee, lunch, out, away, sick). */
+export const STATUS_EMOJI = ['🎯', '☕', '🍽️', '🌴', '🚶', '🤒'] as const
+export const MAX_STATUS_LENGTH = 80
+
+/** A person's short status, shown beside their avatar until `until` passes; then readers drop it. */
+export interface PersonStatus { text: string; emoji: (typeof STATUS_EMOJI)[number] | null; until: string | null }
+
+// Control, format (bidi overrides, zero-width) and line/paragraph separators: words that hide their real shape.
+const printable = (value: string) => !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value)
+export const statusSchema = z.object({
+ text: z.string().trim().min(1).max(MAX_STATUS_LENGTH).refine(printable, 'Use printable words.'),
+ emoji: z.enum(STATUS_EMOJI).nullable().optional(),
+ until: z.iso.datetime().nullable().optional(),
+}).strict()
+
+/** `member.status`: a person sets or clears their own status. Members read it with the rest of the Swarm, nobody else. */
+export function setStatus(state: SuperTabState, actor: Actor, status: z.infer<typeof statusSchema> | null, now: number): void {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'Only a person has a status.', 403)
+ const member = person(state, actor.userId)
+ if (!status) return void delete member.status
+ const until = status.until ? new Date(status.until).toISOString() : null
+ if (until && Date.parse(until) <= now) fail('STATUS_EXPIRED', 'Choose a time that has not passed yet.', 400)
+ member.status = { text: status.text, emoji: status.emoji ?? null, until }
+}
+
+/** Pictures a person may pick instead of uploading one; Desktop draws each. */
+export const AVATAR_PRESETS = ['fox', 'owl', 'cat', 'panda', 'octopus', 'cactus', 'rocket', 'sun'] as const
+/** What a member or agent shows: an uploaded picture or a preset. Absent: the default, initials for a person, a pattern from
+ * the name for an agent (Desktop). An upload keeps its object's key in the private avatar bucket; readers never get the key,
+ * only a short-lived signed link with each read (avatarLinks.ts). */
+export type Avatar = { kind: 'upload'; key: string } | { kind: 'preset'; key: (typeof AVATAR_PRESETS)[number] }
+/** An avatar as readers get it: an upload says only that there is one. */
+export type AvatarView = { kind: 'upload' } | Extract<Avatar, { kind: 'preset' }>
+export const avatarView = (avatar: Avatar): AvatarView => avatar.kind === 'upload' ? { kind: 'upload' } : avatar
+/** [holder] as readers get it, its avatar's stored key left out. */
+export function withAvatarView<T extends { avatar?: Avatar }>(holder: T): Omit<T, 'avatar'> & { avatar?: AvatarView } {
+ return holder.avatar ? { ...holder, avatar: avatarView(holder.avatar) } : holder
+}
+export const avatarChoice = z.discriminatedUnion('kind', [
+ z.object({ kind: z.literal('upload'), id: z.string().min(1).max(160).regex(/^[A-Za-z0-9_-]+$/) }).strict(),
+ z.object({ kind: z.literal('preset'), key: z.enum(AVATAR_PRESETS) }).strict(),
+]).nullable()
+type AvatarChoice = z.infer<typeof avatarChoice>
+/** The avatar upload a command names, found by the store: this actor's, an avatar, and not used yet. */
+export interface AvatarUpload { id: string; key: string }
+
+function chosen(choice: NonNullable<AvatarChoice>, upload: AvatarUpload | undefined): Avatar {
+ if (choice.kind === 'preset') return choice
+ if (upload?.id !== choice.id) fail('AVATAR_UNAVAILABLE', 'Upload this picture again before using it.', 400)
+ return { kind: 'upload', key: upload.key }
+}
+
+/** `member.avatar`: a person sets or clears their own avatar. */
+export function setMemberAvatar(state: SuperTabState, actor: Actor, choice: AvatarChoice, upload: AvatarUpload | undefined): void {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'Set an agent\'s avatar with its own command.', 403)
+ const member = person(state, actor.userId)
+ if (!choice) return void delete member.avatar
+ member.avatar = chosen(choice, upload)
+}
+
+/** `agent.avatar`: the person who contributed the agent, or the Lead of its project, sets or clears its avatar. */
+export function setAgentAvatar(state: SuperTabState, actor: Actor, agentId: string, choice: AvatarChoice, upload: AvatarUpload | undefined): void {
+ const target = agent(state, agentId)
+ const allowed = actor.kind === 'person' ? actor.userId === target.contributorId
+ : ledProject(state, actor.agentId)?.id === agentProjectId(state, target)
+ if (!allowed) fail('FORBIDDEN', 'Only the agent\'s contributor or its project\'s Lead can change its avatar.', 403)
+ if (!choice) return void delete target.avatar
+ target.avatar = chosen(choice, upload)
+}
diff --git a/backend/src/superTabs/reactions.test.ts b/backend/src/superTabs/reactions.test.ts
new file mode 100644
index 000000000..14659cf1e
--- /dev/null
+++ b/backend/src/superTabs/reactions.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor } from './model.js'
+import { reactionCounts } from './reactions.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]' }
+
+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: 1000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const invite = (role: 'viewer' | 'collaborator' = 'collaborator') => {
+ const invited = run({ type: 'invite.create', email: peer.email, role, conversationId: 'lead' })
+ run({ type: 'invite.accept', inviteId: invited.result.inviteId as string }, peer)
+ }
+ const lead = () => state.conversations.find(c => c.id === 'lead')!
+ return { run, invite, lead, get state() { return state } }
+}
+const react = (on: boolean, emoji = 'tada'): Command => ({ type: 'message.react', conversationId: 'lead', messageId: 'm1', emoji, on } as Command)
+const target = (reacted: boolean) => ({ reaction: { messageId: 'm1', reacted } })
+
+describe('reactions', () => {
+ it('bumps the group only when the reaction changes', () => {
+ const f = fixture()
+ expect(f.run(react(true), owner, target(false)).result).toMatchObject({ changed: true })
+ expect(f.lead().reactionSeq).toBe(1)
+ expect(f.run(react(true), owner, target(true)).result).toMatchObject({ changed: false })
+ expect(f.run(react(false), owner, target(false)).result).toMatchObject({ changed: false })
+ expect(f.lead().reactionSeq).toBe(1)
+ f.run(react(false), owner, target(true))
+ expect(f.lead().reactionSeq).toBe(2)
+ })
+
+ it('refuses a message the store did not find here, an unknown emoji, a viewer and an archived group', () => {
+ const f = fixture()
+ expect(() => f.run(react(true))).toThrow(expect.objectContaining({ code: 'NOT_FOUND' }))
+ expect(() => f.run(react(true, 'skull'), owner, target(false))).toThrow()
+ f.invite('viewer')
+ expect(() => f.run(react(true), peer, target(false))).toThrow(expect.objectContaining({ code: 'READ_ONLY' }))
+ const group = f.run({ type: 'conversation.create', title: 'Old', brief: 'Done.', checks: [] }).result.conversationId as string
+ f.run({ type: 'conversation.archive', conversationId: group, archived: true })
+ expect(() => f.run({ type: 'message.react', conversationId: group, messageId: 'm1', emoji: 'tada', on: true }, owner, target(false)))
+ .toThrow(expect.objectContaining({ code: 'ARCHIVED' }))
+ })
+
+ it('counts each emoji in a fixed order, only from reactors still in the Swarm', () => {
+ const f = fixture()
+ f.invite()
+ const rows = [
+ { messageId: 'm1', emoji: 'tada', actorKind: 'person', actorId: 'peer' },
+ { messageId: 'm1', emoji: 'thumbs_up', actorKind: 'person', actorId: 'owner' },
+ { messageId: 'm1', emoji: 'tada', actorKind: 'person', actorId: 'owner' },
+ { messageId: 'm1', emoji: 'tada', actorKind: 'person', actorId: 'left-the-swarm' },
+ { messageId: 'm1', emoji: 'heart', actorKind: 'agent', actorId: 'removed-agent' },
+ { messageId: 'm2', emoji: 'eyes', actorKind: 'person', actorId: 'owner' },
+ ]
+ expect(reactionCounts(f.state, rows).get('m1')).toEqual([
+ { emoji: 'thumbs_up', count: 1, by: [{ kind: 'person', id: 'owner' }] },
+ { emoji: 'tada', count: 2, by: [{ kind: 'person', id: 'peer' }, { kind: 'person', id: 'owner' }] },
+ ])
+ expect(reactionCounts(f.state, rows).get('m2')).toEqual([{ emoji: 'eyes', count: 1, by: [{ kind: 'person', id: 'owner' }] }])
+ })
+})
diff --git a/backend/src/superTabs/reactions.ts b/backend/src/superTabs/reactions.ts
new file mode 100644
index 000000000..843e4c45a
--- /dev/null
+++ b/backend/src/superTabs/reactions.ts
@@ -0,0 +1,39 @@
+import { z } from 'zod'
+import { fail, type SuperTabState } from './model.js'
+
+/** The small set a message can be reacted with, in the order counts show. Desktop draws each (👍 🎉 ❤️ 😄 👀 🚀). */
+export const REACTIONS = ['thumbs_up', 'tada', 'heart', 'laugh', 'eyes', 'rocket'] as const
+export const reactionSchema = z.enum(REACTIONS)
+export type Reaction = (typeof REACTIONS)[number]
+
+/** The message a `message.react` names, found by the store in that conversation and readable by the actor, and whether
+ * the actor already reacted to it with that emoji. */
+export interface ReactionTarget { messageId: string; reacted: boolean }
+/** A stored reaction (schema.prisma SuperTabReaction): one row per message, reactor and emoji. */
+export interface ReactionRow { messageId: string; emoji: string; actorKind: string; actorId: string }
+export interface ReactionCount { emoji: Reaction; count: number; by: Array<{ kind: 'person' | 'agent'; id: string }> }
+
+/** `message.react`: adds or removes the actor's reaction. Only a change bumps the group, so every reader's next change
+ * read picks it up; a repeated add or remove changes nothing. The store writes the row. */
+export function react(group: { reactionSeq?: number }, messageId: string, on: boolean, target: ReactionTarget | undefined): boolean {
+ if (target?.messageId !== messageId) fail('NOT_FOUND', 'This message is unavailable.', 404)
+ const changed = target.reacted !== on
+ if (changed) group.reactionSeq = (group.reactionSeq ?? 0) + 1
+ return changed
+}
+
+/** Each message's counts, emoji in REACTIONS order. A reactor who left the Swarm, or an agent no longer in it, drops out. */
+export function reactionCounts(state: SuperTabState, rows: ReactionRow[]): Map<string, ReactionCount[]> {
+ const present = (row: ReactionRow) => row.actorKind === 'person' ? state.people.some(p => p.id === row.actorId)
+ : row.actorKind === 'agent' && state.agents.some(a => a.id === row.actorId)
+ const counts = new Map<string, ReactionCount[]>()
+ for (const messageId of new Set(rows.map(r => r.messageId))) {
+ const mine = rows.filter(r => r.messageId === messageId && present(r))
+ const shown = REACTIONS.flatMap(emoji => {
+ const by = mine.filter(r => r.emoji === emoji).map(r => ({ kind: r.actorKind as 'person' | 'agent', id: r.actorId }))
+ return by.length ? [{ emoji, count: by.length, by }] : []
+ })
+ if (shown.length) counts.set(messageId, shown)
+ }
+ return counts
+}
diff --git a/backend/src/superTabs/read/contract.ts b/backend/src/superTabs/read/contract.ts
index 50aa6a65a..41f5941a8 100644
--- a/backend/src/superTabs/read/contract.ts
+++ b/backend/src/superTabs/read/contract.ts
@@ -25,10 +25,11 @@ export type GroupChange = LivePart<GroupView> | Tombstone | DormantStub
* invitations filtered (invitations only for the Swarm owner). */
export type HeadView = Pick<SuperTabState, 'version' | 'id' | 'name' | 'project' | 'projects' | 'leadsConversationId' | 'ownerId'
| 'environment' | 'routingPolicy' | 'rules' | 'paused' | 'invitations' | 'localModels'>
-export type MemberView = Person
+/** A member's avatar says only `{ kind: 'upload' }` for an upload: its link comes signed in `derived.avatars`. */
+export type MemberView = Omit<Person, 'avatar'> & { avatar?: import('../profile.js').AvatarView }
/** The stored agent. Time-based and cross-part values (`downSince`, `limitedUntil`, an awaiting decision, the custom
* role) come only in `derived.agents`, so an agent never changes without a new version. */
-export type AgentView = Omit<Agent, 'downNamed' | 'downSince' | 'limitedUntil' | 'roleId'>
+export type AgentView = Omit<Agent, 'downNamed' | 'downSince' | 'limitedUntil' | 'roleId' | 'avatar'> & { avatar?: import('../profile.js').AvatarView }
/** A private conversation's audience: the people it is shared with. The project's Lead always reads it too. */
export interface Audience { people: Array<{ id: string; generation: string }> }
/** A conversation with its own message counter (`lastMessageSequence` and message sequences compare within one group).
@@ -60,6 +61,9 @@ export interface Derived {
otherProjectsWork?: OtherProjectWorkView[]
/** A person only. */
mentionsWaiting?: number
+ /** Signed links to uploaded avatars, by `person:<id>` and `agent:<id>` (avatarLinks.ts): fresh with every read, the same
+ * through each half hour, each opening for at most an hour. Absent when nobody visible has one. */
+ avatars?: Record<string, string>
/** A person only: decisions asked of them, still open. */
decisionsWaiting?: number
/** A person only: a digest of which decisions are open, moving when they change though the count may not. */
@@ -137,7 +141,13 @@ export interface SwarmList {
* newest row the same way. `next` is null at the end. `after` alone (no `afterId`) means strictly after that sequence,
* which is all a poll for new messages needs. */
export interface MessagePageCursor { sequence: number; id: string }
-export interface MessagePage<M = Record<string, unknown>> { messages: M[]; next: MessagePageCursor | null }
+export interface MessagePage<M = Record<string, unknown>> {
+ messages: M[]
+ next: MessagePageCursor | null
+ /** The conversation's reaction counter (reactions.ts): when it moved, read the page shown again for its counts. Each
+ * message carries `reactions: [{ emoji, count, by: [{ kind, id }] }]`, current members only. */
+ reactionSeq: number
+}
/** GET /api/super-tabs/hosts/:machineId/changes?cursor=[&full=1], or POST to the same path with this body when the host
* holds etags (up to 500 Swarms do not fit in a URL). Ask `full` at start and at least every 60 s. */
diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.ts
index 5a678447d..05f62b743 100644
--- a/backend/src/superTabs/read/service.ts
+++ b/backend/src/superTabs/read/service.ts
@@ -18,7 +18,8 @@ import { readableWeek, recentDormantGroups } from '../leaderboard/read.js'
import { LEDGER_WEEKS } from '../leaderboard/record.js'
import { leaderboard } from '../leaderboard/stats.js'
import { WEEK_MS } from '../leaderboard/week.js'
-import { READ_FORMAT, SWARM_MIGRATING, type Changes, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'
+import { READ_FORMAT, SWARM_MIGRATING, type Changes, type Derived, type DormantGroups, type FirstLoad, type OneGroup, type SwarmList } from './contract.js'
+import { AvatarLinks } from '../avatarLinks.js'
import { cursorFor, readCursor } from './cursor.js'
import { changesFor } from './changes.js'
import { envelope, groupView, readerView, seenIn, type ReaderView } from './views.js'
@@ -35,17 +36,27 @@ export class SwarmReads {
constructor(private readonly store: SuperTabStore, private readonly options: { now?: () => number; githubApp?: boolean } = {}) {
this.db = store.db
this.now = options.now ?? store.now
+ this.avatarLinks = store.avatars ? new AvatarLinks(store.avatars) : null
}
+ private readonly avatarLinks: AvatarLinks | null
async firstLoad(user: AuthUser, tabId: string, asAgentId?: string): Promise<FirstLoad> {
const t0 = this.now()
return this.read(user, tabId, async tx => {
const { parts: loaded, view, lastChangedAt } = await this.load(tx, user, tabId, asAgentId, t0, { includeRecentStarts: true })
return { format: READ_FORMAT, tabId, cursor: cursorFor(t0, loaded.visibilityEpoch), serverTime: t0, lastChangedAt, epoch: loaded.visibilityEpoch,
- ...(this.options.githubApp ? { githubApp: true as const } : {}), ...view.parts, derived: view.derived }
+ ...(this.options.githubApp ? { githubApp: true as const } : {}), ...view.parts, derived: await this.withAvatars(view, t0) }
})
}
+ /** The reader's avatar links (avatarLinks.ts), only ever in a member's read: issued afresh each time, never stored. */
+ private async withAvatars(view: ReaderView, now: number): Promise<Derived> {
+ if (!this.avatarLinks) return view.derived
+ const seen = new Set(Object.keys(view.derived.agents))
+ const avatars = await this.avatarLinks.forReader(view.state, view.state.agents.filter(a => seen.has(a.id)), now)
+ return Object.keys(avatars).length ? { ...view.derived, avatars } : view.derived
+ }
+
async changes(user: AuthUser, tabId: string, cursor: string, asAgentId?: string): Promise<Changes> {
const t0 = this.now()
return this.read(user, tabId, async tx => {
@@ -64,7 +75,7 @@ export class SwarmReads {
const dormant = [...new Set(changed.flatMap(p => p.kind === 'start' ? [(p.data as AgentStart).request.conversationId] : []))].filter(id => !held.has(id))
if (dormant.length) read = await this.load(tx, user, tabId, asAgentId, t0, { ...light, groupIds: [...mentioned, ...dormant] }, parts.loadLight)
return { format: READ_FORMAT, reload: false, cursor: cursorFor(t0, read.parts.visibilityEpoch), serverTime: t0, lastChangedAt: read.lastChangedAt,
- epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor), derived: read.view.derived }
+ epoch: read.parts.visibilityEpoch, ...changesFor(read.view, changed, read.actor), derived: await this.withAvatars(read.view, t0) }
})
}
diff --git a/backend/src/superTabs/read/views.ts b/backend/src/superTabs/read/views.ts
index 01e07320a..38cb9b406 100644
--- a/backend/src/superTabs/read/views.ts
+++ b/backend/src/superTabs/read/views.ts
@@ -8,6 +8,7 @@ import { machineSlots, teamAccountRequired, teamWorkRefusal, type ContributedMac
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 type { AgentView, Derived, GroupView, HeadView, LivePart, MachineView, MemberView, ProgressView, StartView } from './contract.js'
export interface ReaderParts {
@@ -61,7 +62,7 @@ export const seenIn = (parts: ReaderView['parts']): Set<string> =>
export function agentView(agent: Agent): AgentView {
const { downNamed: _named, downSince: _since, limitedUntil: _limit, roleId: _role, ...rest } = agent
- return rest
+ return withAvatarView(rest) as AgentView
}
export function readerView(parts: SwarmParts, actor: Actor, now: number, extras: ReadExtras): ReaderView {
@@ -79,7 +80,7 @@ export function readerView(parts: SwarmParts, actor: Actor, now: number, extras:
state,
parts: {
head: envelope(parts.head, head),
- members: parts.members.filter(m => !m.deleted).map(m => envelope(m, m.data!)),
+ members: parts.members.filter(m => !m.deleted).map(m => envelope(m, withAvatarView(m.data!) as MemberView)),
agents: visible.agents.map(a => envelope(agentPart(a.id), agentView(state.agents.find(s => s.id === a.id)!))),
groups: groups.map(g => envelope(groupPart(g.id), groupView(g, seen))),
machines: (visible.machines ?? []).map(m => envelope(machinePart(m.machineId), m)),
diff --git a/backend/src/superTabs/ship.test.ts b/backend/src/superTabs/ship.test.ts
new file mode 100644
index 000000000..85a371bee
--- /dev/null
+++ b/backend/src/superTabs/ship.test.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { createSuperTab, type Actor, type AgentConfiguration } from './model.js'
+import { SHIP_KIND } from './ship.js'
+
+const owner: Extract<Actor, { kind: 'person' }> = { kind: 'person', userId: 'owner', email: '[email protected]' }
+const config: AgentConfiguration = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
+const PR = 'https://github.com/example/app/pull/7'
+
+function fixture() {
+ let state = createSuperTab('tab', 'Office', { 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: 1000, operationId: `op-${++sequence}`, ...context })
+ state = effects.state
+ return effects
+ }
+ const add = (name: string, group: string, lead = false) => run({ type: 'agent.add', conversationId: group, machineId: 'host', harnessId: name,
+ name, configuration: config, lead }, owner, { contribution: { machineOwnerId: 'host-owner', contributorId: 'owner' } }).result.agentId as string
+ const lead = add('River', 'lead', true)
+ const as = (agentId: string): Actor => ({ kind: 'agent', agentId, machineOwnerId: 'host-owner' })
+ const group = (title = 'Avatars', extra: Record<string, unknown> = {}) => run({ type: 'conversation.create', title, brief: 'Add avatars.',
+ checks: [{ description: 'Tests pass', independent: false }], ...extra } as Command).result.conversationId as string
+ const finish = (id: string, worker: string, result = `Merged ${PR}`) => {
+ const work = state.conversations.find(c => c.id === id)!
+ const assignment = work.assignment!.id
+ run({ type: 'work.check', conversationId: id, assignmentId: assignment, checkId: work.checks[0]!.id, passed: true, evidence: 'npm test: 12 passed' }, as(worker))
+ return run({ type: 'work.status', conversationId: id, assignmentId: assignment, status: 'done', result }, as(worker))
+ }
+ const ships = (effects: ReturnType<typeof run>) => effects.messages.filter(m => m.source?.kind === SHIP_KIND)
+ return { run, add, as, group, finish, ships, lead, get state() { return state } }
+}
+
+describe('the ship moment', () => {
+ it('posts one celebration in the project chat naming the requester, builder and reviewers', () => {
+ const f = fixture()
+ const id = f.group()
+ const builder = f.add('Kai', id)
+ const reviewer = f.add('Ivy', id)
+ f.state.agents.find(a => a.id === reviewer)!.role = 'reviewer'
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder }, owner)
+ const [line, ...more] = f.ships(f.finish(id, builder))
+ expect(more).toEqual([])
+ expect(line).toMatchObject({ conversationId: 'lead', recipients: [],
+ source: { kind: SHIP_KIND, conversationId: id, title: 'Avatars', pullRequests: [PR], requesterId: 'owner', builderIds: [builder], reviewerIds: [reviewer] } })
+ expect(line!.text).toBe(`🎉 Shipped: Avatars, requested by dee, built by Kai, reviewed by Ivy. ${PR}`)
+ })
+
+ it('leaves out who asked when nobody is recorded, and counts reviewers of a review group', () => {
+ const f = fixture()
+ const id = f.group()
+ delete f.state.conversations.find(c => c.id === id)!.requesterId
+ const builder = f.add('Kai', id)
+ const review = f.run({ type: 'conversation.create', title: 'Review avatars', brief: 'Review.', reviewOf: id, checks: [] }).result.conversationId as string
+ const reviewer = f.add('Ivy', review)
+ f.state.agents.find(a => a.id === reviewer)!.role = 'reviewer'
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder }, owner)
+ const [line] = f.ships(f.finish(id, builder))
+ expect(line!.source).not.toHaveProperty('requesterId')
+ expect(line!.text).toBe(`🎉 Shipped: Avatars, built by Kai, reviewed by Ivy. ${PR}`)
+ })
+
+ it('celebrates a group once: reassigned and Done again, it stays quiet', () => {
+ const f = fixture()
+ const id = f.group()
+ const builder = f.add('Kai', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder }, owner)
+ expect(f.ships(f.finish(id, builder))).toHaveLength(1)
+ const again = f.add('Ivy', id)
+ f.run({ type: 'agent.release', agentId: builder, decision: 'keep' }, f.as(f.lead))
+ f.run({ type: 'work.assign', conversationId: id, agentId: again }, owner)
+ expect(f.ships(f.finish(id, again, 'Follow-up merged https://github.com/example/app/pull/8'))).toEqual([])
+ })
+
+ it('stays quiet without a linked pull request, for a review group, and for other statuses', () => {
+ const f = fixture()
+ const id = f.group()
+ const builder = f.add('Kai', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder }, owner)
+ const assignment = f.state.conversations.find(c => c.id === id)!.assignment!.id
+ expect(f.ships(f.run({ type: 'work.status', conversationId: id, assignmentId: assignment, status: 'review', result: PR }, f.as(builder)))).toEqual([])
+ expect(f.ships(f.finish(id, builder, 'Done, nothing to merge.'))).toEqual([])
+ })
+
+ it('never names a private conversation, its words or its link', () => {
+ const f = fixture()
+ const id = f.group('Secret plan')
+ const builder = f.add('Kai', id)
+ f.run({ type: 'work.assign', conversationId: id, agentId: builder }, owner)
+ const work = f.state.conversations.find(c => c.id === id)!
+ f.run({ type: 'work.check', conversationId: id, assignmentId: work.assignment!.id, checkId: work.checks[0]!.id, passed: true, evidence: 'ok' }, f.as(builder))
+ // A private conversation is chat only today; were one ever to carry work, its celebration still says nothing of it.
+ f.state.conversations.find(c => c.id === id)!.audience = { people: [{ id: 'owner', generation: 'tab' }] }
+ const done = f.run({ type: 'work.status', conversationId: id, assignmentId: work.assignment!.id, status: 'done', result: `Merged ${PR}` })
+ expect(f.ships(done)).toEqual([])
+ expect(JSON.stringify(done.messages.filter(m => m.conversationId !== id))).not.toContain('Secret plan')
+ })
+})
diff --git a/backend/src/superTabs/ship.ts b/backend/src/superTabs/ship.ts
new file mode 100644
index 000000000..727594cf6
--- /dev/null
+++ b/backend/src/superTabs/ship.ts
@@ -0,0 +1,32 @@
+import { agentRole, isLeads, stableId, type Author, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
+import { agentDisplayName } from './agentNames.js'
+import { groupProject } from './projects.js'
+
+/** The source of the celebration row Desktop draws with confetti. */
+export const SHIP_KIND = 'ship'
+
+/** When the group first shipped, as the leaderboard records it (leaderboard/record.ts `recordStatus`: once, on the first Done). */
+export const shippedAt = (group: Conversation): number | undefined => group.ledger?.shippedAt
+
+/** Work just became Done. When it links a pull request, the project chat gets one line naming who asked, who built it and
+ * who reviewed it ("Done with a linked PR" is shipped: Leads mark Done after the merge). A private conversation is never
+ * celebrated: its title, words and link are its own. No agent is woken by it. A group is one request: only its first ship is
+ * celebrated, not a later attempt's Done (the caller checks `shippedAt` from before the command). */
+export function shipNotice(state: SuperTabState, group: Conversation, author: Author, operationId: string): MessageDraft | null {
+ const pullRequests = group.pullRequestUrls ?? []
+ if (!pullRequests.length || group.audience || group.reviewOf || isLeads(group) || !group.assignment) return null
+ const project = groupProject(state, group)
+ const agentName = (id: string) => agentDisplayName(state.agents, id) ?? state.agents.find(a => a.id === id)?.name
+ const builderIds = [group.assignment.agentId].filter(id => agentName(id))
+ const reviewGroups = state.conversations.filter(c => c.reviewOf === group.id)
+ const reviewerIds = [...new Set([group, ...reviewGroups].flatMap(c => c.agentIds))]
+ .filter(id => !builderIds.includes(id) && state.agents.some(a => a.id === id && agentRole(a) === 'reviewer'))
+ const requester = state.people.find(p => p.id === group.requesterId)
+ const names = (ids: string[]) => ids.map(agentName).join(' and ')
+ const credits = [requester && `requested by ${requester.email.split('@')[0]}`, builderIds.length && `built by ${names(builderIds)}`,
+ reviewerIds.length && `reviewed by ${names(reviewerIds)}`].filter(Boolean)
+ return { id: stableId(operationId, SHIP_KIND), conversationId: project.leadConversationId, author, replyTo: null, recipients: [],
+ text: `🎉 Shipped: ${group.title}${credits.length ? `, ${credits.join(', ')}` : ''}. ${pullRequests.join(' ')}`,
+ source: { kind: SHIP_KIND, conversationId: group.id, title: group.title, pullRequests, ...(requester ? { requesterId: requester.id } : {}),
+ builderIds, reviewerIds } }
+}
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index c7b043072..82e554f37 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -8,7 +8,10 @@ import { machineShareGrant, sharedVia } from '../lib/machineSharePolicy.js'
import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMIT, postable, type Command, type CommandContext } from './commands.js'
import { redactCredentials } from './credentials.js'
-import { attachmentMime, attachmentName, AttachmentTooLarge, checkedType, MAX_ATTACHMENT_BYTES, objectKeyFor, publicUrl, type Attachment, type Attachments } from './attachments.js'
+import type { AvatarUpload } from './profile.js'
+import { reactionCounts, type ReactionTarget } from './reactions.js'
+import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl,
+ type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'
import { randomBytes } from 'node:crypto'
import type { Readable } from 'node:stream'
import { logger } from '../utils/logger.js'
@@ -40,6 +43,8 @@ import { authenticatedEmail, authorizeSwarmJoin, configureSharing, joinSwarmSche
saveSharingSchema, sharingDetails, type JoinSwarm, type SaveSharing } from './sharing.js'
type Transaction = Prisma.TransactionClient
+type ReactCommand = Extract<Command, { type: 'message.react' }>
+const reactionId = (tabId: string, actor: Actor, command: ReactCommand) => stableId(tabId, command.messageId, actorKey(actor), command.emoji)
const json = (value: unknown): Prisma.InputJsonValue => JSON.parse(JSON.stringify(value)) as Prisma.InputJsonValue
type SendCommand = Extract<Command, { type: 'message.send' }>
// Prisma on MongoDB: `usedBy: null` alone misses rows that never had the field.
@@ -183,6 +188,8 @@ const routeDecisionOf = (command: Command): string | undefined => command.type =
export class SuperTabStore {
readonly native: SuperTabNativeStore
+ /** The private avatar bucket, whose links member reads sign (read/service.ts); null when avatar uploads are off. */
+ get avatars(): AvatarStore | null { return this.attachments?.avatars ?? null }
constructor(readonly db: PrismaClient, readonly now: () => number = Date.now,
private readonly attachments: Attachments | null = null, private readonly hooks: SuperTabStoreHooks = {}) {
this.native = new SuperTabNativeStore({
@@ -741,6 +748,10 @@ export class SuperTabStore {
if (command.type === 'mention.done') context.mention = await readMention(tx, tabId, command.mentionId)
if (command.type === 'decision.answer') context.decision = await readAskedDecision(tx, tabId, command.decisionId)
if (command.type === 'message.send' && command.attachmentIds?.length) context.attachments = await this.sendable(tx, tabId, actor, command)
+ if (command.type === 'message.react') context.reaction = await this.reactionTarget(tx, tabId, actor, command)
+ if ((command.type === 'member.avatar' || command.type === 'agent.avatar') && command.avatar?.kind === 'upload') {
+ context.avatarUpload = await this.avatarUpload(tx, tabId, actor, command.avatar.id)
+ }
if (TEAM_WORK_COMMANDS.has(command.type)) {
context.teamMachines = await this.teamMachines(tx, original)
if (this.hooks.teamAccountsIdle) context.teamAccountsIdle = true
@@ -927,6 +938,13 @@ export class SuperTabStore {
if (command.type === 'message.send' && actor.kind === 'person') await resolveByReply(tx, tabId, command.conversationId, actor.userId, context.now)
await writeMentions(tx, tabId, effects.state, effects.messages, context.now)
if (command.type === 'mention.done') await markDone(tx, tabId, command.mentionId, context.mention!.personId, context.now)
+ if (command.type === 'message.react') await this.writeReaction(tx, tabId, actor, command)
+ if (context.avatarUpload) {
+ // Conflicts with a concurrent use of the same picture: only one command can take it.
+ const taken = await tx.superTabAttachment.updateMany({ where: { tabId, id: context.avatarUpload.id, purpose: AVATAR_PURPOSE, ...unused },
+ data: { usedBy: receiptId } })
+ if (taken.count !== 1) fail('AVATAR_UNAVAILABLE', 'Upload this picture again before using it.', 400)
+ }
if (effects.decisions) {
const ids = await writeDecisions(tx, tabId, effects.decisions, context.now)
if (command.type === 'decision.ask') effects.result.decisionIds = ids
@@ -1045,30 +1063,64 @@ export class SuperTabStore {
// A file's name is shown in the chat like its message, so it never keeps a credential either.
const name = attachmentName.transform(value => redactCredentials(value).text).safeParse(file.name), mime = attachmentMime.safeParse(file.mime)
if (!name.success || !mime.success) fail('INVALID_ATTACHMENT', 'Attach a file with a printable name and a content type.', 400)
- const key = await transaction(this.db, async tx => {
- const { actor } = await this.poster(tx, user, tabId, conversationId, asAgentId)
- const key = actorKey(actor)
- // Unsent files cost bucket space, so one actor gets a bounded number an hour.
+ const key = await this.uploader(tabId, tx => this.poster(tx, user, tabId, conversationId, asAgentId).then(p => p.actor))
+ const row = await this.keep(attachments.store, attachments.prefix, tabId, key, { name: name.data, conversationId },
+ async () => checkedType(mime.data, file.body), file.body, MAX_ATTACHMENT_BYTES)
+ return { attachment: { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, row.objectKey) } satisfies Attachment }
+ }
+
+ /** A picture for a person's or an agent's avatar (profile.ts): png, jpg or webp by its real bytes, at most 1 MB. Any
+ * member who may write uploads one; the command that sets it decides whose it becomes. */
+ async uploadAvatar(user: AuthUser, tabId: string, file: { body: Readable }, asAgentId?: string) {
+ // Member-only: never the public attachments bucket. Until a private one is configured, uploads stay off (presets work).
+ const avatars = this.attachments?.avatars ?? fail('AVATARS_UNAVAILABLE', 'Uploading pictures is not set up on this server yet. Pick one of the pictures instead.', 503)
+ const key = await this.uploader(tabId, async tx => {
+ const { state } = await this.load(tx, user, tabId, {})
+ const actor = await this.actor(tx, user, state, asAgentId)
+ author(state, actor, true)
+ return actor
+ })
+ const row = await this.keep(avatars, this.attachments!.prefix, tabId, key, { name: 'avatar', conversationId: '', purpose: AVATAR_PURPOSE }, async () => {
+ const peeked = await peekType(file.body)
+ if (!peeked.type || !AVATAR_TYPES.has(peeked.type)) fail('AVATAR_TYPE', 'Use a PNG, JPEG or WebP picture.', 415)
+ return { mime: peeked.type, body: peeked.body }
+ }, file.body, MAX_AVATAR_BYTES)
+ // No link: a picture is only reached through the signed links member reads carry (avatarLinks.ts).
+ return { avatar: { id: row.id } }
+ }
+
+ /** The uploading actor's key, once it may upload and is under its hourly allowance: unsent files cost bucket space. */
+ private async uploader(tabId: string, allowed: (tx: Transaction) => Promise<Actor>): Promise<string> {
+ return transaction(this.db, async tx => {
+ const key = actorKey(await allowed(tx))
const recent = await tx.superTabAttachment.count({ where: { tabId, actorKey: key, createdAt: { gte: new Date(this.now() - 3_600_000) } } })
if (recent >= 200) fail('RATE_LIMITED', 'You attached 200 files in the last hour. Wait before attaching more.', 429)
return key
})
- const objectKey = objectKeyFor(attachments.prefix, tabId, name.data)
- let size: number, stored = mime.data
+ }
+
+ /** Streams one file into the bucket under a random key, as the type `typed` decides from its first bytes, and records it. */
+ private async keep(bucket: AttachmentStore, prefix: string, tabId: string, actorKey: string, file: { name: string; conversationId: string; purpose?: string },
+ typed: () => Promise<{ mime: string; body: Readable }>, original: Readable, cap: number) {
+ const objectKey = objectKeyFor(prefix, tabId, file.name)
+ let size: number, mime: string
try {
- const checked = await checkedType(mime.data, file.body)
- stored = checked.mime
- size = await attachments.store.put(objectKey, { name: name.data, mime: stored }, checked.body, MAX_ATTACHMENT_BYTES)
+ const checked = await typed()
+ mime = checked.mime
+ size = await bucket.put(objectKey, { name: file.name, mime }, checked.body, cap)
} catch (error) {
- if (error instanceof AttachmentTooLarge) fail('ATTACHMENT_TOO_LARGE', error.message, 413)
+ if (error instanceof SuperTabError) throw error
+ if (error instanceof AttachmentTooLarge) {
+ if (file.purpose === AVATAR_PURPOSE) fail('AVATAR_TOO_LARGE', 'An avatar can be at most 1 MB.', 413)
+ fail('ATTACHMENT_TOO_LARGE', error.message, 413)
+ }
// The client's own stream breaking is the request's; anything else is the bucket's, and the person can try again.
- if (file.body.errored || (error && typeof error === 'object' && 'code' in error && String(error.code).startsWith('FST_'))) throw error
+ if (original.errored || (error && typeof error === 'object' && 'code' in error && String(error.code).startsWith('FST_'))) throw error
logger.error('super-tab attachment storage failed', { tabId, error: error instanceof Error ? error.message : String(error) })
fail('ATTACHMENTS_UNAVAILABLE', 'Could not store the file just now. Try again.', 503)
}
- const row = await this.db.superTabAttachment.create({ data: { id: randomBytes(12).toString('hex'), tabId, conversationId,
- actorKey: key, name: name.data, mime: stored, size, objectKey } })
- return { attachment: { id: row.id, name: row.name, mime: row.mime, size: row.size, url: publicUrl(attachments.publicBase, objectKey) } satisfies Attachment }
+ return this.db.superTabAttachment.create({ data: { id: randomBytes(12).toString('hex'), tabId, conversationId: file.conversationId,
+ actorKey, name: file.name, mime, size, objectKey, ...(file.purpose ? { purpose: file.purpose } : {}) } })
}
/** The actor, once it may post in this conversation. */
@@ -1087,7 +1139,7 @@ export class SuperTabStore {
const rows = await tx.superTabAttachment.findMany({ where: { tabId, id: { in: ids } } })
return ids.map(id => {
const row = rows.find(r => r.id === id)
- if (!row || row.actorKey !== actorKey(actor) || row.conversationId !== command.conversationId) {
+ if (!row || row.actorKey !== actorKey(actor) || row.conversationId !== command.conversationId || row.purpose) {
fail('ATTACHMENT_UNAVAILABLE', 'Attach this file again before sending it.', 400)
}
if (row.usedBy) fail('ATTACHMENT_USED', 'This file was already sent. Attach it again to send it in another message.')
@@ -1095,6 +1147,30 @@ export class SuperTabStore {
})
}
+ /** The message a reaction names, when it is in that conversation and this actor may see it, and whether the actor already
+ * reacted to it with that emoji. An agent-only notice is its recipient's alone. */
+ private async reactionTarget(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand): Promise<ReactionTarget | undefined> {
+ const message = await tx.superTabMessage.findFirst({ where: { id: command.messageId, tabId, conversationId: command.conversationId },
+ select: { id: true, source: true, recipientIds: true } })
+ if (!message || (agentOnly(message.source) && !(actor.kind === 'agent' && message.recipientIds.includes(actor.agentId)))) return undefined
+ return { messageId: message.id, reacted: !!await tx.superTabReaction.findUnique({ where: { id: reactionId(tabId, actor, command) } }) }
+ }
+
+ /** Writes or removes the actor's reaction row. The same reaction twice keeps one row: its id is derived. */
+ private async writeReaction(tx: Transaction, tabId: string, actor: Actor, command: ReactCommand) {
+ const id = reactionId(tabId, actor, command)
+ if (!command.on) return void await tx.superTabReaction.deleteMany({ where: { id } })
+ const actorId = actor.kind === 'person' ? actor.userId : actor.agentId
+ await tx.superTabReaction.upsert({ where: { id }, update: {}, create: { id, tabId, conversationId: command.conversationId,
+ messageId: command.messageId, actorKind: actor.kind, actorId, emoji: command.emoji } })
+ }
+
+ /** The avatar upload a command names, when it is this actor's, an avatar and unused; otherwise the command refuses it. */
+ private async avatarUpload(tx: Transaction, tabId: string, actor: Actor, id: string): Promise<AvatarUpload | undefined> {
+ const row = await tx.superTabAttachment.findFirst({ where: { tabId, id, actorKey: actorKey(actor), purpose: AVATAR_PURPOSE, ...unused } })
+ return row ? { id: row.id, key: row.objectKey } : undefined
+ }
+
/** Keeps the project's stored texts equal to its custom set: the roles the command wrote, nothing for roles it dropped. */
private async writeRoleTexts(tx: Transaction, tabId: string, state: SuperTabState, command: Command) {
if (!('projectId' in command) || !command.projectId) return
@@ -1301,7 +1377,7 @@ export class SuperTabStore {
return transaction(this.db, async tx => {
const { state } = await this.load(tx, user, tabId, { groupIds: [conversationId] })
const actor = await this.actor(tx, user, state, asAgentId)
- readConversation(state, actor, conversationId)
+ const group = readConversation(state, actor, conversationId)
const forward = cursor.after !== undefined
const past = (sequence: number, id: string | undefined, direction: 'gt' | 'lt') => id === undefined ? { sequence: { [direction]: sequence } }
: { OR: [{ sequence: { [direction]: sequence } }, { sequence, id: { [direction]: id } }] }
@@ -1320,10 +1396,15 @@ export class SuperTabStore {
const page = rows.slice(0, 100)
const next = rows.length > 100 ? { sequence: page.at(-1)!.sequence, id: page.at(-1)!.id } : null
if (!forward) page.reverse()
+ const reactions = page.length ? reactionCounts(state, await tx.superTabReaction.findMany({ where: { tabId, messageId: { in: page.map(m => m.id) } },
+ select: { messageId: true, emoji: true, actorKind: true, actorId: true } })) : new Map()
const deliveries = page.length ? await tx.superTabDelivery.findMany({ where: { tabId, messageId: { in: page.map(m => m.id) } },
select: { id: true, messageId: true, agentId: true, status: true, receipt: true,
holdReason: true, holdSince: true, deliveredAt: true, answeredAt: true, createdAt: true, updatedAt: true } }) : []
- return { messages: page.map(m => ({ ...m, mentions: m.mentions ?? [], deliveries: deliveries.filter(d => d.messageId === m.id) })), next }
+ return { messages: page.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],
+ deliveries: deliveries.filter(d => d.messageId === m.id) })), next,
+ // A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).
+ reactionSeq: group.reactionSeq ?? 0 }
})
}
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 1cbcecf4e..d2646e017 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -1,5 +1,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/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts'], hookTimeout: 120000, testTimeout: 30000,
+ 'integration/superTabRead.test.ts', 'integration/superTabLeaderboard.test.ts', 'integration/superTabMigration.test.ts', 'integration/superTabLiveness.test.ts', 'integration/superTabTidy.test.ts',
+ 'integration/superTabProfile.test.ts'], hookTimeout: 120000, testTimeout: 30000,
fileParallelism: false, env: { NODE_ENV: 'test', HARNESS_CREDENTIAL_ENCRYPTION_KEY: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=' } } })
diff --git a/desktop/integration_test/super_tab_delight_native_test.dart b/desktop/integration_test/super_tab_delight_native_test.dart
new file mode 100644
index 000000000..113e24ba3
--- /dev/null
+++ b/desktop/integration_test/super_tab_delight_native_test.dart
@@ -0,0 +1,82 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/foundation.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/test_run.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/profile_sheet.dart';
+import 'package:harness/super_tabs/ship_row.dart';
+import 'package:window_manager/window_manager.dart';
+
+import '../test/super_tab_delight_shots_test.dart' show delightApp, office;
+import 'flutter_test_config.dart';
+
+/// The avatars-and-delight PR's screenshots on a real macOS surface, where
+/// color emoji draw: the in-memory Swarm of the widget capture, never a
+/// backend, account or the live app. Writes to SUPER_TAB_DELIGHT_SHOTS.
+void main() {
+ if (!kUnderTest) throw StateError('Requires FLUTTER_TEST=1');
+ ensureNativeTestBinding();
+ final folder = Platform.environment['SUPER_TAB_DELIGHT_SHOTS'];
+ final boundary = GlobalKey();
+
+ Future<void> shot(String name) async {
+ if (folder == null) return;
+ final render =
+ boundary.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await render.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(folder).create(recursive: true);
+ await File('$folder/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ }
+
+ testWidgets('avatars, status, reactions and a ship moment', (tester) async {
+ expect(defaultTargetPlatform, TargetPlatform.macOS);
+ await windowManager.ensureInitialized();
+ await windowManager.setSize(const Size(1280, 860));
+ await windowManager.setTitle('Swarm delight — test data');
+ await windowManager.setAlwaysOnTop(true);
+ addTearDown(() => windowManager.setAlwaysOnTop(false));
+ await windowManager.show();
+ for (final (brightness, reduceMotion, name) in [
+ (Brightness.dark, false, 'dark'),
+ (Brightness.light, true, 'light-reduced-motion'),
+ ]) {
+ SuperTabShipRow.resetPlayed();
+ grid.AppTheme.brightness.value = brightness;
+ final c = office().controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ delightApp(
+ c,
+ brightness: brightness,
+ reduceMotion: reduceMotion,
+ boundary: boundary,
+ ),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 650));
+ await tester.runAsync(() => shot('office-$name'));
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => shot('office-$name-settled'));
+ final context = tester.element(find.byType(Scaffold).first);
+ showSuperTabProfile(context, c);
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => shot('profile-$name'));
+ Navigator.of(context, rootNavigator: true).pop();
+ await tester.pumpAndSettle();
+ showSuperTabProfile(context, c, agentId: 'kai');
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => shot('agent-avatar-$name'));
+ Navigator.of(context, rootNavigator: true).pop();
+ await tester.pumpAndSettle();
+ await tester.pumpWidget(const SizedBox());
+ c.dispose();
+ }
+ grid.AppTheme.brightness.value = Brightness.dark;
+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));
+}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index d6485d3e0..639fb3ac2 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -96,6 +96,7 @@ import '../settings/experimental_features.dart';
import '../core/local_key_value_store.dart';
import '../core/harness_file_store.dart';
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/view_store.dart';
@@ -1754,6 +1755,7 @@ class AppNotifier extends ChangeNotifier {
storage: localStore ?? HarnessFileStore.shared,
viewStorage: localStore ?? swarmViewStore(),
upload: uploadWith(() => api),
+ avatarUpload: uploadAvatarWith(() => api),
onMention: superTabMentionNotice(systemNotifications),
onTagCounts: notifyListeners,
discoveryInterval: kUnderTest ? Duration.zero : const Duration(seconds: 15),
diff --git a/desktop/lib/super_tabs/agent_details.dart b/desktop/lib/super_tabs/agent_details.dart
index f761c6e9e..35846b56a 100644
--- a/desktop/lib/super_tabs/agent_details.dart
+++ b/desktop/lib/super_tabs/agent_details.dart
@@ -14,6 +14,7 @@ import '../widgets/engine_identity.dart';
import 'controller.dart';
import 'identity.dart';
import 'model.dart';
+import 'profile_sheet.dart';
import 'pull_requests.dart';
/// Facts already observed by the Swarm or the agent's machine. Unknown facts
@@ -248,8 +249,18 @@ Future<void> showSuperTabAgentDetails(
final group = info.taskGroup;
final pr = info.latestGroupPr;
final name = controller.snapshot?.agentName(agent.id) ?? agent.name;
+ // Its contributor dresses it; its Lead may too, from the CLI.
+ final dresses =
+ controller.canWrite &&
+ current.contributorId == controller.accountId;
return AlertDialog(
- title: Text(name),
+ title: Row(
+ children: [
+ SuperTabAvatar.agent(current, name: name, size: 32),
+ const SizedBox(width: 12),
+ Expanded(child: Text(name)),
+ ],
+ ),
content: SizedBox(
width: 440,
child: SingleChildScrollView(
@@ -304,6 +315,13 @@ Future<void> showSuperTabAgentDetails(
),
),
actions: [
+ if (dresses)
+ TextButton(
+ onPressed: () => unawaited(
+ showSuperTabProfile(context, controller, agentId: agent.id),
+ ),
+ child: const Text('Change avatar'),
+ ),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Close'),
diff --git a/desktop/lib/super_tabs/attachment_upload.dart b/desktop/lib/super_tabs/attachment_upload.dart
index e57214b4f..466abcf26 100644
--- a/desktop/lib/super_tabs/attachment_upload.dart
+++ b/desktop/lib/super_tabs/attachment_upload.dart
@@ -109,12 +109,12 @@ SuperTabUpload uploadWith(ApiClient Function() api) =>
body['success'] == true) {
return Map<String, dynamic>.from(body['data'] as Map);
}
- throw _refusal(response);
+ throw superTabUploadRefusal(response);
};
/// What a refused upload says. The backend answers `{error: {code, message}}`;
/// the local daemon, a bare code string such as `{error: 'FORBIDDEN'}`.
-SuperTabFailure _refusal(Response<dynamic> response) {
+SuperTabFailure superTabUploadRefusal(Response<dynamic> response) {
final body = response.data;
final error = body is Map ? body['error'] : null;
final code = error is Map
@@ -129,6 +129,8 @@ SuperTabFailure _refusal(Response<dynamic> response) {
switch (code) {
'FORBIDDEN' => 'You can’t send files in this conversation.',
'ATTACHMENT_TOO_LARGE' => 'That file is over 10 MB.',
+ 'AVATAR_TOO_LARGE' => 'That picture is over 1 MB.',
+ 'AVATAR_TYPE' => 'Use a PNG, JPEG or WebP picture.',
_ => 'Could not upload the file. Try again.',
},
statusCode: response.statusCode ?? 0,
diff --git a/desktop/lib/super_tabs/avatar_art.dart b/desktop/lib/super_tabs/avatar_art.dart
new file mode 100644
index 000000000..c4cdb9320
--- /dev/null
+++ b/desktop/lib/super_tabs/avatar_art.dart
@@ -0,0 +1,162 @@
+import 'package:flutter/material.dart';
+
+import '../widgets/desktop_chrome.dart';
+import 'profile_model.dart';
+
+/// A stable hash of [text] (FNV-1a, 32 bits): the same name draws the same
+/// avatar on every computer and in every build.
+int _hash(String text) {
+ var hash = 0x811c9dc5;
+ for (final unit in text.codeUnits) {
+ hash = ((hash ^ unit) * 0x01000193) & 0xffffffff;
+ }
+ return hash;
+}
+
+double _hue(String identity) {
+ var hash = 0;
+ for (final rune in identity.runes) {
+ hash = (hash * 31 + rune) & 0x7fffffff;
+ }
+ hash = ((hash ^ (hash >> 16)) * 0x45d9f3b) & 0x7fffffff;
+ return (hash % 360).toDouble();
+}
+
+Color _tone(BuildContext context, double hue) => HSLColor.fromAHSL(
+ 1,
+ hue,
+ .42,
+ Theme.of(context).brightness == Brightness.dark ? .72 : .36,
+).toColor();
+
+/// An agent's default face: a 5×5 grid mirrored left to right, and a hue, both
+/// from its name alone.
+({List<bool> cells, double hue}) superTabAgentPattern(String name) {
+ final hash = _hash(name.trim().toLowerCase());
+ final half = [for (var bit = 0; bit < 15; bit++) (hash >> bit) & 1 == 1];
+ if (!half.contains(true)) half[7] = true;
+ return (
+ cells: [
+ for (var row = 0; row < 5; row++)
+ for (final column in const [0, 1, 2, 1, 0]) half[row * 3 + column],
+ ],
+ hue: ((hash >> 16) % 360).toDouble(),
+ );
+}
+
+/// The round face inside an avatar: [picture] when there is one, else the
+/// agent pattern when [pattern] is set, else the name's initial.
+class SuperTabAvatarFace extends StatelessWidget {
+ const SuperTabAvatarFace({
+ super.key,
+ required this.identity,
+ required this.name,
+ required this.size,
+ this.picture,
+ this.pattern = false,
+ });
+ final String identity, name;
+ final double size;
+ final SuperTabAvatarPicture? picture;
+ final bool pattern;
+
+ @override
+ Widget build(BuildContext context) => switch (picture) {
+ SuperTabUploadedAvatar(:final url) => ClipOval(
+ child: Image.network(
+ url.toString(),
+ width: size,
+ height: size,
+ fit: BoxFit.cover,
+ errorBuilder: (context, _, _) => _fallback(context),
+ ),
+ ),
+ SuperTabPresetAvatar(:final glyph) => _disc(
+ context,
+ Text(
+ glyph,
+ textScaler: TextScaler.noScaling,
+ style: TextStyle(fontSize: size * .58, height: 1),
+ ),
+ ),
+ null => _fallback(context),
+ };
+
+ Widget _fallback(BuildContext context) =>
+ pattern ? _pattern(context) : _initial(context);
+
+ Widget _disc(BuildContext context, Widget child, [Color? color]) => Container(
+ width: size,
+ height: size,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: (color ?? _tone(context, _hue(identity))).withValues(alpha: .14),
+ shape: BoxShape.circle,
+ ),
+ child: child,
+ );
+
+ Widget _initial(BuildContext context) {
+ final color = _tone(context, _hue(identity));
+ final words = name
+ .trim()
+ .split(RegExp(r'[\s@._-]+'))
+ .where((w) => w.isNotEmpty)
+ .toList();
+ final initial = words.isEmpty
+ ? '?'
+ : words.first.characters.first.toUpperCase();
+ return _disc(
+ context,
+ Text(
+ initial,
+ textScaler: TextScaler.noScaling,
+ style: DesktopChrome.control(
+ medium: true,
+ color: color,
+ ).copyWith(fontSize: size * .43),
+ ),
+ color,
+ );
+ }
+
+ Widget _pattern(BuildContext context) {
+ final art = superTabAgentPattern(name);
+ final color = _tone(context, art.hue);
+ return _disc(
+ context,
+ CustomPaint(
+ key: const ValueKey('super-avatar-pattern'),
+ size: Size.square(size * .56),
+ painter: _PatternPainter(art.cells, color),
+ ),
+ color,
+ );
+ }
+}
+
+class _PatternPainter extends CustomPainter {
+ const _PatternPainter(this.cells, this.color);
+ final List<bool> cells;
+ final Color color;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final cell = size.width / 5;
+ final paint = Paint()..color = color;
+ for (var i = 0; i < cells.length; i++) {
+ if (!cells[i]) continue;
+ canvas.drawRRect(
+ RRect.fromRectAndRadius(
+ Rect.fromLTWH((i % 5) * cell, (i ~/ 5) * cell, cell, cell),
+ Radius.circular(cell * .2),
+ ),
+ paint,
+ );
+ }
+ }
+
+ @override
+ bool shouldRepaint(_PatternPainter old) =>
+ old.color != color || !identical(old.cells, cells);
+}
diff --git a/desktop/lib/super_tabs/avatar_upload.dart b/desktop/lib/super_tabs/avatar_upload.dart
new file mode 100644
index 000000000..66084c54c
--- /dev/null
+++ b/desktop/lib/super_tabs/avatar_upload.dart
@@ -0,0 +1,92 @@
+import 'dart:typed_data';
+import 'dart:ui' as ui;
+
+import 'package:dio/dio.dart';
+
+import '../api/api_client.dart';
+import 'attachment_upload.dart';
+import 'controller.dart';
+
+/// What the backend takes as an avatar (superTabs/attachments.ts).
+const kSuperTabAvatarMaxBytes = 1024 * 1024;
+
+/// The side of the square picture uploaded: sharp at every avatar size shown.
+const kSuperTabAvatarPixels = 256;
+
+/// Sends one avatar picture and returns the backend's answer,
+/// `{avatar: {id, url}}`; a command then makes it someone's.
+typedef SuperTabAvatarUpload = Future<Map<String, dynamic>> Function({
+ required String tabId,
+ required Uint8List png,
+});
+
+/// The avatar upload of a build that cannot reach the backend with a file.
+Future<Map<String, dynamic>> refuseAvatarUpload({
+ required String tabId,
+ required Uint8List png,
+}) => Future.error(
+ const SuperTabFailure(
+ 'UPLOAD_UNAVAILABLE',
+ 'Pictures can’t be sent from here.',
+ ),
+);
+
+/// Uploads with [api], as chat files go: straight to the backend in a
+/// browser and through the local daemon on a computer.
+SuperTabAvatarUpload uploadAvatarWith(ApiClient Function() api) =>
+ ({required tabId, required png}) async {
+ final response = await api().postForm(
+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/avatars',
+ FormData.fromMap({
+ 'file': MultipartFile.fromBytes(
+ png,
+ filename: 'avatar.png',
+ contentType: DioMediaType.parse('image/png'),
+ ),
+ }),
+ );
+ final body = response.data;
+ if (response.statusCode == 200 &&
+ body is Map &&
+ body['success'] == true) {
+ return Map<String, dynamic>.from(body['data'] as Map);
+ }
+ throw superTabUploadRefusal(response);
+ };
+
+/// [picked] cropped to its middle square and drawn at
+/// [kSuperTabAvatarPixels], as a PNG: what any picture a person picks becomes
+/// before it leaves this computer. A file that is not a picture is refused.
+Future<Uint8List> superTabAvatarPng(Uint8List picked) async {
+ final ui.Image source;
+ try {
+ final codec = await ui.instantiateImageCodec(picked);
+ source = (await codec.getNextFrame()).image;
+ codec.dispose();
+ } catch (_) {
+ throw const SuperTabFailure(
+ 'AVATAR_TYPE',
+ 'Use a PNG, JPEG or WebP picture.',
+ );
+ }
+ final side = source.width < source.height ? source.width : source.height;
+ final crop = ui.Rect.fromLTWH(
+ (source.width - side) / 2,
+ (source.height - side) / 2,
+ side.toDouble(),
+ side.toDouble(),
+ );
+ const pixels = kSuperTabAvatarPixels;
+ final recorder = ui.PictureRecorder();
+ ui.Canvas(recorder).drawImageRect(
+ source,
+ crop,
+ const ui.Rect.fromLTWH(0, 0, pixels * 1.0, pixels * 1.0),
+ ui.Paint()..filterQuality = ui.FilterQuality.high,
+ );
+ final drawn = await recorder.endRecording().toImage(pixels, pixels);
+ source.dispose();
+ final bytes = await drawn.toByteData(format: ui.ImageByteFormat.png);
+ drawn.dispose();
+ return bytes!.buffer.asUint8List();
+}
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 9aa86b995..142c47c59 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';
import '../core/local_key_value_store.dart';
import 'attachment_upload.dart';
+import 'avatar_upload.dart';
import 'controller.dart';
import 'model.dart';
import 'notifications.dart';
@@ -34,6 +35,7 @@ class SuperTabClient {
this.onMention,
this.onTagCounts,
this.upload = refuseUpload,
+ this.avatarUpload = refuseAvatarUpload,
this.discoveryInterval = const Duration(seconds: 15),
}) : viewStorage = viewStorage ?? storage;
final SuperTabTransport transport;
@@ -74,6 +76,7 @@ class SuperTabClient {
bool _paused(String id) =>
_reading.pausesAway && (_loaded[id]?.away ?? false);
final SuperTabUpload upload;
+ final SuperTabAvatarUpload avatarUpload;
final Duration discoveryInterval;
/// How every Swarm tab here keeps itself current. Desktop's unless the host
@@ -470,6 +473,7 @@ class SuperTabClient {
},
save: (state) => storage.write(key, jsonEncode(state)),
upload: upload,
+ avatarUpload: avatarUpload,
reading: _reading,
)..away = _isAway(id);
var seenChange = (lastChangedAt: -1, mentionsWaiting: -1, pmUnread: -1);
diff --git a/desktop/lib/super_tabs/confetti.dart b/desktop/lib/super_tabs/confetti.dart
new file mode 100644
index 000000000..cec66f43d
--- /dev/null
+++ b/desktop/lib/super_tabs/confetti.dart
@@ -0,0 +1,132 @@
+import 'dart:math';
+
+import 'package:flutter/material.dart';
+
+/// A short burst of confetti over its child, once, then gone. Nothing moves
+/// when the system asks for reduced motion: the child shows alone.
+class SuperTabConfetti extends StatefulWidget {
+ const SuperTabConfetti({
+ super.key,
+ required this.seed,
+ required this.child,
+ this.duration = const Duration(milliseconds: 2200),
+ });
+ final int seed;
+ final Widget child;
+ final Duration duration;
+
+ @override
+ State<SuperTabConfetti> createState() => _SuperTabConfettiState();
+}
+
+class _SuperTabConfettiState extends State<SuperTabConfetti>
+ with SingleTickerProviderStateMixin {
+ late final _motion = AnimationController(
+ vsync: this,
+ duration: widget.duration,
+ );
+ late final _pieces = _Piece.burst(widget.seed);
+ bool _done = false;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ if (_done || _motion.isAnimating) return;
+ if (MediaQuery.disableAnimationsOf(context)) {
+ _done = true;
+ return;
+ }
+ _motion.forward().whenComplete(() {
+ if (mounted) setState(() => _done = true);
+ });
+ }
+
+ @override
+ void dispose() {
+ _motion.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => Stack(
+ clipBehavior: Clip.none,
+ children: [
+ widget.child,
+ if (!_done)
+ Positioned.fill(
+ child: IgnorePointer(
+ child: ExcludeSemantics(
+ child: CustomPaint(
+ key: const ValueKey('super-confetti'),
+ painter: _ConfettiPainter(_pieces, _motion),
+ ),
+ ),
+ ),
+ ),
+ ],
+ );
+}
+
+class _Piece {
+ const _Piece(this.x, this.drift, this.lift, this.spin, this.size, this.color);
+ final double x, drift, lift, spin, size;
+ final Color color;
+
+ static const _colors = [
+ Color(0xffff6b6b),
+ Color(0xffffc145),
+ Color(0xff4ecdc4),
+ Color(0xff5b8def),
+ Color(0xffb084f5),
+ Color(0xff6ad08a),
+ ];
+
+ static List<_Piece> burst(int seed) {
+ final random = Random(seed);
+ return [
+ for (var i = 0; i < 40; i++)
+ _Piece(
+ random.nextDouble(),
+ (random.nextDouble() - .5) * .3,
+ .4 + random.nextDouble() * .6,
+ (random.nextDouble() - .5) * 12,
+ 4 + random.nextDouble() * 4,
+ _colors[i % _colors.length],
+ ),
+ ];
+ }
+}
+
+class _ConfettiPainter extends CustomPainter {
+ _ConfettiPainter(this.pieces, this.motion) : super(repaint: motion);
+ final List<_Piece> pieces;
+ final Animation<double> motion;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final t = motion.value;
+ final paint = Paint();
+ for (final piece in pieces) {
+ // Thrown up from the line, then falling past it as it fades.
+ final y = size.height * (1 - piece.lift * 4 * t * (1 - t) * 2 + t * .6);
+ final x = size.width * (piece.x + piece.drift * t);
+ paint.color = piece.color.withValues(alpha: (1 - t).clamp(0, 1));
+ canvas
+ ..save()
+ ..translate(x, y)
+ ..rotate(piece.spin * t)
+ ..drawRect(
+ Rect.fromCenter(
+ center: Offset.zero,
+ width: piece.size,
+ height: piece.size * .5,
+ ),
+ paint,
+ )
+ ..restore();
+ }
+ }
+
+ @override
+ bool shouldRepaint(_ConfettiPainter old) => false;
+}
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index aa3c616ed..6bef55c55 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -8,6 +8,7 @@ import 'package:flutter/foundation.dart';
import '../logging/app_log.dart';
import '../state/harness_attachments.dart';
import 'attachment_upload.dart';
+import 'avatar_upload.dart';
import 'identity.dart';
import 'model.dart';
import 'pm_chat.dart';
@@ -49,6 +50,7 @@ class SuperTabController extends ChangeNotifier {
required this.request,
required this.save,
this.upload = refuseUpload,
+ this.avatarUpload = refuseAvatarUpload,
this.uploadTimeout = const Duration(minutes: 2),
Map<String, dynamic> initial = const {},
this.pollInterval = const Duration(seconds: 3),
@@ -121,6 +123,9 @@ class SuperTabController extends ChangeNotifier {
/// Sends one file to the backend.
final SuperTabUpload upload;
+ /// Sends an avatar picture (profile_actions.dart).
+ final SuperTabAvatarUpload avatarUpload;
+
/// How long an upload may go without a byte moving before the send gives up.
final Duration uploadTimeout;
SuperTabSnapshot? snapshot;
@@ -468,6 +473,9 @@ class SuperTabController extends ChangeNotifier {
}
bool hasOlder(String id) => _before[id] != null;
+
+ /// Each conversation's reaction counter as its last page said it.
+ final _reactionSeq = <String, int>{};
int _loadedMessageSequence(String id) =>
_messages[id]?.reversed
.where((m) => m.source['kind'] != 'update-request')
@@ -1299,6 +1307,15 @@ class SuperTabController extends ChangeNotifier {
}
/// The same messages with the same receipts: posted text does not change.
+ /// Whether [answer] says a reaction changed in [id] since its rows were
+ /// last refreshed: a poll then reads the page shown again (backend
+ /// reactions.ts). The first answer only records where it stands.
+ bool _reactionsMoved(String id, Map<String, dynamic> answer) {
+ final seq = answer['reactionSeq'];
+ final known = _reactionSeq[id];
+ return seq is int && known != null && known != seq;
+ }
+
static bool _sameMessages(
List<SuperTabMessage>? shown,
List<SuperTabMessage> next,
@@ -1306,7 +1323,9 @@ class SuperTabController extends ChangeNotifier {
if (shown == null || shown.length != next.length) return false;
for (var i = 0; i < next.length; i++) {
final a = shown[i], b = next[i];
- if (a.id != b.id || a.deliveries.length != b.deliveries.length) {
+ if (a.id != b.id ||
+ a.deliveries.length != b.deliveries.length ||
+ !_sameReactions(a.reactions, b.reactions)) {
return false;
}
for (var j = 0; j < b.deliveries.length; j++) {
@@ -1316,6 +1335,20 @@ class SuperTabController extends ChangeNotifier {
return true;
}
+ static bool _sameReactions(
+ List<SuperTabReactionCount> a,
+ List<SuperTabReactionCount> b,
+ ) =>
+ a.length == b.length &&
+ [
+ for (var i = 0; i < a.length; i++)
+ a[i].emoji == b[i].emoji &&
+ listEquals(
+ [for (final who in a[i].by) '${who.kind}:${who.id}'],
+ [for (final who in b[i].by) '${who.kind}:${who.id}'],
+ ),
+ ].every((same) => same);
+
String _messagesPath(String id) =>
'$_path/conversations/${Uri.encodeComponent(id)}/messages';
@@ -1422,16 +1455,32 @@ class SuperTabController extends ChangeNotifier {
: await request('GET', '${_messagesPath(id)}$query');
final arrived =
!older && tail != null && (answer['messages'] as List).isNotEmpty;
+ final reacted = !older && _reactionsMoved(id, answer);
+ // Recorded only once the rows are refreshed: a read that fails leaves
+ // the change for the next poll.
+ final reactionSeq = older ? null : answer['reactionSeq'];
if (!_disposed &&
!older &&
- !light &&
+ (!light || reacted) &&
tail != null &&
(answer['messages'] as List).isEmpty) {
- // No new text: refresh delivery receipts in the page already shown.
+ // No new text: refresh delivery receipts in the page already shown,
+ // and on a light read the counts of a reaction that changed there.
answer = await request(
'GET',
'$_path/conversations/${Uri.encodeComponent(id)}/messages?before=${tail + 1}',
);
+ } else if (!_disposed && reacted && arrived) {
+ // New messages and a changed reaction at once: the rows already shown
+ // need their counts too, so the latest page is read with the new ones.
+ final page = await request('GET', _messagesPath(id));
+ answer = {
+ ...answer,
+ 'messages': [
+ ...page['messages'] as List,
+ ...answer['messages'] as List,
+ ],
+ };
}
if (_disposed || accessRevoked || snapshot?.conversation(id) == null) {
return;
@@ -1499,6 +1548,7 @@ class SuperTabController extends ChangeNotifier {
// An adapting read that found nothing new changes nothing on screen.
final same = _policy.adapts && _sameMessages(_messages[id], next);
_messages[id] = next;
+ if (reactionSeq is int) _reactionSeq[id] = reactionSeq;
if (older || replacing || !_before.containsKey(id)) {
_before[id] = SuperTabPage.read(answer['next']);
}
diff --git a/desktop/lib/super_tabs/identity.dart b/desktop/lib/super_tabs/identity.dart
index 5c5df3df9..153bfc1c4 100644
--- a/desktop/lib/super_tabs/identity.dart
+++ b/desktop/lib/super_tabs/identity.dart
@@ -1,59 +1,150 @@
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import '../widgets/desktop_chrome.dart';
+import '../widgets/engine_identity.dart';
+import 'avatar_art.dart';
+import 'model.dart';
+import 'until.dart';
-/// Stable across engine/model changes and shared by the roster and messages.
+/// The one avatar for a person or an agent everywhere in the Swarm: rows,
+/// messages, mentions, the Glance and the leaderboard. Stable across
+/// engine/model changes. An agent wears its engine as a small badge; a person
+/// their status emoji while it lasts.
class SuperTabAvatar extends StatelessWidget {
const SuperTabAvatar({
super.key,
required this.identity,
required this.name,
this.size = 30,
+ this.picture,
+ this.engine,
+ this.status,
+ this.pattern = false,
+ this.now,
});
+
+ SuperTabAvatar.person(
+ SuperTabPerson person, {
+ super.key,
+ this.size = 30,
+ this.now,
+ }) : identity = 'person:${person.id}',
+ name = superTabPersonName(person.email),
+ picture = person.avatar,
+ engine = null,
+ status = person.status,
+ pattern = false;
+
+ /// [engineBadge] off where the row already shows the engine beside the
+ /// name (the roster, messages), so it shows once.
+ SuperTabAvatar.agent(
+ SuperTabAgent agent, {
+ super.key,
+ String? name,
+ this.size = 30,
+ bool engineBadge = true,
+ }) : identity = 'agent:${agent.id}',
+ name = name ?? agent.displayName ?? agent.name,
+ picture = agent.avatar,
+ engine = engineBadge ? agent.engine : null,
+ status = null,
+ pattern = true,
+ now = null;
+
final String identity, name;
final double size;
+ final SuperTabAvatarPicture? picture;
+
+ /// The agent's engine, drawn as its badge; null for a person.
+ final String? engine;
+
+ /// The person's status; it shows until its time, and the avatar redraws
+ /// then by itself.
+ final SuperTabPersonStatus? status;
+
+ /// A fixed time to judge [status] by; the clock's when null.
+ final DateTime? now;
+
+ /// Draw the agent pattern rather than an initial when there is no picture.
+ final bool pattern;
@override
Widget build(BuildContext context) {
- var hash = 0;
- for (final rune in identity.runes) {
- hash = (hash * 31 + rune) & 0x7fffffff;
- }
- hash = ((hash ^ (hash >> 16)) * 0x45d9f3b) & 0x7fffffff;
- final color = HSLColor.fromAHSL(
- 1,
- (hash % 360).toDouble(),
- .42,
- Theme.of(context).brightness == Brightness.dark ? .72 : .36,
- ).toColor();
- final words = name
- .trim()
- .split(RegExp(r'[\s@._-]+'))
- .where((w) => w.isNotEmpty)
- .toList();
- final initial = words.isEmpty
- ? '?'
- : words.first.characters.first.toUpperCase();
- return Container(
- width: size,
- height: size,
- alignment: Alignment.center,
- decoration: BoxDecoration(
- color: color.withValues(alpha: .14),
- shape: BoxShape.circle,
- ),
- child: Text(
- initial,
- textScaler: TextScaler.noScaling,
- style: DesktopChrome.control(
- medium: true,
- color: color,
- ).copyWith(fontSize: size * .43),
+ final badge = size * .46;
+ final face = SuperTabAvatarFace(
+ identity: identity,
+ name: name,
+ size: size,
+ picture: picture,
+ pattern: pattern,
+ );
+ return SuperTabUntil(
+ until: now == null ? status?.until : null,
+ builder: (context) => _drawn(face, badge),
+ );
+ }
+
+ Widget _drawn(Widget face, double badge) {
+ final status = this.status?.shownAt(now ?? clock.now()) == true
+ ? this.status
+ : null;
+ return Semantics(
+ label: status == null ? null : '$name, ${status.label}',
+ child: SizedBox.square(
+ dimension: size,
+ child: Stack(
+ clipBehavior: Clip.none,
+ children: [
+ face,
+ if (engine case final engine? when engine.isNotEmpty)
+ Positioned(
+ right: -badge * .2,
+ bottom: -badge * .2,
+ child: _Badge(
+ size: badge,
+ child: EngineMark(engine: engine, size: badge * .72),
+ ),
+ ),
+ if (status?.emoji case final emoji?)
+ Positioned(
+ right: -badge * .2,
+ bottom: -badge * .2,
+ child: _Badge(
+ size: badge,
+ child: Text(
+ emoji,
+ textScaler: TextScaler.noScaling,
+ style: TextStyle(fontSize: badge * .66, height: 1),
+ ),
+ ),
+ ),
+ ],
+ ),
),
);
}
}
+class _Badge extends StatelessWidget {
+ const _Badge({required this.size, required this.child});
+ final double size;
+ final Widget child;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ width: size,
+ height: size,
+ alignment: Alignment.center,
+ decoration: BoxDecoration(
+ color: DesktopChrome.surface,
+ shape: BoxShape.circle,
+ border: Border.all(color: DesktopChrome.rim, width: .5),
+ ),
+ child: child,
+ );
+}
+
String superTabPersonName(String email) => email.split('@').first;
/// A computer as it calls itself: a Bonjour hostname without its `.local` suffix ("MacBookPro2021"), never mapped
diff --git a/desktop/lib/super_tabs/leaderboard/person_row.dart b/desktop/lib/super_tabs/leaderboard/person_row.dart
index 2f16b984b..ad86f71b6 100644
--- a/desktop/lib/super_tabs/leaderboard/person_row.dart
+++ b/desktop/lib/super_tabs/leaderboard/person_row.dart
@@ -1,8 +1,11 @@
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import '../../widgets/desktop_chrome.dart';
import '../../widgets/finger_target.dart';
import '../identity.dart';
+import '../model.dart';
+import '../until.dart';
import 'format.dart';
import 'model.dart';
@@ -13,19 +16,18 @@ const _nameInset = 32.0;
TextStyle _figures(TextStyle style) =>
style.copyWith(fontFeatures: const [FontFeature.tabularFigures()]);
-/// One person in the Humans section: avatar, name and this week's points in
-/// fixed columns, with Shipped, Unblocked and Lent on a quiet line beneath.
-/// Without a [score] (no board yet, or a server without one) only the name.
+/// One person in the Humans section: avatar, name, status and this week's
+/// points in fixed columns, with Shipped, Unblocked and Lent on a quiet line
+/// beneath. Without a [score] (no board yet, or a server without one) only the
+/// name and status.
class LeaderboardPersonRow extends StatelessWidget {
const LeaderboardPersonRow({
super.key,
- required this.personId,
- required this.name,
- required this.email,
+ required this.person,
required this.score,
required this.onTap,
});
- final String personId, name, email;
+ final SuperTabPerson person;
final SuperTabPersonScore? score;
final VoidCallback onTap;
@@ -44,7 +46,7 @@ class LeaderboardPersonRow extends StatelessWidget {
),
);
return InkWell(
- key: ValueKey('super-person-$personId'),
+ key: ValueKey('super-person-${person.id}'),
onTap: onTap,
child: ConstrainedBox(
// A phone's row is a finger's height; a mouse keeps 36.
@@ -60,20 +62,29 @@ class LeaderboardPersonRow extends StatelessWidget {
children: [
Row(
children: [
- SuperTabAvatar(
- identity: 'person:$personId',
- name: name,
- size: 24,
- ),
+ SuperTabAvatar.person(person, size: 24),
const SizedBox(width: _nameInset - 24),
Expanded(
child: Tooltip(
- message: email,
- child: Text(
- name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(),
+ message: person.email,
+ child: SuperTabUntil(
+ until: person.status?.until,
+ builder: (context) => Text.rich(
+ TextSpan(
+ text: superTabPersonName(person.email),
+ children: [
+ if (person.statusAt(clock.now())
+ case final status?)
+ TextSpan(
+ text: ' ${status.text}',
+ style: DesktopChrome.metadata(),
+ ),
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(),
+ ),
),
),
),
diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dart
index 2a92778a2..67484fa1c 100644
--- a/desktop/lib/super_tabs/machines.dart
+++ b/desktop/lib/super_tabs/machines.dart
@@ -1733,11 +1733,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {
SizedBox(
width: 32,
child: Center(
- child: SuperTabAvatar(
- identity: 'agent:${agent.id}',
- name: name,
- size: 22,
- ),
+ child: SuperTabAvatar.agent(agent, name: name, size: 22),
),
),
Expanded(
@@ -2175,11 +2171,7 @@ class _MachineLine extends StatelessWidget {
padding: const EdgeInsets.only(left: 6),
child: Tooltip(
message: 'Owned by ${superTabPersonName(owner.email)}',
- child: SuperTabAvatar(
- identity: 'person:${owner.id}',
- name: superTabPersonName(owner.email),
- size: 20,
- ),
+ child: SuperTabAvatar.person(owner, size: 20),
),
),
if (view.cleaning)
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 62bc3deea..9f4455933 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -12,6 +12,7 @@ import 'identity.dart';
import 'message_text.dart';
import 'model.dart';
import 'pull_requests.dart';
+import 'reactions.dart';
/// Presentation only. Message identity and reply routing use backend IDs.
class SuperTabMessageRow extends StatefulWidget {
@@ -22,6 +23,7 @@ class SuperTabMessageRow extends StatefulWidget {
required this.onReturnToComposer,
required this.receipts,
this.agent,
+ this.person,
this.machineName,
this.reply,
this.replyAuthor,
@@ -33,6 +35,9 @@ class SuperTabMessageRow extends StatefulWidget {
this.references = const {},
this.onOpenGroup,
this.mentions = const [],
+ this.readerId = '',
+ this.reactorName,
+ this.onReact,
});
final SuperTabMessage message;
@@ -43,6 +48,9 @@ class SuperTabMessageRow extends StatefulWidget {
final ValueChanged<String>? onOpenGroup;
final String author;
final SuperTabAgent? agent;
+
+ /// The person who wrote it, while they are in the Swarm.
+ final SuperTabPerson? person;
final String? machineName;
final SuperTabMessage? reply;
final String? replyAuthor;
@@ -58,6 +66,12 @@ class SuperTabMessageRow extends StatefulWidget {
final VoidCallback onReturnToComposer;
final List<Widget> receipts;
+ /// The reader, whose own reactions are marked; [reactorName] names the
+ /// others. Without [onReact] the counts only show.
+ final String readerId;
+ final SuperTabReactorName? reactorName;
+ final ValueChanged<SuperTabReactionEmoji>? onReact;
+
// Routing notes share the message body column, including grouped messages.
static const horizontalInset = 24.0;
static const avatarSize = 28.0;
@@ -148,6 +162,30 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
].join(' · ');
}
+ Widget _avatar(SuperTabMessage message) {
+ const size = SuperTabMessageRow.avatarSize;
+ if (widget.agent case final agent?) {
+ return SuperTabAvatar.agent(
+ agent,
+ name: widget.author,
+ size: size,
+ engineBadge: false,
+ );
+ }
+ if (widget.person case final person? when !message.fromAgent) {
+ return SuperTabAvatar.person(person, size: size);
+ }
+ // Someone no longer in the Swarm keeps the face their recorded name gives.
+ return SuperTabAvatar(
+ identity: '${message.author['kind']}:${message.authorId}',
+ name: message.fromAgent
+ ? widget.author
+ : superTabPersonName(message.authorName),
+ size: size,
+ pattern: message.fromAgent,
+ );
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -224,16 +262,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
: ExcludeSemantics(
child: Tooltip(
message: _identityDetails,
- child: SuperTabAvatar(
- identity:
- '${message.author['kind']}:${message.authorId}',
- name: message.fromAgent
- ? widget.author
- : superTabPersonName(
- message.authorName,
- ),
- size: SuperTabMessageRow.avatarSize,
- ),
+ child: _avatar(message),
),
),
),
@@ -339,6 +368,12 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
),
),
SuperTabPullRequestLinks(message.text),
+ SuperTabReactionBar(
+ message: message,
+ readerId: widget.readerId,
+ nameOf: widget.reactorName ?? (_, id) => id,
+ onReact: widget.onReact,
+ ),
...widget.receipts,
],
),
@@ -364,6 +399,8 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
+ if (widget.onReact case final react?)
+ SuperTabReactionPicker(onReact: react),
if (widget.onReply != null)
fingerTarget(
enabled: phone,
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index b98081e29..a01613692 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -1,3 +1,8 @@
+import 'identity.dart' show superTabPersonName;
+import 'profile_model.dart';
+
+export 'profile_model.dart';
+
/// Backend records are independent of the desktop's visible panes and tab layout.
Map<String, dynamic> superTabMap(Object? value) => value is Map
? Map<String, dynamic>.from(value)
@@ -27,8 +32,16 @@ class SuperTabPerson {
: id = _text(row, 'id'),
email = _text(row, 'email'),
role = _text(row, 'role'),
- generation = row['generation'] as String?;
+ generation = row['generation'] as String?,
+ avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
+ status = SuperTabPersonStatus.fromJson(row['status']);
final String id, email, role;
+ final SuperTabAvatarPicture? avatar;
+ final SuperTabPersonStatus? status;
+
+ /// Their status while it lasts.
+ SuperTabPersonStatus? statusAt(DateTime now) =>
+ status?.shownAt(now) == true ? status : null;
/// This membership: a new one each time the person joins the Swarm. Null
/// from a backend that does not send it.
@@ -51,10 +64,14 @@ class SuperTabAgent {
role = row['role'] as String?,
roleId = row['roleId'] as String?,
limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),
+ avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
downSince = DateTime.tryParse(row['downSince'] as String? ?? ''),
configuration = Map.unmodifiable(superTabMap(row['configuration']));
final String id, projectId, name, machineId, harnessId, contributorId;
+ /// Set by its contributor or its project's Lead; null draws its pattern.
+ final SuperTabAvatarPicture? avatar;
+
/// Until when routing skips it: its machine saw a usage limit on its screen
/// (spec/2026-10-23-lead-sees-agent-terminal.md). Null when none was seen.
final DateTime? limitedUntil;
@@ -401,7 +418,7 @@ class SuperTabSnapshot {
// Recorded labels remain the fallback for agents no longer in the Swarm.
String authorName(SuperTabMessage message) => message.fromAgent
? agentName(message.authorId, fallback: message.authorName)
- : message.authorName;
+ : 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
@@ -688,6 +705,9 @@ class SuperTabMessage {
source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),
createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),
attachments = _attachments(row['attachments']),
+ reactions = List.unmodifiable(
+ SuperTabReactionCount.listFromJson(row['reactions']),
+ ),
mentions = List.unmodifiable(
(row['mentions'] as List?)?.whereType<String>() ?? const <String>[],
),
@@ -702,6 +722,7 @@ class SuperTabMessage {
final Map<String, dynamic> source;
final DateTime? createdAt;
final List<SuperTabAttachment> attachments;
+ final List<SuperTabReactionCount> reactions;
/// The people a Lead tagged in this message, by person id.
final List<String> mentions;
diff --git a/desktop/lib/super_tabs/notifications.dart b/desktop/lib/super_tabs/notifications.dart
index 7009e5341..395224fd5 100644
--- a/desktop/lib/super_tabs/notifications.dart
+++ b/desktop/lib/super_tabs/notifications.dart
@@ -7,6 +7,7 @@ import '../notify/system_notifications.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../widgets/desktop_chrome.dart';
import 'controller.dart';
+import 'identity.dart';
import 'machine_status.dart' show superTabAgo;
import 'model.dart';
import 'pm_chat.dart';
@@ -21,12 +22,16 @@ class SuperTabMention {
conversationId = row['conversationId'] as String,
conversationTitle = row['conversationTitle'] as String? ?? '',
messageId = row['messageId'] as String,
+ leadId = row['leadId'] as String?,
leadName = row['leadName'] as String? ?? 'Lead',
text = row['text'] as String? ?? '',
createdAt = DateTime.tryParse(row['createdAt'] as String? ?? ''),
resolvedBy = row['resolvedBy'] as String?;
final String id, projectId, projectName, conversationId, conversationTitle;
final String messageId, leadName, text;
+
+ /// The Lead who tagged; null from a backend that does not send it.
+ final String? leadId;
final DateTime? createdAt;
/// `reply` or `done` once it moved to Earlier; null while it waits.
@@ -247,7 +252,20 @@ class _SuperTabNotificationsState extends State<SuperTabNotifications> {
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 10, 8, 10),
child: Row(
+ crossAxisAlignment: CrossAxisAlignment.start,
children: [
+ if (widget.mentions.controller.snapshot?.agent(
+ mention.leadId ?? '',
+ )
+ case final lead?)
+ Padding(
+ padding: const EdgeInsets.only(right: 10, top: 2),
+ child: SuperTabAvatar.agent(
+ lead,
+ name: mention.leadName,
+ size: 24,
+ ),
+ ),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
diff --git a/desktop/lib/super_tabs/parts.dart b/desktop/lib/super_tabs/parts.dart
index ad42a8499..0ad5813c0 100644
--- a/desktop/lib/super_tabs/parts.dart
+++ b/desktop/lib/super_tabs/parts.dart
@@ -234,13 +234,24 @@ class SuperTabParts {
Map<String, dynamic> get state {
final agentsDerived = _derivedMap('agents');
final machinesDerived = _derivedMap('machines');
+ final avatars = _derivedMap('avatars');
final state = <String, dynamic>{
...superTabMap(_head['data']),
'format': superTabReadFormat,
- 'people': [for (final p in _data('members')) p],
+ 'people': [
+ for (final p in _data('members'))
+ _avatarLink(p, avatars['person:${p['id']}']),
+ ],
'agents': [
for (final agent in _data('agents'))
- _overlay(agent, agentsDerived[agent['id']], keepNull: 'workDecision'),
+ _avatarLink(
+ _overlay(
+ agent,
+ agentsDerived[agent['id']],
+ keepNull: 'workDecision',
+ ),
+ avatars['agent:${agent['id']}'],
+ ),
],
'conversations': [
..._data('groups'),
@@ -312,6 +323,21 @@ class SuperTabParts {
Map<String, dynamic> _derivedMap(String name) =>
_derived[name] is Map ? superTabMap(_derived[name]) : const {};
+ /// [record] with its uploaded avatar's signed link from this read (backend avatarLinks.ts), which never stays in a part.
+ static Map<String, dynamic> _avatarLink(
+ Map<String, dynamic> record,
+ Object? link,
+ ) {
+ final avatar = record['avatar'];
+ final uploaded =
+ link is String && avatar is Map && avatar['kind'] == 'upload';
+ if (!uploaded) return record;
+ return {
+ ...record,
+ 'avatar': {...avatar, 'url': link},
+ };
+ }
+
/// [record] with the derived values over it. A null [keepNull] value means the stored one stands.
static Map<String, dynamic> _overlay(
Map<String, dynamic> record,
diff --git a/desktop/lib/super_tabs/profile_actions.dart b/desktop/lib/super_tabs/profile_actions.dart
new file mode 100644
index 000000000..aabf73248
--- /dev/null
+++ b/desktop/lib/super_tabs/profile_actions.dart
@@ -0,0 +1,94 @@
+import 'dart:typed_data';
+
+import 'avatar_upload.dart';
+import 'controller.dart';
+import 'model.dart';
+
+/// Status, avatars and reactions. Each is safe to send again, so each goes as
+/// its own request rather than waiting behind a message being sent; the
+/// answer is null when it went through, or what to tell the person.
+extension SuperTabProfileActions on SuperTabController {
+ Future<String?> setStatus(SuperTabPersonStatus? status) => _profile({
+ 'type': 'member.status',
+ 'status': status == null
+ ? null
+ : {
+ 'text': status.text,
+ 'emoji': ?status.emoji,
+ if (status.until case final until?)
+ 'until': until.toUtc().toIso8601String(),
+ },
+ });
+
+ /// [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].
+ Future<String?> setAvatar(SuperTabPresetAvatar? preset, {String? agentId}) =>
+ _profile({
+ 'type': agentId == null ? 'member.avatar' : 'agent.avatar',
+ 'agentId': ?agentId,
+ 'avatar': preset == null ? null : {'kind': 'preset', 'key': preset.key},
+ });
+
+ /// Resizes [picked] here, uploads it and makes it the avatar.
+ Future<String?> uploadAvatar(Uint8List picked, {String? agentId}) async {
+ if (!canWrite) return _readOnly;
+ try {
+ final png = await superTabAvatarPng(picked);
+ if (png.length > kSuperTabAvatarMaxBytes) {
+ return 'That picture is over 1 MB.';
+ }
+ final answer = await avatarUpload(tabId: tabId, png: png);
+ final id = superTabMap(answer['avatar'])['id'] as String;
+ return await _profile({
+ 'type': agentId == null ? 'member.avatar' : 'agent.avatar',
+ 'agentId': ?agentId,
+ 'avatar': {'kind': 'upload', 'id': id},
+ });
+ } on SuperTabFailure catch (failure) {
+ return failure.message;
+ }
+ }
+
+ /// Adds the reader's [emoji] to [message], or takes it back when it is
+ /// already theirs.
+ Future<String?> react(
+ SuperTabMessage message,
+ SuperTabReactionEmoji emoji,
+ ) async {
+ final mine = message.reactions.any(
+ (r) => r.emoji == emoji && r.includes('person', accountId),
+ );
+ final failure = await _send({
+ 'type': 'message.react',
+ 'conversationId': message.conversationId,
+ 'messageId': message.id,
+ 'emoji': emoji.key,
+ 'on': !mine,
+ });
+ if (failure == null) await loadMessages(message.conversationId);
+ return failure;
+ }
+
+ Future<String?> _profile(Map<String, dynamic> command) async {
+ final failure = await _send(command);
+ if (failure == null) await refresh();
+ return failure;
+ }
+
+ Future<String?> _send(Map<String, dynamic> command) async {
+ if (!canWrite) return _readOnly;
+ try {
+ await request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/commands',
+ body: {'operationId': superTabOperationId(), 'command': command},
+ );
+ return null;
+ } on SuperTabFailure catch (failure) {
+ return failure.message;
+ }
+ }
+}
+
+const _readOnly = 'You have read-only access to this Swarm.';
diff --git a/desktop/lib/super_tabs/profile_model.dart b/desktop/lib/super_tabs/profile_model.dart
new file mode 100644
index 000000000..fdb1a48d4
--- /dev/null
+++ b/desktop/lib/super_tabs/profile_model.dart
@@ -0,0 +1,131 @@
+/// Avatars, status lines and reactions as the backend sends them
+/// (backend superTabs/profile.ts and reactions.ts). Only Swarm members read
+/// them; a value this build does not know reads as absent.
+library;
+
+/// What a member or agent shows instead of the default.
+sealed class SuperTabAvatarPicture {
+ const SuperTabAvatarPicture();
+
+ static SuperTabAvatarPicture? fromJson(Object? value) => switch (value) {
+ {'kind': 'upload', 'url': final String url} => SuperTabUploadedAvatar.of(
+ url,
+ ),
+ {'kind': 'preset', 'key': final String key}
+ when superTabAvatarPresets.containsKey(key) =>
+ SuperTabPresetAvatar(key),
+ _ => null,
+ };
+}
+
+/// Where the backend's private avatar bucket serves its signed links
+/// (backend superTabs/avatarLinks.ts): Cloud Storage's own host.
+const kSuperTabAvatarHost = String.fromEnvironment(
+ 'SUPER_TAB_AVATARS_HOST',
+ defaultValue: 'storage.googleapis.com',
+);
+
+/// A picture someone uploaded, through the signed link a member read carries:
+/// https on the avatar host only, never a public or outside address.
+class SuperTabUploadedAvatar extends SuperTabAvatarPicture {
+ const SuperTabUploadedAvatar._(this.url);
+ final Uri url;
+
+ static SuperTabUploadedAvatar? of(String value) {
+ final url = Uri.tryParse(value);
+ return url != null &&
+ url.scheme == 'https' &&
+ url.host == kSuperTabAvatarHost
+ ? SuperTabUploadedAvatar._(url)
+ : null;
+ }
+}
+
+class SuperTabPresetAvatar extends SuperTabAvatarPicture {
+ const SuperTabPresetAvatar(this.key);
+ final String key;
+ String get glyph => superTabAvatarPresets[key]!;
+}
+
+/// The pictures a person may pick (backend AVATAR_PRESETS), in offer order.
+const superTabAvatarPresets = {
+ 'fox': '🦊',
+ 'owl': '🦉',
+ 'cat': '🐱',
+ 'panda': '🐼',
+ 'octopus': '🐙',
+ 'cactus': '🌵',
+ 'rocket': '🚀',
+ 'sun': '🌞',
+};
+
+/// A person's short status. Shown until [until] passes.
+class SuperTabPersonStatus {
+ const SuperTabPersonStatus({required this.text, this.emoji, this.until});
+ final String text;
+ final String? emoji;
+ final DateTime? until;
+
+ static SuperTabPersonStatus? fromJson(Object? value) => switch (value) {
+ {'text': final String text} when text.trim().isNotEmpty =>
+ SuperTabPersonStatus(
+ text: text,
+ emoji: value['emoji'] is String ? value['emoji'] as String : null,
+ until: DateTime.tryParse(value['until'] as String? ?? ''),
+ ),
+ _ => null,
+ };
+
+ String get label => emoji == null ? text : '$emoji $text';
+ bool shownAt(DateTime now) => until == null || now.isBefore(until!);
+}
+
+/// The status emoji a person may pick, with the words each offers
+/// (backend STATUS_EMOJI).
+const superTabStatusPresets = [
+ ('🎯', 'Focusing'),
+ ('☕', 'Coffee break'),
+ ('🍽️', 'At lunch'),
+ ('🌴', 'Out of office'),
+ ('🚶', 'Away'),
+ ('🤒', 'Out sick'),
+];
+
+/// The reactions a message can carry, in the order counts show.
+enum SuperTabReactionEmoji {
+ thumbsUp('thumbs_up', '👍'),
+ tada('tada', '🎉'),
+ heart('heart', '❤️'),
+ laugh('laugh', '😄'),
+ eyes('eyes', '👀'),
+ rocket('rocket', '🚀');
+
+ const SuperTabReactionEmoji(this.key, this.glyph);
+ final String key, glyph;
+
+ static SuperTabReactionEmoji? of(Object? key) =>
+ values.where((e) => e.key == key).firstOrNull;
+}
+
+/// One emoji's count on one message, and who gave it.
+class SuperTabReactionCount {
+ const SuperTabReactionCount(this.emoji, this.by);
+ final SuperTabReactionEmoji emoji;
+ final List<({String kind, String id})> by;
+ int get count => by.length;
+
+ bool includes(String kind, String id) =>
+ by.any((who) => who.kind == kind && who.id == id);
+
+ static List<SuperTabReactionCount> listFromJson(Object? value) => [
+ if (value is List)
+ for (final row in value)
+ if (row case {'emoji': final Object key}
+ when SuperTabReactionEmoji.of(key) != null)
+ SuperTabReactionCount(SuperTabReactionEmoji.of(key)!, [
+ for (final who in row['by'] as List? ?? const [])
+ if (who case {'kind': final String kind, 'id': final String id})
+ (kind: kind, id: id),
+ ]),
+ ];
+}
diff --git a/desktop/lib/super_tabs/profile_sheet.dart b/desktop/lib/super_tabs/profile_sheet.dart
new file mode 100644
index 000000000..bff64c8e2
--- /dev/null
+++ b/desktop/lib/super_tabs/profile_sheet.dart
@@ -0,0 +1,189 @@
+import 'package:clock/clock.dart';
+
+import 'dart:async';
+import 'dart:typed_data';
+
+import 'package:file_selector/file_selector.dart';
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_dialog.dart';
+import '../widgets/desktop_chrome.dart';
+import 'controller.dart';
+import 'identity.dart';
+import 'model.dart';
+import 'profile_actions.dart';
+import 'status_editor.dart';
+
+/// Picks one picture from this computer, or null when the person cancels.
+Future<Uint8List?> pickSuperTabPicture() async {
+ final file = await openFile(
+ acceptedTypeGroups: const [
+ XTypeGroup(label: 'Pictures', extensions: ['png', 'jpg', 'jpeg', 'webp']),
+ ],
+ );
+ return file?.readAsBytes();
+}
+
+/// 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.
+Future<void> showSuperTabProfile(
+ BuildContext context,
+ SuperTabController controller, {
+ String? agentId,
+ Future<Uint8List?> Function() pickPicture = pickSuperTabPicture,
+}) => showAppDialog<void>(
+ context: context,
+ builder: (context) => _ProfileSheet(
+ controller: controller,
+ agentId: agentId,
+ pickPicture: pickPicture,
+ ),
+);
+
+class _ProfileSheet extends StatefulWidget {
+ const _ProfileSheet({
+ required this.controller,
+ required this.agentId,
+ required this.pickPicture,
+ });
+ final SuperTabController controller;
+ final String? agentId;
+ final Future<Uint8List?> Function() pickPicture;
+
+ @override
+ State<_ProfileSheet> createState() => _ProfileSheetState();
+}
+
+class _ProfileSheetState extends State<_ProfileSheet> {
+ bool _busy = false;
+ String? _error;
+
+ SuperTabController get c => widget.controller;
+
+ Future<void> _run(Future<String?> Function() action) async {
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ final error = await action();
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ });
+ }
+
+ Future<void> _upload() async {
+ final picked = await widget.pickPicture();
+ if (picked == null) return;
+ await _run(() => c.uploadAvatar(picked, agentId: widget.agentId));
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: c,
+ builder: (context, _) {
+ final agent = widget.agentId == null
+ ? null
+ : c.snapshot?.agent(widget.agentId!);
+ final person = c.snapshot?.people
+ .where((p) => p.id == c.accountId)
+ .firstOrNull;
+ final avatar = agent != null
+ ? SuperTabAvatar.agent(agent, size: 56)
+ : person != null
+ ? SuperTabAvatar.person(person, size: 56)
+ : null;
+ final current = agent?.avatar ?? (agent == null ? person?.avatar : null);
+ return AlertDialog(
+ title: Text(
+ agent == null
+ ? 'Your profile'
+ : '${c.snapshot!.agentName(agent.id)}’s avatar',
+ ),
+ content: SizedBox(
+ width: 380,
+ child: SingleChildScrollView(
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ ?avatar,
+ const SizedBox(height: 16),
+ Text('Picture', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 6,
+ runSpacing: 6,
+ children: [
+ for (final MapEntry(:key, :value)
+ in superTabAvatarPresets.entries)
+ IconButton(
+ key: ValueKey('super-avatar-preset-$key'),
+ tooltip: key,
+ isSelected:
+ current is SuperTabPresetAvatar &&
+ current.key == key,
+ onPressed: _busy
+ ? null
+ : () => _run(
+ () => c.setAvatar(
+ SuperTabPresetAvatar(key),
+ agentId: widget.agentId,
+ ),
+ ),
+ icon: Text(value, style: const TextStyle(fontSize: 22)),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ children: [
+ OutlinedButton(
+ onPressed: _busy ? null : () => unawaited(_upload()),
+ child: const Text('Upload picture…'),
+ ),
+ if (current != null)
+ TextButton(
+ onPressed: _busy
+ ? null
+ : () => _run(
+ () =>
+ c.setAvatar(null, agentId: widget.agentId),
+ ),
+ child: const Text('Use default'),
+ ),
+ ],
+ ),
+ if (agent == null && person != null) ...[
+ const SizedBox(height: 20),
+ SuperTabStatusEditor(
+ status: person.statusAt(clock.now()),
+ busy: _busy,
+ onSave: (status) => _run(() => c.setStatus(status)),
+ ),
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(
+ error,
+ style: DesktopChrome.control(
+ color: Theme.of(context).colorScheme.error,
+ ),
+ ),
+ ],
+ ],
+ ),
+ ),
+ ),
+ actions: [
+ TextButton(
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ],
+ );
+ },
+ );
+}
diff --git a/desktop/lib/super_tabs/reactions.dart b/desktop/lib/super_tabs/reactions.dart
new file mode 100644
index 000000000..720daab41
--- /dev/null
+++ b/desktop/lib/super_tabs/reactions.dart
@@ -0,0 +1,158 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import 'model.dart';
+
+/// Who gave a reaction, as the view names them.
+typedef SuperTabReactorName = String Function(String kind, String id);
+
+/// The counts under a message. A chip is the reader's own when they gave it;
+/// tapping it takes theirs back or adds it. Without [onReact] (a reader who
+/// cannot write) the counts only show.
+class SuperTabReactionBar extends StatelessWidget {
+ const SuperTabReactionBar({
+ super.key,
+ required this.message,
+ required this.readerId,
+ required this.nameOf,
+ this.onReact,
+ });
+ final SuperTabMessage message;
+ final String readerId;
+ final SuperTabReactorName nameOf;
+ final ValueChanged<SuperTabReactionEmoji>? onReact;
+
+ @override
+ Widget build(BuildContext context) {
+ if (message.reactions.isEmpty) return const SizedBox.shrink();
+ return Padding(
+ padding: const EdgeInsets.only(top: 6),
+ child: Wrap(
+ spacing: 6,
+ runSpacing: 4,
+ children: [
+ for (final reaction in message.reactions)
+ _Chip(
+ key: ValueKey(
+ 'super-reaction-${message.id}-${reaction.emoji.key}',
+ ),
+ reaction: reaction,
+ mine: reaction.includes('person', readerId),
+ names: _names(reaction),
+ onTap: onReact == null ? null : () => onReact!(reaction.emoji),
+ ),
+ ],
+ ),
+ );
+ }
+
+ String _names(SuperTabReactionCount reaction) {
+ final names = [for (final who in reaction.by) nameOf(who.kind, who.id)];
+ return names.length < 2
+ ? names.join()
+ : '${names.sublist(0, names.length - 1).join(', ')} and ${names.last}';
+ }
+}
+
+class _Chip extends StatelessWidget {
+ const _Chip({
+ super.key,
+ required this.reaction,
+ required this.mine,
+ required this.names,
+ required this.onTap,
+ });
+ final SuperTabReactionCount reaction;
+ final bool mine;
+ final String names;
+ final VoidCallback? onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ final shape = RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ side: BorderSide(color: mine ? DesktopChrome.accent : DesktopChrome.rim),
+ );
+ return Tooltip(
+ message: names,
+ excludeFromSemantics: true,
+ child: Semantics(
+ button: true,
+ selected: mine,
+ enabled: onTap != null,
+ label: '${reaction.emoji.glyph} ${reaction.count}, $names',
+ child: Material(
+ color: mine ? DesktopChrome.selection : grid.AppSurface.recess,
+ shape: shape,
+ clipBehavior: Clip.antiAlias,
+ child: InkWell(
+ onTap: onTap,
+ child: ExcludeSemantics(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(reaction.emoji.glyph),
+ const SizedBox(width: 4),
+ Text(
+ '${reaction.count}',
+ style: DesktopChrome.metadata(
+ color: mine ? DesktopChrome.accent : null,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The message action that adds a reaction: the small set, one tap each.
+class SuperTabReactionPicker extends StatefulWidget {
+ const SuperTabReactionPicker({super.key, required this.onReact});
+ final ValueChanged<SuperTabReactionEmoji> onReact;
+
+ @override
+ State<SuperTabReactionPicker> createState() => _SuperTabReactionPickerState();
+}
+
+class _SuperTabReactionPickerState extends State<SuperTabReactionPicker> {
+ final _menu = MenuController();
+
+ @override
+ Widget build(BuildContext context) => MenuAnchor(
+ controller: _menu,
+ menuChildren: [
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 4),
+ child: Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ for (final emoji in SuperTabReactionEmoji.values)
+ IconButton(
+ tooltip: emoji.key.replaceAll('_', ' '),
+ onPressed: () {
+ _menu.close();
+ widget.onReact(emoji);
+ },
+ icon: Text(emoji.glyph, style: const TextStyle(fontSize: 18)),
+ ),
+ ],
+ ),
+ ),
+ ],
+ builder: (context, menu, _) => IconButton(
+ tooltip: 'Add reaction',
+ iconSize: 16,
+ visualDensity: VisualDensity.compact,
+ onPressed: () => menu.isOpen ? menu.close() : menu.open(),
+ icon: const Text('🙂', style: TextStyle(fontSize: 14)),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/roster.dart b/desktop/lib/super_tabs/roster.dart
index 5db6dbe94..7572993bb 100644
--- a/desktop/lib/super_tabs/roster.dart
+++ b/desktop/lib/super_tabs/roster.dart
@@ -26,6 +26,7 @@ import 'leaderboard/person_row.dart';
import 'leaderboard/reader.dart';
import 'leaderboard/waiting_line.dart';
import 'model.dart';
+import 'profile_sheet.dart';
import 'section_heading.dart';
import 'team_glance.dart';
import 'team_glance_panel.dart';
@@ -240,7 +241,8 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
return native ?? HarnessActivity.unknown;
}
- /// A person's email and role, and their week when the board has them.
+ /// A person's email and role, and their week when the board has them. One's
+ /// own also opens the profile sheet, where one's avatar and status change.
Future<void> _person(SuperTabPerson person, SuperTabPersonScore? score) =>
showAppDialog<void>(
context: context,
@@ -258,6 +260,15 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
],
),
actions: [
+ if (person.id == c.accountId && c.canWrite)
+ TextButton(
+ key: const ValueKey('super-profile-edit'),
+ onPressed: () {
+ Navigator.pop(context);
+ showSuperTabProfile(this.context, c);
+ },
+ child: const Text('Edit profile'),
+ ),
TextButton(
onPressed: () {
Navigator.pop(context);
@@ -424,10 +435,11 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
contentPadding: const EdgeInsets.symmetric(horizontal: 16),
title: Row(
children: [
- SuperTabAvatar(
- identity: 'agent:${agent.id}',
+ SuperTabAvatar.agent(
+ agent,
name: name,
size: 24,
+ engineBadge: false,
),
const SizedBox(width: 8),
Expanded(child: _agentIdentity(name, role, badge)),
@@ -550,9 +562,7 @@ class _SuperTabRosterState extends State<SuperTabRoster> {
),
for (final person in ranked)
LeaderboardPersonRow(
- personId: person.id,
- name: superTabPersonName(person.email),
- email: person.email,
+ person: person,
score: scores[person.id],
onTap: () => _person(person, scores[person.id]),
),
diff --git a/desktop/lib/super_tabs/ship_row.dart b/desktop/lib/super_tabs/ship_row.dart
new file mode 100644
index 000000000..3da4dc50f
--- /dev/null
+++ b/desktop/lib/super_tabs/ship_row.dart
@@ -0,0 +1,138 @@
+import 'package:flutter/material.dart';
+
+import '../widgets/desktop_chrome.dart';
+import 'confetti.dart';
+import 'controller.dart';
+import 'identity.dart';
+import 'model.dart';
+import 'pull_requests.dart';
+
+/// The project chat's line when linked work is Done (backend superTabs/ship.ts):
+/// what shipped, and who asked, built and reviewed it. A fresh one throws
+/// confetti, once per message on this computer.
+class SuperTabShipRow extends StatefulWidget {
+ const SuperTabShipRow({
+ super.key,
+ required this.message,
+ required this.controller,
+ this.now = DateTime.now,
+ });
+ final SuperTabMessage message;
+ final SuperTabController controller;
+ final DateTime Function() now;
+
+ /// How recent a celebration still is: an older one in the history is still.
+ static const fresh = Duration(minutes: 2);
+ static final _played = <String>{};
+ @visibleForTesting
+ static void resetPlayed() => _played.clear();
+
+ static bool shows(SuperTabMessage message) =>
+ message.source['kind'] == 'ship';
+
+ @override
+ State<SuperTabShipRow> createState() => _SuperTabShipRowState();
+}
+
+class _SuperTabShipRowState extends State<SuperTabShipRow> {
+ // Decided once, when the line first appears: a rebuild never cuts it short,
+ // and the same line drawn again later throws none.
+ late final bool _throws = () {
+ final at = widget.message.createdAt;
+ if (at == null || widget.now().difference(at) > SuperTabShipRow.fresh) {
+ return false;
+ }
+ return SuperTabShipRow._played.add(widget.message.id);
+ }();
+
+ SuperTabMessage get message => widget.message;
+
+ List<String> _ids(String key) => [
+ for (final id in message.source[key] as List? ?? const [])
+ if (id is String) id,
+ ];
+
+ @override
+ Widget build(BuildContext context) {
+ final snapshot = widget.controller.snapshot;
+ final title = message.source['title'] as String? ?? '';
+ final requester = snapshot?.people
+ .where((p) => p.id == message.source['requesterId'])
+ .firstOrNull;
+ Widget agents(String label, List<String> ids) => _Credit(label, [
+ for (final id in ids)
+ if (snapshot?.agent(id) case final agent?)
+ (SuperTabAvatar.agent(agent, size: 20), snapshot!.agentName(id)),
+ ]);
+ final line = Container(
+ margin: const EdgeInsets.fromLTRB(24, 12, 24, 0),
+ padding: const EdgeInsets.all(14),
+ decoration: BoxDecoration(
+ color: DesktopChrome.selection,
+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),
+ border: Border.all(color: DesktopChrome.accent.withValues(alpha: .4)),
+ ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Row(
+ children: [
+ const ExcludeSemantics(
+ child: Text('🎉', style: TextStyle(fontSize: 20)),
+ ),
+ const SizedBox(width: 8),
+ Expanded(
+ child: Text(
+ 'Shipped: $title',
+ style: DesktopChrome.control(medium: true),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 16,
+ runSpacing: 6,
+ children: [
+ if (requester != null)
+ _Credit('Requested by', [
+ (
+ SuperTabAvatar.person(requester, size: 20),
+ superTabPersonName(requester.email),
+ ),
+ ]),
+ agents('Built by', _ids('builderIds')),
+ agents('Reviewed by', _ids('reviewerIds')),
+ ],
+ ),
+ SuperTabPullRequestLinks(_ids('pullRequests').join(' ')),
+ ],
+ ),
+ );
+ if (!_throws) return line;
+ return SuperTabConfetti(seed: message.id.hashCode, child: line);
+ }
+}
+
+class _Credit extends StatelessWidget {
+ const _Credit(this.label, this.people);
+ final String label;
+ final List<(Widget, String)> people;
+
+ @override
+ Widget build(BuildContext context) {
+ if (people.isEmpty) return const SizedBox.shrink();
+ return Row(
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ Text(label, style: DesktopChrome.metadata()),
+ for (final (avatar, name) in people) ...[
+ const SizedBox(width: 6),
+ avatar,
+ const SizedBox(width: 4),
+ Text(name, style: DesktopChrome.control()),
+ ],
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/status_editor.dart b/desktop/lib/super_tabs/status_editor.dart
new file mode 100644
index 000000000..67cedfc80
--- /dev/null
+++ b/desktop/lib/super_tabs/status_editor.dart
@@ -0,0 +1,132 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+
+import '../shared/widgets/app_select_field.dart';
+import '../widgets/desktop_chrome.dart';
+import 'model.dart';
+
+/// When a status clears itself.
+enum _Clears { never, hour, fourHours, today }
+
+/// A person's status: a preset or their own words, and when it clears.
+class SuperTabStatusEditor extends StatefulWidget {
+ const SuperTabStatusEditor({
+ super.key,
+ required this.status,
+ required this.busy,
+ required this.onSave,
+ });
+ final SuperTabPersonStatus? status;
+ final bool busy;
+
+ /// Null clears it.
+ final ValueChanged<SuperTabPersonStatus?> onSave;
+
+ @override
+ State<SuperTabStatusEditor> createState() => _SuperTabStatusEditorState();
+}
+
+class _SuperTabStatusEditorState extends State<SuperTabStatusEditor> {
+ late final _text = TextEditingController(text: widget.status?.text ?? '');
+ late String? _emoji = widget.status?.emoji;
+ _Clears _clears = _Clears.never;
+
+ @override
+ void dispose() {
+ _text.dispose();
+ super.dispose();
+ }
+
+ DateTime? _until() {
+ final now = clock.now();
+ return switch (_clears) {
+ _Clears.never => null,
+ _Clears.hour => now.add(const Duration(hours: 1)),
+ _Clears.fourHours => now.add(const Duration(hours: 4)),
+ _Clears.today => () {
+ final local = now.toLocal();
+ return DateTime(local.year, local.month, local.day + 1);
+ }(),
+ };
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final text = _text.text.trim();
+ return Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text('Status', style: DesktopChrome.control(medium: true)),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 6,
+ runSpacing: 6,
+ children: [
+ for (final (emoji, words) in superTabStatusPresets)
+ ChoiceChip(
+ key: ValueKey('super-status-$emoji'),
+ label: Text('$emoji $words'),
+ selected: _emoji == emoji && text == words,
+ onSelected: (_) => setState(() {
+ _emoji = emoji;
+ _text.text = words;
+ }),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ TextField(
+ key: const ValueKey('super-status-text'),
+ controller: _text,
+ maxLength: 80,
+ decoration: const InputDecoration(hintText: 'What are you up to?'),
+ onChanged: (_) => setState(() {}),
+ ),
+ Row(
+ children: [
+ Text('Clears', style: DesktopChrome.metadata()),
+ const SizedBox(width: 8),
+ AppSelectField<_Clears>(
+ key: const ValueKey('super-status-clears'),
+ value: _clears,
+ width: 150,
+ options: const [
+ SelectOption(value: _Clears.never, label: 'Never'),
+ SelectOption(value: _Clears.hour, label: 'In 1 hour'),
+ SelectOption(value: _Clears.fourHours, label: 'In 4 hours'),
+ SelectOption(value: _Clears.today, label: 'End of today'),
+ ],
+ onChanged: (value) => setState(() => _clears = value),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ alignment: WrapAlignment.end,
+ spacing: 8,
+ children: [
+ if (widget.status != null)
+ TextButton(
+ onPressed: widget.busy ? null : () => widget.onSave(null),
+ child: const Text('Clear status'),
+ ),
+ FilledButton(
+ onPressed: widget.busy || text.isEmpty
+ ? null
+ : () => widget.onSave(
+ SuperTabPersonStatus(
+ text: text,
+ emoji: superTabStatusPresets.any((p) => p.$1 == _emoji)
+ ? _emoji
+ : null,
+ until: _until(),
+ ),
+ ),
+ child: const Text('Save status'),
+ ),
+ ],
+ ),
+ ],
+ );
+ }
+}
diff --git a/desktop/lib/super_tabs/until.dart b/desktop/lib/super_tabs/until.dart
new file mode 100644
index 000000000..74d08a2b7
--- /dev/null
+++ b/desktop/lib/super_tabs/until.dart
@@ -0,0 +1,51 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/widgets.dart';
+
+/// Builds [builder] again at [until], when something it shows runs out (a
+/// status that clears itself), even when nothing else changes on the page.
+class SuperTabUntil extends StatefulWidget {
+ const SuperTabUntil({super.key, required this.until, required this.builder});
+ final DateTime? until;
+ final WidgetBuilder builder;
+
+ @override
+ State<SuperTabUntil> createState() => _SuperTabUntilState();
+}
+
+class _SuperTabUntilState extends State<SuperTabUntil> {
+ Timer? _timer;
+
+ @override
+ void initState() {
+ super.initState();
+ _schedule();
+ }
+
+ @override
+ void didUpdateWidget(SuperTabUntil old) {
+ super.didUpdateWidget(old);
+ if (old.until != widget.until) _schedule();
+ }
+
+ void _schedule() {
+ _timer?.cancel();
+ final until = widget.until;
+ if (until == null) return;
+ final left = until.difference(clock.now());
+ if (left.isNegative) return;
+ _timer = Timer(left + const Duration(milliseconds: 1), () {
+ if (mounted) setState(() {});
+ });
+ }
+
+ @override
+ void dispose() {
+ _timer?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => widget.builder(context);
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 68715c15c..98dddf92a 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -17,6 +17,8 @@ import '../state/harness_attachments.dart';
import '../state/workspace_chrome.dart';
import 'roster.dart';
import 'recording_notice.dart';
+import 'identity.dart' show superTabPersonName;
+import 'profile_actions.dart';
import 'pull_requests.dart';
import 'controller.dart';
import 'dialog_scope.dart';
@@ -30,6 +32,7 @@ import 'notifications.dart';
import 'decisions.dart';
import 'decisions_view.dart';
import 'route_row.dart';
+import 'ship_row.dart';
import 'terminal_row.dart';
import 'work_details.dart';
import 'project_sidebar.dart';
@@ -1685,6 +1688,16 @@ class _SuperTabViewState extends State<SuperTabView>
});
}
+ Future<void> _react(
+ SuperTabMessage message,
+ SuperTabReactionEmoji emoji,
+ ) async {
+ final failure = await c.react(message, emoji);
+ if (failure == null || !mounted) return;
+ ScaffoldMessenger.maybeOf(context)
+ ?.showSnackBar(SnackBar(content: Text(failure)));
+ }
+
Widget _message(
SuperTabMessage message,
bool grouped,
@@ -1697,6 +1710,13 @@ class _SuperTabViewState extends State<SuperTabView>
message: message,
);
}
+ if (SuperTabShipRow.shows(message)) {
+ return SuperTabShipRow(
+ key: ValueKey('super-message-${message.id}'),
+ message: message,
+ controller: c,
+ );
+ }
final route = message.route;
if (route != null) {
return SuperTabRouteRow(
@@ -1738,6 +1758,11 @@ class _SuperTabViewState extends State<SuperTabView>
c.selectTerminal(id, null);
},
agent: agent,
+ person: message.fromAgent
+ ? null
+ : c.snapshot?.people
+ .where((p) => p.id == message.authorId)
+ .firstOrNull,
onOpenAgent: agent == null ? null : () => _openAgent(agent),
machineName: agent == null ? null : widget.machineName(agent.machineId),
grouped: grouped,
@@ -1752,6 +1777,17 @@ class _SuperTabViewState extends State<SuperTabView>
}
: null,
onReturnToComposer: _focus.requestFocus,
+ readerId: c.accountId,
+ reactorName: (kind, id) => kind == 'agent'
+ ? c.snapshot?.agentName(id) ?? 'Agent'
+ : c.snapshot?.people
+ .where((p) => p.id == id)
+ .map((p) => superTabPersonName(p.email))
+ .firstOrNull ??
+ 'Someone',
+ onReact: c.canWrite && c.selected?.archived == false
+ ? (emoji) => unawaited(_react(message, emoji))
+ : null,
receipts: [
if (message.source['truncated'] == true ||
message.source['interrupted'] == true)
diff --git a/desktop/test/super_tab_avatar_test.dart b/desktop/test/super_tab_avatar_test.dart
new file mode 100644
index 000000000..6f7581489
--- /dev/null
+++ b/desktop/test/super_tab_avatar_test.dart
@@ -0,0 +1,138 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/avatar_art.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/widgets/engine_identity.dart';
+
+SuperTabAgent agentNamed(
+ String name, {
+ String engine = 'claude',
+ Object? avatar,
+}) => SuperTabAgent.fromJson({
+ 'id': 'id-$name',
+ 'name': name,
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'p',
+ 'configuration': {'engine': engine},
+ 'avatar': ?avatar,
+});
+SuperTabPerson personWith({Object? avatar, Object? status}) =>
+ SuperTabPerson.fromJson({
+ 'id': 'p1',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': ?avatar,
+ 'status': ?status,
+ });
+Widget host(Widget child) => MaterialApp(
+ home: Scaffold(body: Center(child: child)),
+);
+
+void main() {
+ test(
+ 'an agent’s pattern is stable for its name and differs between names',
+ () {
+ final kai = superTabAgentPattern('Kai');
+ expect(superTabAgentPattern('Kai').cells, kai.cells);
+ expect(superTabAgentPattern('Kai').hue, kai.hue);
+ final names = [
+ 'Kai',
+ 'Ivy',
+ 'River',
+ 'Ellis',
+ 'Theo',
+ 'Sage',
+ 'Quinn',
+ 'Atlas',
+ ];
+ final patterns = {
+ for (final n in names) superTabAgentPattern(n).cells.join(),
+ };
+ expect(patterns, hasLength(names.length));
+ // Mirrored left to right, like a face.
+ for (var row = 0; row < 5; row++) {
+ expect(kai.cells[row * 5], kai.cells[row * 5 + 4]);
+ expect(kai.cells[row * 5 + 1], kai.cells[row * 5 + 3]);
+ }
+ expect(kai.cells.where((on) => on), isNotEmpty);
+ },
+ );
+
+ testWidgets('an agent without a picture shows its pattern and engine badge', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ host(SuperTabAvatar.agent(agentNamed('Kai', engine: 'codex'), size: 28)),
+ );
+ expect(find.byKey(const ValueKey('super-avatar-pattern')), findsOneWidget);
+ final badge = tester.widget<EngineMark>(find.byType(EngineMark));
+ expect(badge.engine, 'codex');
+ expect(tester.getSize(find.byType(SuperTabAvatar)), const Size.square(28));
+ });
+
+ testWidgets('a preset shows its picture, an upload its image', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ host(
+ SuperTabAvatar.agent(
+ agentNamed('Kai', avatar: {'kind': 'preset', 'key': 'owl'}),
+ ),
+ ),
+ );
+ expect(find.text('🦉'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-avatar-pattern')), findsNothing);
+ await tester.pumpWidget(
+ host(
+ SuperTabAvatar.person(
+ personWith(
+ avatar: {
+ 'kind': 'upload',
+ 'url': 'https://storage.googleapis.com/avatars/me?X-Goog-Signature=s',
+ },
+ ),
+ ),
+ ),
+ );
+ final image = tester.widget<Image>(find.byType(Image));
+ expect(
+ (image.image as NetworkImage).url,
+ 'https://storage.googleapis.com/avatars/me?X-Goog-Signature=s',
+ );
+ });
+
+ testWidgets(
+ 'a person without a picture keeps their initial; a status shows beside it',
+ (tester) async {
+ final now = DateTime.utc(2026, 10, 27, 9);
+ await tester.pumpWidget(
+ host(
+ SuperTabAvatar.person(
+ personWith(status: {'text': 'Coffee', 'emoji': '☕'}),
+ now: now,
+ ),
+ ),
+ );
+ expect(find.text('D'), findsOneWidget);
+ expect(find.text('☕'), findsOneWidget);
+ expect(find.bySemanticsLabel(RegExp('Coffee')), findsOneWidget);
+ await tester.pumpWidget(
+ host(
+ SuperTabAvatar.person(
+ personWith(
+ status: {
+ 'text': 'Lunch',
+ 'emoji': '🍽️',
+ 'until': '2026-10-27T08:00:00.000Z',
+ },
+ ),
+ now: now,
+ ),
+ ),
+ );
+ expect(find.text('🍽️'), findsNothing);
+ },
+ );
+}
diff --git a/desktop/test/super_tab_avatars_view_test.dart b/desktop/test/super_tab_avatars_view_test.dart
new file mode 100644
index 000000000..8ada1c8aa
--- /dev/null
+++ b/desktop/test/super_tab_avatars_view_test.dart
@@ -0,0 +1,131 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/message_row.dart';
+import 'package:harness/super_tabs/model.dart';
+
+import 'super_tab_roster_test.dart' show RosterFixture;
+
+void main() {
+ testWidgets(
+ 'the roster shows each person’s avatar and status, each agent its pattern',
+ (tester) async {
+ final f = RosterFixture();
+ addTearDown(f.dispose);
+ await f.initialize();
+ final people = f.server.state['people'] as List;
+ people[0] = <String, dynamic>{
+ ...people[0] as Map,
+ 'avatar': {'kind': 'preset', 'key': 'fox'},
+ 'status': {'text': 'Coffee break', 'emoji': '☕'},
+ };
+ f.server.state['agents'] = [
+ for (final agent in f.server.state['agents'] as List)
+ if ((agent as Map)['id'] == 'agent-1')
+ {
+ ...agent,
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ }
+ else
+ agent,
+ ];
+ await f.controller.refresh();
+ await f.show(tester);
+ final person = find.byKey(const ValueKey('super-person-owner'));
+ expect(
+ find.descendant(of: person, matching: find.text('🦊')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: person, matching: find.text('☕')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: person,
+ matching: find.textContaining('Coffee break'),
+ ),
+ findsOneWidget,
+ );
+ expect(f.inRow(1, find.text('🦉')), findsOneWidget);
+ expect(
+ f.inRow(3, find.byKey(const ValueKey('super-avatar-pattern'))),
+ findsOneWidget,
+ );
+ await f.close(tester);
+ },
+ );
+
+ testWidgets('a message shows its author’s avatar', (tester) async {
+ final person = SuperTabPerson.fromJson({
+ 'id': 'owner',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': {'kind': 'preset', 'key': 'cactus'},
+ });
+ final message = SuperTabMessage.fromJson({
+ 'id': 'm1',
+ 'conversationId': 'lead',
+ 'text': 'Morning!',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': 'owner', 'name': '[email protected]'},
+ });
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMessageRow(
+ message: message,
+ author: 'dee',
+ person: person,
+ receipts: const [],
+ onReturnToComposer: () {},
+ ),
+ ),
+ ),
+ );
+ expect(find.text('🌵'), findsOneWidget);
+ });
+ expiryTests();
+}
+
+void expiryTests() {
+ testWidgets(
+ 'an expiring status leaves the roster and the avatar at its time, with nothing else changing',
+ (tester) async {
+ final f = RosterFixture();
+ addTearDown(f.dispose);
+ await f.initialize();
+ final people = f.server.state['people'] as List;
+ final until = clock.now().add(const Duration(minutes: 10)).toUtc();
+ people[0] = <String, dynamic>{
+ ...people[0] as Map,
+ 'status': {
+ 'text': 'At lunch',
+ 'emoji': '🍽️',
+ 'until': until.toIso8601String(),
+ },
+ };
+ await f.controller.refresh();
+ await f.show(tester);
+ final person = find.byKey(const ValueKey('super-person-owner'));
+ expect(
+ find.descendant(of: person, matching: find.textContaining('At lunch')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: person, matching: find.text('🍽️')),
+ findsOneWidget,
+ );
+ await tester.pump(const Duration(minutes: 10, seconds: 1));
+ expect(
+ find.descendant(of: person, matching: find.textContaining('At lunch')),
+ findsNothing,
+ );
+ expect(
+ find.descendant(of: person, matching: find.text('🍽️')),
+ findsNothing,
+ );
+ await f.close(tester);
+ },
+ );
+}
diff --git a/desktop/test/super_tab_delight_shots_test.dart b/desktop/test/super_tab_delight_shots_test.dart
new file mode 100644
index 000000000..167997200
--- /dev/null
+++ b/desktop/test/super_tab_delight_shots_test.dart
@@ -0,0 +1,209 @@
+import 'dart:io';
+
+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/profile_sheet.dart';
+import 'package:harness/super_tabs/ship_row.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'support/capture.dart';
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the avatars-and-delight PR's screenshots there:
+/// the real views over the in-memory Swarm, never a backend or the live app.
+final shots = Platform.environment['SUPER_TAB_DELIGHT_SHOTS'];
+
+String ago(Duration d) => DateTime.now().toUtc().subtract(d).toIso8601String();
+
+ConversationServer office() {
+ final server = ConversationServer();
+ server.state['projects'] = [projectFixture('lead', 'openharness', 'lead')];
+ server.state['people'] = [
+ {
+ 'id': 'owner',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': {'kind': 'preset', 'key': 'fox'},
+ 'status': {'text': 'Focusing', 'emoji': '🎯'},
+ },
+ {
+ 'id': 'ivy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'avatar': {'kind': 'preset', 'key': 'cactus'},
+ 'status': {'text': 'Coffee break', 'emoji': '☕'},
+ },
+ {'id': 'sam', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.state['agents'] = [
+ for (final (id, name, engine) in [
+ ('river', 'River', 'claude'),
+ ('kai', 'Kai', 'claude'),
+ ('ellis', 'Ellis', 'codex'),
+ ('theo', 'Theo', 'codex'),
+ ])
+ {
+ 'id': id,
+ 'projectId': 'lead',
+ 'name': name,
+ 'displayName': name,
+ 'machineId': 'm',
+ 'harnessId': id,
+ 'contributorId': 'owner',
+ 'configuration': {'engine': engine},
+ },
+ ];
+ (server.state['conversations'] as List)[0]['leadId'] = 'river';
+ void say(
+ String text,
+ Map<String, dynamic> author, {
+ List<Map<String, dynamic>>? reactions,
+ Duration at = const Duration(minutes: 9),
+ }) {
+ server.append(text);
+ server.messages.last
+ ..['author'] = author
+ ..['createdAt'] = ago(at)
+ ..['reactions'] = reactions ?? const [];
+ }
+
+ final river = {
+ 'kind': 'agent',
+ 'id': 'river',
+ 'name': 'River',
+ 'displayName': 'River',
+ };
+ say(
+ 'Morning! Avatars and the ship moment are ready for a look.',
+ river,
+ at: const Duration(minutes: 12),
+ );
+ say(
+ 'Love the generated faces 😍',
+ {'kind': 'person', 'id': 'ivy', 'name': '[email protected]'},
+ reactions: [
+ {
+ 'emoji': 'heart',
+ 'count': 2,
+ 'by': [
+ {'kind': 'person', 'id': 'owner'},
+ {'kind': 'agent', 'id': 'kai'},
+ ],
+ },
+ {
+ 'emoji': 'laugh',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': 'sam'},
+ ],
+ },
+ ],
+ );
+ say(
+ 'Merging now.',
+ {'kind': 'person', 'id': 'owner', 'name': '[email protected]'},
+ at: const Duration(minutes: 2),
+ reactions: [
+ {
+ 'emoji': 'rocket',
+ 'count': 3,
+ 'by': [
+ {'kind': 'person', 'id': 'ivy'},
+ {'kind': 'agent', 'id': 'river'},
+ {'kind': 'agent', 'id': 'theo'},
+ ],
+ },
+ ],
+ );
+ server.append('🎉 Shipped: Avatars and moments of delight');
+ server.messages.last
+ ..['author'] = river
+ ..['createdAt'] = ago(const Duration(seconds: 5))
+ ..['source'] = {
+ 'kind': 'ship',
+ 'conversationId': 'group-261',
+ 'title': 'Avatars and moments of delight',
+ 'pullRequests': [
+ 'https://github.com/autonomous-ai/openharness/pull/1760',
+ ],
+ 'requesterId': 'owner',
+ 'builderIds': ['kai'],
+ 'reviewerIds': ['ellis'],
+ };
+ return server;
+}
+
+/// The conversation over [office], as both captures draw it.
+Widget delightApp(
+ SuperTabController c, {
+ Brightness brightness = Brightness.dark,
+ bool reduceMotion = false,
+ Key? boundary,
+}) => RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'MacBookPro2021',
+ ),
+ ),
+ ),
+);
+
+Future<void> showOffice(
+ WidgetTester tester, {
+ Brightness brightness = Brightness.dark,
+ bool reduceMotion = false,
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1280, 860));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ // The app sets the design tokens' brightness from its theme at startup.
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.dark);
+ final c = office().controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ delightApp(c, brightness: brightness, reduceMotion: reduceMotion),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 650));
+}
+
+void main() {
+ setUpAll(() => loadCaptureFonts(shots));
+ setUp(SuperTabShipRow.resetPlayed);
+
+ testWidgets('screenshots for review', (tester) async {
+ await showOffice(tester);
+ await captureWindow(tester, shots, 'office-dark-confetti');
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'office-dark');
+ SuperTabShipRow.resetPlayed();
+ await showOffice(tester, brightness: Brightness.light, reduceMotion: true);
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'office-light-reduced-motion');
+ final context = tester.element(find.byType(SuperTabView));
+ final view = tester.widget<SuperTabView>(find.byType(SuperTabView));
+ showSuperTabProfile(context, view.controller);
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'profile-sheet');
+ await tester.tap(find.text('Close'));
+ await tester.pumpAndSettle();
+ showSuperTabProfile(context, view.controller, agentId: 'kai');
+ await tester.pumpAndSettle();
+ await captureWindow(tester, shots, 'agent-avatar-sheet');
+ }, skip: shots == null);
+}
diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dart
index 21b716c2e..1bcf8efce 100644
--- a/desktop/test/super_tab_mentions_test.dart
+++ b/desktop/test/super_tab_mentions_test.dart
@@ -362,6 +362,34 @@ void main() {
);
});
+ testWidgets('a tag shows the Lead’s avatar beside its name', (
+ tester,
+ ) async {
+ final server = ConversationServer()
+ ..append('Ship it?')
+ ..tag('message-1', text: 'Ship it?', leadId: 'lead-agent');
+ server.state['agents'] = [
+ {
+ 'id': 'lead-agent',
+ 'name': 'Lead',
+ 'displayName': 'Wren',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ },
+ ];
+ 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,
+ );
+ });
+
testWidgets('mark done moves the tag to Earlier and clears the count', (
tester,
) async {
@@ -435,7 +463,7 @@ void main() {
await tester.tap(find.byKey(const ValueKey('super-mention-mention-1')));
await tester.pumpAndSettle();
expect(c.selectedId, 'group');
- expect(find.text('Replying to [email protected]'), findsOneWidget);
+ expect(find.text('Replying to owner'), findsOneWidget);
expect(
find.byKey(const ValueKey('super-message-message-100')).hitTestable(),
findsOneWidget,
diff --git a/desktop/test/super_tab_person_names_test.dart b/desktop/test/super_tab_person_names_test.dart
new file mode 100644
index 000000000..e1be5a7bf
--- /dev/null
+++ b/desktop/test/super_tab_person_names_test.dart
@@ -0,0 +1,51 @@
+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 'support/super_tab_fixture.dart';
+
+void main() {
+ testWidgets(
+ 'a person is named in message headers and replies, never by their address',
+ (tester) async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ {'id': 'ivy', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ server.append('Love the generated faces');
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'ivy',
+ 'name': '[email protected]',
+ };
+ server.append('Thanks!');
+ server.messages.last['replyTo'] = 'message-1';
+ // Someone who has left keeps the name their address gives.
+ server.append('Old note');
+ server.messages.last['author'] = {
+ 'kind': 'person',
+ 'id': 'gone',
+ 'name': '[email protected]',
+ };
+ await showView(tester, server);
+ expect(find.textContaining('@example.com'), findsNothing);
+ expect(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-message-message-1')),
+ matching: find.text('ivy'),
+ ),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: find.byType(SuperTabReplyPreview),
+ matching: find.text('ivy'),
+ ),
+ findsOneWidget,
+ );
+ expect(find.text('sam'), findsOneWidget);
+ },
+ );
+}
diff --git a/desktop/test/super_tab_profile_actions_test.dart b/desktop/test/super_tab_profile_actions_test.dart
new file mode 100644
index 000000000..be3be219f
--- /dev/null
+++ b/desktop/test/super_tab_profile_actions_test.dart
@@ -0,0 +1,168 @@
+import 'dart:typed_data';
+import 'dart:ui' as ui;
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/avatar_upload.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/profile_actions.dart';
+
+import 'support/super_tab_fixture.dart';
+
+Future<Uint8List> picture(int width, int height) async {
+ final recorder = ui.PictureRecorder();
+ ui.Canvas(recorder).drawRect(
+ ui.Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
+ ui.Paint()..color = const ui.Color(0xff3366cc),
+ );
+ final image = await recorder.endRecording().toImage(width, height);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ image.dispose();
+ return bytes!.buffer.asUint8List();
+}
+
+Map<String, dynamic> lastCommand(ConversationServer server) =>
+ Map<String, dynamic>.from(server.posts.last['command'] as Map);
+
+void main() {
+ testWidgets('a picked picture is cropped square and resized before upload', (
+ tester,
+ ) async {
+ await tester.runAsync(() async {
+ final png = await superTabAvatarPng(await picture(900, 400));
+ final codec = await ui.instantiateImageCodec(png);
+ final frame = (await codec.getNextFrame()).image;
+ expect([frame.width, frame.height], [256, 256]);
+ expect(png.length, lessThan(kSuperTabAvatarMaxBytes));
+ expect(png.sublist(0, 4), [0x89, 0x50, 0x4e, 0x47]);
+ frame.dispose();
+ });
+ });
+
+ testWidgets('something that is not a picture is refused here', (
+ tester,
+ ) async {
+ await tester.runAsync(() async {
+ await expectLater(
+ superTabAvatarPng(Uint8List.fromList('<html></html>'.codeUnits)),
+ throwsA(isA<SuperTabFailure>()),
+ );
+ });
+ });
+
+ test('a status is set and cleared as the person’s own', () async {
+ final server = ConversationServer();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ final until = DateTime.utc(2026, 10, 27, 14);
+ expect(
+ await c.setStatus(
+ SuperTabPersonStatus(text: 'Out', emoji: '🌴', until: until),
+ ),
+ isNull,
+ );
+ expect(lastCommand(server), {
+ 'type': 'member.status',
+ 'status': {
+ 'text': 'Out',
+ 'emoji': '🌴',
+ 'until': '2026-10-27T14:00:00.000Z',
+ },
+ });
+ expect(c.snapshot!.people.single.status!.text, 'Out');
+ expect(await c.setStatus(null), isNull);
+ expect(lastCommand(server), {'type': 'member.status', 'status': null});
+ expect(c.snapshot!.people.single.status, isNull);
+ });
+
+ testWidgets('an upload becomes the person’s avatar, a preset an agent’s', (
+ tester,
+ ) async {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'agent-1',
+ 'name': 'Kai',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await tester.runAsync(() async {
+ await c.refresh();
+ expect(await c.uploadAvatar(await picture(300, 300)), isNull);
+ });
+ expect(server.avatarUploads, hasLength(1));
+ expect(lastCommand(server), {
+ 'type': 'member.avatar',
+ 'avatar': {'kind': 'upload', 'id': 'avatar-1'},
+ });
+ expect(c.snapshot!.people.single.avatar, isA<SuperTabUploadedAvatar>());
+ expect(
+ await c.setAvatar(const SuperTabPresetAvatar('owl'), agentId: 'agent-1'),
+ isNull,
+ );
+ expect(lastCommand(server), {
+ 'type': 'agent.avatar',
+ 'agentId': 'agent-1',
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ });
+ expect(c.snapshot!.agent('agent-1')!.avatar, isA<SuperTabPresetAvatar>());
+ expect(await c.setAvatar(null), isNull);
+ expect(lastCommand(server), {'type': 'member.avatar', 'avatar': null});
+ });
+
+ test(
+ 'a reaction toggles the reader’s own, and the page shows the count',
+ () async {
+ final server = ConversationServer()..append('Shipped');
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await c.loadMessages('lead');
+ final message = c.messages('lead').single;
+ expect(await c.react(message, SuperTabReactionEmoji.tada), isNull);
+ expect(lastCommand(server), {
+ 'type': 'message.react',
+ 'conversationId': 'lead',
+ 'messageId': message.id,
+ 'emoji': 'tada',
+ 'on': true,
+ });
+ expect(c.messages('lead').single.reactions.single.count, 1);
+ expect(
+ await c.react(c.messages('lead').single, SuperTabReactionEmoji.tada),
+ isNull,
+ );
+ expect(lastCommand(server)['on'], false);
+ expect(c.messages('lead').single.reactions, isEmpty);
+ },
+ );
+
+ test('a refusal is said in words, and a viewer sends nothing', () async {
+ final server = ConversationServer()
+ ..refuse = {'code': 'FORBIDDEN', 'message': 'Not yours.'};
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(
+ await c.setStatus(const SuperTabPersonStatus(text: 'Hi')),
+ 'Not yours.',
+ );
+ server.refuse = null;
+ server.state['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'viewer'},
+ ];
+ await c.refresh();
+ final sent = server.posts.length;
+ expect(
+ await c.setStatus(const SuperTabPersonStatus(text: 'Hi')),
+ isNotNull,
+ );
+ expect(server.posts, hasLength(sent));
+ });
+}
diff --git a/desktop/test/super_tab_profile_model_test.dart b/desktop/test/super_tab_profile_model_test.dart
new file mode 100644
index 000000000..d5899eaec
--- /dev/null
+++ b/desktop/test/super_tab_profile_model_test.dart
@@ -0,0 +1,154 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/model.dart';
+
+import 'support/super_tab_fixture.dart';
+
+void main() {
+ final now = DateTime.utc(2026, 10, 27, 9);
+
+ test('a person carries their avatar and a status until it is over', () {
+ final person = SuperTabPerson.fromJson({
+ 'id': 'p1',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': {
+ 'kind': 'upload',
+ 'url': 'https://storage.googleapis.com/avatars/a?X-Goog-Signature=s',
+ },
+ 'status': {
+ 'text': 'Out until 2pm',
+ 'emoji': '🌴',
+ 'until': '2026-10-27T14:00:00.000Z',
+ },
+ });
+ expect(person.avatar, isA<SuperTabUploadedAvatar>());
+ expect(
+ (person.avatar! as SuperTabUploadedAvatar).url,
+ Uri.parse('https://storage.googleapis.com/avatars/a?X-Goog-Signature=s'),
+ );
+ expect(person.status!.label, '🌴 Out until 2pm');
+ expect(person.statusAt(now)?.text, 'Out until 2pm');
+ expect(person.statusAt(DateTime.utc(2026, 10, 27, 14)), isNull);
+ });
+
+ test(
+ 'a preset, a missing avatar, and a link that is not ours read safely',
+ () {
+ SuperTabAvatarPicture? read(Object? avatar) => SuperTabPerson.fromJson({
+ 'id': 'p1',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': avatar,
+ }).avatar;
+ expect(
+ (read({'kind': 'preset', 'key': 'fox'})! as SuperTabPresetAvatar).key,
+ 'fox',
+ );
+ expect(read(null), isNull);
+ expect(read({'kind': 'preset', 'key': 'dragon'}), isNull);
+ expect(read({'kind': 'upload', 'url': 'javascript:alert(1)'}), isNull);
+ expect(
+ read({'kind': 'upload', 'url': 'http://tracker.example/p.png'}),
+ isNull,
+ );
+ expect(
+ read({'kind': 'upload', 'url': 'https://elsewhere.example/a.png'}),
+ isNull,
+ );
+ // Avatars are never public: not even the chat files' own CDN.
+ expect(
+ read({
+ 'kind': 'upload',
+ 'url': 'https://cdn.harness.autonomous.ai/a.png',
+ }),
+ isNull,
+ );
+ // An upload whose signed link has not come yet shows the default face.
+ expect(read({'kind': 'upload'}), isNull);
+ expect(read('fox'), isNull);
+ },
+ );
+
+ test(
+ 'an agent carries its avatar; a message carries its reaction counts',
+ () {
+ final agent = SuperTabAgent.fromJson({
+ 'id': 'a1',
+ 'name': 'Kai',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'p1',
+ 'configuration': {'engine': 'claude'},
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ });
+ expect((agent.avatar! as SuperTabPresetAvatar).key, 'owl');
+ final message = SuperTabMessage.fromJson({
+ 'id': 'm1',
+ 'conversationId': 'lead',
+ 'text': 'Shipped',
+ 'sequence': 3,
+ 'author': {'kind': 'person', 'id': 'p1', 'name': '[email protected]'},
+ 'reactions': [
+ {
+ 'emoji': 'tada',
+ 'count': 2,
+ 'by': [
+ {'kind': 'person', 'id': 'p1'},
+ {'kind': 'agent', 'id': 'a1'},
+ ],
+ },
+ {'emoji': 'skull', 'count': 1, 'by': []},
+ ],
+ });
+ expect(message.reactions, hasLength(1));
+ expect(message.reactions.single.emoji, SuperTabReactionEmoji.tada);
+ expect(message.reactions.single.count, 2);
+ expect(message.reactions.single.includes('person', 'p1'), isTrue);
+ expect(message.reactions.single.includes('person', 'p2'), isFalse);
+ expect(SuperTabReactionEmoji.tada.glyph, '🎉');
+ },
+ );
+
+ test(
+ 'a read’s signed link becomes the avatar of the person or agent it names',
+ () async {
+ final server = ConversationServer();
+ server.state['people'] = [
+ {
+ 'id': 'owner',
+ 'email': '[email protected]',
+ 'role': 'owner',
+ 'avatar': {'kind': 'upload'},
+ },
+ ];
+ server.state['agents'] = [
+ {
+ 'id': 'kai',
+ 'name': 'Kai',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ 'avatar': {'kind': 'upload'},
+ },
+ ];
+ server.state['avatars'] = {
+ 'person:owner': superTabSignedAvatar('a1'),
+ 'agent:kai': superTabSignedAvatar('a2'),
+ };
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ expect(
+ (c.snapshot!.people.single.avatar! as SuperTabUploadedAvatar).url
+ .toString(),
+ superTabSignedAvatar('a1'),
+ );
+ expect(
+ (c.snapshot!.agent('kai')!.avatar! as SuperTabUploadedAvatar).url
+ .toString(),
+ superTabSignedAvatar('a2'),
+ );
+ },
+ );
+}
diff --git a/desktop/test/super_tab_profile_sheet_test.dart b/desktop/test/super_tab_profile_sheet_test.dart
new file mode 100644
index 000000000..0cc14ebed
--- /dev/null
+++ b/desktop/test/super_tab_profile_sheet_test.dart
@@ -0,0 +1,217 @@
+import 'dart:typed_data';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/agent_details.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/profile_sheet.dart';
+
+import 'super_tab_profile_actions_test.dart' show picture;
+import 'super_tab_roster_test.dart' show RosterFixture;
+import 'support/super_tab_fixture.dart';
+
+Map<String, dynamic> lastCommand(ConversationServer server) =>
+ Map<String, dynamic>.from(server.posts.last['command'] as Map);
+
+Future<SuperTabController> openSheet(
+ WidgetTester tester,
+ ConversationServer server, {
+ String? agentId,
+ Future<Uint8List?> Function()? pick,
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showSuperTabProfile(
+ context,
+ c,
+ agentId: agentId,
+ pickPicture: pick ?? () async => null,
+ ),
+ child: const Text('Open'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ return c;
+}
+
+void main() {
+ testWidgets('your own row opens your profile from Edit profile', (
+ tester,
+ ) async {
+ final f = RosterFixture();
+ addTearDown(f.dispose);
+ await f.initialize();
+ await f.show(tester);
+ await tester.tap(find.byKey(const ValueKey('super-person-owner')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-profile-edit')));
+ await tester.pumpAndSettle();
+ expect(find.text('Your profile'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-status-text')), findsOneWidget);
+ await f.close(tester);
+ });
+
+ testWidgets('a preset becomes your avatar at once', (tester) async {
+ final server = ConversationServer();
+ final c = await openSheet(tester, server);
+ await tester.tap(find.byKey(const ValueKey('super-avatar-preset-fox')));
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'member.avatar',
+ 'avatar': {'kind': 'preset', 'key': 'fox'},
+ });
+ expect(c.snapshot!.people.single.avatar, isNotNull);
+ await tester.tap(find.text('Use default'));
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {'type': 'member.avatar', 'avatar': null});
+ });
+
+ testWidgets('an uploaded picture is resized and set', (tester) async {
+ final server = ConversationServer();
+ final bytes = (await tester.runAsync(() => picture(500, 300)))!;
+ await openSheet(tester, server, pick: () async => bytes);
+ await tester.runAsync(() async {
+ await tester.tap(find.text('Upload picture…'));
+ for (var i = 0; i < 50 && server.avatarUploads.isEmpty; i++) {
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ }
+ });
+ await tester.pumpAndSettle();
+ expect(server.avatarUploads, hasLength(1));
+ expect(lastCommand(server)['avatar'], {'kind': 'upload', 'id': 'avatar-1'});
+ });
+
+ testWidgets(
+ 'a status is picked, cleared after an hour, and cleared by hand',
+ (tester) async {
+ final server = ConversationServer();
+ final now = DateTime.utc(2026, 10, 27, 9);
+ await withClock(Clock.fixed(now), () async {
+ await openSheet(tester, server);
+ await tester.tap(find.byKey(const ValueKey('super-status-☕')));
+ await tester.pump();
+ expect(find.widgetWithText(TextField, 'Coffee break'), findsOneWidget);
+ await tester.ensureVisible(find.text('Save status'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.byKey(const ValueKey('super-status-clears')));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('In 1 hour').last);
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Save status'));
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'member.status',
+ 'status': {
+ 'text': 'Coffee break',
+ 'emoji': '☕',
+ 'until': '2026-10-27T10:00:00.000Z',
+ },
+ });
+ await tester.ensureVisible(find.text('Clear status'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Clear status'));
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {'type': 'member.status', 'status': null});
+ });
+ },
+ );
+
+ testWidgets('an agent’s sheet changes its avatar and has no status', (
+ 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(find.text('Kai’s avatar'), findsOneWidget);
+ expect(find.byKey(const ValueKey('super-status-text')), findsNothing);
+ await tester.tap(find.byKey(const ValueKey('super-avatar-preset-owl')));
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'agent.avatar',
+ 'agentId': 'agent-1',
+ 'avatar': {'kind': 'preset', 'key': 'owl'},
+ });
+ });
+
+ testWidgets('a refusal is shown in the sheet', (tester) async {
+ final server = ConversationServer();
+ await openSheet(tester, server);
+ server.refuse = {'code': 'FORBIDDEN', 'message': 'Not allowed here.'};
+ await tester.tap(find.byKey(const ValueKey('super-avatar-preset-cat')));
+ await tester.pumpAndSettle();
+ expect(find.text('Not allowed here.'), findsOneWidget);
+ });
+
+ testWidgets('the agent’s contributor changes its avatar from its details', (
+ tester,
+ ) async {
+ for (final contributor in ['owner', 'someone-else']) {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ {
+ 'id': 'agent-1',
+ 'name': 'Kai',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': contributor,
+ 'configuration': {'engine': 'codex'},
+ },
+ ];
+ final c = server.controller();
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => showSuperTabAgentDetails(
+ context,
+ c,
+ null,
+ c.snapshot!.agent('agent-1')!,
+ (_) {},
+ ),
+ child: const Text('Details'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Details'));
+ await tester.pumpAndSettle();
+ expect(find.byType(SuperTabAvatar), findsOneWidget);
+ if (contributor != 'owner') {
+ expect(find.text('Change avatar'), findsNothing);
+ } else {
+ await tester.tap(find.text('Change avatar'));
+ await tester.pumpAndSettle();
+ expect(find.text('Kai’s avatar'), findsOneWidget);
+ }
+ await tester.pumpWidget(const SizedBox());
+ c.dispose();
+ }
+ });
+}
diff --git a/desktop/test/super_tab_reactions_test.dart b/desktop/test/super_tab_reactions_test.dart
new file mode 100644
index 000000000..182056536
--- /dev/null
+++ b/desktop/test/super_tab_reactions_test.dart
@@ -0,0 +1,265 @@
+import 'package:fake_async/fake_async.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/message_row.dart';
+import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/reading.dart';
+
+import 'super_tab_mentions_test.dart' show showView;
+import 'support/super_tab_fixture.dart';
+
+/// What the web build reads with: full reads only now and then once quiet.
+const _web = SuperTabReading(quietPoll: Duration(seconds: 15));
+
+/// Someone else's reaction, as the backend records it.
+void reactAsPeer(ConversationServer server, String messageId) {
+ server.messages.firstWhere((m) => m['id'] == messageId)['reactions'] = [
+ {
+ 'emoji': 'tada',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': 'peer'},
+ ],
+ },
+ ];
+ final group = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'lead');
+ group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
+}
+
+void main() {
+ test('another person’s reaction shows within one quiet poll', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Shipped');
+ final paths = <String>[];
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: (method, path, {body}) {
+ if (method == 'GET') paths.add(path);
+ return server.request(method, path, body: body);
+ },
+ save: server.save,
+ reading: _web,
+ )..start();
+ // Quiet: the polls between full reads ask only for new messages.
+ async.elapse(const Duration(seconds: 61));
+ expect(c.messages('lead').single.reactions, isEmpty);
+ reactAsPeer(server, 'message-1');
+ paths.clear();
+ async.elapse(const Duration(seconds: 3));
+ expect(paths.where((p) => p.contains('/changes')), isEmpty);
+ expect(c.messages('lead').single.reactions.single.count, 1);
+ // Nothing moved since: the next poll reads only what is new.
+ paths.clear();
+ async.elapse(const Duration(seconds: 3));
+ expect(paths.where((p) => p.contains('messages?before=')), isEmpty);
+ c.dispose();
+ });
+ });
+ test('a reaction and a new message in the same quiet poll both show', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..append('Shipped');
+ var failPage = false;
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: (method, path, {body}) {
+ final page =
+ path.endsWith('/messages') || path.contains('messages?before=');
+ if (failPage && method == 'GET' && page) {
+ failPage = false;
+ return Future.error(
+ const SuperTabFailure('UNAVAILABLE', 'Try again.'),
+ );
+ }
+ return server.request(method, path, body: body);
+ },
+ save: server.save,
+ reading: _web,
+ )..start();
+ async.elapse(const Duration(seconds: 61));
+ reactAsPeer(server, 'message-1');
+ server.append('And the docs');
+ async.elapse(const Duration(seconds: 3));
+ expect(c.messages('lead').map((m) => m.text), [
+ 'Shipped',
+ 'And the docs',
+ ]);
+ expect(c.messages('lead').first.reactions.single.count, 1);
+ // A refresh that fails leaves the change to the next poll.
+ server.messages.first['reactions'] = [
+ {
+ 'emoji': 'tada',
+ 'count': 2,
+ 'by': [
+ {'kind': 'person', 'id': 'peer'},
+ {'kind': 'person', 'id': 'sam'},
+ ],
+ },
+ ];
+ final group = (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'lead');
+ group['reactionSeq'] = (group['reactionSeq'] as int) + 1;
+ failPage = true;
+ async.elapse(const Duration(seconds: 3));
+ expect(c.messages('lead').first.reactions.single.count, 1);
+ async.elapse(const Duration(seconds: 3));
+ expect(c.messages('lead').first.reactions.single.count, 2);
+ c.dispose();
+ });
+ });
+
+ reactionWidgetTests();
+
+ testWidgets('reacting in the conversation sends it and shows the count', (
+ tester,
+ ) async {
+ final server = ConversationServer()..append('Shipped');
+ final c = await showView(tester, server);
+ await tester.tap(find.byTooltip('Add reaction'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('🚀'));
+ await tester.pumpAndSettle();
+ expect(server.posts.last['command'], {
+ 'type': 'message.react',
+ 'conversationId': 'lead',
+ 'messageId': 'message-1',
+ 'emoji': 'rocket',
+ 'on': true,
+ });
+ expect(
+ find.byKey(const ValueKey('super-reaction-message-1-rocket')),
+ findsOneWidget,
+ );
+ expect(c.messages('lead').single.reactions.single.count, 1);
+ });
+}
+
+SuperTabMessage reacted({List<Map<String, dynamic>> reactions = const []}) =>
+ SuperTabMessage.fromJson({
+ 'id': 'm1',
+ 'conversationId': 'lead',
+ 'text': 'Shipped the fix',
+ 'sequence': 1,
+ 'author': {'kind': 'person', 'id': 'peer', 'name': '[email protected]'},
+ 'reactions': reactions,
+ });
+
+Future<List<SuperTabReactionEmoji>> showRow(
+ WidgetTester tester,
+ SuperTabMessage message, {
+ bool canReact = true,
+}) async {
+ final picked = <SuperTabReactionEmoji>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabMessageRow(
+ message: message,
+ author: 'ivy',
+ receipts: const [],
+ onReturnToComposer: () {},
+ readerId: 'owner',
+ reactorName: (kind, id) => {'owner': 'dee', 'peer': 'ivy'}[id] ?? id,
+ onReact: canReact ? picked.add : null,
+ ),
+ ),
+ ),
+ );
+ return picked;
+}
+
+void reactionWidgetTests() {
+ testWidgets('counts show under the message, the reader’s own marked', (
+ tester,
+ ) async {
+ final picked = await showRow(
+ tester,
+ reacted(
+ reactions: [
+ {
+ 'emoji': 'thumbs_up',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': 'peer'},
+ ],
+ },
+ {
+ 'emoji': 'tada',
+ 'count': 2,
+ 'by': [
+ {'kind': 'person', 'id': 'owner'},
+ {'kind': 'person', 'id': 'peer'},
+ ],
+ },
+ ],
+ ),
+ );
+ final tada = find.byKey(const ValueKey('super-reaction-m1-tada'));
+ expect(
+ find.descendant(of: tada, matching: find.text('🎉')),
+ findsOneWidget,
+ );
+ expect(find.descendant(of: tada, matching: find.text('2')), findsOneWidget);
+ final label = find.bySemanticsLabel('🎉 2, dee and ivy');
+ expect(
+ tester.getSemantics(label),
+ matchesSemantics(
+ label: '🎉 2, dee and ivy',
+ isButton: true,
+ hasEnabledState: true,
+ isEnabled: true,
+ hasSelectedState: true,
+ isSelected: true,
+ hasTapAction: true,
+ isFocusable: true,
+ hasFocusAction: true,
+ ),
+ );
+ await tester.tap(tada);
+ expect(picked, [SuperTabReactionEmoji.tada]);
+ });
+
+ testWidgets('a reaction is added from the message’s actions', (tester) async {
+ final picked = await showRow(tester, reacted());
+ expect(find.byKey(const ValueKey('super-reaction-m1-tada')), findsNothing);
+ await tester.tap(find.byTooltip('Add reaction'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('👀'));
+ await tester.pumpAndSettle();
+ expect(picked, [SuperTabReactionEmoji.eyes]);
+ });
+
+ testWidgets('a reader who cannot write sees counts and cannot react', (
+ tester,
+ ) async {
+ await showRow(
+ tester,
+ canReact: false,
+ reacted(
+ reactions: [
+ {
+ 'emoji': 'heart',
+ 'count': 1,
+ 'by': [
+ {'kind': 'person', 'id': 'peer'},
+ ],
+ },
+ ],
+ ),
+ );
+ expect(find.text('❤️'), findsOneWidget);
+ expect(find.byTooltip('Add reaction'), findsNothing);
+ final chip = tester.widget<InkWell>(
+ find.descendant(
+ of: find.byKey(const ValueKey('super-reaction-m1-heart')),
+ matching: find.byType(InkWell),
+ ),
+ );
+ expect(chip.onTap, isNull);
+ });
+}
diff --git a/desktop/test/super_tab_ship_test.dart b/desktop/test/super_tab_ship_test.dart
new file mode 100644
index 000000000..3d8e88e4e
--- /dev/null
+++ b/desktop/test/super_tab_ship_test.dart
@@ -0,0 +1,155 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/ship_row.dart';
+
+import 'super_tab_mentions_test.dart' show showView;
+import 'support/super_tab_fixture.dart';
+
+final now = DateTime.utc(2026, 10, 27, 9);
+
+Map<String, dynamic> shipRow({
+ DateTime? at,
+ Map<String, Object?> source = const {},
+}) => {
+ 'id': 'ship-1',
+ 'conversationId': 'lead',
+ 'sequence': 5,
+ 'text': '🎉 Shipped: Avatars, requested by owner, built by Kai, reviewed by Ivy. https://github.com/example/app/pull/7',
+ 'createdAt': (at ?? now).toIso8601String(),
+ 'author': {'kind': 'agent', 'id': 'kai', 'name': 'Kai'},
+ 'source': {
+ 'kind': 'ship',
+ 'conversationId': 'group-1',
+ 'title': 'Avatars',
+ 'pullRequests': ['https://github.com/example/app/pull/7'],
+ 'requesterId': 'owner',
+ 'builderIds': ['kai'],
+ 'reviewerIds': ['ivy'],
+ ...source,
+ },
+};
+
+ConversationServer shipServer({
+ DateTime? at,
+ Map<String, Object?> source = const {},
+}) {
+ final server = ConversationServer();
+ server.state['agents'] = [
+ for (final (id, name) in [('kai', 'Kai'), ('ivy', 'Ivy')])
+ {
+ 'id': id,
+ 'name': name,
+ 'machineId': 'm',
+ 'harnessId': id,
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude'},
+ },
+ ];
+ server.messages.add(shipRow(at: at, source: source));
+ (server.state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == 'lead')['lastMessageSequence'] =
+ 5;
+ return server;
+}
+
+Future<void> show(
+ WidgetTester tester,
+ ConversationServer server, {
+ bool reduceMotion = false,
+}) async {
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await c.loadMessages('lead');
+ await tester.pumpWidget(
+ MaterialApp(
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context).copyWith(disableAnimations: reduceMotion),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: SuperTabShipRow(
+ message: c.messages('lead').single,
+ controller: c,
+ now: () => now,
+ ),
+ ),
+ ),
+ );
+}
+
+void main() {
+ setUp(SuperTabShipRow.resetPlayed);
+
+ testWidgets(
+ 'a ship line names who asked, built and reviewed, each with an avatar',
+ (tester) async {
+ await show(tester, shipServer());
+ expect(find.text('Shipped: Avatars'), findsOneWidget);
+ for (final words in [
+ 'Requested by',
+ 'owner',
+ 'Built by',
+ 'Kai',
+ 'Reviewed by',
+ 'Ivy',
+ ]) {
+ expect(find.text(words), findsOneWidget, reason: words);
+ }
+ expect(find.byType(SuperTabAvatar), findsNWidgets(3));
+ expect(find.text('app · PR #7'), findsOneWidget);
+ await tester.pumpAndSettle();
+ },
+ );
+
+ testWidgets('a fresh celebration throws confetti once, then it is gone', (
+ tester,
+ ) async {
+ await show(tester, shipServer());
+ expect(find.byKey(const ValueKey('super-confetti')), findsOneWidget);
+ await tester.pump(const Duration(seconds: 3));
+ expect(find.byKey(const ValueKey('super-confetti')), findsNothing);
+ await show(tester, shipServer());
+ expect(find.byKey(const ValueKey('super-confetti')), findsNothing);
+ });
+
+ testWidgets('a rebuild during the burst does not cut it short', (tester) async {
+ final server = shipServer();
+ await show(tester, server);
+ await tester.pump(const Duration(milliseconds: 500));
+ await show(tester, server);
+ await tester.pump(const Duration(milliseconds: 500));
+ expect(find.byKey(const ValueKey('super-confetti')), findsOneWidget);
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('reduced motion keeps the line still', (tester) async {
+ await show(tester, shipServer(), reduceMotion: true);
+ expect(find.byKey(const ValueKey('super-confetti')), findsNothing);
+ expect(find.text('Shipped: Avatars'), findsOneWidget);
+ });
+
+ testWidgets('an old celebration in the history throws none', (tester) async {
+ await show(tester, shipServer(at: now.subtract(const Duration(hours: 3))));
+ expect(find.byKey(const ValueKey('super-confetti')), findsNothing);
+ });
+
+ testWidgets('without who asked, that credit is left out', (tester) async {
+ await show(tester, shipServer(source: {'requesterId': null}));
+ expect(find.text('Requested by'), findsNothing);
+ expect(find.byType(SuperTabAvatar), findsNWidgets(2));
+ await tester.pumpAndSettle();
+ });
+
+ testWidgets('the conversation draws a ship message as the celebration', (
+ tester,
+ ) async {
+ await showView(tester, shipServer(at: DateTime.now().toUtc()));
+ expect(find.byType(SuperTabShipRow), findsOneWidget);
+ await tester.pumpAndSettle();
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 3734f54fa..107b6b787 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -7,6 +7,10 @@ import 'package:dio/dio.dart' show CancelToken;
import 'package:harness/super_tabs/attachment_upload.dart';
import 'package:harness/super_tabs/controller.dart';
+/// A signed link as the backend's private avatar bucket hands it out (avatarLinks.ts).
+String superTabSignedAvatar(String id) =>
+ 'https://storage.googleapis.com/avatars/$id?X-Goog-Expires=3600&X-Goog-Signature=fixture';
+
Map<String, dynamic> conversationFixture(String id, String title) => {
'id': id,
'title': title,
@@ -146,6 +150,7 @@ class SwarmPartsBackend {
'decisionsDigest': state['decisionsDigest'],
if (state['otherProjectsWork'] != null)
'otherProjectsWork': state['otherProjectsWork'],
+ if (state['avatars'] != null) 'avatars': state['avatars'],
};
List<MapEntry<String, _HeldPart>> _ordered() =>
@@ -459,6 +464,84 @@ class ConversationServer {
)['lastMessageSequence'] = revision;
}
+ // Avatar pictures uploaded, as the backend's avatar route keeps them.
+ final avatarUploads = <Uint8List>[];
+
+ /// What the backend's avatar route does with a picture.
+ Future<Map<String, dynamic>> uploadAvatar({
+ required String tabId,
+ required Uint8List png,
+ }) async {
+ avatarUploads.add(png);
+ final id = 'avatar-${avatarUploads.length}';
+ return {
+ 'avatar': {'id': id},
+ };
+ }
+
+ /// A person's own status or avatar, or an agent's avatar, as the backend
+ /// stores it (profile.ts).
+ void _profile(Map command, String reader) {
+ final (key, id) = command['type'] == 'agent.avatar'
+ ? ('agents', command['agentId'])
+ : ('people', reader);
+ // An upload's record says only that there is one; its link comes signed with each read (backend avatarLinks.ts).
+ Map<String, dynamic> avatar(Map choice) {
+ if (choice['kind'] != 'upload') return Map<String, dynamic>.from(choice);
+ final links = state['avatars'] ??= <String, dynamic>{};
+ (links as Map)['${key == 'agents' ? 'agent' : 'person'}:$id'] =
+ superTabSignedAvatar(choice['id'] as String);
+ return {'kind': 'upload'};
+ }
+
+ state[key] = <dynamic>[
+ for (final row in state[key] as List)
+ if ((row as Map)['id'] != id)
+ row
+ else
+ <String, dynamic>{
+ ...row,
+ if (command['type'] == 'member.status')
+ 'status': command['status']
+ else
+ 'avatar': command['avatar'] == null
+ ? null
+ : avatar(command['avatar'] as Map),
+ },
+ ];
+ revision++;
+ }
+
+ /// A reaction as the backend keeps it (reactions.ts): one per reactor and
+ /// emoji, and the group bumped only on a change.
+ bool _react(Map command, String reader) {
+ final message = messages.firstWhere((m) => m['id'] == command['messageId']);
+ final counts = [
+ for (final row in message['reactions'] as List? ?? const [])
+ Map<String, dynamic>.from(row as Map),
+ ];
+ final row = counts.where((r) => r['emoji'] == command['emoji']).firstOrNull;
+ final by = [...(row?['by'] as List? ?? const [])];
+ final mine = by.any((who) => (who as Map)['id'] == reader);
+ if (mine == command['on']) return false;
+ if (command['on'] == true) {
+ by.add({'kind': 'person', 'id': reader});
+ } else {
+ by.removeWhere((who) => (who as Map)['id'] == reader);
+ }
+ counts.removeWhere((r) => r['emoji'] == command['emoji']);
+ if (by.isNotEmpty) {
+ counts.add({'emoji': command['emoji'], 'count': by.length, 'by': by});
+ }
+ message['reactions'] = counts;
+ final group = (state['conversations'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((g) => g['id'] == command['conversationId']);
+ group['reactionSeq'] = ((group['reactionSeq'] as int?) ?? 0) + 1;
+ revision++;
+ return true;
+ }
+
/// What the backend does with a file sent to its upload route.
Future<Map<String, dynamic>> upload({
required String tabId,
@@ -541,6 +624,12 @@ class ConversationServer {
);
messages.last['replyTo'] = command['replyTo'];
output['messageId'] = 'message-$revision';
+ } else if (command['type'] == 'member.status' ||
+ command['type'] == 'member.avatar' ||
+ command['type'] == 'agent.avatar') {
+ _profile(command, reader ?? 'owner');
+ } else if (command['type'] == 'message.react') {
+ output['changed'] = _react(command, reader ?? 'owner');
} else if (command['type'] == 'decision.answer') {
answerDecision(
command['decisionId'] as String,
@@ -769,6 +858,12 @@ class ConversationServer {
jsonEncode({
'messages': after == null ? page.reversed.toList() : page,
'next': next,
+ 'reactionSeq':
+ (state['conversations'] as List)
+ .cast<Map>()
+ .where((g) => g['id'] == conversationId)
+ .firstOrNull?['reactionSeq'] ??
+ 0,
}),
) as Map<String, dynamic>;
}
@@ -799,8 +894,10 @@ class ConversationServer {
String conversationId = 'lead',
String text = 'Please confirm the release.',
String createdAt = '2026-10-24T05:00:00Z',
+ String? leadId,
}) {
mentions.add({
+ 'leadId': ?leadId,
'id': 'mention-${mentions.length + 1}',
'projectId': 'lead',
'projectName': 'web-project',
@@ -897,6 +994,7 @@ class ConversationServer {
String account = 'owner',
SuperTabUpload? upload,
}) => SuperTabController(
+ avatarUpload: uploadAvatar,
tabId: 'tab',
accountId: account,
request: (method, path, {body}) => runZoned(
diff --git a/docs/swarms.md b/docs/swarms.md
index 9bd4b7616..597b32b69 100644
--- a/docs/swarms.md
+++ b/docs/swarms.md
@@ -234,6 +234,47 @@ wrote. Private conversations, Chat with PM among them, never count and never
appear in it. Decisions asked of a person will count toward Unblocked once
decisions ship.
+## Avatars, status and celebrations
+
+People and agents each show one avatar wherever they appear: messages, the
+roster, machine rows and mentions. A person sets theirs from their own row in
+the roster. They can pick one of eight pictures or upload a PNG, JPEG or WebP.
+Desktop and the web app crop the upload square and resize it to 256 pixels
+before sending it. The server accepts only those three formats, judged by the
+file's own bytes, and at most 1 MB. Each upload can be used once. Without a picture, a person shows their initial. An
+agent shows a pattern made from its name, the same on every computer, with a
+small Claude or Codex badge. Its contributor changes it from the agent's
+details, and the project's product manager can change it with `agent.avatar`.
+
+A person can also set a short status, such as Focusing, Coffee break or their
+own words up to 80 characters. They can let it clear itself after an hour,
+after four hours or at the end of the day. It shows next to their name and as
+a small emoji on their avatar, and disappears at its time even on a page where
+nothing else changes.
+
+Avatars and status reach only the Swarm's members. Uploaded pictures are kept
+in a private bucket that nobody can read directly. Each member's read of the
+Swarm carries signed links to the pictures it shows. A link stays the same for
+half an hour, so pictures are not fetched on every poll, and stops opening
+within an hour. A copied link expires, and someone removed from the Swarm gets
+no new links. A server without the private bucket (`SUPER_TAB_AVATARS_BUCKET`)
+refuses uploads; the eight pictures still work.
+
+People and agents react to a message with a small set: 👍 🎉 ❤️ 😄 👀 🚀.
+Counts show under the message, with the reader's own highlighted and the names
+on hover. Reacting twice keeps one reaction, and reacting again takes it back.
+Someone who leaves the Swarm drops out of the counts. A reaction changes its
+conversation, so other readers see it within one poll, also when new messages
+arrive in the same poll.
+
+When linked work is marked Done (a group with a pull request, marked Done after
+its merge), the project chat shows one celebration line. It names the person
+who asked for the work, the engineer who built it and the reviewers. A group is
+one request, so only its first Done is celebrated, not a later attempt's. A new
+one throws confetti once on each computer. An old one in the history, or one
+seen with reduced motion, stays still. A private conversation is never celebrated,
+and the line never quotes the work's result.
+
## Lead updates
The default update cadence is five minutes; the project menu also offers one,