xonecas.io
64875
Mc

mini-coder / commit 6065858

fix(ui): make /session robust to missing assistant usage

Ignore historical assistant messages with missing or invalid usage when computing session stats and context anchors.

Adds a regression test for resuming a stored session from the interactive /session selector.

xonecas2026-04-07 606585806ac6b7d5992bfeb01bde85b49f139e93 parent d093f31

3 files changed

src/session.ts+87−5
@@ -370,6 +370,87 @@ export function filterModelMessages(
370370 );
371371 }
372372
373+function toRecord(value: unknown): Record<string, unknown> | null {
374+ return typeof value === "object" && value !== null
375+ ? (value as Record<string, unknown>)
376+ : null;
377+}
378+
379+function readFiniteNumber(
380+ record: Record<string, unknown>,
381+ key: string,
382+): number | null {
383+ const value = record[key];
384+ return typeof value === "number" && Number.isFinite(value) ? value : null;
385+}
386+
387+/**
388+ * Return an assistant message's usage when the persisted shape is valid.
389+ *
390+ * Session rows are treated as untrusted at runtime because older builds or
391+ * external tooling may have stored assistant messages without a `usage`
392+ * payload. Invalid or missing usage is ignored instead of crashing session
393+ * loading or stats calculations.
394+ *
395+ * @param message - Message to inspect.
396+ * @returns The assistant usage payload, or `null` when it is missing/invalid.
397+ */
398+export function getAssistantUsage(
399+ message: PersistedMessage | Message,
400+): AssistantMessage["usage"] | null {
401+ if (message.role !== "assistant") {
402+ return null;
403+ }
404+
405+ const messageRecord = toRecord(message);
406+ const usageRecord = toRecord(messageRecord?.usage);
407+ const costRecord = toRecord(usageRecord?.cost);
408+ if (!usageRecord || !costRecord) {
409+ return null;
410+ }
411+
412+ const input = readFiniteNumber(usageRecord, "input");
413+ const output = readFiniteNumber(usageRecord, "output");
414+ const cacheRead = readFiniteNumber(usageRecord, "cacheRead");
415+ const cacheWrite = readFiniteNumber(usageRecord, "cacheWrite");
416+ const totalTokens = readFiniteNumber(usageRecord, "totalTokens");
417+ const costInput = readFiniteNumber(costRecord, "input");
418+ const costOutput = readFiniteNumber(costRecord, "output");
419+ const costCacheRead = readFiniteNumber(costRecord, "cacheRead");
420+ const costCacheWrite = readFiniteNumber(costRecord, "cacheWrite");
421+ const costTotal = readFiniteNumber(costRecord, "total");
422+
423+ if (
424+ input === null ||
425+ output === null ||
426+ cacheRead === null ||
427+ cacheWrite === null ||
428+ totalTokens === null ||
429+ costInput === null ||
430+ costOutput === null ||
431+ costCacheRead === null ||
432+ costCacheWrite === null ||
433+ costTotal === null
434+ ) {
435+ return null;
436+ }
437+
438+ return {
439+ input,
440+ output,
441+ cacheRead,
442+ cacheWrite,
443+ totalTokens,
444+ cost: {
445+ input: costInput,
446+ output: costOutput,
447+ cacheRead: costCacheRead,
448+ cacheWrite: costCacheWrite,
449+ total: costTotal,
450+ },
451+ };
452+}
453+
373454 /**
374455 * Append a UI-only message to a session's history.
375456 *
@@ -659,12 +740,13 @@ export function computeStats(
659740 let totalCost = 0;
660741
661742 for (const msg of messages) {
662- if (msg.role === "assistant") {
663- const am = msg as AssistantMessage;
664- totalInput += am.usage.input;
665- totalOutput += am.usage.output;
666- totalCost += am.usage.cost.total;
743+ const usage = getAssistantUsage(msg);
744+ if (!usage) {
745+ continue;
667746 }
747+ totalInput += usage.input;
748+ totalOutput += usage.output;
749+ totalCost += usage.cost.total;
668750 }
669751
670752 return { totalInput, totalOutput, totalCost };
src/ui.test.ts+70−0
@@ -487,6 +487,76 @@ describe("ui rendering", () => {
487487 }
488488 });
489489
490+ test("/session resumes a stored session even when historical assistant usage is missing", () => {
491+ const state = createTestState();
492+ const now = Date.now();
493+ const session = createSession(state.db, {
494+ cwd: state.canonicalCwd,
495+ model: "test/beta",
496+ effort: "high",
497+ });
498+
499+ try {
500+ state.db.run(
501+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
502+ [
503+ session.id,
504+ 1,
505+ JSON.stringify({
506+ role: "user",
507+ content: "historical prompt",
508+ timestamp: now,
509+ }),
510+ now,
511+ ],
512+ );
513+ state.db.run(
514+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
515+ [
516+ session.id,
517+ 1,
518+ JSON.stringify({
519+ role: "assistant",
520+ content: [{ type: "text", text: "historical reply" }],
521+ api: "anthropic-messages",
522+ provider: "anthropic",
523+ model: "test/beta",
524+ stopReason: "stop",
525+ timestamp: now + 1,
526+ }),
527+ now + 1,
528+ ],
529+ );
530+ state.db.run("UPDATE sessions SET updated_at = ? WHERE id = ?", [
531+ now + 1,
532+ session.id,
533+ ]);
534+
535+ handleInput("/session", state);
536+
537+ const overlay = renderActiveOverlay(state);
538+ const selectNode = findNodeWithKeyPress(overlay);
539+
540+ expect(selectNode).not.toBeNull();
541+ if (!selectNode) {
542+ throw new Error("Expected overlay to contain a Select root");
543+ }
544+
545+ selectNode.props.onKeyPress?.("enter");
546+
547+ expect(renderActiveOverlay(state)).toBeNull();
548+ expect(state.session?.id).toBe(session.id);
549+
550+ const layout = renderBaseLayout(state, 80, createInputController(state));
551+ const text = collectText(layout);
552+
553+ expect(text).toContain("historical prompt");
554+ expect(text).toContain("historical reply");
555+ } finally {
556+ state.db.close();
557+ }
558+ });
559+
490560 test("/new clears the active session and defers replacement session creation", async () => {
491561 const faux = registerFauxProvider();
492562 const state = createTestState();
src/ui.ts+6−1
@@ -54,6 +54,7 @@ import {
5454 createUiMessage,
5555 filterModelMessages,
5656 forkSession,
57+ getAssistantUsage,
5758 listPromptHistory,
5859 listSessions,
5960 loadMessages,
@@ -407,9 +408,13 @@ function getLatestValidAssistantUsage(
407408 message.stopReason !== "aborted" &&
408409 message.stopReason !== "error"
409410 ) {
411+ const usage = getAssistantUsage(message);
412+ if (!usage) {
413+ continue;
414+ }
410415 return {
411416 index: i,
412- tokens: calculateUsageTokens(message.usage),
417+ tokens: calculateUsageTokens(usage),
413418 };
414419 }
415420 }