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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-03 aw: #2660 #2603 #2604 #2626 #2651 (#2662)
0xken15f18e239287ef
diff --git a/backend/integration/superTabInbox.test.ts b/backend/integration/superTabInbox.test.tsindex 6ac25260a..c51a453b1 100644--- a/backend/integration/superTabInbox.test.ts+++ b/backend/integration/superTabInbox.test.ts@@ -468,6 +468,86 @@ describe('reading a chat never reads a reply only in a thread (Diego, 11-01)', (expect(after.read.map((t: any) => t.root.text)).toEqual(['Peer root'])})+ it('keeps a thread-only reply after SEED_SCAN hidden notices unread once the chat is read', async () => {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Peer question', author: personAuthor(peer) }])+ const old = await sequenceOf(root!)+ await markRead(s.tabId, s.web, old, peer)+ await insert(s.tabId, s.web, [+ ...Array.from({ length: SEED_SCAN }, (_, i) => ({ text: `Hidden notice ${i}`, author: agentAuthor(s.worker),+ source: { kind: 'note', recipientsOnly: true }, recipientIds: [s.worker] })),+ { text: 'Answer', author: agentAuthor(s.worker), thread: root },+ { text: 'Main', author: personAuthor(owner) },+ ])+ const top = await newest(s.tabId, s.web)+ await markRead(s.tabId, s.web, top, peer)+ expect(await marksOf(s.tabId, peer)).toEqual({ [root!]: { sequence: old, follow: null } })+ expect(unreadRoots((await inbox(s.tabId, peer)).body.data)).toEqual(['Peer question: 1'])+ expect((await threadsRead(s.tabId, peer)).body.data.unread.map((t: any) => t.root.text)).toEqual(['Peer question'])+ })++ it('holds a capped chat read at the last scanned reply and seeds the later thread on the next read', async () => {+ const s = await scene()+ const [early, late] = await insert(s.tabId, s.web, [{ text: 'Early', author: personAuthor(peer) }, { text: 'Late', author: personAuthor(peer) }])+ const old = await sequenceOf(late!)+ await markRead(s.tabId, s.web, old, peer)+ const replies = await insert(s.tabId, s.web, Array.from({ length: SEED_SCAN }, (_, i) => ({ text: `Own reply ${i}`, author: personAuthor(peer), thread: early })))+ const boundary = await sequenceOf(replies.at(-1)!)+ await insert(s.tabId, s.web, [{ text: 'Late answer', author: agentAuthor(s.worker), thread: late }, { text: 'Main', author: personAuthor(owner) }])+ const top = await newest(s.tabId, s.web)+ const first = await post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, peer, { sequence: top })+ expect(first.status).toBe(200)+ expect(first.body.data.sequence).toBe(boundary)+ expect((await db.superTabReadMark.findUniqueOrThrow({ where: { id: stableId(s.tabId, s.web, peer.sub) } })).sequence).toBe(boundary)+ expect(unreadRoots((await inbox(s.tabId, peer)).body.data)).toEqual(['Late: 1'])+ await markRead(s.tabId, s.web, top, peer)+ expect(await marksOf(s.tabId, peer)).toEqual({ [late!]: { sequence: boundary, follow: null } })+ expect(unreadRoots((await inbox(s.tabId, peer)).body.data)).toEqual(['Late: 1'])+ })++ it('holds the mark before an unhandled thread when more than 50 threads have answers', async () => {+ const s = await scene()+ const roots = await insert(s.tabId, s.web, Array.from({ length: 51 }, (_, i) => ({ text: `Question ${i}`, author: personAuthor(peer) })))+ const old = await sequenceOf(roots.at(-1)!)+ await markRead(s.tabId, s.web, old, peer)+ const replies = await insert(s.tabId, s.web, roots.map(thread => ({ text: 'Answer', author: agentAuthor(s.worker), thread })))+ await insert(s.tabId, s.web, [{ text: 'Main', author: personAuthor(owner) }])+ const top = await newest(s.tabId, s.web)+ const first = await post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, peer, { sequence: top })+ expect(first.body.data.sequence).toBe(await sequenceOf(replies[49]!))+ expect(Object.keys(await marksOf(s.tabId, peer))).toEqual(expect.arrayContaining(roots.slice(0, 50)))+ expect((await marksOf(s.tabId, peer))[roots[50]!]).toBeUndefined()+ await markRead(s.tabId, s.web, top, peer)+ expect(Object.keys(await marksOf(s.tabId, peer))).toHaveLength(51)+ expect((await marksOf(s.tabId, peer))[roots[0]!]).toEqual({ sequence: old, follow: null })+ })++ it('advances through a row ceiling containing no replies and leaves another chat unchanged', async () => {+ const s = await scene()+ const [root] = await insert(s.tabId, s.web, [{ text: 'Question', author: personAuthor(peer) }])+ await markRead(s.tabId, s.web, await sequenceOf(root!), peer)+ const main = await insert(s.tabId, s.web, Array.from({ length: 5_001 }, (_, i) => ({ text: `Main ${i}`, author: personAuthor(owner) })))+ const top = await newest(s.tabId, s.web)+ const first = await post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, peer, { sequence: top })+ expect(first.body.data.sequence).toBe(await sequenceOf(main[4_999]!))+ await markRead(s.tabId, s.web, top, peer)+ expect((await db.superTabReadMark.findUniqueOrThrow({ where: { id: stableId(s.tabId, s.web, peer.sub) } })).sequence).toBe(top)+ expect(await db.superTabReadMark.count({ where: { tabId: s.tabId, personId: peer.sub, conversationId: { not: s.web } } })).toBe(0)+ })++ it('does not spend the thread-mark budget on threads the person is not in', async () => {+ const s = await scene()+ const roots = await insert(s.tabId, s.web, Array.from({ length: 51 }, (_, i) => ({ text: `Question ${i}`, author: personAuthor(i === 0 ? peer : owner) })))+ const old = await sequenceOf(roots.at(-1)!)+ await markRead(s.tabId, s.web, old, peer)+ await insert(s.tabId, s.web, roots.map(thread => ({ text: 'Answer', author: agentAuthor(s.worker), thread })))+ await insert(s.tabId, s.web, [{ text: 'Main', author: personAuthor(owner) }])+ const top = await newest(s.tabId, s.web)+ const response = await post(`/api/super-tabs/${s.tabId}/conversations/${s.web}/read`, peer, { sequence: top })+ expect(response.body.data.sequence).toBe(top)+ expect(await marksOf(s.tabId, peer)).toEqual({ [roots[0]!]: { sequence: old, follow: null } })+ })+it('does so for each thread the person started, replied in, was tagged in or follows, and for no other', async () => {const s = await scene()const [started, replied, taggedRoot, taggedReply, followed, notTheirs] = await insert(s.tabId, s.web, [@@ -567,12 +647,12 @@ describe('reading a chat never reads a reply only in a thread (Diego, 11-01)', (expect(unreadRoots((await inbox(s.tabId, peer)).body.data)).toEqual(['Peer root: 1'])})- it(`reads one bounded range from the old mark upward (${SEED_SCAN} rows), whatever the range's length`, async () => {+ it(`reads one bounded row range even when main rows vastly outnumber replies, whatever the range's length`, async () => {const s = await scene()const [early, late] = await insert(s.tabId, s.web, [{ text: 'Early', author: personAuthor(peer) }, { text: 'Late', author: personAuthor(peer) }])await markRead(s.tabId, s.web, await sequenceOf(late!), peer)await insert(s.tabId, s.web, [{ text: 'Early reply', author: agentAuthor(s.worker), thread: early },- ...Array.from({ length: SEED_SCAN + 100 }, (_, i) => ({ text: `Main ${i}`, author: personAuthor(owner) })),+ ...Array.from({ length: 5_100 }, (_, i) => ({ text: `Main ${i}`, author: personAuthor(owner) })),{ text: 'Late reply', author: agentAuthor(s.worker), thread: late }])const top = await newest(s.tabId, s.web)await db.$runCommandRaw({ profile: 0 })@@ -589,8 +669,10 @@ describe('reading a chat never reads a reply only in a thread (Diego, 11-01)', (rows.filter(r => r.op !== 'getmore').map(r => ` ${r.ns.split('.').at(-1)} ${r.op} ${r.planSummary ?? ''} docs=${r.docsExamined ?? 0} keys=${r.keysExamined ?? 0}`).join('\n'))// The range read, the thread's root and the look-back for whether the person is in it: never one read per row or thread.expect(messages.length).toBeLessThanOrEqual(3)- expect(examined).toBeLessThanOrEqual(SEED_SCAN + 10)- // The cap: a thread-only reply past the first SEED_SCAN rows of the range is not seen by this read.+ expect(examined).toBeLessThanOrEqual(5_010)+ const stored = await db.superTabReadMark.findUniqueOrThrow({ where: { id: stableId(s.tabId, s.web, peer.sub) } })+ expect(stored.sequence).toBeLessThan(top)+ // The row ceiling holds the mark before the late reply; a later read can seed it.expect(await marksOf(s.tabId, peer)).toEqual({ [early!]: { sequence: await sequenceOf(late!), follow: null } })}, 60_000)})diff --git a/backend/src/superTabs/read/service.ts b/backend/src/superTabs/read/service.tsindex e42cd5ceb..f6ebcd641 100644--- a/backend/src/superTabs/read/service.ts+++ b/backend/src/superTabs/read/service.ts@@ -231,8 +231,8 @@ export class SwarmReads {const { group, state } = await this.readGroup(user, tabId, conversationId)const next = Math.min(sequence, group.data!.lastMessageSequence), now = this.now()const held = await this.db.superTabReadMark.findUnique({ where: { id: stableId(tabId, conversationId, user.sub) }, select: { sequence: true } })- await seedThreadMarks(this.db, { tabId, state, personId: user.sub, conversationId, old: held?.sequence ?? 0, next, now })- const stored = await writeReadMark(this.db, { tabId, personId: user.sub, conversationId, sequence: next, now })+ const safe = await seedThreadMarks(this.db, { tabId, state, personId: user.sub, conversationId, old: held?.sequence ?? 0, next, now })+ const stored = await writeReadMark(this.db, { tabId, personId: user.sub, conversationId, sequence: safe, now })// The replies also in the chat that the mark passes are read in Activity too (activity.ts).await markActivityChatRead(this.db, { tabId, personId: user.sub, conversationId, sequence: stored, now })return { sequence: stored }diff --git a/backend/src/superTabs/read/threadMarkSeeds.ts b/backend/src/superTabs/read/threadMarkSeeds.tsindex 8a1121719..68f4d15a4 100644--- a/backend/src/superTabs/read/threadMarkSeeds.ts+++ b/backend/src/superTabs/read/threadMarkSeeds.ts@@ -10,11 +10,11 @@* of a project they no longer read in their Buddy chat. A thread whose root they cannot read gets no mark, so its id never* reaches their marks. The caller has checked they read the chat, as a person reading as themselves.*- * Cost: one read of the range's first SEED_SCAN rows from `old` upward by the (tabId, conversationId, sequence) index, answering- * only thread replies. Only when one is someone else's reply only in its thread: the delivered-copy check, the threads' mark rows- * and roots by id, the look-back for the person in at most SEED_THREADS threads (MEMBER_SCAN rows each, one read), then one- * conditional write per thread. A reply past the range's first SEED_SCAN rows, or in more than SEED_THREADS threads, is not- * marked; the server logs it.+ * Cost: read at most SEED_ROWS indexed rows and retain at most SEED_SCAN replies. Main rows do not spend the reply+ * budget, but the row ceiling bounds database work. Roots and marks are fetched for at most SEED_SCAN candidate threads;+ * at most SEED_THREADS unknown memberships use MEMBER_SCAN look-back rows each, and at most SEED_THREADS marks are written.+ * Any unhandled range or thread holds the chat mark before it. A later request can advance it; clients may defer that+ * request until another message arrives. Privacy and membership checks below still apply before a mark is written.*/import type { PrismaClient } from '@prisma/client'import { logger } from '../../utils/logger.js'@@ -23,45 +23,52 @@ import { seedThreadMark } from '../readMarks.js'import { readBy } from '../parts/indexed.js'import { BEHIND_THREADS, groupBy, isReply, MEMBER_SCAN, newestInThreads, readable, row, SCAN_FIELDS, UNREAD_SCAN, type Row } from './inbox.js'-/** Rows of the range one chat read looks at, from the old mark upward. */+/** Thread replies of the range one chat read looks at, from the old mark upward. */export const SEED_SCAN = 5 * UNREAD_SCAN-/** Threads one chat read marks at most, newest reply first: as many as the inbox reads behind their chat's mark. */+/** Threads one chat read marks, or checks historical membership of, at most. */export const SEED_THREADS = BEHIND_THREADS+/** Indexed rows examined before filtering replies: main rows do not spend the smaller reply budget. */+export const SEED_ROWS = 10 * SEED_SCANexport interface SeedInput { tabId: string; state: SuperTabState; personId: string; conversationId: string; old: number; next: number; now: number }/** A row is a thread reply: the root is another row. */const REPLY = { $and: [{ $ne: [{ $ifNull: ['$thread', null] }, null] }, { $ne: ['$thread', '$_id'] }] }-/** Marks the threads described above and answers how many it marked. */+/** Marks the threads described above and answers the safe next chat mark. */export async function seedThreadMarks(db: PrismaClient, input: SeedInput): Promise<number> {const { tabId, state, personId, conversationId, old, next } = input- if (old <= 0 || next <= old) return 0+ if (old <= 0 || next <= old) return nextconst [scan] = await db.superTabMessage.aggregateRaw({ pipeline: [- { $match: { tabId, conversationId, sequence: { $gt: old, $lte: next } } }, { $sort: { sequence: 1, _id: 1 } }, { $limit: SEED_SCAN },+ { $match: { tabId, conversationId, sequence: { $gt: old, $lte: next } } }, { $sort: { sequence: 1, _id: 1 } }, { $limit: SEED_ROWS },{ $project: { ...SCAN_FIELDS, alsoInChat: 1 } },{ $group: { _id: null, scanned: { $sum: 1 }, last: { $last: '$sequence' }, replies: { $push: { $cond: [REPLY, '$$ROOT', '$$REMOVE'] } } } },- ] }) as unknown as Array<{ scanned: number; last: number; replies: Array<Record<string, unknown>> }>- if (!scan) return 0- if (scan.scanned >= SEED_SCAN && scan.last < next) logger.warn('[swarm-read-marks] thread replies past the scan not marked', { tabId, conversationId, old, next })+ { $project: { scanned: 1, last: 1, replyCount: { $size: '$replies' }, replies: { $slice: ['$replies', SEED_SCAN] } } },+ ] }) as unknown as Array<{ scanned: number; last: number; replyCount: number; replies: Array<Record<string, unknown>> }>+ if (!scan) return next+ let safe = scan.replyCount >= SEED_SCAN ? Number(scan.replies.at(-1)!.sequence) : scan.scanned >= SEED_ROWS ? scan.last : next+ const holdBefore = (thread: string) => { safe = Math.min(safe, threads.get(thread)![0]!.sequence - 1) }+ const heldSequence = () => {+ if (safe < next) logger.warn('[swarm-read-marks] chat mark held at seed cap', { tabId, conversationId, old, next, safe })+ return safe+ }const own = (a: Pick<Author, 'kind' | 'id'>) => a.kind === 'person' && a.id === personIdconst inIt = (m: Row) => own(m.author) || m.mentions.includes(personId)const waits = (m: Row) => !m.alsoInChat && !own(m.author)const rows = scan.replies.map(raw => row({ ...raw, conversationId }))- if (!rows.some(waits)) return 0+ if (!rows.some(waits)) return heldSequence()const shown = await readable(db, tabId, rows, state)- // Newest reply first.- const byThread = [...groupBy(shown.toReversed(), m => m.thread!)].filter(([, replies]) => replies.some(waits))- if (!byThread.length) return 0- if (byThread.length > SEED_THREADS) logger.warn('[swarm-read-marks] threads past the cap not marked', { tabId, conversationId, threads: byThread.length })- const threads = new Map(byThread.slice(0, SEED_THREADS))+ // Oldest first: never advance past the first reply of an unhandled thread.+ const byThread = [...groupBy(shown, m => m.thread!)].filter(([, replies]) => replies.some(waits))+ if (!byThread.length) return heldSequence()+ const threads = new Map(byThread)// The person's rows of these threads, by id: one with a mark keeps it, an unfollowed one gets none.const held = new Map((await db.superTabThreadMark.aggregateRaw({ pipeline: [{ $match: { _id: { $in: [...threads.keys()].map(thread => stableId(tabId, conversationId, thread, personId)) } } },{ $project: { _id: 0, threadId: 1, sequence: 1, follow: 1 } },] }) as unknown as Array<{ threadId: string; sequence: number; follow?: boolean | null }>).map(r => [r.threadId, r]))const open = [...threads.keys()].filter(thread => { const mark = held.get(thread); return !mark || (Number(mark.sequence) <= 0 && mark.follow !== false) })- if (!open.length) return 0+ if (!open.length) return heldSequence()// Each root by its id, in this chat, one the person reads.const found = (await readBy(db, 'SuperTabMessage', 'id', [{ $match: { _id: { $in: open }, tabId, conversationId } }, { $project: { ...SCAN_FIELDS, conversationId: 1 } }])).map(row)const roots = new Map((await readable(db, tabId, found.filter(m => !isReply(m)), state)).map(m => [m.id, m]))@@ -71,12 +78,14 @@ export async function seedThreadMarks(db: PrismaClient, input: SeedInput): Promi// thread index range; only the rows that name them come back.const unknown = withRoot.filter(thread => !member.has(thread))if (unknown.length) {- const named = await newestInThreads(db, tabId, unknown.map(thread => ({ conversationId, thread, sequence: { $lte: old } })), MEMBER_SCAN, personId)+ if (unknown.length > SEED_THREADS) holdBefore(unknown[SEED_THREADS]!)+ const named = await newestInThreads(db, tabId, unknown.slice(0, SEED_THREADS).map(thread => ({ conversationId, thread, sequence: { $lte: old } })), MEMBER_SCAN, personId)for (const m of await readable(db, tabId, named, state)) member.add(m.thread!)}- let marked = 0- for (const thread of withRoot.filter(t => member.has(t))) {- if (await seedThreadMark(db, { tabId, personId, conversationId, threadId: thread, sequence: old, now: input.now })) marked+++ const eligible = withRoot.filter(t => member.has(t))+ if (eligible.length > SEED_THREADS) holdBefore(eligible[SEED_THREADS]!)+ for (const thread of eligible.slice(0, SEED_THREADS)) {+ await seedThreadMark(db, { tabId, personId, conversationId, threadId: thread, sequence: old, now: input.now })}- return marked+ return heldSequence()}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex b187b2653..7c1ab121a 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -2055,9 +2055,10 @@ class _SwarmScreenState extends State<SwarmScreen> {'searchTooltip': _commandTooltip('Open Harness', 'harnesses.list'),'addPhoneTooltip': _addPhoneTooltip,// Not once the account has a phone: see `state/account_phones.dart`.- 'addPhoneVisible': _accountPhones.showsAddPhone,- 'storeTooltip': _commandTooltip('Explore Harness Store', 'app.store'),- 'devicesVisible': app.devicesEnabled,+ // They moved into the avatar menu (Quiet Swarm, screen 0).+ 'addPhoneVisible': false,+ 'storeVisible': false,+ 'devicesVisible': false,// The row's last control: Sign in, or whose account this is.'account': ?_accountPayload,// Native accessibility explains that ⏎ enters the selected tab.@@ -2273,6 +2274,7 @@ class _SwarmScreenState extends State<SwarmScreen> {'swarm.select_${app.profileSwarms.indexOf(swarm) + 1}',),'kind': swarm.kind,+ if (swarm.isSuperTab) 'quiet': true,if (swarm.superTabId != null &&app.superTabs.peek(swarm.superTabId!)?.canWrite == true)'superTabPaused':@@ -3461,6 +3463,7 @@ class _SwarmScreenState extends State<SwarmScreen> {topInset: _native ? 0 : _tabBarHeight,// Pairing a phone is for a computer; a phone is already here.forPhone: _compact(context),+ devices: app.devicesEnabled,onOpen: onOpen,ownsPointer: (position) => _owns(_accountButtonKey, position),),@@ -3469,6 +3472,10 @@ class _SwarmScreenState extends State<SwarmScreen> {switch (choice) {case AccountMenuChoice.addPhone:await _addPhone(from: AddPhoneOpening.account);+ case AccountMenuChoice.devices:+ _openDevices();+ case AccountMenuChoice.store:+ _openStore();case AccountMenuChoice.customize:await _customize();case AccountMenuChoice.notifications:@@ -4792,14 +4799,6 @@ class _SwarmScreenState extends State<SwarmScreen> {if (app.activeSwarm.isDevices) unawaited(_devicesHarness.open());}- Widget _devicesButton(BuildContext context) => WorkspaceStoreButton(- key: const ValueKey('swarm-devices-button'),- width: WorkspaceStoreButton.widthOf(context, devices: true),- devices: true,- tooltip: 'Manage Harness devices',- onPressed: _shortcutsEnabled ? _openDevices : null,- );-// ── the daemon (daemons/README.md) ─────────────────────────────────────────/// A `daemon_*` or `pair` frame to this computer's harnessd, only while@@ -8162,14 +8161,6 @@ class _SwarmScreenState extends State<SwarmScreen> {children: [_searchButton(theme),_notificationsButton(theme),- if (_accountPhones.showsAddPhone) _addPhoneButton(theme),- if (app.devicesEnabled) _devicesButton(context),- WorkspaceStoreButton(- key: const ValueKey('swarm-store-button'),- width: WorkspaceStoreButton.widthOf(context),- tooltip: _commandTooltip('Explore Harness Store', 'app.store'),- onPressed: _shortcutsEnabled ? _openStore : null,- ),..._accountControl(),],);@@ -9072,37 +9063,12 @@ class _SwarmScreenState extends State<SwarmScreen> {];final toolHeight = workspaceBarControlHeight(context);final prefs = appearancePrefsStore.value.prompt;- final storeWidth = math.min(- WorkspaceStoreButton.widthOf(context),- math.max(0.0, constraints.maxWidth - cell.width * 22),- );- // Sign in or the avatar always stays; see [_accountControl].+ // Sign in or the avatar always stays; see [_accountControl]. Search and+ // notifications beside it; none of it here when the title bar holds them.final accountWidth = _accountControlWidth(context);- // Devices only where Store keeps its full width beside it. A narrow- // window drops it from the bar first; Harness Store still opens it.- final devicesWidth = WorkspaceStoreButton.widthOf(context, devices: true);- final room =- constraints.maxWidth -- cell.width * 22 -- accountWidth -- WorkspaceStoreButton.widthOf(context);- final showDevices = app.devicesEnabled && room >= devicesWidth;- // Add Phone likewise, and it goes before Devices: a phone is added once,- // and the account menu, the Harness menu and `> add phone` still open it.- // Not at all once the account has a phone (`state/account_phones.dart`).- final addPhoneWidth = cell.width * 4;- final showAddPhone =- _accountPhones.showsAddPhone &&- room >= addPhoneWidth + (showDevices ? devicesWidth : 0);- // Search, notifications, Add Phone, Devices, Store and the account —- // none of it here when the title bar holds them.final actionsWidth = _titleBarActions? 0.0- : storeWidth +- cell.width * 8 +- (showAddPhone ? addPhoneWidth : 0) +- (showDevices ? devicesWidth : 0) +- accountWidth;+ : cell.width * 8 + accountWidth;final tabBudget = math.max(0.0,constraints.maxWidth -@@ -9269,15 +9235,12 @@ class _SwarmScreenState extends State<SwarmScreen> {app.requestCloseSwarm(swarm.id),): null,- activity: tags > 0- ? Text(- countText(tags),- key: ValueKey('tab-tags:${swarm.id}'),- style: DesktopChrome.metadata(- color: grid.AppPalette.warn,- ).copyWith(fontWeight: FontWeight.w600),- )- : activity == null || activity.mark.isEmpty+ attention: tags > 0,+ // A Swarm's tab is its name alone (Quiet Swarm, screen 0).+ activity:+ swarm.isSuperTab ||+ activity == null ||+ activity.mark.isEmpty? null: tabStatus((visible) => ActivityMark(@@ -9339,17 +9302,6 @@ class _SwarmScreenState extends State<SwarmScreen> {if (!_titleBarActions) ...[_searchButton(theme),_notificationsButton(theme),- if (showAddPhone) _addPhoneButton(theme),- if (showDevices) _devicesButton(context),- WorkspaceStoreButton(- key: const ValueKey('swarm-store-button'),- width: storeWidth,- tooltip: _commandTooltip(- 'Explore Harness Store',- 'app.store',- ),- onPressed: _shortcutsEnabled ? _openStore : null,- ),..._accountControl(),],if (kIsWeb && _slotShown) _daemonTabButton(),@@ -9405,34 +9357,6 @@ class _SwarmScreenState extends State<SwarmScreen> {String get _addPhoneTooltip => _commandTooltip('Add Phone', 'app.add_phone');- /// Harness ▸ Add Phone…, as a glyph just before Devices ([_addPhone]).- Widget _addPhoneButton(TerminalTheme theme) => WorkspaceBarControl(- key: const ValueKey('swarm-add-phone-button'),- label: 'Add Phone',- tooltip: _addPhoneTooltip,- onPressed: _shortcutsEnabled- ? () => unawaited(_addPhone(from: AddPhoneOpening.titlebar))- : null,- builder: (context, emphasized) => SizedBox(- width: workspaceBarCellSizeOf(context).width * 4,- height: workspaceBarControlHeight(context),- // The plain phone the account menu and Harness ▸ Add Phone… show: one- // silhouette everywhere (design/icon-design-system.md). Its old radio- // waves read as NFC, and were the row's one busy glyph.- child: Icon(- AppIcons.smartphone,- size: 16,- color: theme.foreground.withValues(- alpha: !_shortcutsEnabled- ? .28- : emphasized- ? 1- : .75,- ),- ),- ),- );-Widget _notificationsButton(TerminalTheme theme) => KeyedSubtree(key: _notificationsButtonKey,child: WorkspaceNotificationsButton(diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex 9a64ad192..7413f76e0 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -894,6 +894,14 @@ class SuperTabController extends ChangeNotifier {_changed();}+ /// The devices pane gives way to what was open under it.+ void leaveDevices() {+ if (_disposed || !devicesSelected) return;+ _moveView();+ _saveSoon();+ _changed();+ }+/// Whether the Machines group's "Offline · N" disclosure is open; it starts closed.bool offlineMachinesOpen = false;diff --git a/desktop/lib/super_tabs/leaderboard/models_section.dart b/desktop/lib/super_tabs/leaderboard/models_section.dartindex 46e9ed97c..bae086a9e 100644--- a/desktop/lib/super_tabs/leaderboard/models_section.dart+++ b/desktop/lib/super_tabs/leaderboard/models_section.dart@@ -126,15 +126,19 @@ class LeaderboardModelsSection extends StatelessWidget {required this.board,required this.projectId,required this.collapsed,- required this.onToggleCollapsed,+ this.onToggleCollapsed,this.now = DateTime.now,+ this.heading = true,});final SuperTabLeaderboardReader board;/// The open project; a board of any other shows nothing.final String? projectId;final bool collapsed;- final VoidCallback onToggleCollapsed;+ final VoidCallback? onToggleCollapsed;++ /// False where the page already says Models (Manage).+ final bool heading;final DateTime Function() now;@override@@ -155,16 +159,17 @@ class LeaderboardModelsSection extends StatelessWidget {return Column(crossAxisAlignment: CrossAxisAlignment.stretch,children: [- SuperTabSectionHeading(- 'Models',- key: const ValueKey('super-models-heading'),- endInset: 0,- collapsed: collapsed,- onToggleCollapsed: onToggleCollapsed,- titleTooltip: read.recentModels != null- ? 'Share of agent work, last 7 days'- : 'Share of agent work, $span',- ),+ if (heading)+ SuperTabSectionHeading(+ 'Models',+ key: const ValueKey('super-models-heading'),+ endInset: 0,+ collapsed: collapsed,+ onToggleCollapsed: onToggleCollapsed,+ titleTooltip: read.recentModels != null+ ? 'Share of agent work, last 7 days'+ : 'Share of agent work, $span',+ ),if (!collapsed)for (final share in shares) _row(share, span, style, column),],diff --git a/desktop/lib/super_tabs/machines.dart b/desktop/lib/super_tabs/machines.dartindex 2bea9cf36..67efd514a 100644--- a/desktop/lib/super_tabs/machines.dart+++ b/desktop/lib/super_tabs/machines.dart@@ -92,11 +92,16 @@ class SuperTabMachines extends StatefulWidget {this.onToggleCollapsed,this.onOpenAgent,this.ticks,+ this.manage = false,});final SuperTabController controller;final AppNotifier? app;final bool embedded;+ /// Manage › Machines: one line per machine with its owner and status, and+ /// Add machine at the foot, with no heading of its own (Quiet Swarm, screen 10).+ final bool manage;+/// Runs the one-second clock; by default everywhere but under `flutter test`.@visibleForTestingfinal bool? ticks;@@ -1971,6 +1976,7 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {expanded: expanded,child: _MachineLine(view: view,+ words: widget.manage,onMore: BrowserMenuGuard.inBrowser? (at) => _menu(view, at): null,@@ -2372,19 +2378,60 @@ class _SuperTabMachinesState extends State<SuperTabMachines> {@overrideWidget build(BuildContext context) {final failingSince = c.backendUnreachable ? c.unreachableSince : null;+ final add = c.canWrite && widget.app != null+ ? () => unawaited(+ showAddComputers(+ context,+ c,+ widget.app!,+ readResources: widget.readLocal,+ ),+ )+ : null;+ if (widget.manage) {+ return LaidOutListView(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ // Only a Swarm that can't be read is news, as under the old heading.+ if (c.backendUnreachable)+ Align(+ alignment: Alignment.centerLeft,+ child: SuperTabMachinesPill(+ connecting: c.stillConnecting,+ reconnectingFor: failingSince == null+ ? Duration.zero+ : widget.now().difference(failingSince),+ ),+ ),+ if (_ids.isEmpty)+ Padding(+ padding: const EdgeInsets.all(grid.AppDesktop.controlGap),+ child: Text(+ "Add a machine for this Swarm's agents to use.",+ style: DesktopChrome.metadata(),+ ),+ )+ else+ ..._machines(),+ const SizedBox(height: 8),+ Align(+ alignment: Alignment.centerRight,+ child: TextButton(+ key: const ValueKey('super-manage-add-machine'),+ onPressed: add,+ child: const Text('Add machine'),+ ),+ ),+ ],+ );+ }final children = [SuperTabSectionHeading('Machines',- onAdd: c.canWrite && widget.app != null- ? () => unawaited(- showAddComputers(- context,- c,- widget.app!,- readResources: widget.readLocal,- ),- )- : null,+ onAdd: add,addTooltip: 'Add machine',// Only a Swarm that can't be read is news; a live one says nothing.trailing: c.backendUnreachable@@ -2677,10 +2724,18 @@ const _noQuotaLeft = 'No quota left until it resets.';/// The same leading icon/name and trailing status column as projects.class _MachineLine extends StatelessWidget {- const _MachineLine({required this.view, this.onSetUpTeam, this.onMore});+ const _MachineLine({+ required this.view,+ this.onSetUpTeam,+ this.onMore,+ this.words = false,+ });final _MachineView view;+ /// Its owner and status in words (Manage), not their marks.+ final bool words;+/// In a browser, opens the machine's menu at a point until it closes: the ⋯ that needs no right-click.final Future<void> Function(Offset at)? onMore;@@ -2777,7 +2832,29 @@ class _MachineLine extends StatelessWidget {),),),- if (owner != null)+ if (words) ...[+ if (owner != null)+ Padding(+ padding: const EdgeInsets.only(+ left: grid.AppDesktop.controlGap,+ ),+ child: Text(+ owner.username,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.metadata(),+ ),+ ),+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ ),+ child: Text(switch (view.status) {+ SuperTabMachineStatus.live => 'online',+ final status => superTabMachineStateLabel(status).toLowerCase(),+ }, style: DesktopChrome.metadata()),+ ),+ ] else if (owner != null)Padding(padding: const EdgeInsets.only(left: 6),child: Tooltip(@@ -2795,21 +2872,22 @@ class _MachineLine extends StatelessWidget {key: ValueKey('super-machine-more-${view.id}'),onOpen: open,),- SizedBox(- width: 32,- child: Center(- child: KeyedSubtree(- key: ValueKey(- 'super-machine-state-${view.id}-${view.status.name}',- ),- child: SuperTabMachineDot(- status: view.status,- readingAt: view.readingAt,- arrived: view.arrived,+ if (!words)+ SizedBox(+ width: 32,+ child: Center(+ child: KeyedSubtree(+ key: ValueKey(+ 'super-machine-state-${view.id}-${view.status.name}',+ ),+ child: SuperTabMachineDot(+ status: view.status,+ readingAt: view.readingAt,+ arrived: view.arrived,+ ),),),),- ),],),);diff --git a/desktop/lib/super_tabs/manage_page.dart b/desktop/lib/super_tabs/manage_page.dartnew file mode 100644index 000000000..efc4989f0--- /dev/null+++ b/desktop/lib/super_tabs/manage_page.dart@@ -0,0 +1,413 @@+import 'dart:async';++import 'package:flutter/material.dart';++import '../core/machine_resources.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/theme/appearance_prefs_store.dart';+import '../shared/widgets/app_dialog.dart';+import '../state/app_state.dart';+import '../terminal/terminal_theme_store.dart';+import '../widgets/desktop_chrome.dart';+import '../widgets/laid_out_list.dart';+import 'controller.dart';+import 'dialog_scope.dart';+import 'leaderboard/models_section.dart';+import 'leaderboard/reader.dart';+import 'local_models.dart';+import 'machines.dart';+import 'model.dart';+import 'sharing.dart';+import 'swarm_delete.dart';+import 'swarm_switcher.dart' show PersonalSwarm;++/// What Manage shows (docs/plans/2026-11-02-quiet-swarm-design.md, screens 10,+/// 10b, 10c): what used to stand in the sidebar and the Swarm dropdown, one+/// click away. Devices is the devices pane the view already holds.+enum SuperTabManageTab { machines, models, devices, swarm }++/// Machines, Models, Devices, Swarm, under Manage's heading.+class SuperTabManageTabs extends StatelessWidget {+ const SuperTabManageTabs({+ super.key,+ required this.selected,+ required this.onChoose,+ this.devices = true,+ });++ final SuperTabManageTab selected;+ final ValueChanged<SuperTabManageTab> onChoose;++ /// Whether this build has the devices pane (`AppNotifier.devicesEnabled`).+ final bool devices;++ @override+ Widget build(BuildContext context) {+ Widget tab(SuperTabManageTab value, String label) {+ final on = selected == value;+ return Padding(+ padding: const EdgeInsets.only(right: grid.AppDesktop.menuInset),+ child: Material(+ color: on ? grid.AppSurface.selectedFill : Colors.transparent,+ borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),+ clipBehavior: Clip.antiAlias,+ child: InkWell(+ key: ValueKey('super-manage-tab-${value.name}'),+ onTap: () => onChoose(value),+ hoverColor: grid.AppSurface.hoverFill,+ child: Semantics(+ selected: on,+ button: true,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ vertical: grid.AppDesktop.menuInset,+ ),+ child: Text(+ label,+ style: DesktopChrome.control(+ medium: on,+ color: on ? null : DesktopChrome.muted,+ ),+ ),+ ),+ ),+ ),+ ),+ );+ }++ return Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: Wrap(+ children: [+ tab(SuperTabManageTab.machines, 'Machines'),+ tab(SuperTabManageTab.models, 'Models'),+ if (devices) tab(SuperTabManageTab.devices, 'Devices'),+ tab(SuperTabManageTab.swarm, 'Swarm'),+ ],+ ),+ );+ }+}++/// Manage's Machines, Models or Swarm. Each is built only while it shows, so+/// what it runs (the machines' clock) stops when it does not.+class SuperTabManagePage extends StatelessWidget {+ const SuperTabManagePage({+ super.key,+ required this.controller,+ required this.tab,+ required this.onAddAgent,+ this.app,+ this.board,+ this.onOpenAgent,+ this.readLocal,+ this.now = DateTime.now,+ });++ final SuperTabController controller;+ final SuperTabManageTab tab;+ final AppNotifier? app;+ final SuperTabLeaderboardReader? board;+ final ValueChanged<SuperTabConversation> onAddAgent;+ final ValueChanged<SuperTabAgent>? onOpenAgent;++ /// Forwarded to [SuperTabMachines], for a test without a real machine.+ final Future<MachineResources?> Function(String machineId)? readLocal;+ final DateTime Function() now;++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ // Machines' online state and marks do not touch the controller, as in the+ // sidebar group they came from.+ listenable: Listenable.merge([+ controller,+ if (app case final app?) ...[app, app.agentUnread],+ terminalThemeStore,+ appearancePrefsStore,+ ]),+ builder: (context, _) => DesktopChrome(+ child: switch (tab) {+ SuperTabManageTab.machines => SuperTabMachines(+ controller: controller,+ app: app,+ onAddAgent: onAddAgent,+ onOpenAgent: onOpenAgent,+ readLocal: readLocal,+ now: now,+ manage: true,+ ),+ SuperTabManageTab.models => _ManageModels(+ controller: controller,+ app: app,+ board: board,+ now: now,+ ),+ // The view holds the devices pane in this one's place.+ SuperTabManageTab.devices => const SizedBox.shrink(),+ SuperTabManageTab.swarm => _ManageSwarm(+ controller: controller,+ app: app,+ ),+ },+ ),+ );+}++/// The action at a Manage page's foot, on the right: quiet, as the design draws+/// it.+class _FootAction extends StatelessWidget {+ const _FootAction({+ required this.label,+ required this.onPressed,+ this.actionKey,+ });+ final String label;+ final VoidCallback? onPressed;+ final Key? actionKey;++ @override+ Widget build(BuildContext context) => Align(+ alignment: Alignment.centerRight,+ child: TextButton(key: actionKey, onPressed: onPressed, child: Text(label)),+ );+}++class _ManageModels extends StatelessWidget {+ const _ManageModels({+ required this.controller,+ required this.now,+ this.app,+ this.board,+ });+ final SuperTabController controller;+ final AppNotifier? app;+ final SuperTabLeaderboardReader? board;+ final DateTime Function() now;++ @override+ Widget build(BuildContext context) {+ final projectId = controller.snapshot+ ?.projectFor(controller.selectedId)+ ?.id;+ return LaidOutListView(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ if (board case final board?)+ LeaderboardModelsSection(+ board: board,+ projectId: projectId,+ collapsed: false,+ now: now,+ heading: false,+ ),+ const SizedBox(height: 8),+ _FootAction(+ label: 'Your models…',+ actionKey: const ValueKey('super-local-models'),+ onPressed: controller.snapshot == null+ ? null+ : () => showSwarmLocalModels(+ context,+ controller,+ app: app,+ now: now,+ ),+ ),+ ],+ );+ }+}++class _ManageSwarm extends StatefulWidget {+ const _ManageSwarm({required this.controller, this.app});+ final SuperTabController controller;+ final AppNotifier? app;++ @override+ State<_ManageSwarm> createState() => _ManageSwarmState();+}++class _ManageSwarmState extends State<_ManageSwarm> {+ SuperTabController get c => widget.controller;+ DeletedSwarms? get _deleted {+ final app = widget.app;+ return app == null ? null : DeletedSwarms.of(app);+ }++ @override+ void initState() {+ super.initState();+ if (_deleted case final deleted?) unawaited(deleted.read());+ }++ bool get _isPersonal {+ final app = widget.app;+ return app != null && PersonalSwarm.of(app).id == c.tabId;+ }++ /// Why this person can't leave yet (they contribute a project's coordinator);+ /// null when they can.+ String? get _leaveBlocked {+ final snapshot = c.snapshot;+ if (snapshot == null) return null;+ for (final agent in snapshot.agents) {+ if (agent.contributorId != c.accountId) continue;+ if (snapshot.leadProtectionReason(agent.id) case final reason?) {+ return reason;+ }+ }+ return null;+ }++ Future<void> _delete() async {+ if (!await showDeleteSwarmDialog(context, c)) return;+ final app = widget.app;+ if (app == null) return;+ unawaited(app.superTabs.refreshTabs());+ unawaited(_deleted?.read());+ }++ Future<void> _leave() async {+ final confirmed = await showAppDialog<bool>(+ context: context,+ builder: (context) => SuperTabDialogScope(+ controller: c,+ requireWrite: false,+ child: AlertDialog(+ title: const Text('Leave Swarm?'),+ content: const Text(+ 'Swarm access and agent contributions will be withdrawn.',+ ),+ actions: [+ TextButton(+ onPressed: () => Navigator.pop(context, false),+ child: const Text('Cancel'),+ ),+ FilledButton(+ key: const ValueKey('super-manage-leave-confirm'),+ onPressed: () => Navigator.pop(context, true),+ child: const Text('Leave'),+ ),+ ],+ ),+ ),+ );+ if (confirmed != true || !mounted || c.accessRevoked) return;+ await c.command({'type': 'member.remove', 'userId': c.accountId});+ }++ Widget _fact(String label, Widget value, {Widget? action}) => ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 36),+ child: Row(+ children: [+ Expanded(child: Text(label, style: DesktopChrome.control())),+ value,+ ?action,+ ],+ ),+ );++ Text _value(String text) => Text(+ text,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: DesktopChrome.control(color: DesktopChrome.muted),+ );++ @override+ Widget build(BuildContext context) {+ final snapshot = c.snapshot;+ if (snapshot == null || c.accessRevoked) return const SizedBox.shrink();+ final owner = snapshot.people+ .where((p) => p.id == snapshot.ownerId)+ .firstOrNull;+ final deleted = _deleted;+ final blocked = _leaveBlocked;+ return LaidOutListView(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ _fact('Name', _value(snapshot.name)),+ if (owner != null) _fact('Owner', _value(owner.username)),+ _fact(+ 'People',+ _value('${snapshot.people.length}'),+ action: Padding(+ padding: const EdgeInsets.only(left: grid.AppDesktop.controlGap),+ child: TextButton(+ key: const ValueKey('super-manage-people'),+ onPressed: () => showSuperTabSharing(context, c),+ child: const Text('Manage people'),+ ),+ ),+ ),+ const SizedBox(height: 16),+ // Its owner's alone, never Personal (backend deletion.ts). Everyone+ // else there may leave.+ if (!_isPersonal && c.isOwner)+ _FootAction(+ label: 'Delete Swarm…',+ actionKey: const ValueKey('super-manage-delete'),+ onPressed: _delete,+ )+ else if (!_isPersonal)+ Tooltip(+ message: blocked ?? '',+ child: _FootAction(+ label: 'Leave Swarm…',+ actionKey: const ValueKey('super-manage-leave'),+ onPressed: blocked == null ? _leave : null,+ ),+ ),+ if (deleted != null)+ ListenableBuilder(+ listenable: deleted,+ builder: (context, _) => Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ for (final swarm in deleted.items)+ _fact(+ swarm.name,+ _value(+ deleted.restoreError?.id == swarm.id+ ? deleted.restoreError!.message+ : 'Deleted · ${restoreTimeLeft(swarm.purgeAt, DateTime.now())}',+ ),+ action: Padding(+ padding: const EdgeInsets.only(+ left: grid.AppDesktop.controlGap,+ ),+ child: TextButton(+ key: ValueKey('super-manage-restore-${swarm.id}'),+ onPressed: deleted.restoring(swarm.id)+ ? null+ : () => unawaited(+ deleted.restore(swarm.id, tab: _activeTab),+ ),+ child: const Text('Restore'),+ ),+ ),+ ),+ ],+ ),+ ),+ ],+ );+ }++ /// The workspace tab showing this Swarm, for a restore to show it there.+ String? get _activeTab => widget.app?.swarms+ .where((tab) => tab.isSuperTab && tab.superTabId == c.tabId)+ .firstOrNull+ ?.id;+}diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dartindex 96a462062..c8cc115aa 100644--- a/desktop/lib/super_tabs/project_sidebar.dart+++ b/desktop/lib/super_tabs/project_sidebar.dart@@ -56,35 +56,31 @@ class ProjectSidebar extends StatelessWidget {required this.controller,required this.onSelect,required this.needsHuman,- required this.onAddAgent,this.app,this.onNewProject,this.onNewSwarm,- this.onYourDevices,+ this.onManage,+ this.manageSelected = false,this.devicesSelected = false,this.onNotifications,this.notificationsSelected = false,this.attention,this.activity,- this.onThreads,- this.threadsSelected = false,- this.onOpenAgent,this.onOpenBuddyChat,- this.readLocal,- this.board,- this.now = DateTime.now,});final SuperTabController controller;final ValueChanged<String> onSelect;final int Function(SuperTabConversation group) needsHuman;- final ValueChanged<SuperTabConversation> onAddAgent;final AppNotifier? app;final VoidCallback? onNewProject;/// The existing New Swarm. Given, the bar starts with the Swarm dropdown/// ([SwarmSwitcher]), which offers it last.final VoidCallback? onNewSwarm;- final VoidCallback? onYourDevices;++ /// Opens Manage (Machines, Models, Devices, Swarm), the row at the foot.+ final VoidCallback? onManage;+ final bool manageSelected;final bool devicesSelected;/// Opens the Activity view (Slack's Activity): decisions asked of the@@ -102,34 +98,18 @@ class ProjectSidebar extends StatelessWidget {/// it rows carry no number.final SuperTabAttention? attention;- /// Opens the Threads view; no Threads row without it.- final VoidCallback? onThreads;- final bool threadsSelected;-- /// Whether a row other than a conversation (devices, Notifications,- /// Threads) holds the main pane.+ /// Whether a row other than a conversation (Manage, devices, Notifications)+ /// holds the main pane.bool get _paneCovered =>- devicesSelected || notificationsSelected || threadsSelected;- final ValueChanged<SuperTabAgent>? onOpenAgent;+ manageSelected || devicesSelected || notificationsSelected;/// Opens the reader's Buddy chat in a project, by project id; the/// controller's [SuperTabController.openBuddyChat] when not given.final ValueChanged<String>? onOpenBuddyChat;- /// The open project's week board the right pane shows, for Models; none- /// without it.- final SuperTabLeaderboardReader? board;-- /// Forwarded to the embedded [SuperTabMachines]; a test gives it to have- /// the Machines group's readings taken without a real machine.- @visibleForTesting- final Future<MachineResources?> Function(String machineId)? readLocal;-/// Forwarded to the embedded [SuperTabMachines]; a test gives it to pin/// the clock its readings' ages are counted against.@visibleForTesting- final DateTime Function() now;-/// Projects and workgroups share a text column. Only projects use its icon.static const _iconColumn = SuperTabSectionHeading.actionWidth;@@ -289,7 +269,7 @@ class ProjectSidebar extends StatelessWidget {Widget _drawRow(SuperTabConversation group, {SuperTabProject? project,- // A channel that is no project: # buddy, the reader's one Buddy chat.+ // A chat that is no project: Buddy, the reader's one Buddy chat.String? label,String? key,required bool selected,@@ -341,7 +321,16 @@ class ProjectSidebar extends StatelessWidget {expanded: expanded,child: InkWell(key: ValueKey(key ?? 'super-group-${group.id}'),- onTap: !tappable ? null : onTap ?? () => onSelect(group.id),+ onTap: !tappable+ ? null+ : onTap ??+ // A second click on the open project shows its+ // workgroups (Quiet Swarm: no chevrons).+ (project != null &&+ !_paneCovered &&+ controller.selectedId == group.id+ ? () => controller.toggleProject(project.id)+ : () => onSelect(group.id)),hoverColor: Colors.transparent,focusColor: grid.AppSurface.hoverFill,borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),@@ -350,8 +339,14 @@ class ProjectSidebar extends StatelessWidget {SizedBox(width: SuperTabSectionHeading.indentFor(0)),SizedBox(width: _iconColumn,- child: project != null || label != null+ child: project != null? _channelMark()+ : label != null+ ? Icon(+ AppIcons.bot,+ size: AppIcons.inlineSize,+ color: DesktopChrome.foreground,+ ): null,),Expanded(@@ -507,9 +502,6 @@ class ProjectSidebar extends StatelessWidget {),),),- // At the far right edge, since it is always there and the mark- // beside it comes and goes (Dee, 2026-10-28).- if (project != null) _toggle(project, expanded: expanded),],),),@@ -546,35 +538,6 @@ class ProjectSidebar extends StatelessWidget {child: child,);- /// The chevron that shows or hides a project's conversations: '>' while- /// they are hidden, 'v' while shown. Focused, Enter or Space toggles it; on- /// the focused name, → shows them and ← hides them.- Widget _toggle(SuperTabProject project, {required bool expanded}) =>- Semantics(- button: true,- expanded: expanded,- child: InkWell(- key: ValueKey('super-project-toggle-${project.id}'),- onTap: () => controller.toggleProject(project.id),- // Its row lights whole on hover (_RowSurface).- hoverColor: Colors.transparent,- focusColor: grid.AppSurface.hoverFill,- borderRadius: BorderRadius.circular(DesktopChrome.rowRadius),- child: Tooltip(- message: expanded ? 'Hide conversations' : 'Show conversations',- child: SizedBox(- width: _iconColumn,- height: 36,- child: Icon(- expanded ? AppIcons.chevronDown : AppIcons.chevronRight,- size: AppIcons.inlineSize,- color: DesktopChrome.muted,- ),- ),- ),- ),- );-/// A project's "Closed (N)" row and, when it is open, the closed groups under it: archived ones and finished/// ones that left the active set, as read for the project so far.List<Widget> _closed(_ProjectReading reading) {@@ -739,13 +702,10 @@ class ProjectSidebar extends StatelessWidget {final busy = controller.saving || controller.hasPendingAction;return _drawRow(chat ?? _unopenedSwarmBuddyChat,- label: kSwarmBuddyChannel,+ label: 'Buddy',key: 'super-swarm-buddy',selected:- chat != null &&- !devicesSelected &&- !notificationsSelected &&- controller.selectedId == chat.id,+ chat != null && !_paneCovered && controller.selectedId == chat.id,waiting: false,// Muted, it is greyed and never bold, as every chat (_drawRow).unread: chat != null && controller.unreadShown(chat),@@ -929,166 +889,115 @@ class ProjectSidebar extends StatelessWidget {final reading = _SidebarReading(controller, needsHuman, attention);return Material(color: DesktopChrome.surface,- child: LaidOutListView(- padding: const EdgeInsets.all(8),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,children: [- if ((app, onNewSwarm) case (final app?, final onNewSwarm?))- SwarmSwitcher(- app: app,- controller: controller,- onNewSwarm: onNewSwarm,- row:- ({- required label,- required icon,- required onTap,- required trailing,- }) => _navigationRow(- key: 'super-swarm-switcher',- label: label,- icon: icon,- onTap: onTap,- trailing: trailing,+ Expanded(+ child: LaidOutListView(+ padding: const EdgeInsets.all(8),+ children: [+ if ((app, onNewSwarm) case (final app?, final onNewSwarm?))+ SwarmSwitcher(+ app: app,+ controller: controller,+ onNewSwarm: onNewSwarm,+ row:+ ({+ required label,+ required icon,+ required onTap,+ required trailing,+ }) => _navigationRow(+ key: 'super-swarm-switcher',+ label: label,+ icon: icon,+ onTap: onTap,+ trailing: trailing,+ ),),+ // Slack's Activity, where Notifications was (Lead, 10-31): one row.+ if (onNotifications != null)+ _navigationRow(+ key: 'super-activity',+ label: 'Activity',+ icon: AppIcons.bell,+ onTap: onNotifications,+ selected: notificationsSelected,+ unread: activity?.unread ?? false,+ badge:+ activity?.count ??+ (snapshot?.mentionsWaiting ?? 0) ++ (snapshot?.decisionsWaiting ?? 0),+ ),+ // One Buddy for the whole Swarm, under Activity (Quiet Swarm, screen 1).+ if (controller.oneBuddy) ?_swarmBuddyRow(),+ const SizedBox(height: 20),+ SuperTabSectionHeading(+ key: const ValueKey('project-sidebar-projects'),+ 'Projects',+ // Slack's unread filter: only chats with something unread.+ actions: [+ AppIconButton(+ key: const ValueKey('super-unread-only'),+ icon: AppIcons.listFilter,+ selected: controller.unreadOnly,+ tooltip: controller.unreadOnly+ ? 'Show all chats'+ : 'Show unread chats only',+ onPressed: controller.toggleUnreadOnly,+ ),+ ],+ onAdd: controller.canWrite ? onNewProject : null,+ addTooltip: 'New project',+ endInset: 0,+ collapsed: !controller.projectsGroupOpen,+ onToggleCollapsed: controller.toggleProjectsGroup,+ ),+ if (controller.projectsGroupOpen) ...[+ for (final (_, channel) in _channels(snapshot, reading))+ channel,+ ],+ const SizedBox(height: 16),+ // Buddies replaced Chat with PM in every Swarm (Ken, 10-29); where the+ // server gives one Buddy for the whole Swarm, it is # buddy above.+ if (!controller.oneBuddy) ...[+ SuperTabSectionHeading(+ 'Buddies',+ onAdd:+ controller.canWrite &&+ !controller.saving &&+ !controller.hasPendingAction &&+ buddyProjects(controller).isNotEmpty+ ? () => unawaited(+ showAddBuddy(context, controller, app: app),+ )+ : null,+ addTooltip: 'Add a Buddy',+ endInset: 0,+ collapsed: !controller.buddiesGroupOpen,+ onToggleCollapsed: controller.toggleBuddiesGroup,+ ),+ if (controller.buddiesGroupOpen)+ ..._buddies(projects, reading),+ const SizedBox(height: 16),+ ],+ ],),- if (onNewProject != null)- _navigationRow(- key: 'super-new-project',- label: 'New project',- icon: AppIcons.plus,- onTap: controller.canWrite ? onNewProject : null,- ),- if (onYourDevices != null)- _navigationRow(- key: 'super-your-devices',- label: 'Your devices',- icon: AppIcons.circle,- onTap: onYourDevices,- selected: devicesSelected,- ),- // The Swarm's models (docs/plans/2026-10-23-swarm-local-models.md), for everyone: the owner sets them up here,- // and everyone runs and shares models here once they are. What each machine offers is on the machine.- if (snapshot != null)- _navigationRow(- key: 'super-local-models',- label: 'Your models',- icon: AppIcons.brain,- onTap: () =>- showSwarmLocalModels(context, controller, app: app, now: now),- ),- // Slack's Activity, where Notifications was (Lead, 10-31): one row.- if (onNotifications != null)- _navigationRow(- key: 'super-activity',- label: 'Activity',- icon: AppIcons.bell,- onTap: onNotifications,- selected: notificationsSelected,- unread: activity?.unread ?? false,- badge:- activity?.count ??- (snapshot?.mentionsWaiting ?? 0) +- (snapshot?.decisionsWaiting ?? 0),- ),- if (onThreads != null)- _navigationRow(- key: 'super-threads',- label: 'Threads',- icon: AppIcons.messagesSquare,- onTap: onThreads,- selected: threadsSelected,- unread: attention?.threadsUnread ?? false,- badge: attention?.threadMentions ?? 0,- ),- if (onNewProject != null ||- onYourDevices != null ||- onNotifications != null ||- onThreads != null ||- controller.isOwner ||- snapshot?.localModels?.enabled == true)- const SizedBox(height: 20),- SuperTabSectionHeading(- 'Projects',- // Slack's unread filter: only chats with something unread.- actions: [- AppIconButton(- key: const ValueKey('super-unread-only'),- icon: AppIcons.listFilter,- selected: controller.unreadOnly,- tooltip: controller.unreadOnly- ? 'Show all chats'- : 'Show unread chats only',- onPressed: controller.toggleUnreadOnly,- ),- ],- onAdd: controller.canWrite ? onNewProject : null,- addTooltip: 'New project',- endInset: 0,- collapsed: !controller.projectsGroupOpen,- onToggleCollapsed: controller.toggleProjectsGroup,- ),- if (controller.projectsGroupOpen) ...[- // One Buddy for the whole Swarm, pinned first (Dee, 10-31).- if (controller.oneBuddy) ?_swarmBuddyRow(),- for (final (_, channel) in _channels(snapshot, reading)) channel,- ],- const SizedBox(height: 16),- // Buddies replaced Chat with PM in every Swarm (Ken, 10-29); where the- // server gives one Buddy for the whole Swarm, it is # buddy above.- if (!controller.oneBuddy) ...[- SuperTabSectionHeading(- 'Buddies',- onAdd:- controller.canWrite &&- !controller.saving &&- !controller.hasPendingAction &&- buddyProjects(controller).isNotEmpty- ? () => unawaited(showAddBuddy(context, controller, app: app))- : null,- addTooltip: 'Add a Buddy',- endInset: 0,- collapsed: !controller.buddiesGroupOpen,- onToggleCollapsed: controller.toggleBuddiesGroup,- ),- if (controller.buddiesGroupOpen) ..._buddies(projects, reading),- const SizedBox(height: 16),- ],- // Machine online/offline, unread marks and theme changes do not touch- // the controller the rest of this sidebar rebuilds on, so this group- // watches them itself — the same sources the roster merged before the- // move (roster.dart).- ListenableBuilder(- listenable: Listenable.merge([- controller,- if (app != null) ...[app!, app!.agentUnread],- terminalThemeStore,- appearancePrefsStore,- ]),- builder: (context, _) {- grid.AppTheme.watch(context);- return SuperTabMachines(- controller: controller,- app: app,- onAddAgent: onAddAgent,- onOpenAgent: onOpenAgent,- embedded: true,- collapsed: !controller.machinesGroupOpen,- onToggleCollapsed: controller.toggleMachinesGroup,- readLocal: readLocal,- now: now,- );- },),- if (board case final board?) ...[- const SizedBox(height: 16),- LeaderboardModelsSection(- board: board,- projectId: snapshot?.projectFor(controller.selectedId)?.id,- collapsed: !controller.modelsGroupOpen,- onToggleCollapsed: controller.toggleModelsGroup,- now: now,+ // At the foot, however long the list (Quiet Swarm, screen 1).+ if (onManage != null)+ Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ ),+ child: _navigationRow(+ key: 'super-manage',+ label: 'Manage',+ icon: AppIcons.settings,+ onTap: onManage,+ selected: manageSelected,+ ),),- ],],),);diff --git a/desktop/lib/super_tabs/swarm_delete.dart b/desktop/lib/super_tabs/swarm_delete.dartindex ae069385b..02d7b8e9c 100644--- a/desktop/lib/super_tabs/swarm_delete.dart+++ b/desktop/lib/super_tabs/swarm_delete.dart@@ -12,9 +12,9 @@ import 'model.dart';import 'swarm_switcher.dart' show PersonalSwarm;/// Deleting a Swarm (Dee, 10-31: "owners can delete a Swarm, like deleting a-/// Slack workspace"). Its owner picks Delete in the Swarm dropdown and types-/// its name; everyone loses it at once. For 7 days it is listed under the-/// dropdown's Restore rows, its owner's alone (backend superTabs/deletion.ts).+/// Slack workspace"). Its owner picks Delete in Manage › Swarm and types+/// its name; everyone loses it at once. For 7 days it is listed there to+/// restore, its owner's alone (backend superTabs/deletion.ts)./// One deleted Swarm its owner can still restore.typedef DeletedSwarm = ({String id, String name, DateTime purgeAt});diff --git a/desktop/lib/super_tabs/swarm_switcher.dart b/desktop/lib/super_tabs/swarm_switcher.dartindex fa4f3a5e0..961ed869b 100644--- a/desktop/lib/super_tabs/swarm_switcher.dart+++ b/desktop/lib/super_tabs/swarm_switcher.dart@@ -13,7 +13,6 @@ import 'controller.dart';import 'machines.dart' show contributeComputer;import 'personal_machines.dart';import 'section_heading.dart' show SuperTabSectionHeading;-import 'swarm_delete.dart';/// The Swarm dropdown at the top of a Swarm tab's left bar (Dee, 10-30): the/// Swarm the tab shows, and in its menu Personal, every other Swarm the@@ -422,24 +421,6 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {app.showSuperTabIn(tab, choice.id, choice.name);}- DeletedSwarms get deleted => DeletedSwarms.of(app);-- /// Asks its owner to confirm; once deleted, it leaves this dropdown and- /// its tab moves on as for any Swarm taken away.- Future<void> _delete(BuildContext context) async {- _menu.close();- final c = widget.controller;- if (!await showDeleteSwarmDialog(context, c)) return;- unawaited(app.superTabs.refreshTabs());- unawaited(deleted.read());- }-- /// Restores a deleted Swarm and shows it in this tab.- void _restore(String id) {- _menu.close();- unawaited(deleted.restore(id, tab: _tab));- }-void _pickPersonal() {_menu.close();final tab = _tab;@@ -448,7 +429,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {@overrideWidget build(BuildContext context) => ListenableBuilder(- listenable: Listenable.merge([app, personal, deleted, widget.controller]),+ listenable: Listenable.merge([app, personal, widget.controller]),builder: (context, _) {grid.AppTheme.watch(context);final c = widget.controller;@@ -461,7 +442,6 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {? 'Swarm': app.superTabName(current) ?? c.snapshot?.name ?? 'Swarm';final choices = swarmChoices(app);- final restorable = deleted.items;final personalWaiting = personalId == null || isPersonal? 0: swarmWaiting(app, personalId);@@ -477,10 +457,13 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {controller: _menu,consumeOutsideTap: true,alignmentOffset: const Offset(0, grid.AppControl.menuGap),- style: grid.AppMenu.style(minWidth: width, maxWidth: width),+ style: grid.AppMenu.style(+ minWidth: width,+ maxWidth: width,+ maxHeight: 480,+ ),onOpen: () {if (_tab case final tab?) personal.clearError(tab);- unawaited(deleted.read());},// As wide as the row it opens from.menuChildren: [@@ -513,6 +496,7 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {: badge(choice.waiting),onPressed: () => _pick(choice.id),),+ const AppMenuDivider(),AppMenuItem(key: const ValueKey('swarm-switch-new'),label: 'New Swarm',@@ -523,40 +507,6 @@ class _SwarmSwitcherState extends State<SwarmSwitcher> {widget.onNewSwarm();},),- // Its owner's alone, never Personal (backend deletion.ts).- if (current != null &&- !isPersonal &&- c.isOwner &&- c.snapshot != null)- AppMenuItem(- key: const ValueKey('swarm-switch-delete'),- label: 'Delete “$label”…',- icon: AppIcons.trash2,- danger: true,- expandLabel: true,- onPressed: () => _delete(context),- ),- if (restorable.isNotEmpty) const AppMenuDivider(),- for (final swarm in restorable)- AppMenuItem(- key: ValueKey('swarm-switch-restore-${swarm.id}'),- label: 'Restore “${swarm.name}”',- icon: AppIcons.undo2,- expandLabel: true,- detail: deleted.restoreError?.id == swarm.id- ? deleted.restoreError!.message- : 'Deleted · '- '${restoreTimeLeft(swarm.purgeAt, DateTime.now())}',- trailing: deleted.restoring(swarm.id)- ? const SizedBox.square(- dimension: 12,- child: CircularProgressIndicator(- strokeWidth: 1.5,- ),- )- : null,- onPressed: () => _restore(swarm.id),- ),])SizedBox(width: width, child: item),],diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex dab6e81c1..4e29312cb 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -58,6 +58,7 @@ import 'route_row.dart';import 'terminal_row.dart';import 'thread_panel.dart';import 'work_details.dart';+import 'manage_page.dart';import 'project_sidebar.dart';import 'buddy_sessions.dart';import 'swarm_switcher.dart' show fallBackToPersonal;@@ -153,6 +154,10 @@ class _SuperTabViewState extends State<SuperTabView>bool _showNotifications = false;+ /// Manage holds the main pane; [_manageTab] is which of its pages, but for+ /// Devices, which is the pane the view holds for it ([_devicesVisible]).+ bool _showManage = false;+ SuperTabManageTab _manageTab = SuperTabManageTab.machines;// The message a tag opened, scrolled to once it is laid out.String? _target;// The conversation a link or tag opened at its own message this visit: its@@ -288,6 +293,13 @@ class _SuperTabViewState extends State<SuperTabView>@overridevoid didUpdateWidget(SuperTabView oldWidget) {super.didUpdateWidget(oldWidget);+ // A terminal that opens shows: Manage and Activity outrank it in the pane.+ final terminalNow = widget.terminalsVisible || widget.terminal != null;+ final terminalBefore =+ oldWidget.terminalsVisible || oldWidget.terminal != null;+ if (terminalNow && !terminalBefore && !c.devicesSelected) {+ _showManage = _showNotifications = false;+ }if (oldWidget.controller != c) {_noticesLeave(oldWidget.controller);SuperTabChatNotices.of(c).chatShown = _chatShown;@@ -470,7 +482,8 @@ class _SuperTabViewState extends State<SuperTabView>_devicesVisible ||_terminalsVisible ||_showPullRequests ||- _showNotifications) {+ _showNotifications ||+ _showManage) {return false;}final lifecycle = WidgetsBinding.instance.lifecycleState;@@ -698,7 +711,7 @@ class _SuperTabViewState extends State<SuperTabView>if (group == null || !c.unreadShown(group)) continue;widget.onCloseTerminal?.call();setState(() {- _showNotifications = false;+ _showNotifications = _showManage = false;_showPullRequests = false;});unawaited(c.select(group.id));@@ -1583,35 +1596,19 @@ class _SuperTabViewState extends State<SuperTabView>Widget _sidebar() => ProjectSidebar(controller: c,app: widget.app,- board: _board,- onAddAgent: widget.onAddAgent,onNewProject: widget.onNewProject,onNewSwarm: widget.onNewSwarm,- devicesSelected: _devicesVisible,notificationsSelected: _notificationsVisible,attention: SuperTabAttention.of(c),activity: SuperTabActivity.of(c),+ onManage: _openManage,+ manageSelected: _manageOpen,// Activity on every platform (Lead, 10-31): the Mac's menu bar and Dock// still say what waits, and the sidebar lists it as Slack does.onNotifications: _openActivity,- onOpenAgent: (agent) {- _closeSidebar();- setState(() {- _showPullRequests = false;- _showNotifications = false;- });- (widget.onChooseAgentTerminal ?? widget.onOpenTerminal)(agent);- },- onYourDevices: widget.app?.devicesEnabled != true- ? null- : () {- _closeSidebar();- setState(() => _showNotifications = false);- widget.app!.openDevices();- },needsHuman: (group) => _needsHuman(group).length,onSelect: (id) {- setState(() => _showNotifications = false);+ setState(() => _showNotifications = _showManage = false);c.select(id);_closeSidebar();},@@ -1624,7 +1621,7 @@ class _SuperTabViewState extends State<SuperTabView>/// ([SuperTabController.buddyChatOpener]).Future<bool> _openBuddyChat(String projectId) {setState(() {- _showNotifications = false;+ _showNotifications = _showManage = false;_showPullRequests = false;});widget.onCloseTerminal?.call();@@ -1641,6 +1638,7 @@ class _SuperTabViewState extends State<SuperTabView>widget.onCloseTerminal?.call();setState(() {_showNotifications = true;+ _showManage = false;_showPullRequests = false;});if (request.kind != 'mention') return;@@ -1658,6 +1656,7 @@ class _SuperTabViewState extends State<SuperTabView>_closeSidebar();setState(() {_showNotifications = true;+ _showManage = false;_showPullRequests = false;});widget.onCloseTerminal?.call();@@ -1666,8 +1665,45 @@ class _SuperTabViewState extends State<SuperTabView>bool get _notificationsVisible =>_showNotifications && !_devicesVisible && !c.accessRevoked;- /// Activity holds the main pane, with no chat header.- bool get _listViewHoldsThePane => _notificationsVisible;+ /// Activity or Manage holds the main pane, with no chat header.+ bool get _listViewHoldsThePane => _notificationsVisible || _manageVisible;++ bool get _manageVisible =>+ _showManage &&+ !_showNotifications &&+ !_devicesVisible &&+ !c.accessRevoked;++ /// Manage shows, on any of its pages: Devices is one of them, however it+ /// was opened.+ bool get _manageOpen => _manageVisible || _devicesVisible;++ bool get _hasDevices => widget.app?.devicesEnabled == true;++ /// The sidebar's Manage, on the page it last showed.+ void _openManage() {+ _closeSidebar();+ setState(() {+ _showManage = true;+ _showNotifications = _showPullRequests = false;+ if (_manageTab == SuperTabManageTab.devices && !_hasDevices) {+ _manageTab = SuperTabManageTab.machines;+ }+ });+ if (_manageTab == SuperTabManageTab.devices) widget.app!.openDevices();+ }++ void _chooseManageTab(SuperTabManageTab tab) {+ setState(() {+ _showManage = true;+ _manageTab = tab;+ });+ if (tab == SuperTabManageTab.devices) {+ widget.app!.openDevices();+ } else {+ c.leaveDevices();+ }+ }/// Opens [root]'s thread in its chat from Activity's New replies.void _openThreadFromList(String conversationId, String root) {@@ -1683,7 +1719,7 @@ class _SuperTabViewState extends State<SuperTabView>widget.onCloseTerminal?.call();_closeSidebar();setState(() {- _showNotifications = false;+ _showNotifications = _showManage = false;_showPullRequests = false;});c.select(conversationId);@@ -1761,7 +1797,7 @@ class _SuperTabViewState extends State<SuperTabView>}final shownBy = _rowShowing(id, messageId) ?? messageId;setState(() {- _showNotifications = false;+ _showNotifications = _showManage = false;_showPullRequests = false;_back = null;_target = shownBy;@@ -2185,8 +2221,8 @@ class _SuperTabViewState extends State<SuperTabView>/// [SuperTabWorkgroupName].Widget _title(SuperTabConversation? group) {final style = DesktopChrome.text(medium: true);- final name = _devicesVisible- ? 'Your devices'+ final name = _manageOpen+ ? 'Manage': _notificationsVisible? 'Activity': group == null@@ -2404,7 +2440,7 @@ class _SuperTabViewState extends State<SuperTabView>fingerTarget(enabled: _phone,AppIconButton(- icon: AppIcons.columns2,+ icon: AppIcons.menu,tooltip: 'Conversations',onPressed: () => setState(() => _sidebarOpen = !_sidebarOpen),),@@ -4280,6 +4316,7 @@ class _SuperTabViewState extends State<SuperTabView>setState(() {_showPullRequests = false;_rosterOpen = false;+ _showManage = _showNotifications = false;});(widget.onChooseAgentTerminal ?? widget.onOpenTerminal)(agent);},@@ -4315,10 +4352,20 @@ class _SuperTabViewState extends State<SuperTabView>center: Column(children: [_header(c.selected, narrow, showRoster),+ if (_manageOpen)+ SuperTabManageTabs(+ selected: _devicesVisible+ ? SuperTabManageTab.devices+ : _manageTab,+ devices: _hasDevices,+ onChoose: _chooseManageTab,+ ),Expanded(child: SuperTabPages(index: _devicesVisible? 1+ : _manageVisible+ ? 4: _notificationsVisible? 3: c.snapshot?.projects.isEmpty == true@@ -4347,6 +4394,21 @@ class _SuperTabViewState extends State<SuperTabView>onOpenConversation: _openConversation,): const SizedBox.shrink(),+ _manageVisible+ ? SuperTabManagePage(+ controller: c,+ app: widget.app,+ board: _board,+ tab: _manageTab,+ onAddAgent: widget.onAddAgent,+ onOpenAgent: (agent) {+ setState(() => _showManage = false);+ (widget.onChooseAgentTerminal ??+ widget.onOpenTerminal)+ .call(agent);+ },+ )+ : const SizedBox.shrink(),],),),diff --git a/desktop/lib/widgets/account_menu.dart b/desktop/lib/widgets/account_menu.dartindex cba83efcc..6ce7cd5f8 100644--- a/desktop/lib/widgets/account_menu.dart+++ b/desktop/lib/widgets/account_menu.dart@@ -9,12 +9,21 @@ import 'pane_menu.dart';import 'workspace_account_button.dart';/// What the account menu was asked for.-enum AccountMenuChoice { addPhone, customize, notifications, settings, signOut }+enum AccountMenuChoice {+ addPhone,+ devices,+ store,+ customize,+ notifications,+ settings,+ signOut,+}-/// The menu under the avatar: who is signed in, then Add Phone, Appearance,+/// The menu under the avatar: who is signed in, then Add Phone, Devices, the+/// Store (moved here from the bar: Quiet Swarm, screen 0), Appearance,/// Notifications, Settings and Sign out. Each opens something the app/// already has; the caller does that once this has closed, so the two never-/// stand on screen together. Kept to these five (owner, 2026-10-11).+/// stand on screen together.////// Drawn here rather than as a native menu, so the Mac — whose tab row is/// native — and Linux get the same one. It hangs from the window's top-right@@ -32,6 +41,7 @@ Future<AccountMenuChoice?> showAccountMenu(double topInset = 0,bool focusFirst = false,bool forPhone = false,+ bool devices = true,void Function(void Function() close)? onOpen,bool Function(Offset position)? ownsPointer,}) => showPaneMenu<AccountMenuChoice>(@@ -46,6 +56,7 @@ Future<AccountMenuChoice?> showAccountMenu(name: name,email: email,forPhone: forPhone,+ devices: devices,onChoose: close,),);@@ -57,6 +68,7 @@ class AccountMenu extends StatelessWidget {required this.email,required this.onChoose,this.forPhone = false,+ this.devices = true,});/// As the account gives it; empty when it has only an email.@@ -65,9 +77,12 @@ class AccountMenu extends StatelessWidget {final void Function(AccountMenuChoice? choice) onChoose;/// The web on a phone: rows a finger can hit, and no Add Phone (a phone is- /// already here).+ /// already here). Its compact bar keeps Devices and the Store itself.final bool forPhone;+ /// Whether this build has Devices (`AppNotifier.devicesEnabled`).+ final bool devices;+static const width = 264.0;// Add Phone stays once the account has a phone: a second one is added the@@ -75,12 +90,20 @@ class AccountMenu extends StatelessWidget {// next read as a fault (1.2.64 learned of the phone only when the menu opened).static const _rows = [(AccountMenuChoice.addPhone, AppIcons.smartphone, 'Add Phone'),+ (AccountMenuChoice.devices, AppIcons.circle, 'Devices'),+ (AccountMenuChoice.store, AppIcons.store, 'Store'),(AccountMenuChoice.customize, AppIcons.palette, 'Appearance'),(AccountMenuChoice.notifications, AppIcons.bell, 'Notifications'),(AccountMenuChoice.settings, AppIcons.settings, 'Settings'),(AccountMenuChoice.signOut, AppIcons.logOut, 'Sign out'),];+ bool _shows(AccountMenuChoice choice) => switch (choice) {+ AccountMenuChoice.addPhone || AccountMenuChoice.store => !forPhone,+ AccountMenuChoice.devices => !forPhone && devices,+ _ => true,+ };+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -141,7 +164,7 @@ class AccountMenu extends StatelessWidget {),const AppMenuDivider(),for (final (choice, icon, label) in _rows)- if (!forPhone || choice != AccountMenuChoice.addPhone) ...[+ if (_shows(choice)) ...[// Sign out stands apart from what opens something.if (choice == AccountMenuChoice.signOut)const AppMenuDivider(),diff --git a/desktop/lib/widgets/desktop_workspace_tab.dart b/desktop/lib/widgets/desktop_workspace_tab.dartindex 86e2ccf7f..ade3c2ff0 100644--- a/desktop/lib/widgets/desktop_workspace_tab.dart+++ b/desktop/lib/widgets/desktop_workspace_tab.dart@@ -43,6 +43,7 @@ class DesktopWorkspaceTab extends StatefulWidget {this.activity,this.activityLabel,this.highlighted = false,+ this.attention = false,this.onRename,this.shortcutHint,this.sharedCount,@@ -57,6 +58,10 @@ class DesktopWorkspaceTab extends StatefulWidget {final String id, label;final bool selected, highlighted;++ /// Something there needs the person: the name is bold, and nothing counts+ /// it (Quiet Swarm, screen 0).+ final bool attention;final ValueListenable<bool> showShortcuts;final VoidCallback? onSelect, onClose;final VoidCallback? onRename;@@ -469,9 +474,12 @@ class _DesktopWorkspaceTabState extends State<DesktopWorkspaceTab> {textAlign: TextAlign.center,maxLines: 1,overflow: TextOverflow.ellipsis,- style: DesktopChrome.control(- color: ink,- ),+ style: DesktopChrome.control(color: ink)+ .copyWith(+ fontWeight: widget.attention+ ? grid.AppFont.semibold+ : null,+ ),),),),diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex a13621f6d..6000ed64d 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -2408,6 +2408,9 @@ private final class SwarmTabStrip: NSView {// was before the key existed.phoneButton.isHidden = state["addPhoneVisible"] as? Bool == falsephoneButton.setAccessibilityHidden(phoneButton.isHidden)+ // Absent is shown, as for Add Phone. They moved into the avatar menu.+ storeButton.isHidden = state["storeVisible"] as? Bool == false+ storeButton.setAccessibilityHidden(storeButton.isHidden)// The row's last control: Sign in, or whose account this is. Absent (a// viewer build, teardown), nothing is drawn.let account = state["account"] as? [String: Any]@@ -2440,7 +2443,7 @@ private final class SwarmTabStrip: NSView {children.append(searchButton)if !phoneButton.isHidden { children.append(phoneButton) }if !devicesButton.isHidden { children.append(devicesButton) }- children.append(storeButton)+ if !storeButton.isHidden { children.append(storeButton) }if !accountButton.isHidden { children.append(accountButton) }if !(statusBar.isHidden || passiveFooter) { children.append(statusBar) }setAccessibilityChildren(children)@@ -2460,7 +2463,7 @@ private final class SwarmTabStrip: NSView {control.isEnabled = actionsEnabled}storeButton.font = navigationFont- storeButton.isEnabled = actionsEnabled+ storeButton.isEnabled = actionsEnabled && !storeButton.isHiddendevicesButton.isEnabled = actionsEnabled && !devicesButton.isHiddenaccountButton.isEnabled = actionsEnabled && !accountButton.isHiddensearchButton.foreground = palette.navigationForeground@@ -2563,6 +2566,7 @@ private final class SwarmTabStrip: NSView {tab.selected = id == activeIdtab.keyboardFocus = tabsFocused && id == activeIdtab.actionsEnabled = actionsEnabled+ tab.quiet = row["quiet"] as? Bool == truetab.attention = (row["attention"] as? Int ?? 0) > 0tab.activity = HarnessNativeActivity(row["activity"] as? [String: Any])tab.canShowAgentMessages = row["canShowAgentMessages"] as? Bool == true@@ -2719,7 +2723,7 @@ private final class SwarmTabStrip: NSView {accountButton.frame = NSRect(x: bounds.width - trailing - accountWidth,y: (bounds.height - capsuleHeight) / 2, width: accountWidth, height: capsuleHeight)let actionsEdge = accountButton.isHidden ? bounds.width - trailing : accountButton.frame.minX - 8- let storeWidth = min(storeButton.preferredWidth, max(0, actionsEdge))+ let storeWidth = storeButton.isHidden ? 0 : min(storeButton.preferredWidth, max(0, actionsEdge))storeButton.frame = NSRect(x: actionsEdge - storeWidth,y: (bounds.height - toolHeight) / 2, width: storeWidth, height: toolHeight)let devicesWidth = devicesButton.isHidden ? 0 : devicesButton.preferredWidth@@ -3050,6 +3054,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidativar preferredWidth: CGFloat { Self.maximumLayoutWidth }var selected = false { didSet { if selected != oldValue { invalidateLabel(); updateAccessibility() } } }var attention = false { didSet { if attention != oldValue { invalidateLabel(); updateAccessibility() } } }+ /// A Swarm's tab: its name alone, bold while something there needs you.+ var quiet = false { didSet { if quiet != oldValue { invalidateLabel(); updateAccessibility() } } }var activity: HarnessNativeActivity? {didSet { if activity != oldValue { invalidateLabel(); updateAccessibility() } }}@@ -3061,6 +3067,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati// Keep the old question payload useful for an older Flutter fixture/runner.private var activityLabel: String? { activity?.label ?? (attention ? "Needs your input" : nil) }private var activityMark: String? {+ if quiet { return nil }if let activity { return activity.symbol(frame: activityFrame) }return attention ? "?" : nil}@@ -3266,7 +3273,8 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiparagraph.lineBreakMode = .byTruncatingTailparagraph.alignment = .centerlet label = MeasuredLabel(NSAttributedString(string: displayLabel,- attributes: [.font: labelFont,+ attributes: [.font: quiet && attention+ ? NSFont.systemFont(ofSize: labelFont.pointSize, weight: .semibold) : labelFont,.foregroundColor: foreground, .paragraphStyle: paragraph]))cachedLabel = labelreturn labeldiff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dartindex 7c820ae50..a8e1682a9 100644--- a/desktop/test/add_phone_dialog_test.dart+++ b/desktop/test/add_phone_dialog_test.dart@@ -1318,24 +1318,6 @@ void main() {await tester.pumpWidget(const SizedBox());});- testWidgets('the tab row\'s Add Phone opens the dialog', (tester) async {- final usage = AddPhoneRecorder();- final app = createApp(productMeasurement: usage)- ..status = AppStatus.authenticated;- addTearDown(app.dispose);- await mount(tester, app);- await tester.tap(find.byKey(const ValueKey('swarm-add-phone-button')));- await tester.pump();- await tester.pump(const Duration(milliseconds: 100));- expect(find.byType(AddPhoneDialog), findsOneWidget);- expect(usage.openings, [AddPhoneOpening.titlebar]);-- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pump();- expect(find.byType(AddPhoneDialog), findsNothing);- await tester.pumpWidget(const SizedBox());- });-testWidgets('the account menu\'s Add Phone opens the dialog', (tester,) async {diff --git a/desktop/test/devices_tab_test.dart b/desktop/test/devices_tab_test.dartindex e2e91bd49..4c0fbb63d 100644--- a/desktop/test/devices_tab_test.dart+++ b/desktop/test/devices_tab_test.dart@@ -18,27 +18,21 @@ void main() {newHarnessOpensInBox = composerInBox;addTearDown(() => newHarnessOpensInBox = false);final storage = MemoryStore();- final app = createApp(store: storage);+ final app = createApp(store: storage)+ ..currentUser = const CurrentUserProfile(+ name: 'Dee Example',+ email: '[email protected]',+ );await mount(tester, app);- final button = find.byKey(const ValueKey('swarm-devices-button'));- expect(button, findsOneWidget);+ // In the avatar's menu, not on the bar (Quiet Swarm, screen 0).expect(- tester.getCenter(button).dx,- greaterThan(- tester- .getCenter(find.byKey(const ValueKey('swarm-search-button')))- .dx,- ),+ find.byKey(const ValueKey('swarm-devices-button')),+ findsNothing,);- expect(- tester.getCenter(button).dx,- lessThan(- tester- .getCenter(find.byKey(const ValueKey('swarm-store-button')))- .dx,- ),- );- await tester.tap(button);+ await tester.tap(find.byKey(const ValueKey('swarm-account-button')));+ await tester.pump();+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('account-menu-devices')));await tester.pumpAndSettle();expect(app.activeSwarm.isDevices, isTrue);app.openDevices();diff --git a/desktop/test/quiet_swarm_demo_main.dart b/desktop/test/quiet_swarm_demo_main.dartnew file mode 100644index 000000000..0d4d972cd--- /dev/null+++ b/desktop/test/quiet_swarm_demo_main.dart@@ -0,0 +1,286 @@+// A browser build of the Quiet Swarm screens on made-up data, for the pictures+// Dee looks at before merging (task #2190). Nothing here reaches a server.+//+// flutter build web -t test/quiet_swarm_demo_main.dart+//+// Then serve build/web and open it with ?screen=0|1|8|10|10b|10c|12.+import 'package:dio/dio.dart';+import 'package:flutter/material.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/core/local_key_value_store.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/web/shell/web_chrome.dart';+import 'package:harness/widgets/workspace_account_button.dart';++import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';++const _tabs = ['lampOS', 'strategies', 'autonomous.ai', 'hardware', 'growth'];+const _people = [+ 'ken15',+ 'diego',+ 'dee',+ 'tony',+ 'scholes',+ 'phamngochuy.1989',+];+const _projects = [+ 'computer',+ 'lamp',+ 'openharness',+ 'physical-router',+ 'spaceship',+];+const _machines = [+ ("Diego's Mac", 'diego', true),+ ('Mac 1', 'dee', true),+ ('MacBookPro2021', 'phamngochuy.1989', true),+ ('MacBooks-MacBook-Pro-9', 'scholes', true),+ ('MacBooks-MacBook-Pro-10', 'diego', true),+ ('MacBooks-MacBook-Pro-19', 'tony', true),+ ('MACs-Mac-Studio', 'ken15', true),+ ('Mac 3', 'dee', false),+ ('MacbookPro', 'ken15', false),+];++ConversationServer _swarm(String id, String name) {+ final server = ConversationServer();+ final now = DateTime.now().millisecondsSinceEpoch;+ server.state+ ..['id'] = id+ ..['name'] = name+ ..['ownerId'] = 'ken15'+ ..['swarmBuddy'] = true+ ..['mentionsWaiting'] = id == 'autonomous-ai' ? 3 : 0+ ..['people'] = [+ for (final person in _people)+ {+ 'id': person,+ 'email': '[email protected]',+ 'role': person == 'ken15' ? 'owner' : 'collaborator',+ },+ ]+ ..['projects'] = [+ for (final project in _projects)+ projectFixture(+ project == 'openharness' ? 'lead' : project,+ project,+ project == 'openharness' ? 'lead' : '$project-lead',+ ),+ ]+ ..['machines'] = [+ for (final (machine, owner, online) in _machines)+ {+ 'machineId': machine,+ 'name': machine,+ 'contributorId': owner,+ 'maxAgents': 4,+ 'scope': 'swarm',+ 'observation': {+ // Ahead, so that time passing in the browser leaves it online.+ 'receivedAt': online ? now + 3600000 : now - 3600000,+ 'resources': {'cpuPercent': 20},+ },+ },+ ];+ final groups = server.state['conversations'] as List;+ for (final project in _projects) {+ if (project == 'openharness') continue;+ groups.add({+ 'id': '$project-lead',+ 'title': project,+ 'brief': '',+ 'leadId': null,+ 'archived': false,+ 'agentIds': <String>[],+ 'projectId': project,+ });+ }+ server+ ..append('Prod DB profile: five slow reads to fix.')+ ..append('Three fixes are on main.')+ ..append('ok i like a. let\'s make it perfect.');+ const said = ['ken15', 'ken15', 'diego'];+ for (var i = 0; i < said.length; i++) {+ server.messages[i]['author'] = {+ 'kind': 'person',+ 'id': said[i],+ 'name': said[i],+ };+ }+ server.leaderboard = {+ ...humansSwarm().leaderboard!,+ 'byModel': [+ modelScore('claude', 'claude-opus-5-5', 'high', attempts: 62),+ modelScore('claude', 'claude-sonnet-5-5', 'high', attempts: 21),+ modelScore('codex', 'gpt-6.1-sol', 'high', attempts: 11),+ modelScore('claude', 'deepseek-v4.1', 'high', attempts: 6),+ ],+ };+ return server;+}++class _Memory implements LocalKeyValueStore {+ final values = <String, String>{};+ @override+ Future<String?> read(String key) async => values[key];+ @override+ Future<void> write(String key, String value) async => values[key] = value;+ @override+ Future<void> delete(String key) async => values.remove(key);+}++class _DemoApi extends ApiClient {+ _DemoApi(this.servers, {required super.config, required super.session});+ final Map<String, ConversationServer> servers;++ Response<dynamic> _ok(Object? data) => Response(+ requestOptions: RequestOptions(path: ''),+ statusCode: 200,+ data: {'success': true, 'data': data},+ );++ @override+ Future<Response<dynamic>> superTabCall(+ String method,+ String path, {+ Map<String, dynamic>? body,+ }) async {+ final uri = Uri.parse(path);+ if (uri.path == '/api/super-tabs/list') {+ return _ok({+ 'tabs': [+ for (final id in servers.keys)+ {+ 'id': id,+ 'name': servers[id]!.state['name'],+ 'ownerId': 'ken15',+ // Something in hardware needs the reader: its tab is bold.+ if (id == 'hardware') ...{+ 'mentionsWaiting': 2,+ 'mentionsDigest': 'demo',+ },+ },+ ],+ 'next': null,+ });+ }+ if (uri.path == '/api/super-tabs/deleted') {+ return _ok({'tabs': <dynamic>[]});+ }+ final id = RegExp(r'^/api/super-tabs/([^/]+)/').firstMatch(uri.path);+ final server = servers[id?.group(1)];+ if (server == null) return _ok(<String, dynamic>{});+ return _ok(await server.request(method, path, body: body));+ }+}++/// Presses what has [key] on screen, as a click would.+bool _press(String key) {+ var done = false;+ void visit(Element element) {+ if (done) return;+ final widget = element.widget;+ if (widget.key == ValueKey(key) && widget is InkWell) {+ widget.onTap?.call();+ done = true;+ return;+ }+ if (widget.key == ValueKey(key) && widget is WorkspaceAvatarButton) {+ widget.onPressed?.call();+ done = true;+ return;+ }+ element.visitChildren(visit);+ }++ WidgetsBinding.instance.rootElement?.visitChildren(visit);+ return done;+}++Future<void> _pressWhenThere(String key) async {+ for (var i = 0; i < 100; i++) {+ if (_press(key)) return;+ await Future<void>.delayed(const Duration(milliseconds: 100));+ }+}++Future<void> main() async {+ WidgetsFlutterBinding.ensureInitialized();+ final servers = {+ for (final name in _tabs)+ name.replaceAll('.', '-'): _swarm(name.replaceAll('.', '-'), name),+ };+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+ paneLayoutStore: PaneLayoutStore(storage: _Memory()),+ )..hasNavigationRail = false;+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'This Mac',+ );+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..localOnly = true;+ app.api = _DemoApi(servers, config: AppConfig.dev, session: AuthSession());+ app.status = AppStatus.authenticated;+ app.signedIn = true;+ app.currentUser = const CurrentUserProfile(+ id: 'dee',+ email: '[email protected]',+ );+ app.enterSuperTabs();+ runApp(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: SwarmScreen(+ notifier: app,+ nativeTabs: false,+ // Screen 12 is a Desktop's narrow window, not the web on a phone.+ chrome: Uri.base.queryParameters['screen'] == '12'+ ? null+ : webWorkspaceChrome(app),+ ),+ ),+ );+ app.superTabs.bind('dee');+ try {+ await app.superTabs.refreshTabs().timeout(const Duration(seconds: 3));+ } catch (_) {+ // Whatever it read is drawn.+ }+ final shown = app.swarms.where((s) => s.superTabId == 'autonomous-ai');+ if (shown.isNotEmpty) app.selectSwarm(shown.first.id);+ for (final empty in app.swarms.where((s) => s.superTabId == null).toList()) {+ await app.requestCloseSwarm(empty.id);+ }+ final screen = Uri.base.queryParameters['screen'] ?? '1';+ await Future<void>.delayed(const Duration(seconds: 2));+ switch (screen) {+ case '0m':+ await _pressWhenThere('swarm-account-button');+ case '8':+ await _pressWhenThere('super-swarm-switcher');+ case '10' || '10b' || '10c':+ await _pressWhenThere('super-manage');+ await Future<void>.delayed(const Duration(seconds: 1));+ if (screen == '10b') {+ await _pressWhenThere('super-manage-tab-models');+ await Future<void>.delayed(const Duration(seconds: 3));+ }+ if (screen == '10c') await _pressWhenThere('super-manage-tab-swarm');+ }+}diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dartindex 5df941657..1a8e22013 100644--- a/desktop/test/search_workspace_test.dart+++ b/desktop/test/search_workspace_test.dart@@ -46,18 +46,16 @@ void main() {await mouse.addPointer(location: Offset.zero);var firstHover = true;- Future<void> checkHints(String search, String store) async {+ Future<void> checkHints(String search) async {if (native) {final payload =calls.lastWhere((call) => call.method == 'update').argumentsas Map;expect(payload['searchTooltip'], search);- expect(payload['storeTooltip'], store);+ // Store is in the avatar's menu; the native bar draws none.+ expect(payload['storeVisible'], isFalse);} else {- for (final (key, text) in [- ('swarm-search-button', search),- ('swarm-store-button', store),- ]) {+ for (final (key, text) in [('swarm-search-button', search)]) {await mouse.moveTo(Offset.zero);await tester.pump(const Duration(milliseconds: 300));await mouse.moveTo(tester.getCenter(find.byKey(ValueKey(key))));@@ -76,21 +74,18 @@ void main() {expect(input, isEmpty);}- await checkHints('Open Harness · ⌘P', 'Explore Harness Store · ⌃⌘S');+ await checkHints('Open Harness · ⌘P');map.apply('''{"bindings":[{"keys":"cmd+p","command":null},- {"keys":"cmd+ctrl+s","command":null},- {"keys":"cmd+k","command":"harnesses.list"},- {"keys":"cmd+shift+s","command":"app.store"}+ {"keys":"cmd+k","command":"harnesses.list"}]}''');await tester.pump();- await checkHints('Open Harness · ⌘K', 'Explore Harness Store · ⇧⌘S');+ await checkHints('Open Harness · ⌘K');map.apply('''{"bindings":[- {"keys":"cmd+p","command":null},- {"keys":"cmd+ctrl+s","command":null}+ {"keys":"cmd+p","command":null}]}''');await tester.pump();- await checkHints('Open Harness', 'Explore Harness Store');+ await checkHints('Open Harness');await mouse.removePointer();await tester.pumpWidget(const SizedBox());app.dispose();diff --git a/desktop/test/super_tab_activity_test.dart b/desktop/test/super_tab_activity_test.dartindex 42c5589b6..a38ae7ed1 100644--- a/desktop/test/super_tab_activity_test.dart+++ b/desktop/test/super_tab_activity_test.dart@@ -51,13 +51,11 @@ Future<void> pumpSidebar(listenable: c,builder: (context, _) => ProjectSidebar(controller: c,- onAddAgent: (_) {},needsHuman: (_) => 0,onSelect: c.select,attention: SuperTabAttention.of(c),activity: SuperTabActivity.of(c),onNotifications: () {},- onThreads: () {},),),),@@ -598,7 +596,7 @@ void main() {});});- group('the one # buddy row (#2447) follows the same rules', () {+ group('the one Buddy row (#2447) follows the same rules', () {Future<SuperTabController> show(WidgetTester tester,ConversationServer server,@@ -627,7 +625,7 @@ void main() {final buddyRow = find.byKey(const ValueKey('super-swarm-buddy'));Text buddyName(WidgetTester tester) => tester.widget<Text>(- find.descendant(of: buddyRow, matching: find.text('buddy')),+ find.descendant(of: buddyRow, matching: find.text('Buddy')),);testWidgets('muted: greyed with its mark, never bold; first in the next 'diff --git a/desktop/test/super_tab_attention_shots_test.dart b/desktop/test/super_tab_attention_shots_test.dartindex 8e7c5b176..07c436770 100644--- a/desktop/test/super_tab_attention_shots_test.dart+++ b/desktop/test/super_tab_attention_shots_test.dart@@ -200,7 +200,7 @@ void main() {await mouse.addPointer(location: Offset.zero);await mouse.moveTo(tester.getCenter(- find.byKey(const ValueKey('super-project-toggle-web')),+ find.byKey(const ValueKey('super-group-web-lead')),),);await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_attention_test.dart b/desktop/test/super_tab_attention_test.dartindex 3861662b9..9b8ff89b1 100644--- a/desktop/test/super_tab_attention_test.dart+++ b/desktop/test/super_tab_attention_test.dart@@ -126,7 +126,6 @@ Future<void> pumpSidebar(SuperTabController c,SuperTabAttention attention, {Brightness brightness = Brightness.dark,- bool threadsSelected = false,}) async {await tester.binding.setSurfaceSize(const Size(300, 900));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -138,12 +137,9 @@ Future<void> pumpSidebar(listenable: c,builder: (context, _) => ProjectSidebar(controller: c,- onAddAgent: (_) {},needsHuman: (_) => 0,onSelect: c.select,attention: attention,- onThreads: () {},- threadsSelected: threadsSelected,),),),@@ -227,7 +223,7 @@ void main() {});testWidgets('a tag in a reply that lives only in a thread counts on '- 'Threads, not on the project row', (tester) async {+ 'its thread, not on the project row', (tester) async {final server = projectServer();server.followedThreads = {'unread': [unreadThread('message-1', 2, conversationId: 'lead')],@@ -237,7 +233,7 @@ void main() {server.tag('message-1', threadId: 'message-1');final (c, attention) = await opened(server);await pumpSidebar(tester, c, attention);- expect(inRow('super-threads', find.text('1')), findsOneWidget);+ expect(attention.threadMentions, 1);expect(inRow('super-group-lead', find.byType(SuperTabCountBadge)),findsNothing,@@ -307,8 +303,8 @@ void main() {findsOneWidget,);expect(inRow('super-group-offline', find.text('2')), findsOneWidget);- // Threads carries the tag inside a thread.- expect(inRow('super-threads', find.text('1')), findsOneWidget);+ // The tag inside a thread is counted apart from the row.+ expect(attention.threadMentions, 1);// The project chat: unread, nothing for the reader, so no number.expect(inRow('super-group-lead', find.byType(SuperTabCountBadge)),@@ -400,52 +396,31 @@ void main() {);expect(unread.style?.color, DesktopChrome.foreground);expect(unread.style?.fontWeight, grid.AppFont.semibold);- // Threads: a followed thread has new replies.- final threads = rowText(tester, 'super-threads', 'Threads');- expect(threads.style?.color, DesktopChrome.foreground);- expect(threads.style?.fontWeight, grid.AppFont.semibold);await close(tester, c);});}-- testWidgets('Threads is muted with nothing new', (tester) async {- final server = projectServer();- server.followedThreads = {- 'unread': [],- 'read': [readThread('message-1', 2)],- 'more': false,- };- final c = await openHere(server);- final attention = SuperTabAttention.of(c);- await attention.load();- await pumpSidebar(tester, c, attention);- final threads = rowText(tester, 'super-threads', 'Threads');- expect(threads.style?.color, DesktopChrome.muted);- expect(threads.style?.fontWeight, isNot(grid.AppFont.semibold));- await close(tester, c);- });});- testWidgets('a project row lights whole on hover, chevron included, as wide '- 'as its selected highlight', (tester) async {+ testWidgets('a project row lights whole on hover, as wide as its selected '+ 'highlight', (tester) async {final server = projectServer();server.followedThreads = {'unread': [], 'read': [], 'more': false};final c = await openHere(server);final attention = SuperTabAttention.of(c);c.select('offline');await pumpSidebar(tester, c, attention);- final toggle = find.byKey(const ValueKey('super-project-toggle-lead'));+ final row = find.byKey(const ValueKey('super-group-lead'));final groundFinder = find- .ancestor(of: toggle, matching: find.byType(Material))+ .ancestor(of: row, matching: find.byType(Material)).first;Material ground() => tester.widget<Material>(groundFinder);expect(ground().color, Colors.transparent);final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);addTearDown(mouse.removePointer);await mouse.addPointer(location: Offset.zero);- await mouse.moveTo(tester.getCenter(toggle));+ await mouse.moveTo(tester.getRect(row).centerRight - const Offset(4, 0));await tester.pumpAndSettle();- // The whole row's ground, the one that holds the chevron too.+ // The whole row's ground, out to its end.expect(ground().color, grid.AppSurface.hoverFill);await mouse.moveTo(tester.getCenter(inRow('super-group-lead', find.text('web-project'))),@@ -453,7 +428,7 @@ void main() {await tester.pumpAndSettle();expect(ground().color, grid.AppSurface.hoverFill);final hovered = tester.getRect(groundFinder);- expect(hovered.right, greaterThanOrEqualTo(tester.getRect(toggle).right));+ expect(hovered.right, greaterThanOrEqualTo(tester.getRect(row).right));c.select('lead');await tester.pumpAndSettle();expect(ground().color, grid.AppSurface.selectedFill);@@ -660,26 +635,6 @@ void main() {expect(attention.threadMentions, 0);});- testWidgets('the sidebar Threads row shows no number for a tag in a '- 'thread the list leaves out, the very case of an empty list', (- tester,- ) async {- final server = projectServer();- server.followedThreads = {'unread': [], 'read': [], 'more': true};- server.tag('message-1', threadId: 'message-1', messageSequence: 2);- final c = await openHere(server);- final attention = SuperTabAttention.of(c);- await attention.mentions.load();- await attention.load();- await pumpSidebar(tester, c, attention);- expect(- inRow('super-threads', find.byType(SuperTabCountBadge)),- findsNothing,- );- expect(inRow('super-threads', find.text('1')), findsNothing);- await close(tester, c);- });-test('a tag in a thread the reader unfollowed (never listed) counts ''nothing; in a thread the list shows it counts', () async {final server = projectServer();diff --git a/desktop/test/super_tab_attention_wave2_test.dart b/desktop/test/super_tab_attention_wave2_test.dartindex e03a80382..faf35c71a 100644--- a/desktop/test/super_tab_attention_wave2_test.dart+++ b/desktop/test/super_tab_attention_wave2_test.dart@@ -270,7 +270,7 @@ void main() {if (c.unreadShown(c.snapshot!.conversation(id)!)) id,];expect(order, isNot(contains('roster')));- await tester.tap(find.byKey(const ValueKey('super-group-lead')));+ await tester.tap(find.byKey(const ValueKey('super-message-composer')));await tester.pumpAndSettle();await _keys(tester, [LogicalKeyboardKey.altLeft,@@ -340,7 +340,7 @@ void main() {final (c, _) = await _show(tester, Brightness.dark);final unread = c.snapshot!.conversations.where(c.unreadShown).length;expect(unread, greaterThan(1));- await tester.tap(find.byKey(const ValueKey('super-group-web-lead')));+ await tester.tap(find.byKey(const ValueKey('super-message-composer')));await tester.pumpAndSettle();await _keys(tester, [LogicalKeyboardKey.shiftLeft,diff --git a/desktop/test/super_tab_buddy_chat_counts_test.dart b/desktop/test/super_tab_buddy_chat_counts_test.dartindex 95cd0f72d..a4605c1ea 100644--- a/desktop/test/super_tab_buddy_chat_counts_test.dart+++ b/desktop/test/super_tab_buddy_chat_counts_test.dart@@ -758,11 +758,16 @@ void main() {);expect(tab['attention'], 2);} else {+ // A Swarm's tab is its name, bold when something there waits, with+ // no count (Quiet Swarm, screen 0).+ expect(find.byKey(ValueKey('tab-tags:${swarm.id}')), findsNothing);+ expect(find.byKey(ValueKey('tab-activity:${swarm.id}')), findsNothing);expect(tester- .widget<Text>(find.byKey(ValueKey('tab-tags:${swarm.id}')))- .data,- '2',+ .widget<Text>(find.byKey(ValueKey('tab-label:${swarm.id}')))+ .style+ ?.fontWeight,+ grid.AppFont.semibold,);}await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/super_tab_chat_test.dart b/desktop/test/super_tab_chat_test.dartindex 0b56daf6d..b5ed9302b 100644--- a/desktop/test/super_tab_chat_test.dart+++ b/desktop/test/super_tab_chat_test.dart@@ -392,7 +392,7 @@ void main() {?.fontWeight;expect(c.unread(c.selected!), isFalse);expect(projectWeight(), grid.AppFont.semibold);- await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-group-offline')));await tester.pumpAndSettle();diff --git a/desktop/test/super_tab_closed_groups_test.dart b/desktop/test/super_tab_closed_groups_test.dartindex decd8f44e..5d91ad55d 100644--- a/desktop/test/super_tab_closed_groups_test.dart+++ b/desktop/test/super_tab_closed_groups_test.dart@@ -107,9 +107,7 @@ void main() {final sidebar = find.byType(ProjectSidebar);Finder inside(Finder f) => find.descendant(of: sidebar, matching: f);if (closedRow.evaluate().isEmpty) {- await tester.tap(- find.byKey(const ValueKey('super-project-toggle-lead')),- );+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();}@@ -188,9 +186,7 @@ void main() {await tester.pumpWidget(_app(server, controller));await tester.pumpAndSettle();if (closedRow.evaluate().isEmpty) {- await tester.tap(- find.byKey(const ValueKey('super-project-toggle-lead')),- );+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();}expect(find.text('Closed (1)'), findsOneWidget);diff --git a/desktop/test/super_tab_devices_preview_test.dart b/desktop/test/super_tab_devices_preview_test.dartindex 068ca3b6c..c6b3c24b6 100644--- a/desktop/test/super_tab_devices_preview_test.dart+++ b/desktop/test/super_tab_devices_preview_test.dart@@ -110,8 +110,14 @@ Future<void> _dispose(}void main() {- for (final kind in ['web', 'Finder']) {- testWidgets('$kind viewer survives repeated Devices round trips', (+ for (final (kind, viaManage) in [+ ('web', true),+ ('Finder', true),+ ('web', false),+ ('Finder', false),+ ]) {+ final way = viaManage ? 'Manage' : "the avatar's menu";+ testWidgets('$kind viewer survives repeated Devices round trips, by $way', (tester,) async {final finder = kind == 'Finder';@@ -136,7 +142,16 @@ void main() {expectPreview();for (var visit = 0; visit < 2; visit++) {- await tester.tap(find.byKey(const ValueKey('super-your-devices')));+ if (viaManage) {+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ await tester.tap(+ find.byKey(const ValueKey('super-manage-tab-devices')),+ );+ } else {+ // What the avatar's menu does.+ f.app.openDevices();+ }await tester.pumpAndSettle();expect(c.devicesSelected, isTrue);expect(f.app.activeSwarm, same(tab));diff --git a/desktop/test/super_tab_devices_test.dart b/desktop/test/super_tab_devices_test.dartindex bb40f8a8e..4203c049f 100644--- a/desktop/test/super_tab_devices_test.dart+++ b/desktop/test/super_tab_devices_test.dart@@ -7,6 +7,7 @@ import 'package:harness/devices/devices_harness_controller.dart';import 'package:harness/devices/devices_screen.dart';import 'package:harness/state/pane_arrangement.dart';import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/manage_page.dart';import 'package:harness/super_tabs/workspace.dart';import 'package:harness/widgets/pane_grid.dart';@@ -117,7 +118,9 @@ void main() {? find.byType(TextField).last: field;await tester.enterText(composer, 'An unfinished project message');- await tester.tap(find.byKey(const ValueKey('super-your-devices')));+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-manage-tab-devices')));await tester.pumpAndSettle();expect(f.app.activeSwarm, same(tab));expect(f.app.swarms.map((s) => s.id), before);@@ -136,7 +139,7 @@ void main() {final center = tester.getRect(find.byType(PaneGrid));expect(bounds.left, closeTo(center.left, 2));expect(bounds.right, closeTo(center.right, 2));- await tester.tap(find.byKey(const ValueKey('super-your-devices')));+ await tester.tap(find.byKey(const ValueKey('super-manage-tab-devices')));await tester.pumpAndSettle();expect(tab.panes.single, same(viewer));await tester.tap(find.byKey(const ValueKey('super-group-lead')));@@ -144,6 +147,8 @@ void main() {expect(c.devicesSelected, isFalse);expect(f.app.activeSwarm, same(tab));expect(find.byType(DevicesScreen), findsNothing);+ // A project's row leaves Manage for its chat.+ expect(find.byType(SuperTabManageTabs), findsNothing);expect(find.text('An unfinished project message'), findsOneWidget);expect(f.connection.calls.where(diff --git a/desktop/test/super_tab_manage_page_test.dart b/desktop/test/super_tab_manage_page_test.dartnew file mode 100644index 000000000..898156660--- /dev/null+++ b/desktop/test/super_tab_manage_page_test.dart@@ -0,0 +1,250 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/manage_page.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/humans_fixture.dart';+import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// Manage (docs/plans/2026-11-02-quiet-swarm-design.md, screens 10, 10b, 10c).+void main() {+ Future<({SuperTabController c, ConversationServer server})> show(+ WidgetTester tester, {+ SuperTabManageTab tab = SuperTabManageTab.machines,+ String account = 'owner',+ void Function(ConversationServer server)? setUp,+ bool devices = true,+ }) async {+ final server = ConversationServer();+ server.state['machines'] = [+ {+ 'machineId': 'm1',+ 'name': 'Mac Studio',+ 'contributorId': 'owner',+ 'maxAgents': 4,+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'resources': {'cpuPercent': 1},+ },+ },+ {+ 'machineId': 'm2',+ 'name': 'Old Mac',+ 'contributorId': 'owner',+ 'maxAgents': 4,+ 'observation': {'receivedAt': 1000, 'resources': <String, dynamic>{}},+ },+ ];+ setUp?.call(server);+ final c = server.controller(account: account);+ await c.refresh();+ final AppNotifier app = createApp();+ addTearDown(app.dispose);+ var current = tab;+ await tester.binding.setSurfaceSize(const Size(800, 700));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: StatefulBuilder(+ builder: (context, update) => Column(+ children: [+ SuperTabManageTabs(+ selected: current,+ devices: devices,+ onChoose: (next) => update(() => current = next),+ ),+ Expanded(+ child: SuperTabManagePage(+ controller: c,+ app: app,+ tab: current,+ onAddAgent: (_) {},+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ addTearDown(() async {+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ });+ return (c: c, server: server);+ }++ testWidgets('its four tabs, Devices only where this build has them', (+ tester,+ ) async {+ await show(tester);+ for (final label in const ['Machines', 'Models', 'Devices', 'Swarm']) {+ expect(find.text(label), findsOneWidget, reason: label);+ }+ await tester.tap(find.text('Swarm'));+ await tester.pump();+ expect(find.text('Owner'), findsOneWidget);+ });++ testWidgets('without devices there is no Devices tab', (tester) async {+ await show(tester, devices: false);+ expect(find.text('Devices'), findsNothing);+ });++ group('Machines', () {+ testWidgets('one line each: name, owner, status', (tester) async {+ await show(tester);+ final row = find.byKey(const ValueKey('super-machine-entry-m1'));+ expect(+ find.descendant(of: row, matching: find.text('Mac Studio')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: row, matching: find.text('online')),+ findsOneWidget,+ );+ expect(+ find.descendant(+ of: find.byKey(const ValueKey('super-machine-entry-m2')),+ matching: find.text('offline'),+ ),+ findsOneWidget,+ );+ expect(tester.getSize(row).height, lessThanOrEqualTo(44));+ });++ testWidgets('has Add machine, and no Machines heading of its own', (+ tester,+ ) async {+ await show(tester);+ expect(find.text('Add machine'), findsOneWidget);+ expect(find.byTooltip('Add machine'), findsNothing);+ });+ });++ group('Models', () {+ testWidgets('has Your models', (tester) async {+ await show(tester, tab: SuperTabManageTab.models);+ expect(find.text('Your models…'), findsOneWidget);+ });+ });++ group('Swarm', () {+ testWidgets('says its name, owner and people, with Manage people', (+ tester,+ ) async {+ final s = await show(tester, tab: SuperTabManageTab.swarm);+ expect(find.text(s.c.snapshot!.name), findsOneWidget);+ expect(find.text('Name'), findsOneWidget);+ expect(find.text('Owner'), findsOneWidget);+ expect(find.text('People'), findsOneWidget);+ expect(find.text('${s.c.snapshot!.people.length}'), findsOneWidget);+ expect(find.text('Manage people'), findsOneWidget);+ });++ testWidgets('its owner can delete it, and cannot leave', (tester) async {+ await show(tester, tab: SuperTabManageTab.swarm);+ expect(find.text('Delete Swarm…'), findsOneWidget);+ expect(find.text('Leave Swarm…'), findsNothing);+ });++ testWidgets('a member can leave it, and cannot delete it', (tester) async {+ await show(+ tester,+ tab: SuperTabManageTab.swarm,+ account: 'member',+ setUp: (server) => (server.state['people'] as List).add({+ 'id': 'member',+ 'email': '[email protected]',+ 'role': 'collaborator',+ 'generation': 'g',+ }),+ );+ expect(find.text('Leave Swarm…'), findsOneWidget);+ expect(find.text('Delete Swarm…'), findsNothing);+ });+ });++ group('while Manage shows', () {+ Future<SuperTabController> inView(+ WidgetTester tester,+ List<String> opened,+ ValueNotifier<bool> terminals,+ ) async {+ final server = humansSwarm();+ final c = server.controller();+ await c.refresh();+ await tester.binding.setSurfaceSize(const Size(1300, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: ValueListenableBuilder(+ valueListenable: terminals,+ builder: (context, shown, _) => SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (agent) => opened.add(agent.id),+ machineName: (_) => 'Mac Studio',+ terminalsVisible: shown,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-manage-tab-machines')), findsOne);+ return c;+ }++ Future<void> close(WidgetTester tester, SuperTabController c) async {+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ c.dispose();+ }++ testWidgets('a terminal that opens takes the place of the Manage page', (+ tester,+ ) async {+ final terminals = ValueNotifier(false);+ final c = await inView(tester, [], terminals);+ terminals.value = true;+ await tester.pumpAndSettle();+ expect(+ find.byKey(const ValueKey('super-manage-tab-machines')),+ findsNothing,+ );+ await close(tester, c);+ });++ testWidgets('an agent clicked in the right column leaves it', (+ tester,+ ) async {+ final opened = <String>[];+ final terminals = ValueNotifier(false);+ final c = await inView(tester, opened, terminals);+ final agent = c.snapshot!.agents.first;+ await tester.longPress(find.byKey(ValueKey('super-member-${agent.id}')));+ await tester.pumpAndSettle();+ await tester.tap(find.widgetWithText(FilledButton, 'Open terminal'));+ await tester.pumpAndSettle();+ expect(opened, [agent.id]);+ expect(+ find.byKey(const ValueKey('super-manage-tab-machines')),+ findsNothing,+ );+ await close(tester, c);+ });+ });+}diff --git a/desktop/test/super_tab_members_list_test.dart b/desktop/test/super_tab_members_list_test.dartindex f8297209d..dae9b1d34 100644--- a/desktop/test/super_tab_members_list_test.dart+++ b/desktop/test/super_tab_members_list_test.dart@@ -247,11 +247,20 @@ void main() {);await tester.pumpAndSettle();expect(tester.takeException(), isNull);- for (final number in ['21', '87%']) {+ void holdsWhole(String number) {expect(find.text(number), findsOneWidget, reason: number);final paragraph = tester.renderObject<RenderParagraph>(find.text(number));expect(paragraph.didExceedMaxLines, isFalse, reason: number);}++ holdsWhole('21');+ // The models' shares are in Manage › Models.+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-manage-tab-models')));+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ holdsWhole('87%');await close(tester, controller);});}diff --git a/desktop/test/super_tab_mentions_test.dart b/desktop/test/super_tab_mentions_test.dartindex 3adcc75a0..25fc83127 100644--- a/desktop/test/super_tab_mentions_test.dart+++ b/desktop/test/super_tab_mentions_test.dart@@ -1408,11 +1408,16 @@ void main() {);expect(tab['attention'], 2);} else {+ // A Swarm's tab is its name, bold when something there waits, with+ // no count (Quiet Swarm, screen 0).+ expect(find.byKey(ValueKey('tab-tags:${swarm.id}')), findsNothing);+ expect(find.byKey(ValueKey('tab-activity:${swarm.id}')), findsNothing);expect(tester- .widget<Text>(find.byKey(ValueKey('tab-tags:${swarm.id}')))- .data,- '2',+ .widget<Text>(find.byKey(ValueKey('tab-label:${swarm.id}')))+ .style+ ?.fontWeight,+ grid.AppFont.semibold,);}await tester.pumpWidget(const SizedBox());diff --git a/desktop/test/super_tab_new_messages_test.dart b/desktop/test/super_tab_new_messages_test.dartindex 0168889c4..4016ceac2 100644--- a/desktop/test/super_tab_new_messages_test.dart+++ b/desktop/test/super_tab_new_messages_test.dart@@ -730,7 +730,7 @@ void main() {.text.style?.fontWeight;- await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();expect(weight(), grid.AppFont.semibold);// Read on another device.diff --git a/desktop/test/super_tab_one_buddy_test.dart b/desktop/test/super_tab_one_buddy_test.dartindex 7bd5c7a98..344d6c5c9 100644--- a/desktop/test/super_tab_one_buddy_test.dart+++ b/desktop/test/super_tab_one_buddy_test.dart@@ -9,7 +9,7 @@ import 'support/buddy_fixture.dart';import 'support/super_tab_fixture.dart';/// One Buddy per person per Swarm (Dee, 10-31; spec-/// 2026-10-31-one-buddy-per-swarm): `# buddy` is the first row under+/// 2026-10-31-one-buddy-per-swarm): `Buddy` is the row over/// Projects, with no Buddies section; New session picks a project; older/// project Buddy chats read only.void main() {@@ -135,40 +135,45 @@ void main() {});group('the sidebar', () {- testWidgets('shows # buddy first under Projects and no Buddies section', (- tester,- ) async {- final server = oneBuddySwarm();- giveSwarmBuddy(server);- final c = await show(tester, server);+ testWidgets(+ 'shows Buddy above Projects, with no # and no Buddies section',+ (tester) async {+ final server = oneBuddySwarm();+ giveSwarmBuddy(server);+ final c = await show(tester, server);- expect(buddyRow, findsOneWidget);- expect(- find.descendant(of: buddyRow, matching: find.text('buddy')),- findsOneWidget,- );- expect(titles(tester), isNot(contains('Buddies')));- expect(titles(tester), contains('Projects'));- // First under Projects: above every project's row.- final projectsHeading = tester.getBottomLeft(find.text('Projects')).dy;- final top = tester.getTopLeft(buddyRow).dy;- expect(top, greaterThan(projectsHeading));- expect(- top,- lessThan(- tester- .getTopLeft(find.byKey(const ValueKey('super-project-lead')))- .dy,- ),- );+ expect(buddyRow, findsOneWidget);+ expect(+ find.descendant(of: buddyRow, matching: find.text('Buddy')),+ findsOneWidget,+ );+ expect(+ find.descendant(of: buddyRow, matching: find.text('#')),+ findsNothing,+ );+ expect(titles(tester), isNot(contains('Buddies')));+ expect(titles(tester), contains('Projects'));+ // Over Projects' heading, so over every project's row (Quiet Swarm,+ // screen 1).+ final projectsHeading = tester.getTopLeft(find.text('Projects')).dy;+ expect(tester.getBottomLeft(buddyRow).dy, lessThan(projectsHeading));+ expect(+ projectsHeading,+ lessThan(+ tester+ .getTopLeft(find.byKey(const ValueKey('super-project-lead')))+ .dy,+ ),+ );- await tester.tap(buddyRow);- await tester.pumpAndSettle();- expect(c.selectedId, 'swarm-buddy-peer');- // Its chat says it reads every project, and only its person reads it.- expect(find.textContaining('reads all your projects'), findsOneWidget);- await close(tester, c);- });+ await tester.tap(buddyRow);+ await tester.pumpAndSettle();+ expect(c.selectedId, 'swarm-buddy-peer');+ // Its chat says it reads every project, and only its person reads it.+ expect(find.textContaining('reads all your projects'), findsOneWidget);+ await close(tester, c);+ },+ );testWidgets('opens the one Buddy chat on the server before any Buddy, from the row',diff --git a/desktop/test/super_tab_picker_test.dart b/desktop/test/super_tab_picker_test.dartindex b26c674b5..5f77b9836 100644--- a/desktop/test/super_tab_picker_test.dart+++ b/desktop/test/super_tab_picker_test.dart@@ -14,7 +14,7 @@ import 'package:harness/shortcuts/app_keymap.dart';import 'package:harness/state/harness_placement.dart';import 'package:harness/state/new_harness.dart';import 'package:harness/state/swarm_catalog.dart';-import 'package:harness/super_tabs/project_sidebar.dart';+import 'package:harness/super_tabs/manage_page.dart';import 'package:harness/widgets/desktop_chrome.dart';import 'package:harness/widgets/new_harness_form.dart';import 'package:harness/widgets/swarm_switcher.dart';@@ -126,16 +126,20 @@ void main() {final machine = find.byKey(const ValueKey('super-machine-teammate-machine'),);- if (machine.evaluate().isEmpty &&+ // Machines are in Manage. A narrow window has the sidebar behind a button.+ final manage = find.byKey(const ValueKey('super-manage'));+ if (manage.evaluate().isEmpty &&find.byTooltip('Conversations').evaluate().isNotEmpty) {await tester.tap(find.byTooltip('Conversations'));await tester.pumpAndSettle();}- // The sidebar builds only the rows near its view: at a large text size the- // Machines group starts below it.- final sidebar = find+ await tester.tap(manage);+ await tester.pumpAndSettle();+ // The page builds only the rows near its view: at a large text size they+ // may start below it.+ final page = find.descendant(- of: find.byType(ProjectSidebar),+ of: find.byType(SuperTabManagePage),matching: find.byType(Scrollable),).first;@@ -146,7 +150,7 @@ void main() {i < 50 && machine.evaluate().isEmpty && offline.evaluate().isEmpty;i++) {- await tester.drag(sidebar, const Offset(0, -100));+ await tester.drag(page, const Offset(0, -100));await tester.pumpAndSettle();}if (machine.evaluate().isEmpty && offline.evaluate().isNotEmpty) {diff --git a/desktop/test/super_tab_polish_test.dart b/desktop/test/super_tab_polish_test.dartindex 3958443c5..de60ea1c5 100644--- a/desktop/test/super_tab_polish_test.dart+++ b/desktop/test/super_tab_polish_test.dart@@ -12,7 +12,6 @@ import 'package:harness/core/open_in_browser.dart';import 'package:harness/super_tabs/message_text.dart';import 'package:harness/super_tabs/model.dart';import 'package:harness/super_tabs/recording_notice.dart';-import 'package:harness/super_tabs/project_sidebar.dart';import 'package:harness/super_tabs/view.dart';import 'support/super_tab_fixture.dart';@@ -386,28 +385,23 @@ void main() {await tester.pumpAndSettle();await tester.tap(find.byTooltip('Conversations'));await tester.pumpAndSettle();- // Below the pinned Chat with PM and the projects, a scroll away.- await tester.scrollUntilVisible(- find.text('Machines'),- 100,- scrollable: find- .descendant(- of: find.byType(ProjectSidebar),- matching: find.byType(Scrollable),- )- .first,+ // Manage, where the machines are, stands at the foot however long+ // the list: no scroll away.+ expect(+ find.byKey(const ValueKey('super-manage')).hitTestable(),+ findsOneWidget,);- expect(find.text('Machines'), findsOneWidget);expect(tester.takeException(), isNull);await shot('-projects');expect(tester.takeException(), isNull);} else {- expect(find.text('Machines'), findsOneWidget);expect(find.text('Projects'), findsOneWidget);- // The Machines group lives beside Projects in the left sidebar.+ // Manage's row starts where the project rows do.expect(- tester.getTopLeft(find.text('Machines')).dx,- tester.getTopLeft(find.text('Projects')).dx,+ tester.getTopLeft(find.byKey(const ValueKey('super-manage'))).dx,+ tester+ .getTopLeft(find.byKey(const ValueKey('super-group-lead')))+ .dx,);}// Capture one row treatment across disclosure, label and nested work.diff --git a/desktop/test/super_tab_quiet_sidebar_test.dart b/desktop/test/super_tab_quiet_sidebar_test.dartnew file mode 100644index 000000000..2508da27f--- /dev/null+++ b/desktop/test/super_tab_quiet_sidebar_test.dart@@ -0,0 +1,158 @@+import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/state/app_state.dart';+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/project_sidebar.dart';++import 'support/super_tab_fixture.dart';+import 'swarm_state_test.dart' show createApp;++/// The design's sidebar (docs/plans/2026-11-02-quiet-swarm-design.md, screen+/// 1): the Swarm, Activity, Buddy, Projects with its +, and Manage at the foot.+void main() {+ Future<SuperTabController> show(+ WidgetTester tester, {+ VoidCallback? onNewProject,+ VoidCallback? onManage,+ bool manageSelected = false,+ }) async {+ final server = ConversationServer();+ server.state['swarmBuddy'] = true;+ server.state['projects'] = [projectFixture('lead', 'openharness', 'lead')];+ final c = server.controller();+ await c.refresh();+ final AppNotifier app = createApp();+ addTearDown(app.dispose);+ await tester.binding.setSurfaceSize(const Size(280, 800));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: ProjectSidebar(+ controller: c,+ app: app,+ needsHuman: (_) => 0,+ onSelect: c.select,+ onNewSwarm: () {},+ onNewProject: onNewProject ?? () {},+ onNotifications: () {},+ onManage: onManage ?? () {},+ manageSelected: manageSelected,+ ),+ ),+ ),+ );+ await tester.pump();+ addTearDown(() async {+ await tester.pumpWidget(const SizedBox());+ c.dispose();+ });+ return c;+ }++ double top(WidgetTester tester, String key) =>+ tester.getTopLeft(find.byKey(ValueKey(key))).dy;++ testWidgets('its rows, in the design\'s order', (tester) async {+ await show(tester);+ final order = [+ 'super-swarm-switcher',+ 'super-activity',+ 'super-swarm-buddy',+ 'project-sidebar-projects',+ 'super-project-lead',+ 'super-manage',+ ];+ for (var i = 1; i < order.length; i++) {+ expect(+ top(tester, order[i - 1]),+ lessThan(top(tester, order[i])),+ reason: '${order[i - 1]} over ${order[i]}',+ );+ }+ expect(find.text('Buddy'), findsOneWidget);+ });++ testWidgets('none of what moved', (tester) async {+ await show(tester);+ for (final label in const [+ 'New project',+ 'Your devices',+ 'Your models',+ 'Threads',+ 'Machines',+ 'Models',+ ]) {+ expect(find.text(label), findsNothing, reason: label);+ }+ });++ testWidgets('Manage stands at the foot, however short the list', (+ tester,+ ) async {+ await show(tester);+ expect(+ tester.getBottomLeft(find.byKey(const ValueKey('super-manage'))).dy,+ greaterThan(800 - 60),+ );+ });++ testWidgets('Manage opens, and shows when open', (tester) async {+ var opened = 0;+ await show(tester, onManage: () => opened++);+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ expect(opened, 1);+ });++ testWidgets('while Manage shows, no project row is the open one', (+ tester,+ ) async {+ await show(tester, manageSelected: true);+ final row = tester.widget<Semantics>(+ find+ .ancestor(+ of: find.byKey(const ValueKey('super-manage')),+ matching: find.byType(Semantics),+ )+ .first,+ );+ expect(row.properties.selected, isTrue);+ });++ testWidgets(+ 'a project row has no chevron; a second click shows its workgroups',+ (tester) async {+ final c = await show(tester);+ expect(+ find.byKey(const ValueKey('super-project-toggle-lead')),+ findsNothing,+ );+ await c.select('lead');+ await tester.pump();+ expect(c.expandedProjects, isNot(contains('lead')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));+ await tester.pump();+ expect(c.expandedProjects, contains('lead'));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));+ await tester.pump();+ expect(c.expandedProjects, isNot(contains('lead')));+ await tester.pump(const Duration(seconds: 1));+ },+ );++ testWidgets('+ beside Projects is New project, the same action', (+ tester,+ ) async {+ var opened = 0;+ await show(tester, onNewProject: () => opened++);+ await tester.tap(+ find.descendant(+ of: find.byKey(const ValueKey('project-sidebar-projects')),+ matching: find.byTooltip('New project'),+ ),+ );+ expect(opened, 1);+ });+}diff --git a/desktop/test/super_tab_sidebar_cleanup_test.dart b/desktop/test/super_tab_sidebar_cleanup_test.dartindex 4fac88954..8d5383aff 100644--- a/desktop/test/super_tab_sidebar_cleanup_test.dart+++ b/desktop/test/super_tab_sidebar_cleanup_test.dart@@ -79,18 +79,18 @@ Future<void> closeSwarm(WidgetTester tester, SuperTabController c) async {void main() {// Slack's Activity takes Notifications' place on every platform (Lead,- // 10-31), and takes in Threads (Quiet Swarm): on a Mac too, beside the menu- // bar and the Dock.+ // 10-31), and takes in Threads: on a Mac too, beside the menu bar and the+ // Dock. The rest moved+ // into Manage, at the foot (Quiet Swarm, screen 1).for (final platform in [TargetPlatform.macOS, TargetPlatform.linux]) {- testWidgets('the top reads New project, Your devices, Your models, '- 'Activity with its count', (tester) async {+ testWidgets('the top reads Activity with its count, and Manage is at the '+ 'foot', (tester) async {final c = await showSwarm(tester);- expect(topRows(tester), [- 'New project',- 'Your devices',- 'Your models',- 'Activity3',- ]);+ expect(topRows(tester), ['Activity3']);+ expect(+ tester.getTopLeft(find.byKey(const ValueKey('super-manage'))).dy,+ greaterThan(tester.getTopLeft(find.text('Projects')).dy),+ );expect(find.text('Notifications'), findsNothing);expect(tester.takeException(), isNull);await closeSwarm(tester, c);diff --git a/desktop/test/super_tab_sidebar_models_test.dart b/desktop/test/super_tab_sidebar_models_test.dartindex 9cc922643..755340b4e 100644--- a/desktop/test/super_tab_sidebar_models_test.dart+++ b/desktop/test/super_tab_sidebar_models_test.dart@@ -1,4 +1,3 @@-import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;@@ -9,18 +8,29 @@ import 'package:harness/widgets/engine_identity.dart';import 'support/humans_fixture.dart';import 'support/super_tab_fixture.dart';-/// Models in the left sidebar, after Machines (Dee, 2026-10-29 and 10-30):+/// Manage › Models (Quiet Swarm, screen 10b; Dee, 2026-10-29 and 10-30):/// every model by its exact name with its share of the agents' tasks of the/// last 7 days, largest first, rounded so the rows add up to 100%, behind its/// engine's icon. A record with no reported model is not listed and not in-/// the shares (Scholes, 2026-11-02). Its chevron collapses it like every other section; the+/// the shares (Scholes, 2026-11-02). The/// counts and first-review pass rate are in words on hover and for a screen/// reader.void main() {+ /// Manage's Models. Its Your models action says the page is there, so that a+ /// test finding no model rows is not looking at another page.+ Future<void> openModels(WidgetTester tester) async {+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-manage-tab-models')));+ await tester.pumpAndSettle();+ expect(find.byKey(const ValueKey('super-local-models')), findsOneWidget);+ }+Future<SuperTabController> show(WidgetTester tester,ConversationServer server, {Map<String, dynamic>? initial,+ bool openManage = true,}) async {await tester.binding.setSurfaceSize(const Size(1300, 1400));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -46,6 +56,7 @@ void main() {),);await tester.pumpAndSettle();+ if (openManage) await openModels(tester);return controller;}@@ -56,10 +67,6 @@ void main() {}final heading = find.byKey(const ValueKey('super-models-heading'));- final headingText = find.descendant(- of: heading,- matching: find.text('Models'),- );Finder row(String name) => find.byKey(ValueKey('super-model-$name'));final rows = find.byWidgetPredicate((w) =>@@ -95,22 +102,12 @@ void main() {}testWidgets(- 'is headed Models, says on hover it is the last 7 days, and lists every model largest first after Machines',+ 'has no heading of its own under the Models tab, says on hover it is the last 7 days, and lists every model largest first',(tester) async {final controller = await show(tester, modelsSwarm());- expect(headingText, findsOneWidget);+ expect(heading, findsNothing);expect(find.textContaining('this week'), findsNothing);- // The chevron says what it does, as every section's does; the title- // says what the shares are.- expect(find.byTooltip('Collapse Models'), findsOneWidget);- expect(- find.byTooltip('Share of agent work, last 7 days'),- findsOneWidget,- );- expect(- tester.getTopLeft(heading).dy,- greaterThan(tester.getTopLeft(find.text('Machines')).dy),- );+ expect(find.byTooltip(RegExp('in the last 7 days')), findsNWidgets(3));// 97 tasks of named models (the fixture's 3 with no model are left// out): no Other row, the rest add up to 100.expect(names(tester), ['Opus 5.5', 'Sonnet 5.5', 'GPT-6.1 Sol']);@@ -128,44 +125,6 @@ void main() {},);- testWidgets(- 'says the last 7 days over the title and Collapse over the chevron, and a screen reader hears the action',- (tester) async {- final semantics = tester.ensureSemantics();- final controller = await show(tester, modelsSwarm());- const explained = 'Share of agent work, last 7 days';- final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);- await mouse.addPointer(location: Offset.zero);- addTearDown(mouse.removePointer);- await mouse.moveTo(tester.getCenter(headingText));- await tester.pumpAndSettle(const Duration(seconds: 2));- expect(find.text(explained), findsOneWidget);- expect(find.text('Collapse Models'), findsNothing);- await mouse.moveTo(Offset.zero);- await tester.pumpAndSettle(const Duration(seconds: 2));- await mouse.moveTo(- tester.getCenter(- find.descendant(of: heading, matching: find.byType(Icon)).first,- ),- );- await tester.pumpAndSettle(const Duration(seconds: 2));- expect(find.text('Collapse Models'), findsOneWidget);- expect(find.text(explained), findsNothing);- // The button is named by its title and its action, as Projects' is;- // the explanation is a hint, never its name.- final node = tester.getSemantics(headingText);- expect(node.label, 'Models');- expect(node.tooltip, 'Collapse Models');- expect(node.hint, explained);- expect(- find.bySemanticsLabel(RegExp('Share of agent work')),- findsNothing,- );- semantics.dispose();- await close(tester, controller);- },- );-testWidgets('puts its engine\'s icon before each model\'s name', (tester,) async {@@ -181,11 +140,6 @@ void main() {reason: name,);}- // In the sidebar's icon column: under the channel marks' column.- expect(- tester.getCenter(mark('Opus 5.5', 'claude')).dx,- closeTo(tester.getCenter(find.text('#').first).dx, 1),- );await close(tester, controller);});@@ -204,34 +158,6 @@ void main() {},);- testWidgets(- 'collapses fully from its chevron and expands again, remembered after a restart',- (tester) async {- final server = modelsSwarm();- final controller = await show(tester, server);- expect(controller.modelsGroupOpen, isTrue);- await tester.tap(headingText);- await tester.pumpAndSettle();- // Collapsed: the heading stays, nothing below it.- expect(headingText, findsOneWidget);- expect(rows, findsNothing);- expect(find.text('87%'), findsNothing);- await controller.flush();- expect(server.saved!['modelsGroupOpen'], isFalse);- await close(tester, controller);-- final reopened = await show(tester, server, initial: server.saved);- expect(reopened.modelsGroupOpen, isFalse);- expect(headingText, findsOneWidget);- expect(rows, findsNothing);- await tester.tap(headingText);- await tester.pumpAndSettle();- expect(names(tester), hasLength(3));- expect(inRow('Opus 5.5', find.text('87%')), findsOneWidget);- await close(tester, reopened);- },- );-testWidgets('rounds the shares so all rows add up to 100%', (tester) async {final server = modelsSwarm();// A third each: plain rounding says 33% three times, 99%.@@ -315,45 +241,43 @@ void main() {tester,) async {final server = modelsSwarm();- final controller = await show(tester, server);+ // The right pane is beside the chat: pick its week, then open Manage.+ final controller = await show(tester, server, openManage: false);await tester.tap(find.byKey(const ValueKey('leaderboard-week')));await tester.pumpAndSettle();await tester.tap(find.text('Last week').last);await tester.pumpAndSettle();expect(server.leaderboardReads.last, contains('&week='));- expect(headingText, findsOneWidget);+ await openModels(tester);expect(find.textContaining('last week'), findsNothing);expect(inRow('Opus 5.5', find.text('87%')), findsOneWidget);await close(tester, controller);});- testWidgets(- 'shows the week\'s models from a server before the last 7 days, still headed Models',- (tester) async {- final server = modelsSwarm();- server.leaderboard!.remove('recentModels');- final controller = await show(tester, server);- expect(headingText, findsOneWidget);- expect(find.byTooltip('Share of agent work, this week'), findsOneWidget);- // 32 tasks: Opus at two efforts as one, 14; then 9, 6 and 3; Luna ran- // none of its own.- expect(names(tester), [- 'Opus 5.5',- 'GPT-6.1 Sol',- 'Sonnet 5.5',- 'Haiku 5.5',- ]);- expect(inRow('Opus 5.5', find.text('44%')), findsOneWidget);- expect(inRow('Haiku 5.5', find.text('9%')), findsOneWidget);- expect(- find.byTooltip(- 'Opus 5.5: 14 of 32 tasks this week · 92% passed first review',- ),- findsOneWidget,- );- await close(tester, controller);- },- );+ testWidgets('shows the week\'s models from a server before the last 7 days', (+ tester,+ ) async {+ final server = modelsSwarm();+ server.leaderboard!.remove('recentModels');+ final controller = await show(tester, server);+ // 32 tasks: Opus at two efforts as one, 14; then 9, 6 and 3; Luna ran+ // none of its own.+ expect(names(tester), [+ 'Opus 5.5',+ 'GPT-6.1 Sol',+ 'Sonnet 5.5',+ 'Haiku 5.5',+ ]);+ expect(inRow('Opus 5.5', find.text('44%')), findsOneWidget);+ expect(inRow('Haiku 5.5', find.text('9%')), findsOneWidget);+ expect(+ find.byTooltip(+ 'Opus 5.5: 14 of 32 tasks this week · 92% passed first review',+ ),+ findsOneWidget,+ );+ await close(tester, controller);+ });testWidgets('leaves records with no reported model out of the list and the shares',@@ -394,7 +318,7 @@ void main() {recentModel('claude', null, attempts: 9),];final controller = await show(tester, server);- expect(heading, findsNothing);+ expect(rows, findsNothing);expect(rows, findsNothing);expect(notReported, findsNothing);await close(tester, controller);@@ -428,7 +352,7 @@ void main() {final server = modelsSwarm();server.leaderboard!['recentModels'] = <Object>[];final controller = await show(tester, server);- expect(heading, findsNothing);+ expect(rows, findsNothing);await close(tester, controller);});@@ -447,7 +371,7 @@ void main() {),];final controller = await show(tester, server);- expect(heading, findsNothing);+ expect(rows, findsNothing);await close(tester, controller);});@@ -456,7 +380,7 @@ void main() {(tester) async {final server = modelsSwarm()..failLeaderboardReads = 1;final controller = await show(tester, server);- expect(heading, findsNothing);+ expect(rows, findsNothing);expect(find.textContaining('Loading'), findsNothing);await controller.refresh();await tester.pump(const Duration(minutes: 5));@@ -475,7 +399,7 @@ void main() {server.state['projects'] = <Object>[];await controller.refresh();await tester.pumpAndSettle();- expect(heading, findsNothing);+ expect(rows, findsNothing);expect(find.text('87%'), findsNothing);await close(tester, controller);});@@ -486,7 +410,7 @@ void main() {final server = modelsSwarm();server.leaderboard!['projectId'] = 'other';final controller = await show(tester, server);- expect(heading, findsNothing);+ expect(rows, findsNothing);await close(tester, controller);});}diff --git a/desktop/test/super_tab_sidebar_rows_test.dart b/desktop/test/super_tab_sidebar_rows_test.dartindex 25c064ad0..c57892948 100644--- a/desktop/test/super_tab_sidebar_rows_test.dart+++ b/desktop/test/super_tab_sidebar_rows_test.dart@@ -12,15 +12,14 @@ import 'support/humans_fixture.dart';import 'support/super_tab_fixture.dart';/// The sidebar's rows: a Buddy chat click highlights only that row; a-/// project's name opens its chat and only the chevron at its right end shows-/// or hides its conversations (Dee, 2026-10-28); a machine click expands it,-/// and its details are in the right-click menu.+/// project's row opens its chat and a second click shows or hides its+/// conversations (Quiet Swarm); in Manage, a machine click+/// expands it, and its details are in the right-click menu.void main() {final dm = find.byKey(const ValueKey('super-buddy-lead'));final project = find.byKey(const ValueKey('super-group-lead'));final workgroup = find.byKey(const ValueKey('super-group-offline'));final machine = find.byKey(const ValueKey('super-machine-studio'));- final toggle = find.byKey(const ValueKey('super-project-toggle-lead'));final more = find.byKey(const ValueKey('super-project-more-lead'));Future<SuperTabController> show(@@ -108,7 +107,7 @@ void main() {// A task of the project is open, and its list was then hidden: the// project shows as selected, as in the report.await controller.select('offline');- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(controller.expandedProjects, isEmpty);expect(controller.selectedId, 'offline');@@ -120,7 +119,7 @@ void main() {expect(workgroup, findsNothing);// Open, and a task selected: the Buddy click leaves the list showing.- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();await controller.select('offline');await tester.pumpAndSettle();@@ -149,7 +148,7 @@ void main() {// Open, and the chat left for the Buddy chat: the name comes back to// it without closing the list.- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.tap(dm);await tester.pumpAndSettle();await tester.tap(find.text('Pilot'));@@ -162,33 +161,32 @@ void main() {);testWidgets(- 'the chevron at the far right of a project toggles its list and leaves the chat open',+ 'a second click on the open project toggles its list and leaves its chat open',(tester) async {final controller = await show(tester, humansSwarm());await controller.openBuddyChat('lead');controller.expandedProjects.clear();await tester.tap(dm);await tester.pumpAndSettle();- final chat = controller.selectedId;- Icon chevron() => tester.widget<Icon>(chevronIn(toggle));- expect(chevron().icon, AppIcons.chevronRight);- expect(- tester.getCenter(toggle).dx,- greaterThan(tester.getRect(project).right),- );+ expect(chevronIn(project), findsNothing);++ // The first opens its chat, and leaves its list.+ await tester.tap(project);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'lead');+ expect(controller.expandedProjects, isEmpty);- await tester.tap(toggle);+ await tester.tap(project);await tester.pumpAndSettle();expect(controller.expandedProjects, {'lead'});expect(workgroup, findsOneWidget);- expect(chevron().icon, AppIcons.chevronDown);- expect(controller.selectedId, chat);+ expect(controller.selectedId, 'lead');- await tester.tap(toggle);+ await tester.tap(project);await tester.pumpAndSettle();expect(controller.expandedProjects, isEmpty);expect(workgroup, findsNothing);- expect(controller.selectedId, chat);+ expect(controller.selectedId, 'lead');await close(tester, controller);},);@@ -231,7 +229,7 @@ void main() {final server = humansSwarm();addNumberedWorkgroups(server, 1);final controller = await show(tester, server);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();final g1 = find.byKey(const ValueKey('super-group-g1'));final name = tester@@ -255,7 +253,7 @@ void main() {expect(unreadDot(project), findsNothing);expect(unreadDot(g1), findsNothing);// Collapsed, it is bold for what it hides.- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(weightOf(tester, project, 'Pilot'), grid.AppFont.semibold);await close(tester, controller);@@ -269,7 +267,7 @@ void main() {final server = humansSwarm();addNumberedWorkgroups(server, 2);final controller = await show(tester, server);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();final g1 = find.byKey(const ValueKey('super-group-g1'));final g2 = find.byKey(const ValueKey('super-group-g2'));@@ -284,7 +282,7 @@ void main() {expect(spoken(tester, g1), contains('Unread messages'));expect(spoken(tester, g2), isNot(contains('Unread messages')));// Collapsed, the project is heard as unread for what it hides.- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(spoken(tester, project), contains('Unread messages'));semantics.dispose();@@ -330,7 +328,7 @@ void main() {var controller = await show(tester, server);expect(controller.expandedProjects, isEmpty);expect(workgroup, findsNothing);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();await close(tester, controller);@@ -356,7 +354,6 @@ void main() {controller = await reopen('peer');expect(workgroup, findsOneWidget);- expect(tester.widget<Icon>(chevronIn(toggle)).icon, AppIcons.chevronDown);await close(tester, controller);controller = await reopen('owner');@@ -371,7 +368,7 @@ void main() {final server = humansSwarm();addNumberedWorkgroups(server, 11);final controller = await show(tester, server);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();Finder row(String id) => find.byKey(ValueKey('super-group-$id'));@@ -437,7 +434,7 @@ void main() {final controller = await show(tester, server);server.append('New work', conversationId: 'g1');await controller.refresh();- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(find.byKey(const ValueKey('super-group-g1')), findsOneWidget);expect(find.byKey(const ValueKey('super-group-g2')), findsOneWidget);@@ -462,12 +459,12 @@ void main() {await tester.pumpAndSettle();expect(projectFill(), Colors.transparent);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(controller.selectedId, 'g1');expect(projectFill(), grid.AppSurface.selectedFill);- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(projectFill(), Colors.transparent);await close(tester, controller);@@ -478,20 +475,18 @@ void main() {tester,) async {final controller = await show(tester, humansSwarm());- await tester.tap(toggle);+ controller.toggleProject('lead');await tester.pumpAndSettle();expect(controller.expandedProjects, {'lead'});Focus.of(tester.element(find.text('Pilot'))).requestFocus();await tester.pumpAndSettle();- // Already open: → goes on to the chevron beside the name.+ final name = primaryFocus;+ // Already open: → goes on from the name.await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight);await tester.pumpAndSettle();expect(controller.expandedProjects, {'lead'});- expect(- primaryFocus?.context?.findAncestorWidgetOfExactType<InkWell>()?.key,- const ValueKey('super-project-toggle-lead'),- );+ expect(primaryFocus, isNot(same(name)));await close(tester, controller);});@@ -527,13 +522,14 @@ void main() {},);- testWidgets('the focused chevron toggles with Enter and with Space', (+ testWidgets('the focused open project toggles with Enter and with Space', (tester,) async {final controller = await show(tester, humansSwarm());controller.expandedProjects.clear();await tester.pumpAndSettle();- Focus.of(tester.element(chevronIn(toggle))).requestFocus();+ expect(controller.selectedId, 'lead');+ Focus.of(tester.element(find.text('Pilot'))).requestFocus();await tester.pumpAndSettle();await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pumpAndSettle();@@ -548,6 +544,8 @@ void main() {'a machine click expands and collapses it; Details is in its right-click menu',(tester) async {final controller = await show(tester, humansSwarm());+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();expect(chevronIn(machine), findsNothing);expect(controller.isMachineExpanded('studio'), isFalse);diff --git a/desktop/test/super_tab_sidebar_scale_test.dart b/desktop/test/super_tab_sidebar_scale_test.dartindex 409b22b50..d95f3b619 100644--- a/desktop/test/super_tab_sidebar_scale_test.dart+++ b/desktop/test/super_tab_sidebar_scale_test.dart@@ -122,7 +122,6 @@ void main() {return ProjectSidebar(controller: controller,onSelect: controller.select,- onAddAgent: (_) {},needsHuman: (group) {asked.update(group.id, (n) => n + 1, ifAbsent: () => 1);return 0;diff --git a/desktop/test/super_tab_sidebar_sections_test.dart b/desktop/test/super_tab_sidebar_sections_test.dartindex e1e65150e..df8bc4d98 100644--- a/desktop/test/super_tab_sidebar_sections_test.dart+++ b/desktop/test/super_tab_sidebar_sections_test.dart@@ -63,9 +63,10 @@ void main() {List<String> body(String title) {final all = sections();final i = all.indexWhere((s) => s.title == title);+ // Manage stands at the foot, under the sections.final end = i + 1 < all.length? all[i + 1].top- : tester.getBottomLeft(sidebar).dy;+ : tester.getTopLeft(find.byKey(const ValueKey('super-manage'))).dy;return [for (final elementin find@@ -79,10 +80,7 @@ void main() {final titles = [for (final s in sections()) s.title];// Not a vacuous walk: the sections people asked about are all here.- expect(- titles,- containsAllInOrder(['Projects', 'Buddies', 'Machines', 'Models']),- );+ expect(titles, ['Projects', 'Buddies']);for (final title in titles) {final heading = find.descendant(of: sidebar,diff --git a/desktop/test/super_tab_sidebar_test.dart b/desktop/test/super_tab_sidebar_test.dartindex 02a47494a..78f9f2204 100644--- a/desktop/test/super_tab_sidebar_test.dart+++ b/desktop/test/super_tab_sidebar_test.dart@@ -2,15 +2,21 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/machine_resources.dart';+import 'package:harness/screens/swarm_screen.dart';import 'package:harness/shared/theme/app_icons.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shortcuts/app_keymap.dart';+import 'package:harness/state/swarm_catalog.dart';import 'package:harness/state/app_state.dart';import 'package:harness/super_tabs/controller.dart';-import 'package:harness/super_tabs/machine_status.dart';+import 'package:harness/super_tabs/machines.dart';+import 'package:harness/super_tabs/manage_page.dart';import 'package:harness/super_tabs/model.dart';import 'package:harness/super_tabs/project_sidebar.dart';import 'package:harness/super_tabs/section_heading.dart';+import 'keymap_host_test.dart' show MemoryKeymap;+import 'super_tab_launch_test.dart' show SuperTabLaunchFixture, tabId;import 'support/super_tab_fixture.dart';import 'swarm_state_test.dart' show createApp;@@ -36,17 +42,17 @@ Material rowMaterial(WidgetTester tester, String key) => tester.widget(.first,);+/// The sidebar, with Manage opening Devices, one of its pages: [onManage] and+/// the row's selection follow the controller as they do in the view.Future<void> pumpSidebar(WidgetTester tester,SuperTabController controller,AppNotifier app, {double width = 280,double scale = 1,- bool devices = true,VoidCallback? onNewProject,- VoidCallback? onYourDevices,- DateTime Function()? now,- Future<MachineResources?> Function(String)? readLocal,+ VoidCallback? onManage,+ VoidCallback? onNotifications,}) async {await tester.binding.setSurfaceSize(Size(width, 1000));await tester.pumpWidget(@@ -63,18 +69,49 @@ Future<void> pumpSidebar(builder: (context, _) => ProjectSidebar(controller: controller,app: app,- onAddAgent: (_) {},needsHuman: (_) => 0,onSelect: controller.select,onNewProject: onNewProject ?? () {},- onYourDevices: devices- ? () {- onYourDevices?.call();- controller.selectDevices();- }- : null,- devicesSelected: controller.devicesSelected,- readLocal: readLocal,+ onNotifications: onNotifications ?? () {},+ onManage: () {+ onManage?.call();+ controller.selectDevices();+ },+ manageSelected: controller.devicesSelected,+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+}++/// The Machines group on its own, heading included.+Future<void> pumpMachines(+ WidgetTester tester,+ SuperTabController controller,+ AppNotifier app, {+ double width = 280,+ double scale = 1,+ DateTime Function()? now,+}) async {+ await tester.binding.setSurfaceSize(Size(width, 1000));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(scale)),+ child: child!,+ ),+ home: Scaffold(+ body: ListenableBuilder(+ listenable: controller,+ builder: (context, _) => SuperTabMachines(+ controller: controller,+ app: app,+ onAddAgent: (_) {},+ embedded: true,now: now ?? DateTime.now,),),@@ -118,143 +155,142 @@ Future<SuperTabController> projectSidebar(ConversationServer server) async {void main() {for (final scale in [1.0, 2.0]) {- testWidgets('flat navigation shares text and selection bounds; a project row '- 'opens its chat and shows its workgroups at ${scale}x', (tester) async {- addTearDown(() => tester.binding.setSurfaceSize(null));- final app = createApp(connected: true);- addTearDown(app.dispose);- final server = ConversationServer();- final controller = await projectSidebar(server);- var created = 0;- var openedDevices = 0;- await pumpSidebar(- tester,- controller,- app,- scale: scale,- onNewProject: () => created++,- onYourDevices: () => openedDevices++,- );- final project = find.byKey(const ValueKey('super-group-lead'));- final empty = find.byKey(const ValueKey('super-group-empty-lead'));- final devices = find.byKey(const ValueKey('super-your-devices'));- final newProject = find.byKey(const ValueKey('super-new-project'));- expect(find.byType(OutlinedButton), findsNothing);- expect(- tester.getBottomLeft(devices).dy,- lessThan(tester.getTopLeft(find.text('Projects')).dy),- );- expect(- tester.getBottomLeft(newProject).dy,- lessThan(tester.getTopLeft(devices).dy),- );- expect(inRow('super-group-lead', find.text('#')), findsOneWidget);+ testWidgets(+ 'flat navigation shares text and selection bounds; a project row '+ 'opens its chat and shows its workgroups at ${scale}x',+ (tester) async {+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final server = ConversationServer();+ final controller = await projectSidebar(server);+ var created = 0;+ var openedManage = 0;+ var openedActivity = 0;+ await pumpSidebar(+ tester,+ controller,+ app,+ scale: scale,+ onNewProject: () => created++,+ onManage: () => openedManage++,+ onNotifications: () => openedActivity++,+ );+ final project = find.byKey(const ValueKey('super-group-lead'));+ final empty = find.byKey(const ValueKey('super-group-empty-lead'));+ final manage = find.byKey(const ValueKey('super-manage'));+ final activity = find.byKey(const ValueKey('super-activity'));+ expect(find.byType(OutlinedButton), findsNothing);+ expect(+ tester.getBottomLeft(activity).dy,+ lessThan(tester.getTopLeft(find.text('Projects')).dy),+ );+ expect(+ tester.getTopLeft(manage).dy,+ greaterThan(tester.getBottomLeft(empty).dy),+ );+ expect(inRow('super-group-lead', find.text('#')), findsOneWidget);- // Its name in the Projects list, not its direct message's grey tag.- final sample = inRow(- 'super-group-empty-lead',- find.text('sample-project'),- );- await tester.tap(sample);- await tester.pumpAndSettle();- expect(controller.selectedId, 'empty-lead');- await tester.tap(project);- await tester.pumpAndSettle();- expect(controller.selectedId, 'lead');- expect(inRow('super-group-lead', find.text('#')), findsOneWidget);- final toggle = find.byKey(const ValueKey('super-project-toggle-lead'));- await tester.tap(toggle);- await tester.pumpAndSettle();- final work = find.byKey(const ValueKey('super-group-offline'));- expect(work, findsOneWidget);- final textX = tester- .getTopLeft(inRow('super-group-lead', find.text('web-project')))- .dx;- for (final label in [- find.text('New project'),- find.text('Your devices'),- sample,- // A workgroup's number is grey, with no #: it is no channel.- inRow('super-group-offline', find.text('12 Offline editing')),- ]) {- expect(tester.getTopLeft(label).dx, textX, reason: '$label');- }- // Unread is a bold name, with no dot in either row (Dee, 2026-10-29).- expect(unreadDot('offline'), findsNothing);- expect(unreadDot('lead'), findsNothing);- for (final row in [newProject, devices, work]) {- final bounds = tester.getRect(row);- expect(bounds.left, tester.getRect(project).left);- expect(bounds.right, tester.getRect(toggle).right);- }+ // Its name in the Projects list, not its direct message's grey tag.+ final sample = inRow(+ 'super-group-empty-lead',+ find.text('sample-project'),+ );+ await tester.tap(sample);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'empty-lead');+ await tester.tap(project);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'lead');+ expect(inRow('super-group-lead', find.text('#')), findsOneWidget);+ // A second click shows its workgroups (no chevrons: Quiet Swarm).+ await tester.tap(project);+ await tester.pumpAndSettle();+ final work = find.byKey(const ValueKey('super-group-offline'));+ expect(work, findsOneWidget);+ final textX = tester+ .getTopLeft(inRow('super-group-lead', find.text('web-project')))+ .dx;+ for (final label in [+ find.text('Activity'),+ find.text('Manage'),+ sample,+ // A workgroup's number is grey, with no #: it is no channel.+ inRow('super-group-offline', find.text('12 Offline editing')),+ ]) {+ expect(tester.getTopLeft(label).dx, textX, reason: '$label');+ }+ // Unread is a bold name, with no dot in either row (Dee, 2026-10-29).+ expect(unreadDot('offline'), findsNothing);+ expect(unreadDot('lead'), findsNothing);+ for (final row in [activity, manage, work]) {+ final bounds = tester.getRect(row);+ expect(bounds.left, tester.getRect(project).left);+ expect(bounds.right, tester.getRect(project).right);+ }- await tester.tap(work);- await tester.pumpAndSettle();- expect(controller.selectedId, 'offline');- await tester.tap(empty);- await tester.pumpAndSettle();- expect(controller.selectedId, 'empty-lead');- expect(find.text('No workgroups yet'), findsNothing);- final emptyToggle = find.byKey(- const ValueKey('super-project-toggle-empty'),- );- await tester.tap(emptyToggle);- await tester.pumpAndSettle();- expect(find.text('No workgroups yet'), findsOneWidget);- expect(tester.getTopLeft(find.text('No workgroups yet')).dx, textX);- // A second click on its chevron hides them again.- await tester.tap(emptyToggle);- await tester.pumpAndSettle();- expect(controller.selectedId, 'empty-lead');- expect(find.text('No workgroups yet'), findsNothing);+ await tester.tap(work);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'offline');+ await tester.tap(empty);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'empty-lead');+ expect(find.text('No workgroups yet'), findsNothing);+ await tester.tap(empty);+ await tester.pumpAndSettle();+ expect(find.text('No workgroups yet'), findsOneWidget);+ expect(tester.getTopLeft(find.text('No workgroups yet')).dx, textX);+ // Another click hides them again.+ await tester.tap(empty);+ await tester.pumpAndSettle();+ expect(controller.selectedId, 'empty-lead');+ expect(find.text('No workgroups yet'), findsNothing);- // The plain top actions retain keyboard operation and do not create tabs.- Focus.of(tester.element(find.text('New project'))).requestFocus();- await tester.pump();- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pumpAndSettle();- expect(created, 1);- await tester.tap(find.byTooltip('New project'));- await tester.pumpAndSettle();- expect(created, 2);- final tabsBefore = app.swarms.length;- Focus.of(tester.element(find.text('Your devices'))).requestFocus();- await tester.pump();- await tester.sendKeyEvent(LogicalKeyboardKey.enter);- await tester.pumpAndSettle();- expect(openedDevices, 1);- expect(controller.devicesSelected, isTrue);- expect(controller.selectedId, 'empty-lead');- expect(app.swarms, hasLength(tabsBefore));- expect(- rowMaterial(tester, 'super-your-devices').color,- grid.AppSurface.selectedFill,- );- expect(- rowMaterial(tester, 'super-group-offline').color,- Colors.transparent,- );+ // The plain rows retain keyboard operation and do not create tabs.+ Focus.of(tester.element(find.text('Activity'))).requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(openedActivity, 1);+ await tester.tap(find.byTooltip('New project'));+ await tester.pumpAndSettle();+ expect(created, 1);+ final tabsBefore = app.swarms.length;+ Focus.of(tester.element(find.text('Manage'))).requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(openedManage, 1);+ expect(controller.devicesSelected, isTrue);+ expect(controller.selectedId, 'empty-lead');+ expect(app.swarms, hasLength(tabsBefore));+ expect(+ rowMaterial(tester, 'super-manage').color,+ grid.AppSurface.selectedFill,+ );+ expect(+ rowMaterial(tester, 'super-group-offline').color,+ Colors.transparent,+ );- // Returning to the already selected workgroup still leaves Devices.- await tester.tap(work);- await tester.pumpAndSettle();- expect(controller.devicesSelected, isFalse);- expect(controller.selectedId, 'offline');- expect(- rowMaterial(tester, 'super-group-offline').color,- grid.AppSurface.selectedFill,- );- expect(- rowMaterial(tester, 'super-your-devices').color,- Colors.transparent,- );- expect(tester.takeException(), isNull);- await disposeSidebar(tester, controller);- });+ // Returning to the already selected workgroup still leaves it.+ await tester.tap(work);+ await tester.pumpAndSettle();+ expect(controller.devicesSelected, isFalse);+ expect(controller.selectedId, 'offline');+ expect(+ rowMaterial(tester, 'super-group-offline').color,+ grid.AppSurface.selectedFill,+ );+ expect(rowMaterial(tester, 'super-manage').color, Colors.transparent);+ expect(tester.takeException(), isNull);+ await disposeSidebar(tester, controller);+ },+ );}- testWidgets('reads like a chat app: utilities, Projects A to Z with their '- 'workgroups, Buddies, then Machines; no # product-managers', (+ testWidgets('reads like a chat app: Activity, Projects A to Z with their '+ 'workgroups, Buddies, then Manage; no # product-managers', (tester,) async {addTearDown(() => tester.binding.setSurfaceSize(null));@@ -275,9 +311,7 @@ void main() {await pumpSidebar(tester, controller, app);final order = [- find.byKey(const ValueKey('super-new-project')),- find.byKey(const ValueKey('super-your-devices')),- find.byKey(const ValueKey('super-local-models')),+ find.byKey(const ValueKey('super-activity')),find.text('Projects'),find.byKey(const ValueKey('super-group-empty-lead')),find.text('No workgroups yet'),@@ -286,7 +320,7 @@ void main() {find.text('Buddies'),find.byKey(const ValueKey('super-buddy-lead')),find.byKey(const ValueKey('super-buddy-empty')),- find.text('Machines'),+ find.byKey(const ValueKey('super-manage')),];for (var i = 1; i < order.length; i++) {expect(@@ -312,15 +346,16 @@ void main() {await disposeSidebar(tester, controller);});- testWidgets('section disclosure follows its label and + aligns with the '- 'rows\' right status column', (tester) async {+ testWidgets('section disclosure follows its label and the +s line up', (+ tester,+ ) async {addTearDown(() => tester.binding.setSurfaceSize(null));final app = createApp(connected: true);addTearDown(app.dispose);final controller = await projectSidebar(ConversationServer());for (final width in [180.0, 280.0, 420.0]) {await pumpSidebar(tester, controller, app, width: width);- for (final title in ['Projects', 'Machines']) {+ for (final title in ['Projects', 'Buddies']) {final heading = find.ancestor(of: find.text(title),matching: find.byType(SuperTabSectionHeading),@@ -335,15 +370,9 @@ void main() {expect(chevron.left, closeTo(label.right + 4, .01));expect(tester.getCenter(find.byTooltip('New project')).dx,- tester.getCenter(find.byTooltip('Add machine')).dx,+ tester.getCenter(find.byTooltip('Add a Buddy')).dx,);}- expect(- tester.getCenter(find.byTooltip('New project')).dx,- tester- .getCenter(find.byKey(const ValueKey('super-project-toggle-lead')))- .dx,- );expect(tester.takeException(), isNull);}await disposeSidebar(tester, controller);@@ -370,17 +399,26 @@ void main() {}for (final width in [180.0, 240.0]) {for (final scale in [1.0, 2.0]) {+ final reason = '$width px, ${scale}x, unreachable=$unreachable';await pumpSidebar(tester,controller,app,width: width,scale: scale,+ );+ expect(tester.takeException(), isNull, reason: reason);+ expect(find.text('Manage'), findsOneWidget, reason: reason);++ await pumpMachines(+ tester,+ controller,+ app,+ width: width,+ scale: scale,now: now,);- final reason = '$width px, ${scale}x, unreachable=$unreachable';expect(tester.takeException(), isNull, reason: reason);- expect(find.text('Your devices'), findsOneWidget, reason: reason);expect(find.byTooltip('Add machine'),findsOneWidget,@@ -405,17 +443,14 @@ void main() {}}}- await pumpSidebar(tester, controller, app, devices: false);- expect(find.byKey(const ValueKey('super-your-devices')), findsNothing);- expect(find.byTooltip('Add machine'), findsOneWidget);await disposeSidebar(tester, controller);},);- testWidgets('the left Machines group repaints on a live app change alone', (- tester,- ) async {+ testWidgets('Manage\'s Machines read a live app change when the workspace '+ 'rebuilds', (tester) async {addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.binding.setSurfaceSize(const Size(800, 700));final app = createApp(connected: true);addTearDown(app.dispose);final server = ConversationServer();@@ -432,30 +467,87 @@ void main() {];final controller = server.controller();await controller.refresh();- await pumpSidebar(- tester,- controller,- app,- readLocal: (_) async => const MachineResources(cpuPercent: 10),+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ // The workspace rebuilds on the app; the next test holds it to that.+ body: ListenableBuilder(+ listenable: app,+ builder: (context, _) => SuperTabManagePage(+ controller: controller,+ app: app,+ tab: SuperTabManageTab.machines,+ onAddAgent: (_) {},+ readLocal: (_) async => const MachineResources(cpuPercent: 10),+ ),+ ),+ ),+ ),);+ await tester.pumpAndSettle();await tester.pump();await tester.pump();- final dot = inRow('super-machine-m', find.byType(SuperTabMachineDot));+ final entry = find.byKey(const ValueKey('super-machine-entry-m'));expect(- tester.widget<SuperTabMachineDot>(dot).status,- isNot(SuperTabMachineStatus.offline),+ find.descendant(of: entry, matching: find.text('offline')),+ findsNothing,);await app.handleEventForTest('m', {'type': 'node_status', 'online': false});await tester.pump();expect(find.byKey(const ValueKey('super-machine-m')), findsOneWidget);expect(- tester.widget<SuperTabMachineDot>(dot).status,- SuperTabMachineStatus.offline,+ find.descendant(of: entry, matching: find.text('offline')),+ findsOneWidget,);await disposeSidebar(tester, controller);});+ testWidgets(+ 'the workspace rebuilds Manage\'s Machines on a live app change',+ (tester) async {+ final f = SuperTabLaunchFixture();+ f.app.bindSuperTab(f.app.activeSwarmId, tabId, 'Pilot');+ final c = await f.app.superTabs.open(tabId);+ await c.refresh();+ final map = MemoryKeymap();+ addTearDown(map.dispose);+ final projects = SwarmProjectStore();+ addTearDown(projects.dispose);+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1280, 800);+ addTearDown(tester.view.resetPhysicalSize);+ addTearDown(tester.view.resetDevicePixelRatio);+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) =>+ KeymapProvider(keymap: map, child: child!),+ home: SwarmScreen(+ notifier: f.app,+ nativeTabs: false,+ projectStore: projects,+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.byKey(const ValueKey('super-manage')));+ await tester.pumpAndSettle();+ final machines = find.byType(SuperTabMachines);+ final before = tester.widget(machines);+ await f.app.handleEventForTest('m', {+ 'type': 'node_status',+ 'online': false,+ });+ await tester.pump();+ expect(tester.widget(machines), isNot(same(before)));+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ f.app.superTabs.dispose();+ f.dispose();+ },+ );+testWidgets('section collapse persists and keeps top navigation available', (tester,) async {@@ -465,29 +557,29 @@ void main() {final server = ConversationServer();final controller = await projectSidebar(server);await pumpSidebar(tester, controller, app);- const machinesBody = "Add a machine for this Swarm's agents to use.";+ final buddy = find.byKey(const ValueKey('super-buddy-lead'));expect(inRow('super-group-lead', find.text('web-project')), findsOneWidget);- expect(find.text(machinesBody), findsOneWidget);+ expect(buddy, findsOneWidget);await tester.tap(find.byTooltip('Collapse Projects'));await tester.pumpAndSettle();expect(inRow('super-group-lead', find.text('web-project')), findsNothing);expect(controller.projectsGroupOpen, isFalse);- await tester.tap(find.byTooltip('Collapse Machines'));+ await tester.tap(find.byTooltip('Collapse Buddies'));await tester.pumpAndSettle();- expect(find.text(machinesBody), findsNothing);- expect(controller.machinesGroupOpen, isFalse);- expect(find.text('New project'), findsOneWidget);- expect(find.text('Your devices'), findsOneWidget);+ expect(buddy, findsNothing);+ expect(controller.buddiesGroupOpen, isFalse);+ expect(find.text('Activity'), findsOneWidget);+ expect(find.text('Manage'), findsOneWidget);await controller.flush();final saved = server.saved!;expect(saved['projectsGroupOpen'], isFalse);- expect(saved['machinesGroupOpen'], isFalse);+ expect(saved['buddiesGroupOpen'], isFalse);final reopened = server.controller(initial: saved);await reopened.refresh();expect(reopened.projectsGroupOpen, isFalse);- expect(reopened.machinesGroupOpen, isFalse);+ expect(reopened.buddiesGroupOpen, isFalse);Focus.of(tester.element(find.text('Projects'))).requestFocus();await tester.pump();@@ -519,14 +611,10 @@ void main() {await tester.pumpWidget(MaterialApp(home: Scaffold(- body: ListenableBuilder(- listenable: c,- builder: (context, _) => ProjectSidebar(- controller: c,- onAddAgent: (_) {},- needsHuman: (_) => 0,- onSelect: c.select,- ),+ body: SuperTabManagePage(+ controller: c,+ tab: SuperTabManageTab.models,+ onAddAgent: (_) {},),),),@@ -545,11 +633,11 @@ void main() {final c = server.controller();await c.refresh();await mount(tester, c);- expect(find.text('Your models'), findsOneWidget);+ expect(find.text('Your models…'), findsOneWidget);await tester.tap(open);await tester.pumpAndSettle();- // The page is titled as the row that opens it.- expect(find.text('Your models'), findsNWidgets(2));+ // The page is titled as the action that opens it.+ expect(find.text('Your models'), findsOneWidget);expect(find.byType(Switch), findsNothing);expect(find.textContaining('Set up connects this computer to the Swarm'),diff --git a/desktop/test/super_tab_swarm_delete_test.dart b/desktop/test/super_tab_swarm_delete_test.dartindex 2b8ac8295..53e6181a7 100644--- a/desktop/test/super_tab_swarm_delete_test.dart+++ b/desktop/test/super_tab_swarm_delete_test.dart@@ -7,6 +7,7 @@ import 'package:harness/core/models.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/manage_page.dart';import 'package:harness/super_tabs/project_sidebar.dart';import 'package:harness/super_tabs/swarm_delete.dart';import 'package:harness/super_tabs/swarm_switcher.dart';@@ -245,31 +246,41 @@ Future<SuperTabController> _pump(debugShowCheckedModeBanner: false,theme: grid.buildAppTheme(brightness: brightness),home: Scaffold(- body: Align(- alignment: Alignment.topLeft,- child: SizedBox(- width: 300,- child: ListenableBuilder(- listenable: app,- builder: (context, _) =>- switch (app.superTabs.peek(app.activeSwarm.superTabId!)) {- null => const SizedBox(),- final c => ListenableBuilder(- listenable: c,- builder: (context, _) => ProjectSidebar(- key: ValueKey(c.tabId),- controller: c,- app: app,- onAddAgent: (_) {},- needsHuman: (_) => 0,- onSelect: c.select,- onNewProject: () {},- onNewSwarm: () {},+ body: ListenableBuilder(+ listenable: app,+ builder: (context, _) =>+ switch (app.superTabs.peek(app.activeSwarm.superTabId!)) {+ null => const SizedBox(),+ final c => ListenableBuilder(+ listenable: c,+ builder: (context, _) => Row(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SizedBox(+ width: 300,+ child: ProjectSidebar(+ key: ValueKey(c.tabId),+ controller: c,+ app: app,+ needsHuman: (_) => 0,+ onSelect: c.select,+ onNewProject: () {},+ onNewSwarm: () {},+ ),),- ),- },- ),- ),+ Expanded(+ child: SuperTabManagePage(+ key: ValueKey('manage-${c.tabId}'),+ controller: c,+ app: app,+ tab: SuperTabManageTab.swarm,+ onAddAgent: (_) {},+ ),+ ),+ ],+ ),+ ),+ },),),),@@ -294,7 +305,8 @@ Future<void> _openMenu(WidgetTester tester) async {await tester.pump();}-const _deleteItem = ValueKey('swarm-switch-delete');+const _deleteItem = ValueKey('super-manage-delete');+const _leaveItem = ValueKey('super-manage-leave');const _confirm = ValueKey('swarm-delete-confirm');const _nameField = ValueKey('swarm-delete-name');@@ -306,7 +318,6 @@ Future<void> _run(WidgetTester tester) async {}Future<void> _openDialog(WidgetTester tester) async {- await _openMenu(tester);await tester.tap(find.byKey(_deleteItem));await tester.pump();await tester.pump();@@ -321,14 +332,13 @@ void main() {TestWidgetsFlutterBinding.ensureInitialized();setUpAll(() => loadCaptureFonts(_shots));- testWidgets('the dropdown offers Delete to the owner of the shown Swarm '- 'alone: not to a member, and never for Personal', (tester) async {+ testWidgets('Manage offers Delete to the owner of the shown Swarm alone: '+ 'a member may leave, and Personal offers neither', (tester) async {late AppNotifier app;await tester.runAsync(() async => (app, _) = await _swarms());await _pump(tester, app);- await _openMenu(tester);expect(find.byKey(_deleteItem), findsOneWidget);- expect(find.text('Delete “Alpha”…'), findsOneWidget);+ expect(find.byKey(_leaveItem), findsNothing);await _releaseAll(tester, app);// The owner's Personal Swarm, shown in the tab: never offered.@@ -345,9 +355,8 @@ void main() {await _pump(tester, mine);expect(mine.activeSwarm.superTabId, 'personal');expect(PersonalSwarm.of(mine).id, 'personal');- await _openMenu(tester);- expect(find.byKey(const ValueKey('swarm-switch-personal')), findsOneWidget);expect(find.byKey(_deleteItem), findsNothing);+ expect(find.byKey(_leaveItem), findsNothing);await _releaseAll(tester, mine);late AppNotifier member;@@ -355,12 +364,33 @@ void main() {() async => (member, _) = await _swarms(account: 'member'),);await _pump(tester, member);- await _openMenu(tester);- expect(find.byKey(const ValueKey('swarm-switch-alpha')), findsOneWidget);expect(find.byKey(_deleteItem), findsNothing);+ expect(find.byKey(_leaveItem), findsOneWidget);await _releaseAll(tester, member);});+ testWidgets('the dropdown holds only Swarms', (tester) async {+ late AppNotifier app;+ await tester.runAsync(() async {+ late _Backend backend;+ (app, backend) = await _swarms();+ backend.add('old', 'test-1');+ backend.deleted['old'] =+ backend.now - const Duration(days: 1).inMilliseconds;+ await app.superTabs.refreshTabs();+ });+ await _pump(tester, app);+ await _openMenu(tester);+ expect(find.byKey(const ValueKey('swarm-switch-alpha')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-switch-new')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-switch-delete')), findsNothing);+ expect(+ find.byKey(const ValueKey('swarm-switch-restore-old')),+ findsNothing,+ );+ await _releaseAll(tester, app);+ });+testWidgets('the dialog names who loses access and deletes only once the ''exact name is typed; Cancel sends nothing', (tester) async {late AppNotifier app;@@ -424,12 +454,20 @@ void main() {expect(swarmChoices(app).map((c) => c.id), isNot(contains('alpha')));expect(app.superTabs.ownerOf('alpha'), isNull);- await _openMenu(tester);- expect(find.byKey(const ValueKey('swarm-switch-alpha')), findsNothing);- expect(find.text('Restore “Alpha”'), findsOneWidget);+ // Its tab moves on, and Manage there can bring it back.+ await tester.runAsync(() async {+ backend.add('personal', 'Personal');+ await app.superTabs.refreshTabs();+ final tab = app.swarms.firstWhere((s) => s.superTabId == 'alpha');+ app.showSuperTabIn(tab.id, 'personal', 'Personal');+ await (await app.superTabs.open('personal')).refresh();+ });+ await _pump(tester, app);+ await _run(tester);+ expect(find.text('Alpha'), findsOneWidget);expect(find.text('Deleted · 7 days left'), findsOneWidget);- await tester.tap(find.byKey(const ValueKey('swarm-switch-restore-alpha')));+ await tester.tap(find.byKey(const ValueKey('super-manage-restore-alpha')));await _run(tester);await _run(tester);final (who, id, command) = backend.commands.last;@@ -607,12 +645,6 @@ void main() {await app.superTabs.refreshTabs();});await _pump(tester, app, brightness: brightness);- await _openMenu(tester);- await captureWindow(- tester,- _shots,- 'swarm-delete-menu-${brightness.name}',- );await tester.tap(find.byKey(_deleteItem));await tester.pump();await tester.pump();diff --git a/desktop/test/super_tab_swarm_switcher_test.dart b/desktop/test/super_tab_swarm_switcher_test.dartindex bcd955973..f9550cbb2 100644--- a/desktop/test/super_tab_swarm_switcher_test.dart+++ b/desktop/test/super_tab_swarm_switcher_test.dart@@ -317,7 +317,6 @@ Future<SuperTabController> _pumpBar(key: ValueKey(c.tabId),controller: c,app: app,- onAddAgent: (_) {},needsHuman: (_) => 0,onSelect: c.select,onNewProject: () {},@@ -446,7 +445,9 @@ void main() {expect(bar.dy,lessThan(- tester.getTopLeft(find.byKey(const ValueKey('super-new-project'))).dy,+ tester+ .getTopLeft(find.byKey(const ValueKey('project-sidebar-projects')))+ .dy,),);diff --git a/desktop/test/super_tab_tooltip_freeze_test.dart b/desktop/test/super_tab_tooltip_freeze_test.dartindex 08af893bb..cc2c714f0 100644--- a/desktop/test/super_tab_tooltip_freeze_test.dart+++ b/desktop/test/super_tab_tooltip_freeze_test.dart@@ -59,7 +59,7 @@ void main() {});testWidgets(- 'clicking around the Swarm screen and toggling Machines logs no error',+ 'clicking around the Swarm screen and toggling Projects logs no error',(tester) async {await tester.binding.setSurfaceSize(const Size(1300, 500));addTearDown(() => tester.binding.setSurfaceSize(null));@@ -102,16 +102,27 @@ void main() {}for (var round = 0; round < 3; round++) {- await click(find.byTooltip('Collapse Machines'));- expect(controller.machinesGroupOpen, isFalse);- await click(find.byTooltip('Expand Machines'));- expect(controller.machinesGroupOpen, isTrue);- // Hover a row below Machines, then open Machines as its tooltip opens.- await click(find.byTooltip('Collapse Machines'));- await mouse.moveTo(const Offset(100, 480));+ await click(find.byTooltip('Collapse Projects'));+ expect(controller.projectsGroupOpen, isFalse);+ await click(find.byTooltip('Expand Projects'));+ expect(controller.projectsGroupOpen, isTrue);+ // Hover a project's row, then close Projects as its tooltip opens: the+ // row leaves the list.+ await mouse.moveTo(+ tester.getCenter(find.byKey(const ValueKey('super-group-lead'))),+ );await tester.pump();await tester.binding.delayed(_pastHoverWait);- controller.toggleMachinesGroup();+ controller.toggleProjectsGroup();+ await tester.pump();+ expect(tester.takeException(), isNull);+ // And open it again as a row under it, moved down, is hovered.+ await mouse.moveTo(+ tester.getCenter(find.byKey(const ValueKey('super-buddy-lead'))),+ );+ await tester.pump();+ await tester.binding.delayed(_pastHoverWait);+ controller.toggleProjectsGroup();await tester.pump();expect(tester.takeException(), isNull);await mouse.moveTo(const Offset(100, 60));diff --git a/desktop/test/super_tab_view_test.dart b/desktop/test/super_tab_view_test.dartindex 54a7e1a8a..6c47b18e4 100644--- a/desktop/test/super_tab_view_test.dart+++ b/desktop/test/super_tab_view_test.dart@@ -281,7 +281,7 @@ void main() {await tester.tap(find.byTooltip('Conversations'));await tester.pumpAndSettle();}- await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-group-offline')));await tester.pumpAndSettle();@@ -370,7 +370,7 @@ void main() {expect(server.posts, isEmpty);await tester.tap(find.byTooltip('Conversations'));await tester.pumpAndSettle();- await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();await tester.tap(find.byKey(const ValueKey('super-group-offline')));await tester.pumpAndSettle();diff --git a/desktop/test/swarm_projects_test.dart b/desktop/test/swarm_projects_test.dartindex 5ab51303a..9b484c82c 100644--- a/desktop/test/swarm_projects_test.dart+++ b/desktop/test/swarm_projects_test.dart@@ -85,11 +85,10 @@ void main() {tester.getBottomLeft(create).dy,lessThan(tester.getTopLeft(project).dy),);- await tester.tap(find.byKey(const ValueKey('super-group-lead')));- await tester.pumpAndSettle();expect(c.selectedId, 'lead');expect(find.text('12 Offline editing'), findsNothing);- await tester.tap(find.byKey(const ValueKey('super-project-toggle-lead')));+ // Already open: a click on it shows its workgroups.+ await tester.tap(find.byKey(const ValueKey('super-group-lead')));await tester.pumpAndSettle();expect(find.text('12 Offline editing'), findsOneWidget);await tester.tap(find.byKey(const ValueKey('super-group-offline')));@@ -120,6 +119,9 @@ void main() {matching: find.text('Lamp OS'),);// Enter on the project opens its chat; → shows its workgroups.+ await c.select('offline');+ c.expandedProjects.remove('lead');+ await tester.pumpAndSettle();Focus.of(tester.element(projectName)).requestFocus();await tester.pump();await tester.sendKeyEvent(LogicalKeyboardKey.enter);@@ -138,9 +140,7 @@ void main() {expect(workgroupBounds.left, projectBounds.left);expect(workgroupBounds.right,- tester- .getRect(find.byKey(const ValueKey('super-project-toggle-lead')))- .right,+ tester.getRect(find.byKey(const ValueKey('super-group-lead'))).right,);// Workgroups share the project name column in the compact sidebar.expect(diff --git a/desktop/test/web_chrome_menus_test.dart b/desktop/test/web_chrome_menus_test.dartindex 225306ca8..1f9c25438 100644--- a/desktop/test/web_chrome_menus_test.dart+++ b/desktop/test/web_chrome_menus_test.dart@@ -1,6 +1,7 @@import 'dart:io';import 'package:flutter/material.dart';+import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';import 'package:harness/screens/swarm_screen.dart';@@ -132,15 +133,25 @@ void main() {await _done(tester, app);});- testWidgets('the avatar sits at the right end, Store before it', (- tester,- ) async {+ testWidgets('the avatar sits at the right end, Search and Notifications '+ 'before it, and Store in its menu', (tester) async {final app = await _mount(tester, _wide);- final store = find.byKey(const ValueKey('swarm-store-button'));- expect(- tester.getTopLeft(_avatar).dx,- greaterThan(tester.getTopRight(store).dx - 1),- );+ for (final key in [+ 'swarm-search-button',+ 'workspace-notifications-button',+ ]) {+ expect(+ tester.getTopLeft(_avatar).dx,+ greaterThan(tester.getTopRight(find.byKey(ValueKey(key))).dx - 1),+ reason: key,+ );+ }+ expect(find.byKey(const ValueKey('swarm-store-button')), findsNothing);+ await _tap(tester, _avatar);+ expect(find.byKey(const ValueKey('account-menu-store')), findsOneWidget);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 100));await _done(tester, app);});diff --git a/desktop/test/web_tab_switcher_test.dart b/desktop/test/web_tab_switcher_test.dartindex f93c3a621..5be08710b 100644--- a/desktop/test/web_tab_switcher_test.dart+++ b/desktop/test/web_tab_switcher_test.dart@@ -307,7 +307,8 @@ void main() {testWidgets('a wide window keeps the row of tabs', (tester) async {final app = await mount(tester, const Size(1280, 800));expect(find.byKey(const ValueKey('web-tab-switcher')), findsNothing);- expect(find.byKey(const ValueKey('swarm-store-button')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);+ expect(find.byKey(const ValueKey('swarm-store-button')), findsNothing);expect(find.byKey(const ValueKey('workspace-subscription-usage')),findsOneWidget,diff --git a/desktop/test/workspace_account_test.dart b/desktop/test/workspace_account_test.dartindex c47bf5e6a..1afe387b3 100644--- a/desktop/test/workspace_account_test.dart+++ b/desktop/test/workspace_account_test.dart@@ -11,6 +11,7 @@ import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/shared/widgets/setting_row.dart';import 'package:harness/state/app_state.dart';import 'package:harness/widgets/account_menu.dart';+import 'package:harness/widgets/desktop_workspace_tab.dart';import 'package:harness/widgets/workspace_account_button.dart';import 'support/capture.dart';@@ -92,20 +93,20 @@ void main() {// Where this app draws the row it carries the bell too; on a Mac that is// in the menu bar.final order = [- for (final control in [_search, _bell, _phone, _devices, _store, _signIn])+ for (final control in [_search, _bell, _signIn])tester.getCenter(control).dx,];- expect(- order,- [...order]..sort(),- reason: 'Search, Add Phone, Devices, Store, Sign in',- );+ expect(order, [...order]..sort(), reason: 'Search, Notifications, Sign in');// The only control in the row with a word on it.expect(find.descendant(of: _signIn, matching: find.text('Sign in')),findsOneWidget,);- for (final icon in [_search, _phone, _devices, _store]) {+ // They moved into the avatar menu (Quiet Swarm, screen 0).+ for (final moved in [_phone, _devices, _store]) {+ expect(moved, findsNothing);+ }+ for (final icon in [_search]) {expect(find.descendant(of: icon, matching: find.byType(Text)),findsNothing,@@ -113,11 +114,8 @@ void main() {}// Icons sit side by side; nothing is drawn between them and Sign in.expect(tester.getRect(_search).right, tester.getRect(_bell).left);- expect(tester.getRect(_bell).right, tester.getRect(_phone).left);- expect(tester.getRect(_phone).right, tester.getRect(_devices).left);- expect(tester.getRect(_devices).right, tester.getRect(_store).left);expect(- tester.getRect(_signIn).left - tester.getRect(_store).right,+ tester.getRect(_signIn).left - tester.getRect(_bell).right,grid.AppDesktop.controlGap,);expect(@@ -125,7 +123,6 @@ void main() {1280 - grid.AppDesktop.tabBarTrailingInset,);expect(find.byTooltip('Sign in to Harness'), findsOneWidget);- expect(find.byTooltip('Explore Harness Store · ⌃⌘S'), findsOneWidget);await _capture(tester, 'tab-row-sign-in');}, variant: TargetPlatformVariant.only(TargetPlatform.macOS));@@ -183,7 +180,7 @@ void main() {1280 - grid.AppDesktop.tabBarTrailingInset,);expect(- tester.getRect(_avatar).left - tester.getRect(_store).right,+ tester.getRect(_avatar).left - tester.getRect(_bell).right,grid.AppDesktop.controlGap,);@@ -350,12 +347,14 @@ void main() {expect(_menu, findsOneWidget);});- testWidgets('the menu: who, then five rows, no ellipses', (tester) async {+ testWidgets('the menu: who, then its rows, no ellipses', (tester) async {await _mountMenu(tester);expect(find.text('Dee Example'), findsOneWidget);expect(find.text('[email protected]'), findsOneWidget);final rows = ['Add Phone',+ 'Devices',+ 'Store','Appearance','Notifications','Settings',@@ -433,7 +432,7 @@ void main() {await tester.sendKeyEvent(LogicalKeyboardKey.enter);await tester.pump();await tester.pump();- expect(chosen, AccountMenuChoice.customize);+ expect(chosen, AccountMenuChoice.devices);await _mountMenu(tester, onChoice: answer);await tester.tapAt(const Offset(40, 700));@@ -465,6 +464,41 @@ void main() {expect(chosen, AccountMenuChoice.addPhone);});+ testWidgets('a tab that needs you is bold, with no count', (tester) async {+ Future<TextStyle?> styleOf({required bool attention}) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SizedBox(+ width: 200,+ height: 40,+ child: DesktopWorkspaceTab(+ id: 't',+ label: 'lampOS',+ selected: false,+ attention: attention,+ showShortcuts: ValueNotifier(false),+ onSelect: () {},+ onClose: () {},+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ return tester+ .widget<Text>(find.byKey(const ValueKey('tab-label:t')))+ .style;+ }++ final rest = await styleOf(attention: false);+ final bold = await styleOf(attention: true);+ expect(bold!.fontWeight, grid.AppFont.semibold);+ expect(rest!.fontWeight, isNot(grid.AppFont.semibold));+ expect(find.byType(Text), findsOneWidget);+ });+test('the one letter an account wears', () {expect(accountInitial('Dee Example', '[email protected]'), 'D');expect(accountInitial(null, '[email protected]'), 'Z');diff --git a/desktop/test/workspace_status_test.dart b/desktop/test/workspace_status_test.dartindex f78efbd44..9943af0af 100644--- a/desktop/test/workspace_status_test.dart+++ b/desktop/test/workspace_status_test.dart@@ -1809,7 +1809,8 @@ void main() {reason: 'tabs stop growing at the shared maximum in a roomy window',);expect(find.byKey(const ValueKey('swarm-search-button')), findsOneWidget);- expect(find.byKey(const ValueKey('swarm-store-button')), findsOneWidget);+ // In the avatar's menu (Quiet Swarm, screen 0).+ expect(find.byKey(const ValueKey('swarm-store-button')), findsNothing);for (final old in ['harnesses', 'machines', 'models', 'help']) {expect(find.byKey(ValueKey('swarm-$old-button')), findsNothing);}@@ -1858,18 +1859,12 @@ void main() {),);await tester.pump(const Duration(milliseconds: 100));- final store = find.byKey(const ValueKey('swarm-store-button'));+ // The row's one word is Sign in, which follows the window's text size.+ final signIn = find.byKey(const ValueKey('swarm-sign-in-button'));expect(- MediaQuery.textScalerOf(tester.element(store)).scale(13),+ MediaQuery.textScalerOf(tester.element(signIn)).scale(13),13 * scale,);- // Store is its mark alone (2026-10-11); the row's one word is Sign- // in, which follows the window's text size as Store's name did.- expect(- find.descendant(of: store, matching: find.byType(Text)),- findsNothing,- );- final signIn = find.byKey(const ValueKey('swarm-sign-in-button'));final label = find.descendant(of: signIn,matching: find.text('Sign in'),diff --git a/docs/plans/2026-11-02-phone-activity-row-landing-plan.md b/docs/plans/2026-11-02-phone-activity-row-landing-plan.mdnew file mode 100644index 000000000..c68f8593b--- /dev/null+++ b/docs/plans/2026-11-02-phone-activity-row-landing-plan.md@@ -0,0 +1,90 @@+# Phone Activity rows land on their message Implementation Plan++> **For agentic workers:** This plan is implemented by the Engineer task by task, test first (project instructions, Engineer role), not by subagent-driven-development. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Opening a row in the phone's Activity tab lands on its message: in the thread it lives in, or in the main chat, lit for 2 seconds.++**Architecture:** An Activity item says which thread (if any) its message is in and what the thread should land on (`SwarmThreadFocus`: one message, or the first unread). The chat route carries that focus through `SwarmOpenedChat` and `SwarmProjectPage` to `SwarmConversationPage`, which hands it to `SwarmThreadPage` when it opens the thread. The thread page reads earlier replies until the message is loaded, scrolls to it and lights it for 2 seconds, as the main chat's `_jumpTo` does.++**Tech Stack:** Flutter (mobile/), flutter_test widget tests with `FakeSwarm`.++**Spec:** Task #2126 brief (Tony) and the mockup posted in its conversation (message 5e649c9e). Evidence from code: `mobile/lib/swarm/swarm_activity_page.dart` `_reply`, `swarm_conversation_page.dart` `_jumpTo` / `_openThread`, `swarm_thread_page.dart`.++## Global Constraints++- Swarm code stays out of `cli/src/core`; this change is mobile only.+- Lit for exactly 2 seconds, as the main chat (`Duration(seconds: 2)`).+- Decisions stay answered in Activity: a decision row never opens a chat on a message.+- A row whose message is in the main stream (or also sent to the chat) keeps landing in the main chat as today.+- A thread whose message cannot be found (deleted, too old) opens at its top with no error and no loop.+- Never install a build on a phone; the Tester uses the simulator.+- PR body starts with "Requested by [email protected] through Harness." and holds red/green evidence in a comment.++## Review Focus++- The target is further back than the thread's first pages (5 pages): earlier pages are read until it shows, with a bound.+- The first-unread landing reads the thread's read mark before the thread page marks the thread read.+- A thread with no unread replies lands on its newest reply.+- A reply also sent to the chat (not only in its thread) still lands in the main chat.+- The lit state ends after 2 seconds and does not return when the list rebuilds.+- Back from the thread returns to the chat, then Activity, as Threads does.++## Design++N/A because nothing is stored, synced or exposed: it changes where a tap navigates and scrolls on the phone, using reads the thread page already makes. The only new read is "Show earlier replies" pages, bounded by `SwarmThreadFocus.maxEarlierPages`.++---++### Task 1: Thread page lands on a focus++**Files:**+- Modify: `mobile/lib/swarm/swarm_thread_page.dart` (new `SwarmThreadFocus`, `focus` param, `lit` in `SwarmThreadRow`)+- Modify: `mobile/lib/swarm/swarm_conversation_page.dart` (`_threadRow` passes `lit`; `_openThread(c, root, {focus})`)+- Test: `mobile/test/swarm/swarm_thread_focus_test.dart`++**Interfaces:**+- Produces: `class SwarmThreadFocus { const SwarmThreadFocus.message(String id); const SwarmThreadFocus.firstUnread(); final String? messageId; bool get firstUnread; static const maxEarlierPages = 50; }`+- Produces: `SwarmThreadPage({..., SwarmThreadFocus? focus})`; `SwarmThreadRow` gains `required bool lit`.+- Produces: `SwarmConversationPage.threadFocus` (`SwarmThreadFocus?`), used when the chat opens `threadId`.++- [ ] **Step 1: Write the failing tests** in `swarm_thread_focus_test.dart` (harness copied from `swarm_thread_jump_test.dart`): a thread of 40 replies opened with `SwarmThreadFocus.message('m20')` shows `Reply 20.` on screen and `swarm-lit-m20` present, absent after `pump(Duration(seconds: 2))`; a thread with `older: true` where `m3` is only on the earlier page (route with `before=`) reads that page and lands on `m3`; `firstUnread` with mark 10 of 40 lands on `Reply 11.`; `firstUnread` with mark 40 lands on `Reply 40.`; a missing id leaves the thread at its top with no error text.+- [ ] **Step 2: Run** `flutter test test/swarm/swarm_thread_focus_test.dart` — expect compile failure (`SwarmThreadFocus` undefined).+- [ ] **Step 3: Implement** `SwarmThreadFocus` and the page's landing: after the first load, read `loadEarlier()` while the target is missing and `hasEarlier` (at most `maxEarlierPages`), then reveal as the chat's `_reveal` does (jump near by index until the row is built, then `Scrollable.ensureVisible(alignment: 0.5)`), then set `_lit` for 2 s. `firstUnread` resolves from the thread's read mark captured in `initState` (before `markRead` moves it): the first reply with `sequence` above it, else the newest.+- [ ] **Step 4: Run** the same file — expect PASS. Commit tests first (failing), then code.++### Task 2: The chat route carries the focus++**Files:**+- Modify: `mobile/lib/swarm/swarm_project_page.dart` (`swarmChatRoute`, `SwarmOpenedChat`, `SwarmProjectPage` take `threadFocus`)+- Modify: `mobile/lib/swarm/swarm_conversation_page.dart` (`threadFocus`, `_jumpTo` passes it; a thread reply found in the chat opens its thread with `SwarmThreadFocus.message(messageId)`)+- Test: `mobile/test/swarm/swarm_thread_focus_test.dart` (group "opened from a link")++**Interfaces:**+- Consumes: Task 1's `SwarmThreadFocus`.+- Produces: `swarmChatRoute({..., SwarmThreadFocus? threadFocus})`.++- [ ] **Step 1: Write the failing test**: `SwarmConversationPage(messageId: 'm1', threadId: 'm1', threadFocus: SwarmThreadFocus.message('m20'))` shows the thread with `Reply 20.` lit; and a link with only `messageId: 'm20'` (a thread-only reply) opens its thread at `Reply 20.` lit.+- [ ] **Step 2: Run it** — expect FAIL (`threadFocus` is not a parameter).+- [ ] **Step 3: Implement** the pass-through; forget `threadFocus` with `_threadId` once the chat has shown it (swarm_project_page.dart where `_messageId = _threadId = null`).+- [ ] **Step 4: Run** — PASS. Commit.++### Task 3: Activity rows choose their landing++**Files:**+- Modify: `mobile/lib/swarm/swarm_activity.dart` (`SwarmActivityItem.threadId`, `.threadFocus`)+- Modify: `mobile/lib/swarm/swarm_activity_page.dart` (`_reply` builds the route from them)+- Test: `mobile/test/swarm/swarm_activity_landing_test.dart`++**Interfaces:**+- Produces: `String? SwarmActivityItem.threadId` (the thread root when the message lives only in a thread, else null) and `SwarmThreadFocus? SwarmActivityItem.threadFocus`. Reply and reaction server rows with `entry.threadId`, mentions with `mention.threadId`, a phone-built reaction on a thread-only message: focus on that message. `SwarmActivityThread`: `threadId` the root, `SwarmThreadFocus.firstUnread()`. A decision or work need and any main-stream row: both null.+- Route from a row: `messageId: threadId ?? messageId`, `threadId`, `threadFocus`.++- [ ] **Step 1: Write the failing tests** (harness from `swarm_activity_page_test.dart`): tapping each row type opens the right place — a server reply in a thread, a server reaction on a thread message, a tag in a thread, and each one with the message only on an earlier page of the thread (too far back to be loaded at first): `SwarmThreadPage` is up and the message is lit and on screen; a Threads row lands on its first unread, or the newest when all read; a main-chat reply, tag and reaction still land in the chat, lit, no thread page; a decision row still opens in Activity.+- [ ] **Step 2: Run** — the thread cases FAIL on main (no thread opens; the chat is shown at the root).+- [ ] **Step 3: Implement** the item getters and the route in `_reply`.+- [ ] **Step 4: Run** `flutter test test/swarm/` for the files touched plus `swarm_activity_*_test.dart`, `swarm_threads_*_test.dart`, `swarm_thread_*_test.dart`; then `flutter analyze`. Commit.++### Task 4: Evidence++- [ ] Run each new test against `origin/main`'s lib (stash the lib change) and record the failures; post red/green in a PR comment.+- [ ] Add the Tester step (phone simulator on this Mac) with the task's "Done when": each row type landing, with screenshots.diff --git a/docs/plans/2026-11-02-phone-buddy-sessions-plan.md b/docs/plans/2026-11-02-phone-buddy-sessions-plan.mdnew file mode 100644index 000000000..a5af48f06--- /dev/null+++ b/docs/plans/2026-11-02-phone-buddy-sessions-plan.md@@ -0,0 +1,116 @@+# Phone Buddy sessions Implementation Plan++> **For agentic workers:** Work task by task, test first (project instructions, revision 23: Engineer role, not subagent-driven-development). Steps use checkbox (`- [ ]`) syntax. There is no Execution Handoff: the Engineer goes on to implement.++**Goal:** In the phone app's Buddy chat, a person can start a New session (choosing All projects or one project), reply in a thread with New session (also after its session ended), see the session's status line and End session, as Desktop does.++**Architecture:** A new `mobile/lib/swarm/swarm_buddy_sessions.dart` holds the pure rules (when New session is offered or blocked, status and end words), ported from Desktop's `SuperTabController` (`threadSessionBlocked`, `offersChatSessions`, `offersThreadSessions`) and `buddy_sessions.dart`. `SwarmConversation` and `SwarmThread` carry the New session choice into `message.send` (`newSession`, `sessionProjectId`) and send `buddy.sessionEnd`. The chat composer, the thread reply box and a status line under the thread header draw it. No server changes.++**Tech Stack:** Flutter widgets and `flutter_test`, in `mobile/`.++**Spec:** `docs/superpowers/specs/2026-10-30-buddy-thread-sessions-design.md`, and Desktop's behaviour in `desktop/lib/super_tabs/{controller,view,thread_panel,buddy_sessions}.dart`. Task #2118 (Tony).++## Global Constraints++- The pull request body starts with: `Requested by [email protected] through Harness.`+- A change people see follows the Harness design language; the ASCII mockup was posted in the task conversation first.+- No server changes. Never install a build on anyone's phone.+- All projects: sends no `sessionProjectId`, reads every project, sends no work to a PM. One project: sends `sessionProjectId`, reads only that project, can hand work to its PM.+- New session on a top-level message needs `snapshot.sessionsFromChat`; on a thread reply `snapshot.threadSessions`. Neither is offered on a server that does not say so, and not for 10 minutes after a refusal for the `newSession` field.+- Only the reader's own Buddy chat (`chat.buddyOwnerId == reader.accountId`, not an older Buddy chat) offers sessions.+- Phone copy, exactly as Desktop's: "New session", "All projects · ask anything", "<Project> · ask and hand off work", "Own session" / "<Project> session", "Starting…", "<machine> is offline", "Idle", "End session", "Ending…", and the ended lines of `superTabSessionEndedWords`.++## Review Focus++- A project the person lost access to between choosing it and sending: no `sessionProjectId` goes (Desktop `_chosenSessionProject`).+- A reply with New session never also sends `alsoSend`, and never carries an agent mention (a session's thread hears only its session).+- A refused New session puts the text back in the box and says why; a plain retry sends without New session.+- A thread whose session ended starts a new one on reply: New session shows ticked and locked.+- End session pressed twice sends one `buddy.sessionEnd`; it is disabled while ending.+- A person who cannot write, an archived chat or an older Buddy chat sees no New session.++---++### Task 1: Read the session fields++**Files:**+- Modify: `mobile/lib/swarm/model.dart` (`SuperTabBuddySessionOf`, `SuperTabConversation`, `SuperTabMessage`)+- Test: `mobile/test/swarm/swarm_buddy_session_parse_test.dart`++**Interfaces:**+- Produces: `SuperTabBuddySessionOf.projectId` (`String?`); `SuperTabConversation.sessionFor(String thread)` → `SuperTabBuddySession?`; `SuperTabMessage.sessionEnded` (bool, `source.kind == 'buddy-session-ended'`), `.sessionEndReason` (`String?`), `.sessionRoot` (`buddySession && !threadReply`).++- [ ] **Step 1: Write the failing test** `session fields read as Desktop reads them`: `SuperTabBuddySessionOf.fromJson({'thread':'r','from':1,'projectId':'p'}).projectId == 'p'`, an empty or non-string `projectId` is null; `sessionFor('r')` finds the listed session and `sessionFor('x')` is null; a message with `source: {'kind':'buddy-session-ended','reason':'idle'}` has `sessionEnded` true and `sessionEndReason == 'idle'`, any other message has both false/null.+- [ ] **Step 2: Run it, expect FAIL** (`cd mobile && env -u TMUX flutter test test/swarm/swarm_buddy_session_parse_test.dart`): members not defined.+- [ ] **Step 3: Implement** the members above in `model.dart`, as Desktop's `model.dart` has them.+- [ ] **Step 4: Run it, expect PASS.**+- [ ] **Step 5: Commit** the test first (failing), then the code.++### Task 2: The session rules++**Files:**+- Create: `mobile/lib/swarm/swarm_buddy_sessions.dart`+- Test: `mobile/test/swarm/swarm_buddy_sessions_test.dart`++**Interfaces:**+- Consumes: Task 1; `swarmBuddy(reader, projectId)`, `swarmIsOwnBuddyChat`, `swarmIsOldBuddyChat` (`swarm_buddy.dart`).+- Produces:+ - `String? swarmSessionBlocked(SwarmReader reader, SuperTabConversation chat)`: null when a session can start; else "New work is paused in this Swarm", "Start your Buddy first", "Sessions need a Claude Code Buddy", or "Update Harness on <machine> to start sessions" (Desktop `threadSessionBlocked`; the Buddy is `swarmBuddy(reader, chat.projectId)`, `downSince != null` counts as not running, the machine report is `snapshot.pool(machineId)['observation']['capabilities']` containing `buddySessions`).+ - `bool swarmOffersChatSessions(SwarmReader reader, SuperTabConversation chat)`, `bool swarmOffersThreadSessions(SwarmReader reader, SuperTabConversation chat, {required bool hadSession})`.+ - `({String words, bool live})`-free helpers: `String swarmSessionWords(SuperTabBuddySession session, SwarmReader reader)` returning "Own session · Starting…" / "<Project> session · Idle" style text; `String swarmSessionEndedWords(String? reason)`.++- [ ] **Step 1: Write the failing tests**, one per rule: paused, no Buddy, Buddy down, codex Buddy, host without `buddySessions`, a clear case (null); chat offers only with `sessionsFromChat` and a Buddy; thread offers with `threadSessions` and, for a chat without a Buddy, only when `hadSession`; never in someone else's chat or an older Buddy chat; ended words per reason (`idle`, `ended`, `stopped`, `failed`, `removed`, `maintenance`, unknown).+- [ ] **Step 2: Run, expect FAIL** (file missing).+- [ ] **Step 3: Implement** in `swarm_buddy_sessions.dart`. Port Desktop's logic and words verbatim.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 3: Start a session from the chat (both modes) and end one++**Files:**+- Modify: `mobile/lib/swarm/swarm_conversation.dart` (`_compose`, state, refusal), `mobile/lib/swarm/swarm_buddy_sessions.dart` (`endSession`)+- Test: `mobile/test/swarm/swarm_chat_session_test.dart`++**Interfaces:**+- Consumes: Task 2.+- Produces on `SwarmConversation`: `bool newSession` (get/set, notifies `composer`), `String? sessionProjectId` (get/set), `bool get offersSessions`, `String? get sessionBlocked`; `Future<bool> endSession(String root)`.+- `_compose` adds `'newSession': true` and, when `sessionProjectId` names a project still in `snapshot.projects` and the chat is the Swarm Buddy chat, `'sessionProjectId'`. After the post is taken, `newSession` and `sessionProjectId` reset. A refusal naming `newSession` as an unrecognized key restores the draft and sets `error` to "New sessions aren't available yet; send without it?" and turns the offer off for 10 minutes.+- `endSession(root)` sends `{'type':'buddy.sessionEnd','conversationId':id,'thread':root,'reason':'ended'}` once; false when the chat has no session for `root`.++- [ ] **Step 1: Write the failing tests** (fail on main: no such members): All projects sends `newSession: true` and no `sessionProjectId`; one project sends `sessionProjectId`; a project missing from the snapshot sends none; New session off sends neither; a blocked chat sends no `newSession`; the refusal restores the draft and says why; `endSession` sends one `buddy.sessionEnd`, a second call while the first runs sends none.+- [ ] **Step 2: Run, expect FAIL.**+- [ ] **Step 3: Implement** as above in `SwarmConversation`.+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 4: Reply in a thread with New session++**Files:**+- Modify: `mobile/lib/swarm/swarm_thread.dart`+- Test: `mobile/test/swarm/swarm_thread_session_test.dart`++**Interfaces:**+- Consumes: Tasks 2 and 3.+- Produces on `SwarmThread`: `bool newSession` (get/set), `bool get sessionLocked` (the thread's last session ended and none is live), `String? get sessionBlocked`, `bool get offersSessions`, `SuperTabBuddySession? get session`, `SuperTabMessage? get sessionEndedRow`. `send()` adds `'newSession': true` when on (or locked and not blocked) and then never adds `alsoSend`.++- [ ] **Step 1: Write the failing tests**: a reply with New session carries `newSession` and no `alsoSend`; a thread whose session ended is locked and sends `newSession`; a live session's thread sends a plain reply; a blocked thread sends none; refusal restores the draft.+- [ ] **Step 2: Run, expect FAIL.**+- [ ] **Step 3: Implement.**+- [ ] **Step 4: Run, expect PASS.**+- [ ] **Step 5: Commit** test, then code.++### Task 5: The screens++**Files:**+- Modify: `mobile/lib/swarm/swarm_conversation_page.dart` (`_composer`), `mobile/lib/swarm/swarm_thread_page.dart` (`_box`, status line under the header)+- Create: `mobile/lib/swarm/swarm_session_widgets.dart` (New session chip, "Works in" sheet, status line)+- Test: `mobile/test/swarm/swarm_session_widgets_test.dart`++**Interfaces:**+- Consumes: Tasks 3 and 4. Keys: `swarm-new-session` (chat chip), `swarm-session-project` ("Works in" row), `swarm-session-any`, `swarm-session-in-<projectId>` (sheet rows), `swarm-thread-new-session` (reply box checkbox), `swarm-thread-session-state`, `swarm-thread-session-end`, `swarm-thread-session-ended`.++- [ ] **Step 1: Write the failing widget tests**: the chip shows only where offered and is disabled with its reason when blocked; ticking it shows "Works in: All projects"; the sheet lists All projects and each project; picking one then Send posts `sessionProjectId`; the reply box shows New session, ticked and locked after an ended session; the status line shows "Own session · …" / "<Project> session · …" and End session; End session sends once; the ended line shows the reason.+- [ ] **Step 2: Run, expect FAIL.**+- [ ] **Step 3: Implement** with the existing `SwarmComposerCard` toolbar, `phone_sheet.dart`, `AppType`, `AppPalette`, `TtyTap`, matching `_AlsoSend` and `_TagChip`.+- [ ] **Step 4: Run, expect PASS; then `flutter analyze` (0 issues outside third_party/xterm) and the whole `test/swarm` folder.**+- [ ] **Step 5: Commit** test, then code. Screenshots for the pull request come from the Tester in the simulator.diff --git a/docs/plans/2026-11-02-quiet-swarm-1-sidebar-manage-plan.md b/docs/plans/2026-11-02-quiet-swarm-1-sidebar-manage-plan.mdnew file mode 100644index 000000000..c346e81c3--- /dev/null+++ b/docs/plans/2026-11-02-quiet-swarm-1-sidebar-manage-plan.md@@ -0,0 +1,112 @@+# Quiet Swarm 1/6: sidebar, top bar and Manage Implementation Plan++> **Way of working:** by this project's instructions (Engineer role), not subagent-driven-development: each failing test committed and watched fail before its code, the branch pushed after each task, one independent review of the pull request. There is no Execution Handoff.++**Goal:** The design's sidebar, quieter top bar, Swarm switcher with only Swarms, and a Manage page holding Machines, Models, Devices and Swarm.++**Architecture:** The sidebar becomes a scrolling list with a Manage row pinned under it. Manage is a pane of the Swarm view, selected like Activity is, held by the view and not saved: a restart opens the chat. It hosts the existing machines list, models figures, devices view and delete and restore flows, each unchanged in what it does. The top bar drops Add Phone, Devices and the Store into the avatar menu, and tabs show names only.++**Tech Stack:** Flutter, `flutter_test`, in `desktop/`.++**Spec:** `docs/plans/2026-11-02-quiet-swarm-design.md`, screens 0, 1 (sidebar), 8, 10, 10b, 10c and 12. Task #2190 (Dee).++## Global Constraints++- The PR body starts with: Requested by [email protected] through Harness.+- Build exactly the design's screens; anything it doesn't draw stays as it is.+- `desktop/design/desktop-design-system.md`: no new colors, icons or controls; one line per row; fewer words.+- The project-row red number is changed separately: its widget stays as it is.+- Desktop tests use a memory store and a fake sign-in; never a test that signs this Mac out of the real CLI.+- Swarm code stays out of `cli/src/core`. No on/off switch.+- Others build the other parts in parallel: stay in this task's files, and rebase on main often.+- Dee's look at the screenshots is the merge gate, never an acceptance check.++## Review Focus++- Every function that leaves a screen still has a way in: New project (the + beside Projects), Add Phone, Devices and the Store (avatar menu, and where a shortcut or the Harness menu already opens them), Delete and Restore (Manage › Swarm).+- A Personal Swarm, a viewer, and a member who doesn't own the Swarm each see the right Manage › Swarm: no Delete for a non-owner, no Leave for its owner or in Personal.+- The Threads row goes before part 4's Activity takes Threads in: said in the PR, so the two merge together or Threads stays reachable.+- A Swarm remembered as showing Devices opens there, and an account that lost it opens the chat.+- A Swarm with no Buddy yet, or a server without one Buddy for the Swarm, still has its Buddy row or Buddies section.+- Web on a phone keeps its compact bar: its Add Phone stays off, and the ☰ still opens the sidebar.++## Design++- **Growth, migration, audience, identity:** N/A because nothing new is stored, on a server or in the saved view.+- **Concurrency:** N/A because everything here runs on the UI thread and existing commands.+- **Read cost:** the machines list and models figures build only while Manage shows them, so their timers stop at rest, as the design asks.+- **Scale:** N/A because the lists are the ones shown today.+- **Compatibility:** N/A because nothing saved changes.+- **Failure:** delete, restore and leave keep their own errors, where they now show.+- **Platforms:** macOS, Linux, Windows and the web share this code; the title-bar variant keeps its own actions.++---++### Task 1: The sidebar++**Files:**+- Modify: `desktop/lib/super_tabs/project_sidebar.dart`, `desktop/lib/super_tabs/view.dart` (its wiring only)+- Test: `desktop/test/super_tab_quiet_sidebar_test.dart`++**Interfaces:**+- Produces: `ProjectSidebar.onManage`, `manageSelected`.++- [ ] **Step 1: Write the failing tests:** Switcher, Activity, Buddy, Projects with +, the project rows, and Manage at the bottom, in that order; no New project, Your devices, Your models, Threads, Machines or Models row; + opens New project; Buddy opens the chat.+- [ ] **Step 2: Run to verify they fail.** Run: `flutter test test/super_tab_quiet_sidebar_test.dart`. Expected: FAIL.+- [ ] **Step 3: Implement.** A pinned Manage row under the list; the Buddy row moves above Projects.+- [ ] **Step 4: Run to verify they pass,** then the sidebar tests by the symbols changed.+- [ ] **Step 5: Commit** the test first, then the code; push.++### Task 2: The Manage page++**Files:**+- Create: `desktop/lib/super_tabs/manage_page.dart`+- Modify: `desktop/lib/super_tabs/machines.dart`, `desktop/lib/super_tabs/view.dart` (its pane)+- Test: `desktop/test/super_tab_manage_page_test.dart`++**Interfaces:**+- Consumes: `SuperTabMachines`, `leaderboardModelShares`, `showSwarmLocalModels`, the devices view, `DeletedSwarms`, the Swarm delete dialog, and `sharing.dart`'s leave.+- Produces: `SuperTabManagePage`, `SuperTabManageTab { machines, models, devices, swarm }`.++- [ ] **Step 1: Write the failing tests,** one per tab: Machines lists name, owner and status on one line, with Add machine; Models lists usage with Your models…; Devices shows the devices view; Swarm shows Name, Owner, People with Manage people, Delete Swarm… for its owner, Leave Swarm… for a member, restore rows.+- [ ] **Step 2: Run to verify they fail.** Run: `flutter test test/super_tab_manage_page_test.dart`. Expected: FAIL.+- [ ] **Step 3: Implement** the page, with `SuperTabMachines` given a one-line form.+- [ ] **Step 4: Run to verify they pass,** then `flutter test test/super_tab_machines_test.dart test/super_tab_devices_test.dart`.+- [ ] **Step 5: Commit** the test first, then the code; push.++### Task 3: The Swarm switcher holds only Swarms++**Files:**+- Modify: `desktop/lib/super_tabs/swarm_switcher.dart`+- Test: its own test file++- [ ] **Step 1: Write the failing test:** Personal, the Swarms, a line, New Swarm; no Delete or Restore row.+- [ ] **Step 2: Run to verify it fails.**+- [ ] **Step 3: Implement.** Delete and restore are reached from Manage › Swarm (Task 2).+- [ ] **Step 4: Run to verify it passes.**+- [ ] **Step 5: Commit** the test first, then the code; push.++### Task 4: The top bar++**Files:**+- Modify: `desktop/lib/screens/swarm_screen.dart` (`_tabStrip`, `_showAccountMenu`), `desktop/lib/widgets/account_menu.dart`, `desktop/lib/widgets/desktop_workspace_tab.dart` if its count is there+- Test: `desktop/test/account_menu_test.dart` and the tab strip's test++**Interfaces:**+- Produces: `AccountMenuChoice.devices`, `.store`.++- [ ] **Step 1: Write the failing tests:** the bar has Search, Notifications and the avatar, and no Add Phone, Devices or Store; the avatar menu opens each; a tab shows its name alone, its ⌘ number only while ⌘ is held, no count, and is bold when something there needs you.+- [ ] **Step 2: Run to verify they fail.**+- [ ] **Step 3: Implement.** Keep the bar's width sums right, and the phone's compact bar as it is.+- [ ] **Step 4: Run to verify they pass.**+- [ ] **Step 5: Commit** the test first, then the code; push.++### Task 5: The narrow window, and screenshots++**Files:**+- Test: `desktop/test/super_tab_quiet_sidebar_test.dart`+- Create: the made-up-data screens for the browser build++- [ ] **Step 1: Write the failing test** for screen 12's ☰ where the window is narrow, if it isn't shown there yet; implement it if it isn't.+- [ ] **Step 2:** Capture screens 0, 1, 8, 10, 10b, 10c and 12 from a browser build on made-up data, and put them in the PR.+- [ ] **Step 3:** Run the Desktop tests affected, mark the PR ready and ask the Reviewer.diff --git a/mobile/lib/swarm/model.dart b/mobile/lib/swarm/model.dartindex 5db4ecd94..ba706369d 100644--- a/mobile/lib/swarm/model.dart+++ b/mobile/lib/swarm/model.dart@@ -148,7 +148,7 @@ class SuperTabAgent {{'personId': final String person} => person,_ => null,},- // Read as the desktop does; the phone draws no thread sessions yet.+ // Read as the desktop does.buddySession = SuperTabBuddySessionOf.fromJson(row['buddySession']),limitedUntil = DateTime.tryParse(row['limitedUntil'] as String? ?? ''),alerting = List.unmodifiable(@@ -240,17 +240,26 @@ class SuperTabAgent {/// A thread session's thread and starting sequence (desktop model.dart).class SuperTabBuddySessionOf {- const SuperTabBuddySessionOf(this.thread, this.from);+ const SuperTabBuddySessionOf(this.thread, this.from, [this.projectId]);final String thread;final int from;+ /// The project a session of a person's one Buddy chat works in; null for a+ /// plain session and every older project chat's.+ final String? projectId;+static SuperTabBuddySessionOf? fromJson(Object? value) {if (value is! Map) return null;final json = superTabMap(value);final thread = json['thread'];if (thread is! String || thread.isEmpty) return null;final from = json['from'];- return SuperTabBuddySessionOf(thread, from is num ? from.toInt() : 0);+ final project = json['projectId'];+ return SuperTabBuddySessionOf(+ thread,+ from is num ? from.toInt() : 0,+ project is String && project.isNotEmpty ? project : null,+ );}}@@ -330,6 +339,12 @@ class SuperTabConversation {? SuperTabTask.fromJson(superTabMap(row['task'])): null,lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,+ requesterId = row['requesterId'] as String?,+ shippedAt = row['shippedAt'] is num+ ? DateTime.fromMillisecondsSinceEpoch(+ (row['shippedAt'] as num).toInt(),+ )+ : null,lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),reactionSeq = (row['reactionSeq'] as num?)?.toInt() ?? 0,changedAt = row['changedAt'] is num@@ -368,8 +383,20 @@ class SuperTabConversation {/// A Buddy chat's live or starting thread sessions (desktop model.dart).final List<SuperTabBuddySession> buddySessions;++ /// The live or starting session answering [thread], if any.+ SuperTabBuddySession? sessionFor(String thread) =>+ buddySessions.where((s) => s.thread == thread).firstOrNull;final SuperTabTask? task;final int? number;++ /// The person who asked for this task; null on a conversation that is no+ /// task, and from a server that does not say.+ final String? requesterId;++ /// When it shipped (its first Done); null until it has, and from a server+ /// that does not say.+ final DateTime? shippedAt;String get label => number == null ? title : '#$number $title';final String? leadId;final List<String> agentIds;@@ -556,6 +583,10 @@ class SuperTabSnapshot {harness: effort,}),localModels = SuperTabLocalModels.read(row['localModels']),+ removedMachines = [+ for (final id in row['removedMachines'] as List? ?? const [])+ if (id is String) id,+ ],threadSessions = row['threadSessions'] == true,sessionsFromChat = row['sessionsFromChat'] == true,swarmBuddy = row['swarmBuddy'] == true,@@ -638,10 +669,15 @@ class SuperTabSnapshot {/// Whether this Swarm's server takes a thread reply's New session: true only/// where it says so (backend read/contract.ts `threadSessions`). Read as the- /// desktop reads it (desktop_parity_test.dart); the phone offers no New- /// session yet.+ /// desktop reads it (desktop_parity_test.dart); the Buddy chat's thread reply+ /// box offers New session by it (swarm_buddy_sessions.dart).final bool threadSessions;+ /// The reader's own machines they took out of this Swarm: an automatic add+ /// leaves them out (backend model.ts removedMachines). Empty from an older+ /// backend.+ final List<String> removedMachines;+/// Whether that server also takes New session on a top-level message in a/// Buddy chat (read/contract.ts `sessionsFromChat`); false from an older one.final bool sessionsFromChat;@@ -1197,6 +1233,14 @@ class SuperTabMessage {/// A reply in a Buddy thread session's thread (desktop model.dart).final bool buddySession;++ /// The line the server writes in a thread when its session ends.+ bool get sessionEnded => source['kind'] == 'buddy-session-ended';++ /// Why its session ended, for [sessionEnded] rows: `ended`, `idle`,+ /// `stopped` or `failed`.+ String? get sessionEndReason =>+ sessionEnded ? source['reason'] as String? : null;bool get threadReply => thread != null && thread != id;/// Whether the main stream lists it: a thread reply only when also sent.diff --git a/mobile/lib/swarm/parts.dart b/mobile/lib/swarm/parts.dartindex 85b325878..e29c12d95 100644--- a/mobile/lib/swarm/parts.dart+++ b/mobile/lib/swarm/parts.dart@@ -24,6 +24,7 @@ class SuperTabPartsChange {this.removedGroups = const {},this.dormantGroups = const {},this.readMarksOnly = false,+ this.machinesOnly = false,});/// Some part or a derived value is new: what the screens draw may differ.@@ -37,6 +38,10 @@ class SuperTabPartsChange {/// Only the reader's read marks moved: the page around the view, not what a saved view holds.final bool readMarksOnly;++ /// Only what a machine reports moved (its reading, its Lent, its worked-out+ /// values): what shows machines may differ, nothing else.+ final bool machinesOnly;}/// The parts of one Swarm as this reader last saw them (section 5.1): every part by kind and key at the newest@@ -224,12 +229,14 @@ class SuperTabParts {/// the group out of the active ones, `derived` is replaced, and the cursor moves. A reload answer is the caller's.SuperTabPartsChange apply(Map<String, dynamic> changes) {var changed = false;+ // Anything but a machine's own report moved.+ var beyondMachines = false;final removed = <String>{}, dormant = <String>{};if (changes['head'] != null) {final head = _envelope(changes['head'], live: true);if (_newer('head', head)) {_head = head;- changed = true;+ changed = beyondMachines = true;}}for (final kind in _lists) {@@ -239,6 +246,9 @@ class SuperTabParts {final key = part['key'] as String;if (!_newer('$kind:$key', part)) continue;changed = true;+ if (kind != 'machines' || !_reportOnly(held[key], part)) {+ beyondMachines = true;+ }if (part['deleted'] == true) {held.remove(key);if (kind == 'groups') {@@ -281,6 +291,7 @@ class SuperTabParts {_takeChatSettings(derived.remove('chatSettings')) |readMarksMoved;if (!const DeepCollectionEquality().equals(derived, _derived)) {+ if (!_sameBeyondMachines(derived, _derived)) beyondMachines = true;_derived = derived;changed = true;}@@ -292,9 +303,45 @@ class SuperTabParts {removedGroups: removed,dormantGroups: dormant,readMarksOnly: marksMoved && !changed,+ machinesOnly: changed && !beyondMachines && !marksMoved,);}+ /// Whether [next] says of a held machine only what its reports write: a+ /// heartbeat. A new machine, a removed one, or one renamed or paused is news+ /// to more than the machines list.+ static bool _reportOnly(+ Map<String, dynamic>? held,+ Map<String, dynamic> next,+ ) {+ if (held == null || next['deleted'] == true || next['data'] == null) {+ return false;+ }+ Map<String, dynamic> rest(Map<String, dynamic> part) =>+ Map.of(superTabMap(part['data']))+ ..remove('observation')+ ..remove('lent')+ ..remove('lentDays');+ return const DeepCollectionEquality().equals(rest(held), rest(next));+ }++ static bool _sameBeyondMachines(+ Map<String, dynamic> a,+ Map<String, dynamic> b,+ ) => const DeepCollectionEquality().equals(+ Map.of(a)..remove('machines'),+ Map.of(b)..remove('machines'),+ );++ /// The machines as [state] lists them, with what the server worked out.+ List<Map<String, dynamic>> get machines {+ final worked = _derivedMap('machines');+ return [+ for (final machine in _data('machines'))+ _overlay(machine, worked[machine['machineId']]),+ ];+ }+/// Takes dormant groups read on demand (section 4.5): a page of the dormant list, or one group by id. Each is kept/// unless this reader already holds a newer version of it; one that is active here at a lower version moves out.SuperTabPartsChange addDormant(List groups) {@@ -323,7 +370,6 @@ class SuperTabParts {/// groups come first in the order they were read, then the dormant groups held.Map<String, dynamic> get state {final agentsDerived = _derivedMap('agents');- final machinesDerived = _derivedMap('machines');final avatars = _derivedMap('avatars');final state = <String, dynamic>{...superTabMap(_head['data']),@@ -347,10 +393,7 @@ class SuperTabParts {..._data('groups'),for (final part in _dormant.values) superTabMap(part['data']),],- 'machines': [- for (final machine in _data('machines'))- _overlay(machine, machinesDerived[machine['machineId']]),- ],+ 'machines': machines,'starts': [for (final start in _data('starts')) start],'githubApp': githubApp,};diff --git a/mobile/lib/swarm/swarm_activity.dart b/mobile/lib/swarm/swarm_activity.dartindex 427954a26..a42f69561 100644--- a/mobile/lib/swarm/swarm_activity.dart+++ b/mobile/lib/swarm/swarm_activity.dart@@ -10,6 +10,7 @@ import 'swarm_chat_peeks.dart';import 'swarm_inbox.dart';import 'swarm_reader.dart';import 'swarm_session.dart';+import 'swarm_thread.dart' show SwarmThreadFocus;/// Activity's filters, as Tony's prototype C3 names them.enum SwarmActivityFilter {@@ -50,6 +51,14 @@ sealed class SwarmActivityItem {/// When it happened, where that is known.DateTime? get at;++ /// The root of the thread the row's message lives only in; null for a+ /// message in the chat's main stream, which Reply lands on in the chat.+ String? get threadId => null;++ /// Where that thread lands: on the row's message, or at its first unread+ /// reply for a row that stands for the whole thread.+ SwarmThreadFocus? get threadFocus => null;}/// Something a Swarm asks of the person ([SwarmNeed]): Needs you, or @ for a@@ -75,6 +84,19 @@ class SwarmActivityNeed extends SwarmActivityItem {_ => null,};+ @override+ String? get threadId => switch (need) {+ SwarmMentionNeed(:final mention) => mention.threadId,+ _ => null,+ };++ @override+ SwarmThreadFocus? get threadFocus => switch (need) {+ SwarmMentionNeed(:final mention) when mention.threadId != null =>+ SwarmThreadFocus.message(mention.messageId),+ _ => null,+ };+@overrideDateTime? get at => switch (need) {SwarmDecisionNeed(:final decision) => decision.createdAt,@@ -136,6 +158,12 @@ class SwarmActivityThread extends SwarmActivityItem {@overrideString? get messageId => thread.id;+ @override+ String? get threadId => thread.id;++ @override+ SwarmThreadFocus? get threadFocus => const SwarmThreadFocus.firstUnread();+@overrideDateTime? get at => thread.lastAt;}@@ -161,6 +189,13 @@ class SwarmActivityServerItem extends SwarmActivityItem {@overrideString? get messageId => entry.threadId ?? entry.messageId;+ @override+ String? get threadId => entry.threadId;++ @override+ SwarmThreadFocus? get threadFocus =>+ entry.threadId == null ? null : SwarmThreadFocus.message(entry.messageId);+@overrideDateTime? get at => entry.createdAt;}@@ -193,6 +228,13 @@ class SwarmActivityReaction extends SwarmActivityItem {@overrideString? get messageId => message.id;+ @override+ String? get threadId => message.inMainStream ? null : message.thread;++ @override+ SwarmThreadFocus? get threadFocus =>+ threadId == null ? null : SwarmThreadFocus.message(message.id);+@overrideDateTime? get at => message.createdAt;@@ -513,6 +555,18 @@ class SwarmActivity extends ChangeNotifier {notifyListeners();}+ /// Where [item]'s thread lands when it is opened: ask before [replied],+ /// which reads a whole thread, so its first unread reply is still known.+ SwarmThreadFocus? landingOf(SwarmActivityItem item) {+ if (item is! SwarmActivityThread) return item.threadFocus;+ final reader = inbox.reader(item.swarmId);+ final through =+ reader?.readMarks?.threadThrough(item.chatId, item.thread.id) ??+ reader?.snapshot?.threadMarks[item.chatId]?[item.thread.id] ??+ 0;+ return SwarmThreadFocus.firstUnread(after: through);+ }+bool _open(SwarmActivityNeed item) =>inbox.needs.any((need) => need.key == item.key);diff --git a/mobile/lib/swarm/swarm_activity_page.dart b/mobile/lib/swarm/swarm_activity_page.dartindex f5e1cd0f4..279745353 100644--- a/mobile/lib/swarm/swarm_activity_page.dart+++ b/mobile/lib/swarm/swarm_activity_page.dart@@ -472,7 +472,8 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {);}- /// Opens where [item] was asked, at its message, and counts it handled. A+ /// Opens where [item] was asked, at its message — in its thread, opened+ /// over the chat, when it lives there — and counts it handled. A/// decision opens its chat at the end: decisions are answered here, never/// shown in a chat.void _reply(@@ -480,13 +481,18 @@ class _SwarmActivityViewState extends State<SwarmActivityView> {SwarmSession session,SwarmActivityItem item,) {+ final focus = session.activity.landingOf(item);session.activity.replied(item);unawaited(Navigator.of(context).push(swarmChatRoute(swarmId: item.swarmId,conversationId: item.conversationId,- messageId: item.messageId,+ // A thread opens over the chat at its root, which the chat shows+ // behind it.+ messageId: item.threadId ?? item.messageId,+ threadId: item.threadId,+ threadFocus: focus,),),);diff --git a/mobile/lib/swarm/swarm_buddy_sessions.dart b/mobile/lib/swarm/swarm_buddy_sessions.dartnew file mode 100644index 000000000..e384a4cb7--- /dev/null+++ b/mobile/lib/swarm/swarm_buddy_sessions.dart@@ -0,0 +1,138 @@+import 'model.dart';+import 'swarm_buddy.dart';+import 'swarm_outbox.dart' show SwarmPost;+import 'swarm_reader.dart';++// Buddy thread sessions on the phone (spec docs/superpowers/specs/2026-10-30-+// buddy-thread-sessions-design.md; Desktop's `SuperTabController` and+// `buddy_sessions.dart`): a message or thread of the person's own Buddy chat+// may start a session of its own, answering there while the Buddy keeps+// answering the chat. This holds the rules for when that is offered and the+// words for how a session stands; the chat and its thread carry the choice.++/// What a message refused for New session says: the server does not take it+/// yet (an older backend, or one of its servers during a release).+const swarmSessionsUnavailable =+ "New sessions aren't available yet; send without it?";++/// Whether [post] was refused only because the server does not know New+/// session (the schema's `Unrecognized key`, naming the field).+bool swarmRefusedForSessions(SwarmPost post) {+ final command = post.body['command'];+ final failure = post.refusedBy;+ return command is Map &&+ command['newSession'] == true &&+ failure != null &&+ failure.code == 'VALIDATION_ERROR' &&+ failure.message.contains('Unrecognized key') &&+ failure.message.contains('newSession');+}++/// How long New session is not offered after a server refused it.+const swarmSessionsRefusedFor = Duration(minutes: 10);++final _refusedAt = Expando<DateTime>('swarm sessions refused');++/// [reader]'s server refused New session as an unknown field, though it said+/// it takes it: not offered for [swarmSessionsRefusedFor] after.+void swarmSessionsRefused(SwarmReader reader, {DateTime? now}) =>+ _refusedAt[reader] = now ?? DateTime.now();++bool _serverTakesSessions(SwarmReader reader, {required bool fromChat}) {+ final snapshot = reader.snapshot;+ if (snapshot == null ||+ !snapshot.threadSessions ||+ (fromChat && !snapshot.sessionsFromChat)) {+ return false;+ }+ final refused = _refusedAt[reader];+ return refused == null ||+ DateTime.now().difference(refused) >= swarmSessionsRefusedFor;+}++/// Whether [chat] is the reader's own Buddy chat, where a thread may have a+/// session of its own: not someone else's, nor an older one kept to read.+bool swarmOwnBuddyChat(SwarmReader reader, SuperTabConversation chat) =>+ !reader.accessRevoked &&+ chat.isBuddyChat &&+ chat.buddyOwnerId == reader.accountId &&+ !swarmIsOldBuddyChat(reader, chat.id);++/// Whether [chat]'s own composer shows New session: the reader's own Buddy+/// chat, with a Buddy, on a server that takes New session on a top-level+/// message. It may still show disabled, saying why ([swarmSessionBlocked]).+bool swarmOffersChatSessions(SwarmReader reader, SuperTabConversation chat) =>+ swarmOwnBuddyChat(reader, chat) &&+ _serverTakesSessions(reader, fromChat: true) &&+ swarmBuddy(reader, chat.projectId) != null;++/// Whether [chat]'s thread reply box shows New session: the reader's own+/// Buddy chat, with a Buddy — or a thread that [hadSession], whose reply must+/// start a new one. It may still show disabled, saying why.+bool swarmOffersThreadSessions(+ SwarmReader reader,+ SuperTabConversation chat, {+ required bool hadSession,+}) =>+ swarmOwnBuddyChat(reader, chat) &&+ _serverTakesSessions(reader, fromChat: false) &&+ (swarmBuddy(reader, chat.projectId) != null || hadSession);++/// Why [chat] cannot start a session now, as the disabled choice says it;+/// null when it can, as far as the phone can tell (the server still decides,+/// and its refusal shows in the composer).+String? swarmSessionBlocked(SwarmReader reader, SuperTabConversation chat) {+ final snapshot = reader.snapshot;+ if (snapshot == null) return null;+ if (snapshot.paused) return 'New work is paused in this Swarm';+ final main = swarmBuddy(reader, chat.projectId);+ if (main == null || main.downSince != null) return 'Start your Buddy first';+ if (main.engine != 'claude') return 'Sessions need a Claude Code Buddy';+ // The host says what it can run in its report; a machine the phone has no+ // report of is left to the server.+ final observation = snapshot.pool(main.machineId)?['observation'];+ if (observation is Map) {+ final capabilities = observation['capabilities'];+ if (capabilities is! List || !capabilities.contains('buddySessions')) {+ return 'Update Harness on ${swarmBuddyMachineName(reader, main.machineId)} '+ 'to start sessions';+ }+ }+ return null;+}++/// Why a session ended, as its thread says it.+String swarmSessionEndedWords(String? reason) => switch (reason) {+ 'idle' => 'Session ended: idle for 30 minutes',+ 'ended' => 'Session ended: you ended it',+ 'stopped' => 'Session ended: it stopped unexpectedly',+ 'failed' => 'Session ended: it couldn\'t start',+ 'removed' => 'Session ended: its Buddy was removed or replaced',+ 'maintenance' => 'Session ended: Harness was updated',+ _ => 'Session ended',+};++/// A live session's line: which session it is and how it stands. A session of+/// one project names it ("Web session"), else it is the "Own session"; it is+/// starting until its agent joins, offline while its machine reports it gone,+/// else running (the phone sees no terminal to tell working from idle).+String swarmSessionWords(+ SwarmReader reader,+ SuperTabConversation chat,+ SuperTabBuddySession session,+) {+ final agent = session.agentId == null+ ? null+ : reader.snapshot?.agent(session.agentId!);+ final projectId = agent?.buddySession?.projectId;+ final project = projectId == null+ ? null+ : reader.snapshot?.projects.where((p) => p.id == projectId).firstOrNull;+ final who = project == null ? 'Own session' : '${project.name} session';+ final state = agent == null+ ? 'Starting…'+ : agent.downSince != null+ ? '${swarmBuddyMachineName(reader, agent.machineId)} is offline'+ : 'Running';+ return '$who · $state';+}diff --git a/mobile/lib/swarm/swarm_conversation.dart b/mobile/lib/swarm/swarm_conversation.dartindex 7c11f9ab3..7a1b74fcf 100644--- a/mobile/lib/swarm/swarm_conversation.dart+++ b/mobile/lib/swarm/swarm_conversation.dart@@ -7,6 +7,7 @@ import 'model.dart';import 'prompt_alerts.dart';import 'swarm_chat_cache.dart';import 'swarm_buddy.dart' show swarmIsOldBuddyChat;+import 'swarm_buddy_sessions.dart';import 'swarm_outbox.dart';import 'swarm_outgoing_files.dart';import 'swarm_reader.dart';@@ -257,7 +258,12 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_uploads.forget(post.files);}_restore(post);- error = post.error;+ if (swarmRefusedForSessions(post)) {+ swarmSessionsRefused(reader);+ error = swarmSessionsUnavailable;+ } else {+ error = post.error;+ }},);@@ -316,6 +322,106 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {_composer.changed();}+ /// New session is chosen for the next post (Desktop's chat composer), and+ /// the project it works in: none is All projects.+ bool _newSession = false;+ String? _sessionProjectId;++ /// Whether the composer shows New session: the person's own Buddy chat, on+ /// a server that takes it, where they may post. It may still show disabled,+ /// saying why ([sessionBlocked]).+ bool get offersSessions {+ final group = conversation;+ return group != null && canPost && swarmOffersChatSessions(reader, group);+ }++ /// Why New session cannot start a session now; null when it can.+ String? get sessionBlocked {+ final group = conversation;+ return group == null || !offersSessions+ ? null+ : swarmSessionBlocked(reader, group);+ }++ /// Whether the next post starts a session: chosen, offered and not blocked.+ bool get newSession =>+ _newSession && offersSessions && sessionBlocked == null;+ set newSession(bool value) {+ if (_newSession == value) return;+ _newSession = value;+ _composer.changed();+ }++ /// The project the next session works in, while the person still reads it+ /// (a lost one is no longer chosen); null is All projects: it reads every+ /// project and sends no work to a PM.+ String? get sessionProjectId =>+ reader.snapshot?.projects.any((p) => p.id == _sessionProjectId) == true+ ? _sessionProjectId+ : null;+ set sessionProjectId(String? value) {+ if (_sessionProjectId == value) return;+ _sessionProjectId = value;+ _composer.changed();+ }++ /// The threads whose session an end is under way for.+ final _ending = <String>{};++ /// Why the last End session was refused; null when it was not. The page+ /// that pressed it says it (the thread's).+ String? endRefusal;++ /// Whether an end is under way for [root]'s session.+ bool endingSession(String root) => _ending.contains(root);++ /// Ends [root]'s session in the person's own Buddy chat (Desktop's+ /// `endThreadSession`): closing the thread only hides it, this stops it.+ /// False when there is none, one end is already under way, or the backend+ /// refused (said in [error]).+ Future<bool> endSession(String root) async {+ final group = conversation;+ if (_disposed ||+ group == null ||+ !canPost ||+ group.sessionFor(root) == null ||+ !_ending.add(root)) {+ return false;+ }+ endRefusal = null;+ notifyListeners();+ String? refused;+ try {+ await reader.request(+ 'POST',+ '/api/super-tabs/${Uri.encodeComponent(reader.tabId)}/commands',+ body: {+ 'operationId': superTabOperationId(),+ 'command': {+ 'type': 'buddy.sessionEnd',+ 'conversationId': id,+ 'thread': root,+ 'reason': 'ended',+ },+ },+ );+ } on SuperTabFailure catch (failure) {+ refused = failure.message;+ } catch (_) {+ refused = 'The session did not end. Try again.';+ }+ if (_disposed) return refused == null;+ _ending.remove(root);+ if (refused != null) {+ endRefusal = refused;+ } else {+ unawaited(reader.refresh());+ unawaited(_reread());+ }+ notifyListeners();+ return refused == null;+ }+/// The person may post here: a writer of the Swarm, in a conversation that/// is not archived, nor an older Buddy chat kept to read.bool get canPost {@@ -734,6 +840,8 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {if (ids == null || _disposed) return false;final body = _compose(ids);if (body == null) return false;+ final startsSession = newSession;+ final root = _replyingTo?.thread ?? _replyingTo?.id;final post = SwarmPost(body: body,messageId: superTabMessageId(@@ -742,17 +850,39 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {operationId: body['operationId'] as String,),files: outgoing,- held: (draft: _draft, mentions: Map.of(_mentions), replyTo: _replyingTo),+ held: (+ draft: _draft,+ mentions: Map.of(_mentions),+ replyTo: _replyingTo,+ newSession: _newSession,+ sessionProjectId: _sessionProjectId,+ ),);_draft = '';_mentions.clear();_replyingTo = null;+ _newSession = false;+ _sessionProjectId = null;// Only what goes with this post: more may have been added meanwhile.for (final file in outgoing) {files.remove(file);}error = null;- return _answered(post, await _outbox.add(post));+ final taken = _answered(post, await _outbox.add(post));+ // Its thread opens beside the chat: the session answers there. A+ // top-level message is its own thread's root.+ if (taken && startsSession) _startedRoot = root ?? post.messageId;+ return taken;+ }++ String? _startedRoot;++ /// The thread whose session the last post started, once the backend took+ /// it; read once.+ String? takeStartedSession() {+ final root = _startedRoot;+ _startedRoot = null;+ return root;}/// Sends [post], not confirmed, again under its own operation id: the@@ -1208,12 +1338,20 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {String draft,Map<String, String> mentions,SuperTabMessage? replyTo,+ bool newSession,+ String? sessionProjectId,})) {return;}_draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';_mentions.addAll(sent.mentions);_replyingTo ??= sent.replyTo;+ // Refused for New session itself, it comes back without it, ready to send+ // as a plain message; refused for anything else, the choice stays.+ if (!swarmRefusedForSessions(post)) {+ _newSession = _newSession || sent.newSession;+ _sessionProjectId ??= sent.sessionProjectId;+ }if (post.files.isNotEmpty) {final since = files.files;files@@ -1250,6 +1388,10 @@ class SwarmConversation extends ChangeNotifier implements SwarmFilesBox {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,+ if (newSession) 'newSession': true,+ // A New session in one project of the person's one Buddy chat.+ if (newSession && sessionProjectId != null && group.isSwarmBuddyChat)+ 'sessionProjectId': sessionProjectId,},};}diff --git a/mobile/lib/swarm/swarm_conversation_page.dart b/mobile/lib/swarm/swarm_conversation_page.dartindex 4f03a1cbe..d94ac84fa 100644--- a/mobile/lib/swarm/swarm_conversation_page.dart+++ b/mobile/lib/swarm/swarm_conversation_page.dart@@ -25,6 +25,7 @@ import 'swarm_post_line.dart';import 'swarm_attach.dart';import 'swarm_buddy.dart';import 'swarm_buddy_chat.dart';+import 'swarm_session_widgets.dart';import 'swarm_buddy_tab.dart'show SwarmBuddyDot, SwarmBuddyMark, swarmBuddyMark;import 'swarm_chat_menu.dart';@@ -117,6 +118,7 @@ class SwarmConversationPage extends StatefulWidget {this.buddy,this.messageId,this.threadId,+ this.threadFocus,this.mention,this.homeC = false,this.tabRoot = false,@@ -131,6 +133,9 @@ class SwarmConversationPage extends StatefulWidget {/// chat behind it at the root.final String? threadId;+ /// Where [threadId]'s thread lands as it opens; its top when none.+ final SwarmThreadFocus? threadFocus;+/// An agent to @mention in the draft as the chat opens: the PM, as its/// private line is answered in the project chat.final String? mention;@@ -176,6 +181,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// What the last pick left out, or why it could not pick, over the files.final _attachNote = ValueNotifier<String?>(null);+ /// Why New session is greyed, once it is tapped (a phone has no hover).+ final _sessionNote = ValueNotifier<String?>(null);+/// A picker is up: one at a time.bool _picking = false;@@ -702,6 +710,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_text.dispose();_focus.dispose();_attachNote.dispose();+ _sessionNote.dispose();_scroll.dispose();super.dispose();}@@ -823,6 +832,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>void _send(SwarmConversation c) {_target = null;_attachNote.value = null;+ _sessionNote.value = null;if (_scroll.hasClients && _scroll.offset > 0) _toFoot();unawaited(_post(c));}@@ -832,9 +842,14 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// typed; a post refused or not confirmed keeps it up, to send again.Future<void> _post(SwarmConversation c) async {final sent = await c.send();+ final started = c.takeStartedSession();if (sent && mounted && _conversation == c && c.draft.isEmpty) {_focus.unfocus();}+ // A message that started a session opens its thread: it answers there.+ if (sent && started != null && mounted && _conversation == c) {+ _openThread(c, started);+ }}/// Sends [post], not confirmed, again from where it shows; taken, the@@ -853,7 +868,11 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>}/// Opens [root]'s thread of [c] over the chat, full screen.- void _openThread(SwarmConversation c, String root) {+ void _openThread(+ SwarmConversation c,+ String root, {+ SwarmThreadFocus? focus,+ }) {if (_acting != null) setState(() => _acting = null);_focus.unfocus();unawaited(@@ -865,17 +884,27 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>swarmId: widget.swarmId,chat: c,root: root,+ focus: focus,title: _view.value?.title,row:- (t, m, {required grouped, required acting, required onTap}) =>- _threadRow(- c,- t,- m,- grouped: grouped,- acting: acting,- onTap: onTap,- ),+ (+ t,+ m, {+ required grouped,+ required acting,+ required lit,+ required followed,+ required onTap,+ }) => _threadRow(+ c,+ t,+ m,+ grouped: grouped,+ acting: acting,+ lit: lit,+ followed: followed,+ onTap: onTap,+ ),pending: (t, post) => _threadPending(c, t, post),),),@@ -893,6 +922,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>SuperTabMessage m, {required bool grouped,required bool acting,+ required bool lit,+ required bool followed,required VoidCallback onTap,}) {final view = _view.value;@@ -910,7 +941,8 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>taggedAddresses: _taggedOf(c, m),readerId: c.reader.accountId,grouped: grouped,- lit: false,+ lit: lit,+ followed: followed,quote: null,actions: acting,onTap: onTap,@@ -965,6 +997,7 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>/// The thread the chat opens with, until its first jump/// ([SwarmConversationPage.threadId]).late String? _threadAt = widget.threadId;+ late SwarmThreadFocus? _threadFocusAt = widget.threadFocus;/// Brings [messageId] into view and lights it — read in from earlier pages/// when it is further back — or says why it cannot.@@ -972,8 +1005,9 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>if (_finding) return;// Only the jump the chat opened with opens [SwarmConversationPage.threadId]:// a quote of the root tapped later brings the root into view.- final thread = _threadAt;+ final thread = _threadAt, focus = _threadFocusAt;_threadAt = null;+ _threadFocusAt = null;final landing = _land();setState(() {_finding = true;@@ -993,10 +1027,13 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>if (thread == messageId &&!c.reader.accessRevoked &&c.reader.snapshot?.conversation(c.id) != null) {- _openThread(c, messageId);- }- if (target != null && target.threadReply) {- _openThread(c, target.thread!);+ _openThread(c, messageId, focus: focus);+ } else if (target != null && target.threadReply) {+ _openThread(+ c,+ target.thread!,+ focus: SwarmThreadFocus.message(messageId),+ );if (!target.inMainStream) {setState(() => _finding = false);if (!_scroll.hasClients || _scroll.offset <= _readingBack) {@@ -2167,6 +2204,34 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>style: AppType.caption(color: AppPalette.textSecondary),),),+ ValueListenableBuilder(+ valueListenable: _sessionNote,+ builder: (context, note, _) => note == null || talking+ ? const SizedBox.shrink()+ : Padding(+ padding: const EdgeInsets.fromLTRB(+ AppSpace.xs,+ 0,+ AppSpace.xs,+ AppSpace.s,+ ),+ child: Text(+ note,+ key: const ValueKey('swarm-session-note'),+ style: AppType.caption(color: tty.yellow),+ ),+ ),+ ),+ // Where a session works is the Swarm's one Buddy chat's to pick;+ // a project's own Buddy chat sends no project.+ if (c.newSession &&+ !talking &&+ c.conversation?.isSwarmBuddyChat == true)+ SwarmSessionProjectRow(+ key: const ValueKey('swarm-session-project'),+ chat: c,+ onTap: () => unawaited(showSwarmSessionProjects(context, c)),+ ),Flexible(child: SwarmComposerCard(focus: _focus,@@ -2203,7 +2268,30 @@ class _SwarmConversationPageState extends State<SwarmConversationPage>_focus.requestFocus();},),- const Spacer(),+ // The rest of the row: the chip takes what its label+ // needs, and gives up letters only when the row is full.+ Expanded(+ child: c.offersSessions+ ? Align(+ alignment: Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.only(+ left: AppSpace.xs,+ ),+ child: SwarmNewSessionChip(+ on: c.newSession,+ blocked: c.sessionBlocked,+ onChanged: (on) {+ _sessionNote.value = null;+ c.newSession = on;+ },+ onBlocked: () =>+ _sessionNote.value = c.sessionBlocked,+ ),+ ),+ )+ : const SizedBox.shrink(),+ ),if (voice != null) SwarmVoiceMic(voice: voice),SwarmRoundButton(key: const ValueKey('swarm-send'),diff --git a/mobile/lib/swarm/swarm_project_page.dart b/mobile/lib/swarm/swarm_project_page.dartindex 06622cd0c..c765a5fb8 100644--- a/mobile/lib/swarm/swarm_project_page.dart+++ b/mobile/lib/swarm/swarm_project_page.dart@@ -35,6 +35,7 @@ import 'swarm_session.dart';import 'swarm_style.dart';import 'swarm_task_status.dart';import 'swarm_terminal_row.dart';+import 'swarm_thread.dart' show SwarmThreadFocus;import 'swarm_unread.dart';import 'team_glance.dart';@@ -105,20 +106,23 @@ void openSwarmProject(}/// A route to chat [conversationId] of Swarm [swarmId], at [messageId], or-/// with [threadId]'s thread open over it at its root, as a notice, a link,-/// Activity, Threads or a row opens it ([SwarmOpenedChat]). A decision opens-/// in Activity instead, where it is answered.+/// with [threadId]'s thread open over it at its root, or at [threadFocus],+/// as a notice, a link, Activity, Threads or a row opens it+/// ([SwarmOpenedChat]). A decision opens in Activity instead, where it is+/// answered.Route<void> swarmChatRoute({required String swarmId,required String conversationId,String? messageId,String? threadId,+ SwarmThreadFocus? threadFocus,}) => phoneRoute((_) => SwarmOpenedChat(swarmId: swarmId,conversationId: conversationId,messageId: messageId,threadId: threadId,+ threadFocus: threadFocus,),listensForItself: true,);@@ -143,6 +147,7 @@ class SwarmOpenedChat extends StatefulWidget {required this.conversationId,this.messageId,this.threadId,+ this.threadFocus,});final String swarmId, conversationId;@@ -151,6 +156,9 @@ class SwarmOpenedChat extends StatefulWidget {/// The thread opened over the chat ([SwarmConversationPage.threadId]).final String? threadId;+ /// Where that thread lands ([SwarmConversationPage.threadFocus]).+ final SwarmThreadFocus? threadFocus;+@overrideState<SwarmOpenedChat> createState() => _SwarmOpenedChatState();}@@ -265,6 +273,7 @@ class _SwarmOpenedChatState extends State<SwarmOpenedChat> {projectId: projectId,messageId: widget.messageId,threadId: widget.threadId,+ threadFocus: widget.threadFocus,),null => SwarmConversationPage(key: const ValueKey('swarm-opened-chat'),@@ -272,6 +281,7 @@ class _SwarmOpenedChatState extends State<SwarmOpenedChat> {conversationId: widget.conversationId,messageId: widget.messageId,threadId: widget.threadId,+ threadFocus: widget.threadFocus,),};}@@ -296,6 +306,7 @@ class SwarmProjectPage extends StatefulWidget {this.mention,this.messageId,this.threadId,+ this.threadFocus,});final String swarmId, projectId;@@ -315,6 +326,9 @@ class SwarmProjectPage extends StatefulWidget {/// ([SwarmConversationPage.threadId]). Only the first time the chat shows.final String? messageId, threadId;+ /// Where that thread lands ([SwarmConversationPage.threadFocus]).+ final SwarmThreadFocus? threadFocus;+@overrideState<SwarmProjectPage> createState() => _SwarmProjectPageState();}@@ -331,6 +345,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {/// Where the chat opens ([SwarmProjectPage.messageId]): forgotten once/// another tab is picked, so the chat shown again opens at its end.late String? _messageId = widget.messageId, _threadId = widget.threadId;+ late SwarmThreadFocus? _threadFocus = widget.threadFocus;/// What the page shows of the inbox ([_inboxChanged]): its Swarm's/// reader, whether there are several Swarms, why the list was not read.@@ -613,6 +628,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {mention: widget.mention,messageId: _messageId,threadId: _threadId,+ threadFocus: _threadFocus,homeC: _homeC,),SwarmProjectTab.buddy => SwarmProjectBuddy(@@ -680,7 +696,7 @@ class _SwarmProjectPageState extends State<SwarmProjectPage> {: swarmChatNews(reader, asks, chat),onSelect: (tab) => setState(() {_tab = tab;- _messageId = _threadId = null;+ _messageId = _threadId = _threadFocus = null;}),),),diff --git a/mobile/lib/swarm/swarm_session_widgets.dart b/mobile/lib/swarm/swarm_session_widgets.dartnew file mode 100644index 000000000..c2cca8a97--- /dev/null+++ b/mobile/lib/swarm/swarm_session_widgets.dart@@ -0,0 +1,348 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';++import 'package:harness_mobile/phone/phone_sheet.dart';+import 'package:harness_mobile/phone/tty.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/swarm_tokens_set_b.dart';++import 'swarm_buddy_sessions.dart';+import 'swarm_conversation.dart';+import 'swarm_message_row.dart' show swarmChatText;+import 'swarm_thread.dart';++// Buddy thread sessions on the phone (task #2118; Desktop's New session in the+// chat composer and the thread's reply box, `buddy_sessions.dart`): the pieces+// the chat's composer and the thread page put together. What each shows is+// worked out by SwarmConversation and SwarmThread; these only draw it.++/// New session in the chat composer's toolbar, beside @ Tag: on in the+/// accent. Disabled while the chat [blocked] it, a tap saying why through+/// [onBlocked] (a phone has no hover).+class SwarmNewSessionChip extends StatelessWidget {+ const SwarmNewSessionChip({+ super.key,+ required this.on,+ required this.blocked,+ required this.onChanged,+ this.onBlocked,+ });++ final bool on;++ /// Why a session cannot start now; null when it can.+ final String? blocked;+ final ValueChanged<bool> onChanged;++ /// The chip was tapped while [blocked].+ final VoidCallback? onBlocked;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final disabled = blocked != null;+ final ink = disabled+ ? AppPalette.textFaint+ : on+ ? AppPalette.accentOnSurface+ : AppPalette.textSecondary;+ void tap() => disabled ? onBlocked?.call() : onChanged(!on);+ return Semantics(+ button: true,+ checked: on && !disabled,+ enabled: !disabled,+ label: 'New session',+ hint: blocked ?? 'Starts a separate Buddy session for this message',+ excludeSemantics: true,+ onTap: tap,+ child: GestureDetector(+ key: const ValueKey('swarm-new-session'),+ behavior: HitTestBehavior.opaque,+ onTap: tap,+ child: SizedBox(+ height: 44,+ // Only as wide as the chip: in a roomy row a plain Center would+ // fill it and put the chip in the middle.+ child: Center(+ widthFactor: 1,+ child: Container(+ height: 36,+ padding: SwarmComposer.tagPadding,+ decoration: BoxDecoration(+ color: on && !disabled+ ? AppPalette.accentOnSurface.withValues(alpha: 0.16)+ : tty.text.withValues(alpha: 0.08),+ borderRadius: BorderRadius.circular(SwarmComposer.tagRadius),+ ),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Icon(LucideIcons.messageSquarePlus, size: 17, color: ink),+ const SizedBox(width: 5),+ Flexible(+ child: Text(+ 'New session',+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 14,+ color: ink,+ weight: FontWeight.w500,+ height: 1.2,+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ ),+ );+ }+}++/// "Works in: All projects ⌄" over the composer while New session is on:+/// where the session works. A tap opens [showSwarmSessionProjects].+class SwarmSessionProjectRow extends StatelessWidget {+ const SwarmSessionProjectRow({+ super.key,+ required this.chat,+ required this.onTap,+ });++ final SwarmConversation chat;+ final VoidCallback onTap;++ @override+ Widget build(BuildContext context) {+ final chosen = chat.sessionProjectId;+ final name = chat.reader.snapshot?.projects+ .where((p) => p.id == chosen)+ .firstOrNull+ ?.name;+ return Semantics(+ button: true,+ label: 'Where this session works: ${name ?? 'All projects'}',+ excludeSemantics: true,+ onTap: onTap,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: onTap,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44),+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.xs),+ child: Row(+ children: [+ Text(+ 'Works in:',+ style: swarmChatText(13.5, color: AppPalette.textSecondary),+ ),+ const SizedBox(width: AppSpace.xs),+ Flexible(+ child: Text(+ name ?? 'All projects',+ key: const ValueKey('swarm-session-project-name'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(+ 14,+ color: AppPalette.textPrimary,+ weight: FontWeight.w500,+ ),+ ),+ ),+ const SizedBox(width: AppSpace.xs),+ Icon(+ LucideIcons.chevronDown,+ size: 16,+ color: AppPalette.textSecondary,+ ),+ ],+ ),+ ),+ ),+ ),+ );+ }+}++/// The sheet that picks where a New session works: every project the person+/// reads, sending no work to a PM, or one project, whose PM it alone can hand+/// work to (Desktop's words).+Future<void> showSwarmSessionProjects(+ BuildContext context,+ SwarmConversation chat,+) {+ final chosen = chat.sessionProjectId;+ PhoneSheetAction row(String label, String? projectId) => PhoneSheetAction(+ icon: projectId == chosen+ ? LucideIcons.check300+ : LucideIcons.folderOpen300,+ label: label,+ value: projectId == chosen ? '✓' : null,+ valueColor: AppPalette.textPrimary,+ onTap: () => chat.sessionProjectId = projectId,+ );+ return showPhoneSheet(+ context,+ title: 'Where this session works',+ actions: [+ row('All projects · ask anything', null),+ for (final project in chat.reader.snapshot?.projects ?? const [])+ row('${project.name} · ask and hand off work', project.id),+ ],+ );+}++/// New session in the thread's reply box: a check beside its words. On and+/// locked once the thread's session ended, the reply starting a new one;+/// disabled with its reason while the chat cannot start one.+class SwarmNewSessionCheck extends StatelessWidget {+ const SwarmNewSessionCheck({super.key, required this.thread});++ final SwarmThread thread;++ @override+ Widget build(BuildContext context) {+ final blocked = thread.sessionBlocked;+ final locked = thread.sessionLocked;+ final on = thread.newSession;+ final enabled = !locked && blocked == null;+ final note =+ blocked ??+ (locked+ ? 'This thread\'s session ended. Your reply starts a new one.'+ : null);+ void tap() => thread.newSession = !on;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Semantics(+ key: const ValueKey('swarm-thread-new-session'),+ checked: on,+ enabled: enabled,+ label: 'New session',+ hint: note ?? 'Starts a separate Buddy session for this thread',+ excludeSemantics: true,+ child: GestureDetector(+ behavior: HitTestBehavior.opaque,+ onTap: enabled ? tap : null,+ child: ConstrainedBox(+ constraints: const BoxConstraints(minHeight: 44),+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ Checkbox(+ value: on,+ visualDensity: VisualDensity.compact,+ materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,+ onChanged: enabled ? (_) => tap() : null,+ ),+ const SizedBox(width: AppSpace.s),+ Text(+ 'New session',+ style: swarmChatText(+ 14,+ color: enabled+ ? AppPalette.textPrimary+ : AppPalette.textFaint,+ ),+ ),+ ],+ ),+ ),+ ),+ ),+ if (note != null)+ Padding(+ padding: const EdgeInsets.only(+ left: AppSpace.xs,+ bottom: AppSpace.s,+ ),+ child: Text(+ note,+ key: const ValueKey('swarm-thread-new-session-note'),+ style: swarmChatText(13, color: AppPalette.textSecondary),+ ),+ ),+ ],+ );+ }+}++/// Under the thread page's header: which session answers the thread and how+/// it stands, with End session as a quiet text action; or why its last+/// session ended. Nothing for a thread with neither.+class SwarmThreadSessionLine extends StatelessWidget {+ const SwarmThreadSessionLine({super.key, required this.thread});++ final SwarmThread thread;++ @override+ Widget build(BuildContext context) {+ final tty = Tty.of(context);+ final chat = thread.chat.conversation;+ final session = thread.session;+ final Widget line;+ if (chat != null && session != null) {+ final ending = thread.endingSession;+ line = Row(+ children: [+ Expanded(+ child: Text(+ swarmSessionWords(thread.reader, chat, session),+ key: const ValueKey('swarm-thread-session-state'),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: swarmChatText(13.5, color: AppPalette.textSecondary),+ ),+ ),+ if (thread.canPost)+ TtyTap(+ semanticsLabel: ending ? 'Ending session' : 'End session',+ onTap: ending ? null : () => unawaited(thread.endSession()),+ child: Padding(+ key: const ValueKey('swarm-thread-session-end'),+ padding: const EdgeInsets.symmetric(+ horizontal: AppSpace.s,+ vertical: AppSpace.m,+ ),+ child: Text(+ ending ? 'Ending…' : 'End session',+ style: swarmChatText(+ 14,+ color: ending+ ? AppPalette.textFaint+ : AppPalette.accentOnSurface,+ ),+ ),+ ),+ ),+ ],+ );+ } else if (thread.sessionEndedRow case final ended?) {+ line = Text(+ swarmSessionEndedWords(ended.sessionEndReason),+ key: const ValueKey('swarm-thread-session-ended'),+ style: swarmChatText(13.5, color: AppPalette.textFaint),+ );+ } else {+ return const SizedBox.shrink();+ }+ return Container(+ key: const ValueKey('swarm-thread-session-line'),+ padding: const EdgeInsets.symmetric(horizontal: AppSpace.screenInset),+ decoration: BoxDecoration(+ border: Border(+ bottom: BorderSide(color: tty.text.withValues(alpha: 0.08)),+ ),+ ),+ child: line,+ );+ }+}diff --git a/mobile/lib/swarm/swarm_thread.dart b/mobile/lib/swarm/swarm_thread.dartindex fdd96531f..d9e5fcd8e 100644--- a/mobile/lib/swarm/swarm_thread.dart+++ b/mobile/lib/swarm/swarm_thread.dart@@ -3,6 +3,7 @@ import 'dart:async';import 'package:flutter/foundation.dart';import 'model.dart';+import 'swarm_buddy_sessions.dart';import 'swarm_conversation.dart';import 'swarm_outbox.dart';import 'swarm_outgoing_files.dart';@@ -10,6 +11,28 @@ import 'swarm_reader.dart';import 'swarm_request.dart';import 'swarm_uploads.dart';+/// Where a thread opens: on one of its messages, or at its first unread+/// reply — the newest when all are read. Activity, a link and a tag open a+/// thread this way, so the person does not scroll to find what they came for.+class SwarmThreadFocus {+ const SwarmThreadFocus.message(String this.messageId) : after = null;+ const SwarmThreadFocus.firstUnread({this.after}) : messageId = null;++ /// The message to land on; null for the first unread reply.+ final String? messageId;++ /// For the first unread reply: the sequence the thread was read through+ /// when the person asked, which opening it may since have moved. Null reads+ /// the thread's mark as the page opens.+ final int? after;++ bool get firstUnread => messageId == null;++ /// How many pages of earlier replies are read to find [messageId], as many+ /// as the chat reads back to a quoted message.+ static const maxEarlierPages = 50;+}+/// One thread of a chat on the phone: its root, its replies and the reply/// box — the desktop's thread panel (`SuperTabThreadPanel`) and what its/// controller does for it (`loadThread`, `sendThreadReply`).@@ -182,6 +205,90 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {_composer.changed();}+ /// New session is chosen for the next reply (Desktop's thread composer).+ bool _newSession = false;++ /// The person's own Buddy chat, on a server that takes New session for a+ /// reply — with a Buddy, or in a thread that had a session, whose reply+ /// must start a new one.+ bool get _sessionsPossible {+ final group = chat.conversation;+ return group != null &&+ canPost &&+ swarmOffersThreadSessions(reader, group, hadSession: _hadSession);+ }++ /// Whether the box shows New session: [_sessionsPossible], in a thread no+ /// session answers now (Desktop's `_offersSession`). It may still show+ /// disabled, saying why ([sessionBlocked]).+ bool get offersSessions => _sessionsPossible && session == null;++ /// Whether the box shows Also send: not in a session's thread, which stays+ /// in the thread, nor for a reply that starts a session.+ bool get offersAlsoSend => !newSession && session == null;++ /// Why a session cannot start now; null when it can.+ String? get sessionBlocked {+ final group = chat.conversation;+ return group == null || !_sessionsPossible+ ? null+ : swarmSessionBlocked(reader, group);+ }++ /// A reply from or to a thread session is in the thread.+ bool get _hadSession => messages.any((m) => m.buddySession);++ /// The live or starting session answering the thread; null when none does,+ /// or in a chat that is not the person's own Buddy chat. Shown whether or+ /// not New session is offered.+ SuperTabBuddySession? get session {+ final group = chat.conversation;+ return group == null || !swarmOwnBuddyChat(reader, group)+ ? null+ : group.sessionFor(root);+ }++ /// The row saying the thread's last session ended (its ended line, else its+ /// last session reply), while no session answers it: a plain reply would be+ /// refused, so a new one must start.+ SuperTabMessage? get sessionEndedRow {+ final group = chat.conversation;+ if (group == null || !swarmOwnBuddyChat(reader, group) || session != null) {+ return null;+ }+ final rows = messages;+ return rows.where((m) => m.sessionEnded).lastOrNull ??+ rows.where((m) => m.buddySession).lastOrNull;+ }++ /// The thread's session ended: New session shows on and locked.+ bool get sessionLocked => _sessionsPossible && sessionEndedRow != null;++ /// Whether the next reply starts a session: locked, or chosen and not+ /// blocked.+ bool get newSession =>+ offersSessions &&+ (sessionLocked || (_newSession && sessionBlocked == null));+ set newSession(bool value) {+ if (_newSession == value) return;+ _newSession = value;+ _composer.changed();+ }++ /// Ends the thread's session ([SwarmConversation.endSession]).+ Future<bool> endSession() async {+ if (_disposed) return false;+ final done = await chat.endSession(root);+ if (_disposed) return done;+ // Said where the person pressed it: this page shows the thread's error.+ if (!done && chat.endRefusal != null) error = chat.endRefusal;+ _tell();+ return done;+ }++ /// An end is under way for the thread's session.+ bool get endingSession => chat.endingSession(root);+/// Where Also send puts a reply, as the desktop names the chat.String get alsoSendLabel {final group = chat.conversation;@@ -224,7 +331,12 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {// the reply leaves them uploaded.if (failure.code.contains('ATTACHMENT')) _uploads.forget(post.files);_restore(post);- error = post.error;+ if (swarmRefusedForSessions(post)) {+ swarmSessionsRefused(reader);+ error = swarmSessionsUnavailable;+ } else {+ error = post.error;+ }},);@@ -513,6 +625,7 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {return false;}final operationId = superTabOperationId();+ final startsSession = newSession;final post = SwarmPost(body: {'operationId': operationId,@@ -522,7 +635,9 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {'text': text,'replyTo': root,'recipientIds': const <String>[],- if (_alsoSend) 'alsoSend': true,+ // A session's thread stays in the thread: never also sent.+ if (_alsoSend && offersAlsoSend) 'alsoSend': true,+ if (startsSession) 'newSession': 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,@@ -534,11 +649,12 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {operationId: operationId,),files: outgoing,- held: (draft: _draft, alsoSend: _alsoSend),+ held: (draft: _draft, alsoSend: _alsoSend, newSession: _newSession),);_draft = '';chat.setThreadDraft(root, '');_alsoSend = false;+ _newSession = false;// Only what goes with this reply: more may have been added meanwhile.for (final file in outgoing) {files.remove(file);@@ -591,9 +707,13 @@ class SwarmThread extends ChangeNotifier implements SwarmFilesBox {/// typed or added since.void _restore(SwarmPost post) {final sent = post.held;- if (sent is! ({String draft, bool alsoSend})) return;+ if (sent is! ({String draft, bool alsoSend, bool newSession})) return;draft = _draft.trim().isEmpty ? sent.draft : '${sent.draft}\n$_draft';_alsoSend = _alsoSend || sent.alsoSend;+ // Refused for New session itself, it comes back as a plain reply.+ if (!swarmRefusedForSessions(post)) {+ _newSession = _newSession || sent.newSession;+ }if (post.files.isNotEmpty) {final since = files.files;filesdiff --git a/mobile/lib/swarm/swarm_thread_page.dart b/mobile/lib/swarm/swarm_thread_page.dartindex 104ec197c..054d4a8cc 100644--- a/mobile/lib/swarm/swarm_thread_page.dart+++ b/mobile/lib/swarm/swarm_thread_page.dart@@ -20,6 +20,7 @@ import 'swarm_message_row.dart';import 'swarm_outbox.dart';import 'swarm_paste.dart';import 'swarm_session.dart';+import 'swarm_session_widgets.dart';import 'swarm_thread.dart';import 'swarm_voice.dart';@@ -30,6 +31,8 @@ typedef SwarmThreadRow = Widget Function(SuperTabMessage message, {required bool grouped,required bool acting,+ required bool lit,+ required bool followed,required VoidCallback onTap,});@@ -56,6 +59,7 @@ class SwarmThreadPage extends StatefulWidget {required this.title,required this.row,required this.pending,+ this.focus,});final String swarmId;@@ -69,6 +73,9 @@ class SwarmThreadPage extends StatefulWidget {final SwarmThreadRow row;final SwarmThreadPending pending;+ /// Where the thread lands once it is read; none shows it from its top.+ final SwarmThreadFocus? focus;+@overrideState<SwarmThreadPage> createState() => _SwarmThreadPageState();}@@ -109,6 +116,100 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {});}+ /// The thread's read mark as it was when the page opened, before showing+ /// the thread moves it: the first unread reply is the first after it.+ late final int _readThrough = widget.focus?.after ?? _markAtOpen();++ int _markAtOpen() {+ final chat = widget.chat, reader = chat.reader;+ return reader.readMarks?.threadThrough(chat.id, widget.root) ??+ reader.snapshot?.threadMarks[chat.id]?[widget.root] ??+ 0;+ }++ /// The message the thread landed on, lit for a moment and keyed to be+ /// brought into view.+ String? _target, _lit;+ Timer? _litTimer;+ final _targetKey = GlobalKey();+ bool _landing = false;++ /// Once the thread is read: finds the focus (reading earlier replies back+ /// to it, a bounded number of pages), scrolls to it and lights it for+ /// 2 seconds, as the chat does for a quoted message.+ void _land() {+ final focus = widget.focus;+ if (focus == null || _landing || _thread.state != SwarmChatState.loaded) {+ return;+ }+ _landing = true;+ unawaited(_findFocus(focus));+ }++ Future<void> _findFocus(SwarmThreadFocus focus) async {+ // The read that brought the thread is still finishing: its listeners run+ // before it lets another one start.+ await Future<void>.delayed(Duration.zero);+ final id = focus.messageId;+ String? target;+ if (id != null) {+ var pages = 0;+ bool found() => _thread.messages.any((m) => m.id == id);+ while (mounted &&+ !found() &&+ _thread.hasEarlier &&+ _thread.error == null &&+ pages++ < SwarmThreadFocus.maxEarlierPages) {+ await _thread.loadEarlier();+ }+ if (found()) target = id;+ } else {+ final replies = _thread.replies;+ target = replies.where((m) => m.sequence > _readThrough).firstOrNull?.id;+ target ??= replies.lastOrNull?.id;+ }+ if (!mounted || target == null) return;+ setState(() {+ _target = target;+ _lit = target;+ });+ _litTimer?.cancel();+ _litTimer = Timer(const Duration(seconds: 2), () {+ if (mounted) setState(() => _lit = null);+ });+ _reveal(target, 0);+ }++ /// The list builds only the rows near what is shown: it jumps near the+ /// target by its place in the list until its row is built, then brings it+ /// to the middle (as the chat's `_reveal` does).+ void _reveal(String id, int attempt) {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted || _target != id) return;+ if (_targetKey.currentContext case final row?) {+ unawaited(+ Scrollable.ensureVisible(+ row,+ alignment: 0.5,+ duration: const Duration(milliseconds: 250),+ ),+ );+ return;+ }+ final index = _thread.messages.indexWhere((m) => m.id == id);+ if (!_scroll.hasClients || index < 0 || attempt > 20) return;+ final count = _thread.messages.length;+ _scroll.position.jumpTo(+ (_scroll.position.maxScrollExtent * index / count).clamp(+ 0,+ _scroll.position.maxScrollExtent,+ ),+ );+ _reveal(id, attempt + 1);+ });+ WidgetsBinding.instance.scheduleFrame();+ }+/// What the last pick left out, or why it could not pick, under the box.final _attachNote = ValueNotifier<String?>(null);bool _picking = false;@@ -130,6 +231,9 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {_thread.composer.addListener(_drafted);_thread.addListener(_seen);_thread.addListener(_guardVoice);+ _thread.addListener(_land);+ // Before the thread shows, so showing it does not move the mark first.+ _readThrough;unawaited(_thread.load());}@@ -188,6 +292,8 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {_thread.composer.removeListener(_drafted);_thread.removeListener(_seen);_thread.removeListener(_guardVoice);+ _thread.removeListener(_land);+ _litTimer?.cancel();_voice?.dispose();_thread.dispose();_attachNote.dispose();@@ -297,6 +403,10 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {crossAxisAlignment: CrossAxisAlignment.stretch,children: [_header(context, tty),+ ListenableBuilder(+ listenable: _thread,+ builder: (context, _) => SwarmThreadSessionLine(thread: _thread),+ ),Expanded(child: Stack(children: [@@ -418,10 +528,13 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {m,grouped: grouped,acting: _acting == m.id,+ lit: _lit == m.id,+ followed: _target == m.id,onTap: () => _toggleActions(m.id),);- return _acting == m.id- ? KeyedSubtree(key: _actingKey, child: built)+ if (_acting == m.id) return KeyedSubtree(key: _actingKey, child: built);+ return _target == m.id+ ? KeyedSubtree(key: _targetKey, child: built): built;}@@ -606,6 +719,7 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {style: AppType.caption(color: AppPalette.textSecondary),),),+ if (t.offersSessions && !talking) SwarmNewSessionCheck(thread: t),SwarmComposerCard(focus: _focus,chips: t.files.files.isEmpty ? null : SwarmOutgoingChips(box: t),@@ -634,13 +748,16 @@ class _SwarmThreadPageState extends State<SwarmThreadPage> {? () => unawaited(_pickFiles()): null,),- Expanded(- child: _AlsoSend(- label: t.alsoSendLabel,- value: t.alsoSend,- onChanged: (on) => t.alsoSend = on,- ),- ),+ if (t.offersAlsoSend)+ Expanded(+ child: _AlsoSend(+ label: t.alsoSendLabel,+ value: t.alsoSend,+ onChanged: (on) => t.alsoSend = on,+ ),+ )+ else+ const Spacer(),// The main chat's mic, beside Send as there.if (voice != null) SwarmVoiceMic(voice: voice),SwarmRoundButton(diff --git a/mobile/test/swarm/swarm_activity_landing_test.dart b/mobile/test/swarm/swarm_activity_landing_test.dartnew file mode 100644index 000000000..5624dede4--- /dev/null+++ b/mobile/test/swarm/swarm_activity_landing_test.dart@@ -0,0 +1,288 @@+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/swarm/swarm_activity_page.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';+import 'package:harness_mobile/swarm/swarm_thread_page.dart';++import '../voice_fakes.dart';+import 'swarm_activity_fixture.dart';+import 'swarm_fixture.dart';++/// Opening an Activity row lands on its message (Tony, 2026-11-02): one in a+/// thread opens that thread at it, read in from earlier pages when it is+/// further back, and lights it; one in the main chat lights it there; a+/// whole thread opens at its first unread reply, else its newest; a decision+/// stays answered in Activity.+void main() {+ /// A reply of the thread under [root], [n] of it: its text is "Reply n of+ /// root." and its sequence 100 + n, after the chat's own rows.+ Map<String, dynamic> reply(String root, int n) => {+ ...activityMessage('$root-$n', 100 + n, text: 'Reply $n of $root.'),+ 'thread': root,+ 'replyTo': root,+ };++ /// The thread under [root] with [count] replies, in pages of [perPage],+ /// newest first, the root last; the page before is read with its cursor.+ void thread(FakeSwarm fake, String root, int count, {int perPage = 100}) {+ Map<String, dynamic> page(int to) {+ final from = to - perPage + 1 < 1 ? 1 : to - perPage + 1;+ return {+ 'messages': [+ for (var n = to; n >= from; n--) reply(root, n),+ activityMessage(root, 3, text: 'About $root.', mine: true),+ ],+ 'next': from > 1 ? {'sequence': 100 + from, 'id': '$root-$from'} : null,+ 'threads': [activityThread(root, last: 100 + count)],+ };+ }++ final path = '$activityChatPath?thread=$root';+ fake.routes[path] = (_) => page(count);+ for (var to = count - perPage; to >= 1; to -= perPage) {+ final before = to + 1;+ fake.routes['$path&before=${100 + before}&beforeId=$root-$before'] = (+ _,+ ) => page(to);+ }+ }++ /// The project chat: the person's thread roots and a main-chat message of+ /// theirs, all on its newest page.+ Map<String, dynamic> chat() => {+ 'messages': [+ activityMessage('root-t', 3, text: 'About root-t.', mine: true),+ activityMessage('root-far', 4, text: 'About root-far.', mine: true),+ activityMessage('main-1', 5, text: 'Copy is fixed.', mine: true),+ ],+ 'threads': [+ activityThread('root-t', last: 140),+ activityThread('root-far', last: 700),+ ],+ 'next': null,+ };++ /// [rows] on a server with Activity (or none: the phone builds its own),+ /// the threads root-t (40 replies) and root-far (600) behind them.+ Future<FakeSwarm> pump(+ WidgetTester tester, {+ List<Map<String, dynamic>>? rows,+ Map<String, int>? threadMarks,+ Map<String, dynamic>? mention,+ }) async {+ final fake = activityBackend(+ page: chat,+ activityDigest: rows == null ? null : () => 'digest-1',+ threadMarks: threadMarks,+ );+ if (rows != null) {+ fake.routes[activityPath] = (_) => {'items': rows, 'more': false};+ fake.routes['$activityPath/read'] = (_) => {'marked': 0};+ }+ if (mention != null) {+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': [mention],+ };+ }+ thread(fake, 'root-t', 40);+ thread(fake, 'root-far', 600);+ 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: const SwarmActivityPage(),+ ),+ );+ await tester.pumpAndSettle();+ return fake;+ }++ Finder key(String value) => find.byKey(ValueKey(value));++ Future<void> filter(WidgetTester tester, String name) async {+ await tester.ensureVisible(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-activity-filter-$name'));+ await tester.pumpAndSettle();+ }++ /// Taps [row]'s Reply and lets the chat, and the thread over it, open.+ Future<void> open(WidgetTester tester, String row) async {+ await tester.tap(key(row));+ await tester.pumpAndSettle();+ }++ /// [text] is drawn inside the thread page's list.+ bool inView(WidgetTester tester, String text) {+ final f = find.text(text);+ if (f.evaluate().isEmpty) return false;+ final view = tester.getRect(key('swarm-thread-messages'));+ final row = tester.getRect(f);+ return row.top >= view.top && row.bottom <= view.bottom;+ }++ Finder lit(String id) => key('swarm-lit-$id');++ Map<String, dynamic> row(+ String id, {+ String kind = 'reply',+ required String messageId,+ String? threadId,+ }) => activityRow(+ id,+ kind: kind,+ messageId: messageId,+ threadId: threadId,+ emoji: kind == 'reaction' ? 'thumbs_up' : null,+ );++ group('a message in a thread', () {+ testWidgets('a reply opens its thread at it, lit', (tester) async {+ await pump(+ tester,+ rows: [row('r1', messageId: 'root-t-20', threadId: 'root-t')],+ );+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-reply-activity:$tab:r1');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 20 of root-t.'), isTrue);+ expect(lit('root-t-20'), findsOneWidget);+ });++ testWidgets('a reaction opens its thread at the message', (tester) async {+ await pump(+ tester,+ rows: [+ row(+ 'x1',+ kind: 'reaction',+ messageId: 'root-t-33',+ threadId: 'root-t',+ ),+ ],+ );+ await filter(tester, 'reactions');+ await open(tester, 'swarm-activity-reply-activity:$tab:x1');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 33 of root-t.'), isTrue);+ expect(lit('root-t-33'), findsOneWidget);+ });++ testWidgets('a tag opens its thread at it', (tester) async {+ await pump(+ tester,+ rows: const [],+ mention: {+ 'id': 'm1',+ 'projectName': 'Mobile',+ 'conversationId': leadChat,+ 'conversationTitle': 'Mobile',+ 'messageId': 'root-t-27',+ 'leadName': 'River',+ 'text': 'Can you check the copy?',+ 'threadId': 'root-t',+ 'messageSequence': 127,+ },+ );+ await filter(tester, 'mentions');+ await open(tester, 'swarm-activity-reply-mention:m1');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 27 of root-t.'), isTrue);+ expect(lit('root-t-27'), findsOneWidget);+ });++ testWidgets('one too far back to be loaded at first is read in', (+ tester,+ ) async {+ await pump(+ tester,+ rows: [row('r1', messageId: 'root-far-3', threadId: 'root-far')],+ );+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-reply-activity:$tab:r1');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 3 of root-far.'), isTrue);+ expect(lit('root-far-3'), findsOneWidget);+ });++ testWidgets('the light goes out after 2 seconds', (tester) async {+ await pump(+ tester,+ rows: [row('r1', messageId: 'root-t-20', threadId: 'root-t')],+ );+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-reply-activity:$tab:r1');+ expect(lit('root-t-20'), findsOneWidget);++ await tester.pump(const Duration(seconds: 2, milliseconds: 100));+ await tester.pumpAndSettle();++ expect(lit('root-t-20'), findsNothing);+ expect(inView(tester, 'Reply 20 of root-t.'), isTrue);+ });+ });++ group('a message in the main chat', () {+ testWidgets('a reply lands on it in the chat, lit, no thread', (+ tester,+ ) async {+ await pump(tester, rows: [row('r1', messageId: 'main-1')]);+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-reply-activity:$tab:r1');++ expect(find.byType(SwarmThreadPage), findsNothing);+ expect(lit('main-1'), findsOneWidget);+ });+ });++ group('a row for a whole thread', () {+ testWidgets('opens at the first unread reply', (tester) async {+ await pump(tester, threadMarks: {'root-t': 110});+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-reply-thread:$tab:root-t');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 11 of root-t.'), isTrue);+ });++ testWidgets('with every reply read opens at the newest', (tester) async {+ await pump(tester, threadMarks: {'root-t': 140});+ await filter(tester, 'threads');+ await open(tester, 'swarm-activity-row-thread:$tab:root-t');++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(inView(tester, 'Reply 40 of root-t.'), isTrue);+ });+ });++ testWidgets('a decision is still answered in Activity, no chat opens', (+ tester,+ ) async {+ await pump(tester, rows: const []);++ await tester.tap(key('swarm-activity-row-decision:d1'));+ await tester.pumpAndSettle();++ expect(key('swarm-option-d1-1'), findsOneWidget);+ expect(find.byType(SwarmThreadPage), findsNothing);+ });+}diff --git a/mobile/test/swarm/swarm_activity_page_test.dart b/mobile/test/swarm/swarm_activity_page_test.dartindex b9be2361f..24d6589e9 100644--- a/mobile/test/swarm/swarm_activity_page_test.dart+++ b/mobile/test/swarm/swarm_activity_page_test.dart@@ -9,6 +9,7 @@ import 'package:harness_mobile/swarm/swarm_activity_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_thread_page.dart';import '../voice_fakes.dart';import 'swarm_activity_fixture.dart';@@ -255,11 +256,13 @@ void main() {await tester.tap(key('swarm-activity-reply-thread:$tab:root-1'));await tester.pumpAndSettle();+ // The thread is open over its chat, which is at the root behind it.+ expect(find.byType(SwarmThreadPage), findsOneWidget);final page = tester.widget<SwarmConversationPage>(- find.byType(SwarmConversationPage),+ find.byType(SwarmConversationPage, skipOffstage: false),);expect((page.conversationId, page.messageId), (leadChat, 'root-1'));- expectHomeCProject('Mobile');+ expect(page.threadId, 'root-1');});testWidgets("Reactions: who reacted how to the person's message", (diff --git a/mobile/test/swarm/swarm_buddy_session_parse_test.dart b/mobile/test/swarm/swarm_buddy_session_parse_test.dartindex 19d786a64..ecf44c97e 100644--- a/mobile/test/swarm/swarm_buddy_session_parse_test.dart+++ b/mobile/test/swarm/swarm_buddy_session_parse_test.dart@@ -46,4 +46,58 @@ void main() {'s',);});+ test('session fields read as Desktop reads them (project, lookup, ended)', () {+ expect(+ SuperTabBuddySessionOf.fromJson({+ 'thread': 'r',+ 'from': 1,+ 'projectId': 'p',+ })!.projectId,+ 'p',+ );+ expect(+ SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': ''})!+ .projectId,+ isNull,+ );+ expect(+ SuperTabBuddySessionOf.fromJson({'thread': 'r', 'projectId': 3})!+ .projectId,+ isNull,+ );+ final chat = SuperTabConversation.fromJson({+ 'id': 'c',+ 'kind': 'buddy',+ 'buddyOwnerId': 'p',+ 'title': 'Wren',+ 'agentIds': <String>[],+ 'archived': false,+ 'brief': '',+ 'checks': <dynamic>[],+ 'assignment': null,+ 'lastMessageSequence': 0,+ 'buddySessions': [+ {'thread': 'r', 'startId': 's'},+ ],+ });+ expect(chat.sessionFor('r')!.startId, 's');+ expect(chat.sessionFor('x'), isNull);+ SuperTabMessage message(Map<String, dynamic> extra) =>+ SuperTabMessage.fromJson({+ 'id': 'm',+ 'conversationId': 'c',+ 'text': 't',+ 'sequence': 1,+ 'author': {'kind': 'agent', 'id': 'a'},+ 'thread': 'm',+ ...extra,+ });+ final ended = message({+ 'buddySession': true,+ 'source': {'kind': 'buddy-session-ended', 'reason': 'idle'},+ });+ expect([ended.sessionEnded, ended.sessionEndReason], [true, 'idle']);+ final plain = message({'buddySession': true});+ expect([plain.sessionEnded, plain.sessionEndReason], [false, null]);+ });}diff --git a/mobile/test/swarm/swarm_buddy_sessions_test.dart b/mobile/test/swarm/swarm_buddy_sessions_test.dartnew file mode 100644index 000000000..cad431035--- /dev/null+++ b/mobile/test/swarm/swarm_buddy_sessions_test.dart@@ -0,0 +1,143 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';+import 'package:harness_mobile/swarm/swarm_buddy_sessions.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';++import 'swarm_fixture.dart';+import 'swarm_session_fixture.dart';++/// When the phone offers New session and when it says it cannot, as Desktop's+/// `offersChatSessions`, `offersThreadSessions` and `threadSessionBlocked`+/// decide (spec 2026-10-30-buddy-thread-sessions).+void main() {+ Future<(SwarmReader, SuperTabConversation)> rig(FakeSwarm fake) async {+ final reader = await sessionReader(fake);+ addTearDown(reader.dispose);+ return (reader, reader.snapshot!.conversation(sessionChat)!);+ }++ group('why a session cannot start (Desktop threadSessionBlocked)', () {+ test('nothing in the way: null', () async {+ final (reader, chat) = await rig(sessionBackend());+ expect(swarmSessionBlocked(reader, chat), isNull);+ });++ test('a paused Swarm', () async {+ final (reader, chat) = await rig(sessionBackend(paused: true));+ expect(+ swarmSessionBlocked(reader, chat),+ 'New work is paused in this Swarm',+ );+ });++ test('no Buddy running, or its machine down', () async {+ var (reader, chat) = await rig(sessionBackend(buddy: false));+ expect(swarmSessionBlocked(reader, chat), 'Start your Buddy first');+ (reader, chat) = await rig(+ sessionBackend(downSince: '2026-11-02T01:00:00.000Z'),+ );+ expect(swarmSessionBlocked(reader, chat), 'Start your Buddy first');+ });++ test('a Buddy that is not Claude Code', () async {+ final (reader, chat) = await rig(sessionBackend(engine: 'codex'));+ expect(+ swarmSessionBlocked(reader, chat),+ 'Sessions need a Claude Code Buddy',+ );+ });++ test(+ 'a machine whose report lacks buddySessions names the machine',+ () async {+ final (reader, chat) = await rig(+ sessionBackend(machine: sessionMachine(capabilities: const [])),+ );+ expect(+ swarmSessionBlocked(reader, chat),+ 'Update Harness on Tonys-MacBook-Pro to start sessions',+ );+ },+ );++ test('an older host, whose report has no capabilities list', () async {+ final (reader, chat) = await rig(+ sessionBackend(machine: sessionMachine(capabilities: null)),+ );+ expect(+ swarmSessionBlocked(reader, chat),+ 'Update Harness on Tonys-MacBook-Pro to start sessions',+ );+ });+ });++ group('where New session is offered', () {+ test('the chat composer needs sessionsFromChat and a Buddy', () async {+ var (reader, chat) = await rig(sessionBackend());+ expect(swarmOffersChatSessions(reader, chat), isTrue);+ (reader, chat) = await rig(sessionBackend(sessionsFromChat: false));+ expect(swarmOffersChatSessions(reader, chat), isFalse);+ (reader, chat) = await rig(sessionBackend(buddy: false));+ expect(swarmOffersChatSessions(reader, chat), isFalse);+ });++ test('a thread reply needs threadSessions; a thread that had a session '+ 'offers it with no Buddy running', () async {+ var (reader, chat) = await rig(sessionBackend());+ expect(+ swarmOffersThreadSessions(reader, chat, hadSession: false),+ isTrue,+ );+ (reader, chat) = await rig(sessionBackend(threadSessions: false));+ expect(+ swarmOffersThreadSessions(reader, chat, hadSession: true),+ isFalse,+ );+ (reader, chat) = await rig(sessionBackend(buddy: false));+ expect(+ swarmOffersThreadSessions(reader, chat, hadSession: false),+ isFalse,+ );+ expect(swarmOffersThreadSessions(reader, chat, hadSession: true), isTrue);+ });++ test('never in an older Buddy chat or someone else\'s', () async {+ final fake = sessionBackend();+ final reader = await sessionReader(fake);+ addTearDown(reader.dispose);+ // The Swarm's lead chat is neither.+ final lead = reader.snapshot!.conversation(leadChat)!;+ expect(swarmOffersChatSessions(reader, lead), isFalse);+ expect(+ swarmOffersThreadSessions(reader, lead, hadSession: true),+ isFalse,+ );+ });+ });++ test('why a session ended, as its thread says it', () {+ expect(+ swarmSessionEndedWords('idle'),+ 'Session ended: idle for 30 minutes',+ );+ expect(swarmSessionEndedWords('ended'), 'Session ended: you ended it');+ expect(+ swarmSessionEndedWords('stopped'),+ 'Session ended: it stopped unexpectedly',+ );+ expect(+ swarmSessionEndedWords('failed'),+ 'Session ended: it couldn\'t start',+ );+ expect(+ swarmSessionEndedWords('removed'),+ 'Session ended: its Buddy was removed or replaced',+ );+ expect(+ swarmSessionEndedWords('maintenance'),+ 'Session ended: Harness was updated',+ );+ expect(swarmSessionEndedWords(null), 'Session ended');+ expect(swarmSessionEndedWords('other'), 'Session ended');+ });+}diff --git a/mobile/test/swarm/swarm_chat_session_test.dart b/mobile/test/swarm/swarm_chat_session_test.dartnew file mode 100644index 000000000..4be2710cd--- /dev/null+++ b/mobile/test/swarm/swarm_chat_session_test.dart@@ -0,0 +1,162 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_buddy_sessions.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_reader.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';++import 'swarm_fixture.dart';+import 'swarm_session_fixture.dart';++/// New session in the Buddy chat's composer (Desktop `send(newSession:,+/// sessionProjectId:)`): All projects sends no project and reads every+/// project; one project sends it. And End session.+void main() {+ Future<(FakeSwarm, SwarmReader, SwarmConversation)> rig({+ FakeSwarm? backend,+ }) async {+ final fake = backend ?? sessionBackend();+ final reader = await sessionReader(fake);+ addTearDown(reader.dispose);+ final chat = SwarmConversation(reader, sessionChat);+ addTearDown(chat.dispose);+ await chat.load();+ return (fake, reader, chat);+ }++ Map<String, dynamic> sent(FakeSwarm fake) =>+ fake.commands.lastWhere((c) => c['type'] == 'message.send');++ test(+ 'New session over All projects sends newSession and no project',+ () async {+ final (fake, _, chat) = await rig();+ expect(chat.offersSessions, isTrue);+ chat.newSession = true;+ chat.draft = 'Fix the flaky login test';+ expect(await chat.send(), isTrue);+ final command = sent(fake);+ expect(command['newSession'], isTrue);+ expect(command.containsKey('sessionProjectId'), isFalse);+ expect(command['text'], 'Fix the flaky login test');+ // Taken: the next message is a plain one.+ expect(chat.newSession, isFalse);+ },+ );++ test('New session over one project sends that project', () async {+ final (fake, _, chat) = await rig();+ chat+ ..newSession = true+ ..sessionProjectId = webProject+ ..draft = 'Ship the web fix';+ expect(await chat.send(), isTrue);+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake)['sessionProjectId'], webProject);+ expect(chat.sessionProjectId, isNull);+ });++ test('a project the person lost is no longer chosen', () async {+ final (fake, _, chat) = await rig();+ chat+ ..newSession = true+ ..sessionProjectId = 'project-gone'+ ..draft = 'Anything';+ expect(chat.sessionProjectId, isNull);+ expect(await chat.send(), isTrue);+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake).containsKey('sessionProjectId'), isFalse);+ });++ test('with New session off, a message is plain', () async {+ final (fake, _, chat) = await rig();+ chat.draft = 'Just a question';+ expect(await chat.send(), isTrue);+ expect(sent(fake).containsKey('newSession'), isFalse);+ expect(sent(fake).containsKey('sessionProjectId'), isFalse);+ });++ test('a chat that cannot start a session sends a plain message', () async {+ final (fake, _, chat) = await rig(backend: sessionBackend(engine: 'codex'));+ expect(chat.offersSessions, isTrue);+ expect(chat.sessionBlocked, 'Sessions need a Claude Code Buddy');+ chat+ ..newSession = true+ ..draft = 'Hello';+ expect(chat.newSession, isFalse);+ expect(await chat.send(), isTrue);+ expect(sent(fake).containsKey('newSession'), isFalse);+ });++ test('no New session where the server does not take it', () async {+ final (_, _, chat) = await rig(+ backend: sessionBackend(sessionsFromChat: false),+ );+ expect(chat.offersSessions, isFalse);+ });++ test('a server that does not know newSession gives the text back and says '+ 'so', () async {+ final fake = sessionBackend();+ fake.routes[sessionCommands] = (_) => throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ "command: Unrecognized key: 'newSession'",+ statusCode: 400,+ );+ final (_, reader, chat) = await rig(backend: fake);+ chat+ ..newSession = true+ ..draft = 'Start one';+ expect(await chat.send(), isFalse);+ expect(chat.draft, 'Start one');+ expect(chat.error, swarmSessionsUnavailable);+ // Not offered for a while after.+ expect(chat.offersSessions, isFalse);+ expect(reader.snapshot, isNotNull);+ });++ group('End session', () {+ final live = [+ {'thread': 'm1', 'startId': 's1', 'agentId': 'agent-session', 'at': 1},+ ];++ test('sends one buddy.sessionEnd for the thread, however often it is '+ 'pressed', () async {+ final fake = sessionBackend(sessions: live);+ final gate = Completer<void>();+ fake.routes[sessionCommands] = (_) async {+ await gate.future;+ return {'result': <String, dynamic>{}};+ };+ final (_, _, chat) = await rig(backend: fake);+ final first = chat.endSession('m1');+ final second = chat.endSession('m1');+ gate.complete();+ expect(await first, isTrue);+ expect(await second, isFalse);+ final ends = [+ for (final c in fake.commands)+ if (c['type'] == 'buddy.sessionEnd') c,+ ];+ expect(ends, hasLength(1));+ expect(ends.single, {+ 'type': 'buddy.sessionEnd',+ 'conversationId': sessionChat,+ 'thread': 'm1',+ 'reason': 'ended',+ });+ });++ test('nothing for a thread with no live session', () async {+ final (fake, _, chat) = await rig(+ backend: sessionBackend(sessions: live),+ );+ expect(await chat.endSession('other'), isFalse);+ expect(+ fake.commands.where((c) => c['type'] == 'buddy.sessionEnd'),+ isEmpty,+ );+ });+ });+}diff --git a/mobile/test/swarm/swarm_session_fixture.dart b/mobile/test/swarm/swarm_session_fixture.dartnew file mode 100644index 000000000..ac1294124--- /dev/null+++ b/mobile/test/swarm/swarm_session_fixture.dart@@ -0,0 +1,154 @@+import 'package:harness_mobile/swarm/swarm_reader.dart';++import 'swarm_fixture.dart';++/// The person's one Buddy chat with thread sessions on, as the server sends it+/// (backend read/contract.ts `swarmBuddy`, `threadSessions`, `sessionsFromChat`),+/// over the projects Mobile and Web.+const sessionChat = 'buddy-one';+const webProject = 'project-web';+const sessionCommands = '/api/super-tabs/$tab/commands';+const sessionMessages =+ '/api/super-tabs/$tab/conversations/$sessionChat/messages';++Map<String, dynamic> sessionMessage(+ String id,+ int sequence, {+ String? root,+ bool session = false,+ Map<String, dynamic>? source,+ String author = 'agent-wren',+}) => {+ 'id': id,+ 'conversationId': sessionChat,+ 'text': 'text of $id',+ 'sequence': sequence,+ 'author': author == me+ ? {'kind': 'person', 'id': me, 'name': 'tony'}+ : {'kind': 'agent', 'id': author, 'name': 'Wren'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'createdAt': DateTime.utc(2026, 11, 2, 1, sequence).toIso8601String(),+ 'thread': root ?? id,+ if (session) 'buddySession': true,+ 'source': ?source,+};++/// A machine reporting now, able to run thread sessions unless [capabilities]+/// says otherwise.+Map<String, dynamic> sessionMachine({+ String id = 'mac-1',+ String name = 'Tonys-MacBook-Pro.local',+ List<String>? capabilities = const ['buddySessions'],+}) => {+ 'machineId': id,+ 'name': name,+ 'contributorId': me,+ 'engines': ['claude', 'codex'],+ 'observation': {+ 'receivedAt': DateTime.now().millisecondsSinceEpoch,+ 'capabilities': ?capabilities,+ },+};++/// One Swarm where the person's one Buddy chat has [page], its Buddy running+/// unless [buddy] is false, and [sessions] live in it.+FakeSwarm sessionBackend({+ List<Map<String, dynamic>> page = const [],+ List<Map<String, dynamic>> sessions = const [],+ List<Map<String, dynamic>> extraAgents = const [],+ bool buddy = true,+ String engine = 'claude',+ String? downSince,+ bool paused = false,+ bool threadSessions = true,+ bool sessionsFromChat = true,+ bool swarmBuddy = true,+ bool swarmChat = true,+ String role = 'owner',+ Map<String, dynamic>? machine,+}) {+ final derived = {+ 'swarmBuddy': swarmBuddy,+ 'threadSessions': threadSessions,+ 'sessionsFromChat': sessionsFromChat,+ };+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ head: {+ ...headData(+ projects: [+ ...(headData()['projects'] as List).cast<Map<String, dynamic>>(),+ {+ 'id': webProject,+ 'name': 'Web',+ 'ownerId': me,+ 'leadConversationId': 'lead-web',+ 'visibility': 'public',+ 'members': <Object>[],+ 'updateMinutes': 5,+ },+ ],+ ),+ 'paused': paused,+ },+ groups: [+ {+ ...groupData(+ sessionChat,+ title: "$me's Buddy",+ agentIds: [if (buddy) 'agent-wren'],+ lastMessageSequence: page.length,+ ),+ 'kind': swarmChat ? 'swarm-buddy' : 'buddy',+ 'buddyOwnerId': me,+ 'buddySessions': sessions,+ if (swarmChat) 'projectId': null,+ }..removeWhere((k, v) => k == 'projectId' && v == null),+ {...groupData('lead-web', title: 'Web'), 'projectId': webProject},+ ],+ agents: [+ agent('agent-lead', name: 'Lead', displayName: 'River'),+ if (buddy)+ {+ ...buddyData('agent-wren', displayName: 'Wren', engine: engine),+ if (swarmChat) 'buddyScope': 'swarm',+ 'downSince': ?downSince,+ if (swarmChat) 'projectId': null,+ }..removeWhere((k, v) => k == 'projectId' && v == null),+ ...extraAgents,+ ],+ machines: [machine ?? sessionMachine()],+ derived: derived,+ ),+ 'members': [part(me, 1, person(me, role: role))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) =>+ changes(cursor: 'c2', derived: derived);+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[sessionMessages] = (_) => {+ 'messages': page.reversed.toList(),+ 'next': null,+ };+ fake.routes[sessionCommands] = (_) => {'result': <String, dynamic>{}};+ return fake;+}++/// A reader of [fake]'s Swarm, read once.+Future<SwarmReader> sessionReader(FakeSwarm fake) async {+ final reader = SwarmReader(tabId: tab, accountId: me, request: fake.request);+ await reader.refresh();+ return reader;+}diff --git a/mobile/test/swarm/swarm_session_widgets_test.dart b/mobile/test/swarm/swarm_session_widgets_test.dartnew file mode 100644index 000000000..bef705bad--- /dev/null+++ b/mobile/test/swarm/swarm_session_widgets_test.dart@@ -0,0 +1,361 @@+import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart' show RenderParagraph;+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_conversation_page.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_session.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';+import 'swarm_session_fixture.dart';++/// New session on the phone's Buddy chat (task #2118): the chip and its+/// "Works in" pick in the composer, the reply box's New session in a thread,+/// the session's status line with End session, and the line of a session that+/// ended. Behaviour as Desktop's (spec 2026-10-30-buddy-thread-sessions).+void main() {+ Finder key(String value) => find.byKey(ValueKey(value));++ Future<SwarmHost> pump(+ WidgetTester tester,+ FakeSwarm fake, {+ String? thread,+ }) async {+ tester.view.physicalSize = const Size(1170, 2532);+ tester.view.devicePixelRatio = 3;+ addTearDown(tester.view.reset);+ final features = ExperimentalFeaturesStore(storage: MemoryKeyValueStore())+ ..value = {PhoneExperiment.swarm};+ final account = ValueNotifier<String?>(me);+ final host = SwarmHost(+ accountId: () => account.value,+ account: account,+ request: fake.request,+ upload: refuseSwarmUpload,+ notices: SilentSystemNotices(),+ features: features,+ )..foreground = false;+ addTearDown(host.dispose);+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ builder: (context, child) => SwarmScope(notifier: host, child: child!),+ home: SwarmConversationPage(+ swarmId: tab,+ conversationId: sessionChat,+ messageId: thread,+ threadId: thread,+ ),+ ),+ );+ await tester.pumpAndSettle();+ return host;+ }++ Map<String, dynamic> sent(FakeSwarm fake) =>+ fake.commands.lastWhere((c) => c['type'] == 'message.send');++ /// A backend whose thread m1 reads [replies].+ FakeSwarm threadBackend({+ required List<Map<String, dynamic>> replies,+ List<Map<String, dynamic>> sessions = const [],+ List<Map<String, dynamic>> extraAgents = const [],+ String engine = 'claude',+ }) {+ final rows = [sessionMessage('m1', 1, author: me), ...replies];+ final fake = sessionBackend(+ page: rows,+ sessions: sessions,+ extraAgents: extraAgents,+ engine: engine,+ );+ fake.routes['$sessionMessages?thread=m1'] = (_) => {+ 'messages': rows.reversed.toList(),+ 'next': null,+ };+ return fake;+ }++ group('the chat composer', () {+ testWidgets('has no New session where the server does not take it', (+ tester,+ ) async {+ await pump(tester, sessionBackend(sessionsFromChat: false));+ expect(key('swarm-new-session'), findsNothing);+ });++ testWidgets('New session over All projects: no project is sent, and the '+ 'session\'s thread opens', (tester) async {+ final fake = sessionBackend();+ await pump(tester, fake);+ expect(key('swarm-new-session'), findsOneWidget);+ expect(key('swarm-session-project'), findsNothing);+ await tester.tap(key('swarm-new-session'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-session-project-name')).data,+ 'All projects',+ );+ await tester.enterText(find.byType(TextField), 'Fix the flaky test');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake).containsKey('sessionProjectId'), isFalse);+ // Its thread is up, the session answering there.+ expect(key('swarm-thread-header'), findsOneWidget);+ });++ testWidgets('New session over one project sends that project', (+ tester,+ ) async {+ final fake = sessionBackend();+ await pump(tester, fake);+ await tester.tap(key('swarm-new-session'));+ await tester.pumpAndSettle();+ await tester.tap(key('swarm-session-project'));+ await tester.pumpAndSettle();+ expect(find.text('All projects · ask anything'), findsOneWidget);+ expect(find.text('Mobile · ask and hand off work'), findsOneWidget);+ await tester.tap(find.text('Web · ask and hand off work'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-session-project-name')).data,+ 'Web',+ );+ await tester.enterText(find.byType(TextField), 'Ship the web fix');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake)['sessionProjectId'], webProject);+ });++ testWidgets('a project\'s own Buddy chat, where the Swarm has no one '+ 'Buddy, offers no project to pick', (tester) async {+ final fake = sessionBackend(swarmChat: false, swarmBuddy: false);+ await pump(tester, fake);+ await tester.tap(key('swarm-new-session'));+ await tester.pumpAndSettle();+ expect(key('swarm-session-project'), findsNothing);+ });++ testWidgets('the chip shows its whole label when the row has room for it '+ '(the test font is wider than the phone\'s)', (tester) async {+ await pump(tester, sessionBackend());+ // Room for the label beside + and Tag, but not for twice its width:+ // the chip is not squeezed to half of what is left.+ tester.view.physicalSize = const Size(1680, 2532);+ await tester.pumpAndSettle();+ final label = tester.renderObject<RenderParagraph>(+ find.text('New session'),+ );+ expect(label.didExceedMaxLines, isFalse);+ });++ testWidgets('the chip sits right after Tag, not in the middle of the '+ 'row', (tester) async {+ await pump(tester, sessionBackend());+ // Room to spare beside + and Tag: the chip is not centred in it.+ tester.view.physicalSize = const Size(2100, 2532);+ await tester.pumpAndSettle();+ final tag = tester.getTopRight(key('swarm-tag'));+ // Its label, past the chip's own icon and padding.+ final label = tester.getTopLeft(find.text('New session'));+ expect(label.dx - tag.dx, lessThan(60));+ });++ testWidgets('a chat that cannot start one says why when the chip is '+ 'tapped, and sends plain', (tester) async {+ final fake = sessionBackend(engine: 'codex');+ await pump(tester, fake);+ await tester.tap(key('swarm-new-session'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-session-note')).data,+ 'Sessions need a Claude Code Buddy',+ );+ expect(key('swarm-session-project'), findsNothing);+ await tester.enterText(find.byType(TextField), 'Hello');+ await tester.pump();+ await tester.tap(key('swarm-send'));+ await tester.pumpAndSettle();+ expect(sent(fake).containsKey('newSession'), isFalse);+ });+ });++ group('a thread', () {+ final plain = [sessionMessage('m2', 2, root: 'm1', author: me)];+ final live = [+ sessionMessage('m2', 2, root: 'm1', author: me, session: true),+ sessionMessage('m3', 3, root: 'm1', session: true),+ ];++ testWidgets('a reply with New session starts one, and never also goes '+ 'to the chat', (tester) async {+ final fake = threadBackend(replies: plain);+ await pump(tester, fake, thread: 'm1');+ expect(key('swarm-thread-session-line'), findsNothing);+ await tester.tap(key('swarm-thread-also-send'));+ await tester.pump();+ await tester.tap(key('swarm-thread-new-session'));+ await tester.pump();+ // A reply that starts a session is not offered to the chat too.+ expect(key('swarm-thread-also-send'), findsNothing);+ await tester.enterText(key('swarm-thread-field'), 'Look into it');+ await tester.pump();+ await tester.tap(key('swarm-thread-send'));+ await tester.pumpAndSettle();+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake)['replyTo'], 'm1');+ expect(sent(fake).containsKey('alsoSend'), isFalse);+ });++ testWidgets('a live session shows its status line; End session ends it '+ 'once', (tester) async {+ final fake = threadBackend(+ replies: live,+ sessions: [+ {+ 'thread': 'm1',+ 'startId': 's1',+ 'agentId': 'agent-session',+ 'at': 1,+ },+ ],+ extraAgents: [+ {+ ...agent('agent-session', name: 'Session'),+ 'buddySession': {+ 'thread': 'm1',+ 'from': 1,+ 'projectId': webProject,+ },+ },+ ],+ );+ await pump(tester, fake, thread: 'm1');+ expect(+ tester.widget<Text>(key('swarm-thread-session-state')).data,+ 'Web session · Running',+ );+ await tester.tap(key('swarm-thread-session-end'));+ await tester.pumpAndSettle();+ final ends = fake.commands.where((c) => c['type'] == 'buddy.sessionEnd');+ expect(ends, hasLength(1));+ expect(ends.single['thread'], 'm1');+ expect(ends.single['reason'], 'ended');+ });++ testWidgets('a session\'s thread offers neither New session nor Also '+ 'send', (tester) async {+ final fake = threadBackend(+ replies: live,+ sessions: [+ {'thread': 'm1', 'startId': 's1', 'at': 1},+ ],+ );+ await pump(tester, fake, thread: 'm1');+ expect(key('swarm-thread-new-session'), findsNothing);+ expect(key('swarm-thread-also-send'), findsNothing);+ });++ testWidgets('a refused End session says why on the thread page', (+ tester,+ ) async {+ final fake = threadBackend(+ replies: live,+ sessions: [+ {'thread': 'm1', 'startId': 's1', 'at': 1},+ ],+ );+ fake.routes[sessionCommands] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'The session could not be ended.',+ statusCode: 403,+ );+ await pump(tester, fake, thread: 'm1');+ await tester.tap(key('swarm-thread-session-end'));+ await tester.pumpAndSettle();+ expect(+ tester.widget<Text>(key('swarm-thread-post-error')).data,+ 'The session could not be ended.',+ );+ expect(find.text('End session'), findsOneWidget);+ });++ testWidgets('a session still starting says so', (tester) async {+ final fake = threadBackend(+ replies: live,+ sessions: [+ {'thread': 'm1', 'startId': 's1', 'at': 1},+ ],+ );+ await pump(tester, fake, thread: 'm1');+ expect(+ tester.widget<Text>(key('swarm-thread-session-state')).data,+ 'Own session · Starting…',+ );+ });++ testWidgets('an ended session says why, and the reply starts a new one: '+ 'New session is ticked and locked', (tester) async {+ final fake = threadBackend(+ replies: [+ ...live,+ sessionMessage(+ 'm4',+ 4,+ root: 'm1',+ session: true,+ source: {'kind': 'buddy-session-ended', 'reason': 'idle'},+ ),+ ],+ );+ await pump(tester, fake, thread: 'm1');+ expect(+ tester.widget<Text>(key('swarm-thread-session-ended')).data,+ 'Session ended: idle for 30 minutes',+ );+ expect(key('swarm-thread-session-end'), findsNothing);+ expect(+ tester.widget<Text>(key('swarm-thread-new-session-note')).data,+ 'This thread\'s session ended. Your reply starts a new one.',+ );+ final check = tester.widget<Checkbox>(+ find.descendant(+ of: key('swarm-thread-new-session'),+ matching: find.byType(Checkbox),+ ),+ );+ expect(check.value, isTrue);+ expect(check.onChanged, isNull);+ await tester.enterText(key('swarm-thread-field'), 'Carry on');+ await tester.pump();+ await tester.tap(key('swarm-thread-send'));+ await tester.pumpAndSettle();+ expect(sent(fake)['newSession'], isTrue);+ });++ testWidgets('a blocked chat shows New session greyed with its reason', (+ tester,+ ) async {+ final fake = threadBackend(replies: plain, engine: 'codex');+ await pump(tester, fake, thread: 'm1');+ expect(+ tester.widget<Text>(key('swarm-thread-new-session-note')).data,+ 'Sessions need a Claude Code Buddy',+ );+ final check = tester.widget<Checkbox>(+ find.descendant(+ of: key('swarm-thread-new-session'),+ matching: find.byType(Checkbox),+ ),+ );+ expect(check.onChanged, isNull);+ });+ });+}diff --git a/mobile/test/swarm/swarm_task_fields_test.dart b/mobile/test/swarm/swarm_task_fields_test.dartnew file mode 100644index 000000000..899bfbd7d--- /dev/null+++ b/mobile/test/swarm/swarm_task_fields_test.dart@@ -0,0 +1,55 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/model.dart';++/// What Desktop's model reads of a task and a Swarm, read the same way+/// (desktop_parity_test.dart names the fields; this holds their values).+void main() {+ Map<String, dynamic> group([Map<String, dynamic> more = const {}]) => {+ 'id': 'g',+ 'title': 'Task',+ 'brief': '',+ 'leadId': null,+ 'archived': false,+ 'agentIds': <String>[],+ ...more,+ };+ Map<String, dynamic> swarm([Map<String, dynamic> more = const {}]) => {+ 'version': 1,+ 'id': 'tab',+ 'name': 'Swarm',+ 'ownerId': 'owner',+ 'paused': false,+ 'people': <dynamic>[],+ 'agents': <dynamic>[],+ 'conversations': <dynamic>[],+ 'invitations': <dynamic>[],+ 'projects': <dynamic>[],+ ...more,+ };++ test('a task says who asked and when it shipped', () {+ final task = SuperTabConversation.fromJson(+ group({'requesterId': 'tony', 'shippedAt': 1000}),+ );+ expect(task.requesterId, 'tony');+ expect(task.shippedAt, DateTime.fromMillisecondsSinceEpoch(1000));+ });++ test('a server that does not say leaves both empty', () {+ final task = SuperTabConversation.fromJson(group());+ expect(task.requesterId, isNull);+ expect(task.shippedAt, isNull);+ });++ test('a Swarm lists the machines the reader took out, strings only', () {+ expect(+ SuperTabSnapshot.fromJson(+ swarm({+ 'removedMachines': ['m1', 3, 'm2'],+ }),+ ).removedMachines,+ ['m1', 'm2'],+ );+ expect(SuperTabSnapshot.fromJson(swarm()).removedMachines, isEmpty);+ });+}diff --git a/mobile/test/swarm/swarm_thread_focus_test.dart b/mobile/test/swarm/swarm_thread_focus_test.dartnew file mode 100644index 000000000..48eee9ea5--- /dev/null+++ b/mobile/test/swarm/swarm_thread_focus_test.dart@@ -0,0 +1,239 @@+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_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_thread.dart';+import 'package:harness_mobile/swarm/swarm_thread_page.dart';++import '../voice_fakes.dart';+import 'swarm_fixture.dart';++/// A thread opened at a message (Tony, 2026-11-02): an Activity row, a link+/// or a tag lands on the message in its thread — read in from earlier pages+/// when it is further back — and lights it for 2 seconds, as the main chat+/// does; a whole thread lands on its first unread reply, else its newest.+void main() {+ const messages = '/api/super-tabs/$tab/conversations/g1/messages';+ const thread = '$messages?thread=m1';+ final list = find.byKey(const ValueKey('swarm-thread-messages'));++ /// Message [sequence] of g1: the root is m1; every other is a reply in its+ /// thread, only there.+ Map<String, dynamic> said(int sequence) => {+ 'id': 'm$sequence',+ 'conversationId': 'g1',+ 'text': sequence == 1 ? 'The question.' : 'Reply $sequence.',+ 'sequence': sequence,+ 'author': {'kind': 'agent', 'id': 'agent-builder', 'name': 'agent-builder'},+ 'attachments': <Object>[],+ 'reactions': <Object>[],+ 'thread': 'm1',+ if (sequence > 1) 'replyTo': 'm1',+ 'createdAt': DateTime.utc(2026, 10, 29, 1, sequence).toIso8601String(),+ };++ Map<String, dynamic> lineOf(int replies, int last) => {+ 'id': 'm1',+ 'replies': replies,+ 'lastSequence': last,+ 'lastAt': DateTime.utc(2026, 10, 29, 2).toIso8601String(),+ 'authors': [+ {'kind': 'agent', 'id': 'agent-builder', 'name': 'agent-builder'},+ ],+ 'people': <String>[],+ };++ /// g1 whose thread under m1 holds replies 2..[last]. The thread's pages are+ /// [perPage] replies; the newest page answers the plain thread read and+ /// each earlier one the `before` read, so a reply further back than the+ /// pages read on open is only found by reading on.+ FakeSwarm backend(int last, {int mark = 0, int perPage = 100}) {+ final fake = FakeSwarm();+ fake.routes['/api/super-tabs/list'] = (_) => {+ 'tabs': [+ {'id': tab, 'name': 'Phone Swarm', 'ownerId': me},+ ],+ 'next': null,+ };+ fake.routes['/api/super-tabs/$tab/parts'] = (_) => {+ ...firstLoad(+ groups: [+ groupData(+ 'g1',+ title: 'Fix login',+ agentIds: ['agent-lead', 'agent-builder'],+ lastMessageSequence: last,+ ),+ ],+ derived: {+ 'readMarks': {'g1': 1},+ 'threadMarks': {+ 'g1': {'m1': mark},+ },+ },+ ),+ 'members': [part(me, 1, person(me))],+ };+ fake.routes['/api/super-tabs/$tab/changes'] = (_) => changes(cursor: 'c2');+ fake.routes['/api/super-tabs/$tab/decisions?state=open'] = (_) => {+ 'decisions': <Object>[],+ };+ fake.routes['/api/super-tabs/$tab/mentions?state=waiting'] = (_) => {+ 'mentions': <Object>[],+ };+ fake.routes[messages] = (_) => {+ 'messages': [said(1)],+ 'next': null,+ 'threads': [lineOf(last - 1, last)],+ };+ // Replies [from]..[to], newest first, with the cursor to the page before.+ Map<String, dynamic> page(int to) {+ final from = to - perPage + 1 < 2 ? 2 : to - perPage + 1;+ return {+ 'messages': [for (var i = to; i >= from; i--) said(i), said(1)],+ 'next': from > 2 ? {'sequence': from, 'id': 'm$from'} : null,+ 'threads': [lineOf(last - 1, last)],+ };+ }++ fake.routes[thread] = (_) => page(last);+ for (var to = last - perPage; to >= 2; to -= perPage) {+ final before = to + 1;+ fake.routes['$thread&before=$before&beforeId=m$before'] = (_) => page(to);+ }+ return fake;+ }++ /// The chat g1 opened at the thread m1 with [focus] on screen.+ Future<void> openAt(+ WidgetTester tester,+ FakeSwarm fake, {+ SwarmThreadFocus? focus,+ String? messageId = 'm1',+ }) 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,+ upload: refuseSwarmUpload,+ 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: SwarmConversationPage(+ swarmId: tab,+ conversationId: 'g1',+ messageId: messageId,+ threadId: 'm1',+ threadFocus: focus,+ ),+ ),+ );+ await tester.pumpAndSettle();+ }++ bool onScreen(WidgetTester tester, Finder f) {+ if (f.evaluate().isEmpty) return false;+ final view = tester.getRect(list);+ final row = tester.getRect(f);+ return row.top >= view.top && row.bottom <= view.bottom;+ }++ Finder lit(String id) => find.byKey(ValueKey('swarm-lit-$id'));++ /// The opacity of the wash behind message [id]'s row: what the person sees+ /// of it being lit.+ double washOf(WidgetTester tester, String id) {+ final row = tester.widget(find.byKey(ValueKey('swarm-message-$id')));+ if (row is! AnimatedContainer) return 0;+ return ((row.decoration as BoxDecoration).color ?? Colors.transparent).a;+ }++ group('a message in the thread', () {+ testWidgets('lands on it and lights it for 2 seconds', (tester) async {+ await openAt(+ tester,+ backend(40),+ focus: const SwarmThreadFocus.message('m20'),+ );++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(onScreen(tester, find.text('Reply 20.')), isTrue);+ expect(lit('m20'), findsOneWidget);+ expect(+ washOf(tester, 'm20'),+ greaterThan(0),+ reason: 'drawn, not just marked',+ );++ await tester.pump(const Duration(seconds: 2, milliseconds: 50));+ await tester.pumpAndSettle();+ expect(lit('m20'), findsNothing);+ expect(washOf(tester, 'm20'), 0, reason: 'the light went out');+ expect(onScreen(tester, find.text('Reply 20.')), isTrue);+ });++ testWidgets('further back than the pages read on open: reads on until '+ 'it shows, then lands on it', (tester) async {+ // 600 replies in pages of 100: the newest five are read on open, so+ // reply 3 is on the last page and not loaded at first.+ final fake = backend(600, perPage: 100);+ await openAt(tester, fake, focus: const SwarmThreadFocus.message('m3'));++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(onScreen(tester, find.text('Reply 3.')), isTrue);+ expect(lit('m3'), findsOneWidget);+ });++ testWidgets('one that is not in the thread leaves it at its top, no '+ 'error, no endless reading', (tester) async {+ final fake = backend(40);+ await openAt(tester, fake, focus: const SwarmThreadFocus.message('m999'));++ expect(find.byType(SwarmThreadPage), findsOneWidget);+ expect(find.text('The question.'), findsOneWidget);+ expect(find.textContaining('Could not'), findsNothing);+ expect(+ fake.paths.where((p) => p.startsWith(thread)).length,+ lessThan(10),+ );+ });+ });++ group('a whole thread', () {+ testWidgets('lands on its first unread reply', (tester) async {+ await openAt(+ tester,+ backend(40, mark: 10),+ focus: const SwarmThreadFocus.firstUnread(),+ );++ expect(onScreen(tester, find.text('Reply 11.')), isTrue);+ expect(onScreen(tester, find.text('The question.')), isFalse);+ });++ testWidgets('with every reply read lands on the newest', (tester) async {+ await openAt(+ tester,+ backend(40, mark: 40),+ focus: const SwarmThreadFocus.firstUnread(),+ );++ expect(onScreen(tester, find.text('Reply 40.')), isTrue);+ });+ });+}diff --git a/mobile/test/swarm/swarm_thread_session_test.dart b/mobile/test/swarm/swarm_thread_session_test.dartnew file mode 100644index 000000000..efeec46d8--- /dev/null+++ b/mobile/test/swarm/swarm_thread_session_test.dart@@ -0,0 +1,236 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/swarm/swarm_buddy_sessions.dart';+import 'package:harness_mobile/swarm/swarm_conversation.dart';+import 'package:harness_mobile/swarm/swarm_request.dart';+import 'package:harness_mobile/swarm/swarm_thread.dart';++import 'swarm_fixture.dart';+import 'swarm_session_fixture.dart';++/// New session in a thread's reply box of the person's own Buddy chat+/// (Desktop `sendThreadReply(newSession:)`, `threadSessionEnded`): a reply+/// starts a session, also in a thread whose session ended, and never goes to+/// the main chat too.+void main() {+ final live = [+ {'thread': 'm1', 'startId': 's1', 'agentId': 'agent-session', 'at': 1},+ ];++ Future<(FakeSwarm, SwarmConversation, SwarmThread)> rig({+ FakeSwarm? backend,+ List<Map<String, dynamic>>? page,+ }) async {+ final rows =+ page ??+ [+ sessionMessage('m1', 1, author: me),+ sessionMessage('m2', 2, root: 'm1', author: me),+ ];+ final fake = backend ?? sessionBackend(page: rows);+ fake.routes['$sessionMessages?thread=m1'] = (_) => {+ 'messages': [+ for (final m in rows.reversed)+ if (m['thread'] == 'm1') m,+ ],+ 'next': null,+ };+ final reader = await sessionReader(fake);+ addTearDown(reader.dispose);+ final chat = SwarmConversation(reader, sessionChat);+ addTearDown(chat.dispose);+ await chat.load();+ final thread = SwarmThread(chat, 'm1');+ addTearDown(thread.dispose);+ await thread.load();+ return (fake, chat, thread);+ }++ Map<String, dynamic> sent(FakeSwarm fake) =>+ fake.commands.lastWhere((c) => c['type'] == 'message.send');++ test('a reply with New session starts a session and never also goes to the '+ 'chat', () async {+ final (fake, _, thread) = await rig();+ expect(thread.offersSessions, isTrue);+ thread+ ..newSession = true+ ..alsoSend = true+ ..draft = 'Look into this';+ expect(await thread.send(), isTrue);+ expect(sent(fake)['newSession'], isTrue);+ expect(sent(fake)['replyTo'], 'm1');+ expect(sent(fake).containsKey('alsoSend'), isFalse);+ // Taken: the next reply is a plain one.+ expect(thread.newSession, isFalse);+ });++ test('a plain reply sends neither', () async {+ final (fake, _, thread) = await rig();+ thread.draft = 'Just a reply';+ expect(await thread.send(), isTrue);+ expect(sent(fake).containsKey('newSession'), isFalse);+ });++ test('a thread whose session ended starts a new one on reply: locked on, '+ 'and the ended line says why', () async {+ final (fake, _, thread) = await rig(+ page: [+ sessionMessage('m1', 1, author: me),+ sessionMessage('m2', 2, root: 'm1', session: true),+ sessionMessage(+ 'm3',+ 3,+ root: 'm1',+ session: true,+ source: {'kind': 'buddy-session-ended', 'reason': 'idle'},+ ),+ ],+ );+ expect(thread.session, isNull);+ expect(thread.sessionLocked, isTrue);+ expect(thread.newSession, isTrue);+ expect(thread.sessionEndedRow!.sessionEndReason, 'idle');+ thread.draft = 'Carry on';+ expect(await thread.send(), isTrue);+ expect(sent(fake)['newSession'], isTrue);+ });++ test('a thread that never had a session is not locked', () async {+ final (_, _, thread) = await rig(+ page: [sessionMessage('m1', 1, author: me)],+ );+ expect(thread.sessionLocked, isFalse);+ expect(thread.sessionEndedRow, isNull);+ expect(thread.newSession, isFalse);+ });++ test('a live session answers its thread; End session ends it once', () async {+ final (fake, _, thread) = await rig(+ backend: sessionBackend(sessions: live),+ );+ expect(thread.session!.agentId, 'agent-session');+ expect(thread.sessionLocked, isFalse);+ final first = thread.endSession();+ final second = thread.endSession();+ expect(thread.endingSession, isTrue);+ expect(await first, isTrue);+ expect(await second, isFalse);+ expect(+ fake.commands.where((c) => c['type'] == 'buddy.sessionEnd'),+ hasLength(1),+ );+ expect(thread.endingSession, isFalse);+ });++ test('a blocked chat says why and sends a plain reply', () async {+ final (fake, _, thread) = await rig(+ backend: sessionBackend(+ engine: 'codex',+ page: [sessionMessage('m1', 1, author: me)],+ ),+ page: [sessionMessage('m1', 1, author: me)],+ );+ expect(thread.sessionBlocked, 'Sessions need a Claude Code Buddy');+ thread+ ..newSession = true+ ..draft = 'Hi';+ expect(thread.newSession, isFalse);+ expect(await thread.send(), isTrue);+ expect(sent(fake).containsKey('newSession'), isFalse);+ });++ test('no New session where the server takes none for a reply', () async {+ final (_, _, thread) = await rig(+ backend: sessionBackend(+ threadSessions: false,+ page: [sessionMessage('m1', 1, author: me)],+ ),+ page: [sessionMessage('m1', 1, author: me)],+ );+ expect(thread.offersSessions, isFalse);+ });++ test('a server that does not know newSession gives the reply back', () async {+ final fake = sessionBackend(page: [sessionMessage('m1', 1, author: me)]);+ fake.routes[sessionCommands] = (_) => throw const SuperTabFailure(+ 'VALIDATION_ERROR',+ "command: Unrecognized key: 'newSession'",+ statusCode: 400,+ );+ final (_, _, thread) = await rig(+ backend: fake,+ page: [sessionMessage('m1', 1, author: me)],+ );+ thread+ ..newSession = true+ ..draft = 'Start one';+ expect(await thread.send(), isFalse);+ expect(thread.draft, 'Start one');+ expect(thread.error, swarmSessionsUnavailable);+ expect(thread.offersSessions, isFalse);+ });++ group(+ 'a thread a session answers now (Desktop offersAlsoSend, _offersSession)',+ () {+ final liveRows = [+ sessionMessage('m1', 1, author: me),+ sessionMessage('m2', 2, root: 'm1', author: me, session: true),+ sessionMessage('m3', 3, root: 'm1', session: true),+ ];+ final live = [+ {'thread': 'm1', 'startId': 's1', 'agentId': 'agent-session', 'at': 1},+ ];++ test('offers neither New session nor Also send, and sends a plain reply '+ 'to the session', () async {+ final (fake, _, thread) = await rig(+ backend: sessionBackend(sessions: live, page: liveRows),+ page: liveRows,+ );+ expect(thread.session, isNotNull);+ expect(thread.offersSessions, isFalse);+ expect(thread.offersAlsoSend, isFalse);+ thread+ ..newSession = true+ ..alsoSend = true+ ..draft = 'Next step';+ expect(thread.newSession, isFalse);+ expect(await thread.send(), isTrue);+ expect(sent(fake).containsKey('newSession'), isFalse);+ expect(sent(fake).containsKey('alsoSend'), isFalse);+ });++ test('Also send is offered in a plain thread, not for a reply that '+ 'starts a session', () async {+ final (_, _, thread) = await rig();+ expect(thread.offersAlsoSend, isTrue);+ thread.newSession = true;+ expect(thread.offersAlsoSend, isFalse);+ });++ test('its status line stays after a server refusal, while New session '+ 'is not offered', () async {+ final (_, chat, thread) = await rig(+ backend: sessionBackend(sessions: live, page: liveRows),+ page: liveRows,+ );+ swarmSessionsRefused(chat.reader);+ expect(thread.session, isNotNull);+ });++ test('a refused End session says why in the thread', () async {+ final fake = sessionBackend(sessions: live, page: liveRows);+ fake.routes[sessionCommands] = (_) => throw const SuperTabFailure(+ 'FORBIDDEN',+ 'The session could not be ended.',+ statusCode: 403,+ );+ final (_, _, thread) = await rig(backend: fake, page: liveRows);+ expect(await thread.endSession(), isFalse);+ expect(thread.error, 'The session could not be ended.');+ expect(thread.endingSession, isFalse);+ });+ },+ );+}