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({
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 },
})))
}) as typeof fetch
@@ -1114,6 +1119,9 @@ describe("NanobotTui layout", () => {
await waitUntil(() => ui.ready)
expect(ui.activeTurn).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.submit()
@@ -1896,14 +1904,15 @@ describe("NanobotTui layout", () => {
requests.push(url)
const older = url.includes("before=older-page")
return Promise.resolve(new Response(JSON.stringify({
messages: older
schemaVersion: 3, projection: "events",
events: older
? [
{ role: "user", content: "oldest question" },
{ role: "assistant", content: "oldest answer" },
{ event: "user_message", chat_id: "chat", starts_turn: true, text: "oldest question" },
{ event: "stream_end", chat_id: "chat", text: "oldest answer" },
]
: [
{ role: "user", content: "recent question" },
{ role: "assistant", content: "recent answer" },
{ event: "user_message", chat_id: "chat", starts_turn: true, text: "recent question" },
{ event: "stream_end", chat_id: "chat", text: "recent answer" },
],
page: older
? { has_more_before: false, before_cursor: null }
@@ -3084,10 +3093,8 @@ describe("NanobotTui layout", () => {
app.accept({ ...event, phase: "started" })
app.accept({ ...event, phase: "succeeded" })
resolveFetch(Response.json({
messages: [{
role: "assistant", kind: "compaction", content: "",
compaction: { id: "idle", phase: "succeeded" },
}],
schemaVersion: 3, projection: "events",
events: [{ event: "context_compaction", chat_id: "chat", compaction_id: "idle", phase: "succeeded" }],
}))
await waitUntil(() => (app as unknown as { ready: boolean }).ready)
await setup.renderOnce()
@@ -3119,7 +3126,8 @@ describe("NanobotTui layout", () => {
app.accept({ event: "delta", chat_id: "chat", text: "live after reconnect" })
expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)
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 },
})))
await Bun.sleep(5)
@@ -3146,7 +3154,8 @@ describe("NanobotTui layout", () => {
request += 1
if (request === 1) {
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 },
})))
}
@@ -3180,7 +3189,8 @@ describe("NanobotTui layout", () => {
expect(ui.status.plainText).toContain("Not sent · press Enter to retry when ready")
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 },
})))
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
let requested = ""
globalThis.fetch = ((input: string | URL | Request) => {
requested = String(input)
return Promise.resolve(new Response(JSON.stringify({
messages: [
{ role: "user", content: "hello", turnId: "turn-1" },
{
role: "user",
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 },
return Promise.resolve(Response.json({
schemaVersion: 3, projection: "events",
events: [
{ event: "user_message", chat_id: "chat", starts_turn: true, text: "hello", turn_id: "turn-1" },
{ event: "stream_end", chat_id: "chat", text: "hi" },
],
page: { has_more_before: true, before_cursor: "older-1" },
})))
}))
}) as typeof fetch
try {
const history = await fetchHistory("http://nanobot.test", "token", "chat", "newer-page")
expect(history).toEqual({
expect(await fetchHistory("http://nanobot.test", "token", "chat", "newer-page")).toEqual({
messages: [
{ role: "user", content: "hello", turnId: "turn-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 },
{ role: "assistant", content: "hi", forkIndex: 1 },
],
hasMoreBefore: true,
beforeCursor: "older-1",
userMessageOffset: 0,
hasMoreBefore: true, beforeCursor: "older-1", userMessageOffset: 0,
})
expect(requested).toContain("before=newer-page")
} finally {
@@ -1136,35 +1108,18 @@ describe("gateway protocol", () => {
test("loads compaction history as activity rows", async () => {
const original = globalThis.fetch
globalThis.fetch = Object.assign(async () => Response.json({
messages: [
{ role: "assistant", content: "before" },
...["started", "succeeded", "failed", "cancelled"].map((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" },
],
schemaVersion: 3, projection: "events",
events: ["started", "succeeded", "failed", "cancelled"].map((phase) => ({
event: "context_compaction", chat_id: "chat", compaction_id: phase, phase,
})),
}), { preconnect: original.preconnect })
try {
const history = await fetchHistory("http://nanobot.test", "token", "chat")
expect(history.messages).toEqual([
{ role: "assistant", content: "before", forkIndex: 0 },
...(["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({
role: "activity" as const, content: "", compaction: { id: phase, phase },
expect(history.messages).toEqual(
(["started", "succeeded", "failed", "cancelled"] as const).map((phase) => ({
role: "activity", content: "", compaction: { id: phase, phase },
})),
{ role: "assistant", content: "after", forkIndex: 0 },
])
)
} finally {
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"
export type { ContextCompaction, RecoveryState, RetryStatus } from "../../packages/client-events/notifications"
@@ -589,11 +589,52 @@ async function fetchApi(
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 {
messages?: Array<Record<string, unknown>>
events: HistoryEvent[]
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(
apiUrl: string,
apiToken: string,
@@ -602,7 +643,7 @@ async function fetchThreadPage(
reauthenticate?: ApiReauthenticator,
signal?: AbortSignal,
): Promise<ThreadPage> {
if (!apiUrl || !apiToken) return {}
if (!apiUrl || !apiToken) return { events: [] }
const key = encodeURIComponent(`websocket:${chatId}`)
const params = new URLSearchParams({ limit: "120", direction: "latest" })
if (beforeCursor) params.set("before", beforeCursor)
@@ -613,9 +654,22 @@ async function fetchThreadPage(
reauthenticate,
signal,
)
if (response.status === 404) return {}
if (response.status === 404) return { events: [] }
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. */
@@ -631,14 +685,13 @@ export async function fetchSessionUsage(
const snapshot: SessionUsageSnapshot = { context: null, rounds: [] }
const seenTurns = new Set<unknown>()
let contextResolved = false
for (const message of [...(payload.messages ?? [])].reverse()) {
if (message.kind === "compaction" && isRecord(message.compaction)
&& message.compaction.phase === "succeeded") contextResolved = true
if (message.role !== "assistant" || message.kind === "trace" || message.isStreaming) continue
const usage = isTokenUsage(message.usage) ? message.usage : null
for (const event of [...payload.events].reverse()) {
if (event.event === "context_compaction" && event.phase === "succeeded") contextResolved = true
if (event.event !== "turn_end") continue
const usage = event.usage
if (!contextResolved && typeof usage?.context_tokens === "number"
&& Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) {
const window = message.contextWindowTokens
const window = event.context_window_tokens
snapshot.context = {
tokens: usage.context_tokens,
...(typeof window === "number" && Number.isFinite(window) && window > 0
@@ -646,13 +699,12 @@ export async function fetchSessionUsage(
}
contextResolved = true
}
const turnKey = message.turnId || message.id || message
const turnKey = event.turn_id || event
if (seenTurns.has(turnKey)) continue
seenTurns.add(turnKey)
const rounds = Array.isArray(message.roundUsages) ? message.roundUsages : []
for (const round of [...rounds].reverse()) {
for (const round of [...(event.round_usages ?? [])].reverse()) {
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) {
snapshot.rounds.push(round)
}
@@ -674,65 +726,74 @@ export async function fetchHistory(
? Math.max(0, payload.page.user_message_offset)
: 0
const messages: HistoryMessage[] = []
for (const message of payload.messages || []) {
const role = message.role
const content = message.content
if (message.kind === "compaction") {
const compaction = message.compaction
if (isRecord(compaction)
&& typeof compaction.id === "string"
&& compaction.id
&& isCompactionPhase(compaction.phase)) {
let stream: { row: HistoryMessage; turnId?: string } | null = null
let lastAnswer: { row: HistoryMessage; turnId?: string } | null = null
for (const event of payload.events) {
switch (event.event) {
case "user_message": {
if (event.starts_turn) stream = null
const media = event.media_urls ?? []
if (!event.text.trim() && !media.length) break
userIndex += 1
messages.push({
role: "activity",
content: "",
compaction: { id: compaction.id, phase: compaction.phase },
role: "user", content: event.text,
...(media.length ? { media } : {}),
...(event.turn_id ? { turnId: event.turn_id } : {}),
})
lastAnswer = null
break
}
continue
}
if (role === "tool" && message.kind === "trace") {
const traces = Array.isArray(message.traces)
? message.traces.filter((value): value is string => typeof value === "string")
: []
const toolEvents = Array.isArray(message.toolEvents)
? message.toolEvents.filter(isToolEvent)
: undefined
const fileEdits = Array.isArray(message.fileEdits)
? message.fileEdits.filter(isFileEdit)
: undefined
const activity = traces.join("\n") || (typeof content === "string" ? content : "")
messages.push({
role: "activity",
content: activity,
...(toolEvents?.length ? { toolEvents } : {}),
...(fileEdits?.length ? { fileEdits } : {}),
})
continue
}
if (
(role !== "user" && role !== "assistant")
|| message.kind === "reasoning"
|| typeof content !== "string"
) {
continue
}
const media = Array.isArray(message.media) ? message.media.filter(isMediaAttachment) : []
if (role === "user") {
if (!content.trim() && !media.length) continue
userIndex += 1
messages.push({
role: "user",
content,
...(media.length ? { media } : {}),
...(typeof message.turnId === "string" ? { turnId: message.turnId } : {}),
})
} else if (content.trim()) {
messages.push({ role: "assistant", content, forkIndex: userIndex })
case "delta":
case "stream_end":
if (!stream || stream.turnId !== event.turn_id) {
const row: HistoryMessage = { role: "assistant", content: "", forkIndex: userIndex }
messages.push(row)
stream = { row, turnId: event.turn_id }
}
if (event.event === "delta") stream.row.content += event.text
else if (event.text !== undefined) stream.row.content = event.text
lastAnswer = stream
if (event.event === "stream_end" && !(event.resuming && event.merge_next)) stream = null
break
case "message":
if (event.kind === "reasoning") break
if (event.kind === "tool_hint" || event.kind === "progress") {
messages.push({
role: "activity", content: event.text,
...(event.tool_events?.length ? { toolEvents: event.tool_events } : {}),
})
} else {
// A final message can repeat the answer already saved by stream_end.
if (stream && stream.turnId === event.turn_id) stream.row.content = event.text
else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) {
const row: HistoryMessage = { role: "assistant", content: event.text, forkIndex: userIndex }
messages.push(row)
lastAnswer = { row, turnId: event.turn_id }
}
stream = null
}
break
case "file_edit":
if (event.edits.length) messages.push({ role: "activity", content: "", fileEdits: event.edits })
break
case "context_compaction":
stream = null
messages.push({
role: "activity", content: "",
compaction: { id: event.compaction_id, phase: event.phase },
})
break
case "turn_end":
stream = null
lastAnswer = null
break
case "reasoning_delta":
case "reasoning_end":
break
}
}
return {
messages,
messages: messages.filter((row) => row.role !== "assistant" || row.content.trim()),
hasMoreBefore: payload.page?.has_more_before === true,
beforeCursor: typeof payload.page?.before_cursor === "string"
? payload.page.before_cursor
+7 -6
View File
@@ -8,10 +8,11 @@ import type { RecoveryState } from "./protocol"
const originalFetch = globalThis.fetch
const page = (input = 9000) => ({
messages: [{
id: "reply", turnId: "turn", role: "assistant", content: "Saved reply",
usage: { prompt_tokens: 15000, context_tokens: 9000 }, contextWindowTokens: 262144,
roundUsages: [
schemaVersion: 3, projection: "events",
events: [{
event: "turn_end", chat_id: "chat", turn_id: "turn",
usage: { prompt_tokens: 15000, context_tokens: 9000 }, context_window_tokens: 262144,
round_usages: [
{ prompt_tokens: 3000, completion_tokens: 100, cached_tokens: 0 },
{ prompt_tokens: input, completion_tokens: 200, cached_tokens: 6000 },
],
@@ -220,7 +221,7 @@ describe("TUI /usage", () => {
const { app, ui, client } = await mount((init) => {
requests++
// 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
return new Promise((_resolve, reject) => {
signal?.addEventListener("abort", () => reject(signal!.reason), { once: true })
@@ -262,7 +263,7 @@ describe("TUI /usage", () => {
const { app, ui, client } = await mount(() => {
requests++
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)
client.attach("other-chat")
+43 -40
View File
@@ -20,12 +20,15 @@ function mockResponses(...responses: Response[]) {
return fetchMock
}
function thread(messages: Array<Record<string, unknown>>) {
return Response.json({ messages })
function thread(events: Array<Record<string, unknown>>) {
return Response.json({
schemaVersion: 3, projection: "events",
events: events.map((event) => ({ chat_id: chatId, ...event })),
})
}
function assistant(turnId: string, fields: Record<string, unknown>) {
return { role: "assistant", content: "answer", turnId, ...fields }
function completed(turnId: string, fields: Record<string, unknown>) {
return { event: "turn_end", turn_id: turnId, ...fields }
}
describe("fetchSessionUsage", () => {
@@ -35,11 +38,11 @@ describe("fetchSessionUsage", () => {
completion_tokens: index + 1,
}))
const fetchMock = mockResponses(thread([
assistant("first", { id: "first-a", roundUsages: rounds.slice(0, 4) }),
assistant("first", { id: "first-b", roundUsages: rounds.slice(0, 4) }),
assistant("second", { id: "second-a", roundUsages: rounds.slice(4, 8) }),
assistant("second", { id: "second-b", roundUsages: rounds.slice(4, 8) }),
assistant("third", { roundUsages: rounds.slice(8) }),
completed("first", { projection_id: "first-a", round_usages: rounds.slice(0, 4) }),
completed("first", { projection_id: "first-b", round_usages: rounds.slice(0, 4) }),
completed("second", { projection_id: "second-a", round_usages: rounds.slice(4, 8) }),
completed("second", { projection_id: "second-b", round_usages: rounds.slice(4, 8) }),
completed("third", { round_usages: rounds.slice(8) }),
]))
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 () => {
mockResponses(thread([
assistant("aggregate-only", { usage: { prompt_tokens: 90_000, total_tokens: 91_000 } }),
assistant("invalid-rounds", {
completed("aggregate-only", { usage: { prompt_tokens: 90_000, total_tokens: 91_000 } }),
completed("invalid-rounds", {
usage: { prompt_tokens: 80_000, context_tokens: 12 },
contextWindowTokens: 1_000,
roundUsages: [null, {}, { completion_tokens: 2 }, { prompt_tokens: 0 },
context_window_tokens: 1_000,
round_usages: [null, {}, { completion_tokens: 2 }, { prompt_tokens: 0 },
{ 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 }
mockResponses(thread([
assistant("old", { usage: { context_tokens: 100 }, contextWindowTokens: 1_000 }),
assistant("context", {
completed("old", { usage: { context_tokens: 100 }, context_window_tokens: 1_000 }),
completed("context", {
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 },
contextWindowTokens: 100_000,
roundUsages: [round],
context_window_tokens: 100_000,
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 noise = { usage: { context_tokens: 999 }, roundUsages: [{ prompt_tokens: 999 }] }
const noise = { usage: { context_tokens: 999 }, round_usages: [{ prompt_tokens: 999 }] }
mockResponses(thread([
assistant("usage-only", { content: undefined, usage: { context_tokens: 80 }, roundUsages: [rounds[0]] }),
assistant("empty", {
content: "", usage: { context_tokens: 160 }, contextWindowTokens: 2_000,
roundUsages: [rounds[1]],
completed("usage-only", { usage: { context_tokens: 80 }, round_usages: [rounds[0]] }),
completed("empty", {
usage: { context_tokens: 160 }, context_window_tokens: 2_000,
round_usages: [rounds[1]],
}),
assistant("empty", { isStreaming: true, ...noise }),
assistant("empty", { kind: "trace", ...noise }),
{ role: "tool", kind: "trace", ...noise },
{ role: "user", content: "question", ...noise },
{ event: "delta", text: "still running", ...noise },
{ event: "stream_end", text: "unfinished turn", ...noise },
{ event: "message", kind: "tool_hint", text: "tool", ...noise },
{ event: "user_message", starts_turn: true, text: "question", ...noise },
]))
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 () => {
const oldRound = { prompt_tokens: 800 }
const newRound = { prompt_tokens: 120 }
const old = assistant("old", {
usage: { context_tokens: 800 }, contextWindowTokens: 1_000, roundUsages: [oldRound],
const old = completed("old", {
usage: { context_tokens: 800 }, context_window_tokens: 1_000, round_usages: [oldRound],
})
const compaction = (phase: string) => ({
role: "activity", kind: "compaction", compaction: { id: "compact-1", phase },
event: "context_compaction", compaction_id: "compact-1", phase,
})
mockResponses(
thread([old, compaction("started")]),
thread([old, compaction("failed")]),
thread([old, compaction("succeeded")]),
thread([old, compaction("succeeded"), assistant("new", {
usage: { context_tokens: 120 }, contextWindowTokens: 2_000, roundUsages: [newRound],
thread([old, compaction("succeeded"), completed("new", {
usage: { context_tokens: 120 }, context_window_tokens: 2_000, round_usages: [newRound],
})]),
)
@@ -147,11 +150,11 @@ describe("fetchSessionUsage", () => {
{ prompt_tokens: 40 },
{ 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([
assistant("old", { usage: { context_tokens: 88 }, contextWindowTokens: 64_000 }),
assistant("latest", {
usage: { context_tokens: 0 }, contextWindowTokens: capacity, roundUsages: rounds,
completed("old", { usage: { context_tokens: 88 }, context_window_tokens: 64_000 }),
completed("latest", {
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 fetchMock = mockResponses(
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)