fix(webui): update usage and tool progress during active turns (#6553)

* fix(webui): stream model status and usage during active turns

* fix(webui): keep live rounds and active-run status consistent

* fix(webui): reuse existing run indicators without extra status text

* fix(webui): preserve live activity and batch durable delivery

Cancel and drain sibling tools when progress notifications fail, retain balanced checkpoints, and keep model telemetry separate from answer provenance.

Group-commit already queued activity at the channel delivery boundary while preserving FIFO, generation ownership, per-envelope admission, and commit-before-fanout semantics. Isolate invalid members without dropping valid neighboring events.

Retain tool detail lazy grouping and cover scheduling, cancellation, persistence, encoding failures, and projection regressions.

* test(webui): separate standard-library imports in batch regression

* test: tighten live execution checks and clarify contracts

* refactor: remove redundant live execution comments

* refactor: settle tool results through one output path
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-04 16:27:24 +08:00
1 parent 006a535537
commit 8ff04aad2b
52 files changed
+2065 -211

No files matched your search

+47 -9
View File
@@ -714,7 +714,10 @@ for (const elapsedMs of [0, 80]) test(`fast responses reclaim completed slots an
expect(nextHeld.anchorTop - atNewHead.anchorTop).toBeCloseTo(48, 0);
await completePrepend(history, body, "Question 16", "Question 28", nextHeld.anchorTop);
await expect(body.locator(".thread-history-slot")).toHaveCount(0);
expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=28"]);
expect(history.reads).toEqual([
"?limit=120&before=40&include_model_requests=1",
"?limit=120&before=28&include_model_requests=1",
]);
});
test("ordinary middle reading never reveals an exhausted overlay, even when the complete beginning is cached", async ({ page }) => {
@@ -920,7 +923,12 @@ test("navigation-window loading and errors remain visible and retry uses the nav
expect(Math.abs(navigationSpacing.boundaryGap! - navigationSpacing.referenceGap!)).toBeLessThan(1);
await positionAtTop(body);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&after=50", "?limit=24&before=38", "?limit=24&before=38"]);
expect(history.reads).toEqual([
"?limit=24&after=38&include_model_requests=1",
"?limit=24&after=50&include_model_requests=1",
"?limit=24&before=38&include_model_requests=1",
"?limit=24&before=38&include_model_requests=1",
]);
});
async function jumpViaRail(page: Page, index: number) {
@@ -963,7 +971,10 @@ test("failed Blocks animate without visible error text; pulling retries once and
await expect.poll(() => displacement(body)).toBe(0);
expect((await historyGeometry(body, "Question 40")).slotBeforeKey).toBe("u40");
await expectCoordinates(body, "Question 40", held);
expect(history.reads).toEqual(["?limit=120&before=40", "?limit=120&before=40"]);
expect(history.reads).toEqual([
"?limit=120&before=40&include_model_requests=1",
"?limit=120&before=40&include_model_requests=1",
]);
history.complete();
await expect(body.getByText("Question 28", { exact: true })).toBeAttached();
@@ -1003,7 +1014,11 @@ test("cross-path unloaded rail jump has visible navigation feedback outside a sc
await retry.click();
await expect.poll(() => history.reads.length).toBe(3);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
expect(history.reads).toEqual(["?limit=120&before=40", "?limit=24&after=10", "?limit=24&after=10"]);
expect(history.reads).toEqual([
"?limit=120&before=40&include_model_requests=1",
"?limit=24&after=10&include_model_requests=1",
"?limit=24&after=10&include_model_requests=1",
]);
history.complete();
await expect(body.getByText("Question 10", { exact: true })).toBeInViewport();
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
@@ -1044,7 +1059,12 @@ test("cross-path newer has visible navigation feedback and forward input retries
await page.mouse.wheel(0, 120);
await expect.poll(() => history.reads.length).toBe(4);
await expect(page.locator('.thread-history-status[data-state="loading"]')).toBeInViewport();
expect(history.reads).toEqual(["?limit=24&after=10", "?limit=24&before=10", "?limit=24&after=22", "?limit=24&after=22"]);
expect(history.reads).toEqual([
"?limit=24&after=10&include_model_requests=1",
"?limit=24&before=10&include_model_requests=1",
"?limit=24&after=22&include_model_requests=1",
"?limit=24&after=22&include_model_requests=1",
]);
history.complete();
await expect(body.getByText("Question 33", { exact: true })).toBeAttached();
await expect(page.locator('.thread-history-status[data-state="loading"]')).toHaveCount(0);
@@ -1088,7 +1108,10 @@ test("cross-path older errors never float after latest or a loaded rail jump, bu
expect(history.reads).toHaveLength(initialReads + 1);
await retry.click();
await expect.poll(() => history.reads.length).toBe(initialReads + 2);
expect(history.reads.slice(initialReads)).toEqual(["?limit=120&before=40", "?limit=120&before=40"]);
expect(history.reads.slice(initialReads)).toEqual([
"?limit=120&before=40&include_model_requests=1",
"?limit=120&before=40&include_model_requests=1",
]);
history.complete();
await expect(body.getByText("Question 28", { exact: true })).toBeAttached();
await expect(body.locator(".thread-history-slot")).toHaveCount(0);
@@ -1178,7 +1201,11 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
await expect(slot).toHaveCount(0);
await expectAnchorCoordinate(body, "Question 26", secondHeld.anchorTop);
expect((await historyGeometry(body, "Question 26")).slotBeforeKey).toBeNull();
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26"]);
expect(history.reads).toEqual([
"?limit=24&after=38&include_model_requests=1",
"?limit=24&before=38&include_model_requests=1",
"?limit=24&before=26&include_model_requests=1",
]);
const atNewHead = await approachNextHead("Question 14");
expect(atNewHead.firstKey).toBe("u14");
@@ -1201,7 +1228,12 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(36);
await expect(header).toHaveCount(0);
await expect(page.getByText("No earlier messages", { exact: true })).toHaveCount(0);
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14"]);
expect(history.reads).toEqual([
"?limit=24&after=38&include_model_requests=1",
"?limit=24&before=38&include_model_requests=1",
"?limit=24&before=26&include_model_requests=1",
"?limit=24&before=14&include_model_requests=1",
]);
const atKeyboardHead = await approachNextHead("Question 2");
expect(atKeyboardHead.firstKey).toBe("u2");
@@ -1228,7 +1260,13 @@ test("bounded navigation retains three pages and reclaims each completed wheel o
await expect(body.getByText("Question 25", { exact: true })).toBeAttached();
await expect(body.getByText("Question 26", { exact: true })).toHaveCount(0);
await expect(body.locator('[data-thread-display-unit^="u"]')).toHaveCount(26);
expect(history.reads).toEqual(["?limit=24&after=38", "?limit=24&before=38", "?limit=24&before=26", "?limit=24&before=14", "?limit=24&before=2"]);
expect(history.reads).toEqual([
"?limit=24&after=38&include_model_requests=1",
"?limit=24&before=38&include_model_requests=1",
"?limit=24&before=26&include_model_requests=1",
"?limit=24&before=14&include_model_requests=1",
"?limit=24&before=2&include_model_requests=1",
]);
});
+5 -3
View File
@@ -52,20 +52,22 @@ test("complete rail scrolls independently, jumps to unloaded history and returns
await expect(first).toBeFocused();
await first.press("Enter");
await expect(body.getByText("Question 0", { exact: true })).toBeInViewport();
expect(reads).toEqual(["?limit=24&after=0"]);
expect(reads).toEqual(["?limit=24&after=0&include_model_requests=1"]);
await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0);
// Force input-before-scroll ordering instead of relying on compositor timing.
await body.evaluate((node) => node.addEventListener("wheel", () => undefined, { passive: false }));
for (const after of [10, 20, 30, 40]) {
await body.hover();
await page.mouse.wheel(0, 10000);
await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}`)).toBe(true);
await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}&include_model_requests=1`)).toBe(true);
await expect(body.getByText(`Question ${after + 9}`, { exact: true })).toBeAttached();
}
expect(await body.locator("[data-user-prompt-id]").count()).toBeLessThanOrEqual(30);
await body.hover();
await page.mouse.wheel(0, -100000);
await expect.poll(() => reads.some((query) => query.startsWith("?limit=24&before="))).toBe(true);
await expect.poll(() => reads.some((query) => (
query.startsWith("?limit=24&before=") && query.endsWith("&include_model_requests=1")
))).toBe(true);
await page.getByRole("button", { name: "Scroll to bottom" }).click();
await expect(body.getByText("Question 1999", { exact: true })).toBeVisible();
await expect(rail.locator('[aria-current="location"]')).toBeInViewport();
+14 -18
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } fr
import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";
import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext";
import { FilePreviewPanel } from "@/components/FilePreviewPanel";
@@ -77,18 +78,15 @@ import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage | null {
function latestComposerContextUsage(messages: ComposerUsageSnapshot[]): ComposerContextUsage | null {
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (message.kind === "compaction" && message.compaction?.phase === "succeeded") {
if (message.compacted) {
return null;
}
const contextTokens = message.usage?.context_tokens;
if (
message.role !== "assistant"
|| message.kind === "trace"
|| message.isStreaming
|| typeof contextTokens !== "number"
typeof contextTokens !== "number"
|| !Number.isFinite(contextTokens)
|| contextTokens < 0
) {
@@ -104,23 +102,19 @@ function latestComposerContextUsage(messages: UIMessage[]): ComposerContextUsage
return null;
}
function recentComposerRoundUsage(messages: UIMessage[]): ComposerRoundUsage[] {
function recentComposerRoundUsage(messages: ComposerUsageSnapshot[]): ComposerRoundUsage[] {
const recent: ComposerRoundUsage[] = [];
const seenTurns = new Set<string>();
for (let index = messages.length - 1; index >= 0 && recent.length < 8; index -= 1) {
const message = messages[index];
const turnKey = message.turnId || message.id;
if (
message.role !== "assistant"
|| message.kind === "trace"
|| message.isStreaming
|| seenTurns.has(turnKey)
) {
if (seenTurns.has(turnKey)) {
continue;
}
seenTurns.add(turnKey);
const rounds: RoundUsage[] = message.roundUsages ?? [];
if (!rounds.length) continue;
seenTurns.add(turnKey);
for (let roundIndex = rounds.length - 1; roundIndex >= 0; roundIndex -= 1) {
const round = rounds[roundIndex];
const inputTokens = round.prompt_tokens;
@@ -589,6 +583,7 @@ export function ThreadShell({
}, [chatId, onTurnEnd]);
const {
messages,
modelRequests,
messagesKey,
messagesReady,
isStreaming,
@@ -700,13 +695,14 @@ export function ThreadShell({
useEffect(() => {
if (hasAppMentions) requestMentionCatalogs();
}, [hasAppMentions, requestMentionCatalogs]);
const usageSnapshots = useMemo(() => composerUsageSnapshots(messages, modelRequests), [messages, modelRequests]);
const composerContextUsage = useMemo(
() => latestComposerContextUsage(displayMessages),
[displayMessages],
() => latestComposerContextUsage(usageSnapshots),
[usageSnapshots],
);
const composerRoundUsage = useMemo(
() => recentComposerRoundUsage(displayMessages),
[displayMessages],
() => recentComposerRoundUsage(usageSnapshots),
[usageSnapshots],
);
const currentGoalState = messagesReady ? goalState : undefined;
// Recovery decisions gate queued input, not the ledger-owned run state.
+15 -2
View File
@@ -36,6 +36,7 @@ import type {
RetryStatus,
UIMediaAttachment,
UIMessage,
UIModelRequestSnapshot,
WorkspaceScopePayload,
} from "@/lib/types";
@@ -147,6 +148,7 @@ export function useNanobotStream(
historyActiveTurnId: string | null = null,
): {
messages: UIMessage[];
modelRequests: ReadonlyMap<string, UIModelRequestSnapshot>;
/** Conversation owning these messages, including while a selection is handing over. */
messagesKey: string | null;
/** Whether ``messages`` belongs to the current ``chatId`` after a session switch. */
@@ -197,6 +199,7 @@ export function useNanobotStream(
historyRunGenerationRef.current = { chatId, generation: chatId ? client.getRunGeneration(chatId) : 0 };
}
const [messages, setRenderedMessages] = useState<UIMessage[]>(initialTranscript.messages);
const [modelRequests, setModelRequests] = useState(initialTranscript.modelRequests);
const messagesRef = useRef(messages);
// Keep received state ahead of React's batched render: navigation can unmount
// this hook after a stream flush but before the queued render commits.
@@ -205,6 +208,7 @@ export function useNanobotStream(
messagesRef.current = next;
transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: next };
setRenderedMessages(next);
setModelRequests(transcriptRef.current.modelRequests);
setHistoryState(transcriptRef.current.paging);
}, []);
const [messageScope, setMessageScope] = useState({ chatId, historyKey, client });
@@ -717,6 +721,11 @@ export function useNanobotStream(
});
return;
}
if (ev.event === "model_request") {
flushPendingStreamEvents();
applyProjectionEvent(ev);
return;
}
const sideChannelEvent = isSideChannelEvent(ev);
if (ev.event === "context_compaction") {
flushPendingStreamEvents();
@@ -1042,8 +1051,11 @@ export function useNanobotStream(
flushPendingStreamEvents();
setRetryStatus(null);
setMessages((prev) => {
const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
transcriptRef.current.projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled);
const settled = prev.map((m) => ({ ...m, isStreaming: false }));
const projection = resetThreadProjectionCursor(transcriptRef.current.projection, settled);
const modelRequests = new Map(projection.modelRequests);
for (const [turn, snapshot] of modelRequests) modelRequests.set(turn, { ...snapshot, ended: true });
transcriptRef.current.projection = { ...projection, modelRequests };
return settled;
});
client.finishRunLocally(chatId);
@@ -1075,6 +1087,7 @@ export function useNanobotStream(
return {
messages,
modelRequests,
messagesKey: messageScope.historyKey ?? messageScope.chatId,
messagesReady: messageScope.chatId === chatId && messageScope.historyKey === historyKey && messageScope.client === client,
isStreaming,
+14
View File
@@ -387,6 +387,19 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|| !isCompactionPhase(value.phase)
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
return value as unknown as ThreadProjectionEvent;
case "model_request": {
const isUsage = (usage: unknown) => isRecord(usage)
&& Object.values(usage).every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0);
if (typeof value.request_id !== "string" || !value.request_id
|| typeof value.run_id !== "string" || !value.run_id
|| !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0
|| !["started", "completed", "failed", "cancelled"].includes(String(value.phase))
|| (value.usage !== undefined && !isUsage(value.usage))
|| (value.round_usages !== undefined && (!Array.isArray(value.round_usages) || !value.round_usages.every(isUsage)))
|| (value.context_window_tokens !== undefined && (typeof value.context_window_tokens !== "number"
|| !Number.isFinite(value.context_window_tokens) || value.context_window_tokens < 0))) break;
return value as unknown as ThreadProjectionEvent;
}
case "turn_end":
return value as unknown as ThreadProjectionEvent;
}
@@ -436,6 +449,7 @@ export async function fetchWebuiThread(
if (options?.direction) params.set("direction", options.direction);
if (options?.before) params.set("before", options.before);
if (options?.after) params.set("after", options.after);
params.set("include_model_requests", "1");
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
+72
View File
@@ -0,0 +1,72 @@
import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types";
export type ComposerUsageSnapshot = Pick<UIMessage,
"id" | "turnId" | "createdAt" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"
> & { compacted?: boolean };
export function reconcileModelRequest(
current: UIModelRequestSnapshot | undefined,
incoming: UIModelRequestSnapshot,
): UIModelRequestSnapshot {
if (!current) return incoming;
if ((current.ended && !incoming.ended) || current.retiredRunIds.includes(incoming.runId)) return current;
if (current.turnSeq !== undefined && incoming.turnSeq !== undefined) {
if (incoming.turnSeq < current.turnSeq
|| (incoming.turnSeq === current.turnSeq && !(incoming.ended && !current.ended))) return current;
} else if (current.runId === incoming.runId) {
if (incoming.sequence < current.sequence
|| (incoming.sequence === current.sequence && !(incoming.ended && !current.ended))) return current;
} else if (!incoming.retiredRunIds.includes(current.runId)) return current;
return { ...incoming, retiredRunIds: Array.from(new Set([
...current.retiredRunIds, ...incoming.retiredRunIds,
...(current.runId !== incoming.runId ? [current.runId] : []),
])) };
}
/** Select one authoritative usage snapshot per turn, independent of text rows. */
export function composerUsageSnapshots(
messages: UIMessage[],
snapshots: ReadonlyMap<string, UIModelRequestSnapshot>,
): ComposerUsageSnapshot[] {
const lastRows = new Map<string, number>();
const compactions = new Map<string, number | undefined>();
messages.forEach((row, index) => {
if (!row.turnId) return;
lastRows.set(row.turnId, index);
if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {
compactions.set(row.turnId, row.compaction.turnSeq);
}
});
const rows = messages.flatMap((row, index): ComposerUsageSnapshot[] => {
const snapshot = row.turnId ? snapshots.get(row.turnId) : undefined;
if (snapshot) {
if (lastRows.get(row.turnId!) !== index) return [];
const compactionSeq = compactions.get(row.turnId!);
const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined
&& compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq);
return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted,
completedAt: snapshot.completedAt ?? row.completedAt, usage: snapshot.usage,
roundUsages: snapshot.roundUsages, contextWindowTokens: snapshot.contextWindowTokens }];
}
if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {
return [{ id: row.id, createdAt: row.createdAt, compacted: true }];
}
if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return [];
return [row];
});
// Proactive requests can precede any body. They need usage, not placeholder rows.
const unanchored = Array.from(snapshots, ([turnId, snapshot]) => ({
id: `model-request:${turnId}`, turnId, ...snapshot,
})).filter((snapshot) => !lastRows.has(snapshot.turnId))
.sort((left, right) => left.createdAt - right.createdAt);
if (!unanchored.length) return rows;
const result: ComposerUsageSnapshot[] = [];
let index = 0;
for (const row of rows) {
while (index < unanchored.length && unanchored[index].createdAt <= row.createdAt) {
result.push(unanchored[index++]);
}
result.push(row);
}
return [...result, ...unanchored.slice(index)];
}
+1
View File
@@ -19,6 +19,7 @@ export function copyThreadCheckpoint(
projection: {
...checkpoint.projection,
messages,
modelRequests: new Map(checkpoint.projection.modelRequests),
closedAssistantIds: new Set(checkpoint.projection.closedAssistantIds),
closedAnswerStreamIds: new Set(checkpoint.projection.closedAnswerStreamIds),
closedTurnIds: new Set(checkpoint.projection.closedTurnIds),
+49 -3
View File
@@ -10,6 +10,7 @@ import type {
ToolProgressEvent,
UIFileEdit,
UIMessage,
UIModelRequestSnapshot,
UITurnPhase,
} from "@/lib/types";
@@ -21,6 +22,7 @@ const FILE_EDIT_TOOL_NAMES = new Set(["write_file", "edit_file", "apply_patch"])
export interface ThreadProjectionState {
messages: UIMessage[];
modelRequests: ReadonlyMap<string, UIModelRequestSnapshot>;
activeAssistantId: string | null;
closedAssistantIds: Set<string>;
/** Completed wire identities also fence late deltas for textless ends. */
@@ -399,6 +401,7 @@ export function createThreadProjectionState(
): ThreadProjectionState {
return {
messages,
modelRequests: new Map(),
activeAssistantId: null,
closedAssistantIds: new Set(),
closedAnswerStreamIds: new Set(),
@@ -418,6 +421,7 @@ export function resetThreadProjectionCursor(
): ThreadProjectionState {
return {
...createThreadProjectionState(messages),
modelRequests: state.modelRequests,
activitySegmentCounter: state.activitySegmentCounter,
closedTurnIds: new Set(state.closedTurnIds),
turnAliases: new Map(state.turnAliases),
@@ -727,9 +731,9 @@ function projectToolActivity(
: event.text
? [event.text]
: [];
if (lines.length === 0) return;
const deferredDetail = event.trace_detail;
if (lines.length === 0 && !deferredDetail) return;
const segmentId = ensureProjectionActivitySegment(state);
const turn = turnFieldsForProjection(state, event, "activity");
const last = state.messages[state.messages.length - 1];
@@ -780,7 +784,7 @@ function projectToolActivity(
id,
role: "tool",
kind: "trace",
content: lines[lines.length - 1],
content: lines[lines.length - 1] ?? "",
traces: lines,
...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),
...(deferredDetail ? { traceDetail: deferredDetail } : {}),
@@ -857,6 +861,35 @@ export function projectThreadEvent(
turnAliases: new Map(previous.turnAliases),
};
if (event.event === "model_request") {
if (!event.turn_id || state.closedTurnIds.has(event.turn_id)) return state;
const previousRequest = state.modelRequests.get(event.turn_id);
if (previousRequest?.ended
|| previousRequest?.retiredRunIds.includes(event.run_id)
|| (previousRequest?.runId === event.run_id && event.sequence <= previousRequest.sequence)
|| (previousRequest?.turnSeq !== undefined && event.turn_seq !== undefined
&& event.turn_seq <= previousRequest.turnSeq)) return state;
const modelRequest: UIModelRequestSnapshot = {
...previousRequest,
createdAt: previousRequest?.createdAt ?? projectionCreatedAt(event, options),
runId: event.run_id,
sequence: event.sequence,
turnSeq: event.turn_seq,
...((event.phase === "completed" || event.phase === "failed")
&& (event.usage?.request_count ?? 0) > (
previousRequest?.runId === event.run_id ? previousRequest.usage?.request_count ?? 0 : 0
) ? { usageTurnSeq: event.turn_seq } : {}),
retiredRunIds: previousRequest && previousRequest.runId !== event.run_id
? [...previousRequest.retiredRunIds, previousRequest.runId]
: previousRequest?.retiredRunIds ?? [],
...(event.usage !== undefined ? { usage: event.usage } : {}),
...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),
...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),
};
state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest);
return state;
}
if (event.event === "user_message") {
if (event.provenance?.session_message) {
const messageId = event.provenance.session_message.message_id?.trim();
@@ -1002,6 +1035,7 @@ export function projectThreadEvent(
compaction: {
id: event.compaction_id,
phase: event.phase,
turnSeq: event.turn_seq,
reason: event.reason,
...(!options.persisted ? { announce: true } : {}),
},
@@ -1089,6 +1123,18 @@ export function projectThreadEvent(
state.activitySegmentId = null;
state.fileEditSegmentId = null;
state.messages = finalizeStreamedTurn(state.messages);
const modelRequests = new Map(state.modelRequests);
for (const [turnId, snapshot] of modelRequests) {
if (turn.turnId && turnId !== turn.turnId) continue;
modelRequests.set(turnId, { ...snapshot, ended: true,
turnSeq: event.turn_seq ?? snapshot.turnSeq,
...(!options.persisted ? { completedAt: options.now } : {}),
...(event.usage !== undefined ? { usage: event.usage } : {}),
...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),
...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),
});
}
state.modelRequests = modelRequests;
const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0
? Math.round(event.latency_ms)
: undefined;
+18 -2
View File
@@ -6,6 +6,7 @@ import {
import { persistedCanonicalRunState } from "./canonical-run-snapshot";
import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint";
import { hasPendingAgentActivity } from "./activity-timeline";
import { reconcileModelRequest } from "./model-request";
import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types";
type Ranges = Array<[number, number]>;
@@ -159,6 +160,7 @@ export class ThreadTranscript {
}
get messages(): UIMessage[] { return this.projection.messages; }
get modelRequests() { return this.projection.modelRequests; }
private installUnit(unit: Unit): void {
this.order = Math.max(this.order, unit.order + 1);
@@ -246,6 +248,11 @@ export class ThreadTranscript {
project(event: ThreadProjectionEvent, options: {
createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number;
}): UIMessage[] {
// Telemetry never contributes body sources, memberships, or admission barriers.
if (event.event === "model_request") {
this.projection = projectThreadEvent(this.projection, event, options);
return this.messages;
}
if (!options.persisted && this.represented(event)) return this.messages;
if (!event.projection_id && (!event.turn_id || event.turn_seq === undefined)) {
event = { ...event, projection_id: options.createId() };
@@ -478,15 +485,19 @@ export class ThreadTranscript {
}
if (keepSuffix) nextMessages.push(...this.messages.slice(previous)
.filter((row) => !replaced.has(this.byRow.get(row.id)!)));
const modelRequests = new Map(this.modelRequests);
for (const [turn, snapshot] of candidate.modelRequests) {
modelRequests.set(turn, reconcileModelRequest(modelRequests.get(turn), snapshot));
}
this.projection = fullyAdopt && read.kind !== "older"
? { ...candidate.projection, messages: nextMessages,
? { ...candidate.projection, messages: nextMessages, modelRequests,
activitySegmentId: candidate.projection.activitySegmentId
? segments.get(candidate.projection.activitySegmentId) ?? null : null,
fileEditSegmentId: candidate.projection.fileEditSegmentId
? segments.get(candidate.projection.fileEditSegmentId) ?? null : null,
closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]),
closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) }
: { ...this.projection, messages: nextMessages };
: { ...this.projection, messages: nextMessages, modelRequests };
if (fullyAdopt && read.kind !== "older") {
const retained = new Set(prefix.map((row) => row.id));
for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit);
@@ -559,6 +570,11 @@ export class ThreadTranscript {
.filter((key) => retainedStreams.has(key)));
const retainedTurns = new Set(Array.from(this.units).flatMap((unit) => Array.from(unit.members.keys())));
for (const row of nextMessages) if (row.turnId) retainedTurns.add(row.turnId);
for (const [turn, snapshot] of modelRequests) {
if (reset && snapshot.ended && !retainedTurns.has(turn) && !candidate.modelRequests.has(turn)) {
modelRequests.delete(turn);
} else retainedTurns.add(turn);
}
const retainedRows = new Set(nextMessages.map((row) => row.id));
const retainedBoundaries = new Set(Array.from(this.units).flatMap((unit) => unit.text
.map((text) => JSON.stringify([text.turn, text.phase, text.stream]))));
+30
View File
@@ -8,6 +8,8 @@ type Role = "user" | "assistant" | "tool" | "system";
type MessageKind = "message" | "trace" | "compaction";
export interface UIContextCompaction extends ContextCompaction {
/** Lifecycle event sequence, independent of the row's display position. */
turnSeq?: number;
/** Live wire transitions announce; hydrated transcript rows stay silent. */
announce?: boolean;
}
@@ -180,6 +182,22 @@ export interface UIMessage {
deliveryErrorKind?: MessageDeliveryErrorKind;
}
/** Turn-owned telemetry, not a transcript row or body-history source. */
export interface UIModelRequestSnapshot {
runId: string;
sequence: number;
turnSeq?: number;
retiredRunIds: string[];
createdAt: number;
completedAt?: number;
/** Last turn sequence reporting fresh context usage. */
usageTurnSeq?: number;
ended?: boolean;
usage?: TurnUsage;
roundUsages?: RoundUsage[];
contextWindowTokens?: number;
}
export interface UICliAppAttachment {
name: string;
display_name?: string;
@@ -1583,6 +1601,17 @@ export type InboundEvent =
fallback?: boolean;
reauth_provider?: string;
}
| ({
event: "model_request";
chat_id: string;
request_id: string;
run_id: string;
sequence: number;
phase: "started" | "completed" | "failed" | "cancelled";
usage?: TurnUsage;
round_usages?: RoundUsage[];
context_window_tokens?: number;
} & InboundTurnMetadata)
| ({
event: "turn_end";
chat_id: string;
@@ -1650,6 +1679,7 @@ export type InboundEvent =
};
type ThreadProjectionEventName =
| "model_request"
| "user_message"
| "message"
| "file_edit"
@@ -185,7 +185,7 @@ describe("AgentActivityCluster", () => {
.toHaveAttribute("aria-label", `${path} 編集`);
});
it("loads deferred trace details only after completed activity is expanded", async () => {
it.each(["exec(…)", ""])("loads deferred trace details only after completed activity is expanded (summary=%s)", async (summary) => {
const onLoadTraceDetails = vi.fn();
render(
<AgentActivityCluster
@@ -193,8 +193,8 @@ describe("AgentActivityCluster", () => {
id: "t-deferred",
role: "tool",
kind: "trace",
content: "exec(…)",
traces: ["exec(…)"],
content: summary,
traces: summary ? [summary] : [],
traceDetail: {
ref: "9.tr-deadbeefdeadbeef",
bytes: 40_000,
+12 -3
View File
@@ -32,6 +32,7 @@ import {
fetchSkills,
fetchTrendingMarketplaceSkills,
fetchWebuiThread,
fetchSubagentThread,
fetchWebuiThreadTraceDetail,
fetchWorkspaces,
importMcpConfig,
@@ -97,11 +98,19 @@ describe("webui API helpers", () => {
vi.unstubAllGlobals();
});
it("fetches a subagent thread from its parent session", async () => {
await fetchSubagentThread("tok", "websocket:chat-1", "task-1");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/subagents/task-1/webui-thread",
expect.objectContaining({ headers: { Authorization: "Bearer tok" } }),
);
});
it("percent-encodes websocket keys when fetching webui-thread snapshot", async () => {
await fetchWebuiThread("tok", "websocket:chat-1");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -117,7 +126,7 @@ describe("webui API helpers", () => {
});
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D",
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&include_model_requests=1",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -163,7 +172,7 @@ describe("webui API helpers", () => {
})).resolves.toBe(cached);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread",
"/api/sessions/websocket%3Achat-1/webui-thread?include_model_requests=1",
expect.objectContaining({
headers: {
Authorization: "Bearer tok",
@@ -43,7 +43,7 @@ describe("shared latest thread requests", () => {
const surviving = fetchLatestWebuiThread(client, "token", KEY);
expect(fetchMock).toHaveBeenCalledTimes(1);
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest",
"/api/sessions/websocket%3Ashared/webui-thread?limit=40&direction=latest&include_model_requests=1",
expect.objectContaining({ headers: { Authorization: "Bearer token", "If-None-Match": '"cached"' } }),
);
const rejected = expect(first).rejects.toMatchObject({ name: "AbortError" });
+205
View File
@@ -0,0 +1,205 @@
import { describe, expect, it } from "vitest";
import { parseWebuiThreadPayload } from "@/lib/api";
import { composerUsageSnapshots } from "@/lib/model-request";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadTranscript } from "@/lib/thread-transcript";
import type { ThreadProjectionEvent } from "@/lib/types";
const envelope = { chat_id: "chat", turn_id: "turn" };
const request = (sequence: number, extra: Partial<Extract<ThreadProjectionEvent, { event: "model_request" }>> = {}): ThreadProjectionEvent => ({
...envelope, event: "model_request", run_id: "run", request_id: `request-${sequence}`,
sequence, turn_seq: sequence, phase: "started", ...extra,
});
const usage = (count: number) => ({ prompt_tokens: count * 100, completion_tokens: count * 10,
context_tokens: 100 + count, request_count: count });
const rounds = (count: number) => Array.from({ length: count }, (_, index) => ({ prompt_tokens: 100 + index, completion_tokens: 10 }));
function project(transcript: ThreadTranscript, event: ThreadProjectionEvent, persisted = false) {
return transcript.project(event, { createId: () => `event-${event.turn_seq}`, now: 1, persisted });
}
describe("model request snapshots", () => {
it("validates request identity, phase, sequence, and usage at the history boundary", () => {
for (const invalid of [{ phase: "unknown" }, { sequence: -1 }, { run_id: null }, { usage: { context_tokens: "123" } }]) {
expect(() => parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [{ ...request(1), ...invalid }] })).toThrow();
}
expect(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [] }).events).toEqual([]);
});
it("updates active usage cumulatively, retains it during the next call, and replaces the final snapshot", () => {
const transcript = new ThreadTranscript();
const events: ThreadProjectionEvent[] = [{ ...envelope, event: "user_message", text: "hello", starts_turn: true, turn_seq: 0 }];
project(transcript, events[0]);
for (let count = 1; count <= 3; count++) {
const event = request(count * 2, { phase: "completed", usage: usage(count), round_usages: rounds(count), context_window_tokens: 128000 });
events.push(event); project(transcript, event);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage?.request_count).toBe(count);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.roundUsages).toHaveLength(count);
}
const started = request(7);
events.push(started); project(transcript, started);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage?.context_tokens).toBe(103);
const answer: ThreadProjectionEvent = { ...envelope, event: "delta", text: "answer", turn_seq: 8 };
events.push(answer); project(transcript, answer);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests)).toHaveLength(1);
const end: ThreadProjectionEvent = { ...envelope, event: "turn_end", turn_seq: 9, usage: usage(3), round_usages: rounds(3) };
events.push(end); project(transcript, end);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).flatMap((entry) => entry.roundUsages ?? [])).toHaveLength(3);
const replay = new ThreadTranscript();
events.forEach((event) => project(replay, event, true));
expect(composerUsageSnapshots(replay.messages, replay.modelRequests).at(-1)?.usage).toEqual(usage(3));
project(transcript, request(10, { usage: usage(99) }));
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage).toEqual(usage(3));
});
it.each([false, true])("invalidates compacted context until fresh completion (persisted=%s)", (persisted) => {
const transcript = new ThreadTranscript();
const send = (event: ThreadProjectionEvent) => project(transcript, event, persisted);
const latest = () => composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!;
send(request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }));
expect(projectWebuiThreadMessages(transcript.messages)).toEqual([]);
send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "started", turn_seq: 2 });
expect(latest().compacted).toBe(false);
send({ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 });
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
send(request(4, { usage: usage(1), round_usages: rounds(1) }));
expect(latest().compacted).toBe(true);
expect(latest().roundUsages).toEqual(rounds(1));
expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]);
const smaller = { ...usage(2), context_tokens: 50 };
send(request(5, { request_id: "request-4", phase: "completed", usage: smaller, round_usages: rounds(2) }));
expect(latest().compacted).toBe(false);
expect(latest().usage?.context_tokens).toBe(50);
send({ ...envelope, event: "turn_end", turn_seq: 6, usage: smaller, round_usages: rounds(2) });
expect(latest().compacted).toBe(false);
expect(latest().usage?.context_tokens).toBe(50);
expect(latest().roundUsages).toEqual(rounds(2));
expect(projectWebuiThreadMessages(transcript.messages).map((row) => row.kind)).toEqual(["compaction"]);
});
it.each([false, true])("does not treat turn-end cumulative usage as fresh after compaction (persisted=%s)", (persisted) => {
const transcript = new ThreadTranscript();
for (const event of [
request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }),
{ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "started", turn_seq: 2 },
{ ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 3 },
{ ...envelope, event: "turn_end", turn_seq: 4, usage: usage(1), round_usages: rounds(1) },
] as ThreadProjectionEvent[]) project(transcript, event, persisted);
const snapshot = composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)!;
expect(snapshot.compacted).toBe(true);
expect(snapshot.roundUsages).toEqual(rounds(1));
});
it("preserves legacy compaction invalidation and historical rounds without request events", () => {
const transcript = new ThreadTranscript();
project(transcript, { ...envelope, event: "delta", text: "answer", turn_seq: 1 });
project(transcript, { ...envelope, event: "turn_end", usage: usage(1), round_usages: rounds(1), turn_seq: 2 });
project(transcript, { ...envelope, turn_id: "compact-turn", event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 1 });
const snapshots = composerUsageSnapshots(transcript.messages, transcript.modelRequests);
expect(snapshots.at(-1)?.compacted).toBe(true);
expect(snapshots.flatMap((row) => row.roundUsages ?? [])).toEqual(rounds(1));
});
it("rejects duplicates, reordered snapshots, and superseded runs after checkpoint restoration", () => {
const transcript = new ThreadTranscript();
project(transcript, request(2, { usage: usage(2) }));
project(transcript, request(1, { usage: usage(1) }));
project(transcript, request(2, { usage: usage(99) }));
project(transcript, request(1, { run_id: "new-run", turn_seq: 3, usage: usage(3) }));
const restored = new ThreadTranscript([], transcript.save());
project(restored, request(4, { usage: usage(99) }));
expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)?.usage).toEqual(usage(3));
expect(projectWebuiThreadMessages(restored.messages)).toEqual([]);
});
it("reconciles reconnect history without replacing newer live usage", () => {
const transcript = new ThreadTranscript();
const initial = request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) });
project(transcript, initial);
const read = transcript.begin("latest");
project(transcript, request(2, { phase: "completed", usage: usage(2), round_usages: rounds(2) }));
expect(transcript.accept({ schemaVersion: 3, projection: "events", events: [initial] }, read)).toBe(true);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.usage).toEqual(usage(2));
const fresh = new ThreadTranscript();
expect(fresh.accept(parseWebuiThreadPayload({ schemaVersion: 3, projection: "events", events: [initial, request(2)] }), fresh.begin("initial"))).toBe(true);
expect(composerUsageSnapshots(fresh.messages, fresh.modelRequests).at(-1)?.roundUsages).toHaveLength(1);
});
it("retains proactive usage without body rows across history and clears it with a completed history reset", () => {
const transcript = new ThreadTranscript();
const events: ThreadProjectionEvent[] = [
{ ...envelope, turn_id: "old", event: "message", text: "Old answer", turn_seq: 1, created_at_ms: 1000 },
{ ...envelope, turn_id: "old", event: "turn_end", turn_seq: 2, usage: usage(1), round_usages: rounds(1) },
];
const body = { schemaVersion: 3 as const, projection: "events" as const, events, completed_turn_ids: ["old"] };
expect(transcript.accept(body, transcript.begin("initial"))).toBe(true);
const read = transcript.begin("latest");
project(transcript, request(1, { phase: "completed", created_at_ms: 2000, usage: usage(2), round_usages: rounds(2) }));
expect(transcript.accept(body, read)).toBe(true);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).map((row) => row.usage)).toEqual([usage(1), usage(2)]);
project(transcript, { ...envelope, event: "turn_end", turn_seq: 2, usage: usage(2), round_usages: rounds(2) });
const restored = new ThreadTranscript([], transcript.save());
expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)?.usage).toEqual(usage(2));
expect(restored.accept({ schemaVersion: 3, projection: "events", events: [] }, restored.begin("latest"))).toBe(true);
expect(composerUsageSnapshots(restored.messages, restored.modelRequests)).toEqual([]);
});
it("backfills missed answer and tool history while retaining newer live usage", () => {
const transcript = new ThreadTranscript();
const user: ThreadProjectionEvent = { ...envelope, event: "user_message", text: "question", starts_turn: true, turn_seq: 0 };
const initial = request(1);
project(transcript, user);
project(transcript, initial);
const read = transcript.begin("latest");
const latest = request(3, { turn_seq: 5, phase: "completed", usage: usage(2), round_usages: rounds(2), context_window_tokens: 128000 });
project(transcript, latest);
const events: ThreadProjectionEvent[] = [user, initial,
request(2, { phase: "completed", usage: usage(1), round_usages: rounds(1) }),
{ ...envelope, event: "stream_end", turn_seq: 3, stream_id: "missed-answer", text: "missed answer", resuming: true },
{ ...envelope, event: "message", turn_seq: 4, kind: "tool_hint", text: "", tool_events: [{
version: 1, name: "read_file", call_id: "missed-tool", phase: "end",
arguments: { path: "example.txt" }, result: "missed tool result",
}] },
];
expect(transcript.accept({ schemaVersion: 3, projection: "events", events,
active_turn_id: "turn", completed_turn_ids: [], has_pending_tool_calls: true }, read)).toBe(true);
expect(transcript.messages.map((row) => row.content)).toContain("missed answer");
expect(transcript.messages.flatMap((row) => row.toolEvents ?? [])).toMatchObject([
{ call_id: "missed-tool", phase: "end", result: "missed tool result" },
]);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)).toMatchObject({
usage: usage(2), roundUsages: rounds(2), contextWindowTokens: 128000,
});
const restored = new ThreadTranscript([], transcript.save());
const final: ThreadProjectionEvent = { ...envelope, event: "turn_end", turn_seq: 6,
usage: usage(3), round_usages: rounds(3), context_window_tokens: 64000 };
project(restored, final);
expect(composerUsageSnapshots(restored.messages, restored.modelRequests).at(-1)).toMatchObject({
usage: usage(3), roundUsages: rounds(3), contextWindowTokens: 64000,
});
const reloaded = new ThreadTranscript();
expect(reloaded.accept({ schemaVersion: 3, projection: "events", events: [...events, latest, final],
completed_turn_ids: ["turn"] }, reloaded.begin("initial"))).toBe(true);
expect(composerUsageSnapshots(reloaded.messages, reloaded.modelRequests).at(-1)?.usage).toEqual(usage(3));
expect(reloaded.messages.map((row) => row.content)).toContain("missed answer");
});
it.each([false, true])("does not treat a missing-usage completion as fresh after compaction (replay=%s)", (persisted) => {
const transcript = new ThreadTranscript();
project(transcript, request(1, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), persisted);
project(transcript, { ...envelope, event: "context_compaction", compaction_id: "compact", phase: "succeeded", turn_seq: 2 }, persisted);
project(transcript, request(3, { usage: usage(1), round_usages: rounds(1) }), persisted);
project(transcript, request(4, { phase: "completed", usage: usage(1), round_usages: rounds(1) }), persisted);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.compacted).toBe(true);
project(transcript, request(5, { phase: "failed", usage: usage(2), round_usages: rounds(2) }), persisted);
expect(composerUsageSnapshots(transcript.messages, transcript.modelRequests).at(-1)?.compacted).toBe(false);
});
it("keeps active history snapshots and bounds rounds to the latest eight calls", () => {
const replay = new ThreadTranscript();
project(replay, request(1, { phase: "completed", usage: usage(10), round_usages: rounds(10) }), true);
project(replay, request(2), true);
const snapshot = composerUsageSnapshots(replay.messages, replay.modelRequests).at(-1)!;
expect(snapshot.roundUsages).toHaveLength(8);
expect(snapshot.roundUsages?.[0].prompt_tokens).toBe(102);
});
});
@@ -193,7 +193,7 @@ describe("canonical thread event projection", () => {
expect(normalizeProjection(messages)).toEqual(fixtureCase.expected);
});
it("keeps deferred activity rows separately addressable in one segment", () => {
it.each(["read_file(…)", ""])("keeps deferred activity rows separately addressable in one segment (summary=%s)", (summary) => {
const firstDetail = { ref: "2.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 };
const secondDetail = { ref: "2.history-bbbbbbbbbbbbbbbbbbbb", bytes: 41_000, traceCount: 1 };
@@ -209,7 +209,7 @@ describe("canonical thread event projection", () => {
{
event: "message",
chat_id: "chat-1",
text: "read_file(…)",
text: summary,
kind: "tool_hint",
projection_id: "history-bbbbbbbbbbbbbbbbbbbb",
trace_detail: secondDetail,
@@ -217,6 +217,7 @@ describe("canonical thread event projection", () => {
]);
expect(messages).toHaveLength(2);
expect(messages.map((message) => message.content)).toEqual(["exec(…)", summary]);
expect(messages.map((message) => message.traceDetail)).toEqual([
firstDetail,
secondDetail,
+32
View File
@@ -1032,6 +1032,38 @@ describe("ThreadShell", () => {
expect(screen.getAllByTestId("round-usage-bar")).toHaveLength(4);
});
it("updates composer usage from active model snapshots without changing the body", async () => {
const client = makeClient();
const envelope = { chat_id: "live-usage", turn_id: "live-turn" };
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => Promise.resolve(
String(input).includes("websocket%3Alive-usage/webui-thread")
? httpJson({ schemaVersion: 3, projection: "events", active_turn_id: "live-turn", has_pending_tool_calls: true,
events: [{ ...envelope, event: "user_message", text: "Waiting for answer", starts_turn: true, turn_seq: 0 }] })
: { ok: false, status: 404, json: async () => ({}) },
)));
render(wrap(client, <ThreadShell
session={session("live-usage")} title="Live usage" onToggleSidebar={() => {}}
settingsSnapshot={modelSettings("test-model", "deepseek")}
/>));
await screen.findByText("Waiting for answer");
act(() => client._emitChat("live-usage", { ...envelope, event: "model_request", request_id: "first", run_id: "run",
phase: "completed", sequence: 1, turn_seq: 1, context_window_tokens: 1000,
usage: { prompt_tokens: 100, completion_tokens: 10, context_tokens: 100, request_count: 1 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }],
}));
const trigger = await screen.findByTestId("composer-context-usage");
expect(trigger).toHaveAccessibleName("Context 10%. Open context usage");
act(() => client._emitChat("live-usage", { ...envelope, event: "model_request", request_id: "second", run_id: "run",
phase: "completed", sequence: 2, turn_seq: 2, context_window_tokens: 1000,
usage: { prompt_tokens: 300, completion_tokens: 20, context_tokens: 200, request_count: 2 },
round_usages: [{ prompt_tokens: 100, completion_tokens: 10 }, { prompt_tokens: 200, completion_tokens: 10 }],
}));
expect(trigger).toHaveAccessibleName("Context 20%. Open context usage");
fireEvent.click(trigger);
expect(await screen.findAllByTestId("round-usage-bar")).toHaveLength(2);
expect(screen.getByText("Waiting for answer")).toBeInTheDocument();
});
it.each([false, true])("restores context after compaction only with newer usage (%s)", async (newReply) => {
const client = makeClient();
const messages: UIMessage[] = [
+28
View File
@@ -5,6 +5,7 @@ import { describe, expect, it, vi } from "vitest";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { normalizeActivityTimeline } from "@/lib/activity-timeline";
import { composerUsageSnapshots } from "@/lib/model-request";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import type { NanobotClient, StreamError } from "@/lib/nanobot-client";
import type {
@@ -3837,3 +3838,30 @@ describe("live canonical event projection", () => {
]);
});
});
it("projects active model usage without ending the turn and ignores late usage after stop", () => {
const fake = fakeClient();
const { result } = renderHook(() => useNanobotStream("chat-model", EMPTY_MESSAGES), {
wrapper: wrap(fake.client),
});
const envelope = { chat_id: "chat-model", turn_id: "turn-model" };
act(() => {
fake.emit("chat-model", { ...envelope, event: "goal_status", status: "running", started_at: 1700 });
fake.emit("chat-model", { ...envelope, event: "user_message", text: "hello", starts_turn: true, turn_seq: 0 });
fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "first", run_id: "run",
sequence: 1, turn_seq: 1, phase: "completed", usage: { prompt_tokens: 105000, completion_tokens: 100,
context_tokens: 105000, request_count: 1 }, round_usages: [{ prompt_tokens: 105000, completion_tokens: 100 }] });
fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "second", run_id: "run",
sequence: 2, turn_seq: 2, phase: "started" });
});
expect(result.current.isStreaming).toBe(true);
expect(composerUsageSnapshots(result.current.messages, result.current.modelRequests).at(-1)?.usage?.context_tokens).toBe(105000);
act(() => result.current.stop());
expect(result.current.isStreaming).toBe(false);
act(() => fake.emit("chat-model", { ...envelope, event: "model_request", request_id: "late", run_id: "run",
sequence: 3, turn_seq: 3, phase: "completed", usage: { prompt_tokens: 999, completion_tokens: 1,
context_tokens: 999, request_count: 2 } }));
expect(result.current.isStreaming).toBe(false);
expect(composerUsageSnapshots(result.current.messages, result.current.modelRequests).at(-1)?.usage?.context_tokens).toBe(105000);
});
+1 -1
View File
@@ -306,7 +306,7 @@ describe("durable run recovery", () => {
await reopen();
expect(fetchMock).toHaveBeenCalledWith(
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest",
"/api/sessions/websocket%3Ainactive/webui-thread?limit=40&direction=latest&include_model_requests=1",
expect.objectContaining({ headers: { Authorization: "Bearer renewed-token" } }),
);
expect(client.getRunStartedAt("inactive")).toBeNull();