The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Round dial: the desktop follows the dial into Buddy chats (#2269)
harness-for-autonomous[bot]a270d3e787ae
diff --git a/cli/e2e/dialBuddyChat.e2e.ts b/cli/e2e/dialBuddyChat.e2e.tsnew file mode 100644index 000000000..9da8a414d--- /dev/null+++ b/cli/e2e/dialBuddyChat.e2e.ts@@ -0,0 +1,125 @@+/**+ * The desktop follows the round dial into Buddy chats (Diego, 10-30), end to end: the real daemon on a throwaway home, a+ * fake backend serving one Swarm whose reader has a Buddy running on this machine, a fake round dial that speaks the Swarm+ * cards and Buddy screens on a pseudo-terminal, and a window on the local socket. The cards travel the production path,+ * read by the Super Tab service, checked on their way into the core and handed to the devices process, which once lost+ * the Buddy's session id there and left a tap on its notification opening a terminal tab. What the window is told is+ * checked: the Buddy chat for the Buddy side and the Buddy's tap, the Lead chat for the PM side, a tile for any other agent,+ * and the Buddy's session id never on the cable.+ */+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { afterEach, expect, it, onTestFailed } from 'vitest'+import { LocalClient } from './harness/client.js'+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'+import { FakeDial, type DialMessage } from './harness/fakeDial.js'+import { overOldRoutes } from './harness/swarmReads.js'++const ME: FakeMachine = { machineId: 'c9'.repeat(16), computerId: 'e2e-dial-buddy-computer', name: 'Fixture', token: 'e2e-dial-buddy-token' }+const TAB = 'dial-buddy-tab'+const PERSON = { id: 'person-me', email: '[email protected]' }+const ROUND = { swarmCard: 'v1', superTab: 'wait-v1', swarmChat: 'v1', swarmBuddy: 'v1' }++let daemon: IsolatedDaemon | undefined, backend: FakeBackend | undefined, dial: FakeDial | undefined+const clients: LocalClient[] = []+afterEach(async () => {+ clients.splice(0).forEach((client) => client.close())+ await daemon?.close(); daemon = undefined+ await dial?.close(); dial = undefined+ await backend?.close(); backend = undefined+})++it('opens the Buddy chat for the Buddy side and the Buddy\'s tap, the Lead chat for the PM side, and a tile for any other agent', async () => {+ const relay = await FakeBackend.start(); backend = relay; relay.addMachine(ME); relay.me = PERSON+ const device = await FakeDial.open({ capabilities: ROUND }); dial = device+ const d = await IsolatedDaemon.create({ env: {+ CABLE_DISABLE: 'false', HARNESSD_TEST_DIAL_PORT: device.path,+ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: ME.computerId,+ ANTHROPIC_API_KEY: 'fixture-not-a-credential', OPENAI_API_KEY: 'fixture-not-a-credential',+ } }); daemon = d+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))+ writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({ version: 1, accessToken: ME.token,+ autonomousEnv: 'prod', computerId: ME.computerId, machineId: ME.machineId,+ expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',+ }), { mode: 0o600 })+ onTestFailed(() => {+ console.log(`---- daemon log\n${d.log().split('\n').slice(-160).join('\n')}`)+ console.log(`---- the dial heard\n${device.messages.map((m) => m.t).join(' ')}`)+ console.log(`---- backend saw\n${relay.seen.slice(-40).join('\n')}`)+ })+ await d.start()+ // A signed-in daemon serves under its account's machine id.+ const window = await LocalClient.connect(d, { machineId: ME.machineId }); clients.push(window)++ // Two agents here: the reader's Buddy, and an ordinary one the Swarm does not know.+ const create = async (folder: string): Promise<string> => {+ const cwd = join(d.projectsDir, folder)+ mkdirSync(cwd, { recursive: true })+ const created = await window.request('agent_create', { engine: 'claude', cwd, bypassPermission: true }, 90_000)+ expect(created.error, JSON.stringify(created)).toBeUndefined()+ const id = created.agent.id as string+ await until(`${folder} to bind`, async () => ((await window.request('agents_list', {})).agents as Array<Record<string, unknown>>)+ .find((agent) => agent.id === id)?.sessionId || null, 60_000, 500)+ return id+ }+ const buddyHarness = await create('buddy'), ordinary = await create('ordinary')++ // The Swarm: one project, its Lead on another machine, and the reader's Buddy chat with the Buddy running here.+ const state = {+ name: 'Dial Buddy', paused: false, ownerId: PERSON.id, buddies: true, people: [{ id: PERSON.id, email: PERSON.email }],+ projects: [{ id: 'web', name: 'web', leadConversationId: 'lead-web' }],+ agents: [+ { id: 'lead1', harnessId: 'lead-harness', machineId: 'd0'.repeat(16), machineOwnerId: PERSON.id, configuration: { engine: 'claude' } },+ { id: 'buddy1', name: "me's Buddy", harnessId: buddyHarness, machineId: ME.machineId, machineOwnerId: PERSON.id,+ projectId: 'web', buddyOf: { personId: PERSON.id, generation: 'g1' }, configuration: { engine: 'claude' } },+ ],+ conversations: [+ { id: 'lead-web', projectId: 'web', leadId: 'lead1', archived: false, assignment: null, lastMessageSequence: 0 },+ { id: 'buddy-web', projectId: 'web', kind: 'buddy', buddyOwnerId: PERSON.id, agentIds: ['buddy1'], leadId: null, archived: false, assignment: null, lastMessageSequence: 0 },+ ],+ }+ relay.superTabs = overOldRoutes(async (method, raw) => {+ const path = new URL(raw, relay.httpUrl).pathname+ if (method !== 'GET') return { status: 404, error: { code: 'NOT_FOUND', message: 'Not in this fixture.' } }+ if (path.startsWith(`/api/super-tabs/hosts/${ME.machineId}`)) return { data: [] }+ if (path === '/api/super-tabs') return { data: { tabs: [{ id: TAB, name: state.name, revision: 1 }], next: null } }+ if (path === `/api/super-tabs/${TAB}`) return { data: { state, revision: 1 } }+ if (path.startsWith(`/api/super-tabs/${TAB}/`)) return { data: { messages: [], conversations: [] } }+ return { status: 404, error: { code: 'NOT_FOUND', message: 'Not in this fixture.' } }+ })++ await device.greet()+ const cards = await device.next((m) => m.t === 'supertab' && Array.isArray(m.leads) && (m.leads as DialMessage[]).some((l) => l.buddy), 60_000, 'the Swarm card with its Buddy')+ // The Buddy's session id stays on this computer: no frame to the dial carries it.+ expect(JSON.stringify(device.messages)).not.toContain(buddyHarness)+ expect(cards.id).toBe(TAB)++ const told = (since: number) => window.frames.slice(since).filter((f) => f.type === 'dial_super_tab' || f.type === 'dial_open')+ // The dial picks the project, swipes to the Buddy side, and back to the PM.+ let since = window.frames.length+ device.send({ t: 'supertab.select', tab: TAB, lead: 'lead1' })+ await window.waitFor((f) => f.type === 'dial_super_tab', 15_000, 'the pick', since)+ since = window.frames.length+ device.send({ t: 'supertab.side', tab: TAB, side: 'buddy' })+ await window.waitFor((f) => f.type === 'dial_super_tab', 15_000, 'the Buddy side', since)+ expect(told(since).map((f) => f.payload)).toEqual([{ superTabId: TAB, projectId: 'web', chat: 'buddy' }])+ since = window.frames.length+ device.send({ t: 'supertab.side', tab: TAB, side: 'pm' })+ await window.waitFor((f) => f.type === 'dial_super_tab', 15_000, 'the PM side', since)+ expect(told(since).map((f) => f.payload)).toEqual([{ superTabId: TAB, projectId: 'web', chat: 'pm' }])++ // A tap on the Buddy's notification: its chat in the Swarm tab, and no tile.+ since = window.frames.length+ device.send({ t: 'agent.open', agentId: buddyHarness })+ await window.waitFor((f) => f.type === 'dial_super_tab' || f.type === 'dial_open', 15_000, 'the Buddy\'s tap', since)+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect(told(since).map((f) => [f.type, f.payload])).toEqual([['dial_super_tab', { superTabId: TAB, projectId: 'web', chat: 'buddy' }]])++ // Any other agent: a tile, as today.+ since = window.frames.length+ device.send({ t: 'agent.open', agentId: ordinary })+ await window.waitFor((f) => f.type === 'dial_open', 15_000, 'the ordinary tap', since)+ await new Promise((resolve) => setTimeout(resolve, 500))+ expect(told(since).map((f) => [f.type, f.payload?.agentId])).toEqual([['dial_open', ordinary]])+})diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.tsindex d0dab77df..299cd8b51 100644--- a/cli/e2e/harness/fakeBackend.ts+++ b/cli/e2e/harness/fakeBackend.ts@@ -108,6 +108,8 @@ export class FakeBackend {superTabs: ((method: string, path: string, body: Record<string, any>, machine: FakeMachine) => Promise<{status?: number; data?: unknown; error?: { code: string; message: string }}>) | null = null+ /** What `GET /api/auth/me` answers: the signed-in person; null, a 404 as before. */+ me: { id: string; email: string } | null = null/** Opt-in fixture: older scenarios keep the endpoint absent, as on an older backend. */productUsage: { enabled: boolean; revision: number; reports: Record<string, unknown>[]; stallReports?: boolean } | null = null/** `POST /api/route/jev`, Harness's hosted Jev. Unset answers 503 JEV_BUSY, which callers treat as unavailable. */@@ -175,6 +177,9 @@ export class FakeBackend {})return}+ if (backend.me && req.method === 'GET' && req.url?.split('?')[0] === '/api/auth/me') {+ res.end(json({ success: true, data: { user: backend.me } })); return+ }const usage = backend.productUsageif (usage && req.url === '/api/product-usage/settings' && req.method === 'GET') {res.end(json({ success: true, data: { enabled: usage.enabled, revision: usage.revision } })); returndiff --git a/cli/e2e/harness/fakeDial.ts b/cli/e2e/harness/fakeDial.tsindex 8f0100958..ae0e81f59 100644--- a/cli/e2e/harness/fakeDial.ts+++ b/cli/e2e/harness/fakeDial.ts@@ -20,6 +20,8 @@ export interface FakeDialOptions {mac?: string/** The settings it says it holds when it greets, as the firmware reads them from its flash. */settings?: Record<string, unknown>+ /** The capabilities its greeting names (`swarmCard: 'v1'`, …), as a firmware that speaks them does. */+ capabilities?: Record<string, string>}export class FakeDial {@@ -29,6 +31,7 @@ export class FakeDial {private readonly decoder = new CableDecoder()private readonly mac: stringprivate readonly settings?: Record<string, unknown>+ private readonly capabilities: Record<string, string>/** When the daemon last said anything, and whether it has welcomed this dial since it last went quiet. */private heardAt = 0private welcomed = false@@ -37,6 +40,7 @@ export class FakeDial {private constructor(private readonly bridge: ChildProcess, readonly path: string, options: FakeDialOptions) {this.mac = options.mac ?? 'e2:e0:00:00:00:01'this.settings = options.settings+ this.capabilities = options.capabilities ?? {}bridge.stdout!.on('data', (chunk: Buffer) => {this.decoder.feed(chunk, (frame) => {if (frame.type !== CableType.Json) return@@ -68,7 +72,7 @@ export class FakeDial {}private hello(): DialMessage {- return { t: 'hello', product: 'harness', proto: 3, mac: this.mac, fw: '0.0.0-e2e', hw: 'e2e', ...(this.settings ? { settings: this.settings } : {}) }+ return { t: 'hello', product: 'harness', proto: 3, mac: this.mac, fw: '0.0.0-e2e', hw: 'e2e', ...this.capabilities, ...(this.settings ? { settings: this.settings } : {}) }}send(message: DialMessage): void {diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex c2b12f856..bd91044da 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -1028,6 +1028,8 @@ describe('Swarm cards', () => {expect(w.swarmCardsWanted).toHaveBeenCalledWith(true)expect(w.swarmCardOpen).toHaveBeenCalledWith('c1', 'st1', 'l1', false)expect(w.superTabSelected).toHaveBeenCalledWith('st1', 'p1')+ host.superTabSelected('st1', 'p1', 'buddy')+ expect(w.superTabSelected).toHaveBeenLastCalledWith('st1', 'p1', 'buddy')expect(await host.swarmCardRecap('st1', 'l1')).toEqual({ tabId: 'st1', leadId: 'l1', text: 'hi', at: 1, none: false })// A dial that speaks swarmChat asks for the chat on the face: the flag goes on to the wiring.host.swarmCardOpen('c1', 'st1', 'l1', true)diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 3eec30d57..b0ada2562 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -117,7 +117,7 @@ export interface CableHostWiring {* `refused` with the backend's reason when it refused the post. */swarmSay?: (harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean) => Promise<SaidOnCard>/** A device picked a Lead: the window opens that Swarm tab and project. */- superTabSelected?: (superTabId: string, projectId: string) => void+ superTabSelected?: (superTabId: string, projectId: string, chat?: CardSide) => void/** A finger on the dial's glass, in pieces, while it is down; `superTabId` when it scrolls that Swarm's chat (a Pro's Lead view). */scrolled?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number, superTabId?: string) => void/** The dial came, went, or started taking an update — see CableSession's onDialStatus. */@@ -449,8 +449,9 @@ export class DaemonCableHost implements CableHost {return this.wiring.swarmSay?.(harnessId, text, chat, ...pinned) ?? Promise.resolve({ said: false })}- superTabSelected(superTabId: string, projectId: string): void {- this.wiring.superTabSelected?.(superTabId, projectId)+ superTabSelected(superTabId: string, projectId: string, chat?: CardSide): void {+ if (chat) this.wiring.superTabSelected?.(superTabId, projectId, chat)+ else this.wiring.superTabSelected?.(superTabId, projectId)}/**diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex 85bfb9602..d9289b13f 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -14,7 +14,8 @@ import { describe, expect, it, vi } from 'vitest'import { CABLE_MAX_FRAME, CableDecoder, CableType, encodeCableFrame } from './cableFrame.js'import { CableSession, recapFrame, type CableAgent, type CableHost, type CableMachine, type CablePort } from './cableSession.js'import { DialLog } from './dialLog.js'-import type { SaidOnCard, SwarmCard, SwarmLead } from '../superTabs/cards.js'+import { leadsOf, type SaidOnCard, type SwarmCard, type SwarmLead } from '../superTabs/cards.js'+import { createSuperTabCards } from '../superTabs/inCore/cards.js'import type { PetStore } from './pets/store.js'/** A port whose two ends are both in this process. */@@ -4639,6 +4640,190 @@ describe('swarm cards', () => {}})+ // ── the desktop follows the dial into Buddy chats (Diego, 10-30) ─────────────────────────────────────────────+ const onDesk = (projectId = 'proj1') => ({ superTabId: 'st1', projectId, fromDevice: false })+ const mine = { ...buddy, local: 'h-buddy' }+ const twoProjects = () => [withBuddy({ local: 'h-lead1', buddy: mine }), lead(2, { chat: pmChat, sideChat: pmChat, buddies: true, local: 'h-lead2' })]++ it('a swipe to the Buddy side opens that project\'s Buddy chat on the desktop, and back to the PM its Lead chat', async () => {+ const state = { cards: [card('st1', twoProjects())], open: onDesk() as ReturnType<typeof onDesk> | null }+ const swarmCardSide = vi.fn()+ const host = cardHost(state, { swarmCardSide })+ const { session, port } = await connect(host)+ try {+ port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toEqual([{ t: 'supertab.focus', tab: 'st1', lead: 'lead1' }]), NEXT_TICKS)+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy']])+ port.say({ t: 'supertab.side', tab: 'st1', side: 'pm' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy'], ['st1', 'proj1', 'pm']])+ // The cards still hear each side: the dial's faces follow from them as before.+ expect(swarmCardSide.mock.calls).toEqual([['st1', 'buddy'], ['st1', 'pm']])+ // The window's announce of the move it made for the dial is not sent back as a focus.+ state.open = { ...onDesk(), fromDevice: true }+ await session.syncSwarmCards(true)+ expect(ofType(port, 'supertab.focus')).toHaveLength(1)+ } 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)+ 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.select', tab: 'st1', lead: 'lead2' }); await settle()+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls.at(-1)).toEqual(['st1', 'proj2', 'buddy'])+ } finally { await session.stop() }+ })++ it('a swipe asks the desktop nothing new from an older dial, for a Swarm the dial is not in, or to a Buddy the reader has not got', async () => {+ // An older round dial and the Pro: the side frame is not theirs, and nothing reaches the window.+ for (const hello of [ROUND, PRO]) {+ const host = cardHost({ cards: [card('st1', twoProjects())], open: onDesk() })+ const { session, port } = await connect(host)+ try {+ port.say(hello)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' }); await settle()+ expect(host.superTabSelected).not.toHaveBeenCalled()+ } finally { await session.stop() }+ }+ // A Swarm with no project known on the dial face: no project is guessed.+ const unknown = cardHost({ cards: [card('st1', twoProjects()), card('st2', [lead(5, { buddies: true, buddy: mine })])], open: onDesk() })+ const first = await connect(unknown)+ try {+ first.port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(first.port, 'supertab.focus')).toHaveLength(1), NEXT_TICKS)+ first.port.say({ t: 'supertab.side', tab: 'st2', side: 'buddy' })+ first.port.say({ t: 'supertab.side', tab: 'st9', side: 'pm' }); await settle()+ expect(unknown.superTabSelected).not.toHaveBeenCalled()+ } finally { await first.session.stop() }+ // The project on the face has no Buddy of the reader's (another person's never reaches the cards): no Buddy chat is+ // opened, or made, for it; the PM side still opens the Lead chat.+ const none = cardHost({ cards: [card('st1', twoProjects())], open: onDesk('proj2') })+ const second = await connect(none)+ try {+ second.port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(second.port, 'supertab.focus')).toHaveLength(1), NEXT_TICKS)+ second.port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy' })+ second.port.say({ t: 'supertab.side', tab: 'st1', side: 'pm' }); await settle()+ expect(vi.mocked(none.superTabSelected!).mock.calls).toEqual([['st1', 'proj2', 'pm']])+ } finally { await second.session.stop() }+ })++ it('a project picked on the Buddy side opens that project\'s Buddy chat', async () => {+ const state = { cards: [card('st1', [withBuddy({ buddy: mine }), lead(2, { buddies: true, buddy: { ...mine, chatId: 'b2' } }), lead(3, { buddies: true })], { side: 'buddy' })], open: onDesk() }+ const host = cardHost(state)+ const { session, port } = await connect(host)+ try {+ port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ port.say({ t: 'supertab.select', tab: 'st1', lead: 'lead2' }); await settle()+ // No Buddy in project 3: its Lead chat, as today.+ port.say({ t: 'supertab.select', tab: 'st1', lead: 'lead3' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj2', 'buddy'], ['st1', 'proj3']])+ } finally { await session.stop() }+ })++ it('tapping the reader\'s Buddy or a Lead that runs here opens its Swarm chat; any other agent opens a tile as today', async () => {+ const host = cardHost({ cards: [card('st1', twoProjects())] })+ 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()+ port.say({ t: 'agent.open', agentId: 'h-lead2' }); await settle()+ port.say({ t: 'agent.open', agentId: 'a1' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy'], ['st1', 'proj2', 'pm']])+ expect(vi.mocked(host.openAgent).mock.calls).toEqual([['a1', undefined]])+ // A question screen still brings the agent forward, as today.+ port.say({ t: 'agent.open', agentId: 'h-buddy', reason: 'question' }); await settle()+ expect(vi.mocked(host.openAgent).mock.calls.at(-1)).toEqual(['h-buddy', 'question'])+ } finally { await 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).+ for (const hello of [ROUND, { t: 'hello', product: 'harness', mac: 'ee:ff' }]) {+ const host = cardHost({ cards: [card('st1', twoProjects())] })+ const { session, port } = await connect(host)+ try {+ port.say(hello)+ await vi.waitFor(() => expect(port.types()).toContain('welcome'))+ port.say({ t: 'agent.open', agentId: 'h-buddy' }); await settle()+ port.say({ t: 'agent.open', agentId: 'h-lead2' }); await settle()+ port.say({ t: 'agent.open', agentId: 'a1' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy'], ['st1', 'proj2', 'pm']])+ expect(vi.mocked(host.openAgent).mock.calls).toEqual([['a1', undefined]])+ } finally { await session.stop() }+ }+ })++ it('a tap opens a tile as today from the Pro, and when the id is claimed twice or not by this computer', async () => {+ // The Pro picks Leads on its own cards and has no Buddy screen; the ruling and Diego's proposal are the round dial's.+ const pro = cardHost({ cards: [card('st1', twoProjects())] })+ const proSession = await connect(pro)+ try {+ proSession.port.say(PRO)+ await vi.waitFor(() => expect(ofType(proSession.port, 'supertab')).toHaveLength(1))+ proSession.port.say({ t: 'agent.open', agentId: 'h-buddy' }); await settle()+ expect(pro.superTabSelected).not.toHaveBeenCalled()+ expect(vi.mocked(pro.openAgent).mock.calls).toEqual([['h-buddy', undefined]])+ } finally { await proSession.session.stop() }+ // The same session id in two Swarms' cards is no one Swarm's: nothing is guessed. A Lead not here has no session id.+ const host = cardHost({ cards: [card('st1', twoProjects()), card('st2', [lead(7, { local: 'h-lead2' }), lead(8, { local: '' })])] })+ const { session, port } = await connect(host)+ try {+ port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(2))+ port.say({ t: 'agent.open', agentId: 'h-lead2' })+ port.say({ t: 'agent.open', agentId: 'lead8' }); await settle()+ expect(host.superTabSelected).not.toHaveBeenCalled()+ expect(vi.mocked(host.openAgent).mock.calls).toEqual([['h-lead2', undefined], ['lead8', undefined]])+ } finally { await session.stop() }+ })++ it('a tap on the reader\'s Buddy opens its chat with cards generated from a Swarm and passed through the core', async () => {+ // The cards as production makes them: read from a Swarm (superTabs/cards.ts) and checked on their way into the core+ // (superTabs/inCore/cards.ts), which once dropped the Buddy's session id and left every Buddy tap on a terminal tab.+ const agent = (id: string, over: Record<string, unknown> = {}) =>+ ({ id, harnessId: `h-${id}`, machineId: 'm1', machineOwnerId: 'me', configuration: { engine: 'claude' }, ...over })+ const state = {+ name: 'openharness', buddies: true, people: [{ id: 'me', email: '[email protected]' }],+ projects: [{ id: 'web', name: 'web', leadConversationId: 'lead-web' }],+ agents: [agent('a1'), agent('y1', { name: "me's Buddy", buddyOf: { personId: 'me', generation: 'g1' } })],+ conversations: [{ id: 'lead-web', projectId: 'web', leadId: 'a1', archived: false },+ { id: 'pm-web', projectId: 'web', kind: 'buddy', buddyOwnerId: 'me', agentIds: ['y1'], archived: false }],+ }+ let forwarded: SwarmCard[] | null = null+ const core = createSuperTabCards({ swarmCards: (items) => { forwarded = items }, swarmCardRecap: vi.fn() })+ core.cards([{ id: 'st1', name: 'openharness', ...leadsOf(state, 'm1', () => ({ inTurn: false }), 'me') }])+ const host = cardHost({ cards: null }, { swarmCards: () => forwarded })+ 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-y1' }); await settle()+ expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'web', 'buddy']])+ expect(host.openAgent).not.toHaveBeenCalled()+ // …and the id still never reaches the dial.+ expect(JSON.stringify(ofType(port, 'supertab'))).not.toContain('h-y1')+ } finally { await session.stop() }+ })++ it('the Buddy\'s session id stays on this computer: the dial\'s buddy block is unchanged', async () => {+ const { session, port } = await connect(cardHost({ cards: [card('st1', twoProjects())] }))+ try {+ port.say(BUDDY)+ await vi.waitFor(() => expect(ofType(port, 'supertab')).toHaveLength(1))+ expect((ofType(port, 'supertab')[0].leads as Array<{ buddy?: unknown }>)[0].buddy).toEqual(buddy)+ } finally { await session.stop() }+ })+it('a buddy notice reaches only a swarmBuddy dial, apart from the Lead\'s', async () => {for (const hello of [BUDDY, ROUND]) {const state = { cards: [card('st1', [withBuddy()])] }diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex 665a6ea59..b0a608778 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -184,8 +184,12 @@ function chatLead(l: SwarmLead, chat = l.chat): Record<string, unknown> {}/** A Lead's entry for a swarmBuddy dial (spec 2026-10-29-round-dial-pm-buddy): the face on the side it keeps, and while the* Swarm has Buddies on, `buddies` and the reader's Buddy. With Buddies off it is a swarmChat dial's entry. */+/** The Buddy as the dial draws it: its session id stays on this computer. */+function dialBuddy({ local: _local, ...drawn }: SwarmBuddy): Record<string, unknown> {+ return { ...drawn }+}function buddyLead(l: SwarmLead): Record<string, unknown> {- return { ...chatLead(l, l.sideChat ?? l.chat), ...(l.buddies ? { buddies: true } : {}), ...(l.buddies && l.buddy ? { buddy: { ...l.buddy } } : {}) }+ return { ...chatLead(l, l.sideChat ?? l.chat), ...(l.buddies ? { buddies: true } : {}), ...(l.buddies && l.buddy ? { buddy: dialBuddy(l.buddy) } : {}) }}/** A Swarm agent's id as the backend makes it; a harness's id is a UUID, so the two never meet. */const SWARM_AGENT_ID = /^[0-9a-f]{24}$/@@ -356,7 +360,7 @@ import type { FormCommand, FormResult } from './windowForm.js'import { deriveLongRecap, extendShortRecap } from '../lib/deviceRecap.js'import type { TurnStatsFields } from './turnStats.js'import type { Tier } from '../lib/notifyTier.js'-import type { CardChat, CardSide, LeadNotice, LeadRecap, SaidOnCard, SwarmCard, SwarmChat, SwarmLead } from '../superTabs/cards.js'+import type { CardChat, CardSide, LeadNotice, LeadRecap, SaidOnCard, SwarmBuddy, SwarmCard, SwarmChat, SwarmLead } from '../superTabs/cards.js'import { truncateUtf8 } from '../lib/deviceRecentTrim.js'export interface RouteDecision {@@ -401,8 +405,9 @@ export interface CableHost {* `refused`: the backend refused the post, whose words are never typed anywhere instead. `chatId`: the chat they were* spoken to, the only one they may be posted in. */swarmSay?(harnessId: string, text: string, chat?: CardChat, chatId?: string, reviewed?: boolean): Promise<SaidOnCard>- /** A device picked a Lead: the window opens that Swarm tab and project. */- superTabSelected?(superTabId: string, projectId: string): void+ /** A device picked a Lead: the window opens that Swarm tab and project. `chat` (a round dial that speaks swarmBuddy): the+ * 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 } | nullappName(): string@@ -1441,7 +1446,10 @@ export class CableSession {case 'supertab.side': {// Only a dial that keeps sides, for a Swarm id it can hold; anything else is a frame this daemon cannot use.const tab = str('tab') ?? '', side = str('side')- if (this.swarmBuddy && CARD_ID.test(tab) && (side === 'pm' || side === 'buddy')) this.host.swarmCardSide?.(tab, side)+ if (this.swarmBuddy && CARD_ID.test(tab) && (side === 'pm' || side === 'buddy')) {+ this.host.swarmCardSide?.(tab, side)+ this.followSide(tab, side)+ }return}case 'swarm.select':@@ -1531,10 +1539,17 @@ export class CableSession {await this.syncPlayerLibrary(true)return}- case 'agent.open':+ case 'agent.open': {// Only the one reason the window knows; anything else reads as a tap, the older frame's meaning.- if (str('agentId')) this.host.openAgent(str('agentId')!, str('reason') === 'question' ? 'question' : undefined)+ const agentId = str('agentId'), reason = str('reason') === 'question' ? 'question' as const : undefined+ if (!agentId) return+ // A tap on the reader's Buddy or a Lead running here opens its chat in the Swarm tab: a terminal tab of its own is+ // one whose close stopped the Buddy (Diego, 10-30). A question screen brings the agent forward as before.+ const swarm = reason ? null : this.swarmSessionOf(agentId)+ if (swarm) this.openSwarmChat(swarm.tab, swarm.projectId, swarm.chat)+ else this.host.openAgent(agentId, reason)return+ }case 'agent.fork': {// The dial's Fork action. The host opens the new agent in the window itself; the dial only needs// to hear a refusal, as a toast, so a press that did nothing is not a press that was lost.@@ -2986,10 +3001,10 @@ export class CableSession {if (type === 'supertab.select') {const projectId = this.host.swarmCards?.()?.find((c) => c.id === tab)?.leads.find((l) => l.id === lead)?.projectIdif (!projectId) { this.log(`cable: ignored pick of unknown Lead ${lead}`); return }- // Remembered before the window answers, so its announce of this very project is not sent back as a focus.- this.focusedKey = `${tab}/${projectId}`- this.picked = { key: this.focusedKey, at: Date.now() }- this.host.superTabSelected?.(tab, projectId)+ // A swarmBuddy dial on the Buddy side: the next project's Buddy chat, where the reader has one there.+ const card = this.host.swarmCards?.()?.find((c) => c.id === tab)+ const onBuddy = this.swarmBuddy && card?.side === 'buddy' && this.buddyIn(card, projectId)+ this.openSwarmChat(tab, projectId, onBuddy ? 'buddy' : undefined)return}// A repeat for the same Lead inside a second is answered from the first read, not read again. Dropping it left a dial@@ -3008,6 +3023,54 @@ export class CableSession {if (recap) await this.queued(async () => { await this.send(recapFrame(recap)) })}+ /** 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 {+ this.focusedKey = `${tab}/${projectId}`+ this.picked = { key: this.focusedKey, at: Date.now() }+ if (chat) this.host.superTabSelected?.(tab, projectId, chat)+ else this.host.superTabSelected?.(tab, projectId)+ }++ /** The reader's Buddy in a project of a card, when Buddies are on and they have one there. */+ private buddyIn(card: SwarmCard, projectId: string): boolean {+ const lead = card.leads.find((l) => l.projectId === projectId)+ return lead?.buddies === true && lead.buddy !== undefined+ }++ /**+ * A swarmBuddy dial swiped a Swarm to a side: the desktop opens the Buddy chat (or the Lead chat) of the project on the+ * dial's face, which is the one it last picked or was pointed at in that Swarm. With none known there, no project is+ * 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 card = this.host.swarmCards?.()?.find((c) => c.id === tab)+ if (!card?.leads.some((l) => l.projectId === projectId)) return+ if (side === 'buddy' && !this.buddyIn(card, projectId)) return+ this.openSwarmChat(tab, projectId, side)+ }++ /**+ * The Swarm session a round dial's tap names: the reader's Buddy ('buddy') or a Lead ('pm') whose session runs on this+ * computer, by the session id the cards hold for it. Any round dial, older ones too (PM ruling, 10-30): the tap is a+ * notification's, not a Buddy screen's. The Pro keeps its tile: it picks Leads on its own cards, has no Buddy screen,+ * and Diego's proposal and the ruling are the round dial's. An id the cards hold twice is no one session's, and opens a+ * tile as before; so does every other agent.+ */+ private swarmSessionOf(agentId: string): { tab: string; projectId: string; chat: CardSide } | null {+ if (this.greetedBoard === 'pro') return null+ const found: Array<{ tab: string; projectId: string; chat: CardSide }> = []+ for (const card of this.host.swarmCards?.() ?? []) {+ for (const lead of card.leads) {+ if (lead.local === agentId) found.push({ tab: card.id, projectId: lead.projectId, chat: 'pm' })+ if (lead.buddies && lead.buddy?.local === agentId) found.push({ tab: card.id, projectId: lead.projectId, chat: 'buddy' })+ }+ }+ return found.length === 1 ? found[0] : null+ }+// ── swarms ────────────────────────────────────────────────────────────────────────────────────────private lastSwarmsKey = ''diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 457723b83..87cbf49e9 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -1254,7 +1254,10 @@ export interface SwarmChat { kind: ChatKind; id: string; name: string; working:export interface LeadNotice { chat: 'lead' | 'pm' | 'buddy'; chatId: string; id: string; text: string; at: number }/** The reader's own Buddy in a project, for a round dial's Buddy screen: its chat, name and engine, Desktop's pattern for* its name (`cells`, the 15 half bits; `color`, `#rrggbb`), and `live` false while it is down. */-export interface SwarmBuddy { chatId: string; name: string; engine: string; cells: number; color: string; live: boolean }+export interface SwarmBuddy { chatId: string; name: string; engine: string; cells: number; color: string; live: boolean+ /** Its session id when it runs on this computer: how a tap on its notification is told from any other agent's. Never sent+ * to a device. */+ local?: string }/** The screen a round dial shows of each project of a Swarm: the PM's (today's face) or the reader's Buddy's. */export type CardSide = 'pm' | 'buddy'/** Which chat a card request is about: the Lead's conversation (false, the Pro), today's face (true, a swarmChat dial), ordiff --git a/cli/src/services/devices.spec.ts b/cli/src/services/devices.spec.tsindex f13b1a82b..dd8500392 100644--- a/cli/src/services/devices.spec.ts+++ b/cli/src/services/devices.spec.ts@@ -748,6 +748,11 @@ describe('what the windows say, reaching the dial', () => {[{ action: 'cardOpen', session: 'c1', tabId: 'st1', leadId: 'lead1' }], [{ action: 'cardOpen', session: 'c1', tabId: 'st1', leadId: null }]])seen.host.superTabSelected!('st1', 'proj1')expect(vi.mocked(core.clients.sendLocal)).toHaveBeenCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', projectId: 'proj1' } })+ // A round dial's side rides along, so the window opens the Buddy chat or the Lead chat the dial shows.+ seen.host.superTabSelected!('st1', 'proj1', 'buddy')+ expect(vi.mocked(core.clients.sendLocal)).toHaveBeenLastCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', projectId: 'proj1', chat: 'buddy' } })+ seen.host.superTabSelected!('st1', 'proj1', 'pm')+ expect(vi.mocked(core.clients.sendLocal)).toHaveBeenLastCalledWith({ type: 'dial_super_tab', payload: { superTabId: 'st1', projectId: 'proj1', chat: 'pm' } })})})diff --git a/cli/src/services/devices.ts b/cli/src/services/devices.tsindex c43fcbf2a..2cbec361b 100644--- a/cli/src/services/devices.ts+++ b/cli/src/services/devices.ts@@ -266,8 +266,10 @@ export function startDevices(core: CoreApi, ports: CorePorts, deps: DevicesDeps)// An error (no service, a refused post) is not `said`: the words go to the harness instead, never lost.swarmSay: async (harnessId, text, chat, chatId, reviewed) => saidOf(await askCards({ action: 'cardSay', harnessId, text, ...chatFlag(chat),...(chatId ? { chatId, ...(reviewed ? { reviewed: true } : {}) } : {}) })),- // The Pro picked a Lead: the window opens that Swarm tab and project. Harmless with no window.- superTabSelected: (superTabId, projectId) => core.clients.sendLocal({ type: 'dial_super_tab', payload: { superTabId, projectId } }),+ // The Pro picked a Lead: the window opens that Swarm tab and project. Harmless with no window. `chat`, from a round dial+ // that keeps sides: the Buddy chat or the Lead chat there; a window from before it opens the project's Lead chat.+ superTabSelected: (superTabId, projectId, chat) =>+ core.clients.sendLocal({ type: 'dial_super_tab', payload: { superTabId, projectId, ...(chat ? { chat } : {}) } }),scrolled: (phase, dy, velocity, superTabId) => core.clients.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity, ...(superTabId ? { superTabId } : {}) } }),// Gestures stay at this desk. The device inventory and its settings also reach the owner's other// machines, through the encrypted device-management event.diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.tsindex 2c07091b8..87aaaa088 100644--- a/cli/src/superTabs/cards.spec.ts+++ b/cli/src/superTabs/cards.spec.ts@@ -885,12 +885,21 @@ describe('leadsOf Buddies', () => {leadsOf(state, 'm1', idle, 'me', focus, side).leads.find(l => l.projectId === 'web')!it('gives each Lead a buddy block for the reader\'s own Buddy, with Desktop\'s avatar', () => {- expect(web(on()).buddy).toEqual({ chatId: 'pm-web', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true })+ expect(web(on()).buddy).toEqual({ chatId: 'pm-web', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true, local: 'h-y1' })// The project with no Buddy chat has no block.expect(leadsOf(on(), 'm1', idle, 'me').leads.find(l => l.projectId === 'mobile')).not.toHaveProperty('buddy')// A Buddy that is down is still the Buddy; its display name is the one Desktop draws and shows.const down = on({ agents: [...chats().agents as object[], buddy({ downSince: '2026-10-29T00:00:00.000Z', displayName: "ken's Buddy" })] })- expect(web(down).buddy).toEqual({ chatId: 'pm-web', name: "ken's Buddy", engine: 'codex', cells: 30735, color: '#d69abb', live: false })+ expect(web(down).buddy).toEqual({ chatId: 'pm-web', name: "ken's Buddy", engine: 'codex', cells: 30735, color: '#d69abb', live: false, local: 'h-y1' })+ })++ it('names the Buddy\'s session only when it runs on this computer, so a tap on it can be told from any other', () => {+ // On another machine, or with no session the core holds here: no id, and a tap on the dial opens nothing new.+ const elsewhere = on({ agents: [...chats().agents as object[], buddy({ machineId: 'm2' })] })+ expect(web(elsewhere).buddy).not.toHaveProperty('local')+ expect(leadsOf(on(), 'm1', h => h === 'h-y1' ? null : { inTurn: false }, 'me').leads.find(l => l.projectId === 'web')!.buddy).not.toHaveProperty('local')+ const unnamed = on({ agents: [...chats().agents as object[], buddy({ harnessId: '' })] })+ expect(web(unnamed).buddy).not.toHaveProperty('local')})it('marks buddies only while the Swarm has them on', () => {diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.tsindex f50c6a638..b648ce645 100644--- a/cli/src/superTabs/cards.ts+++ b/cli/src/superTabs/cards.ts@@ -103,12 +103,12 @@ function voicesOf(face: Face, leadId: string, agents: Json[], me: string | undefreturn new Set(idsOf(face.conversation.agentIds))}/** The reader's Buddy in a project as a dial draws it, from Desktop's pattern for its whole name. */-function buddyOf(agents: Json[], chat: Json, me: string | undefined): SwarmBuddy | undefined {+function buddyOf(agents: Json[], chat: Json, me: string | undefined, local: (a: Json) => string): SwarmBuddy | undefined {const [found] = buddiesIn(agents, chat, me)if (!found) return undefined- const name = agentName(found)+ const name = agentName(found), here = local(found)return { chatId: chat.id as string, name: cut(name, NAME_BYTES), engine: String(object(found.configuration).engine ?? ''), ...buddyAvatar(name),- live: typeof found.downSince !== 'string' }+ live: typeof found.downSince !== 'string', ...(here ? { local: here } : {}) }}/**@@ -158,7 +158,7 @@ export function leadsOf(state: Json, machineId: string, live: (harnessId: stringconst chat = chatOf(faceOf(conversations, projectId, lead, focus, me, buddies))const buddyChat = buddies ? buddyChatOf(conversations, projectId, me) : undefinedconst sideChat = buddies ? chatOf(sideFaceOf(conversations, projectId, lead, focus, me, side)) : undefined- const buddy = buddyChat && buddyOf(agents, buddyChat, me)+ const buddy = buddyChat && buddyOf(agents, buddyChat, me, a => turnHere(a) && cardId(a.harnessId) ? String(a.harnessId) : '')leads.push({id: String(agent.id), projectId: String(project.id ?? 'lead'), project: cut(String(project.name ?? ''), NAME_BYTES), engine: String(object(agent.configuration).engine ?? ''),owner: owner && typeof owner.email === 'string' ? cut(owner.email, NAME_BYTES) : '',diff --git a/cli/src/superTabs/inCore/cards.spec.ts b/cli/src/superTabs/inCore/cards.spec.tsindex a780f6b88..fe232a36a 100644--- a/cli/src/superTabs/inCore/cards.spec.ts+++ b/cli/src/superTabs/inCore/cards.spec.ts@@ -128,6 +128,17 @@ describe('the Swarm cards on the devices', () => {expect(swarmCardRecap).toHaveBeenCalledOnce()})// Round dial PM and Buddy screens (spec 2026-10-29): the swarmBuddy dial's fields, checked as the chat and notice are.+ it('keeps the Buddy\'s session id on its way to the devices service; an unsound one is dropped and the Buddy kept', () => {+ const { cards, swarmCards } = setup()+ const buddy = (over: Record<string, unknown> = {}) => ({ chatId: 'b1', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true, ...over })+ cards.cards([card('t1', [lead('l1', { buddies: true, buddy: buddy({ local: 'h-buddy' }) })])])+ expect(swarmCards.mock.calls.at(-1)![0][0].leads[0].buddy).toEqual(buddy({ local: 'h-buddy' }))+ for (const bad of ['bad id', 'x'.repeat(48), 5, '']) {+ cards.cards([card('t1', [lead('l1', { buddies: true, buddy: buddy({ local: bad }) })])])+ expect(swarmCards.mock.calls.at(-1)![0][0].leads[0].buddy).toEqual(buddy())+ }+ })+it('keeps a sound side chat, buddies flag, buddy block and buddy notice, drops a malformed one', () => {const { cards, swarmCards, swarmCardRecap } = setup()const buddy = (over: Record<string, unknown> = {}) => ({ chatId: 'b1', name: "diego's Buddy", engine: 'codex', cells: 25513, color: '#d6a79a', live: true, ...over })diff --git a/cli/src/superTabs/inCore/cards.ts b/cli/src/superTabs/inCore/cards.tsindex ba1242846..f5655b9e7 100644--- a/cli/src/superTabs/inCore/cards.ts+++ b/cli/src/superTabs/inCore/cards.ts@@ -72,7 +72,10 @@ function buddyIn(value: unknown): SwarmBuddy | null {const buddy = object(value)if (!id(buddy.chatId) || typeof buddy.name !== 'string' || typeof buddy.engine !== 'string' || typeof buddy.live !== 'boolean') return nullif (!whole(buddy.cells) || buddy.cells > MAX_CELLS || typeof buddy.color !== 'string' || !COLOR.test(buddy.color)) return null- return { chatId: buddy.chatId, name: cut(buddy.name, NAME_BYTES), engine: cut(buddy.engine, ENGINE_BYTES), cells: buddy.cells, color: buddy.color, live: buddy.live }+ // Its session here, which tells a tap on its notification from any other agent's (cableSession agent.open). Kept on this+ // computer: the devices service strips it from every frame. An unsound one is left out and the Buddy is kept.+ return { chatId: buddy.chatId, name: cut(buddy.name, NAME_BYTES), engine: cut(buddy.engine, ENGINE_BYTES), cells: buddy.cells, color: buddy.color, live: buddy.live,+ ...(id(buddy.local) ? { local: buddy.local } : {}) }}/** A Lead the service sent, checked and cut; null when it is not one. */diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 1f246db66..850a11f36 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -4472,11 +4472,16 @@ class AppNotifier extends ChangeNotifier {}}+ /// A device picked a project of a Swarm: show that Swarm, then its Lead+ /// chat, or with [buddy] (a round dial on its Buddy side, or a tap on the+ /// reader's Buddy) the reader's own Buddy chat there when they have one.+ /// Never a terminal tab: closing one stopped the Buddy (Diego, 10-30).Future<void> _openSuperTabProject(MachineState source,String tabId,- String projectId,- ) async {+ String projectId, {+ bool buddy = false,+ }) async {final open = swarms.where((s) => s.superTabId == tabId).firstOrNull;final name = open?.name ?? _superTabNames[tabId];// A tab this account does not belong to is nobody's to open.@@ -4503,7 +4508,15 @@ class AppNotifier extends ChangeNotifier {.where((p) => p.id == projectId).firstOrNull;if (project == null) return;- controller.select(project.leadConversationId);+ // Only an existing chat of the reader's own: a device never makes one.+ if (buddy && controller.buddyChat(projectId) != null) {+ await (controller.buddyChatOpener ?? controller.openBuddyChat)(+ projectId,+ );+ if (_disposed || _devicePick != pick) return;+ } else {+ controller.select(project.leadConversationId);+ }// Selecting what is already selected announces nothing by itself._announceOpenPanesToDial();} catch (error) {@@ -21411,11 +21424,18 @@ class AppNotifier extends ChangeNotifier {break;case 'dial_super_tab':// The Harness Pro picked a Lead's project. Show that Swarm, then the- // project's Lead chat as a click on its row in the sidebar does.+ // project's Lead chat as a click on its row in the sidebar does. A+ // round dial names the chat it shows: 'buddy' opens the reader's+ // Buddy chat there; anything else is the Lead chat.final tabId = payload['superTabId'];final projectId = payload['projectId'];if (tabId is String && projectId is String) {- await _openSuperTabProject(machine, tabId, projectId);+ await _openSuperTabProject(+ machine,+ tabId,+ projectId,+ buddy: payload['chat'] == 'buddy',+ );}break;case 'dial_forked':diff --git a/desktop/test/super_tab_dial_test.dart b/desktop/test/super_tab_dial_test.dartindex d0c4a99ca..f63918493 100644--- a/desktop/test/super_tab_dial_test.dart+++ b/desktop/test/super_tab_dial_test.dart@@ -263,6 +263,117 @@ void main() {return (f, c);}+ // The desktop follows the round dial into Buddy chats (Diego, 10-30): the+ // dial's side, and a tap on its Buddy's notification, open the chat in the+ // Swarm tab, never a terminal tab of its own.+ Future<void> follow(+ SuperTabLaunchFixture f,+ String project,+ String chat, {+ String tab = tabId,+ }) => f.app.handleEventForTest('m', {+ 'type': 'dial_super_tab',+ 'payload': {'superTabId': tab, 'projectId': project, 'chat': chat},+ });++ test('the dial\'s Buddy side opens the project\'s Buddy chat in the Swarm tab, with no new tab', () async {+ final (f, c) = await openChats();+ final swarm = f.app.activeSwarmId;+ f.app.newSwarm(newTabPage: true);+ final count = f.app.swarms.length;+ final before = announces(f).length;+ await follow(f, 'design', 'buddy');+ await settle();+ expect(f.app.activeSwarmId, swarm);+ expect(f.app.swarms, hasLength(count));+ expect(c.selectedId, 'design-pm');+ final after = announces(f).skip(before).toList();+ expect(after, isNotEmpty);+ // Each announce is the dial's own move: the daemon keeps the dial's side+ // and sends no focus back.+ expect(after.every((a) => a['fromDevice'] == true), isTrue);+ expect(row(after.last)['conversationId'], 'design-pm');+ f.app.announceWindowForeground();+ await settle();+ expect(announces(f).last.containsKey('fromDevice'), isFalse);+ });++ test('the dial\'s PM side opens the project\'s Lead chat', () async {+ final (f, c) = await openChats();+ final count = f.app.swarms.length;+ await follow(f, 'design', 'buddy');+ await settle();+ expect(c.selectedId, 'design-pm');+ final before = announces(f).length;+ await follow(f, 'design', 'pm');+ await settle();+ expect(c.selectedId, 'design-lead');+ expect(f.app.swarms, hasLength(count));+ final after = announces(f).skip(before).toList();+ expect(after.every((a) => a['fromDevice'] == true), isTrue);+ expect(row(after.last)['conversationId'], 'design-lead');+ });++ 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;+ // Another person's Buddy chat in the project is never the reader's.+ (server.state['conversations'] as List).add({+ ...conversationFixture('lead-sam', "sam's Buddy"),+ 'projectId': 'lead',+ 'kind': 'buddy',+ 'buddyOwnerId': 'sam',+ });+ await c.refresh();+ c.select('design-fix');+ await settle();+ await follow(f, 'lead', 'buddy');+ await settle();+ expect(c.selectedId, 'lead');+ final ids = [+ for (final g in (server.state['conversations'] as List).cast<Map>())+ g['id'],+ ];+ expect(ids.where((id) => '$id'.startsWith('buddy-')), isEmpty);+ });++ test('access revoked while the dial\'s Buddy open is in flight opens nothing', () async {+ final (f, c) = await openChats();+ final server = f.connection.server;+ final hold = server.holdReads = Completer<void>();+ // The Swarm's rows are gone when the pick arrives; its read is answered+ // with the access already removed.+ c.revokeAccess('Access removed.');+ server.state['conversations'] = <Map<String, dynamic>>[];+ server.state['projects'] = <Map<String, dynamic>>[];+ final picking = follow(f, 'design', 'buddy');+ await settle();+ server.holdReads = null;+ hold.complete();+ await picking;+ await settle();+ expect(c.selectedId, isNot('design-pm'));+ expect(c.buddyChat('design'), isNull);+ // The device's mark does not outlive the pick that found nothing.+ f.app.announceWindowForeground();+ await settle();+ expect(announces(f).last.containsKey('fromDevice'), isFalse);+ });++ test('an unknown chat, tab or project from the dial opens nothing new', () async {+ final (f, c) = await openChats();+ final count = f.app.swarms.length;+ await follow(f, 'design', 'terminal');+ await settle();+ // An unknown chat reads as the older pick: the project's Lead chat.+ expect(c.selectedId, 'design-lead');+ await follow(f, 'nope', 'buddy');+ await follow(f, 'design', 'buddy', tab: 'ffffffffffffffffffffffff');+ await settle();+ expect(c.selectedId, 'design-lead');+ expect(f.app.swarms, hasLength(count));+ });+test('a Swarm tab announces the open conversation\'s id', () async {final (f, c) = await openChats();f.app.announceWindowForeground();