Skip to content

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

Merge batch 11-03 ca: #2718 #2742 (#2762)

0xken15af7e94d4adf3
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index e2f7e43c8..c54d06a61 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -1006,6 +1006,12 @@ describe('Swarm cards', () => {
expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: '', fromDevice: false })
})
+ it('names the thread the window has open beside that conversation', () => {
+ const host = new DaemonCableHost(wiring())
+ host.setSwarms({ active: 't1', tiles: [], swarms: [{ id: 't1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st1', projectId: 'p1', conversationId: 'pm1', threadRoot: 'm1' }] })
+ expect(host.activeSwarmProject()).toEqual({ superTabId: 'st1', projectId: 'p1', conversationId: 'pm1', threadRoot: 'm1', fromDevice: false })
+ })
+
it('names the conversation the window has open in the active Swarm tab, when it names one', () => {
const host = new DaemonCableHost(wiring())
const swarms = [
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index 6c4165003..af8e0c4c7 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -575,13 +575,15 @@ export class DaemonCableHost implements CableHost {
* The active tab when it is a Swarm, with its open project or '' when none is (its Chat with PM, a DM, or a Swarm
* not loaded yet); `fromDevice` when the announce was a device's own pick. A Swarm tab with no project used to read
* as no Swarm at all, and the dial stayed on "Nothing on this tab" while the window showed the Swarm. `conversationId`: the
- * conversation it has open there, when the window names one, which the round dial's face follows.
+ * conversation it has open there, when the window names one, which the round dial's face follows, and `threadRoot` the
+ * thread whose pane is on screen beside it.
*/
- activeSwarmProject(): { superTabId: string; projectId: string; conversationId?: string; fromDevice: boolean } | null {
+ activeSwarmProject(): { superTabId: string; projectId: string; conversationId?: string; threadRoot?: string; fromDevice: boolean } | null {
const app = this.swarms
const tab = app?.swarms.find((s) => s.id === app.active)
return app && tab?.superTabId ? { superTabId: tab.superTabId, projectId: tab.projectId ?? '',
- ...(tab.conversationId ? { conversationId: tab.conversationId } : {}), fromDevice: app.fromDevice === true } : null
+ ...(tab.conversationId ? { conversationId: tab.conversationId, ...(tab.threadRoot ? { threadRoot: tab.threadRoot } : {}) } : {}),
+ fromDevice: app.fromDevice === true } : null
}
selectSwarm(swarmId: string): void {
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index 5f5b7ca3e..e76c8815b 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -16,7 +16,7 @@ import { DaemonCableHost } from './cableHost.js'
import type { MachineFleet } from './machineFleet.js'
import { CableSession, recapFrame, type CableAgent, type CableHost, type CableMachine, type CablePort } from './cableSession.js'
import { DialLog } from './dialLog.js'
-import { leadsOf, type SaidOnCard, type SwarmCard, type SwarmLead } from '../superTabs/cards.js'
+import { leadsOf, type LeadRecap, type SaidOnCard, type SwarmCard, type SwarmLead } from '../superTabs/cards.js'
import { createSuperTabCards } from '../superTabs/inCore/cards.js'
import type { PetStore } from './pets/store.js'
@@ -4140,6 +4140,35 @@ describe('swarm cards', () => {
} finally { await session.stop() }
})
+ // A dial's recap that came back with nothing left its face on the resting pet and said nowhere why (Diego, 2026-11-03).
+ it('logs a recap that came back empty or failed once per Lead and reason, and again after one came back', async () => {
+ const lines: string[] = []
+ const host = cardHost({ cards: [card('st1')] }, { log: (l) => lines.push(l) })
+ const { session, port } = await connect(host)
+ const recapLines = () => lines.filter((l) => l.startsWith('cable: recap for'))
+ const ask = async (answer: () => Promise<LeadRecap | null>) => {
+ vi.mocked(host.swarmCardRecap!).mockImplementationOnce(answer)
+ port.say({ t: 'supertab.recap.get', tab: 'st1', lead: 'lead1' })
+ await settle(); await settle()
+ // A pushed recap for that Lead ends the repeat window, so the next ask is read again.
+ await session.swarmCardRecap({ tabId: 'st1', leadId: 'lead1', text: 'x', at: 1, none: false })
+ }
+ try {
+ port.say(PRO)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ await ask(async () => null)
+ await ask(async () => null)
+ expect(recapLines()).toEqual(['cable: recap for lead1 came back empty'])
+ await ask(async () => { throw new Error('SERVICE_UNAVAILABLE') })
+ await ask(async () => { throw new Error('SERVICE_UNAVAILABLE') })
+ expect(recapLines()).toEqual(['cable: recap for lead1 came back empty', 'cable: recap for lead1 failed (SERVICE_UNAVAILABLE)'])
+ await ask(async () => ({ tabId: 'st1', leadId: 'lead1', text: 'Shipped it.', at: 1792560000, none: false }))
+ await ask(async () => null)
+ expect(recapLines()).toHaveLength(3)
+ expect(recapLines().at(-1)).toBe('cable: recap for lead1 came back empty')
+ } finally { await session.stop() }
+ })
+
it('supertab.open tells the core which Lead is open, and a pushed recap reaches the device only for that Lead', async () => {
const host = cardHost({ cards: [card('st1')] })
const { session, port } = await connect(host)
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 07a36e91c..b9775d0fe 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -339,6 +339,8 @@ export interface AppSwarms {
superTabId?: string; projectId?: string
/** The conversation the window has open in that Swarm tab, when it is one (its Lead's, Chat with PM or a group). */
conversationId?: string
+ /** The root of the thread whose pane is on screen beside that conversation, which the round dial's face follows. */
+ threadRoot?: string
}>
/** The ACTIVE swarm's grid. Empty from a window that predates the field, or one with no panes. */
tiles: CableTile[]
@@ -417,7 +419,7 @@ export interface CableHost {
* reader's Buddy chat there ('buddy') or the project's Lead chat ('pm'), so the desktop follows the dial's side. */
superTabSelected?(superTabId: string, projectId: string, chat?: CardSide): void
/** The Swarm tab the window has on screen and the project open in it ('' when none is); null when the active tab is not a Swarm or there is no window. */
- activeSwarmProject?(): { superTabId: string; projectId: string; conversationId?: string; fromDevice: boolean } | null
+ activeSwarmProject?(): { superTabId: string; projectId: string; conversationId?: string; threadRoot?: string; fromDevice: boolean } | null
appName(): string
voiceLang(): string
/** The window's latest selected pane, including selections made before this dial attached. */
@@ -2770,6 +2772,8 @@ export class CableSession {
/** The project this Pro itself picked last and when: the desktop's announce of it is no news, and a stale one of another is held off. */
private picked: { key: string; at: number } | null = null
private lastRecapGet: { key: string; at: number; read: Promise<LeadRecap | null> } | null = null
+ /** `${lead} ${why}` of each recap that came back with nothing and was logged (recapMissed). */
+ private readonly recapsMissed = new Set<string>()
/** A swarmChat dial's alerts (`${tab}:${lead}`): the notice it was last given or shown as already there, and whether it
* was read on the desktop since. A notice is sent once, never on an attach or resync (it was there before), never for
* the chat the desktop has open; `notice.read` once when the desktop opens the chat of one that was sent. */
@@ -3056,7 +3060,8 @@ export class CableSession {
if (this.lastRecapGet?.key !== asked || now - this.lastRecapGet.at >= RECAP_REPEAT_MS || !listed) {
const read = Promise.resolve()
.then(() => this.host.swarmCardRecap?.(tab, lead, ...this.chatFlag()) ?? null)
- .catch((err) => { this.log(`cable: recap for ${lead} failed (${(err as Error).message})`); return null })
+ .then((recap) => { this.recapMissed(lead, recap ? null : 'came back empty'); return recap },
+ (err) => { this.recapMissed(lead, `failed (${(err as Error).message})`); return null })
this.lastRecapGet = { key: asked, at: now, read }
}
const recap = await this.lastRecapGet.read
@@ -3064,6 +3069,15 @@ export class CableSession {
if (recap) await this.queued(async () => { await this.send(recapFrame(recap)) })
}
+ /** A recap the dial asked for that came back with nothing leaves its face on the resting pet: said once per Lead and why,
+ * and again after one came back (`why` null). */
+ private recapMissed(lead: string, why: string | null): void {
+ if (why === null) { for (const key of [...this.recapsMissed]) if (key.startsWith(`${lead} `)) this.recapsMissed.delete(key); return }
+ if (this.recapsMissed.has(`${lead} ${why}`)) return
+ this.recapsMissed.add(`${lead} ${why}`)
+ this.log(`cable: recap for ${lead} ${why}`)
+ }
+
/** Open a project's chat in its Swarm tab for this dial. Remembered before the window answers, so its announce of this very
* project is not sent back as a focus. */
private openSwarmChat(tab: string, projectId: string, chat: CardSide | undefined): void {
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 7ad4f7553..b1977aebd 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -811,6 +811,32 @@ describe('local CLI WebSocket', () => {
ws.close()
})
+ it('app_swarms keeps the open thread\'s root beside its conversation, and drops one that is not an id', async () => {
+ const backend = new FakeBackend()
+ const seen: unknown[] = []
+ server = http.createServer((_req, res) => { res.statusCode = 404; res.end() })
+ local = attachLocalWsServer(server, { machineId, backend, onAppSwarms: (swarms) => seen.push(swarms) })
+ await new Promise<void>((resolve) => server!.listen(0, '127.0.0.1', resolve))
+ const ws = new WebSocket(`ws://127.0.0.1:${(server.address() as AddressInfo).port}/api/local-ws`)
+ await onceOpen(ws)
+ const connected = onceMessage(ws)
+ ws.send(JSON.stringify({ type: 'machine_select', payload: { machineId, localProtocolVersion: 1 } }))
+ await connected
+ ws.send(JSON.stringify({ type: 'app_swarms', payload: { active: 's1', swarms: [
+ { id: 's1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'pm-1', threadRoot: 'm-1' },
+ { id: 's2', name: 'Bad', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'pm-1', threadRoot: 'no spaces' },
+ { id: 's3', name: 'Alone', agentIds: [], panes: 1, superTabId: 'st_1', threadRoot: 'm-1' },
+ ] } }))
+ await vi.waitFor(() => expect(seen).toHaveLength(1))
+ expect(seen[0]).toEqual({ active: 's1', tiles: [], swarms: [
+ { id: 's1', name: 'Swarm', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'pm-1', threadRoot: 'm-1' },
+ { id: 's2', name: 'Bad', agentIds: [], panes: 1, superTabId: 'st_1', conversationId: 'pm-1' },
+ // A thread is of a conversation: with none named, there is none.
+ { id: 's3', name: 'Alone', agentIds: [], panes: 1, superTabId: 'st_1' },
+ ] })
+ ws.close()
+ })
+
it('app_swarms keeps a Swarm tab\'s conversationId, and drops one that is not an id', async () => {
const backend = new FakeBackend()
const seen: unknown[] = []
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 2ca9183c9..e943f1221 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -258,8 +258,10 @@ function appSwarmsFrom(payload: unknown): AppSwarms | null {
const projectId = typeof r.projectId === 'string' && CARD_ID.test(r.projectId) ? r.projectId : undefined
// And the conversation it has open (its Lead's, the person's Buddy chat or a group), which the round dial's face follows.
const conversationId = typeof r.conversationId === 'string' && CARD_ID.test(r.conversationId) ? r.conversationId : undefined
+ // And the thread open beside it, by its root: a thread is of a conversation, so with none named there is none.
+ const threadRoot = conversationId && typeof r.threadRoot === 'string' && CARD_ID.test(r.threadRoot) ? r.threadRoot : undefined
swarms.push({ id: r.id, name: r.name.slice(0, 80), agentIds, panes, ...(superTabId ? { superTabId } : {}), ...(projectId ? { projectId } : {}),
- ...(conversationId ? { conversationId } : {}) })
+ ...(conversationId ? { conversationId } : {}), ...(threadRoot ? { threadRoot } : {}) })
if (swarms.length === 24) break // the window's own ceiling
}
if (swarms.length === 0) return null
diff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.ts
index f48a8f73b..a3261a5e5 100644
--- a/cli/src/services/devices.spec.ts
+++ b/cli/src/services/devices.spec.ts
@@ -637,9 +637,9 @@ describe('what the windows say, reaching the dial', () => {
it('tells the cards the window\'s open Swarm conversation, again only when it changes', () => {
const superTabRequest = vi.fn(async () => ({ ok: true }))
const { port, reconnected } = withRequest(superTabRequest)
- const open = (active: string, conversationId?: string) => ({ active, tiles: [], swarms: [
+ const open = (active: string, conversationId?: string, threadRoot?: string) => ({ active, tiles: [], swarms: [
{ id: 'plain', name: 'plain', agentIds: [], panes: 0 },
- { id: 'tab-st1', name: 'st1', agentIds: [], panes: 0, superTabId: 'st1', projectId: 'p1', ...(conversationId ? { conversationId } : {}) }] })
+ { id: 'tab-st1', name: 'st1', agentIds: [], panes: 0, superTabId: 'st1', projectId: 'p1', ...(conversationId ? { conversationId } : {}), ...(threadRoot ? { threadRoot } : {}) }] })
port.swarms(open('tab-st1', 'pm1'))
seen.host.swarmCardsWanted!(true)
expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'pm1' } })
@@ -659,6 +659,12 @@ describe('what the windows say, reaching the dial', () => {
superTabRequest.mockClear()
reconnected.forEach((run) => run())
expect(superTabRequest.mock.calls).toEqual([[{ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'g1' } }]])
+ // A thread opened beside it is news, and so is its closing.
+ port.swarms(open('tab-st1', 'g1', 'm1'))
+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'g1', threadRoot: 'm1' } })
+ port.swarms(open('tab-st1', 'g1'))
+ expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['st1'], focus: { tabId: 'st1', conversationId: 'g1' } })
+ superTabRequest.mockClear()
// Nobody wants cards: a focus change says nothing.
seen.host.swarmCardsWanted!(false)
superTabRequest.mockClear()
@@ -692,6 +698,12 @@ describe('what the windows say, reaching the dial', () => {
expect(superTabRequest).toHaveBeenLastCalledWith({ action: 'cardOpen', session: 'c1', tabId: 'st1', leadId: null })
})
+ // A refusal turned into null said nowhere why the dial's face stayed on the resting pet (Diego, 2026-11-03).
+ it('fails a refused recap with the service\'s code, so the dial\'s log says why', async () => {
+ withRequest(vi.fn(async () => ({ error: 'SERVICE_UNAVAILABLE' })))
+ await expect(seen.host.swarmCardRecap!('st1', 'lead1', true)).rejects.toThrow('SERVICE_UNAVAILABLE')
+ })
+
it('asks for a swarmBuddy dial\'s face with the buddy flag, says so on its recap, and sends its side as cardSide', async () => {
const answers: Array<Record<string, unknown>> = [
{ ok: true, text: 'from the Buddy', at: 3, none: false, chatId: 'b1', buddy: true },
@@ -728,7 +740,10 @@ describe('what the windows say, reaching the dial', () => {
expect(got).toMatchObject({ tabId: 'st1', leadId: 'lead1', at: 1792560000, none: false })
expect(got!.text).toBe('é'.repeat(750))
expect(await seen.host.swarmCardRecap!('st1', 'lead2')).toEqual({ tabId: 'st1', leadId: 'lead2', text: 'none', at: 0, none: true })
- for (let i = 0; i < 6; i++) expect(await seen.host.swarmCardRecap!('st1', 'lead1')).toBeNull()
+ // A refusal fails with its code; anything else unusable is null.
+ await expect(seen.host.swarmCardRecap!('st1', 'lead1')).rejects.toThrow('NOT_FOUND')
+ for (let i = 0; i < 4; i++) expect(await seen.host.swarmCardRecap!('st1', 'lead1')).toBeNull()
+ await expect(seen.host.swarmCardRecap!('st1', 'lead1')).rejects.toThrow('SERVICE_UNAVAILABLE')
})
it('posts words for a Lead through the service; anything but said: true sends the turn instead', async () => {
@@ -757,7 +772,7 @@ describe('what the windows say, reaching the dial', () => {
it('answers no recap when the core has no service to ask', async () => {
start()
- expect(await seen.host.swarmCardRecap!('st1', 'lead1')).toBeNull()
+ await expect(seen.host.swarmCardRecap!('st1', 'lead1')).rejects.toThrow('SERVICE_UNAVAILABLE')
seen.host.swarmCardOpen!('c1', 'st1', 'lead1') // nothing to tell, and nothing thrown
})
diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.ts
index df89b437e..b9123a277 100644
--- a/cli/src/services/devices.ts
+++ b/cli/src/services/devices.ts
@@ -190,7 +190,7 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
let cardInclude: string[] = []
// The conversation the window has open in its active Swarm tab, which the round dial's face follows (design
// 2026-10-28-round-dial-swarm-chat): said with the wish, and left out when there is none, as before.
- let cardFocus: { tabId: string; conversationId: string; fromDevice?: true } | null = null
+ let cardFocus: { tabId: string; conversationId: string; threadRoot?: string; fromDevice?: true } | null = null
const tellCards = (): void => {
const on = cardDevices > 0
void askCards({ action: 'cardsWanted', on, include: on ? cardInclude : [], ...(on && cardFocus ? { focus: cardFocus } : {}) })
@@ -254,6 +254,8 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
// name that chat by an id: a dial never shows it for another one.
swarmCardRecap: async (tabId, leadId, chat) => {
const r = await askCards({ action: 'cardRecap', tabId, leadId, ...chatFlag(chat) })
+ // A refusal fails with its code, which the dial's log names; null was silent (Diego, 2026-11-03).
+ if (r.ok !== true && typeof r.error === 'string') throw new Error(r.error)
if (r.ok !== true || typeof r.text !== 'string' || typeof r.at !== 'number' || !Number.isInteger(r.at) || r.at < 0 || typeof r.none !== 'boolean') return null
if (chat && !(typeof r.chatId === 'string' && CHAT_ID.test(r.chatId))) return null
return { tabId, leadId, text: truncateUtf8(r.text, 1500), at: r.at, none: r.none, ...(chat ? { chatId: r.chatId as string } : {}),
@@ -582,9 +584,11 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)
const include = [...new Set((swarms?.swarms ?? []).map((s) => s.superTabId).filter((id): id is string => !!id))].slice(0, 16)
const open = cableHost.activeSwarmProject()
// `fromDevice`: the window followed a device's own pick, which the cards keep a dial's side through.
+ // `threadRoot`: the thread open beside it, whose opening or closing moves the dial's face too.
const focus = open?.conversationId
- ? { tabId: open.superTabId, conversationId: open.conversationId, ...(open.fromDevice ? { fromDevice: true as const } : {}) } : null
- const refocused = `${focus?.tabId}/${focus?.conversationId}` !== `${cardFocus?.tabId}/${cardFocus?.conversationId}`
+ ? { tabId: open.superTabId, conversationId: open.conversationId, ...(open.threadRoot ? { threadRoot: open.threadRoot } : {}),
+ ...(open.fromDevice ? { fromDevice: true as const } : {}) } : null
+ const refocused = `${focus?.tabId}/${focus?.conversationId}/${focus?.threadRoot}` !== `${cardFocus?.tabId}/${cardFocus?.conversationId}/${cardFocus?.threadRoot}`
if (include.join(',') !== cardInclude.join(',') || refocused) { cardInclude = include; cardFocus = focus; if (cardDevices > 0) tellCards() }
void cable.syncSwarms()
void cable.syncAgents()
diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.ts
index 7861be907..eb4247e4a 100644
--- a/cli/src/superTabs/cards.spec.ts
+++ b/cli/src/superTabs/cards.spec.ts
@@ -21,10 +21,10 @@ const idle = () => ({ inTurn: false })
const work = (id: string, status: string) => conv(`w-${id}`, null, { projectId: id, assignment: { status } })
describe('leadsOf', () => {
- it('picks one Lead per project through its lead conversation, in project order', () => {
+ it('picks one Lead per project through its lead conversation, in the app\'s project order', () => {
const { count, leads } = leadsOf(swarm(), 'm1', idle)
expect(count).toBe(2)
- expect(leads.map(l => [l.id, l.projectId, l.project, l.engine, l.local, l.state])).toEqual([['a1', 'web', 'web', 'claude', 'h-a1', 'done'], ['a2', 'mobile', 'mobile', 'claude', 'h-a2', 'done']])
+ expect(leads.map(l => [l.id, l.projectId, l.project, l.engine, l.local, l.state])).toEqual([['a2', 'mobile', 'mobile', 'claude', 'h-a2', 'done'], ['a1', 'web', 'web', 'claude', 'h-a1', 'done']])
})
it('reads an old tab without projects as the one `lead` project, and skips a project with no Lead agent', () => {
@@ -91,25 +91,42 @@ describe('leadsOf', () => {
expect(leadsOf(swarm(), 'm1', () => null).leads.map(l => l.local)).toEqual(['', ''])
})
- it('orders ask, stuck, work, done with ties in project order, and caps at 12 Leads', () => {
- const projects = Array.from({ length: 13 }, (_, i) => ({ id: `p${i}`, name: `P${i}`, leadConversationId: `lead-p${i}` }))
+ it('orders ask, stuck, work, done with ties in the app\'s project order, and caps at 12 Leads', () => {
+ const projects = Array.from({ length: 13 }, (_, i) => ({ id: `p${i}`, name: `P${String(i).padStart(2, '0')}`, leadConversationId: `lead-p${i}` }))
const many = swarm({ projects, agents: projects.map((_, i) => agent(`a${i}`)),
conversations: [...projects.map((p, i) => conv(p.leadConversationId, `a${i}`, { projectId: p.id })), work('p5', 'blocked'), work('p9', 'needs_human'), work('p2', 'working'), work('p7', 'needs_human')] })
const { count, leads } = leadsOf(many, 'm1', idle)
expect(count).toBe(13)
expect(leads).toHaveLength(12)
- expect(leads.slice(0, 5).map(l => [l.project, l.state])).toEqual([['P7', 'ask'], ['P9', 'ask'], ['P5', 'stuck'], ['P2', 'work'], ['P0', 'done']])
+ expect(leads.slice(0, 5).map(l => [l.project, l.state])).toEqual([['P07', 'ask'], ['P09', 'ask'], ['P05', 'stuck'], ['P02', 'work'], ['P00', 'done']])
})
- it('gives each Lead its project\'s index as `order`, whatever place urgency gives it', () => {
+ // Diego's dial, 2026-11-03: a swipe went by creation order while the app lists projects A to Z (project_sidebar.dart).
+ it('orders Leads as the app lists projects: by name A to Z, whatever the case', () => {
+ const named = swarm({
+ projects: [{ id: 'z', name: 'Zeta', leadConversationId: 'lead-z' }, { id: 'a', name: 'alpha', leadConversationId: 'lead-a' }, { id: 'm', name: 'Mid', leadConversationId: 'lead-m' }],
+ agents: [agent('a1'), agent('a2'), agent('a3')],
+ conversations: [conv('lead-z', 'a1', { projectId: 'z' }), conv('lead-a', 'a2', { projectId: 'a' }), conv('lead-m', 'a3', { projectId: 'm' })],
+ })
+ expect(leadsOf(named, 'm1', idle).leads.map(l => [l.project, l.order])).toEqual([['alpha', 0], ['Mid', 1], ['Zeta', 2]])
+ })
+
+ it('keeps server order between projects whose names differ only in case', () => {
+ const twins = swarm({ projects: [{ id: 'web', name: 'web', leadConversationId: 'lead-web' }, { id: 'mobile', name: 'Web', leadConversationId: 'lead-mobile' }] })
+ expect(leadsOf(twins, 'm1', idle).leads.map(l => [l.projectId, l.order])).toEqual([['web', 0], ['mobile', 1]])
+ const flipped = swarm({ projects: [{ id: 'mobile', name: 'Web', leadConversationId: 'lead-mobile' }, { id: 'web', name: 'web', leadConversationId: 'lead-web' }] })
+ expect(leadsOf(flipped, 'm1', idle).leads.map(l => [l.projectId, l.order])).toEqual([['mobile', 0], ['web', 1]])
+ })
+
+ it('gives each Lead its project\'s place in the app\'s A to Z list as `order`, whatever place urgency gives it', () => {
const three = swarm({
projects: [...swarm().projects, { id: 'api', name: 'api', leadConversationId: 'lead-api' }],
agents: [agent('a1'), agent('a2'), agent('a3')],
conversations: [...swarm().conversations, conv('lead-api', 'a3', { projectId: 'api' }), work('mobile', 'needs_human'), work('api', 'working')],
})
- expect(leadsOf(three, 'm1', idle).leads.map(l => [l.project, l.state, l.order])).toEqual([['mobile', 'ask', 1], ['api', 'work', 2], ['web', 'done', 0]])
- // The 12 most urgent of 13 keep their own index: the one left out leaves a gap.
- const projects = Array.from({ length: 13 }, (_, i) => ({ id: `p${i}`, name: `P${i}`, leadConversationId: `lead-p${i}` }))
+ expect(leadsOf(three, 'm1', idle).leads.map(l => [l.project, l.state, l.order])).toEqual([['mobile', 'ask', 1], ['api', 'work', 0], ['web', 'done', 2]])
+ // The 12 most urgent of 13 keep their own place: the one left out leaves a gap.
+ const projects = Array.from({ length: 13 }, (_, i) => ({ id: `p${i}`, name: `P${String(i).padStart(2, '0')}`, leadConversationId: `lead-p${i}` }))
const many = swarm({ projects, agents: projects.map((_, i) => agent(`a${i}`)),
conversations: [...projects.map((p, i) => conv(p.leadConversationId, `a${i}`, { projectId: p.id })), ...projects.slice(1).map(p => work(p.id, 'working'))] })
expect(leadsOf(many, 'm1', idle).leads.map(l => l.order)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
@@ -207,9 +224,32 @@ describe('lastAgentMessage', () => {
})
})
+// Diego's dial, 2026-11-03: the chat recap showed the PM's latest thread reply, not its latest message in the chat.
+describe('lastAgentMessage in a chat or a thread', () => {
+ const row = (sequence: number, over: Record<string, unknown> = {}) => ({ id: `m${sequence}`, sequence, text: `t${sequence}`, author: { kind: 'agent', id: 'a1' }, createdAt: '2026-10-22T00:00:00.000Z', ...over })
+ const lead = new Set(['a1'])
+ const rows = [row(1, { thread: 'm1' }), row(2), row(3, { thread: 'm1', alsoInChat: true }), row(4, { thread: 'm1' }), row(5, { thread: 'm9' })]
+
+ it('in the chat, skips a thread reply but keeps a top-level message, one from before threads and a reply also sent to the chat', () => {
+ expect(lastAgentMessage(rows, lead, 'chat')?.text).toBe('t3')
+ expect(lastAgentMessage(rows.filter(r => r.sequence !== 3), lead, 'chat')?.text).toBe('t2')
+ expect(lastAgentMessage([row(1, { thread: 'm1' }), row(4, { thread: 'm1' })], lead, 'chat')?.text).toBe('t1')
+ // Unscoped, as the notices read: every row.
+ expect(lastAgentMessage(rows, lead)?.text).toBe('t5')
+ })
+
+ it('in a thread, takes only that thread\'s rows, its root among them', () => {
+ expect(lastAgentMessage(rows, lead, { thread: 'm1' })?.text).toBe('t4')
+ expect(lastAgentMessage([row(1, { thread: 'm1' }), row(5, { thread: 'm9' })], lead, { thread: 'm1' })?.text).toBe('t1')
+ expect(lastAgentMessage(rows, lead, { thread: 'nope' })).toBeNull()
+ })
+})
+
/** A fake backend: tabs by id with the time each last changed, a message store per conversation, and call counting. */
-function setup(tabs: Record<string, { lastChangedAt: number; state: Record<string, unknown> }>, extra: { activity?: Record<string, 'working' | 'idle'>; elapsed?: number; messages?: (path: string) => unknown; post?: () => { status: number; body: Record<string, unknown> } } = {}) {
+function setup(tabs: Record<string, { lastChangedAt: number; state: Record<string, unknown> }>, extra: { activity?: Record<string, 'working' | 'idle'>; elapsed?: number; messages?: (path: string) => unknown; post?: () => { status: number; body: Record<string, unknown> }; delayMs?: number } = {}) {
const calls: string[] = []
+ // Message reads in flight now and at most, for a backend whose reads take `delayMs`.
+ let reading = 0, mostReading = 0
const failing = new Map<string, number>()
let listFails = false
let pages: Record<string, { next: string | null }> = {}
@@ -235,7 +275,11 @@ function setup(tabs: Record<string, { lastChangedAt: number; state: Record<strin
return { status: 200, body: { success: true, data: swarmReply(path, tabs[tab[1]].state, { lastChangedAt: tabs[tab[1]].lastChangedAt }) } }
}
// The real messages page: { messages, next }, `next` the (sequence, id) cursor of the page before.
- return { status: 200, body: { success: true, data: { ...(extra.messages?.(path) ?? { messages: [], next: null }) as object } } }
+ reading++; mostReading = Math.max(mostReading, reading)
+ try {
+ if (extra.delayMs) await new Promise(resolve => setTimeout(resolve, extra.delayMs))
+ return { status: 200, body: { success: true, data: { ...(extra.messages?.(path) ?? { messages: [], next: null }) as object } } }
+ } finally { reading-- }
})
const core = fakeCore({
account: { backend: call as unknown as CoreApi['account']['backend'], identity: vi.fn(async () => ({ accountId: 'me', email: '[email protected]' })) },
@@ -248,7 +292,7 @@ function setup(tabs: Record<string, { lastChangedAt: number; state: Record<strin
const cards = new SwarmCards(core, 'm1', { now: () => clock, intervalMs: 5000, log })
const seen: SwarmCard[][] = []
cards.onCards = c => seen.push(c)
- return { cards, calls, seen, call, core, failing, tabs, log, paginate: (p: typeof pages) => { pages = p }, pageBy: (n: number) => { pageSize = n }, breakList: (v = true) => { listFails = v }, advance: (ms: number) => { clock += ms } }
+ return { cards, calls, seen, call, core, failing, tabs, log, mostReading: () => mostReading, paginate: (p: typeof pages) => { pages = p }, pageBy: (n: number) => { pageSize = n }, breakList: (v = true) => { listFails = v }, advance: (ms: number) => { clock += ms } }
}
/** Each read of a tab, named by the tab: a changes read, or a first load that no changes read of it asked for. */
function detailReads(calls: string[]): string[] {
@@ -709,20 +753,6 @@ describe('SwarmCards open recaps and recap reads', () => {
expect(pushed).toEqual(['m2'])
})
- it('has at most two recap reads in flight and refuses a third', async () => {
- const release: Array<() => void> = []
- const t = setup({ t1: { lastChangedAt: 1, state: swarm({ conversations: [conv('lead-web', 'a1', { projectId: 'web', lastMessageSequence: 4 }), conv('lead-mobile', 'a2', { projectId: 'mobile', lastMessageSequence: 4 })],
- agents: [agent('a1'), agent('a2'), agent('a3')] }) } }, {
- messages: () => new Promise(resolve => { release.push(() => resolve({ messages: [msg(4, 'a1'), msg(4, 'a2')], next: null })) }) as never })
- // The fake backend returns the promise's value as data.
- await t.cards.tick()
- const a = t.cards.recap('t1', 'a1'), b = t.cards.recap('t1', 'a2')
- await vi.waitFor(() => expect(release).toHaveLength(2))
- await expect(t.cards.recap('t1', 'a1')).rejects.toThrow()
- release.forEach(r => r())
- await Promise.all([a, b])
- })
-
it('forgets the recap of a Lead whose tab is gone', async () => {
const t = setup({ t1: { lastChangedAt: 1, state: withSequence(2) }, t2: { lastChangedAt: 1, state: swarm() } }, { messages: () => ({ messages: [msg(2, 'a1')], next: null }) })
await t.cards.tick()
@@ -737,18 +767,20 @@ describe('SwarmCards open recaps and recap reads', () => {
})
})
-/** `web` with its three chats at the given sequences, each conversation's page served from `pages` (newest first or not: the code orders). */
+/** `web` with its three chats at the given sequences, each conversation's page served from `pages` (newest first or not: the code orders);
+ * a thread's page from `${conversation}#${root}`. */
/** With `withBuddy`, the Swarm has Buddies on and the reader's Buddy (`y1`, "diego's Buddy" on Codex) is in their `web` chat. */
-function chatSwarm(pages: Record<string, unknown[] | (() => unknown[])>, withBuddy = false) {
+function chatSwarm(pages: Record<string, unknown[] | (() => unknown[])>, withBuddy = false, delayMs = 0) {
const state = (lead = 1, pmSeq = 1, groupSeq = 1) => chats({
...(withBuddy ? { buddies: true, agents: [...chats().agents as object[], buddy()] } : {}),
conversations: [
conv('lead-web', 'a1', { projectId: 'web', lastMessageSequence: lead }), conv('lead-mobile', 'a2', { projectId: 'mobile' }),
pm({ lastMessageSequence: pmSeq, ...(withBuddy ? { agentIds: ['y1'] } : {}) }), group({ lastMessageSequence: groupSeq })] })
const t = setup({ t1: { lastChangedAt: 1, state: state() } }, { messages: path => {
- const page = pages[/conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? ''] ?? []
+ const id = /conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? '', thread = /[?&]thread=([^&]+)/.exec(path)?.[1]
+ const page = pages[thread ? `${id}#${thread}` : id] ?? []
return { messages: typeof page === 'function' ? page() : page, next: null }
- } })
+ }, delayMs })
const move = async (lead: number, pmSeq = 1, groupSeq = 1) => { t.tabs.t1.lastChangedAt++; t.tabs.t1.state = state(lead, pmSeq, groupSeq); await t.cards.tick() }
const webLead = (cards = t.seen.at(-1)) => cards?.[0].leads.find(l => l.id === 'a1')
const reads = (conversation: string) => t.calls.filter(c => c.includes(`/conversations/${conversation}/messages`)).length
@@ -1082,6 +1114,159 @@ describe('leadsOf Buddies', () => {
})
})
+// Diego's dial, 2026-11-03: a switch to the PM or Buddy side showed the resting pet 5-6 s before the recap, the dial's own
+// read refused while the notices' and the pushes' two reads ran.
+describe('SwarmCards dial recap', () => {
+ const buddySays = [said(1, 'a1', { text: 'from the PM' }), said(2, 'y1', { text: 'from the Buddy' })]
+
+ it('answers the dial\'s recap while two background reads run', async () => {
+ const t = chatSwarm({ 'lead-web': [said(2, 'a1', { text: 'lead says' })], 'pm-web': buddySays, 'lead-mobile': [said(1, 'a2', { text: 'mobile says' })] }, true, 50)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.open('s1', 't1', 'a1', 'buddy')
+ // The Lead spoke: the poll reads its conversation for the notice.
+ const polled = t.move(2)
+ await vi.waitFor(() => expect(t.reads('lead-web')).toBe(1), { interval: 1 })
+ // The dial swiped: the push of its new face reads the Buddy chat.
+ t.cards.side('t1', 'buddy')
+ await vi.waitFor(() => expect(t.reads('pm-web')).toBe(1), { interval: 1 })
+ await expect(t.cards.recap('t1', 'a2', 'buddy')).resolves.toMatchObject({ text: 'mobile says', none: false, chatId: 'lead-mobile' })
+ await polled
+ t.cards.want(false)
+ })
+
+ it('answers a side switch from the held recap with no backend request', async () => {
+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'lead says' })], 'pm-web': buddySays }, true)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).toMatchObject({ text: 'lead says', chatId: 'lead-web' })
+ t.cards.side('t1', 'buddy')
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).toMatchObject({ text: 'from the Buddy', chatId: 'pm-web' })
+ // A poll between the swipes keeps the recap of the side not shown.
+ await t.cards.tick()
+ t.calls.length = 0
+ t.cards.side('t1', 'pm')
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).toMatchObject({ text: 'lead says', chatId: 'lead-web' })
+ expect(t.calls.filter(c => c.includes('/messages'))).toEqual([])
+ t.cards.want(false)
+ })
+
+ it('answers a held recap at once when its chat moved on, then pushes the newer one', async () => {
+ let latest = 1
+ const t = chatSwarm({ 'g-web': () => [said(latest, 'b1', { text: `group ${latest}` })] })
+ const pushed: string[] = []
+ t.cards.onRecap = r => pushed.push(r.text)
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'g-web' })
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'group 1', chatId: 'g-web' })
+ latest = 2
+ await t.move(1, 1, 2)
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'group 1', chatId: 'g-web' })
+ await vi.waitFor(() => expect(pushed).toEqual(['group 2']))
+ // The newer one is held: asked again, it is answered with no read.
+ const reads = t.reads('g-web')
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'group 2' })
+ expect(t.reads('g-web')).toBe(reads)
+ t.cards.want(false)
+ })
+
+ it('answers from the Lead\'s notice for that chat before any recap was read, without waiting on a read', async () => {
+ let offline = false
+ const t = chatSwarm({ 'lead-web': () => { if (offline) throw new Error('offline'); return [said(2, 'a1', { text: 'lead says' })] } })
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ await t.move(2)
+ expect(t.webLead()?.notice).toMatchObject({ text: 'lead says', chatId: 'lead-web' })
+ // The read after the answer fails: the answer did not wait on it.
+ offline = true
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'lead says', chatId: 'lead-web', none: false })
+ t.cards.want(false)
+ })
+
+ it('reads the dial\'s recaps one at a time, every one answered', async () => {
+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'web says' })], 'lead-mobile': [said(1, 'a2', { text: 'mobile says' })] }, false, 50)
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ const answers = await Promise.all([t.cards.recap('t1', 'a1', true), t.cards.recap('t1', 'a2', true), t.cards.recap('t1', 'a1')])
+ expect(answers.map(a => a.text)).toEqual(['web says', 'mobile says', 'web says'])
+ expect(t.mostReading()).toBe(1)
+ t.cards.want(false)
+ })
+})
+
+describe('SwarmCards chat recap and threads', () => {
+ it('recaps the chat with the agent\'s latest top-level message, not a thread reply', async () => {
+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'top', thread: 'x1' }), said(2, 'a1', { text: 'in the thread', thread: 'x1' })] })
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'top', chatId: 'lead-web' })
+ expect(await t.cards.recap('t1', 'a1')).toMatchObject({ text: 'top' })
+ t.cards.want(false)
+ })
+
+ const threadPages = {
+ 'lead-web': [said(1, 'a1', { text: 'top', thread: 'x1' }), said(2, 'a1', { text: 'other top' }), said(5, 'b1', { text: 'worker reply', thread: 'x1' })],
+ 'lead-web#x1': [said(1, 'a1', { text: 'top', thread: 'x1' }), said(5, 'b1', { text: 'worker reply', thread: 'x1' }),
+ said(6, 'me', { author: { kind: 'person', id: 'me' }, text: 'mine', thread: 'x1' })],
+ }
+ const onThread = { tabId: 't1', conversationId: 'lead-web', threadRoot: 'x1' }
+
+ it('shows a thread on the face by its newest agent reply, and closing it pushes the chat recap', async () => {
+ const t = chatSwarm(threadPages)
+ const pushed: string[] = []
+ t.cards.onRecap = r => pushed.push(r.text)
+ t.cards.want(true, [], onThread)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.open('s1', 't1', 'a1', true)
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'worker reply', chatId: 'lead-web', none: false })
+ expect(t.calls.filter(c => c.includes('/messages'))).toEqual(['GET /api/super-tabs/t1/conversations/lead-web/messages?thread=x1'])
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web' })
+ await vi.waitFor(() => expect(pushed).toEqual(['other top']))
+ // Opened again, the thread's recap is its own, not the chat's.
+ t.cards.want(true, [], onThread)
+ await vi.waitFor(() => expect(pushed).toEqual(['other top', 'worker reply']))
+ t.cards.want(false)
+ })
+
+ it('says words spoken with a thread on the face in that thread, and in the chat once it closed', async () => {
+ const t = chatSwarm(threadPages)
+ t.cards.want(true, [], onThread)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ expect(await t.cards.say('h-a1', 'in the thread', true)).toEqual({ said: true })
+ expect(await t.cards.say('h-a1', 'pinned to the chat', true, 'lead-web')).toEqual({ said: true })
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'lead-web' })
+ expect(await t.cards.say('h-a1', 'in the chat', true, 'lead-web')).toEqual({ said: true })
+ const posts = t.call.mock.calls.filter(c => c[0] === 'POST').map(c => (c[2] as { command: { conversationId: string; text: string; replyTo: string | null } }).command)
+ expect(posts.map(p => [p.conversationId, p.text, p.replyTo])).toEqual([['lead-web', 'in the thread', 'x1'], ['lead-web', 'pinned to the chat', 'x1'], ['lead-web', 'in the chat', null]])
+ t.cards.want(false)
+ })
+
+ it('leaves out a thread whose conversation is not the one on the face', async () => {
+ const t = chatSwarm({ ...threadPages, 'pm-web': [said(2, 'y1', { text: 'from the Buddy' })] }, true)
+ t.cards.want(true, [], onThread)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.side('t1', 'buddy')
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).toMatchObject({ text: 'from the Buddy', chatId: 'pm-web' })
+ expect(await t.cards.say('h-a1', 'to the Buddy', 'buddy')).toEqual({ said: true })
+ const [post] = t.call.mock.calls.filter(c => c[0] === 'POST').map(c => (c[2] as { command: { conversationId: string; replyTo: string | null } }).command)
+ expect([post.conversationId, post.replyTo]).toEqual(['pm-web', null])
+ // The Pro's Lead recap never follows the face.
+ expect(await t.cards.recap('t1', 'a1')).toMatchObject({ text: 'other top' })
+ expect(t.calls.filter(c => c.includes('?thread='))).toEqual([])
+ t.cards.want(false)
+ })
+
+ it('never answers the chat recap from a notice that is a thread reply', async () => {
+ const t = chatSwarm({ 'lead-web': [said(1, 'a1', { text: 'top', thread: 'x1' }), said(2, 'a1', { text: 'in the thread', thread: 'x1' })] })
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ await t.move(2)
+ expect(t.webLead()?.notice).toMatchObject({ text: 'in the thread' })
+ expect(await t.cards.recap('t1', 'a1', true)).toMatchObject({ text: 'top', chatId: 'lead-web' })
+ t.cards.want(false)
+ })
+})
+
describe('SwarmCards Buddy side', () => {
const buddySays = [said(1, 'a1', { text: 'from the PM' }), said(2, 'y1', { text: 'from the Buddy' }), said(3, 'me', { author: { kind: 'person', id: 'me' }, text: 'mine' })]
diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.ts
index ef3cef77c..b2386accb 100644
--- a/cli/src/superTabs/cards.ts
+++ b/cli/src/superTabs/cards.ts
@@ -20,7 +20,7 @@
import { randomUUID } from 'node:crypto'
import type { BackendNotice, CoreApi } from '../core/api.js'
import { backend, SuperTabHostError } from './host.js'
-import { identifier, object } from './wire.js'
+import { identifier, object, within } from './wire.js'
import { SwarmReads, type SwarmRead } from './swarmReads.js'
import { buddyAvatar } from './buddyAvatar.js'
@@ -30,6 +30,8 @@ import type { CardChat, CardFocus, CardSide, ChatKind, LeadNotice, LeadRecap, Le
export type { CardChat, CardFocus, CardSide, LeadNotice, LeadRecap, LeadState, SaidOnCard, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../core/api.js'
const MAX_CARDS = 16, MAX_LEADS = 12, NAME_BYTES = 48, RECAP_BYTES = 1500, MAX_LIST_PAGES = 10, MAX_RECAPS_IN_FLIGHT = 2
+/** The longest a dial's recap read waits on the one before it. */
+const ASK_WAIT_MS = 10_000
/** The Pro keeps an id in 48 bytes with its NUL: 47 characters at most reach it. */
const ID_BYTES = 47
export const cardId = (v: unknown): v is string => identifier(v) && v.length <= ID_BYTES
@@ -122,8 +124,10 @@ function buddyOf(agents: Json[], chat: Json, me: string | undefined, local: (a:
}
/**
- * One Lead per project of the Swarm, most urgent first with ties in project order; the 12 most urgent are kept, and each
- * carries its project's index as `order` (gaps where a project has no Lead or was cut). `live` says whether this machine's core has a
+ * One Lead per project of the Swarm, most urgent first with ties in the app's project order; the 12 most urgent are kept, and
+ * each carries its project's place in that order as `order` (gaps where a project has no Lead or was cut), which a dial swipes
+ * by. The app's order is by name, case-insensitively A to Z (desktop super_tabs/project_sidebar.dart: the sidebar and
+ * superTabSidebarOrder), ties in server order: the two must match. `live` says whether this machine's core has a
* harness and whether it is in a turn (null: not here); `me` is the signed-in person's id, so a Lead on someone else's
* machine names that owner (people[] has an email, which is the name a Swarm shows a person by).
*/
@@ -138,7 +142,12 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: string
: conversations.find(c => (Array.isArray(c.agentIds) && c.agentIds.includes(a.id)) || c.leadId === a.id)?.projectId ?? 'lead'
const turnHere = (a: Json) => a.machineId === machineId && typeof a.harnessId === 'string' && a.harnessId !== '' ? live(a.harnessId) : null
const leads: SwarmLead[] = []
- for (const [order, project] of projects.entries()) {
+ // Compared by code unit, as Dart's String.compareTo; Array.sort is stable, so a tie keeps server order.
+ const named = (p: Json) => String(p.name ?? '').toLowerCase()
+ const places = new Map(projects.map((p, i) => ({ p, i })).sort((a, b) => named(a.p) < named(b.p) ? -1 : named(a.p) > named(b.p) ? 1 : a.i - b.i)
+ .map(({ p }, place) => [p, place]))
+ for (const project of projects) {
+ const order = places.get(project)!
const lead = conversations.find(c => c.id === project.leadConversationId)
const agent = lead && agents.find(a => a.id === lead.leadId)
if (!agent) continue
@@ -176,8 +185,8 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: string
...(sideChat ? { sideChat } : {}), ...(buddies ? { buddies: true as const } : {}), ...(buddy ? { buddy } : {}),
})
}
- // Array.sort is stable: equal urgency keeps the project order.
- const ordered = leads.map((l, i) => ({ l, i })).sort((a, b) => ORDER[a.l.state] - ORDER[b.l.state] || a.i - b.i).map(x => x.l)
+ // Equal urgency keeps the app's project order.
+ const ordered = [...leads].sort((a, b) => ORDER[a.state] - ORDER[b.state] || a.order - b.order)
return { count: ordered.length, leads: ordered.slice(0, MAX_LEADS) }
}
@@ -195,14 +204,21 @@ function faceChat(face: Face, leadId: string, agents: Json[], me: string | undef
return { kind, id: conversation.id as string, name, working, ...(secs.length ? { since: Math.max(...secs) } : {}) }
}
+/** Where a message is looked for: anywhere in the page, in the chat's main stream (a top-level message, one from before
+ * threads, or a thread reply also sent to the chat: backend catchUp.ts `inMainStream`), or in one thread, its root among it. */
+export type MessagePlace = 'any' | 'chat' | { thread: string }
+const isIn = (m: Json, place: MessagePlace): boolean => place === 'any' ? true
+ : place === 'chat' ? typeof m.thread !== 'string' || m.thread === m.id || m.alsoInChat === true
+ : m.thread === place.thread
+
/** The newest row one of the chat's agents wrote: a person-visible message, not a system row (`source`), the person's or
- * another agent's. `at` in seconds; `id` the message's, or '' when it has none. */
-export function lastAgentMessage(messages: Json[], agentIds: ReadonlySet<string>): { text: string; at: number; id: string; sequence: number } | null {
+ * another agent's, in `place`. `at` in seconds; `id` the message's, or '' when it has none. */
+export function lastAgentMessage(messages: Json[], agentIds: ReadonlySet<string>, place: MessagePlace = 'any'): { text: string; at: number; id: string; sequence: number } | null {
let best: { text: string; at: number; id: string; sequence: number } | null = null
for (const item of messages) {
const m = object(item)
const author = object(m.author).id
- if (m.source != null || typeof author !== 'string' || !agentIds.has(author) || typeof m.text !== 'string') continue
+ if (m.source != null || typeof author !== 'string' || !agentIds.has(author) || typeof m.text !== 'string' || !isIn(m, place)) continue
const sequence = typeof m.sequence === 'number' ? m.sequence : -1
if (best && sequence <= best.sequence) continue
const stamp = typeof m.createdAt === 'number' ? m.createdAt : Date.parse(String(m.createdAt))
@@ -212,16 +228,22 @@ export function lastAgentMessage(messages: Json[], agentIds: ReadonlySet<string>
}
interface TabCache { lastChangedAt: number | null; state: Json }
-interface Cached { sequence: number; recap: LeadRecap }
+/** A recap read, and the thread it is of when one was on the face. */
+interface Cached { sequence: number; recap: LeadRecap; thread?: string }
+/** The window's focus, with the thread whose pane is on screen beside its conversation (Desktop's app_swarms `threadRoot`). */
+type Focus = CardFocus & { threadRoot?: string }
/** A Lead some Harness Pro has the recap of open, and the sessions (one per Pro) that have it open. With `chat` (a round dial
* that speaks `swarmChat`, or 'buddy' for one that speaks swarmBuddy), the recap is that dial's face chat's, and `chatId`
* the chat it was last told of. */
-interface Opened { tabId: string; leadId: string; chat: CardChat; chatId: string | null; sequence: number | null; sessions: Set<string> }
-/** Where a recap is read, or talk is posted: a conversation, how far it has gone, and whose messages are its recap. */
-interface Target { id: string; sequence: number; voices: Set<string>; chatId?: string }
+interface Opened { tabId: string; leadId: string; chat: CardChat; chatId: string | null; thread: string | null; sequence: number | null; sessions: Set<string> }
+/** Where a recap is read, or talk is posted: a conversation, how far it has gone, and whose messages are its recap; `buddy`
+ * when it is a swarmBuddy dial's Buddy face, whose notice is the Buddy's; `thread` the root of the thread open on the face. */
+interface Target { id: string; sequence: number; voices: Set<string>; chatId?: string; buddy?: true; thread?: string }
const recapKey = (tabId: string, leadId: string, chatId?: string) => chatId === undefined ? `${tabId}:${leadId}` : `${tabId}:${leadId}:${chatId}`
-/** A recap's cache key: an older dial's and a swarmBuddy dial's recap of one Buddy chat hear different voices. */
-const cachedKey = (tabId: string, leadId: string, chatId: string | undefined, chat: CardChat) => `${recapKey(tabId, leadId, chatId)}${chat === 'buddy' ? ':buddy' : ''}`
+/** A recap's cache key: an older dial's and a swarmBuddy dial's recap of one Buddy chat hear different voices, and a thread on
+ * the face is apart from its chat. */
+const cachedKey = (tabId: string, leadId: string, target: Pick<Target, 'chatId' | 'thread'>, chat: CardChat) =>
+ `${recapKey(tabId, leadId, target.chatId)}${target.thread === undefined ? '' : `#${target.thread}`}${chat === 'buddy' ? ':buddy' : ''}`
const isSide = (v: unknown): v is CardSide => v === 'pm' || v === 'buddy'
/** Spec 2026-11-02-poll-cost Part 4.3: the list was read every 5 s whatever changed (prod 2026-11-02: about 200 list reads a
* minute). While the server says it pushes this account's Swarm changes (`swarm_changed` naming none, repeated every 4
@@ -259,10 +281,13 @@ export class SwarmCards {
private me: string | undefined
private include: string[] = []
/** The conversation the window has open in a Swarm tab: that project's face follows it. */
- private focus: CardFocus | null = null
+ private focus: Focus | null = null
private opened = new Map<string, Opened>()
private openBy = new Map<string, string>()
+ /** Background reads of recaps and notices in flight, at most MAX_RECAPS_IN_FLIGHT. */
private recapsRunning = 0
+ /** The dial's own recap reads, one at a time and apart from the background's: a dial is never refused its recap. */
+ private asking: Promise<unknown> | null = null
/** One push of open recaps at a time: a focus change and a poll that both see a new face push it once. */
private pushing: Promise<void> = Promise.resolve()
/** The alert baseline: per watched conversation (`${tab}:${conversation}`), the last sequence whose messages were seen. */
@@ -271,6 +296,8 @@ export class SwarmCards {
private notices = new Map<string, LeadNotice>()
/** Each Lead's newest quiet notice from the reader's Buddy (`${tab}:${lead}`): apart, so it never hides the Lead's. */
private buddyNotices = new Map<string, LeadNotice>()
+ /** The notices that are messages of their chat's main stream, not thread replies: only these answer a chat's recap. */
+ private inChat = new WeakSet<LeadNotice>()
/** The side a swarmBuddy dial swiped to, per Swarm; cleared by the window's next focus change (the newest wins). */
private sides = new Map<string, CardSide>()
/** Watched conversations whose last read failed, so a run of failures is logged once. */
@@ -293,7 +320,7 @@ export class SwarmCards {
/** Poll while a capable Pro is attached; none otherwise (no request at all). `include`: the Swarms the desktop has tabs for,
* read first. `focus`: the conversation the window has open in a Swarm tab; a change rebuilds the cards at once from the
* last reads, with no request. */
- want(on: boolean, include: string[] = [], focus: CardFocus | null = null): void {
+ want(on: boolean, include: string[] = [], focus: Focus | null = null): void {
if (!on) {
if (this.timer) clearInterval(this.timer)
this.timer = undefined
@@ -309,8 +336,10 @@ export class SwarmCards {
const moved = wanted.join(',') !== this.include.join(',')
this.include = wanted
const next = focus && cardId(focus.tabId) && cardId(focus.conversationId)
- ? { tabId: focus.tabId, conversationId: focus.conversationId, ...(focus.fromDevice === true ? { fromDevice: true as const } : {}) } : null
- const refocused = `${next?.tabId}/${next?.conversationId}` !== `${this.focus?.tabId}/${this.focus?.conversationId}`
+ ? { tabId: focus.tabId, conversationId: focus.conversationId, ...(cardId(focus.threadRoot) ? { threadRoot: focus.threadRoot } : {}),
+ ...(focus.fromDevice === true ? { fromDevice: true as const } : {}) } : null
+ // A thread opened or closed beside the conversation moves the face too.
+ const refocused = `${next?.tabId}/${next?.conversationId}/${next?.threadRoot}` !== `${this.focus?.tabId}/${this.focus?.conversationId}/${this.focus?.threadRoot}`
this.focus = next
// The desktop's own move clears the dial's side; the move a dial's pick caused is the dial's, and keeps it.
if (refocused && !next?.fromDevice) this.sides.clear()
@@ -364,8 +393,8 @@ export class SwarmCards {
if (!entry) {
// From what the Pro was shown when there is a recap read, else from the first read of the tab: the next change is pushed.
const target = this.target(tabId, leadId, chat)
- entry = { tabId, leadId, chat, chatId: target?.chatId ?? null,
- sequence: target ? this.recaps.get(cachedKey(tabId, leadId, target.chatId, chat))?.sequence ?? target.sequence : null, sessions: new Set() }
+ entry = { tabId, leadId, chat, chatId: target?.chatId ?? null, thread: target?.thread ?? null,
+ sequence: target ? this.recaps.get(cachedKey(tabId, leadId, target, chat))?.sequence ?? target.sequence : null, sessions: new Set() }
this.opened.set(key, entry)
}
entry.sessions.add(session)
@@ -519,8 +548,8 @@ export class SwarmCards {
try {
const page = object(await backend(this.core, 'GET', `/api/super-tabs/${tabId}/conversations/${swarmChat.id}/messages`))
const after = list(page.messages).filter(m => typeof m.sequence === 'number' && m.sequence > baseline)
- const said = lastAgentMessage(after, new Set(buddiesIn(agents, swarmChat, this.me).map(a => a.id as string)))
- for (const { leadId } of projects) raise(this.buddyNotices, recapKey(tabId, leadId), 'buddy', swarmChat.id as string, said)
+ const voices = new Set(buddiesIn(agents, swarmChat, this.me).map(a => a.id as string))
+ for (const { leadId } of projects) this.raise(this.buddyNotices, recapKey(tabId, leadId), 'buddy', swarmChat.id as string, after, voices)
this.seen.set(key, sequence)
this.failed.delete(key)
} catch (error) {
@@ -546,10 +575,10 @@ export class SwarmCards {
try {
const page = object(await backend(this.core, 'GET', `/api/super-tabs/${tabId}/conversations/${conversation.id}/messages`))
const after = list(page.messages).filter(m => typeof m.sequence === 'number' && m.sequence > baseline)
- raise(this.notices, recapKey(tabId, leadId), chat, conversation.id, lastAgentMessage(after, new Set([leadId])))
+ this.raise(this.notices, recapKey(tabId, leadId), chat, conversation.id, after, new Set([leadId]))
if (chat === 'pm' && buddies) {
const voices = new Set(buddiesIn(agents, conversation, this.me).map(a => a.id as string))
- raise(this.buddyNotices, recapKey(tabId, leadId), 'buddy', conversation.id, lastAgentMessage(after, voices))
+ this.raise(this.buddyNotices, recapKey(tabId, leadId), 'buddy', conversation.id, after, voices)
}
this.seen.set(key, sequence)
this.failed.delete(key)
@@ -570,6 +599,18 @@ export class SwarmCards {
}
}
+ /** The newest message `voices` said in `messages` becomes the held notice at `key`, unless one held is newer; marked as the
+ * chat's own when it is no thread reply. */
+ private raise(held: Map<string, LeadNotice>, key: string, chat: LeadNotice['chat'], chatId: string, messages: Json[], voices: ReadonlySet<string>): void {
+ const said = lastAgentMessage(messages, voices)
+ if (!said || !cardId(said.id)) return
+ const notice: LeadNotice = { chat, chatId, id: said.id, text: cut(said.text, RECAP_BYTES), at: said.at }
+ const before = held.get(key)
+ if (before && before.at > notice.at) return
+ held.set(key, notice)
+ if (lastAgentMessage(messages, voices, 'chat')?.id === said.id) this.inChat.add(notice)
+ }
+
private forgetNotices(): void { this.notices.clear(); this.buddyNotices.clear(); this.failed.clear() }
/** Which of the Leads that run here are in a turn, and since when (the core's windows' own measure of "working"). */
@@ -603,50 +644,110 @@ export class SwarmCards {
const found = leadProjects(state).find(p => p.leadId === leadId)
if (!found || !identifier(found.lead.id)) return null
if (!chat) return { id: found.lead.id, sequence: sequenceOf(found.lead), voices: new Set([leadId]) }
- const focus = this.focus?.tabId === tabId ? this.focus.conversationId : undefined
+ const open = this.focus?.tabId === tabId ? this.focus : null, focus = open?.conversationId
const conversations = list(state.conversations), projectId = projectKey(found.project), buddies = state.buddies === true
const face = chat === 'buddy' && buddies ? sideFaceOf(conversations, projectId, found.lead, focus, this.me, this.sideOf(tabId, state))
: faceOf(conversations, projectId, found.lead, focus, this.me, buddies)
if (!face) return null
const id = face.conversation.id as string
- return { id, sequence: sequenceOf(face.conversation), voices: voicesOf(face, leadId, list(state.agents), this.me), chatId: id }
+ // The thread open beside the window's conversation, while that conversation is the one on the face: any agent's reply
+ // there is its recap (a worker answering in the Lead's thread, the Buddy's thread session).
+ const thread = open?.threadRoot !== undefined && open.conversationId === id ? open.threadRoot : undefined
+ const voices = thread === undefined ? voicesOf(face, leadId, list(state.agents), this.me)
+ : new Set(list(state.agents).map(a => a.id).filter((a): a is string => typeof a === 'string'))
+ return { id, sequence: sequenceOf(face.conversation), voices, chatId: id,
+ ...(face.kind === 'buddy' ? { buddy: true as const } : {}), ...(thread === undefined ? {} : { thread }) }
}
/** What the Lead last said: the newest page of its conversation, then one page back; `none` when neither holds a row of its own.
- * With `chat`, what the chat on its face last heard from its agents, naming that chat. */
+ * With `chat`, what the chat on its face last heard from its agents, naming that chat. The dial's own read: never refused,
+ * and answered at once from the recap held for that chat or the notice from it, read again after when the chat moved on. */
async recap(tabId: string, leadId: string, chat: CardChat = false): Promise<LeadRecap> {
if (!cardId(tabId) || !cardId(leadId)) return { tabId, leadId, text: '', at: 0, none: true }
- let found = this.target(tabId, leadId, chat)
- if (!found) {
+ const quick = this.held(tabId, leadId, chat)
+ if (quick) {
+ if (quick.stale) this.refresh(tabId, leadId, chat, quick.recap)
+ return quick.recap
+ }
+ return this.asked(() => this.read(tabId, leadId, chat, 'device'))
+ }
+
+ /** The dial's reads, one after another; one asked while none runs starts at once, and one never waits on a read that
+ * hangs for longer than ASK_WAIT_MS. */
+ private asked<T>(read: () => Promise<T>): Promise<T> {
+ const run = this.asking ? within(this.asking, ASK_WAIT_MS).then(read) : read()
+ const done: Promise<unknown> = run.catch(() => {}).then(() => { if (this.asking === done) this.asking = null })
+ this.asking = done
+ return run
+ }
+
+ /** What can be answered for the chat on the face with no read: the recap held for it, or the newer notice from it, with the
+ * sequence it was read at (-1 for a notice); `stale` when the chat has moved on since, so it is read again. */
+ private held(tabId: string, leadId: string, chat: CardChat): { recap: LeadRecap; sequence: number; stale: boolean } | null {
+ const found = this.target(tabId, leadId, chat)
+ if (!found) return null
+ const kept = this.recaps.get(cachedKey(tabId, leadId, found, chat))
+ // A notice is of the chat, never of a thread on the face.
+ const notice = found.thread === undefined ? (found.buddy ? this.buddyNotices : this.notices).get(recapKey(tabId, leadId)) : undefined
+ const heard = notice && notice.chatId === found.id && this.inChat.has(notice) ? notice : undefined
+ if (kept && (!heard || heard.at <= kept.recap.at)) return { recap: kept.recap, sequence: kept.sequence, stale: kept.sequence !== found.sequence }
+ if (!heard) return null
+ return { recap: { tabId, leadId, text: heard.text, at: heard.at, none: false, ...namedFor(found, chat) }, sequence: -1, stale: true }
+ }
+
+ /** The chat moved on since what the dial was answered: read again, on the dial's lane, and pushed when it says otherwise. */
+ private refresh(tabId: string, leadId: string, chat: CardChat, shown: LeadRecap): void {
+ void this.asked(() => this.read(tabId, leadId, chat, 'device')).then(recap => {
+ // Its open sessions are told this one: their next push is for the chat's next move.
+ const target = this.target(tabId, leadId, chat), kept = target && this.recaps.get(cachedKey(tabId, leadId, target, chat))
+ for (const open of this.opened.values()) {
+ if (kept && open.tabId === tabId && open.leadId === leadId && open.chat === chat && open.chatId === (target.chatId ?? null)
+ && open.thread === (target.thread ?? null)) open.sequence = kept.sequence
+ }
+ if (recap.text !== shown.text || recap.at !== shown.at || recap.none !== shown.none || recap.chatId !== shown.chatId) this.onRecap?.(recap)
+ }, () => { /* read again at the next push or ask */ })
+ }
+
+ /** The backend read of a recap. `background` (a push) takes one of the two background slots or is refused; `device` (the
+ * dial asked) runs on the dial's own lane. */
+ private async read(tabId: string, leadId: string, chat: CardChat, lane: 'device' | 'background'): Promise<LeadRecap> {
+ // At most two background reads run at once, so a loop of pushes cannot flood the backend; the dial's run one by one.
+ const slot = async <T>(run: () => Promise<T>): Promise<T> => {
+ if (lane === 'device') return run()
if (this.recapsRunning >= MAX_RECAPS_IN_FLIGHT) throw new Error('too many recap reads at once')
this.recapsRunning++
- try { this.tabs.set(tabId, tabOf(await this.reads.read(tabId))) } finally { this.recapsRunning-- }
+ try { return await run() } finally { this.recapsRunning-- }
+ }
+ let found = this.target(tabId, leadId, chat)
+ if (!found) {
+ await slot(async () => { this.tabs.set(tabId, tabOf(await this.reads.read(tabId))) })
found = this.target(tabId, leadId, chat)
}
if (!found) return { tabId, leadId, text: '', at: 0, none: true }
- const named = found.chatId === undefined ? {} : { chatId: found.chatId, ...(chat === 'buddy' ? { buddy: true as const } : {}) }
- const key = cachedKey(tabId, leadId, found.chatId, chat), held = this.recaps.get(key)
- if (held && held.sequence === found.sequence) return held.recap
- // At most two backend reads of recaps run at once: a Pro that asks in a loop cannot flood the backend.
- if (this.recapsRunning >= MAX_RECAPS_IN_FLIGHT) throw new Error('too many recap reads at once')
- this.recapsRunning++
+ const target = found, named = namedFor(target, chat)
+ const key = cachedKey(tabId, leadId, target, chat), held = this.recaps.get(key)
+ if (held && held.sequence === target.sequence) return held.recap
const reader = this.me
- try {
- const path = `/api/super-tabs/${tabId}/conversations/${found.id}/messages`
- const newest = object(await backend(this.core, 'GET', path))
- let said = lastAgentMessage(list(newest.messages), found.voices)
+ // A thread on the face is read by its root, as Desktop reads it (super_tabs/controller.dart loadThread).
+ const place: MessagePlace = target.thread === undefined ? 'chat' : { thread: target.thread }
+ const thread = target.thread === undefined ? '' : `thread=${encodeURIComponent(target.thread)}`
+ return slot(async () => {
+ const path = `/api/super-tabs/${tabId}/conversations/${target.id}/messages`
+ const newest = object(await backend(this.core, 'GET', thread ? `${path}?${thread}` : path))
+ let said = lastAgentMessage(list(newest.messages), target.voices, place)
// The page before, from the page's own (sequence, id) cursor: a page edge inside equal sequences skips nothing (design 4.6).
const before = object(newest.next)
if (!said && typeof before.sequence === 'number' && identifier(before.id)) {
- said = lastAgentMessage(list(object(await backend(this.core, 'GET', `${path}?before=${before.sequence}&beforeId=${before.id}`)).messages), found.voices)
+ said = lastAgentMessage(list(object(await backend(this.core, 'GET', `${path}?${thread ? `${thread}&` : ''}before=${before.sequence}&beforeId=${before.id}`)).messages), target.voices, place)
}
// Access to the Swarm ended, another person signed in, or the face moved on while the read was out: the answer is not
// this reader's to have now (a Buddy chat is its owner's alone), so it is neither given nor kept.
- if (this.me !== reader || this.target(tabId, leadId, chat)?.id !== found.id) return { tabId, leadId, text: '', at: 0, none: true }
+ const now = this.target(tabId, leadId, chat)
+ if (this.me !== reader || now?.id !== target.id || now.thread !== target.thread) return { tabId, leadId, text: '', at: 0, none: true }
const recap: LeadRecap = said ? { tabId, leadId, text: cut(said.text, RECAP_BYTES), at: said.at, none: false, ...named } : { tabId, leadId, text: '', at: 0, none: true, ...named }
- this.recaps.set(key, { sequence: found.sequence, recap })
+ this.recaps.set(key, { sequence: target.sequence, recap, ...(target.thread === undefined ? {} : { thread: target.thread }) })
return recap
- } finally { this.recapsRunning-- }
+ })
}
/** Words spoken on a Pro to a Lead that runs here (its harness): posted as the person in that Lead's conversation, as typed in
@@ -667,9 +768,11 @@ export class SwarmCards {
const to = chatId === undefined || found.id === chatId ? found.id
: reviewed && this.chatOfLead(state, agent!.id as string, chatId) ? chatId : null
if (!to) return { said: false, refused: { code: 'CHAT_MOVED', message: 'That chat is no longer on the dial. Say it again.' } }
+ // A thread on the face as the words are sent, in that chat, is where they go: a reply to its root.
+ const replyTo = to === found.id ? found.thread ?? null : null
try {
await backend(this.core, 'POST', `/api/super-tabs/${tabId}/commands`, { operationId: `pro-voice-${randomUUID()}`,
- command: { type: 'message.send', conversationId: to, text, replyTo: null, recipientIds: [] } })
+ command: { type: 'message.send', conversationId: to, text, replyTo, recipientIds: [] } })
} catch (error) {
if (error instanceof SuperTabHostError && error.status >= 400 && error.status < 500) return { said: false, refused: { code: error.code, message: error.message } }
throw error
@@ -690,12 +793,15 @@ export class SwarmCards {
: inProject(c, projectKey(found.project)) && (!isBuddyChat(c) || isReadersBuddyChat(c, this.me)))
}
- /** Remembered recaps are kept only for Leads that are still in a tab, and a chat's only while it is on the face. */
+ /** Remembered recaps are kept only for Leads that are still in a tab, and a chat's only while it could be on the Lead's
+ * face: a swipe back to the other side, or the window back on a chat, is answered from it at once. */
private prune(): void {
for (const [key, held] of this.recaps) {
const { tabId, leadId, chatId, buddy } = held.recap
- const now = this.target(tabId, leadId, buddy ? 'buddy' : chatId !== undefined)
- if (!now || now.chatId !== chatId) this.recaps.delete(key)
+ const state = this.tabs.get(tabId)?.state
+ if (!state || !leadProjects(state).some(p => p.leadId === leadId) || (chatId !== undefined && !this.chatOfLead(state, leadId, chatId))) this.recaps.delete(key)
+ // A thread's only while it is on the face.
+ else if (held.thread !== undefined && this.target(tabId, leadId, buddy ? 'buddy' : true)?.thread !== held.thread) this.recaps.delete(key)
}
}
@@ -710,25 +816,29 @@ export class SwarmCards {
for (const open of [...this.opened.values()]) {
const target = this.target(open.tabId, open.leadId, open.chat)
if (!target) continue
- if (open.sequence === null) { open.sequence = target.sequence; open.chatId = target.chatId ?? null; continue }
- if (open.sequence === target.sequence && open.chatId === (target.chatId ?? null)) continue
- const recap = await this.recap(open.tabId, open.leadId, open.chat).catch(() => null)
+ const thread = target.thread ?? null
+ if (open.sequence === null) { open.sequence = target.sequence; open.chatId = target.chatId ?? null; open.thread = thread; continue }
+ if (open.sequence === target.sequence && open.chatId === (target.chatId ?? null) && open.thread === thread) continue
+ // Another chat or thread on the face (a swipe, the window's move): what is held for it is pushed at once, and read again after.
+ const moved = open.chatId !== (target.chatId ?? null) || open.thread !== thread
+ const quick = moved ? this.held(open.tabId, open.leadId, open.chat) : null
+ const recap = quick?.recap ?? await this.read(open.tabId, open.leadId, open.chat, 'background').catch(() => null)
if (!recap) continue
- open.sequence = target.sequence
+ open.sequence = quick ? quick.sequence : target.sequence
open.chatId = target.chatId ?? null
+ open.thread = thread
this.onRecap?.(recap)
+ if (quick?.stale) this.refresh(open.tabId, open.leadId, open.chat, recap)
}
}
}
-/** The newest message said becomes the held notice at `key`, unless one held is newer. */
-function raise(held: Map<string, LeadNotice>, key: string, chat: LeadNotice['chat'], chatId: string, said: ReturnType<typeof lastAgentMessage>): void {
- if (!said || !cardId(said.id)) return
- const notice: LeadNotice = { chat, chatId, id: said.id, text: cut(said.text, RECAP_BYTES), at: said.at }
- const before = held.get(key)
- if (!before || before.at <= notice.at) held.set(key, notice)
+/** How a chat's recap names it: by its id, and as a swarmBuddy dial's when asked for one. */
+function namedFor(target: Target, chat: CardChat): { chatId?: string; buddy?: true } {
+ return target.chatId === undefined ? {} : { chatId: target.chatId, ...(chat === 'buddy' ? { buddy: true as const } : {}) }
}
+
/** Each project of a tab whose Lead conversation names its Lead: the project, that conversation and the Lead agent's id. */
function leadProjects(state: Json): Array<{ project: Json; lead: Json; leadId: string }> {
const conversations = list(state.conversations)
diff --git a/cli/src/superTabs/inCore/cards.spec.ts b/cli/src/superTabs/inCore/cards.spec.ts
index fe232a36a..05bdac7e3 100644
--- a/cli/src/superTabs/inCore/cards.spec.ts
+++ b/cli/src/superTabs/inCore/cards.spec.ts
@@ -263,6 +263,11 @@ describe('whether the Swarm cards are wanted, which the core owns', () => {
expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus: { ...focus, fromDevice: true } })
cards.want(true, ['t1'], { ...focus, fromDevice: 1 })
expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus })
+ // The thread the window has open beside it rides along, an id or nothing; its change is a change.
+ cards.want(true, ['t1'], { ...focus, threadRoot: 'm1' })
+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus: { ...focus, threadRoot: 'm1' } })
+ cards.want(true, ['t1'], { ...focus, threadRoot: 'bad id' })
+ expect(request).toHaveBeenLastCalledWith({ action: 'cardsWanted', on: true, include: ['t1'], focus })
// The devices gone take the focus with them.
cards.want(true, ['t1'], focus)
cards.devicesGone()
diff --git a/cli/src/superTabs/inCore/cards.ts b/cli/src/superTabs/inCore/cards.ts
index f5655b9e7..46d210b18 100644
--- a/cli/src/superTabs/inCore/cards.ts
+++ b/cli/src/superTabs/inCore/cards.ts
@@ -132,7 +132,7 @@ export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log =
let last: SwarmCard[] | null = null
/** Whether any capable device wants cards, the Swarms to read first, and the conversation the window has open in a Swarm tab. */
let wanted = false, include: string[] = []
- let focus: { tabId: string; conversationId: string; fromDevice?: true } | null = null
+ let focus: { tabId: string; conversationId: string; threadRoot?: string; fromDevice?: true } | null = null
const route = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
try {
const answer = await request?.(payload)
@@ -147,8 +147,9 @@ export function createSuperTabCards({ swarmCards, swarmCardRecap, request, log =
const next = on && Array.isArray(swarms) ? [...new Set(swarms.filter(id))].slice(0, MAX_CARDS) : []
const asked = object(open)
const nextFocus = on && id(asked.tabId) && id(asked.conversationId)
- ? { tabId: asked.tabId, conversationId: asked.conversationId, ...(asked.fromDevice === true ? { fromDevice: true as const } : {}) } : null
- const key = (f: typeof focus) => `${f?.tabId}/${f?.conversationId}/${f?.fromDevice === true}`
+ ? { tabId: asked.tabId, conversationId: asked.conversationId, ...(id(asked.threadRoot) ? { threadRoot: asked.threadRoot } : {}),
+ ...(asked.fromDevice === true ? { fromDevice: true as const } : {}) } : null
+ const key = (f: typeof focus) => `${f?.tabId}/${f?.conversationId}/${f?.threadRoot}/${f?.fromDevice === true}`
if (on === wanted && next.join(',') === include.join(',') && key(nextFocus) === key(focus)) return
wanted = on
include = next
diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.ts
index 972164dc3..f822fc9f0 100644
--- a/cli/src/superTabs/service.spec.ts
+++ b/cli/src/superTabs/service.spec.ts
@@ -916,6 +916,11 @@ describe('the Swarm cards the devices ask for', () => {
expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], { tabId: 's1', conversationId: 'g1', fromDevice: true })
await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus: { tabId: 's1', conversationId: 'g1', fromDevice: 'yes' } }, owner)
expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], { tabId: 's1', conversationId: 'g1' })
+ // The thread open beside it, an id or nothing.
+ await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus: { tabId: 's1', conversationId: 'g1', threadRoot: 'm1' } }, owner)
+ expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], { tabId: 's1', conversationId: 'g1', threadRoot: 'm1' })
+ await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus: { tabId: 's1', conversationId: 'g1', threadRoot: 'bad id' } }, owner)
+ expect(t.cards.want).toHaveBeenLastCalledWith(true, ['s1'], { tabId: 's1', conversationId: 'g1' })
// A focus that is not two ids is none.
for (const focus of [{ tabId: 'bad id', conversationId: 'g1' }, { tabId: 's1', conversationId: 'x'.repeat(48) }, { tabId: 's1' }, 'g1']) {
await t.ask({ action: 'cardsWanted', on: true, include: ['s1'], focus }, owner)
diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.ts
index e6ef6d412..607e60f3f 100644
--- a/cli/src/superTabs/service.ts
+++ b/cli/src/superTabs/service.ts
@@ -501,7 +501,8 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =
const include = Array.isArray(payload.include) ? payload.include.filter(cardId) : []
const asked = payload.focus && typeof payload.focus === 'object' ? payload.focus as Record<string, unknown> : {}
const focus = cardId(asked.tabId) && cardId(asked.conversationId)
- ? { tabId: asked.tabId, conversationId: asked.conversationId, ...(asked.fromDevice === true ? { fromDevice: true as const } : {}) } : null
+ ? { tabId: asked.tabId, conversationId: asked.conversationId, ...(cardId(asked.threadRoot) ? { threadRoot: asked.threadRoot } : {}),
+ ...(asked.fromDevice === true ? { fromDevice: true as const } : {}) } : null
cards().want(payload.on === true, include, focus)
return { ok: true }
}
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 40d66b929..e62515988 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -6084,6 +6084,12 @@ class AppNotifier extends ChangeNotifier {
return controller.snapshot?.conversation(id) == null ? null : id;
}
+ /// The thread whose pane is on screen beside that conversation, by its
+ /// root: the round dial shows and answers it while it stays open.
+ String? _dialThread(String tabId) => _dialConversation(tabId) == null
+ ? null
+ : superTabs.peek(tabId)?.threadOnScreen;
+
/// The tile roster and the tabs, to every daemon this window reaches over
/// its loopback ([_deskConnection]) — never a relayed machine's.
void _announceOpenPanesToDial() {
@@ -6152,6 +6158,7 @@ class AppNotifier extends ChangeNotifier {
'superTabId': tabId,
'projectId': ?_rememberDialProject(tabId),
'conversationId': ?_dialConversation(tabId),
+ 'threadRoot': ?_dialThread(tabId),
},
'agentIds': [
for (final pane in swarm.panes)
diff --git a/desktop/lib/super_tabs/client.dart b/desktop/lib/super_tabs/client.dart
index 4ea001207..ebc3b466f 100644
--- a/desktop/lib/super_tabs/client.dart
+++ b/desktop/lib/super_tabs/client.dart
@@ -752,6 +752,7 @@ class SuperTabClient {
buddyUnread: -1,
);
var seenSelected = controller.selectedId;
+ var seenThread = controller.threadOnScreen;
controller.addListener(() {
if (_reading.drawsSaved && generation == _generation) {
if (controller.accessRevoked) {
@@ -763,8 +764,12 @@ class SuperTabClient {
_saveViewSoon(id);
}
}
- if (controller.selectedId != seenSelected) {
+ // A thread opened or closed beside the chat is a selection too: the
+ // round dial's face follows it.
+ if (controller.selectedId != seenSelected ||
+ controller.threadOnScreen != seenThread) {
seenSelected = controller.selectedId;
+ seenThread = controller.threadOnScreen;
onSelection?.call(controller);
}
if (controller.snapshot case final snapshot?) {
diff --git a/desktop/lib/super_tabs/composer_toggle.dart b/desktop/lib/super_tabs/composer_toggle.dart
index a9bd1ee7b..e212986e9 100644
--- a/desktop/lib/super_tabs/composer_toggle.dart
+++ b/desktop/lib/super_tabs/composer_toggle.dart
@@ -4,11 +4,13 @@ import '../shared/theme/app_icons.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../widgets/desktop_chrome.dart';
-/// A composer choice on the send row (New session, Also send): the shared
-/// compact pill, read as an option to turn on (Scholes, 10-31). Off, it is
-/// outlined with an empty circle; on, accent-tinted with a check. Its hover
-/// hint says what it does, or why it can't be chosen now ([onChanged] null).
-/// A label too long for its place ends in "…"; the circle always shows.
+/// A composer choice (New session, Also send): a checkbox, an empty square
+/// before its label when off and an accent checked square when on, with no
+/// pill around it, so two of them read as independent options, never an
+/// either-or choice (Scholes, 11-03; a circle in an outlined pill read as a
+/// radio). Hover shades it as any quiet control. Its hover hint says what it
+/// does, or why it can't be chosen now ([onChanged] null: greyed). A label too
+/// long for its place ends in "…"; the square always shows.
class SuperTabComposerToggle extends StatelessWidget {
const SuperTabComposerToggle({
super.key,
@@ -29,8 +31,8 @@ class SuperTabComposerToggle extends StatelessWidget {
/// The width this choice takes with [label] in one line, as drawn in
/// [context] (its text size included): what a send row measures to tell
- /// whether a label fits. Matches [DesktopPill]'s compact choice: side
- /// padding, the icon and its gap, and the reserved rim.
+ /// whether a label fits. Matches [DesktopPill]'s compact quiet control:
+ /// side padding, the icon and its gap, and the reserved rim.
static double widthOf(BuildContext context, String label) {
final text = TextPainter(
text: TextSpan(
@@ -60,13 +62,11 @@ class SuperTabComposerToggle extends StatelessWidget {
child: DesktopPill(
label: label,
compact: true,
- choice: true,
+ quiet: true,
textSize: _textSize,
- selected: on,
- foregroundColor: on ? DesktopChrome.accent : null,
leadingGap: _gap,
leading: Icon(
- on ? AppIcons.circleCheck : AppIcons.circle,
+ on ? AppIcons.squareCheck : AppIcons.square,
key: ValueKey(on ? 'composer-toggle-check' : 'composer-toggle-off'),
size: _iconSize,
color: onChanged == null ? ink.withValues(alpha: .38) : ink,
diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dart
index ed33d43d7..b884e0c18 100644
--- a/desktop/lib/super_tabs/controller.dart
+++ b/desktop/lib/super_tabs/controller.dart
@@ -876,11 +876,27 @@ class SuperTabController extends ChangeNotifier {
if (!_threadUnshown) return;
_threadUnshown = false;
if (openedThread case final open?) _seeThread(open.root);
+ // The round dial follows a thread whose pane is on screen.
+ _changed();
}
/// The pane of the open thread left the screen: the app went to the
/// background, another Swarm came to the front, or something covers it.
- void threadPaneHidden() => _threadUnshown = true;
+ /// Called from a build or a dispose, so the round dial, which follows a
+ /// thread only while its pane is on screen, is told after it.
+ void threadPaneHidden() {
+ if (_threadUnshown) return;
+ _threadUnshown = true;
+ if (openedThread != null) scheduleMicrotask(_changed);
+ }
+
+ /// The root of the thread open beside the selected conversation while its
+ /// pane is on screen, which the round dial's face follows; null otherwise.
+ String? get threadOnScreen => switch (openedThread) {
+ final open? when open.conversationId == selectedId && !_threadUnshown =>
+ open.root,
+ _ => null,
+ };
final _attachments = <String, HarnessAttachments>{};
diff --git a/desktop/lib/super_tabs/pane_layout.dart b/desktop/lib/super_tabs/pane_layout.dart
index f802ede41..54e0db9e1 100644
--- a/desktop/lib/super_tabs/pane_layout.dart
+++ b/desktop/lib/super_tabs/pane_layout.dart
@@ -26,9 +26,10 @@ class SuperTabPaneLayout extends StatefulWidget {
static const leftWidth = 300.0;
static const rightWidth = 280.0;
- /// A thread's default width (Scholes, 10-31): room for its reply box's
- /// options on one row ("New session" and "Also to chat"). [rightWidth]
- /// stays the narrowest the pane goes.
+ /// A thread's default width (Scholes, 10-31). Its reply box's Also send
+ /// shares the send row with New session only from about 410px; here it
+ /// takes its own line under the box, in full (11-03). [rightWidth] stays
+ /// the narrowest the pane goes.
static const threadWidth = 340.0;
/// The roster drawer's share of a narrow window at most. On a phone it filled the screen, leaving no
diff --git a/desktop/lib/super_tabs/project_sidebar.dart b/desktop/lib/super_tabs/project_sidebar.dart
index 57e335eb5..03ff609e5 100644
--- a/desktop/lib/super_tabs/project_sidebar.dart
+++ b/desktop/lib/super_tabs/project_sidebar.dart
@@ -856,7 +856,9 @@ class ProjectSidebar extends StatelessWidget {
controller.unreadShown(group) ||
(attention?.mentionsIn(group.id) ?? 0) > 0;
- /// Every project with its workgroups, by name from A to Z.
+ /// Every project with its workgroups, by name from A to Z. The round dial
+ /// swipes projects in this order (cli superTabs/cards.ts `leadsOf`): the
+ /// two must match.
List<(String, Widget)> _channels(
SuperTabSnapshot? snapshot,
_SidebarReading reading,
@@ -1192,7 +1194,9 @@ List<SuperTabConversation> superTabOpenWorkgroups(
/// The chats in the order the sidebar lists them, for Option+Shift+Down and
/// Up (Slack's next unread): the reader's one Buddy chat (`# buddy`, first
/// under Projects), each project from A to Z, its chat then its open
-/// workgroups newest first, then the reader's project Buddy chats.
+/// workgroups newest first, then the reader's project Buddy chats. The round
+/// dial swipes projects in this A to Z order too (cli superTabs/cards.ts
+/// `leadsOf`): the two must match.
List<String> superTabSidebarOrder(SuperTabController controller) {
final snapshot = controller.snapshot;
if (snapshot == null) return const [];
diff --git a/desktop/lib/super_tabs/reply_box.dart b/desktop/lib/super_tabs/reply_box.dart
index 3cf760d65..a3dc68910 100644
--- a/desktop/lib/super_tabs/reply_box.dart
+++ b/desktop/lib/super_tabs/reply_box.dart
@@ -63,6 +63,15 @@ class SuperTabReplyBox extends StatelessWidget {
/// The field's hint: what an empty box says it is for.
final String hint;
+ /// The Tab order inside an [OrderedTraversalPolicy] group around the box:
+ /// the field (and its files) first, then the options, wherever the owner
+ /// places them ([optionsOrder], such as the pane's Also send on its own line
+ /// under the box), then attach and send. Outside such a group it has no
+ /// effect, and the reading order applies.
+ static const fieldOrder = NumericFocusOrder(1),
+ optionsOrder = 2.0,
+ sendOrder = NumericFocusOrder(3);
+
@override
Widget build(BuildContext context) => NewHarnessDropZone(
attachments: files,
@@ -157,23 +166,29 @@ class SuperTabReplyBox extends StatelessWidget {
Row(
children: [
Expanded(child: options ?? const SizedBox.shrink()),
- NewHarnessAttachButton(
- attachments: files,
- enabled: writable && !busy,
+ FocusTraversalOrder(
+ order: sendOrder,
+ child: NewHarnessAttachButton(
+ attachments: files,
+ enabled: writable && !busy,
+ ),
),
- ListenableBuilder(
- listenable: Listenable.merge([files, text]),
- builder: (context, _) => AppIconButton(
- key: sendKey,
- icon: AppIcons.arrowUp,
- tooltip: 'Send reply',
- color: DesktopChrome.accent,
- onPressed:
- writable &&
- !busy &&
- (text.text.trim().isNotEmpty || !files.isEmpty)
- ? onSend
- : null,
+ FocusTraversalOrder(
+ order: sendOrder,
+ child: ListenableBuilder(
+ listenable: Listenable.merge([files, text]),
+ builder: (context, _) => AppIconButton(
+ key: sendKey,
+ icon: AppIcons.arrowUp,
+ tooltip: 'Send reply',
+ color: DesktopChrome.accent,
+ onPressed:
+ writable &&
+ !busy &&
+ (text.text.trim().isNotEmpty || !files.isEmpty)
+ ? onSend
+ : null,
+ ),
),
),
],
diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dart
index e6194034f..2d504434f 100644
--- a/desktop/lib/super_tabs/thread_panel.dart
+++ b/desktop/lib/super_tabs/thread_panel.dart
@@ -159,23 +159,26 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
_measureAfterFrame();
}
- /// Where "Also send" also puts the reply, full wording first (Scholes,
- /// 10-31): the project chat as its sidebar row names it, else the main
- /// chat. A narrower send row takes the short one, never shorter: it still
- /// says what the option does and where.
- List<String> get _alsoSendLabels {
+ /// Where "Also send" also puts the reply, always in full (Scholes, 11-03:
+ /// "Also to chat" did not say where): the project chat as its sidebar row
+ /// names it, else the main chat.
+ String get _alsoSendLabel {
final group = c.selected, snapshot = c.snapshot;
String? channel;
if (group != null && snapshot != null && snapshot.isProjectLead(group.id)) {
channel = snapshot.projectFor(group.id)?.name;
}
return channel == null
- ? const ['Also post to the main chat', 'Also to chat']
- : ['Also post to #$channel', 'Also to #$channel'];
+ ? 'Also post to the main chat'
+ : 'Also post to #$channel';
}
- /// One line, always the full wording.
- String get _alsoSendHint => '${_alsoSendLabels.first} as well as this thread';
+ String get _alsoSendHint => '$_alsoSendLabel as well as this thread';
+
+ /// Whether Also send sits on its own line under the box: its full label
+ /// has no room beside New session on the send row. Set from the send row's
+ /// width once it is laid out ([_choices]).
+ bool _alsoBelow = false;
// An older Buddy chat is kept to read: no thread reply there either (security review 1 of #2437).
bool get _writable =>
@@ -202,8 +205,11 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
/// A session's thread stays in the thread: Also send is not offered there,
/// nor for a reply that starts one.
- bool get _offersAlsoSend =>
- !_startsSession && c.threadSession(widget.root) == null;
+ bool get _offersAlsoSend => !_startsSession && _alsoSendPossible;
+
+ /// Whether this thread offers Also send whenever New session is off: its
+ /// place is laid out for it, so turning New session on never moves the box.
+ bool get _alsoSendPossible => c.threadSession(widget.root) == null;
/// The files waiting to go with this thread's next reply.
HarnessAttachments get _files =>
@@ -469,56 +475,46 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
grid.AppDesktop.groupGap,
grid.AppDesktop.groupGap,
),
- child: Column(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.stretch,
- children: [
- ListenableBuilder(
- listenable: Listenable.merge([
- _composer,
- _tagIndex,
- _tagDismissed,
- ]),
- builder: (context, _) {
- final choices = _tagChoices;
- if (choices.isEmpty) return const SizedBox.shrink();
- return Padding(
- padding: const EdgeInsets.only(
- bottom: grid.AppDesktop.controlGap,
+ child: // The Tab order holds wherever Also send sits (reply_box.dart
+ // fieldOrder).
+ FocusTraversalGroup(
+ policy: OrderedTraversalPolicy(),
+ child: Column(
+ mainAxisSize: MainAxisSize.min,
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ ListenableBuilder(
+ listenable: Listenable.merge([
+ _composer,
+ _tagIndex,
+ _tagDismissed,
+ ]),
+ builder: (context, _) {
+ final choices = _tagChoices;
+ if (choices.isEmpty) return const SizedBox.shrink();
+ return Padding(
+ padding: const EdgeInsets.only(
+ bottom: grid.AppDesktop.controlGap,
+ ),
+ child: SuperTabCompletionList(
+ listKey: const ValueKey(
+ 'super-thread-completions',
+ ),
+ choices: choices,
+ index: _tagIndex.value,
+ rowKeys: _tagRows,
+ ),
+ );
+ },
),
- child: SuperTabCompletionList(
- listKey: const ValueKey('super-thread-completions'),
- choices: choices,
- index: _tagIndex.value,
- rowKeys: _tagRows,
+ FocusTraversalOrder(
+ order: SuperTabReplyBox.fieldOrder,
+ child: _composerBox(),
),
- );
- },
- ),
- _composerBox(),
- // Its place is kept while New session is offered, so the
- // box never moves as the choice is toggled.
- if (_offersSession)
- Padding(
- padding: const EdgeInsets.only(
- top: grid.AppDesktop.controlGap,
- ),
- child: Visibility(
- visible: _startsSession,
- maintainSize: true,
- maintainAnimation: true,
- maintainState: true,
- child: Text(
- 'Your reply starts a new Buddy session',
- key: const ValueKey('super-thread-session-note'),
- style: DesktopChrome.metadata(
- color: DesktopChrome.muted,
- ),
- ),
- ),
+ ?_underBox(),
+ ],
),
- ],
- ),
+ ),
),
],
),
@@ -563,54 +559,106 @@ class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {
inputFormatters: [_tagBackspace],
);
- /// The send row's options, left of attach and send, on one line at any
- /// width (Scholes, 10-31): Also send names where it posts in full where
- /// that fits beside New session, else its short wording; where even that
- /// has no room (a window too narrow for the thread's default width), the
- /// labels end in "…", their circles still showing.
+ /// What sits under the box: Also send on its own line where it has no room
+ /// on the send row, and the muted note while the reply starts a session.
+ /// They never show together, so they share one place; each keeps its place
+ /// while hidden, so the box never moves as New session is toggled.
+ Widget? _underBox() {
+ final note = _offersSession
+ ? Padding(
+ padding: const EdgeInsets.only(top: grid.AppDesktop.controlGap),
+ child: Visibility(
+ visible: _startsSession,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: Text(
+ 'Your reply starts a new Buddy session',
+ key: const ValueKey('super-thread-session-note'),
+ style: DesktopChrome.metadata(color: DesktopChrome.muted),
+ ),
+ ),
+ )
+ : null;
+ if (!(_alsoSendPossible && _alsoBelow)) return note;
+ // Its square under the send row's first one: the box's inset.
+ final line = Visibility(
+ visible: _offersAlsoSend,
+ maintainSize: true,
+ maintainAnimation: true,
+ maintainState: true,
+ child: Padding(
+ key: const ValueKey('super-thread-also-line'),
+ padding: const EdgeInsets.only(
+ top: grid.AppDesktop.controlGap,
+ left: grid.AppDesktop.groupGap,
+ ),
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: _alsoSendChoice(_writable),
+ ),
+ ),
+ );
+ return note == null ? line : Stack(children: [line, note]);
+ }
+
+ /// The send row's options, left of attach and send (Scholes, 11-03): New
+ /// session, then Also send in full where both fit; where they do not, Also
+ /// send moves to its own line under the box ([_alsoBelow]), never to a
+ /// shorter label. The choice rests on the row's width alone, so it settles
+ /// after one frame, in which Also send is drawn in neither place.
Widget _choices(bool writable) => LayoutBuilder(
builder: (context, constraints) {
double width(String label) =>
SuperTabComposerToggle.widthOf(context, label);
final session = _offersSession ? _sessionLabel : null;
- final alsos = _offersAlsoSend ? _alsoSendLabels : null;
- final room =
- constraints.maxWidth -
- (session == null
- ? 0
- : width(session) + (alsos == null ? 0 : _choiceGap));
- final also = alsos?.firstWhere(
- (label) => width(label) <= room,
- orElse: () => alsos.last,
+ // Measured whether or not New session is on, so the place stays put.
+ final also = _alsoSendPossible ? _alsoSendLabel : null;
+ final needed =
+ (session == null ? 0 : width(session)) +
+ (session != null && also != null ? _choiceGap : 0) +
+ (also == null ? 0 : width(also));
+ final below = also != null && needed > constraints.maxWidth;
+ final inline = _offersAlsoSend && !below && !_alsoBelow;
+ if (below != _alsoBelow) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && below != _alsoBelow) {
+ setState(() => _alsoBelow = below);
+ }
+ });
+ }
+ final sessionChoice = FocusTraversalOrder(
+ order: const NumericFocusOrder(SuperTabReplyBox.optionsOrder),
+ child: _sessionChoice(writable),
);
- // Fixed while both fit, Also send taking what is left; sharing the row
- // otherwise.
- final fits = room >= (also == null ? 0 : width(also));
return Row(
children: [
+ // Its own width beside Also send, which then fits; alone it may end
+ // in "…" in a pane narrower than the app allows.
if (session != null)
- fits && also != null
- ? _sessionChoice(writable)
- : Flexible(child: _sessionChoice(writable)),
- if (session != null && also != null)
- const SizedBox(width: _choiceGap),
- if (also != null)
- Flexible(
- child: SuperTabComposerToggle(
- key: const ValueKey('super-thread-also-send'),
- on: _alsoSend,
- label: also,
- hint: _alsoSendHint,
- onChanged: writable
- ? (on) => setState(() => _alsoSend = on)
- : null,
- ),
- ),
+ inline ? sessionChoice : Flexible(child: sessionChoice),
+ if (inline) ...[
+ if (session != null) const SizedBox(width: _choiceGap),
+ Flexible(child: _alsoSendChoice(writable)),
+ ],
],
);
},
);
+ /// Also send, on the send row or on its own line under the box; after New
+ /// session in the Tab order either way.
+ Widget _alsoSendChoice(bool writable) => FocusTraversalOrder(
+ order: const NumericFocusOrder(SuperTabReplyBox.optionsOrder + .1),
+ child: SuperTabComposerToggle(
+ key: const ValueKey('super-thread-also-send'),
+ on: _alsoSend,
+ label: _alsoSendLabel,
+ hint: _alsoSendHint,
+ onChanged: writable ? (on) => setState(() => _alsoSend = on) : null,
+ ),
+ );
+
static const _choiceGap = 4.0;
static const _sessionLabel = 'New session';
diff --git a/desktop/test/super_tab_buddy_sessions_test.dart b/desktop/test/super_tab_buddy_sessions_test.dart
index a939c4547..4b033af58 100644
--- a/desktop/test/super_tab_buddy_sessions_test.dart
+++ b/desktop/test/super_tab_buddy_sessions_test.dart
@@ -200,9 +200,14 @@ void main() {
expect(newSession, findsOneWidget);
expect(alsoSend, findsOneWidget);
expect(box(tester, newSession).on, isFalse);
- // Left of Also send on one row, at any width (Scholes, 10-31).
+ // Left of Also send on one row, or above it where Also send takes its
+ // own line under the box (Scholes, 11-03).
final a = tester.getRect(newSession), b = tester.getRect(alsoSend);
- expect(a.top == b.top && a.left < b.left, isTrue);
+ expect(
+ (a.top == b.top && a.left < b.left) ||
+ (b.top > a.bottom && (a.left - b.left).abs() < .5),
+ isTrue,
+ );
expect(
find.byTooltip('Starts a separate Buddy session for this thread'),
findsOneWidget,
@@ -212,7 +217,7 @@ void main() {
await tester.pump();
expect(box(tester, newSession).on, isTrue);
// A session's thread stays in the thread.
- expect(alsoSend, findsNothing);
+ expect(alsoSend.hitTestable(), findsNothing);
await tester.enterText(composer, 'Measure it now');
await tester.pump();
@@ -228,8 +233,8 @@ void main() {
expect(newSession, findsNothing);
});
- testSessions('the choices are compact chips on the send row, not '
- 'checkboxes', (tester) async {
+ testSessions('the choices are compact checkboxes drawn as a square before '
+ 'the label, not Material checkboxes', (tester) async {
final server = buddyChat();
final c = await show(tester, server);
await openThread(tester, c, 'message-1');
@@ -239,25 +244,28 @@ void main() {
findsNothing,
);
expect(box(tester, newSession).label, 'New session');
- // The default 280px pane has no room for the full wording beside New
- // session: its hint keeps it.
- expect(box(tester, alsoSend).label, 'Also to chat');
+ // Always the full wording (Scholes, 11-03): with no room beside New
+ // session, it takes its own line under the box.
+ expect(box(tester, alsoSend).label, 'Also post to the main chat');
expect(
find.byTooltip('Also post to the main chat as well as this thread'),
findsOneWidget,
);
- // Both sit on the send row, left of its buttons, and are compact: no
- // taller than the send button. (One line at real fonts: the PR's
- // screenshots; the test font is far wider.)
+ // New session sits on the send row, left of its buttons; Also send on
+ // its line under the box. Both are compact: no taller than the send
+ // button. (The PR's screenshots show real fonts; the test font is far
+ // wider.)
final row = tester.getRect(send);
final surface = tester.getRect(
find.byKey(const ValueKey('super-thread-composer-surface')),
);
- for (final chip in [newSession, alsoSend]) {
- final rect = tester.getRect(chip);
- expect(rect.right, lessThan(row.left));
+ final session = tester.getRect(newSession);
+ expect(session.right, lessThan(row.left));
+ expect(surface.contains(session.center), isTrue);
+ final also = tester.getRect(alsoSend);
+ expect(also.top, greaterThanOrEqualTo(surface.bottom));
+ for (final rect in [session, also]) {
expect(rect.height, lessThanOrEqualTo(row.height));
- expect(surface.contains(rect.center), isTrue);
}
// The muted line shows only while the reply starts a session; its place
// is kept, so it never pushes the box up under the cursor.
@@ -271,7 +279,7 @@ void main() {
await tester.tap(newSession);
await tester.pump();
expect(box(tester, newSession).on, isTrue);
- expect(alsoSend, findsNothing);
+ expect(alsoSend.hitTestable(), findsNothing);
expect(
tester.widget<Text>(note).data,
'Your reply starts a new Buddy session',
@@ -413,7 +421,7 @@ void main() {
await openThread(tester, c, 'message-1');
expect(tester.widget<Text>(state).data, 'Own session · Starting…');
expect(newSession, findsNothing);
- expect(alsoSend, findsNothing);
+ expect(alsoSend.hitTestable(), findsNothing);
});
testSessions('a session on a computer that went offline names it', (
@@ -486,7 +494,7 @@ void main() {
);
expect(box(tester, newSession).on, isTrue);
expect(box(tester, newSession).onChanged, isNull);
- expect(alsoSend, findsNothing);
+ expect(alsoSend.hitTestable(), findsNothing);
await tester.enterText(composer, 'Go on');
await tester.pump();
await tester.tap(send);
@@ -680,7 +688,7 @@ void main() {
await openThread(tester, c, 'message-1');
expect(box(tester, newSession).on, isTrue);
expect(box(tester, newSession).onChanged, isNull);
- expect(alsoSend, findsNothing);
+ expect(alsoSend.hitTestable(), findsNothing);
expect(tester.widget<Text>(ended).data, 'Session ended');
});
diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dart
index f13db38d4..3fa216ebc 100644
--- a/desktop/test/super_tab_dial_test.dart
+++ b/desktop/test/super_tab_dial_test.dart
@@ -461,6 +461,29 @@ void main() {
expect(row(after.last)['conversationId'], 'design-fix');
});
+ // Diego's dial, 2026-11-03: a thread open on Desktop was neither shown nor
+ // answered on the dial.
+ test('the Swarm row names the open thread while its pane shows, and not after it closes', () async {
+ final (f, c) = await openChats();
+ c.select('design-fix');
+ await settle();
+ expect(row(announces(f).last).containsKey('threadRoot'), isFalse);
+ c.openThread('m-root');
+ await settle();
+ expect(row(announces(f).last)['conversationId'], 'design-fix');
+ expect(row(announces(f).last)['threadRoot'], 'm-root');
+ c.closeThread();
+ await settle();
+ expect(row(announces(f).last)['conversationId'], 'design-fix');
+ expect(row(announces(f).last).containsKey('threadRoot'), isFalse);
+ // A thread of another conversation is not on screen beside this one.
+ c.openThread('m-root');
+ c.select('design-lead');
+ await settle();
+ expect(row(announces(f).last)['conversationId'], 'design-lead');
+ expect(row(announces(f).last).containsKey('threadRoot'), isFalse);
+ });
+
test('a decisions view or an unloaded Swarm leaves conversationId out', () async {
final (f, c) = await openChats();
c.select('design-pm');
diff --git a/desktop/test/super_tab_reply_box_shots_test.dart b/desktop/test/super_tab_reply_box_shots_test.dart
index 5ba1f914b..7822becad 100644
--- a/desktop/test/super_tab_reply_box_shots_test.dart
+++ b/desktop/test/super_tab_reply_box_shots_test.dart
@@ -13,10 +13,11 @@ import 'support/super_tab_fixture.dart';
/// Set to a folder to write the PR's screenshots there.
final shots = Platform.environment['SUPER_TAB_REPLY_BOX_SHOTS'];
-/// The thread reply box's options as the PR shows them (Scholes, 10-31), in
-/// both appearances: a project thread and a Buddy thread, Also send off and
-/// on, at the thread's default width, widened, and dragged to the 280px
-/// minimum (the "…" fallback), and the hover hint.
+/// The thread reply box's options as the PR shows them (Scholes, 11-03), in
+/// both appearances: square checkboxes at rest, on and on hover (with its
+/// hint), in a project thread and a Buddy thread, at the thread's default
+/// width (Also send on its own line), widened (one row), and dragged to the
+/// 280px minimum. The main chat's New session: super_tab_session_chips_shots.
void main() {
setUpAll(() async {
if (shots != null) await loadPreviewFonts();
@@ -69,6 +70,8 @@ void main() {
for (final scene in [
'project-off',
'project-on',
+ 'project-hint',
+ 'project-280-off',
'buddy-off',
'buddy-on',
'buddy-hint',
diff --git a/desktop/test/super_tab_reply_box_test.dart b/desktop/test/super_tab_reply_box_test.dart
index 313da2d24..294653fb3 100644
--- a/desktop/test/super_tab_reply_box_test.dart
+++ b/desktop/test/super_tab_reply_box_test.dart
@@ -2,13 +2,16 @@ import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
+import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_icons.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/super_tabs/composer_toggle.dart';
import 'package:harness/super_tabs/controller.dart';
import 'package:harness/super_tabs/model.dart';
import 'package:harness/super_tabs/pane_layout.dart';
import 'package:harness/super_tabs/thread_panel.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'box_render_preview_test.dart' show loadPreviewFonts;
import 'support/super_tab_fixture.dart';
@@ -136,7 +139,8 @@ void main() {
SuperTabComposerToggle box(WidgetTester tester, Finder finder) =>
tester.widget<SuperTabComposerToggle>(finder);
- /// The circle (off) or check (on) inside [chip], drawn inside its bounds.
+ /// The empty square (off) or checked square (on) inside [chip], drawn
+ /// inside its bounds: a checkbox, never a radio's circle (Scholes, 11-03).
void expectMark(WidgetTester tester, Finder chip, {required bool on}) {
final mark = find.descendant(
of: chip,
@@ -145,6 +149,10 @@ void main() {
),
);
expect(mark, findsOneWidget);
+ expect(
+ tester.widget<Icon>(mark).icon,
+ on ? AppIcons.squareCheck : AppIcons.square,
+ );
final rect = tester.getRect(mark), bounds = tester.getRect(chip);
expect(rect.width, greaterThan(0));
expect(bounds.contains(rect.center), isTrue);
@@ -167,6 +175,64 @@ void main() {
}
}
+ final alsoLine = find.byKey(const ValueKey('super-thread-also-line'));
+
+ /// [label] drawn whole inside [chip]: one line, no "…".
+ void expectWhole(WidgetTester tester, Finder chip, String label) {
+ final text = find.descendant(of: chip, matching: find.text(label));
+ final paragraph = tester.renderObject<RenderParagraph>(text);
+ expect(paragraph.didExceedMaxLines, isFalse, reason: label);
+ expect(
+ paragraph.size.width,
+ greaterThanOrEqualTo(paragraph.getMaxIntrinsicWidth(100) - .5),
+ reason: label,
+ );
+ }
+
+ /// Also send's [label] on its line under the box: whole wherever it
+ /// measures to fit that line in the face drawn (the Mac's face fits it at
+ /// every width the app allows, the screenshots show); in a face too wide
+ /// for even that (the test font on Linux CI), it ends in "…" there and
+ /// nothing overflows.
+ void expectWholeUnderBox(WidgetTester tester, String label) {
+ final room = tester.getRect(surface).width - 16;
+ if (SuperTabComposerToggle.widthOf(tester.element(alsoSend), label) <=
+ room) {
+ expectWhole(tester, alsoSend, label);
+ } else {
+ final text = find.descendant(of: alsoSend, matching: find.text(label));
+ expect(
+ tester.renderObject<RenderParagraph>(text).didExceedMaxLines,
+ isTrue,
+ );
+ expect(
+ tester.getRect(alsoSend).right,
+ lessThanOrEqualTo(tester.getRect(surface).right),
+ );
+ }
+ }
+
+ /// Also send on its own line under the box, its square under the send
+ /// row's first one, not on the send row.
+ void expectUnderBox(WidgetTester tester) {
+ expect(alsoLine, findsOneWidget);
+ expect(find.descendant(of: alsoLine, matching: alsoSend), findsOneWidget);
+ final rect = tester.getRect(alsoSend), box = tester.getRect(surface);
+ expect(rect.top, greaterThanOrEqualTo(box.bottom));
+ final mark = tester.getRect(
+ find
+ .descendant(
+ of: alsoSend,
+ matching: find.byKey(const ValueKey('composer-toggle-off')),
+ )
+ .hitTestable(),
+ );
+ // Under the send row's first square: the options start 16 in, and the
+ // control's own padding is 6.
+ expect((mark.left - (box.left + 16 + 6)).abs(), lessThan(.5));
+ expect(rect.right, lessThanOrEqualTo(box.right));
+ }
+
group('Also send names where it posts', () {
testBox('a project thread names the project chat in full', (tester) async {
await panel(tester, projectChat(), 'lead', width: 800);
@@ -205,13 +271,16 @@ void main() {
double widthOf(WidgetTester tester, String label) =>
SuperTabComposerToggle.widthOf(tester.element(alsoSend), label);
+ // Scholes, 11-03: "Also to chat" did not say where the reply goes. The
+ // full wording always shows; where it has no room beside New session,
+ // Also send takes its own line under the box.
for (final (kind, full, short) in [
('project', 'Also post to #Pilot', 'Also to #Pilot'),
('Buddy', 'Also post to the main chat', 'Also to chat'),
]) {
- testBox('a $kind thread steps down to "$short" where "$full" has no '
- 'room, never shorter: below that the label ends in "…" and its '
- 'circle shows', (tester) async {
+ testBox('a $kind thread keeps "$full" on the send row while it fits, '
+ 'and moves it, in full, to its own line under the box where it does '
+ 'not', (tester) async {
final buddy = kind == 'Buddy';
ConversationServer server() => buddy ? buddyChat() : projectChat();
final conversation = buddy ? 'offline' : 'lead';
@@ -219,27 +288,43 @@ void main() {
final room = roomIn(tester);
final beside = buddy ? widthOf(tester, 'New session') + 4 : 0.0;
final fullFits = widthOf(tester, full) + beside;
- final shortFits = widthOf(tester, short) + beside;
double paneFor(double needed) => 800 - room(800) + needed;
await tester.pumpWidget(const SizedBox());
await shown.flush();
- for (final (pane, label) in [
- (paneFor(fullFits) + 1, full),
- (paneFor(fullFits) - 1, short),
- (paneFor(shortFits) + 1, short),
- (paneFor(shortFits) - 12, short),
+ for (final (pane, below) in [
+ (paneFor(fullFits) + 1, false),
+ (paneFor(fullFits) - 1, true),
+ for (final width in [
+ SuperTabPaneLayout.threadWidth,
+ SuperTabPaneLayout.rightWidth,
+ ])
+ (width, paneFor(fullFits) > width),
]) {
await panel(tester, server(), conversation, width: pane);
- expect(box(tester, alsoSend).label, label, reason: 'at $pane');
+ expect(box(tester, alsoSend).label, full, reason: 'at $pane');
+ expect(find.text(short), findsNothing);
+ if (below) {
+ expectWholeUnderBox(tester, full);
+ } else {
+ expectWhole(tester, alsoSend, full);
+ }
expect(
find.byTooltip('$full as well as this thread'),
findsOneWidget,
);
- if (buddy) expect(box(tester, newSession).label, 'New session');
- expectOneRow(tester, [if (buddy) newSession, alsoSend]);
+ if (buddy) {
+ expect(box(tester, newSession).label, 'New session');
+ expectOneRow(tester, [newSession]);
+ expectMark(tester, newSession, on: false);
+ }
expectMark(tester, alsoSend, on: false);
- if (buddy) expectMark(tester, newSession, on: false);
+ if (below) {
+ expectUnderBox(tester);
+ } else {
+ expect(alsoLine, findsNothing, reason: 'at $pane');
+ expectOneRow(tester, [if (buddy) newSession, alsoSend]);
+ }
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
await shown.flush();
@@ -249,7 +334,43 @@ void main() {
});
group('the options read as on/off choices', () {
- testBox('off is an empty circle, on a check; tapping toggles it', (
+ // Scholes, 11-03: an outlined pill with a circle read as a radio, so New
+ // session and Also send looked like an either-or choice.
+ testBox('a checkbox with no pill around it, off or on', (tester) async {
+ await panel(tester, projectChat(), 'lead', width: 800);
+ DesktopPill pill() => tester.widget<DesktopPill>(
+ find.descendant(of: alsoSend, matching: find.byType(DesktopPill)),
+ );
+ expect(pill().quiet, isTrue);
+ expect(pill().choice, isFalse);
+ expect(pill().selected, isNull);
+ await tester.tap(alsoSend);
+ await tester.pump();
+ expectMark(tester, alsoSend, on: true);
+ expect(pill().quiet, isTrue);
+ expect(pill().selected, isNull);
+ });
+
+ testBox('a New session that can\'t start now is a greyed empty square', (
+ tester,
+ ) async {
+ final server = buddyChat()..state['paused'] = true;
+ await panel(tester, server, 'offline', width: 800);
+ expectMark(tester, newSession, on: false);
+ final mark = tester.widget<Icon>(
+ find.descendant(
+ of: newSession,
+ matching: find.byKey(const ValueKey('composer-toggle-off')),
+ ),
+ );
+ expect(mark.color!.a, lessThan(.5));
+ expect(
+ find.byTooltip('New work is paused in this Swarm'),
+ findsOneWidget,
+ );
+ });
+
+ testBox('off is an empty square, on a checked square; tapping toggles it', (
tester,
) async {
await panel(tester, projectChat(), 'lead', width: 800);
@@ -294,7 +415,8 @@ void main() {
await tester.tap(newSession);
await tester.pump();
expectMark(tester, newSession, on: true);
- expect(alsoSend, findsNothing);
+ // Hidden, its place kept.
+ expect(alsoSend.hitTestable(), findsNothing);
expect(
tester
.widget<Visibility>(
@@ -312,19 +434,20 @@ void main() {
});
});
- group('one row at any width and text size', () {
+ group('at any width and text size', () {
for (final (width, scale) in [
(SuperTabPaneLayout.threadWidth, 1.0),
// The pane's minimum grows with the text (pane_layout.dart).
(SuperTabPaneLayout.rightWidth * 1.6, 1.6),
(SuperTabPaneLayout.rightWidth * 2, 2.0),
- // A window too narrow for the thread's default: "…", the marks stay.
(SuperTabPaneLayout.rightWidth, 1.0),
- // Narrower than the app allows.
+ // Narrower than the app allows: only here may the line under the box
+ // end in "…".
(SuperTabPaneLayout.rightWidth, 2.0),
]) {
- testBox('${width.round()}px at ${scale}x: one row, no overflow, both '
- 'marks showing', (tester) async {
+ testBox('${width.round()}px at ${scale}x: no overflow, New session on '
+ 'the send row, both squares showing, Also send in full on the row '
+ 'or under the box', (tester) async {
await panel(
tester,
buddyChat(),
@@ -333,13 +456,20 @@ void main() {
textScale: scale,
);
expect(tester.takeException(), isNull);
- expectOneRow(tester, [newSession, alsoSend]);
+ expectOneRow(tester, [newSession]);
expectMark(tester, newSession, on: false);
expectMark(tester, alsoSend, on: false);
- // One line each: the same top and height, never wrapped below.
- final a = tester.getRect(newSession), b = tester.getRect(alsoSend);
- expect(a.top, b.top);
- expect(a.height, b.height);
+ expect(box(tester, alsoSend).label, 'Also post to the main chat');
+ if (alsoLine.evaluate().isEmpty) {
+ expectOneRow(tester, [newSession, alsoSend]);
+ } else {
+ expectUnderBox(tester);
+ }
+ if (alsoLine.evaluate().isEmpty) {
+ expectWhole(tester, alsoSend, 'Also post to the main chat');
+ } else {
+ expectWholeUnderBox(tester, 'Also post to the main chat');
+ }
});
}
@@ -349,27 +479,81 @@ void main() {
expect(newSession, findsNothing);
expectOneRow(tester, [alsoSend]);
});
+
+ testBox('in the narrow layout, turning New session on and off never moves '
+ 'the box', (tester) async {
+ await panel(
+ tester,
+ buddyChat(),
+ 'offline',
+ width: SuperTabPaneLayout.rightWidth,
+ );
+ expectUnderBox(tester);
+ final before = tester.getRect(surface);
+ final line = tester.getRect(alsoLine);
+ await tester.tap(newSession);
+ await tester.pump();
+ // Hidden, its place kept.
+ expect(alsoSend.hitTestable(), findsNothing);
+ expect(tester.getRect(surface), before);
+ // The note takes Also send's line: the two never show together, so no
+ // empty band opens between the box and the note.
+ expect(tester.getRect(note).top, lessThan(line.bottom));
+ expect(tester.getRect(note).top, greaterThanOrEqualTo(before.bottom));
+ await tester.tap(newSession);
+ await tester.pump();
+ expectUnderBox(tester);
+ expect(tester.getRect(surface), before);
+ });
});
+ // The keyboard order stays as it was wherever Also send sits.
+ for (final width in [800.0, SuperTabPaneLayout.rightWidth]) {
+ testBox('Tab goes from the reply to New session, Also send, attach and '
+ 'send at ${width.round()}px', (tester) async {
+ await panel(tester, buddyChat(), 'offline', width: width);
+ final order = [
+ newSession,
+ alsoSend,
+ find.byKey(const ValueKey('new-harness-attach')),
+ send,
+ ];
+ // Send takes focus only with something to send.
+ await tester.enterText(
+ find.byKey(const ValueKey('super-thread-composer')),
+ 'Ship it',
+ );
+ await tester.pump();
+ for (final next in order) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ final focused = FocusManager.instance.primaryFocus!.context!;
+ expect(
+ find
+ .descendant(
+ of: next,
+ matching: find.byElementPredicate((e) => e == focused),
+ )
+ .evaluate()
+ .isNotEmpty,
+ isTrue,
+ reason: '$next at $width',
+ );
+ }
+ });
+ }
+
+ // The default width was chosen for "New session" and "Also to chat" on one
+ // row (10-31); the full wording needs about 410px there, so at 340px it
+ // takes its own line, whole.
testBox('at the thread\'s default width, in the Mac\'s face, a Buddy '
- 'thread fits "New session" and "Also to chat" with no "…", and a '
- 'project thread names #openharness in full', (tester) async {
+ 'thread shows "New session" on the send row and "Also post to the main '
+ 'chat" whole under the box, and a project thread names #openharness in '
+ 'full on the row', (tester) async {
await panel(tester, buddyChat(), 'offline');
- expect(box(tester, newSession).label, 'New session');
- expect(box(tester, alsoSend).label, 'Also to chat');
- for (final (chip, label) in [
- (newSession, 'New session'),
- (alsoSend, 'Also to chat'),
- ]) {
- final text = find.descendant(of: chip, matching: find.text(label));
- final paragraph = tester.renderObject<RenderParagraph>(text);
- expect(paragraph.didExceedMaxLines, isFalse, reason: label);
- expect(
- paragraph.size.width,
- greaterThanOrEqualTo(paragraph.getMaxIntrinsicWidth(100) - .5),
- reason: label,
- );
- }
+ expectWhole(tester, newSession, 'New session');
+ expectUnderBox(tester);
+ expectWhole(tester, alsoSend, 'Also post to the main chat');
await tester.pumpWidget(const SizedBox());
await shown.flush();
@@ -377,5 +561,8 @@ void main() {
project.state['name'] = 'openharness';
await panel(tester, project, 'lead');
expect(box(tester, alsoSend).label, 'Also post to #openharness');
+ expect(alsoLine, findsNothing);
+ expectOneRow(tester, [alsoSend]);
+ expectWhole(tester, alsoSend, 'Also post to #openharness');
}, skip: !systemFace);
}
diff --git a/docs/plans/2026-11-03-dial-recap-order-threads-plan.md b/docs/plans/2026-11-03-dial-recap-order-threads-plan.md
new file mode 100644
index 000000000..204670778
--- /dev/null
+++ b/docs/plans/2026-11-03-dial-recap-order-threads-plan.md
@@ -0,0 +1,105 @@
+# Round Dial: Recap at Once, the App's Project Order, and Threads Implementation Plan
+
+> **How this is worked:** by the project's instructions, task by task, each failing test committed before its code.
+
+**Goal:** The round dial's recap answers at once on a side switch, its projects swipe in the app's A to Z order, and its chat recap skips thread replies while a thread open on Desktop is shown and answered on the dial.
+
+**Architecture:** All three live in `SwarmCards` (cli/src/superTabs/cards.ts). (1) The dial's own recap read gets a lane of its own, one at a time, apart from the two background reads (notices, pushes); a recap held for the same chat, or a notice from it, is answered first and refreshed after, and the dial's daemon logs an empty or failed recap once per Lead and reason. (2) `leadsOf` ranks projects by name, case-insensitively A to Z, ties in server order, and `order` is that rank. (3) `lastAgentMessage` takes where to look (the chat's main stream, or one thread); Desktop names the open thread on the Swarm row (`threadRoot`), which rides the focus to the cards; a face with a thread reads and answers in it.
+
+**Tech Stack:** TypeScript, Vitest (CLI); Dart, Flutter 3.47.2 (Desktop).
+
+**Spec:** Task #2300 (Diego's three dial proposals), its brief in conversation 1ef9eace7e5c207a545f1a22.
+
+## Global Constraints
+
+- The PR body starts with: `Requested by [email protected] through Harness.`
+- No firmware change. Never publish firmware, run upload scripts or touch the device update manifest.
+- Swarm code stays out of `cli/src/core`: the focus's `threadRoot` is typed in the Swarm's files, not in `core/api.ts`.
+- Never run a test that signs this Mac out of the real CLI; Desktop tests use a memory store and a fake sign-in.
+- Before Ready: a failing-first test for every risk below, red/green evidence in a PR comment, and the full Super Tab integration suite (`npm run test:super-tabs`).
+- Files beyond the brief's list, each a pass-through or a comment: `cli/src/localWsServer.ts` (reads `threadRoot` off `app_swarms`), `cli/src/superTabs/inCore/cards.ts` and `cli/src/superTabs/service.ts` (carry it in the focus), `desktop/lib/super_tabs/client.dart` (re-announces on a thread opening or closing), `desktop/lib/super_tabs/controller.dart` (says whether the thread's pane is on screen), `desktop/lib/super_tabs/project_sidebar.dart` (the note that the orders must match).
+
+## Review Focus
+
+1. Two dials, or one dial asking in a loop: device reads queue one at a time, so the backend never sees more than three recap reads at once (two background, one device). Test: two device recaps asked together both answer, and the second read starts after the first ends.
+2. A held recap from before another person signed in is never answered: the cache is cleared on a change of reader, as today. Test: covered by the existing reader-change test, kept green.
+3. A thread on the face whose root is in another conversation (the window moved to another chat with the thread pane still naming the old one) is not used: the thread counts only when it is in the face's own conversation. Test in Task 4.
+4. Words said while a thread was on the face that closed before they were sent go to the chat, never to a thread no longer shown. Test in Task 4.
+5. A project named with only case differences ("web" and "Web") keeps server order between them. Test in Task 2.
+
+---
+
+### Task 1: The dial's recap is never refused, answers at once from what is held, and an empty one is logged
+
+**Files:**
+- Modify: `cli/src/superTabs/cards.ts` (`recap`, `pushOpenNow`, `prune`, `watchNotices`/`raise`)
+- Modify: `cli/src/services/devices.ts:255-257` (`swarmCardRecap`: a refusal throws its code instead of null)
+- Modify: `cli/src/cable/cableSession.ts:3031-3043` (log once per Lead and reason)
+- Test: `cli/src/superTabs/cards.spec.ts`, `cli/src/cable/cableSession.spec.ts`
+
+**Interfaces:**
+- Produces: `SwarmCards.recap(tabId, leadId, chat)` is the device's read: it waits for the device lane (one at a time) and never throws "too many recap reads". A private `read(tabId, leadId, chat, lane: 'device' | 'background')` does the backend read; `pushOpenNow` uses `'background'` (still at most `MAX_RECAPS_IN_FLIGHT = 2`, a refusal retried next tick).
+- Produces: a recap held for the target's cache key (any sequence), else the Lead's notice for the target chat when it is a main-stream message, is answered at once; when it is older than the chat (`sequence` moved, or answered from a notice) a device-lane refresh follows and `onRecap` pushes it when its text, time or chat differ.
+- Produces: `prune` keeps a recap while its chat could be on this Lead's face (`chatOfLead`), not only while it is on it, so a swipe back finds it.
+
+- [ ] **Step 1: Write the failing tests** (cards.spec.ts, `describe('SwarmCards dial recap')`)
+ - `answers the dial's recap while two background reads run`: message reads take 50 ms; a tick reading a moved Lead conversation and a side switch's push are in flight; `await cards.recap('t1', 'a1', 'buddy')` resolves to the Lead's text, no throw.
+ - `answers a side switch from the held recap with no backend request`: PM recap read, swipe to Buddy (recap read), a tick, swipe back to PM; `cards.recap` answers the PM text and no `GET …/messages` is made.
+ - `answers a stale held recap at once and pushes the newer one`: the Lead conversation moved; `cards.recap` answers the old text, then `onRecap` gets the new text.
+ - `queues two device recaps one after the other`.
+- [ ] **Step 2: Write the failing test** (cableSession.spec.ts) `logs a recap answered empty once per Lead and reason`: host recap answers null twice for a1 → one log line naming a1; a failure with a reason → one more line; a good answer and another null → a line again.
+- [ ] **Step 3: Run** `cd cli && npx vitest run src/superTabs/cards.spec.ts src/cable/cableSession.spec.ts` — Expected: the new tests FAIL ("too many recap reads at once", a messages read made, no log line).
+- [ ] **Step 4: Commit the failing tests.**
+- [ ] **Step 5: Implement** as the Interfaces say; devices.ts throws `new Error(String(r.error ?? 'not a recap'))` for a refused or unsound answer; cableSession keeps a `Set` of `${lead}:${reason}` logged, cleared for that Lead by a recap that came back.
+- [ ] **Step 6: Run** the same command — Expected: PASS, whole files.
+- [ ] **Step 7: Commit.**
+
+### Task 2: Leads in the app's order
+
+**Files:**
+- Modify: `cli/src/superTabs/cards.ts:124-182` (`leadsOf`)
+- Modify: `desktop/lib/super_tabs/project_sidebar.dart` (comment at both sorts: the dial's `leadsOf` must match)
+- Test: `cli/src/superTabs/cards.spec.ts`
+
+**Interfaces:**
+- Produces: each `SwarmLead.order` is its project's rank by `name.toLowerCase()` compared by code unit (Dart's `compareTo`), ties by server index; urgency sort ties go by that rank; the 12 most urgent are kept.
+
+- [ ] **Step 1: Write the failing tests:** `orders Leads as the app lists projects`: projects `Zeta, alpha, Mid` → `order` alpha 0, Mid 1, Zeta 2 and, all done, leads `[alpha, Mid, Zeta]`; `keeps server order for a name tie`: `web` then `Web` → orders 0, 1. Update the two existing order tests to the A to Z rank.
+- [ ] **Step 2: Run** `npx vitest run src/superTabs/cards.spec.ts -t "order"` — Expected: FAIL (creation order).
+- [ ] **Step 3: Commit the failing tests.**
+- [ ] **Step 4: Implement** the rank in `leadsOf`, the note in both files.
+- [ ] **Step 5: Run** the file — Expected: PASS. **Step 6: Commit.**
+
+### Task 3: The chat recap skips thread replies
+
+**Files:**
+- Modify: `cli/src/superTabs/cards.ts:198-212` (`lastAgentMessage`)
+- Test: `cli/src/superTabs/cards.spec.ts`
+
+**Interfaces:**
+- Produces: `lastAgentMessage(messages, agentIds, place: 'any' | 'chat' | { thread: string } = 'any')`. `'chat'`: the main stream (`!thread || thread === id || alsoInChat`, backend catchUp.ts `inMainStream`); `{ thread }`: rows whose `thread` is that root. Notices keep `'any'`; recaps of a chat use `'chat'`.
+
+- [ ] **Step 1: Write the failing tests:** `lastAgentMessage in the chat skips a thread reply but keeps one also sent to the chat`; `the chat recap is the agent's latest top-level message, not a thread reply` (SwarmCards.recap over a page whose newest Lead row is a thread reply).
+- [ ] **Step 2: Run** — Expected: FAIL (the reply's text). **Step 3: Commit.**
+- [ ] **Step 4: Implement.** **Step 5: Run** — PASS. **Step 6: Commit.**
+
+### Task 4: A thread open on Desktop is the dial's face
+
+**Files:**
+- Modify: `desktop/lib/state/app_state.dart:6080-6154` (`_dialThread`, `'threadRoot'` on the row)
+- Modify: `desktop/lib/super_tabs/controller.dart:862-877` (`threadPaneOnScreen`; `threadPaneShown` notifies)
+- Modify: `desktop/lib/super_tabs/client.dart:766-769` (an `openedThread` change calls `onSelection`)
+- Modify: `cli/src/cable/cableSession.ts:328` (`AppSwarms` row `threadRoot?`), `cli/src/localWsServer.ts:237` (read it, an id or nothing)
+- Modify: `cli/src/cable/cableHost.ts:580` (`activeSwarmProject` carries `threadRoot`), `cli/src/services/devices.ts:583` (focus carries it, a change refocuses)
+- Modify: `cli/src/superTabs/inCore/cards.ts:146`, `cli/src/superTabs/service.ts:500` (carry it)
+- Modify: `cli/src/superTabs/cards.ts` (`want`, `target`, `Opened`, `pushOpenNow`, cache key, `say`)
+- Test: `desktop/test/super_tab_dial_test.dart`, `cli/src/superTabs/cards.spec.ts`, `cli/src/cable/cableHost.spec.ts`
+
+**Interfaces:**
+- Produces: the `app_swarms` row's `threadRoot` (the open thread's root id) while the selected conversation's thread pane is on screen; absent otherwise.
+- Produces: `SwarmCards.want(on, include, focus: CardFocus & { threadRoot?: string })`; a change of `threadRoot` is a refocus.
+- Produces: `Target.thread?: string`, set when the face's conversation is the focused one and the focus names a thread; `recap` then reads `…/messages?thread=ROOT` and takes the newest agent message there; the cache key and `Opened` include the thread; `say` posts `replyTo: thread` when `target` at send time has it.
+
+- [ ] **Step 1: Write the failing tests:** Desktop `the Swarm row names the open thread while its pane shows, and not after it closes`; cards.spec `a thread on the face shows its newest agent reply and closing it pushes the chat recap`; `words said with a thread on the face reply in it`; `a thread whose chat is not on the face is not used` and `words said after the thread closed go to the chat` (Review Focus 3, 4); cableHost.spec `activeSwarmProject carries the thread root`.
+- [ ] **Step 2: Run** `cd desktop && flutter test test/super_tab_dial_test.dart` and the CLI files — Expected: FAIL. **Step 3: Commit.**
+- [ ] **Step 4: Implement** as the Interfaces say. **Step 5: Run** — PASS, then `npx tsc --noEmit -p cli`, `npm run test:super-tabs`, `flutter analyze` on the changed files. **Step 6: Commit and push.**
diff --git a/docs/plans/2026-11-03-thread-reply-checkboxes-plan.md b/docs/plans/2026-11-03-thread-reply-checkboxes-plan.md
new file mode 100644
index 000000000..3bcc3a59f
--- /dev/null
+++ b/docs/plans/2026-11-03-thread-reply-checkboxes-plan.md
@@ -0,0 +1,110 @@
+# Thread reply options as checkboxes, Also send in full: implementation plan
+
+> Worked by this project's instructions (Engineer role): this plan is the pull request's first commit. Then each task is
+> done test first, by one Engineer, with one Review step and one Test step on the pull request. Steps use checkbox
+> (`- [ ]`) syntax.
+
+**Goal:** in the Desktop thread reply box, New session and Also send look like square checkboxes, and Also send always
+reads in full ("Also post to the main chat" / "Also post to #project"). Where the full label does not fit beside New
+session, Also send moves to its own line under the box.
+
+**Architecture:** `SuperTabComposerToggle` (shared by the thread box and the main chat's New session) draws a quiet
+control: a square (off) or square-check (on, accent) before its label, with no pill outline. The thread panel measures
+its send row once. If New session and the full Also send fit, both stay on the row. If not, the row keeps New session,
+and Also send goes on a line under the box, aligned with the box's text. The Tab order does not depend on placement:
+field, New session, Also send, attach, send. An ordered focus group keeps it.
+
+**Tech Stack:** Flutter 3.47.2 Desktop (`flutter_test` widget tests, headless screenshots in
+`super_tab_reply_box_shots_test.dart`).
+
+**Spec:** task #2353 brief (Lead, 2026-11-03), and the mockup Scholes approved in the project chat (2026-11-03 14:24 VN):
+
+```
+Default width: both fit on one row Narrow: Also send moves to its own line under the box
+│ ☐ New session ☐ Also post to the main chat 📎 ↑ │ │ ☐ New session 📎 ↑ │
+ ☐ Also post to the main chat
+On: ☑ New session
+```
+
+## Global Constraints
+
+- PR body first line: "Requested by [email protected] through Harness."
+- Out of scope: what the options do. Harness design language (desktop/design/desktop-design-system.md). The keyboard
+ order does not change.
+- Never show the short labels ("Also to chat", "Also to #project").
+- Before Ready: a test that fails without the fix for every risk named here, red/green evidence in a PR comment, and
+ screenshots at rest, on and on hover. Also before Ready, run `python3 scripts/check-ui-style.py --only desktop/lib/super_tabs`.
+- Desktop tests use a memory store and a fake sign-in, never the real CLI.
+
+## Design
+
+N/A because the change stores, syncs and exposes no data: it changes the layout of two existing controls.
+
+## Review Focus
+
+1. At the thread's narrowest width with 2x text, even the line under the box is too narrow for the full label. The label
+ then ends in "…" on its own line, and nothing overflows (Task 2 test at 280px, 2x).
+2. Toggling New session hides Also send. The box and the line under it must not jump (Task 2 test: the box's rect is
+ unchanged).
+3. Moving Also send under the box must not change the Tab order (Task 2 test: Tab from the field).
+4. The disabled look (a blocked New session) must still read as a checkbox, greyed (Task 1 test).
+5. The main chat's New session gets the same look with no layout change (Task 1 test in the main composer).
+
+---
+
+### Task 1: the checkbox look
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/composer_toggle.dart`
+- Test: `desktop/test/super_tab_reply_box_test.dart`
+
+**Interfaces:**
+- Produces: `SuperTabComposerToggle`, same constructor. Off: `Icon(AppIcons.square)`, key `composer-toggle-off`. On:
+ `Icon(AppIcons.squareCheck)` in accent, key `composer-toggle-check`. The control is `DesktopPill(quiet: true)`, with
+ no rim at rest and no fill when on. `widthOf` is unchanged.
+
+- [ ] **Step 1: failing tests.** `off is an empty square, on a checked square; tapping toggles it`: the mark's icon is
+ `AppIcons.square` / `AppIcons.squareCheck`. `no pill outline at rest or when on`: the pill is quiet.
+ `a blocked New session is a greyed square`.
+- [ ] **Step 2: run them and see them fail** (`flutter test test/super_tab_reply_box_test.dart`).
+- [ ] **Step 3: implement.**
+- [ ] **Step 4: run them and see them pass.** Then run every test file that names `composer-toggle` or
+ `super-chat-new-session`.
+- [ ] **Step 5: commit** test first, then code.
+
+### Task 2: Also send in full, under the box when it does not fit
+
+**Files:**
+- Modify: `desktop/lib/super_tabs/thread_panel.dart` (`_alsoSendLabels` becomes one label; `_choices`; the line under
+ the box)
+- Modify: `desktop/lib/super_tabs/reply_box.dart` (`FocusTraversalOrder` on the field, attach and send; this has no
+ effect outside an ordered group)
+- Test: `desktop/test/super_tab_reply_box_test.dart`
+
+**Interfaces:**
+- Produces: key `super-thread-also-send` on the toggle wherever it sits, and key `super-thread-also-line` on the line
+ under the box.
+
+- [ ] **Step 1: failing tests** (they replace the step-down tests):
+ - `Also send always reads in full`: Buddy and project threads at 800px, the default 340px, and 280px at 1x. The label
+ is the full one, with no "…" (`didExceedMaxLines` false), and neither short label appears.
+ - `where both fit they share the send row; where not, Also send is on its own line under the box`: at the exact
+ boundary ±1px, it is on the row or on `super-thread-also-line` under the surface, left-aligned with it.
+ - `toggling New session never moves the box`, in the narrow layout.
+ - `Tab goes field, New session, Also send, attach, send`, in both layouts.
+ - `at 280px with 2x text nothing overflows`: Also send is on its line, and its label may end in "…".
+- [ ] **Step 2: run them and see them fail.**
+- [ ] **Step 3: implement.** `_choices` decides "fits" from its constraints and records it after the frame
+ (`_alsoBelow`). The decision depends only on the width, so it settles in one frame. While Also send is below, the
+ row draws only New session.
+- [ ] **Step 4: run them and see them pass**, plus `super_tab_thread_composer_test.dart`,
+ `super_tab_threads_test.dart`, `super_tab_buddy_sessions_test.dart`, `laid_out_list_test.dart` and the style check.
+- [ ] **Step 5: commit** test first, then code.
+
+### Task 3: screenshots
+
+**Files:** `desktop/test/super_tab_reply_box_shots_test.dart`
+
+- [ ] Scenes: project and Buddy threads, off, on and hover, at the default width and at the narrowest, light and dark.
+ Also the main chat's New session, off and on.
+- [ ] Commit the PNGs in their own commit, link them in the PR body, and remove them in the next commit.