Skip to content

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

fix(route): record a question when it is asked, not when its answer is summarised

0xdiego2575d8496c7a53
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 18401bd4f..441b54c25 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -364,6 +364,8 @@ export class BackendSocket {
onBusy: (() => void) | null = null
/** Answers the device `project_recent` RPC (cli.ts wires this to CommanderMirror.recent). */
recentProvider: RecentProvider | null = null
+ /** The person's own last questions for an agent, newest first. See the `agent_recent` case. */
+ recentAsksProvider: ((agentId: string, n: number) => string[]) | null = null
/** Runtime Model/Effort integration, wired by cli.ts for registered tmux sessions. */
runtimeModelsProvider: ((sessionId?: string) => Promise<RuntimeModelOption[]>) | null = null
/** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field
@@ -1447,7 +1449,13 @@ export class BackendSocket {
if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
const n = Math.max(1, Math.min(5, Number(payload.n) || 2))
const events = this.recentProvider ? this.recentProvider(projectId, n) : []
- reply(type, requestId, { agentId: projectId, events })
+ // ASKS TRAVEL AS THEIR OWN LIST, beside the events rather than inside them. A question exists
+ // the moment it is asked; a recap exists once the turn has been answered and summarised. They
+ // are different lengths on any machine where a turn ended without one, so a reply that folds
+ // the questions into the event rows loses exactly the newest ones — and a REMOTE agent then
+ // reaches the router with nothing but its name.
+ const asks = this.recentAsksProvider ? this.recentAsksProvider(projectId, n) : []
+ reply(type, requestId, { agentId: projectId, events, asks })
return
}
diff --git a/cli/src/cable/cableHost.spec.ts b/cli/src/cable/cableHost.spec.ts
index 2cb9fd73e..107f8fef7 100644
--- a/cli/src/cable/cableHost.spec.ts
+++ b/cli/src/cable/cableHost.spec.ts
@@ -23,6 +23,7 @@ function wiring(over: Partial<CableHostWiring> = {}): CableHostWiring {
stopTurn: vi.fn(),
answer: vi.fn(),
recent: () => [],
+ recentAsks: () => [],
log: vi.fn(),
...over,
}
@@ -31,6 +32,7 @@ function wiring(over: Partial<CableHostWiring> = {}): CableHostWiring {
function fleetOf(machines: FleetMachine[]): MachineFleet {
return {
list: async () => ({ machines, source: 'backend' as const }),
+ recentAsks: async () => [],
online: async () => {},
select: async () => {},
release: vi.fn(),
diff --git a/cli/src/cable/cableHost.ts b/cli/src/cable/cableHost.ts
index a3630f570..63b9a6684 100644
--- a/cli/src/cable/cableHost.ts
+++ b/cli/src/cable/cableHost.ts
@@ -30,6 +30,8 @@ export interface RecentTurn {
}
export interface CableHostWiring {
+ /** The person's own last questions to a LOCAL agent, newest first. */
+ recentAsks: (agentId: string) => string[]
machineName: () => string
/** This computer's machineId, or '' when the daemon has never resolved one (signed out). */
machineId: () => string
@@ -620,6 +622,21 @@ export class DaemonCableHost implements CableHost {
.filter((s) => s.recap || s.text || s.ask)
}
+ /**
+ * The person's own last questions to an agent, newest first — what the router ranks on.
+ *
+ * Its own trip rather than a field on [recentSummaries]: a question is recorded when it is asked and
+ * a recap when the answer is summarised, so the two lists are different lengths on any machine where
+ * a turn ended without one. Folding them together is what left the newest question — the one that
+ * says where the next one belongs — off the end.
+ */
+ async recentAsks(agentId: string): Promise<string[]> {
+ const raw = this.isLocalAgent(agentId)
+ ? this.wiring.recentAsks(agentId)
+ : await this.fleet!.recentAsks(this.machineOf(agentId), agentId)
+ return raw.map((a) => (a || '').replace(/\s+/g, ' ').trim()).filter(Boolean)
+ }
+
async listModels(agentId: string): Promise<string[]> {
if (!this.isLocalAgent(agentId)) return this.fleet!.listModels(this.machineOf(agentId), agentId)
@@ -688,9 +705,7 @@ export class DaemonCableHost implements CableHost {
// when an agent has none; the local ladder below it still reads `recentSummary`, where a recap
// standing in for a missing ask is the best it has. Mixing the two into one field is what let a
// summary of the agent's own replies reach a prompt that called them the person's questions.
- prompts: (await this.recentSummaries(a.id))
- .map((r) => (r.ask || '').replace(/\s+/g, ' ').trim())
- .filter(Boolean),
+ prompts: await this.recentAsks(a.id),
recentSummary: (await this.recentSummaries(a.id))
.map((r) => r.ask || r.recap || r.text || '')
.filter(Boolean)
diff --git a/cli/src/cable/machineFleet.ts b/cli/src/cable/machineFleet.ts
index e96397a44..945e70809 100644
--- a/cli/src/cable/machineFleet.ts
+++ b/cli/src/cable/machineFleet.ts
@@ -73,6 +73,8 @@ export interface MachineFleet {
updateAgent(machineId: string, agentId: string, model?: string, effort?: string): void
listModels(machineId: string, agentId: string): Promise<string[]>
recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]>
+ /** The person's own last questions to that agent, newest first — the router's input. */
+ recentAsks(machineId: string, agentId: string): Promise<string[]>
/**
* How the last round trip to this machine went, or null if nobody has asked it yet.
*
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 9ced8d4f5..bae9d1383 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -1901,6 +1901,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device
// and the voice router know. Resolve across the two, or every tile restores empty.
backend.recentProvider = (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n)
+ backend.recentAsksProvider = (id, n) => mirror.recentAsks(registry.resolve(id)?.sessionId || id, n)
const runtimeController = new RuntimeProfileController({
manager: runtimeProfiles,
@@ -2958,9 +2959,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// a Vietnamese sentence at sixty takes the object with it — which is the topic. The bound that
// matters now lives at the two ends: ASK_MAX_CHARS where the question is recorded, and the
// endpoint's own per-prompt ceiling.
- prompts: (await host.recentSummaries(agent.id))
- .map((turn) => (turn.ask || '').replace(/\s+/g, ' ').trim())
- .filter(Boolean),
+ prompts: await host.recentAsks(agent.id),
})))
// 20s, not the shared 12s: this path answers a person watching a spinner in their own window, and
// it is under nobody else's deadline — the app's rpc waits longer still. The dial and the web keep
@@ -4027,6 +4026,7 @@ async function runForeground(session: AuthSession): Promise<void> {
// named a question that does not exist.
answer: (agentId, requestId, answers) => backend.onQuestionAnswer?.({ agentId, requestId, answers }),
recent: (id, n) => mirror.recent(registry.resolve(id)?.sessionId || id, n),
+ recentAsks: (id) => mirror.recentAsks(registry.resolve(id)?.sessionId || id),
runtimeProfile: (session) => runtimeProfiles.selectedModel(session),
updateAgent: (agentId, model, effort) => {
const s = registry.resolve(agentId)
diff --git a/cli/src/device/deviceFleet.ts b/cli/src/device/deviceFleet.ts
index bb389f102..d03d1a274 100644
--- a/cli/src/device/deviceFleet.ts
+++ b/cli/src/device/deviceFleet.ts
@@ -48,6 +48,8 @@ export interface DeviceFleetOpts {
export class DeviceFleet implements MachineFleet {
private lingerTimer: NodeJS.Timeout | null = null
private readonly recapCache = new Map<string, RecentTurn[]>()
+ /** Filled by the same `agent_recent` round trip the recaps come from — see recentSummaries. */
+ private readonly askCache = new Map<string, string[]>()
private readonly listeners = new Set<(e: FleetEvent) => void>()
/**
* How the last round trip to each machine went.
@@ -117,6 +119,7 @@ export class DeviceFleet implements MachineFleet {
// machine you were reading and pick up another one"; now every other machine's tiles are still on the
// dial's carousel, and blanking them would make a select look like N agents forgetting their work.
for (const key of [...this.recapCache.keys()]) if (key.startsWith(`${machineId}:`)) this.recapCache.delete(key)
+ for (const key of [...this.askCache.keys()]) if (key.startsWith(`${machineId}:`)) this.askCache.delete(key)
// NOTHING is read over the lane for this computer. Selecting it is an ANNOUNCEMENT — it tells the
// backend where the dial is — and its agents, turns and recaps all come from this process. Asking the
// cloud for them instead round-trips to ourselves and, because a computer-backed machine is
@@ -143,6 +146,7 @@ export class DeviceFleet implements MachineFleet {
if (!immediate) return
this.opts.link.release()
this.recapCache.clear()
+ this.askCache.clear()
}
@@ -235,6 +239,15 @@ export class DeviceFleet implements MachineFleet {
return raw.map((m) => (typeof m === 'string' ? m : String((m as Record<string, unknown>)?.id ?? ''))).filter(Boolean)
}
+ /** The person's own last questions to a remote agent, newest first. Cached with the recaps. */
+ async recentAsks(machineId: string, agentId: string): Promise<string[]> {
+ const key = `${machineId}:${agentId}`
+ const cached = this.askCache.get(key)
+ if (cached) return cached
+ await this.recentSummaries(machineId, agentId) // one round trip fills both
+ return this.askCache.get(key) ?? []
+ }
+
async recentSummaries(machineId: string, agentId: string): Promise<RecentTurn[]> {
const key = `${machineId}:${agentId}`
const cached = this.recapCache.get(key)
@@ -256,6 +269,10 @@ export class DeviceFleet implements MachineFleet {
}
})
this.recapCache.set(key, turns)
+ this.askCache.set(
+ key,
+ (Array.isArray(res.asks) ? res.asks : []).filter((a): a is string => typeof a === 'string' && !!a.trim()),
+ )
return turns
} catch (err) {
diff --git a/cli/src/lib/commander.spec.ts b/cli/src/lib/commander.spec.ts
index d6c6a9bf0..3bbdf9f79 100644
--- a/cli/src/lib/commander.spec.ts
+++ b/cli/src/lib/commander.spec.ts
@@ -41,10 +41,50 @@ describe('CommanderMirror recap events', () => {
await vi.runAllTimersAsync()
await Promise.resolve()
- const turn = mirror.recent('session-ask', 3)[0]
- expect(turn.ask).toBe('Chiến tranh thế giới thứ hai kết thúc vào năm nào?')
- // The recap is still exactly what it was — this adds a field, it does not change one.
- expect(turn.recap).toBe('1945.')
+ expect(mirror.recentAsks('session-ask')).toEqual(['Chiến tranh thế giới thứ hai kết thúc vào năm nào?'])
+ // The recap is still exactly what it was — this adds a list, it does not change one.
+ expect(mirror.recent('session-ask', 3)[0].recap).toBe('1945.')
+ })
+
+ it('keeps the question even when the turn produces no summary at all', async () => {
+ // The fault this replaced: the ask was written in the summariser's success branch, so a turn with
+ // no assistant text — or a summariser that returned null — left no record of what was asked.
+ // Measured on a real machine: three of eight agents had any questions on record, and the missing
+ // ones were the NEWEST, which is the signal the router most needs.
+ const mirror = new CommanderMirror({
+ send: () => {},
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+
+ mirror.ingest([
+ { type: 'turn_started', payload: { userMessage: 'qua bong vang vietnam 2026 thuoc ve ai' } },
+ { type: 'turn_ended', payload: {} },
+ ] as LiveEvent[], 'session-nosummary')
+
+ await vi.runAllTimersAsync()
+ await Promise.resolve()
+
+ expect(mirror.recentAsks('session-nosummary')).toEqual(['qua bong vang vietnam 2026 thuoc ve ai'])
+ // …and there is genuinely no recap for it. The question stands on its own.
+ expect(mirror.recent('session-nosummary', 3)).toEqual([])
+ })
+
+ it('keeps the three newest questions, newest first', async () => {
+ const mirror = new CommanderMirror({
+ send: () => {},
+ sendWeb: () => {},
+ hasDevice: () => true,
+ summarize: async () => null,
+ dataDir,
+ })
+ for (const q of ['one', 'two', 'three', 'four']) {
+ mirror.ingest([{ type: 'turn_started', payload: { userMessage: q } }] as LiveEvent[], 'session-many')
+ }
+ await vi.runAllTimersAsync()
+ expect(mirror.recentAsks('session-many')).toEqual(['four', 'three', 'two'])
})
it('fans a TodoWrite out to the device as a todo list, whatever engine produced it', () => {
diff --git a/cli/src/lib/commander.ts b/cli/src/lib/commander.ts
index 6311e27a8..b45590f3d 100644
--- a/cli/src/lib/commander.ts
+++ b/cli/src/lib/commander.ts
@@ -337,6 +337,18 @@ export class CommanderMirror {
st.summarizing = false
st.lastAssistantText = ''
st.lastUserMessage = e.payload.userMessage || ''
+ // RECORDED HERE, WHEN IT IS ASKED — not when the answer is summarised.
+ //
+ // It used to be written in the summariser's success branch, index-aligned with the recaps,
+ // which meant a question only existed once its ANSWER had been summarised. Measured on this
+ // desk: three of eight agents had any questions on record at all, and the missing ones were
+ // the newest — a turn that produced no assistant text, or whose summariser returned null,
+ // left no trace of what the person had asked. The router then ranked those agents on their
+ // name alone, which is exactly the case it is worst at.
+ //
+ // The question is a fact about the TURN, not about the recap, so it is kept on its own list
+ // and no longer has to wait for, or stay in step with, anything else.
+ this.rememberAsk(sessionId, e.payload.userMessage || '')
st.turnOpen = true
st.everOpened = true
st.lastTool = null
@@ -625,9 +637,6 @@ export class CommanderMirror {
// Recorded in the SAME branch as the summary, so the two arrays cannot drift out of step —
// a turn that produced no summary produces no row in either.
this.rememberFullText(sessionId, text)
- // Recorded in the SAME branch as the summary and the full text, so all three arrays stay
- // index-aligned: a turn either contributes a row to each or to none.
- this.rememberAsk(sessionId, userMessage)
this.saveSoon()
const { recap, body } = splitSummary(summary)
this.trace(sessionId, `${sid} done in ${ms}ms · recap="${recap}" · bodyLen=${body.length}`)
@@ -700,7 +709,7 @@ export class CommanderMirror {
* Falls back to the single latest summary when the history is empty, so the recaps already on disk from
* before this existed are usable on the first run rather than after three more turns.
*/
- recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string; fullText?: string; ask?: string }> {
+ recent(sessionId: string, n = 2): Array<{ kind: string; text: string; recap?: string; fullText?: string }> {
const want = Math.max(1, n)
const stored = this.history.get(sessionId) ?? []
const latest = this.summaries.get(sessionId)
@@ -708,20 +717,31 @@ export class CommanderMirror {
const usingHistory = stored.length > 0
const all = usingHistory ? stored : latest ? [latest] : []
const fulls = this.fullTexts.get(sessionId) ?? []
- const asks = this.asks.get(sessionId) ?? []
return all
.slice(0, want)
// PAIRED BEFORE FILTERING, not after. The filter below drops empty summaries, and dropping them
// from one array while reading the other by position is how a turn ends up carrying the previous
// turn's answer — wrong in the one way nobody would think to check.
- .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0], ask: asks[usingHistory ? at : 0] }))
+ .map((summary, at) => ({ summary, full: fulls[usingHistory ? at : 0] }))
.filter(({ summary }) => summary && summary.trim())
- .map(({ summary, full, ask }) => {
+ .map(({ summary, full }) => {
const { recap, body } = splitSummary(summary)
- return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}), ...(ask ? { ask } : {}) }
+ return { kind: 'summary', text: body || recap, recap, ...(full ? { fullText: full } : {}) }
})
}
+ /**
+ * The person's own last questions to this agent, newest first.
+ *
+ * Its OWN accessor rather than a field on [recent], because the two no longer describe the same
+ * thing: a recap exists once a turn has been answered and summarised, a question exists the moment
+ * it is asked. Pairing them cost the newest question — the one most likely to say where the next
+ * one belongs — every time a turn ended without a summary.
+ */
+ recentAsks(sessionId: string, n = RECENT_TURNS): string[] {
+ return (this.asks.get(sessionId) ?? []).filter(Boolean).slice(0, Math.max(1, n))
+ }
+
/** The newest turn's complete final answer, for a consumer that reads rather than glances. */
lastFullText(sessionId: string): string | undefined {
return this.fullTexts.get(sessionId)?.[0]