Skip to content

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

Merge batch 11-04 b1210: #2891 #2899 #2892 #2903 #2907 #2906 #2913 (#2925)

0xken15b54a1878f589
diff --git a/backend/integration/superTabPersonalLead.test.ts b/backend/integration/superTabPersonalLead.test.ts
new file mode 100644
index 000000000..e9e3a0e36
--- /dev/null
+++ b/backend/integration/superTabPersonalLead.test.ts
@@ -0,0 +1,71 @@
+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 type { AuthUser } from '../src/lib/ssoAuth.js'
+import { SuperTabStore } from '../src/superTabs/store.js'
+import { MemoryAttachmentStore } from '../src/superTabs/attachments.js'
+import type { Command } from '../src/superTabs/commands.js'
+import { PERSONAL_SWARM_OPERATION } from '../src/superTabs/deletion.js'
+
+// A Personal Swarm's project chat with no Lead (task #2633): the person's messages wait for the Lead their Desktop starts, and
+// are delivered to it, by delivery as any other, once it joins. A fresh loopback replica set, created here.
+let replica: MongoMemoryReplSet
+let db: PrismaClient
+const owner: AuthUser = { sub: '330000000000000000000001', email: '[email protected]', autonomousEnv: 'prod', role: 'user' }
+const config = { engine: 'claude', model: 'fixture-model', effort: 'high', contextWindow: 200000, engineVersion: 'fixture' }
+
+beforeAll(async () => {
+ replica = await MongoMemoryReplSet.create({ binary: { version: '7.0.24', downloadDir: join(tmpdir(), 'harness-super-tab-mongodb-binaries') },
+ replSet: { count: 1, ip: '127.0.0.1', storageEngine: 'wiredTiger' } })
+ const uri = replica.getUri(`swarm_personal_lead_test_${randomUUID().replaceAll('-', '_')}`)
+ await promisify(execFile)(join(process.cwd(), 'node_modules/.bin/prisma'), ['db', 'push', '--skip-generate'], {
+ env: { ...process.env, DATABASE_URL: uri }, timeout: 60000,
+ })
+ db = new PrismaClient({ datasources: { db: { url: uri } } })
+ await db.user.create({ data: { id: owner.sub, externalId: `fixture-${owner.sub}`, email: owner.email, autonomousEnv: owner.autonomousEnv } })
+ await db.machine.create({ data: { machineId: 'huy-mac', userId: owner.sub, apiKey: 'fixture-huy-mac', managerId: 'fixture', autonomousEnv: 'prod', authMode: 'remote' } })
+})
+afterAll(async () => {
+ await db?.$disconnect()
+ await replica?.stop()
+})
+
+async function personal(operationId = PERSONAL_SWARM_OPERATION) {
+ const store = new SuperTabStore(db, () => Date.now(), { store: new MemoryAttachmentStore(), prefix: 'super-tabs', publicBase: 'https://cdn.example.test' })
+ const tab = (await store.create(owner, operationId, 'Personal', 'private')).id
+ const execute = (command: Command) => store.execute(owner, tab, { operationId: randomUUID(), command })
+ const games = (await execute({ type: 'project.create', name: 'Games', visibility: 'private', brief: '' })).result as { projectId: string; conversationId: string }
+ const send = async (text: string) => String((await execute({ type: 'message.send', conversationId: games.conversationId, text, replyTo: null, recipientIds: [] }))
+ .result.messageId)
+ const join = async () => String((await execute({ type: 'agent.add', conversationId: games.conversationId, machineId: 'huy-mac', harnessId: randomUUID(), name: 'Lead',
+ configuration: config, lead: true })).result.agentId)
+ return { store, tab, execute, games, send, join }
+}
+const delivered = async (tab: string, agentId: string) =>
+ (await db.superTabDelivery.findMany({ where: { tabId: tab, agentId }, orderBy: { createdAt: 'asc' } })).map(d => d.messageId)
+
+describe('a Personal Swarm project chat with no Lead', () => {
+ it('delivers the person\'s waiting messages to the Lead that joins, once', async () => {
+ const f = await personal()
+ const first = await f.send('make the landing page dark')
+ expect((await f.execute({ type: 'lead.claim', projectId: f.games.projectId, machineId: 'huy-mac' })).result.leadStart).toBe('start')
+ const second = await f.send('and the buttons round')
+ const lead = await f.join()
+ expect((await delivered(f.tab, lead)).sort()).toEqual([first, second].sort())
+ // Once it leads, a message goes to it as to any Lead, and nothing waits any more.
+ const third = await f.send('thanks')
+ expect((await delivered(f.tab, lead)).sort()).toEqual([first, second, third].sort())
+ })
+
+ it('in a Team Swarm delivers nothing that was sent before its Lead joined', async () => {
+ const f = await personal(randomUUID())
+ await f.send('hello')
+ const lead = await f.join()
+ expect(await delivered(f.tab, lead)).toEqual([])
+ })
+})
diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.ts
index ba48983a4..022520936 100644
--- a/backend/src/superTabs/commands.test.ts
+++ b/backend/src/superTabs/commands.test.ts
@@ -4269,19 +4269,92 @@ describe('agent.stopRefused', () => {
})
describe('archiving unfinished work', () => {
- /** A task Peer asked for, its worker's attempt left at [status]. */
- function task(status: 'lost' | 'stopped' | 'cancelled' | 'done') {
+ /** A task Peer asked for (or, with [asked] false, the owner opened for themselves), its worker's attempt left at [status],
+ * in the Swarm's first project or in [project] when given (a project Peer creates, so its owner is not the Swarm owner). */
+ function task(status: 'lost' | 'stopped' | 'cancelled' | 'done' | 'working', { asked = true, peerProject = false } = {}) {
const f = fixture()
f.invite()
- const group = f.run({ type: 'conversation.create', title: 'Round tabs', brief: 'Drop closed tabs.', requesterId: 'peer',
- checks: [{ description: 'Closed tabs leave the dial.', independent: false }] }).result.conversationId as string
+ const projectId = peerProject ? f.run({ type: 'project.create', name: 'Dial', visibility: 'public', brief: '' }, peer).result.projectId as string : undefined
+ const group = f.run({ type: 'conversation.create', title: 'Round tabs', brief: 'Drop closed tabs.', ...(asked ? { requesterId: 'peer' } : {}),
+ ...(projectId ? { projectId } : {}), checks: [{ description: 'Closed tabs leave the dial.', independent: false }] }).result.conversationId as string
const worker = f.add('worker', 'owner', group)
const assignmentId = f.run({ type: 'work.assign', conversationId: group, agentId: worker }).result.assignmentId as string
if (status === 'cancelled') f.run({ type: 'work.cancel', conversationId: group, assignmentId, reason: 'Superseded by the dial rewrite.' })
- else f.state.conversations.find(c => c.id === group)!.assignment!.status = status
+ else if (status !== 'working') f.state.conversations.find(c => c.id === group)!.assignment!.status = status
return { f, group, assignmentId }
}
- const archive = (t: ReturnType<typeof task>) => t.f.run({ type: 'conversation.archive', conversationId: t.group, archived: true })
+ const archive = (t: ReturnType<typeof task>, actor: Actor = owner) => t.f.run({ type: 'conversation.archive', conversationId: t.group, archived: true }, actor)
+ const cancel = (t: ReturnType<typeof task>, actor: Actor) =>
+ t.f.run({ type: 'work.cancel', conversationId: t.group, assignmentId: t.assignmentId, reason: 'Nobody can finish it here.' }, actor)
+ const at = (t: ReturnType<typeof task>) => t.f.state.conversations.find(c => c.id === t.group)!
+ const WHO_CANCELS_ENDED = 'Only the person who asked for this task, its project\'s owner, the Swarm owner or an agent of this project can cancel it.'
+ const WHO_CANCELS_LIVE = 'Only an agent of this project or the Swarm owner can cancel work in progress. Ask the project\'s coordinator.'
+
+ // Diego, 2026-11-04 (#2639, a regression from #1903): a member who is not the Swarm owner could neither archive nor cancel a
+ // dead task they asked for, so it stayed in the Swarm for good.
+ it.each(['lost', 'stopped'] as const)('lets the requester cancel a %s task with a reason, which then archives and tags nobody', status => {
+ const t = task(status)
+ const cancelled = cancel(t, peer)
+ expect(at(t).assignment).toMatchObject({ status: 'cancelled', result: 'Nobody can finish it here.' })
+ // Nobody is left to tell: its worker stopped or lost the task already.
+ expect(cancelled.messages.filter(m => m.conversationId === t.group)).toEqual([expect.objectContaining({ recipients: [],
+ text: 'peer cancelled this task: Nobody can finish it here.' })])
+ // A retry keeps the first reason and says nothing more.
+ expect(t.f.run({ type: 'work.cancel', conversationId: t.group, assignmentId: t.assignmentId, reason: 'Again.' }, peer).messages).toEqual([])
+ expect(at(t).assignment!.result).toBe('Nobody can finish it here.')
+ expect(archive(t, peer).messages).toEqual([])
+ expect(at(t).archived).toBe(true)
+ })
+
+ it('lets a project\'s owner who is not the Swarm owner cancel a lost task in their project', () => {
+ const t = task('lost', { asked: false, peerProject: true })
+ cancel(t, peer)
+ expect(at(t).assignment!.status).toBe('cancelled')
+ // The owner asked for it, and hears that it closed without shipping.
+ expect(archive(t, peer).messages).toEqual([expect.objectContaining({ mentions: ['owner'] })])
+ expect(at(t).archived).toBe(true)
+ })
+
+ it('still refuses a collaborator who did not ask for a task, working or lost, and says who can cancel it', () => {
+ const working = task('working', { asked: false })
+ expect(() => cancel(working, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN', message: WHO_CANCELS_LIVE }))
+ expect(at(working).assignment!.status).toBe('working')
+ const lost = task('lost', { asked: false })
+ expect(() => cancel(lost, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN', message: WHO_CANCELS_ENDED }))
+ expect(at(lost).assignment!.status).toBe('lost')
+ })
+
+ it('refuses the requester while its agent still works on it, and another project\'s owner on a lost one', () => {
+ const working = task('working')
+ expect(() => cancel(working, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN', message: WHO_CANCELS_LIVE }))
+ expect(at(working).assignment!.status).toBe('working')
+ const lost = task('lost', { asked: false })
+ lost.f.run({ type: 'project.create', name: 'Elsewhere', visibility: 'public', brief: '' }, peer)
+ expect(() => cancel(lost, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(at(lost).assignment!.status).toBe('lost')
+ })
+
+ // Security review 2 of #2907: a collaborator who did not ask could name themselves its requester, then cancel it. Among
+ // people only an owner names who asked; agents still name the person they opened it for.
+ it('refuses a collaborator who names themselves requester of a lost task, so they still cannot cancel it', () => {
+ const t = task('lost', { asked: false })
+ expect(() => t.f.run({ type: 'conversation.requester', conversationId: t.group, personId: 'peer' }, peer))
+ .toThrow(expect.objectContaining({ code: 'FORBIDDEN', message: 'Among people, only the Swarm owner or the project\'s owner names who asked for a task.' }))
+ expect(() => t.f.run({ type: 'conversation.requester', conversationId: t.group, personId: null }, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(at(t).requesterId).toBe('owner')
+ expect(() => cancel(t, peer)).toThrow(expect.objectContaining({ code: 'FORBIDDEN' }))
+ expect(at(t).assignment!.status).toBe('lost')
+ // The owner of the task's project still names them, and then they may close it.
+ t.f.run({ type: 'conversation.requester', conversationId: t.group, personId: 'peer' })
+ cancel(t, peer)
+ expect(at(t).assignment!.status).toBe('cancelled')
+ })
+
+ it('names who can cancel when it refuses to archive unfinished work', () => {
+ const t = task('lost', { asked: false })
+ expect(() => archive(t, peer)).toThrow(expect.objectContaining({ code: 'WORK_UNFINISHED',
+ message: `This task did not finish. Hand it on, or cancel it with a reason, before archiving. ${WHO_CANCELS_ENDED}` }))
+ })
it.each(['lost', 'stopped'] as const)('refuses to archive a %s task by hand, so nothing unfinished closes silently', status => {
const t = task(status)
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index cec8d53d0..89250200f 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -41,7 +41,7 @@ import { shippedAt } from './ship.js'
import { syncTaskLines } from './taskLine.js'
import { assignedNotice, tellBuddies } from './buddyNews.js'
import { bindPullRequestCards, bindTaskCard, pullRequestCard, recordCardMerged } from './cards.js'
-import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, statusSchema, type AvatarUpload } from './profile.js'
+import { avatarChoice, setAgentAvatar, setMemberAvatar, setStatus, setTimeZone, statusSchema, type AvatarUpload } from './profile.js'
import { cancelledTags, cancelReason, switchExpired, unfinishedWork } from './tidy.js'
import { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, groupRepositoryUrl, canReadAgent, canReadProject, deleteProject, markConfidential, onTeamAccount, requireSingleRegistration, groupProject, inviteLanding, ledProject, manageProject, MAX_ROLES, mutableProjects, placeRules, projectAgent, projectMembers, projectOf, projectsOf, readAgent, readConversation, readProject, requestedByLine, sameProject, sharedWithLeads, withRoleDefaults, type SwarmProject, PROJECT_STATUS_MAX } from './projects.js'
import { recordClosing } from './closedAgents.js'
@@ -51,7 +51,7 @@ import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liv
import { BUDDY_REQUIREMENTS, buddyChatId, buddyReady, chosenBuddyName, isBuddy, isBuddyChat, isSwarmBuddy, isSwarmBuddyChat, MAX_PROPOSAL_ASKS, MAX_PROPOSAL_ATTACHMENTS, openBuddyChat, openSwarmBuddyChat, PM_LINE_KIND, PROPOSAL_ASK_MS, PROPOSAL_SENT_KIND, proposalSentText, proposalText, proposalTitle, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'
import { askBuddyModel, buddyModelResult, sendBuddyHome, sessionModel } from './buddyModel.js'
-import { launchRefusedLine, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, LEAD_CAPABILITY, placeLead } from './leadStart.js'
+import { launchRefusedLine, leadArrived, LEAD_CLAIM_MS, leadJoined, leadOvertaken, leadStartFailed, leadStarting, leadHost, leadWaits, LEAD_CAPABILITY, placeLead } from './leadStart.js'
import { appendRouting, coordinatorNameOf, routingSummary, FIRST_INSTRUCTIONS, FIRST_SUMMARY, instructionsHash, instructionsTextSchema, legacyRoleName, liveNotes, MAX_NOTES, noteTextSchema, roleNameSchema, summarySchema, type PmNote } from './instructions.js'
import { INSTRUCTIONS_TEMPLATE } from './instructionsTemplate.js'
import { placeAfter, queueSiblings } from './taskQueue.js'
@@ -199,6 +199,8 @@ export const commandSchema = z.discriminatedUnion('type', [
z.object({ type: z.literal('lead.start'), projectId: id, machineId: id.nullable(), engine: swarmEngine,
model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional(),
branchRef: z.string().max(1024).regex(/^refs\/(heads|remotes)\/[^\s\x00-\x1f\x7f]+$/).optional(), repositoryUrl: repositoryUrl.optional() }).strict(),
+ // A Personal Swarm's one start of a project's Lead by its person's Desktop, on their message in its chat (leadStart.ts).
+ z.object({ type: z.literal('lead.claim'), projectId: id, machineId: id }).strict(),
z.object({ type: z.literal('lead.switch'), projectId: id, engine: swarmEngine, profileId: id, machineId: id.optional(),
model: z.string().trim().min(1).max(200).optional(), effort: z.string().trim().min(1).max(80).optional() }).strict(),
z.object({ type: z.literal('project.skills'), projectId: id, mode: z.enum(['default', 'orchestration', 'custom']), askedIn: askedInSchema.optional() }).strict(),
@@ -296,6 +298,7 @@ export const commandSchema = z.discriminatedUnion('type', [
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.timeZone'), timeZone: z.string().min(1).max(64).nullable() }).strict(),
z.object({ type: z.literal('member.avatar'), avatar: avatarChoice }).strict(),
z.object({ type: z.literal('member.username'), username: z.string().max(64).nullable() }).strict(),
z.object({ type: z.literal('member.name'), name: z.string().max(200).nullable() }).strict(),
@@ -643,9 +646,9 @@ export function authorizeCommandAccess(state: SuperTabState, actor: Actor, comma
if (command.type === 'swarm.delete' || command.type === 'swarm.restore') return
// Marking one's own tag done changes only one's own list, so a viewer may do it too.
// Answering a decision asked of oneself changes only that decision, so a viewer may do it too.
- // So does choosing one's own username (usernames.ts) or name (personNames.ts).
+ // So does choosing one's own username (usernames.ts) or name (personNames.ts), and one's app telling one's time zone.
if (command.type === 'mention.done' || command.type === 'decision.answer' || command.type === 'member.username'
- || command.type === 'member.name') return void author(state, actor)
+ || command.type === 'member.name' || command.type === 'member.timeZone') return void author(state, actor)
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
author(state, actor, !leaving)
const buddy = actor.kind === 'agent' ? state.agents.find(a => a.id === actor.agentId && isBuddy(a)) : undefined
@@ -773,6 +776,9 @@ function proposalRequester(state: SuperTabState, project: SwarmProject, personId
const member = personId ? state.people.find(p => p.id === personId) : undefined
return member && canReadProject(state, { kind: 'person', userId: member.id, email: member.email }, project) ? member.id : undefined
}
+/** Who may cancel a lost or stopped task, and a live one (work.cancel), for the refusals that name them. */
+const WHO_CANCELS_ENDED = 'Only the person who asked for this task, its project\'s owner, the Swarm owner or an agent of this project can cancel it.'
+const WHO_CANCELS_LIVE = 'Only an agent of this project or the Swarm owner can cancel work in progress. Ask the project\'s coordinator.'
/** What an agent opening a group for nobody is told, so the person who asked still gets the credit (groups #294, #327). */
export const REQUESTER_UNKNOWN = 'Name the person who asked: conversation.requester with their personId for this group, or requesterId when you open a group.'
@@ -891,7 +897,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
if (command.type === 'swarm.delete' && (actor.kind !== 'person' || actor.userId !== state.ownerId)) notThere()
const leaving = command.type === 'member.remove' && actor.kind === 'person' && command.userId === actor.userId
const sender = author(state, actor, !leaving && command.type !== 'decision.answer' && command.type !== 'member.username'
- && command.type !== 'member.name')
+ && command.type !== 'member.name' && command.type !== 'member.timeZone')
authorizeCommandAccess(state, actor, command, context)
/** A machine's owner said so: they sent the command, or the Lead of the chat [askedIn] names passes on a message they wrote
* there in the last day, as routing rules are (machine.engineResume, machine.projects). */
@@ -1240,6 +1246,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
* one already starting takes it too. Nothing while they have no one Buddy, as before. When it cannot start, why, in plain
* words, for the line that tells its person (buddyDownLine).
*/
+ /** [project]'s Lead [agentId] joined its chat: it hears what its person sent there while it had none (leadStart.ts). */
+ const arrived = (project: SwarmProject, agentId: string) => {
+ if (!project.leadWaiting && !project.leadClaim) return
+ const late = leadArrived(state, project, agentId, context.now)
+ if (late.length) effects.lateDeliveries = [...effects.lateDeliveries ?? [], ...late]
+ }
const startOldChatBuddy = (chat: Conversation): string | undefined => {
if (command.type !== 'message.send' || actor.kind !== 'person') return
const owner = requireChatOwner(state, chat, actor.userId)
@@ -1570,6 +1582,26 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
Object.assign(result, { startId: start.id, machineId: start.request.machineId })
break
}
+ case 'lead.claim': {
+ // Only a Personal Swarm: its person's Desktop starts the Lead on their own machine, where their project's folder is. A
+ // Team Swarm's project gets its coordinator from a person who chooses it (task #2633).
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person starts a project\'s coordinator.', 403)
+ if (!isPersonalSwarm(state)) fail('PERSONAL_SWARM_ONLY', 'Only a Personal Swarm starts a project\'s coordinator on its first message.', 409)
+ if (state.paused) fail('PAUSED', 'New work is paused in this Swarm.')
+ const project = manageProject(state, actor, command.projectId)
+ const home = conversation(state, project.leadConversationId)
+ if (home.leadId && home.agentIds.includes(home.leadId)) fail('LEAD_EXISTS', `This project already has its ${coordinatorNameOf(project)}.`)
+ // One start at a time: another machine's recent claim, or a start the Swarm runs, is the one. The same machine claims
+ // again only once its own start ended, which its Desktop knows.
+ const held = project.leadClaim
+ if (leadStarting(state, project.id) || (held && held.machineId !== command.machineId && context.now - held.at < LEAD_CLAIM_MS)) {
+ result.leadStart = 'waiting'
+ break
+ }
+ project.leadClaim = { id: operationId, machineId: command.machineId, at: context.now }
+ result.leadStart = 'start'
+ break
+ }
case 'lead.switch': {
if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'A person moves a project\'s coordinator.', 403)
const project = projectOf(state, command.projectId)
@@ -2067,6 +2099,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
chatOnly(command.conversationId)
projectChatWork(command.conversationId)
const group = open(state, command.conversationId)
+ // Its requester may close it once it is lost or stopped (work.cancel), so among people only an owner names who asked;
+ // anyone else could name themselves and cancel a task they never asked for (security review 2 of #2907). Agents name
+ // the person they opened it for, as before.
+ if (actor.kind === 'person' && ![state.ownerId, groupProject(state, group).ownerId].includes(actor.userId)) {
+ fail('FORBIDDEN', 'Among people, only the Swarm owner or the project\'s owner names who asked for a task.', 403)
+ }
if (command.personId) group.requesterId = requester(state, groupProject(state, group), command.personId)
else delete group.requesterId
break
@@ -2129,7 +2167,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
const group = conversation(state, command.conversationId)
if (group.id === groupProject(state, group).leadConversationId) fail('LEAD_CONVERSATION', 'The Lead conversation stays available.')
if (command.archived && activeWork(group)) fail('WORK_ACTIVE', 'Resolve the active assignment before archiving this conversation.')
- if (command.archived && unfinishedWork(group)) fail('WORK_UNFINISHED', 'This task did not finish. Hand it on, or cancel it with a reason, before archiving.')
+ if (command.archived && unfinishedWork(group)) fail('WORK_UNFINISHED', `This task did not finish. Hand it on, or cancel it with a reason, before archiving. ${WHO_CANCELS_ENDED}`)
const tags = command.archived && !group.archived ? cancelledTags(state, group, actor) : []
if (tags.length) message(group.id, `Archived without shipping: the task was cancelled${cancelReason(group) ? ` (${cancelReason(group)})` : ''}.`, [], null, SYSTEM_ROW, undefined, tags)
group.archived = command.archived
@@ -2214,6 +2252,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
keepLead(group, agentId)
if (group.leadId && group.leadId !== agentId && activeWork(group)) fail('WORK_ACTIVE', 'Reconcile active work before replacing its lead.')
group.leadId = agentId
+ if (group.id === project.leadConversationId) arrived(project, agentId)
}
result.agentId = agentId
// Creation already handed this first request to the native harness (and
@@ -2668,6 +2707,7 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
// The people's to read: it answers the start a person asked for, whose "Waiting for a machine" line they read.
const joined = leadJoined(state, start, group, agentId)
message(group.id, joined.text, [], null, joined.source)
+ if (group.leadId === agentId) arrived(projectOf(state, start.request.leadFor.projectId), agentId)
}
}
// A Buddy always starts on a Swarm machine: its chat hears once it settles, as the Lead does for a worker.
@@ -2959,6 +2999,9 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
case 'member.status':
setStatus(state, actor, command.status, context.now)
break
+ case 'member.timeZone':
+ setTimeZone(state, actor, command.timeZone)
+ break
case 'message.react': {
// A reaction joins nobody to a task: only where the agent already is (project instructions, phase 4).
const group = open(state, command.conversationId)
@@ -3107,6 +3150,12 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
message(group.id, text, recipients, command.replyTo, command.agentOnly ? { ...AGENT_ONLY, ...command.notice ? { notice: command.notice } : {} } : undefined, attachments, mentions, command.mentionsIfNoWorker)
// After the person's message: nobody answers it, so its person is told why (Dee, review of #2447).
if (buddyDown) buddyDownLine(group, buddyDown)
+ // A Personal Swarm project chat with no Lead: the message waits for the Lead its person's Desktop starts (task #2633).
+ // A Team Swarm's says Not sent, as before.
+ const unled = actor.kind === 'person' && !recipients.length && !isBuddyChat(group) && isPersonalSwarm(state) ? groupProject(state, group) : undefined
+ if (unled && unled.leadConversationId === group.id && state.projects?.includes(unled) && !(group.leadId && group.agentIds.includes(group.leadId))) {
+ leadWaits(unled, operationId, context.now)
+ }
// The message that makes it LOOP_NOTICE_AT in a row between two agents tells their Lead, once; delivery is never held.
const speaker = actor.kind === 'agent' ? agent(state, actor.agentId) : null
const partner = speaker && recipients.length === 1 && recipients[0] !== speaker.id ? agent(state, recipients[0]!) : null
@@ -3437,11 +3486,16 @@ function applyCommandOnce(original: SuperTabState, actor: Actor, input: Command,
break
}
if (!assignment || assignment.id !== command.assignmentId) fail('STALE_ASSIGNMENT', 'This is no longer the active assignment.')
- if (!allowed) fail('FORBIDDEN', 'Only an agent of this project or the tab owner can cancel work.', 403)
- // A retry after the cancel keeps the first reason and tells the worker once.
- if (assignment.status === 'cancelled') break
// A stopped task is unfinished too, and only a cancel closes it (tidy.ts unfinishedWork): its worker is finished already.
const lost = assignment.status === 'lost', stopped = assignment.status === 'stopped'
+ // With no worker left to tell, the person who asked for it and its project's owner close it too, or it would stay for
+ // good where most people are not the Swarm owner (Diego, 2026-11-04, #2639). Live work stays the project's agents' and
+ // the Swarm owner's.
+ const ended = lost || stopped || assignment.status === 'cancelled'
+ const closes = ended && actor.kind === 'person' && [group.requesterId, project.ownerId].includes(actor.userId)
+ if (!allowed && !closes) fail('FORBIDDEN', ended ? WHO_CANCELS_ENDED : WHO_CANCELS_LIVE, 403)
+ // A retry after the cancel keeps the first reason and tells the worker once.
+ if (assignment.status === 'cancelled') break
if (!activeWork(group) && !lost && !stopped) fail('ATTEMPT_CLOSED', 'This attempt has already ended.')
// A removed worker (reconciling) can never confirm a stop, so this is the only way to close its task; nobody is left to tell.
// A lost task's agent was told already that its task moved, and does not wait for a decision.
diff --git a/backend/src/superTabs/leadStart.ts b/backend/src/superTabs/leadStart.ts
index d02096dcc..788f91819 100644
--- a/backend/src/superTabs/leadStart.ts
+++ b/backend/src/superTabs/leadStart.ts
@@ -228,3 +228,30 @@ export function leadStartFailed(state: SuperTabState, start: AgentStart, reason:
Object.assign(placement, { status: 'failed', reason: publicReason(reason) })
return failureNotice(start.request.name, reason)
}
+
+/** How long a person's message in their Personal Swarm's project chat with no Lead waits for its Lead (task #2633, Huy 11-04):
+ * one sent longer before the Lead joins is not delivered to it. */
+export const LEAD_WAIT_MS = 30 * 60_000
+/** At most this many messages wait for a project's Lead, the newest. */
+export const MAX_LEAD_WAITING = 20
+/** How long one Desktop's claim to start a project's Lead (lead.claim) holds off another machine's: past it, that start is
+ * taken as lost. A native start takes a few minutes at most, an engine's install included. */
+export const LEAD_CLAIM_MS = 10 * 60_000
+
+/** Records message [id] as waiting for [project]'s Lead, dropping what waited too long, keeping the newest. */
+export function leadWaits(project: SwarmProject, id: string, now: number): void {
+ project.leadWaiting = [...(project.leadWaiting ?? []).filter(w => now - w.at < LEAD_WAIT_MS), { id, at: now }].slice(-MAX_LEAD_WAITING)
+}
+
+/** [project]'s Lead [agentId] joined its chat: the messages its person sent there while it had none are delivered to it, as a
+ * Buddy's waiting messages are (store.ts writeLateDeliveries checks each is its person's own row in that chat), and what waited
+ * and the claim end. */
+export function leadArrived(state: SuperTabState, project: SwarmProject, agentId: string, now: number) {
+ const waiting = (project.leadWaiting ?? []).filter(w => now - w.at < LEAD_WAIT_MS)
+ delete project.leadWaiting
+ delete project.leadClaim
+ const owner = state.people.find(p => p.id === project.ownerId)
+ if (!owner) return []
+ return waiting.map(w => ({ messageId: w.id, conversationId: project.leadConversationId, agentId, lead: true as const,
+ author: { kind: 'person' as const, id: owner.id, generation: owner.generation } }))
+}
diff --git a/backend/src/superTabs/leadWaiting.test.ts b/backend/src/superTabs/leadWaiting.test.ts
new file mode 100644
index 000000000..90f751a5b
--- /dev/null
+++ b/backend/src/superTabs/leadWaiting.test.ts
@@ -0,0 +1,137 @@
+import { describe, expect, it } from 'vitest'
+import { applyCommand, type Command, type CommandContext } from './commands.js'
+import { PERSONAL_SWARM_OPERATION } from './deletion.js'
+import { createSuperTab, stableId, visibleState, type Actor, type AgentConfiguration, type SuperTabState } from './model.js'
+import { projectsOf } from './projects.js'
+
+// A Personal Swarm's project chat with no Lead (task #2633, Huy 11-04): the person's message waits for the project's Lead,
+// which their Desktop starts on their own machine after one claim (lead.claim), and reaches it once it joins. A Team Swarm
+// keeps "Not sent": nothing waits there and nothing is claimed.
+
+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 NOW = 1_000_000
+const MINUTE = 60_000
+
+function fixture(personal = true) {
+ const id = personal ? stableId('super-tab', 'prod', 'owner', PERSONAL_SWARM_OPERATION) : 'team'
+ let state = createSuperTab(id, personal ? 'Personal' : 'Team', { id: 'owner', email: owner.email }, 'prod')
+ let sequence = 0
+ let now = NOW
+ const run = (command: Command, actor: Actor = owner, context: Partial<CommandContext> = {}, operationId = `op-${++sequence}`) => {
+ const effects = applyCommand(state, actor, command, { now, operationId, ...context })
+ state = effects.state
+ return effects
+ }
+ const created = run({ type: 'project.create', name: 'Games', visibility: 'private', brief: '' }).result as { projectId: string; conversationId: string }
+ const project = () => projectsOf(state).find(p => p.id === created.projectId)!
+ /** The id of the message it sent. */
+ const send = (text: string) => run({ type: 'message.send', conversationId: created.conversationId, text, replyTo: null, recipientIds: [] })
+ .result.messageId as string
+ const claim = (machineId: string) => run({ type: 'lead.claim', projectId: created.projectId, machineId }).result.leadStart
+ const join = (harnessId: string, repo: boolean) => run({ type: 'agent.add', conversationId: created.conversationId, machineId: 'mac', harnessId, name: 'Lead',
+ configuration: config, lead: true, ...(repo ? { project: { cwd: '/Users/huy/games', repositoryUrl: 'https://github.com/huy/games' } } : {}) },
+ owner, { contribution: { machineOwnerId: 'owner', contributorId: 'owner' } })
+ return { run, send, claim, join, project, conversationId: created.conversationId, projectId: created.projectId,
+ get state(): SuperTabState { return state }, advance: (ms: number) => { now += ms } }
+}
+
+const refusal = (run: () => unknown) => {
+ try { run(); return 'applied' } catch (error) { return (error as { code?: string }).code }
+}
+
+describe('a Personal Swarm project chat with no Lead', () => {
+ it('keeps the message for the Lead, and the first claim starts it', () => {
+ const f = fixture()
+ const m1 = f.send('make the landing page dark')
+ expect(f.project().leadWaiting).toEqual([{ id: m1, at: NOW }])
+ expect(f.claim('mac')).toBe('start')
+ expect(f.project().leadClaim).toMatchObject({ machineId: 'mac', at: NOW })
+ })
+
+ it('delivers the waiting message to the Lead that joins with a repo, and clears what waited', () => {
+ const f = fixture()
+ const m1 = f.send('make the landing page dark')
+ f.claim('mac')
+ const joined = f.join('h1', true)
+ const agentId = joined.result.agentId as string
+ expect(joined.lateDeliveries).toEqual([{ messageId: m1, conversationId: f.conversationId, agentId, lead: true,
+ author: { kind: 'person', id: 'owner', generation: f.state.people[0]!.generation } }])
+ expect(f.project().leadWaiting).toBeUndefined()
+ expect(f.project().leadClaim).toBeUndefined()
+ expect(f.project().repository).toMatchObject({ cwd: '/Users/huy/games' })
+ })
+
+ it('delivers the waiting message to the Lead that joins with no repo', () => {
+ const f = fixture()
+ const m1 = f.send('a scratch idea')
+ f.claim('mac')
+ const joined = f.join('h1', false)
+ expect(joined.lateDeliveries?.map(d => d.messageId)).toEqual([m1])
+ expect(f.project().repository).toBeUndefined()
+ })
+
+ it('starts one Lead for two quick sends: the second claim from another machine waits, and both messages reach the Lead', () => {
+ const f = fixture()
+ const m1 = f.send('first')
+ expect(f.claim('mac')).toBe('start')
+ const m2 = f.send('second')
+ expect(f.claim('mini')).toBe('waiting')
+ expect(f.project().leadClaim).toMatchObject({ machineId: 'mac' })
+ expect(f.join('h1', false).lateDeliveries?.map(d => d.messageId)).toEqual([m1, m2])
+ })
+
+ it('lets the claiming machine claim again, and another machine once the claim is 10 minutes old', () => {
+ const f = fixture()
+ f.send('first')
+ expect(f.claim('mac')).toBe('start')
+ expect(f.claim('mac')).toBe('start')
+ f.advance(9 * MINUTE)
+ expect(f.claim('mini')).toBe('waiting')
+ f.advance(MINUTE)
+ expect(f.claim('mini')).toBe('start')
+ expect(f.project().leadClaim).toMatchObject({ machineId: 'mini' })
+ })
+
+ it('never delivers a message that waited over 30 minutes, and keeps at most 20', () => {
+ const f = fixture()
+ f.send('old')
+ f.advance(31 * MINUTE)
+ const sent = Array.from({ length: 21 }, (_, i) => f.send(`new ${i}`))
+ expect(f.project().leadWaiting?.map(w => w.id)).toEqual(sent.slice(1))
+ expect(f.join('h1', false).lateDeliveries?.map(d => d.messageId)).toEqual(sent.slice(1))
+ })
+
+ it('keeps nothing once the chat has its Lead, and refuses a claim then', () => {
+ const f = fixture()
+ f.join('h1', false)
+ f.send('hello')
+ expect(f.project().leadWaiting).toBeUndefined()
+ expect(refusal(() => f.claim('mac'))).toBe('LEAD_EXISTS')
+ })
+})
+
+describe('who reads the claim', () => {
+ it('names its machine to the project\'s readers, never to a Buddy', () => {
+ const f = fixture()
+ f.send('hello')
+ f.claim('mac')
+ const owner = f.state.people[0]!
+ f.state.agents.push({ id: 'buddy', machineId: 'mac', harnessId: 'b1', machineOwnerId: 'owner', contributorId: 'owner',
+ membershipGeneration: owner.generation, hostGrant: null, name: 'Buddy', configuration: config, configurationVersion: 'v',
+ buddyOf: { personId: 'owner', generation: owner.generation }, buddyScope: 'swarm' } as never)
+ const read = (actor: Actor) => visibleState(f.state, actor, NOW).projects!.find(p => p.id === f.projectId)!
+ expect(read({ kind: 'person', userId: 'owner', email: '[email protected]' }).leadClaim).toMatchObject({ machineId: 'mac' })
+ expect(read({ kind: 'agent', agentId: 'buddy', machineOwnerId: 'owner' } as Actor).leadClaim).toBeUndefined()
+ })
+})
+
+describe('a Team Swarm project chat with no Lead', () => {
+ it('keeps nothing for a Lead and refuses the claim, so it still says Not sent', () => {
+ const f = fixture(false)
+ f.send('hello')
+ expect(f.project().leadWaiting).toBeUndefined()
+ expect(refusal(() => f.claim('mac'))).toBe('PERSONAL_SWARM_ONLY')
+ expect(f.join('h1', false).lateDeliveries).toBeUndefined()
+ })
+})
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 5a505388c..bd0425921 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -20,6 +20,9 @@ export interface Person {
generation: string
/** Their own short status (profile.ts); only Swarm members read it. */
status?: import('./profile.js').PersonStatus
+ /** Their time zone's IANA name ("Asia/Ho_Chi_Minh"), as their own app reports it (profile.ts); absent until it has.
+ * Only Swarm members read it, for the local time on a person's card. */
+ timeZone?: string
/** Their own avatar (profile.ts); only Swarm members read it. */
avatar?: import('./profile.js').Avatar
/** The name they chose (usernames.ts), or one kept for them; absent, readers work out their default. Only members read it. */
@@ -697,7 +700,8 @@ export interface CommandEffects {
decisions?: import('./decisions.js').DecisionDraft[]
decisionAnswer?: import('./decisions.js').DecisionAnswer
/** Deliveries of messages already stored: a Buddy thread session's first messages, sent while it started (buddySessions.ts). */
- lateDeliveries?: Array<{ messageId: string; conversationId: string; agentId: string; author: { kind: 'person'; id: string; generation: string } }>
+ /** `lead`: a project's Lead hearing its person's messages sent while the chat had none (leadStart.ts leadArrived). */
+ lateDeliveries?: Array<{ messageId: string; conversationId: string; agentId: string; author: { kind: 'person'; id: string; generation: string }; lead?: true }>
/** A project's new instructions revision, written outside the tab state by the store (instructions.ts). */
instructions?: import('./instructions.js').InstructionsWrite
/** A coordinator's note kept or a note removed, written outside the tab state by the store (instructions.ts). */
@@ -1001,6 +1005,8 @@ export function visibleState(state: SuperTabState, actor: Actor, now = Date.now(
for (const project of visible.projects ?? []) {
const lead = project.lead
if (lead) project.lead = { status: lead.status, ...(lead.reason !== undefined ? { reason: lead.reason } : {}) } as typeof lead
+ // Which of its person's machines starts the Lead of a Personal project (leadStart.ts) is a machine too.
+ delete project.leadClaim
}
if (visible.project) visible.project = { repositoryUrl: visible.project.repositoryUrl } as typeof visible.project
delete visible.rules
diff --git a/backend/src/superTabs/profile.test.ts b/backend/src/superTabs/profile.test.ts
index c23e6da91..55fe0a124 100644
--- a/backend/src/superTabs/profile.test.ts
+++ b/backend/src/superTabs/profile.test.ts
@@ -64,6 +64,33 @@ describe('status line', () => {
})
})
+describe('time zone', () => {
+ it('sets and clears the person’s own zone, read by members', () => {
+ const f = fixture()
+ f.invite()
+ f.run({ type: 'member.timeZone', timeZone: 'Asia/Ho_Chi_Minh' })
+ expect(f.member('owner')!.timeZone).toBe('Asia/Ho_Chi_Minh')
+ expect(visibleState(f.state, peer).people.find(p => p.id === 'owner')!.timeZone).toBe('Asia/Ho_Chi_Minh')
+ f.run({ type: 'member.timeZone', timeZone: null })
+ expect(f.member('owner')!.timeZone).toBeUndefined()
+ })
+
+ it('refuses an unknown zone and an agent', () => {
+ const f = fixture()
+ expect(() => f.run({ type: 'member.timeZone', timeZone: 'Mars/Base' })).toThrow(expect.objectContaining({ code: 'TIME_ZONE' }))
+ expect(() => f.run({ type: 'member.timeZone', timeZone: 'Asia/Ho_Chi_Minh' }, { kind: 'agent', agentId: 'a1', machineOwnerId: 'owner' }))
+ .toThrow()
+ expect(f.member('owner')!.timeZone).toBeUndefined()
+ })
+
+ it('a viewer may set their own', () => {
+ const f = fixture()
+ f.invite('viewer')
+ f.run({ type: 'member.timeZone', timeZone: 'Europe/Berlin' }, peer)
+ expect(f.member('peer')!.timeZone).toBe('Europe/Berlin')
+ })
+})
+
describe('avatars', () => {
const upload = { id: 'u1', key: 'avatars/tab/0123abcd/avatar' }
const config = { engine: 'claude', model: 'opus', effort: 'high', contextWindow: null, engineVersion: null }
diff --git a/backend/src/superTabs/profile.ts b/backend/src/superTabs/profile.ts
index 9901cad39..fb7d61a4a 100644
--- a/backend/src/superTabs/profile.ts
+++ b/backend/src/superTabs/profile.ts
@@ -1,5 +1,6 @@
import { z } from 'zod'
import { agent, fail, person, type Actor, type SuperTabState } from './model.js'
+import { knownTimeZone } from './digest.js'
import { agentProjectId, projectAgent } from './projects.js'
/** The emoji a status may wear. Desktop offers each with its words (focus, coffee, lunch, out, away, sick). */
@@ -27,6 +28,15 @@ export function setStatus(state: SuperTabState, actor: Actor, status: z.infer<ty
member.status = { text: status.text, emoji: status.emoji ?? null, until }
}
+/** `member.timeZone`: a person's own app tells the Swarm their time zone, or that it knows none. A viewer may too. */
+export function setTimeZone(state: SuperTabState, actor: Actor, timeZone: string | null): void {
+ if (actor.kind !== 'person') fail('HUMAN_REQUIRED', 'Only a person has a time zone.', 403)
+ const member = person(state, actor.userId)
+ if (timeZone === null) return void delete member.timeZone
+ if (!knownTimeZone(timeZone)) fail('TIME_ZONE', 'Name a time zone such as Asia/Ho_Chi_Minh.', 400)
+ member.timeZone = timeZone
+}
+
/** 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
diff --git a/backend/src/superTabs/projects.ts b/backend/src/superTabs/projects.ts
index 9823f12fb..91ff838ea 100644
--- a/backend/src/superTabs/projects.ts
+++ b/backend/src/superTabs/projects.ts
@@ -57,6 +57,11 @@ export interface SwarmProject {
roles?: ProjectRole[]
/** Its Product Manager started by the Swarm on one of its machines, or waiting for one (leadStart.ts). */
lead?: import('./leadStart.js').LeadPlacement
+ /** A Personal Swarm project chat with no Lead: its person's messages sent there, delivered to its Lead once it joins
+ * (leadStart.ts leadWaits). Ids and times only, at most MAX_LEAD_WAITING; cleared when a Lead joins. */
+ leadWaiting?: Array<{ id: string; at: number }>
+ /** The one start of its Lead a Desktop of its person's claimed (lead.claim), from [machineId]; cleared when a Lead joins. */
+ leadClaim?: { id: string; machineId: string; at: number }
/** What its chat was last told of new Reviewers (reviewCapacity.ts), under `any`: none can start, or they soon will not.
* Absent once a machine is usable again, so the next shortage is told. Per engine before 2026-10-30, never read since. */
reviewCapacity?: Partial<Record<'any' | 'claude' | 'codex', 'out' | 'low'>>
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index 7c309a21c..5cca2795c 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -2587,8 +2587,8 @@ export class SuperTabStore {
const author = row?.author as unknown as Author | undefined
const target = agent(state, l.agentId)
// A session hears its thread's rows; the one Buddy's session in an older project chat (commands.ts startOldChatBuddy)
- // hears that chat's main rows, never a thread session's.
- const heard = target.buddySession ? !!row?.buddySession : !!target.buddyNarrow && !row?.buddySession
+ // hears that chat's main rows, never a thread session's; so does a project's Lead that joined a chat with none (leadArrived).
+ const heard = target.buddySession ? !!row?.buddySession : (!!target.buddyNarrow || !!l.lead) && !row?.buddySession
if (!row || row.tabId !== tabId || row.conversationId !== l.conversationId || !heard || author?.kind !== 'person' || author.id !== l.author.id
|| author.membershipGeneration !== l.author.generation) continue
if (await tx.superTabDelivery.findUnique({ where: { id: stableId(l.messageId, l.agentId) }, select: { id: true } })) continue
diff --git a/backend/vitest.super-tabs.config.ts b/backend/vitest.super-tabs.config.ts
index 5d9c2faab..ef17be8e6 100644
--- a/backend/vitest.super-tabs.config.ts
+++ b/backend/vitest.super-tabs.config.ts
@@ -5,7 +5,7 @@ export default defineConfig({ test: { include: ['integration/superTabs.test.ts',
'integration/superTabTidy.test.ts', 'integration/superTabProfile.test.ts', 'integration/superTabLegacyDrop.test.ts', 'integration/shareRaces.test.ts', 'integration/superTabIndexes.test.ts', 'integration/superTabRouteDecisions.test.ts',
'integration/superTabHotReads.test.ts', 'integration/swarmSweepStarts.test.ts', 'integration/superTabGroupPlans.test.ts', 'integration/superTabInvitationPlans.test.ts', 'integration/superTabCache.test.ts', 'integration/superTabCacheDelta.test.ts', 'integration/superTabHostGroups.test.ts', 'integration/superTabMachineReports.test.ts', 'integration/superTabHeldParts.test.ts',
'integration/superTabObserver.test.ts', 'integration/productUsageConflicts.test.ts', 'integration/productUsageReceipts.test.ts', 'integration/schemaRelease.test.ts', 'integration/superTabBuddies.test.ts', 'integration/superTabNotAvailable.test.ts',
- 'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
+ 'integration/superTabBuddyProbes.test.ts', 'integration/superTabBuddySessions.test.ts', 'integration/superTabSwarmBuddy.test.ts', 'integration/superTabPersonalLead.test.ts', 'integration/superTabCosts.test.ts', 'integration/harnessSharesList.test.ts', 'integration/harnessSharesIndexPlan.test.ts', 'integration/atlasSnapshot.test.ts', 'integration/queryStats.test.ts',
'integration/superTabEvidence.test.ts', 'integration/superTabAttemptModels.test.ts', 'integration/superTabNamedReads.test.ts', 'integration/swarmSweepPlans.test.ts', 'integration/workerIndexPlans.test.ts', 'integration/superTabReflection.test.ts',
'integration/superTabMessagePages.test.ts', 'integration/superTabDeliveryCompaction.test.ts', 'integration/superTabNoticeDigest.test.ts', 'integration/superTabDigestHour.test.ts', 'integration/superTabCommandLoads.test.ts', 'integration/superTabThreads.test.ts', 'integration/superTabMachineRemovals.test.ts',
'integration/superTabInstructions.test.ts', 'integration/superTabWorkflow.test.ts', 'integration/superTabTaskLines.test.ts', 'integration/superTabDeletion.test.ts', 'integration/communityReports.test.ts', 'integration/superTabMachineNames.test.ts', 'integration/superTabTagsClear.test.ts', 'integration/swarmAgentTombstones.test.ts', 'integration/superTabPullRequestEvents.test.ts', 'integration/superTabProposals.test.ts'], hookTimeout: 120000, testTimeout: 30000, setupFiles: ['integration/noDefaultDigest.test-support.ts', 'integration/cacheOn.test-support.ts', 'src/lib/noRedis.test-support.ts'],
diff --git a/cli/src/gateway/accountHttp.spec.ts b/cli/src/gateway/accountHttp.spec.ts
index 1b26d8699..88d205a6d 100644
--- a/cli/src/gateway/accountHttp.spec.ts
+++ b/cli/src/gateway/accountHttp.spec.ts
@@ -157,6 +157,33 @@ describe('account HTTP in the gateway', () => {
expect((await restarted.machines()).status).toBe(503)
})
+ // Task #2598: the relay answers a machine this list shows offline without a dial (lib/remoteRelay.ts).
+ it('tells which machines the backend\'s list shows offline, and nothing on a sign-out', async () => {
+ const offline = vi.fn()
+ const { deps, request } = setup()
+ const api = createAccountHttp({ ...deps, offline })
+ request.mockResolvedValueOnce(response({ success: true, data: { machines: [
+ { machineId: 'off', computerId: 'a', status: 'stopped' }, { machineId: 'gone', computerId: 'b', status: 'offline' },
+ { machineId: 'on', computerId: 'c', status: 'running' }, { machineId: 'new', computerId: 'd', status: 'provisioning' },
+ ] } }))
+ await api.machines()
+ expect(offline).toHaveBeenLastCalledWith(['off', 'gone'])
+ request.mockResolvedValueOnce(response({}, 401))
+ await api.machines()
+ expect(offline).toHaveBeenLastCalledWith(null)
+ })
+
+ it('asks the list again only when it is older than asked, sharing a read in flight', async () => {
+ const { api, request } = setup()
+ await api.machines()
+ expect(request).toHaveBeenCalledTimes(1)
+ await api.recheck(60_000)
+ expect(request).toHaveBeenCalledTimes(1)
+ await new Promise(resolve => setTimeout(resolve, 5))
+ await Promise.all([api.recheck(1), api.recheck(1)])
+ expect(request).toHaveBeenCalledTimes(2)
+ })
+
it('does not serve stale rows across accounts or after a real refusal', async () => {
const { api, request, account } = setup()
await api.machines(true)
diff --git a/cli/src/gateway/accountHttp.ts b/cli/src/gateway/accountHttp.ts
index 2f2684ab7..737880b04 100644
--- a/cli/src/gateway/accountHttp.ts
+++ b/cli/src/gateway/accountHttp.ts
@@ -18,6 +18,9 @@ interface AccountHttpDeps {
/** Every machine list the backend answered (its body), and null on a sign-out: the trust group reads which of the
* account's machines are team machines from it (lib/e2ee/machineKinds.ts). */
listed?(body: Record<string, unknown> | null): void
+ /** The machines the backend's list shows offline, and null when the list is not the backend's: the relay answers
+ * their selects without a dial (lib/remoteRelay.ts). */
+ offline?(machineIds: string[] | null): void
log?(line: string): void
}
@@ -95,6 +98,7 @@ export function createAccountHttp(deps: AccountHttpDeps) {
const { machines, source } = cache.list()
deps.reachable?.(source !== 'backend' ? null : machines.filter(m => m.state !== 'offline').map(m => m.machineId))
deps.listed?.(source === 'backend' ? body : null)
+ deps.offline?.(source !== 'backend' ? null : machines.filter(m => m.state === 'offline').map(m => m.machineId))
deps.changed?.({ owner: deps.account().machineId, body, fetchedAt: cache.lastResponse()?.fetchedAt ?? Date.now() })
})
const restored = cache.lastResponse()
@@ -125,5 +129,12 @@ export function createAccountHttp(deps: AccountHttpDeps) {
return (res.body.data as { gridName?: string } | undefined)?.gridName ?? null
}
- return { backend, machines, mintGridName }
+ /** Read the list again unless it was read within `maxAgeMs`; a read in flight is shared. The relay asks this for
+ * the selects it holds on the list's word (lib/remoteRelay.ts). */
+ async function recheck(maxAgeMs: number): Promise<void> {
+ if (!deps.account().machineId) return
+ await cache.refresh({ maxAgeMs })
+ }
+
+ return { backend, machines, mintGridName, recheck }
}
diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.ts
index 6767868c7..cc6ae2bd8 100644
--- a/cli/src/gateway/start.ts
+++ b/cli/src/gateway/start.ts
@@ -146,6 +146,8 @@ export function startGateway(host: GatewayHost): StartedGateway {
computer: { id: host.computerId, name: host.machineName, hostname: host.hostname }, environment: host.autonomousEnv,
changed: host.machines,
reachable: (ids) => { reachable = ids ? new Set(ids) : null },
+ // Called on a list read, never while this is built: the pool below exists by then.
+ offline: (ids) => { relayPool.listed(ids) },
listed: (body) => {
if (!body) { machineKinds.clear(); return }
machineKinds.adopt(body)
@@ -200,6 +202,7 @@ export function startGateway(host: GatewayHost): StartedGateway {
relayPeers,
{
onSessionReady: (machineId) => groupSyncer?.sessionOpened(machineId),
+ recheckList: (maxAgeMs) => accountHttp.recheck(maxAgeMs),
// A machine the account's device key log names under this very key will trust us as soon as it
// reads the log: keep its pin through a few denials, and nudge it (and us) to read.
expectsTrust: (machineId, pub) => {
diff --git a/cli/src/lib/remoteRelay.ts b/cli/src/lib/remoteRelay.ts
index 4a16ecb7a..3a3c3e611 100644
--- a/cli/src/lib/remoteRelay.ts
+++ b/cli/src/lib/remoteRelay.ts
@@ -59,8 +59,28 @@ const ISOLATED_DIAL_COOLDOWN_MS = 30_000
// median 0.4 s, open, sign in, select, refused, closed, because the window's pool dialled again on every
// select its local clients made: the app's retry, a TUI, a CLI command.
const REFUSED_BACKOFF_MAX_MS = 30_000
+// A machine refused as offline, which no list says is offline (LISTED_RECHECK_MS), is asked again after 30 s, then 1, 2,
+// 4 minutes, and at most every 5: a machine that is off is usually off for long, and every ask is a socket and a sign-in.
+// A list that shows it online lifts this at once.
+const OFFLINE_BACKOFF_FIRST_MS = 30_000
+const OFFLINE_BACKOFF_MAX_MS = 5 * 60_000
// A retry-after longer than this is read as this: a wrong answer must not shut a machine out for long.
const RETRY_AFTER_MAX_MS = 5 * 60_000
+// A machine the account's machine list shows offline is not dialled at all: its selects are answered MACHINE_OFFLINE
+// from the list until a list shows it online. Prod, 2026-11-04: about 3,600 web-ws opens an hour from 76 users, mostly
+// CLI 0.5.33, each signed in, refused MACHINE_OFFLINE and closed in ~120 ms. The backoff above is per machine and capped
+// at 30 s, so a person with many offline machines kept the loop going, and every open cost the backend a session
+// sign-in. While selects are held the list is asked again at most this often: one read for every machine, served from
+// the cache when anything else read it since.
+const LISTED_RECHECK_MS = 5 * 60_000
+// An explicit redial (a person pressing Retry) of a held machine asks the list again at once, served from the cache when
+// it is younger than this, and dials if the list now shows the machine back. No online event reaches the CLI (review of
+// #2891: the backend pushes a list change only on create, rename, delete or share), so without it a machine back for a
+// minute stayed unreachable until the 5-minute recheck. One list read for every machine, never a socket per machine.
+const REDIAL_RECHECK_MS = 30_000
+// A list read longer ago than this holds nothing: the backoff decides again, so a list nothing can re-read (the
+// backend unreachable over REST) cannot shut a machine out.
+const LISTED_TRUST_MS = 15 * 60_000
// Warm background sessions kept per machine. Each concurrent background client needs its own (they
// must not see each other's frames), so the cap is "how many pollers may overlap on one machine and
// still find a warm session"; beyond it the extra session is closed on detach, as `shelf full`, so the backend's
@@ -275,11 +295,20 @@ export interface RemoteRelayPoolOptions {
refusals?: Map<string, Refusal>
/** The clock the backoff reads; a test's own. */
now?: () => number
+ /** Shared record of the machines the account's machine list last showed offline (LISTED_RECHECK_MS). */
+ listedOffline?: ListedOffline
+ /** Ask the machine list again unless it was read within `maxAgeMs`: a held select may be of a machine back since. It
+ * settles once the list read (and `listed()` was told), or failed. */
+ recheckList?: (maxAgeMs: number) => Promise<void>
}
+/** The machines the account's machine list last showed offline, when it was read, and when a held select last asked
+ * for it again. `at` 0: no list the backend answered, which holds nothing. */
+export interface ListedOffline { ids: Set<string>; at: number; asked: number }
+
/** A machine whose last dials failed `count` times in a row: selects of it before `until` get `error` back.
- * `asked`: the backend set `until` (its retry-after), which even an explicit redial waits out. */
-interface Refusal { until: number; error: unknown; count: number; asked: boolean }
+ * `askedUntil`: the end of the backend's own retry-after, which even an explicit redial waits out. */
+interface Refusal { until: number; error: unknown; count: number; askedUntil: number }
const DENIED_TRIES = 3
const DENIED_WINDOW_MS = 60_000
@@ -299,6 +328,8 @@ export class RemoteRelayPool {
private readonly denials: Map<string, number[]>
private readonly refusals: Map<string, Refusal>
private readonly now: () => number
+ private readonly listedOffline: ListedOffline
+ private readonly recheckList: ((maxAgeMs: number) => Promise<void>) | null
/** Warm background pools per machine, each holding one lingering session nobody is attached to —
* see acquireIsolated(). A pool is either here (idle) or in a client's hands, never both. */
private readonly idleIsolated = new Map<string, RemoteRelayPool[]>()
@@ -323,6 +354,33 @@ export class RemoteRelayPool {
this.denials = opts.denials ?? new Map()
this.refusals = opts.refusals ?? new Map()
this.now = opts.now ?? Date.now
+ this.listedOffline = opts.listedOffline ?? { ids: new Set(), at: 0, asked: 0 }
+ this.recheckList = opts.recheckList ?? null
+ }
+
+ /** The account's machine list was read: these of its machines are offline. null: the list is not the backend's
+ * (a sign-out, or no read yet), which holds nothing. A machine it no longer shows offline is dialled at its next
+ * select, whatever backoff its last refusal left: the list is what says it came back. */
+ listed(offline: string[] | null): void {
+ const next = new Set(offline ?? [])
+ for (const machineId of this.listedOffline.ids) {
+ if (next.has(machineId)) continue
+ this.refusals.delete(machineId)
+ this.lastDialFailure.delete(machineId)
+ }
+ this.listedOffline.ids = next
+ this.listedOffline.at = offline ? this.now() : 0
+ }
+
+ /** Whether the machine list says `machineId` is offline, recently enough to answer its select without a dial. */
+ private heldByList(machineId: string): boolean {
+ const listed = this.listedOffline
+ if (!listed.at || !listed.ids.has(machineId) || this.now() - listed.at >= LISTED_TRUST_MS) return false
+ if (this.now() - listed.asked >= LISTED_RECHECK_MS) {
+ listed.asked = this.now()
+ void this.recheckList?.(LISTED_RECHECK_MS).catch(() => { /* the next held select asks again */ })
+ }
+ return true
}
/** `machineId` denied this machine's key. Drop the pin — unless the device key log says it should
@@ -357,7 +415,8 @@ export class RemoteRelayPool {
const shelf = this.idleIsolated.get(machineId) ?? []
const pool = shelf.pop() ?? new RemoteRelayPool(this.auth, this.backendWsBase, this.selfIdentity, this.peers,
{ p2p: false, lingerMs: ISOLATED_LINGER_MS, dialCooldownMs: ISOLATED_DIAL_COOLDOWN_MS, dialFailures: this.lastDialFailure,
- ...(this.expectsTrust ? { expectsTrust: this.expectsTrust } : {}), denials: this.denials, refusals: this.refusals, now: this.now })
+ ...(this.expectsTrust ? { expectsTrust: this.expectsTrust } : {}), denials: this.denials, refusals: this.refusals, now: this.now,
+ listedOffline: this.listedOffline, ...(this.recheckList ? { recheckList: this.recheckList } : {}) })
const session = await pool.acquire(machineId, autonomousEnv, selectFrame, {
...sink,
sendFrame: frame => sink.sendFrame(frame.type === 'connected'
@@ -458,8 +517,16 @@ export class RemoteRelayPool {
// An explicit redial (`forceReconnect`: the app saw its session die, or a person asked again) is not made to
// wait out the backoff, only what the backend itself asked for.
const redial = (selectFrame.payload as { forceReconnect?: unknown } | undefined)?.forceReconnect === true
+ // Not even an explicit redial: the backend, whose list this is, would refuse it. A redial asks the list first.
+ if (this.heldByList(machineId)) {
+ if (!redial || !this.recheckList) return Promise.reject(new RelayConnectError('MACHINE_OFFLINE', 1013))
+ return this.recheckList(REDIAL_RECHECK_MS).catch(() => { /* answered from the list it has */ }).then(() => {
+ if (this.heldByList(machineId)) throw new RelayConnectError('MACHINE_OFFLINE', 1013)
+ return this.connect(machineId, autonomousEnv, selectFrame)
+ })
+ }
const refused = this.refusals.get(machineId)
- if (refused && this.now() < refused.until && (refused.asked || !redial)) return Promise.reject(refused.error)
+ if (refused && this.now() < (redial ? refused.askedUntil : refused.until)) return Promise.reject(refused.error)
const failed = this.lastDialFailure.get(machineId)
if (failed && this.dialCooldownMs > 0 && Date.now() - failed.at < this.dialCooldownMs) {
return Promise.reject(failed.error)
@@ -508,10 +575,13 @@ export class RemoteRelayPool {
}
}
const count = (this.refusals.get(machineId)?.count ?? 0) + 1
- const backoff = Math.min(REFUSED_BACKOFF_MAX_MS, 1_000 * 2 ** (count - 1))
+ const offline = error instanceof RelayConnectError && error.message === 'MACHINE_OFFLINE'
+ const backoff = offline
+ ? Math.min(OFFLINE_BACKOFF_MAX_MS, OFFLINE_BACKOFF_FIRST_MS * 2 ** (count - 1))
+ : Math.min(REFUSED_BACKOFF_MAX_MS, 1_000 * 2 ** (count - 1))
const asked = error instanceof RelayConnectError && typeof error.retryAfterMs === 'number' && Number.isFinite(error.retryAfterMs)
? Math.min(Math.max(error.retryAfterMs, 0), RETRY_AFTER_MAX_MS) : 0
- this.refusals.set(machineId, { until: this.now() + Math.max(backoff, asked), error, count, asked: asked > backoff })
+ this.refusals.set(machineId, { until: this.now() + Math.max(backoff, asked), error, count, askedUntil: this.now() + asked })
}
private async dial(machineId: string, autonomousEnv: string, selectFrame: Frame, forceRefresh: boolean): Promise<Entry> {
diff --git a/cli/src/lib/remoteRelayListed.spec.ts b/cli/src/lib/remoteRelayListed.spec.ts
new file mode 100644
index 000000000..091700772
--- /dev/null
+++ b/cli/src/lib/remoteRelayListed.spec.ts
@@ -0,0 +1,154 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { WebSocketServer } from 'ws'
+import type { AddressInfo } from 'node:net'
+import { RemoteRelayPool } from './remoteRelay.js'
+import { MachinePeerStore } from './e2ee/machinePeers.js'
+import { b64e, newIdentity } from './e2ee/core.js'
+import type { LocalClientSink } from '../backendSocket.js'
+
+/**
+ * A machine the account's machine list already shows offline is not dialled. Prod, 2026-11-04: about 3,600 web-ws
+ * opens an hour from 76 users, mostly CLI 0.5.33, each signed in, refused MACHINE_OFFLINE and closed in ~120 ms. The
+ * 2026-10-28 backoff is per machine and capped at 30 s, so a person with many offline machines kept the loop going,
+ * and every open cost the backend a session sign-in.
+ */
+const machineId = 'abcdabcdabcdabcdabcdabcdabcdabcd'
+const other = 'efefefefefefefefefefefefefefefef'
+const sink: LocalClientSink = { sendFrame: () => true, sendBinary: () => true }
+const select = (id: string, extra: Record<string, unknown> = {}) => ({ type: 'machine_select', payload: { machineId: id, ...extra } })
+const offline = { message: 'MACHINE_OFFLINE', closeCode: 1013 }
+const cleanups: Array<() => Promise<void>> = []
+afterEach(async () => { for (const cleanup of cleanups.splice(0)) await cleanup() })
+
+/** A backend that refuses every select as webWs.ts refuses a relay's select of an offline machine. */
+async function offlineBackend(onRecheck?: (maxAgeMs: number) => void) {
+ const dials: string[] = []
+ const wss = new WebSocketServer({ port: 0, host: '127.0.0.1' })
+ await new Promise<void>(resolve => wss.once('listening', resolve))
+ wss.on('connection', ws => {
+ ws.send(JSON.stringify({ type: 'connected', payload: { userId: 'user-1' } }))
+ ws.on('message', raw => {
+ const frame = JSON.parse(raw.toString()) as { type: string; payload: { machineId: string } }
+ if (frame.type !== 'machine_select') return
+ dials.push(frame.payload.machineId)
+ ws.send(JSON.stringify({ type: 'machine_select_error', payload: { machineId: frame.payload.machineId, error: 'MACHINE_OFFLINE', retryAfterMs: 30_000 } }))
+ })
+ })
+ let now = 1_000_000
+ let rechecks = 0
+ const asked: number[] = []
+ const peers = new MachinePeerStore()
+ peers.pin(machineId, b64e(newIdentity().pub), 'test remote')
+ peers.pin(other, b64e(newIdentity().pub), 'test remote 2')
+ const pool = new RemoteRelayPool(
+ { accessToken: async () => 'fixture-token' } as never,
+ `ws://127.0.0.1:${(wss.address() as AddressInfo).port}`,
+ newIdentity(), peers, { p2p: false, now: () => now, recheckList: async (maxAgeMs) => { rechecks++; asked.push(maxAgeMs); onRecheck?.(maxAgeMs) } },
+ )
+ cleanups.push(async () => {
+ peers.unlink(machineId); peers.unlink(other)
+ pool.close()
+ for (const ws of wss.clients) ws.terminate()
+ await new Promise<void>(resolve => wss.close(() => resolve()))
+ })
+ return {
+ pool,
+ dials: (id = machineId) => dials.filter(d => d === id).length,
+ rechecks: () => rechecks,
+ asked: () => asked,
+ advance(ms: number) { now += ms },
+ window: (id = machineId) => pool.acquire(id, 'prod', select(id), sink, () => {}),
+ redial: () => pool.acquire(machineId, 'prod', select(machineId, { forceReconnect: true }), sink, () => {}),
+ background: () => pool.acquireIsolated(machineId, 'prod', select(machineId), sink, () => {}),
+ }
+}
+
+describe('a machine the machine list shows offline', () => {
+ it('is not dialled by the window, a background client or an explicit redial', async () => {
+ const b = await offlineBackend()
+ b.pool.listed([machineId])
+ for (let minute = 0; minute < 10; minute++) {
+ await expect(b.window()).rejects.toMatchObject(offline)
+ await expect(b.background()).rejects.toMatchObject(offline)
+ await expect(b.redial()).rejects.toMatchObject(offline)
+ b.advance(60_000)
+ }
+ expect(b.dials()).toBe(0)
+ })
+
+ it('is dialled again as soon as the list shows it online', async () => {
+ const b = await offlineBackend()
+ b.pool.listed([machineId])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(0)
+ b.pool.listed([])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(1)
+ })
+
+ it('coming online lifts the backoff of an earlier refusal, so the next select dials at once', async () => {
+ const b = await offlineBackend()
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(1)
+ b.pool.listed([machineId])
+ b.advance(5_000)
+ b.pool.listed([])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ await expect(b.background()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(2)
+ })
+
+ it('asks the list again at most every 5 minutes while selects are held', async () => {
+ const b = await offlineBackend()
+ b.pool.listed([machineId])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ await expect(b.background()).rejects.toMatchObject(offline)
+ expect(b.rechecks()).toBe(1)
+ b.advance(5 * 60_000 - 1)
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.rechecks()).toBe(1)
+ b.advance(1)
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.rechecks()).toBe(2)
+ })
+
+ // Review of #2891: no online event reaches the CLI (the backend pushes a list change only on create, rename, delete or
+ // share), so a person pressing Retry on a machine back for a minute would have waited for the 5-minute recheck.
+ it('asks the list again on an explicit redial, at most 30 s old, and dials if it shows the machine back', async () => {
+ let back = false
+ let pool: RemoteRelayPool | null = null
+ const b = await offlineBackend(() => { if (back) pool?.listed([]) })
+ pool = b.pool
+ b.pool.listed([machineId])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ await expect(b.redial()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(0)
+ expect(b.asked()).toEqual([5 * 60_000, 30_000])
+
+ back = true
+ b.advance(60_000)
+ await expect(b.redial()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(1)
+ expect(b.asked()).toEqual([5 * 60_000, 30_000, 30_000])
+ })
+
+ it('holds nothing on a list that is not the backend\'s, or one read more than 15 minutes ago', async () => {
+ const b = await offlineBackend()
+ b.pool.listed([machineId])
+ b.pool.listed(null)
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(1)
+
+ b.pool.listed([other])
+ b.advance(15 * 60_000)
+ await expect(b.window(other)).rejects.toMatchObject(offline)
+ expect(b.dials(other)).toBe(1)
+ })
+
+ it('does not hold a machine the list does not show offline', async () => {
+ const b = await offlineBackend()
+ b.pool.listed([other])
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expect(b.dials()).toBe(1)
+ })
+})
diff --git a/cli/src/lib/remoteRelayRefusal.spec.ts b/cli/src/lib/remoteRelayRefusal.spec.ts
index f0c935dd6..338f89b38 100644
--- a/cli/src/lib/remoteRelayRefusal.spec.ts
+++ b/cli/src/lib/remoteRelayRefusal.spec.ts
@@ -87,6 +87,23 @@ describe('a machine the backend refuses', () => {
expect(b.dials()).toBe(1)
})
+ // Prod, 2026-11-04: ~3,600 refused opens an hour, mostly CLI 0.5.33, whose offline machines were asked every 30 s.
+ it('refused as offline is asked again after 30 s, then 1, 2, 4 minutes, at most every 5', async () => {
+ const b = await refusingBackend({ error: 'MACHINE_OFFLINE', retryAfterMs: 30_000 })
+ const offline = { message: 'MACHINE_OFFLINE' }
+ const expected: number[] = []
+ for (const wait of [30, 60, 120, 240, 300, 300]) {
+ await expect(b.window()).rejects.toMatchObject(offline)
+ expected.push(b.dials())
+ b.advance(wait * 1_000 - 1)
+ await expect(b.window()).rejects.toMatchObject(offline)
+ await expect(b.background()).rejects.toMatchObject(offline)
+ expect(b.dials(), `${wait} s`).toBe(expected.length)
+ b.advance(1)
+ }
+ expect(expected).toEqual([1, 2, 3, 4, 5, 6])
+ })
+
it('without a retry-after is asked again after 1, 2, 4 … seconds, at most every 30', async () => {
const b = await refusingBackend({ error: 'NOT_YOUR_MACHINE' })
const refused = { message: 'NOT_YOUR_MACHINE' }
diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.md
index 5f5ac802f..8d7834ef4 100644
--- a/desktop/design/desktop-design-system.md
+++ b/desktop/design/desktop-design-system.md
@@ -179,6 +179,10 @@ Avoid repeatedly drawing cards inside a dialog.
The terminal's chosen color palette remains independent from UI focus blue.
All modal veils share one 95% token: black in dark appearance, white in light.
+The chat's picture viewer is the one exception: `AppDesktop.mediaVeil`, a
+see-through black in both appearances, with its own white ink and control fills
+(`mediaInk`, `mediaInkMuted`, `mediaControl`, `mediaControlHover`), because a
+picture reads best on dark.
Cmd-N and Cmd-P must have exactly the same backdrop darkness, including coverage
of the native footer. Popovers have no independent full-window veil.
diff --git a/desktop/lib/shared/theme/app_theme.dart b/desktop/lib/shared/theme/app_theme.dart
index eb34a26e6..974087ae5 100644
--- a/desktop/lib/shared/theme/app_theme.dart
+++ b/desktop/lib/shared/theme/app_theme.dart
@@ -1514,6 +1514,16 @@ abstract final class AppDesktop {
static const lightVeil = Color(0xF2FFFFFF);
static Color veil(Brightness brightness) =>
brightness == Brightness.dark ? darkVeil : lightVeil;
+
+ /// The chat's picture viewer: a see-through dark veil in both appearances,
+ /// as a picture reads best on dark (River, 11-04), and the ink and control
+ /// fills drawn on it. The one exception to [veil]
+ /// (desktop-design-system.md).
+ static const mediaVeil = Color(0xF2000000);
+ static const mediaInk = Color(0xFFFFFFFF);
+ static const mediaInkMuted = Color(0xB3FFFFFF);
+ static const mediaControl = Color(0x26FFFFFF);
+ static const mediaControlHover = Color(0x40FFFFFF);
}
/// Desktop feedback is visible on the next frame. Keep these shared names so
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index bf84669f2..92fffd4e6 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -13961,7 +13961,9 @@ class AppNotifier extends ChangeNotifier {
}
var changed = false;
for (final tab in swarms) {
+ // A Swarm's tab keeps the Swarm's name (task #2647).
if (!tab.nameIsCustom &&
+ !tab.isSuperTab &&
tab.titleMachineId == machine.machine.machineId &&
tab.titleAgentId == agent.id) {
final title = Swarm.titleFor(agent);
@@ -20110,6 +20112,7 @@ class AppNotifier extends ChangeNotifier {
}
if (firstAgent &&
!target.nameIsCustom &&
+ !target.isSuperTab &&
!target.isCompanions &&
!target.isDevices) {
final agent = machine.agents
@@ -20808,7 +20811,10 @@ class AppNotifier extends ChangeNotifier {
target.panes.add(pane);
// A tab that had no harness in it takes this one's name, the way it
// would for a harness opened into it.
- if (firstAgent && !target.nameIsCustom && pane.agentId != null) {
+ if (firstAgent &&
+ !target.nameIsCustom &&
+ !target.isSuperTab &&
+ pane.agentId != null) {
final agent = machineStates[pane.machineId]?.agents
.where((agent) => agent.id == pane.agentId)
.firstOrNull;
diff --git a/desktop/lib/state/workspace_status.dart b/desktop/lib/state/workspace_status.dart
index 8737164e2..fe496b6bc 100644
--- a/desktop/lib/state/workspace_status.dart
+++ b/desktop/lib/state/workspace_status.dart
@@ -94,8 +94,11 @@ String? _autoName(AppNotifier app, Swarm tab) {
/// With Auto rename on, a name from the tab's machine replaces the vote.
Map<String, String> workspaceTabNames(AppNotifier app) {
final candidates = <String, List<_TabName>>{};
+ // A tab showing a Swarm is called what the Swarm is called, whatever its
+ // panes run: never their folder, project or type (task #2647).
+ bool namedBySwarm(Swarm tab) => tab.isSuperTab && tab.superTabId != null;
for (final tab in app.swarms) {
- if (tab.nameIsCustom) {
+ if (tab.nameIsCustom || namedBySwarm(tab)) {
candidates[tab.id] = [];
continue;
}
@@ -150,7 +153,7 @@ Map<String, String> workspaceTabNames(AppNotifier app) {
final autoNames = {for (final tab in app.swarms) tab.id: _autoName(app, tab)};
return {
for (final tab in app.swarms)
- tab.id: tab.nameIsCustom
+ tab.id: tab.nameIsCustom || namedBySwarm(tab)
? tab.name
: tab.isStore
? 'store'
@@ -255,10 +258,7 @@ class WorkspacePaneContext {
pane.sharedHarness != null || machine?.machine.isShared == true;
// Another account's name: plain, one line (the bar ellipsizes it).
final ownerName = shared
- ? [
- pane.sharedOwnerName,
- machine?.machine.ownerName,
- ]
+ ? [pane.sharedOwnerName, machine?.machine.ownerName]
.whereType<String>()
.map(plainSharedText)
.where((n) => n.isNotEmpty)
diff --git a/desktop/lib/super_tabs/attachment_chips.dart b/desktop/lib/super_tabs/attachment_chips.dart
index be1a38616..568011de7 100644
--- a/desktop/lib/super_tabs/attachment_chips.dart
+++ b/desktop/lib/super_tabs/attachment_chips.dart
@@ -47,16 +47,7 @@ class SuperTabAttachments extends StatelessWidget {
final pictures = <SuperTabAttachment>[];
final chips = <SuperTabAttachment>[];
for (final file in attachments) {
- // A browser's fetch follows a redirect off the attachments host, so
- // there a picture stays a chip that opens in a new tab. A picture over
- // the form's limit is a chip too: every reader would fetch and decode
- // it whole to draw it in place. So is one whose link this app refuses.
- final inPlace =
- file.isImage &&
- file.size <= kSuperTabFormAttachmentMaxBytes &&
- !kIsWeb &&
- !ref(file).refused;
- (inPlace ? pictures : chips).add(file);
+ (superTabShowsInPlace(ref(file)) ? pictures : chips).add(file);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
@@ -81,6 +72,17 @@ class SuperTabAttachments extends StatelessWidget {
}
}
+/// Whether a message draws [ref]'s picture in place, and the viewer pages
+/// through it. A browser's fetch follows a redirect off the attachments
+/// host, so there a picture stays a chip that opens in a new tab. A picture
+/// over the form's limit is a chip too: every reader would fetch and decode
+/// it whole to draw it in place. So is one whose link this app refuses.
+bool superTabShowsInPlace(SuperTabFileRef ref) =>
+ ref.file.isImage &&
+ ref.file.size <= kSuperTabFormAttachmentMaxBytes &&
+ !kIsWeb &&
+ !ref.refused;
+
class _AttachmentChip extends StatefulWidget {
const _AttachmentChip({super.key, required this.file});
diff --git a/desktop/lib/super_tabs/attachment_image.dart b/desktop/lib/super_tabs/attachment_image.dart
index e14465087..d204b6f80 100644
--- a/desktop/lib/super_tabs/attachment_image.dart
+++ b/desktop/lib/super_tabs/attachment_image.dart
@@ -1,12 +1,16 @@
+import 'dart:async';
+
import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
-import '../shared/widgets/app_dialog.dart';
+import '../shared/widgets/app_icon_button.dart';
import '../widgets/desktop_chrome.dart';
import 'attachment_upload.dart';
import 'attachment_viewer.dart';
import 'file_links.dart';
+import 'message_more_menu.dart';
import 'model.dart';
/// A picture in a message, as Slack shows one: at most [maxSide] each way
@@ -120,11 +124,7 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {
key: ValueKey('super-attachment-inline:${file.id}'),
borderRadius: radius,
mouseCursor: SystemMouseCursors.click,
- onTap: () => showAppDialog<void>(
- context: context,
- builder: (_) =>
- SuperTabImageViewer(file: file, url: url, ref: _ref),
- ),
+ onTap: () => superTabOpenImage(context, _ref),
child: ConstrainedBox(
constraints: const BoxConstraints(
maxWidth: SuperTabInlineImage.maxSide,
@@ -182,59 +182,543 @@ class _SuperTabInlineImageState extends State<SuperTabInlineImage> {
);
}
-/// A message's picture over the whole window, fetched when it opens, with
-/// Download, Open in browser and Close. [ref] gives those two a fresh link
-/// once [url] is about to end.
-class SuperTabImageViewer extends StatelessWidget {
- const SuperTabImageViewer({
+/// The pictures of one chat or thread, oldest first, for the viewer to page
+/// through: the chat view puts one above each list of rows.
+class SuperTabImageGallery extends InheritedWidget {
+ const SuperTabImageGallery({
+ super.key,
+ required this.images,
+ this.thread,
+ required super.child,
+ });
+
+ /// Read when a picture is opened, not on every build.
+ final List<SuperTabImageItem> Function() images;
+
+ /// The thread's root, for a thread's pictures.
+ final String? thread;
+
+ static SuperTabImageGallery? maybeOf(BuildContext context) =>
+ context.getInheritedWidgetOfExactType<SuperTabImageGallery>();
+
+ @override
+ bool updateShouldNotify(SuperTabImageGallery old) => false;
+}
+
+/// Where the viewer is drawn: the chat view shows it over the chat, beside
+/// an open thread.
+class SuperTabImageStage extends InheritedWidget {
+ const SuperTabImageStage({
super.key,
- required this.file,
- required this.url,
- this.ref,
+ required this.open,
+ required super.child,
});
- final SuperTabAttachment file;
- final Uri url;
- final SuperTabFileRef? ref;
+ final void Function(
+ List<SuperTabImageItem> images,
+ int index, {
+ String? thread,
+ })
+ open;
+
+ static SuperTabImageStage? maybeOf(BuildContext context) =>
+ context.getInheritedWidgetOfExactType<SuperTabImageStage>();
@override
- Widget build(BuildContext context) => Dialog.fullscreen(
- key: ValueKey('super-attachment-viewer:${file.id}'),
- backgroundColor: DesktopChrome.surface,
- child: Padding(
- padding: const EdgeInsets.all(grid.AppDesktop.panelPadding),
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- Text(
- file.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: DesktopChrome.control(medium: true),
+ bool updateShouldNotify(SuperTabImageStage old) => false;
+}
+
+/// Opens the picture [ref] among its gallery's, on the stage; with neither
+/// above [context], it alone over the whole window.
+void superTabOpenImage(BuildContext context, SuperTabFileRef ref) {
+ final gallery = SuperTabImageGallery.maybeOf(context);
+ final images = [...?gallery?.images()];
+ var index = images.indexWhere(
+ (image) =>
+ image.ref.messageId == ref.messageId && image.file.id == ref.file.id,
+ );
+ if (index < 0) {
+ images
+ ..clear()
+ ..add(SuperTabImageItem(ref: ref));
+ index = 0;
+ } else {
+ // The row's own ref may hold a fresher link than the gallery's.
+ images[index] = images[index].withRef(ref);
+ }
+ if (SuperTabImageStage.maybeOf(context) case final stage?) {
+ stage.open(images, index, thread: gallery?.thread);
+ return;
+ }
+ unawaited(
+ showGeneralDialog<void>(
+ context: context,
+ barrierColor: Colors.transparent,
+ pageBuilder: (context, _, _) => SuperTabImageViewer(
+ images: images,
+ index: index,
+ onClose: () => Navigator.pop(context),
+ ),
+ ),
+ );
+}
+
+/// One picture the viewer pages through: the file, and who posted it, when
+/// and where, as the chat names them.
+@immutable
+class SuperTabImageItem {
+ const SuperTabImageItem({
+ required this.ref,
+ this.sender,
+ this.avatar,
+ this.postedAt,
+ this.place,
+ this.onShowInChat,
+ });
+
+ final SuperTabFileRef ref;
+
+ /// The sender's name and face, as their row shows them.
+ final String? sender;
+ final Widget? avatar;
+ final DateTime? postedAt;
+
+ /// Where it was posted: "# openharness".
+ final String? place;
+
+ /// Goes to its message in the chat; More offers it.
+ final VoidCallback? onShowInChat;
+
+ SuperTabAttachment get file => ref.file;
+
+ SuperTabImageItem withRef(SuperTabFileRef ref) => SuperTabImageItem(
+ ref: ref,
+ sender: sender,
+ avatar: avatar,
+ postedAt: postedAt,
+ place: place,
+ onShowInChat: onShowInChat,
+ );
+}
+
+/// How long ago a picture was posted, in words: "just now", "5 minutes ago",
+/// "14 days ago".
+String superTabPostedAgo(Duration age) {
+ String ago(int count, String unit) =>
+ '$count $unit${count == 1 ? '' : 's'} ago';
+ if (age.inMinutes < 1) return 'just now';
+ if (age.inHours < 1) return ago(age.inMinutes, 'minute');
+ if (age.inDays < 1) return ago(age.inHours, 'hour');
+ return ago(age.inDays, 'day');
+}
+
+/// A chat's pictures as Slack shows them (Huy, 11-04): over a see-through
+/// dark veil, the sender, when and where at the top left, the picture in the
+/// middle with previous and next (and the Left and Right keys) through
+/// [images], rotate and zoom at the bottom left, Download, Open in browser
+/// and More at the bottom right. Esc, ×, or a click on the veil calls
+/// [onClose]. Each picture is drawn from its link at hand, else a fresh one.
+class SuperTabImageViewer extends StatefulWidget {
+ const SuperTabImageViewer({
+ super.key,
+ required this.images,
+ required this.index,
+ required this.onClose,
+ }) : assert(images.length > 0);
+
+ final List<SuperTabImageItem> images;
+ final int index;
+ final VoidCallback onClose;
+
+ static const zoomMin = 1.0, zoomMax = 4.0, zoomStep = .25;
+
+ @override
+ State<SuperTabImageViewer> createState() => _SuperTabImageViewerState();
+}
+
+class _SuperTabImageViewerState extends State<SuperTabImageViewer> {
+ late int _index = widget.index.clamp(0, widget.images.length - 1);
+ final _zoom = TransformationController();
+ final _focus = FocusScopeNode(debugLabel: 'Image viewer');
+ int _turns = 0;
+ Size _viewport = Size.zero;
+
+ /// The shown picture's link; null while one is asked for, or when none
+ /// came ([_failed]).
+ Uri? _url;
+ bool _failed = false;
+
+ SuperTabImageItem get _item => widget.images[_index];
+ double get _scale => _zoom.value.getMaxScaleOnAxis();
+
+ @override
+ void initState() {
+ super.initState();
+ _zoom.addListener(_zoomed);
+ _load();
+ // Its keys are its own, whatever had them: Esc closes it, not what is
+ // under it, and nothing typed reaches the composer. Closed, its scope
+ // gives them back to what had them.
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _focus.requestFocus();
+ });
+ }
+
+ @override
+ void dispose() {
+ _zoom
+ ..removeListener(_zoomed)
+ ..dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ void _zoomed() => setState(() {});
+
+ void _load() {
+ final ref = _item.ref;
+ _url = ref.current;
+ _failed = false;
+ if (_url != null) return;
+ WidgetsBinding.instance.addPostFrameCallback((_) async {
+ if (!mounted) return;
+ final url = await superTabOpenableLink(context, ref);
+ // Another picture is shown by now: this answer is not for it.
+ if (!mounted || !identical(ref, _item.ref)) return;
+ setState(() {
+ _url = url;
+ _failed = url == null;
+ });
+ });
+ }
+
+ /// Shows the picture at [to], unturned at 100%; past either end, nothing.
+ void _go(int to) {
+ if (to < 0 || to >= widget.images.length || to == _index) return;
+ setState(() {
+ _index = to;
+ _turns = 0;
+ _zoom.value = Matrix4.identity();
+ _load();
+ });
+ }
+
+ /// Zooms to [scale] about the middle of the picture's area.
+ void _setZoom(double scale) {
+ final s = scale.clamp(
+ SuperTabImageViewer.zoomMin,
+ SuperTabImageViewer.zoomMax,
+ );
+ final middle = _viewport.center(Offset.zero);
+ _zoom.value = Matrix4.diagonal3Values(s, s, 1)
+ ..setTranslationRaw(middle.dx * (1 - s), middle.dy * (1 - s), 0);
+ }
+
+ /// The next step of [SuperTabImageViewer.zoomStep] up or down from now.
+ void _step(int direction) {
+ const step = SuperTabImageViewer.zoomStep;
+ final at = _scale / step;
+ // A pinch may leave it between steps: the next whole step that way.
+ final steps = direction > 0
+ ? (at + 1e-6).floor() + 1
+ : (at - 1e-6).ceil() - 1;
+ _setZoom(steps * step);
+ }
+
+ KeyEventResult _key(FocusNode _, KeyEvent event) {
+ if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
+ return KeyEventResult.ignored;
+ }
+ final key = event.logicalKey;
+ if (key == LogicalKeyboardKey.escape) {
+ if (event is KeyDownEvent) widget.onClose();
+ } else if (key == LogicalKeyboardKey.arrowLeft) {
+ _go(_index - 1);
+ } else if (key == LogicalKeyboardKey.arrowRight) {
+ _go(_index + 1);
+ } else {
+ return KeyEventResult.ignored;
+ }
+ return KeyEventResult.handled;
+ }
+
+ Widget _button(
+ String name,
+ IconData icon,
+ String tooltip,
+ VoidCallback? onPressed, {
+ double size = AppIcons.inlineSize,
+ }) => AppIconButton(
+ key: ValueKey('super-image-$name'),
+ icon: icon,
+ tooltip: tooltip,
+ size: size,
+ color: grid.AppDesktop.mediaInkMuted,
+ hoverColor: grid.AppDesktop.mediaInk,
+ hoverFill: grid.AppDesktop.mediaControlHover,
+ onPressed: onPressed,
+ );
+
+ /// Previous or next, in a round well at the picture's side; nothing past
+ /// either end.
+ Widget _arrow(bool next) {
+ final to = _index + (next ? 1 : -1);
+ final shown = to >= 0 && to < widget.images.length;
+ return SizedBox(
+ width: _side,
+ child: !shown
+ ? null
+ : Center(
+ child: DecoratedBox(
+ decoration: const BoxDecoration(
+ color: grid.AppDesktop.mediaControl,
+ shape: BoxShape.circle,
+ ),
+ child: _button(
+ next ? 'next' : 'previous',
+ next ? AppIcons.chevronRight : AppIcons.chevronLeft,
+ next ? 'Next' : 'Previous',
+ () => _go(to),
+ size: grid.AppDesktop.iconSize + 4,
+ ),
+ ),
+ ),
+ );
+ }
+
+ /// A bar keeps every click on it: one on a control that can't act (minus
+ /// at 100%), a label or the space between them is no click on the veil.
+ Widget _bar(Widget bar) => GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: () {},
+ child: bar,
+ );
+
+ static const _side = 72.0;
+ static const _ink = grid.AppDesktop.mediaInk;
+
+ Widget _header() {
+ final item = _item;
+ final posted = item.postedAt;
+ final when = [
+ if (posted != null)
+ superTabPostedAgo(DateTime.now().difference(posted.toLocal())),
+ if (item.place case final place?) 'in $place',
+ ].join(' ');
+ return Row(
+ children: [
+ if (item.avatar case final avatar?) ...[
+ avatar,
+ const SizedBox(width: grid.AppDesktop.controlGap + 4),
+ ],
+ Expanded(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: MainAxisSize.min,
+ children: [
+ if (item.sender case final sender?)
+ Text(
+ sender,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.control(color: _ink, medium: true),
+ ),
+ Text(
+ [if (when.isNotEmpty) when, item.file.name].join(' · '),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(
+ color: grid.AppDesktop.mediaInkMuted,
+ ),
+ ),
+ ],
+ ),
+ ),
+ _button('close', AppIcons.close, 'Close', widget.onClose),
+ ],
+ );
+ }
+
+ Widget _picture() {
+ final file = _item.file;
+ final url = _url;
+ if (url == null) {
+ return _failed
+ ? Text(
+ 'This image can’t be shown here.',
+ style: DesktopChrome.metadata(
+ color: grid.AppDesktop.mediaInkMuted,
+ ),
+ )
+ : const CircularProgressIndicator(color: _ink);
+ }
+ return RotatedBox(
+ quarterTurns: _turns,
+ child: Image(
+ key: ValueKey('super-attachment-image:${file.id}'),
+ image: attachmentPicture(url),
+ fit: BoxFit.contain,
+ loadingBuilder: (_, child, progress) => progress == null
+ ? child
+ : const CircularProgressIndicator(color: _ink),
+ errorBuilder: (_, _, _) => Text(
+ 'This image can’t be shown here.',
+ style: DesktopChrome.metadata(color: grid.AppDesktop.mediaInkMuted),
+ ),
+ ),
+ );
+ }
+
+ Widget _controls() {
+ final scale = _scale.clamp(
+ SuperTabImageViewer.zoomMin,
+ SuperTabImageViewer.zoomMax,
+ );
+ final item = _item;
+ final url = _url;
+ return Row(
+ children: [
+ _button(
+ 'rotate',
+ AppIcons.rotateCw,
+ 'Rotate',
+ () => setState(() => _turns = (_turns + 1) % 4),
+ ),
+ const SizedBox(width: grid.AppDesktop.groupGap),
+ _button(
+ 'zoom-out',
+ AppIcons.minus,
+ 'Zoom out',
+ scale <= SuperTabImageViewer.zoomMin ? null : () => _step(-1),
+ ),
+ SizedBox(
+ width: 160,
+ child: SliderTheme(
+ data: SliderTheme.of(context).copyWith(
+ activeTrackColor: _ink,
+ inactiveTrackColor: grid.AppDesktop.mediaControlHover,
+ thumbColor: _ink,
+ overlayColor: grid.AppDesktop.mediaControl,
+ tickMarkShape: SliderTickMarkShape.noTickMark,
+ ),
+ child: Slider(
+ key: const ValueKey('super-image-zoom'),
+ value: scale,
+ min: SuperTabImageViewer.zoomMin,
+ max: SuperTabImageViewer.zoomMax,
+ divisions:
+ ((SuperTabImageViewer.zoomMax - SuperTabImageViewer.zoomMin) /
+ SuperTabImageViewer.zoomStep)
+ .round(),
+ semanticFormatterCallback: (value) => '${(value * 100).round()}%',
+ onChanged: _setZoom,
+ ),
+ ),
+ ),
+ _button(
+ 'zoom-in',
+ AppIcons.plus,
+ 'Zoom in',
+ scale >= SuperTabImageViewer.zoomMax ? null : () => _step(1),
+ ),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ SizedBox(
+ width: 44,
+ child: Text(
+ '${(scale * 100).round()}%',
+ style: DesktopChrome.metadata(color: grid.AppDesktop.mediaInkMuted),
),
- const SizedBox(height: grid.AppDesktop.groupGap),
- Expanded(
- child: InteractiveViewer(
- child: Image(
- key: ValueKey('super-attachment-image:${file.id}'),
- image: attachmentPicture(url),
- fit: BoxFit.contain,
- loadingBuilder: (_, child, progress) => progress == null
- ? child
- : const Center(child: CircularProgressIndicator()),
- errorBuilder: (_, _, _) => Center(
- child: Text(
- 'This image can’t be shown here.',
- style: DesktopChrome.metadata(),
+ ),
+ Expanded(
+ child: url == null
+ ? const SizedBox.shrink()
+ : AttachmentViewerActions(
+ key: ValueKey('super-image-actions:${item.file.id}'),
+ file: item.file,
+ url: url,
+ ref: item.ref,
+ close: false,
+ ink: _ink,
+ fill: grid.AppDesktop.mediaControl,
+ more: switch (item.onShowInChat) {
+ final show? => SuperTabMessageMoreMenu(
+ color: grid.AppDesktop.mediaInkMuted,
+ hoverColor: _ink,
+ hoverFill: grid.AppDesktop.mediaControlHover,
+ actions: [
+ (
+ label: 'Show in chat',
+ icon: AppIcons.messageSquare,
+ onPressed: () {
+ widget.onClose();
+ show();
+ },
+ ),
+ ],
+ ),
+ null => null,
+ },
+ ),
+ ),
+ ],
+ );
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ return FocusScope(
+ node: _focus,
+ autofocus: true,
+ onKeyEvent: _key,
+ child: Material(
+ key: const ValueKey('super-attachment-viewer'),
+ color: grid.AppDesktop.mediaVeil,
+ child: GestureDetector(
+ // A click on the veil closes it; the picture and the controls keep
+ // their own.
+ key: const ValueKey('super-image-veil'),
+ behavior: HitTestBehavior.opaque,
+ onTap: widget.onClose,
+ child: Padding(
+ padding: const EdgeInsets.all(grid.AppDesktop.panelPadding),
+ child: Column(
+ children: [
+ _bar(_header()),
+ const SizedBox(height: grid.AppDesktop.groupGap),
+ Expanded(
+ child: Row(
+ children: [
+ _arrow(false),
+ Expanded(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ _viewport = constraints.biggest;
+ return InteractiveViewer(
+ transformationController: _zoom,
+ minScale: SuperTabImageViewer.zoomMin,
+ maxScale: SuperTabImageViewer.zoomMax,
+ child: Center(
+ child: GestureDetector(
+ onTap: () {},
+ child: _picture(),
+ ),
+ ),
+ );
+ },
+ ),
+ ),
+ _arrow(true),
+ ],
),
),
- ),
+ const SizedBox(height: grid.AppDesktop.groupGap),
+ _bar(_controls()),
+ ],
),
),
- const SizedBox(height: grid.AppDesktop.groupGap),
- AttachmentViewerActions(file: file, url: url, ref: ref),
- ],
+ ),
),
- ),
- );
+ );
+ }
}
diff --git a/desktop/lib/super_tabs/attachment_viewer.dart b/desktop/lib/super_tabs/attachment_viewer.dart
index cff347878..c76fcc340 100644
--- a/desktop/lib/super_tabs/attachment_viewer.dart
+++ b/desktop/lib/super_tabs/attachment_viewer.dart
@@ -104,12 +104,28 @@ class AttachmentViewerActions extends StatefulWidget {
required this.file,
required this.url,
this.ref,
+ this.close = true,
+ this.more,
+ this.ink,
+ this.fill,
});
final SuperTabAttachment file;
final Uri url;
final SuperTabFileRef? ref;
+ /// Whether Close is offered; the picture viewer closes by its own ×.
+ final bool close;
+
+ /// After the buttons: the picture viewer's More.
+ final Widget? more;
+
+ /// The buttons' and the outcome's ink, on the picture viewer's veil.
+ final Color? ink;
+
+ /// The buttons' fill there, the same in both appearances.
+ final Color? fill;
+
@override
State<AttachmentViewerActions> createState() =>
_AttachmentViewerActionsState();
@@ -160,26 +176,49 @@ class _AttachmentViewerActionsState extends State<AttachmentViewerActions> {
}
@override
- Widget build(BuildContext context) => Row(
- children: [
- if (_outcome != null) Text(_outcome!, style: DesktopChrome.metadata()),
- const Spacer(),
- // A browser cannot write to a chosen path; Open in browser saves there.
- if (!kIsWeb)
+ Widget build(BuildContext context) {
+ final ink = widget.ink;
+ final style = ink == null
+ ? null
+ : TextButton.styleFrom(
+ foregroundColor: ink,
+ backgroundColor: widget.fill,
+ side: BorderSide.none,
+ );
+ return Row(
+ children: [
+ if (_outcome != null)
+ Flexible(
+ child: Text(
+ _outcome!,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: DesktopChrome.metadata(color: ink),
+ ),
+ ),
+ const Spacer(),
+ // A browser cannot write to a chosen path; Open in browser saves there.
+ if (!kIsWeb)
+ TextButton(
+ style: style,
+ onPressed: _saving ? null : _download,
+ child: const Text('Download'),
+ ),
TextButton(
- onPressed: _saving ? null : _download,
- child: const Text('Download'),
+ style: style,
+ onPressed: _openInBrowser,
+ child: const Text('Open in browser'),
),
- TextButton(
- onPressed: _openInBrowser,
- child: const Text('Open in browser'),
- ),
- TextButton(
- onPressed: () => Navigator.pop(context),
- child: const Text('Close'),
- ),
- ],
- );
+ if (widget.close)
+ TextButton(
+ style: style,
+ onPressed: () => Navigator.pop(context),
+ child: const Text('Close'),
+ ),
+ ?widget.more,
+ ],
+ );
+ }
}
/// The picture at [url], read through [attachmentFetcher] like any chat file:
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index ebc3b466f..0706f15fd 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -572,6 +572,7 @@ class SuperTabClient {
} while (after != null);
discoveryError = null;
_owners = owners;
+ _listed = tabs.keys.toSet();
final hidden = Set<String>.unmodifiable({..._hidden, ..._creating});
onTabs!(tabs.values.toList(), hidden);
// Every page read: a Swarm not listed is no longer this account's.
@@ -606,6 +607,23 @@ class SuperTabClient {
});
}
+ /// The Swarms the last list read that answered named.
+ Set<String> _listed = const {};
+
+ /// Whether the account's list still names Swarm [id], read afresh (or
+ /// joining a read under way): a Swarm refuses a read while its backend
+ /// restarts, and only the list says it is gone. Throws when the list cannot
+ /// be read, or the account changed meanwhile.
+ Future<bool> _stillListed(String id) async {
+ final generation = _generation;
+ await refreshTabs();
+ if (generation != _generation) {
+ throw const SuperTabFailure('ACCOUNT_CHANGED', 'The account changed.');
+ }
+ if (discoveryError case final error?) throw error;
+ return _listed.contains(id);
+ }
+
/// One page of the Swarm list, with each Swarm's waiting tags while the
/// backend counts them. A backend from before that refuses the query: the
/// page is read without it, and every page after it for the session.
@@ -741,6 +759,7 @@ class SuperTabClient {
upload: upload,
avatarUpload: avatarUpload,
reading: _reading,
+ stillListed: onTabs == null ? null : () => _stillListed(id),
)
..away = _isAway(id)
..pushUntil = _pushUntil;
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 387ef13ae..32d5e9ed8 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -23,6 +23,7 @@ import 'parts.dart';
import 'read_marks.dart';
import 'reading.dart';
import 'linked_tasks.dart';
+import 'local_time_zone.dart';
import 'task_steps.dart';
/// A messages read started beside a state read, and what it asked for.
@@ -195,6 +196,7 @@ class SuperTabController extends ChangeNotifier {
Map<String, dynamic> initial = const {},
this.pollInterval = const Duration(seconds: 3),
SuperTabReading reading = const SuperTabReading(),
+ this.stillListed,
}) : _policy = reading {
if (initial['tabId'] == tabId && initial['accountId'] == accountId) {
final order = initial['sendOrder'];
@@ -3540,6 +3542,36 @@ class SuperTabController extends ChangeNotifier {
_changed();
}
+ /// The zone this app last told the Swarm, or tried to: told once per zone
+ /// and session, so an older backend's refusal is not sent again.
+ String? _zoneTold;
+
+ /// Tells the Swarm the reader's time zone when it differs from the one it
+ /// keeps for them (backend `member.timeZone`), for the local time on their
+ /// card. Quietly: a refusal (an older backend) leaves their card without a
+ /// time, which is what it shows anyway.
+ void _reportTimeZone(SuperTabSnapshot next) {
+ final zone = superTabLocalTimeZone();
+ if (zone == null || zone == _zoneTold) return;
+ final me = next.people.where((p) => p.id == accountId).firstOrNull;
+ if (me == null || me.timeZone == zone) return;
+ _zoneTold = zone;
+ unawaited(
+ request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(tabId)}/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {'type': 'member.timeZone', 'timeZone': zone},
+ },
+ ).then<void>(
+ (_) {},
+ onError: (Object error) =>
+ appLog.debug('swarm', 'time zone not told: $error'),
+ ),
+ );
+ }
+
Future<void> refresh() {
if (_disposed || accessRevoked || updateRequired) return Future.value();
return _refreshing ??= _read().whenComplete(() {
@@ -3634,6 +3666,7 @@ class SuperTabController extends ChangeNotifier {
throw const FormatException('A different Swarm was returned.');
}
snapshot = next;
+ _reportTimeZone(next);
_notifyKept.removeWhere((_, kept) => kept.$2 < serial);
final allowed = next.conversations.map((c) => c.id).toSet();
// What this device keeps of a group goes with the group itself (a
@@ -4346,6 +4379,12 @@ class SuperTabController extends ChangeNotifier {
_poll?.cancel();
}
+ /// Whether the account's Swarm list still names this Swarm: true while it
+ /// does, false once a list read that answered leaves it out; it throws when
+ /// the list cannot be read. Null: a refused read is final at once.
+ final Future<bool> Function()? stillListed;
+ bool _checkingListed = false;
+
void _readFailure(Object failure, {bool revokeTab = true}) {
if (_disposed) return;
if (_isUpdateRequired(failure)) return _requireUpdate();
@@ -4355,25 +4394,54 @@ class SuperTabController extends ChangeNotifier {
if (revokeTab &&
failure is SuperTabFailure &&
const {'FORBIDDEN', 'NOT_FOUND'}.contains(failure.code)) {
- accessRevoked = true;
- devicesSelected = false;
- _forgetClosedShipped();
- _forgetAttention();
- snapshot = null;
- _showingSaved = false;
- _parts = null;
- _messages.clear();
- _staleHeld.clear();
- _forgetNewer();
- _quoted.clear();
- _quoting.clear();
- _forgetThreads();
- _poll?.cancel();
- _firstReadRetry?.cancel();
- cancelUpload();
+ // A backend restarting under an open Swarm can refuse a read it answers
+ // a moment later (Dee's "autonomous.ai", 2026-11-04). Only the list says
+ // the Swarm is gone: until it does, this is a failed read like any
+ // other, and the Swarm keeps what it shows and says Reconnecting.
+ if (stillListed case final listed?) {
+ unawaited(_takeAwayUnlessListed(listed));
+ return;
+ }
+ _takeAway();
}
}
+ Future<void> _takeAwayUnlessListed(Future<bool> Function() listed) async {
+ if (_checkingListed) return;
+ _checkingListed = true;
+ bool? still;
+ try {
+ still = await listed();
+ } catch (_) {
+ still = null;
+ } finally {
+ _checkingListed = false;
+ }
+ if (_disposed || accessRevoked || still != false) return;
+ _takeAway();
+ _changed();
+ }
+
+ /// The Swarm is not this account's any more: nothing of it is kept or read.
+ void _takeAway() {
+ accessRevoked = true;
+ devicesSelected = false;
+ _forgetClosedShipped();
+ _forgetAttention();
+ snapshot = null;
+ _showingSaved = false;
+ _parts = null;
+ _messages.clear();
+ _staleHeld.clear();
+ _forgetNewer();
+ _quoted.clear();
+ _quoting.clear();
+ _forgetThreads();
+ _poll?.cancel();
+ _firstReadRetry?.cancel();
+ cancelUpload();
+ }
+
/// Joins a read of [id] in the same direction already under way, so a
/// caller can wait for it.
Future<void> loadMessages(String id, {bool older = false}) {
diff --git a/desktop/lib/super_tabs/day_pill.dart b/desktop/lib/super_tabs/day_pill.dart
index b443e0c65..618a72d00 100644
--- a/desktop/lib/super_tabs/day_pill.dart
+++ b/desktop/lib/super_tabs/day_pill.dart
@@ -12,6 +12,10 @@ import '../widgets/desktop_chrome.dart';
/// [SuperTabDayMark] with its time; rows without one are not counted. With
/// nothing hidden above the list's top (the start of what is read) it shows
/// nothing, and the inline day line says the day.
+///
+/// A day line's label in [child] is a [SuperTabDayLabel]. Once a label
+/// reaches the pill, the pill takes its place, as Slack's: the pill says the
+/// label's day and the label is not painted, so one label shows (Huy 11-04).
class SuperTabStickyDay extends StatefulWidget {
const SuperTabStickyDay({
super.key,
@@ -34,6 +38,7 @@ class SuperTabStickyDay extends StatefulWidget {
class _SuperTabStickyDayState extends State<SuperTabStickyDay> {
final _marks = <_SuperTabDayMarkState>{};
+ final _labels = <_SuperTabDayLabelState>{};
DateTime? _day;
bool _measuring = false;
@@ -56,17 +61,26 @@ class _SuperTabStickyDayState extends State<SuperTabStickyDay> {
WidgetsBinding.instance.addPostFrameCallback((_) {
_measuring = false;
if (!mounted) return;
- final day = _dayAtTop();
+ final (:day, :under) = _measure();
+ // The pill and the labels it covers change in the same frame.
if (day != _day) setState(() => _day = day);
+ for (final label in _labels.toList()) {
+ label._cover(under.contains(label));
+ }
});
}
- /// The local day of the row at the top edge: the one the edge cuts
- /// through, else the highest one below it; null when nothing is hidden
- /// above the list's top.
- DateTime? _dayAtTop() {
+ /// The pill's day and the day line labels it covers, null and none when
+ /// nothing is hidden above the list's top.
+ ///
+ /// The day is that of the lowest label whose top has reached the pill's
+ /// bottom edge, which the pill covers with every label above it; with none,
+ /// the day of the row at the top edge: the one the edge cuts through, else
+ /// the highest one below it.
+ ({DateTime? day, Set<_SuperTabDayLabelState> under}) _measure() {
+ const none = (day: null, under: <_SuperTabDayLabelState>{});
final list = context.findRenderObject();
- if (list is! RenderBox || !list.hasSize) return null;
+ if (list is! RenderBox || !list.hasSize) return none;
({double top, DateTime time})? at;
ScrollPosition? position;
for (final mark in _marks) {
@@ -84,10 +98,28 @@ class _SuperTabStickyDayState extends State<SuperTabStickyDay> {
(top <= 0 ? at.top > 0 || top > at.top : at.top > 0 && top < at.top);
if (better) at = (top: top, time: time);
}
- if (at == null || position == null || !position.hasPixels) return null;
- if (position.extentBefore <= 0) return null;
- final local = at.time.toLocal();
- return DateTime(local.year, local.month, local.day);
+ if (at == null || position == null || !position.hasPixels) return none;
+ if (position.extentBefore <= 0) return none;
+ final under = <_SuperTabDayLabelState>{};
+ ({double top, DateTime day})? passed;
+ for (final label in _labels) {
+ final box = label.context.findRenderObject();
+ if (box is! RenderBox || !box.attached || !box.hasSize) continue;
+ final top = box.localToGlobal(Offset.zero, ancestor: list).dy;
+ // The pill's text is set as the label's, inside the pill's padding.
+ if (top >= SuperTabDayPill.top + SuperTabDayPill.heightFor(box.size)) {
+ continue;
+ }
+ under.add(label);
+ if (passed == null || top > passed.top) {
+ passed = (top: top, day: label.widget.day);
+ }
+ }
+ final local = (passed?.day ?? at.time).toLocal();
+ return (
+ day: DateTime(local.year, local.month, local.day),
+ under: widget.hidden ? const {} : under,
+ );
}
bool _onScroll(Notification event) {
@@ -118,7 +150,7 @@ class _SuperTabStickyDayState extends State<SuperTabStickyDay> {
),
if (day != null && !widget.hidden)
Positioned(
- top: grid.AppDesktop.controlGap,
+ top: SuperTabDayPill.top,
left: 0,
right: 0,
child: IgnorePointer(
@@ -136,6 +168,75 @@ class _SuperTabStickyDayState extends State<SuperTabStickyDay> {
}
}
+/// A day line's label, which the [SuperTabStickyDay] above it covers once
+/// the pill reaches it. A covered label keeps its place, so no row moves, and
+/// a screen reader still reads it.
+class SuperTabDayLabel extends StatefulWidget {
+ const SuperTabDayLabel({super.key, required this.day, required this.child});
+
+ /// The day the label says.
+ final DateTime day;
+ final Widget child;
+
+ @override
+ State<SuperTabDayLabel> createState() => _SuperTabDayLabelState();
+}
+
+class _SuperTabDayLabelState extends State<SuperTabDayLabel> {
+ _SuperTabStickyDayState? _list;
+ bool _covered = false;
+
+ void _cover(bool covered) {
+ if (covered != _covered && mounted) setState(() => _covered = covered);
+ }
+
+ void _join() {
+ final list = context
+ .getInheritedWidgetOfExactType<_SuperTabDayScope>()
+ ?.state;
+ if (list == _list) return;
+ _list?._labels.remove(this);
+ _list = list?.._labels.add(this);
+ }
+
+ void _leave() {
+ _list?._labels.remove(this);
+ _list = null;
+ _covered = false;
+ }
+
+ @override
+ void activate() {
+ super.activate();
+ _join();
+ }
+
+ @override
+ void deactivate() {
+ _leave();
+ super.deactivate();
+ }
+
+ @override
+ void dispose() {
+ _leave();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ _join();
+ return Visibility(
+ visible: !_covered,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ maintainSemantics: true,
+ child: widget.child,
+ );
+ }
+}
+
class _SuperTabDayScope extends InheritedWidget {
const _SuperTabDayScope({required this.state, required super.child});
@@ -206,21 +307,35 @@ class SuperTabDayPill extends StatelessWidget {
final DateTime day;
+ /// The pill's distance from the list's top.
+ static const top = grid.AppDesktop.controlGap;
+
+ static const _padding = EdgeInsets.symmetric(
+ horizontal: grid.AppDesktop.controlGap + grid.AppDesktop.menuInset,
+ vertical: grid.AppDesktop.listRowGap,
+ );
+ static const _rim = 1.0;
+
+ /// The pill's height around a label of [label]'s size, set in the same
+ /// style as the pill's text.
+ static double heightFor(Size label) =>
+ label.height + _padding.vertical + 2 * _rim;
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
return DecoratedBox(
decoration: ShapeDecoration(
- color: DesktopChrome.surface,
- shape: StadiumBorder(side: BorderSide(color: DesktopChrome.rim)),
+ // Opaque, so the rows it floats over never read through it.
+ color: DesktopChrome.surface.withValues(alpha: 1),
+ shape: StadiumBorder(
+ side: BorderSide(color: DesktopChrome.rim, width: _rim),
+ ),
// Lifted off the rows it floats over, as Slack's.
shadows: grid.AppGlass.cardShadow,
),
child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: grid.AppDesktop.controlGap + grid.AppDesktop.menuInset,
- vertical: grid.AppDesktop.listRowGap,
- ),
+ padding: _padding,
child: Text(
MaterialLocalizations.of(context).formatMediumDate(day),
maxLines: 1,
diff --git a/desktop/lib/super_tabs/identity_card.dart b/desktop/lib/super_tabs/identity_card.dart
new file mode 100644
index 000000000..c047d45b8
--- /dev/null
+++ b/desktop/lib/super_tabs/identity_card.dart
@@ -0,0 +1,492 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import '../shared/theme/app_icons.dart';
+import '../shared/theme/app_theme.dart' as grid;
+import '../widgets/desktop_chrome.dart';
+import '../widgets/engine_identity.dart';
+import 'machine_icon.dart';
+import 'profile_model.dart';
+import 'swarm_type.dart';
+import 'zone_time.dart';
+
+/// What the card over a chat name or avatar shows (Huy, 11-04, like Slack's):
+/// a person's name, status and local time; an agent's name, engine and model,
+/// machine and task. A fact nobody knows is left out, never guessed.
+sealed class SuperTabIdentityFacts {
+ const SuperTabIdentityFacts(this.name);
+ final String name;
+}
+
+class SuperTabPersonFacts extends SuperTabIdentityFacts {
+ const SuperTabPersonFacts(super.name, {this.status, this.timeZone});
+
+ /// Their status while it lasts.
+ final SuperTabPersonStatus? status;
+
+ /// Their zone's IANA name, for the time where they are; null until their
+ /// app has told the Swarm.
+ final String? timeZone;
+}
+
+class SuperTabAgentFacts extends SuperTabIdentityFacts {
+ const SuperTabAgentFacts(
+ super.name, {
+ this.engine,
+ this.model,
+ this.machine,
+ this.deviceType,
+ this.task,
+ this.onOpenTask,
+ });
+
+ /// The engine's id (`claude`), for its mark and its name.
+ final String? engine;
+
+ /// The model as people know it ("Opus 5.5").
+ final String? model;
+ final String? machine, deviceType;
+
+ /// What it is doing with its task, the task's number and title in it
+ /// ("Working on #2605 Chat: a card…").
+ final String? task;
+
+ /// Opens the task's chat.
+ final VoidCallback? onOpenTask;
+}
+
+/// The card itself: the shared popover surface, flat rows, no avatar (the
+/// row beside it has one).
+class SuperTabIdentityCard extends StatefulWidget {
+ const SuperTabIdentityCard({super.key, required this.facts});
+
+ final SuperTabIdentityFacts facts;
+
+ static const minWidth = 220.0, maxWidth = 320.0;
+
+ @override
+ State<SuperTabIdentityCard> createState() => _SuperTabIdentityCardState();
+}
+
+class _SuperTabIdentityCardState extends State<SuperTabIdentityCard> {
+ static const _inset = grid.AppDesktop.groupGap;
+ static const _rowGap = grid.AppDesktop.menuInset;
+
+ @override
+ void initState() {
+ super.initState();
+ // The zone table is read the first time a card needs it; the card
+ // gains its time line once it is in.
+ if (widget.facts case SuperTabPersonFacts(timeZone: _?)
+ when !superTabZonesLoaded) {
+ superTabLoadZones().then((_) {
+ if (mounted) setState(() {});
+ });
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final highContrast = MediaQuery.highContrastOf(context);
+ final facts = widget.facts;
+ final rows = <Widget>[
+ Text(
+ facts.name,
+ key: const ValueKey('super-identity-card-name'),
+ style: SwarmType.name(context),
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ...switch (facts) {
+ SuperTabPersonFacts(:final status, :final timeZone) => [
+ if (status != null)
+ _Line(
+ leading: status.emoji == null
+ ? null
+ : Text(status.emoji!, style: DesktopChrome.text()),
+ text: status.text,
+ ),
+ if (superTabTimeNow(timeZone, clock.now()) case final localTime?)
+ _Line(
+ key: const ValueKey('super-identity-card-time'),
+ leading: Icon(
+ AppIcons.clock,
+ size: AppIcons.inlineSize,
+ color: DesktopChrome.muted,
+ ),
+ text: '${localTime.format(context)} local time',
+ ),
+ ],
+ SuperTabAgentFacts() => [
+ if (_engineLine(facts) case final line?)
+ _Line(
+ leading: EngineMark(
+ engine: facts.engine,
+ size: AppIcons.inlineSize,
+ ),
+ text: line,
+ ),
+ if (facts.machine case final machine?)
+ _Line(
+ leading: SuperTabMachineIcon(
+ deviceType: facts.deviceType,
+ color: DesktopChrome.muted,
+ ),
+ text: machine,
+ ),
+ if (facts.task case final task?)
+ _TaskLine(text: task, onOpen: facts.onOpenTask),
+ ],
+ },
+ ];
+ return ConstrainedBox(
+ constraints: const BoxConstraints(
+ minWidth: SuperTabIdentityCard.minWidth,
+ maxWidth: SuperTabIdentityCard.maxWidth,
+ ),
+ child: IntrinsicWidth(
+ child: DecoratedBox(
+ key: const ValueKey('super-identity-card'),
+ decoration: BoxDecoration(
+ color: grid.AppMenu.fill,
+ borderRadius: BorderRadius.circular(grid.AppMenu.panelRadius),
+ border: Border.all(
+ color: highContrast
+ ? DesktopChrome.foreground.withValues(alpha: .55)
+ : grid.AppMenu.rim,
+ ),
+ boxShadow: grid.AppSurface.shadow,
+ ),
+ child: Material(
+ type: MaterialType.transparency,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(grid.AppMenu.panelRadius),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(_inset),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ for (final (i, row) in rows.indexed) ...[
+ if (i > 0) const SizedBox(height: _rowGap),
+ row,
+ ],
+ ],
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ static String? _engineLine(SuperTabAgentFacts facts) {
+ final engine = facts.engine?.trim().isNotEmpty == true
+ ? engineIdentity(facts.engine).label
+ : null;
+ final parts = [?engine, ?facts.model];
+ return parts.isEmpty ? null : parts.join(' ');
+ }
+}
+
+/// One fact: an optional mark, then its words.
+class _Line extends StatelessWidget {
+ const _Line({super.key, this.leading, required this.text});
+
+ final Widget? leading;
+ final String text;
+
+ @override
+ Widget build(BuildContext context) => Row(
+ children: [
+ if (leading case final mark?) ...[
+ SizedBox.square(dimension: AppIcons.inlineSize, child: mark),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ ],
+ Flexible(
+ child: Text(
+ text,
+ style: DesktopChrome.text(),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ ],
+ );
+}
+
+/// The agent's task, as a link to its chat: a hand cursor, the hover fill
+/// and an underline, and a chevron, so its colour is not the only sign.
+class _TaskLine extends StatefulWidget {
+ const _TaskLine({required this.text, this.onOpen});
+
+ final String text;
+ final VoidCallback? onOpen;
+
+ @override
+ State<_TaskLine> createState() => _TaskLineState();
+}
+
+class _TaskLineState extends State<_TaskLine> {
+ var _hovered = false, _focused = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final active = _hovered || _focused;
+ final style = DesktopChrome.text(color: grid.AppPalette.accentOnSurface);
+ return Semantics(
+ link: true,
+ label: '${widget.text}, open its chat',
+ excludeSemantics: true,
+ child: InkWell(
+ key: const ValueKey('super-identity-card-task'),
+ onTap: widget.onOpen,
+ onHover: (hovered) => setState(() => _hovered = hovered),
+ onFocusChange: (focused) => setState(() => _focused = focused),
+ mouseCursor: SystemMouseCursors.click,
+ borderRadius: BorderRadius.circular(grid.AppControl.menuRadius),
+ hoverColor: Colors.transparent,
+ focusColor: Colors.transparent,
+ child: Ink(
+ decoration: BoxDecoration(
+ color: active ? grid.AppSurface.hoverFill : Colors.transparent,
+ borderRadius: BorderRadius.circular(grid.AppControl.menuRadius),
+ border: Border.all(
+ color: _focused ? DesktopChrome.focusRing : Colors.transparent,
+ ),
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ widget.text,
+ style: active
+ ? style.copyWith(decoration: TextDecoration.underline)
+ : style,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ ),
+ ),
+ const SizedBox(width: grid.AppDesktop.controlGap),
+ Icon(
+ AppIcons.chevronRight,
+ size: AppIcons.inlineSize,
+ color: grid.AppPalette.accentOnSurface,
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// Shows [facts]'s card under [child], a chat name or avatar: after
+/// [openDelay] of hover, at once when keyboard focus lands in [child], and
+/// gone [closeDelay] after the pointer and the focus have left both [child]
+/// and the card. Escape closes it and keeps the focus where it was. The card
+/// follows its anchor as the chat scrolls, and opens above it when there is
+/// no room below.
+class SuperTabHoverCard extends StatefulWidget {
+ const SuperTabHoverCard({
+ super.key,
+ required this.facts,
+ required this.child,
+ });
+
+ /// Worked out when the card opens, so it shows what is true then.
+ final SuperTabIdentityFacts Function() facts;
+ final Widget child;
+
+ static const openDelay = Duration(milliseconds: 500);
+ static const closeDelay = Duration(milliseconds: 150);
+
+ /// Room the card needs below its anchor before it opens above instead.
+ static const _roomBelow = 200.0;
+ static const _gap = grid.AppDesktop.menuInset;
+
+ @override
+ State<SuperTabHoverCard> createState() => _SuperTabHoverCardState();
+}
+
+class _SuperTabHoverCardState extends State<SuperTabHoverCard> {
+ final _portal = OverlayPortalController();
+ final _link = LayerLink();
+ final _anchorFocus = FocusNode(
+ debugLabel: 'Identity card anchor',
+ canRequestFocus: false,
+ skipTraversal: true,
+ );
+ final _cardFocus = FocusNode(
+ debugLabel: 'Identity card',
+ canRequestFocus: false,
+ skipTraversal: true,
+ );
+ Timer? _openTimer, _closeTimer;
+ var _overAnchor = false, _overCard = false, _above = false;
+
+ /// Escape closed the card: the focus it sends back to the name does not
+ /// open it again, until the focus has left the name.
+ var _dismissed = false;
+ SuperTabIdentityFacts? _facts;
+
+ @override
+ void initState() {
+ super.initState();
+ _anchorFocus.addListener(_focusMoved);
+ _cardFocus.addListener(_focusMoved);
+ }
+
+ @override
+ void dispose() {
+ _openTimer?.cancel();
+ _closeTimer?.cancel();
+ _anchorFocus.dispose();
+ _cardFocus.dispose();
+ super.dispose();
+ }
+
+ bool get _focused => _anchorFocus.hasFocus || _cardFocus.hasFocus;
+
+ void _focusMoved() {
+ if (!mounted) return;
+ if (_anchorFocus.hasFocus && !_portal.isShowing) {
+ if (!_dismissed) _show();
+ } else if (!_focused) {
+ _dismissed = false;
+ _hideSoon();
+ }
+ }
+
+ void _enterAnchor() {
+ _overAnchor = true;
+ _closeTimer?.cancel();
+ if (_portal.isShowing) return;
+ unawaited(superTabLoadZones());
+ _openTimer?.cancel();
+ _openTimer = Timer(SuperTabHoverCard.openDelay, _show);
+ }
+
+ void _show() {
+ _openTimer?.cancel();
+ _closeTimer?.cancel();
+ if (!mounted) return;
+ final box = context.findRenderObject() as RenderBox?;
+ final overlay =
+ Overlay.maybeOf(context)?.context.findRenderObject() as RenderBox?;
+ if (box != null && overlay != null && box.hasSize) {
+ final bottom = box
+ .localToGlobal(box.size.bottomLeft(Offset.zero), ancestor: overlay)
+ .dy;
+ _above = overlay.size.height - bottom < SuperTabHoverCard._roomBelow;
+ }
+ setState(() => _facts = widget.facts());
+ _portal.show();
+ }
+
+ void _hideSoon() {
+ _openTimer?.cancel();
+ if (!_portal.isShowing) return;
+ _closeTimer?.cancel();
+ _closeTimer = Timer(SuperTabHoverCard.closeDelay, () {
+ if (!mounted || _overAnchor || _overCard || _focused) return;
+ _portal.hide();
+ });
+ }
+
+ void _hideNow() {
+ _openTimer?.cancel();
+ _closeTimer?.cancel();
+ _portal.hide();
+ }
+
+ /// Escape closes the card. While it is open, Tab on the name goes into
+ /// the card (its own reading order would take the row's buttons beside the
+ /// name first) and Shift-Tab in the card goes back to the name.
+ KeyEventResult _onKey(FocusNode _, KeyEvent event) {
+ if (event is! KeyDownEvent || !_portal.isShowing) {
+ return KeyEventResult.ignored;
+ }
+ final inCard = _cardFocus.hasFocus;
+ if (event.logicalKey == LogicalKeyboardKey.escape) {
+ _dismissed = true;
+ _hideNow();
+ // Back to the name the card belongs to.
+ if (inCard) _nameFocus?.requestFocus();
+ return KeyEventResult.handled;
+ }
+ if (event.logicalKey != LogicalKeyboardKey.tab) {
+ return KeyEventResult.ignored;
+ }
+ final back = HardwareKeyboard.instance.isShiftPressed;
+ final target = switch ((inCard, back)) {
+ (false, false) => _cardFocus.traversalDescendants.firstOrNull,
+ (true, true) => _nameFocus,
+ _ => null,
+ };
+ if (target == null) return KeyEventResult.ignored;
+ target.requestFocus();
+ return KeyEventResult.handled;
+ }
+
+ FocusNode? get _nameFocus => _anchorFocus.traversalDescendants.firstOrNull;
+
+ @override
+ Widget build(BuildContext context) => OverlayPortal(
+ controller: _portal,
+ overlayChildBuilder: (_) => CompositedTransformFollower(
+ link: _link,
+ showWhenUnlinked: false,
+ targetAnchor: _above ? Alignment.topLeft : Alignment.bottomLeft,
+ followerAnchor: _above ? Alignment.bottomLeft : Alignment.topLeft,
+ offset: Offset(
+ 0,
+ _above ? -SuperTabHoverCard._gap : SuperTabHoverCard._gap,
+ ),
+ child: Align(
+ alignment: _above ? Alignment.bottomLeft : Alignment.topLeft,
+ child: Focus(
+ focusNode: _cardFocus,
+ onKeyEvent: _onKey,
+ child: FocusTraversalGroup(
+ child: MouseRegion(
+ onEnter: (_) {
+ _overCard = true;
+ _closeTimer?.cancel();
+ },
+ onExit: (_) {
+ _overCard = false;
+ _hideSoon();
+ },
+ child: switch (_facts) {
+ final facts? => SuperTabIdentityCard(facts: facts),
+ null => const SizedBox.shrink(),
+ },
+ ),
+ ),
+ ),
+ ),
+ ),
+ child: CompositedTransformTarget(
+ link: _link,
+ child: Focus(
+ focusNode: _anchorFocus,
+ onKeyEvent: _onKey,
+ child: MouseRegion(
+ onEnter: (_) => _enterAnchor(),
+ onExit: (_) {
+ _overAnchor = false;
+ _hideSoon();
+ },
+ child: widget.child,
+ ),
+ ),
+ ),
+ );
+}
diff --git a/desktop/lib/super_tabs/local_time_zone.dart b/desktop/lib/super_tabs/local_time_zone.dart
new file mode 100644
index 000000000..83d76ca5b
--- /dev/null
+++ b/desktop/lib/super_tabs/local_time_zone.dart
@@ -0,0 +1,35 @@
+import 'package:flutter/foundation.dart';
+
+import '../core/test_run.dart';
+import 'local_time_zone_native.dart'
+ if (dart.library.js_interop) 'local_time_zone_web.dart'
+ as platform;
+
+/// Stands in for this computer's zone in a test; null reads the computer's.
+@visibleForTesting
+String? Function()? superTabLocalTimeZoneOverride;
+
+/// This computer's time zone by its IANA name ("Asia/Ho_Chi_Minh"), which
+/// the reader's app tells the Swarm for the local time on their card
+/// (Huy, 11-04; River: the name, so daylight saving stays right). Null when
+/// it names none: Windows, whose zones have names of their own, and a test.
+String? superTabLocalTimeZone() {
+ if (superTabLocalTimeZoneOverride case final override?) return override();
+ if (kUnderTest) return null;
+ try {
+ final zone = platform.localTimeZone()?.trim();
+ return zone == null || zone.isEmpty ? null : zone;
+ } catch (_) {
+ return null;
+ }
+}
+
+/// The zone a `/etc/localtime` link names: what follows `zoneinfo/` in its
+/// target (macOS `/var/db/timezone/zoneinfo/…`, Linux `/usr/share/zoneinfo/…`).
+String? superTabZoneFromLink(String target) {
+ const marker = '/zoneinfo/';
+ final at = target.indexOf(marker);
+ if (at < 0) return null;
+ final name = target.substring(at + marker.length);
+ return name.isEmpty ? null : name;
+}
diff --git a/desktop/lib/super_tabs/local_time_zone_native.dart b/desktop/lib/super_tabs/local_time_zone_native.dart
new file mode 100644
index 000000000..92076518b
--- /dev/null
+++ b/desktop/lib/super_tabs/local_time_zone_native.dart
@@ -0,0 +1,20 @@
+import 'dart:io';
+
+import 'local_time_zone.dart' show superTabZoneFromLink;
+
+/// A Mac's or a Linux computer's zone: `TZ` when it names one, else the
+/// `/etc/localtime` link, else Debian's `/etc/timezone`. Windows names its
+/// zones its own way, so it gives none.
+String? localTimeZone() {
+ if (Platform.isWindows) return null;
+ final tz = Platform.environment['TZ'];
+ if (tz != null && RegExp(r'^[A-Za-z]+(/[A-Za-z0-9_+-]+)+$').hasMatch(tz)) {
+ return tz;
+ }
+ final link = Link('/etc/localtime');
+ if (link.existsSync()) {
+ if (superTabZoneFromLink(link.targetSync()) case final zone?) return zone;
+ }
+ final file = File('/etc/timezone');
+ return file.existsSync() ? file.readAsStringSync().trim() : null;
+}
diff --git a/desktop/lib/super_tabs/local_time_zone_web.dart b/desktop/lib/super_tabs/local_time_zone_web.dart
new file mode 100644
index 000000000..8c06ea189
--- /dev/null
+++ b/desktop/lib/super_tabs/local_time_zone_web.dart
@@ -0,0 +1,14 @@
+import 'dart:js_interop';
+
+@JS('Intl.DateTimeFormat')
+extension type _DateTimeFormat._(JSObject _) implements JSObject {
+ external _DateTimeFormat();
+ external _ResolvedOptions resolvedOptions();
+}
+
+extension type _ResolvedOptions._(JSObject _) implements JSObject {
+ external String? get timeZone;
+}
+
+/// The browser's zone, as `Intl` resolves it.
+String? localTimeZone() => _DateTimeFormat().resolvedOptions().timeZone;
diff --git a/desktop/lib/super_tabs/message_more_menu.dart b/desktop/lib/super_tabs/message_more_menu.dart
index 6843d3d65..9edcdc8d2 100644
--- a/desktop/lib/super_tabs/message_more_menu.dart
+++ b/desktop/lib/super_tabs/message_more_menu.dart
@@ -15,9 +15,19 @@ typedef SuperTabMoreAction = ({
/// The ⋯ of a message's hover bar: the choices that have no button of their
/// own. Each closes the menu, then runs.
class SuperTabMessageMoreMenu extends StatefulWidget {
- const SuperTabMessageMoreMenu({super.key, required this.actions});
+ const SuperTabMessageMoreMenu({
+ super.key,
+ required this.actions,
+ this.color,
+ this.hoverColor,
+ this.hoverFill,
+ });
final List<SuperTabMoreAction> actions;
+ /// The ⋯'s ink and lift, for a menu drawn on the picture viewer's veil
+ /// ([AppIconButton] by default).
+ final Color? color, hoverColor, hoverFill;
+
@override
State<SuperTabMessageMoreMenu> createState() =>
_SuperTabMessageMoreMenuState();
@@ -69,6 +79,9 @@ class _SuperTabMessageMoreMenuState extends State<SuperTabMessageMoreMenu> {
icon: AppIcons.ellipsis,
focusNode: _focus,
tooltip: 'More',
+ color: widget.color,
+ hoverColor: widget.hoverColor,
+ hoverFill: widget.hoverFill,
onPressed: () => menu.isOpen ? menu.close() : menu.open(),
),
);
diff --git a/desktop/lib/super_tabs/message_receipt.dart b/desktop/lib/super_tabs/message_receipt.dart
index f00cdba3b..045470eb8 100644
--- a/desktop/lib/super_tabs/message_receipt.dart
+++ b/desktop/lib/super_tabs/message_receipt.dart
@@ -11,6 +11,7 @@ import '../widgets/desktop_chrome.dart';
import 'controller.dart';
import 'machine_status.dart';
import 'model.dart';
+import 'personal_lead.dart';
/// How long a queued delivery's claims fail before its sender is told, and how
/// long a queued message waits with no claim fields before the same (prod 10-30,
@@ -55,15 +56,26 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
- widget.app?.addListener(_changed);
+ _listen(widget.app);
+ }
+
+ /// [app], and the Lead its Personal project starts (personal_lead.dart).
+ void _listen(AppNotifier? app) {
+ app?.addListener(_changed);
+ if (app != null) PersonalLeadStarter.of(app).addListener(_changed);
+ }
+
+ void _unlisten(AppNotifier? app) {
+ app?.removeListener(_changed);
+ if (app != null) PersonalLeadStarter.of(app).removeListener(_changed);
}
@override
void didUpdateWidget(SuperTabMessageReceipt oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.app != widget.app) {
- oldWidget.app?.removeListener(_changed);
- widget.app?.addListener(_changed);
+ _unlisten(oldWidget.app);
+ _listen(widget.app);
}
}
@@ -99,7 +111,7 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
@override
void dispose() {
_timer?.cancel();
- widget.app?.removeListener(_changed);
+ _unlisten(widget.app);
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@@ -196,8 +208,23 @@ class _SuperTabMessageReceiptState extends State<SuperTabMessageReceipt>
c.selected?.leadId == null &&
// A Buddy chat has no Lead: its Buddy takes the message.
c.selected?.isBuddyChat != true) {
- title = 'Not sent · this chat has no Lead';
- actions.add(('Add a Lead', c.canWrite ? widget.onAddLead : null));
+ // In a Personal Swarm this Desktop starts the project's Lead, which the
+ // server keeps the message for (task #2633); else, or when it could
+ // not start, Add a Lead.
+ final app = widget.app;
+ final start = app == null
+ ? null
+ : PersonalLeadStarter.of(app).statusOf(c, message.conversationId);
+ if (start != null && !start.failed) {
+ color = DesktopChrome.muted;
+ title = 'Starting a Lead…';
+ sending = true;
+ } else {
+ title = start == null
+ ? 'Not sent · this chat has no Lead'
+ : 'Couldn’t start a Lead: ${start.reason}';
+ actions.add(('Add a Lead', c.canWrite ? widget.onAddLead : null));
+ }
} else if (delivery?.status == 'cancelled') {
title = 'Not sent';
} else if (delivery?.pending == true && offline) {
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index dcac96de1..2b5cf7a7e 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -11,6 +11,7 @@ import '../widgets/engine_identity.dart';
import '../widgets/finger_target.dart';
import 'attachment_chips.dart';
import 'identity.dart';
+import 'identity_card.dart';
import 'machine_status.dart' show superTabAgo;
import 'message_link.dart';
import 'message_link_preview.dart';
@@ -21,6 +22,38 @@ import 'pull_requests.dart';
import 'reactions.dart';
import 'swarm_type.dart';
+/// The face [message]'s row shows for its sender, shown as [author]: the
+/// [agent] or [person] who wrote it, while they are in the Swarm.
+Widget superTabMessageAvatar(
+ SuperTabMessage message, {
+ required String author,
+ SuperTabAgent? agent,
+ SuperTabPerson? person,
+ double size = SuperTabMessageRow.avatarSize,
+}) {
+ const radius = grid.AppDesktop.messageAvatarRadius;
+ if (agent != null) {
+ return SuperTabAvatar.agent(
+ agent,
+ name: author,
+ size: size,
+ engineBadge: false,
+ radius: radius,
+ );
+ }
+ if (person != null && !message.fromAgent) {
+ return SuperTabAvatar.person(person, size: size, radius: radius);
+ }
+ // Someone no longer in the Swarm keeps the face their recorded name gives.
+ return SuperTabAvatar(
+ identity: '${message.author['kind']}:${message.authorId}',
+ name: message.fromAgent ? author : superTabPersonName(message.authorName),
+ size: size,
+ pattern: message.fromAgent,
+ radius: radius,
+ );
+}
+
/// Presentation only. Message identity and reply routing use backend IDs.
class SuperTabMessageRow extends StatefulWidget {
const SuperTabMessageRow({
@@ -60,10 +93,15 @@ class SuperTabMessageRow extends StatefulWidget {
this.link,
this.linkTarget,
this.onOpenLink,
+ this.identity,
});
final SuperTabMessage message;
+ /// Who wrote it, for the card hovering or focusing its name or avatar shows
+ /// (Huy, 11-04); without it the avatar keeps its tooltip.
+ final SuperTabIdentityFacts Function()? identity;
+
/// The live card [message] is (live_card.dart), drawn in place of its pull
/// request links; null for a plain message.
final Widget? card;
@@ -265,30 +303,49 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
].join(' · ');
}
- Widget _avatar(SuperTabMessage message) {
- const size = SuperTabMessageRow.avatarSize;
- const radius = grid.AppDesktop.messageAvatarRadius;
- if (widget.agent case final agent?) {
- return SuperTabAvatar.agent(
- agent,
- name: widget.author,
- size: size,
- engineBadge: false,
- radius: radius,
- );
- }
- if (widget.person case final person? when !message.fromAgent) {
- return SuperTabAvatar.person(person, size: size, radius: radius);
+ Widget _avatar(SuperTabMessage message) => superTabMessageAvatar(
+ message,
+ author: widget.author,
+ agent: widget.agent,
+ person: widget.person,
+ );
+
+ /// The sender's name: opens the agent when it is one, and shows the card
+ /// on hover or keyboard focus, so a person's name takes focus too.
+ Widget _name(TextStyle style, bool finger) {
+ final name = fingerTarget(
+ enabled: finger,
+ Align(
+ alignment: Alignment.centerLeft,
+ widthFactor: 1,
+ heightFactor: 1,
+ child: Text(widget.author, style: style),
+ ),
+ );
+ final identity = widget.identity;
+ if (identity == null) {
+ return InkWell(onTap: widget.onOpenAgent, child: name);
}
- // 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,
- radius: radius,
+ return SuperTabHoverCard(
+ facts: identity,
+ child: widget.onOpenAgent == null
+ ? Focus(
+ child: Builder(
+ builder: (context) => DecoratedBox(
+ decoration: BoxDecoration(
+ border: Border(
+ bottom: BorderSide(
+ color: Focus.of(context).hasFocus
+ ? DesktopChrome.focusRing
+ : Colors.transparent,
+ ),
+ ),
+ ),
+ child: name,
+ ),
+ ),
+ )
+ : InkWell(onTap: widget.onOpenAgent, child: name),
);
}
@@ -432,10 +489,16 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
child: widget.grouped
? _groupedTime(context, active)
: ExcludeSemantics(
- child: Tooltip(
- message: _identityDetails,
- child: _avatar(message),
- ),
+ child: switch (widget.identity) {
+ final identity? => SuperTabHoverCard(
+ facts: identity,
+ child: _avatar(message),
+ ),
+ null => Tooltip(
+ message: _identityDetails,
+ child: _avatar(message),
+ ),
+ },
),
),
const SizedBox(width: SuperTabMessageRow.avatarGap),
@@ -452,21 +515,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
crossAxisAlignment:
WrapCrossAlignment.center,
children: [
- InkWell(
- onTap: widget.onOpenAgent,
- child: fingerTarget(
- enabled: finger,
- Align(
- alignment: Alignment.centerLeft,
- widthFactor: 1,
- heightFactor: 1,
- child: Text(
- widget.author,
- style: authorStyle,
- ),
- ),
- ),
- ),
+ _name(authorStyle, finger),
if (message.fromAgent)
Tooltip(
message: _identityDetails,
diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dart
index 96bace68f..e77897846 100644
--- a/desktop/lib/super_tabs/model.dart
+++ b/desktop/lib/super_tabs/model.dart
@@ -49,6 +49,10 @@ class SuperTabPerson {
joinedVia = row['joinedVia'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
status = SuperTabPersonStatus.fromJson(row['status']),
+ timeZone = switch (row['timeZone']) {
+ final String zone when zone.trim().isNotEmpty => zone,
+ _ => null,
+ },
chosenUsername = row['username'] as String?,
name = switch (row['name']) {
final String name when name.trim().isNotEmpty => name,
@@ -65,6 +69,7 @@ class SuperTabPerson {
joinedVia = person.joinedVia,
avatar = person.avatar,
status = person.status,
+ timeZone = person.timeZone,
chosenUsername = person.chosenUsername,
name = person.name;
final String id, email, role;
@@ -88,6 +93,10 @@ class SuperTabPerson {
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
+ /// Their time zone's IANA name, as their own app told the Swarm
+ /// (local_time_zone.dart); null until it has, and from an older server.
+ final String? timeZone;
+
/// Their status while it lasts.
SuperTabPersonStatus? statusAt(DateTime now) =>
status?.shownAt(now) == true ? status : null;
diff --git a/desktop/lib/super_tabs/pane_layout.dart b/desktop/lib/super_tabs/pane_layout.dart
index f9985a74d..f17a70fb7 100644
--- a/desktop/lib/super_tabs/pane_layout.dart
+++ b/desktop/lib/super_tabs/pane_layout.dart
@@ -21,6 +21,7 @@ class SuperTabPaneLayout extends StatefulWidget {
this.right,
this.storage,
this.rightDefault = rightWidth,
+ this.over,
});
static const storageKey = 'super-tab-pane-widths';
@@ -51,6 +52,10 @@ class SuperTabPaneLayout extends StatefulWidget {
/// width, saved, wins): [threadWidth] while it shows a thread.
final double rightDefault;
+ /// Drawn over the left and centre panes, leaving the right one as it is:
+ /// the picture viewer beside an open thread, as in Slack (Huy, 11-04).
+ final Widget? over;
+
@override
State<SuperTabPaneLayout> createState() => _SuperTabPaneLayoutState();
}
@@ -225,6 +230,14 @@ class _SuperTabPaneLayoutState extends State<SuperTabPaneLayout> {
],
),
),
+ if (widget.over case final over?)
+ Positioned(
+ left: 0,
+ top: 0,
+ bottom: 0,
+ width: width - right,
+ child: over,
+ ),
],
);
},
diff --git a/desktop/lib/super_tabs/personal_lead.dart b/desktop/lib/super_tabs/personal_lead.dart
new file mode 100644
index 000000000..713d76764
--- /dev/null
+++ b/desktop/lib/super_tabs/personal_lead.dart
@@ -0,0 +1,302 @@
+import 'dart:async';
+
+import 'package:clock/clock.dart';
+import 'package:flutter/foundation.dart';
+
+import '../core/project_folder.dart';
+import '../state/app_state.dart';
+import '../state/new_harness.dart' show kLeadModel;
+import 'controller.dart';
+import 'launch.dart';
+import 'model.dart';
+import 'personal_projects.dart';
+
+/// How long a start this Desktop asked for, or saw another of the person's
+/// machines claim, shows as starting: the server's claim holds as long
+/// (backend leadStart.ts LEAD_CLAIM_MS).
+const kPersonalLeadStartWindow = Duration(minutes: 10);
+
+/// Where a project's Lead starts: the person's machine, its engine, and the
+/// repo's folder there, or null for a new folder in the Harness projects one.
+typedef PersonalLeadPlan = ({
+ String machineId,
+ String engine,
+ String? folder,
+ String projectName,
+});
+
+/// What this Desktop knows of a project chat's Lead start: starting since
+/// [at], or failed with [reason].
+@immutable
+class PersonalLeadStatus {
+ const PersonalLeadStatus.starting(this.at) : reason = null;
+ const PersonalLeadStatus.failed(String this.reason) : at = null;
+ final DateTime? at;
+ final String? reason;
+ bool get failed => reason != null;
+}
+
+/// A Personal Swarm project chat's Lead, started by this Desktop on the
+/// person's message there (task #2633, Huy 11-04: "Not sent, this chat has no
+/// Lead" was the first thing a new person met). Only Desktop knows a Personal
+/// project's folder (personal_projects.dart), so the Lead starts here, as Add
+/// a Lead's own-machine start does, without its form: on this computer, or
+/// the person's computer whose pane holds the project's repo, in that repo's
+/// folder, else in a new folder of the Harness projects folder. The server
+/// keeps the message for it, and one claim (lead.claim) keeps two of the
+/// person's Desktops from starting two. A Team Swarm starts nothing.
+class PersonalLeadStarter extends ChangeNotifier {
+ PersonalLeadStarter._(this.app);
+ static final _of = Expando<PersonalLeadStarter>();
+ static PersonalLeadStarter of(AppNotifier app) =>
+ _of[app] ??= PersonalLeadStarter._(app);
+
+ final AppNotifier app;
+ final _status = <String, PersonalLeadStatus>{};
+
+ /// The native start and join, in tests.
+ @visibleForTesting
+ static Future<void> Function(
+ SuperTabController c,
+ String conversationId,
+ PersonalLeadPlan plan,
+ )?
+ launchForTest;
+
+ String _key(SuperTabController c, String conversationId) =>
+ '${c.accountId}/${c.tabId}/$conversationId';
+
+ /// The start of [conversationId]'s Lead as this Desktop knows it: one
+ /// starting for longer than the claim holds is no longer shown.
+ PersonalLeadStatus? statusOf(SuperTabController c, String conversationId) {
+ final status = _status[_key(c, conversationId)];
+ if (status?.at case final at?
+ when clock.now().difference(at) >= kPersonalLeadStartWindow) {
+ return null;
+ }
+ return status;
+ }
+
+ /// Sets [conversationId]'s start as a test reads it.
+ @visibleForTesting
+ void setStatusForTest(
+ SuperTabController c,
+ String conversationId,
+ PersonalLeadStatus status,
+ ) => _set(_key(c, conversationId), status);
+
+ void _set(String key, PersonalLeadStatus status) {
+ _status[key] = status;
+ notifyListeners();
+ }
+
+ /// Whether a message sent in [conversationId] of [c] starts its project's
+ /// Lead: the signed-in person's own Personal Swarm, a project's chat, and no
+ /// Lead there.
+ bool wants(SuperTabController c, String conversationId) {
+ if (!PersonalProjects.of(app).eligible(c)) return false;
+ final snapshot = c.snapshot!;
+ final group = snapshot.conversation(conversationId);
+ if (group == null || group.archived || group.isBuddyChat) return false;
+ if (!snapshot.isProjectLead(conversationId)) return false;
+ final project = snapshot.projectFor(conversationId);
+ return project != null && snapshot.leadOf(project.id) == null;
+ }
+
+ /// Starts [conversationId]'s Lead after a message there, once: a start
+ /// already running here, or one another of the person's machines claimed,
+ /// is the one.
+ Future<void> start(SuperTabController c, String conversationId) async {
+ final key = _key(c, conversationId);
+ if (statusOf(c, conversationId) case final status? when !status.failed) {
+ return;
+ }
+ _set(key, PersonalLeadStatus.starting(clock.now()));
+ try {
+ final project = c.snapshot?.projectFor(conversationId);
+ if (project == null) {
+ throw const SuperTabFailure(
+ 'PROJECT_UNAVAILABLE',
+ 'this project is no longer available',
+ );
+ }
+ final plan = planFor(c, conversationId);
+ final claim = await c.request(
+ 'POST',
+ '/api/super-tabs/${Uri.encodeComponent(c.tabId)}/commands',
+ body: {
+ 'operationId': superTabOperationId(),
+ 'command': {
+ 'type': 'lead.claim',
+ 'projectId': project.id,
+ 'machineId': plan.machineId,
+ },
+ },
+ );
+ // Another of the person's machines starts it: its join ends the note.
+ if (superTabMap(claim['result'])['leadStart'] == 'waiting') return;
+ await (launchForTest ?? _launch)(c, conversationId, plan);
+ // Starting until the chat reads its Lead and the message's delivery.
+ unawaited(c.refresh().catchError((Object _) {}));
+ } on SuperTabFailure catch (failure) {
+ _set(key, PersonalLeadStatus.failed(_reason(failure)));
+ } catch (error) {
+ _set(key, PersonalLeadStatus.failed(_trim('$error')));
+ }
+ }
+
+ /// Where [conversationId]'s Lead starts, or throws why it cannot: the repo's
+ /// folder on this computer, else on the person's computer whose pane holds
+ /// it; with no repo, this computer, else another of theirs connected.
+ PersonalLeadPlan planFor(SuperTabController c, String conversationId) {
+ final project = c.snapshot!.projectFor(conversationId)!;
+ bool usable(MachineState? m) =>
+ m != null &&
+ !m.belongsToOtherAccount &&
+ !m.machine.isTeamAccount &&
+ !m.isOffline;
+ String? repoFolder(String machineId, String? agentId) {
+ final agent = app
+ .stateOf(machineId)
+ ?.agents
+ .where((a) => a.id == agentId)
+ .firstOrNull;
+ final where = agent?.project;
+ if (where == null ||
+ (normalizedRemote(where.repository) ??
+ normalizedRemote(where.remote)) ==
+ null) {
+ return null;
+ }
+ return where.root ?? where.cwd;
+ }
+
+ final machines = app.machineStates.values.where(usable).toList();
+ final local = machines.where((m) => m.isLocalMachine).firstOrNull;
+ final repos = [
+ for (final pane in PersonalProjects.of(app).panesFor(c, conversationId))
+ if (usable(app.stateOf(pane.machineId)))
+ if (repoFolder(pane.machineId, pane.agentId) case final folder?)
+ (machineId: pane.machineId, folder: folder),
+ ];
+ final repo =
+ repos
+ .where((r) => r.machineId == local?.machine.machineId)
+ .firstOrNull ??
+ repos.firstOrNull;
+ final machine = repo != null
+ ? app.stateOf(repo.machineId)!
+ : local ?? machines.firstOrNull;
+ if (machine == null) {
+ throw const SuperTabFailure(
+ 'NO_MACHINE',
+ 'none of your computers is online',
+ );
+ }
+ final engine = _engineOn(machine);
+ if (engine == null) {
+ throw SuperTabFailure(
+ 'NO_ENGINE',
+ 'Claude Code and Codex aren’t signed in on '
+ '${machine.machine.displayName}',
+ );
+ }
+ return (
+ machineId: machine.machine.machineId,
+ engine: engine,
+ folder: repo?.folder,
+ projectName: project.name,
+ );
+ }
+
+ /// Claude Code first, else Codex: one installed (or that installs on
+ /// start) and not signed out. An engine list not read yet tries Claude
+ /// Code, whose start then says what is missing.
+ String? _engineOn(MachineState machine) {
+ final engines = machine.engines;
+ if (!engines.loaded) return 'claude';
+ for (final engine in const ['claude', 'codex']) {
+ final known = engines[engine];
+ if (known != null &&
+ (known.installed || known.installable) &&
+ known.signedIn != false) {
+ return engine;
+ }
+ }
+ return null;
+ }
+
+ /// The Lead's own-machine start, as Add a Lead's New Harness runs it
+ /// (launch.dart): its journal, the native start, then its join as Lead.
+ Future<void> _launch(
+ SuperTabController c,
+ String conversationId,
+ PersonalLeadPlan plan,
+ ) async {
+ final tab = app.swarms.where((s) => s.superTabId == c.tabId).firstOrNull;
+ if (tab == null) {
+ throw const SuperTabFailure(
+ 'SWARM_UNAVAILABLE',
+ 'open your Personal Swarm in a tab first',
+ );
+ }
+ final integration = await SuperTabLaunch.open(app, tab, conversationId);
+ // A start of this chat's Lead from before is finished, not repeated.
+ if (integration.pending) {
+ await integration.resume!();
+ return;
+ }
+ final prompt = await integration.prepare(plan.machineId, '', plan.engine);
+ final attempt = AgentCreationAttempt(
+ background: true,
+ beforeSubmit: integration.beforeSubmit,
+ launchModel: plan.engine == 'claude'
+ ? (model: kLeadModel.model, effort: kLeadModel.effort)
+ : null,
+ );
+ integration
+ ..engine = plan.engine
+ ..folder = plan.folder;
+ final failure = await app.createAgent(
+ plan.machineId,
+ engine: plan.engine,
+ folder: plan.folder,
+ // A suggested name: a folder of it already there (an earlier start's)
+ // is numbered past, not refused.
+ projectFolder: plan.folder == null
+ ? ProjectFolderRequest.generated(
+ label: 'Lead',
+ at: clock.now(),
+ name: plan.projectName,
+ )
+ : null,
+ swarmId: tab.id,
+ permissionMode: integration.forcedPermissionMode,
+ swarmRole: integration.swarmRole,
+ swarmSkillMode: integration.swarmSkillMode,
+ prompt: prompt,
+ attempt: attempt,
+ );
+ if (failure != null) throw SuperTabFailure('CREATE_FAILED', failure);
+ final harnessId = attempt.agentId;
+ if (harnessId == null) {
+ throw const SuperTabFailure(
+ 'CREATE_FAILED',
+ 'the computer didn’t say which harness it started',
+ );
+ }
+ integration.launchModelRefused = attempt.launchModelRefused;
+ await integration.complete(plan.machineId, harnessId);
+ }
+
+ /// A failure in the receipt's words: an older server that does not know the
+ /// claim says so, any other its own reason, without a final full stop.
+ String _reason(SuperTabFailure failure) => failure.code == 'VALIDATION_ERROR'
+ ? 'this Swarm’s server needs an update'
+ : _trim(failure.message);
+
+ String _trim(String text) {
+ final line = text.trim().split('\n').first;
+ return line.endsWith('.') ? line.substring(0, line.length - 1) : line;
+ }
+}
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index 22838173b..30e33b368 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -5,6 +5,7 @@ import 'package:clock/clock.dart';
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kIsWeb;
+import 'package:clock/clock.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'
show RenderSliverMultiBoxAdaptor, SliverMultiBoxAdaptorParentData;
@@ -31,6 +32,7 @@ import 'roster.dart';
import 'recording_notice.dart';
import 'profile_actions.dart';
import 'live_card.dart';
+import 'personal_lead.dart';
import 'personal_projects.dart';
import 'private_project_lock.dart';
import 'pull_request_facts.dart';
@@ -41,6 +43,8 @@ import 'composer_newline.dart';
import 'composer_tags.dart';
import 'composer_toggle.dart';
import 'activity.dart';
+import 'attachment_chips.dart' show superTabShowsInPlace;
+import 'attachment_image.dart';
import 'activity_view.dart';
import 'attention.dart';
import 'controller.dart';
@@ -49,6 +53,9 @@ import 'dialog_scope.dart';
import 'folder_zip.dart';
import 'instructions_panel.dart';
import 'model.dart';
+import 'agent_details.dart';
+import 'identity.dart' show superTabMachineName;
+import 'identity_card.dart';
import 'prompt_alerts.dart';
import 'workgroup_name.dart';
import 'message_link.dart';
@@ -878,6 +885,13 @@ class _SuperTabViewState extends State<SuperTabView>
},
);
if (!mounted) return;
+ // In the person's Personal Swarm a project chat with no Lead starts one
+ // on their computer; the message waits for it (task #2633).
+ final app = widget.app;
+ if (result != null && app != null) {
+ final lead = PersonalLeadStarter.of(app);
+ if (lead.wants(c, id)) unawaited(lead.start(c, id));
+ }
if (newSession && result != null) _chatSessions.remove(id);
// Refused for New session, its text is back as the chat's draft: it shows
// in the box, ready to send without it, unless another chat is shown or
@@ -2198,6 +2212,62 @@ class _SuperTabViewState extends State<SuperTabView>
.toList() ??
const [];
+ /// What the card over [message]'s name or avatar shows, worked out as it
+ /// opens (Huy, 11-04): a person's status and zone; an agent's engine and
+ /// model, machine and task, as its details dialog reads them.
+ SuperTabIdentityFacts _identityFacts(
+ SuperTabMessage message,
+ SuperTabAgent? agent,
+ ) {
+ final name = c.snapshot?.authorName(message) ?? message.authorName;
+ if (agent == null) {
+ if (message.fromAgent) return SuperTabAgentFacts(name);
+ final person = _people[message.authorId];
+ return SuperTabPersonFacts(
+ person?.shownName ?? name,
+ status: person?.statusAt(clock.now()),
+ timeZone: person?.timeZone,
+ );
+ }
+ final info = SuperTabAgentInfo(c, widget.app, agent);
+ final place = c.snapshot?.placeOf(agent.machineId) ?? agent.machineId;
+ final device = superTabMap(
+ superTabMap(c.snapshot?.pool(place)?['observation'])['resources'],
+ )['deviceType'];
+ final group = info.taskGroup;
+ return SuperTabAgentFacts(
+ agent.displayName ?? name,
+ engine: agent.engine,
+ model: info.model,
+ machine: superTabMachineName(
+ info.machine ?? widget.machineName(agent.machineId),
+ ),
+ deviceType: device is String ? device : null,
+ task: group == null ? null : _taskLine(info, group),
+ onOpenTask: group == null ? null : () => _openGroup(group.id),
+ );
+ }
+
+ /// What the agent does with [group], its number and title in place of the
+ /// quoted title: "Working on #2605 Chat: a card…".
+ static String _taskLine(SuperTabAgentInfo info, SuperTabConversation group) {
+ final named = switch (group.number) {
+ final number? => '#$number ${group.title}',
+ null => group.title,
+ };
+ final status = info.status;
+ final quoted = '"${group.title}"';
+ return status != null && status.contains(quoted)
+ ? status.replaceFirst(quoted, named)
+ : named;
+ }
+
+ void _openGroup(String id) {
+ setState(() => _showPullRequests = false);
+ c.select(id);
+ c.selectTerminal(id, null);
+ }
+
void _openAgent(SuperTabAgent agent) {
setState(() {
_showPullRequests = _showTasks = false;
@@ -2250,19 +2320,7 @@ class _SuperTabViewState extends State<SuperTabView>
? c.snapshot?.projects.isEmpty == true
? c.snapshot!.name
: 'Choose a project'
- : c.snapshot!.isProjectLead(group.id)
- ? '${project!.isPrivate ? '' : '# '}${project.name}'
- // An older Buddy chat in a project says which, as the menu that opens
- // it does; the one Buddy chat is the sidebar's # buddy.
- : c.isEarlierBuddyChat(group)
- ? 'Earlier Buddy chat · ${c.snapshot!.projects.where((p) => p.id == group.projectId).firstOrNull?.name ?? 'a project'}'
- : _buddyName(group) == null
- ? null
- : group.isSwarmBuddyChat
- ? 'Buddy'
- : c.buddy(group.projectId) == null && group.buddyName == null
- ? 'Your Buddy'
- : '${_buddyName(group)} · Your Buddy';
+ : _groupName(group);
if (name == null) return SuperTabWorkgroupName(group!, style: style);
if (group != null &&
c.snapshot!.isProjectLead(group.id) &&
@@ -2298,6 +2356,106 @@ class _SuperTabViewState extends State<SuperTabView>
);
}
+ /// [group]'s name as the sidebar names it: "# openharness", a Buddy chat's;
+ /// null for a workgroup, named by [SuperTabWorkgroupName].
+ String? _groupName(SuperTabConversation group) =>
+ c.snapshot!.isProjectLead(group.id)
+ ? switch (c.snapshot!.projectFor(group.id)!) {
+ final project => '${project.isPrivate ? '' : '# '}${project.name}',
+ }
+ // An older Buddy chat in a project says which, as the menu that opens
+ // it does; the one Buddy chat is the sidebar's # buddy.
+ : c.isEarlierBuddyChat(group)
+ ? 'Earlier Buddy chat · ${c.snapshot!.projects.where((p) => p.id == group.projectId).firstOrNull?.name ?? 'a project'}'
+ : _buddyName(group) == null
+ ? null
+ : group.isSwarmBuddyChat
+ ? 'Buddy'
+ : c.buddy(group.projectId) == null && group.buddyName == null
+ ? 'Your Buddy'
+ : '${_buddyName(group)} · Your Buddy';
+
+ /// The pictures [messages] show in place, oldest first, each with its
+ /// sender as its row shows them and where it was posted, for the viewer.
+ List<SuperTabImageItem> _images(List<SuperTabMessage> messages) {
+ final group = c.selected;
+ final place = group == null
+ ? null
+ : _groupName(group) ?? SuperTabWorkgroupName.plain(group);
+ return [
+ for (final message in messages)
+ for (final file in message.attachments)
+ if (SuperTabFileRef(
+ file,
+ conversationId: message.conversationId,
+ messageId: message.id,
+ fresh: widget.controller.readFileLink,
+ )
+ case final ref when superTabShowsInPlace(ref))
+ SuperTabImageItem(
+ ref: ref,
+ sender: _shownAuthor(c, message),
+ avatar: superTabMessageAvatar(
+ message,
+ author: _shownAuthor(c, message),
+ agent: message.fromAgent
+ ? c.snapshot?.agent(message.authorId)
+ : null,
+ person: message.fromAgent ? null : _people[message.authorId],
+ size: _viewerAvatar,
+ ),
+ postedAt: message.createdAt,
+ place: place,
+ onShowInChat: () =>
+ unawaited(_openMessage(message.conversationId, message.id)),
+ ),
+ ];
+ }
+
+ static const _viewerAvatar = 32.0;
+
+ /// The pictures open in the viewer, in the conversation (and thread) they
+ /// were opened in; another one closes it.
+ ({
+ String? conversationId,
+ String? thread,
+ List<SuperTabImageItem> images,
+ int index,
+ })?
+ _viewing;
+
+ void _openImages(
+ List<SuperTabImageItem> images,
+ int index, {
+ String? thread,
+ }) => setState(
+ () => _viewing = (
+ conversationId: c.selectedId,
+ thread: thread,
+ images: images,
+ index: index,
+ ),
+ );
+
+ void _closeImages() => setState(() => _viewing = null);
+
+ /// The open viewer, while its conversation and thread still are.
+ Widget? _imageViewer() {
+ final viewing = _viewing;
+ if (viewing == null) return null;
+ if (viewing.conversationId != c.selectedId ||
+ (viewing.thread != null && c.openedThread?.root != viewing.thread)) {
+ _viewing = null;
+ return null;
+ }
+ return SuperTabImageViewer(
+ key: ObjectKey(viewing),
+ images: viewing.images,
+ index: viewing.index,
+ onClose: _closeImages,
+ );
+ }
+
/// The composer's hint, naming the open conversation as its sidebar row
/// does: "Message #openharness", "Message Wren".
String _messageHint(SuperTabConversation group) {
@@ -3279,6 +3437,7 @@ class _SuperTabViewState extends State<SuperTabView>
agent: agent,
person: message.fromAgent ? null : _people[message.authorId],
member: _member,
+ identity: grouped ? null : () => _identityFacts(message, agent),
onOpenAgent: agent == null ? null : () => _openAgent(agent),
machineName: agent == null ? null : widget.machineName(agent.machineId),
grouped: grouped,
@@ -3385,17 +3544,21 @@ class _SuperTabViewState extends State<SuperTabView>
if (open == null || open.conversationId != c.selectedId) return null;
final rows = c.threadMessages(open.root);
final byId = {for (final m in rows) m.id: m};
- return SuperTabThreadPanel(
- controller: c,
- root: open.root,
- row: (message, grouped) =>
- _message(message, grouped, byId, inThread: true),
- // The thread panel groups its own rows; one on its way keeps its name.
- outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),
- sessionActivity: (session) =>
- superTabSessionActivity(c, widget.app, session),
- machineName: widget.machineName,
- onScroll: (list) => _threadScroll = list,
+ return SuperTabImageGallery(
+ images: () => _images(rows),
+ thread: open.root,
+ child: SuperTabThreadPanel(
+ controller: c,
+ root: open.root,
+ row: (message, grouped) =>
+ _message(message, grouped, byId, inThread: true),
+ // The thread panel groups its own rows; one on its way keeps its name.
+ outgoing: (sent) => _outgoingRow(sent, byId, grouped: false),
+ sessionActivity: (session) =>
+ superTabSessionActivity(c, widget.app, session),
+ machineName: widget.machineName,
+ onScroll: (list) => _threadScroll = list,
+ ),
);
}
@@ -3590,9 +3753,14 @@ class _SuperTabViewState extends State<SuperTabView>
Expanded(child: Divider(color: DesktopChrome.rim)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
- child: Text(
- MaterialLocalizations.of(context).formatMediumDate(time.toLocal()),
- style: DesktopChrome.metadata(),
+ // The day pill takes its place once it reaches the pill.
+ child: SuperTabDayLabel(
+ day: time,
+ child: Text(
+ MaterialLocalizations.of(context)
+ .formatMediumDate(time.toLocal()),
+ style: DesktopChrome.metadata(),
+ ),
),
),
Expanded(child: Divider(color: DesktopChrome.rim)),
@@ -3805,7 +3973,18 @@ class _SuperTabViewState extends State<SuperTabView>
padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 8),
child: Row(
children: [
- Expanded(child: Text(c.error!, style: DesktopChrome.control())),
+ // A Swarm that was read and now cannot be (a backend or this
+ // computer's Harness restarting) keeps what it shows and says
+ // so quietly; it reads again by itself (task #2647).
+ Expanded(
+ child: c.backendUnreachable && c.snapshot != null
+ ? Text(
+ 'Reconnecting…',
+ key: const ValueKey('super-reconnecting'),
+ style: DesktopChrome.metadata(),
+ )
+ : Text(c.error!, style: DesktopChrome.control()),
+ ),
if (!c.accessRevoked && !c.updateRequired)
TextButton(
onPressed: () => unawaited(c.refresh()),
@@ -4511,7 +4690,7 @@ class _SuperTabViewState extends State<SuperTabView>
_syncThreadPane();
return SuperTabFiles(
fresh: widget.controller.readFileLink,
- child: _swarm(context),
+ child: SuperTabImageStage(open: _openImages, child: _swarm(context)),
);
}
@@ -4526,6 +4705,7 @@ class _SuperTabViewState extends State<SuperTabView>
final wide =
constraints.maxWidth >= MediaQuery.textScalerOf(context).scale(1080);
final thread = _threadPanel();
+ final viewer = _imageViewer();
// A thread opened since Members takes its side and closes it.
if (thread != null) _rosterOpen = false;
final threadDrawer = thread != null && !wide;
@@ -4583,6 +4763,8 @@ class _SuperTabViewState extends State<SuperTabView>
rightDefault: thread == null
? SuperTabPaneLayout.rightWidth
: SuperTabPaneLayout.threadWidth,
+ // Over the chat, beside an open thread, as in Slack.
+ over: wide ? viewer : null,
center: Column(
children: [
_header(c.selected, narrow),
@@ -4615,7 +4797,10 @@ class _SuperTabViewState extends State<SuperTabView>
? 5
: 0,
children: [
- _conversation(narrow),
+ SuperTabImageGallery(
+ images: () => _images(_shownMessages(c.selectedId)),
+ child: _conversation(narrow),
+ ),
terminal ?? const SizedBox.shrink(),
_showPullRequests
? SuperTabPullRequests(
@@ -4753,6 +4938,9 @@ class _SuperTabViewState extends State<SuperTabView>
),
),
),
+ // Without a thread beside the chat, over the whole window.
+ if (!wide && viewer != null)
+ Positioned.fill(child: BlockSemantics(child: viewer)),
],
),
);
diff --git a/desktop/lib/super_tabs/zone_time.dart b/desktop/lib/super_tabs/zone_time.dart
new file mode 100644
index 000000000..eff09f813
--- /dev/null
+++ b/desktop/lib/super_tabs/zone_time.dart
@@ -0,0 +1,37 @@
+import 'package:flutter/material.dart';
+import 'package:timezone/data/latest_10y.dart' deferred as zones;
+import 'package:timezone/timezone.dart' as tz;
+
+Future<void>? _zonesLoading;
+var _zonesLoaded = false;
+
+/// The zone table, read once, the first time a card needs it: deferred, so
+/// a browser downloads it then rather than with the app.
+Future<void> superTabLoadZones() => _zonesLoading ??= zones
+ .loadLibrary()
+ .then((_) => zones.initializeTimeZones())
+ .then((_) => _zonesLoaded = true);
+
+/// Whether [superTabTimeNow] can answer yet.
+bool get superTabZonesLoaded => _zonesLoaded;
+
+/// The time of day in [zone] (an IANA name, "Asia/Ho_Chi_Minh") at [now],
+/// daylight saving included, once the table is loaded. Null for no zone, or
+/// one the table lacks: the card then shows no time rather than a guess
+/// (Huy, 11-04).
+TimeOfDay? superTabTimeNow(String? zone, DateTime now) {
+ if (zone == null || !_zonesLoaded) return null;
+ try {
+ final there = tz.TZDateTime.from(now, tz.getLocation(zone));
+ return TimeOfDay(hour: there.hour, minute: there.minute);
+ } on tz.LocationNotFoundException {
+ return null;
+ }
+}
+
+/// [superTabTimeNow], loading the table first.
+Future<TimeOfDay?> superTabTimeIn(String? zone, DateTime now) async {
+ if (zone == null) return null;
+ await superTabLoadZones();
+ return superTabTimeNow(zone, now);
+}
diff --git a/desktop/pubspec.lock b/desktop/pubspec.lock
index b81dbc78b..b6fbfd0c0 100644
--- a/desktop/pubspec.lock
+++ b/desktop/pubspec.lock
@@ -660,6 +660,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.7.12"
+ timezone:
+ dependency: "direct main"
+ description:
+ name: timezone
+ sha256: "9f4e5a1a0e4fef7dd3424842c0575db01bfb7a11730e8d55753fcd5c5c98767b"
+ url: "https://pub.dev"
+ source: hosted
+ version: "0.11.2"
typed_data:
dependency: transitive
description:
diff --git a/desktop/pubspec.yaml b/desktop/pubspec.yaml
index cd4016c1a..bab709740 100644
--- a/desktop/pubspec.yaml
+++ b/desktop/pubspec.yaml
@@ -104,6 +104,10 @@ dependencies:
# Dart, no native plugin, so the macOS SPM package list is unchanged.
re_editor: ^0.10.0
re_highlight: ^0.0.3
+ # The Dart team's IANA zone table: the local time on a person's card in the
+ # Swarm chat (super_tabs/zone_time.dart), daylight saving included. Pure
+ # Dart; its 10-year data is a deferred import, out of the web's first load.
+ timezone: ^0.11.2
dev_dependencies:
flutter_test:
diff --git a/desktop/test/super_tab_day_pill_test.dart b/desktop/test/super_tab_day_pill_test.dart
index 407621b3d..dfa7745db 100644
--- a/desktop/test/super_tab_day_pill_test.dart
+++ b/desktop/test/super_tab_day_pill_test.dart
@@ -87,16 +87,16 @@ String? _pill(WidgetTester tester, Key key) {
return tester.widget<Text>(text.first).data;
}
-ScrollController _chatScroll(WidgetTester tester) => tester
- .widget<CustomScrollView>(
- find.byWidgetPredicate(
- (w) =>
- w is CustomScrollView &&
- w.key is PageStorageKey &&
- '${(w.key as PageStorageKey).value}'.startsWith('super-messages-'),
- ),
- )
- .controller!;
+/// The chat's message list.
+final _chatList = find.byWidgetPredicate(
+ (w) =>
+ w is CustomScrollView &&
+ w.key is PageStorageKey &&
+ '${(w.key as PageStorageKey).value}'.startsWith('super-messages-'),
+);
+
+ScrollController _chatScroll(WidgetTester tester) =>
+ tester.widget<CustomScrollView>(_chatList).controller!;
ScrollController _threadScroll(WidgetTester tester) => tester
.widget<ListView>(
@@ -143,6 +143,70 @@ String _rowInView(WidgetTester tester, {double margin = 200}) {
throw StateError('no message row in view');
}
+/// The chat's day lines saying [day] that are painted: neither hidden nor
+/// faded out under the pill.
+Iterable<Rect> _dayLines(WidgetTester tester, String day) sync* {
+ for (final element
+ in find.descendant(of: _chatList, matching: find.text(day)).evaluate()) {
+ var painted = true;
+ element.visitAncestorElements((ancestor) {
+ final widget = ancestor.widget;
+ if (widget is Visibility && !widget.visible ||
+ widget is Opacity && widget.opacity == 0) {
+ painted = false;
+ }
+ return painted && widget is! CustomScrollView;
+ });
+ final box = element.renderObject;
+ if (!painted || box is! RenderBox || !box.attached) continue;
+ yield box.localToGlobal(Offset.zero) & box.size;
+ }
+}
+
+/// At this place in the chat, one label at most says each day where the
+/// pill is: no day line under the pill, none repeating the pill's day.
+void _oneLabel(WidgetTester tester, List<String> days, String where) {
+ final pill = find.byKey(_chatPill);
+ if (pill.evaluate().isEmpty) return;
+ final shown = _pill(tester, _chatPill);
+ final rect = tester.getRect(pill);
+ for (final day in days) {
+ for (final line in _dayLines(tester, day)) {
+ expect(
+ line.overlaps(rect),
+ isFalse,
+ reason:
+ '$where: the "$day" day line at $line is under the pill at $rect',
+ );
+ expect(
+ day,
+ isNot(shown),
+ reason: '$where: the pill and a day line at $line both say "$day"',
+ );
+ }
+ }
+}
+
+/// The chat scrolled so that Tuesday's day line sits [offset] pixels from
+/// the list's top.
+Future<void> _tuesdayLineAt(
+ WidgetTester tester,
+ ScrollController scroll,
+ String tuesday,
+ double offset,
+) async {
+ final listTop = tester.getTopLeft(_chatList).dy;
+ for (var i = 0; i < 4; i++) {
+ final line = _dayLines(tester, tuesday).firstOrNull;
+ if (line == null) break;
+ await _scrollTo(
+ tester,
+ scroll,
+ scroll.position.pixels + line.top - listTop - offset,
+ );
+ }
+}
+
Future<void> _open(
WidgetTester tester,
SuperTabController c, {
@@ -176,6 +240,20 @@ Future<double> _scrollBackTo(
return start - scroll.position.pixels;
}
+/// Writes what [picture] shows to [name].png in [shots], when it is set.
+Future<void> _shoot(WidgetTester tester, GlobalKey picture, String name) async {
+ if (shots == null) return;
+ await tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()! as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/$name.png').writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+}
+
void main() {
setUpAll(() async {
if (shots != null) await loadPreviewFonts();
@@ -285,6 +363,57 @@ void main() {
await c.flush();
});
+ testWidgets('scrolling across a day line never shows two day labels '
+ 'where the pill is', (tester) async {
+ final c = _twoDays().controller();
+ addTearDown(c.dispose);
+ await _open(tester, c);
+ final tuesday = _day(tester, _tuesday), monday = _day(tester, _monday);
+ final days = [monday, tuesday];
+ final scroll = _chatScroll(tester);
+
+ // Monday at the top, Tuesday's day line a little below the pill.
+ await _scrollBackTo(tester, scroll, _chatPill, monday);
+ await _tuesdayLineAt(tester, scroll, tuesday, 80);
+ expect(_pill(tester, _chatPill), monday);
+ final start = scroll.position.pixels;
+
+ // Down past it two pixels at a time: the line meets the pill and the
+ // pill takes its place, then back up.
+ for (var moved = 0.0; moved <= 140; moved += 2) {
+ await _scrollTo(tester, scroll, start + moved);
+ _oneLabel(tester, days, 'down $moved');
+ }
+ expect(_pill(tester, _chatPill), tuesday);
+ for (var moved = 140.0; moved >= 0; moved -= 2) {
+ await _scrollTo(tester, scroll, start + moved);
+ _oneLabel(tester, days, 'up $moved');
+ }
+ expect(_pill(tester, _chatPill), monday);
+ // Below the pill, Tuesday's line says its day again.
+ expect(_dayLines(tester, tuesday), isNotEmpty);
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
+ testWidgets("the day line's place keeps its size while the pill takes it", (
+ tester,
+ ) async {
+ final c = _twoDays().controller();
+ addTearDown(c.dispose);
+ await _open(tester, c);
+ final tuesday = _day(tester, _tuesday), monday = _day(tester, _monday);
+ final scroll = _chatScroll(tester);
+ await _scrollBackTo(tester, scroll, _chatPill, monday);
+ await _tuesdayLineAt(tester, scroll, tuesday, 80);
+ final row = _rowInView(tester, margin: 300), before = _topOf(tester, row);
+ await _scrollTo(tester, scroll, scroll.position.pixels + 70);
+ expect(_pill(tester, _chatPill), tuesday);
+ expect(_topOf(tester, row) - before, moreOrLessEquals(-70, epsilon: .5));
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+
for (final brightness in Brightness.values) {
testWidgets('screenshots for review (${brightness.name})', (tester) async {
final picture = GlobalKey();
@@ -309,21 +438,30 @@ void main() {
await tester.pumpAndSettle();
// Written before the checks, so main's run writes the "before" image.
- if (shots != null) {
- await tester.runAsync(() async {
- final boundary =
- picture.currentContext!.findRenderObject()!
- as RenderRepaintBoundary;
- final image = await boundary.toImage(pixelRatio: 1.5);
- final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
- await Directory(shots!).create(recursive: true);
- await File('$shots/day-pill-${brightness.name}.png')
- .writeAsBytes(bytes!.buffer.asUint8List());
- image.dispose();
- });
- }
+ await _shoot(tester, picture, 'day-pill-${brightness.name}');
expect(_pill(tester, _chatPill), monday);
expect(_pill(tester, _threadPill), _day(tester, _tuesday));
+
+ // Tuesday's day line half under the pill (Huy 11-04): one label,
+ // on a fill nothing reads through.
+ final tuesday = _day(tester, _tuesday);
+ await _tuesdayLineAt(tester, scroll, tuesday, 22);
+ await tester.pumpAndSettle();
+ await _shoot(tester, picture, 'day-pill-over-line-${brightness.name}');
+ _oneLabel(tester, [monday, tuesday], brightness.name);
+ for (final key in [_chatPill, _threadPill]) {
+ final fill = tester
+ .widget<DecoratedBox>(
+ find
+ .descendant(
+ of: find.byKey(key),
+ matching: find.byType(DecoratedBox),
+ )
+ .first,
+ )
+ .decoration;
+ expect((fill as ShapeDecoration).color!.a, 1.0);
+ }
await tester.pumpWidget(const SizedBox());
await c.flush();
});
diff --git a/desktop/test/super_tab_file_links_test.dart b/desktop/test/super_tab_file_links_test.dart
index 9065472b1..32840593e 100644
--- a/desktop/test/super_tab_file_links_test.dart
+++ b/desktop/test/super_tab_file_links_test.dart
@@ -471,7 +471,7 @@ void main() {
await tester.pumpAndSettle();
expect(server.fileLinkReads, hasLength(1));
expect(opened, [Uri.parse(_signed('p1', 'shot.png', sig: 'later'))]);
- await tester.tap(find.text('Close'));
+ await tester.tap(find.byKey(const ValueKey('super-image-close')));
await tester.pumpAndSettle();
await close(tester, c);
});
diff --git a/desktop/test/super_tab_first_read_test.dart b/desktop/test/super_tab_first_read_test.dart
index e32df32b7..a4169374e 100644
--- a/desktop/test/super_tab_first_read_test.dart
+++ b/desktop/test/super_tab_first_read_test.dart
@@ -281,6 +281,101 @@ void main() {
},
);
+ group('a restart refuses reads for a while (task #2647)', () {
+ const refusals = [
+ SuperTabFailure(
+ 'NOT_FOUND',
+ 'This Super Tab is unavailable.',
+ statusCode: 404,
+ ),
+ SuperTabFailure(
+ 'FORBIDDEN',
+ 'You cannot read this Swarm.',
+ statusCode: 403,
+ ),
+ ];
+
+ test('while the list still has the Swarm, or cannot be read, it stays '
+ 'open with its state and name, says Reconnecting, and reads again', () {
+ fakeAsync((async) {
+ final server = ConversationServer()..state['name'] = 'autonomous.ai';
+ final daemon = _Daemon(server);
+ Object? listFailure;
+ var asked = 0;
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: daemon.call,
+ save: server.save,
+ reading: SuperTabReading.desktop,
+ stillListed: () async {
+ asked++;
+ if (listFailure case final failure?) throw failure;
+ return true;
+ },
+ )..start();
+ async.elapse(const Duration(seconds: 1));
+ expect(c.snapshot?.name, 'autonomous.ai');
+
+ daemon.failure = _unreachable;
+ async.elapse(const Duration(seconds: 4));
+ expect(c.backendUnreachable, isTrue);
+ expect(asked, 0, reason: 'a dropped read asks nothing');
+
+ for (final unreadable in [true, false]) {
+ listFailure = unreadable ? _unreachable : null;
+ for (final refusal in refusals) {
+ daemon.failure = refusal;
+ async.elapse(const Duration(seconds: 4));
+ final when =
+ '${refusal.code}, list ${unreadable ? 'unreadable' : 'has it'}';
+ expect(c.accessRevoked, isFalse, reason: when);
+ expect(c.snapshot?.name, 'autonomous.ai', reason: when);
+ expect(c.backendUnreachable, isTrue, reason: when);
+ }
+ }
+ expect(asked, greaterThan(0));
+
+ daemon.failure = null;
+ async.elapse(const Duration(seconds: 4));
+ expect(c.backendUnreachable, isFalse);
+ expect(c.error, isNull);
+ expect(c.snapshot?.name, 'autonomous.ai');
+ c.dispose();
+ });
+ });
+
+ test('once a list read that answered leaves it out, the refusal takes '
+ 'the Swarm away as before', () {
+ fakeAsync((async) {
+ final server = ConversationServer();
+ final daemon = _Daemon(server);
+ final c = SuperTabController(
+ tabId: 'tab',
+ accountId: 'owner',
+ request: daemon.call,
+ save: server.save,
+ reading: SuperTabReading.desktop,
+ stillListed: () async => false,
+ )..start();
+ async.elapse(const Duration(seconds: 1));
+ expect(c.snapshot, isNotNull);
+ daemon.failure = refusals.first;
+ async.elapse(const Duration(seconds: 4));
+ expect(c.accessRevoked, isTrue);
+ expect(c.snapshot, isNull);
+ final reads = daemon.states;
+ async.elapse(const Duration(seconds: 30));
+ expect(
+ daemon.states,
+ reads,
+ reason: 'a Swarm taken away reads nothing',
+ );
+ c.dispose();
+ });
+ });
+ });
+
testWidgets('the pill says Connecting until a read has been answered', (
tester,
) async {
diff --git a/desktop/test/super_tab_identity_card_shots_test.dart b/desktop/test/super_tab_identity_card_shots_test.dart
new file mode 100644
index 000000000..3edc268c3
--- /dev/null
+++ b/desktop/test/super_tab_identity_card_shots_test.dart
@@ -0,0 +1,170 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:clock/clock.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/identity_card.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/zone_time.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_CARD_SHOTS'];
+
+final _now = DateTime.utc(2026, 11, 4, 8, 42);
+
+/// The chat as Huy sees it (11-04): his message and an agent's, the agent
+/// working on this task on 0xken15's MacBook Pro.
+ConversationServer _server() {
+ final server = ConversationServer();
+ final state = server.state;
+ (state['people'] as List).add({
+ 'id': 'huy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'name': 'Huy Pham',
+ 'status': {'text': 'Out of office', 'emoji': '🌴'},
+ 'timeZone': 'Asia/Ho_Chi_Minh',
+ });
+ (state['agents'] as List).add({
+ 'id': 'shrike2',
+ 'name': 'Shrike2',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude', 'model': 'claude-opus-5-5'},
+ });
+ state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'MacbookPro.local',
+ 'observation': {
+ 'resources': {'deviceType': 'MacBook Pro'},
+ },
+ },
+ ];
+ ((state['conversations'] as List)[1] as Map)
+ ..['title'] = 'Chat: a card on hover over a name or avatar'
+ ..['number'] = 2605
+ ..['agentIds'] = ['shrike2']
+ ..['assignment'] = {'id': 'w1', 'agentId': 'shrike2', 'status': 'working'};
+ void say(String text, Map<String, Object> author, int minutesAgo) {
+ server.append(text);
+ server.messages.last
+ ..['author'] = author
+ ..['createdAt'] = _now
+ .subtract(Duration(minutes: minutesAgo))
+ .toIso8601String();
+ }
+
+ say('Can the card show where the agent runs?', {
+ 'kind': 'person',
+ 'id': 'huy',
+ 'name': '[email protected]',
+ }, 9);
+ say('Yes: its machine, engine and model, and its task.', {
+ 'kind': 'agent',
+ 'id': 'shrike2',
+ 'name': 'Shrike2',
+ }, 2);
+ return server;
+}
+
+void main() {
+ setUpAll(() async {
+ if (shots == null) return;
+ await superTabLoadZones();
+ await loadPreviewFonts();
+ // The status emoji, drawn as a Mac draws it: the system face lacks it
+ // and the theme falls back through Helvetica Neue.
+ const emoji = '/System/Library/Fonts/Apple Color Emoji.ttc';
+ if (File(emoji).existsSync()) {
+ final bytes = File(emoji).readAsBytesSync();
+ await (FontLoader(
+ 'Helvetica Neue',
+ )..addFont(Future.value(ByteData.view(bytes.buffer)))).load();
+ }
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('identity card screenshots (${brightness.name})', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final picture = GlobalKey();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(1100, 620));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ addTearDown(mouse.removePointer);
+
+ Future<void> shot(String name) => tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 2);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/card-$name-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+
+ final server = _server();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.pumpWidget(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'MacbookPro.local',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ Finder inRow(int index, Finder matching) => find.descendant(
+ of: find.byKey(
+ ValueKey('super-message-${server.messages[index]['id']}'),
+ ),
+ matching: matching,
+ );
+
+ Future<void> hover(Finder target, String name) async {
+ await mouse.moveTo(tester.getCenter(target));
+ await tester.pump(SuperTabHoverCard.openDelay);
+ await tester.pumpAndSettle();
+ await shot(name);
+ await mouse.moveTo(Offset.zero);
+ await tester.pump(SuperTabHoverCard.closeDelay);
+ await tester.pumpAndSettle();
+ }
+
+ await hover(inRow(0, find.text('Huy Pham')), 'person');
+ await hover(inRow(1, find.byType(SuperTabAvatar)), 'agent');
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ });
+ }, skip: shots == null);
+ }
+}
diff --git a/desktop/test/super_tab_identity_card_test.dart b/desktop/test/super_tab_identity_card_test.dart
new file mode 100644
index 000000000..40a16192e
--- /dev/null
+++ b/desktop/test/super_tab_identity_card_test.dart
@@ -0,0 +1,241 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/identity_card.dart';
+import 'package:harness/super_tabs/profile_model.dart';
+import 'package:harness/super_tabs/zone_time.dart';
+
+/// Huy (11-04): hovering a name or avatar shows a small card, like Slack's.
+final _now = DateTime.utc(2026, 11, 4, 8, 42);
+
+const _status = SuperTabPersonStatus(text: 'Out of office', emoji: '🌴');
+
+Widget _host(Widget child) => MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: Padding(padding: const EdgeInsets.all(40), child: child),
+ ),
+ ),
+);
+
+final _card = find.byKey(const ValueKey('super-identity-card'));
+
+/// A name that takes focus, as the chat's names do, under a hover card.
+Widget _anchor(
+ SuperTabIdentityFacts facts, {
+ FocusNode? focus,
+ VoidCallback? onTap,
+}) => _host(
+ Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SuperTabHoverCard(
+ facts: () => facts,
+ child: InkWell(
+ focusNode: focus,
+ onTap: onTap ?? () {},
+ child: const Text('Huy Pham', key: ValueKey('name')),
+ ),
+ ),
+ const SizedBox(height: 400),
+ const Text('elsewhere', key: ValueKey('elsewhere')),
+ ],
+ ),
+);
+
+Future<TestGesture> _mouse(WidgetTester tester) async {
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ addTearDown(mouse.removePointer);
+ return mouse;
+}
+
+void main() {
+ setUpAll(superTabLoadZones);
+
+ testWidgets('a person’s card shows name, status and local time', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ await tester.pumpWidget(
+ _host(
+ const SuperTabIdentityCard(
+ facts: SuperTabPersonFacts(
+ 'Huy Pham',
+ status: _status,
+ timeZone: 'Asia/Ho_Chi_Minh',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ });
+ expect(find.text('Huy Pham'), findsOneWidget);
+ expect(find.text('Out of office'), findsOneWidget);
+ expect(find.text('🌴'), findsOneWidget);
+ expect(find.text('3:42 PM local time'), findsOneWidget);
+ });
+
+ testWidgets('a person’s card leaves out a time it does not know', (
+ tester,
+ ) async {
+ for (final zone in [null, 'Mars/Base']) {
+ await tester.pumpWidget(
+ _host(
+ SuperTabIdentityCard(
+ facts: SuperTabPersonFacts('Huy Pham', timeZone: zone),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ expect(find.text('Huy Pham'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-identity-card-time')),
+ findsNothing,
+ );
+ }
+ });
+
+ testWidgets('an agent’s card shows engine and model, machine and task', (
+ tester,
+ ) async {
+ var opened = 0;
+ await tester.pumpWidget(
+ _host(
+ SuperTabIdentityCard(
+ facts: SuperTabAgentFacts(
+ 'Shrike2',
+ engine: 'claude',
+ model: 'Opus 5.5',
+ machine: 'MacbookPro.local',
+ task: 'Working on #2605 Chat: a card',
+ onOpenTask: () => opened++,
+ ),
+ ),
+ ),
+ );
+ expect(find.text('Shrike2'), findsOneWidget);
+ expect(find.text('Claude Opus 5.5'), findsOneWidget);
+ expect(find.text('MacbookPro.local'), findsOneWidget);
+ await tester.tap(find.byKey(const ValueKey('super-identity-card-task')));
+ expect(opened, 1);
+ });
+
+ testWidgets('opens after the hover delay, not before', (tester) async {
+ await tester.pumpWidget(_anchor(const SuperTabPersonFacts('Huy Pham')));
+ final mouse = await _mouse(tester);
+ await mouse.moveTo(tester.getCenter(find.byKey(const ValueKey('name'))));
+ await tester.pump(const Duration(milliseconds: 400));
+ expect(_card, findsNothing);
+ await tester.pump(const Duration(milliseconds: 150));
+ expect(_card, findsOneWidget);
+ });
+
+ testWidgets('closes when the pointer leaves', (tester) async {
+ await tester.pumpWidget(_anchor(const SuperTabPersonFacts('Huy Pham')));
+ final mouse = await _mouse(tester);
+ await mouse.moveTo(tester.getCenter(find.byKey(const ValueKey('name'))));
+ await tester.pump(SuperTabHoverCard.openDelay);
+ expect(_card, findsOneWidget);
+ await mouse.moveTo(
+ tester.getCenter(find.byKey(const ValueKey('elsewhere'))),
+ );
+ await tester.pump(SuperTabHoverCard.closeDelay);
+ await tester.pump();
+ expect(_card, findsNothing);
+ });
+
+ testWidgets('stays open while the pointer crosses into the card', (
+ tester,
+ ) async {
+ await tester.pumpWidget(_anchor(const SuperTabPersonFacts('Huy Pham')));
+ final mouse = await _mouse(tester);
+ await mouse.moveTo(tester.getCenter(find.byKey(const ValueKey('name'))));
+ await tester.pump(SuperTabHoverCard.openDelay);
+ // Through the gap under the name, then onto the card.
+ final name = tester.getRect(find.byKey(const ValueKey('name')));
+ await mouse.moveTo(name.bottomLeft + const Offset(4, 3));
+ await tester.pump(const Duration(milliseconds: 50));
+ await mouse.moveTo(tester.getCenter(_card));
+ await tester.pump(const Duration(seconds: 1));
+ expect(_card, findsOneWidget);
+ });
+
+ testWidgets('keyboard focus opens it and Escape closes it, focus kept', (
+ tester,
+ ) async {
+ final focus = FocusNode();
+ addTearDown(focus.dispose);
+ await tester.pumpWidget(
+ _anchor(const SuperTabPersonFacts('Huy Pham'), focus: focus),
+ );
+ focus.requestFocus();
+ await tester.pump();
+ expect(_card, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(_card, findsNothing);
+ expect(focus.hasPrimaryFocus, isTrue);
+ });
+
+ testWidgets(
+ 'Escape on the task line closes the card and returns to the name',
+ (tester) async {
+ final focus = FocusNode();
+ addTearDown(focus.dispose);
+ await tester.pumpWidget(
+ _anchor(
+ SuperTabAgentFacts(
+ 'Shrike2',
+ engine: 'claude',
+ task: 'Working on #2605 Chat: a card',
+ onOpenTask: () {},
+ ),
+ focus: focus,
+ ),
+ );
+ focus.requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(focus.hasPrimaryFocus, isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await tester.pump(SuperTabHoverCard.openDelay);
+ expect(_card, findsNothing);
+ expect(focus.hasPrimaryFocus, isTrue);
+ },
+ );
+
+ testWidgets('Tab reaches the task line and Enter opens the task', (
+ tester,
+ ) async {
+ final focus = FocusNode();
+ addTearDown(focus.dispose);
+ var opened = 0;
+ await tester.pumpWidget(
+ _anchor(
+ SuperTabAgentFacts(
+ 'Shrike2',
+ engine: 'claude',
+ task: 'Working on #2605 Chat: a card',
+ onOpenTask: () => opened++,
+ ),
+ focus: focus,
+ ),
+ );
+ focus.requestFocus();
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ // The task line holds focus: Enter on it, not on the name, opens it.
+ expect(focus.hasPrimaryFocus, isFalse);
+ expect(_card, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
+ expect(opened, 1);
+ });
+}
diff --git a/desktop/test/super_tab_identity_card_view_test.dart b/desktop/test/super_tab_identity_card_view_test.dart
new file mode 100644
index 000000000..7911a9e4b
--- /dev/null
+++ b/desktop/test/super_tab_identity_card_view_test.dart
@@ -0,0 +1,233 @@
+import 'package:clock/clock.dart';
+import 'package:flutter/gestures.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/identity.dart';
+import 'package:harness/super_tabs/identity_card.dart';
+import 'package:harness/super_tabs/view.dart';
+import 'package:harness/super_tabs/zone_time.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Huy (11-04): hovering a name or avatar in the chat shows who it is. A
+/// person: name, status, local time. An agent: engine and model, machine,
+/// and its task, which opens that task's chat.
+final _now = DateTime.utc(2026, 11, 4, 8, 42);
+final _card = find.byKey(const ValueKey('super-identity-card'));
+
+const _dee = {'kind': 'person', 'id': 'dee', 'name': '[email protected]'};
+const _shrike = {'kind': 'agent', 'id': 'shrike2', 'name': 'Shrike2'};
+
+ConversationServer _server({bool assigned = true}) {
+ final server = ConversationServer();
+ final state = server.state;
+ (state['people'] as List).add({
+ 'id': 'dee',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'name': 'Dee Tran',
+ 'status': {'text': 'Out of office', 'emoji': '🌴'},
+ 'timeZone': 'Asia/Ho_Chi_Minh',
+ });
+ (state['agents'] as List).add({
+ 'id': 'shrike2',
+ 'name': 'Shrike2',
+ 'machineId': 'm',
+ 'harnessId': 'h',
+ 'contributorId': 'owner',
+ 'configuration': {'engine': 'claude', 'model': 'claude-opus-5-5'},
+ });
+ state['machines'] = [
+ {
+ 'machineId': 'm',
+ 'name': 'MacbookPro.local',
+ 'observation': {
+ 'resources': {'deviceType': 'MacBook Pro'},
+ },
+ },
+ ];
+ final task = (state['conversations'] as List)[1] as Map;
+ task['number'] = 2605;
+ task['agentIds'] = ['shrike2'];
+ if (assigned) {
+ task['assignment'] = {
+ 'id': 'w1',
+ 'agentId': 'shrike2',
+ 'status': 'working',
+ };
+ }
+ return server;
+}
+
+void _say(ConversationServer server, String text, Map<String, Object> author) {
+ server.append(text);
+ server.messages.last
+ ..['author'] = author
+ ..['createdAt'] = _now.toIso8601String();
+}
+
+Future<SuperTabController> _open(
+ WidgetTester tester,
+ ConversationServer server,
+) async {
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await tester.binding.setSurfaceSize(const Size(1280, 860));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ return c;
+}
+
+Future<TestGesture> _hover(WidgetTester tester, Finder target) async {
+ final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
+ await mouse.addPointer(location: Offset.zero);
+ addTearDown(mouse.removePointer);
+ await mouse.moveTo(tester.getCenter(target));
+ await tester.pump(SuperTabHoverCard.openDelay);
+ await tester.pump();
+ return mouse;
+}
+
+Finder _inRow(String messageId, Finder matching) => find.descendant(
+ of: find.byKey(ValueKey('super-message-$messageId')),
+ matching: matching,
+);
+
+void main() {
+ setUpAll(superTabLoadZones);
+
+ testWidgets('hovering a person’s name shows their card with local time', (
+ tester,
+ ) async {
+ await withClock(Clock.fixed(_now), () async {
+ final server = _server();
+ _say(server, 'Can the card show where the agent runs?', _dee);
+ await _open(tester, server);
+ final id = server.messages.last['id'] as String;
+ await _hover(tester, _inRow(id, find.text('Dee Tran')));
+ expect(_card, findsOneWidget);
+ final card = find.descendant(of: _card, matching: find.byType(Text));
+ final words = tester.widgetList<Text>(card).map((t) => t.data).toList();
+ expect(words, contains('Out of office'));
+ expect(words, contains('3:42 PM local time'));
+ });
+ });
+
+ testWidgets(
+ 'hovering an agent’s avatar shows its machine, model and task, and the task opens its chat',
+ (tester) async {
+ final server = _server();
+ _say(
+ server,
+ 'Yes: its machine, engine and model, and its task.',
+ _shrike,
+ );
+ final c = await _open(tester, server);
+ final id = server.messages.last['id'] as String;
+ await _hover(tester, _inRow(id, find.byType(SuperTabAvatar)));
+ expect(_card, findsOneWidget);
+ expect(
+ find.descendant(of: _card, matching: find.text('Claude Opus 5.5')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(of: _card, matching: find.text('MacbookPro')),
+ findsOneWidget,
+ );
+ final task = find.byKey(const ValueKey('super-identity-card-task'));
+ expect(
+ find.descendant(
+ of: task,
+ matching: find.textContaining('#2605 Offline editing'),
+ ),
+ findsOneWidget,
+ );
+ await tester.tap(task);
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ expect(_card, findsNothing);
+ },
+ );
+
+ testWidgets(
+ 'Tab from an agent’s name in the chat reaches its task line, and Enter opens the task (Osprey, test step)',
+ (tester) async {
+ final server = _server();
+ _say(server, 'Keyboard, please.', _shrike);
+ final c = await _open(tester, server);
+ // Tab through the chat until the name's card opens.
+ for (var tabs = 0; _card.evaluate().isEmpty && tabs < 80; tabs++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ expect(_card, findsOneWidget);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ await tester.pump(SuperTabHoverCard.openDelay);
+ expect(_card, findsOneWidget, reason: 'Tab from the name closed it');
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pumpAndSettle();
+ expect(c.selectedId, 'offline');
+ },
+ );
+
+ testWidgets('Shift-Tab from the task line returns to the name', (
+ tester,
+ ) async {
+ final server = _server();
+ _say(server, 'Keyboard, please.', _shrike);
+ await _open(tester, server);
+ for (var tabs = 0; _card.evaluate().isEmpty && tabs < 80; tabs++) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ }
+ final name = FocusManager.instance.primaryFocus;
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(FocusManager.instance.primaryFocus, isNot(name));
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.pump();
+ expect(FocusManager.instance.primaryFocus, name);
+ expect(_card, findsOneWidget);
+ });
+
+ testWidgets('a grouped line has no card', (tester) async {
+ final server = _server();
+ _say(server, 'First line', _dee);
+ _say(server, 'Second line', _dee);
+ await _open(tester, server);
+ final id = server.messages.last['id'] as String;
+ expect(_inRow(id, find.byType(SuperTabHoverCard)), findsNothing);
+ });
+
+ testWidgets('no task line without a readable task', (tester) async {
+ final server = _server(assigned: false);
+ _say(server, 'Idle for now.', _shrike);
+ await _open(tester, server);
+ final id = server.messages.last['id'] as String;
+ await _hover(tester, _inRow(id, find.byType(SuperTabAvatar)));
+ expect(_card, findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-identity-card-task')),
+ findsNothing,
+ );
+ });
+}
diff --git a/desktop/test/super_tab_image_viewer_shots_test.dart b/desktop/test/super_tab_image_viewer_shots_test.dart
new file mode 100644
index 000000000..87856fca3
--- /dev/null
+++ b/desktop/test/super_tab_image_viewer_shots_test.dart
@@ -0,0 +1,180 @@
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/super_tabs/attachment_viewer.dart';
+import 'package:harness/super_tabs/view.dart';
+
+import 'box_render_preview_test.dart' show loadPreviewFonts;
+import 'support/super_tab_fixture.dart';
+
+/// Set to a folder to write the PR's screenshots there.
+final shots = Platform.environment['SUPER_TAB_IMAGE_SHOTS'];
+
+/// A 1440×900 stand-in for a pasted screenshot: a window with a sidebar.
+Future<ui.Image> _screenshot() async {
+ final recorder = ui.PictureRecorder();
+ final canvas = Canvas(recorder);
+ canvas
+ ..drawRect(
+ const Rect.fromLTWH(0, 0, 1440, 900),
+ Paint()..color = const Color(0xFFF2F4F8),
+ )
+ ..drawRect(
+ const Rect.fromLTWH(0, 0, 320, 900),
+ Paint()..color = const Color(0xFF2B3442),
+ );
+ for (var i = 0; i < 6; i++) {
+ canvas.drawRRect(
+ RRect.fromLTRBR(
+ 400,
+ 80.0 + i * 120,
+ 1360,
+ 160.0 + i * 120,
+ const Radius.circular(16),
+ ),
+ Paint()..color = const Color(0xFFDCE3EE),
+ );
+ }
+ return recorder.endRecording().toImage(1440, 900);
+}
+
+/// The chat's picture viewer as the PR shows it (Huy, 11-04): opened from the
+/// chat while a thread is open beside it, in both appearances.
+void main() {
+ setUpAll(() async {
+ if (shots != null) await loadPreviewFonts();
+ });
+
+ for (final brightness in Brightness.values) {
+ testWidgets('screenshots for review (${brightness.name})', (tester) async {
+ final png = (await tester.runAsync(() async {
+ final image = await _screenshot();
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ return data!.buffer.asUint8List();
+ }))!;
+ final original = attachmentImage;
+ attachmentImage = (_) => MemoryImage(png);
+ addTearDown(() => attachmentImage = original);
+
+ final picture = GlobalKey();
+ final server = ConversationServer()..threads = true;
+ (server.state['people'] as List).add({
+ 'id': 'huy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ });
+ const pm = {
+ 'kind': 'agent',
+ 'id': 'pm',
+ 'name': 'Lead',
+ 'displayName': 'River',
+ };
+ const huy = {'kind': 'person', 'id': 'huy', 'name': '[email protected]'};
+ final now = DateTime.now().toUtc();
+ void say(
+ String text,
+ Map<String, Object> author, {
+ String? thread,
+ List<Map<String, Object>> files = const [],
+ Duration ago = Duration.zero,
+ }) {
+ server.append(text, attachments: files);
+ server.messages.last
+ ..['author'] = author
+ ..['createdAt'] = now.subtract(ago).toIso8601String();
+ if (thread != null) {
+ server.messages.last
+ ..['thread'] = thread
+ ..['replyTo'] = thread;
+ }
+ }
+
+ Map<String, Object> file(String id, String name) => {
+ 'id': id,
+ 'name': name,
+ 'mime': 'image/png',
+ 'size': 182 * 1024,
+ 'url': 'https://cdn.harness.autonomous.ai/$id/$name',
+ };
+
+ say(
+ 'The viewer covers the thread. Slack keeps it open:',
+ huy,
+ ago: const Duration(days: 14),
+ files: [file('a1', 'slack-viewer.png')],
+ );
+ say(
+ 'Here is ours today.',
+ huy,
+ ago: const Duration(days: 14),
+ files: [file('a2', 'harness-viewer.png')],
+ );
+ say('I will build it like that.', pm, thread: 'message-1');
+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';
+ final c = server.controller(account: 'huy');
+ addTearDown(c.dispose);
+ await c.refresh();
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);
+ await tester.binding.setSurfaceSize(const Size(1440, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: brightness),
+ builder: (context, child) =>
+ RepaintBoundary(key: picture, child: child),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: c,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Mac Studio',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+
+ Future<void> shot(String name) => tester.runAsync(() async {
+ final boundary =
+ picture.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary;
+ final image = await boundary.toImage(pixelRatio: 1.5);
+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/image-viewer-$name-${brightness.name}.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+
+ await tester.tap(
+ find.byKey(const ValueKey('super-thread-line-message-1')),
+ );
+ await tester.pumpAndSettle();
+ // The chat's picture; the thread shows its root's too.
+ await tester.tap(
+ find.byKey(const ValueKey('super-attachment-inline:a1')).first,
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+ await shot('open');
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(
+ find.byKey(const ValueKey('super-attachment-image:a1')),
+ findsNothing,
+ );
+ await tester.pumpWidget(const SizedBox());
+ await c.flush();
+ }, skip: shots == null);
+ }
+}
diff --git a/desktop/test/super_tab_image_viewer_test.dart b/desktop/test/super_tab_image_viewer_test.dart
new file mode 100644
index 000000000..34067e15b
--- /dev/null
+++ b/desktop/test/super_tab_image_viewer_test.dart
@@ -0,0 +1,400 @@
+// A chat's picture opens as Slack opens one (Huy, 11-04): over a dark veil,
+// its sender, when and where at the top left, previous and next through the
+// other pictures, rotate and zoom at the bottom left, Download, Open in
+// browser and More at the bottom right; Esc or a click outside closes it.
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/attachment_image.dart';
+import 'package:harness/super_tabs/attachment_upload.dart';
+import 'package:harness/super_tabs/attachment_viewer.dart';
+import 'package:harness/super_tabs/file_links.dart';
+import 'package:harness/super_tabs/model.dart';
+
+/// A [width]×[height] PNG, drawn for real so a picture has a shape to keep.
+Future<Uint8List> _png(WidgetTester tester, int width, int height) async =>
+ (await tester.runAsync(() async {
+ final recorder = ui.PictureRecorder();
+ Canvas(recorder).drawRect(
+ Rect.fromLTWH(0, 0, width.toDouble(), height.toDouble()),
+ Paint()..color = const Color(0xFF3060A0),
+ );
+ final image = await recorder.endRecording().toImage(width, height);
+ final data = await image.toByteData(format: ui.ImageByteFormat.png);
+ return data!.buffer.asUint8List();
+ }))!;
+
+SuperTabImageItem _item(
+ String id, {
+ String sender = 'Huy',
+ Duration ago = const Duration(days: 14, hours: 1),
+ String place = '# openharness',
+ VoidCallback? onShowInChat,
+}) => SuperTabImageItem(
+ ref: SuperTabFileRef(
+ SuperTabAttachment.fromJson({
+ 'id': id,
+ 'name': '$id.png',
+ 'mime': 'image/png',
+ 'size': 120 * 1024,
+ 'url': 'https://cdn.harness.autonomous.ai/$id/$id.png',
+ }),
+ ),
+ sender: sender,
+ avatar: SizedBox.square(key: ValueKey('avatar-$sender'), dimension: 32),
+ postedAt: DateTime.now().subtract(ago),
+ place: place,
+ onShowInChat: onShowInChat,
+);
+
+void main() {
+ late ImageProvider Function(Uri) original;
+ late Uint8List png;
+
+ setUp(() => original = attachmentImage);
+ tearDown(() => attachmentImage = original);
+
+ Finder picture(String id) =>
+ find.byKey(ValueKey('super-attachment-image:$id'));
+ Finder button(String name) => find.byKey(ValueKey('super-image-$name'));
+
+ /// The viewer over a 1100×800 window, at [index] of [images].
+ Future<List<int>> open(
+ WidgetTester tester,
+ List<SuperTabImageItem> images, {
+ int index = 0,
+ }) async {
+ png = await _png(tester, 720, 360);
+ attachmentImage = (_) => MemoryImage(png);
+ await tester.binding.setSurfaceSize(const Size(1100, 800));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ final closed = <int>[];
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabImageViewer(
+ images: images,
+ index: index,
+ onClose: () => closed.add(1),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+ return closed;
+ }
+
+ double scale(WidgetTester tester) => tester
+ .widget<InteractiveViewer>(find.byType(InteractiveViewer))
+ .transformationController!
+ .value
+ .getMaxScaleOnAxis();
+
+ int turns(WidgetTester tester, String id) => tester
+ .widget<RotatedBox>(
+ find.ancestor(of: picture(id), matching: find.byType(RotatedBox)),
+ )
+ .quarterTurns;
+
+ group('previous and next', () {
+ testWidgets('the arrows page through the pictures, none past the ends', (
+ tester,
+ ) async {
+ await open(tester, [_item('a1'), _item('a2'), _item('a3')]);
+ expect(picture('a1'), findsOneWidget);
+ expect(button('previous'), findsNothing);
+
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ expect(picture('a2'), findsOneWidget);
+ expect(picture('a1'), findsNothing);
+ expect(button('previous'), findsOneWidget);
+
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ expect(picture('a3'), findsOneWidget);
+ expect(button('next'), findsNothing);
+
+ await tester.tap(button('previous'));
+ await tester.pumpAndSettle();
+ expect(picture('a2'), findsOneWidget);
+ });
+
+ testWidgets('the Left and Right keys do the same', (tester) async {
+ await open(tester, [_item('a1'), _item('a2'), _item('a3')], index: 1);
+ expect(picture('a2'), findsOneWidget);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
+ await tester.pumpAndSettle();
+ expect(picture('a3'), findsOneWidget);
+ // The last stays the last.
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);
+ await tester.pumpAndSettle();
+ expect(picture('a3'), findsOneWidget);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pumpAndSettle();
+ expect(picture('a1'), findsOneWidget);
+ });
+
+ testWidgets('one picture alone has no arrows', (tester) async {
+ await open(tester, [_item('a1')]);
+ expect(button('previous'), findsNothing);
+ expect(button('next'), findsNothing);
+ });
+
+ testWidgets('the header follows the picture shown', (tester) async {
+ await open(tester, [
+ _item('a1'),
+ _item('a2', sender: 'River', ago: const Duration(minutes: 5)),
+ ]);
+ expect(find.text('Huy'), findsOneWidget);
+ expect(
+ find.text('14 days ago in # openharness · a1.png'),
+ findsOneWidget,
+ );
+ expect(find.byKey(const ValueKey('avatar-Huy')), findsOneWidget);
+
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ expect(find.text('River'), findsOneWidget);
+ expect(
+ find.text('5 minutes ago in # openharness · a2.png'),
+ findsOneWidget,
+ );
+ });
+ });
+
+ group('zoom and rotate', () {
+ testWidgets('plus and minus step the zoom by 25%, shown beside it', (
+ tester,
+ ) async {
+ await open(tester, [_item('a1')]);
+ expect(find.text('100%'), findsOneWidget);
+ expect(scale(tester), 1);
+
+ await tester.tap(button('zoom-in'));
+ await tester.pumpAndSettle();
+ expect(find.text('125%'), findsOneWidget);
+ expect(scale(tester), closeTo(1.25, 1e-9));
+ expect(tester.widget<Slider>(button('zoom')).value, 1.25);
+
+ await tester.tap(button('zoom-out'));
+ await tester.tap(button('zoom-out'));
+ await tester.pumpAndSettle();
+ // 100% is the least.
+ expect(find.text('100%'), findsOneWidget);
+ expect(scale(tester), closeTo(1, 1e-9));
+ });
+
+ testWidgets('the slider zooms up to 400%', (tester) async {
+ await open(tester, [_item('a1')]);
+ await tester.drag(button('zoom'), const Offset(400, 0));
+ await tester.pumpAndSettle();
+ expect(find.text('400%'), findsOneWidget);
+ expect(scale(tester), closeTo(4, 1e-9));
+
+ await tester.tap(button('zoom-in'));
+ await tester.pumpAndSettle();
+ expect(find.text('400%'), findsOneWidget);
+ });
+
+ testWidgets('rotate turns a quarter each click', (tester) async {
+ await open(tester, [_item('a1')]);
+ expect(turns(tester, 'a1'), 0);
+ await tester.tap(button('rotate'));
+ await tester.pumpAndSettle();
+ expect(turns(tester, 'a1'), 1);
+ await tester.tap(button('rotate'));
+ await tester.pumpAndSettle();
+ expect(turns(tester, 'a1'), 2);
+ });
+
+ testWidgets('the next picture starts unturned at 100%', (tester) async {
+ await open(tester, [_item('a1'), _item('a2')]);
+ await tester.tap(button('rotate'));
+ await tester.tap(button('zoom-in'));
+ await tester.pumpAndSettle();
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ expect(turns(tester, 'a2'), 0);
+ expect(find.text('100%'), findsOneWidget);
+ expect(scale(tester), closeTo(1, 1e-9));
+ });
+ });
+
+ group('closing', () {
+ testWidgets('Esc closes it', (tester) async {
+ final closed = await open(tester, [_item('a1')]);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(closed, [1]);
+ });
+
+ testWidgets('a click on the veil closes it, on the picture does not', (
+ tester,
+ ) async {
+ final closed = await open(tester, [_item('a1'), _item('a2')]);
+ await tester.tap(picture('a1'));
+ await tester.tap(button('next'));
+ await tester.tap(button('rotate'));
+ await tester.pump();
+ expect(closed, isEmpty);
+
+ // Beside the picture, below the header.
+ await tester.tapAt(const Offset(120, 200));
+ await tester.pump();
+ expect(closed, [1]);
+ });
+
+ // Lynx's test of #2892: minus at 100% closed it, the click falling
+ // through to the veil.
+ testWidgets('a click on the bars, a control at its end included, leaves '
+ 'it open', (tester) async {
+ final closed = await open(tester, [_item('a1')]);
+ await tester.tap(button('zoom-out'));
+ await tester.tap(find.text('100%'));
+ await tester.tap(find.text('Huy'));
+ await tester.drag(button('zoom'), const Offset(400, 0));
+ await tester.pumpAndSettle();
+ await tester.tap(button('zoom-in'));
+ await tester.pump();
+ expect(find.text('400%'), findsOneWidget);
+ expect(closed, isEmpty);
+ });
+
+ testWidgets('× closes it', (tester) async {
+ final closed = await open(tester, [_item('a1')]);
+ await tester.tap(button('close'));
+ await tester.pump();
+ expect(closed, [1]);
+ });
+ });
+
+ group('actions', () {
+ testWidgets('Download and Open in browser stay, and Close is ×', (
+ tester,
+ ) async {
+ await open(tester, [_item('a1')]);
+ expect(find.text('Download'), findsOneWidget);
+ expect(find.text('Open in browser'), findsOneWidget);
+ expect(find.text('Close'), findsNothing);
+ });
+
+ testWidgets('More holds Show in chat, which closes the viewer', (
+ tester,
+ ) async {
+ var shown = 0;
+ final closed = await open(tester, [
+ _item('a1', onShowInChat: () => shown++),
+ ]);
+ await tester.tap(find.byTooltip('More'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Show in chat'));
+ await tester.pumpAndSettle();
+ expect(shown, 1);
+ expect(closed, [1]);
+ });
+ });
+
+ group('links', () {
+ final now = DateTime.utc(2026, 11, 4, 3);
+ setUp(() => superTabFileClock = () => now);
+ tearDown(() => superTabFileClock = DateTime.now);
+
+ String signed(String id, {String sig = '1'}) =>
+ 'https://$kSuperTabFilesHost/bucket/super-tabs/tab/$id/$id.png'
+ '?X-Goog-Signature=$sig';
+
+ /// [id]'s picture whose signed link ended a minute ago; [fresh] answers
+ /// the ask for another.
+ SuperTabImageItem ended(
+ String id,
+ Future<SuperTabAttachment> Function() fresh,
+ ) => SuperTabImageItem(
+ ref: SuperTabFileRef(
+ SuperTabAttachment.fromJson({
+ 'id': id,
+ 'name': '$id.png',
+ 'mime': 'image/png',
+ 'size': 120 * 1024,
+ 'url': 'https://cdn.harness.autonomous.ai/$id/$id.png',
+ 'link': signed(id),
+ 'expiresAt': now.millisecondsSinceEpoch - 60000,
+ }),
+ conversationId: 'lead',
+ messageId: 'message-$id',
+ fresh: (_, _, _) => fresh(),
+ ),
+ sender: 'Huy',
+ );
+
+ testWidgets('a later picture whose link ended is drawn from a fresh one', (
+ tester,
+ ) async {
+ var asked = 0;
+ final drawn = <Uri>[];
+ await open(tester, [
+ _item('a1'),
+ ended('a2', () async {
+ asked++;
+ return SuperTabAttachment.fromJson({
+ 'id': 'a2',
+ 'name': 'a2.png',
+ 'mime': 'image/png',
+ 'size': 120 * 1024,
+ 'url': 'https://cdn.harness.autonomous.ai/a2/a2.png',
+ 'link': signed('a2', sig: 'fresh'),
+ 'expiresAt': now.millisecondsSinceEpoch + 900000,
+ });
+ }),
+ ]);
+ attachmentImage = (url) {
+ drawn.add(url);
+ return MemoryImage(png);
+ };
+ // Asked for only once it is shown.
+ expect(asked, 0);
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+ expect(asked, 1);
+ expect(picture('a2'), findsOneWidget);
+ expect(drawn, [Uri.parse(signed('a2', sig: 'fresh'))]);
+ });
+
+ testWidgets('one with no fresh link says it can’t be shown', (
+ tester,
+ ) async {
+ await open(tester, [
+ _item('a1'),
+ ended('a2', () async => throw StateError('offline')),
+ ]);
+ await tester.tap(button('next'));
+ await tester.pumpAndSettle();
+ expect(picture('a2'), findsNothing);
+ expect(find.text('This image can’t be shown here.'), findsOneWidget);
+ // Its place still reads, and the way back still works.
+ expect(find.textContaining('a2.png'), findsOneWidget);
+ await tester.tap(button('previous'));
+ await tester.pumpAndSettle();
+ expect(picture('a1'), findsOneWidget);
+ });
+ });
+
+ test('times read in words', () {
+ expect(superTabPostedAgo(const Duration(seconds: 20)), 'just now');
+ expect(superTabPostedAgo(const Duration(minutes: 1)), '1 minute ago');
+ expect(superTabPostedAgo(const Duration(minutes: 5)), '5 minutes ago');
+ expect(superTabPostedAgo(const Duration(hours: 1)), '1 hour ago');
+ expect(superTabPostedAgo(const Duration(hours: 3)), '3 hours ago');
+ expect(superTabPostedAgo(const Duration(days: 1)), '1 day ago');
+ expect(superTabPostedAgo(const Duration(days: 14)), '14 days ago');
+ });
+}
diff --git a/desktop/test/super_tab_launch_test.dart b/desktop/test/super_tab_launch_test.dart
index d1cc2258b..2ae4a0955 100644
--- a/desktop/test/super_tab_launch_test.dart
+++ b/desktop/test/super_tab_launch_test.dart
@@ -89,6 +89,9 @@ class SuperTabFixtureConnection extends WsConn {
bool nativeSurface = false;
bool failFiles = false, failCreation = false, changeAccountOnUpload = false;
+ /// The code a [failCreation] failure names, as a daemon's refusal does.
+ String? failCreationCode;
+
/// The machine's Claude Code takes no model or effort flags: refused before
/// any receipt, as the daemon does (`LAUNCH_MODEL_UNSUPPORTED`).
bool refuseLaunchModel = false;
@@ -390,7 +393,10 @@ class SuperTabFixtureConnection extends WsConn {
return {
'creationId': payload['creationId'],
'state': 'failed',
- 'failure': {'detail': 'Fixture engine unavailable'},
+ 'failure': {
+ 'detail': 'Fixture engine unavailable',
+ 'code': ?failCreationCode,
+ },
};
}
return {
diff --git a/desktop/test/super_tab_message_media_test.dart b/desktop/test/super_tab_message_media_test.dart
index 544b97d57..150257b2d 100644
--- a/desktop/test/super_tab_message_media_test.dart
+++ b/desktop/test/super_tab_message_media_test.dart
@@ -11,6 +11,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/attachment_upload.dart';
import 'package:harness/super_tabs/attachment_viewer.dart';
import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/thread_panel.dart';
import 'package:harness/super_tabs/view.dart';
import 'support/super_tab_fixture.dart';
@@ -211,7 +212,7 @@ void main() {
find.byKey(const ValueKey('super-attachment-inline:a1')),
);
await tester.pumpAndSettle();
- final viewer = find.byKey(const ValueKey('super-attachment-viewer:a1'));
+ final viewer = find.byKey(const ValueKey('super-attachment-viewer'));
expect(viewer, findsOneWidget);
expect(tester.getSize(viewer), const Size(1100, 800));
expect(
@@ -220,7 +221,7 @@ void main() {
);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Open in browser'), findsOneWidget);
- await tester.tap(find.text('Close'));
+ await tester.tap(find.byKey(const ValueKey('super-image-close')));
await tester.pumpAndSettle();
expect(viewer, findsNothing);
await close(tester, c);
@@ -276,6 +277,221 @@ void main() {
});
});
+ group('the viewer over the chat', () {
+ /// A chat of two pictures, [a1] in message-1 and [a2] in message-2, and
+ /// a reply to message-1 carrying [a3], in a window [size] wide, with
+ /// message-1's thread open.
+ Future<SuperTabController> chat(
+ WidgetTester tester, {
+ Size size = const Size(1400, 900),
+ }) async {
+ pictures['a1.png'] = await _png(tester, 720, 360);
+ pictures['a2.png'] = await _png(tester, 360, 720);
+ pictures['a3.png'] = await _png(tester, 400, 400);
+ final server = ConversationServer()..threads = true;
+ server
+ ..append('First', attachments: [_file('a1', 'a1.png', 'image/png')])
+ ..append('Second', attachments: [_file('a2', 'a2.png', 'image/png')])
+ ..append(
+ 'In the thread',
+ attachments: [_file('a3', 'a3.png', 'image/png')],
+ );
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1';
+ final controller = server.controller();
+ await controller.refresh();
+ await tester.binding.setSurfaceSize(size);
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SuperTabView(
+ controller: controller,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ machineName: (_) => 'Test Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(
+ find.byKey(const ValueKey('super-thread-line-message-1')),
+ );
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+ return controller;
+ }
+
+ final viewer = find.byKey(const ValueKey('super-attachment-viewer'));
+ final thread = find.byType(SuperTabThreadPanel);
+ Finder picture(String id) =>
+ find.byKey(ValueKey('super-attachment-image:$id'));
+ Finder inline(String id) =>
+ find.byKey(ValueKey('super-attachment-inline:$id'));
+ Finder button(String name) => find.byKey(ValueKey('super-image-$name'));
+
+ Future<void> settle(WidgetTester tester) async {
+ await tester.pumpAndSettle();
+ await tester.runAsync(() => Future<void>.delayed(Durations.short2));
+ await tester.pumpAndSettle();
+ }
+
+ testWidgets('it covers the chat and leaves the open thread beside it', (
+ tester,
+ ) async {
+ final c = await chat(tester);
+ // The chat's a1; the thread shows its root's too.
+ await tester.tap(
+ find
+ .descendant(of: find.byType(SuperTabView), matching: inline('a1'))
+ .first,
+ );
+ await settle(tester);
+ expect(viewer, findsOneWidget);
+ final over = tester.getRect(viewer), beside = tester.getRect(thread);
+ expect(over.left, 0);
+ expect(over.right, lessThanOrEqualTo(beside.left));
+ expect(over.height, 900);
+ expect(thread.hitTestable(), findsOneWidget);
+ // Its sender, when and where.
+ expect(
+ find.descendant(of: viewer, matching: find.text('You')),
+ findsOneWidget,
+ );
+ expect(
+ find.descendant(
+ of: viewer,
+ matching: find.textContaining(' ago in # Pilot · a1.png'),
+ ),
+ findsOneWidget,
+ );
+ await close(tester, c);
+ });
+
+ testWidgets("from the chat it pages through the chat's pictures only", (
+ tester,
+ ) async {
+ final c = await chat(tester);
+ await tester.tap(inline('a1').first);
+ await settle(tester);
+ expect(picture('a1'), findsOneWidget);
+ await tester.tap(button('next'));
+ await settle(tester);
+ expect(picture('a2'), findsOneWidget);
+ // The thread's reply is not in the chat.
+ expect(button('next'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets("from the thread it pages through the thread's pictures only", (
+ tester,
+ ) async {
+ final c = await chat(tester);
+ await tester.tap(find.descendant(of: thread, matching: inline('a3')));
+ await settle(tester);
+ expect(picture('a3'), findsOneWidget);
+ expect(button('next'), findsNothing);
+ await tester.tap(button('previous'));
+ await settle(tester);
+ // The thread's root, not the chat's other picture.
+ expect(picture('a1'), findsOneWidget);
+ expect(button('previous'), findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('Esc closes it and keeps the thread', (tester) async {
+ final c = await chat(tester);
+ await tester.tap(inline('a2'));
+ await settle(tester);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(viewer, findsNothing);
+ expect(thread, findsOneWidget);
+ await close(tester, c);
+ });
+
+ testWidgets('what is typed while it is open never reaches the composer, '
+ 'and the composer has the keys again once it closes', (tester) async {
+ final c = await chat(tester);
+ final composer = find.byKey(const ValueKey('super-message-composer'));
+ EditableText field() => tester.widget<EditableText>(
+ find.descendant(of: composer, matching: find.byType(EditableText)),
+ );
+ await tester.tap(composer);
+ await tester.pumpAndSettle();
+ expect(field().focusNode.hasFocus, isTrue);
+
+ await tester.tap(inline('a2'));
+ await settle(tester);
+ expect(field().focusNode.hasFocus, isFalse);
+ await tester.sendKeyEvent(LogicalKeyboardKey.keyX);
+ await tester.sendKeyEvent(LogicalKeyboardKey.space);
+ await tester.pump();
+ expect(field().controller.text, isEmpty);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(viewer, findsNothing);
+ expect(field().focusNode.hasFocus, isTrue);
+ await close(tester, c);
+ });
+
+ testWidgets("closing the thread closes its picture's viewer", (
+ tester,
+ ) async {
+ final c = await chat(tester);
+ await tester.tap(find.descendant(of: thread, matching: inline('a3')));
+ await settle(tester);
+ expect(viewer, findsOneWidget);
+ c.closeThread();
+ await settle(tester);
+ expect(viewer, findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('Show in chat closes it', (tester) async {
+ final c = await chat(tester);
+ await tester.tap(inline('a2'));
+ await settle(tester);
+ await tester.tap(
+ find.descendant(of: viewer, matching: find.byTooltip('More')),
+ );
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Show in chat'));
+ await settle(tester);
+ expect(viewer, findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('another conversation closes it', (tester) async {
+ final c = await chat(tester);
+ await tester.tap(inline('a2'));
+ await settle(tester);
+ expect(viewer, findsOneWidget);
+ await c.select('offline');
+ await settle(tester);
+ expect(viewer, findsNothing);
+ await close(tester, c);
+ });
+
+ testWidgets('with the thread as a drawer it covers the window, and Esc '
+ 'closes it, not the drawer', (tester) async {
+ final c = await chat(tester, size: const Size(900, 800));
+ await tester.tap(find.descendant(of: thread, matching: inline('a3')));
+ await settle(tester);
+ expect(tester.getRect(viewer), const Rect.fromLTWH(0, 0, 900, 800));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pumpAndSettle();
+ expect(viewer, findsNothing);
+ expect(thread, findsOneWidget);
+ await close(tester, c);
+ });
+ });
+
testWidgets('other files are one compact chip each: name · size', (
tester,
) async {
diff --git a/desktop/test/super_tab_personal_lead_shots_test.dart b/desktop/test/super_tab_personal_lead_shots_test.dart
new file mode 100644
index 000000000..168600109
--- /dev/null
+++ b/desktop/test/super_tab_personal_lead_shots_test.dart
@@ -0,0 +1,63 @@
+import 'dart:io';
+
+import 'package:clock/clock.dart';
+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/personal_lead.dart';
+
+import 'super_tab_receipt_test.dart' show ReceiptFixture;
+import 'support/capture.dart';
+import 'swarm_state_test.dart' show createApp;
+
+/// Set to a folder to write the PR's pictures of a Personal project's Lead
+/// starting, and failing to, under the person's message (task #2633, for Huy).
+final _shots = Platform.environment['PERSONAL_LEAD_SHOTS'];
+
+void main() {
+ setUpAll(() => loadCaptureFonts(_shots));
+
+ for (final brightness in Brightness.values) {
+ for (final failed in [false, true]) {
+ final name =
+ 'personal-lead-${failed ? 'failed' : 'starting'}-${brightness.name}';
+ testWidgets(name, (tester) async {
+ if (_shots == null) return;
+ final previous = grid.AppTheme.brightness.value;
+ grid.AppTheme.brightness.value = brightness;
+ addTearDown(() => grid.AppTheme.brightness.value = previous);
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final f = ReceiptFixture(tester, status: null);
+ await f.show(
+ app: app,
+ brightness: brightness,
+ prepare: () {
+ (f.server.state['conversations'] as List).first['leadId'] = null;
+ f.message['text'] = 'Make the landing page dark by default.';
+ },
+ );
+ PersonalLeadStarter.of(app).setStatusForTest(
+ f.controller,
+ 'lead',
+ failed
+ ? const PersonalLeadStatus.failed(
+ 'Claude Code and Codex aren’t signed in on Studio',
+ )
+ : PersonalLeadStatus.starting(clock.now()),
+ );
+ // A still mark: the spinner never settles.
+ tester.platformDispatcher.accessibilityFeaturesTestValue =
+ const FakeAccessibilityFeatures(disableAnimations: true);
+ addTearDown(
+ tester.platformDispatcher.clearAccessibilityFeaturesTestValue,
+ );
+ await tester.pump();
+ await captureWindow(tester, _shots, name);
+ await tester.pumpWidget(const SizedBox());
+ await f.controller.flush();
+ f.controller.dispose();
+ });
+ }
+ }
+}
diff --git a/desktop/test/super_tab_personal_lead_test.dart b/desktop/test/super_tab_personal_lead_test.dart
new file mode 100644
index 000000000..3b2dbed85
--- /dev/null
+++ b/desktop/test/super_tab_personal_lead_test.dart
@@ -0,0 +1,192 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/core/models.dart';
+import 'package:harness/core/project_folder.dart';
+import 'package:harness/state/swarm.dart';
+import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/super_tabs/controller.dart';
+import 'package:harness/super_tabs/personal_lead.dart';
+import 'package:harness/super_tabs/personal_projects.dart';
+import 'package:harness/super_tabs/swarm_switcher.dart';
+
+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;
+
+// Huy, 11-04 (task #2633): in his Personal Swarm, a message in # Games, which
+// had no Lead, said "Not sent, this chat has no Lead". Now Desktop starts the
+// project's Lead on his own computer, in the repo's folder when the project has
+// a repo, and the message waits for it on the server.
+
+Agent _agent(String id, {String? remote, required String cwd}) => Agent(
+ id: id,
+ name: 'Agent $id',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(
+ name: cwd.split('/').last,
+ cwd: cwd,
+ root: remote == null ? null : cwd,
+ remote: remote,
+ ),
+);
+
+var _paneIds = 7000;
+
+/// One desk tab of the person's on this Mac with one pane: in a checkout of
+/// [remote], or in a plain folder.
+void _desk(SuperTabLaunchFixture f, {String? remote, required String cwd}) {
+ f.app.machineStates['m']!.agents = [_agent('n1', remote: remote, cwd: cwd)];
+ f.app.swarms.add(
+ Swarm(id: 'desk', name: 'Games')
+ ..panes.add(TerminalPane(id: _paneIds++, machineId: 'm', agentId: 'n1')),
+ );
+}
+
+/// The fixture's Swarm, made the person's Personal one, with its projects made
+/// for the desk; [personal] false leaves it a Team Swarm.
+Future<SuperTabController> _swarm(
+ SuperTabLaunchFixture f, {
+ bool personal = true,
+}) async {
+ for (final state in f.app.machineStates.values) {
+ state.localOnly = true;
+ }
+ f.connection.server.state
+ ..['name'] = personal ? 'Personal' : 'Team'
+ ..['ownerId'] = 'owner'
+ ..['people'] = [
+ {'id': 'owner', 'email': '[email protected]', 'role': 'owner'},
+ if (!personal)
+ {'id': 'peer', 'email': '[email protected]', 'role': 'collaborator'},
+ ];
+ if (personal) {
+ await f.app.superTabs.storage.write('super_tab.personal.owner', tabId);
+ }
+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Personal');
+ PersonalSwarm.of(f.app).id;
+ for (var i = 0; i < 20; i++) {
+ await Future<void>.microtask(() {});
+ }
+ final c = await f.app.superTabs.open(tabId);
+ await c.refresh();
+ if (personal) await PersonalProjects.of(f.app).sync(c);
+ return c;
+}
+
+/// The project chat the desk's pane belongs to.
+String _games(SuperTabController c) =>
+ c.snapshot!.projects.firstWhere((p) => p.id != 'lead').leadConversationId;
+
+List<Map> _commands(SuperTabLaunchFixture f, String type) => [
+ for (final post in f.connection.server.posts)
+ if ((post['command'] as Map?)?['type'] == type) post['command'] as Map,
+];
+
+Map<String, dynamic> _create(SuperTabLaunchFixture f) =>
+ f.connection.calls.singleWhere((c) => c.$1 == 'agent_create').$2;
+
+void main() {
+ test('a message in a repo project with no Lead starts one in the repo\'s '
+ 'folder on this Mac and joins it as Lead', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f, remote: '[email protected]:huy/games.git', cwd: '/Users/huy/games');
+ final c = await _swarm(f);
+ final games = _games(c);
+ final starter = PersonalLeadStarter.of(f.app);
+ expect(starter.wants(c, games), isTrue);
+ await starter.start(c, games);
+ expect(_commands(f, 'lead.claim').single['machineId'], 'm');
+ final create = _create(f);
+ expect(create['cwd'], '/Users/huy/games');
+ expect(create['swarmRole'], 'lead');
+ expect(create['engine'], 'claude');
+ final join = f.connection.joins.single['command'] as Map;
+ expect(join['lead'], isTrue);
+ expect(join['conversationId'], games);
+ // The message is the server's to deliver: the join carries none.
+ expect(join.containsKey('initialMessage'), isFalse);
+ expect(starter.statusOf(c, games)?.failed, isFalse);
+ });
+
+ test('a message in a project with no repo starts its Lead in a new folder '
+ 'of the Harness projects folder', () async {
+ // This computer makes the folder itself: a fixture one, never the disk's.
+ final asked = <ProjectFolderRequest>[];
+ final f = SuperTabLaunchFixture(
+ prepareFolder: (request) async {
+ asked.add(request);
+ return '/fixture/Harness/${request.folderName}';
+ },
+ );
+ _desk(f, cwd: '/Users/huy/scratch');
+ final c = await _swarm(f);
+ final games = _games(c);
+ await PersonalLeadStarter.of(f.app).start(c, games);
+ // Named after the project, numbered past a folder of that name already
+ // there rather than refused, as a suggested name is.
+ expect(asked.single.folderName, 'Games');
+ expect(asked.single.isGenerated, isTrue);
+ expect(_create(f)['cwd'], '/fixture/Harness/Games');
+ expect((f.connection.joins.single['command'] as Map)['lead'], isTrue);
+ });
+
+ test(
+ 'a failed start says why, and starts again on the next message',
+ () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');
+ final c = await _swarm(f);
+ final games = _games(c);
+ final starter = PersonalLeadStarter.of(f.app);
+ f.connection
+ ..failCreation = true
+ ..failCreationCode = 'ENGINE_LAUNCH_REFUSED';
+ await starter.start(c, games);
+ final status = starter.statusOf(c, games)!;
+ expect(status.failed, isTrue);
+ expect(status.reason, 'Fixture engine unavailable');
+ expect(f.connection.joins, isEmpty);
+ f.connection.failCreation = false;
+ await starter.start(c, games);
+ expect((f.connection.joins.single['command'] as Map)['lead'], isTrue);
+ },
+ );
+
+ test('two quick messages start one Lead', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');
+ final c = await _swarm(f);
+ final games = _games(c);
+ final starter = PersonalLeadStarter.of(f.app);
+ await Future.wait([starter.start(c, games), starter.start(c, games)]);
+ expect(_commands(f, 'lead.claim'), hasLength(1));
+ expect(
+ f.connection.calls.where((call) => call.$1 == 'agent_create'),
+ hasLength(1),
+ );
+ });
+
+ test('a start another of the person\'s machines claimed starts nothing '
+ 'here and shows as starting', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');
+ final c = await _swarm(f);
+ final games = _games(c);
+ final project = (f.connection.server.state['projects'] as List)
+ .cast<Map<String, dynamic>>()
+ .firstWhere((p) => p['leadConversationId'] == games);
+ project['leadClaim'] = {'machineId': 'laptop'};
+ final starter = PersonalLeadStarter.of(f.app);
+ await starter.start(c, games);
+ expect(
+ f.connection.calls.where((call) => call.$1 == 'agent_create'),
+ isEmpty,
+ );
+ expect(starter.statusOf(c, games)?.failed, isFalse);
+ });
+
+ test('a Team Swarm starts no Lead', () async {
+ final f = SuperTabLaunchFixture();
+ _desk(f, remote: 'https://github.com/huy/games', cwd: '/Users/huy/games');
+ final c = await _swarm(f, personal: false);
+ expect(PersonalLeadStarter.of(f.app).wants(c, 'lead'), isFalse);
+ });
+}
diff --git a/desktop/test/super_tab_receipt_test.dart b/desktop/test/super_tab_receipt_test.dart
index 3d3d36909..e4aaf9efa 100644
--- a/desktop/test/super_tab_receipt_test.dart
+++ b/desktop/test/super_tab_receipt_test.dart
@@ -7,6 +7,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
+import 'package:harness/super_tabs/personal_lead.dart';
import 'package:harness/super_tabs/view.dart';
import 'support/super_tab_fixture.dart';
@@ -27,7 +28,11 @@ class ReceiptFixture {
Map<String, dynamic> get delivery =>
(message['deliveries'] as List).single as Map<String, dynamic>;
- Future<void> show({AppNotifier? app, void Function()? prepare}) async {
+ Future<void> show({
+ AppNotifier? app,
+ void Function()? prepare,
+ Brightness brightness = Brightness.light,
+ }) async {
server.state['agents'] = [
{
'id': 'lead-agent',
@@ -71,7 +76,8 @@ class ReceiptFixture {
addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget(
MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.light),
+ debugShowCheckedModeBanner: false,
+ theme: grid.buildAppTheme(brightness: brightness),
home: Scaffold(
body: SuperTabView(
controller: controller,
@@ -305,6 +311,81 @@ void main() {
await f.close();
});
+ // Huy, 11-04 (task #2633): in a Personal Swarm the message waits for the
+ // Lead Desktop starts, which the line says, or why it could not start.
+ testWidgets('receipt: no Lead in a Personal project says its Lead starts', (
+ tester,
+ ) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final f = ReceiptFixture(tester, status: null);
+ await f.show(
+ app: app,
+ prepare: () =>
+ (f.server.state['conversations'] as List).first['leadId'] = null,
+ );
+ PersonalLeadStarter.of(app).setStatusForTest(
+ f.controller,
+ 'lead',
+ PersonalLeadStatus.starting(clock.now()),
+ );
+ await tester.pump();
+ expect(find.text('Starting a Lead…'), findsOneWidget);
+ expect(find.textContaining('Not sent'), findsNothing);
+ expect(find.text('Add a Lead'), findsNothing);
+ await f.close();
+ });
+
+ testWidgets(
+ 'receipt: a Personal project\'s Lead that could not start says why and '
+ 'offers Add a Lead',
+ (tester) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final f = ReceiptFixture(tester, status: null);
+ await f.show(
+ app: app,
+ prepare: () =>
+ (f.server.state['conversations'] as List).first['leadId'] = null,
+ );
+ PersonalLeadStarter.of(app).setStatusForTest(
+ f.controller,
+ 'lead',
+ const PersonalLeadStatus.failed(
+ 'Claude Code and Codex aren’t signed in on Studio',
+ ),
+ );
+ await tester.pump();
+ expect(
+ find.text(
+ 'Couldn’t start a Lead: Claude Code and Codex aren’t signed in on '
+ 'Studio',
+ ),
+ findsOneWidget,
+ );
+ expect(find.textContaining('Not sent'), findsNothing);
+ await tester.tap(find.text('Add a Lead'));
+ expect(f.addedLead, isTrue);
+ await f.close();
+ },
+ );
+
+ testWidgets('receipt: no Lead and no start, with an app, is still not sent', (
+ tester,
+ ) async {
+ final app = createApp(connected: true);
+ addTearDown(app.dispose);
+ final f = ReceiptFixture(tester, status: null);
+ await f.show(
+ app: app,
+ prepare: () =>
+ (f.server.state['conversations'] as List).first['leadId'] = null,
+ );
+ expect(find.text('Not sent · this chat has no Lead'), findsOneWidget);
+ expect(find.text('Add a Lead'), findsOneWidget);
+ await f.close();
+ });
+
testWidgets(
'receipt: only latest own message carries a receipt, even after another person speaks',
(tester) async {
diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dart
index f9550cbb2..73671717f 100644
--- a/desktop/test/super_tab_swarm_switcher_test.dart
+++ b/desktop/test/super_tab_swarm_switcher_test.dart
@@ -49,6 +49,17 @@ class _Backend {
/// The account the next request is from.
String account = 'owner';
+ /// While set, every read of a Swarm's state fails so, as a backend
+ /// restarting under it answers (task #2647).
+ Object? stateReadFailure;
+
+ /// While set, the account's Swarm list fails so.
+ Object? listFailure;
+
+ /// While true, this computer's Harness is restarting (a CLI update): every
+ /// request to it fails as its dropped socket does.
+ bool daemonRestarting = false;
+
ConversationServer add(
String id,
String name, {
@@ -87,6 +98,7 @@ class _Backend {
}) async {
final uri = Uri.parse(path);
if (uri.path == '/api/super-tabs/list') {
+ if (listFailure case final failure?) throw failure;
return {
'tabs': [
for (final tab in tabs)
@@ -118,6 +130,11 @@ class _Backend {
return {'id': id, 'revision': 0};
}
final swarm = RegExp(r'^/api/super-tabs/([^/]+)/').firstMatch(uri.path);
+ if (stateReadFailure case final failure?
+ when method == 'GET' &&
+ RegExp(r'/(parts|changes)$').hasMatch(uri.path)) {
+ throw failure;
+ }
final server = servers[swarm?.group(1)];
if (server == null) {
throw const SuperTabFailure('NOT_FOUND', 'Swarm not found.');
@@ -146,6 +163,7 @@ class _Connection extends WsConn {
Duration timeout = const Duration(seconds: 20),
}) async {
if (type != 'super_tabs') return {};
+ if (backend.daemonRestarting) throw Exception('WS disconnected');
final action = payload['action'] as String?;
if (action == 'backend') {
return {
@@ -873,6 +891,154 @@ void main() {
});
}
+ group('a restart under an open Swarm (task #2647)', () {
+ const dropped = SuperTabFailure(
+ 'BACKEND_UNAVAILABLE',
+ 'Could not reach the Harness backend.',
+ statusCode: 502,
+ );
+ const refusals = [
+ SuperTabFailure(
+ 'NOT_FOUND',
+ 'This Super Tab is unavailable.',
+ statusCode: 404,
+ ),
+ SuperTabFailure(
+ 'FORBIDDEN',
+ 'You cannot read this Swarm.',
+ statusCode: 403,
+ ),
+ ];
+
+ /// Alpha shown in a tab, Personal picked here before, as on Dee's Mac:
+ /// a Swarm taken away would move this tab to Personal.
+ Future<(AppNotifier, _Backend, String, SuperTabController)> shown() async {
+ final (app, backend) = await _twoTabs();
+ final tab = app.activeSwarmId;
+ await PersonalSwarm.of(app).show(tab);
+ await _settle();
+ app.showSuperTabIn(tab, 'alpha', 'Alpha');
+ await _settle();
+ final alpha = await app.superTabs.open('alpha');
+ await alpha.refresh();
+ return (app, backend, tab, alpha);
+ }
+
+ testWidgets('a Harness restart, then reads that drop and are refused while '
+ 'the list still has the Swarm (or cannot be read), keep it open in its '
+ 'tab under its own name, saying Reconnecting; it reads again once the '
+ 'backend is back', (tester) async {
+ late AppNotifier app;
+ late _Backend backend;
+ late String tab;
+ late SuperTabController alpha;
+ await tester.runAsync(() async {
+ (app, backend, tab, alpha) = await shown();
+ });
+ await tester.binding.setSurfaceSize(const Size(1200, 900));
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ home: Scaffold(
+ body: SuperTabView(
+ controller: alpha,
+ app: app,
+ onInvite: () {},
+ onAddAgent: (_) {},
+ onOpenTerminal: (_) {},
+ onNewSwarm: () {},
+ machineName: (_) => 'Team Mac',
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(_rowText('Alpha'), findsOneWidget);
+
+ Future<void> poll() async {
+ await tester.runAsync(() async {
+ await alpha.refresh();
+ await _settle();
+ });
+ await tester.pump();
+ await tester.runAsync(() => _settle());
+ await tester.pump();
+ }
+
+ void stillAlpha(String when) {
+ expect(alpha.accessRevoked, isFalse, reason: when);
+ expect(_shown(app, tab), 'alpha', reason: when);
+ expect(app.activeSwarm.name, 'Alpha', reason: when);
+ expect(_rowText('Alpha'), findsOneWidget, reason: when);
+ expect(_rowText('Swarm'), findsNothing, reason: when);
+ expect(
+ swarmChoices(app).map((c) => (c.id, c.name)),
+ contains(('alpha', 'Alpha')),
+ reason: when,
+ );
+ }
+
+ // CLI v0.5.35 restarts this computer's Harness under the open Swarm.
+ backend.daemonRestarting = true;
+ await poll();
+ stillAlpha('daemon restarting');
+ expect(alpha.backendUnreachable, isTrue);
+ expect(find.text('Reconnecting…'), findsOneWidget);
+ backend.daemonRestarting = false;
+
+ // Then the backend restarts: its reads drop...
+ backend.stateReadFailure = dropped;
+ await poll();
+ stillAlpha('dropped');
+ expect(alpha.backendUnreachable, isTrue);
+ expect(find.text('Reconnecting…'), findsOneWidget);
+
+ // The restarting backend refuses, and its list cannot be read yet.
+ backend.listFailure = dropped;
+ for (final refusal in refusals) {
+ backend.stateReadFailure = refusal;
+ await poll();
+ stillAlpha('${refusal.code}, list unreadable');
+ expect(alpha.backendUnreachable, isTrue);
+ }
+ // The list answers, still with Alpha, while its reads are refused.
+ backend.listFailure = null;
+ for (final refusal in refusals) {
+ backend.stateReadFailure = refusal;
+ await poll();
+ stillAlpha('${refusal.code}, list has it');
+ expect(alpha.backendUnreachable, isTrue);
+ }
+ // Quiet: one line, never the refusal's own words.
+ expect(find.text('Reconnecting…'), findsOneWidget);
+ for (final refusal in refusals) {
+ expect(find.text(refusal.message), findsNothing);
+ }
+ expect(find.text('Conversation unavailable.'), findsNothing);
+
+ backend.stateReadFailure = null;
+ await poll();
+ stillAlpha('back');
+ expect(alpha.backendUnreachable, isFalse);
+ expect(alpha.snapshot?.name, 'Alpha');
+ await _releaseAll(tester, app);
+ });
+
+ test('a refusal once the list no longer has the Swarm still takes it '
+ 'away and moves the tab to Personal', () async {
+ final (app, backend, tab, alpha) = await shown();
+ final personal = PersonalSwarm.of(app).id!;
+ backend.tabs.removeWhere((t) => t['id'] == 'alpha');
+ backend.stateReadFailure = refusals.last;
+ await alpha.refresh();
+ await _settle();
+ expect(alpha.accessRevoked, isTrue);
+ await fallBackToPersonal(app, alpha);
+ expect(_shown(app, tab), personal);
+ });
+ });
+
test('a failure to add this computer says so in the tab Personal was '
'picked in, and only there', () async {
final (app, backend) = await _twoTabs();
diff --git a/desktop/test/super_tab_time_zone_test.dart b/desktop/test/super_tab_time_zone_test.dart
new file mode 100644
index 000000000..b3a9139bc
--- /dev/null
+++ b/desktop/test/super_tab_time_zone_test.dart
@@ -0,0 +1,106 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/local_time_zone.dart';
+import 'package:harness/super_tabs/model.dart';
+
+import 'support/super_tab_fixture.dart';
+
+/// Huy (11-04): a person's card shows their local time, from the time zone
+/// their own app tells the Swarm (River: its IANA name, not an offset).
+Iterable<Map> _zoneReports(ConversationServer server) => server.posts
+ .map((p) => p['command'] as Map)
+ .where((c) => c['type'] == 'member.timeZone');
+
+void main() {
+ tearDown(() => superTabLocalTimeZoneOverride = null);
+
+ test('reads a person’s zone', () {
+ final person = SuperTabPerson.fromJson({
+ 'id': 'huy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ 'timeZone': 'Asia/Ho_Chi_Minh',
+ });
+ expect(person.timeZone, 'Asia/Ho_Chi_Minh');
+ expect(
+ SuperTabPerson.fromJson({
+ 'id': 'ivy',
+ 'email': '[email protected]',
+ 'role': 'collaborator',
+ }).timeZone,
+ isNull,
+ );
+ });
+
+ test('a zone is the name after zoneinfo in the localtime link', () {
+ expect(
+ superTabZoneFromLink('/var/db/timezone/zoneinfo/Asia/Ho_Chi_Minh'),
+ 'Asia/Ho_Chi_Minh',
+ );
+ expect(
+ superTabZoneFromLink('/usr/share/zoneinfo/America/Argentina/Salta'),
+ 'America/Argentina/Salta',
+ );
+ expect(superTabZoneFromLink('/usr/share/zoneinfo/UTC'), 'UTC');
+ expect(superTabZoneFromLink('/etc/foo'), isNull);
+ expect(superTabZoneFromLink('/usr/share/zoneinfo/'), isNull);
+ });
+
+ test('reports the zone once when it differs from the stored one', () async {
+ superTabLocalTimeZoneOverride = () => 'Asia/Ho_Chi_Minh';
+ final server = ConversationServer();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await pumpEventQueue();
+ expect(_zoneReports(server).map((c) => c['timeZone']), [
+ 'Asia/Ho_Chi_Minh',
+ ]);
+ await c.refresh();
+ await pumpEventQueue();
+ expect(
+ c.snapshot!.people.firstWhere((p) => p.id == 'owner').timeZone,
+ 'Asia/Ho_Chi_Minh',
+ );
+ server.append('Later');
+ await c.refresh();
+ await pumpEventQueue();
+ expect(_zoneReports(server), hasLength(1));
+ });
+
+ test('does not report a zone already stored', () async {
+ superTabLocalTimeZoneOverride = () => 'Asia/Ho_Chi_Minh';
+ final server = ConversationServer();
+ ((server.state['people'] as List).first as Map)['timeZone'] =
+ 'Asia/Ho_Chi_Minh';
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await pumpEventQueue();
+ expect(_zoneReports(server), isEmpty);
+ });
+
+ test('reports nothing when this computer names no zone', () async {
+ superTabLocalTimeZoneOverride = () => null;
+ final server = ConversationServer();
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await pumpEventQueue();
+ expect(_zoneReports(server), isEmpty);
+ });
+
+ test('a refused report is not sent again and shows nothing', () async {
+ superTabLocalTimeZoneOverride = () => 'Europe/Berlin';
+ final server = ConversationServer()
+ ..unknownCommand = ((command) => command['type'] == 'member.timeZone');
+ final c = server.controller();
+ addTearDown(c.dispose);
+ await c.refresh();
+ await pumpEventQueue();
+ server.append('Later');
+ await c.refresh();
+ await pumpEventQueue();
+ expect(_zoneReports(server), hasLength(1));
+ expect(c.error, isNull);
+ });
+}
diff --git a/desktop/test/super_tab_web_direct_test.dart b/desktop/test/super_tab_web_direct_test.dart
index 04fadbfa6..eaead8c64 100644
--- a/desktop/test/super_tab_web_direct_test.dart
+++ b/desktop/test/super_tab_web_direct_test.dart
@@ -245,7 +245,8 @@ void main() {
backend.forbidden = true;
await c.refresh();
- expect(c.accessRevoked, isTrue);
+ // The refusal is final once the list, read again, no longer has it.
+ await _until(() => c.accessRevoked, what: 'the Swarm taken away');
expect(c.snapshot, isNull);
expect(c.messages('lead'), isEmpty);
});
diff --git a/desktop/test/super_tab_zone_time_test.dart b/desktop/test/super_tab_zone_time_test.dart
new file mode 100644
index 000000000..1e626b201
--- /dev/null
+++ b/desktop/test/super_tab_zone_time_test.dart
@@ -0,0 +1,37 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/super_tabs/zone_time.dart';
+
+/// A person's card shows the time where they are, from their zone's name, so
+/// daylight saving stays right (River, 11-04); a zone it cannot read gives no
+/// time rather than a guess.
+void main() {
+ test('Asia/Ho_Chi_Minh at 08:42Z is 15:42', () async {
+ expect(
+ await superTabTimeIn('Asia/Ho_Chi_Minh', DateTime.utc(2026, 11, 4, 8, 42)),
+ const TimeOfDay(hour: 15, minute: 42),
+ );
+ });
+
+ test('New York keeps daylight saving', () async {
+ expect(
+ await superTabTimeIn('America/New_York', DateTime.utc(2026, 7, 1, 16)),
+ const TimeOfDay(hour: 12, minute: 0),
+ );
+ expect(
+ await superTabTimeIn('America/New_York', DateTime.utc(2026, 12, 1, 17)),
+ const TimeOfDay(hour: 12, minute: 0),
+ );
+ });
+
+ test('unknown zone gives no time', () async {
+ expect(
+ await superTabTimeIn('Mars/Base', DateTime.utc(2026, 11, 4)),
+ isNull,
+ );
+ });
+
+ test('no zone gives no time', () async {
+ expect(await superTabTimeIn(null, DateTime.utc(2026, 11, 4)), isNull);
+ });
+}
diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dart
index 51bb0110f..94a876972 100644
--- a/desktop/test/support/super_tab_fixture.dart
+++ b/desktop/test/support/super_tab_fixture.dart
@@ -872,6 +872,8 @@ class ConversationServer {
...row,
if (command['type'] == 'member.status')
'status': command['status']
+ else if (command['type'] == 'member.timeZone')
+ 'timeZone': command['timeZone']
else if (command['type'] == 'member.username')
'username': (command['username'] as String?)?.toLowerCase()
else if (command['type'] == 'member.name')
@@ -1133,6 +1135,7 @@ class ConversationServer {
output['startId'] = operationId;
}
} else if (command['type'] == 'member.status' ||
+ command['type'] == 'member.timeZone' ||
command['type'] == 'member.username' ||
command['type'] == 'member.name' ||
command['type'] == 'member.avatar' ||
@@ -1381,6 +1384,20 @@ class ConversationServer {
},
});
output['conversationId'] = id;
+ } else if (command['type'] == 'lead.claim') {
+ // One start of a project's Lead (backend commands.ts lead.claim):
+ // another machine's claim is the one; the same machine claims again.
+ final project = (state['projects'] as List?)
+ ?.cast<Map<String, dynamic>>()
+ .where((p) => p['id'] == command['projectId'])
+ .firstOrNull;
+ final held = project?['leadClaim'];
+ if (held is Map && held['machineId'] != command['machineId']) {
+ output['leadStart'] = 'waiting';
+ } else {
+ project?['leadClaim'] = {'machineId': command['machineId']};
+ output['leadStart'] = 'start';
+ }
} else if (command['type'] == 'lead.start') {
if (leadRefusal case final refusal?) {
leadRefusal = null;
diff --git a/desktop/test/support/web_swarm_backend.dart b/desktop/test/support/web_swarm_backend.dart
index 4cea8c950..47bd3dd82 100644
--- a/desktop/test/support/web_swarm_backend.dart
+++ b/desktop/test/support/web_swarm_backend.dart
@@ -20,8 +20,8 @@ class WebSwarmBackend extends ApiClient {
final ConversationServer server;
final calls = <String>[];
- /// The person lost the Swarm: every read is refused, as the backend
- /// refuses one they may no longer read.
+ /// The person lost the Swarm: every read of it is refused, as the backend
+ /// refuses one they may no longer read, and their list no longer has it.
bool forbidden = false;
/// No answer at all: the browser is offline or the backend unreachable.
@@ -45,6 +45,16 @@ class WebSwarmBackend extends ApiClient {
type: DioExceptionType.connectionError,
);
}
+ if (forbidden && Uri.parse(path).path == '/api/super-tabs/list') {
+ return Response(
+ requestOptions: options,
+ statusCode: 200,
+ data: {
+ 'success': true,
+ 'data': {'tabs': <Object>[], 'next': null},
+ },
+ );
+ }
if (forbidden) {
return Response(
requestOptions: options,
diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dart
index 9943af0af..032f74e9b 100644
--- a/desktop/test/workspace_status_test.dart
+++ b/desktop/test/workspace_status_test.dart
@@ -1191,6 +1191,46 @@ void main() {
expect(app.swarms.first.name, 'My workspace');
});
+ test('a Swarm tab never takes its agents\' folder, project or names as its '
+ 'name, even one not marked as named by hand (task #2647)', () async {
+ final app = createApp();
+ addTearDown(app.dispose);
+ // A Lead with no repository works in the Swarm's own folder.
+ app.stateOf('m')!.agents = const [
+ Agent(
+ id: 'lead',
+ name: 'Lead',
+ engine: 'claude',
+ project: AgentProject(
+ name: 'swarms',
+ cwd: '/Users/dee/harnesses/swarms',
+ ),
+ ),
+ ];
+ app.swarms.clear();
+ final tab =
+ Swarm(
+ id: 't',
+ name: 'autonomous.ai',
+ kind: 'superTab',
+ nameIsCustom: false,
+ )
+ ..superTabId = 'c51479bd73b59e58176ad9e4'
+ ..titleMachineId = 'm'
+ ..titleAgentId = 'lead'
+ ..panes.add(TerminalPane(id: 1, machineId: 'm', agentId: 'lead'));
+ app.swarms.add(tab);
+ expect(workspaceTabNames(app)['t'], 'autonomous.ai');
+ // Its agent renamed (as a restarted daemon announces every agent) leaves
+ // the Swarm's name alone.
+ await app.handleEventForTest('m', {
+ 'type': 'agent_renamed',
+ 'payload': {'agentId': 'lead', 'name': 'River'},
+ });
+ expect(tab.name, 'autonomous.ai');
+ expect(workspaceTabNames(app)['t'], 'autonomous.ai');
+ });
+
test('machine names distinguish the same project on different machines', () {
final app = createApp();
addTearDown(app.dispose);
diff --git a/docs/plans/2026-11-04-cancel-lost-task-requester-plan.md b/docs/plans/2026-11-04-cancel-lost-task-requester-plan.md
new file mode 100644
index 000000000..f6f60c008
--- /dev/null
+++ b/docs/plans/2026-11-04-cancel-lost-task-requester-plan.md
@@ -0,0 +1,63 @@
+# Requester and Project Owner Cancel a Lost or Stopped Task Implementation Plan
+
+> **For agentic workers:** The assigned Engineer implements this plan task by task in this session, test first, by the project's instructions. No subagents: one handler and its tests.
+
+**Goal:** The person who asked for a task, and the owner of its project, can cancel it with a reason once it is lost or stopped, so it then archives; nobody gains a way to cancel live work.
+
+**Architecture:** `work.cancel` in `backend/src/superTabs/commands.ts` keeps today's check (`projectAgent` or the Swarm owner) for every attempt, and also accepts a person who is the task's `requesterId` or its project's `ownerId` when the attempt is `lost` or `stopped`, the two states `tidy.ts unfinishedWork` holds back from archiving and which have no worker left to tell. The refusals that stay (`FORBIDDEN` on cancel, `WORK_UNFINISHED` on archive) name who can cancel.
+
+**Tech Stack:** TypeScript, Vitest (`backend/src/superTabs/commands.test.ts`).
+
+**Spec:** Swarm task #2639, conversation 7f54fe5584fdafeea5c394e8 (Diego, 2026-11-04; regression from #1903).
+
+## Global Constraints
+
+- Only `lost` or `stopped` attempts widen; `working`, `review`, `blocked`, `needs_human` and `reconciling` stay as today.
+- Only the task's requester or its own project's owner widen, as a person; a viewer is still refused before the handler (READ_ONLY), and a person who can no longer read the task is still refused (readConversation).
+- The unassigned and ended-step paths of `work.cancel` are unchanged.
+- An already-cancelled attempt also lets the requester and the project's owner through, where it changes nothing (a retry keeps the first reason and tells nobody).
+- Cancelling a lost or stopped task ends its open steps, as any cancel does (`endStepsOf`): with no worker left, a Reviewer or Tester still on a step has nothing to check.
+- Among people, only the Swarm owner or the project's owner names or clears a task's requester (`conversation.requester`), since the requester may now close it; agents of the project name it as before. No app sends it as a person (security reviews 1 and 2 of #2907).
+- Two independent security reviews by two different Reviewers.
+- PR body first line: "Requested by [email protected] through Harness."
+- Swarm code stays out of cli/src/core.
+
+## Review Focus
+
+- A collaborator who did not ask for a lost task cannot cancel it.
+- The owner of another project cannot cancel a lost task in this one.
+- The requester cannot cancel their own task while its agent is still working (live work stays the project's agents' and the Swarm owner's).
+- After the requester cancels and archives, nobody is tagged; after the project owner cancels and the requester did not archive, the requester is still tagged as today.
+- A retry of the requester's cancel changes nothing (the existing `cancelled` early return).
+- A collaborator who names themselves requester of a lost task is refused, so they still cannot cancel it (security reviews 1 and 2).
+
+---
+
+### Task 1: Requester and project owner cancel a lost or stopped task
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts` (`work.cancel`, `conversation.archive`'s WORK_UNFINISHED message, `conversation.requester`)
+- Test: `backend/src/superTabs/commands.test.ts` (`archiving unfinished work`)
+
+**Interfaces:**
+- Consumes: `groupProject(state, group).ownerId`, `group.requesterId`, `Actor` person `userId`.
+- Produces: no new exports.
+
+- [ ] **Step 1: Write the failing tests** in `describe('archiving unfinished work')`, using its `task()` fixture (Peer invited by `f.invite()` and named requester):
+ - Peer cancels a lost task and a stopped task with a reason; each then archives and tags nobody.
+ - Peer, owning a second project (not the Swarm owner), cancels a lost task in that project that the Swarm owner asked for.
+ - Peer, a collaborator who is not the requester, still cannot cancel a working task, nor a lost one, and the refusal names who can.
+ - Peer, the requester, cannot cancel the task while it is working; the owner of another project cannot cancel a lost task here.
+- [ ] **Step 2: Run them and watch them fail**
+
+Run: `cd backend && npx vitest run src/superTabs/commands.test.ts -t 'archiving unfinished work'`
+Expected: the allow cases FAIL with FORBIDDEN; the deny cases' message assertions FAIL on the old wording.
+
+- [ ] **Step 3: Commit the failing tests**
+- [ ] **Step 4: Implement** in `work.cancel`: after the stale-assignment check, `allowed || (lost/stopped && person && (userId === group.requesterId || userId === project.ownerId))`; the FORBIDDEN text names who can cancel each kind of task; the archive's WORK_UNFINISHED text names who can cancel.
+- [ ] **Step 5: Run the same tests and the `work.cancel` tests and watch them pass**
+
+Run: `cd backend && npx vitest run src/superTabs/commands.test.ts src/superTabs/tidy.test.ts`
+Expected: PASS
+
+- [ ] **Step 6: Commit the fix**
diff --git a/docs/plans/2026-11-04-chat-image-viewer-plan.md b/docs/plans/2026-11-04-chat-image-viewer-plan.md
new file mode 100644
index 000000000..67221863a
--- /dev/null
+++ b/docs/plans/2026-11-04-chat-image-viewer-plan.md
@@ -0,0 +1,96 @@
+# Chat image viewer Implementation Plan
+
+> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.
+
+**Goal:** A picture in a chat opens as Slack opens one: a see-through veil over the chat that leaves an open thread pane visible on the right, the sender, when and where at the top left, the picture centred with previous and next through the other pictures of that chat or thread, rotate and zoom at the bottom left, Download, Open in browser and More at the bottom right. Esc or a click outside closes it. Strengthens "Tell the PM what you want, and your crew ships it": the screenshots a crew posts read in place, without losing the thread beside them.
+
+**Architecture:** The chat view holds one open viewer and draws it over the panes left of the right pane (`SuperTabPaneLayout.over`), or over the whole window when the thread is a drawer. The chat list and the thread pane each put a `SuperTabImageGallery` above their rows: the pictures of that scope, oldest first, each with its sender, time and place, built from the messages the view already holds. A picture in a row looks up its gallery and opens the viewer at itself. With no gallery or no stage above it (a row drawn anywhere else), the viewer opens over the whole window as before, with that one picture.
+
+**Tech Stack:** Flutter/Dart Desktop (and its web build).
+
+**Spec:** Task #2606 in Super Tab conversation 768e7d2d01a4ea5f3e142681 (Huy, 2026-11-04; brief from River the same day).
+
+## Look
+
+```
+┌ sidebar ┬──────────────── chat (veil) ─────────────────────┬─ thread ─┐
+│ │ (H) Huy [×] │ │
+│ │ 14 days ago in # openharness · shot.png │ replies │
+│ │ │ stay │
+│ │ [‹] ┌─────────────────────┐ [›] │ visible │
+│ │ │ picture │ │ and │
+│ │ └─────────────────────┘ │ usable │
+│ │ │ │
+│ │ [⟳] [−] ───●────── [+] 100% Download Open in browser [⋯] │
+└─────────┴───────────────────────────────────────────────────┴──────────┘
+```
+
+## Global Constraints
+
+- Harness Design Language (desktop/design/desktop-design-system.md): tokens only, flat rows, colour never the only signal, no explanatory sentences.
+- The veil is dark in both appearances (River, 11-04: a picture reads best on dark, as in Slack and Photos): one media veil token, `grid.AppDesktop.mediaVeil`, with the ink and control fill drawn on it (`mediaInk`, `mediaInkMuted`, `mediaControl`, `mediaControlHover`), the same in light and dark. The design system names it as the image viewer's exception to the one modal veil.
+- Keeps today's Download (not in a browser) and Open in browser, each asking for a fresh link when the one at hand is about to end (`AttachmentViewerActions`).
+- Previous and next: buttons at the picture's left and right, and the Left and Right keys, through the pictures shown in place in the same scope: the chat's pictures from the chat, the thread's from the thread. No previous button on the first, no next on the last.
+- Zoom: a slider with minus and plus, 100% to 400% in 25% steps, its percentage shown beside it; pinch and scroll zoom move it too. Rotate turns a quarter clockwise each click. A new picture starts at 100%, unturned.
+- Top left: the sender's avatar and name as their row shows them, then "14 days ago in # openharness · shot.png". Time in words: "just now", "1 minute ago", "5 minutes ago", "1 hour ago", "3 hours ago", "1 day ago", "14 days ago".
+- More holds only Show in chat (closes the viewer and goes to the message) (River, 11-04).
+- Esc closes; a click on the veil closes; a click on the picture or a control does not.
+- Web: a browser still shows a picture as a chip that opens in a new tab (a browser cannot refuse a redirect off file storage, `attachment_viewer_web_test.dart`), so the overlay is drawn only by Desktop. Its code is shared and builds for the web. The PR names this as a known limit (River, 11-04).
+- Desktop tests use a memory store and a fake sign-in (`ConversationServer`). Desktop guard tests (`check-ui-style`, `laid_out_list_test`) pass before Ready.
+
+## Review Focus
+
+- The conversation changes, or the thread closes, while the viewer is open: it closes rather than showing pictures of a chat no longer open.
+- A picture further along whose link has ended or was never signed: the viewer asks for a fresh one, and says it can't be shown if none comes.
+- A sender who has left the Swarm: their recorded name and the face it gives, as their row shows.
+- A narrow window where the thread is a drawer: the viewer covers the window and Esc closes the viewer, not the drawer.
+- Keys typed while the viewer is open never reach the composer under it.
+
+---
+
+### Task 1: The viewer overlay
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/attachment_image.dart` (replace `SuperTabImageViewer`, add `SuperTabImageItem`, `SuperTabImageGallery`, `SuperTabImageStage`, `superTabPostedAgo`)
+- Modify: `desktop/lib/super_tabs/attachment_viewer.dart` (`AttachmentViewerActions`: optional Close, trailing More)
+- Modify: `desktop/lib/shared/theme/app_theme.dart` (the media tokens), `desktop/design/desktop-design-system.md` (the exception)
+- Test: `desktop/test/super_tab_image_viewer_test.dart` (new)
+
+**Interfaces:**
+- Produces:
+ - `class SuperTabImageItem { SuperTabImageItem({required SuperTabFileRef ref, required String sender, required Widget avatar, DateTime? postedAt, String? place, VoidCallback? onShowInChat}); }`
+ - `class SuperTabImageViewer extends StatefulWidget { const SuperTabImageViewer({Key? key, required List<SuperTabImageItem> images, required int index, required VoidCallback onClose}); }` keyed `super-attachment-viewer`, its picture `super-attachment-image:<file id>`, its buttons `super-image-previous`, `super-image-next`, `super-image-rotate`, `super-image-zoom-out`, `super-image-zoom-in`, slider `super-image-zoom`, veil `super-image-veil`.
+ - `String superTabPostedAgo(Duration age)`.
+ - `AttachmentViewerActions({..., bool close = true, Widget? more})`.
+
+- [ ] **Step 1: Write the failing tests** (pumping `SuperTabImageViewer` alone with three items): next and previous buttons and the Right/Left keys change the picture shown, the first has no previous and the last no next; plus moves the slider to 125% and the picture's scale to 1.25, minus back to 100%, the slider dragged to the end reads 400%; rotate sets the picture's quarter turns to 1, then 2; Esc and a tap on the veil call `onClose`, a tap on the picture does not; the header reads the sender, "14 days ago in # openharness · shot.png"; Download and Open in browser are there and there is no Close; More offers Show in chat, which calls it and closes; `superTabPostedAgo` reads the times in Global Constraints.
+- [ ] **Step 2: Run them and watch them fail** — `flutter test test/super_tab_image_viewer_test.dart` (the new names do not exist).
+- [ ] **Step 3: Implement** the overlay as a `Stack` over the veil: header row, `InteractiveViewer` with a `TransformationController` around a `RotatedBox`, the arrows at the sides, the control row at the bottom; a `Focus(autofocus)` handles Esc, Left and Right. Each item's link is `ref.current`, else asked for with `superTabOpenableLink`.
+- [ ] **Step 4: Run them and watch them pass.**
+- [ ] **Step 5: Commit** the test first, then the code.
+
+### Task 2: Open it over the chat, through that chat's or thread's pictures
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/attachment_image.dart` (`SuperTabInlineImage` opens through the gallery and stage)
+- Modify: `desktop/lib/super_tabs/attachment_chips.dart` (`superTabFileRef` and `superTabShowsInPlace`, shared with the gallery)
+- Modify: `desktop/lib/super_tabs/message_row.dart` (`superTabMessageAvatar`, the row's own avatar, shared)
+- Modify: `desktop/lib/super_tabs/pane_layout.dart` (`over`: drawn over the left and centre panes)
+- Modify: `desktop/lib/super_tabs/view.dart` (the stage, a gallery for the chat and one for the thread, the place name)
+- Test: `desktop/test/super_tab_message_media_test.dart` (the old full-screen test becomes the overlay's)
+
+**Interfaces:**
+- Consumes: Task 1's `SuperTabImageViewer`, `SuperTabImageItem`.
+- Produces: `SuperTabImageGallery({required List<SuperTabImageItem> Function() images, required Widget child})`, `SuperTabImageStage({required void Function(List<SuperTabImageItem>, int) open})` (`maybeOf`); `SuperTabPaneLayout(over: Widget?)`.
+
+- [ ] **Step 1: Write the failing tests** in the full chat view (`SuperTabView` over `ConversationServer`, 1400×900 so a thread sits beside the chat): a click on a picture opens the viewer whose right edge is at the thread pane's left, and the thread's reply is still hit-testable; its header names the sender and "in # …"; with two messages of pictures, next goes to the second; a picture in the thread pages only through the thread's pictures; Show in chat closes it; switching conversation closes it; at 900 wide (thread as a drawer) the viewer covers the window and Esc closes the viewer while the drawer stays.
+- [ ] **Step 2: Run them and watch them fail.**
+- [ ] **Step 3: Implement** as in Architecture.
+- [ ] **Step 4: Run** the tests of what changed: `super_tab_message_media_test.dart`, `super_tab_image_viewer_test.dart`, `super_tab_file_links_test.dart`, `super_tab_attachments_test.dart`, `super_tab_message_rows_shots_test.dart`, `super_tab_phone_targets_test.dart`, the pane layout's tests.
+- [ ] **Step 5: Commit** the test first, then the code.
+
+### Task 3: Screenshots and Ready
+
+- [ ] `super_tab_image_viewer_shots_test.dart` (light and dark, a thread open beside the chat) writes the before shots on main and the after shots on the branch with `SUPER_TAB_IMAGE_SHOTS`; attach them to the PR.
+- [ ] Run the changed tests, the guard tests (`check-ui-style`, `laid_out_list_test`), `flutter analyze`, and a web build compile. The whole Desktop suite runs in the PR's CI once it is ready; that green run is the suite evidence (instructions revision 56).
+- [ ] Red/green evidence in a PR comment; mark Ready; add the review and test steps.
diff --git a/docs/plans/2026-11-04-day-pill-divider-overlap-plan.md b/docs/plans/2026-11-04-day-pill-divider-overlap-plan.md
new file mode 100644
index 000000000..a02bedb6c
--- /dev/null
+++ b/docs/plans/2026-11-04-day-pill-divider-overlap-plan.md
@@ -0,0 +1,52 @@
+# Day pill over its own day line: one label — plan
+
+**Goal:** While the Swarm chat's sticky day pill (#2425, #2784) floats over a day line, only one day label shows:
+the pill takes the line's place, as Slack's, and its fill is opaque in light and dark (Huy 11-04).
+
+**Way of working:** this project's Engineer flow: plan first, then each task's failing test before its code, one pull
+request, one independent review.
+
+**Architecture:** `SuperTabStickyDay` (desktop/lib/super_tabs/day_pill.dart) already measures the rows under it after
+each frame. The chat's day line label (`_date` in view.dart) becomes a `SuperTabDayLabel` that registers with the same
+scope. After each frame the sticky day measures the labels too: every label whose top has reached the pill's bottom
+edge is hidden (painted invisible, same size, so no row moves), and the pill says the day of the lowest such label, else
+the day of the row at the top as before. So a line meets the pill, the pill turns to the line's day and the line's
+label goes; scrolling back, the label returns once it is below the pill. The rule lines stay; the pill covers their
+middle.
+
+**Tech stack:** Flutter widgets, flutter_test widget tests with the Super Tab fixture (memory store, fake sign-in).
+
+**Spec:** task #2643 brief (Huy 11-04).
+
+```
+before after
+──────── Wed, Nov 4 ──────── ────────(Wed, Nov 4)────────
+ (Wed, Nov 4) ← overlap ↑ pill only; line label hidden
+Lead Pushed the branch… Lead Pushed the branch…
+```
+
+## Global constraints
+
+- The pill still floats: no row moves when it shows, changes or hides, or when a label hides.
+- Threads have no day lines; the thread pill keeps its behaviour.
+- Desktop and web build the same widgets; nothing platform-specific.
+- Tests use the memory store and fake sign-in of `test/support/super_tab_fixture.dart`.
+
+## Review focus
+
+- The pill's day and the hidden label are decided from the same measurement, so they can never disagree for a frame.
+- A hidden label keeps its size and its semantics (screen readers still read the day line).
+
+## Task 1: one label where the pill meets a day line
+
+**Files:** `desktop/lib/super_tabs/day_pill.dart`, `desktop/lib/super_tabs/view.dart`,
+`desktop/test/super_tab_day_pill_test.dart`
+
+**Interfaces:** `SuperTabDayLabel({required DateTime day, required Widget child})`.
+
+- [ ] Failing test: scrolling the chat in small steps across Tuesday's day line, at no step do the pill and a visible
+ day-line label overlap, and the pill never shows next to a visible label of its own day under it.
+- [ ] Failing test: the pill's fill is opaque in light and dark.
+- [ ] Run them, see them fail.
+- [ ] Implement `SuperTabDayLabel` and the measurement; opaque fill.
+- [ ] Run the pill tests and the Super Tab view tests; screenshots in light and dark.
diff --git a/docs/plans/2026-11-04-identity-hover-card-plan.md b/docs/plans/2026-11-04-identity-hover-card-plan.md
new file mode 100644
index 000000000..5d1c97ff0
--- /dev/null
+++ b/docs/plans/2026-11-04-identity-hover-card-plan.md
@@ -0,0 +1,138 @@
+# Identity hover card Implementation Plan
+
+> **For agentic workers:** Follow the project Engineer workflow: plan first in a draft PR; implement task by task with a committed failing test before its passing code; one independent review step on the pull request.
+
+**Goal:** Hovering a name or avatar in a Swarm chat shows a small card: for a person their name, status and local time; for an agent its engine and model, machine, and the task it works on as a link to that task's chat. Desktop and web. Strengthens "Every lab in one crew, on the team's own machines": who someone is, where an agent runs and what it is doing are one hover away.
+
+**Architecture:** The card is one shared Flutter widget (`identity_card.dart`) fed plain facts the chat view works out: a person's from the Swarm's people, an agent's from `SuperTabAgentInfo` (the facts the agent details dialog already uses). The Swarm stores no time zone today, so the backend gains one per person (`member.timeZone`, an IANA name), which each person's own app reports when it differs; readers turn the name into a local time with the Dart team's `timezone` package, loaded only when a card first needs it.
+
+**Tech Stack:** TypeScript, Zod, Vitest (backend); Flutter/Dart Desktop and web, `package:timezone`.
+
+**Spec:** Task #2605 in Super Tab conversation cdbc82e3d4e7f7c81d9d9fe8 (Huy, 2026-11-04; River's brief, and River's ruling the same day: report the zone name, not a UTC offset).
+
+## Global Constraints
+
+- Look, as posted for Huy (screenshots in the task thread):
+
+ ```
+ Person Agent
+ ┌──────────────────────┐ ┌──────────────────────────────────┐
+ │ Huy Pham │ │ Shrike2 │
+ │ 🌴 Out of office │ │ ✳ Claude Opus 5.5 │
+ │ 🕒 3:42 PM local time│ │ 💻 MacbookPro │
+ └──────────────────────┘ │ Working on #2605 Chat: a card… › │
+ └──────────────────────────────────┘
+ ```
+
+- Opens after 500 ms of hover on the avatar or the name; closes 150 ms after the pointer has left both the anchor and the card. Keyboard focus on the name opens it at once; Escape closes it and keeps focus on the name; Tab from the name reaches the task line; Enter there opens the task's chat.
+- A fact nobody knows is left out: no status, no zone, an unknown zone, no machine, no task. Never a guessed time.
+- Not repeated from the row: no avatar and no message time in the card.
+- Harness Design Language: tokens only (`scripts/check-ui-style.py`), the shared popover surface (`AppMenu.fill`, `AppMenu.rim`, `AppMenu.panelRadius`, `AppSurface.shadow`), flat rows, the task link has a hand cursor, an underline and a chevron on hover/focus so colour is not its only sign, no explanatory sentences.
+- Copy: `<time> local time`; the task line is `SuperTabAgentInfo.status` with `#<number> <title>` in place of the quoted title.
+- Desktop tests use a memory store and a fake sign-in; no test touches the real CLI.
+- The zone is the IANA name (`Asia/Ho_Chi_Minh`), never an offset (River, 11-04).
+
+## Design
+
+- Growth: one short string per person, deleted with the person's membership record.
+- Concurrency: `member.timeZone` runs in the Swarm's state transaction like `member.status`; last write wins, and it is the person's own.
+- Read cost: the zone rides in the people part, which changes only when someone's zone changes; an app sends only when its zone differs from the stored one, once per value per session.
+- Scale: 10x people is 10x tiny strings; the first warning is `member.timeZone` commands per minute, which should be near zero at rest.
+- Compatibility: an older app ignores the field. A new app on an older backend gets a refusal for the unknown command, ignores it, and its card shows no time.
+- Migration + rollback: none; nothing reads an absent field. A rollback leaves stored zones unread.
+- Audience: the server sends people only to members (`model.ts` visible state), as it does status.
+- Identity: the actor's own person id (`actor.userId`); an agent may not set one, and nobody sets another's.
+- Failure: a refused or failed report is silent by design, and the card then shows no time rather than a wrong one. An unknown zone name is refused by the server (`knownTimeZone`).
+- Platforms: macOS, Linux and web report a zone; Windows reports none (its zone names are not IANA ones) so Windows people show no time; the phone app is not changed.
+
+## Review Focus
+
+- A person whose app never reported a zone, or reported one this build's table lacks: no time line, no crash (Task 3 test `unknown zone gives no time`).
+- An older backend refusing `member.timeZone`: no error shown, no resend loop (Task 2 test `a refused report is not sent again`).
+- The pointer moving from the name into the card: the card stays open (Task 4 test `stays open while the pointer crosses into the card`).
+- A grouped follow-up line has no name or avatar: no card anchor there (Task 5 test `a grouped line has no card`).
+- An agent with no task, or a task the reader may not read: no task line (Task 5 test `no task line without a readable task`).
+
+---
+
+### Task 1: Backend `member.timeZone`
+
+**Files:**
+- Modify: `backend/src/superTabs/model.ts` (`Person.timeZone?: string`)
+- Modify: `backend/src/superTabs/profile.ts` (`setTimeZone`)
+- Modify: `backend/src/superTabs/commands.ts` (schema line beside `member.status`, viewer rule beside `member.username`, dispatch)
+- Test: `backend/src/superTabs/profile.test.ts`
+
+**Interfaces:**
+- Produces: command `{ type: 'member.timeZone', timeZone: string | null }` (string 1..64); readers get `people[].timeZone`.
+
+- [x] **Step 1: Failing tests** in `profile.test.ts`, `describe('time zone')`: `sets and clears the person's own zone` (`Asia/Ho_Chi_Minh` stored, `null` deletes it); `refuses an unknown zone and an agent` (`Mars/Base` throws with code `TIME_ZONE`; an agent actor throws; nothing stored); `a viewer may set their own` (viewer actor succeeds).
+- [x] **Step 2:** `cd backend && npx vitest run src/superTabs/profile.test.ts` fails on the unknown command.
+- [x] **Step 3:** `setTimeZone(state, actor, timeZone: string | null)` in `profile.ts`: person only (`HUMAN_REQUIRED`), `knownTimeZone` from `digest.ts` or `fail('TIME_ZONE', 'Name a time zone such as Asia/Ho_Chi_Minh.', 400)`; null deletes. Add the command to the viewer-allowed list with `member.username`.
+- [x] **Step 4:** the same run passes; `npx tsc --noEmit -p .` clean.
+- [x] **Step 5:** commit.
+
+### Task 2: Desktop reports the reader's zone
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/model.dart` (`SuperTabPerson.timeZone`)
+- Create: `desktop/lib/super_tabs/local_time_zone.dart` (conditional export), `local_time_zone_native.dart`, `local_time_zone_web.dart`
+- Modify: `desktop/lib/super_tabs/profile_actions.dart` (`reportTimeZone`), `desktop/lib/super_tabs/controller.dart` (call after a read)
+- Modify: `desktop/test/support/super_tab_fixture.dart` (`member.timeZone` like `member.status`)
+- Test: `desktop/test/super_tab_time_zone_test.dart`
+
+**Interfaces:**
+- Produces: `String? SuperTabPerson.timeZone`; `String? superTabLocalTimeZone()` with a `@visibleForTesting` override `superTabLocalTimeZoneOverride`; `Future<void> SuperTabController.reportTimeZone()`.
+
+- [x] **Step 1: Failing tests:** `reads a person's zone` (fromJson); `zoneFromLocaltimeLink` maps `/var/db/timezone/zoneinfo/Asia/Ho_Chi_Minh` and `/usr/share/zoneinfo/Europe/Berlin` to their names and `/etc/foo` to null; `reports the zone once when it differs` (fixture records one `member.timeZone` after `refresh()`, none after a second refresh); `does not report a zone already stored`; `a refused report is not sent again` (fixture refuses the command: no error surfaced, one attempt over two refreshes).
+- [x] **Step 2:** `flutter test test/super_tab_time_zone_test.dart` fails.
+- [x] **Step 3:** native reads `TZ` when it is an `Area/City` name, else the `/etc/localtime` link after `zoneinfo/`, else Linux's `/etc/timezone`; Windows null. Web reads `Intl.DateTimeFormat().resolvedOptions().timeZone` through `dart:js_interop`. The controller calls `reportTimeZone()` after a read that built a snapshot, unawaited; it remembers the value it tried.
+- [x] **Step 4:** the test file passes.
+- [x] **Step 5:** commit.
+
+### Task 3: Local time from a zone name
+
+**Files:**
+- Modify: `desktop/pubspec.yaml`, `desktop/pubspec.lock` (`timezone: ^0.11.2`)
+- Create: `desktop/lib/super_tabs/zone_time.dart`
+- Test: `desktop/test/super_tab_zone_time_test.dart`
+
+**Interfaces:**
+- Produces: `Future<TimeOfDay?> superTabTimeIn(String? zone, DateTime nowUtc)`.
+
+- [x] **Step 1: Failing tests:** `Asia/Ho_Chi_Minh at 08:42Z is 15:42`; `New York keeps daylight saving` (`2026-07-01T16:00Z` → 12:00, `2026-12-01T17:00Z` → 12:00); `unknown zone gives no time`; `null gives no time`.
+- [x] **Step 2:** fails (no file).
+- [x] **Step 3:** deferred import of `package:timezone/data/latest_10y.dart`, initialized once; `tz.getLocation` in a try, null on `LocationNotFoundException`.
+- [x] **Step 4:** passes. Note the `latest_10y` data size in the PR's dependency justification.
+- [x] **Step 5:** commit.
+
+### Task 4: The card and its hover
+
+**Files:**
+- Create: `desktop/lib/super_tabs/identity_card.dart` (`SuperTabIdentityFacts`, `SuperTabPersonFacts`, `SuperTabAgentFacts`, `SuperTabIdentityCard`, `SuperTabHoverCard`)
+- Test: `desktop/test/super_tab_identity_card_test.dart`, `desktop/test/super_tab_identity_card_shots_test.dart` (screenshots only with `SUPER_TAB_CARD_SHOTS`)
+
+**Interfaces:**
+- Produces: `SuperTabHoverCard({required Widget child, required SuperTabIdentityFacts Function() facts, FocusNode? focusNode})`, `SuperTabHoverCard.openDelay = Duration(milliseconds: 500)`, `closeDelay = Duration(milliseconds: 150)`; keys `super-identity-card`, `super-identity-card-name`, `super-identity-card-time`, `super-identity-card-task`.
+
+- [x] **Step 1: Failing tests:** `a person's card shows name, status and local time`; `a person's card leaves out a time it does not know`; `an agent's card shows engine and model, machine and task`; `opens after the hover delay, not before`; `closes when the pointer leaves`; `stays open while the pointer crosses into the card`; `keyboard focus opens it and Escape closes it, focus kept`; `Tab reaches the task line and Enter opens the task`.
+- [x] **Step 2:** fails.
+- [x] **Step 3:** `OverlayPortal` + `CompositedTransformFollower` under the anchor, flipped above when there is no room below; `Timer`s for the delays; the card inside a `FocusTraversalGroup` so Tab follows the name.
+- [x] **Step 4:** passes; `python3 ../scripts/check-ui-style.py` passes.
+- [x] **Step 5:** commit.
+
+### Task 5: Wire the card into the chat
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/message_row.dart` (wrap avatar and name; drop the avatar's identity tooltip; person name focusable)
+- Modify: `desktop/lib/super_tabs/view.dart` (build facts; open a task with `c.select`)
+- Test: `desktop/test/super_tab_identity_card_view_test.dart`
+
+**Interfaces:**
+- Consumes: Tasks 2–4. Produces: `SuperTabMessageRow.identity` (`SuperTabIdentityFacts Function()?`).
+
+- [x] **Step 1: Failing tests** on the `ConversationServer` fixture: `hovering a person's name shows their card with local time`; `hovering an agent's avatar shows its machine, model and task, and the task opens its chat`; `a grouped line has no card`; `no task line without a readable task`.
+- [x] **Step 2:** fails.
+- [x] **Step 3:** person facts from `_people` (`statusAt(now)`, `superTabTimeIn(person.timeZone, now)`); agent facts from `SuperTabAgentInfo(c, widget.app, agent)` (`engine`, `model`, `machine`, task line, `onOpenTask` selecting `taskGroup.id`).
+- [x] **Step 4:** passes; `flutter test test/laid_out_list_test.dart` and `check-ui-style.py` pass; before/after screenshots, light and dark, into the PR.
+- [x] **Step 5:** commit.
diff --git a/docs/plans/2026-11-04-personal-lead-autostart-plan.md b/docs/plans/2026-11-04-personal-lead-autostart-plan.md
new file mode 100644
index 000000000..d21022c0e
--- /dev/null
+++ b/docs/plans/2026-11-04-personal-lead-autostart-plan.md
@@ -0,0 +1,126 @@
+# Personal Swarm Lead Auto-Start Implementation Plan
+
+> **For agentic workers:** The assigned Engineer implements this plan task by task in this session, test first
+> (Swarm project instructions, Engineer role). No Execution Handoff.
+
+**Goal:** In a person's Personal Swarm, a message sent in a project chat that has no Lead starts that project's Lead
+on the person's own machine and is delivered to it once it runs, instead of "Not sent · this chat has no Lead".
+
+**Architecture:** Desktop starts the Lead, the backend keeps the message and the one-start guarantee.
+
+- The person's Desktop already starts a project's Product Manager on its own machine (`SuperTabLaunch`: a native
+ start, then `agent.add` with `lead: true`). Only Desktop knows the project's repo folder: a Personal project's panes
+ stay on the person's computers and the server learns only the project's name (`personal_projects.dart`). So the
+ start stays on Desktop, run without the New Harness form.
+- Backend `message.send`: a person's message in a Personal Swarm project chat with no Lead is recorded as waiting for
+ the project's Lead (`project.leadWaiting`, ids and times only, at most 20).
+- Backend `lead.claim` (new, person only, Personal Swarm only): the one start per project. The first claim answers
+ `start`; while a claim from another machine is under 10 minutes old, a claim answers `waiting`. A claim from the
+ same machine replaces its own (that Desktop's earlier attempt ended). A Team Swarm refuses it.
+- When a Lead joins the project chat (`agent.add` with `lead`, or a Swarm-started Lead's `agent.started`), the
+ waiting messages of the last 30 minutes are delivered to it (`lateDeliveries`, as a Buddy's waiting messages are),
+ and the waiting list and claim are cleared.
+- Desktop `PersonalLeadStarter`: on a send in the Personal Swarm's project chat with no Lead it claims, then starts the
+ Lead on this Mac (or the person's machine whose pane holds the project's repo), in the repo's folder when the project
+ has one, else a new folder in the default Harness projects folder, Claude Code first, else Codex. One start per
+ project at a time on this Desktop, and the server's claim across Desktops.
+- Desktop receipt: "Starting a Lead…" (muted, spinner) while a start runs; "Couldn't start a Lead: <reason> · Add a
+ Lead" when it failed; a Team Swarm keeps "Not sent · this chat has no Lead · Add a Lead".
+
+**Tech Stack:** TypeScript backend (Vitest), Flutter Desktop (widget tests with the memory store and a fake sign-in).
+
+**Spec:** Swarm task #2633, conversation c85441c4d697a0af4e04631f (Huy, 11-04).
+
+## Global Constraints
+
+- Personal Swarm only; Team Swarms keep today's behaviour, message and receipt alike.
+- Never more than one Lead start for one project at a time.
+- Swarm code stays out of `cli/src/core`. Desktop tests use a memory store and a fake sign-in; no test signs out the
+ real CLI.
+- Harness Design Language: the receipt line keeps its existing form (14 px icon, 12 px metadata text, quiet link
+ actions); copy follows the Naming System ("Lead" as the existing receipt says it).
+- PR body's first line: `Requested by [email protected] through Harness.`
+
+## Design
+
+- Growth: `leadWaiting` holds at most 20 ids and is cleared when a Lead joins; entries older than 30 minutes are never
+ delivered and are dropped on the next write. `leadClaim` is one record per project, replaced or cleared.
+- Concurrency: both are written by commands, which run under the Swarm state's one lock, so two claims are ordered.
+- Read cost: no new read; the late deliveries read each waiting message by its primary key (at most 20).
+- Scale: 10x people means 10x Personal Swarms, each with its own state; nothing is shared between them.
+- Compatibility: an older Desktop sends no claim and keeps "Not sent"; its message still waits for the Lead. The phone
+ says "Waiting for a Lead · open Harness on your computer to start one" for a message the server keeps (River, 11-04);
+ a phone with an older server keeps "Not sent". A newer Desktop against an older backend gets `lead.claim` refused as unknown and shows the start failed with
+ Add a Lead.
+- Migration and rollback: new optional fields only; a rollback leaves them unread.
+- Audience: the server refuses `lead.claim` outside the owner's Personal Swarm and from anyone but a person who manages
+ the project; deliveries go only to the Lead that joined, of the person's own messages. A Buddy reads no claim (it names
+ a machine).
+- Identity: the Lead runs on the person's own machine as them, through the existing local start.
+- Failure: a refused claim or a failed start says why on the receipt with Add a Lead.
+- Platforms: Desktop on macOS, Linux and Windows run the same code; the phone is unchanged.
+
+## Review Focus
+
+- A Team Swarm send is unchanged (no waiting record, no claim, same receipt).
+- Two quick sends produce one native start and one claim.
+- Late deliveries reach only the joined Lead and only the person's own main-chat messages.
+- The start uses the repo folder on the machine that holds it, never a folder from another machine.
+
+---
+
+### Task 1: Backend: waiting messages and the claim
+
+**Files:**
+- Modify: `backend/src/superTabs/commands.ts`, `backend/src/superTabs/projects.ts`, `backend/src/superTabs/model.ts`,
+ `backend/src/superTabs/store.ts`
+- Test: `backend/src/superTabs/leadWaiting.test.ts`
+
+**Interfaces:**
+- `lead.claim { projectId, machineId }` → result `{ leadStart: 'start' | 'waiting' }`.
+- `SwarmProject.leadWaiting?: Array<{ id: string; at: number }>`, `SwarmProject.leadClaim?: { id; machineId; at }`.
+- `CommandEffects.lateDeliveries[].lead?: true`.
+
+- [x] Failing tests: a Personal Swarm send with no Lead records the message; a claim answers `start`, a second from
+ another machine `waiting`; `agent.add` as Lead (with a repo, and without) yields a late delivery of the message
+ and clears both; a Team Swarm records nothing and refuses the claim.
+- [x] Run them and watch them fail.
+- [x] Implement; run the tests of the changed files.
+
+### Task 2: Desktop: the starter
+
+**Files:**
+- Create: `desktop/lib/super_tabs/personal_lead.dart`
+- Modify: `desktop/lib/super_tabs/view.dart` (send path)
+- Test: `desktop/test/super_tab_personal_lead_test.dart`
+
+**Interfaces:**
+- `PersonalLeadStarter.of(app)`: `wants(c, conversationId)`, `afterSend(c, conversationId)`, `stateOf(...)` →
+ starting / failed(reason).
+
+- [x] Failing tests: a send with no Lead claims and starts one in the repo's folder (repo case) or a new Harness folder
+ (no-repo case), and joins it as Lead; a failed start records the reason; two quick sends make one start; a Team
+ Swarm starts nothing.
+- [x] Run them and watch them fail.
+- [x] Implement; run the tests of the changed files.
+
+### Task 3: Desktop: the receipt note
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/message_receipt.dart`
+- Test: `desktop/test/super_tab_receipt_test.dart`, `desktop/test/super_tab_personal_lead_shots_test.dart`
+
+- [x] Failing tests: "Starting a Lead…" while starting; "Couldn't start a Lead: <reason>" with Add a Lead after a
+ failure; a Team Swarm still says "Not sent · this chat has no Lead".
+- [x] Run them and watch them fail.
+- [x] Implement; capture light and dark screenshots of both lines; run the receipt tests.
+
+### Task 4: Phone: the waiting line (River, 11-04)
+
+**Files:**
+- Modify: `mobile/lib/swarm/model.dart`, `mobile/lib/swarm/swarm_message_receipt.dart`
+- Test: `mobile/test/swarm/swarm_no_lead_receipt_test.dart`
+
+- [x] Failing test: a message the server keeps for the Lead (`leadWaiting`) reads "Waiting for a Lead · open Harness on
+ your computer to start one", without Not sent or Add a Lead.
+- [x] Implement; run the phone receipt tests.
diff --git a/docs/plans/2026-11-04-relay-offline-hold-plan.md b/docs/plans/2026-11-04-relay-offline-hold-plan.md
new file mode 100644
index 000000000..025a7dd33
--- /dev/null
+++ b/docs/plans/2026-11-04-relay-offline-hold-plan.md
@@ -0,0 +1,119 @@
+# Relay: no dial for a machine the list shows offline — Implementation Plan
+
+> Written by the writing-plans skill as this project's instructions use it: the Engineer implements it task by task,
+> each failing test committed before its code. No execution handoff.
+
+**Goal:** The CLI relay never opens a backend socket for a machine the account's machine list shows offline; it
+dials again once the list shows it online. A machine refused as offline with no list to go by is asked again after
+30 s, 1, 2, 4, then every 5 minutes instead of every 30 s.
+
+**Architecture:** The gateway's machine list (`accountHttp.ts`, the one `GET /api/machines` cache) tells the relay
+pool which machines it last read as offline. `RemoteRelayPool.connect()` answers a select of such a machine with
+`MACHINE_OFFLINE` from that record, without a socket, and while it holds selects asks the list again at most every
+5 minutes (one read for every machine, served from the cache when anything else read it lately). A list that
+says a held machine is online lifts its hold and its backoff, so the next select dials at once. The background
+pools share the window pool's record, as they share its refusals.
+
+**Tech Stack:** TypeScript, Node `ws`, vitest.
+
+**Spec:** Task #2598's brief (Ken's database plan, Group B item 5, 2026-11-04); `cli/src/lib/remoteRelay.ts`'s
+2026-10-28 backoff (#2027).
+
+## Global Constraints
+
+- Owns the CLI relay dialer and its backoff and their tests: `cli/src/lib/remoteRelay.ts`,
+ `cli/src/gateway/accountHttp.ts`, `cli/src/gateway/start.ts` (wiring only). Nothing in `cli/src/core`.
+- CLI specs with a scratchpad TMPDIR (`TMPDIR=$(mktemp -d)`); temp files only in `mktemp -d` folders.
+- Never run a test that signs the Mac out of the real CLI.
+- Measure refused opens per hour before and after from the backend logs (aggregates only): the `ws counters` line
+ and the relay's `web-ws disconnected` lines with `client=relay`, same weekday hours.
+- PR body first line: "Requested by [email protected] through Harness."
+- Ships with the next CLI release, through the PM's batch.
+
+## Design
+
+- **Growth:** the record holds one id per machine on the account's list, replaced whole on every list read; a
+ sign-out (list null) clears it.
+- **Concurrency:** one gateway process, single-threaded; the pools share one in-memory record.
+- **Read cost:** held selects cost no backend read; the list is re-read at most every 5 minutes per daemon while
+ selects are held, and not at all when something else read it within that time.
+- **Scale:** at 10× offline machines per user the dials stay 0 and list reads stay ≤12 an hour per daemon; the
+ first warning is the `ws counters` relay connects per minute.
+- **Compatibility:** no wire change. Old backends and old windows see the same `MACHINE_OFFLINE` (1013) they see
+ today. Old CLIs keep their 30 s backoff until they update.
+- **Migration + rollback:** none; in-memory only. Rollback is the previous CLI.
+- **Audience:** the backend still refuses every select it gets; this only sends fewer.
+- **Identity:** the daemon's own sign-in, as today.
+- **Failure:** a held select is answered `MACHINE_OFFLINE`, which the app already shows and parks on. A list that
+ could not be read keeps the last one; one older than 15 minutes holds nothing, and the ordinary backoff decides.
+- **Platforms:** all; no platform code.
+
+## Review Focus
+
+- A machine that comes online while nothing reads the list: held at most 5 minutes (the next select re-reads it).
+- A list from before a sign-in change: a null list (sign-out) lifts every hold.
+- A machine the list does not name (a shared machine, a list from before it was added): never held by the list.
+- An explicit redial (`forceReconnect`) of a listed-offline machine: held too; the backend would refuse it.
+- A machine the list shows online that the backend still refuses: the longer offline backoff, not the list. Both read
+ the same presence, so they disagree only for a moment.
+- An explicit redial inside the backend's retry-after: waits it out even when the backoff step equals it (the old
+ record lost that when the two were equal; Task 2 keeps the retry-after's end on its own).
+
+---
+
+### Task 1: The pool holds machines the list shows offline
+
+**Files:**
+- Modify: `cli/src/lib/remoteRelay.ts`
+- Test: `cli/src/lib/remoteRelayListed.spec.ts` (new)
+
+**Interfaces:**
+- Produces: `RemoteRelayPool.listed(offline: string[] | null): void`; option
+ `recheckList?: () => void` on `RemoteRelayPoolOptions`; shared record option `listedOffline?: ListedOffline`.
+
+- [x] **Step 1: Write the failing tests** (`remoteRelayListed.spec.ts`, a fake backend that answers every select
+ `MACHINE_OFFLINE` and counts sockets):
+ - `listed([m])` then window, background and redial selects: each rejects `{ message: 'MACHINE_OFFLINE',
+ closeCode: 1013 }`; 0 sockets, also 10 minutes later.
+ - then `listed([])` (online): the next select dials (1 socket).
+ - after a refusal backoff, `listed([])` lifts it: the next select dials at once.
+ - `listed(null)`: nothing held; a list read 15 minutes ago holds nothing.
+ - held selects call `recheckList` once, again only 5 minutes later.
+ - a machine absent from the list is dialled as before.
+- [x] **Step 2: Run and watch them fail:** `cd cli && TMPDIR=$(mktemp -d) npx vitest run src/lib/remoteRelayListed.spec.ts`
+- [x] **Step 3: Implement** `listed()`, the hold in `connect()`, the shared record passed to background pools.
+- [x] **Step 4: Run them and `src/lib/remoteRelay*.spec.ts`; all pass.**
+- [x] **Step 5: Commit** test, then code.
+
+### Task 2: A machine refused as offline backs off to 5 minutes
+
+**Files:**
+- Modify: `cli/src/lib/remoteRelay.ts` (`backOff`)
+- Test: `cli/src/lib/remoteRelayRefusal.spec.ts`
+
+- [x] **Step 1: Failing test:** `MACHINE_OFFLINE` with `retryAfterMs: 30_000` is dialled again after 30 s, 60 s,
+ 2, 4, 5, 5 minutes; other refusals keep 1, 2, 4 … 30 s.
+- [x] **Step 2: Run, watch it fail.**
+- [x] **Step 3: Implement:** for `MACHINE_OFFLINE`, backoff `min(OFFLINE_BACKOFF_MAX_MS = 5 min, 30 s × 2^(n-1))`.
+- [x] **Step 4: Run the relay specs; pass.**
+- [x] **Step 5: Commit** test, then code.
+
+### Task 3: The gateway's machine list tells the pool
+
+**Files:**
+- Modify: `cli/src/gateway/accountHttp.ts` (dep `offline?(machineIds: string[] | null)`, return `recheck(maxAgeMs)`),
+ `cli/src/gateway/start.ts` (wire `offline` → `relayPool.listed`, `recheckList` → `recheck`)
+- Test: `cli/src/gateway/accountHttp.spec.ts`
+
+- [x] **Step 1: Failing test:** a list read with one machine `stopped` and one `running` calls `offline([stopped])`;
+ a sign-out calls `offline(null)`; `recheck(60_000)` within a minute of a read makes no request.
+- [x] **Step 2: Run, watch it fail.**
+- [x] **Step 3: Implement.**
+- [x] **Step 4: Run `src/gateway` and relay specs, `npm run typecheck`.**
+- [x] **Step 5: Commit** test, then code.
+
+### Task 4: Evidence
+
+- [ ] Before/after refused opens per hour from the backend logs (aggregates): before ~3,600 an hour (the brief, 2026-11-04);
+ after read hourly from the production logs by an agent on Ken's Mac once the CLI release ships (River, 2026-11-04).
+- [x] Red/green evidence comment on the PR.
diff --git a/docs/plans/2026-11-04-swarm-restart-keeps-swarm-plan.md b/docs/plans/2026-11-04-swarm-restart-keeps-swarm-plan.md
new file mode 100644
index 000000000..15893e4c1
--- /dev/null
+++ b/docs/plans/2026-11-04-swarm-restart-keeps-swarm-plan.md
@@ -0,0 +1,82 @@
+# A restart never closes a Swarm or shows it under a wrong name: plan
+
+> Way of working: this plan's Engineer implements it task by task, test first (test-driven-development), in one pull
+> request. No subagents, no execution handoff.
+
+**Goal:** A Swarm open in Desktop stays open, under its own name, while the backend or the local daemon restarts. While
+its reads fail it shows the quiet "Reconnecting · 1m" pill it already has, and it recovers by itself.
+
+**Architecture:** Today a Swarm read refused as `NOT_FOUND` or `FORBIDDEN` revokes the open Swarm at once
+(`SuperTabController._readFailure`): its state, messages and poll are dropped, the view says "Conversation
+unavailable.", the Swarm dropdown's label falls back to the default "Swarm", and with Personal picked the tab moves to
+Personal. One such answer during a restart is enough. The fix asks the account's Swarm list first: a refusal revokes
+only when a list read that succeeded no longer names the Swarm. While the list still names it, or cannot be read, the
+refusal is a failed read like any other: the Swarm keeps what it shows, says Reconnecting and reads again at its next
+poll.
+
+**Tech Stack:** Flutter Desktop (`desktop/lib/super_tabs/controller.dart`, `client.dart`), flutter_test with fake
+transports, memory stores and a fake sign-in.
+
+**Spec:** Task #2647 (Dee, 2026-11-04 11:02 VN): "autonomous.ai" closed and came back under a default name while the
+backend restarted twice and CLI v0.5.35 restarted daemons.
+
+## Global Constraints
+
+- Desktop only. No backend or CLI change; Swarm code stays out of `cli/src/core`.
+- A real loss still revokes: the account's list, read successfully, without this Swarm. A first read refused for a
+ Swarm the list does not name stays final, as today.
+- Tests use a memory store and a fake sign-in; none touch the real CLI login.
+- No new switch: the behavior ships on.
+
+## Review Focus
+
+- A Swarm the person really lost (removed, deleted) still closes: only a successful list read keeps it open.
+- A refusal never leaves a Swarm in a state that can neither recover nor close (the poll keeps running while kept).
+- One list read per refusal at most, shared by concurrent refusals; no extra reads while reads succeed.
+
+## Design
+
+- growth: N/A because nothing is stored; the check reuses the existing list read.
+- concurrency: one check in flight per Swarm (a flag on its controller); the list read joins discovery in flight.
+- read cost: a list read only after a refusal, at most one per poll; none while reads succeed.
+- scale: at 10x Swarms per account, still one list read per refused Swarm read; the list's page count warns first.
+- compatibility: no wire change; old and new backends answer the same reads.
+- migration + rollback: N/A because no stored data changes; rollback is the previous build.
+- audience: the server still enforces every read; this only decides what Desktop keeps on screen.
+- identity: reads stay the signed-in person's own.
+- failure: a kept Swarm says Reconnecting with how long, never nothing; a confirmed loss says so as today.
+- platforms: Desktop (macOS, Linux, Windows) and the web build, which share the controller.
+
+## Task 1: a refused read during a restart keeps the Swarm open under its name
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/controller.dart` (`_readFailure`, new `stillListed` hook)
+- Modify: `desktop/lib/super_tabs/client.dart` (wires the hook to the Swarm list)
+- Test: `desktop/test/super_tab_first_read_test.dart`, `desktop/test/super_tab_swarm_switcher_test.dart`
+
+**Interfaces:**
+- `SuperTabController({..., Future<bool> Function()? stillListed})`: true while the account's list names the Swarm,
+ false once a list read that succeeded leaves it out; a throw means it cannot be told.
+- `SuperTabClient.stillListed(String id)`: reads the list (joining a read in flight) and answers as above.
+
+- [x] Failing test (controller): reads drop, then are refused `NOT_FOUND` and `FORBIDDEN` for a while, with the list
+ still naming the Swarm (and unreadable for part of it): the Swarm keeps its snapshot and name, says Reconnecting,
+ is never revoked, and shows the backend's state again when reads answer.
+- [x] Failing test (controller): the same refusal with the list no longer naming the Swarm revokes it.
+- [x] Failing test (app): Swarm "autonomous.ai" open in a tab, the fake backend drops and refuses its reads for a while:
+ the tab stays, bound to the Swarm, the dropdown's label and the Swarm menu say "autonomous.ai" throughout, never
+ "Swarm", and it is not moved to Personal.
+- [x] Watch them fail; implement; watch them pass; run the tests of the files changed and of their importers.
+
+## Task 2: a Swarm tab never shows an agent's folder, project or type as its name
+
+River (2026-11-04): never show a fallback folder name as a Swarm's name.
+
+**Files:**
+- Modify: `desktop/lib/state/workspace_status.dart` (`workspaceTabNames`), `desktop/lib/state/app_state.dart`
+ (agent titles: `_syncAgentName` and the two first-agent titles)
+- Test: `desktop/test/workspace_status_test.dart`
+
+- [x] Failing test: a tab bound to Swarm "autonomous.ai", not marked as named by hand, holding a Lead whose folder is
+ `~/harnesses/swarms`, is named "code" by the vote today; a restarted daemon's agent rename would retitle it.
+- [x] A tab bound to a Swarm is named by the Swarm alone: it takes no part in the vote, and agent titles skip it.
diff --git a/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-dark.png b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-dark.png
new file mode 100644
index 000000000..a51b6cec9
Binary files /dev/null and b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-dark.png differ
diff --git a/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-light.png b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-light.png
new file mode 100644
index 000000000..f3c44af87
Binary files /dev/null and b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-failed-light.png differ
diff --git a/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-dark.png b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-dark.png
new file mode 100644
index 000000000..331d26877
Binary files /dev/null and b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-dark.png differ
diff --git a/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-light.png b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-light.png
new file mode 100644
index 000000000..ac9f6ae25
Binary files /dev/null and b/docs/plans/assets/2026-11-04-personal-lead/personal-lead-starting-light.png differ
diff --git a/docs/plans/assets/chat-image-viewer/after-dark.png b/docs/plans/assets/chat-image-viewer/after-dark.png
new file mode 100644
index 000000000..71ddda282
Binary files /dev/null and b/docs/plans/assets/chat-image-viewer/after-dark.png differ
diff --git a/docs/plans/assets/chat-image-viewer/after-light.png b/docs/plans/assets/chat-image-viewer/after-light.png
new file mode 100644
index 000000000..deb65963e
Binary files /dev/null and b/docs/plans/assets/chat-image-viewer/after-light.png differ
diff --git a/docs/plans/assets/chat-image-viewer/before-dark.png b/docs/plans/assets/chat-image-viewer/before-dark.png
new file mode 100644
index 000000000..5492ce3e8
Binary files /dev/null and b/docs/plans/assets/chat-image-viewer/before-dark.png differ
diff --git a/docs/plans/assets/chat-image-viewer/before-light.png b/docs/plans/assets/chat-image-viewer/before-light.png
new file mode 100644
index 000000000..6ad1ecf66
Binary files /dev/null and b/docs/plans/assets/chat-image-viewer/before-light.png differ
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 0ba8581b4..7fa6d2857 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -54,6 +54,10 @@ class SuperTabPerson {
joinedVia = row['joinedVia'] as String?,
avatar = SuperTabAvatarPicture.fromJson(row['avatar']),
status = SuperTabPersonStatus.fromJson(row['status']),
+ timeZone = switch (row['timeZone']) {
+ final String zone when zone.trim().isNotEmpty => zone,
+ _ => null,
+ },
chosenUsername = row['username'] as String?,
name = switch (row['name']) {
final String name when name.trim().isNotEmpty => name,
@@ -70,12 +74,17 @@ class SuperTabPerson {
joinedVia = person.joinedVia,
avatar = person.avatar,
status = person.status,
+ timeZone = person.timeZone,
chosenUsername = person.chosenUsername,
name = person.name;
final String id, email, role;
final SuperTabAvatarPicture? avatar;
final SuperTabPersonStatus? status;
+ /// Their time zone's IANA name, as their own app told the Swarm (Desktop's
+ /// local_time_zone.dart); null until it has. The phone shows no card yet.
+ final String? timeZone;
+
/// How the Swarm tags them (`@username`), as the server sends it; from an
/// older server, their default ([superTabUsernames]). Desktop's rule.
final String username;
@@ -542,9 +551,18 @@ class SuperTabProject {
status = SuperTabProjectStatus.read(row['status']),
repository = row['repository'] is Map
? Map.unmodifiable(superTabMap(row['repository']))
- : null;
+ : null,
+ leadWaiting = {
+ for (final entry in row['leadWaiting'] as List? ?? const [])
+ if (entry is Map && entry['id'] is String) entry['id'] as String,
+ };
final String id, name, ownerId, leadConversationId;
+ /// The person's messages the server keeps for this project's Lead: a
+ /// Personal Swarm's chat with none, whose Lead their computer starts
+ /// (backend leadStart.ts). Empty from a server before it.
+ final Set<String> leadWaiting;
+
/// Read as the desktop's model reads it; the phone starts no agents.
final String skillMode;
diff --git a/mobile/lib/swarm/swarm_message_receipt.dart b/mobile/lib/swarm/swarm_message_receipt.dart
index 2d95264b4..1a40af37f 100644
--- a/mobile/lib/swarm/swarm_message_receipt.dart
+++ b/mobile/lib/swarm/swarm_message_receipt.dart
@@ -137,6 +137,17 @@ class _SwarmMessageReceiptState extends State<SwarmMessageReceipt>
!group.isBuddyChat &&
reader.error == null) {
_wakeUpAt(null, now);
+ // Kept for the Lead the person's computer starts (a Personal Swarm,
+ // task #2633): it will be delivered, so it is not "Not sent".
+ if (snapshot.projectFor(group.id)?.leadWaiting.contains(message.id) ==
+ true) {
+ return _line(
+ icon: LucideIcons.clock,
+ color: AppPalette.textSecondary,
+ title:
+ 'Waiting for a Lead · open Harness on your computer to start one',
+ );
+ }
return _noLead(context, c, snapshot.isProjectLead(group.id));
}
// Said only of a recipient of this chat, from what was just read: a row
diff --git a/mobile/test/swarm/swarm_no_lead_receipt_test.dart b/mobile/test/swarm/swarm_no_lead_receipt_test.dart
index 447d14a5e..5a597b0a8 100644
--- a/mobile/test/swarm/swarm_no_lead_receipt_test.dart
+++ b/mobile/test/swarm/swarm_no_lead_receipt_test.dart
@@ -53,13 +53,24 @@ void main() {
String? kind,
String role = 'owner',
bool machines = true,
+ bool waiting = false,
FutureOr<Object?> Function(Map<String, dynamic>? body)? command,
}) {
final fake = FakeSwarm();
fake.routes['/api/super-tabs/$tab/parts'] = (_) {
final load = firstLoad(
head: headData(
- projects: [swarmProject(project, 'Mobile', repo: harnessRepo)],
+ projects: [
+ {
+ ...swarmProject(project, 'Mobile', repo: harnessRepo),
+ // The server keeps the message for the project's Lead: a
+ // Personal Swarm's chat with none (backend leadStart.ts).
+ if (waiting)
+ 'leadWaiting': [
+ {'id': 'm1', 'at': 1},
+ ],
+ },
+ ],
),
groups: [
if (chat != leadChat)
@@ -149,6 +160,23 @@ void main() {
expect(find.text('Add a Lead'), findsOneWidget);
});
+ // River, 11-04 (task #2633): in a Personal Swarm the server keeps the
+ // message for the Lead the person's computer starts, so it is not "Not
+ // sent"; the phone starts none itself.
+ testWidgets('a message the server keeps for the Lead waits for one', (
+ tester,
+ ) async {
+ await show(tester, rig(waiting: true));
+ expect(
+ find.text(
+ 'Waiting for a Lead · open Harness on your computer to start one',
+ ),
+ findsOneWidget,
+ );
+ expect(find.text(line), findsNothing);
+ expect(find.text('Add a Lead'), findsNothing);
+ });
+
testWidgets('none where the chat has its Lead', (tester) async {
await show(tester, rig(lead: true));
expect(find.text(line), findsNothing);