refactor(webui): remove legacy message projection (#5823)

* refactor(webui): defer oversized replay traces as events

* fix(webui): type deferred trace index set

* refactor(webui): remove legacy message projection

* fix(webui): type event protocol boundaries

* test(webui): assert canonical thread events
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-20 16:48:13 +08:00
1 parent 756c8bb7ed
commit 0983762fe5
23 files changed
+943 -2839

No files matched your search

+10 -12
View File
@@ -53,7 +53,8 @@ import type {
WorkspaceScopePayload,
WorkspacesPayload,
} from "@/lib/types";
import { projectWebuiThreadMessages } from "@/lib/thread-display-compat";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { cn } from "@/lib/utils";
import { useClient } from "@/providers/ClientProvider";
@@ -771,17 +772,14 @@ export function ThreadShell({
const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref)
.then((detail) => {
if (activeHistoryKeyRef.current !== requestKey) return;
setMessages((current) => current.map((message) => (
message.traceDetail?.ref === ref
? {
...message,
content: detail.content,
traces: detail.traces,
toolEvents: detail.toolEvents,
traceDetail: undefined,
}
: message
)));
const projected = projectThreadEvents(detail.events);
setMessages((current) => current.flatMap((message) => {
if (message.traceDetail?.ref !== ref) return [message];
return projected.map((replacement) => ({
...replacement,
activitySegmentId: message.activitySegmentId ?? replacement.activitySegmentId,
}));
}));
})
.catch((error: unknown) => {
if (activeHistoryKeyRef.current !== requestKey) return;
+10 -26
View File
@@ -38,36 +38,20 @@ function isAbortError(error: unknown): boolean {
export type SessionHistoryContinuity = "initial" | "overlap" | "reset";
function persistedMessagesToUi(messages: UIMessage[]): UIMessage[] {
return messages.map((m, idx) => ({
...m,
id: m.id ?? `hist-${idx}`,
createdAt: typeof m.createdAt === "number" ? m.createdAt : Date.now(),
}));
}
function projectPersistedThread(body: WebuiThreadPersistedPayload | null): {
messages: UIMessage[];
forkBoundaryMessageCount: number | null;
} {
if (body?.events) {
const messages = projectThreadEvents(body.events);
const boundaryIndex = body.fork_boundary_event_index;
const forkBoundaryMessageCount = typeof boundaryIndex === "number"
&& Number.isInteger(boundaryIndex)
&& boundaryIndex >= 0
&& boundaryIndex <= body.events.length
? projectThreadEvents(body.events.slice(0, boundaryIndex)).length
: null;
return { messages, forkBoundaryMessageCount };
}
const messages = persistedMessagesToUi(body?.messages ?? []);
return {
messages,
forkBoundaryMessageCount: typeof body?.fork_boundary_message_count === "number"
? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length))
: null,
};
const events = body?.events ?? [];
const messages = projectThreadEvents(events);
const boundaryIndex = body?.fork_boundary_event_index;
const forkBoundaryMessageCount = typeof boundaryIndex === "number"
&& Number.isInteger(boundaryIndex)
&& boundaryIndex >= 0
&& boundaryIndex <= events.length
? projectThreadEvents(events.slice(0, boundaryIndex)).length
: null;
return { messages, forkBoundaryMessageCount };
}
function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean {
+36 -8
View File
@@ -290,6 +290,18 @@ function hasValidProjectionMetadata(value: Record<string, unknown>): boolean {
);
}
function isProjectionTraceDetail(value: unknown): boolean {
return isRecord(value)
&& typeof value.ref === "string"
&& /^\d{1,12}\.history-[0-9a-f]{20}$/.test(value.ref)
&& typeof value.bytes === "number"
&& Number.isFinite(value.bytes)
&& value.bytes >= 0
&& typeof value.traceCount === "number"
&& Number.isInteger(value.traceCount)
&& value.traceCount >= 0;
}
function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {
throw new Error("Invalid WebUI thread event");
@@ -328,6 +340,10 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
case "message":
if (typeof value.text !== "string") break;
if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break;
if (value.trace_detail !== undefined && (
!["tool_hint", "progress"].includes(String(value.kind))
|| !isProjectionTraceDetail(value.trace_detail)
)) break;
if (value.media_urls !== undefined && (
!Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia)
)) break;
@@ -356,19 +372,32 @@ function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPayload {
if (!isRecord(value) || typeof value.schemaVersion !== "number") {
throw new Error("Invalid WebUI thread response");
}
if (value.messages !== undefined && !Array.isArray(value.messages)) {
throw new Error("Invalid WebUI thread messages");
}
if (value.events !== undefined && !Array.isArray(value.events)) {
if (value.projection !== "events" || !Array.isArray(value.events)) {
throw new Error("Invalid WebUI thread events");
}
const events = value.events?.map(parseThreadProjectionEvent);
const events = value.events.map(parseThreadProjectionEvent);
return {
...value,
...(events ? { events } : {}),
projection: "events",
events,
} as unknown as WebuiThreadPersistedPayload;
}
function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDetailPayload {
if (
!isRecord(value)
|| typeof value.message_id !== "string"
|| !/^history-[0-9a-f]{20}$/.test(value.message_id)
|| !Array.isArray(value.events)
) {
throw new Error("Invalid WebUI thread trace detail response");
}
return {
message_id: value.message_id,
events: value.events.map(parseThreadProjectionEvent),
};
}
export async function fetchWebuiThread(
token: string,
key: string,
@@ -381,7 +410,6 @@ export async function fetchWebuiThread(
if (options?.limit !== undefined) params.set("limit", String(options.limit));
if (options?.direction) params.set("direction", options.direction);
if (options?.before) params.set("before", options.before);
params.set("projection", "events");
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
@@ -413,7 +441,7 @@ export async function fetchWebuiThreadTraceDetail(
cache: "no-store",
});
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
return (await res.json()) as WebuiThreadTraceDetailPayload;
return parseWebuiThreadTraceDetailPayload(await res.json());
}
export async function fetchFilePreview(
@@ -3,27 +3,6 @@ import { isSystemCommandTurnId } from "@/lib/nanobot-client";
import { scrubSubagentUiMessages } from "@/lib/subagent-channel-display";
import type { UIMessage } from "@/lib/types";
/**
* Older WebUI disk snapshots and historical sessions may still contain
* ``kind: "long_task"`` rows from the retired orchestrator UI. Map them to
* ordinary trace rows so the thread stays readable without bespoke cards.
*/
export function normalizeLegacyLongTaskMessages(messages: UIMessage[]): UIMessage[] {
return messages.map((m) => {
const kind = (m as { kind?: string }).kind;
if (kind !== "long_task") return m;
const text = (m.content ?? "").trim() || "(legacy thread activity)";
return {
id: m.id,
role: "tool",
kind: "trace",
content: text,
traces: [text],
createdAt: m.createdAt,
};
});
}
interface PreparedMessage {
message: UIMessage;
hidden: boolean;
@@ -36,7 +15,7 @@ const completionMessages = new WeakMap<UIMessage, { completedAt: number; message
function prepareMessage(original: UIMessage): PreparedMessage {
const cached = preparedMessages.get(original);
if (cached) return cached;
const message = scrubSubagentUiMessages(normalizeLegacyLongTaskMessages([original]))[0];
const message = scrubSubagentUiMessages([original])[0];
const prepared = {
message,
hidden: isSystemCommandTurnId(message.turnId)
+4
View File
@@ -643,6 +643,7 @@ function projectToolActivity(
: [];
if (lines.length === 0) return;
const deferredDetail = event.trace_detail;
const segmentId = ensureProjectionActivitySegment(state);
const turn = turnFieldsForProjection(state, event, "activity");
const last = state.messages[state.messages.length - 1];
@@ -650,6 +651,8 @@ function projectToolActivity(
last
&& last.kind === "trace"
&& !last.isStreaming
&& !last.traceDetail
&& !deferredDetail
&& (!last.activitySegmentId || last.activitySegmentId === segmentId)
) {
const previousTraces = last.traces?.length
@@ -692,6 +695,7 @@ function projectToolActivity(
content: lines[lines.length - 1],
traces: lines,
...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),
...(deferredDetail ? { traceDetail: deferredDetail } : {}),
activitySegmentId: segmentId,
...turn,
createdAt: projectionCreatedAt(event, options),
+12 -15
View File
@@ -71,6 +71,12 @@ export interface ResponseSource {
fallback?: boolean;
}
export interface UITraceDetail {
ref: string;
bytes: number;
traceCount: number;
}
export interface RetryStatus extends WireRetryStatus {
next_retry_at?: number;
turn_id?: string;
@@ -91,11 +97,7 @@ export interface UIMessage {
* distinguish running, completed, and failed tool phases. */
toolEvents?: ToolProgressEvent[];
/** Oversized persisted trace content that can be fetched when activity is expanded. */
traceDetail?: {
ref: string;
bytes: number;
traceCount: number;
};
traceDetail?: UITraceDetail;
/** Activity rows: explicit file edits emitted by edit tools. */
fileEdits?: UIFileEdit[];
/** Activity rows created during the same agent phase share one collapsible block. */
@@ -1387,6 +1389,8 @@ export type InboundEvent =
media?: string[];
media_urls?: Array<{ url: string; name?: string }>;
tool_events?: ToolProgressEvent[];
/** Oversized persisted activity detail, fetched only when the trace is expanded. */
trace_detail?: UITraceDetail;
/** Present when the frame is an agent breadcrumb (e.g. tool hint,
* generic progress line) rather than a conversational reply. */
kind?: "tool_hint" | "progress" | "reasoning";
@@ -1572,8 +1576,6 @@ export interface OutboundMcpPresetMention {
interface WebuiThreadPagePayload {
before_cursor?: string | null;
has_more_before?: boolean;
loaded_message_count?: number;
total_known_message_count?: number;
user_message_offset?: number;
loaded_event_count?: number;
}
@@ -1584,12 +1586,9 @@ export interface WebuiThreadPersistedPayload {
savedAt?: string;
/** Cheap server revision used for application-managed conditional revalidation. */
revision?: string;
/** Legacy server-projected snapshots, retained as a compatibility fallback. */
messages?: UIMessage[];
/** Canonical transcript events projected by the same reducer as live events. */
events?: ThreadProjectionEvent[];
projection?: "events";
fork_boundary_message_count?: number;
events: ThreadProjectionEvent[];
projection: "events";
fork_boundary_event_index?: number;
/** Turn ids backed by an explicit persisted ``turn_end`` event. */
completed_turn_ids?: string[];
@@ -1602,9 +1601,7 @@ export interface WebuiThreadPersistedPayload {
export interface WebuiThreadTraceDetailPayload {
message_id: string;
content: string;
traces?: string[];
toolEvents?: ToolProgressEvent[];
events: ThreadProjectionEvent[];
}
export interface FilePreviewPayload {
+82 -9
View File
@@ -83,9 +83,8 @@ describe("webui API helpers", () => {
ok: true,
json: async () => ({
schemaVersion: 3,
deleted: true,
key: "websocket:chat-1",
messages: [],
projection: "events",
events: [],
}),
}),
);
@@ -100,7 +99,7 @@ describe("webui API helpers", () => {
await fetchWebuiThread("tok", "websocket:chat-1");
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?projection=events",
"/api/sessions/websocket%3Achat-1/webui-thread",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -116,7 +115,7 @@ describe("webui API helpers", () => {
});
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D&projection=events",
"/api/sessions/websocket%3Achat-1/webui-thread?limit=120&before=abc%2B%2F%3D",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -128,7 +127,8 @@ describe("webui API helpers", () => {
const cached = {
schemaVersion: 3,
revision: "rev-1",
messages: [],
projection: "events" as const,
events: [],
};
vi.mocked(fetch).mockResolvedValueOnce({
ok: false,
@@ -141,7 +141,7 @@ describe("webui API helpers", () => {
})).resolves.toBe(cached);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread?projection=events",
"/api/sessions/websocket%3Achat-1/webui-thread",
expect.objectContaining({
headers: {
Authorization: "Bearer tok",
@@ -204,11 +204,84 @@ describe("webui API helpers", () => {
await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({ events: [event] });
});
it("rejects legacy message-projected thread payloads", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ schemaVersion: 3, messages: [] }),
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(
"Invalid WebUI thread events",
);
});
it("accepts validated deferred trace metadata on canonical thread events", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
schemaVersion: 3,
projection: "events",
events: [{
event: "message",
chat_id: "chat-1",
text: "exec(…)",
kind: "progress",
trace_detail: {
ref: "2.history-aaaaaaaaaaaaaaaaaaaa",
bytes: 40_000,
traceCount: 1,
},
}],
}),
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1")).resolves.toMatchObject({
events: [{ trace_detail: { bytes: 40_000, traceCount: 1 } }],
});
});
it("rejects malformed deferred trace metadata at the HTTP boundary", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
schemaVersion: 3,
projection: "events",
events: [{
event: "message",
chat_id: "chat-1",
text: "exec(…)",
kind: "progress",
trace_detail: { ref: "bad", bytes: "many", traceCount: 1 },
}],
}),
} as Response);
await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(
"Invalid WebUI thread projection event: message",
);
});
it("fetches deferred trace details with encoded session and ref", async () => {
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
message_id: "history-aaaaaaaaaaaaaaaaaaaa",
events: [],
}),
} as Response);
await fetchWebuiThreadTraceDetail(
"tok",
"websocket:chat-1",
"9.history-aaaaaaaaaaaaaaaaaaaa",
);
expect(fetch).toHaveBeenCalledWith(
"/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.tr-deadbeefdeadbeef",
"/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.history-aaaaaaaaaaaaaaaaaaaa",
expect.objectContaining({
headers: { Authorization: "Bearer tok" },
credentials: "same-origin",
@@ -1,10 +1,7 @@
import { describe, expect, it } from "vitest";
import { deriveTitle, isModelCommandText, visibleSessionPreview } from "@/lib/format";
import {
normalizeLegacyLongTaskMessages,
projectWebuiThreadMessages,
} from "@/lib/thread-display-compat";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import type { UIMessage } from "@/lib/types";
const STARTED_AT = Date.UTC(2026, 6, 25, 12, 34, 0);
@@ -31,21 +28,7 @@ function message(
};
}
describe("normalizeLegacyLongTaskMessages", () => {
it("maps legacy long_task rows to trace lines", () => {
const legacy = {
id: "x",
role: "assistant",
kind: "long_task",
content: "long_task · done",
createdAt: 1,
} as unknown as UIMessage;
const out = normalizeLegacyLongTaskMessages([legacy]);
expect(out[0]!.kind).toBe("trace");
expect(out[0]!.role).toBe("tool");
expect(out[0]!.traces).toEqual(["long_task · done"]);
});
describe("command display projection", () => {
it("removes model and silent-command turns without hiding concurrent replies", () => {
const visible = projectWebuiThreadMessages([
message("user", { id: "model", content: "/model fast", turnId: "model-turn" }),
@@ -139,7 +122,7 @@ describe("projectWebuiThreadMessages", () => {
expect(visible[1]?.completedAt).toBeUndefined();
});
it("uses the nearest user start for legacy rows without turn metadata", () => {
it("uses the nearest user start for rows without turn metadata", () => {
const visible = projectWebuiThreadMessages([
message("user"),
message("assistant", {
@@ -20,6 +20,7 @@ const SEMANTIC_MESSAGE_FIELDS = [
"kind",
"traces",
"toolEvents",
"traceDetail",
"fileEdits",
"images",
"media",
@@ -98,4 +99,35 @@ describe("canonical thread event projection", () => {
const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript));
expect(normalizeProjection(messages)).toEqual(fixtureCase.expected);
});
it("keeps deferred activity rows separately addressable in one segment", () => {
const firstDetail = { ref: "2.history-aaaaaaaaaaaaaaaaaaaa", bytes: 40_000, traceCount: 1 };
const secondDetail = { ref: "2.history-bbbbbbbbbbbbbbbbbbbb", bytes: 41_000, traceCount: 1 };
const messages = projectThreadEvents([
{
event: "message",
chat_id: "chat-1",
text: "exec(…)",
kind: "progress",
projection_id: "history-aaaaaaaaaaaaaaaaaaaa",
trace_detail: firstDetail,
},
{
event: "message",
chat_id: "chat-1",
text: "read_file(…)",
kind: "tool_hint",
projection_id: "history-bbbbbbbbbbbbbbbbbbbb",
trace_detail: secondDetail,
},
]);
expect(messages).toHaveLength(2);
expect(messages.map((message) => message.traceDetail)).toEqual([
firstDetail,
secondDetail,
]);
expect(messages[0].activitySegmentId).toBe(messages[1].activitySegmentId);
});
});
+44 -20
View File
@@ -17,6 +17,7 @@ import type {
UIMessage,
WebuiThreadPersistedPayload,
} from "@/lib/types";
import { canonicalThreadPayload } from "./thread-test-payload";
const HERO_GREETING_PATTERN =
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
@@ -248,8 +249,8 @@ function session(chatId: string, modelPreset?: string | null) {
function transcriptFromSimpleMessages(
rows: Array<{ role: "user" | "assistant"; content: string; turnId?: string }>,
): { schemaVersion: number; messages: UIMessage[] } {
return {
): WebuiThreadPersistedPayload {
return canonicalThreadPayload({
schemaVersion: 3,
messages: rows.map((m, i) => ({
id: `m-${i}`,
@@ -258,14 +259,19 @@ function transcriptFromSimpleMessages(
...(m.turnId ? { turnId: m.turnId } : {}),
createdAt: 1000 + i,
})),
};
})!;
}
function httpJson(body: unknown) {
const normalized = body && typeof body === "object"
&& "schemaVersion" in body
&& "messages" in body
? canonicalThreadPayload(body as never)
: body;
return {
ok: true,
status: 200,
json: async () => body,
json: async () => normalized,
};
}
@@ -274,7 +280,7 @@ function traceDetailThread(
answer: string,
revision?: string,
): WebuiThreadPersistedPayload {
return {
return canonicalThreadPayload({
schemaVersion: 3,
...(revision ? { revision } : {}),
messages: [
@@ -285,7 +291,13 @@ function traceDetailThread(
content: deferred ? "exec(…)" : 'exec({"command":"echo full"})',
traces: [deferred ? "exec(…)" : 'exec({"command":"echo full"})'],
...(deferred
? { traceDetail: { ref: "1.trace-shared", bytes: 40_000, traceCount: 1 } }
? {
traceDetail: {
ref: "1.history-aaaaaaaaaaaaaaaaaaaa",
bytes: 40_000,
traceCount: 1,
},
}
: {}),
createdAt: 1_000,
},
@@ -296,7 +308,7 @@ function traceDetailThread(
createdAt: 2_000,
},
],
};
})!;
}
function setDocumentVisibility(value: DocumentVisibilityState): void {
@@ -476,9 +488,14 @@ describe("ThreadShell", () => {
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
}
return Promise.resolve(httpJson({
message_id: "trace-deferred",
content: 'exec({"command":"echo full"})',
traces: ['exec({"command":"echo full"})'],
message_id: "history-aaaaaaaaaaaaaaaaaaaa",
events: [{
event: "message",
chat_id: "trace-detail-retry",
projection_id: "trace-deferred",
kind: "progress",
text: 'exec({"command":"echo full"})',
}],
}));
}
if (url.includes("websocket%3Atrace-detail-retry/webui-thread")) {
@@ -491,7 +508,11 @@ describe("ThreadShell", () => {
kind: "trace",
content: "exec(…)",
traces: ["exec(…)"],
traceDetail: { ref: "1.trace-deferred", bytes: 40_000, traceCount: 1 },
traceDetail: {
ref: "1.history-aaaaaaaaaaaaaaaaaaaa",
bytes: 40_000,
traceCount: 1,
},
createdAt: 1_000,
},
{ id: "answer", role: "assistant", content: "done", createdAt: 2_000 },
@@ -521,9 +542,11 @@ describe("ThreadShell", () => {
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(detailCalls).toBe(2));
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
await waitFor(() => expect(document.body).toHaveTextContent("echo full"));
fireEvent.click(activity);
fireEvent.click(activity);
const resolvedActivity = screen.getByRole("button", { name: /Worked/ });
fireEvent.click(resolvedActivity);
fireEvent.click(resolvedActivity);
await act(async () => Promise.resolve());
expect(detailCalls).toBe(2);
});
@@ -2652,11 +2675,6 @@ describe("ThreadShell", () => {
});
await waitFor(() => expect(screen.getByText("strict partial")).toBeInTheDocument());
client.reconcileCanonicalCompletion.mockClear();
const reconcileAfterCommit = client.reconcileCanonicalCompletion.getMockImplementation();
client.reconcileCanonicalCompletion.mockImplementation((...args) => {
expect(screen.getByText("strict canonical answer")).toBeInTheDocument();
return reconcileAfterCommit?.(...args) ?? false;
});
canonicalComplete = true;
act(() => client._emitSessionUpdate("strict-canonical", "thread"));
@@ -3673,7 +3691,10 @@ describe("ThreadShell", () => {
{ role: "user", content: "question" },
{ role: "assistant", content: "answer" },
]);
thread.messages[1]!.media = [{
const answer = thread.events.find(
(event) => event.event === "message" && event.text === "answer",
);
if (answer?.event === "message") answer.media_urls = [{
kind: "image",
url: "/api/media/stable/image",
name: "answer.png",
@@ -3724,7 +3745,10 @@ describe("ThreadShell", () => {
{ role: "user", content: "question" },
{ role: "assistant", content: "answer" },
]);
thread.messages[1]!.media = [{
const answer = thread.events.find(
(event) => event.event === "message" && event.text === "answer",
);
if (answer?.event === "message") answer.media_urls = [{
kind: "image",
url: "/api/media/stable/token-image",
name: "token-answer.png",
+154
View File
@@ -0,0 +1,154 @@
import type {
ThreadProjectionEvent,
UIMessage,
WebuiThreadPersistedPayload,
} from "@/lib/types";
// UI-focused tests can describe their expected rows compactly here, but this
// builder always feeds the application the canonical event protocol. The HTTP
// boundary separately verifies that message-projected payloads are rejected.
type MessageFixturePayload = Omit<
Partial<WebuiThreadPersistedPayload>,
"events" | "projection"
> & {
schemaVersion: number;
messages: UIMessage[];
fork_boundary_message_count?: number;
};
function eventBase(message: UIMessage, suffix = "") {
return {
chat_id: "test-history",
projection_id: `${message.id}${suffix}`,
created_at_ms: message.createdAt,
...(message.turnId ? { turn_id: message.turnId } : {}),
...(message.turnPhase ? { turn_phase: message.turnPhase } : {}),
...(message.turnSeq !== undefined ? { turn_seq: message.turnSeq } : {}),
};
}
function completionEvent(message: UIMessage): ThreadProjectionEvent | null {
if (
message.latencyMs === undefined
&& message.usage === undefined
&& message.roundUsages === undefined
&& message.contextWindowTokens === undefined
) return null;
return {
event: "turn_end",
...eventBase(message, ":complete"),
...(message.latencyMs !== undefined ? { latency_ms: message.latencyMs } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(message.roundUsages ? { round_usages: message.roundUsages } : {}),
...(message.contextWindowTokens !== undefined
? { context_window_tokens: message.contextWindowTokens }
: {}),
};
}
function messageEvents(message: UIMessage): ThreadProjectionEvent[] {
const base = eventBase(message);
if (message.role === "user") {
return [{
event: "user_message",
...base,
text: message.content,
starts_turn: true,
...(message.media?.length ? { media_urls: message.media } : {}),
...(message.cliApps?.length ? { cli_apps: message.cliApps } : {}),
...(message.mcpPresets?.length ? { mcp_presets: message.mcpPresets } : {}),
...(message.sessionMentions?.length
? { session_mentions: message.sessionMentions }
: {}),
}];
}
if (message.kind === "compaction" && message.compaction) {
return [{
event: "context_compaction",
...base,
compaction_id: message.compaction.id,
phase: message.compaction.phase,
}];
}
if (message.kind === "trace" || message.role === "tool") {
const events: ThreadProjectionEvent[] = [];
const traces = message.traceDetail
? [message.content]
: message.traces?.length
? message.traces
: message.content
? [message.content]
: [];
traces.forEach((text, index) => {
events.push({
event: "message",
...eventBase(message, traces.length === 1 ? "" : `:trace:${index}`),
text,
kind: "progress",
...(index === traces.length - 1 && message.toolEvents?.length
? { tool_events: message.toolEvents }
: {}),
...(index === 0 && message.traceDetail
? { trace_detail: message.traceDetail }
: {}),
});
});
if (message.fileEdits?.length) {
events.push({
event: "file_edit",
...eventBase(message, ":files"),
edits: message.fileEdits,
});
}
return events;
}
const events: ThreadProjectionEvent[] = [];
if (message.reasoning) {
events.push({
event: "reasoning_delta",
...eventBase(message, ":reasoning"),
text: message.reasoning,
});
events.push({
event: "reasoning_end",
...eventBase(message, ":reasoning-end"),
});
}
events.push({
event: "message",
...base,
text: message.content,
...(message.media?.length ? { media_urls: message.media } : {}),
...(message.latencyMs !== undefined ? { latency_ms: message.latencyMs } : {}),
});
const completion = completionEvent(message);
if (completion) events.push(completion);
return events;
}
export function canonicalThreadPayload(
payload: WebuiThreadPersistedPayload | MessageFixturePayload | null,
): WebuiThreadPersistedPayload | null {
if (payload === null || "events" in payload) return payload;
const events = payload.messages.flatMap(messageEvents);
const boundary = payload.fork_boundary_message_count;
const forkBoundaryEventIndex = typeof boundary === "number"
? payload.messages.slice(0, boundary).flatMap(messageEvents).length
: undefined;
const rest = { ...payload } as Record<string, unknown>;
delete rest.messages;
delete rest.fork_boundary_message_count;
const canonical = payload as unknown as Record<string, unknown>;
delete canonical.messages;
delete canonical.fork_boundary_message_count;
Object.assign(canonical, {
...rest,
projection: "events",
events,
...(forkBoundaryEventIndex !== undefined
? { fork_boundary_event_index: forkBoundaryEventIndex }
: {}),
});
return payload as unknown as WebuiThreadPersistedPayload;
}
+13 -2
View File
@@ -6,6 +6,7 @@ import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSession
import * as api from "@/lib/api";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ClientProvider } from "@/providers/ClientProvider";
import { canonicalThreadPayload } from "./thread-test-payload";
vi.mock("@/lib/api", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/api")>();
@@ -17,6 +18,16 @@ vi.mock("@/lib/api", async (importOriginal) => {
};
});
const fetchThreadMock = vi.mocked(api.fetchWebuiThread);
const rawMockResolvedValue = fetchThreadMock.mockResolvedValue.bind(fetchThreadMock);
const rawMockResolvedValueOnce = fetchThreadMock.mockResolvedValueOnce.bind(fetchThreadMock);
fetchThreadMock.mockResolvedValue = ((value) => rawMockResolvedValue(
canonicalThreadPayload(value as never),
)) as typeof fetchThreadMock.mockResolvedValue;
fetchThreadMock.mockResolvedValueOnce = ((value) => rawMockResolvedValueOnce(
canonicalThreadPayload(value as never),
)) as typeof fetchThreadMock.mockResolvedValueOnce;
function fakeClient() {
const sessionUpdateHandlers = new Set<(chatId: string, scope?: string) => void>();
return {
@@ -1246,7 +1257,7 @@ describe("useSessions", () => {
expect(result.current.lineage).toBeGreaterThan(oldLineage);
await act(async () => {
resolveOlder?.({
resolveOlder?.(canonicalThreadPayload({
schemaVersion: 3,
messages: [
{ id: "stale-prefix", role: "user", content: "stale prefix", createdAt: 1 },
@@ -1255,7 +1266,7 @@ describe("useSessions", () => {
before_cursor: null,
has_more_before: false,
},
});
}));
await olderRequest;
});