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
feat(cable): build the dial's carousel around the window's open tiles
0xdiego25c253ada193f8
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.tsindex a6d93af03..b2a058748 100644--- a/cli/src/cable/cableHost.spec.ts+++ b/cli/src/cable/cableHost.spec.ts@@ -238,6 +238,86 @@ describe('DaemonCableHost.listAgents across machines', () => {expect(agents.map((a) => a.machineId)).toEqual(['mine', 'other', 'third'])})+ it('keeps a machine\'s agents when the backend cannot be asked', async () => {+ // The failure this exists for, measured on the real dial: `unknown` means the backend could not be+ // reached — MachineListCache.degrade() marks EVERY machine with it in one go — and reading it as+ // "the machine is gone" emptied a remote machine off the carousel mid-session, silently, while the+ // window went on showing those agents.+ AGENTS.length = 0+ const machines: FleetMachine[] = [{ ...REMOTE }]+ const host = new DaemonCableHost(wiring(), crossFleet({ other: [{ id: 'r1', name: 'api' }] }, machines))+ expect((await settled(host)).map((a) => a.id)).toEqual(['r1'])++ machines[0].state = 'unknown'+ // Well past REMOTE_GRACE_MS: this is not a grace period, it is a different question.+ vi.setSystemTime(Date.now() + 10 * 60_000)+ expect((await settled(host)).map((a) => a.id)).toEqual(['r1'])+ vi.useRealTimers()+ })++ it('drops them when the machine itself says it is offline, and says so', async () => {+ AGENTS.length = 0+ const log = vi.fn()+ const machines: FleetMachine[] = [{ ...REMOTE }]+ const host = new DaemonCableHost(wiring({ log }), crossFleet({ other: [{ id: 'r1', name: 'api' }] }, machines))+ expect((await settled(host)).map((a) => a.id)).toEqual(['r1'])++ machines[0].state = 'offline'+ expect((await settled(host)).map((a) => a.id)).toEqual([])+ // An agent leaving the carousel is the one event that cannot be diagnosed from its absence.+ expect(log.mock.calls.flat().join('\n')).toContain('left the carousel')+ })++ it('holds a tile the window has open even when its machine goes offline', async () => {+ // The desk is the contract between the two screens. A hole in it makes a swipe skip a tile and an+ // agent chosen in the window have nowhere to land.+ AGENTS.length = 0+ const machines: FleetMachine[] = [{ ...REMOTE }]+ const host = new DaemonCableHost(wiring(), crossFleet({ other: [{ id: 'r1', name: 'api' }] }, machines))+ await settled(host)+ host.setDesk(['r1'])++ machines[0].state = 'offline'+ const agents = await settled(host)+ expect(agents.map((a) => a.id)).toEqual(['r1'])+ // Under the name and machine it was last seen with, not a placeholder.+ expect(agents[0]).toMatchObject({ name: 'api', machineId: 'other', machine: 'office-imac' })+ expect(host.knows('r1')).toBe(true)+ })++ it('lists every agent, marking the ones the carousel does not walk', async () => {+ // Ring first, then the rest — the session sends the count of the first+ // group, so the ORDER is the split. Every agent is still listed, because+ // the dial's own count and its switcher read this list.+ AGENTS.length = 0+ for (const agentId of ['a1', 'a2', 'a3', 'a4']) {+ AGENTS.push({ agentId, registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })+ }+ const host = new DaemonCableHost(wiring())+ await settled(host)+ // Tiles at both ends of the list: a2 and a3 are between them, so neither is+ // reached by stepping off an edge.+ host.setDesk(['a1', 'a4'])++ const agents = await host.listAgents()+ expect(agents.map((a) => a.id)).toEqual(['a1', 'a4', 'a2', 'a3'])+ expect(agents.filter((a) => !a.offRing).map((a) => a.id)).toEqual(['a1', 'a4'])+ expect(agents.filter((a) => a.offRing).map((a) => a.id)).toEqual(['a2', 'a3'])+ })++ it('does not resurrect an agent that has no tile', async () => {+ // The memory is only a warrant for what the window is showing. An agent that was deleted must stay+ // deleted.+ AGENTS.length = 0+ const machines: FleetMachine[] = [{ ...REMOTE }]+ const host = new DaemonCableHost(wiring(), crossFleet({ other: [{ id: 'r1', name: 'api' }] }, machines))+ await settled(host)++ machines[0].state = 'offline'+ expect((await settled(host)).map((a) => a.id)).toEqual([])+ expect(host.knows('r1')).toBe(false)+ })+it('sends a turn to the agent’s OWN machine, not to the selected one', async () => {// The single worst outcome this feature can produce is a turn delivered to a different computer, so// the routing is asserted with the wheel deliberately pointed somewhere else.@@ -262,7 +342,50 @@ describe('DaemonCableHost.listAgents across machines', () => {host.focus('r1')- expect(focused).toHaveBeenCalledWith('other', 'r1')+ // No edge: the window has reported no tiles, so there is no desk to be off+ // the end of and nothing for it to replace.+ expect(focused).toHaveBeenCalledWith('other', 'r1', undefined)+ })++ it('tells the window which end of the desk an off-desk agent belongs to', async () => {+ // The dial never reports which way the thumb went. It does not have to: an+ // agent's side of the ring is the answer, and the ring is built here.+ AGENTS.length = 0+ for (const agentId of ['a1', 'a2', 'a3']) {+ AGENTS.push({ agentId, registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })+ }+ const focused = vi.fn()+ const host = new DaemonCableHost(wiring({ focused }))+ await settled(host)++ host.setDesk(['a2'])+ await host.listAgents()++ host.focus('a3')+ expect(focused).toHaveBeenLastCalledWith(expect.any(String), 'a3', 'tail')+ host.focus('a1')+ expect(focused).toHaveBeenLastCalledWith(expect.any(String), 'a1', 'head')+ // On the desk already: the window focuses that tile rather than replacing+ // one, so there is no edge to name.+ host.focus('a2')+ expect(focused).toHaveBeenLastCalledWith(expect.any(String), 'a2', undefined)+ })++ it('pushes the agents in ring order, tiles first', async () => {+ AGENTS.length = 0+ for (const agentId of ['a1', 'a2', 'a3', 'a4']) {+ AGENTS.push({ agentId, registeredAt: 1, active: true, terminalAvailable: true, engine: 'claude' })+ }+ const host = new DaemonCableHost(wiring({}))+ await settled(host)++ host.setDesk(['a3', 'a1'])+ const ids = (await host.listAgents()).map((a) => a.id)+ // Tiles in TILE order in the middle; a2 is nearer a1's end walking back,+ // a4 nearer a3's end walking forward.+ expect(ids.slice(ids.indexOf('a3'), ids.indexOf('a3') + 2)).toEqual(['a3', 'a1'])+ expect(ids).toHaveLength(4)+ expect(new Set(ids).size).toBe(4)})it('does not guess a machine for an unknown dial focus', async () => {diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.tsindex 952b52235..e3dc07d50 100644--- a/cli/src/cable/cableHost.ts+++ b/cli/src/cable/cableHost.ts@@ -8,6 +8,7 @@// read, the router is the one the backend already calls for remote machines, and the turn events arrive// as the very `commander_event` cards the WiFi device receives — teed at the socket rather than emitted// again here, so the two device surfaces cannot drift.+import { deskRing, type DeskEdge } from './deskRing.js'import { join } from 'node:path'import { AuthSessionManager, readAuthSession } from '../lib/authSession.js'@@ -43,7 +44,7 @@ export interface CableHostWiring {/** The runtime catalog, from the same provider the web and the WiFi device read. */listModels?: (agentId: string) => Promise<Array<{ id: string }>>/** The dial moved to another agent — the desktop window should show that agent on its own machine. */- focused?: (machineId: string, agentId: string) => void+ focused?: (machineId: string, agentId: string, edge?: DeskEdge) => void/** A finger on the dial's glass, in pieces, while it is down. */scrolled?: (phase: 'down' | 'move' | 'up', dy: number, velocity: number) => voidlog: (line: string) => void@@ -273,6 +274,41 @@ export class DaemonCableHost implements CableHost {* its whole life waiting on the network to answer a question whose answer changes every few minutes.* `refreshRemotes()` does the asking, off to the side, on its own slower clock.*/+ /**+ * The window's tiles, in tile order. Empty until the app says otherwise, and+ * empty is meaningful: with no tiles the ring is just the flat list.+ */+ private desk: string[] = []++ /** Which edge of the desk an off-desk agent belongs to. Rebuilt with the ring. */+ private deskEdge = new Map<string, DeskEdge>()++ /**+ * Every agent this daemon has listed since it started, by id.+ *+ * Kept for ONE purpose: a tile open in the window must always be a tile on the dial. A machine can+ * leave the list for reasons that have nothing to do with its agents — the backend going quiet, the+ * machine going offline while its work stays on screen — and a desk with a hole in it makes a swipe+ * skip a tile and an agent chosen in the window have nowhere to land.+ */+ private knownAgents = new Map<string, CableAgent>()++ /** Tiles currently held on the ring from that memory, so it is logged once and not every tick. */+ private deskHeld = new Set<string>()++ /** Last logged shape of the ring, so the line above prints on change only. */+ private deskShape = ''++ /**+ * The window changed which agents have a tile, or what order they are in.+ *+ * Order is the payload, not just membership: the dial walks the same grid the+ * eyes are on, so the tiles come first in the carousel and in their own order.+ */+ setDesk(agentIds: string[]): void {+ this.desk = [...agentIds]+ }+async listAgents(): Promise<CableAgent[]> {const out = this.localAgents()const { machines } = await this.listMachines()@@ -287,7 +323,66 @@ export class DaemonCableHost implements CableHost {const next = new Map<string, string>()for (const a of out) if (a.machineId) next.set(a.id, a.machineId)this.agentMachine = next- return out++ // The order the dial actually walks: the window's tiles in the middle, and+ // the rest arranged around them so one step off either edge is one step+ // along the list from the tile you left. Computed HERE, on the same+ // snapshot, because this is the only place that holds every machine's+ // agents in one list — the window knows its tiles, not the wheel order they+ // sit in.+ const byId = new Map(out.map((a) => [a.id, a]))++ for (const a of out) this.knownAgents.set(a.id, a)+ // A tile the window has open, whose agent has left the list. Put it back — under the name and+ // machine it was last seen with, so the dial's tile keeps saying what the window's tile says.+ //+ // Gated on being ON THE DESK, and only that: an agent that was deleted, or one simply never+ // opened, must not be resurrected by this memory. The window holding a tile is the whole warrant.+ const missing = this.desk.filter((id) => !byId.has(id))+ for (const id of missing) {+ const remembered = this.knownAgents.get(id)+ if (!remembered) continue+ // Appended, not slotted back where it was. When a machine drops out none of its agents are left+ // to sit beside, so the end of the list is the only honest place; and the ring is built around+ // the DESK, so where a tile sits in the flat list only shifts which agents the arcs reach.+ // Never routed by position either — `agentMachine` below is what sends a turn home.+ out.push(remembered)+ byId.set(id, remembered)+ if (remembered.machineId) this.agentMachine.set(id, remembered.machineId)+ if (!this.deskHeld.has(id)) {+ this.deskHeld.add(id)+ this.wiring.log(`cable: holding ${id.slice(0, 8)} on the ring — the window has a tile for it`)+ }+ }+ for (const id of [...this.deskHeld]) if (!missing.includes(id)) this.deskHeld.delete(id)++ const ring = deskRing(out.map((a) => a.id), this.desk)+ this.deskEdge = ring.edgeOf+ // Walked agents first, then the ones the dial knows but does not walk to —+ // the session sends the count of the first group, so the order is the split.+ const listed = [...ring.order, ...ring.offRing]+ // One line per CHANGE. The failure this catches is silent by nature: tiles+ // whose ids this daemon does not know leave the ring flat and every agent+ // edgeless, which looks exactly like the feature not being installed.+ const onDesk = new Set(this.desk)+ const short = (id: string) => `${onDesk.has(id) ? '*' : ''}${id.slice(0, 4)}`+ // Both halves: what the thumb walks, and what the dial merely knows. Reading+ // only the first half is how "the dial says 5 agents" looked like a counting+ // bug rather than a list that had been cut in two.+ const shape = ring.order.map(short).join(' ')+ + (ring.offRing.length ? ` · off-ring ${ring.offRing.map(short).join(' ')}` : '')+ if (shape !== this.deskShape) {+ this.deskShape = shape+ // The WHOLE ring, marked: `*` is a tile. Short of this the shape has to be+ // guessed from behaviour, and every guess so far has been wrong about+ // which end the agents nobody stepped onto ended up at.+ this.wiring.log(`cable: ring ${shape}`)+ }+ const offRing = new Set(ring.offRing)+ return listed+ .map((id) => byId.get(id))+ .filter((a): a is CableAgent => !!a)+ .map((a) => (offRing.has(a.id) ? { ...a, offRing: true } : a))}/**@@ -300,6 +395,11 @@ export class DaemonCableHost implements CableHost {return this.agentMachine.get(agentId) ?? ''}+ /** Whether this daemon's last list held that agent — see CableHost.knows. */+ knows(agentId: string): boolean {+ return this.agentMachine.has(agentId)+ }+/** True when the agent belongs to this computer (or is unknown, which is handled at the call site). */private isLocalAgent(agentId: string): boolean {const machineId = this.machineOf(agentId)@@ -316,6 +416,14 @@ export class DaemonCableHost implements CableHost {* blip is the common case, and dropping every one of a machine's tiles off the carousel for a few* seconds — then putting them back — is a far worse lie than briefly showing a list that is a minute* old.+ *+ * `unknown` is NOT a reason to drop anything, and reading it as one cost a morning. It means the+ * backend could not be asked — `MachineListCache.degrade()` sets every machine to it in one go when+ * the list cannot be refreshed, on the stated principle that the rows are "stale but not wrong". The+ * agents follow the rows: kept, with no timer, until the backend actually says offline. Measured on+ * the real dial, the old reading emptied a remote machine off the carousel mid-session with no log+ * line, while the window went on showing those agents — which is what made a swipe run out of agents+ * early, and an agent chosen in the window have no tile to move to.*/private refreshRemotes(machines: CableMachine[]): void {if (!this.fleet) return@@ -323,11 +431,18 @@ export class DaemonCableHost implements CableHost {for (const m of machines) {if (m.local) continueconst entry = this.remoteAgents.get(m.id)- if (m.state !== 'ready') {- // Not an error and not worth a grace period: the machine itself says it has nothing to offer.- if (entry && entry.agents.length) this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })+ if (m.state === 'offline' || m.state === 'needs-link') {+ // The machine ITSELF says it has nothing to offer, which is different from not being able to+ // ask it. No grace period, but never silently: an agent leaving the carousel is exactly the+ // event that is impossible to diagnose after the fact from its absence.+ if (entry && entry.agents.length) {+ this.remoteAgents.set(m.id, { agents: [], at: now, asked: entry.asked })+ this.wiring.log(`cable: ${m.name} is ${m.state} — its ${entry.agents.length} agents left the carousel`)+ }continue}+ // Not ready and not refused: the backend could not be asked. Keep what it last said.+ if (m.state !== 'ready') continueif (entry && now - entry.asked < REMOTE_REFRESH_MS) continueif (this.inFlight.has(m.id)) continuethis.inFlight.add(m.id)@@ -386,8 +501,13 @@ export class DaemonCableHost implements CableHost {this.wiring.log(`cable: ignored focus for unknown agent ${agentId}`)return}- this.wiring.log(`cable: focus ${machineId}/${agentId}`)- this.wiring.focused?.(machineId, agentId)+ // Which tile the window should put this agent in, for one it has no tile+ // for: the edge of the desk the agent belongs to. The dial never says which+ // way the thumb went — it does not have to, because an agent's side of the+ // ring already answers it.+ const edge = this.deskEdge.get(agentId)+ this.wiring.log(`cable: focus ${machineId}/${agentId}${edge ? ` (off-desk, ${edge})` : ''}`)+ this.wiring.focused?.(machineId, agentId, edge)}scrolled(phase: 'down' | 'move' | 'up', dy: number, velocity: number): void {diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.tsindex ffef1ea6c..4917d2a3d 100644--- a/cli/src/cable/cableSession.spec.ts+++ b/cli/src/cable/cableSession.spec.ts@@ -562,6 +562,21 @@ describe('cable session', () => {await session.stop()})+ it('says how many of the agents it just sent are on the carousel', async () => {+ // The dial walks the first N and merely knows the rest. A firmware that+ // predates the field ignores it and walks them all, exactly as before.+ const agents: CableAgent[] = [+ { id: 'a1', name: 'one' },+ { id: 'a2', name: 'two', offRing: true },+ ]+ const { session, port } = await connect(makeHost({ listAgents: async () => agents }))+ port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })+ await session.pushAgents()++ expect(port.sent.filter((m) => m.t === 'agents.end').at(-1)).toMatchObject({ ring: 1 })+ await session.stop()+ })+it('marks a summary quiet when the window already has that agent on screen', async () => {const { session, port } = await connect(makeHost({}))port.say({ t: 'hello', product: 'harness', mac: 'aa:bb' })diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.tsindex a6582bc49..fcbc30daf 100644--- a/cli/src/cable/cableSession.ts+++ b/cli/src/cable/cableSession.ts@@ -87,6 +87,16 @@ export interface CableAgent {engine?: stringmodel?: stringeffort?: string+ /**+ * An agent the dial KNOWS but does not walk to.+ *+ * The carousel is built around the window's tiles, and an agent sitting+ * between them in list order is off neither edge — see `deskRing`. It is+ * still sent: the dial counts its agents on the overview and lists them in+ * the pull-down switcher, and a dial that says "5 agents" to someone who has+ * eleven is simply wrong. What it is left out of is the walk.+ */+ offRing?: boolean/*** The machine this agent lives on, and that machine's name.*@@ -155,6 +165,14 @@ export interface CableHost {*/answer(agentId: string, requestId: string, answers: Record<string, string>): voidfocus(agentId: string): void+ /**+ * Does this daemon's own agent list hold that id?+ *+ * Only for saying so. A `focus` for an agent the dial has no tile for lands on nothing, and from the+ * outside that is indistinguishable from the dial ignoring the window — which is exactly the report+ * that took a morning to explain. Optional, so a host that cannot answer simply says nothing.+ */+ knows?(agentId: string): boolean/** A finger moving on the dial's glass, on its way to whatever window is open on this computer. */scrolled(phase: 'down' | 'move' | 'up', dy: number, velocity: number): voidupdateAgent(agentId: string, model?: string, effort?: string): void@@ -886,7 +904,10 @@ export class CableSession {})}- await this.send({ t: 'agents.end' })+ // How many of the agents just sent are on the CAROUSEL. They come first, so+ // a count is enough, and a firmware that predates the field walks all of+ // them exactly as it did before.+ await this.send({ t: 'agents.end', ring: agents.filter((a) => !a.offRing).length })}/**@@ -1076,7 +1097,9 @@ export class CableSession {// A newer selection can arrive while the remote machine RPC/list push is in flight. Never let// this older transaction focus after it finishes.if (generation !== this.appFocusGeneration || agentId === this.dialFocus) return- this.host.log(`cable: following the app to agent ${agentId}`)+ // Said before the frame goes out, not after: the frame itself succeeds either way.+ const unknown = this.host.knows?.(agentId) === false+ this.host.log(`cable: following the app to agent ${agentId}${unknown ? ' — NOT in this daemon\'s list, the dial has no tile for it' : ''}`)this.expectedAppFocusEcho = agentIdthis.expectedAppFocusEchoUntil = Date.now() + APP_FOCUS_SETTLE_MSawait this.focusAgent(agentId)diff --git a/cli/src/cable/deskRing.spec.ts b/cli/src/cable/deskRing.spec.tsnew file mode 100644index 000000000..df4a0fbe4--- /dev/null+++ b/cli/src/cable/deskRing.spec.ts@@ -0,0 +1,196 @@+import { describe, expect, it } from 'vitest'+import { deskRing } from './deskRing.js'++// The fixture from the design review, so a case here reads the same as the case+// that was approved:+//+// machine mac : a1 a2 a3 a4 a5 machine vm : b1 b2 b3 b4+// tiles : [1]=a2 [2]=b1 [3]=a5 [4]=b2+const FLAT = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4']+const DESK = ['a2', 'b1', 'a5', 'b2']++describe('desk ring', () => {+ it('puts the tiles in the middle, in tile order', () => {+ // Tile order, NOT flat order: the dial walks the grid the eyes are on, and+ // a5 sits between b1 and b2 here because that is where its tile sits.+ const { order } = deskRing(FLAT, DESK)+ const desk = order.slice(order.indexOf('a2'), order.indexOf('a2') + 4)+ expect(desk).toEqual(DESK)+ })++ it('the step past the last tile is the next agent on that tile\'s machine', () => {+ // C2: off the tail from b2 (machine vm) lands on b3, not on some agent of+ // whichever machine happens to be first in the list.+ const { order, edgeOf } = deskRing(FLAT, DESK)+ expect(order[order.indexOf('b2') + 1]).toBe('b3')+ expect(edgeOf.get('b3')).toBe('tail')+ })++ it('the step before the first tile is the agent before it on ITS machine', () => {+ // C5: off the head from a2 (machine mac) lands on a1.+ const { order, edgeOf } = deskRing(FLAT, DESK)+ expect(order[order.indexOf('a2') - 1]).toBe('a1')+ expect(edgeOf.get('a1')).toBe('head')+ })++ it('holds each agent it carries once, and says which it does not carry', () => {+ // The ring is the desk plus the two directions off it. a3 and a4 sit BETWEEN+ // the first and last tile in list order, so they are in neither direction —+ // see the note in deskRing.ts for why neither end of the ring can hold them.+ const { order } = deskRing(FLAT, DESK)+ expect(order).toEqual(['a1', 'a2', 'b1', 'a5', 'b2', 'b3', 'b4'])+ expect(new Set(order).size).toBe(order.length)+ expect(order).not.toContain('a3')+ expect(order).not.toContain('a4')+ })++ it('hands back what it left off the walk, rather than losing it', () => {+ // The dial is still TOLD about these. It counts its agents on the overview+ // and lists them in the pull-down switcher, so dropping them outright made+ // it say "5 agents" to someone who has eleven.+ const { order, offRing } = deskRing(FLAT, DESK)+ expect(offRing).toEqual(['a3', 'a4'])+ expect([...order, ...offRing].sort()).toEqual([...FLAT].sort())+ })++ it('an agent belongs to the end of the desk it is reached from', () => {+ const { edgeOf } = deskRing(FLAT, DESK)+ // Past b2, the last tile: the rest of the list forward.+ expect(edgeOf.get('b3')).toBe('tail')+ expect(edgeOf.get('b4')).toBe('tail')+ // Before a2, the first tile: the list running back.+ expect(edgeOf.get('a1')).toBe('head')+ // Off the ring, so no end claims them and there is nothing to replace.+ expect(edgeOf.has('a3')).toBe(false)+ expect(edgeOf.has('a4')).toBe(false)+ })++ it('walks on into the next machine when a machine runs out', () => {+ // C4/D3: b2 is on `vm`, so the step off that tile is the rest of vm — and+ // when a machine runs out the list carries on into the next one, because it+ // is one list. It stops at the list's end, where Settings is.+ const { order } = deskRing(FLAT, DESK)+ expect(order.slice(order.indexOf('b2') + 1)).toEqual(['b3', 'b4'])+ })++ it('the walk ENDS instead of circling, which is what reaches Settings', () => {+ // The bug this rule exists for, found on the real dial: the arcs used to+ // wrap. Every step onto an off-desk agent puts it on the desk and re-forms+ // the ring, so a wrapping walk never reached an end — the thumb went round+ // eleven agents forever, and the Settings and Machines tiles, which the+ // carousel keeps AFTER the agents, could not be reached at all.+ const { order } = deskRing(FLAT, DESK)+ expect(new Set(order).size).toBe(order.length)+ // Both ends of the ring are the list's own ends in that direction, so one+ // more step off either is the overview on the left, Settings on the right.+ expect(order[0]).toBe('a1')+ expect(order[order.length - 1]).toBe('b4')+ })++ it('with nothing past the last tile, the leftovers tuck into the other arc', () => {+ // Mirror of the case above: b4 is the list's last agent AND a tile, so the+ // forward arc is empty and there is no "inside" on the right to tuck into.+ // The left arc takes them — one step in, so its first element is still the+ // list's first agent and the overview stays one step off the ring's end.+ const { order } = deskRing(FLAT, ['a3', 'b4'])+ expect(order[0]).toBe('a1')+ expect(order[order.length - 1]).toBe('b4')+ // The step left off a3 is still the agent before it in the list.+ expect(order[order.indexOf('a3') - 1]).toBe('a2')+ })++ it('a desk holding BOTH ends of the list is the whole ring', () => {+ // Reported twice from the dial, once from each side: tile 1 was the first+ // agent in the list and tile 4 the last, so there is nothing to the left of+ // the first tile and nothing to the right of the last one. The swipe then+ // walks the open tiles and nothing else — one step off either end is the+ // overview or Settings, which is what the end of the list means.+ const desk = ['a1', 'a3', 'b1', 'b4']+ const { order, edgeOf } = deskRing(FLAT, desk)+ expect(order).toEqual(desk)+ // No end is left to claim, so nothing off the ring can claim one.+ expect(edgeOf.size).toBe(0)+ })++ it('one agent past the desk is that step, and the ring end', () => {+ const desk = ['a1', 'a3', 'b1', 'b3']+ const { order, edgeOf } = deskRing(FLAT, desk)+ expect(order).toEqual([...desk, 'b4'])+ expect(edgeOf.get('b4')).toBe('tail')+ })++ it('a walk off the last tile reaches the other machine before Settings', () => {+ // The exact shape on the dial when this was reported, ids and all: nine+ // agents on this computer and two on `machine-remote-3`, four tiles open,+ // the last of them `fa69` on that remote machine.+ const flat = [+ '5899', '37c1', 'dbae', 'acf6', 'f9aa', 'b884', '562d', 'a9e2', '9e01', // this computer+ 'fa69', 'f3c3', // machine-remote-3+ ]+ const { order } = deskRing(flat, ['5899', 'acf6', 'b884', 'fa69'])+ // One step right off the last tile is that machine's remaining agent, and+ // the ring ends there — so the step after it is Settings.+ expect(order[order.indexOf('fa69') + 1]).toBe('f3c3')+ expect(order[order.length - 1]).toBe('f3c3')+ // And one step LEFT off the first tile is the overview, because `5899` is+ // the first agent in the list: exactly the report this rule came from.+ expect(order[0]).toBe('5899')+ })++ it('the left end is CLEAR when the first tile is the first agent', () => {+ // Straight from the dial: pane 1 held the first agent in the list, and a+ // swipe left landed on some other machine's agent instead of the overview.+ // Leftovers used to be parked at the far left, which put one of them+ // between the first tile and the overview the carousel keeps before the+ // agents.+ const { order } = deskRing(FLAT, ['a1', 'b2']);+ expect(order[0]).toBe('a1')+ })++ it('the walk back ENDS at the start of the list, before the overview', () => {+ const { order } = deskRing(FLAT, ['a3'])+ // Left off the only tile: a2, then a1, then the carousel's own overview.+ const at = order.indexOf('a3')+ expect(order.slice(0, at)).toEqual(['a1', 'a2'])+ })++ it('a single tile makes the dial a plain browser of the list', () => {+ // C6: one tile means both edges are the same tile, so both directions+ // replace it. Everything belongs to the forward arc; nothing is listed+ // twice.+ const { order, edgeOf } = deskRing(FLAT, ['a3'])+ expect([...order].sort()).toEqual([...FLAT].sort())+ expect(new Set(order).size).toBe(order.length)+ // One step each way off the only tile is one step each way in the list.+ const at = order.indexOf('a3')+ expect(order[at + 1]).toBe('a4')+ expect(order[at - 1]).toBe('a2')+ // Both edges are the same tile, so whichever way the thumb goes the window+ // replaces that tile — the dial is a plain browser of the list.+ expect(edgeOf.get('a4')).toBe('tail')+ expect(edgeOf.get('a2')).toBe('head')+ })++ it('with no tiles the flat list stands, and no agent claims an edge', () => {+ // C7/D4: there is no desk to walk off, so there is no edge tile to replace+ // — the window opens a new tile instead, and that is its call to make.+ const { order, edgeOf } = deskRing(FLAT, [])+ expect(order).toEqual(FLAT)+ expect(edgeOf.size).toBe(0)+ })++ it('ignores a tile naming an agent the list has never heard of', () => {+ // A tile can name an agent on a machine that has gone quiet. That is a+ // reason to leave it out of the ring, not to drop the ring.+ const { order } = deskRing(FLAT, ['a2', 'ghost', 'b1'])+ expect(order).toContain('a2')+ expect(order).toContain('b1')+ expect(order).not.toContain('ghost')+ })++ it('every tile open means a ring of exactly the tiles', () => {+ const { order, edgeOf } = deskRing(['a1', 'a2'], ['a2', 'a1'])+ expect(order).toEqual(['a2', 'a1'])+ expect(edgeOf.size).toBe(0)+ })+})diff --git a/cli/src/cable/deskRing.ts b/cli/src/cable/deskRing.tsnew file mode 100644index 000000000..500670ecf--- /dev/null+++ b/cli/src/cable/deskRing.ts@@ -0,0 +1,109 @@+/**+ * The order the dial's carousel walks, given what the window has on screen.+ *+ * The dial holds every agent on every machine in one flat ring. This turns that+ * flat list into a ring built around THE DESK — the agents the window has a tile+ * for, in tile order — so a thumb walking the dial walks the same grid the eyes+ * are looking at.+ *+ * Past either edge of the desk the ring continues into the agents that have no+ * tile, and WHICH ones depends on the edge you left from: forward from the last+ * tile picks up the flat list after that agent, backward from the first tile+ * picks it up before. Two boundary positions cut the flat list into two arcs,+ * one for each edge, so every agent is reachable from exactly one direction and+ * none is reachable twice.+ *+ * Landing on one of those agents is what puts it ON the desk — the window+ * replaces the tile at the edge it belongs to. Which is why the arcs matter+ * beyond ordering: the arc an agent sits in IS the answer to "which tile does+ * this replace", and it is an answer the daemon can give without the dial ever+ * reporting which way the thumb moved.+ */+export type DeskEdge = 'head' | 'tail'++export interface DeskRing {+ /** Ids in carousel order: head arc, then the desk, then the tail arc. */+ order: string[]+ /**+ * Agents the carousel does not walk: the ones between the desk's outermost+ * tiles in list order, which are in neither direction off an edge.+ *+ * They are still SENT to the dial — it keeps a tile's worth of knowledge for+ * every agent, and the overview's count and the pull-down switcher both read+ * that, so leaving them out made the dial say "5 agents" to someone who has+ * eleven. What they are left out of is the walk.+ */+ offRing: string[]+ /** Which edge an off-desk agent belongs to. Desk members are absent. */+ edgeOf: Map<string, DeskEdge>+}++/**+ * @param flat every agent id, in the order the dial reads them today (this+ * computer first, then each machine in wheel order).+ * @param desk the window's tiles, in tile order. Ids the flat list does not+ * know are ignored: a tile can name an agent on a machine that has+ * gone quiet, and a ring is no place to learn that.+ */+export function deskRing(flat: string[], desk: string[]): DeskRing {+ const known = new Set(flat)+ const onDesk = desk.filter((id) => known.has(id))+ const edgeOf = new Map<string, DeskEdge>()++ // No tiles: nothing to build a ring around, and the flat list is already the+ // answer. Everything is off-desk, and landing on any of it opens a new tile+ // rather than replacing one — so neither edge applies.+ if (onDesk.length === 0) return { order: [...flat], offRing: [], edgeOf }++ const deskSet = new Set(onDesk)+ const rest = flat.filter((id) => !deskSet.has(id))+ const first = flat.indexOf(onDesk[0])+ const last = flat.indexOf(onDesk[onDesk.length - 1])++ // The arcs do NOT wrap, and that is the whole point of them.+ //+ // The dial's carousel is `overview → agents… → Settings → Machines`, so the+ // way back to those screens is off the END of the agents. A wrapping arc+ // never has an end: every step onto an off-desk agent puts it ON the desk,+ // the ring re-forms around it, and the walk begins again — measured on the+ // real dial, that is a thumb going round eleven agents forever with Settings+ // and Machines unreachable. So forward stops at the last agent in the list,+ // and the carousel's own wrap takes it from there.+ const pos = new Map(flat.map((id, at) => [id, at]));+ const firstPos = pos.get(onDesk[0])!+ const lastPos = pos.get(onDesk[onDesk.length - 1])!++ // Past the last tile: the list carrying on from THAT agent — the rest of its+ // machine, then the machines after it.+ const tail = rest.filter((id) => pos.get(id)! > lastPos)+ const claimed = new Set(tail)+ // Before the first tile: the list running back from it. Placed before the+ // desk, so one step left off the desk is one step back in the list.+ const head = rest.filter((id) => pos.get(id)! < firstPos && !claimed.has(id))+ for (const id of head) claimed.add(id)+ // Agents that lie BETWEEN the desk's outermost tiles in list order are not on+ // the ring at all.+ //+ // Stepping off a tile means "carry on through the list in that direction", so+ // an agent inside the desk's own span is in neither direction — it is not the+ // next thing left of the first tile, nor the next thing right of the last+ // one. Every attempt to give it a place put it at an END of the ring, and+ // both ends are spoken for: the carousel keeps the overview before the agents+ // and Settings after them, so an agent parked at either one stands between+ // the desk and the way back to those screens. Measured on the real dial,+ // twice, once from each side.+ //+ // They are returned as `offRing` rather than dropped: the dial is still told+ // about them, so the overview's count and the pull-down switcher stay honest.+ // They are simply not walked to — reach one from the window, or from that+ // switcher, and opening it puts it on the desk and back on the ring.+ // Which end an off-desk agent was reached from IS which tile it replaces. The+ // dial never reports the direction of the thumb and does not have to: its side+ // of the ring already says it.+ for (const id of tail) edgeOf.set(id, 'tail')+ for (const id of head) edgeOf.set(id, 'head')++ const order = [...head, ...onDesk, ...tail]+ const placed = new Set(order)+ return { order, offRing: rest.filter((id) => !placed.has(id)), edgeOf }+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f5e3cb463..988ccd950 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -100,7 +100,7 @@ import { CommanderMirror } from './lib/commander.js'import {setSummaryPoolDeviceConnected,shutdownSummaryPool,- summarizeTurnText,+ deriveTurnSummary,syncSummaryPoolSessions,} from './lib/summarize.js'import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from './lib/voiceRouter.js'@@ -193,6 +193,18 @@ let cableRef: CableSession | null = null/** The same object the session holds — module scope so the recap gates can ask which machine is selected* without threading it through every constructor between here and there. */let cableHostRef: DaemonCableHost | null = null+/**+ * The window's tiles, in tile order, as last reported.+ *+ * Kept HERE rather than only handed to the cable host, because the window can+ * report them before that host exists: the local websocket server is listening+ * long before the cable is wired up, and a daemon restart has the app+ * reconnecting into that window. The roster is only re-sent when it CHANGES, so+ * one early report used to leave the dial's ring flat and edgeless for as long+ * as the tiles held still — which looks exactly like the feature not being+ * installed, and cost most of a morning proving otherwise.+ */+let appPaneAgents: string[] = []/** Module scope for the same reason cableRef is: shutdown() has to release the socket. */let deviceLinkRef: DeviceLink | null = null@@ -1817,15 +1829,11 @@ async function runForeground(session: AuthSession): Promise<void> {// Live cards stream to whatever is actually rendering. The dial has one screen and it is always the// one in front of the user, so a cable session counts as active by construction.active: () => backend.hasActiveCommander() || cableWatchingLocal(),- summarize: async (text, signal, userMessage, sessionId) => {- const session = sessionId ? registry.bySession(sessionId) : undefined- // Gateway agents recap through OpenRouter directly (no vendor credential to spend). The probe is- // cached per live process, so this resolves without touching the process table again.- const gateway = session?.gateway === 'ori' && session.processIdentity- ? await probeGatewayRuntime(session.processIdentity)- : undefined- return summarizeTurnText(text, signal, userMessage, session?.engine ?? 'claude', gateway)- },+ // NO MODEL IN THE LOOP. The dial is cabled to the Mac whose window already shows this text in+ // full, so the recap is a glance and the detail is one turn of the head away. A one-shot recap+ // cost ~9s of the user's turn to say something they were already looking at.+ summarize: async (text) => deriveTurnSummary(text),+ summarizeIsLocal: true,nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,readLastTurn: async (sessionId) => {@@ -2762,6 +2770,12 @@ async function runForeground(session: AuthSession): Promise<void> {// tiles on a grid all four are on screen, and asking which one the eye is// on is a question the window cannot answer honestly anyway.onAppPanes: (agentIds) => {+ // ORDER matters here, not just membership. The dial's carousel is built+ // around these — tiles first, in tile order — so the thumb walks the same+ // grid the eyes are on. `openPaneAgents` below only ever asks "is this+ // one on screen", which is why it can stay a set.+ appPaneAgents = agentIds+ cableHostRef?.setDesk(agentIds)const next = new Set(agentIds)// Logged on CHANGE only. It fires on every pane add, close and reconnect,// and it is the one place the whole feature is observable from — without@@ -3762,11 +3776,18 @@ async function runForeground(session: AuthSession): Promise<void> {// Both of these are LOCAL-ONLY on purpose (backend.sendLocal, not backend.send): they describe a hand// at this desk, not a change in what the machine is doing, and the cloud web audience may be sitting// at another computer entirely.- focused: (machineId, agentId) => backend.sendLocal({ type: 'dial_focus', payload: { machineId, agentId } }),+ // `edge` is present only for an agent the window has NO tile for, and says+ // which end of the desk it belongs to — so the window replaces the first+ // tile or the last one rather than guessing, and the dial never has to+ // report which way the thumb moved.+ focused: (machineId, agentId, edge) =>+ backend.sendLocal({ type: 'dial_focus', payload: { machineId, agentId, ...(edge ? { edge } : {}) } }),scrolled: (phase, dy, velocity) => backend.sendLocal({ type: 'dial_scroll', payload: { phase, dy, velocity } }),log: (line) => console.log(`[cable] ${line}`),}, fleet)cableHostRef = cableHost+ // Anything the window said while this was still being built.+ cableHost.setDesk(appPaneAgents)const cable = new CableSession(cableHost, join(env.ADAPTER_DATA_DIR, 'dial.log'))cableRef = cablediff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.tsindex 9884cd0fd..806310115 100644--- a/cli/src/lib/commander.ts+++ b/cli/src/lib/commander.ts@@ -39,6 +39,8 @@ export interface CommanderMirrorOpts {* badges. Omitted → defaults to hasDevice (single-machine firmware: attached == active, streams as before). */active?: () => booleansummarize: (text: string, signal?: AbortSignal, userMessage?: string, sessionId?: string) => Promise<string | null>+ /** True when `summarize` is a local derivation rather than a model call — see startSummary. */+ summarizeIsLocal?: boolean/** Agent display name for a sessionId — rides the summary's outer frame so a BACKGROUND machine's device* notification shows the agent name on line 2 (its tile isn't loaded). */nameFor?: (sessionId: string) => string | undefined@@ -532,8 +534,14 @@ export class CommanderMirror {this.trace(sessionId, `${sid} summarizing · source=${source} · textLen=${text.length} · device=${device}${this.opts.recapForce ? ' · recapForce' : ''}${ask ? ` · ask="${ask}"` : ''}`)// Device: busy "Summarizing…" card. Web: the "Summarizing for device…" indicator (mirrors the// node's handleBrainSummaryEvent — the web ignores the summary text, only toggles the flag).- this.emit(sessionId, { kind: 'processing', text: 'Summarizing…' })- this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId } })+ //+ // Both are skipped when the summary is derived locally: it lands in the same tick, so the card+ // would be a flash of "Summarizing…" replaced before anyone could read it — a waiting state for a+ // wait that no longer happens.+ if (!this.opts.summarizeIsLocal) {+ this.emit(sessionId, { kind: 'processing', text: 'Summarizing…' })+ this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId } })+ }this.opts.summarize(text, ac.signal, userMessage, sessionId)@@ -553,7 +561,9 @@ export class CommanderMirror {} else {this.trace(sessionId, `${sid} summarizer returned NULL after ${ms}ms → done`)this.emit(sessionId, { kind: 'done', text: 'done' })- this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })+ if (!this.opts.summarizeIsLocal) {+ this.opts.sendWeb({ type: 'turn_summary_pending', dbSessionId: sessionId, payload: { sessionId, done: true } })+ }}}).catch((err) => {diff --git a/cli/src/lib/deriveTurnSummary.spec.ts b/cli/src/lib/deriveTurnSummary.spec.tsnew file mode 100644index 000000000..00bd41987--- /dev/null+++ b/cli/src/lib/deriveTurnSummary.spec.ts@@ -0,0 +1,68 @@+// The dial's recap, without a model.+//+// The interesting cases are all the same shape: an engine's last message is MARKDOWN, and the naive+// `slice(0, 60)` of markdown is a heading and a severed word. What is asserted here is that the cut+// lands on words a person can read.+import { describe, expect, it } from 'vitest'+import { BODY_MAX_CHARS, RECAP_MAX_CHARS, deriveTurnSummary } from './summarize.js'++const parts = (text: string) => {+ const out = deriveTurnSummary(text)+ if (!out) return null+ const nl = out.indexOf('\n\n')+ return { recap: out.slice(0, nl), body: out.slice(nl + 2) }+}++describe('deriveTurnSummary', () => {+ it('takes the first real sentence, not the markdown around it', () => {+ const p = parts('## Kết quả\n\n- **SJC**: 149,1 triệu đồng/lượng (bán ra, TP.HCM)\n- PNJ: 148 triệu')!+ // Not "## Kết quả", which is what a heading collapses to and says nothing.+ expect(p.recap).not.toContain('#')+ expect(p.recap).toContain('SJC')+ expect(p.recap).not.toContain('**')+ })++ it('skips a bare label that names the shape of the answer', () => {+ const p = parts('Kết quả:\n\nĐã cập nhật đường retry và chạy lại test.')!+ expect(p.recap.startsWith('Đã cập nhật')).toBe(true)+ })++ it('marks a cut with an ellipsis and keeps to the budget', () => {+ const long = 'Đã cập nhật đường retry trong src/api/client.ts, chạy lại toàn bộ test và mọi thứ đều xanh.'+ const p = parts(long)!+ expect(p.recap.length).toBeLessThanOrEqual(RECAP_MAX_CHARS)+ expect(p.recap.endsWith('…')).toBe(true)+ // The cut lands between words, not through one.+ expect(p.recap.slice(0, -1)).toBe(p.recap.slice(0, -1).trimEnd())+ expect(long.startsWith(p.recap.slice(0, -1))).toBe(true)+ })++ it('leaves something that already fits completely alone', () => {+ const p = parts('SJC hôm nay bán ra 149,1 triệu đồng/lượng.')!+ expect(p.recap).toBe('SJC hôm nay bán ra 149,1 triệu đồng/lượng.')+ expect(p.recap.endsWith('…')).toBe(false)+ })++ it('caps the body too, since the window is where anyone reads the whole thing', () => {+ const p = parts('a'.repeat(40) + ' ' + 'b'.repeat(400))!+ expect(p.body.length).toBeLessThanOrEqual(BODY_MAX_CHARS)+ expect(p.body.endsWith('…')).toBe(true)+ })++ it('throws away fenced code and tables rather than drawing half a shell command', () => {+ const p = parts('Chạy lệnh sau để kiểm tra.\n\n```sh\nnpm run build && npm test -- --watch\n```')!+ expect(p.body).not.toContain('npm run build')+ expect(p.recap).toContain('Chạy lệnh')+ })++ it('does not let one unbroken token collapse the line to nothing', () => {+ // A word-boundary cut would leave almost nothing here, so the budget wins over the boundary.+ const p = parts('/Users/duynguyen/go/src/github.com/autonomous-ai/autonomous-harness/cli/src/lib/x.ts')!+ expect(p.recap.length).toBeGreaterThan(RECAP_MAX_CHARS - 5)+ })++ it('answers null when there is nothing a person could read', () => {+ expect(deriveTurnSummary('')).toBeNull()+ expect(deriveTurnSummary('```\ncode only\n```')).toBeNull()+ })+})diff --git a/cli/src/lib/summarize.ts b/cli/src/lib/summarize.tsindex 6a4656578..ffe09abd3 100644--- a/cli/src/lib/summarize.ts+++ b/cli/src/lib/summarize.ts@@ -215,6 +215,95 @@ async function cleanupRecapSession(engine: AgentEngine, scratch: string, sessionif (engine === 'cursor') await cleanupCursorOneShotSession(sessionId)}+/** The tile headline. */+export const RECAP_MAX_CHARS = 60+/** The body the dial's tap-to-read screen shows. */+export const BODY_MAX_CHARS = 250++/**+ * Turn the engine's own final message into the dial's `recap\n\nbody`, with no model in the loop.+ *+ * The dial is cabled to a Mac whose window is already showing this text in full, so the recap is a+ * GLANCE, not a substitute for reading: whoever wants the detail turns their head. That is what buys+ * the ~9s the one-shot used to cost on every turn, and it is why this truncates with an ellipsis where+ * the model-written recap never did — "…" is honest here precisely because the rest is one glance away.+ *+ * The work is not the cut, it is what gets cut. An engine's last message is markdown: a heading, then+ * bullets, then maybe a table. `slice(0, 60)` of that yields "## Kết quả\n\n- **SJC**: 149,1 triệu+ * đồng/lượn" — a markdown heading and a severed word. So the text is flattened to prose first, and the+ * recap comes from the first line that carries any.+ */+export function deriveTurnSummary(text: string): string | null {+ // Markers go, LINE BREAKS STAY. Flattening first merges a label into the sentence under it — "Kết+ // quả:" and its answer become one run with no boundary left to find, and the recap opens on the+ // word that says least.+ const stripped = stripMarkdown(text)+ const body = stripped.replace(/\s+/g, ' ').trim()+ if (!body) return null+ const recap = clip(firstProseLine(stripped) || body, RECAP_MAX_CHARS)+ return `${recap}\n\n${clip(body, BODY_MAX_CHARS)}`+}++/** Cut to `max` characters on a word boundary, marking the cut. Never mid-word if it can be helped. */+function clip(text: string, max: number): string {+ const t = text.trim()+ if (t.length <= max) return t+ const head = t.slice(0, max - 1)+ const space = head.lastIndexOf(' ')+ // Only honour the word boundary when it is not throwing most of the budget away — a long unbroken+ // token (a path, a URL) would otherwise collapse the line to nothing.+ return `${(space > max * 0.6 ? head.slice(0, space) : head).replace(/[\s,;:–—-]+$/, '')}…`+}++/**+ * Markdown → one flat run of prose the dial can draw.+ *+ * Fenced code and tables go entirely: a tile is 466px of round glass, and half a shell command wrapped+ * across three lines says less than the sentence next to it.+ */+function stripMarkdown(text: string): string {+ return text+ .replace(/```[\s\S]*?```/g, '\n') // fenced code+ .replace(/^\s*\|.*\|\s*$/gm, '') // table rows+ .replace(/^\s{0,3}#{1,6}\s*/gm, '') // headings — the marker, not the words+ .replace(/^\s*[-*+]\s+/gm, '') // bullet markers+ .replace(/^\s*\d+\.\s+/gm, '') // ordered-list markers+ .replace(/^\s*>\s?/gm, '') // block quotes+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1') // links and images → their label+ .replace(/[*_~`]/g, '') // emphasis and inline code marks+ .replace(/[ \t]+/g, ' ')+ .trim()+}++/**+ * The first line with real words in it.+ *+ * Skips lead-ins that name the shape of the answer rather than the answer — "Kết quả:", "Here's what I+ * found:" — because those are exactly what a heading collapses into once its `##` is gone, and a tile+ * reading "Kết quả" has told the user nothing.+ */+function firstProseLine(stripped: string): string {+ // Lines first, then sentences within a line: the line is the structure markdown actually carries,+ // and a label only reads as a label while it still has a line of its own.+ const candidates: string[] = []+ for (const line of stripped.split(/\n+/)) {+ for (const piece of line.split(/(?<=[.!?])\s+/)) {+ const candidate = piece.trim()+ if (candidate.length < 3) continue+ if (/^[^\p{L}\p{N}]+$/u.test(candidate)) continue // punctuation or symbols only+ candidates.push(candidate)+ }+ }+ // A LABEL is a short line that never finishes a thought — "Kết quả:", and the same words again once+ // a heading's `##` has been taken off it. Both name the shape of the answer instead of giving it, so+ // skip past them while there is anything else to say. Alone, a short line IS the answer.+ const answer = candidates.find((c) => c.length > LABEL_MAX_CHARS || /[.!?]$/.test(c)) ?? candidates[0]+ return (answer ?? '').replace(/:$/, '')+}++/** Longer than this and a line is saying something, not naming a section. */+const LABEL_MAX_CHARS = 24+export async function summarizeTurnText(text: string,signal?: AbortSignal,