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.

Round dial: the Buddy side finds the reader's one Swarm Buddy again (Diego) (#2500)

0xken15812c1d105997
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index 731e43e68..5e2d3412f 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -4825,6 +4825,47 @@ describe('swarm cards', () => {
} finally { await session.stop() }
})
+ // Review of #2500: with the window on # buddy (the Swarm's one Buddy chat, no project) the PM side had no project to open.
+ it('a swipe back to the PM side from the Swarm\'s Buddy chat, which names no project, opens the Lead chat of the project the dial has open, else the first', async () => {
+ const state = { cards: [card('st1', [withBuddy({ buddy: mine }), lead(2, { buddies: true, buddy: mine, chat: pmChat, sideChat: pmChat })])], open: { superTabId: 'st1', projectId: '', conversationId: 'pm1', fromDevice: false } }
+ const host = cardHost(state)
+ const { session, port } = await connect(host)
+ try {
+ port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toHaveLength(1), NEXT_TICKS)
+ // Already on the Buddy side: nothing to open.
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' }); await settle()
+ expect(host.superTabSelected).not.toHaveBeenCalled()
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'pm' }); await settle()
+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'pm']])
+ } finally { await session.stop() }
+ // The dial has the second project open: that one.
+ const second = cardHost({ cards: state.cards, open: { superTabId: 'st1', projectId: '', conversationId: 'pm1', fromDevice: false } })
+ const again = await connect(second)
+ try {
+ again.port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(again.port, 'supertab.focus')).toHaveLength(1), NEXT_TICKS)
+ again.port.say({ t: 'supertab.open', tab: 'st1', lead: 'lead2' }); await settle()
+ again.port.say({ t: 'supertab.side', tab: 'st1', side: 'pm' }); await settle()
+ expect(vi.mocked(second.superTabSelected!).mock.calls).toEqual([['st1', 'proj2', 'pm']])
+ } finally { await again.session.stop() }
+ })
+
+ // Second review of #2500: a DM or Chat with PM names no project either, but is not the Buddy chat: the swipe opens nothing.
+ it('a swipe to the PM side from a chat with no project that is not the reader\'s Buddy chat (a DM, Chat with PM) opens nothing', async () => {
+ for (const conversationId of ['dm1', undefined]) {
+ const cards = [card('st1', [withBuddy({ buddy: mine }), lead(2, { buddies: true, buddy: mine, chat: pmChat, sideChat: pmChat })])]
+ const host = cardHost({ cards, open: { superTabId: 'st1', projectId: '', ...(conversationId ? { conversationId } : {}), fromDevice: false } })
+ const { session, port } = await connect(host)
+ try {
+ port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toHaveLength(1), NEXT_TICKS)
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'pm' }); await settle()
+ expect(host.superTabSelected).not.toHaveBeenCalled()
+ } finally { await session.stop() }
+ }
+ })
+
it('the swipe follows the project the dial last picked in that Swarm', async () => {
const state = { cards: [card('st1', [withBuddy({ buddy: mine }), lead(2, { buddies: true, buddy: { ...mine, chatId: 'b2' } })])], open: onDesk() }
const host = cardHost(state)
@@ -4904,6 +4945,34 @@ describe('swarm cards', () => {
} finally { await session.stop() }
})
+ // Diego, 11-02: with one Buddy per Swarm every card of the Swarm carries the same Buddy session, so the tap found two
+ // claims and opened a terminal tile of its own (whose close stops the Buddy) instead of the Buddy chat.
+ it('a tap on the Swarm\'s one Buddy, which every card carries, opens its chat in the project the dial is on, else the first', async () => {
+ const shared = () => [withBuddy({ local: 'h-lead1', buddy: mine }), lead(2, { chat: pmChat, sideChat: pmChat, buddies: true, local: 'h-lead2', buddy: mine })]
+ const host = cardHost({ cards: [card('st1', shared())] })
+ const { session, port } = await connect(host)
+ try {
+ port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ port.say({ t: 'agent.open', agentId: 'h-buddy' }); await settle()
+ // The dial is now on project 1; a pick of project 2 moves it, and the Buddy opens there.
+ port.say({ t: 'supertab.select', tab: 'st1', lead: 'lead2' }); await settle()
+ port.say({ t: 'agent.open', agentId: 'h-buddy' }); await settle()
+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy'], ['st1', 'proj2'], ['st1', 'proj2', 'buddy']])
+ expect(host.openAgent).not.toHaveBeenCalled()
+ } finally { await session.stop() }
+ // The same Buddy session on the cards of two Swarms is still no one Swarm's.
+ const two = cardHost({ cards: [card('st1', shared()), card('st2', [lead(7, { buddies: true, buddy: mine })])] })
+ const second = await connect(two)
+ try {
+ second.port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(second.port, 'supertab')).toHaveLength(2))
+ second.port.say({ t: 'agent.open', agentId: 'h-buddy' }); await settle()
+ expect(two.superTabSelected).not.toHaveBeenCalled()
+ expect(vi.mocked(two.openAgent).mock.calls).toEqual([['h-buddy', undefined]])
+ } finally { await second.session.stop() }
+ })
+
it('a tap on the Buddy or a Lead opens its Swarm chat from any round dial, older ones too', async () => {
// A round dial from before swarmBuddy, and one from before the Swarm cards altogether (the core may still hold cards
// another device asked for): the tap is a round dial's, whatever its swipes can do (PM ruling, 10-30).
@@ -5007,6 +5076,29 @@ describe('swarm cards', () => {
}
})
+ // Review of #2500: with one Swarm Buddy, its one word badges every card; seeing the Buddy side clears them all.
+ it('showing the Buddy side reads the Swarm Buddy\'s notice on every card that shares it, and no other chat\'s', async () => {
+ const own = { ...buddyNotice('o1'), chatId: 'own-chat' }
+ const state = { cards: [card('st1', [withBuddy(), lead(2, { chat: pmChat, sideChat: buddyChat, buddies: true }), lead(3, { chat: pmChat, sideChat: buddyChat, buddies: true })])] }
+ const { session, port } = await connect(cardHost(state))
+ try {
+ port.say(BUDDY)
+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))
+ await settle(); await settle()
+ state.cards = [card('st1', [withBuddy({ buddyNotice: buddyNotice('b1') }), lead(2, { chat: pmChat, sideChat: buddyChat, buddies: true, buddyNotice: buddyNotice('b1') }),
+ lead(3, { chat: pmChat, sideChat: buddyChat, buddies: true, buddyNotice: own })])]
+ await session.syncSwarmCards()
+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice')).toHaveLength(3))
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' })
+ await vi.waitFor(() => expect(ofType(port, 'supertab.notice.read')).toHaveLength(2))
+ expect(ofType(port, 'supertab.notice.read')).toEqual([
+ { t: 'supertab.notice.read', tab: 'st1', lead: 'lead1', chatId: 'pm1' }, { t: 'supertab.notice.read', tab: 'st1', lead: 'lead2', chatId: 'pm1' }])
+ // Swiping again reads nothing twice; the Lead whose own chat spoke is still unread.
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' }); await settle(); await settle()
+ expect(ofType(port, 'supertab.notice.read')).toHaveLength(2)
+ } finally { await session.stop() }
+ })
+
it('asks recaps, opens and talks for the face on its side, and takes only the recaps of that face', async () => {
const swarmSay = vi.fn(async () => ({ said: true as const }))
const host = cardHost({ cards: [card('st1', [withBuddy()])] }, {
@@ -5294,6 +5386,18 @@ describe('swarm cards', () => {
expect(frame.leads.map((l) => l.buddy.name)).toEqual(Array(12).fill('é'.repeat(24)))
})
+ // Review of #2500: one Swarm Buddy is on all 12 Leads (the same chat id and name on each), at the longest ids a dial holds.
+ it('12 Leads that all carry the Swarm\'s one Buddy stay under 8192 bytes and the 512-token guard, and keep their Buddy block', async () => {
+ const shared = fullCards((kind, l) => `${kind}${'x'.repeat(44)}${String(l).padStart(2, '0')}`)
+ for (const l of shared[0].leads) l.buddy = { ...l.buddy!, chatId: `s${'x'.repeat(46)}`, local: undefined }
+ const frame = await sent(shared)
+ expect(frame.leads).toHaveLength(12)
+ expect(Buffer.byteLength(JSON.stringify(frame))).toBeLessThan(8192)
+ expect(tokens(frame)).toBeLessThan(512)
+ // Every Lead still tells the dial a Buddy exists; the Buddies' names may be cut, never the block.
+ expect(frame.leads.every((l) => 'buddy' in l)).toBe(true)
+ })
+
it('shortens the Buddies\' names, on a character, rather than send a frame the cable cannot carry', async () => {
// Every id at the 47 characters a dial holds: 8,211 bytes with whole names, and a frame over the cap closes the link.
const frame = await sent(fullCards((kind, l) => `${kind}${'x'.repeat(44)}${String(l).padStart(2, '0')}`))
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 3e7bf4229..81fe96381 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -1451,6 +1451,7 @@ export class CableSession {
if (this.swarmBuddy && CARD_ID.test(tab) && (side === 'pm' || side === 'buddy')) {
this.host.swarmCardSide?.(tab, side)
this.followSide(tab, side)
+ if (side === 'buddy') this.queued(() => this.readSharedBuddyNotices(tab)).catch((err) => this.log(`cable: Buddy notices not cleared (${(err as Error).message})`))
}
return
}
@@ -2917,6 +2918,23 @@ export class CableSession {
for (const key of [...this.notices.keys()]) if (!live.has(key)) this.notices.delete(key)
}
+ /**
+ * The dial showed the Buddy side of a Swarm. The reader's one Swarm Buddy speaks on every card, so one word badged them
+ * all, and the dial clears only the Lead it shows (review of #2500): the others' badges for the same chat are read here,
+ * so seeing the Buddy once is reading it once. A chat only one Lead's notice names (an older Swarm's own) is left alone.
+ */
+ private async readSharedBuddyNotices(tab: string): Promise<void> {
+ const leads = this.host.swarmCards?.()?.find((c) => c.id === tab)?.leads.slice(0, SWARM_LEADS_MAX) ?? []
+ for (const lead of leads) {
+ const notice = lead.buddyNotice
+ if (!notice || leads.filter((l) => l.buddyNotice?.chatId === notice.chatId).length < 2) continue
+ const held = this.notices.get(`${tab}:${lead.id}:buddy`)
+ if (!held?.open || held.id !== notice.id) continue
+ held.open = false
+ await this.send({ t: 'supertab.notice.read', tab, lead: lead.id, chatId: notice.chatId })
+ }
+ }
+
/** One alert of a Lead (held at `key`): sent once when it is new, unless replayed or read on the desktop (`openChat`, the
* conversation the window has open in that Swarm); read on the dial once the desktop opens the chat of one it was sent. */
private async pushNotice(key: string, tab: string, lead: string, notice: LeadNotice | undefined, replay: boolean, openChat: string | undefined): Promise<void> {
@@ -3046,10 +3064,22 @@ export class CableSession {
* guessed; a Buddy side where the reader has no Buddy opens nothing, so no Buddy chat is made from a swipe.
*/
private followSide(tab: string, side: CardSide): void {
- const [focusedTab, projectId] = this.focusedKey.split('/')
- if (focusedTab !== tab || !projectId) return
+ const [focusedTab, focusedProject] = this.focusedKey.split('/')
+ if (focusedTab !== tab) return
const card = this.host.swarmCards?.()?.find((c) => c.id === tab)
- if (!card?.leads.some((l) => l.projectId === projectId)) return
+ // The window is on the Swarm's one Buddy chat, which names no project (# buddy): the Buddy side is already open, and the
+ // PM side opens the Lead chat of the project the dial has open, else its first, so the dial is not stranded on # buddy
+ // (review of #2500). The Buddy side there asks for nothing. Only that chat: a DM or Chat with PM names no project either,
+ // and a swipe from one of them opens nothing, as before (second review of #2500).
+ let projectId = focusedProject
+ const window = this.host.activeSwarmProject?.()
+ const onBuddy = window?.superTabId === tab && window.conversationId !== undefined
+ && card?.leads.some((l) => l.buddies === true && l.buddy?.chatId === window.conversationId) === true
+ if (!projectId && side === 'pm' && card && onBuddy) {
+ const shown = this.openLead?.tabId === tab ? card.leads.find((l) => l.id === this.openLead?.leadId) : undefined
+ projectId = (shown ?? card.leads[0])?.projectId
+ }
+ if (!projectId || !card?.leads.some((l) => l.projectId === projectId)) return
if (side === 'buddy' && !this.buddyIn(card, projectId)) return
this.openSwarmChat(tab, projectId, side)
}
@@ -3070,7 +3100,15 @@ export class CableSession {
if (lead.buddies && lead.buddy?.local === agentId) found.push({ tab: card.id, projectId: lead.projectId, chat: 'buddy' })
}
}
- return found.length === 1 ? found[0] : null
+ if (found.length === 1) return found[0]
+ // The reader's one Swarm Buddy is every project's Buddy, so its session is on each card of its Swarm: a tap on it opens
+ // the chat in the project the dial is on, else the first. Two sessions of different Swarms, or a Lead beside it, stay
+ // ambiguous, as before.
+ const [first] = found
+ if (first?.chat === 'buddy' && found.every((f) => f.chat === 'buddy' && f.tab === first.tab)) {
+ return found.find((f) => `${f.tab}/${f.projectId}` === this.focusedKey) ?? first
+ }
+ return null
}
// ── swarms ────────────────────────────────────────────────────────────────────────────────────────
diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.ts
index 0d2cb08c1..69e3f2741 100644
--- a/cli/src/superTabs/cards.spec.ts
+++ b/cli/src/superTabs/cards.spec.ts
@@ -1261,3 +1261,186 @@ describe('SwarmCards Buddy notices', () => {
expect(t.webLead()).not.toHaveProperty('buddyNotice')
})
})
+
+// Diego, 11-02: "the round dial no longer shows the Buddy screen when I pull down". Since One Buddy per Swarm (#2447) the
+// reader's Buddy chat belongs to the Swarm (kind swarm-buddy, no project), and the cards looked for one in each project.
+describe('one Buddy per Swarm', () => {
+ /** The reader's one chat for the Swarm, as the backend sends it (buddies.ts openSwarmBuddyChat, read/views.ts groupView). */
+ const sb = (over: Record<string, unknown> = {}) => conv('sb', null, { projectId: undefined, kind: 'swarm-buddy', buddyOwnerId: 'me', agentIds: ['y1'], ...over })
+ const one = (over: Record<string, unknown> = {}) => chats({ buddies: true, agents: [...chats().agents as object[], buddy({ buddyScope: 'swarm' })],
+ conversations: [...swarm().conversations, sb(), group()], ...over })
+ const lead = (state: Record<string, unknown>, project = 'web', focus?: string, side?: 'pm' | 'buddy') =>
+ leadsOf(state, 'm1', idle, 'me', focus, side).leads.find(l => l.projectId === project)!
+ const inLead = { kind: 'lead', id: 'lead-web', name: 'Lead', working: false }
+
+ it('gives every project\'s card the reader\'s one Buddy, and the Buddy side shows its chat', () => {
+ const block = { chatId: 'sb', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true, local: 'h-y1' }
+ for (const project of ['web', 'mobile']) {
+ expect(lead(one(), project).buddy).toEqual(block)
+ expect(lead(one(), project, undefined, 'buddy').sideChat).toEqual({ kind: 'buddy', id: 'sb', name: "diego's Buddy", working: false })
+ }
+ // The PM side and an older dial's face are the project's Lead, as before: the Swarm chat is no project's PM line.
+ expect(lead(one()).sideChat).toEqual(inLead)
+ expect(lead(one(), 'web', undefined, 'buddy').chat).toEqual(inLead)
+ })
+
+ it('prefers the Swarm chat over an older Buddy chat of the project, and falls back to it when the Swarm chat is gone', () => {
+ const both = one({ conversations: [...swarm().conversations, pm({ agentIds: ['y1'] }), sb(), group()] })
+ expect(lead(both).buddy).toMatchObject({ chatId: 'sb' })
+ expect(lead(both, 'web', undefined, 'buddy').sideChat).toMatchObject({ kind: 'buddy', id: 'sb' })
+ // Archived: the older chat of the project is what an older Swarm keeps, and the other project has none.
+ const archived = one({ conversations: [...swarm().conversations, pm({ agentIds: ['y1'] }), sb({ archived: true }), group()] })
+ expect(lead(archived).buddy).toMatchObject({ chatId: 'pm-web' })
+ expect(lead(archived, 'mobile')).not.toHaveProperty('buddy')
+ })
+
+ it('leaves an older Swarm as it was: the Buddy chat of each project, none for a project without one', () => {
+ const older = chats({ buddies: true, agents: [...chats().agents as object[], buddy()], conversations: [...swarm().conversations, pm({ agentIds: ['y1'] }), group()] })
+ expect(lead(older).buddy).toMatchObject({ chatId: 'pm-web' })
+ expect(lead(older, 'mobile')).not.toHaveProperty('buddy')
+ })
+
+ it('marks no Buddy while Buddies are off, with nobody signed in, or for a chat whose id the dial cannot hold', () => {
+ expect(lead(one({ buddies: undefined }))).not.toHaveProperty('buddy')
+ expect(leadsOf(one(), 'm1', idle, undefined).leads[0]).not.toHaveProperty('buddy')
+ const long = one({ conversations: [...swarm().conversations, sb({ id: 's'.repeat(48) }), group()] })
+ expect(lead(long)).not.toHaveProperty('buddy')
+ })
+
+ // Privacy: the backend sends a Buddy chat to its owner alone, and the dial checks again.
+ it('never takes another person\'s Swarm chat or Buddy, whatever a read holds or the window has open', () => {
+ const sams = one({ agents: [...chats().agents as object[], buddy({ buddyOf: { personId: 'sam', generation: 'g2' }, buddyScope: 'swarm' })],
+ conversations: [...swarm().conversations, sb({ buddyOwnerId: 'sam' }), group()] })
+ for (const side of [undefined, 'pm', 'buddy'] as const) {
+ const l = lead(sams, 'web', 'sb', side)
+ expect([l.chat, l.sideChat]).toEqual([inLead, inLead])
+ expect(l).not.toHaveProperty('buddy')
+ }
+ // Sam's Buddy listed in the reader's own chat (an agent id reused or misfiled) is not the reader's, and the block never
+ // carries its name or avatar.
+ const misfiled = one({ agents: [...chats().agents as object[], buddy({ buddyOf: { personId: 'sam', generation: 'g2' }, displayName: 'Sam secret' })] })
+ expect(lead(misfiled)).not.toHaveProperty('buddy')
+ expect(lead(misfiled, 'web', undefined, 'buddy').sideChat).toEqual({ kind: 'buddy', id: 'sb', name: 'Buddy', working: false })
+ expect(JSON.stringify(leadsOf(misfiled, 'm1', idle, 'me', undefined, 'buddy'))).not.toContain('Sam secret')
+ // A thread session of the reader's Buddy is not "the Buddy", and an agent id reused in a project chat is not either.
+ const session = agent('y1', { buddyOf: { personId: 'me', generation: 'g1' }, buddySession: { thread: 'r', from: 1 }, name: 'Thread' })
+ expect(lead(one({ agents: [...chats().agents as object[], session] }))).not.toHaveProperty('buddy')
+ })
+
+ it('does not take the Swarm chat for a project chat of the dial\'s older face', () => {
+ // The Swarm chat has no project: an older dial's face (the window open on it) stays the project's Lead, never `pm`.
+ expect(lead(one(), 'web', 'sb').chat).toEqual(inLead)
+ expect(lead(one(), 'mobile', 'sb').chat).toMatchObject({ kind: 'lead', id: 'lead-mobile' })
+ })
+})
+
+describe('SwarmCards with one Buddy per Swarm', () => {
+ const sb = (seq = 1) => conv('sb', null, { projectId: undefined, kind: 'swarm-buddy', buddyOwnerId: 'me', agentIds: ['y1'], lastMessageSequence: seq })
+ const state = (seq = 1, over: Record<string, unknown> = {}) => chats({ buddies: true, agents: [...chats().agents as object[], buddy({ buddyScope: 'swarm' })],
+ conversations: [...swarm().conversations, sb(seq), group()], ...over })
+ const hears = [said(1, 'a1', { text: 'from the PM' }), said(2, 'y1', { text: 'from the Buddy' }), said(3, 'me', { author: { kind: 'person', id: 'me' }, text: 'mine' })]
+ const build = (pages: Record<string, unknown[]> = { sb: hears }) => {
+ const t = setup({ t1: { lastChangedAt: 1, state: state() } }, { messages: path => ({ messages: pages[/conversations\/([^/]+)\/messages/.exec(path)?.[1] ?? ''] ?? [], next: null }) })
+ const lead = (id: string, cards = t.seen.at(-1)) => cards?.[0].leads.find(l => l.id === id)
+ const reads = () => t.calls.filter(c => c.includes('/conversations/sb/messages')).length
+ const move = async (seq: number, over: Record<string, unknown> = {}) => { t.tabs.t1.lastChangedAt++; t.tabs.t1.state = state(seq, over); await t.cards.tick() }
+ return { ...t, lead, reads, move }
+ }
+
+ it('recaps the Buddy side from the Swarm chat\'s Buddy voice, and speaks to the Swarm chat, from any project', async () => {
+ const t = build()
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.side('t1', 'buddy')
+ for (const lead of ['a1', 'a2']) {
+ expect(t.lead(lead)?.sideChat).toMatchObject({ kind: 'buddy', id: 'sb' })
+ expect(await t.cards.recap('t1', lead, 'buddy')).toEqual({ tabId: 't1', leadId: lead, text: 'from the Buddy', at: saidAt, none: false, chatId: 'sb', buddy: true })
+ }
+ expect(await t.cards.say('h-a2', 'hello Buddy', 'buddy')).toEqual({ said: true })
+ expect((t.call.mock.calls.find(c => c[0] === 'POST')![2] as { command: { conversationId: string } }).command.conversationId).toBe('sb')
+ t.cards.want(false)
+ })
+
+ it('shows the Buddy side when the window opens the Swarm chat, and the PM side after a swipe back', async () => {
+ const t = build()
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.want(true, [], { tabId: 't1', conversationId: 'sb' })
+ expect(t.seen.at(-1)?.[0].side).toBe('buddy')
+ expect(t.lead('a1')?.sideChat).toMatchObject({ kind: 'buddy', id: 'sb' })
+ expect(t.lead('a1')?.chat).toMatchObject({ kind: 'lead' })
+ t.cards.side('t1', 'pm')
+ expect(t.lead('a1')?.sideChat).toMatchObject({ kind: 'lead' })
+ t.cards.want(false)
+ })
+
+ it('notices the Buddy\'s new word on every project\'s card from one read, and keeps the baseline when that read fails', async () => {
+ const t = build()
+ await t.cards.tick()
+ await t.cards.tick()
+ expect(t.reads()).toBe(0)
+ expect(t.lead('a1')).not.toHaveProperty('buddyNotice')
+ await t.move(3)
+ for (const lead of ['a1', 'a2']) expect(t.lead(lead)?.buddyNotice).toEqual({ chat: 'buddy', chatId: 'sb', id: 'x2', text: 'from the Buddy', at: saidAt })
+ expect(t.reads()).toBe(1)
+ // The Swarm chat is no Lead's private line: the Lead's own notice is not raised from it.
+ expect(t.lead('a1')).not.toHaveProperty('notice')
+ })
+
+ it('a failed read of the Swarm chat keeps the baseline, is logged once and is tried again at the next poll', async () => {
+ const t = build({ sb: [...hears, said(5, 'y1', { text: 'later' })] })
+ await t.cards.tick()
+ const served = t.call.getMockImplementation()!
+ t.call.mockImplementation(async (method, path, body) => {
+ if (path.includes('/conversations/sb/messages')) throw new Error('offline')
+ return served(method, path, body)
+ })
+ await t.move(5)
+ await t.move(5)
+ expect(t.log).toHaveBeenCalledTimes(1)
+ expect(t.lead('a1')).not.toHaveProperty('buddyNotice')
+ t.call.mockImplementation(served)
+ await t.move(5)
+ expect(t.lead('a1')?.buddyNotice).toMatchObject({ chatId: 'sb', text: 'later' })
+ })
+
+ it('drops the notice with the chat when access to the Swarm chat goes, and never reads another person\'s', async () => {
+ const t = build()
+ await t.cards.tick()
+ await t.move(3)
+ expect(t.lead('a1')?.buddyNotice).toBeDefined()
+ // The chat leaves the reader's rows (the membership ended): nothing of it is kept.
+ await t.move(3, { conversations: [...swarm().conversations, group()] })
+ expect(t.lead('a1')).not.toHaveProperty('buddyNotice')
+ expect(t.lead('a1')).not.toHaveProperty('buddy')
+ // Another person's Swarm chat moving is never read.
+ const readsBefore = t.reads()
+ await t.move(9, { conversations: [...swarm().conversations, { ...sb(9), buddyOwnerId: 'sam' }, group()] })
+ await t.move(10, { conversations: [...swarm().conversations, { ...sb(10), buddyOwnerId: 'sam' }, group()] })
+ expect(t.reads()).toBe(readsBefore)
+ expect(t.lead('a1')).not.toHaveProperty('buddyNotice')
+ })
+
+ it('refuses a recap or a word for the Swarm chat once it stops being the reader\'s while the read is out, and for a stale or foreign chat id', async () => {
+ const t = build()
+ t.cards.want(true, [], null)
+ await vi.waitFor(() => expect(t.seen).toHaveLength(1))
+ t.cards.side('t1', 'buddy')
+ // The read is out when the chat is replaced by Sam's: the answer is neither given nor kept.
+ t.call.mockImplementationOnce(async () => {
+ t.tabs.t1.state = state(1, { conversations: [...swarm().conversations, { ...sb(), buddyOwnerId: 'sam' }, group()] })
+ t.cards.side('t1', 'pm')
+ return { status: 200, body: { success: true, data: { messages: hears, next: null } } }
+ })
+ expect(await t.cards.recap('t1', 'a1', 'buddy')).toMatchObject({ none: true, text: '' })
+ // Words reviewed for a chat id that is not on this project's face are refused alike for Sam's chat, a private chat and a stranger.
+ t.tabs.t1.lastChangedAt++
+ t.tabs.t1.state = state(1, { conversations: [...swarm().conversations, { ...sb(), buddyOwnerId: 'sam' }, conv('priv-1', null, { projectId: 'mobile', audience: { people: [{ id: 'sam' }] } }), group()] })
+ await t.cards.tick()
+ for (const chatId of ['sb', 'priv-1', 'nope']) {
+ expect(await t.cards.say('h-a1', 'secret', 'buddy', chatId, true)).toEqual({ said: false, refused: { code: 'CHAT_MOVED', message: expect.any(String) } })
+ }
+ expect(t.call.mock.calls.filter(c => c[0] === 'POST')).toHaveLength(0)
+ t.cards.want(false)
+ })
+})
diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.ts
index 0e1d5b53d..e10fc1835 100644
--- a/cli/src/superTabs/cards.ts
+++ b/cli/src/superTabs/cards.ts
@@ -48,7 +48,11 @@ const list = (v: unknown): Json[] => Array.isArray(v) ? v.map(object) : []
const projectKey = (project: Json): string => String(project.id ?? 'lead')
const inProject = (conversation: Json, projectId: string): boolean => (conversation.projectId ?? 'lead') === projectId
/** A Buddy chat (backend buddies.ts), where the PM's private lines land since Buddies replaced Chat with PM (10-29). */
-const isBuddyChat = (conversation: Json): boolean => conversation.kind === 'buddy'
+const isBuddyChat = (conversation: Json): boolean => conversation.kind === 'buddy' || conversation.kind === 'swarm-buddy'
+/** A person's one Buddy chat for the whole Swarm (backend buddies.ts, Dee 10-31): it has no project, so no project's id
+ * finds it. Since #2447 it is where the reader's Buddy lives, and a card that looked only in its own project lost the
+ * dial's Buddy side (Diego, 11-02). */
+const isSwarmBuddyChat = (conversation: Json): boolean => conversation.kind === 'swarm-buddy'
/** A Chat with PM: a private conversation with an audience that is not a Buddy chat. Read-only once Buddies are on
* (backend commands.ts `PM_CHAT_READ_ONLY`), so words spoken to it on the dial would only be refused. */
const isChatWithPm = (conversation: Json): boolean => conversation.audience != null && !isBuddyChat(conversation)
@@ -59,9 +63,12 @@ const isReadersBuddyChat = (conversation: Json, me: string | undefined): boolean
const sequenceOf = (conversation: Json): number => typeof conversation.lastMessageSequence === 'number' ? conversation.lastMessageSequence : 0
const idsOf = (v: unknown): string[] => Array.isArray(v) ? v.filter((id): id is string => typeof id === 'string') : []
-/** The reader's live Buddy chat in a project, when its id is one a dial can hold. */
+/** The reader's live Buddy chat for a project, when its id is one a dial can hold: their one Swarm Buddy chat when the Swarm
+ * has given them one (every project shares it), else their Buddy chat in that project, as older Swarms keep it. Another
+ * person's chat is neither, whatever a read holds. */
function buddyChatOf(conversations: Json[], projectId: string, me: string | undefined): Json | undefined {
- return conversations.find(c => isReadersBuddyChat(c, me) && inProject(c, projectId) && c.archived !== true && cardId(c.id))
+ const live = (c: Json) => isReadersBuddyChat(c, me) && c.archived !== true && cardId(c.id)
+ return conversations.find(c => isSwarmBuddyChat(c) && live(c)) ?? conversations.find(c => !isSwarmBuddyChat(c) && inProject(c, projectId) && live(c))
}
/** The reader's Buddies in their chat: the chat's agents that are a Buddy of the reader. One whose `buddyOf` names someone
* else (an agent id reused or misfiled) is not, and neither is a thread session (spec 2026-10-30-buddy-thread-sessions),
@@ -445,10 +452,35 @@ export class SwarmCards {
const watched = new Set<string>()
for (const [tabId, { state }] of this.tabs) {
const conversations = list(state.conversations), agents = list(state.agents), buddies = state.buddies === true
- for (const { project, lead, leadId } of leadProjects(state)) {
+ const projects = leadProjects(state)
+ // The reader's one Swarm Buddy chat is every project's Buddy: read once per poll (its key is the chat's), and its newest
+ // word is the quiet notice of each Lead alike. A project's own Buddy chat (older Swarms) is that project's alone.
+ const swarmChat = buddies ? conversations.find(c => isSwarmBuddyChat(c) && isReadersBuddyChat(c, this.me) && c.archived !== true && cardId(c.id)) : undefined
+ if (swarmChat && typeof swarmChat.lastMessageSequence === 'number') {
+ const key = `${tabId}:${swarmChat.id}`, sequence = swarmChat.lastMessageSequence, baseline = this.seen.get(key)
+ watched.add(key)
+ if (baseline === undefined) this.seen.set(key, sequence)
+ else if (sequence > baseline && this.recapsRunning < MAX_RECAPS_IN_FLIGHT) {
+ this.recapsRunning++
+ 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)
+ this.seen.set(key, sequence)
+ this.failed.delete(key)
+ } catch (error) {
+ if (!this.failed.has(key)) {
+ this.failed.add(key)
+ this.log(`[super-tabs] the Buddy's new message could not be read for the dial; tried again at the next poll: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ } finally { this.recapsRunning-- }
+ }
+ }
+ for (const { project, lead, leadId } of projects) {
const projectId = projectKey(project)
const chats: Array<{ conversation: Json; chat: 'lead' | 'pm' }> = [{ conversation: lead, chat: 'lead' },
- ...conversations.filter(c => inProject(c, projectId) && isReadersBuddyChat(c, this.me) && c.archived !== true).map(conversation => ({ conversation, chat: 'pm' as const }))]
+ ...conversations.filter(c => !isSwarmBuddyChat(c) && inProject(c, projectId) && isReadersBuddyChat(c, this.me) && c.archived !== true).map(conversation => ({ conversation, chat: 'pm' as const }))]
for (const { conversation, chat } of chats) {
if (!cardId(conversation.id) || typeof conversation.lastMessageSequence !== 'number') continue
const key = `${tabId}:${conversation.id}`, sequence = conversation.lastMessageSequence
@@ -600,7 +632,8 @@ export class SwarmCards {
if (!found) return false
if (found.lead.id === chatId) return true
const c = list(state.conversations).find(c => c.id === chatId)
- return !!c && cardId(c.id) && inProject(c, projectKey(found.project)) && c.archived !== true && (!isBuddyChat(c) || isReadersBuddyChat(c, this.me))
+ return !!c && cardId(c.id) && c.archived !== true && (isSwarmBuddyChat(c) ? isReadersBuddyChat(c, this.me)
+ : 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. */
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 00d7db8ca..fc5e8c463 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -4680,9 +4680,17 @@ class AppNotifier extends ChangeNotifier {
.firstOrNull;
if (project == null) return;
// Only an existing chat of the reader's own: a device never makes one.
- if (buddy && controller.buddyChat(projectId) != null) {
+ // Where the Swarm gives one Buddy per person, that is their Swarm chat
+ // (# buddy, which names no project), whichever project the dial is on;
+ // an earlier project chat there is history (Diego, 11-02).
+ final buddyKey =
+ controller.oneBuddy &&
+ controller.buddyChat(SuperTabController.kSwarmBuddyKey) != null
+ ? SuperTabController.kSwarmBuddyKey
+ : projectId;
+ if (buddy && controller.buddyChat(buddyKey) != null) {
await (controller.buddyChatOpener ?? controller.openBuddyChat)(
- projectId,
+ buddyKey,
);
if (_disposed || _devicePick != pick) return;
} else {
diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dart
index f63918493..f13db38d4 100644
--- a/desktop/test/super_tab_dial_test.dart
+++ b/desktop/test/super_tab_dial_test.dart
@@ -314,6 +314,67 @@ void main() {
expect(row(after.last)['conversationId'], 'design-lead');
});
+ // Diego, 11-02: with one Buddy per Swarm the reader's Buddy chat is the
+ // Swarm's (kind swarm-buddy, no project). The dial's Buddy side, a swipe or a
+ // tap on its Buddy used to look for a chat of the project and land on the
+ // earlier project chat (history) or the Lead chat.
+ Future<(SuperTabLaunchFixture, SuperTabController)> openOneBuddy() async {
+ final (f, c) = await openChats();
+ final server = f.connection.server;
+ server.state['swarmBuddy'] = true;
+ (server.state['conversations'] as List).add(
+ {
+ ...conversationFixture('swarm-buddy-owner', "owner's Buddy"),
+ 'kind': 'swarm-buddy',
+ 'buddyOwnerId': 'owner',
+ }..remove('projectId'),
+ );
+ await c.refresh();
+ return (f, c);
+ }
+
+ test('with one Buddy per Swarm the dial\'s Buddy side opens the Swarm chat, from any project, never the earlier project chat', () async {
+ final (f, c) = await openOneBuddy();
+ expect(c.oneBuddy, isTrue);
+ for (final project in ['design', 'lead']) {
+ c.select('design-fix');
+ await settle();
+ await follow(f, project, 'buddy');
+ await settle();
+ expect(c.selectedId, 'swarm-buddy-owner');
+ }
+ // Back to the PM side from there: the project's Lead chat.
+ await follow(f, 'design', 'pm');
+ await settle();
+ expect(c.selectedId, 'design-lead');
+ });
+
+ test('another person\'s Swarm Buddy chat is never opened, and the Lead chat opens instead', () async {
+ final (f, c) = await openOneBuddy();
+ final server = f.connection.server;
+ for (final row in (server.state['conversations'] as List).cast<Map>()) {
+ if (row['kind'] == 'swarm-buddy') row['buddyOwnerId'] = 'sam';
+ }
+ (server.state['conversations'] as List).removeWhere(
+ (row) => (row as Map)['id'] == 'design-pm',
+ );
+ await c.refresh();
+ await follow(f, 'design', 'buddy');
+ await settle();
+ expect(c.selectedId, 'design-lead');
+ });
+
+ test(
+ 'an older Swarm keeps the project\'s Buddy chat for the dial\'s Buddy side',
+ () async {
+ final (f, c) = await openChats();
+ expect(c.oneBuddy, isFalse);
+ await follow(f, 'design', 'buddy');
+ await settle();
+ expect(c.selectedId, 'design-pm');
+ },
+ );
+
test('a Buddy side where the reader has no Buddy chat opens the Lead chat and makes none', () async {
final (f, c) = await openChats();
final server = f.connection.server;