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-02 1610: #2523 #2534 (#2557)

0xken155e05523b6bd5
diff --git a/backend/integration/superTabBuddySessions.test.ts b/backend/integration/superTabBuddySessions.test.ts
index 70024bcae..a30ab065a 100644
--- a/backend/integration/superTabBuddySessions.test.ts
+++ b/backend/integration/superTabBuddySessions.test.ts
@@ -198,19 +198,37 @@ describe('a Buddy thread session', () => {
expect(text(await f.store.messages(peer, f.tab, f.chat, { thread: root }))).toEqual(['main 12', 'Measure prod CPU for the last day'])
})
- it('runs at most 3 at once, and of two starts racing for the last place exactly one wins', async () => {
- const f = await swarm()
- const roots = [await f.say('one'), await f.say('two'), await f.say('three'), await f.say('four')]
+ it('has no count of its own: a session past the old limit of 3 starts, and two starting together both do', async () => {
+ const f = await swarm({ maxAgents: 10 })
+ const roots = [await f.say('one'), await f.say('two'), await f.say('three'), await f.say('four'), await f.say('five')]
await f.session(roots[0]!)
await f.reply(roots[1]!, 'second', { newSession: true })
- const raced = await Promise.allSettled([f.reply(roots[2]!, 'third', { newSession: true }), f.reply(roots[3]!, 'fourth', { newSession: true })])
- expect(raced.filter(r => r.status === 'fulfilled')).toHaveLength(1)
- expect(raced.flatMap(r => r.status === 'rejected' ? [(r.reason as { code?: string }).code] : [])).toEqual(['BUDDY_SESSIONS_FULL'])
+ await f.reply(roots[2]!, 'third', { newSession: true })
+ const raced = await Promise.allSettled([f.reply(roots[3]!, 'fourth', { newSession: true }), f.reply(roots[4]!, 'fifth', { newSession: true })])
+ expect(raced.map(r => r.status)).toEqual(['fulfilled', 'fulfilled'])
const chat = (await f.store.read(peer, f.tab)).state.conversations.find(c => c.id === f.chat)!
- expect(chat.buddySessions).toHaveLength(3)
+ expect(chat.buddySessions!.map(e => e.thread).sort()).toEqual([...roots].sort())
await expect(f.reply(roots[0]!, 'again', { newSession: true })).rejects.toMatchObject({ code: 'BUDDY_SESSION_EXISTS' })
})
+ it('stops at its machine\'s own limit, in words a person can act on, leaving no start or message, and starts once a place frees', async () => {
+ // The main Buddy and one session fill it.
+ const f = await swarm({ maxAgents: 2 })
+ const [a, b] = [await f.say('a'), await f.say('b')]
+ const { agentId } = await f.session(a)
+ const harnessId = (await f.store.read(peer, f.tab)).state.agents.find(x => x.id === agentId)!.harnessId
+ const before = await f.store.messages(peer, f.tab, f.chat, {})
+ await expect(f.reply(b, 'No room', { newSession: true })).rejects.toMatchObject({ code: 'MACHINE_FULL',
+ message: 'Peer Mac is already running as many agents as it allows. End a session there, or try again when one finishes.' })
+ const state = (await f.store.read(peer, f.tab)).state
+ expect(state.conversations.find(c => c.id === f.chat)!.buddySessions!.map(e => e.thread)).toEqual([a])
+ expect(state.machines!.find(m => m.machineId === 'peer-mac')!.maxAgents).toBe(2)
+ expect((await f.store.messages(peer, f.tab, f.chat, {})).messages.map(m => m.id)).toEqual(before.messages.map(m => m.id))
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: f.chat, thread: a, reason: 'ended' }, peer)
+ await f.execute({ type: 'agent.sessionClosed', agentId, harnessId } as Command, peer)
+ await expect(f.session(b, 'Room now')).resolves.toBeTruthy()
+ })
+
it('ends on its person\'s word: its session closes, its line stays in the thread, and only a new session continues there', async () => {
const f = await swarm()
const root = await f.say('Start here')
diff --git a/backend/integration/superTabSwarmBuddy.test.ts b/backend/integration/superTabSwarmBuddy.test.ts
index ad01d0443..767b9429e 100644
--- a/backend/integration/superTabSwarmBuddy.test.ts
+++ b/backend/integration/superTabSwarmBuddy.test.ts
@@ -321,6 +321,50 @@ describe('a project session', () => {
expect((await f.store.read(peer, f.tab, agentId)).state.conversations.map(c => c.id)).not.toContain(f.secret.conversationId)
})
+ it('reopens with its history and its project, as a thread\'s reply box sends it, naming none; of another project it reads none of it', async () => {
+ const f = await swarm()
+ const { chat } = await buddy(f)
+ const { thread, agentId } = await projectSession(f, chat, f.web.projectId, 'Plan web sync')
+ await send(f, chat, 'EARLIER ANSWER: use a queue', { replyTo: thread }, peer, agentId)
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'idle' }, peer)
+ const reopen = async (text: string, projectId?: string) =>
+ f.launch(String((await send(f, chat, text, { replyTo: thread, newSession: true, ...(projectId ? { sessionProjectId: projectId } : {}) })).result.startId))
+ const again = await reopen('Carry on')
+ expect((await f.store.read(peer, f.tab)).state.agents.find(a => a.id === again)).toMatchObject({ projectId: f.web.projectId, buddySession: { projectId: f.web.projectId } })
+ expect(await texts(f, chat, peer, again, { thread })).toEqual(['Plan web sync', 'EARLIER ANSWER: use a queue', 'Session ended: idle for 30 minutes.', 'Carry on'])
+ await send(f, chat, 'SECOND ANSWER', { replyTo: thread }, peer, again)
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'ended' }, peer)
+ // Another project's session in that thread reads its person's words alone, and the next keeps that project.
+ const other = await reopen('Now the secret project', f.secret.projectId)
+ const read = JSON.stringify(await f.store.messages(peer, f.tab, chat, { thread }, other))
+ expect(read).not.toContain('EARLIER ANSWER')
+ expect(read).not.toContain('SECOND ANSWER')
+ expect(read).toContain('Plan web sync')
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread, reason: 'ended' }, peer)
+ const third = await reopen('Back again')
+ expect((await f.store.read(peer, f.tab)).state.agents.find(a => a.id === third)).toMatchObject({ projectId: f.secret.projectId })
+ })
+
+ it('reopens a plain session plain, and refuses to reopen in a project its person lost, as it refuses a made-up one', async () => {
+ const f = await swarm()
+ const { chat } = await buddy(f)
+ const plain = await projectSession(f, chat, undefined, 'Measure prod CPU')
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread: plain.thread, reason: 'ended' }, peer)
+ const started = await send(f, chat, 'Carry on', { replyTo: plain.thread, newSession: true })
+ const again = await f.launch(String(started.result.startId))
+ expect((await f.store.read(peer, f.tab)).state.agents.find(a => a.id === again)!.buddySession!.projectId).toBeUndefined()
+
+ const lost = await projectSession(f, chat, f.secret.projectId, 'SECRET SESSION SENTINEL')
+ await f.execute({ type: 'buddy.sessionEnd', conversationId: chat, thread: lost.thread, reason: 'ended' }, peer)
+ const madeUp = await send(f, chat, 'x', { replyTo: lost.thread, newSession: true, sessionProjectId: 'invented-project' }).catch((e: { code?: string }) => e.code)
+ await f.execute({ type: 'project.sharing', projectId: f.secret.projectId, visibility: 'private', memberIds: [owner.sub] })
+ const before = (await f.store.read(peer, f.tab)).state.agents.length
+ const refused = await send(f, chat, 'y', { replyTo: lost.thread, newSession: true }).catch((e: { code?: string; message?: string }) => e)
+ expect((refused as { code?: string }).code).toBe(madeUp)
+ expect(JSON.stringify((refused as { message?: string }).message)).not.toContain('Secret')
+ expect((await f.store.read(peer, f.tab)).state.agents.length).toBe(before)
+ })
+
it('reads in its thread only its person\'s words and its own, never a main-Buddy root or excerpt', async () => {
const f = await swarm()
const { chat, main } = await buddy(f)
diff --git a/backend/src/superTabs/buddySessions.ts b/backend/src/superTabs/buddySessions.ts
index 4f5acc158..360e9ed10 100644
--- a/backend/src/superTabs/buddySessions.ts
+++ b/backend/src/superTabs/buddySessions.ts
@@ -7,8 +7,6 @@ import { isBuddy, isBuddyChat, isSwarmBuddyChat } from './buddies.js'
import { canReadProject, projectsOf } from './projects.js'
import { fail, stableId, type Agent, type AgentStart, type Author, type BuddySessionEntry, type Conversation, type MessageDraft, type SuperTabState } from './model.js'
-/** At most this many live or starting sessions per Buddy chat, the main Buddy not counted. */
-export const MAX_BUDDY_SESSIONS = 3
/** At most this many of the person's messages wait for a session that is still starting. */
export const MAX_SESSION_WAITING = 20
/** What a machine's host reports (`capabilities`) when it can run thread sessions. */
@@ -132,7 +130,8 @@ export function sessionReadsRow(reader: Pick<Agent, 'id' | 'buddyOf' | 'buddySes
if (own?.projectId) {
const owner = chatOwner(group as Conversation)
return row => (row.id === own.thread || row.thread === own.thread) && !lost(row) && (ownWords(row, owner?.id, reader.id)
- || (row.source as { kind?: unknown } | null | undefined)?.kind === SESSION_ENDED_KIND)
+ || (row.source as { kind?: unknown } | null | undefined)?.kind === SESSION_ENDED_KIND
+ || earlierSessionOf(row, own.projectId!))
}
if (own) return row => (row.id === own.thread || row.thread === own.thread) && !lost(row)
return row => !row.buddySession && !lost(row)
@@ -144,6 +143,12 @@ function ownWords(row: SessionRow, personId: string | undefined, selfId: string)
return !!author && ((author.kind === 'person' && author.id === personId) || (author.kind === 'agent' && author.id === selfId))
}
+/** Whether [row] is an agent's row of a session of [projectId] in this thread, so one reopened there has its history (Scholes,
+ * 11-02). The server sets the mark on the row: a main Buddy's rows and another project's session's never carry it. */
+function earlierSessionOf(row: SessionRow, projectId: string): boolean {
+ return (row.author as { kind?: unknown } | null | undefined)?.kind === 'agent' && row.buddySession === true && row.buddyProject === projectId
+}
+
/** In a person's one Buddy chat, the rows of a project its person no longer reads, or that is gone: each row of a project
* session's thread and each PM's private line carries its project (MessageDraft.buddyProject), and an older PM line its
* source's. On the row itself, so hiding has no limit (security review 2 of #2435). */
diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.ts
index 300e7d8c1..be4d57f37 100644
--- a/backend/src/superTabs/commands.ts
+++ b/backend/src/superTabs/commands.ts
@@ -36,7 +36,7 @@ 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 { BUILT_IN_ROLE_DEFAULTS, agentProjectId, audienceOf, canReadProject, deleteProject, isConfidential, 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 { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_BUDDY_SESSIONS, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
+import { BUDDY_SESSION_CAPABILITY, chatOwner, endSessionEntry, entryProject, liveSessions, mainBuddyOf, MAX_SESSION_WAITING, requireChatOwner, SESSION_ENDED_KIND, sessionAgentsOf, sessionOf, setSessions, type SessionEndReason } from './buddySessions.js'
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, renameBuddy, requireBuddyCommand, swarmBuddyChatId } from './buddies.js'
import { BUDDY_OWN_MACHINE_REFUSAL, CODEX_BUDDY_REFUSAL } from './buddyContract.js'
import { launchRefusedLine, leadJoined, leadStartFailed, leadStarting, placeLead } from './leadStart.js'
@@ -379,7 +379,9 @@ export interface CommandContext {
reply?: { id: string; conversationId: string; author: Author; createdAt: number; thread?: string | null; threadSource?: Record<string, unknown> | null
agentOnly?: true
/** In a Buddy chat: its thread has had a thread session (a `buddySession` reply), read by the store (buddySessions.ts). */
- sessionThread?: true }
+ sessionThread?: true
+ /** The project of the thread's latest session row: a session reopened there keeps it (Scholes, 11-02). */
+ sessionProject?: string }
/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */
openTags?: Array<{ messageId: string; createdAt: number }>
/** For `buddy.rename` and `buddy.create`: the names chosen in this Swarm's Buddy chats, quiet ones included, read by the
@@ -1009,12 +1011,18 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma
if (!pool?.observation?.capabilities?.includes(BUDDY_SESSION_CAPABILITY)) {
fail('BUDDY_SESSION_UNSUPPORTED', `Update Harness on ${pool?.name ?? 'your Buddy\'s computer'} to start sessions.`)
}
- if (liveSessions(state, chat).length >= MAX_BUDDY_SESSIONS) fail('BUDDY_SESSIONS_FULL', `${MAX_BUDDY_SESSIONS} sessions are running. End one to start another.`)
+ // Sessions have no count of their own (Scholes, 11-02): idle ones close themselves. The one limit is the machine's, which
+ // its owner set to protect it (Lead, 11-02), said in words a person can act on. A Buddy-only machine has none (below).
+ if (!pool.buddyOnly && machineSlots(state, pool) >= pool.maxAgents) {
+ fail('MACHINE_FULL', `${pool.name} is already running as many agents as it allows. End a session there, or try again when one finishes.`)
+ }
const contributor = person(state, main.contributorId)
// In the one Buddy chat a session works in one project its person reads, or, with none named, as the main Buddy does
// (spec: The model). A project's own chat has its project.
const swarm = isSwarmBuddyChat(chat)
- const project = swarm ? command.sessionProjectId ? readProject(state, actor, command.sessionProjectId) : undefined : groupProject(state, chat)
+ // Reopened in its thread with none named (a thread's reply box has no choice), it keeps its project, while its person reads it.
+ const projectId = command.sessionProjectId ?? context.reply?.sessionProject
+ const project = swarm ? projectId ? readProject(state, actor, projectId) : undefined : groupProject(state, chat)
const me = person(state, owner.id)
const folder = project ? { cwd: projectFolder(pool, project), worktree: true, ...(swarm ? { buddyNarrow: true as const } : {}) }
: { cwd: buddyHomeFolder(pool, me), worktree: false, buddyScope: 'swarm' as const, buddyProjects: buddyProjectsOn(state, pool, me) }
diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.ts
index 3a6faa8a7..ca267a7b2 100644
--- a/backend/src/superTabs/model.ts
+++ b/backend/src/superTabs/model.ts
@@ -112,7 +112,7 @@ export interface Agent {
/** A thread session's thread root and the main chat's last sequence it may read (buddySessions.ts). A project session also
* names its project (buddies.ts; Dee, 10-31): it reads that project alone, and is the only Buddy that writes into it. */
export interface BuddySession { thread: string; from: number; projectId?: string }
-/** A Buddy chat's live or starting thread session, at most MAX_BUDDY_SESSIONS (buddySessions.ts). `agentId` once it runs;
+/** A Buddy chat's live or starting thread session (buddySessions.ts); it leaves when the session ends. `agentId` once it runs;
* `waiting`, the person's messages sent while it started, delivered to it when it joins. */
export interface BuddySessionEntry { thread: string; startId: string; agentId?: string; at: number; waiting?: string[] }
export type AgentRole = 'builder' | 'reviewer'
diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.ts
index fed09a112..f042f3b0c 100644
--- a/backend/src/superTabs/store.ts
+++ b/backend/src/superTabs/store.ts
@@ -1362,14 +1362,16 @@ export class SuperTabStore {
// The thread's root says whose proposal the reply answers (buddyNews.ts): the reply itself, or one more read by id.
const root = reply?.thread && reply.thread !== reply.id
? await tx.superTabMessage.findFirst({ where: { id: reply.thread, tabId, conversationId: command.conversationId }, select: { source: true } }) : reply
- // In a Buddy chat: whether the thread ever had a session (buddySessions.ts), by the thread index, one row at most.
+ // In a Buddy chat: whether the thread ever had a session (buddySessions.ts), by the thread index, one row at most: its
+ // latest, whose project a session reopened there keeps.
const buddyChat = original.conversations.find(c => c.id === command.conversationId)
- const sessionThread = reply?.thread && buddyChat && isBuddyChat(buddyChat)
- ? !!await tx.superTabMessage.findFirst({ where: { tabId, conversationId: command.conversationId, thread: reply.thread, buddySession: true }, select: { id: true } })
- : false
+ const sessionRow = reply?.thread && buddyChat && isBuddyChat(buddyChat)
+ ? await tx.superTabMessage.findFirst({ where: { tabId, conversationId: command.conversationId, thread: reply.thread, buddySession: true },
+ orderBy: [{ sequence: 'desc' }, { id: 'desc' }], select: { buddyProject: true } })
+ : null
if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime(),
thread: reply.thread, threadSource: (root?.source ?? null) as Record<string, unknown> | null,
- ...(agentOnly(reply.source, reply.recipientIds) ? { agentOnly: true } : {}), ...(sessionThread ? { sessionThread: true as const } : {}) }
+ ...(agentOnly(reply.source, reply.recipientIds) ? { agentOnly: true } : {}), ...(sessionRow ? { sessionThread: true as const, ...(sessionRow.buddyProject ? { sessionProject: sessionRow.buddyProject } : {}) } : {}) }
}
if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)
// A stale save is refused with the stored text, to merge (instructions.ts); an older client's rule.set appends to it
diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.ts
index bdda43cd2..9a6511d54 100644
--- a/cli/src/core/experimentQueries.spec.ts
+++ b/cli/src/core/experimentQueries.spec.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../lib/registry.js'
import { fakeCore } from '../testing/fakeCore.js'
+import { processCoreApi } from '../services/processCoreApi.js'
import { answerExperimentQuery, answerMachineAddonsQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'
const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSession
@@ -27,6 +28,22 @@ describe('the cloud agents\' doors', () => {
})
describe('the Super Tab service\'s door', () => {
+ it('answers a Buddy session\'s turn through the real process path, to the Super Tab service alone', async () => {
+ const activity = vi.fn(async () => ({ harness: 'working' as const }))
+ const core = fakeCore({ agents: { activity } } as never)
+ const both = new Set(['superTabs', 'cloud'])
+ const api = (service: string) => processCoreApi('/data', service, { ask: async (query: string, payload: Record<string, unknown>) => {
+ const answer = await answerExperimentQuery(core, both, service, query, payload)
+ if (!answer) throw new Error('UNKNOWN_QUERY')
+ return answer
+ } })
+ expect(await api('superTabs').agents.activity(['harness'])).toEqual({ harness: 'working' })
+ expect(activity).toHaveBeenCalledWith(['harness'])
+ activity.mockClear()
+ expect(await api('cloud').agents.activity(['harness'])).toEqual({})
+ expect(activity).not.toHaveBeenCalled()
+ })
+
it('is the Super Tab service\'s alone, and hands its members\' waits to the core whole', async () => {
const superTabs = { attention: vi.fn(), cards: vi.fn(), cardRecap: vi.fn(), shareObservers: vi.fn(), screen: vi.fn(), input: vi.fn(), inputIfScreen: vi.fn() }
const core = fakeCore({ superTabs })
diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.ts
index f37848dc6..e2ea4fd22 100644
--- a/cli/src/core/experimentQueries.ts
+++ b/cli/src/core/experimentQueries.ts
@@ -43,7 +43,7 @@ import { nativeTurnCursorIn } from '../lib/nativeTurnObservations.js'
type Payload = Record<string, unknown>
type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account' | 'cloud' | 'superTabs' | 'transcripts'>
-const QUERIES: ReadonlySet<string> = new Set(['shown', 'close_swarm', 'keep_lead_alive', 'close_member', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input', 'super_tab_input_if_screen'])
+const QUERIES: ReadonlySet<string> = new Set(['shown', 'activity', 'close_swarm', 'keep_lead_alive', 'close_member', 'stopped', 'gone', 'creation_status', 'native_turns', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send', 'account', 'cloud_publish', 'cloud_ask', 'cloud_unask', 'super_tab_attention', 'super_tab_cards', 'super_tab_card_recap', 'super_tab_observers', 'super_tab_screen', 'super_tab_input', 'super_tab_input_if_screen'])
const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
const text = (value: unknown): string => (typeof value === 'string' ? value : '')
@@ -109,6 +109,12 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySet
? { ...await (core.agents.keepLeadAlive?.(agentId) ?? { ok: false, error: 'UNSUPPORTED' }) }
: { ...await (core.agents.closeMember?.(agentId, creationId as string | undefined) ?? { error: 'UNSUPPORTED' }) }
}
+ // Whether its agents are in a turn: a Buddy session's idle end asks before ending one (superTabs/host.ts).
+ case 'activity': {
+ if (service !== 'superTabs') return { error: 'NOT_SUPER_TABS' }
+ const ids = Array.isArray(payload.agentIds) ? payload.agentIds.filter((id): id is string => typeof id === 'string').slice(0, 64) : []
+ return { activity: await core.agents.activity(ids) }
+ }
case 'stopped':
return { stopped: !!text(payload.agentId) && await core.agents.stopped?.(text(payload.agentId)) === true }
case 'gone':
diff --git a/cli/src/superTabs/host.spec.ts b/cli/src/superTabs/host.spec.ts
index 014ba9914..56edd6955 100644
--- a/cli/src/superTabs/host.spec.ts
+++ b/cli/src/superTabs/host.spec.ts
@@ -3744,6 +3744,8 @@ function lifeFixture(rows: Record<string, unknown>[], options: SuperTabHostOptio
t.core.agents.byAgent = vi.fn(() => (live ? { agentId: 'harness' } : undefined) as never)
t.core.agents.keepLeadAlive = keepLeadAlive
t.core.agents.closeMember = closeMember
+ // No turn open, unless a test says otherwise.
+ t.core.agents.activity = vi.fn(async (ids: string[]) => Object.fromEntries(ids.map(id => [id, 'idle' as const])))
t.core.account.backend = async (_method, path, body) => {
if ((body as any)?.command) { commands.push(body as Record<string, unknown>); return { status: 200, body: { data: {} } } }
if (path.includes('/hosts/')) return { status: 200, body: { data: hostForm(rows, { tabs: ['tab'] }) } }
@@ -3842,6 +3844,37 @@ describe('ending a Buddy\'s thread sessions', () => {
await vi.waitFor(() => expect(ends(t)).toHaveLength(1))
})
+ it('never ends one in a long job with a quiet screen: an open turn is work, and it ends 30 minutes after the turn closes', async () => {
+ const t = lifeFixture([sessionRow()])
+ t.live(true)
+ let state = 'working'
+ t.core.agents.activity = vi.fn(async () => ({ harness: state })) as never
+ await t.poll()
+ await awake(t, 3 * BUDDY_SESSION_IDLE_MS)
+ expect(ends(t)).toEqual([])
+ expect(t.core.agents.activity).toHaveBeenCalledWith(['harness'])
+ state = 'idle'
+ await awake(t, BUDDY_SESSION_IDLE_MS)
+ await t.poll(1)
+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))
+ })
+
+ // A failed read in the Swarm's own process answers no state at all (processCoreApi.ts), and an open turn whose evidence lapsed
+ // answers unknown: neither says it is idle.
+ for (const [what, answer] of [['fails', async () => { throw new Error('worker restarting') }], ['answers nothing', async () => ({})], ['answers unknown', async () => ({ harness: 'unknown' })]] as const) {
+ it(`does not end one whose activity read ${what}, and ends it once the read says idle`, async () => {
+ const t = lifeFixture([sessionRow()])
+ t.live(true)
+ t.core.agents.activity = vi.fn(answer) as never
+ await t.poll()
+ await awake(t, BUDDY_SESSION_IDLE_MS + 60_000)
+ expect(ends(t)).toEqual([])
+ t.core.agents.activity = vi.fn(async () => ({ harness: 'idle' })) as never
+ await awake(t, 5 * 60_000)
+ await vi.waitFor(() => expect(ends(t)).toHaveLength(1))
+ })
+ }
+
it('never ends one a delivery waits for', async () => {
const t = lifeFixture([sessionRow()])
t.live(true)
diff --git a/cli/src/superTabs/host.ts b/cli/src/superTabs/host.ts
index 6a0acc34c..0ca7f35a6 100644
--- a/cli/src/superTabs/host.ts
+++ b/cli/src/superTabs/host.ts
@@ -357,7 +357,7 @@ const agentIdOf = (machineId: string, harnessId: string) =>
export const buddyChatIdOf = (projectId: string, personId: string, generation: string) =>
createHash('sha256').update(JSON.stringify(['buddy', projectId, personId, generation])).digest('hex').slice(0, 24)
/** A Buddy's thread session (spec 2026-10-30-buddy-thread-sessions) ends after this long with its screen unchanged, nothing
- * waiting for it and nothing delivered to it: a session still working on a long question changes its screen. */
+ * waiting for it, nothing delivered to it and no turn open: a long job with a quiet screen is still working. */
export const BUDDY_SESSION_IDLE_MS = 30 * 60_000
/** How long a thread session's terminal may be missing before it counts as stopped, so a slow read is never taken for one. */
export const BUDDY_SESSION_GONE_MS = 60_000
@@ -1200,7 +1200,7 @@ export class SuperTabHost {
/** A Buddy's thread sessions (spec 2026-10-30-buddy-thread-sessions) end on their own, so none is left running on its
* person's machine: idle for BUDDY_SESSION_IDLE_MS, with no screen change, nothing waiting for it and nothing delivered
- * in that time, or its terminal gone for BUDDY_SESSION_GONE_MS. This host asks the backend as the machine's owner, who is
+ * in that time and no turn open, or its terminal gone for BUDDY_SESSION_GONE_MS. This host asks the backend as the machine's owner, who is
* the Buddy's person (a Buddy runs only on its person's own machine); the backend then ends it, and this host closes it
* as any session the backend ends (endSession). Asked once, retried with backoff while the backend does not answer. */
private watchThreadSessions(data: unknown[]): void {
@@ -1250,9 +1250,20 @@ export class SuperTabHost {
const ending = reason, short = String(agent.harnessId).slice(0, 8)
// One id per session and reason: a retry is the same request, and a changed reason never reuses an id for another.
// An older chat's Buddy is removed from that chat, as its person's Remove there does; its chat stays.
- void backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/commands`, { operationId: `buddy-session-end-${agent.id}-${ending}`,
+ const harnessId = agent.harnessId
+ const end = () => backend(this.core, 'POST', `/api/super-tabs/${row.tabId}/commands`, { operationId: `buddy-session-end-${agent.id}-${ending}`,
command: oldChat ? { type: 'buddy.remove', projectId: agent.projectId } : { type: 'buddy.sessionEnd', conversationId, thread: session.thread, reason: ending } })
.then(() => { state.ended = true; this.log(`Ended thread session ${short} in Swarm ${row.tabId}: ${ending}.`) })
+ // A long job can leave the screen as it was: its spinner is not progress (terminal.ts STATUS_LINE). Only a closed turn ends
+ // it (Scholes, 11-02: a busy session never closes). An open turn with its evidence lapsed reads unknown, and a read that
+ // failed reads as no answer (processCoreApi.ts): neither says it is idle, so it retries.
+ void (ending === 'idle' ? this.core.agents.activity([harnessId]) : Promise.resolve({ [harnessId]: 'idle' } as Record<string, string>))
+ .then(activity => {
+ const turn = activity[harnessId]
+ if (turn === 'working') state.activeAt = this.now()
+ else if (turn === 'idle') return end()
+ else throw new Error('its turn could not be read')
+ })
.catch(error => {
state.retryAt = this.now() + Math.min(END_RETRY_MAX_MS, END_RETRY_MS * 2 ** state.failures++)
this.log(`Could not end thread session ${short} in Swarm ${row.tabId} (${ending}): ${error instanceof Error ? error.message : String(error)}`)
diff --git a/desktop/lib/super_tabs/buddy_sessions.dart b/desktop/lib/super_tabs/buddy_sessions.dart
index 94702920c..575aa8a6e 100644
--- a/desktop/lib/super_tabs/buddy_sessions.dart
+++ b/desktop/lib/super_tabs/buddy_sessions.dart
@@ -75,29 +75,28 @@ Widget _mark(HarnessActivity activity) => ActivityMark(
),
);
-/// The line under the thread pane's header: which session answers the
-/// thread and what it is doing, with End session as a quiet text action; or
-/// why its last session ended. Nothing for a thread with neither.
-class SuperTabThreadSessionLine extends StatefulWidget {
- const SuperTabThreadSessionLine({
+/// End session, for [root]'s session: in the thread pane, and on the thread's
+/// line in the chat ([metadata], that line's size), so a session is closed
+/// without opening it.
+class SuperTabSessionEnd extends StatefulWidget {
+ const SuperTabSessionEnd({
super.key,
required this.controller,
required this.root,
- required this.activityOf,
+ this.metadata = false,
});
final SuperTabController controller;
final String root;
- final SuperTabSessionActivity activityOf;
+ final bool metadata;
@override
- State<SuperTabThreadSessionLine> createState() =>
- _SuperTabThreadSessionLineState();
+ State<SuperTabSessionEnd> createState() => _SuperTabSessionEndState();
}
-class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {
- // The thread an End session is under way for: its answer changes nothing
- // once another thread is shown.
+class _SuperTabSessionEndState extends State<SuperTabSessionEnd> {
+ // The thread an end is under way for: its answer changes nothing once
+ // another thread is shown.
String? _ending;
Future<void> _end() async {
@@ -110,11 +109,51 @@ class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {
}
@override
- void didUpdateWidget(SuperTabThreadSessionLine old) {
+ void didUpdateWidget(SuperTabSessionEnd old) {
super.didUpdateWidget(old);
if (old.root != widget.root) _ending = null;
}
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final ending = _ending == widget.root;
+ return SuperTabLink(
+ label: ending ? 'Ending session' : 'End session',
+ // Disabled while its end is on its way: pointer, keyboard and screen
+ // readers alike.
+ onTap: ending ? null : () => unawaited(_end()),
+ child: Text(
+ ending ? 'Ending…' : 'End session',
+ style: widget.metadata
+ ? DesktopChrome.metadata(color: DesktopChrome.foreground)
+ : DesktopChrome.control(),
+ ),
+ );
+ }
+}
+
+/// The line under the thread pane's header: which session answers the
+/// thread and what it is doing, with End session as a quiet text action; or
+/// why its last session ended. Nothing for a thread with neither.
+class SuperTabThreadSessionLine extends StatefulWidget {
+ const SuperTabThreadSessionLine({
+ super.key,
+ required this.controller,
+ required this.root,
+ required this.activityOf,
+ });
+
+ final SuperTabController controller;
+ final String root;
+ final SuperTabSessionActivity activityOf;
+
+ @override
+ State<SuperTabThreadSessionLine> createState() =>
+ _SuperTabThreadSessionLineState();
+}
+
+class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -150,16 +189,10 @@ class _SuperTabThreadSessionLineState extends State<SuperTabThreadSessionLine> {
),
),
if (c.canWrite)
- SuperTabLink(
+ SuperTabSessionEnd(
key: const ValueKey('super-thread-session-end'),
- label: _ending == widget.root ? 'Ending session' : 'End session',
- // Disabled while its end is on its way: pointer, keyboard and
- // screen readers alike.
- onTap: _ending == widget.root ? null : () => unawaited(_end()),
- child: Text(
- _ending == widget.root ? 'Ending…' : 'End session',
- style: DesktopChrome.control(color: DesktopChrome.muted),
- ),
+ controller: c,
+ root: widget.root,
),
],
);
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index 3e77204a0..397186cf6 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -1626,9 +1626,6 @@ class SuperTabController extends ChangeNotifier {
// ── Buddy thread sessions (spec 2026-10-30-buddy-thread-sessions) ───────
- /// How many thread sessions a Buddy chat may run at once (backend limit).
- static const maxBuddySessions = 3;
-
/// When the server last refused a reply's New session as a field it does not
/// know, though it said it takes them (one of its servers older during a
/// release): New session is not offered for [_sessionsRefusedFor] after.
@@ -1735,10 +1732,6 @@ class SuperTabController extends ChangeNotifier {
messages.where((m) => m.buddySession).lastOrNull;
}
- /// Whether the open Buddy chat already runs [maxBuddySessions] sessions.
- bool get buddySessionsFull =>
- (_ownBuddyChat?.buddySessions.length ?? 0) >= maxBuddySessions;
-
/// Ends [root]'s session in the reader's own Buddy chat. Closing the thread
/// pane only hides it; this stops it. False when refused or not sent.
Future<bool> endThreadSession(String root) async {
diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dart
index 8a3c75fa0..154d63146 100644
--- a/desktop/lib/super_tabs/message_row.dart
+++ b/desktop/lib/super_tabs/message_row.dart
@@ -53,6 +53,7 @@ class SuperTabMessageRow extends StatefulWidget {
this.threadUnread = false,
this.onOpenThread,
this.threadTrailing,
+ this.threadEnd,
this.member,
this.link,
this.linkTarget,
@@ -76,6 +77,9 @@ class SuperTabMessageRow extends StatefulWidget {
/// Ends the thread line: the mark of a thread's own Buddy session.
final Widget? threadTrailing;
+ /// After [threadTrailing], outside the thread's link: End session.
+ final Widget? threadEnd;
+
/// Who a thread's reply author is in the Swarm now, for the faces on its
/// reply line; without it each shows the face its recorded name gives.
final SuperTabMemberOf? member;
@@ -541,6 +545,7 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {
onOpen: open,
member: widget.member,
trailing: widget.threadTrailing,
+ end: widget.threadEnd,
),
...widget.receipts,
],
@@ -774,12 +779,16 @@ class SuperTabThreadLine extends StatelessWidget {
required this.onOpen,
this.member,
this.trailing,
+ this.end,
});
final SuperTabThread thread;
/// Drawn after the line's link, outside it: a thread session's mark.
final Widget? trailing;
+
+ /// Drawn last, outside the line's link: End session.
+ final Widget? end;
final bool unread;
final VoidCallback onOpen;
@@ -813,13 +822,14 @@ class SuperTabThreadLine extends StatelessWidget {
grid.AppTheme.watch(context);
// A session's thread with no reply yet: its mark is the line, and opens it.
if (thread.replies == 0 && trailing != null) {
+ final open = SuperTabLink(
+ label: 'Open thread',
+ onTap: onOpen,
+ child: trailing!,
+ );
return Padding(
padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),
- child: SuperTabLink(
- label: 'Open thread',
- onTap: onOpen,
- child: trailing!,
- ),
+ child: end == null ? open : _wrapped([open, _dot, end!]),
);
}
final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';
@@ -855,7 +865,16 @@ class SuperTabThreadLine extends StatelessWidget {
padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),
child: trailing == null
? link
- : Row(mainAxisSize: MainAxisSize.min, children: [link, trailing!]),
+ : _wrapped([link, trailing!, if (end != null) ...[_dot, end!]]),
);
}
+
+ Widget get _dot =>
+ ExcludeSemantics(child: Text(' · ', style: DesktopChrome.metadata()));
+
+ /// On one line while it fits, and on two in a narrow chat.
+ Widget _wrapped(List<Widget> children) => Wrap(
+ crossAxisAlignment: WrapCrossAlignment.center,
+ children: children,
+ );
}
diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dart
index f3e468935..1766bbb31 100644
--- a/desktop/lib/super_tabs/thread_panel.dart
+++ b/desktop/lib/super_tabs/thread_panel.dart
@@ -197,10 +197,7 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
/// Whether this reply starts a session.
bool get _startsSession =>
_offersSession &&
- (_sessionLocked ||
- (_newSession &&
- !c.buddySessionsFull &&
- c.threadSessionBlocked == null));
+ (_sessionLocked || (_newSession && c.threadSessionBlocked == null));
/// A session's thread stays in the thread: Also send is not offered there,
/// nor for a reply that starts one.
@@ -614,22 +611,19 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
/// ended; greyed while it can't start, its hover saying why.
Widget _sessionChoice(bool writable) {
final locked = _sessionLocked;
- // What the server would refuse is said before sending: a block (paused,
- // no Buddy, an older host) before the limit.
+ // What the server would refuse is said before sending: paused, no Buddy,
+ // an older host.
final blocked = c.threadSessionBlocked;
- final full = !locked && blocked == null && c.buddySessionsFull;
return SuperTabComposerToggle(
key: const ValueKey('super-thread-new-session'),
- on: locked || (_newSession && !full && blocked == null),
+ on: locked || (_newSession && blocked == null),
label: _sessionLabel,
hint:
blocked ??
(locked
? 'This thread\'s session ended. Your reply starts a new one.'
- : full
- ? '${SuperTabController.maxBuddySessions} sessions running. End one to start another.'
: 'Starts a separate Buddy session for this thread'),
- onChanged: writable && !locked && !full && blocked == null
+ onChanged: writable && !locked && blocked == null
? (on) => setState(() => _newSession = on)
: null,
);
diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dart
index d873446a0..dde2eb838 100644
--- a/desktop/lib/super_tabs/view.dart
+++ b/desktop/lib/super_tabs/view.dart
@@ -803,8 +803,7 @@ class _SuperTabViewState extends State<SuperTabView>
final newSession =
_chatSessions.contains(id) &&
c.offersChatSessions &&
- c.threadSessionBlocked == null &&
- !c.buddySessionsFull;
+ c.threadSessionBlocked == null;
final result = await c.send(
replyTo: _replies[id]?.id,
newSession: newSession,
@@ -854,17 +853,12 @@ class _SuperTabViewState extends State<SuperTabView>
Widget _chatSessionChoice(bool writable) {
final id = c.selectedId;
final blocked = c.threadSessionBlocked;
- final full = blocked == null && c.buddySessionsFull;
return SuperTabComposerToggle(
key: const ValueKey('super-chat-new-session'),
- on: _chatSessions.contains(id) && blocked == null && !full,
+ on: _chatSessions.contains(id) && blocked == null,
label: 'New session',
- hint:
- blocked ??
- (full
- ? '${SuperTabController.maxBuddySessions} sessions running. End one to start another.'
- : 'Starts a separate Buddy session for this message'),
- onChanged: writable && blocked == null && !full
+ hint: blocked ?? 'Starts a separate Buddy session for this message',
+ onChanged: writable && blocked == null
? (on) => setState(
() => on ? _chatSessions.add(id) : _chatSessions.remove(id),
)
@@ -2825,6 +2819,18 @@ class _SuperTabViewState extends State<SuperTabView>
),
null => null,
},
+ threadEnd:
+ thread == null ||
+ inThread ||
+ !c.canWrite ||
+ c.threadSession(thread.id) == null
+ ? null
+ : SuperTabSessionEnd(
+ key: ValueKey('super-thread-session-end-${thread.id}'),
+ controller: c,
+ root: thread.id,
+ metadata: true,
+ ),
onOpenThread:
!inThread && root != null && (thread != null || message.threadReply)
? () => c.openThread(root)
@@ -3904,8 +3910,7 @@ class _SuperTabViewState extends State<SuperTabView>
child: Visibility(
visible:
_chatSessions.contains(chatId) &&
- c.threadSessionBlocked == null &&
- !c.buddySessionsFull,
+ c.threadSessionBlocked == null,
maintainSize: true,
maintainAnimation: true,
maintainState: true,
diff --git a/desktop/test/super_tab_buddy_sessions_test.dart b/desktop/test/super_tab_buddy_sessions_test.dart
index 54dd4299d..a939c4547 100644
--- a/desktop/test/super_tab_buddy_sessions_test.dart
+++ b/desktop/test/super_tab_buddy_sessions_test.dart
@@ -384,30 +384,25 @@ void main() {
expect(newSession, findsNothing);
});
- testSessions('at the limit the choice is unavailable and says why', (
- tester,
- ) async {
- final server = buddyChat();
- for (final thread in ['t-a', 't-b', 't-c']) {
- addSession(server, thread, agentId: 'session-$thread');
- }
- final c = await show(tester, server);
- await openThread(tester, c, 'message-1');
- expect(inThread(find.text('New session')), findsOneWidget);
- expect(box(tester, newSession).onChanged, isNull);
- expect(box(tester, newSession).on, isFalse);
- expect(
- inThread(find.byTooltip('3 sessions running. End one to start another.')),
- findsOneWidget,
- );
- // Tapping the words does nothing either; a reply goes plain.
- await tester.tap(newSession);
- await tester.enterText(composer, 'Plain');
- await tester.pump();
- await tester.tap(send);
- await tester.pumpAndSettle();
- expect(lastCommand(server).containsKey('newSession'), isFalse);
- });
+ testSessions(
+ 'past the old limit of 3 the choice stays on offer and is sent',
+ (tester) async {
+ final server = buddyChat();
+ for (final thread in ['t-a', 't-b', 't-c', 't-d']) {
+ addSession(server, thread, agentId: 'session-$thread');
+ }
+ final c = await show(tester, server);
+ await openThread(tester, c, 'message-1');
+ expect(box(tester, newSession).onChanged, isNotNull);
+ await tester.tap(newSession);
+ await tester.pump();
+ await tester.enterText(composer, 'A fifth');
+ await tester.pump();
+ await tester.tap(send);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server)['newSession'], isTrue);
+ },
+ );
testSessions('a starting session says so, and its thread offers no choice', (
tester,
@@ -527,6 +522,42 @@ void main() {
);
});
+ testSessions('the chat\'s thread line ends a session without opening it, '
+ 'and only a session\'s line offers it', (tester) async {
+ final server = buddyChat();
+ server.append('Reading the pod logs…', conversationId: 'offline');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['buddySession'] = true;
+ server.append('Second topic', conversationId: 'offline');
+ server.append('A reply', conversationId: 'offline');
+ server.messages.last
+ ..['thread'] = 'message-4'
+ ..['replyTo'] = 'message-4';
+ addSession(server, 'message-1', agentId: 'session-1');
+ final c = await show(tester, server);
+ final endInChat = find.byKey(
+ const ValueKey('super-thread-session-end-message-1'),
+ );
+ expect(endInChat, findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('super-thread-session-end-message-4')),
+ findsNothing,
+ );
+ expect(find.bySemanticsLabel('End session'), findsOneWidget);
+ await tester.tap(endInChat);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server), {
+ 'type': 'buddy.sessionEnd',
+ 'conversationId': 'offline',
+ 'thread': 'message-1',
+ 'reason': 'ended',
+ });
+ // The tap ended it; it did not open the thread.
+ expect(c.openedThread, isNull);
+ });
+
test('the Buddy is the main session, never a thread\'s own', () async {
final server = buddyChat();
// A session listed first, and its start, must not stand for the Buddy.
@@ -573,6 +604,33 @@ void main() {
expect(await c.endThreadSession('message-1'), isFalse);
});
+ testSessions('access lost takes End session off the chat\'s thread line, and '
+ 'a tap already on its way changes nothing after', (tester) async {
+ final server = buddyChat();
+ server.append('A reply', conversationId: 'offline');
+ server.messages.last
+ ..['thread'] = 'message-1'
+ ..['replyTo'] = 'message-1'
+ ..['buddySession'] = true;
+ addSession(server, 'message-1', agentId: 'session-1');
+ final c = await show(tester, server);
+ final endInChat = find.byKey(
+ const ValueKey('super-thread-session-end-message-1'),
+ );
+ final hold = server.holdCommands = Completer<void>();
+ await tester.tap(endInChat);
+ await tester.pump();
+ expect(find.text('Ending…'), findsOneWidget);
+ c.revokeAccess('You no longer have access to this Swarm.');
+ await tester.pump();
+ expect(endInChat, findsNothing);
+ hold.complete();
+ server.holdCommands = null;
+ await tester.pumpAndSettle();
+ expect(endInChat, findsNothing);
+ expect(find.text('Ending…'), findsNothing);
+ });
+
testSessions('a late End session answer leaves another thread as it is', (
tester,
) async {
@@ -757,6 +815,30 @@ void main() {
expect(alsoSend, findsOneWidget);
});
+ testSessions('a full machine is said in the server\'s own plain words, and '
+ 'the reply waits to be sent again', (tester) async {
+ const words =
+ 'Peer Mac is already running as many agents as it allows. End a '
+ 'session there, or try again when one finishes.';
+ final server = buddyChat();
+ final c = await show(tester, server);
+ await openThread(tester, c, 'message-1');
+ server
+ ..refuse = {'code': 'MACHINE_FULL', 'message': words}
+ ..refuseStatus = 409;
+ await tester.tap(newSession);
+ await tester.pump();
+ await tester.enterText(composer, 'Measure it now');
+ await tester.pump();
+ await tester.tap(send);
+ await tester.pumpAndSettle();
+ expect(lastCommand(server)['newSession'], isTrue);
+ expect(tester.widget<Text>(threadError).data, words);
+ // Not lost: it waits as Not sent, for Retry once a place frees.
+ expect(find.text('Not sent'), findsOneWidget);
+ expect(find.text('Measure it now'), findsOneWidget);
+ });
+
testSessions('a New session reply the server refuses keeps its text in the '
'box, says so plainly, and sends without it', (tester) async {
final server = buddyChat();
@@ -1149,7 +1231,9 @@ void main() {
await tester.pump();
final sent = server.posts.length;
expect(find.text('Ending…'), findsOneWidget);
- final link = tester.widget<SuperTabLink>(end);
+ final link = tester.widget<SuperTabLink>(
+ find.descendant(of: end, matching: find.byType(SuperTabLink)),
+ );
expect(link.onTap, isNull);
expect(
tester.getSemantics(end),
diff --git a/docs/plans/2026-11-02-buddy-sessions-no-limit-plan.md b/docs/plans/2026-11-02-buddy-sessions-no-limit-plan.md
new file mode 100644
index 000000000..8c2949263
--- /dev/null
+++ b/docs/plans/2026-11-02-buddy-sessions-no-limit-plan.md
@@ -0,0 +1,67 @@
+# Buddy sessions: no count of their own Implementation Plan
+
+> Written after the code: the project's rule for a plan file arrived while this task was in review (Ken, 2026-11-02). It records
+> the plan as carried out. Tests were written alongside the code, not first; each test's failure was shown by removing its
+> fix (evidence on PR #2534).
+
+**Goal:** A person opens as many extra Buddy sessions as their machine allows; idle ones close themselves, a busy one never
+does, a closed one reopens with its history and project, and each has a visible End session.
+
+**Architecture:** The server stops counting a chat's sessions and keeps only the machine's own agent limit, in plain words. The
+host asks the core whether a session's turn is open before its idle end. A session reopened in its thread keeps the project of
+the thread's latest session row and reads that project's earlier session rows. Desktop drops the count and shows End session on
+the chat's thread line too.
+
+**Tech Stack:** backend TypeScript (Prisma on MongoDB, vitest); CLI daemon TypeScript (vitest); Flutter (Desktop).
+
+**Spec:** `docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md`, updated in this pull request.
+
+## Global Constraints
+
+- The machine's agent limit stays: it is its owner's setting (Lead, in the task's thread, 2026-11-02).
+- The main Buddy's start and stop do not change.
+- A session reads nothing of another project or of the main Buddy's rows.
+- A session's chat and history are kept when it closes.
+- Security-sensitive: two independent reviews. Backend change: the full Super Tab integration suite before Ready.
+
+## Files
+
+- `backend/src/superTabs/buddySessions.ts`: the read rule; the count's constant goes.
+- `backend/src/superTabs/commands.ts`, `store.ts`, `model.ts`: the start rule; the thread's latest session project.
+- `cli/src/superTabs/host.ts`: the idle end asks about the turn.
+- `cli/src/core/experimentQueries.ts`: answers `activity` to the Swarm's own process.
+- `desktop/lib/super_tabs/{buddy_sessions,controller,message_row,thread_panel,view}.dart`: no count; End session on the line.
+- Tests beside each; the spec above.
+
+## Task 1: No count, the machine's limit in plain words
+
+- [x] Replace "runs at most 3" with a test that a fifth session starts and two racing starts both succeed; see it fail.
+- [x] Add a test that a full machine refuses in plain words, leaves no start, entry or message, and starts once a place frees.
+- [x] Remove `MAX_BUDDY_SESSIONS` and its check; refuse on the machine's limit before the start is written.
+- [x] Run `integration/superTabBuddySessions.test.ts`; expect pass.
+
+## Task 2: A busy session never closes
+
+- [x] Add host tests: an open turn with a quiet screen stays; a read that fails, answers nothing or answers unknown stays.
+- [x] Add a test through `processCoreApi` and `answerExperimentQuery` that the Swarm's process gets the answer, and no other does.
+- [x] See them fail; answer `activity` to `superTabs`; end only on a read that says idle.
+- [x] Run `src/superTabs/host.spec.ts` and `src/core/experimentQueries.spec.ts`; expect pass.
+
+## Task 3: Reopening keeps history and project
+
+- [x] Add tests: reopened naming no project, as a thread's reply box does, it keeps its project and reads the earlier answers;
+ another project's session reads none of them; a plain one stays plain; one in a project its person lost is refused alike.
+- [x] See them fail; add the read rule and the inherited project.
+- [x] Run `integration/superTabSwarmBuddy.test.ts`; expect pass.
+
+## Task 4: End session on Desktop
+
+- [x] Post the ASCII mockup to the person who asked.
+- [x] Add widget tests: past 3 New session stays on offer; End session on the chat's line ends without opening; access lost removes it.
+- [x] See them fail; drop the count, share one End session widget, draw it outside the thread's link, wrap in a narrow chat.
+- [x] Run `test/super_tab_buddy_sessions_test.dart` and `test/super_tab_threads_test.dart`; expect pass.
+
+## Task 5: Evidence and review
+
+- [x] Run the full backend Super Tab integration suite; compare any failure with clean main.
+- [x] Post red/green evidence on the pull request; add two review steps and message the Reviewers.
diff --git a/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md b/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md
index 9e9d159bf..47e0f341c 100644
--- a/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md
+++ b/docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md
@@ -64,13 +64,12 @@ it, and says so.
- The message is a thread reply (`replyTo` set, landing in a thread).
- The thread has no live or starting session.
- The main Buddy exists, and its machine's host says it can run sessions (see Compatibility).
- - The chat has fewer than 3 live or starting sessions (`BUDDY_SESSIONS_FULL`: "3 sessions are running. End one to
- start another.").
+ - Its machine has a free place (`MACHINE_FULL`, in plain words). Sessions have no count of their own (Scholes, 11-02).
- **What it writes,** in the same command:
- The message, tagged `buddySession: true`.
- An `AgentStart` with `buddyOf`, `buddySession: { thread: root, from: <the message's sequence> }`, and the main
Buddy's machine, engine and model.
- - An entry `{ thread, startId, at }` in the chat's `buddySessions` (at most 3).
+ - An entry `{ thread, startId, at }` in the chat's `buddySessions`.
- **First delivery.** On `agent.started` for a thread session, the server sets `agentId` on the chat's entry and writes
a delivery to the new agent for each of the person's `buddySession` messages in that thread, in order, that is still
waiting. So the first message reaches it through the same `accept()` as any other: the person check, the `run:`
@@ -123,7 +122,8 @@ A session ends in these cases:
2. **30 minutes idle.** The host on the person's machine judges this from what it already reports per session:
- no screen or transcript change (`harnessProgress`) for 30 minutes;
- no open delivery to the session;
- - no person message in its thread for 30 minutes.
+ - no person message in its thread for 30 minutes;
+ - no open turn: a long job's screen can stay the same, and a busy session never ends (Scholes, 11-02).
A session still working on a long question changes its screen, so it is not idle. The host sends
`buddy.sessionEnd { agentId, reason: 'idle' }` as the machine's owner, who is the person.
@@ -208,9 +208,7 @@ it is checked, **Also send to the chat** is hidden: a session's thread stays in
**2. At the limit.** The checkbox is disabled and says why.
-```
-││☐ New session · 3 running, end one first 📎 ↑││
-```
+A machine with no free place refuses the send, in plain words, and the reply stays in the box.
**3. A thread with a session.** One line under the header shows which session answers and whether it's working, with
**End session** as a quiet text button. The states are: `Starting…`, `⠋ Working`, `✓ Idle` and `◌ Your Mac is
@@ -257,7 +255,8 @@ there would be refused.
```
Ruling: no session list in the sidebar or the header. Why: "less is better". The threads are where the sessions are,
-and the thread line shows which ones are working. Cost if wrong: with 3 sessions, the person scrolls to find them.
+and the thread line shows which ones are working, with its own **End session** (Scholes, 11-02). Cost if wrong: with many
+sessions, the person scrolls to find them.
## Design (docs/feature-design-rules.md)
@@ -267,7 +266,7 @@ Reviewed revision: ______ Reviewer (another engine): ______
| Record | Created | Updated | Finished / removed |
|---|---|---|---|
- | Chat `buddySessions` entry | New session | `agentId` at start | End, idle, failed start, unexpected stop, main Buddy removed, access lost. At most 3, so it can't grow. |
+ | Chat `buddySessions` entry | New session | `agentId` at start | End, idle, failed start, unexpected stop, main Buddy removed, access lost. Bounded by its machine's agent limit and the idle end. |
| Session `Agent` | `agent.started` | liveness, as any agent | `removeAgent`, then `closingSessions` until the host confirms (existing) |
| Session `AgentStart` | New session | dispatch and start (existing) | Existing start lifecycle (`finishedAt`, purge) |
| Message `buddySession` tag | each message in a session thread | never | with its message (existing message lifecycle) |
@@ -287,7 +286,7 @@ Reviewed revision: ______ Reviewer (another engine): ______
delivery, nor the reverse. Test: a delivery held for the main session while a session's delivery is accepted.
- Thin slice: two concurrent New session sends against a live store; exactly one start.
3. **Read cost.**
- - Routing reads only the chat's `buddySessions` (at most 3 entries), which is already loaded.
+ - Routing reads only the chat's `buddySessions` (at most its machine's agent limit), which is already loaded.
- A session's reads are thread reads on the existing `[tabId, conversationId, thread, sequence]` index.
- The excerpt is one indexed read of at most 10 main-stream messages before `from`.
- The main session's reads add `buddySession != true` to the query it already runs.
@@ -296,7 +295,7 @@ Reviewed revision: ______ Reviewer (another engine): ______
- Removals: an ended session leaves `agentIds` and `buddySessions` through the existing change feed, so Desktop drops
its marks.
4. **Scale.**
- - At most 3 sessions per person per project.
+ - At most its machine's agent limit, which its owner sets; idle sessions end by themselves.
- At 10x people, there are 10x Claude processes, each on its own person's Mac. The server holds at most 3 small
entries per chat.
- The first warning is sessions refused because the machine is full, and Macs low on memory: each session is one
@@ -304,7 +303,7 @@ Reviewed revision: ______ Reviewer (another engine): ______
- **Where it shows** (security review 1: the usage counters this line first named do not exist, and the fixed usage
vocabulary is shared with the CLI, so this uses the server log instead). The backend logs three lines with ids only:
- `Buddy session started` (Swarm and start id);
- - `Buddy session refused` (Swarm and refusal code: `BUDDY_SESSIONS_FULL`, `BUDDY_SESSION_UNSUPPORTED`,
+ - `Buddy session refused` (Swarm and refusal code: `MACHINE_FULL`, `BUDDY_SESSION_UNSUPPORTED`,
`BUDDY_SESSION_ENGINE`, `BUDDY_SESSION_NO_BUDDY` and the machine's capacity refusals);
- `Buddy session ended`, with the reason (`ended`, `idle`, `stopped`, `failed`, `removed`, `maintenance`), logged
once committed.
@@ -432,7 +431,7 @@ Records and views:
the sequence of the message that started it. The main Buddy has none.
- `AgentStartRequest.buddySession?`: the same, written only by `message.send` with `newSession`. Never any message text.
- `Conversation.buddySessions?: Array<{ thread: string; startId: string; agentId?: string; at: number }>`: a Buddy chat's
- live or starting sessions, at most 3. `agentId` is set once started.
+ live or starting sessions. `agentId` is set once started.
- `Message.buddySession?: true`: a reply in a session thread, from the person or the session.
- Message `source.kind === 'buddy-session-ended'` with `source.reason` (`ended` | `idle` | `stopped` | `failed`) and
`source.thread`: the quiet line in the thread when a session ends.
@@ -441,7 +440,7 @@ Records and views:
Commands:
- `message.send` takes `newSession?: true`. Refusals:
- - `BUDDY_SESSIONS_FULL`: 3 running.
+ - `MACHINE_FULL`: its machine has no free place.
- `BUDDY_SESSION_EXISTS`: the thread has one.
- `BUDDY_SESSION_UNSUPPORTED`: old host.
- `BUDDY_SESSION_CHAT`: not the person's own Buddy chat, or not a thread reply.
diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dart
index 91cdcfde2..947be28f3 100644
--- a/mobile/lib/swarm/model.dart
+++ b/mobile/lib/swarm/model.dart
@@ -127,7 +127,11 @@ class SuperTabAgent {
SuperTabAgent.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
hasProjectId = row['projectId'] != null,
- projectId = row['projectId'] as String? ?? 'lead',
+ // A person's one Buddy reads every project they read: it belongs to none,
+ // as on the desktop (spec 2026-10-31-one-buddy-per-swarm).
+ projectId =
+ row['projectId'] as String? ??
+ (row['buddyScope'] == 'swarm' ? '' : 'lead'),
buddyScope = row['buddyScope'] as String?,
buddyNarrow = row['buddyNarrow'] == true,
name = _text(row, 'name'),
@@ -262,8 +266,12 @@ class SuperTabTask {
class SuperTabConversation {
SuperTabConversation.fromJson(Map<String, dynamic> row)
: id = _text(row, 'id'),
- // A group from before projects belongs to the first.
- projectId = row['projectId'] as String? ?? 'lead',
+ // A group from before projects belongs to the first; a person's one
+ // Buddy chat for the Swarm belongs to none (spec
+ // 2026-10-31-one-buddy-per-swarm).
+ projectId =
+ row['projectId'] as String? ??
+ (row['kind'] == 'swarm-buddy' ? '' : 'lead'),
kind = row['kind'] as String?,
buddyOwnerId = row['buddyOwnerId'] as String?,
buddyName = row['buddyName'] as String?,
@@ -280,7 +288,9 @@ class SuperTabConversation {
archived = row['archived'] == true,
dormant = row['dormant'] == true,
// A Buddy chat names no audience: its person alone reads it.
- audience = row['kind'] == 'buddy' && row['buddyOwnerId'] is String
+ audience =
+ (row['kind'] == 'buddy' || row['kind'] == 'swarm-buddy') &&
+ row['buddyOwnerId'] is String
? List.unmodifiable([row['buddyOwnerId'] as String])
: row['audience'] is Map
? List.unmodifiable([
@@ -329,7 +339,11 @@ class SuperTabConversation {
/// chat with their Buddy. A `leads` one, the removed Product Managers'
/// conversation, is in no read ([SuperTabSnapshot.fromJson]).
final String? kind;
- bool get isBuddyChat => kind == 'buddy';
+ bool get isBuddyChat => kind == 'buddy' || kind == 'swarm-buddy';
+
+ /// A person's one Buddy chat for the whole Swarm (spec
+ /// 2026-10-31-one-buddy-per-swarm): in no project, keyed by the empty id.
+ bool get isSwarmBuddyChat => kind == 'swarm-buddy';
/// The person a Buddy chat belongs to; only they read it.
final String? buddyOwnerId;
diff --git a/mobile/lib/swarm/swarm_buddies_page.dart b/mobile/lib/swarm/swarm_buddies_page.dart
deleted file mode 100644
index 2f1904267..000000000
--- a/mobile/lib/swarm/swarm_buddies_page.dart
+++ /dev/null
@@ -1,413 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:lucide_icons_flutter/lucide_icons.dart';
-
-import 'package:harness_mobile/phone/fzf.dart' show fzfAge;
-import 'package:harness_mobile/phone/out_of_sight.dart';
-import 'package:harness_mobile/shared/theme/app_space.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart';
-import 'package:harness_mobile/shared/theme/app_type.dart';
-import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
-
-import 'swarm_buddy.dart' show swarmCanWrite;
-import 'swarm_buddy_chat.dart' show openSwarmBuddy;
-import 'swarm_buddy_list.dart';
-import 'swarm_conversation_page.dart' show openSwarmConversation;
-import 'swarm_row.dart';
-import 'swarm_session.dart';
-import 'swarm_style.dart';
-
-/// Buddies (Tony's prototype C2): its title in the terminal's face, then a
-/// row for each project ([SwarmBuddyRow]), newest first — its tile, its
-/// name, how the person's Buddy there stands, and the last message of their
-/// Buddy chat — bold with a dot while that chat has something unread. A tap
-/// opens that Buddy chat, where the Buddy is started too: Swarm Home C's
-/// project has no Buddy tab. The Buddies tab's screen.
-///
-/// Only while it is in sight ([OutOfSight]) does it read the Buddy chats
-/// ([SwarmBuddyList.watch]) and keep the Swarm's notices quiet.
-class SwarmBuddiesView extends StatefulWidget {
- const SwarmBuddiesView({super.key, this.leading});
-
- /// Before the title: a page's back; none on the tab.
- final Widget? leading;
-
- @override
- State<SwarmBuddiesView> createState() => _SwarmBuddiesViewState();
-}
-
-class _SwarmBuddiesViewState extends State<SwarmBuddiesView> {
- SwarmSession? _session;
- bool _seen = false;
-
- /// The row whose Buddy chat is being opened: a second tap waits for it.
- String? _opening;
-
- /// Why the last row tapped did not open, while that row is listed.
- ({String row, String text})? _failed;
-
- @override
- void didChangeDependencies() {
- super.didChangeDependencies();
- final session = SwarmScope.of(context);
- final seen = session != null && !OutOfSight.of(context);
- if (identical(session, _session) && seen == _seen) return;
- _see(false);
- _session = session;
- _see(seen);
- }
-
- /// In sight: the Buddy chats are read as they move, the inbox is read now,
- /// and the Swarm's notices keep quiet. Out of sight, none of it.
- void _see(bool seen) {
- final session = _session;
- if (session == null || seen == _seen) return;
- _seen = seen;
- if (seen) {
- session.enter();
- session.buddyList.watch();
- unawaited(session.inbox.refresh());
- } else {
- session.buddyList.unwatch();
- session.leave();
- }
- }
-
- @override
- void dispose() {
- _see(false);
- super.dispose();
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final session = _session;
- return Material(
- color: AppPalette.windowBg,
- child: SafeArea(
- bottom: false,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- if (widget.leading case final leading?)
- SwarmTopBar(leading: leading, title: 'Buddies')
- else
- const SwarmTabHeader('Buddies'),
- if (session != null)
- Expanded(
- child: ListenWhileInSight(
- listenable: session.buddyList,
- builder: (context) => _body(context, session),
- ),
- ),
- ],
- ),
- ),
- );
- }
-
- Widget _body(BuildContext context, SwarmSession session) {
- final list = session.buddyList, inbox = session.inbox;
- final rows = list.rows;
- final now = DateTime.now();
- final note = AppType.caption(color: AppPalette.textSecondary, height: 1.35);
- return ListView(
- padding: EdgeInsets.fromLTRB(
- AppSpace.m,
- AppSpace.xs,
- AppSpace.m,
- MediaQuery.paddingOf(context).bottom + AppSpace.xl,
- ),
- children: [
- if (_failed case final failed?
- when rows.any((row) => row.key == failed.row))
- _Note(
- key: const ValueKey('swarm-buddies-open-failed'),
- text: failed.text,
- action: SwarmButton(
- label: 'OK',
- style: SwarmButtonStyle.link,
- onPressed: () => setState(() => _failed = null),
- ),
- ),
- if (list.unreadChats)
- _Note(
- text: 'Some Buddy chats could not be read.',
- action: SwarmButton(
- key: const ValueKey('swarm-buddies-retry'),
- label: 'Try again',
- style: SwarmButtonStyle.link,
- onPressed: list.retry,
- ),
- ),
- if (!inbox.loaded && inbox.error != null)
- _Note(
- text: inbox.error!,
- action: SwarmButton(
- key: const ValueKey('swarm-buddies-retry-list'),
- label: 'Try again',
- style: SwarmButtonStyle.link,
- onPressed: () => unawaited(inbox.refresh()),
- ),
- )
- else if (rows.isEmpty && !inbox.loaded)
- SwarmSkeletonRows(id: 'swarm-buddies-loading')
- else if (rows.isEmpty)
- Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppSpace.xs,
- vertical: AppSpace.s,
- ),
- child: Text(
- 'No projects yet.',
- key: const ValueKey('swarm-buddies-none'),
- style: note,
- ),
- )
- else
- SwarmGroup(
- children: [
- for (final row in rows)
- SwarmBuddiesRow(
- key: ValueKey('swarm-buddies-row-${row.key}'),
- row: row,
- line: swarmBuddyLine(row, inbox.reader(row.swarmId)),
- now: now,
- onTap: () => _open(context, row),
- ),
- ],
- ),
- ],
- );
- }
-
- /// Opens [row]'s Buddy chat, made on the server first when there is none
- /// yet ([openSwarmBuddy]); a viewer with none is told so, and nothing is
- /// asked.
- void _open(BuildContext context, SwarmBuddyRow row) {
- if (_opening != null) return;
- setState(() => _failed = null);
- if (row.chat case final chat?) {
- openSwarmConversation(context, row.swarmId, chat.id);
- return;
- }
- final reader = _session?.inbox.reader(row.swarmId);
- if (reader == null || reader.accessRevoked) return;
- if (!swarmCanWrite(reader)) {
- setState(
- () => _failed = (
- row: row.key,
- text: 'You have no Buddy in this project.',
- ),
- );
- return;
- }
- setState(() => _opening = row.key);
- unawaited(
- openSwarmBuddy(context, reader, row.swarmId, row.project.id).then((
- error,
- ) {
- if (!mounted) return;
- setState(() {
- _opening = null;
- if (error != null) _failed = (row: row.key, text: error);
- });
- }),
- );
- }
-}
-
-/// A line over the rows, with what to do about it at its end.
-class _Note extends StatelessWidget {
- const _Note({super.key, required this.text, required this.action});
-
- final String text;
- final Widget action;
-
- @override
- Widget build(BuildContext context) => Padding(
- padding: const EdgeInsets.only(left: AppSpace.xs, bottom: AppSpace.s),
- child: Row(
- children: [
- Expanded(
- child: Text(
- text,
- style: AppType.caption(
- color: AppPalette.textSecondary,
- height: 1.35,
- ),
- ),
- ),
- action,
- ],
- ),
- );
-}
-
-/// One project on Buddies, as prototype C2 draws it: its tile; its name —
-/// bold and bright while its Buddy chat has something unread, quiet
-/// otherwise — with how its Buddy stands after it and when the chat last
-/// moved at the end; under them the chat's last message ([line]), and a dot
-/// at its end while unread. A muted chat is never unread, and has a crossed
-/// bell after its name, as the desktop's sidebar draws one.
-class SwarmBuddiesRow extends StatelessWidget {
- const SwarmBuddiesRow({
- super.key,
- required this.row,
- required this.line,
- required this.now,
- required this.onTap,
- });
-
- final SwarmBuddyRow row;
- final String line;
- final DateTime now;
- final VoidCallback onTap;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final unread = row.unread;
- final state = row.note ?? 'running';
- final age = switch (row.at) {
- final at? => fzfAge(at.toLocal(), now.toLocal()),
- null => '',
- };
- return Semantics(
- button: true,
- label: [
- row.project.name,
- '${row.name} $state',
- if (line.isNotEmpty) line,
- if (unread) 'Unread messages',
- if (row.muted) 'Muted',
- ].join(', '),
- excludeSemantics: true,
- child: Material(
- color: Colors.transparent,
- child: InkWell(
- onTap: onTap,
- child: ConstrainedBox(
- constraints: const BoxConstraints(minHeight: SwarmRow.height),
- child: Padding(
- padding: const EdgeInsets.symmetric(
- horizontal: AppSpace.l,
- vertical: AppSpace.m,
- ),
- child: Row(
- children: [
- SwarmProjectTile(row.project.name),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
- mainAxisSize: MainAxisSize.min,
- children: [
- Row(
- crossAxisAlignment: CrossAxisAlignment.baseline,
- textBaseline: TextBaseline.alphabetic,
- children: [
- Expanded(
- child: Row(
- crossAxisAlignment: CrossAxisAlignment.baseline,
- textBaseline: TextBaseline.alphabetic,
- children: [
- Flexible(
- child: Text(
- row.project.name,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.label(
- color: unread
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
- height: 1.3,
- fontWeight: unread
- ? AppFont.semibold
- : null,
- ),
- ),
- ),
- if (row.muted) ...[
- const SizedBox(width: AppSpace.xs),
- Icon(
- LucideIcons.bellOff,
- key: ValueKey(
- 'swarm-buddies-muted-${row.key}',
- ),
- size: 13,
- color: AppPalette.textFaint,
- ),
- ],
- const SizedBox(width: AppSpace.s),
- Text(
- state,
- style: AppType.caption(
- color: row.note == null
- ? AppColors.success
- : AppPalette.textFaint,
- height: 1.3,
- ),
- ),
- ],
- ),
- ),
- if (age.isNotEmpty) ...[
- const SizedBox(width: AppSpace.s),
- Text(
- age,
- key: ValueKey('swarm-buddies-age-${row.key}'),
- style: AppType.caption(
- color: AppPalette.textFaint,
- height: 1.3,
- ),
- ),
- ],
- ],
- ),
- const SizedBox(height: 2),
- Row(
- children: [
- Expanded(
- child: Text(
- line,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: AppType.caption(
- color: unread
- ? AppPalette.textPrimary
- : AppPalette.textSecondary,
- height: 1.35,
- ),
- ),
- ),
- if (unread) ...[
- const SizedBox(width: AppSpace.s),
- Container(
- key: ValueKey(
- 'swarm-buddies-unread-${row.key}',
- ),
- width: 7,
- height: 7,
- decoration: BoxDecoration(
- color: AppPalette.textPrimary,
- shape: BoxShape.circle,
- ),
- ),
- ],
- ],
- ),
- ],
- ),
- ),
- ],
- ),
- ),
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/swarm/swarm_buddy.dart b/mobile/lib/swarm/swarm_buddy.dart
index 1b195b098..43c8cd676 100644
--- a/mobile/lib/swarm/swarm_buddy.dart
+++ b/mobile/lib/swarm/swarm_buddy.dart
@@ -6,6 +6,11 @@ import 'swarm_reader.dart';
import 'swarm_request.dart';
import 'swarm_start.dart';
+/// The key the person's one Buddy for the whole Swarm goes by among the
+/// project ids here: its chat and agent belong to no project (the desktop's
+/// `SuperTabController.kSwarmBuddyKey`).
+const swarmBuddyKey = '';
+
/// What the phone knows of Buddies (spec: Buddies, 10-28; in every Swarm
/// since #2090, where they replaced Chat with PM): each person's Buddy chat in
/// each project, where the PM's private lines to them land, and the Buddy that
@@ -37,14 +42,20 @@ class SwarmBuddies {
final chatOwners = <String, String>{};
final ownChats = <String, String>{};
for (final row in _rows(state['conversations'])) {
- if (row case {
- 'kind': 'buddy',
- 'id': final String id,
- 'buddyOwnerId': final String owner,
- }) {
+ if (row
+ case {
+ 'kind': final String kind,
+ 'id': final String id,
+ 'buddyOwnerId': final String owner,
+ }
+ when kind == 'buddy' || kind == 'swarm-buddy') {
chatOwners[id] = owner;
if (owner == accountId) {
- ownChats.putIfAbsent(row['projectId'] as String? ?? 'lead', () => id);
+ ownChats.putIfAbsent(
+ row['projectId'] as String? ??
+ (kind == 'swarm-buddy' ? swarmBuddyKey : 'lead'),
+ () => id,
+ );
}
}
}
@@ -56,9 +67,12 @@ class SwarmBuddies {
'buddyOf': {'personId': final String person},
}) {
buddyOwners[id] = person;
- if (person == accountId) {
+ // A thread's own session is never the Buddy (the desktop's
+ // `isMainBuddy`), and it stays listed above, out of the team.
+ if (person == accountId && row['buddySession'] == null) {
ownBuddies.putIfAbsent(
- row['projectId'] as String? ?? 'lead',
+ row['projectId'] as String? ??
+ (row['buddyScope'] == 'swarm' ? swarmBuddyKey : 'lead'),
() => id,
);
}
@@ -86,10 +100,12 @@ class SwarmBuddies {
/// Every Buddy the read holds, anyone's, with the person it belongs to.
final Map<String, String> buddyOwners;
- /// The reader's own Buddy chat in each project, by project id.
+ /// The reader's own Buddy chat in each project, by project id; their one
+ /// chat for the Swarm under [swarmBuddyKey].
final Map<String, String> ownChats;
- /// The reader's own Buddy in each project, its agent id by project id.
+ /// The reader's own Buddy in each project, its agent id by project id; their
+ /// one Buddy for the Swarm under [swarmBuddyKey]. Never a thread's session.
final Map<String, String> ownBuddies;
/// The starts of the reader's own Buddies, oldest first: one is under way
@@ -148,6 +164,42 @@ bool swarmIsBuddyChat(SwarmReader reader, String conversationId) =>
bool swarmIsOwnBuddyChat(SwarmReader reader, String conversationId) =>
reader.buddies.chatOwners[conversationId] == reader.accountId;
+/// Whether [conversationId] is the person's older Buddy chat in a project,
+/// where the Swarm gives one Buddy for the whole Swarm: its history reads, and
+/// nothing is written there (the desktop's `isEarlierBuddyChat`). The server
+/// still takes a post from an app that does not say it knows this.
+bool swarmIsOldBuddyChat(SwarmReader reader, String conversationId) {
+ final snapshot = reader.snapshot;
+ final group = snapshot?.conversation(conversationId);
+ return snapshot?.swarmBuddy == true &&
+ group != null &&
+ group.isBuddyChat &&
+ !group.isSwarmBuddyChat;
+}
+
+/// The person's older Buddy chats with something in them, newest first, each
+/// with its project: only in projects they read now, so one they lost drops
+/// off, and none where the Swarm has no one Buddy (the desktop's Buddy menu).
+List<({SuperTabProject project, SuperTabConversation chat})> swarmOldBuddyChats(
+ SwarmReader reader,
+) {
+ final snapshot = reader.snapshot;
+ if (snapshot == null || !snapshot.swarmBuddy || reader.accessRevoked) {
+ return const [];
+ }
+ final chats = [
+ for (final project in snapshot.projects)
+ if (swarmBuddyChat(reader, project.id) case final chat?
+ when chat.lastMessageSequence > 0 && !chat.isSwarmBuddyChat)
+ (project: project, chat: chat),
+ ];
+ final never = DateTime.fromMillisecondsSinceEpoch(0, isUtc: true);
+ chats.sort(
+ (a, b) => (b.chat.changedAt ?? never).compareTo(a.chat.changedAt ?? never),
+ );
+ return chats;
+}
+
/// Whether [message] is one of the PM's private lines to the person: its
/// project's Lead writing in the person's own Buddy chat, where it writes but
/// cannot read (#2090; the desktop's `_shownAuthor`).
@@ -170,8 +222,12 @@ Map<String, dynamic>? swarmBuddyStart(SwarmReader reader, String projectId) {
final chat = reader.buddies.ownChats[projectId];
for (final start in reader.buddies.ownStarts.reversed) {
final request = start['request'] as Map;
+ // A thread session's start is its thread's, never the Buddy's own.
+ if (request['buddySession'] != null) continue;
if (request['projectId'] == projectId ||
- (chat != null && request['conversationId'] == chat)) {
+ (chat != null && request['conversationId'] == chat) ||
+ // The one Buddy's start, before its chat is read here.
+ (projectId == swarmBuddyKey && request['buddyScope'] == 'swarm')) {
return start;
}
}
@@ -452,7 +508,7 @@ Future<String?> openSwarmBuddyChat(SwarmReader reader, String projectId) async {
if (operation.length > 160) operation = operation.substring(0, 160);
final result = await _command(reader, {
'type': 'buddy.chat',
- 'projectId': projectId,
+ if (projectId != swarmBuddyKey) 'projectId': projectId,
}, operation: operation);
return result['conversationId'] as String?;
}
@@ -469,7 +525,7 @@ Future<String?> startSwarmBuddy(
}) async {
final result = await _command(reader, {
'type': 'buddy.create',
- 'projectId': projectId,
+ if (projectId != swarmBuddyKey) 'projectId': projectId,
'machineId': machineId,
'engine': engine,
'setup': ?setup,
@@ -481,7 +537,10 @@ Future<String?> startSwarmBuddy(
/// Removes the person's Buddy in [projectId]: its session stops and its chat
/// stays. Reads the Swarm again; a refusal throws.
Future<void> removeSwarmBuddy(SwarmReader reader, String projectId) async {
- await _command(reader, {'type': 'buddy.remove', 'projectId': projectId});
+ await _command(reader, {
+ 'type': 'buddy.remove',
+ if (projectId != swarmBuddyKey) 'projectId': projectId,
+ });
await reader.refresh();
}
diff --git a/mobile/lib/swarm/swarm_buddy_chat.dart b/mobile/lib/swarm/swarm_buddy_chat.dart
index 03bbdee84..c44c27641 100644
--- a/mobile/lib/swarm/swarm_buddy_chat.dart
+++ b/mobile/lib/swarm/swarm_buddy_chat.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/phone/fzf.dart' show fzfAge;
import 'package:harness_mobile/phone/phone_shell_scope.dart';
import 'package:harness_mobile/phone/phone_sheet.dart';
import 'package:harness_mobile/shared/theme/app_icon_size.dart';
@@ -25,6 +26,10 @@ import 'swarm_start.dart' show SwarmOwnComputer;
import 'swarm_terminal_row.dart';
import 'swarm_style.dart';
+/// The Swarm a Buddy chat shows in the Buddy tab, by name, and how to pick
+/// another from its menu.
+typedef SwarmBuddySwitch = ({String name, VoidCallback open});
+
/// Opens the person's Buddy chat in [projectId] over [context]'s page, on the
/// server first when the read holds none ([openSwarmBuddyChat]). Answers what
/// went wrong as a sentence to show, or null once it is open — or once there
@@ -438,18 +443,22 @@ class _Field extends StatelessWidget {
static const _labelWidth = AppSpace.xl * 3;
}
-/// At the end of the person's own Buddy chat's header, while they may
-/// write: ⋮, with Open terminal first (Tony, 11-01: the Buddy's terminal on
-/// this phone, as Team's agent rows open theirs; dimmed with why while it
-/// cannot be, [swarmTerminalAction]), Rename Buddy, and Remove Buddy
-/// while one runs, which asks first, then stops it; the chat stays (the
-/// desktop's Buddy options); and the chat's Notifications, as its menu on
-/// the desktop has. Nothing in anyone else's Buddy chat.
+/// At the end of the person's own Buddy chat's header: ⋮. While they may
+/// write, with Open terminal first (Tony, 11-01: the Buddy's terminal on this
+/// phone, as Team's agent rows open theirs; dimmed with why while it cannot
+/// be, [swarmTerminalAction]), Rename Buddy, and Remove Buddy while one runs,
+/// which asks first, then stops it; the chat stays (the desktop's Buddy
+/// options); and the chat's Notifications, as its menu on the desktop has.
+/// In their one chat for the Swarm, for a viewer too, Old chats with their
+/// older Buddy chats, and the Swarm to switch from in the Buddy tab. Nothing
+/// in anyone else's Buddy chat, or for a viewer with nothing to offer.
class SwarmBuddyMenuButton extends StatelessWidget {
const SwarmBuddyMenuButton({
super.key,
required this.actions,
required this.chatId,
+ this.swarmId,
+ this.swarmSwitch,
});
final SwarmBuddyActions actions;
@@ -458,6 +467,73 @@ class SwarmBuddyMenuButton extends StatelessWidget {
/// rather than its project. Null while that chat is not known yet.
final String? chatId;
+ /// The Swarm the chat is in, for what Old chats opens; none offers no Old
+ /// chats.
+ final String? swarmId;
+
+ /// The Swarm row, in the Buddy tab with others to pick; null for none.
+ final SwarmBuddySwitch? swarmSwitch;
+
+ /// Old chats and the Swarm row: rows a viewer has too.
+ bool _hasOthers(SwarmReader reader) =>
+ swarmSwitch != null || _oldChats(reader).isNotEmpty;
+
+ /// The older Buddy chats to offer, from the person's one chat alone.
+ List<({SuperTabProject project, SuperTabConversation chat})> _oldChats(
+ SwarmReader reader,
+ ) => swarmId != null && actions.projectId == swarmBuddyKey
+ ? swarmOldBuddyChats(reader)
+ : const [];
+
+ /// Old chats, by project, newest first: each opens read only. The sheet goes
+ /// with access to the Swarm, and a project lost meanwhile leaves its rows.
+ Future<void> _openOldChats(BuildContext context) async {
+ final reader = actions.reader;
+ Route<void>? sheet;
+ void moved() {
+ final route = sheet;
+ if (route == null || !reader.accessRevoked) return;
+ sheet = null;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (route.isActive) route.navigator?.removeRoute(route);
+ });
+ }
+
+ reader.addListener(moved);
+ try {
+ await showPhoneSheet(
+ context,
+ title: 'Old chats',
+ onShown: (route) => sheet = route,
+ rebuildOn: reader,
+ rows: () => (
+ actions: [
+ for (final (:project, :chat) in _oldChats(reader))
+ PhoneSheetAction(
+ icon: LucideIcons.messageCircle,
+ label: project.name,
+ value: switch (chat.changedAt) {
+ final at? => fzfAge(at.toLocal(), DateTime.now()),
+ null => null,
+ },
+ chevron: true,
+ onTap: () {
+ if (context.mounted &&
+ !reader.accessRevoked &&
+ swarmIsOldBuddyChat(reader, chat.id)) {
+ openSwarmConversation(context, swarmId!, chat.id);
+ }
+ },
+ ),
+ ],
+ sections: const <PhoneSheetSection>[],
+ ),
+ );
+ } finally {
+ reader.removeListener(moved);
+ }
+ }
+
/// The sheet, with the chat's Notifications under the Buddy's own rows
/// ([swarmNotifySection]). It goes once the chat is no longer the
/// person's own Buddy chat to read (access lost, or signed out), they may
@@ -475,6 +551,7 @@ class SwarmBuddyMenuButton extends StatelessWidget {
_ => null,
};
var buddyId = running();
+ final wrote = swarmCanWrite(reader);
Route<void>? sheet;
void moved() {
final route = sheet;
@@ -483,7 +560,7 @@ class SwarmBuddyMenuButton extends StatelessWidget {
if (route == null ||
(!reader.accessRevoked &&
swarmIsOwnBuddyChat(reader, chatId) &&
- swarmCanWrite(reader) &&
+ swarmCanWrite(reader) == wrote &&
now == buddyId)) {
return;
}
@@ -504,21 +581,42 @@ class SwarmBuddyMenuButton extends StatelessWidget {
final buddy = swarmBuddy(reader, actions.projectId);
return (
actions: [
- swarmTerminalAction(
- agent: () => swarmBuddy(reader, actions.projectId),
- allowed: () =>
- !reader.accessRevoked &&
- swarmIsOwnBuddyChat(reader, chatId) &&
- swarmCanWrite(reader),
- shell: shell,
- computers: computers,
- ),
- PhoneSheetAction(
- icon: LucideIcons.pencil,
- label: 'Rename Buddy',
- onTap: () => unawaited(_rename(context, chatId)),
- ),
- if (buddy != null)
+ if (wrote) ...[
+ swarmTerminalAction(
+ agent: () => swarmBuddy(reader, actions.projectId),
+ allowed: () =>
+ !reader.accessRevoked &&
+ swarmIsOwnBuddyChat(reader, chatId) &&
+ swarmCanWrite(reader),
+ shell: shell,
+ computers: computers,
+ ),
+ PhoneSheetAction(
+ icon: LucideIcons.pencil,
+ label: 'Rename Buddy',
+ onTap: () => unawaited(_rename(context, chatId)),
+ ),
+ ],
+ if (_oldChats(reader).isNotEmpty)
+ PhoneSheetAction(
+ icon: LucideIcons.history,
+ label: 'Old chats',
+ chevron: true,
+ onTap: () {
+ if (context.mounted && !reader.accessRevoked) {
+ unawaited(_openOldChats(context));
+ }
+ },
+ ),
+ if (swarmSwitch case final swarm?)
+ PhoneSheetAction(
+ icon: LucideIcons.hexagon,
+ label: 'Swarm',
+ value: swarm.name,
+ chevron: true,
+ onTap: swarm.open,
+ ),
+ if (wrote && buddy != null)
PhoneSheetAction(
icon: LucideIcons.userMinus,
label: 'Remove Buddy',
@@ -586,7 +684,7 @@ class SwarmBuddyMenuButton extends StatelessWidget {
final chat = chatId;
if (chat == null ||
!swarmIsOwnBuddyChat(reader, chat) ||
- !swarmCanWrite(reader)) {
+ (!swarmCanWrite(reader) && !_hasOthers(reader))) {
return const SizedBox.shrink();
}
final busy = actions.busy;
diff --git a/mobile/lib/swarm/swarm_buddy_list.dart b/mobile/lib/swarm/swarm_buddy_list.dart
deleted file mode 100644
index 0a6d63fdc..000000000
--- a/mobile/lib/swarm/swarm_buddy_list.dart
+++ /dev/null
@@ -1,244 +0,0 @@
-import 'package:flutter/foundation.dart';
-
-import 'identity.dart';
-import 'model.dart';
-import 'swarm_buddy.dart';
-import 'swarm_chat_notify.dart';
-import 'swarm_inbox.dart';
-import 'swarm_reader.dart';
-import 'swarm_session.dart';
-import 'swarm_unread.dart';
-
-/// One project on Buddies (Tony's prototype C2): the person's own Buddy in
-/// [project] of Swarm [swarmId], by its [name] ("Buddy" while none runs) and
-/// how it stands ([note]: "offline", "starting" or "not started"; null while
-/// it runs), their Buddy chat there ([chat]; null while none is opened) and
-/// the last message in it once read ([last]), [unread] while the chat has a
-/// message past the person's read mark.
-@immutable
-class SwarmBuddyRow {
- const SwarmBuddyRow({
- required this.swarmId,
- required this.project,
- required this.name,
- this.note,
- this.chat,
- this.last,
- this.unread = false,
- this.muted = false,
- });
-
- final String swarmId;
- final SuperTabProject project;
- final String name;
- final String? note;
- final SuperTabConversation? chat;
- final SuperTabMessage? last;
-
- /// Its chat has something unread, and is not muted.
- final bool unread;
-
- /// The person muted its chat ([SwarmNotify.muted]): greyed, never unread.
- final bool muted;
-
- /// When the chat last moved: its last message, or the chat's own change
- /// until that is read.
- DateTime? get at => last?.createdAt ?? chat?.changedAt;
-
- /// The row's key: a project id may be in another Swarm too.
- String get key => '$swarmId/${project.id}';
-}
-
-/// [row]'s second line: its last message on one line, "You: " before the
-/// person's own and the writer's name before the PM's private lines
-/// ([swarmIsPmLine]), named in [reader], the row's own Swarm; what stands in
-/// for it while there is none. Empty while the last message is not read.
-String swarmBuddyLine(SwarmBuddyRow row, SwarmReader? reader) {
- final chat = row.chat;
- final last = row.last;
- if (chat == null) return 'No Buddy yet';
- if (last == null) return chat.mainSequence == 0 ? 'No messages yet' : '';
- final text = last.text.replaceAll(RegExp(r'\s+'), ' ').trim();
- final said = text.isNotEmpty
- ? text
- : switch (last.attachments.length) {
- 0 => '',
- 1 => 'Sent a file',
- final n => 'Sent $n files',
- };
- final snapshot = reader?.snapshot;
- final String? who;
- if (!last.fromAgent && last.authorId == reader?.accountId) {
- who = 'You';
- } else if (reader != null && swarmIsPmLine(reader, last)) {
- who = snapshot?.agentName(last.authorId, fallback: last.authorName);
- } else if (!last.fromAgent) {
- final email = snapshot?.people
- .where((p) => p.id == last.authorId)
- .firstOrNull
- ?.email;
- who = email == null || email.isEmpty
- ? 'Someone'
- : superTabPersonName(email);
- } else {
- who = null;
- }
- return who == null ? said : '$who: $said';
-}
-
-/// Buddies (Tony's prototype C2; Product Manager's brief 10-30): a row for
-/// each project of every listed Swarm ([SwarmBuddyRow]), newest first, with
-/// the person's own Buddy there and their Buddy chat's last message.
-///
-/// Each of the person's own Buddy chats is read from its last message on
-/// ([SwarmChatPeeks]), only while Buddies is [shown] and only when that
-/// message moved; a reply only in a thread does not move it. Another
-/// person's Buddy chat is never listed or read. Nothing is kept beyond what
-/// the peeks keep, which leave with the Swarm's access.
-class SwarmBuddyList extends ChangeNotifier {
- SwarmBuddyList(this.session) {
- inbox.addListener(_changed);
- session.peeks.addListener(_changed);
- }
-
- final SwarmSession session;
-
- SwarmInbox get inbox => session.inbox;
-
- bool _disposed = false;
- List<SwarmBuddyRow>? _rows;
-
- /// Screens showing Buddies ([watch]): while there is one, the Buddy chats
- /// are read when their last message moves.
- int _views = 0;
- bool get shown => _views > 0;
-
- /// A screen shows Buddies: its chats are read as they move.
- void watch() {
- if (_disposed || _views++ > 0) return;
- _want();
- }
-
- /// That screen went, or out of sight: once none shows it, the chats still
- /// waiting their turn for it are not read ([SwarmChatPeeks.withdraw]).
- void unwatch() {
- if (_views > 0 && --_views == 0) session.peeks.withdraw(this);
- }
-
- /// Every project's row, newest first; those with no time after, in the
- /// order read.
- List<SwarmBuddyRow> get rows => _rows ??= _build();
-
- /// The tab's badge: the Buddy chats with something unread.
- int get badge => rows.where((row) => row.unread).length;
-
- /// Some Buddy chat could not be read at its last message.
- bool get unreadChats => _anyChat(session.peeks.failedAt);
-
- /// A Buddy chat is being read for the first time since it moved, with
- /// nothing of it read yet.
- bool get reading => _anyChat(
- (reader, chat) =>
- session.peeks.busyAt(reader, chat) &&
- session.peeks.of(reader, chat) == null,
- );
-
- /// The person's Try again: the Buddy chats that failed are read again.
- void retry() => _anyChat((reader, chat) {
- session.peeks.retry(reader, chat, owner: this);
- return false;
- });
-
- bool _anyChat(bool Function(SwarmReader reader, String chatId) test) {
- for (final (reader, chat) in _chats()) {
- if (test(reader, chat.id)) return true;
- }
- return false;
- }
-
- /// The listed Swarms the person can still read, each with its reader.
- Iterable<(String, SwarmReader, SuperTabSnapshot)> _swarms() sync* {
- for (final swarm in inbox.swarms) {
- final reader = inbox.reader(swarm.id);
- final snapshot = reader?.snapshot;
- if (reader == null || snapshot == null || reader.accessRevoked) {
- continue;
- }
- yield (swarm.id, reader, snapshot);
- }
- }
-
- /// The person's own Buddy chats with a message in them.
- Iterable<(SwarmReader, SuperTabConversation)> _chats() sync* {
- for (final (_, reader, snapshot) in _swarms()) {
- for (final project in snapshot.projects) {
- final chat = swarmBuddyChat(reader, project.id);
- if (chat != null && chat.mainSequence > 0) yield (reader, chat);
- }
- }
- }
-
- /// Asks for each Buddy chat from its last message on: read only if that
- /// moved since it was last read.
- void _want() {
- for (final (reader, chat) in _chats()) {
- final last = chat.mainSequence;
- session.peeks.want(
- reader,
- chat.id,
- counter: last,
- after: last - 1,
- owner: this,
- );
- }
- }
-
- List<SwarmBuddyRow> _build() {
- final rows = <SwarmBuddyRow>[];
- for (final (id, reader, snapshot) in _swarms()) {
- for (final project in snapshot.projects) {
- final chat = swarmBuddyChat(reader, project.id);
- final peek = chat == null ? null : session.peeks.of(reader, chat.id);
- rows.add(
- SwarmBuddyRow(
- swarmId: id,
- project: project,
- name: swarmBuddyName(reader, project.id),
- note: swarmBuddyNote(reader, project.id),
- chat: chat,
- last: peek?.messages.where((m) => m.inMainStream).lastOrNull,
- // A muted chat never shows unread or counts (the desktop's
- // `buddyUnread`).
- unread: chat != null && swarmUnreadShown(reader, chat),
- muted: chat != null && swarmMuted(reader, chat),
- ),
- );
- }
- }
- // Stable: what has no time keeps the order read, after the rest.
- final order = {for (final (i, row) in rows.indexed) row: i};
- return List.unmodifiable(
- rows..sort((a, b) {
- final (x, y) = (a.at, b.at);
- if (x != null && y != null && x != y) return y.compareTo(x);
- if ((x == null) != (y == null)) return x == null ? 1 : -1;
- return order[a]!.compareTo(order[b]!);
- }),
- );
- }
-
- void _changed() {
- if (_disposed) return;
- _rows = null;
- if (shown) _want();
- notifyListeners();
- }
-
- @override
- void dispose() {
- _disposed = true;
- inbox.removeListener(_changed);
- session.peeks.removeListener(_changed);
- super.dispose();
- }
-}
diff --git a/mobile/lib/swarm/swarm_buddy_tab.dart b/mobile/lib/swarm/swarm_buddy_tab.dart
new file mode 100644
index 000000000..82288c2e8
--- /dev/null
+++ b/mobile/lib/swarm/swarm_buddy_tab.dart
@@ -0,0 +1,440 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/phone/out_of_sight.dart';
+import 'package:harness_mobile/phone/phone_sheet.dart';
+import 'package:harness_mobile/shared/theme/app_space.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/app_type.dart';
+import 'package:harness_mobile/theme/app_theme.dart' show AppColors;
+
+import 'swarm_buddy.dart';
+import 'swarm_conversation_page.dart';
+import 'swarm_home_top.dart' show swarmHomeListing, swarmHomeOffers;
+import 'swarm_inbox.dart';
+import 'swarm_reader.dart';
+import 'swarm_request.dart';
+import 'swarm_session.dart';
+import 'swarm_style.dart';
+import 'swarm_unread.dart';
+
+/// The Swarm the Buddy tab shows: the one the person last used
+/// ([SwarmHomePrefs.buddySwarmId]) or Home shows alone; before either, the one
+/// whose Buddy chat moved last, else the first. Never one the account lost or
+/// whose read was taken away; null with none.
+SwarmListing? swarmBuddySwarm(SwarmSession session) {
+ final inbox = session.inbox;
+ final offered = [
+ for (final swarm in inbox.swarms)
+ if (swarmHomeOffers(inbox, swarm.id)) swarm,
+ ];
+ if (offered.isEmpty) return null;
+ for (final id in [session.home.buddySwarmId, session.home.swarmId]) {
+ if (offered.where((swarm) => swarm.id == id).firstOrNull
+ case final swarm?) {
+ return swarm;
+ }
+ }
+ DateTime? moved(SwarmListing swarm) {
+ final reader = inbox.reader(swarm.id);
+ return reader == null
+ ? null
+ : swarmBuddyChat(reader, swarmBuddyKey)?.changedAt;
+ }
+
+ var newest = offered.first;
+ for (final swarm in offered.skip(1)) {
+ final (a, b) = (moved(swarm), moved(newest));
+ if (a != null && (b == null || a.isAfter(b))) newest = swarm;
+ }
+ return newest;
+}
+
+/// Whether [swarmBuddySwarm] can be trusted to act on: a choice is kept, or
+/// there is one Swarm, or every Swarm has answered its read. Before that the
+/// tab waits rather than open a chat, or keep a pick, in the first Swarm listed
+/// because the one used last has not been read yet.
+bool swarmBuddySwarmSettled(SwarmSession session) {
+ final inbox = session.inbox, home = session.home;
+ if (!home.loaded) return false;
+ final offered = [
+ for (final swarm in inbox.swarms)
+ if (swarmHomeOffers(inbox, swarm.id)) swarm.id,
+ ];
+ if (offered.length < 2 ||
+ offered.contains(home.buddySwarmId) ||
+ offered.contains(home.swarmId)) {
+ return true;
+ }
+ return offered.every((id) => !(inbox.reader(id)?.loading ?? false));
+}
+
+/// The Swarms whose one Buddy chat has something unread: the tab's count. A
+/// Swarm's older Buddy chats never count (the desktop's `_countedBuddyChats`),
+/// nor does a muted chat.
+int swarmBuddyTabBadge(SwarmSession session) {
+ final inbox = session.inbox;
+ var count = 0;
+ for (final swarm in inbox.swarms) {
+ final reader = inbox.reader(swarm.id);
+ if (reader == null || reader.accessRevoked) continue;
+ final chat = swarmBuddyChat(reader, swarmBuddyKey);
+ if (chat != null && swarmUnreadShown(reader, chat)) count++;
+ }
+ return count;
+}
+
+/// How a Buddy stands on its dot: lit while it runs, quiet while it is down.
+enum SwarmBuddyMark {
+ running('running'),
+ offline('offline');
+
+ const SwarmBuddyMark(this.label);
+
+ /// The word a screen reader says for the dot.
+ final String label;
+}
+
+/// The dot for the person's one Buddy in [reader]'s Swarm: what the desktop's
+/// # buddy row shows of it. None with no Buddy (none started, or one starting).
+SwarmBuddyMark? swarmBuddyMark(SwarmReader reader) {
+ if (reader.accessRevoked) return null;
+ final agent = swarmBuddy(reader, swarmBuddyKey);
+ if (agent == null) return null;
+ return agent.downSince == null
+ ? SwarmBuddyMark.running
+ : SwarmBuddyMark.offline;
+}
+
+/// The dot on the tab's glyph: the Buddy of the Swarm the tab shows.
+SwarmBuddyMark? swarmBuddyTabMark(SwarmSession session) {
+ final swarm = swarmBuddySwarm(session);
+ final reader = swarm == null ? null : session.inbox.reader(swarm.id);
+ return reader == null ? null : swarmBuddyMark(reader);
+}
+
+/// [mark] as a small dot, green while the Buddy runs; [ring] sets it off from
+/// what it sits on, as on the tab's glyph.
+class SwarmBuddyDot extends StatelessWidget {
+ const SwarmBuddyDot(this.mark, {super.key, this.ring});
+
+ final SwarmBuddyMark mark;
+ final Color? ring;
+
+ @override
+ Widget build(BuildContext context) => Container(
+ width: 9,
+ height: 9,
+ decoration: BoxDecoration(
+ color: mark == SwarmBuddyMark.running
+ ? AppColors.success
+ : AppPalette.textFaint,
+ shape: BoxShape.circle,
+ border: ring == null ? null : Border.all(color: ring!, width: 1.5),
+ ),
+ );
+}
+
+/// Picks the Swarm the Buddy tab shows, among those the account can read, by
+/// name; the one shown says current, another with something unread says so. A
+/// Swarm that leaves while it is open leaves the sheet, and is not picked.
+Future<void> showSwarmBuddySwitcher(
+ BuildContext context,
+ SwarmSession session,
+) => showPhoneSheet(
+ context,
+ title: 'Swarm',
+ rebuildOn: Listenable.merge([session.inbox, session.home]),
+ rows: () {
+ final inbox = session.inbox;
+ final shown = swarmBuddySwarm(session)?.id;
+ return (
+ actions: [
+ for (final swarm in inbox.swarms)
+ if (swarmHomeOffers(inbox, swarm.id))
+ PhoneSheetAction(
+ icon: LucideIcons.hexagon,
+ label: swarm.name,
+ value: swarm.id == shown
+ ? 'current'
+ : switch (inbox.reader(swarm.id)) {
+ final reader?
+ when switch (swarmBuddyChat(reader, swarmBuddyKey)) {
+ final chat? => swarmUnreadShown(reader, chat),
+ null => false,
+ } =>
+ 'unread',
+ _ => null,
+ },
+ onTap: () {
+ if (swarmHomeOffers(inbox, swarm.id)) {
+ session.home.showBuddy(swarm.id);
+ }
+ },
+ ),
+ ],
+ sections: const <PhoneSheetSection>[],
+ );
+ },
+);
+
+/// The Buddy tab (Tony, 11-02): the person's one Buddy chat of the Swarm they
+/// last used ([swarmBuddySwarm]), opened at once, its Start there while no
+/// Buddy runs. Several Swarms switch from its ⋮ ([showSwarmBuddySwitcher]).
+///
+/// A chat the read does not hold yet is opened on the server first, once for
+/// each read of the Swarm; a refusal says so with Try again, and an answer
+/// that comes after the Swarm was left or lost is dropped. A viewer, who opens
+/// nothing, is told they have none.
+class SwarmBuddyTabView extends StatefulWidget {
+ const SwarmBuddyTabView({super.key});
+
+ @override
+ State<SwarmBuddyTabView> createState() => _SwarmBuddyTabViewState();
+}
+
+/// A request for one read of one Swarm: [generation] is its reader's at the
+/// time ([SwarmReader.generation]), so a read anew from nothing asks again.
+typedef _Ask = ({String swarmId, int generation});
+
+class _SwarmBuddyTabViewState extends State<SwarmBuddyTabView> {
+ SwarmSession? _session;
+ bool _seen = false;
+
+ /// The chat being opened on the server, the one it answered with, and what
+ /// went wrong: each for the Swarm and read it names.
+ _Ask? _asking;
+ ({_Ask ask, String chatId})? _opened;
+ ({_Ask ask, String text})? _failed;
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final session = SwarmScope.of(context);
+ final seen = session != null && !OutOfSight.of(context);
+ if (identical(session, _session) && seen == _seen) return;
+ final same = identical(session, _session);
+ _see(false);
+ if (!same) {
+ // Another account, or signed out: nothing of the last one stays.
+ _asking = null;
+ _opened = null;
+ _failed = null;
+ }
+ _session = session;
+ _see(seen);
+ }
+
+ /// In sight: the Swarms are read, and their notices keep quiet.
+ void _see(bool seen) {
+ final session = _session;
+ if (session == null || seen == _seen) return;
+ _seen = seen;
+ if (seen) {
+ session.enter();
+ unawaited(session.inbox.refresh());
+ } else {
+ session.leave();
+ }
+ }
+
+ @override
+ void dispose() {
+ _see(false);
+ super.dispose();
+ }
+
+ /// Opens the one Buddy chat of [ask]'s Swarm on the server. An answer once
+ /// another ask took over is dropped; one kept counts only for the same Swarm
+ /// and read ([_body] compares the ask), so access lost, which reads anew, or
+ /// another Swarm shown never takes it up.
+ Future<void> _open(SwarmSession session, SwarmReader reader, _Ask ask) async {
+ _asking = ask;
+ String? id, error;
+ try {
+ id = await openSwarmBuddyChat(reader, swarmBuddyKey);
+ if (id == null) error = 'Your Buddy chat is not ready yet. Try again.';
+ } on SuperTabFailure catch (failure) {
+ error = failure.message;
+ } catch (_) {
+ error = 'Could not open your Buddy chat. Try again.';
+ }
+ if (!mounted || !identical(_session, session) || _asking != ask) return;
+ setState(() {
+ _asking = null;
+ if (id != null) {
+ _opened = (ask: ask, chatId: id);
+ // Read now, so its state shows at once rather than at the next poll.
+ unawaited(reader.refresh());
+ }
+ if (error != null) _failed = (ask: ask, text: error);
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final session = _session;
+ return Material(
+ color: AppPalette.windowBg,
+ child: session == null
+ ? const SizedBox.shrink()
+ : ListenWhileInSight(
+ listenable: Listenable.merge([session.inbox, session.home]),
+ builder: (context) => _body(context, session),
+ ),
+ );
+ }
+
+ Widget _body(BuildContext context, SwarmSession session) {
+ final inbox = session.inbox;
+ final swarm = swarmBuddySwarm(session);
+ if (swarm == null) {
+ if (inbox.error case final error? when !inbox.loaded) {
+ return _Plain(
+ note: error,
+ retryKey: 'swarm-buddy-retry-list',
+ onRetry: () => unawaited(inbox.refresh()),
+ );
+ }
+ return swarmHomeListing(inbox)
+ ? const _Plain(loading: true)
+ : const _Plain(note: 'No Swarm yet.');
+ }
+ if (!swarmBuddySwarmSettled(session)) return const _Plain(loading: true);
+ final reader = inbox.reader(swarm.id);
+ final snapshot = reader?.snapshot;
+ final several =
+ inbox.swarms.where((s) => swarmHomeOffers(inbox, s.id)).length > 1;
+ void pick() => unawaited(showSwarmBuddySwitcher(context, session));
+ final title = several ? pick : null;
+ if (reader == null || snapshot == null) {
+ if (reader?.error case final error?) {
+ return _Plain(
+ note: error,
+ retryKey: 'swarm-buddy-retry-read',
+ onRetry: () => unawaited(reader!.refresh()),
+ onTitle: title,
+ );
+ }
+ return _Plain(loading: true, onTitle: title);
+ }
+ if (!snapshot.swarmBuddy) {
+ // What the phone kept from an older read says nothing of it yet.
+ return reader.reads.value == 0
+ ? _Plain(loading: true, onTitle: title)
+ : _Plain(
+ note: 'Update your Harness server to use Buddy here.',
+ onTitle: title,
+ );
+ }
+ final ask = (swarmId: swarm.id, generation: reader.generation);
+ final chat =
+ reader.buddies.ownChats[swarmBuddyKey] ??
+ (_opened?.ask == ask ? _opened!.chatId : null);
+ if (chat != null) {
+ // Used now: a chat moving in another Swarm does not take the tab there.
+ if (session.home.loaded && session.home.buddySwarmId != swarm.id) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && swarmBuddySwarm(session)?.id == swarm.id) {
+ session.home.showBuddy(swarm.id);
+ }
+ });
+ }
+ return SwarmConversationPage(
+ key: ValueKey('swarm-buddy-tab-${swarm.id}/$chat'),
+ swarmId: swarm.id,
+ conversationId: chat,
+ tabRoot: true,
+ swarmSwitch: several ? (name: swarm.name, open: pick) : null,
+ );
+ }
+ if (!swarmCanWrite(reader)) {
+ return _Plain(note: 'You have no Buddy in this Swarm.', onTitle: title);
+ }
+ if (_failed case final failed? when failed.ask == ask) {
+ return _Plain(
+ note: failed.text,
+ retryKey: 'swarm-buddy-retry-open',
+ onRetry: () => setState(() => _failed = null),
+ onTitle: title,
+ );
+ }
+ if (_asking != ask) {
+ // Once for this read; a build while it is out asks nothing more.
+ _asking = ask;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && _asking == ask && identical(_session, session)) {
+ unawaited(_open(session, reader, ask));
+ }
+ });
+ }
+ return _Plain(loading: true, onTitle: title);
+ }
+}
+
+/// The tab before there is a chat to show: its title, then a skeleton while
+/// [loading], or [note] with Try again when [onRetry] is given. [onTitle]
+/// switches Swarm, with several to switch between.
+class _Plain extends StatelessWidget {
+ const _Plain({
+ this.loading = false,
+ this.note,
+ this.retryKey,
+ this.onRetry,
+ this.onTitle,
+ });
+
+ final bool loading;
+ final String? note;
+ final String? retryKey;
+ final VoidCallback? onRetry;
+ final VoidCallback? onTitle;
+
+ @override
+ Widget build(BuildContext context) => SafeArea(
+ bottom: false,
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ SwarmTabHeader(
+ 'Buddy',
+ onTitle: onTitle,
+ titleLabel: onTitle == null ? null : 'Buddy. Switch Swarm',
+ ),
+ if (loading)
+ Padding(
+ padding: const EdgeInsets.all(AppSpace.m),
+ child: SwarmSkeletonRows(id: 'swarm-buddy-loading'),
+ )
+ else if (note case final note?)
+ Padding(
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.screenInset,
+ vertical: AppSpace.s,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ note,
+ key: const ValueKey('swarm-buddy-note'),
+ style: AppType.body(color: AppPalette.textSecondary),
+ ),
+ ),
+ if (onRetry != null)
+ SwarmButton(
+ key: retryKey == null ? null : ValueKey<String>(retryKey!),
+ label: 'Try again',
+ style: SwarmButtonStyle.link,
+ onPressed: onRetry,
+ ),
+ ],
+ ),
+ ),
+ ],
+ ),
+ );
+}
diff --git a/mobile/lib/swarm/swarm_chat_menu.dart b/mobile/lib/swarm/swarm_chat_menu.dart
index 35a3b4eea..e11187a40 100644
--- a/mobile/lib/swarm/swarm_chat_menu.dart
+++ b/mobile/lib/swarm/swarm_chat_menu.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/shared/widgets/touch_target.dart';
import 'swarm_chat_manage.dart';
import 'swarm_chat_notify.dart';
+import 'swarm_buddy.dart' show swarmIsOldBuddyChat;
import 'swarm_reader.dart';
/// The chat menu's Notifications rows (the desktop's chat menu, Slack's
@@ -100,7 +101,10 @@ Future<void> showSwarmNotifySheet(
try {
await showPhoneSheet(
context,
- title: reader.snapshot?.conversation(chatId)?.title ?? '',
+ // An old Buddy chat's stored title is only the Buddy's default name.
+ title: swarmIsOldBuddyChat(reader, chatId)
+ ? 'Old chat'
+ : reader.snapshot?.conversation(chatId)?.title ?? '',
onShown: (route) {
sheet = route;
onShown?.call(route);
diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dart
index dbc13042b..7c11f9ab3 100644
--- a/mobile/lib/swarm/swarm_conversation.dart
+++ b/mobile/lib/swarm/swarm_conversation.dart
@@ -6,6 +6,7 @@ import 'package:flutter/foundation.dart';
import 'model.dart';
import 'prompt_alerts.dart';
import 'swarm_chat_cache.dart';
+import 'swarm_buddy.dart' show swarmIsOldBuddyChat;
import 'swarm_outbox.dart';
import 'swarm_outgoing_files.dart';
import 'swarm_reader.dart';
@@ -316,11 +317,16 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
}
/// The person may post here: a writer of the Swarm, in a conversation that
- /// is not archived.
+ /// is not archived, nor an older Buddy chat kept to read.
bool get canPost {
final snapshot = reader.snapshot;
final group = conversation;
- if (snapshot == null || group == null || group.archived) return false;
+ if (snapshot == null ||
+ group == null ||
+ group.archived ||
+ swarmIsOldBuddyChat(reader, id)) {
+ return false;
+ }
return snapshot.people
.where((p) => p.id == reader.accountId)
.firstOrNull
@@ -861,6 +867,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
'messageId': message.id,
'emoji': emoji.key,
'on': on,
+ // As the desktop's: the server refuses it in an older Buddy chat.
+ if (reader.snapshot?.swarmBuddy == true) 'oneBuddy': true,
},
},
);
@@ -1240,6 +1248,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {
],
if (tagged.isNotEmpty) 'mentions': tagged,
if (attachmentIds.isNotEmpty) 'attachmentIds': attachmentIds,
+ // As the desktop's: the server refuses it in an older Buddy chat.
+ if (reader.snapshot?.swarmBuddy == true) 'oneBuddy': true,
},
};
}
diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dart
index 4655cd921..4f03a1cbe 100644
--- a/mobile/lib/swarm/swarm_conversation_page.dart
+++ b/mobile/lib/swarm/swarm_conversation_page.dart
@@ -25,6 +25,8 @@ import 'swarm_post_line.dart';
import 'swarm_attach.dart';
import 'swarm_buddy.dart';
import 'swarm_buddy_chat.dart';
+import 'swarm_buddy_tab.dart'
+ show SwarmBuddyDot, SwarmBuddyMark, swarmBuddyMark;
import 'swarm_chat_menu.dart';
import 'swarm_file_links.dart';
import 'swarm_choices.dart';
@@ -117,6 +119,8 @@ class SwarmConversationPage extends StatefulWidget {
this.threadId,
this.mention,
this.homeC = false,
+ this.tabRoot = false,
+ this.swarmSwitch,
});
final String swarmId, conversationId;
@@ -150,6 +154,14 @@ class SwarmConversationPage extends StatefulWidget {
/// Buddy tab and on its own page.
final bool homeC;
+ /// At the root of a tab, as the Buddy tab holds the person's Buddy chat: no
+ /// back in its header, and its Buddy's dot before its name.
+ final bool tabRoot;
+
+ /// The Swarm it is in and how to pick another, for its Buddy menu; null with
+ /// no other Swarm to pick.
+ final SwarmBuddySwitch? swarmSwitch;
+
@override
State<SwarmConversationPage> createState() => _SwarmConversationPageState();
}
@@ -1135,12 +1147,30 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
required String? title,
String? project,
Widget? action,
+ SwarmBuddyMark? mark,
}) => Padding(
key: const ValueKey('swarm-chat-header'),
- padding: const EdgeInsets.fromLTRB(0, AppSpace.xs, _headerEnd, AppSpace.xs),
+ padding: EdgeInsets.fromLTRB(
+ widget.tabRoot ? AppSpace.screenInset : 0,
+ AppSpace.xs,
+ _headerEnd,
+ AppSpace.xs,
+ ),
child: Row(
children: [
- TtyBackButton(onPressed: () => Navigator.of(context).maybePop()),
+ if (!widget.tabRoot)
+ TtyBackButton(onPressed: () => Navigator.of(context).maybePop()),
+ if (mark != null)
+ Padding(
+ padding: const EdgeInsetsDirectional.only(end: AppSpace.s),
+ child: Semantics(
+ label: 'Buddy ${mark.label}',
+ child: SwarmBuddyDot(
+ mark,
+ key: const ValueKey('swarm-buddy-dot'),
+ ),
+ ),
+ ),
Expanded(
child: title == null
? Column(
@@ -1223,6 +1253,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
? view.title
: null,
project: view.project,
+ mark: widget.tabRoot ? swarmBuddyMark(c.reader) : null,
// The person's own Buddy chat: its Notifications, Rename Buddy,
// Remove Buddy. Any other chat: its Notifications (the desktop's
// chat menu).
@@ -1230,6 +1261,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
final buddy? => SwarmBuddyMenuButton(
actions: buddy,
chatId: widget.conversationId,
+ swarmId: widget.swarmId,
+ swarmSwitch: widget.swarmSwitch,
),
null => SwarmChatMenuButton(reader: c.reader, chatId: c.id),
},
@@ -1348,7 +1381,38 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
);
},
),
- if (view.canPost)
+ if (view.old)
+ Padding(
+ key: const ValueKey('swarm-old-chat'),
+ padding: const EdgeInsets.symmetric(
+ horizontal: AppSpace.l,
+ vertical: AppSpace.s,
+ ),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ 'Old chat, kept to read.',
+ style: swarmChatText(
+ 13.5,
+ color: AppPalette.textSecondary,
+ ),
+ ),
+ ),
+ if (swarmCanWrite(c.reader) ||
+ swarmBuddyChat(c.reader, swarmBuddyKey) != null)
+ SwarmButton(
+ key: const ValueKey(
+ 'swarm-old-chat-open-buddy',
+ ),
+ label: 'Open Buddy',
+ style: SwarmButtonStyle.link,
+ onPressed: () => _openBuddy(c),
+ ),
+ ],
+ ),
+ )
+ else if (view.canPost)
Flexible(
child: ListenableBuilder(
listenable: Listenable.merge([c.composer, _voice]),
@@ -1380,6 +1444,24 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>
],
);
+ /// From an old chat, back to the person's one Buddy: the Buddy tab, in this
+ /// Swarm, with what covered it gone; its chat as its own page with no tabs
+ /// up.
+ void _openBuddy(SwarmConversation c) {
+ final session = _session;
+ if (session == null) return;
+ final show = session.showBuddyTab;
+ if (show == null) {
+ unawaited(
+ openSwarmBuddy(context, c.reader, widget.swarmId, swarmBuddyKey),
+ );
+ return;
+ }
+ session.home.showBuddy(widget.swarmId);
+ Navigator.of(context).popUntil((route) => route.isFirst);
+ show();
+ }
+
/// Opens [projectId]'s chat with [pmId] mentioned in its draft: the PM's
/// private line answered where the PM reads, and everyone with it.
void _answerIn(String projectId, String pmId) => openSwarmProject(
@@ -2160,6 +2242,7 @@ class _ChatView {
required this.project,
required this.canPost,
required this.archived,
+ required this.old,
required this.names,
required this.mentions,
required this.roles,
@@ -2183,9 +2266,14 @@ class _ChatView {
final group = c.conversation;
final agents = snapshot?.agents ?? const <SuperTabAgent>[];
final names = [for (final agent in agents) snapshot!.agentName(agent.id)];
+ // An older Buddy chat, where the Swarm gives one Buddy: kept to read, with
+ // no Buddy of its own to start, name or ask (the desktop's).
+ final old = group != null && swarmIsOldBuddyChat(reader, group.id);
// The person's own Buddy chat (#2090): named after their Buddy, and
- // holding every question the PM asked them in its project, as on Desktop.
- final buddyProject = group != null && swarmIsOwnBuddyChat(reader, group.id)
+ // holding every question the PM asked them in its project, as on Desktop;
+ // their one chat for the Swarm holds every project's.
+ final buddyProject =
+ group != null && !old && swarmIsOwnBuddyChat(reader, group.id)
? group.projectId
: null;
final buddy = buddyProject == null
@@ -2205,15 +2293,21 @@ class _ChatView {
for (final need in session.inbox.needs)
if (need is SwarmDecisionNeed &&
need.swarmId == reader.tabId &&
- need.decision.projectId == buddyProject)
+ (buddyProject == swarmBuddyKey ||
+ need.decision.projectId == buddyProject))
need,
];
return _ChatView(
known: group != null,
- title: group == null ? 'Chat' : buddy ?? group.label,
+ title: group == null
+ ? 'Chat'
+ : old
+ ? 'Old chat'
+ : buddy ?? group.label,
project: buddy != null && project != null ? '#$project' : project,
canPost: c.canPost,
archived: group?.archived ?? false,
+ old: old,
names: names,
mentions: before != null && listEquals(before.names, names)
? before.mentions
@@ -2253,6 +2347,9 @@ class _ChatView {
final String? project;
final bool canPost, archived;
+ /// An older Buddy chat, kept to read ([swarmIsOldBuddyChat]).
+ final bool old;
+
/// The Swarm's agents by name, and the @mentions of them marked in
/// messages: made again only when a name changed.
final List<String> names;
@@ -2308,6 +2405,7 @@ class _ChatView {
other.project == project &&
other.canPost == canPost &&
other.archived == archived &&
+ other.old == old &&
listEquals(other.names, names) &&
mapEquals(other.roles, roles) &&
setEquals(other.leads, leads) &&
@@ -2324,6 +2422,7 @@ class _ChatView {
project,
canPost,
archived,
+ old,
Object.hashAll(names),
Object.hashAll(mentionable),
decisions,
diff --git a/mobile/lib/swarm/swarm_home_prefs.dart b/mobile/lib/swarm/swarm_home_prefs.dart
index d29597617..42f94ba50 100644
--- a/mobile/lib/swarm/swarm_home_prefs.dart
+++ b/mobile/lib/swarm/swarm_home_prefs.dart
@@ -15,6 +15,7 @@ typedef _SwarmHomeKept = ({
SwarmHomeFilter filter,
SwarmHomeSort sort,
bool unreadsFirst,
+ String? buddySwarm,
});
/// What the person chose for Swarm Home on this phone (Tony, 2026-10-29):
@@ -60,6 +61,11 @@ class SwarmHomePrefs extends ChangeNotifier {
String? get swarmId => _swarmId;
String? _swarmId;
+ /// The Swarm the Buddy tab last showed, the person's latest pick among
+ /// their Swarms there or on Home; null before they use one.
+ String? get buddySwarmId => _buddySwarmId;
+ String? _buddySwarmId;
+
/// Which projects Home lists ([swarmHomeFiltered]), kept on this phone as
/// the desktop keeps its unread filter on its computer.
SwarmHomeFilter get filter => _filter;
@@ -95,7 +101,8 @@ class SwarmHomePrefs extends ChangeNotifier {
bool _shownChosen = false,
_filterChosen = false,
_sortChosen = false,
- _unreadsChosen = false;
+ _unreadsChosen = false,
+ _buddyChosen = false;
/// The account's Swarms, as [keepOnly] last heard them; null before. What
/// is read back is held to them too.
@@ -152,11 +159,25 @@ class SwarmHomePrefs extends ChangeNotifier {
_shownChosen = true;
_touched = true;
}
- if (_swarmId == swarmId) return;
+ final buddy = swarmId != null && swarmId != _buddySwarmId;
+ if (buddy) _chooseBuddySwarm(swarmId);
+ if (_swarmId == swarmId && !buddy) return;
_swarmId = swarmId;
_changed();
}
+ /// The Buddy tab shows Swarm [swarmId], from now on until another is used.
+ void showBuddy(String swarmId) {
+ if (_buddySwarmId == swarmId) return;
+ _chooseBuddySwarm(swarmId);
+ _changed();
+ }
+
+ void _chooseBuddySwarm(String swarmId) {
+ if (!_loaded) _buddyChosen = true;
+ _buddySwarmId = swarmId;
+ }
+
/// Home lists the projects [filter] lets through.
void setFilter(SwarmHomeFilter filter) {
if (!_loaded) {
@@ -217,7 +238,10 @@ class SwarmHomePrefs extends ChangeNotifier {
_folds.removeWhere(other);
final gone = _swarmId != null && !swarmIds.contains(_swarmId);
if (gone) _swarmId = null;
- return gone || _pins.length + _folds.length != before;
+ final buddyGone =
+ _buddySwarmId != null && !swarmIds.contains(_buddySwarmId);
+ if (buddyGone) _buddySwarmId = null;
+ return gone || buddyGone || _pins.length + _folds.length != before;
}
/// At most [keptPins] pins and [keptFolds] folds, the oldest going first;
@@ -276,6 +300,7 @@ class SwarmHomePrefs extends ChangeNotifier {
if (!_filterChosen) _filter = read.filter;
if (!_sortChosen) _sort = read.sort;
if (!_unreadsChosen) _unreadsFirst = read.unreadsFirst;
+ if (!_buddyChosen) _buddySwarmId = read.buddySwarm;
// Left meanwhile: the later time stands.
if (seenAt != null && seenAt.isAfter(_seenAt ?? DateTime(0))) {
_seenAt = seenAt;
@@ -298,6 +323,7 @@ class SwarmHomePrefs extends ChangeNotifier {
filter: SwarmHomeFilter.all,
sort: SwarmHomeSort.sections,
unreadsFirst: false,
+ buddySwarm: null,
);
/// What was kept: written before folds were, it has none; before the
@@ -329,6 +355,9 @@ class SwarmHomePrefs extends ChangeNotifier {
? SwarmHomeSort.newest
: SwarmHomeSort.sections,
unreadsFirst: json['unreadsFirst'] == true,
+ buddySwarm: json['buddySwarm'] is String
+ ? json['buddySwarm'] as String
+ : null,
);
} on FormatException {
return _nothingKept;
@@ -342,6 +371,7 @@ class SwarmHomePrefs extends ChangeNotifier {
if (_pins.isEmpty &&
_folds.isEmpty &&
_swarmId == null &&
+ _buddySwarmId == null &&
_seenAt == null &&
!viewChanged) {
await store.delete(_key);
@@ -352,6 +382,7 @@ class SwarmHomePrefs extends ChangeNotifier {
'pins': [..._pins],
if (_folds.isNotEmpty) 'folded': [..._folds],
'swarm': ?_swarmId,
+ 'buddySwarm': ?_buddySwarmId,
'seen': ?_seenAt?.millisecondsSinceEpoch,
if (_filter == SwarmHomeFilter.unread) 'unread': true,
if (_filter == SwarmHomeFilter.mentions) 'filter': 'mentions',
diff --git a/mobile/lib/swarm/swarm_home_view.dart b/mobile/lib/swarm/swarm_home_view.dart
index 0a0085289..a3a4ee76f 100644
--- a/mobile/lib/swarm/swarm_home_view.dart
+++ b/mobile/lib/swarm/swarm_home_view.dart
@@ -29,6 +29,7 @@ SwarmHomeSwarm swarmHomeSwarm(
'name': snapshot.name,
'ownerId': snapshot.ownerId,
'paused': snapshot.paused,
+ if (snapshot.swarmBuddy) 'swarmBuddy': true,
'projects': [for (final p in snapshot.projects) _project(p)],
'people': [
for (final p in snapshot.people)
@@ -42,7 +43,9 @@ SwarmHomeSwarm swarmHomeSwarm(
],
'agents': [
for (final a in snapshot.agents)
- {
+ // A thread's own session is not drawn: kept, it would read as the
+ // Buddy until the next read.
+ if (a.buddySession == null) {
..._agent(a),
if (buddies.buddyOwners[a.id] case final owner?)
'buddyOf': {'personId': owner},
@@ -53,7 +56,7 @@ SwarmHomeSwarm swarmHomeSwarm(
{
..._conversation(c),
if (buddies.chatOwners[c.id] case final owner?) ...{
- 'kind': 'buddy',
+ 'kind': c.isSwarmBuddyChat ? 'swarm-buddy' : 'buddy',
'buddyOwnerId': owner,
},
},
@@ -92,6 +95,7 @@ Map<String, dynamic> _agent(SuperTabAgent a) => {
'projectId': a.hasProjectId ? a.projectId : null,
'name': a.name,
'displayName': ?a.displayName,
+ 'buddyScope': ?a.buddyScope,
'machineId': a.machineId,
'harnessId': a.harnessId,
'contributorId': a.contributorId,
diff --git a/mobile/lib/swarm/swarm_new_message_sheet.dart b/mobile/lib/swarm/swarm_new_message_sheet.dart
index ab9e1fa8e..fbf257ada 100644
--- a/mobile/lib/swarm/swarm_new_message_sheet.dart
+++ b/mobile/lib/swarm/swarm_new_message_sheet.dart
@@ -128,6 +128,7 @@ swarmNewMessageChats(SwarmInbox inbox, List<SwarmListing> swarms) {
if (own != null &&
own.projectId == project.id &&
!own.archived &&
+ !swarmIsOldBuddyChat(reader, own.id) &&
own.buddyOwnerId == reader.accountId) {
chats.add(
SwarmNewMessageChat(
diff --git a/mobile/lib/swarm/swarm_session.dart b/mobile/lib/swarm/swarm_session.dart
index dad1c8983..ac1e863d5 100644
--- a/mobile/lib/swarm/swarm_session.dart
+++ b/mobile/lib/swarm/swarm_session.dart
@@ -8,7 +8,6 @@ import '../notify/system_notices.dart';
import '../phone/voice_input_controller.dart';
import '../settings/experimental_features.dart';
import 'swarm_activity.dart';
-import 'swarm_buddy_list.dart';
import 'swarm_chat_peeks.dart';
import 'swarm_choices.dart';
import 'swarm_dictation.dart';
@@ -64,8 +63,7 @@ class SwarmSession extends ChangeNotifier {
final String accountId;
final SwarmInbox inbox;
- /// The project and Buddy chats read for Activity and Buddies, a few at a
- /// time ([SwarmChatPeeks]).
+ /// The project chats read for Activity, a few at a time ([SwarmChatPeeks]).
final peeks = SwarmChatPeeks();
/// Activity, in place of Needs you: its filters, counts and handled rows.
@@ -73,10 +71,9 @@ class SwarmSession extends ChangeNotifier {
SwarmActivity get activity => _activity ??= SwarmActivity(this);
SwarmActivity? _activity;
- /// Buddies: the person's own Buddy in each project, with its chat's last
- /// message. Made when a screen first asks for it.
- SwarmBuddyList get buddyList => _buddyList ??= SwarmBuddyList(this);
- SwarmBuddyList? _buddyList;
+ /// Brings the Buddy tab forward, while Swarm's tabs are up ([SwarmTabsPage]);
+ /// null under none.
+ VoidCallback? showBuddyTab;
/// What the person chose for Home on this phone: the projects pinned and
/// the one Swarm shown. A Swarm the account no longer has takes its own.
@@ -295,7 +292,6 @@ class SwarmSession extends ChangeNotifier {
}
_held.clear();
_activity?.dispose();
- _buddyList?.dispose();
peeks.dispose();
inbox.removeListener(_needsChanged);
_announcer.clear();
diff --git a/mobile/lib/swarm/swarm_tabs.dart b/mobile/lib/swarm/swarm_tabs.dart
index 74ef6c26a..709c02455 100644
--- a/mobile/lib/swarm/swarm_tabs.dart
+++ b/mobile/lib/swarm/swarm_tabs.dart
@@ -9,7 +9,7 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/app_type.dart';
import 'swarm_activity_page.dart';
-import 'swarm_buddies_page.dart';
+import 'swarm_buddy_tab.dart';
import 'swarm_page.dart';
import 'swarm_session.dart';
import 'swarm_style.dart';
@@ -21,8 +21,8 @@ enum SwarmTab {
/// Swarm Home: the Swarms' projects, and what moved in them.
home,
- /// The person's Buddy in each project.
- buddies,
+ /// The person's one Buddy: its chat, in the Swarm they last used.
+ buddy,
/// What needs the person, and what came for them.
activity,
@@ -44,6 +44,7 @@ class SwarmTabEntry {
required this.icon,
required this.screen,
this.badge,
+ this.mark,
});
final SwarmTab tab;
@@ -57,11 +58,15 @@ class SwarmTabEntry {
/// The count on the glyph, from the account's Swarm, read again whenever
/// the Swarm changes; none for null or 0.
final SwarmTabBadge? Function(SwarmSession session)? badge;
+
+ /// A dot on the glyph saying how what the tab shows stands, and that in
+ /// words for a screen reader; none for null. Read as the count is.
+ final SwarmBuddyMark? Function(SwarmSession session)? mark;
}
/// Swarm's tabs, in the bar's order: each part of Swarm plugs its screen in
-/// here, one entry each: Home; Buddies ([SwarmBuddiesView]) with the Buddy
-/// chats that have something unread counted; Activity ([SwarmActivityView])
+/// here, one entry each: Home; Buddy ([SwarmBuddyTabView]) with the Swarms whose
+/// Buddy chat has something unread counted, lit while the Buddy runs; Activity ([SwarmActivityView])
/// with what waits on the person counted; and You ([SwarmYouPage]).
/// [onSettings] opens the phone's Settings over the tabs, from You.
List<SwarmTabEntry> swarmTabs({
@@ -74,11 +79,12 @@ List<SwarmTabEntry> swarmTabs({
screen: (_) => const SwarmPage(),
),
SwarmTabEntry(
- tab: SwarmTab.buddies,
- label: 'Buddies',
+ tab: SwarmTab.buddy,
+ label: 'Buddy',
icon: LucideIcons.messageCircle300,
- screen: (_) => const SwarmBuddiesView(),
- badge: (session) => (count: session.buddyList.badge, warn: false),
+ screen: (_) => const SwarmBuddyTabView(),
+ badge: (session) => (count: swarmBuddyTabBadge(session), warn: false),
+ mark: swarmBuddyTabMark,
),
SwarmTabEntry(
tab: SwarmTab.activity,
@@ -135,6 +141,25 @@ class _SwarmTabsPageState extends State<SwarmTabsPage> {
/// after, so opening a tab builds nothing under the others.
final _screens = <SwarmTab, Widget>{};
+ SwarmSession? _session;
+
+ void _showBuddy() => _show(SwarmTab.buddy);
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final session = SwarmScope.of(context);
+ if (identical(session, _session)) return;
+ _session?.showBuddyTab = null;
+ _session = session?..showBuddyTab = _showBuddy;
+ }
+
+ @override
+ void dispose() {
+ _session?.showBuddyTab = null;
+ super.dispose();
+ }
+
void _show(SwarmTab tab) {
if (tab == _open || !_tabs.any((entry) => entry.tab == tab)) return;
setState(() => _open = tab);
@@ -226,6 +251,7 @@ class SwarmTabBar extends StatelessWidget {
entry: entry,
open: entry.tab == open,
badge: session == null ? null : entry.badge?.call(session),
+ mark: session == null ? null : entry.mark?.call(session),
onTap: () => onOpen(entry.tab),
),
),
@@ -249,12 +275,14 @@ class _TabButton extends StatelessWidget {
required this.entry,
required this.open,
required this.badge,
+ required this.mark,
required this.onTap,
});
final SwarmTabEntry entry;
final bool open;
final SwarmTabBadge? badge;
+ final SwarmBuddyMark? mark;
final VoidCallback onTap;
@override
@@ -271,7 +299,7 @@ class _TabButton extends StatelessWidget {
key: ValueKey('swarm-tab-$name'),
button: true,
selected: open,
- label: count > 0 ? '${entry.label}, $count' : entry.label,
+ label: [entry.label, ?mark?.label, if (count > 0) '$count'].join(', '),
onTap: tap,
excludeSemantics: true,
child: GestureDetector(
@@ -292,6 +320,16 @@ class _TabButton extends StatelessWidget {
clipBehavior: Clip.none,
children: [
Icon(entry.icon, size: 26, color: ink),
+ if (mark case final mark?)
+ Positioned(
+ right: -2,
+ bottom: -1,
+ child: SwarmBuddyDot(
+ mark,
+ key: ValueKey('swarm-tab-mark-$name'),
+ ring: Tty.of(context).ground,
+ ),
+ ),
if (count > 0)
Positioned(
left: 15,
diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dart
index b40f3cc67..fdd96531f 100644
--- a/mobile/lib/swarm/swarm_thread.dart
+++ b/mobile/lib/swarm/swarm_thread.dart
@@ -524,6 +524,8 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {
'recipientIds': const <String>[],
if (_alsoSend) 'alsoSend': true,
if (ids.isNotEmpty) 'attachmentIds': ids,
+ // As the desktop's: the server refuses it in an older Buddy chat.
+ if (reader.snapshot?.swarmBuddy == true) 'oneBuddy': true,
},
},
messageId: superTabMessageId(
diff --git a/mobile/test/swarm/swarm_activity_shots_test.dart b/mobile/test/swarm/swarm_activity_shots_test.dart
index 40759d0f0..a6d3be10c 100644
--- a/mobile/test/swarm/swarm_activity_shots_test.dart
+++ b/mobile/test/swarm/swarm_activity_shots_test.dart
@@ -490,7 +490,7 @@ void main() {
const tabs = [
'swarm-tab-home',
- 'swarm-tab-buddies',
+ 'swarm-tab-buddy',
'swarm-tab-activity',
'swarm-tab-you',
];
@@ -535,9 +535,9 @@ void main() {
'swarm-activity-reply-',
]);
- await openTab('buddies');
- await capture('buddies');
- await captureTargets('buddies-targets', [...tabs, 'swarm-buddies-row-']);
+ await openTab('buddy');
+ await capture('buddy');
+ await captureTargets('buddy-targets', tabs);
await tester.pumpWidget(const SizedBox());
host.dispose();
diff --git a/mobile/test/swarm/swarm_buddies_fixture.dart b/mobile/test/swarm/swarm_buddies_fixture.dart
deleted file mode 100644
index bca057a6e..000000000
--- a/mobile/test/swarm/swarm_buddies_fixture.dart
+++ /dev/null
@@ -1,172 +0,0 @@
-import 'swarm_fixture.dart';
-
-/// Buddies' backend as a test scripts it (swarm_buddy_list_test.dart,
-/// swarm_buddies_page_test.dart), built by hand so it reads like the wire.
-
-const buddiesWeb = 'project-2';
-const buddiesDocs = 'project-3';
-
-/// The person's Buddy chats: Mobile's, where Wren runs, and Web's, where
-/// Kite is offline. Docs has none.
-const buddiesMobileChat = 'buddy-mobile';
-const buddiesWebChat = 'buddy-web';
-
-/// Someone else's Buddy chat in Mobile: never listed, never read.
-const buddiesTheirChat = 'buddy-ann';
-
-String buddiesChatPath(String chat, {String swarmId = tab}) =>
- '/api/super-tabs/$swarmId/conversations/$chat/messages';
-
-Map<String, dynamic> buddiesMessage(
- String chat,
- int sequence, {
- String text = '',
- bool mine = false,
- String author = 'agent-wren',
- String? thread,
-}) => {
- 'id': '$chat-$sequence',
- 'conversationId': chat,
- 'text': text.isEmpty ? 'Row $sequence' : text,
- 'sequence': sequence,
- 'thread': ?thread,
- 'author': mine
- ? {'kind': 'person', 'id': me, 'name': '[email protected]'}
- : {'kind': 'agent', 'id': author, 'name': 'Buddy'},
- 'createdAt': DateTime.utc(2026, 10, 29, 8, sequence).toIso8601String(),
-};
-
-Map<String, dynamic> buddiesProject(String id, String name, String lead) => {
- 'id': id,
- 'name': name,
- 'ownerId': me,
- 'leadConversationId': lead,
- 'visibility': 'public',
- 'members': <Object>[],
- 'updateMinutes': 5,
-};
-
-/// Swarm [swarmId]'s first load: Mobile, Web and Docs, each with its project
-/// chat; the person's Buddy chats in Mobile ([mobileSequence] rows, Wren's
-/// Buddy [wren] by name, running) and Web (4 rows, Kite offline); someone
-/// else's Buddy chat in Mobile. The server's read marks are [readMarks].
-Map<String, dynamic> buddiesLoad({
- String swarmId = tab,
- String swarmName = 'Phone Swarm',
- int mobileSequence = 7,
- int? mobileMainSequence,
- String wren = 'Wren',
- Map<String, int> readMarks = const {buddiesMobileChat: 5, buddiesWebChat: 4},
-}) {
- Map<String, dynamic> inWeb(Map<String, dynamic> row) => {
- ...row,
- 'projectId': buddiesWeb,
- };
- Map<String, dynamic> inDocs(Map<String, dynamic> row) => {
- ...row,
- 'projectId': buddiesDocs,
- };
- return firstLoad(
- tabId: swarmId,
- derived: {'readMarks': readMarks},
- head: headData(
- id: swarmId,
- name: swarmName,
- projects: [
- buddiesProject(project, 'Mobile', leadChat),
- buddiesProject(buddiesWeb, 'Web', 'group-lead-web'),
- buddiesProject(buddiesDocs, 'Docs', 'group-lead-docs'),
- ],
- ),
- agents: [
- agent('agent-lead', name: 'Lead', displayName: 'River'),
- buddyData('agent-wren', displayName: wren),
- inWeb({
- ...buddyData('agent-kite', displayName: 'Kite'),
- 'downSince': '2026-10-29T07:00:00.000Z',
- }),
- buddyData('agent-ann', owner: 'person-ann', displayName: 'Ann'),
- ],
- groups: [
- {
- ...buddyChatData(
- buddiesMobileChat,
- agentIds: ['agent-wren'],
- lastMessageSequence: mobileSequence,
- ),
- 'lastMainSequence': ?mobileMainSequence,
- },
- inWeb(
- buddyChatData(
- buddiesWebChat,
- agentIds: ['agent-kite'],
- lastMessageSequence: 4,
- ),
- ),
- buddyChatData(
- buddiesTheirChat,
- owner: 'person-ann',
- agentIds: ['agent-ann'],
- lastMessageSequence: 3,
- ),
- inWeb(groupData('group-lead-web', title: 'Web', leadId: 'agent-lead')),
- inDocs(groupData('group-lead-docs', title: 'Docs', leadId: 'agent-lead')),
- ],
- );
-}
-
-/// One Swarm as [buddiesLoad] has it. Mobile's Buddy chat answers Wren's
-/// last line, Web's the person's own; every other chat answers nothing.
-FakeSwarm buddiesBackend({
- int mobileSequence = 7,
- int? mobileMainSequence,
- Map<String, int> readMarks = const {buddiesMobileChat: 5, buddiesWebChat: 4},
-}) {
- final fake = FakeSwarm();
- fake.routes['/api/super-tabs/list'] = (_) => {
- 'tabs': [
- {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 1},
- ],
- 'next': null,
- };
- fake.routes['/api/super-tabs/$tab/parts'] = (_) => buddiesLoad(
- mobileSequence: mobileSequence,
- mobileMainSequence: mobileMainSequence,
- readMarks: readMarks,
- );
- fake.routes['/api/super-tabs/$tab/changes'] = (_) =>
- changes(cursor: 'c2', derived: {'readMarks': readMarks});
- fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {
- 'decisions': <Object>[],
- };
- fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {
- 'mentions': <Object>[],
- };
- fake.routes['/api/super-tabs/$tab/commands'] = (body) => {
- 'result': switch (body?['command']) {
- {'type': 'buddy.chat', 'projectId': buddiesDocs} => {
- 'conversationId': 'buddy-docs',
- },
- _ => <String, dynamic>{},
- },
- };
- fake.routes['/api/super-tabs/$tab/conversations/'] = (_) => {
- 'messages': <Object>[],
- 'next': null,
- };
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {
- 'messages': [
- buddiesMessage(buddiesMobileChat, 7, text: 'Done: the build is up.'),
- ],
- 'threads': <Object>[],
- 'next': null,
- };
- fake.routes[buddiesChatPath(buddiesWebChat)] = (_) => {
- 'messages': [
- buddiesMessage(buddiesWebChat, 4, text: 'Is 0.9 out yet?', mine: true),
- ],
- 'threads': <Object>[],
- 'next': null,
- };
- return fake;
-}
diff --git a/mobile/test/swarm/swarm_buddies_page_test.dart b/mobile/test/swarm/swarm_buddies_page_test.dart
deleted file mode 100644
index 6ad8f91f5..000000000
--- a/mobile/test/swarm/swarm_buddies_page_test.dart
+++ /dev/null
@@ -1,356 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter/material.dart';
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/notify/system_notices.dart';
-import 'package:harness_mobile/phone/out_of_sight.dart';
-import 'package:harness_mobile/settings/experimental_features.dart';
-import 'package:harness_mobile/shared/theme/app_theme.dart' show AppFont;
-import 'package:harness_mobile/swarm/swarm_buddies_page.dart';
-import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
-import 'package:harness_mobile/swarm/swarm_request.dart';
-import 'package:harness_mobile/swarm/swarm_session.dart';
-import 'package:harness_mobile/swarm/swarm_style.dart';
-
-import '../voice_fakes.dart';
-import 'swarm_buddies_fixture.dart';
-import 'swarm_fixture.dart';
-
-/// The Buddies screen (Tony's prototype C2): a row per project, its tile and
-/// name, how the person's Buddy there stands and the last message of their
-/// Buddy chat; unread ones bold; a tap opens that chat. It reads only while
-/// on screen, says what it could not read, and shows nothing of a Swarm the
-/// person can no longer read.
-void main() {
- const mobile = 'swarm-buddies-row-$tab/$project';
- const web = 'swarm-buddies-row-$tab/$buddiesWeb';
- const docs = 'swarm-buddies-row-$tab/$buddiesDocs';
-
- /// [home] under a signed-in shell's Swarm, Swarm on, on a 390-point phone.
- Future<SwarmHost> pump(
- WidgetTester tester,
- FakeSwarm fake, {
- Widget home = const SwarmBuddiesView(),
- }) async {
- await tester.binding.setSurfaceSize(const Size(390, 844));
- addTearDown(() => tester.binding.setSurfaceSize(null));
- final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
- ..value = {PhoneExperiment.swarm};
- final account = ValueNotifier<String?>(me);
- final host = SwarmHost(
- accountId: () => account.value,
- account: account,
- request: fake.request,
- notices: SilentSystemNotices(),
- features: features,
- readMarks: MemoryKeyValueStore(),
- )..foreground = false;
- addTearDown(host.dispose);
- await tester.pumpWidget(
- MaterialApp(
- builder: (context, child) => SwarmScope(notifier: host, child: child!),
- home: home,
- ),
- );
- await tester.pumpAndSettle();
- return host;
- }
-
- Finder key(String value) => find.byKey(ValueKey(value));
-
- /// The Buddy chat is a page of its own, with its own header: Swarm Home C
- /// has no Buddy tab, and no project page of direction B opens under it.
- void expectOwnPage() {
- expect(key('swarm-chat-header'), findsOneWidget, reason: 'its header');
- expect(key('swarm-project-tab-buddy'), findsNothing, reason: "B's tabs");
- }
-
- Finder inside(String row, Finder finder) =>
- find.descendant(of: key(row), matching: finder);
-
- int chatReads(FakeSwarm fake) =>
- fake.paths.where((p) => p.contains('/messages')).length;
-
- FontWeight? weightOf(WidgetTester tester, String row, String text) =>
- tester.widget<Text>(inside(row, find.text(text))).style?.fontWeight;
-
- testWidgets("its title, then a row per project, newest first: its tile and "
- "name, its Buddy's state and the last message", (tester) async {
- await pump(tester, buddiesBackend());
-
- expect(find.text('Buddies'), findsOneWidget);
- expect(inside(mobile, find.byType(SwarmProjectTile)), findsOneWidget);
- expect(inside(mobile, find.text('Mobile')), findsOneWidget);
- expect(inside(mobile, find.text('running')), findsOneWidget);
- expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);
- expect(inside(web, find.text('offline')), findsOneWidget);
- expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);
- expect(inside(docs, find.text('not started')), findsOneWidget);
- expect(inside(docs, find.text('No Buddy yet')), findsOneWidget);
- double y(String row) => tester.getTopLeft(key(row)).dy;
- expect(y(mobile), lessThan(y(web)));
- expect(y(web), lessThan(y(docs)));
- expect(
- find.text("person-ann's Buddy"),
- findsNothing,
- reason: "someone else's Buddy chat is not listed",
- );
- });
-
- testWidgets("each row's time sits at its end, whatever its name's length", (
- tester,
- ) async {
- await pump(tester, buddiesBackend());
-
- double end(String row) =>
- tester.getTopRight(key('swarm-buddies-age-$tab/$row')).dx;
- expect(end(buddiesWeb), end(project));
- expect(
- end(project),
- closeTo(tester.getTopRight(key(mobile)).dx - 16, .5),
- reason: "at the row's inset",
- );
- });
-
- testWidgets('a chat with something unread is bold, with a dot; a read one '
- 'is quiet', (tester) async {
- await pump(tester, buddiesBackend());
-
- expect(weightOf(tester, mobile, 'Mobile'), AppFont.semibold);
- expect(key('swarm-buddies-unread-$tab/$project'), findsOneWidget);
- expect(weightOf(tester, web, 'Web'), isNot(AppFont.semibold));
- expect(key('swarm-buddies-unread-$tab/$buddiesWeb'), findsNothing);
- expect(find.bySemanticsLabel(RegExp('Unread messages')), findsOneWidget);
- });
-
- testWidgets('every row is a thumb tall, and a tap opens its Buddy chat', (
- tester,
- ) async {
- await pump(tester, buddiesBackend());
-
- for (final row in [mobile, web, docs]) {
- expect(tester.getSize(key(row)).height, greaterThanOrEqualTo(44));
- }
- await tester.tap(key(mobile));
- await tester.pumpAndSettle();
-
- final page = tester.widget<SwarmConversationPage>(
- find.byType(SwarmConversationPage),
- );
- expect((page.swarmId, page.conversationId), (tab, buddiesMobileChat));
- expectOwnPage();
- });
-
- testWidgets('a project with no Buddy chat opens one on a tap', (
- tester,
- ) async {
- final fake = buddiesBackend();
- await pump(tester, fake);
-
- await tester.tap(key(docs));
- await tester.pumpAndSettle();
-
- expect(fake.commands.single, {
- 'type': 'buddy.chat',
- 'projectId': buddiesDocs,
- });
- final page = tester.widget<SwarmConversationPage>(
- find.byType(SwarmConversationPage),
- );
- expect((page.swarmId, page.conversationId), (tab, 'buddy-docs'));
- expectOwnPage();
- });
-
- testWidgets('two quick taps on a row with its chat open one chat', (
- tester,
- ) async {
- await pump(tester, buddiesBackend());
-
- // Two in one frame, then a third a frame later, at the row's start
- // where it is then: still in sight while the chat slides in over it.
- await tester.tap(key(mobile));
- await tester.tap(key(mobile));
- await tester.pump(const Duration(milliseconds: 16));
- await tester.tapAt(tester.getTopLeft(key(mobile)) + const Offset(24, 24));
- await tester.pumpAndSettle();
-
- expect(
- find.byType(SwarmConversationPage, skipOffstage: false),
- findsOneWidget,
- );
- });
-
- testWidgets('two quick taps on a row with no chat yet ask once and open '
- 'one chat', (tester) async {
- final fake = buddiesBackend();
- final gate = Completer<void>();
- final answer = fake.routes['/api/super-tabs/$tab/commands']!;
- fake.routes['/api/super-tabs/$tab/commands'] = (body) async {
- await gate.future;
- return answer(body);
- };
- await pump(tester, fake);
-
- await tester.tap(key(docs));
- await tester.pump();
- await tester.tap(key(docs));
- await tester.pump();
- gate.complete();
- await tester.pumpAndSettle();
-
- expect(fake.commands, hasLength(1));
- expect(find.byType(SwarmConversationPage), findsOneWidget);
- });
-
- testWidgets('an open the server refuses says why and opens nothing', (
- tester,
- ) async {
- final fake = buddiesBackend();
- fake.routes['/api/super-tabs/$tab/commands'] = (_) =>
- throw const SuperTabFailure('FORBIDDEN', 'You cannot do that here.');
- await pump(tester, fake);
-
- await tester.tap(key(docs));
- await tester.pumpAndSettle();
-
- expect(find.byType(SwarmConversationPage), findsNothing);
- expect(find.text('You cannot do that here.'), findsOneWidget);
- });
-
- testWidgets('a viewer with no Buddy chat there is told so, and nothing is '
- 'asked of the server', (tester) async {
- final fake = buddiesBackend();
- fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
- ...buddiesLoad(),
- 'members': [part(me, 1, person(me, role: 'viewer'))],
- };
- await pump(tester, fake);
-
- await tester.tap(key(docs));
- await tester.pumpAndSettle();
-
- expect(fake.commands, isEmpty);
- expect(find.byType(SwarmConversationPage), findsNothing);
- expect(find.text('You have no Buddy in this project.'), findsOneWidget);
- });
-
- testWidgets('access lost while a chat is being opened: nothing opens', (
- tester,
- ) async {
- final fake = buddiesBackend();
- final gate = Completer<void>();
- final answer = fake.routes['/api/super-tabs/$tab/commands']!;
- fake.routes['/api/super-tabs/$tab/commands'] = (body) async {
- await gate.future;
- return answer(body);
- };
- final host = await pump(tester, fake);
-
- await tester.tap(key(docs));
- await tester.pump();
- host.session!.inbox.reader(tab)!.revoke();
- gate.complete();
- // A chat opened would pulse its skeleton for ever: frames, not settle.
- for (var i = 0; i < 10; i++) {
- await tester.pump(const Duration(milliseconds: 100));
- }
-
- expect(find.byType(SwarmConversationPage), findsNothing);
- expect(find.text('buddy-docs'), findsNothing);
- });
-
- testWidgets('out of sight, it reads no chat; in sight again, it does', (
- tester,
- ) async {
- final fake = buddiesBackend();
- final hidden = ValueNotifier(true);
- addTearDown(hidden.dispose);
- await pump(
- tester,
- fake,
- home: ValueListenableBuilder<bool>(
- valueListenable: hidden,
- builder: (context, out, _) =>
- OutOfSight(hidden: out, child: const SwarmBuddiesView()),
- ),
- );
- expect(chatReads(fake), 0);
-
- hidden.value = false;
- await tester.pumpAndSettle();
- expect(chatReads(fake), 2);
- expect(find.text('Done: the build is up.'), findsOneWidget);
- });
-
- testWidgets('a chat that could not be read says so; Try again reads it; '
- 'none waits on a stuck Loading', (tester) async {
- final fake = buddiesBackend();
- var fail = true;
- final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) => fail
- ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')
- : answer(body);
- await pump(tester, fake);
-
- expect(find.text('Some Buddy chats could not be read.'), findsOneWidget);
- expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);
- expect(key('swarm-buddies-loading'), findsNothing);
- expect(
- tester.getSize(key('swarm-buddies-retry')).height,
- greaterThanOrEqualTo(44),
- );
-
- fail = false;
- await tester.tap(key('swarm-buddies-retry'));
- await tester.pumpAndSettle();
-
- expect(find.text('Some Buddy chats could not be read.'), findsNothing);
- expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);
- });
-
- testWidgets('the rows show while their chats are read, their last line '
- 'filling as each answers', (tester) async {
- final fake = buddiesBackend();
- final gate = Completer<void>();
- final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {
- await gate.future;
- return answer(body);
- };
- await pump(tester, fake);
-
- expect(key(mobile), findsOneWidget);
- expect(inside(mobile, find.text('Done: the build is up.')), findsNothing);
- expect(inside(web, find.text('You: Is 0.9 out yet?')), findsOneWidget);
-
- gate.complete();
- await tester.pumpAndSettle();
- expect(inside(mobile, find.text('Done: the build is up.')), findsOneWidget);
- });
-
- testWidgets('access lost while it is open: every row of that Swarm goes', (
- tester,
- ) async {
- final host = await pump(tester, buddiesBackend());
- expect(key(mobile), findsOneWidget);
-
- host.session!.inbox.reader(tab)!.revoke();
- await tester.pumpAndSettle();
-
- for (final row in [mobile, web, docs]) {
- expect(key(row), findsNothing);
- }
- expect(find.text('Done: the build is up.'), findsNothing);
- expect(find.text('Mobile'), findsNothing);
- });
-
- testWidgets('a Swarm with no project says so', (tester) async {
- final fake = buddiesBackend();
- fake.routes['/api/super-tabs/$tab/parts'] = (_) =>
- firstLoad(head: headData(projects: const []));
- await pump(tester, fake);
-
- expect(key('swarm-buddies-none'), findsOneWidget);
- expect(find.text('No projects yet.'), findsOneWidget);
- });
-}
diff --git a/mobile/test/swarm/swarm_buddy_list_test.dart b/mobile/test/swarm/swarm_buddy_list_test.dart
deleted file mode 100644
index 80fe458bf..000000000
--- a/mobile/test/swarm/swarm_buddy_list_test.dart
+++ /dev/null
@@ -1,382 +0,0 @@
-import 'dart:async';
-
-import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/notify/system_notices.dart';
-import 'package:harness_mobile/swarm/swarm_buddy_list.dart';
-import 'package:harness_mobile/swarm/swarm_chat_notify.dart';
-import 'package:harness_mobile/swarm/swarm_request.dart';
-import 'package:harness_mobile/swarm/swarm_session.dart';
-
-import '../voice_fakes.dart' show MemoryKeyValueStore;
-import 'swarm_buddies_fixture.dart';
-import 'swarm_fixture.dart';
-
-/// Buddies (Tony's prototype C2): one row per project of every Swarm, with
-/// the person's own Buddy there, how it stands and the last message of their
-/// Buddy chat, read from that message on and only while Buddies is on screen.
-void main() {
- TestWidgetsFlutterBinding.ensureInitialized();
-
- Future<SwarmSession> start(FakeSwarm fake) async {
- final session = SwarmSession(
- accountId: me,
- request: fake.request,
- notices: SilentSystemNotices(),
- readMarks: MemoryKeyValueStore(),
- );
- addTearDown(session.dispose);
- await session.inbox.refresh();
- await settle();
- return session;
- }
-
- List<String> reads(FakeSwarm fake) => [
- for (final path in fake.paths)
- if (path.contains('/messages')) path,
- ];
-
- SwarmBuddyRow row(SwarmBuddyList list, String projectId, {String? swarm}) =>
- list.rows.singleWhere(
- (row) =>
- row.project.id == projectId &&
- (swarm == null || row.swarmId == swarm),
- );
-
- test(
- 'one row per project, newest first; one with no Buddy chat last',
- () async {
- final session = await start(buddiesBackend());
- final list = session.buddyList..watch();
- await settle();
-
- expect(
- [for (final row in list.rows) row.project.name],
- ['Mobile', 'Web', 'Docs'],
- );
- expect(row(list, project).chat?.id, buddiesMobileChat);
- expect(row(list, buddiesDocs).chat, isNull);
- },
- );
-
- test('reads nothing until Buddies is on screen, then each of the '
- "person's Buddy chats from its last message on, once", () async {
- final fake = buddiesBackend();
- final session = await start(fake);
- final list = session.buddyList;
- expect(reads(fake), isEmpty);
-
- list.watch();
- await settle();
- expect(reads(fake)..sort(), [
- '${buddiesChatPath(buddiesMobileChat)}?after=6',
- '${buddiesChatPath(buddiesWebChat)}?after=3',
- ], reason: "never someone else's Buddy chat, nor a project chat");
-
- list.unwatch();
- list.watch();
- await settle();
- expect(reads(fake), hasLength(2), reason: 'nothing moved: nothing read');
- });
-
- test('out of sight before its chats are read: what waits is taken back '
- 'and read only once Buddies shows again', () async {
- final fake = buddiesBackend();
- final session = await start(fake);
- final reader = session.inbox.reader(tab)!;
- // Another list's two reads hold both slots.
- final other = Object();
- final gates = [Completer<void>(), Completer<void>()];
- for (final (i, gate) in gates.indexed) {
- fake.routes[buddiesChatPath('other-$i')] = (_) async {
- await gate.future;
- return {'messages': <Object>[], 'next': null};
- };
- session.peeks.want(reader, 'other-$i', counter: 1, owner: other);
- }
- List<String> buddyReads() => [
- for (final path in reads(fake))
- if (!path.contains('/other-')) path,
- ];
- final list = session.buddyList..watch();
- await settle();
- expect(buddyReads(), isEmpty);
-
- list.unwatch();
- for (final gate in gates) {
- gate.complete();
- }
- await settle();
- expect(buddyReads(), isEmpty, reason: 'nothing starts out of sight');
-
- list.watch();
- await settle();
- expect(buddyReads(), hasLength(2));
- });
-
- test("each row's last message, its Buddy's name and how it stands", () async {
- final session = await start(buddiesBackend());
- final list = session.buddyList..watch();
- await settle();
- final reader = session.inbox.reader(tab)!;
-
- final mobile = row(list, project);
- expect(mobile.last?.text, 'Done: the build is up.');
- expect(swarmBuddyLine(mobile, reader), 'Done: the build is up.');
- expect((mobile.name, mobile.note), ('Wren', null), reason: 'it runs');
-
- final web = row(list, buddiesWeb);
- expect(swarmBuddyLine(web, reader), 'You: Is 0.9 out yet?');
- expect((web.name, web.note), ('Kite', 'offline'));
-
- final docs = row(list, buddiesDocs);
- expect(swarmBuddyLine(docs, reader), 'No Buddy yet');
- expect((docs.name, docs.note), ('Buddy', 'not started'));
- });
-
- test('a muted Buddy chat is never unread and never counts on the badge, '
- 'muted on the desktop or chosen on this phone', () async {
- final fake = buddiesBackend();
- final load = fake.routes['/api/super-tabs/$tab/parts']!;
- fake.routes['/api/super-tabs/$tab/parts'] = (body) {
- final answer = Map<String, dynamic>.of(
- load(body) as Map<String, dynamic>,
- );
- answer['derived'] = {
- ...answer['derived'] as Map<String, dynamic>,
- 'chatSettings': {buddiesMobileChat: 'muted'},
- };
- return answer;
- };
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
-
- expect(row(list, project).unread, isFalse);
- expect(row(list, project).muted, isTrue);
- expect(row(list, buddiesWeb).muted, isFalse);
- expect(list.badge, 0);
-
- // Back to Mentions only from this phone: unread again at once.
- fake.routes['/api/super-tabs/$tab/conversations/$buddiesMobileChat/'
- 'notifications'] = (_) =>
- Completer<Object?>().future;
- unawaited(
- session.inbox
- .reader(tab)!
- .setNotify(buddiesMobileChat, SwarmNotify.mentions),
- );
- await settle();
- expect(row(list, project).unread, isTrue);
- expect(row(list, project).muted, isFalse);
- expect(list.badge, 1);
- });
-
- test('a chat past its read mark is unread; the badge counts those', () async {
- final session = await start(buddiesBackend());
- final list = session.buddyList..watch();
- await settle();
-
- expect(row(list, project).unread, isTrue);
- expect(row(list, buddiesWeb).unread, isFalse);
- expect(row(list, buddiesDocs).unread, isFalse);
- expect(list.badge, 1);
- });
-
- test('a new message in the chat is read again; a reply only in a thread '
- 'is not', () async {
- final fake = buddiesBackend();
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
- expect(reads(fake), hasLength(2));
-
- var version = 30;
- Future<void> move(int sequence, int main) async {
- fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
- cursor: 'c${version++}',
- derived: const {
- 'readMarks': {buddiesMobileChat: 5, buddiesWebChat: 4},
- },
- groups: [
- part(buddiesMobileChat, version, {
- ...buddyChatData(
- buddiesMobileChat,
- agentIds: ['agent-wren'],
- lastMessageSequence: sequence,
- ),
- 'lastMainSequence': main,
- }),
- ],
- );
- await session.inbox.refresh();
- await settle();
- }
-
- await move(8, 7);
- expect(reads(fake), hasLength(2), reason: 'a thread reply moved it');
-
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {
- 'messages': [buddiesMessage(buddiesMobileChat, 9, text: 'Next one')],
- 'threads': <Object>[],
- 'next': null,
- };
- await move(9, 9);
- expect(reads(fake).last, '${buddiesChatPath(buddiesMobileChat)}?after=8');
- expect(row(list, project).last?.text, 'Next one');
- });
-
- test('the last message is the newest in the chat itself, not a reply in '
- 'a thread', () async {
- final fake = buddiesBackend(mobileSequence: 9, mobileMainSequence: 8);
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) => {
- 'messages': [
- buddiesMessage(buddiesMobileChat, 8, text: 'In the chat'),
- buddiesMessage(
- buddiesMobileChat,
- 9,
- text: 'In a thread',
- thread: '$buddiesMobileChat-8',
- ),
- ],
- 'threads': <Object>[],
- 'next': null,
- };
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
-
- expect(row(list, project).last?.text, 'In the chat');
- });
-
- test('access lost while Buddies is open: its rows go, and an answer still '
- 'on its way is dropped', () async {
- final fake = buddiesBackend();
- final gate = Completer<void>();
- final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {
- await gate.future;
- return answer(body);
- };
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
- expect(row(list, buddiesWeb).last, isNotNull);
-
- session.inbox.reader(tab)!.revoke();
- gate.complete();
- await settle();
-
- expect(list.rows, isEmpty);
- expect(list.badge, 0);
- expect(session.peeks.held, 0, reason: 'nothing of it left in memory');
- });
-
- test('the same Buddy id and chat id in two Swarms: each row reads and '
- 'names its own', () async {
- final fake = buddiesBackend();
- const other = 'tab-2';
- fake.routes['/api/super-tabs/list'] = (_) => {
- 'tabs': [
- {'id': tab, 'name': 'Phone Swarm', 'ownerId': me, 'lastChangedAt': 2},
- {'id': other, 'name': 'Other', 'ownerId': me, 'lastChangedAt': 1},
- ],
- 'next': null,
- };
- fake.routes['/api/super-tabs/$other/parts'] = (_) =>
- buddiesLoad(swarmId: other, swarmName: 'Other', wren: 'Pip');
- fake.routes['/api/super-tabs/$other/changes'] = (_) =>
- changes(cursor: 'c2');
- fake.routes['/api/super-tabs/$other/decisions?state=open'] = (_) => {
- 'decisions': <Object>[],
- };
- fake.routes['/api/super-tabs/$other/mentions?state=waiting'] = (_) => {
- 'mentions': <Object>[],
- };
- fake.routes[buddiesChatPath(buddiesMobileChat, swarmId: other)] = (_) => {
- 'messages': [
- buddiesMessage(buddiesMobileChat, 7, text: 'From the other Swarm'),
- ],
- 'threads': <Object>[],
- 'next': null,
- };
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
-
- final mine = row(list, project, swarm: tab);
- final theirs = row(list, project, swarm: other);
- expect((mine.name, mine.last?.text), ('Wren', 'Done: the build is up.'));
- expect((theirs.name, theirs.last?.text), ('Pip', 'From the other Swarm'));
- expect(mine.key, isNot(theirs.key));
- });
-
- test('a chat that fails to read says so, is tried a few times, and Try '
- 'again reads it once more; never stuck reading', () async {
- final fake = buddiesBackend();
- var fail = true;
- final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) => fail
- ? throw const SuperTabFailure('MACHINE_UNAVAILABLE', 'No computer.')
- : answer(body);
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
- // Shown again and again, at the same counter.
- for (var i = 0; i < 4; i++) {
- list
- ..unwatch()
- ..watch();
- await settle();
- }
-
- int mobileReads() =>
- reads(fake)
- .where((p) => p.startsWith(buddiesChatPath(buddiesMobileChat)))
- .length;
- expect(mobileReads(), 3);
- expect(list.unreadChats, isTrue);
- expect(list.reading, isFalse);
- expect(row(list, project).last, isNull);
-
- fail = false;
- list.retry();
- await settle();
- expect(mobileReads(), 4);
- expect(list.unreadChats, isFalse);
- expect(row(list, project).last?.text, 'Done: the build is up.');
- });
-
- test(
- 'a Buddy chat the person may no longer read is skipped quietly',
- () async {
- final fake = buddiesBackend();
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (_) =>
- throw const SuperTabFailure('FORBIDDEN', 'Not yours.');
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
-
- expect(list.unreadChats, isFalse);
- expect(row(list, project).last, isNull);
- expect(row(list, buddiesWeb).last, isNotNull);
- },
- );
-
- test('says it is reading while a chat is read for the first time', () async {
- final fake = buddiesBackend();
- final gate = Completer<void>();
- final answer = fake.routes[buddiesChatPath(buddiesMobileChat)]!;
- fake.routes[buddiesChatPath(buddiesMobileChat)] = (body) async {
- await gate.future;
- return answer(body);
- };
- final session = await start(fake);
- final list = session.buddyList..watch();
- await settle();
- expect(list.reading, isTrue);
-
- gate.complete();
- await settle();
- expect(list.reading, isFalse);
- });
-}
diff --git a/mobile/test/swarm/swarm_buddy_tab_shots_test.dart b/mobile/test/swarm/swarm_buddy_tab_shots_test.dart
new file mode 100644
index 000000000..2525eccf5
--- /dev/null
+++ b/mobile/test/swarm/swarm_buddy_tab_shots_test.dart
@@ -0,0 +1,225 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/shared/theme/color_palette.dart';
+import 'package:harness_mobile/swarm/swarm_tabs.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// Review screenshots of the Buddy tab, 390 points wide in both phone themes,
+/// from made-up data, to the folder `SWARM_BUDDY_TAB_SHOTS` names: running,
+/// no Buddy yet, its ⋮ with two Swarms, Old chats and an old chat.
+final shots = Platform.environment['SWARM_BUDDY_TAB_SHOTS'];
+
+void main() {
+ setUpAll(() async {
+ if (shots == null || !Platform.isMacOS) return;
+ final sf = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNS.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFont', 'Roboto']) {
+ await (FontLoader(family)..addFont(Future.value(sf))).load();
+ }
+ final mono = ByteData.sublistView(
+ await File('/System/Library/Fonts/SFNSMono.ttf').readAsBytes(),
+ );
+ for (final family in ['.AppleSystemUIFontMonospaced', 'monospace']) {
+ await (FontLoader(family)..addFont(Future.value(mono))).load();
+ }
+ final manifest =
+ jsonDecode(await rootBundle.loadString('FontManifest.json')) as List;
+ for (final entry in manifest.cast<Map<String, dynamic>>()) {
+ final loader = FontLoader(entry['family'] as String);
+ for (final font in (entry['fonts'] as List).cast<Map>()) {
+ loader.addFont(rootBundle.load(font['asset'] as String));
+ }
+ await loader.load();
+ }
+ });
+
+ testWidgets('the Buddy tab, in both phone themes', (tester) async {
+ const chat = 'buddy-one', old = 'buddy-old';
+ addTearDown(() => tester.binding.setSurfaceSize(null));
+ Map<String, dynamic> line(
+ String id,
+ int sequence,
+ String text, {
+ bool mine = false,
+ }) => {
+ 'id': id,
+ 'conversationId': id.startsWith('o') ? old : chat,
+ 'text': text,
+ 'sequence': sequence,
+ 'author': mine
+ ? {'kind': 'person', 'id': me, 'name': 'tony'}
+ : {'kind': 'agent', 'id': 'agent-wren', 'name': 'Wren'},
+ 'createdAt': DateTime.now()
+ .subtract(Duration(minutes: 9 - sequence))
+ .toUtc()
+ .toIso8601String(),
+ };
+ for (final palette in [HarnessPalette.graphite, HarnessPalette.paper]) {
+ final brightness = palette.brightness;
+ AppTheme.palette.value = palette;
+ AppTheme.brightness.value = brightness;
+ await tester.binding.setSurfaceSize(const Size(390, 780));
+ for (final state in [
+ 'running',
+ 'start',
+ 'menu',
+ 'old-list',
+ 'old-chat',
+ ]) {
+ final running = state != 'start';
+ final fake = FakeSwarm();
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ {'id': tab, 'name': 'autonomous.ai', 'ownerId': me},
+ if (state == 'menu')
+ {'id': 'swarm-2', 'name': 'Home lab', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ const derived = {'swarmBuddy': true};
+ final load = {
+ ...firstLoad(
+ groups: [
+ {
+ ...groupData(
+ chat,
+ title: 'Buddy',
+ agentIds: const ['agent-wren'],
+ lastMessageSequence: 3,
+ ),
+ 'kind': 'swarm-buddy',
+ 'buddyOwnerId': me,
+ 'buddyName': 'Wren',
+ }..remove('projectId'),
+ buddyChatData(old, lastMessageSequence: 2),
+ ],
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ if (running)
+ {
+ ...buddyData('agent-wren', displayName: 'Wren'),
+ 'buddyScope': 'swarm',
+ }..remove('projectId'),
+ ],
+ machines: [
+ {
+ 'machineId': 'mac-1',
+ 'name': "Tony's Mac",
+ 'contributorId': me,
+ 'engines': ['claude', 'codex'],
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ },
+ },
+ ],
+ derived: derived,
+ ),
+ 'members': [
+ part(me, 1, {...person(me), 'email': '[email protected]'}),
+ ],
+ };
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => load;
+ fake.routes['/api/super-tabs/swarm-2/parts'] = (_) =>
+ firstLoad(tabId: 'swarm-2', derived: derived);
+ for (final swarm in [tab, 'swarm-2']) {
+ fake.routes['/api/super-tabs/$swarm/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$swarm/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$swarm/mentions?state=waiting'] = (_) =>
+ {'mentions': <Object>[]};
+ }
+ fake.routes['/api/super-tabs/$tab/conversations/$chat/messages'] =
+ (_) => {
+ 'messages': [
+ line('m3', 3, 'It treats your one Buddy as every project\'s.'),
+ line('m2', 2, 'Look at the held pull request.', mine: true),
+ line('m1', 1, 'Morning. What are we looking at?'),
+ ],
+ 'next': null,
+ };
+ fake.routes['/api/super-tabs/$tab/conversations/$old/messages'] = (_) =>
+ {
+ 'messages': [
+ line('o2', 2, 'Notes from before the one Buddy.'),
+ line('o1', 1, 'Can you read the release plan?', mine: true),
+ ],
+ 'next': null,
+ };
+ final host = SwarmHost(
+ accountId: () => me,
+ account: ValueNotifier<String?>(me),
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm},
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (_, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmTabsPage(),
+ ),
+ ),
+ );
+ Future<void> settle() async {
+ for (var i = 0; i < 12; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ await settle();
+ await tester.tap(find.byKey(const ValueKey('swarm-tab-buddy')));
+ await settle();
+ if (state != 'running' && state != 'start') {
+ await tester.tap(find.byKey(const ValueKey('swarm-buddy-menu')));
+ await settle();
+ expect(find.text('Old chats'), findsOneWidget);
+ }
+ if (state == 'old-list' || state == 'old-chat') {
+ await tester.tap(find.text('Old chats'));
+ await settle();
+ }
+ if (state == 'old-chat') {
+ await tester.tap(find.text('Mobile'));
+ await settle();
+ }
+ expect(tester.takeException(), isNull);
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()!
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 3);
+ final png = await image.toByteData(format: ui.ImageByteFormat.png);
+ await Directory(shots!).create(recursive: true);
+ await File('$shots/phone-buddy-tab-$state-${brightness.name}-390.png')
+ .writeAsBytes(png!.buffer.asUint8List());
+ image.dispose();
+ });
+ await tester.pumpWidget(const SizedBox());
+ host.dispose();
+ await tester.pump(const Duration(minutes: 1));
+ }
+ }
+ }, skip: shots == null);
+}
diff --git a/mobile/test/swarm/swarm_buddy_tab_test.dart b/mobile/test/swarm/swarm_buddy_tab_test.dart
new file mode 100644
index 000000000..2fd1d76ea
--- /dev/null
+++ b/mobile/test/swarm/swarm_buddy_tab_test.dart
@@ -0,0 +1,1021 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/settings/experimental_features.dart';
+import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
+import 'package:harness_mobile/swarm/swarm_buddy.dart';
+import 'package:harness_mobile/swarm/swarm_home_list.dart';
+import 'package:harness_mobile/swarm/swarm_home_prefs.dart';
+import 'package:harness_mobile/swarm/swarm_home_view.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_new_message_sheet.dart';
+import 'package:harness_mobile/swarm/swarm_request.dart';
+import 'package:harness_mobile/swarm/swarm_session.dart';
+import 'package:harness_mobile/swarm/swarm_tabs.dart';
+
+import '../voice_fakes.dart';
+import 'swarm_fixture.dart';
+
+/// The Buddy tab (Tony, 11-02): the person's one Buddy chat, opened at once,
+/// in the state Desktop shows; their older chats read only from its ⋮.
+void main() {
+ const one = 'buddy-one';
+ const oldMobile = 'buddy-old-mobile';
+ const oldWeb = 'buddy-old-web';
+ const other = 'swarm-2';
+ const web = 'project-web';
+ String commands(String swarm) => '/api/super-tabs/$swarm/commands';
+ String messages(String chat, {String swarm = tab}) =>
+ '/api/super-tabs/$swarm/conversations/$chat/messages';
+
+ Map<String, dynamic> oneChat({
+ String id = one,
+ String owner = me,
+ int last = 1,
+ }) => {
+ ...groupData(
+ id,
+ title: "$owner's Buddy",
+ agentIds: const ['agent-wren'],
+ lastMessageSequence: last,
+ ),
+ 'kind': 'swarm-buddy',
+ 'buddyOwnerId': owner,
+ }..remove('projectId');
+
+ Map<String, dynamic> wren({String owner = me, String? downSince}) => {
+ ...buddyData('agent-wren', owner: owner, displayName: 'Wren'),
+ 'buddyScope': 'swarm',
+ 'downSince': ?downSince,
+ }..remove('projectId');
+
+ Map<String, dynamic> webProject() => {
+ 'id': web,
+ 'name': 'Web',
+ 'ownerId': me,
+ 'leadConversationId': 'lead-web',
+ 'visibility': 'public',
+ 'members': <Object>[],
+ 'updateMinutes': 5,
+ };
+
+ Map<String, dynamic> line(String chat, int sequence, String text) => {
+ 'id': '$chat-$sequence',
+ 'conversationId': chat,
+ 'text': text,
+ 'sequence': sequence,
+ 'author': {'kind': 'agent', 'id': 'agent-wren', 'name': 'Wren'},
+ 'attachments': <Object>[],
+ 'reactions': <Object>[],
+ 'createdAt': DateTime.utc(2026, 11, 2, 1, sequence).toIso8601String(),
+ };
+
+ /// [swarm] of [fake]: one Buddy chat [chats] and agents [agents], over the
+ /// projects Mobile (and Web) with the server's one Buddy on unless [flag] is
+ /// off.
+ void route(
+ FakeSwarm fake, {
+ String swarm = tab,
+ List<Map<String, dynamic>> chats = const [],
+ List<Map<String, dynamic>> agents = const [],
+ List<Map<String, dynamic>> starts = const [],
+ String role = 'owner',
+ bool flag = true,
+ }) {
+ final derived = {'swarmBuddy': ?(flag ? true : null)};
+ fake.routes['/api/super-tabs/$swarm/parts'] = (_) => {
+ ...firstLoad(
+ tabId: swarm,
+ head: headData(
+ id: swarm,
+ projects: [
+ ...(headData()['projects'] as List).cast<Map<String, dynamic>>(),
+ webProject(),
+ ],
+ ),
+ groups: [
+ for (final chat in chats) chat,
+ {...groupData('lead-web', title: 'Web'), 'projectId': web},
+ ],
+ agents: [
+ agent('agent-lead', name: 'Lead', displayName: 'River'),
+ ...agents,
+ ],
+ starts: starts,
+ derived: derived,
+ ),
+ 'members': [part(me, 1, person(me, role: role))],
+ };
+ fake.routes['/api/super-tabs/$swarm/changes'] = (_) =>
+ changes(cursor: 'c2', derived: derived);
+ fake.routes['/api/super-tabs/$swarm/decisions?state=open'] = (_) => {
+ 'decisions': <Object>[],
+ };
+ fake.routes['/api/super-tabs/$swarm/mentions?state=waiting'] = (_) => {
+ 'mentions': <Object>[],
+ };
+ fake.routes[commands(swarm)] = (_) => {'result': <String, dynamic>{}};
+ }
+
+ void listed(FakeSwarm fake, List<String> swarms) =>
+ fake.routes['/api/super-tabs/list'] = (_) => {
+ 'tabs': [
+ for (final swarm in swarms)
+ {'id': swarm, 'name': 'Swarm $swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+
+ FakeSwarm backend({
+ List<Map<String, dynamic>>? chats,
+ List<Map<String, dynamic>>? agents,
+ List<Map<String, dynamic>> starts = const [],
+ String role = 'owner',
+ bool flag = true,
+ }) {
+ final fake = FakeSwarm();
+ listed(fake, [tab]);
+ route(
+ fake,
+ chats: chats ?? [oneChat()],
+ agents: agents ?? [wren()],
+ starts: starts,
+ role: role,
+ flag: flag,
+ );
+ fake.routes[messages(one)] = (_) => {
+ 'messages': [line(one, 1, 'Hello from the one Buddy')],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ Map<String, dynamic> oldChat(String id, {String? projectId, int last = 2}) =>
+ {
+ ...buddyChatData(id, lastMessageSequence: last),
+ 'projectId': projectId ?? project,
+ };
+
+ late ValueNotifier<String?> account;
+
+ /// Long enough for a sheet or page to finish moving; a skeleton shown while
+ /// something is out never settles, so this does not wait for that.
+ Future<void> settle(WidgetTester tester) async {
+ for (var i = 0; i < 12; i++) {
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+ }
+
+ Future<SwarmHost> pump(WidgetTester tester, FakeSwarm fake) async {
+ tester.view.physicalSize = const Size(1170, 2532);
+ tester.view.devicePixelRatio = 3;
+ addTearDown(tester.view.reset);
+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())
+ ..value = {PhoneExperiment.swarm};
+ account = ValueNotifier<String?>(me);
+ final host = SwarmHost(
+ accountId: () => account.value,
+ account: account,
+ request: fake.request,
+ notices: SilentSystemNotices(),
+ features: features,
+ readMarks: MemoryKeyValueStore(),
+ )..foreground = false;
+ addTearDown(host.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: grid.buildAppTheme(brightness: Brightness.dark),
+ builder: (context, child) => SwarmScope(notifier: host, child: child!),
+ home: const SwarmTabsPage(),
+ ),
+ );
+ await settle(tester);
+ return host;
+ }
+
+ Finder key(String value) => find.byKey(ValueKey(value));
+
+ Future<void> openTab(WidgetTester tester) async {
+ await tester.tap(key('swarm-tab-buddy'));
+ await settle(tester);
+ }
+
+ Future<void> openMenu(WidgetTester tester) async {
+ await tester.tap(key('swarm-buddy-menu'));
+ await settle(tester);
+ }
+
+ Iterable<Map<String, dynamic>> sent(FakeSwarm fake, String type) => [
+ for (final call in fake.calls)
+ if (call.path.endsWith('/commands') &&
+ (call.body?['command'] as Map?)?['type'] == type)
+ Map<String, dynamic>.from(call.body!['command'] as Map),
+ ];
+
+ group('with the Buddy running on Desktop', () {
+ testWidgets('the tab is lit, named Buddy, and its chat opens at once, with '
+ 'no project list and no way back', (tester) async {
+ await pump(tester, backend());
+
+ expect(key('swarm-tab-mark-buddy'), findsOneWidget);
+ expect(
+ tester.getSemantics(key('swarm-tab-buddy')).label,
+ contains('running'),
+ );
+ await openTab(tester);
+
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+ expect(tester.widget<Text>(key('swarm-title')).data, 'Wren');
+ expect(key('swarm-buddy-dot'), findsOneWidget);
+ expect(key('tty-back'), findsNothing);
+ expect(key('swarm-buddy-start'), findsNothing);
+ expect(find.text('not started'), findsNothing);
+ });
+
+ testWidgets('a post goes to the one chat, saying the app knows one Buddy, '
+ 'as the desktop does', (tester) async {
+ final fake = backend();
+ await pump(tester, fake);
+ await openTab(tester);
+
+ await tester.enterText(find.byType(TextField), 'Are you there?');
+ await tester.pump();
+ await tester.tap(key('swarm-send'));
+ await settle(tester);
+
+ final post = sent(fake, 'message.send').single;
+ expect(post['conversationId'], one);
+ expect(post['oneBuddy'], isTrue);
+ });
+
+ testWidgets('a down Buddy dims the tab: offline with Start again', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(agents: [wren(downSince: '2026-11-02T01:00:00.000Z')]),
+ );
+ expect(
+ tester.getSemantics(key('swarm-tab-buddy')).label,
+ contains('offline'),
+ );
+ await openTab(tester);
+ expect(key('swarm-buddy-offline'), findsOneWidget);
+ });
+
+ test(
+ 'someone else\'s Buddy, or a thread session, is never the person\'s',
+ () {
+ final buddies = SwarmBuddies.read({
+ 'agents': [
+ wren(owner: 'person-ann'),
+ {
+ ...wren(),
+ 'id': 'agent-session',
+ 'buddySession': {'thread': 't1'},
+ },
+ ],
+ 'conversations': [oneChat(owner: 'person-ann', id: 'ann-chat')],
+ }, me);
+ expect(buddies.ownBuddies, isEmpty);
+ expect(buddies.ownChats, isEmpty);
+ expect(buddies.buddyOwners.keys, ['agent-wren', 'agent-session']);
+ expect(buddies.chatOwners, {'ann-chat': 'person-ann'});
+ },
+ );
+ });
+
+ group('with no Buddy yet', () {
+ testWidgets('the tab is not lit, and Start starts the one Buddy from the '
+ 'phone, naming no project', (tester) async {
+ final fake = backend(agents: const []);
+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {
+ ...firstLoad(
+ groups: [oneChat()],
+ machines: [
+ {
+ 'machineId': 'mac-1',
+ 'name': "Tony's Mac",
+ 'contributorId': me,
+ 'engines': ['claude'],
+ 'observation': {
+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,
+ },
+ },
+ ],
+ derived: const {'swarmBuddy': true},
+ ),
+ };
+ await pump(tester, fake);
+ expect(key('swarm-tab-mark-buddy'), findsNothing);
+ await openTab(tester);
+
+ await tester.tap(key('swarm-buddy-start-button'));
+ await settle(tester);
+
+ final start = sent(fake, 'buddy.create').single;
+ expect(start.containsKey('projectId'), isFalse);
+ expect(start['machineId'], 'mac-1');
+ });
+
+ testWidgets('a start under way, made with no project, shows Starting', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ backend(
+ agents: const [],
+ starts: [
+ {
+ 'id': 's1',
+ 'request': {
+ 'buddyOf': {'personId': me},
+ 'buddyScope': 'swarm',
+ 'machineId': 'mac-1',
+ 'engine': 'claude',
+ },
+ },
+ ],
+ ),
+ );
+ await openTab(tester);
+ expect(key('swarm-buddy-starting'), findsOneWidget);
+ });
+
+ testWidgets('with no chat read, it opens one on the server once, as the '
+ 'desktop asks for it', (tester) async {
+ final fake = backend(chats: const [], agents: const []);
+ fake.routes[commands(tab)] = (_) => {
+ 'result': {'conversationId': one},
+ };
+ await pump(tester, fake);
+ await openTab(tester);
+
+ final asked = sent(fake, 'buddy.chat');
+ expect(asked, hasLength(1));
+ expect(asked.single.containsKey('projectId'), isFalse);
+ expect(fake.paths, contains(messages(one)));
+ });
+
+ testWidgets('a refused open says why, stops loading, asks once, and Try '
+ 'again asks again', (tester) async {
+ final fake = backend(chats: const [], agents: const []);
+ var refuse = true;
+ fake.routes[commands(tab)] = (_) {
+ if (refuse) throw const SuperTabFailure('DOWN', 'Server is down.');
+ // Opened: the Swarm's next read holds it.
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
+ cursor: 'c3',
+ groups: [part(one, 30, oneChat())],
+ derived: const {'swarmBuddy': true},
+ );
+ return {
+ 'result': {'conversationId': one},
+ };
+ };
+ await pump(tester, fake);
+ await openTab(tester);
+
+ expect(find.text('Server is down.'), findsOneWidget);
+ expect(key('swarm-buddy-loading'), findsNothing);
+ expect(sent(fake, 'buddy.chat'), hasLength(1));
+
+ refuse = false;
+ await tester.tap(key('swarm-buddy-retry-open'));
+ await settle(tester);
+
+ expect(sent(fake, 'buddy.chat'), hasLength(2));
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+ });
+
+ testWidgets('a viewer with none is told so, and nothing is asked', (
+ tester,
+ ) async {
+ final fake = backend(chats: const [], agents: const [], role: 'viewer');
+ await pump(tester, fake);
+ await openTab(tester);
+ expect(find.text('You have no Buddy in this Swarm.'), findsOneWidget);
+ expect(sent(fake, 'buddy.chat'), isEmpty);
+ });
+ });
+
+ group('Old chats', () {
+ FakeSwarm withOld() {
+ final fake = backend(
+ chats: [
+ oneChat(),
+ oldChat(oldMobile),
+ // Nothing in it: no history to keep.
+ oldChat(oldWeb, projectId: web, last: 0),
+ // Someone else's: never listed.
+ {
+ ...buddyChatData(
+ 'old-ann',
+ owner: 'person-ann',
+ lastMessageSequence: 3,
+ ),
+ 'projectId': project,
+ },
+ ],
+ );
+ fake.routes[messages(oldMobile)] = (_) => {
+ 'messages': [line(oldMobile, 2, 'From before the one Buddy')],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ Future<void> openOld(WidgetTester tester) async {
+ await openMenu(tester);
+ await tester.tap(find.text('Old chats'));
+ await settle(tester);
+ await tester.tap(find.text('Mobile'));
+ await settle(tester);
+ }
+
+ testWidgets('list each project with history; one opens read only, with no '
+ 'composer, Buddy bar or menu of its Buddy', (tester) async {
+ final fake = withOld();
+ await pump(tester, fake);
+ await openTab(tester);
+ await openMenu(tester);
+ await tester.tap(find.text('Old chats'));
+ await settle(tester);
+ expect(find.text('Mobile'), findsOneWidget);
+ expect(find.text('Web'), findsNothing);
+ await tester.tap(find.text('Mobile'));
+ await settle(tester);
+
+ expect(find.text('From before the one Buddy'), findsOneWidget);
+ expect(tester.widget<Text>(key('swarm-title')).data, 'Old chat');
+ expect(key('swarm-old-chat'), findsOneWidget);
+ expect(find.byType(TextField), findsNothing);
+ expect(key('swarm-buddy-bar'), findsNothing);
+ expect(key('swarm-buddy-menu'), findsNothing);
+ expect(key('tty-back'), findsOneWidget);
+ });
+
+ testWidgets('sending there is blocked: nothing reaches the server', (
+ tester,
+ ) async {
+ final fake = withOld();
+ final host = await pump(tester, fake);
+ await openTab(tester);
+ await openOld(tester);
+
+ expect(find.byType(TextField), findsNothing);
+ expect(key('swarm-send'), findsNothing);
+ // A tap on the line offers no reply or reaction.
+ await tester.tap(find.text('From before the one Buddy'));
+ await settle(tester);
+ expect(key('swarm-reply-$oldMobile-2'), findsNothing);
+ expect(sent(fake, 'message.send'), isEmpty);
+ expect(sent(fake, 'message.react'), isEmpty);
+ expect(
+ swarmIsOldBuddyChat(host.session!.inbox.reader(tab)!, oldMobile),
+ isTrue,
+ );
+ });
+
+ testWidgets('Open Buddy leads back to the one chat', (tester) async {
+ await pump(tester, withOld());
+ await openTab(tester);
+ await openOld(tester);
+ await tester.tap(key('swarm-old-chat-open-buddy'));
+ await settle(tester);
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+ expect(key('swarm-old-chat'), findsNothing);
+ // The tab itself, not a second page of its chat over it.
+ expect(key('swarm-tab-buddy'), findsOneWidget);
+ expect(key('tty-back'), findsNothing);
+ });
+
+ testWidgets('an old chat\'s ⋮ is titled Old chat, not its stored title', (
+ tester,
+ ) async {
+ await pump(tester, withOld());
+ await openTab(tester);
+ await openOld(tester);
+ await tester.tap(key('swarm-chat-menu'));
+ await settle(tester);
+ expect(find.text("$me's Buddy"), findsNothing);
+ });
+
+ testWidgets('a project the person no longer reads drops off', (
+ tester,
+ ) async {
+ final fake = backend(
+ chats: [
+ oneChat(),
+ oldChat(oldWeb, projectId: 'project-gone'),
+ ],
+ );
+ await pump(tester, fake);
+ await openTab(tester);
+ await openMenu(tester);
+ expect(find.text('Old chats'), findsNothing);
+ });
+
+ testWidgets('the sheet closes when access goes while it is open', (
+ tester,
+ ) async {
+ final host = await pump(tester, withOld());
+ await openTab(tester);
+ await openMenu(tester);
+ await tester.tap(find.text('Old chats'));
+ await settle(tester);
+ expect(find.text('Mobile'), findsOneWidget);
+ expect(find.text('Old chats'), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await settle(tester);
+
+ expect(find.text('Mobile'), findsNothing);
+ expect(find.text('Old chats'), findsNothing, reason: 'the sheet is gone');
+ });
+
+ testWidgets('where the server gives no one Buddy, a Buddy chat stays as '
+ 'it was', (tester) async {
+ final host = await pump(
+ tester,
+ backend(chats: [oldChat(oldMobile)], flag: false),
+ );
+ await openTab(tester);
+ final reader = host.session!.inbox.reader(tab)!;
+ expect(swarmIsOldBuddyChat(reader, oldMobile), isFalse);
+ expect(swarmOldBuddyChats(reader), isEmpty);
+ expect(key('swarm-buddy-note'), findsOneWidget);
+ });
+
+ testWidgets('New message offers no old chat to write in', (tester) async {
+ final host = await pump(tester, withOld());
+ final chats = swarmNewMessageChats(
+ host.session!.inbox,
+ host.session!.inbox.swarms,
+ ).chats;
+ expect(chats.where((c) => c.chatId == oldMobile), isEmpty);
+ });
+ });
+
+ group('with several Swarms', () {
+ FakeSwarm two({int? mineMoved, int? otherMoved}) {
+ final fake = FakeSwarm();
+ listed(fake, [tab, other]);
+ route(fake, chats: [oneChat()], agents: [wren()]);
+ route(
+ fake,
+ swarm: other,
+ chats: [oneChat(id: 'buddy-two')],
+ );
+
+ /// When each chat last moved is its part's own time, as the server says.
+ void moved(String swarm, String chat, int? at) {
+ final load = fake.routes['/api/super-tabs/$swarm/parts']!;
+ fake.routes['/api/super-tabs/$swarm/parts'] = (body) async {
+ final first = Map<String, dynamic>.of(
+ await load(body) as Map<String, dynamic>,
+ );
+ first['groups'] = [
+ for (final row in first['groups'] as List)
+ {
+ ...row as Map<String, dynamic>,
+ if (row['key'] == chat) 'changedAt': ?at,
+ },
+ ];
+ return first;
+ };
+ }
+
+ moved(tab, one, mineMoved);
+ moved(other, 'buddy-two', otherMoved);
+ fake.routes[messages(one)] = (_) => {
+ 'messages': [line(one, 1, 'In the first Swarm')],
+ 'next': null,
+ };
+ fake.routes[messages('buddy-two', swarm: other)] = (_) => {
+ 'messages': [line('buddy-two', 1, 'In the second Swarm')],
+ 'next': null,
+ };
+ return fake;
+ }
+
+ testWidgets('opens the one whose Buddy chat moved last, and switches from '
+ 'the ⋮, kept for next time', (tester) async {
+ final host = await pump(tester, two(mineMoved: 10, otherMoved: 20));
+ await openTab(tester);
+ expect(find.text('In the second Swarm'), findsOneWidget);
+ expect(key('swarm-tab-mark-buddy'), findsNothing);
+
+ await openMenu(tester);
+ await tester.tap(find.text('Swarm'));
+ await settle(tester);
+ await tester.tap(find.text('Swarm $tab'));
+ await settle(tester);
+
+ expect(find.text('In the first Swarm'), findsOneWidget);
+ expect(find.text('In the second Swarm'), findsNothing);
+ expect(key('swarm-tab-mark-buddy'), findsOneWidget);
+ expect(host.session!.home.buddySwarmId, tab);
+ });
+
+ testWidgets('a chat moving elsewhere does not take the tab there', (
+ tester,
+ ) async {
+ final fake = two(mineMoved: 20, otherMoved: 10);
+ final host = await pump(tester, fake);
+ await openTab(tester);
+ expect(find.text('In the first Swarm'), findsOneWidget);
+
+ fake.routes['/api/super-tabs/$other/changes'] = (_) => changes(
+ cursor: 'c3',
+ groups: [part('buddy-two', 30, oneChat(id: 'buddy-two'))],
+ derived: const {'swarmBuddy': true},
+ );
+ await host.session!.inbox.reader(other)!.refresh();
+ await settle(tester);
+
+ expect(find.text('In the first Swarm'), findsOneWidget);
+ });
+
+ testWidgets('the Swarm sheet says which Swarm is shown', (tester) async {
+ await pump(tester, two(mineMoved: 20, otherMoved: 10));
+ await openTab(tester);
+ await openMenu(tester);
+ await tester.tap(find.text('Swarm'));
+ await settle(tester);
+ expect(find.text('current'), findsOneWidget);
+ });
+
+ testWidgets('with no choice kept, it waits for every Swarm before picking: '
+ 'nothing opens in the first listed', (tester) async {
+ final fake = FakeSwarm();
+ listed(fake, [tab, other]);
+ route(fake);
+ route(
+ fake,
+ swarm: other,
+ chats: [oneChat(id: 'buddy-two')],
+ );
+ fake.routes[messages('buddy-two', swarm: other)] = (_) => {
+ 'messages': [line('buddy-two', 1, 'In the second Swarm')],
+ 'next': null,
+ };
+ final load = fake.routes['/api/super-tabs/$other/parts']!;
+ final slow = Completer<void>();
+ fake.routes['/api/super-tabs/$other/parts'] = (body) async {
+ await slow.future;
+ return load(body);
+ };
+ await pump(tester, fake);
+ await openTab(tester);
+ expect(sent(fake, 'buddy.chat'), isEmpty);
+ expect(key('swarm-buddy-loading'), findsOneWidget);
+
+ slow.complete();
+ await settle(tester);
+
+ expect(sent(fake, 'buddy.chat'), isEmpty);
+ expect(find.text('In the second Swarm'), findsOneWidget);
+ });
+
+ testWidgets('with one Swarm there is no Swarm row', (tester) async {
+ await pump(tester, backend());
+ await openTab(tester);
+ await openMenu(tester);
+ expect(find.text('Swarm'), findsNothing);
+ });
+
+ testWidgets('losing the Swarm shown moves to the other, and nothing of it '
+ 'stays', (tester) async {
+ final host = await pump(tester, two(mineMoved: 20, otherMoved: 10));
+ await openTab(tester);
+ expect(find.text('In the first Swarm'), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await settle(tester);
+
+ expect(find.text('In the first Swarm'), findsNothing);
+ expect(find.text('In the second Swarm'), findsOneWidget);
+ expect(key('swarm-tab-mark-buddy'), findsNothing);
+ });
+
+ testWidgets('an open that answers after the person switched away changes '
+ 'nothing', (tester) async {
+ final fake = FakeSwarm();
+ listed(fake, [tab, other]);
+ route(fake);
+ route(
+ fake,
+ swarm: other,
+ chats: [oneChat(id: 'buddy-two')],
+ );
+ fake.routes[messages('buddy-two', swarm: other)] = (_) => {
+ 'messages': [line('buddy-two', 1, 'In the second Swarm')],
+ 'next': null,
+ };
+ final answer = Completer<Object?>();
+ fake.routes[commands(tab)] = (_) => answer.future;
+ final host = await pump(tester, fake);
+ host.session!.home.showBuddy(tab);
+ await settle(tester);
+ await openTab(tester);
+ expect(sent(fake, 'buddy.chat'), hasLength(1));
+
+ host.session!.home.showBuddy(other);
+ await settle(tester);
+ expect(find.text('In the second Swarm'), findsOneWidget);
+
+ answer.complete({
+ 'result': {'conversationId': one},
+ });
+ await settle(tester);
+
+ expect(find.text('In the second Swarm'), findsOneWidget);
+ expect(fake.paths, isNot(contains(messages(one))));
+ });
+ });
+
+ group('stale answers', () {
+ testWidgets('an open answering once another Swarm asked for its own opens '
+ 'nothing there, and that Swarm is asked once', (tester) async {
+ final fake = FakeSwarm();
+ listed(fake, [tab, other]);
+ route(fake);
+ route(fake, swarm: other);
+ final first = Completer<Object?>(), second = Completer<Object?>();
+ fake.routes[commands(tab)] = (_) => first.future;
+ fake.routes[commands(other)] = (_) => second.future;
+ int asked(String swarm) => [
+ for (final call in fake.calls)
+ if (call.path == commands(swarm) &&
+ (call.body?['command'] as Map?)?['type'] == 'buddy.chat')
+ call,
+ ].length;
+ final host = await pump(tester, fake);
+ host.session!.home.showBuddy(tab);
+ await openTab(tester);
+ expect(asked(tab), 1);
+
+ host.session!.home.showBuddy(other);
+ await settle(tester);
+ expect(asked(other), 1);
+
+ first.complete({
+ 'result': {'conversationId': one},
+ });
+ await settle(tester);
+
+ expect(fake.paths, isNot(contains(messages(one))));
+ expect(asked(other), 1);
+ expect(key('swarm-buddy-loading'), findsOneWidget);
+ second.complete({'result': <String, dynamic>{}});
+ await settle(tester);
+ });
+ });
+
+ group('an opened chat stays with its Swarm', () {
+ testWidgets('another Swarm with none never opens it', (tester) async {
+ final fake = FakeSwarm();
+ listed(fake, [tab, other]);
+ route(fake);
+ route(fake, swarm: other);
+ fake.routes[commands(tab)] = (_) => {
+ 'result': {'conversationId': one},
+ };
+ fake.routes[messages(one)] = (_) => {
+ 'messages': [line(one, 1, 'In the first Swarm')],
+ 'next': null,
+ };
+ final hold = Completer<Object?>();
+ fake.routes[commands(other)] = (_) => hold.future;
+ final host = await pump(tester, fake);
+ host.session!.home.showBuddy(tab);
+ await openTab(tester);
+ expect(fake.paths, contains(messages(one)));
+
+ host.session!.home.showBuddy(other);
+ await settle(tester);
+
+ expect(fake.paths, isNot(contains(messages(one, swarm: other))));
+ hold.complete({'result': <String, dynamic>{}});
+ await settle(tester);
+ });
+ });
+
+ group('when access goes', () {
+ testWidgets('while the chat is open: it closes, the dot goes, nothing of '
+ 'it stays', (tester) async {
+ final host = await pump(tester, backend());
+ await openTab(tester);
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await settle(tester);
+
+ expect(find.text('Hello from the one Buddy'), findsNothing);
+ expect(find.text('Wren'), findsNothing);
+ expect(key('swarm-tab-mark-buddy'), findsNothing);
+ expect(key('swarm-tab-badge-buddy'), findsNothing);
+ });
+
+ testWidgets('while an open is out: its answer is dropped', (tester) async {
+ final fake = backend(chats: const [], agents: const []);
+ final answer = Completer<Object?>();
+ fake.routes[commands(tab)] = (_) => answer.future;
+ final host = await pump(tester, fake);
+ await openTab(tester);
+ expect(sent(fake, 'buddy.chat'), hasLength(1));
+
+ host.session!.inbox.reader(tab)!.revoke();
+ await settle(tester);
+ answer.complete({
+ 'result': {'conversationId': one},
+ });
+ await settle(tester);
+
+ expect(fake.paths, isNot(contains(messages(one))));
+ expect(find.text('Hello from the one Buddy'), findsNothing);
+ });
+
+ testWidgets('on signing out: the chat goes', (tester) async {
+ await pump(tester, backend());
+ await openTab(tester);
+ account.value = null;
+ await settle(tester);
+ expect(find.text('Hello from the one Buddy'), findsNothing);
+ });
+
+ testWidgets('a menu open as the person becomes a viewer loses its write '
+ 'rows', (tester) async {
+ final fake = backend();
+ final host = await pump(tester, fake);
+ await openTab(tester);
+ await openMenu(tester);
+ expect(find.text('Rename Buddy'), findsOneWidget);
+
+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => {
+ ...changes(cursor: 'c3', derived: const {'swarmBuddy': true}),
+ 'members': [part(me, 9, person(me, role: 'viewer'))],
+ };
+ await host.session!.inbox.reader(tab)!.refresh();
+ await settle(tester);
+
+ expect(find.text('Rename Buddy'), findsNothing);
+ });
+ });
+
+ group('a failed first read', () {
+ testWidgets('says so, with no stuck Loading, and once it recovers the tab '
+ 'is lit and its chat opens', (tester) async {
+ final fake = backend();
+ final good = fake.routes['/api/super-tabs/$tab/parts']!;
+ var down = true;
+ fake.routes['/api/super-tabs/$tab/parts'] = (body) => down
+ ? throw const SuperTabFailure('DOWN', 'Down.', statusCode: 503)
+ : good(body);
+ final host = await pump(tester, fake);
+ await openTab(tester);
+ expect(key('swarm-tab-mark-buddy'), findsNothing);
+ expect(key('swarm-buddy-retry-read'), findsOneWidget);
+ expect(key('swarm-buddy-loading'), findsNothing);
+
+ down = false;
+ await tester.tap(key('swarm-buddy-retry-read'));
+ await settle(tester);
+
+ expect(key('swarm-tab-mark-buddy'), findsOneWidget);
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+ expect(host.session!.inbox.reader(tab)!.error, isNull);
+ });
+
+ testWidgets('of the Swarm list says so with Try again', (tester) async {
+ final fake = FakeSwarm();
+ var down = true;
+ fake.routes['/api/super-tabs/list'] = (_) => down
+ ? throw const SuperTabFailure('DOWN', 'Down.', statusCode: 503)
+ : {
+ 'tabs': [
+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},
+ ],
+ 'next': null,
+ };
+ route(fake, chats: [oneChat()], agents: [wren()]);
+ fake.routes[messages(one)] = (_) => {
+ 'messages': [line(one, 1, 'Hello from the one Buddy')],
+ 'next': null,
+ };
+ await pump(tester, fake);
+ await openTab(tester);
+ expect(key('swarm-buddy-retry-list'), findsOneWidget);
+
+ down = false;
+ await tester.tap(key('swarm-buddy-retry-list'));
+ await settle(tester);
+ expect(find.text('Hello from the one Buddy'), findsOneWidget);
+ });
+ });
+
+ group('kept on the phone', () {
+ test('the view Home keeps holds the one chat, the Buddy and the server\'s '
+ 'word, and no thread session as the Buddy', () {
+ final state = <String, dynamic>{
+ ...headData(),
+ 'swarmBuddy': true,
+ 'people': [person(me)],
+ 'agents': [
+ // First, as a read may list it: kept, it would stand as the Buddy.
+ {
+ ...wren(),
+ 'id': 'agent-session',
+ 'buddySession': {'thread': 't1'},
+ },
+ wren(),
+ ],
+ 'conversations': [oneChat()],
+ };
+ final snapshot = SuperTabSnapshot.fromJson(state);
+ final kept = swarmHomeSwarm(
+ snapshot,
+ const {},
+ buddies: SwarmBuddies.read(state, me),
+ );
+ final back = SuperTabSnapshot.fromJson(kept.state);
+ final buddies = SwarmBuddies.read(kept.state, me);
+ expect(back.swarmBuddy, isTrue);
+ expect(back.conversation(one)!.isSwarmBuddyChat, isTrue);
+ expect(buddies.ownChats[swarmBuddyKey], one);
+ expect(buddies.ownBuddies[swarmBuddyKey], 'agent-wren');
+ });
+
+ test('the Swarm last used is kept per account, read back, and goes with '
+ 'the Swarm', () async {
+ final store = MemoryKeyValueStore();
+ final first = SwarmHomePrefs(accountId: me, store: store);
+ await pumpEventQueue();
+ first.showBuddy(other);
+ await pumpEventQueue();
+
+ final back = SwarmHomePrefs(accountId: me, store: store);
+ await pumpEventQueue();
+ expect(back.buddySwarmId, other);
+
+ final someoneElse = SwarmHomePrefs(accountId: 'ann', store: store);
+ await pumpEventQueue();
+ expect(someoneElse.buddySwarmId, isNull);
+
+ back.keepOnly({tab});
+ expect(back.buddySwarmId, isNull);
+ });
+
+ test('Home choosing one Swarm counts as using it', () async {
+ final prefs = SwarmHomePrefs(accountId: me);
+ prefs.show(other);
+ expect(prefs.buddySwarmId, other);
+ prefs.show(null);
+ expect(prefs.buddySwarmId, other);
+ });
+
+ test(
+ 'the Buddy tab\'s Swarm and Home\'s Sort and Filter are kept together, '
+ 'each chosen before the choices are back standing over what is read',
+ () async {
+ final store = MemoryKeyValueStore();
+ final first = SwarmHomePrefs(accountId: 'me', store: store);
+ await pumpEventQueue();
+ first
+ ..showBuddy('s1')
+ ..setFilter(SwarmHomeFilter.mentions)
+ ..setSort(SwarmHomeSort.newest)
+ ..setUnreadsFirst(true);
+ await pumpEventQueue();
+ first.dispose();
+
+ final back = SwarmHomePrefs(accountId: 'me', store: store);
+ await pumpEventQueue();
+ expect(back.buddySwarmId, 's1');
+ expect(back.filter, SwarmHomeFilter.mentions);
+ expect(back.sort, SwarmHomeSort.newest);
+ expect(back.unreadsFirst, isTrue);
+ back.dispose();
+
+ final early = SwarmHomePrefs(accountId: 'me', store: store)
+ ..showBuddy('s2');
+ await pumpEventQueue();
+ expect(early.buddySwarmId, 's2');
+ expect(early.filter, SwarmHomeFilter.mentions);
+ early.dispose();
+
+ final kept = SwarmHomePrefs(accountId: 'me', store: store);
+ await pumpEventQueue();
+ expect(
+ kept.buddySwarmId,
+ 's2',
+ reason: 'written though nothing else moved',
+ );
+ kept.dispose();
+ },
+ );
+ });
+}
diff --git a/mobile/test/swarm/swarm_chat_menu_test.dart b/mobile/test/swarm/swarm_chat_menu_test.dart
index f8a84d242..ec74bb0fe 100644
--- a/mobile/test/swarm/swarm_chat_menu_test.dart
+++ b/mobile/test/swarm/swarm_chat_menu_test.dart
@@ -6,9 +6,6 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/notify/system_notices.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
-import 'package:harness_mobile/swarm/model.dart';
-import 'package:harness_mobile/swarm/swarm_buddies_page.dart';
-import 'package:harness_mobile/swarm/swarm_buddy_list.dart';
import 'package:harness_mobile/swarm/swarm_chat_notify.dart';
import 'package:harness_mobile/swarm/swarm_conversation_page.dart';
import 'package:harness_mobile/swarm/swarm_project_page.dart';
@@ -290,37 +287,4 @@ void main() {
expect(key('swarm-chat-menu'), findsNothing);
});
});
-
- testWidgets('a muted Buddy chat on Buddies: greyed with a crossed bell, '
- 'no dot', (tester) async {
- final row = SwarmBuddyRow(
- swarmId: tab,
- project: SuperTabProject.fromJson({
- 'id': project,
- 'name': 'Mobile',
- 'ownerId': me,
- 'leadConversationId': leadChat,
- 'visibility': 'public',
- 'members': <Object>[],
- }),
- name: 'Wren',
- muted: true,
- );
- await tester.pumpWidget(
- MaterialApp(
- theme: grid.buildAppTheme(brightness: Brightness.dark),
- home: Scaffold(
- body: SwarmBuddiesRow(
- row: row,
- line: 'Done',
- now: DateTime.utc(2026, 11, 1),
- onTap: () {},
- ),
- ),
- ),
- );
-
- expect(key('swarm-buddies-muted-${row.key}'), findsOneWidget);
- expect(key('swarm-buddies-unread-${row.key}'), findsNothing);
- });
}
diff --git a/mobile/test/swarm/swarm_home_list_test.dart b/mobile/test/swarm/swarm_home_list_test.dart
index af777319e..624cbfcfa 100644
--- a/mobile/test/swarm/swarm_home_list_test.dart
+++ b/mobile/test/swarm/swarm_home_list_test.dart
@@ -368,6 +368,8 @@ void main() {
expect(jsonDecode(store.values[key]!), {
'pins': [swarmHomeProjectKey(tab, 'p1')],
'swarm': tab,
+ // Home showing one Swarm counts as using it, for the Buddy tab.
+ 'buddySwarm': tab,
});
});
diff --git a/mobile/test/swarm/swarm_tabs_test.dart b/mobile/test/swarm/swarm_tabs_test.dart
index 8f49ce8db..b567ef610 100644
--- a/mobile/test/swarm/swarm_tabs_test.dart
+++ b/mobile/test/swarm/swarm_tabs_test.dart
@@ -7,14 +7,12 @@ import 'package:harness_mobile/phone/out_of_sight.dart';
import 'package:harness_mobile/settings/experimental_features.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/swarm/swarm_activity_page.dart';
-import 'package:harness_mobile/swarm/swarm_buddies_page.dart';
import 'package:harness_mobile/swarm/swarm_page.dart';
import 'package:harness_mobile/swarm/swarm_session.dart';
import 'package:harness_mobile/swarm/swarm_tabs.dart';
import 'package:harness_mobile/swarm/swarm_you_page.dart';
import '../voice_fakes.dart';
-import 'swarm_buddies_fixture.dart';
import 'swarm_fixture.dart';
/// A tab's screen that says which it is, whether it is out of sight, and how
@@ -63,7 +61,7 @@ class _ProbeState extends State<_Probe> {
const _names = {
SwarmTab.home: 'Home',
- SwarmTab.buddies: 'Buddies',
+ SwarmTab.buddy: 'Buddy',
SwarmTab.activity: 'Activity',
SwarmTab.you: 'You',
};
@@ -186,7 +184,7 @@ void main() {
Finder said(String text) => find.text(text, skipOffstage: false);
- testWidgets('the bar reads Home, Buddies, Activity and You, and opens on '
+ testWidgets('the bar reads Home, Buddy, Activity and You, and opens on '
'Swarm Home', (tester) async {
await pump(tester, _tabs);
@@ -254,13 +252,13 @@ void main() {
await pump(tester, SwarmTabsPage(tabs: _probes(made)));
expect(made, [SwarmTab.home]);
- await open(tester, SwarmTab.buddies);
+ await open(tester, SwarmTab.buddy);
await open(tester, SwarmTab.activity);
- await open(tester, SwarmTab.buddies);
+ await open(tester, SwarmTab.buddy);
await open(tester, SwarmTab.home);
await open(tester, SwarmTab.home);
- expect(made, [SwarmTab.home, SwarmTab.buddies, SwarmTab.activity]);
+ expect(made, [SwarmTab.home, SwarmTab.buddy, SwarmTab.activity]);
});
testWidgets('a count shows on its tab while there is one, and follows the '
@@ -324,7 +322,7 @@ void main() {
testWidgets('$count tabs share the bar alike, each a thumb\'s width or '
'more, and each opens its own screen', (tester) async {
final tabs = _probes([]);
- if (count == 3) tabs.removeWhere((e) => e.tab == SwarmTab.buddies);
+ if (count == 3) tabs.removeWhere((e) => e.tab == SwarmTab.buddy);
await pump(tester, SwarmTabsPage(tabs: tabs));
final rects = [for (final e in tabs) tester.getRect(tabOf(e.tab))];
@@ -478,62 +476,6 @@ void main() {
expect(find.text('Ship it?'), findsOneWidget);
});
- testWidgets('Buddies opens Buddies, as a tab with no way back, and counts '
- 'the Buddy chats with something unread', (tester) async {
- await pump(tester, _tabs, fake: buddiesBackend());
- final badge = find.byKey(const ValueKey('swarm-tab-badge-buddies'));
- expect(
- find.descendant(of: badge, matching: find.text('1')),
- findsOneWidget,
- );
-
- await open(tester, SwarmTab.buddies);
-
- expect(find.byType(SwarmBuddiesView), findsOneWidget);
- expect(
- tester.widget<Text>(find.byKey(const ValueKey('swarm-title'))).data,
- 'Buddies',
- );
- expect(find.byKey(const ValueKey('tty-back')), findsNothing);
- expect(find.text('Done: the build is up.'), findsOneWidget);
- });
-
- testWidgets('Buddies reads its chats only while its tab is open', (
- tester,
- ) async {
- final fake = buddiesBackend();
- int reads() => fake.paths.where((p) => p.contains('/messages')).length;
- await pump(tester, _tabs, fake: fake);
- expect(reads(), 0, reason: 'its count needs no chat read');
-
- await open(tester, SwarmTab.buddies);
- expect(reads(), 2);
-
- await open(tester, SwarmTab.home);
- expect(host.session!.buddyList.shown, isFalse);
- // A new message in the Buddy chat while Buddies is out of sight.
- fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(
- cursor: 'c3',
- groups: [
- part(
- buddiesMobileChat,
- 30,
- buddyChatData(
- buddiesMobileChat,
- agentIds: ['agent-wren'],
- lastMessageSequence: 9,
- ),
- ),
- ],
- );
- await host.session!.inbox.refresh();
- await tester.pumpAndSettle();
- expect(reads(), 2, reason: 'out of sight, nothing is read');
-
- await open(tester, SwarmTab.buddies);
- expect(reads(), 3);
- });
-
testWidgets('You opens the person\'s own page, and its Settings the '
'phone\'s, over the tabs', (tester) async {
await pump(tester, _tabs);