fix(tui): restore session history from canonical events

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-28 13:42:59 +08:00
1 parent c7b806c559
commit b8893aba56
6 files changed
+324 -190

No files matched your search

+23 -13
View File
@@ -1061,7 +1061,12 @@ describe("NanobotTui layout", () => {
return Promise.resolve(new Response(JSON.stringify({}))) return Promise.resolve(new Response(JSON.stringify({})))
} }
return Promise.resolve(new Response(JSON.stringify({ return Promise.resolve(new Response(JSON.stringify({
messages: [], schemaVersion: 3, projection: "events",
events: url.includes("websocket%3Aother") ? [
{ event: "user_message", chat_id: "other", starts_turn: true, text: "saved question" },
{ event: "stream_end", chat_id: "other", text: "saved answer" },
{ event: "turn_end", chat_id: "other" },
] : [],
page: { has_more_before: false }, page: { has_more_before: false },
}))) })))
}) as typeof fetch }) as typeof fetch
@@ -1114,6 +1119,9 @@ describe("NanobotTui layout", () => {
await waitUntil(() => ui.ready) await waitUntil(() => ui.ready)
expect(ui.activeTurn).toBe(false) expect(ui.activeTurn).toBe(false)
expect(ui.queuePreview.root.visible).toBe(false) expect(ui.queuePreview.root.visible).toBe(false)
await setup.flush()
expect(setup.captureCharFrame()).toContain("saved question")
expect(setup.captureCharFrame()).toContain("saved answer")
ui.composer.setText("/sessions") ui.composer.setText("/sessions")
ui.composer.submit() ui.composer.submit()
@@ -1896,14 +1904,15 @@ describe("NanobotTui layout", () => {
requests.push(url) requests.push(url)
const older = url.includes("before=older-page") const older = url.includes("before=older-page")
return Promise.resolve(new Response(JSON.stringify({ return Promise.resolve(new Response(JSON.stringify({
messages: older schemaVersion: 3, projection: "events",
events: older
? [ ? [
{ role: "user", content: "oldest question" }, { event: "user_message", chat_id: "chat", starts_turn: true, text: "oldest question" },
{ role: "assistant", content: "oldest answer" }, { event: "stream_end", chat_id: "chat", text: "oldest answer" },
] ]
: [ : [
{ role: "user", content: "recent question" }, { event: "user_message", chat_id: "chat", starts_turn: true, text: "recent question" },
{ role: "assistant", content: "recent answer" }, { event: "stream_end", chat_id: "chat", text: "recent answer" },
], ],
page: older page: older
? { has_more_before: false, before_cursor: null } ? { has_more_before: false, before_cursor: null }
@@ -3084,10 +3093,8 @@ describe("NanobotTui layout", () => {
app.accept({ ...event, phase: "started" }) app.accept({ ...event, phase: "started" })
app.accept({ ...event, phase: "succeeded" }) app.accept({ ...event, phase: "succeeded" })
resolveFetch(Response.json({ resolveFetch(Response.json({
messages: [{ schemaVersion: 3, projection: "events",
role: "assistant", kind: "compaction", content: "", events: [{ event: "context_compaction", chat_id: "chat", compaction_id: "idle", phase: "succeeded" }],
compaction: { id: "idle", phase: "succeeded" },
}],
})) }))
await waitUntil(() => (app as unknown as { ready: boolean }).ready) await waitUntil(() => (app as unknown as { ready: boolean }).ready)
await setup.renderOnce() await setup.renderOnce()
@@ -3119,7 +3126,8 @@ describe("NanobotTui layout", () => {
app.accept({ event: "delta", chat_id: "chat", text: "live after reconnect" }) app.accept({ event: "delta", chat_id: "chat", text: "live after reconnect" })
expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false) expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)
resolveFetch(new Response(JSON.stringify({ resolveFetch(new Response(JSON.stringify({
messages: [{ role: "assistant", content: "persisted before reconnect" }], schemaVersion: 3, projection: "events",
events: [{ event: "stream_end", chat_id: "chat", text: "persisted before reconnect" }],
page: { has_more_before: false }, page: { has_more_before: false },
}))) })))
await Bun.sleep(5) await Bun.sleep(5)
@@ -3146,7 +3154,8 @@ describe("NanobotTui layout", () => {
request += 1 request += 1
if (request === 1) { if (request === 1) {
return Promise.resolve(new Response(JSON.stringify({ return Promise.resolve(new Response(JSON.stringify({
messages: [{ role: "assistant", content: "initial history" }], schemaVersion: 3, projection: "events",
events: [{ event: "stream_end", chat_id: "chat", text: "initial history" }],
page: { has_more_before: false }, page: { has_more_before: false },
}))) })))
} }
@@ -3180,7 +3189,8 @@ describe("NanobotTui layout", () => {
expect(ui.status.plainText).toContain("Not sent · press Enter to retry when ready") expect(ui.status.plainText).toContain("Not sent · press Enter to retry when ready")
resolveReconnect(new Response(JSON.stringify({ resolveReconnect(new Response(JSON.stringify({
messages: [{ role: "assistant", content: "restored history" }], schemaVersion: 3, projection: "events",
events: [{ event: "stream_end", chat_id: "chat", text: "restored history" }],
page: { has_more_before: false }, page: { has_more_before: false },
}))) })))
await waitUntil(() => ui.ready) await waitUntil(() => ui.ready)
+104
View File
@@ -0,0 +1,104 @@
import { afterEach, expect, test } from "bun:test"
import { fetchHistory, fetchSessionUsage } from "./protocol"
const originalFetch = globalThis.fetch
afterEach(() => { globalThis.fetch = originalFetch })
function respond(events: Array<Record<string, unknown>>, page = {}) {
globalThis.fetch = Object.assign(async () => Response.json({
schemaVersion: 3, projection: "events",
events: events.map((event) => ({ chat_id: "chat", turn_id: "turn", ...event })),
page,
}), { preconnect: originalFetch.preconnect })
}
test("restores canonical event history, media, tools, file edits and absolute fork indices", async () => {
const media = [{ kind: "image" as const, url: "/api/media/image", name: "shot.png" }]
const tools = [{ phase: "end", call_id: "read", name: "read_file" }]
const edits = [{ tool: "edit_file", path: "a.py", added: 1 }]
respond([
{ event: "user_message", starts_turn: true, text: "question", media_urls: media, projection_id: "user" },
{ event: "user_message", starts_turn: true, text: "question", media_urls: media, projection_id: "user" },
{ event: "reasoning_delta", text: "private reasoning" },
{ event: "reasoning_end", text: "private reasoning" },
{ event: "message", kind: "reasoning", text: "private reasoning" },
{ event: "message", kind: "tool_hint", text: "read_file", tool_events: tools },
{ event: "file_edit", edits },
{ event: "delta", text: "partial" },
{ event: "stream_end", text: "answer" },
{ event: "message", text: "answer" },
{ event: "turn_end" },
], { has_more_before: true, before_cursor: "older", user_message_offset: 7 })
expect(await fetchHistory("http://fixture", "token", "chat")).toEqual({
messages: [
{ role: "user", content: "question", media, turnId: "turn" },
{ role: "activity", content: "read_file", toolEvents: tools },
{ role: "activity", content: "", fileEdits: edits },
{ role: "assistant", content: "answer", forkIndex: 8 },
],
hasMoreBefore: true, beforeCursor: "older", userMessageOffset: 7,
})
})
test("keeps distinct answer segments and resumes an unfinished stream", async () => {
respond([
{ event: "user_message", starts_turn: true, text: "question" },
{ event: "delta", text: "first" },
{ event: "stream_end", text: "first" },
{ event: "message", kind: "progress", text: "tool summary", trace_detail: { ref: "trace" } },
{ event: "stream_end", text: "second", resuming: true, merge_next: true },
{ event: "delta", text: " continued" },
{ event: "stream_end" },
{ event: "turn_end" },
{ event: "user_message", starts_turn: true, text: "next", turn_id: "next" },
{ event: "delta", text: "unfinished", turn_id: "next" },
])
const history = await fetchHistory("http://fixture", "token", "chat")
expect(history.messages.map((row) => row.content)).toEqual([
"question", "first", "tool summary", "second continued", "next", "unfinished",
])
})
test("recovers usage from turn_end and respects successful compaction boundaries", async () => {
const rounds = Array.from({ length: 10 }, (_, i) => ({ prompt_tokens: (i + 1) * 10 }))
const completed = {
event: "turn_end", usage: { context_tokens: 100 },
context_window_tokens: 1000, round_usages: rounds,
}
respond([{ event: "stream_end", text: "answer" }, completed])
expect(await fetchSessionUsage("http://fixture", "token", "chat")).toEqual({
context: { tokens: 100, windowTokens: 1000 }, rounds: rounds.slice(-8),
})
const compacted = { event: "context_compaction", compaction_id: "compact", phase: "succeeded" }
respond([completed, compacted, { event: "delta", text: "still running", turn_id: "next" }])
expect(await fetchSessionUsage("http://fixture", "token", "chat")).toEqual({
context: null, rounds: rounds.slice(-8),
})
expect((await fetchHistory("http://fixture", "token", "chat")).messages[0]).toEqual({
role: "activity", content: "", compaction: { id: "compact", phase: "succeeded" },
})
respond([completed, compacted, { ...completed, turn_id: "next", usage: { context_tokens: 20 }, round_usages: [] }])
expect((await fetchSessionUsage("http://fixture", "token", "chat")).context)
.toEqual({ tokens: 20, windowTokens: 1000 })
})
test("rejects unsupported successful responses and malformed events instead of showing empty history", async () => {
for (const payload of [
{}, { schemaVersion: 3, messages: [] },
{ schemaVersion: 3, projection: "events", events: null },
{ schemaVersion: 3, projection: "future", messages: [] },
]) {
globalThis.fetch = Object.assign(async () => Response.json(payload), { preconnect: originalFetch.preconnect })
await expect(fetchHistory("http://fixture", "token", "chat")).rejects.toThrow("history response")
}
for (const event of [
{ event: "user_message", text: 42 },
{ event: "stream_end", text: "answer", turn_id: 42 },
{ event: "turn_end", context_window_tokens: "64000" },
]) {
respond([event])
await expect(fetchHistory("http://fixture", "token", "chat")).rejects.toThrow("Invalid history event")
}
respond([])
expect((await fetchHistory("http://fixture", "token", "chat")).messages).toEqual([])
})
+18 -63
View File
@@ -1077,55 +1077,27 @@ describe("gateway protocol", () => {
} }
}) })
test("reports when the bounded history snapshot omits earlier turns", async () => { test("reports when canonical history omits earlier turns", async () => {
const original = globalThis.fetch const original = globalThis.fetch
let requested = "" let requested = ""
globalThis.fetch = ((input: string | URL | Request) => { globalThis.fetch = ((input: string | URL | Request) => {
requested = String(input) requested = String(input)
return Promise.resolve(new Response(JSON.stringify({ return Promise.resolve(Response.json({
messages: [ schemaVersion: 3, projection: "events",
{ role: "user", content: "hello", turnId: "turn-1" }, events: [
{ { event: "user_message", chat_id: "chat", starts_turn: true, text: "hello", turn_id: "turn-1" },
role: "user", { event: "stream_end", chat_id: "chat", text: "hi" },
content: "",
turnId: "turn-image",
media: [{ kind: "image", url: "/api/media/sig/image", name: "shot.png" }],
},
{
role: "tool",
kind: "trace",
content: "read_file",
traces: ["read_file"],
toolEvents: [{ phase: "end", call_id: "read-1", name: "read_file" }],
},
{ role: "assistant", kind: "reasoning", content: "private thought" },
{ role: "assistant", content: "hi", forkIndex: 2 },
], ],
page: { has_more_before: true, before_cursor: "older-1" }, page: { has_more_before: true, before_cursor: "older-1" },
}))) }))
}) as typeof fetch }) as typeof fetch
try { try {
const history = await fetchHistory("http://nanobot.test", "token", "chat", "newer-page") expect(await fetchHistory("http://nanobot.test", "token", "chat", "newer-page")).toEqual({
expect(history).toEqual({
messages: [ messages: [
{ role: "user", content: "hello", turnId: "turn-1" }, { role: "user", content: "hello", turnId: "turn-1" },
{ { role: "assistant", content: "hi", forkIndex: 1 },
role: "user",
content: "",
turnId: "turn-image",
media: [{ kind: "image", url: "/api/media/sig/image", name: "shot.png" }],
},
{
role: "activity",
content: "read_file",
toolEvents: [{ phase: "end", call_id: "read-1", name: "read_file" }],
},
{ role: "assistant", content: "hi", forkIndex: 2 },
], ],
hasMoreBefore: true, hasMoreBefore: true, beforeCursor: "older-1", userMessageOffset: 0,
beforeCursor: "older-1",
userMessageOffset: 0,
}) })
expect(requested).toContain("before=newer-page") expect(requested).toContain("before=newer-page")
} finally { } finally {
@@ -1136,35 +1108,18 @@ describe("gateway protocol", () => {
test("loads compaction history as activity rows", async () => { test("loads compaction history as activity rows", async () => {
const original = globalThis.fetch const original = globalThis.fetch
globalThis.fetch = Object.assign(async () => Response.json({ globalThis.fetch = Object.assign(async () => Response.json({
messages: [ schemaVersion: 3, projection: "events",
{ role: "assistant", content: "before" }, events: ["started", "succeeded", "failed", "cancelled"].map((phase) => ({
...["started", "succeeded", "failed", "cancelled"].map((phase) => ({ event: "context_compaction", chat_id: "chat", compaction_id: phase, phase,
role: "assistant", })),
kind: "compaction",
content: "",
compaction: { id: phase, phase },
})),
{ role: "assistant", kind: "compaction", content: "invalid", compaction: null },
{
role: "assistant", kind: "compaction", content: "invalid",
compaction: { id: "", phase: "succeeded" },
},
{
role: "assistant", kind: "compaction", content: "invalid",
compaction: { id: "unknown", phase: "unknown" },
},
{ role: "assistant", content: "after" },
],
}), { preconnect: original.preconnect }) }), { preconnect: original.preconnect })
try { try {
const history = await fetchHistory("http://nanobot.test", "token", "chat") const history = await fetchHistory("http://nanobot.test", "token", "chat")
expect(history.messages).toEqual([ expect(history.messages).toEqual(
{ role: "assistant", content: "before", forkIndex: 0 }, (["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({
...(["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({ role: "activity", content: "", compaction: { id: phase, phase },
role: "activity" as const, content: "", compaction: { id: phase, phase },
})), })),
{ role: "assistant", content: "after", forkIndex: 0 }, )
])
} finally { } finally {
globalThis.fetch = original globalThis.fetch = original
} }
+129 -68
View File
@@ -1,4 +1,4 @@
import { decodeNotification, isCompactionPhase, isRecoveryState } from "../../packages/client-events/notifications" import { decodeNotification, isRecoveryState } from "../../packages/client-events/notifications"
import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications" import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"
export type { ContextCompaction, RecoveryState, RetryStatus } from "../../packages/client-events/notifications" export type { ContextCompaction, RecoveryState, RetryStatus } from "../../packages/client-events/notifications"
@@ -589,11 +589,52 @@ async function fetchApi(
return request(await reauthenticate(apiToken)) return request(await reauthenticate(apiToken))
} }
type HistoryEvent = Extract<InboundEvent, { event:
| "user_message" | "message" | "file_edit" | "delta" | "stream_end"
| "reasoning_delta" | "reasoning_end" | "context_compaction" | "turn_end"
}> & { round_usages?: TokenUsage[] }
interface ThreadPage { interface ThreadPage {
messages?: Array<Record<string, unknown>> events: HistoryEvent[]
page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number } page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number }
} }
function parseHistoryEvents(values: unknown[]): HistoryEvent[] {
const events: HistoryEvent[] = []
const seen = new Set<string>()
for (const value of values) {
const event = decodeInboundEvent(value)
if (!event || !isRecord(value) || !optional(value.turn_id, "string")) {
throw new Error("Invalid history event")
}
if (typeof value.projection_id === "string") {
if (seen.has(value.projection_id)) continue
seen.add(value.projection_id)
}
switch (event.event) {
case "user_message":
case "message":
case "file_edit":
case "delta":
case "stream_end":
case "reasoning_delta":
case "reasoning_end":
case "context_compaction":
events.push(event)
break
case "turn_end":
events.push({
...event,
round_usages: Array.isArray(value.round_usages) ? value.round_usages.filter(isTokenUsage) : [],
})
break
default:
throw new Error(`Unsupported history event: ${event.event}`)
}
}
return events
}
async function fetchThreadPage( async function fetchThreadPage(
apiUrl: string, apiUrl: string,
apiToken: string, apiToken: string,
@@ -602,7 +643,7 @@ async function fetchThreadPage(
reauthenticate?: ApiReauthenticator, reauthenticate?: ApiReauthenticator,
signal?: AbortSignal, signal?: AbortSignal,
): Promise<ThreadPage> { ): Promise<ThreadPage> {
if (!apiUrl || !apiToken) return {} if (!apiUrl || !apiToken) return { events: [] }
const key = encodeURIComponent(`websocket:${chatId}`) const key = encodeURIComponent(`websocket:${chatId}`)
const params = new URLSearchParams({ limit: "120", direction: "latest" }) const params = new URLSearchParams({ limit: "120", direction: "latest" })
if (beforeCursor) params.set("before", beforeCursor) if (beforeCursor) params.set("before", beforeCursor)
@@ -613,9 +654,22 @@ async function fetchThreadPage(
reauthenticate, reauthenticate,
signal, signal,
) )
if (response.status === 404) return {} if (response.status === 404) return { events: [] }
if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`) if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`)
return await response.json() as ThreadPage const payload: unknown = await response.json()
if (!isRecord(payload) || typeof payload.schemaVersion !== "number") {
throw new Error("Invalid history response")
}
const page = isRecord(payload.page) ? payload.page : undefined
const pagination = {
has_more_before: page?.has_more_before === true,
before_cursor: typeof page?.before_cursor === "string" ? page.before_cursor : undefined,
user_message_offset: typeof page?.user_message_offset === "number" ? page.user_message_offset : undefined,
}
if (payload.projection === "events" && Array.isArray(payload.events)) {
return { events: parseHistoryEvents(payload.events), page: pagination }
}
throw new Error("Unsupported history response format")
} }
/** Same recent model-call samples and context boundary as the WebUI usage popover. */ /** Same recent model-call samples and context boundary as the WebUI usage popover. */
@@ -631,14 +685,13 @@ export async function fetchSessionUsage(
const snapshot: SessionUsageSnapshot = { context: null, rounds: [] } const snapshot: SessionUsageSnapshot = { context: null, rounds: [] }
const seenTurns = new Set<unknown>() const seenTurns = new Set<unknown>()
let contextResolved = false let contextResolved = false
for (const message of [...(payload.messages ?? [])].reverse()) { for (const event of [...payload.events].reverse()) {
if (message.kind === "compaction" && isRecord(message.compaction) if (event.event === "context_compaction" && event.phase === "succeeded") contextResolved = true
&& message.compaction.phase === "succeeded") contextResolved = true if (event.event !== "turn_end") continue
if (message.role !== "assistant" || message.kind === "trace" || message.isStreaming) continue const usage = event.usage
const usage = isTokenUsage(message.usage) ? message.usage : null
if (!contextResolved && typeof usage?.context_tokens === "number" if (!contextResolved && typeof usage?.context_tokens === "number"
&& Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) { && Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) {
const window = message.contextWindowTokens const window = event.context_window_tokens
snapshot.context = { snapshot.context = {
tokens: usage.context_tokens, tokens: usage.context_tokens,
...(typeof window === "number" && Number.isFinite(window) && window > 0 ...(typeof window === "number" && Number.isFinite(window) && window > 0
@@ -646,13 +699,12 @@ export async function fetchSessionUsage(
} }
contextResolved = true contextResolved = true
} }
const turnKey = message.turnId || message.id || message const turnKey = event.turn_id || event
if (seenTurns.has(turnKey)) continue if (seenTurns.has(turnKey)) continue
seenTurns.add(turnKey) seenTurns.add(turnKey)
const rounds = Array.isArray(message.roundUsages) ? message.roundUsages : [] for (const round of [...(event.round_usages ?? [])].reverse()) {
for (const round of [...rounds].reverse()) {
if (snapshot.rounds.length >= 8) break if (snapshot.rounds.length >= 8) break
if (isTokenUsage(round) && typeof round.prompt_tokens === "number" if (typeof round.prompt_tokens === "number"
&& Number.isFinite(round.prompt_tokens) && round.prompt_tokens > 0) { && Number.isFinite(round.prompt_tokens) && round.prompt_tokens > 0) {
snapshot.rounds.push(round) snapshot.rounds.push(round)
} }
@@ -674,65 +726,74 @@ export async function fetchHistory(
? Math.max(0, payload.page.user_message_offset) ? Math.max(0, payload.page.user_message_offset)
: 0 : 0
const messages: HistoryMessage[] = [] const messages: HistoryMessage[] = []
for (const message of payload.messages || []) { let stream: { row: HistoryMessage; turnId?: string } | null = null
const role = message.role let lastAnswer: { row: HistoryMessage; turnId?: string } | null = null
const content = message.content for (const event of payload.events) {
if (message.kind === "compaction") { switch (event.event) {
const compaction = message.compaction case "user_message": {
if (isRecord(compaction) if (event.starts_turn) stream = null
&& typeof compaction.id === "string" const media = event.media_urls ?? []
&& compaction.id if (!event.text.trim() && !media.length) break
&& isCompactionPhase(compaction.phase)) { userIndex += 1
messages.push({ messages.push({
role: "activity", role: "user", content: event.text,
content: "", ...(media.length ? { media } : {}),
compaction: { id: compaction.id, phase: compaction.phase }, ...(event.turn_id ? { turnId: event.turn_id } : {}),
}) })
lastAnswer = null
break
} }
continue case "delta":
} case "stream_end":
if (role === "tool" && message.kind === "trace") { if (!stream || stream.turnId !== event.turn_id) {
const traces = Array.isArray(message.traces) const row: HistoryMessage = { role: "assistant", content: "", forkIndex: userIndex }
? message.traces.filter((value): value is string => typeof value === "string") messages.push(row)
: [] stream = { row, turnId: event.turn_id }
const toolEvents = Array.isArray(message.toolEvents) }
? message.toolEvents.filter(isToolEvent) if (event.event === "delta") stream.row.content += event.text
: undefined else if (event.text !== undefined) stream.row.content = event.text
const fileEdits = Array.isArray(message.fileEdits) lastAnswer = stream
? message.fileEdits.filter(isFileEdit) if (event.event === "stream_end" && !(event.resuming && event.merge_next)) stream = null
: undefined break
const activity = traces.join("\n") || (typeof content === "string" ? content : "") case "message":
messages.push({ if (event.kind === "reasoning") break
role: "activity", if (event.kind === "tool_hint" || event.kind === "progress") {
content: activity, messages.push({
...(toolEvents?.length ? { toolEvents } : {}), role: "activity", content: event.text,
...(fileEdits?.length ? { fileEdits } : {}), ...(event.tool_events?.length ? { toolEvents: event.tool_events } : {}),
}) })
continue } else {
} // A final message can repeat the answer already saved by stream_end.
if ( if (stream && stream.turnId === event.turn_id) stream.row.content = event.text
(role !== "user" && role !== "assistant") else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) {
|| message.kind === "reasoning" const row: HistoryMessage = { role: "assistant", content: event.text, forkIndex: userIndex }
|| typeof content !== "string" messages.push(row)
) { lastAnswer = { row, turnId: event.turn_id }
continue }
} stream = null
const media = Array.isArray(message.media) ? message.media.filter(isMediaAttachment) : [] }
if (role === "user") { break
if (!content.trim() && !media.length) continue case "file_edit":
userIndex += 1 if (event.edits.length) messages.push({ role: "activity", content: "", fileEdits: event.edits })
messages.push({ break
role: "user", case "context_compaction":
content, stream = null
...(media.length ? { media } : {}), messages.push({
...(typeof message.turnId === "string" ? { turnId: message.turnId } : {}), role: "activity", content: "",
}) compaction: { id: event.compaction_id, phase: event.phase },
} else if (content.trim()) { })
messages.push({ role: "assistant", content, forkIndex: userIndex }) break
case "turn_end":
stream = null
lastAnswer = null
break
case "reasoning_delta":
case "reasoning_end":
break
} }
} }
return { return {
messages, messages: messages.filter((row) => row.role !== "assistant" || row.content.trim()),
hasMoreBefore: payload.page?.has_more_before === true, hasMoreBefore: payload.page?.has_more_before === true,
beforeCursor: typeof payload.page?.before_cursor === "string" beforeCursor: typeof payload.page?.before_cursor === "string"
? payload.page.before_cursor ? payload.page.before_cursor
+7 -6
View File
@@ -8,10 +8,11 @@ import type { RecoveryState } from "./protocol"
const originalFetch = globalThis.fetch const originalFetch = globalThis.fetch
const page = (input = 9000) => ({ const page = (input = 9000) => ({
messages: [{ schemaVersion: 3, projection: "events",
id: "reply", turnId: "turn", role: "assistant", content: "Saved reply", events: [{
usage: { prompt_tokens: 15000, context_tokens: 9000 }, contextWindowTokens: 262144, event: "turn_end", chat_id: "chat", turn_id: "turn",
roundUsages: [ usage: { prompt_tokens: 15000, context_tokens: 9000 }, context_window_tokens: 262144,
round_usages: [
{ prompt_tokens: 3000, completion_tokens: 100, cached_tokens: 0 }, { prompt_tokens: 3000, completion_tokens: 100, cached_tokens: 0 },
{ prompt_tokens: input, completion_tokens: 200, cached_tokens: 6000 }, { prompt_tokens: input, completion_tokens: 200, cached_tokens: 6000 },
], ],
@@ -220,7 +221,7 @@ describe("TUI /usage", () => {
const { app, ui, client } = await mount((init) => { const { app, ui, client } = await mount((init) => {
requests++ requests++
// Session hydration is independent of the usage request. // Session hydration is independent of the usage request.
if (requests > 1) return Promise.resolve(Response.json({ messages: [] })) if (requests > 1) return Promise.resolve(Response.json({ schemaVersion: 3, projection: "events", events: [] }))
signal = init?.signal signal = init?.signal
return new Promise((_resolve, reject) => { return new Promise((_resolve, reject) => {
signal?.addEventListener("abort", () => reject(signal!.reason), { once: true }) signal?.addEventListener("abort", () => reject(signal!.reason), { once: true })
@@ -262,7 +263,7 @@ describe("TUI /usage", () => {
const { app, ui, client } = await mount(() => { const { app, ui, client } = await mount(() => {
requests++ requests++
if (requests === 1) return new Promise((resolve) => { finish = resolve }) if (requests === 1) return new Promise((resolve) => { finish = resolve })
return Promise.resolve(Response.json({ messages: [] })) return Promise.resolve(Response.json({ schemaVersion: 3, projection: "events", events: [] }))
}) })
await open(ui) await open(ui)
client.attach("other-chat") client.attach("other-chat")
+43 -40
View File
@@ -20,12 +20,15 @@ function mockResponses(...responses: Response[]) {
return fetchMock return fetchMock
} }
function thread(messages: Array<Record<string, unknown>>) { function thread(events: Array<Record<string, unknown>>) {
return Response.json({ messages }) return Response.json({
schemaVersion: 3, projection: "events",
events: events.map((event) => ({ chat_id: chatId, ...event })),
})
} }
function assistant(turnId: string, fields: Record<string, unknown>) { function completed(turnId: string, fields: Record<string, unknown>) {
return { role: "assistant", content: "answer", turnId, ...fields } return { event: "turn_end", turn_id: turnId, ...fields }
} }
describe("fetchSessionUsage", () => { describe("fetchSessionUsage", () => {
@@ -35,11 +38,11 @@ describe("fetchSessionUsage", () => {
completion_tokens: index + 1, completion_tokens: index + 1,
})) }))
const fetchMock = mockResponses(thread([ const fetchMock = mockResponses(thread([
assistant("first", { id: "first-a", roundUsages: rounds.slice(0, 4) }), completed("first", { projection_id: "first-a", round_usages: rounds.slice(0, 4) }),
assistant("first", { id: "first-b", roundUsages: rounds.slice(0, 4) }), completed("first", { projection_id: "first-b", round_usages: rounds.slice(0, 4) }),
assistant("second", { id: "second-a", roundUsages: rounds.slice(4, 8) }), completed("second", { projection_id: "second-a", round_usages: rounds.slice(4, 8) }),
assistant("second", { id: "second-b", roundUsages: rounds.slice(4, 8) }), completed("second", { projection_id: "second-b", round_usages: rounds.slice(4, 8) }),
assistant("third", { roundUsages: rounds.slice(8) }), completed("third", { round_usages: rounds.slice(8) }),
])) ]))
expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({
@@ -54,11 +57,11 @@ describe("fetchSessionUsage", () => {
test("never substitutes aggregate prompt usage for missing or invalid round samples", async () => { test("never substitutes aggregate prompt usage for missing or invalid round samples", async () => {
mockResponses(thread([ mockResponses(thread([
assistant("aggregate-only", { usage: { prompt_tokens: 90_000, total_tokens: 91_000 } }), completed("aggregate-only", { usage: { prompt_tokens: 90_000, total_tokens: 91_000 } }),
assistant("invalid-rounds", { completed("invalid-rounds", {
usage: { prompt_tokens: 80_000, context_tokens: 12 }, usage: { prompt_tokens: 80_000, context_tokens: 12 },
contextWindowTokens: 1_000, context_window_tokens: 1_000,
roundUsages: [null, {}, { completion_tokens: 2 }, { prompt_tokens: 0 }, round_usages: [null, {}, { completion_tokens: 2 }, { prompt_tokens: 0 },
{ prompt_tokens: -1 }, { prompt_tokens: "500" }], { prompt_tokens: -1 }, { prompt_tokens: "500" }],
}), }),
])) ]))
@@ -69,18 +72,18 @@ describe("fetchSessionUsage", () => {
}) })
}) })
test("takes context and capacity from the latest message with context usage, not its neighbors", async () => { test("takes context and capacity from the latest completed turn with context usage", async () => {
const round = { prompt_tokens: 70, context_tokens: 999 } const round = { prompt_tokens: 70, context_tokens: 999 }
mockResponses(thread([ mockResponses(thread([
assistant("old", { usage: { context_tokens: 100 }, contextWindowTokens: 1_000 }), completed("old", { usage: { context_tokens: 100 }, context_window_tokens: 1_000 }),
assistant("context", { completed("context", {
usage: { prompt_tokens: 50_000, context_tokens: 250 }, usage: { prompt_tokens: 50_000, context_tokens: 250 },
contextWindowTokens: 4_000, context_window_tokens: 4_000,
}), }),
assistant("newer", { completed("newer", {
usage: { prompt_tokens: 90_000, total_tokens: 91_000 }, usage: { prompt_tokens: 90_000, total_tokens: 91_000 },
contextWindowTokens: 100_000, context_window_tokens: 100_000,
roundUsages: [round], round_usages: [round],
}), }),
])) ]))
@@ -90,19 +93,19 @@ describe("fetchSessionUsage", () => {
}) })
}) })
test("keeps usage-only and empty assistants while ignoring streaming, trace and non-assistant rows", async () => { test("reads completed usage while ignoring unfinished streams, tools and user events", async () => {
const rounds = [{ prompt_tokens: 80 }, { prompt_tokens: 160, cached_tokens: 40 }] const rounds = [{ prompt_tokens: 80 }, { prompt_tokens: 160, cached_tokens: 40 }]
const noise = { usage: { context_tokens: 999 }, roundUsages: [{ prompt_tokens: 999 }] } const noise = { usage: { context_tokens: 999 }, round_usages: [{ prompt_tokens: 999 }] }
mockResponses(thread([ mockResponses(thread([
assistant("usage-only", { content: undefined, usage: { context_tokens: 80 }, roundUsages: [rounds[0]] }), completed("usage-only", { usage: { context_tokens: 80 }, round_usages: [rounds[0]] }),
assistant("empty", { completed("empty", {
content: "", usage: { context_tokens: 160 }, contextWindowTokens: 2_000, usage: { context_tokens: 160 }, context_window_tokens: 2_000,
roundUsages: [rounds[1]], round_usages: [rounds[1]],
}), }),
assistant("empty", { isStreaming: true, ...noise }), { event: "delta", text: "still running", ...noise },
assistant("empty", { kind: "trace", ...noise }), { event: "stream_end", text: "unfinished turn", ...noise },
{ role: "tool", kind: "trace", ...noise }, { event: "message", kind: "tool_hint", text: "tool", ...noise },
{ role: "user", content: "question", ...noise }, { event: "user_message", starts_turn: true, text: "question", ...noise },
])) ]))
expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({ expect(await fetchSessionUsage(apiUrl, apiToken, chatId)).toStrictEqual({
@@ -114,18 +117,18 @@ describe("fetchSessionUsage", () => {
test("successful compaction clears context but not bars, and later completed usage restores it", async () => { test("successful compaction clears context but not bars, and later completed usage restores it", async () => {
const oldRound = { prompt_tokens: 800 } const oldRound = { prompt_tokens: 800 }
const newRound = { prompt_tokens: 120 } const newRound = { prompt_tokens: 120 }
const old = assistant("old", { const old = completed("old", {
usage: { context_tokens: 800 }, contextWindowTokens: 1_000, roundUsages: [oldRound], usage: { context_tokens: 800 }, context_window_tokens: 1_000, round_usages: [oldRound],
}) })
const compaction = (phase: string) => ({ const compaction = (phase: string) => ({
role: "activity", kind: "compaction", compaction: { id: "compact-1", phase }, event: "context_compaction", compaction_id: "compact-1", phase,
}) })
mockResponses( mockResponses(
thread([old, compaction("started")]), thread([old, compaction("started")]),
thread([old, compaction("failed")]), thread([old, compaction("failed")]),
thread([old, compaction("succeeded")]), thread([old, compaction("succeeded")]),
thread([old, compaction("succeeded"), assistant("new", { thread([old, compaction("succeeded"), completed("new", {
usage: { context_tokens: 120 }, contextWindowTokens: 2_000, roundUsages: [newRound], usage: { context_tokens: 120 }, context_window_tokens: 2_000, round_usages: [newRound],
})]), })]),
) )
@@ -147,11 +150,11 @@ describe("fetchSessionUsage", () => {
{ prompt_tokens: 40 }, { prompt_tokens: 40 },
{ prompt_tokens: 80, cached_tokens: 0, cache_write_tokens: 0 }, { prompt_tokens: 80, cached_tokens: 0, cache_write_tokens: 0 },
] ]
for (const capacity of [undefined, 0, -1, "64000", null]) { for (const capacity of [undefined, 0, -1]) {
mockResponses(thread([ mockResponses(thread([
assistant("old", { usage: { context_tokens: 88 }, contextWindowTokens: 64_000 }), completed("old", { usage: { context_tokens: 88 }, context_window_tokens: 64_000 }),
assistant("latest", { completed("latest", {
usage: { context_tokens: 0 }, contextWindowTokens: capacity, roundUsages: rounds, usage: { context_tokens: 0 }, context_window_tokens: capacity, round_usages: rounds,
}), }),
])) ]))
@@ -177,7 +180,7 @@ describe("fetchSessionUsage", () => {
const fresh = { apiUrl: "http://refreshed.test", apiToken: "fresh-token" } const fresh = { apiUrl: "http://refreshed.test", apiToken: "fresh-token" }
const fetchMock = mockResponses( const fetchMock = mockResponses(
new Response("expired", { status: 401 }), new Response("expired", { status: 401 }),
thread([assistant("fresh", { usage: { context_tokens: 42 } })]), thread([completed("fresh", { usage: { context_tokens: 42 } })]),
) )
const reauthenticate = mock(async (_rejectedToken: string) => fresh) const reauthenticate = mock(async (_rejectedToken: string) => fresh)