refactor(webui): unify live and replay event projection (#5819)
* refactor(webui): unify live and replay event projection * chore(webui): mark legacy projection cleanup * fix(webui): rewrite streamed replay media URLs
This commit is contained in:
1 parent
3d4200ff0d
commit
db675a43b6
14 files changed
+1726
-665
No files matched your search
+152
-617
@@ -4,32 +4,23 @@ import { useTranslation } from "react-i18next";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { toMediaAttachment } from "@/lib/media";
|
||||
import { resolveModelRequestFailureCopy } from "@/lib/model-request-failure";
|
||||
import {
|
||||
mergeToolProgressEvents,
|
||||
mergeToolProgressTraceLines,
|
||||
normalizeToolProgressEvents,
|
||||
toolTraceLinesFromEvents,
|
||||
} from "@/lib/tool-traces";
|
||||
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||
import type { StreamError } from "@/lib/nanobot-client";
|
||||
import {
|
||||
closeReasoningStream,
|
||||
filterCoveredFileEditToolEvents,
|
||||
clearThreadProjectionActivity,
|
||||
closeThreadProjectionAnswer,
|
||||
createThreadProjectionState,
|
||||
finalizeStreamedTurn,
|
||||
findActiveAssistantPlaceholderIndex,
|
||||
findFileEditTraceIndex,
|
||||
findStreamingAssistantIndex,
|
||||
isReasoningOnlyPlaceholder,
|
||||
matchesTurn,
|
||||
mergeFileEdits,
|
||||
replaceMessageAt,
|
||||
stampLastAssistantCompletion,
|
||||
stripCoveredFileEditToolHintsFromMessages,
|
||||
projectThreadEvent,
|
||||
resetThreadProjectionCursor,
|
||||
turnFieldsFromEvent,
|
||||
} from "@/lib/thread-event-projection";
|
||||
import type { UIMessageTurnFields } from "@/lib/thread-event-projection";
|
||||
import type {
|
||||
ThreadProjectionEvent,
|
||||
ThreadProjectionState,
|
||||
UIMessageTurnFields,
|
||||
} from "@/lib/thread-event-projection";
|
||||
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
|
||||
import { readLocalPreferences } from "@/lib/local-preferences";
|
||||
import type {
|
||||
@@ -47,17 +38,6 @@ import type {
|
||||
WorkspaceScopePayload,
|
||||
} from "@/lib/types";
|
||||
|
||||
interface StreamBuffer {
|
||||
/** ID of the assistant message currently receiving deltas (cleared when its segment closes). */
|
||||
messageId: string;
|
||||
mergeReasoning?: boolean;
|
||||
}
|
||||
|
||||
interface ActiveAssistantCursor {
|
||||
id: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
type PendingStreamEvent =
|
||||
| { kind: "delta"; text: string; turn: UIMessageTurnFields; source?: UIMessage["source"] }
|
||||
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields };
|
||||
@@ -66,98 +46,6 @@ const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
||||
// Markdown and layout work must leave room for input between visible updates.
|
||||
const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
|
||||
|
||||
/**
|
||||
* Append a reasoning chunk to the last open reasoning stream in ``prev``.
|
||||
*
|
||||
* Lookup rule: reasoning can only extend the current reasoning placeholder.
|
||||
* Once ordinary answer text has appeared, the next reasoning chunk starts a
|
||||
* fresh activity surface so streamed output stays in arrival order while the
|
||||
* final answer remains the only visible answer bubble.
|
||||
*/
|
||||
function attachReasoningChunk(
|
||||
prev: UIMessage[],
|
||||
chunk: string,
|
||||
segments?: {
|
||||
ensure: () => string;
|
||||
},
|
||||
turn: UIMessageTurnFields = {},
|
||||
): UIMessage[] {
|
||||
for (let i = prev.length - 1; i >= 0; i -= 1) {
|
||||
const candidate = prev[i];
|
||||
// A user turn is a hard boundary: reasoning after it belongs to the new
|
||||
// assistant turn, never to an earlier assistant reply.
|
||||
if (candidate.role === "user") break;
|
||||
// A trace row (e.g. Used tools) is also a phase boundary. Reasoning after
|
||||
// tools belongs to the next assistant iteration, not the assistant turn
|
||||
// that produced those tool calls.
|
||||
if (candidate.kind === "trace") break;
|
||||
if (candidate.role !== "assistant") continue;
|
||||
if (!matchesTurn(candidate, turn)) break;
|
||||
const activitySegmentId = candidate.activitySegmentId ?? segments?.ensure();
|
||||
const hasAnswer = candidate.content.length > 0;
|
||||
if (hasAnswer) break;
|
||||
// ``reasoning_end`` closes this row even though the assistant placeholder
|
||||
// stays streaming for the rest of the turn. The next reasoning stream must
|
||||
// get its own row when an intervening tool trace is delayed or unavailable.
|
||||
if (
|
||||
candidate.reasoningStreaming
|
||||
|| (candidate.isStreaming && candidate.reasoning === undefined)
|
||||
) {
|
||||
const merged: UIMessage = {
|
||||
...candidate,
|
||||
reasoning: (candidate.reasoning ?? "") + chunk,
|
||||
reasoningStreaming: true,
|
||||
...(activitySegmentId ? { activitySegmentId } : {}),
|
||||
...turn,
|
||||
};
|
||||
return [...prev.slice(0, i), merged, ...prev.slice(i + 1)];
|
||||
}
|
||||
break;
|
||||
}
|
||||
const activitySegmentId = segments?.ensure();
|
||||
return [
|
||||
...prev,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: "assistant",
|
||||
content: "",
|
||||
isStreaming: true,
|
||||
reasoning: chunk,
|
||||
reasoningStreaming: true,
|
||||
...(activitySegmentId ? { activitySegmentId } : {}),
|
||||
...turn,
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function absorbCompleteAssistantMessage(
|
||||
prev: UIMessage[],
|
||||
message: Omit<UIMessage, "id" | "role" | "createdAt">,
|
||||
): UIMessage[] {
|
||||
const last = prev[prev.length - 1];
|
||||
if (!last || !isReasoningOnlyPlaceholder(last) || !matchesTurn(last, message)) {
|
||||
return [
|
||||
...prev,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: "assistant",
|
||||
createdAt: Date.now(),
|
||||
...message,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [
|
||||
...prev.slice(0, -1),
|
||||
{
|
||||
...last,
|
||||
...message,
|
||||
isStreaming: false,
|
||||
reasoningStreaming: false,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribe to a chat by ID. Returns the in-memory message list for the chat,
|
||||
* a streaming flag, and a ``send`` function. Initial history must be seeded
|
||||
@@ -297,17 +185,13 @@ export function useNanobotStream(
|
||||
const [goalState, setGoalState] = useState<GoalStateWsPayload | undefined>(undefined);
|
||||
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
|
||||
const [streamError, setStreamError] = useState<StreamError | null>(null);
|
||||
const buffer = useRef<StreamBuffer | null>(null);
|
||||
const activeAssistantRef = useRef<ActiveAssistantCursor | null>(null);
|
||||
const closedAssistantStreamIdsRef = useRef<Set<string>>(new Set());
|
||||
const activitySegmentRef = useRef<string | null>(null);
|
||||
const fileEditSegmentRef = useRef<string | null>(null);
|
||||
const activitySegmentCounterRef = useRef(0);
|
||||
const projectionRef = useRef<ThreadProjectionState>(
|
||||
createThreadProjectionState(initialMessages),
|
||||
);
|
||||
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
||||
const streamFrameRef = useRef<number | null>(null);
|
||||
const streamTimerRef = useRef<number | null>(null);
|
||||
const lastStreamFlushRef = useRef(0);
|
||||
const suppressStreamUntilTurnEndRef = useRef(false);
|
||||
const sideChannelTurnIdsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
const dismissStreamError = useCallback(() => setStreamError(null), []);
|
||||
@@ -340,39 +224,14 @@ export function useNanobotStream(
|
||||
return turnId !== undefined && sideChannelTurnIdsRef.current.has(turnId);
|
||||
}, []);
|
||||
|
||||
const createActivitySegmentId = useCallback((activate = true) => {
|
||||
activitySegmentCounterRef.current += 1;
|
||||
const id = `activity-${activitySegmentCounterRef.current}`;
|
||||
if (activate) activitySegmentRef.current = id;
|
||||
return id;
|
||||
}, []);
|
||||
|
||||
const freshActivitySegmentId = useCallback(
|
||||
() => createActivitySegmentId(true),
|
||||
[createActivitySegmentId],
|
||||
);
|
||||
|
||||
const detachedActivitySegmentId = useCallback(
|
||||
() => createActivitySegmentId(false),
|
||||
[createActivitySegmentId],
|
||||
);
|
||||
|
||||
const ensureActivitySegmentId = useCallback(() => {
|
||||
if (activitySegmentRef.current) return activitySegmentRef.current;
|
||||
return freshActivitySegmentId();
|
||||
}, [freshActivitySegmentId]);
|
||||
|
||||
const clearActivitySegment = useCallback(() => {
|
||||
activitySegmentRef.current = null;
|
||||
fileEditSegmentRef.current = null;
|
||||
projectionRef.current = clearThreadProjectionActivity(projectionRef.current);
|
||||
}, []);
|
||||
|
||||
const closeActiveAssistantStream = useCallback(() => {
|
||||
const closedStreamId = buffer.current?.messageId ?? activeAssistantRef.current?.id;
|
||||
if (closedStreamId) closedAssistantStreamIdsRef.current.add(closedStreamId);
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
return !!closedStreamId;
|
||||
const hadActiveAssistant = projectionRef.current.activeAssistantId !== null;
|
||||
projectionRef.current = closeThreadProjectionAnswer(projectionRef.current);
|
||||
return hadActiveAssistant;
|
||||
}, []);
|
||||
|
||||
const applyStreamError = useCallback((err: StreamError) => {
|
||||
@@ -398,37 +257,36 @@ export function useNanobotStream(
|
||||
.map((message) => message.activitySegmentId)
|
||||
.filter((segmentId): segmentId is string => typeof segmentId === "string"),
|
||||
);
|
||||
if (
|
||||
activeAssistantRef.current
|
||||
&& rejectedIds.has(activeAssistantRef.current.id)
|
||||
) {
|
||||
activeAssistantRef.current = null;
|
||||
}
|
||||
if (buffer.current && rejectedIds.has(buffer.current.messageId)) {
|
||||
buffer.current = null;
|
||||
}
|
||||
for (const id of rejectedIds) closedAssistantStreamIdsRef.current.delete(id);
|
||||
if (
|
||||
activitySegmentRef.current
|
||||
&& rejectedSegments.has(activitySegmentRef.current)
|
||||
) {
|
||||
activitySegmentRef.current = null;
|
||||
}
|
||||
if (
|
||||
fileEditSegmentRef.current
|
||||
&& rejectedSegments.has(fileEditSegmentRef.current)
|
||||
) {
|
||||
fileEditSegmentRef.current = null;
|
||||
}
|
||||
return prev.flatMap((message) => {
|
||||
const projection = projectionRef.current;
|
||||
const closedAssistantIds = new Set(projection.closedAssistantIds);
|
||||
for (const id of rejectedIds) closedAssistantIds.delete(id);
|
||||
const nextMessages = prev.flatMap<UIMessage>((message) => {
|
||||
if (message.turnId !== rejectedTurnId) return [message];
|
||||
if (message.role !== "user") return [];
|
||||
return [{
|
||||
...message,
|
||||
deliveryStatus: "failed",
|
||||
deliveryStatus: "failed" as const,
|
||||
deliveryErrorKind: err.kind,
|
||||
}];
|
||||
});
|
||||
projectionRef.current = {
|
||||
...projection,
|
||||
messages: nextMessages,
|
||||
activeAssistantId: projection.activeAssistantId
|
||||
&& rejectedIds.has(projection.activeAssistantId)
|
||||
? null
|
||||
: projection.activeAssistantId,
|
||||
closedAssistantIds,
|
||||
activitySegmentId: projection.activitySegmentId
|
||||
&& rejectedSegments.has(projection.activitySegmentId)
|
||||
? null
|
||||
: projection.activitySegmentId,
|
||||
fileEditSegmentId: projection.fileEditSegmentId
|
||||
&& rejectedSegments.has(projection.fileEditSegmentId)
|
||||
? null
|
||||
: projection.fileEditSegmentId,
|
||||
};
|
||||
return nextMessages;
|
||||
});
|
||||
|
||||
const remainingStartedAt = client.getRunStartedAt(chatId);
|
||||
@@ -438,96 +296,19 @@ export function useNanobotStream(
|
||||
);
|
||||
setRunStartedAt(remainingStartedAt);
|
||||
setIsStreaming(hasRemainingRun);
|
||||
if (!hasRemainingRun) suppressStreamUntilTurnEndRef.current = false;
|
||||
if (!hasRemainingRun) {
|
||||
projectionRef.current = {
|
||||
...projectionRef.current,
|
||||
suppressUntilTurnEnd: false,
|
||||
};
|
||||
}
|
||||
}, [chatId, client]);
|
||||
|
||||
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
||||
|
||||
const resolveActiveAssistantIndex = useCallback((
|
||||
prev: UIMessage[],
|
||||
turn: UIMessageTurnFields = {},
|
||||
): number | null => {
|
||||
const cursor = activeAssistantRef.current;
|
||||
if (!cursor) return null;
|
||||
const indexed = prev[cursor.index];
|
||||
if (
|
||||
indexed?.id === cursor.id
|
||||
&& indexed.role === "assistant"
|
||||
&& indexed.kind !== "trace"
|
||||
&& indexed.isStreaming
|
||||
&& matchesTurn(indexed, turn)
|
||||
) {
|
||||
return cursor.index;
|
||||
}
|
||||
const idx = prev.findIndex((m) => m.id === cursor.id);
|
||||
if (idx === -1) {
|
||||
activeAssistantRef.current = null;
|
||||
return null;
|
||||
}
|
||||
const found = prev[idx];
|
||||
if (
|
||||
found.role !== "assistant"
|
||||
|| found.kind === "trace"
|
||||
|| !found.isStreaming
|
||||
|| !matchesTurn(found, turn)
|
||||
) {
|
||||
activeAssistantRef.current = null;
|
||||
return null;
|
||||
}
|
||||
activeAssistantRef.current = { id: cursor.id, index: idx };
|
||||
return idx;
|
||||
}, []);
|
||||
|
||||
const appendAnswerChunk = useCallback(
|
||||
(
|
||||
prev: UIMessage[],
|
||||
chunk: string,
|
||||
turn: UIMessageTurnFields = {},
|
||||
source?: UIMessage["source"],
|
||||
): UIMessage[] => {
|
||||
let next = prev;
|
||||
let targetIndex = resolveActiveAssistantIndex(next, turn);
|
||||
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findActiveAssistantPlaceholderIndex(next, turn);
|
||||
}
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn);
|
||||
}
|
||||
if (targetIndex === null) {
|
||||
const id = crypto.randomUUID();
|
||||
next = [
|
||||
...next,
|
||||
{
|
||||
id,
|
||||
role: "assistant",
|
||||
content: "",
|
||||
isStreaming: true,
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
];
|
||||
targetIndex = next.length - 1;
|
||||
}
|
||||
|
||||
const target = next[targetIndex];
|
||||
const merged: UIMessage = {
|
||||
...target,
|
||||
content: target.content + chunk,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(source ? { source } : {}),
|
||||
};
|
||||
closedAssistantStreamIdsRef.current.delete(merged.id);
|
||||
activeAssistantRef.current = { id: merged.id, index: targetIndex };
|
||||
if (buffer.current?.messageId !== merged.id) buffer.current = { messageId: merged.id };
|
||||
return replaceMessageAt(next, targetIndex, merged);
|
||||
},
|
||||
[resolveActiveAssistantIndex],
|
||||
);
|
||||
|
||||
const applyPendingStreamEvents = useCallback(
|
||||
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
|
||||
let next = prev;
|
||||
let projection = { ...projectionRef.current, messages: prev };
|
||||
for (let index = 0; index < events.length; index++) {
|
||||
const event = events[index];
|
||||
const chunks = [event.text];
|
||||
@@ -543,39 +324,33 @@ export function useNanobotStream(
|
||||
index++;
|
||||
}
|
||||
const text = chunks.join("");
|
||||
if (event.kind === "delta") {
|
||||
next = appendAnswerChunk(next, text, turn, event.source);
|
||||
} else {
|
||||
const continuationIndex = buffer.current?.mergeReasoning
|
||||
? resolveActiveAssistantIndex(next, turn)
|
||||
: null;
|
||||
if (continuationIndex !== null) {
|
||||
// Length continuation keeps one Markdown answer and its reasoning
|
||||
// together. Ordinary reasoning still opens a new activity surface.
|
||||
const target = next[continuationIndex];
|
||||
const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : "";
|
||||
next = replaceMessageAt(next, continuationIndex, {
|
||||
...target,
|
||||
reasoning: (target.reasoning ?? "") + separator + text,
|
||||
reasoningStreaming: true,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (closeActiveAssistantStream()) clearActivitySegment();
|
||||
next = attachReasoningChunk(
|
||||
next,
|
||||
text,
|
||||
{ ensure: ensureActivitySegmentId },
|
||||
turn,
|
||||
);
|
||||
}
|
||||
const projectedEvent: ThreadProjectionEvent = event.kind === "delta"
|
||||
? {
|
||||
event: "delta",
|
||||
chat_id: chatId ?? "",
|
||||
text,
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
turn_seq: turn.turnSeq,
|
||||
source: event.source,
|
||||
}
|
||||
: {
|
||||
event: "reasoning_delta",
|
||||
chat_id: chatId ?? "",
|
||||
text,
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
turn_seq: turn.turnSeq,
|
||||
};
|
||||
projection = projectThreadEvent(projection, projectedEvent, {
|
||||
createId: () => crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
});
|
||||
}
|
||||
return next;
|
||||
projectionRef.current = projection;
|
||||
return projection.messages;
|
||||
},
|
||||
[
|
||||
appendAnswerChunk, clearActivitySegment, closeActiveAssistantStream,
|
||||
ensureActivitySegmentId, resolveActiveAssistantIndex,
|
||||
],
|
||||
[chatId],
|
||||
);
|
||||
|
||||
const flushPendingStreamEvents = useCallback((options?: {
|
||||
@@ -605,65 +380,32 @@ export function useNanobotStream(
|
||||
}
|
||||
pendingStreamEventsRef.current = [];
|
||||
setMessages((prev) => {
|
||||
let next = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
|
||||
if (finalAnswerText !== undefined) {
|
||||
const targetIndex =
|
||||
resolveActiveAssistantIndex(next, turn)
|
||||
?? findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn);
|
||||
if (targetIndex !== null) {
|
||||
const target = next[targetIndex];
|
||||
const merged = {
|
||||
...target,
|
||||
content: finalAnswerText,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(source ? { source } : {}),
|
||||
};
|
||||
next = replaceMessageAt(next, targetIndex, merged);
|
||||
if (!options?.closeAnswerSegment) {
|
||||
closedAssistantStreamIdsRef.current.delete(merged.id);
|
||||
activeAssistantRef.current = { id: merged.id, index: targetIndex };
|
||||
buffer.current = { messageId: merged.id };
|
||||
}
|
||||
} else {
|
||||
const id = crypto.randomUUID();
|
||||
next = [
|
||||
...next,
|
||||
{
|
||||
id,
|
||||
role: "assistant",
|
||||
content: finalAnswerText,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(source ? { source } : {}),
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
];
|
||||
if (options?.closeAnswerSegment) {
|
||||
closedAssistantStreamIdsRef.current.add(id);
|
||||
} else {
|
||||
activeAssistantRef.current = { id, index: next.length - 1 };
|
||||
buffer.current = { messageId: id };
|
||||
}
|
||||
}
|
||||
} else if (source) {
|
||||
const targetIndex =
|
||||
resolveActiveAssistantIndex(next, turn)
|
||||
?? findStreamingAssistantIndex(next, closedAssistantStreamIdsRef.current, turn);
|
||||
if (targetIndex !== null) {
|
||||
const target = next[targetIndex];
|
||||
next = replaceMessageAt(next, targetIndex, {
|
||||
...target,
|
||||
...turn,
|
||||
source,
|
||||
});
|
||||
}
|
||||
const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
|
||||
let projection = { ...projectionRef.current, messages: nextMessages };
|
||||
if (
|
||||
finalAnswerText !== undefined
|
||||
|| source !== undefined
|
||||
|| options?.mergeReasoning
|
||||
|| options?.closeAnswerSegment
|
||||
) {
|
||||
projection = projectThreadEvent(projection, {
|
||||
event: "stream_end",
|
||||
chat_id: chatId ?? "",
|
||||
...(finalAnswerText !== undefined ? { text: finalAnswerText } : {}),
|
||||
...(source ? { source } : {}),
|
||||
...(options?.mergeReasoning ? { resuming: true, merge_next: true } : {}),
|
||||
turn_id: turn.turnId,
|
||||
turn_phase: turn.turnPhase,
|
||||
turn_seq: turn.turnSeq,
|
||||
}, {
|
||||
createId: () => crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
});
|
||||
}
|
||||
if (options?.mergeReasoning && buffer.current) buffer.current.mergeReasoning = true;
|
||||
if (options?.closeAnswerSegment) closeActiveAssistantStream();
|
||||
return next;
|
||||
projectionRef.current = projection;
|
||||
return projection.messages;
|
||||
});
|
||||
}, [applyPendingStreamEvents, closeActiveAssistantStream, resolveActiveAssistantIndex]);
|
||||
}, [applyPendingStreamEvents, chatId, closeActiveAssistantStream]);
|
||||
|
||||
const schedulePendingStreamFlush = useCallback(function schedule() {
|
||||
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
||||
@@ -735,13 +477,16 @@ export function useNanobotStream(
|
||||
return;
|
||||
}
|
||||
flushPendingStreamEvents();
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
setMessages((prev) => prev.map((message) => (
|
||||
message.isStreaming ? { ...message, isStreaming: false } : message
|
||||
)));
|
||||
setMessages((prev) => {
|
||||
const settled = prev.map((message) => (
|
||||
message.isStreaming ? { ...message, isStreaming: false } : message
|
||||
));
|
||||
projectionRef.current = resetThreadProjectionCursor(
|
||||
projectionRef.current,
|
||||
settled,
|
||||
);
|
||||
return settled;
|
||||
});
|
||||
setRunStartedAt(null);
|
||||
setIsStreaming(false);
|
||||
});
|
||||
@@ -764,13 +509,9 @@ export function useNanobotStream(
|
||||
setRetryStatus(null);
|
||||
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
|
||||
setRecoveryState(null);
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
projectionRef.current = createThreadProjectionState(initialMessages);
|
||||
clearPendingStreamWork();
|
||||
sideChannelTurnIdsRef.current.clear();
|
||||
suppressStreamUntilTurnEndRef.current = false;
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [chatId, client, clearActivitySegment, clearPendingStreamWork]);
|
||||
|
||||
@@ -778,6 +519,25 @@ export function useNanobotStream(
|
||||
if (hasPendingToolCalls) setIsStreaming(true);
|
||||
}, [hasPendingToolCalls]);
|
||||
|
||||
const applyProjectionEvent = useCallback((
|
||||
event: ThreadProjectionEvent,
|
||||
options?: { sideChannel?: boolean },
|
||||
) => {
|
||||
setMessages((prev) => {
|
||||
const projection = projectThreadEvent(
|
||||
{ ...projectionRef.current, messages: prev },
|
||||
event,
|
||||
{
|
||||
createId: () => crypto.randomUUID(),
|
||||
now: Date.now(),
|
||||
sideChannel: options?.sideChannel,
|
||||
},
|
||||
);
|
||||
projectionRef.current = projection;
|
||||
return projection.messages;
|
||||
});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chatId) return;
|
||||
|
||||
@@ -892,10 +652,9 @@ export function useNanobotStream(
|
||||
|| ev.event === "stream_end"
|
||||
) setRetryStatus(null);
|
||||
if (ev.event === "delta") {
|
||||
if (suppressStreamUntilTurnEndRef.current) return;
|
||||
if (projectionRef.current.suppressUntilTurnEnd) return;
|
||||
const chunk = typeof ev.text === "string" ? ev.text : "";
|
||||
if (!chunk) return;
|
||||
clearActivitySegment();
|
||||
setIsStreaming(true);
|
||||
pendingStreamEventsRef.current.push({
|
||||
kind: "delta",
|
||||
@@ -908,10 +667,9 @@ export function useNanobotStream(
|
||||
}
|
||||
|
||||
if (ev.event === "reasoning_delta") {
|
||||
if (suppressStreamUntilTurnEndRef.current) return;
|
||||
if (projectionRef.current.suppressUntilTurnEnd) return;
|
||||
const chunk = ev.text;
|
||||
if (!chunk) return;
|
||||
if (fileEditSegmentRef.current) clearActivitySegment();
|
||||
setIsStreaming(true);
|
||||
pendingStreamEventsRef.current.push({
|
||||
kind: "reasoning",
|
||||
@@ -932,7 +690,7 @@ export function useNanobotStream(
|
||||
turn,
|
||||
source: ev.source,
|
||||
});
|
||||
if (suppressStreamUntilTurnEndRef.current) return;
|
||||
if (projectionRef.current.suppressUntilTurnEnd) return;
|
||||
if (ev.resuming) {
|
||||
setIsStreaming(true);
|
||||
return;
|
||||
@@ -944,17 +702,11 @@ export function useNanobotStream(
|
||||
return;
|
||||
}
|
||||
|
||||
const shouldCloseAnswerBeforeEvent =
|
||||
ev.event === "file_edit"
|
||||
|| (
|
||||
ev.event === "message"
|
||||
&& (ev.kind === "tool_hint" || ev.kind === "progress")
|
||||
);
|
||||
flushPendingStreamEvents({ closeAnswerSegment: shouldCloseAnswerBeforeEvent });
|
||||
flushPendingStreamEvents();
|
||||
|
||||
if (ev.event === "reasoning_end") {
|
||||
if (suppressStreamUntilTurnEndRef.current) return;
|
||||
setMessages((prev) => closeReasoningStream(prev, Date.now()));
|
||||
if (projectionRef.current.suppressUntilTurnEnd) return;
|
||||
applyProjectionEvent(ev);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1034,33 +786,7 @@ export function useNanobotStream(
|
||||
}
|
||||
: null;
|
||||
if (modelFailure) setStreamError(modelFailure);
|
||||
const completedAt = Date.now();
|
||||
setMessages((prev) => {
|
||||
let finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
|
||||
const latencyMs =
|
||||
typeof ev.latency_ms === "number" && ev.latency_ms >= 0
|
||||
? Math.round(ev.latency_ms)
|
||||
: undefined;
|
||||
finalized = stampLastAssistantCompletion(
|
||||
finalized,
|
||||
{
|
||||
...(latencyMs !== undefined ? { latencyMs } : {}),
|
||||
...(ev.usage ? { usage: ev.usage } : {}),
|
||||
...(ev.round_usages?.length ? { roundUsages: ev.round_usages } : {}),
|
||||
...(typeof ev.context_window_tokens === "number"
|
||||
? { contextWindowTokens: ev.context_window_tokens }
|
||||
: {}),
|
||||
completedAt,
|
||||
},
|
||||
ev.turn_id,
|
||||
);
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
clearActivitySegment();
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
return finalized;
|
||||
});
|
||||
suppressStreamUntilTurnEndRef.current = false;
|
||||
applyProjectionEvent(ev);
|
||||
notifyInBackground(
|
||||
modelFailure
|
||||
? resolveModelRequestFailureCopy(modelFailure, t).body
|
||||
@@ -1134,193 +860,14 @@ export function useNanobotStream(
|
||||
}
|
||||
|
||||
if (ev.event === "message") {
|
||||
if (
|
||||
suppressStreamUntilTurnEndRef.current &&
|
||||
(ev.kind === "tool_hint" || ev.kind === "progress" || ev.kind === "reasoning")
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// Back-compat: a legacy ``kind: "reasoning"`` message (no streaming
|
||||
// partner) is treated as one complete delta + immediate end so the
|
||||
// bubble renders identically to the streaming path.
|
||||
if (ev.kind === "reasoning") {
|
||||
const line = ev.text;
|
||||
if (!line) return;
|
||||
if (fileEditSegmentRef.current) clearActivitySegment();
|
||||
setMessages((prev) => closeReasoningStream(
|
||||
attachReasoningChunk(
|
||||
prev,
|
||||
line,
|
||||
{ ensure: ensureActivitySegmentId },
|
||||
turnFieldsFromEvent(ev, "reasoning"),
|
||||
),
|
||||
Date.now(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
// Intermediate agent breadcrumbs (tool-call hints, raw progress).
|
||||
// Attach them to the last trace row if it was the last emitted item
|
||||
// so a sequence of calls collapses into one compact trace group.
|
||||
if (ev.kind === "tool_hint" || ev.kind === "progress") {
|
||||
const structuredEvents = normalizeToolProgressEvents(ev.tool_events);
|
||||
const turn = turnFieldsFromEvent(ev, "activity");
|
||||
setMessages((prev) => {
|
||||
const segmentId = ensureActivitySegmentId();
|
||||
const base = prev;
|
||||
const visibleStructuredEvents = filterCoveredFileEditToolEvents(base, structuredEvents);
|
||||
const structuredLines = toolTraceLinesFromEvents(visibleStructuredEvents);
|
||||
const lines = structuredLines.length > 0
|
||||
? structuredLines
|
||||
: structuredEvents.length > 0
|
||||
? []
|
||||
: ev.text
|
||||
? [ev.text]
|
||||
: [];
|
||||
if (lines.length === 0) return base;
|
||||
const last = base[base.length - 1];
|
||||
if (
|
||||
last
|
||||
&& last.kind === "trace"
|
||||
&& !last.isStreaming
|
||||
&& (!last.activitySegmentId || last.activitySegmentId === segmentId)
|
||||
) {
|
||||
const previousTraces = last.traces?.length
|
||||
? last.traces
|
||||
: last.content
|
||||
? [last.content]
|
||||
: [];
|
||||
const mergedEvents = visibleStructuredEvents.length > 0
|
||||
? mergeToolProgressEvents(last.toolEvents, visibleStructuredEvents)
|
||||
: last.toolEvents;
|
||||
const mergedLines = visibleStructuredEvents.length > 0
|
||||
? mergeToolProgressTraceLines(
|
||||
previousTraces,
|
||||
last.toolEvents,
|
||||
structuredLines,
|
||||
visibleStructuredEvents,
|
||||
)
|
||||
: null;
|
||||
const merged: UIMessage = {
|
||||
...last,
|
||||
traces: mergedLines ?? [...previousTraces, ...lines],
|
||||
content: mergedLines
|
||||
? mergedLines[mergedLines.length - 1]
|
||||
: lines[lines.length - 1],
|
||||
toolEvents: mergedEvents,
|
||||
activitySegmentId: last.activitySegmentId ?? segmentId,
|
||||
...turn,
|
||||
};
|
||||
return [...base.slice(0, -1), merged];
|
||||
}
|
||||
return [
|
||||
...base,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: lines[lines.length - 1],
|
||||
traces: lines,
|
||||
...(visibleStructuredEvents.length ? { toolEvents: visibleStructuredEvents } : {}),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
];
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const media = ev.media_urls?.length
|
||||
? ev.media_urls.map((m) => toMediaAttachment(m))
|
||||
: ev.media?.map((url) => toMediaAttachment({ url }));
|
||||
const hasMedia = !!media && media.length > 0;
|
||||
if (sideChannelEvent) {
|
||||
setMessages((prev) => absorbCompleteAssistantMessage(prev, {
|
||||
content: ev.text,
|
||||
...(hasMedia ? { media } : {}),
|
||||
...(ev.source ? { source: ev.source } : {}),
|
||||
...turnFieldsFromEvent(ev, "answer"),
|
||||
}));
|
||||
if (typeof ev.turn_id === "string") sideChannelTurnIdsRef.current.delete(ev.turn_id);
|
||||
return;
|
||||
}
|
||||
|
||||
// A complete (non-streamed) assistant message. If a stream was in
|
||||
// flight, drop the placeholder so we don't render the text twice.
|
||||
// ``turn_end`` is the turn boundary. ``stream_end`` only closes the
|
||||
// current text segment so a following tool/reasoning segment remains
|
||||
// part of the same live activity surface.
|
||||
clearActivitySegment();
|
||||
setMessages((prev) => {
|
||||
const activeId = buffer.current?.messageId;
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
const filtered = activeId ? prev.filter((m) => m.id !== activeId) : prev;
|
||||
const content = ev.text;
|
||||
const lat =
|
||||
typeof ev.latency_ms === "number" && ev.latency_ms >= 0
|
||||
? Math.round(ev.latency_ms)
|
||||
: undefined;
|
||||
return absorbCompleteAssistantMessage(filtered, {
|
||||
content,
|
||||
...(hasMedia ? { media } : {}),
|
||||
...(lat !== undefined ? { latencyMs: lat } : {}),
|
||||
...(ev.source ? { source: ev.source } : {}),
|
||||
...turnFieldsFromEvent(ev, "answer"),
|
||||
});
|
||||
});
|
||||
if (hasMedia) {
|
||||
suppressStreamUntilTurnEndRef.current = true;
|
||||
applyProjectionEvent(ev, { sideChannel: sideChannelEvent });
|
||||
if (sideChannelEvent && typeof ev.turn_id === "string") {
|
||||
sideChannelTurnIdsRef.current.delete(ev.turn_id);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (ev.event === "file_edit") {
|
||||
const edits = Array.isArray(ev.edits) ? ev.edits : [];
|
||||
if (edits.length === 0) return;
|
||||
const normalized = mergeFileEdits(undefined, edits);
|
||||
if (normalized.length === 0) return;
|
||||
const turn = turnFieldsFromEvent(ev, "activity");
|
||||
const opensFileEditPhase = normalized.some(
|
||||
(edit) => edit.status === "editing" || edit.phase === "start",
|
||||
);
|
||||
let eventSegmentId = fileEditSegmentRef.current;
|
||||
if (!eventSegmentId && opensFileEditPhase) {
|
||||
eventSegmentId = detachedActivitySegmentId();
|
||||
fileEditSegmentRef.current = eventSegmentId;
|
||||
}
|
||||
setMessages((prev) => {
|
||||
let segmentId = eventSegmentId;
|
||||
const base = stripCoveredFileEditToolHintsFromMessages(prev, normalized, turn);
|
||||
const targetIndex = findFileEditTraceIndex(base, segmentId, normalized);
|
||||
if (targetIndex !== null) {
|
||||
const target = base[targetIndex];
|
||||
segmentId = target.activitySegmentId ?? segmentId ?? detachedActivitySegmentId();
|
||||
if (opensFileEditPhase) fileEditSegmentRef.current = segmentId;
|
||||
const merged: UIMessage = {
|
||||
...target,
|
||||
fileEdits: mergeFileEdits(target.fileEdits, normalized),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
};
|
||||
return replaceMessageAt(base, targetIndex, merged);
|
||||
}
|
||||
segmentId = segmentId ?? detachedActivitySegmentId();
|
||||
if (opensFileEditPhase) fileEditSegmentRef.current = segmentId;
|
||||
return [
|
||||
...base,
|
||||
{
|
||||
id: crypto.randomUUID(),
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "",
|
||||
traces: [],
|
||||
fileEdits: normalized,
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
];
|
||||
});
|
||||
applyProjectionEvent(ev);
|
||||
return;
|
||||
}
|
||||
};
|
||||
@@ -1328,21 +875,17 @@ export function useNanobotStream(
|
||||
const unsub = client.onChat(chatId, handle);
|
||||
return () => {
|
||||
unsub();
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
||||
clearPendingStreamWork();
|
||||
};
|
||||
}, [
|
||||
applyProjectionEvent,
|
||||
applyStreamError,
|
||||
chatId,
|
||||
closeActiveAssistantStream,
|
||||
client,
|
||||
clearActivitySegment,
|
||||
clearPendingStreamWork,
|
||||
detachedActivitySegmentId,
|
||||
ensureActivitySegmentId,
|
||||
flushPendingStreamEvents,
|
||||
isSideChannelEvent,
|
||||
notifyInBackground,
|
||||
@@ -1376,29 +919,26 @@ export function useNanobotStream(
|
||||
if (sideChannel) sideChannelTurnIdsRef.current.add(turnId);
|
||||
const previews = hasAttachments ? images!.map((i) => i.preview) : undefined;
|
||||
setMessages((prev) => {
|
||||
let projection = { ...projectionRef.current, messages: prev };
|
||||
if ((!sideChannel && !continueActiveTurn) || finalizeActiveTurn) {
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
suppressStreamUntilTurnEndRef.current = false;
|
||||
projection = resetThreadProjectionCursor(projection, prev);
|
||||
} else if (continueActiveTurn) {
|
||||
// Guidance belongs to the active backend turn. Preserve the answer
|
||||
// cursor so its resuming stream_end can finalize the text already
|
||||
// shown before the new user row, while starting fresh activity after it.
|
||||
clearActivitySegment();
|
||||
projection = clearThreadProjectionActivity(projection);
|
||||
}
|
||||
const base = finalizeActiveTurn ? finalizeStreamedTurn(prev) : prev;
|
||||
return [
|
||||
const next: UIMessage[] = [
|
||||
...base,
|
||||
{
|
||||
id: userMessageId,
|
||||
role: "user",
|
||||
role: "user" as const,
|
||||
content: outboundContent,
|
||||
turnId,
|
||||
turnPhase: "user",
|
||||
turnSeq: 0,
|
||||
deliveryStatus: "sending",
|
||||
deliveryStatus: "sending" as const,
|
||||
createdAt: Date.now(),
|
||||
...(previews ? { media: previews } : {}),
|
||||
...(options?.cliApps?.length ? { cliApps: options.cliApps } : {}),
|
||||
@@ -1406,8 +946,10 @@ export function useNanobotStream(
|
||||
...(options?.sessionMentions?.length
|
||||
? { sessionMentions: options.sessionMentions }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
projectionRef.current = { ...projection, messages: next };
|
||||
return next;
|
||||
});
|
||||
if (!sideChannel) setIsStreaming(true);
|
||||
const wireMedia = hasAttachments ? images!.map((i) => i.media) : undefined;
|
||||
@@ -1432,13 +974,10 @@ export function useNanobotStream(
|
||||
setIsStreaming(false);
|
||||
setRetryStatus(null);
|
||||
setMessages((prev) => {
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
return prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
|
||||
const settled = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
|
||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current, settled);
|
||||
return settled;
|
||||
});
|
||||
suppressStreamUntilTurnEndRef.current = false;
|
||||
setRunStartedAt(null);
|
||||
client.finishRunLocally(chatId);
|
||||
client.sendMessage(chatId, "/stop");
|
||||
@@ -1446,11 +985,7 @@ export function useNanobotStream(
|
||||
|
||||
const reconcileTurnComplete = useCallback(() => {
|
||||
clearPendingStreamWork();
|
||||
buffer.current = null;
|
||||
activeAssistantRef.current = null;
|
||||
closedAssistantStreamIdsRef.current.clear();
|
||||
clearActivitySegment();
|
||||
suppressStreamUntilTurnEndRef.current = false;
|
||||
projectionRef.current = resetThreadProjectionCursor(projectionRef.current);
|
||||
setRunStartedAt(null);
|
||||
setRetryStatus(null);
|
||||
setIsStreaming(false);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@/lib/api";
|
||||
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||
import { deriveTitle } from "@/lib/format";
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import type {
|
||||
ChatSummary,
|
||||
@@ -45,6 +46,30 @@ function persistedMessagesToUi(messages: UIMessage[]): UIMessage[] {
|
||||
}));
|
||||
}
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean {
|
||||
return (
|
||||
a.role === b.role
|
||||
@@ -166,7 +191,8 @@ function cachedHistoryState(
|
||||
body: WebuiThreadPersistedPayload,
|
||||
version: number,
|
||||
): SessionHistoryState {
|
||||
const messages = persistedMessagesToUi(body.messages ?? []);
|
||||
const projected = projectPersistedThread(body);
|
||||
const messages = projected.messages;
|
||||
return {
|
||||
key,
|
||||
messages,
|
||||
@@ -175,9 +201,7 @@ function cachedHistoryState(
|
||||
error: null,
|
||||
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
|
||||
completedTurnIds: completedTurnIdsFromThread(body),
|
||||
forkBoundaryMessageCount: typeof body.fork_boundary_message_count === "number"
|
||||
? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length))
|
||||
: null,
|
||||
forkBoundaryMessageCount: projected.forkBoundaryMessageCount,
|
||||
beforeCursor: body.page?.before_cursor ?? null,
|
||||
hasMoreBefore: body.page?.has_more_before === true,
|
||||
userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0),
|
||||
@@ -458,11 +482,10 @@ export function useSessionHistory(key: string | null): {
|
||||
historyVersionRef.current += 1;
|
||||
const responseVersion = historyVersionRef.current;
|
||||
const completedTurnIds = completedTurnIdsFromThread(body);
|
||||
const ui = persistedMessagesToUi(body?.messages ?? []);
|
||||
const projected = projectPersistedThread(body);
|
||||
const ui = projected.messages;
|
||||
const hasPending = hasPendingToolCallsFromThread(body, ui);
|
||||
const forkBoundary = typeof body?.fork_boundary_message_count === "number"
|
||||
? Math.max(0, Math.min(body.fork_boundary_message_count, ui.length))
|
||||
: null;
|
||||
const forkBoundary = projected.forkBoundaryMessageCount;
|
||||
setState((prev) => {
|
||||
const merged = prev.key === key
|
||||
? mergeLatestHistory(prev.messages, ui, prev.lineage === 0)
|
||||
@@ -571,7 +594,8 @@ export function useSessionHistory(key: string | null): {
|
||||
});
|
||||
setState((prev) => {
|
||||
if (!matchesRequest(prev)) return prev;
|
||||
if (!body?.messages?.length) {
|
||||
const projected = projectPersistedThread(body);
|
||||
if (!body || !projected.messages.length) {
|
||||
return {
|
||||
...prev,
|
||||
loadingOlder: false,
|
||||
@@ -579,10 +603,8 @@ export function useSessionHistory(key: string | null): {
|
||||
beforeCursor: null,
|
||||
};
|
||||
}
|
||||
const older = persistedMessagesToUi(body.messages);
|
||||
const olderBoundary = typeof body.fork_boundary_message_count === "number"
|
||||
? Math.max(0, Math.min(body.fork_boundary_message_count, older.length))
|
||||
: null;
|
||||
const older = projected.messages;
|
||||
const olderBoundary = projected.forkBoundaryMessageCount;
|
||||
const shiftedBoundary = prev.forkBoundaryMessageCount === null
|
||||
? null
|
||||
: prev.forkBoundaryMessageCount + older.length;
|
||||
|
||||
+131
-1
@@ -38,6 +38,7 @@ import type {
|
||||
SlashCommand,
|
||||
SlashCommandLifecycle,
|
||||
TranscriptionSettingsUpdate,
|
||||
ThreadProjectionEvent,
|
||||
WebSearchSettingsUpdate,
|
||||
WorkspacesPayload,
|
||||
WebuiThreadPersistedPayload,
|
||||
@@ -231,6 +232,134 @@ export interface FetchWebuiThreadOptions {
|
||||
cached?: WebuiThreadPersistedPayload;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isRecordArray(value: unknown): value is Array<Record<string, unknown>> {
|
||||
return Array.isArray(value) && value.every(isRecord);
|
||||
}
|
||||
|
||||
function isProjectionMedia(value: unknown): boolean {
|
||||
return isRecord(value)
|
||||
&& typeof value.url === "string"
|
||||
&& (value.name === undefined || typeof value.name === "string")
|
||||
&& (value.kind === undefined || ["image", "video", "file"].includes(String(value.kind)));
|
||||
}
|
||||
|
||||
function hasStringField(value: Record<string, unknown>, field: string): boolean {
|
||||
return typeof value[field] === "string";
|
||||
}
|
||||
|
||||
function isProjectionFileEdit(value: unknown): boolean {
|
||||
return isRecord(value)
|
||||
&& hasStringField(value, "call_id")
|
||||
&& hasStringField(value, "tool")
|
||||
&& hasStringField(value, "path")
|
||||
&& typeof value.added === "number"
|
||||
&& typeof value.deleted === "number"
|
||||
&& ["editing", "done", "error"].includes(String(value.status));
|
||||
}
|
||||
|
||||
function hasValidProjectionMetadata(value: Record<string, unknown>): boolean {
|
||||
return (
|
||||
(value.projection_id === undefined || typeof value.projection_id === "string")
|
||||
&& (value.created_at_ms === undefined || typeof value.created_at_ms === "number")
|
||||
&& (value.turn_id === undefined || typeof value.turn_id === "string")
|
||||
&& (value.turn_phase === undefined || [
|
||||
"user", "reasoning", "activity", "answer", "complete",
|
||||
].includes(String(value.turn_phase)))
|
||||
&& (value.turn_seq === undefined || typeof value.turn_seq === "number")
|
||||
&& (
|
||||
value.source === undefined
|
||||
|| (
|
||||
isRecord(value.source)
|
||||
&& typeof value.source.kind === "string"
|
||||
&& (value.source.label === undefined || typeof value.source.label === "string")
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
||||
if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {
|
||||
throw new Error("Invalid WebUI thread event");
|
||||
}
|
||||
if (!hasValidProjectionMetadata(value)) {
|
||||
throw new Error("Invalid WebUI thread event metadata");
|
||||
}
|
||||
switch (value.event) {
|
||||
case "user_message":
|
||||
if (typeof value.text !== "string" || typeof value.starts_turn !== "boolean") break;
|
||||
if (value.media_urls !== undefined && (
|
||||
!Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia)
|
||||
)) break;
|
||||
if (value.cli_apps !== undefined && (
|
||||
!isRecordArray(value.cli_apps) || !value.cli_apps.every((item) => hasStringField(item, "name"))
|
||||
)) break;
|
||||
if (value.mcp_presets !== undefined && (
|
||||
!isRecordArray(value.mcp_presets)
|
||||
|| !value.mcp_presets.every((item) => hasStringField(item, "name"))
|
||||
)) break;
|
||||
if (value.session_mentions !== undefined && (
|
||||
!isRecordArray(value.session_mentions)
|
||||
|| !value.session_mentions.every((item) => (
|
||||
hasStringField(item, "name")
|
||||
&& hasStringField(item, "session_key")
|
||||
&& hasStringField(item, "title")
|
||||
))
|
||||
)) break;
|
||||
if (value.provenance !== undefined && (
|
||||
!isRecord(value.provenance)
|
||||
|| !isRecord(value.provenance.session_message)
|
||||
|| !hasStringField(value.provenance.session_message, "message_id")
|
||||
|| !isRecord(value.provenance.session_message.session)
|
||||
)) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "message":
|
||||
if (typeof value.text !== "string") break;
|
||||
if (value.tool_events !== undefined && !isRecordArray(value.tool_events)) break;
|
||||
if (value.media_urls !== undefined && (
|
||||
!Array.isArray(value.media_urls) || !value.media_urls.every(isProjectionMedia)
|
||||
)) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "file_edit":
|
||||
if (!Array.isArray(value.edits) || !value.edits.every(isProjectionFileEdit)) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "delta":
|
||||
case "reasoning_delta":
|
||||
if (typeof value.text !== "string") break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "stream_end":
|
||||
case "reasoning_end":
|
||||
if (value.text !== undefined && typeof value.text !== "string") break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "context_compaction":
|
||||
if (typeof value.compaction_id !== "string" || typeof value.phase !== "string") break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "turn_end":
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
}
|
||||
throw new Error(`Invalid WebUI thread projection event: ${value.event}`);
|
||||
}
|
||||
|
||||
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)) {
|
||||
throw new Error("Invalid WebUI thread events");
|
||||
}
|
||||
const events = value.events?.map(parseThreadProjectionEvent);
|
||||
return {
|
||||
...value,
|
||||
...(events ? { events } : {}),
|
||||
} as unknown as WebuiThreadPersistedPayload;
|
||||
}
|
||||
|
||||
export async function fetchWebuiThread(
|
||||
token: string,
|
||||
key: string,
|
||||
@@ -243,6 +372,7 @@ 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}`;
|
||||
@@ -257,7 +387,7 @@ export async function fetchWebuiThread(
|
||||
if (res.status === 304 && options?.cached) return options.cached;
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
|
||||
return (await res.json()) as WebuiThreadPersistedPayload;
|
||||
return parseWebuiThreadPayload(await res.json());
|
||||
}
|
||||
|
||||
export async function fetchWebuiThreadTraceDetail(
|
||||
|
||||
@@ -1,21 +1,43 @@
|
||||
import { toolTraceLinesFromEvents } from "@/lib/tool-traces";
|
||||
import { toMediaAttachment } from "@/lib/media";
|
||||
import {
|
||||
mergeToolProgressEvents,
|
||||
mergeToolProgressTraceLines,
|
||||
normalizeToolProgressEvents,
|
||||
toolTraceLinesFromEvents,
|
||||
} from "@/lib/tool-traces";
|
||||
import type {
|
||||
ThreadProjectionEvent,
|
||||
ToolProgressEvent,
|
||||
UIFileEdit,
|
||||
UIMessage,
|
||||
UITurnPhase,
|
||||
} from "@/lib/types";
|
||||
|
||||
export type { ThreadProjectionEvent } from "@/lib/types";
|
||||
|
||||
export type UIMessageTurnFields = Pick<UIMessage, "turnId" | "turnPhase" | "turnSeq">;
|
||||
|
||||
const FILE_EDIT_TOOL_NAMES = new Set(["write_file", "edit_file", "apply_patch"]);
|
||||
|
||||
/**
|
||||
* PR3 projection seam: replay can share these folds once GatewayContext exposes
|
||||
* an ordered canonical-event sequence and a monotonic per-thread revision.
|
||||
* Snapshot acceptance and revision comparison stay outside this projection;
|
||||
* until then, history continues to consume server-projected UIMessage snapshots.
|
||||
*/
|
||||
export interface ThreadProjectionState {
|
||||
messages: UIMessage[];
|
||||
activeAssistantId: string | null;
|
||||
closedAssistantIds: Set<string>;
|
||||
mergeReasoning: boolean;
|
||||
activitySegmentId: string | null;
|
||||
fileEditSegmentId: string | null;
|
||||
activitySegmentCounter: number;
|
||||
suppressUntilTurnEnd: boolean;
|
||||
closedTurnIds: Set<string>;
|
||||
turnAliases: Map<string, string>;
|
||||
}
|
||||
|
||||
export interface ThreadProjectionOptions {
|
||||
createId: () => string;
|
||||
now: number;
|
||||
persisted?: boolean;
|
||||
sideChannel?: boolean;
|
||||
}
|
||||
|
||||
export function turnFieldsFromEvent(
|
||||
ev: { turn_id?: string; turn_phase?: UITurnPhase; turn_seq?: number },
|
||||
@@ -88,12 +110,13 @@ export function replaceMessageAt(
|
||||
|
||||
/** Close the active reasoning stream segment. ``now`` is supplied by the caller
|
||||
* so the projection remains deterministic for replay and fixture tests. */
|
||||
export function closeReasoningStream(prev: UIMessage[], now: number): UIMessage[] {
|
||||
export function closeReasoningStream(prev: UIMessage[], now?: number): UIMessage[] {
|
||||
for (let i = prev.length - 1; i >= 0; i -= 1) {
|
||||
const candidate = prev[i];
|
||||
if (!candidate.reasoningStreaming) continue;
|
||||
const latencyMs =
|
||||
candidate.latencyMs === undefined
|
||||
now !== undefined
|
||||
&& candidate.latencyMs === undefined
|
||||
&& Number.isFinite(candidate.createdAt)
|
||||
&& candidate.createdAt > 1_000_000_000_000
|
||||
? Math.max(0, Math.round(now - candidate.createdAt))
|
||||
@@ -343,3 +366,644 @@ export function finalizeStreamedTurn(
|
||||
: m,
|
||||
);
|
||||
}
|
||||
|
||||
export function createThreadProjectionState(
|
||||
messages: UIMessage[] = [],
|
||||
): ThreadProjectionState {
|
||||
return {
|
||||
messages,
|
||||
activeAssistantId: null,
|
||||
closedAssistantIds: new Set(),
|
||||
mergeReasoning: false,
|
||||
activitySegmentId: null,
|
||||
fileEditSegmentId: null,
|
||||
activitySegmentCounter: 0,
|
||||
suppressUntilTurnEnd: false,
|
||||
closedTurnIds: new Set(),
|
||||
turnAliases: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
export function resetThreadProjectionCursor(
|
||||
state: ThreadProjectionState,
|
||||
messages: UIMessage[] = state.messages,
|
||||
): ThreadProjectionState {
|
||||
return {
|
||||
...createThreadProjectionState(messages),
|
||||
activitySegmentCounter: state.activitySegmentCounter,
|
||||
closedTurnIds: new Set(state.closedTurnIds),
|
||||
turnAliases: new Map(state.turnAliases),
|
||||
};
|
||||
}
|
||||
|
||||
export function clearThreadProjectionActivity(
|
||||
state: ThreadProjectionState,
|
||||
): ThreadProjectionState {
|
||||
return {
|
||||
...state,
|
||||
activitySegmentId: null,
|
||||
fileEditSegmentId: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function closeThreadProjectionAnswer(
|
||||
state: ThreadProjectionState,
|
||||
): ThreadProjectionState {
|
||||
if (!state.activeAssistantId) return state;
|
||||
const closedAssistantIds = new Set(state.closedAssistantIds);
|
||||
closedAssistantIds.add(state.activeAssistantId);
|
||||
return {
|
||||
...state,
|
||||
activeAssistantId: null,
|
||||
closedAssistantIds,
|
||||
mergeReasoning: false,
|
||||
};
|
||||
}
|
||||
|
||||
function projectionCreatedAt(event: ThreadProjectionEvent, options: ThreadProjectionOptions): number {
|
||||
return typeof event.created_at_ms === "number" && Number.isFinite(event.created_at_ms)
|
||||
? event.created_at_ms
|
||||
: options.now;
|
||||
}
|
||||
|
||||
function projectionMessageId(
|
||||
event: ThreadProjectionEvent,
|
||||
options: ThreadProjectionOptions,
|
||||
): string {
|
||||
return typeof event.projection_id === "string" && event.projection_id.length > 0
|
||||
? event.projection_id
|
||||
: options.createId();
|
||||
}
|
||||
|
||||
function turnFieldsForProjection(
|
||||
state: ThreadProjectionState,
|
||||
event: ThreadProjectionEvent,
|
||||
fallbackPhase?: UITurnPhase,
|
||||
): UIMessageTurnFields {
|
||||
const fields = turnFieldsFromEvent(event, fallbackPhase);
|
||||
const rawTurnId = fields.turnId;
|
||||
if (!rawTurnId || !state.closedTurnIds.has(rawTurnId)) return fields;
|
||||
let alias = state.turnAliases.get(rawTurnId);
|
||||
if (!alias) {
|
||||
const suffix = event.projection_id || event.created_at_ms || state.messages.length;
|
||||
alias = `${rawTurnId}:replay:${suffix}`;
|
||||
state.turnAliases.set(rawTurnId, alias);
|
||||
}
|
||||
return { ...fields, turnId: alias };
|
||||
}
|
||||
|
||||
function ensureProjectionActivitySegment(state: ThreadProjectionState): string {
|
||||
if (state.activitySegmentId) return state.activitySegmentId;
|
||||
state.activitySegmentCounter += 1;
|
||||
state.activitySegmentId = `activity-${state.activitySegmentCounter}`;
|
||||
return state.activitySegmentId;
|
||||
}
|
||||
|
||||
function detachedProjectionActivitySegment(state: ThreadProjectionState): string {
|
||||
state.activitySegmentCounter += 1;
|
||||
return `activity-${state.activitySegmentCounter}`;
|
||||
}
|
||||
|
||||
function activeAssistantIndex(
|
||||
state: ThreadProjectionState,
|
||||
turn: UIMessageTurnFields,
|
||||
): number | null {
|
||||
if (!state.activeAssistantId) return null;
|
||||
const index = state.messages.findIndex((message) => message.id === state.activeAssistantId);
|
||||
if (index < 0) {
|
||||
state.activeAssistantId = null;
|
||||
state.mergeReasoning = false;
|
||||
return null;
|
||||
}
|
||||
const message = state.messages[index];
|
||||
if (
|
||||
message.role !== "assistant"
|
||||
|| message.kind === "trace"
|
||||
|| !message.isStreaming
|
||||
|| !matchesTurn(message, turn)
|
||||
) {
|
||||
state.activeAssistantId = null;
|
||||
state.mergeReasoning = false;
|
||||
return null;
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
function appendAnswerText(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "delta" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
const turn = turnFieldsForProjection(state, event, "answer");
|
||||
let targetIndex = activeAssistantIndex(state, turn);
|
||||
if (targetIndex === null) targetIndex = findActiveAssistantPlaceholderIndex(state.messages, turn);
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn);
|
||||
}
|
||||
if (targetIndex === null) {
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id,
|
||||
role: "assistant",
|
||||
content: "",
|
||||
isStreaming: true,
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
targetIndex = state.messages.length - 1;
|
||||
}
|
||||
const target = state.messages[targetIndex];
|
||||
const merged: UIMessage = {
|
||||
...target,
|
||||
content: target.content + event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
};
|
||||
state.closedAssistantIds.delete(merged.id);
|
||||
state.activeAssistantId = merged.id;
|
||||
state.mergeReasoning = false;
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, merged);
|
||||
}
|
||||
|
||||
function attachProjectedReasoning(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "reasoning_delta" | "reasoning_end" }>,
|
||||
text: string,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
const turn = turnFieldsForProjection(state, event, "reasoning");
|
||||
const activeAssistantBeforeContinuation = state.activeAssistantId;
|
||||
const continuationIndex = state.mergeReasoning
|
||||
? activeAssistantIndex(state, turn)
|
||||
: null;
|
||||
if (continuationIndex !== null) {
|
||||
const target = state.messages[continuationIndex];
|
||||
const separator = target.reasoning && !target.reasoningStreaming ? "\n\n" : "";
|
||||
state.messages = replaceMessageAt(state.messages, continuationIndex, {
|
||||
...target,
|
||||
reasoning: (target.reasoning ?? "") + separator + text,
|
||||
reasoningStreaming: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.fileEditSegmentId || activeAssistantBeforeContinuation) {
|
||||
if (activeAssistantBeforeContinuation && !state.activeAssistantId) {
|
||||
state.closedAssistantIds.add(activeAssistantBeforeContinuation);
|
||||
}
|
||||
const closed = closeThreadProjectionAnswer(state);
|
||||
Object.assign(state, clearThreadProjectionActivity(closed));
|
||||
}
|
||||
for (let index = state.messages.length - 1; index >= 0; index -= 1) {
|
||||
const candidate = state.messages[index];
|
||||
if (candidate.role === "user" || candidate.kind === "trace") break;
|
||||
if (candidate.role !== "assistant") continue;
|
||||
if (!matchesTurn(candidate, turn) || candidate.content.length > 0) break;
|
||||
if (candidate.reasoningStreaming || (candidate.isStreaming && candidate.reasoning === undefined)) {
|
||||
const activitySegmentId = candidate.activitySegmentId
|
||||
?? ensureProjectionActivitySegment(state);
|
||||
state.messages = replaceMessageAt(state.messages, index, {
|
||||
...candidate,
|
||||
reasoning: (candidate.reasoning ?? "") + text,
|
||||
reasoningStreaming: true,
|
||||
activitySegmentId,
|
||||
...turn,
|
||||
});
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const activitySegmentId = ensureProjectionActivitySegment(state);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id: projectionMessageId(event, options),
|
||||
role: "assistant",
|
||||
content: "",
|
||||
isStreaming: true,
|
||||
reasoning: text,
|
||||
reasoningStreaming: true,
|
||||
activitySegmentId,
|
||||
...turn,
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function absorbProjectedAssistantMessage(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "message" }>,
|
||||
message: Omit<UIMessage, "id" | "role" | "createdAt">,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
const last = state.messages[state.messages.length - 1];
|
||||
if (last && isReasoningOnlyPlaceholder(last) && matchesTurn(last, message)) {
|
||||
state.messages = [
|
||||
...state.messages.slice(0, -1),
|
||||
{
|
||||
...last,
|
||||
...message,
|
||||
isStreaming: false,
|
||||
reasoningStreaming: false,
|
||||
},
|
||||
];
|
||||
return;
|
||||
}
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id: projectionMessageId(event, options),
|
||||
role: "assistant",
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
...message,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function projectToolActivity(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "message" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
const structuredEvents = normalizeToolProgressEvents(event.tool_events);
|
||||
const visibleEvents = filterCoveredFileEditToolEvents(state.messages, structuredEvents);
|
||||
const structuredLines = toolTraceLinesFromEvents(visibleEvents);
|
||||
const lines = structuredLines.length > 0
|
||||
? structuredLines
|
||||
: structuredEvents.length > 0
|
||||
? []
|
||||
: event.text
|
||||
? [event.text]
|
||||
: [];
|
||||
if (lines.length === 0) return;
|
||||
|
||||
const segmentId = ensureProjectionActivitySegment(state);
|
||||
const turn = turnFieldsForProjection(state, event, "activity");
|
||||
const last = state.messages[state.messages.length - 1];
|
||||
if (
|
||||
last
|
||||
&& last.kind === "trace"
|
||||
&& !last.isStreaming
|
||||
&& (!last.activitySegmentId || last.activitySegmentId === segmentId)
|
||||
) {
|
||||
const previousTraces = last.traces?.length
|
||||
? last.traces
|
||||
: last.content
|
||||
? [last.content]
|
||||
: [];
|
||||
const mergedEvents = visibleEvents.length > 0
|
||||
? mergeToolProgressEvents(last.toolEvents, visibleEvents)
|
||||
: last.toolEvents;
|
||||
const mergedLines = visibleEvents.length > 0
|
||||
? mergeToolProgressTraceLines(
|
||||
previousTraces,
|
||||
last.toolEvents,
|
||||
structuredLines,
|
||||
visibleEvents,
|
||||
)
|
||||
: null;
|
||||
state.messages = [
|
||||
...state.messages.slice(0, -1),
|
||||
{
|
||||
...last,
|
||||
traces: mergedLines ?? [...previousTraces, ...lines],
|
||||
content: mergedLines
|
||||
? mergedLines[mergedLines.length - 1]
|
||||
: lines[lines.length - 1],
|
||||
toolEvents: mergedEvents,
|
||||
activitySegmentId: last.activitySegmentId ?? segmentId,
|
||||
...turn,
|
||||
},
|
||||
];
|
||||
return;
|
||||
}
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id: projectionMessageId(event, options),
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: lines[lines.length - 1],
|
||||
traces: lines,
|
||||
...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function projectFileEdits(
|
||||
state: ThreadProjectionState,
|
||||
event: Extract<ThreadProjectionEvent, { event: "file_edit" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
const normalized = mergeFileEdits(undefined, event.edits);
|
||||
if (normalized.length === 0) return;
|
||||
const turn = turnFieldsForProjection(state, event, "activity");
|
||||
const opensPhase = normalized.some(
|
||||
(edit) => edit.status === "editing" || edit.phase === "start",
|
||||
);
|
||||
let segmentId = state.fileEditSegmentId;
|
||||
if (!segmentId && opensPhase) {
|
||||
segmentId = detachedProjectionActivitySegment(state);
|
||||
state.fileEditSegmentId = segmentId;
|
||||
}
|
||||
const base = stripCoveredFileEditToolHintsFromMessages(state.messages, normalized, turn);
|
||||
const targetIndex = findFileEditTraceIndex(base, segmentId, normalized);
|
||||
if (targetIndex !== null) {
|
||||
const target = base[targetIndex];
|
||||
segmentId = target.activitySegmentId ?? segmentId ?? detachedProjectionActivitySegment(state);
|
||||
if (opensPhase) state.fileEditSegmentId = segmentId;
|
||||
state.messages = replaceMessageAt(base, targetIndex, {
|
||||
...target,
|
||||
fileEdits: mergeFileEdits(target.fileEdits, normalized),
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
});
|
||||
return;
|
||||
}
|
||||
segmentId = segmentId ?? detachedProjectionActivitySegment(state);
|
||||
if (opensPhase) state.fileEditSegmentId = segmentId;
|
||||
state.messages = [
|
||||
...base,
|
||||
{
|
||||
id: projectionMessageId(event, options),
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "",
|
||||
traces: [],
|
||||
fileEdits: normalized,
|
||||
activitySegmentId: segmentId,
|
||||
...turn,
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/** Canonical UI-message reducer shared by WebSocket delivery and transcript replay. */
|
||||
export function projectThreadEvent(
|
||||
previous: ThreadProjectionState,
|
||||
event: ThreadProjectionEvent,
|
||||
options: ThreadProjectionOptions,
|
||||
): ThreadProjectionState {
|
||||
const state: ThreadProjectionState = {
|
||||
...previous,
|
||||
closedAssistantIds: new Set(previous.closedAssistantIds),
|
||||
closedTurnIds: new Set(previous.closedTurnIds),
|
||||
turnAliases: new Map(previous.turnAliases),
|
||||
};
|
||||
|
||||
if (event.event === "user_message") {
|
||||
if (event.provenance?.session_message) {
|
||||
const messageId = event.provenance.session_message.message_id?.trim();
|
||||
if (!messageId || state.messages.some(
|
||||
(message) => message.sessionMessage?.message_id === messageId,
|
||||
)) return state;
|
||||
} else if (event.turn_id && state.messages.some(
|
||||
(message) => message.role === "user" && message.turnId === event.turn_id,
|
||||
)) return state;
|
||||
if (state.activeAssistantId) {
|
||||
state.messages = state.messages.map((message) => (
|
||||
message.id === state.activeAssistantId ? { ...message, isStreaming: false } : message
|
||||
));
|
||||
}
|
||||
state.messages = closeReasoningStream(
|
||||
state.messages,
|
||||
options.persisted ? undefined : options.now,
|
||||
);
|
||||
Object.assign(state, resetThreadProjectionCursor(state, state.messages));
|
||||
const media = event.media_urls?.map((item) => toMediaAttachment(item));
|
||||
const turn = turnFieldsForProjection(state, event, "user");
|
||||
const row: UIMessage = {
|
||||
id: projectionMessageId(event, options),
|
||||
role: "user",
|
||||
content: event.text,
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
...turn,
|
||||
...(!options.persisted ? { deliveryStatus: "accepted" as const } : {}),
|
||||
...(media?.length ? { media } : {}),
|
||||
...(event.cli_apps?.length ? { cliApps: event.cli_apps } : {}),
|
||||
...(event.mcp_presets?.length ? { mcpPresets: event.mcp_presets } : {}),
|
||||
...(event.session_mentions?.length ? { sessionMentions: event.session_mentions } : {}),
|
||||
...(event.provenance?.session_message
|
||||
? { sessionMessage: event.provenance.session_message }
|
||||
: {}),
|
||||
};
|
||||
if (media?.length && media.every((item) => item.kind === "image")) {
|
||||
row.images = media.map(({ url, name }) => ({ url, name }));
|
||||
}
|
||||
state.messages = [...state.messages, row];
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "delta") {
|
||||
if (!state.suppressUntilTurnEnd && event.text) {
|
||||
state.activitySegmentId = null;
|
||||
state.fileEditSegmentId = null;
|
||||
appendAnswerText(state, event, options);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "stream_end") {
|
||||
if (state.suppressUntilTurnEnd) return state;
|
||||
const turn = turnFieldsForProjection(state, event, "answer");
|
||||
const mergeNext = event.resuming === true && event.merge_next === true;
|
||||
let targetIndex = activeAssistantIndex(state, turn);
|
||||
if (targetIndex === null) {
|
||||
targetIndex = findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn);
|
||||
}
|
||||
if (typeof event.text === "string") {
|
||||
if (targetIndex === null) {
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
{
|
||||
id,
|
||||
role: "assistant",
|
||||
content: event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
},
|
||||
];
|
||||
targetIndex = state.messages.length - 1;
|
||||
} else {
|
||||
const target = state.messages[targetIndex];
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, {
|
||||
...target,
|
||||
content: event.text,
|
||||
isStreaming: true,
|
||||
...turn,
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
});
|
||||
}
|
||||
} else if (event.source && targetIndex !== null) {
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, {
|
||||
...state.messages[targetIndex],
|
||||
...turn,
|
||||
source: event.source,
|
||||
});
|
||||
}
|
||||
if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id;
|
||||
state.mergeReasoning = mergeNext && state.activeAssistantId !== null;
|
||||
if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "reasoning_delta") {
|
||||
if (!state.suppressUntilTurnEnd && event.text) {
|
||||
attachProjectedReasoning(state, event, event.text, options);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "reasoning_end") {
|
||||
if (state.suppressUntilTurnEnd) return state;
|
||||
if (event.text) attachProjectedReasoning(state, event, event.text, options);
|
||||
state.messages = closeReasoningStream(
|
||||
state.messages,
|
||||
options.persisted ? undefined : options.now,
|
||||
);
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "context_compaction") {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
const id = `compaction-${event.compaction_id}`;
|
||||
const existing = state.messages.findIndex((message) => message.id === id);
|
||||
const message: UIMessage = {
|
||||
id,
|
||||
role: "assistant",
|
||||
content: "",
|
||||
kind: "compaction",
|
||||
createdAt: projectionCreatedAt(event, options),
|
||||
compaction: {
|
||||
id: event.compaction_id,
|
||||
phase: event.phase,
|
||||
...(!options.persisted ? { announce: true } : {}),
|
||||
},
|
||||
...turnFieldsForProjection(state, event, "activity"),
|
||||
};
|
||||
if (existing < 0) state.messages = [...state.messages, message];
|
||||
else state.messages = replaceMessageAt(state.messages, existing, {
|
||||
...message,
|
||||
createdAt: state.messages[existing].createdAt,
|
||||
});
|
||||
state.activitySegmentId = null;
|
||||
state.fileEditSegmentId = null;
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "message") {
|
||||
if (
|
||||
state.suppressUntilTurnEnd
|
||||
&& (event.kind === "tool_hint" || event.kind === "progress" || event.kind === "reasoning")
|
||||
) return state;
|
||||
if (event.kind === "reasoning") {
|
||||
if (event.text) {
|
||||
attachProjectedReasoning(state, {
|
||||
...event,
|
||||
event: "reasoning_delta",
|
||||
}, event.text, options);
|
||||
state.messages = closeReasoningStream(
|
||||
state.messages,
|
||||
options.persisted ? undefined : options.now,
|
||||
);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
if (event.kind === "tool_hint" || event.kind === "progress") {
|
||||
projectToolActivity(state, event, options);
|
||||
return state;
|
||||
}
|
||||
|
||||
const media = event.media_urls?.map((item) => toMediaAttachment(item))
|
||||
?? event.media?.map((url) => toMediaAttachment({ url }));
|
||||
const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0
|
||||
? Math.round(event.latency_ms)
|
||||
: undefined;
|
||||
const projected = {
|
||||
content: event.text,
|
||||
...(media?.length ? { media } : {}),
|
||||
...(latencyMs !== undefined ? { latencyMs } : {}),
|
||||
...(event.source ? { source: event.source } : {}),
|
||||
...turnFieldsForProjection(state, event, "answer"),
|
||||
};
|
||||
if (options.sideChannel) {
|
||||
absorbProjectedAssistantMessage(state, event, projected, options);
|
||||
return state;
|
||||
}
|
||||
const activeId = state.activeAssistantId;
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
if (activeId) state.messages = state.messages.filter((message) => message.id !== activeId);
|
||||
absorbProjectedAssistantMessage(state, event, projected, options);
|
||||
state.activitySegmentId = null;
|
||||
state.fileEditSegmentId = null;
|
||||
if (media?.length) state.suppressUntilTurnEnd = true;
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "file_edit") {
|
||||
projectFileEdits(state, event, options);
|
||||
return state;
|
||||
}
|
||||
|
||||
const turn = turnFieldsForProjection(state, event, "complete");
|
||||
state.suppressUntilTurnEnd = false;
|
||||
state.activitySegmentId = null;
|
||||
state.fileEditSegmentId = null;
|
||||
state.messages = finalizeStreamedTurn(state.messages);
|
||||
const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0
|
||||
? Math.round(event.latency_ms)
|
||||
: undefined;
|
||||
state.messages = stampLastAssistantCompletion(
|
||||
state.messages,
|
||||
{
|
||||
...(latencyMs !== undefined ? { latencyMs } : {}),
|
||||
...(event.usage ? { usage: event.usage } : {}),
|
||||
...(event.round_usages?.length ? { roundUsages: event.round_usages } : {}),
|
||||
...(typeof event.context_window_tokens === "number"
|
||||
? { contextWindowTokens: event.context_window_tokens }
|
||||
: {}),
|
||||
...(!options.persisted ? { completedAt: options.now } : {}),
|
||||
},
|
||||
turn.turnId,
|
||||
);
|
||||
state.activeAssistantId = null;
|
||||
state.closedAssistantIds.clear();
|
||||
state.mergeReasoning = false;
|
||||
if (event.turn_id) {
|
||||
if (state.turnAliases.has(event.turn_id)) state.turnAliases.delete(event.turn_id);
|
||||
else state.closedTurnIds.add(event.turn_id);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] {
|
||||
let state = createThreadProjectionState();
|
||||
const fallbackNow = Date.now();
|
||||
events.forEach((event, index) => {
|
||||
state = projectThreadEvent(state, event, {
|
||||
createId: () => `history-${index}`,
|
||||
now: typeof event.created_at_ms === "number"
|
||||
? event.created_at_ms
|
||||
: fallbackNow + index,
|
||||
persisted: true,
|
||||
});
|
||||
});
|
||||
return state.messages.map((row) => {
|
||||
const message = { ...row };
|
||||
delete message.isStreaming;
|
||||
delete message.reasoningStreaming;
|
||||
return message;
|
||||
});
|
||||
}
|
||||
+28
-1
@@ -1424,6 +1424,8 @@ export type InboundEvent =
|
||||
event: "reasoning_end";
|
||||
chat_id: string;
|
||||
stream_id?: string;
|
||||
/** Legacy persisted transcripts may carry the final reasoning text here. */
|
||||
text?: string;
|
||||
} & InboundTurnMetadata)
|
||||
| {
|
||||
event: "runtime_model_updated";
|
||||
@@ -1503,6 +1505,25 @@ export type InboundEvent =
|
||||
turn_id?: string;
|
||||
};
|
||||
|
||||
type ThreadProjectionEventName =
|
||||
| "user_message"
|
||||
| "message"
|
||||
| "file_edit"
|
||||
| "delta"
|
||||
| "stream_end"
|
||||
| "reasoning_delta"
|
||||
| "reasoning_end"
|
||||
| "context_compaction"
|
||||
| "turn_end";
|
||||
|
||||
export type ThreadProjectionEvent = Extract<
|
||||
InboundEvent,
|
||||
{ event: ThreadProjectionEventName }
|
||||
> & {
|
||||
projection_id?: string;
|
||||
created_at_ms?: number;
|
||||
};
|
||||
|
||||
/** Base64-encoded file attached to an outbound ``message`` envelope.
|
||||
*
|
||||
* ``data_url`` must use a server-whitelisted image, video, or document MIME
|
||||
@@ -1542,6 +1563,7 @@ interface WebuiThreadPagePayload {
|
||||
loaded_message_count?: number;
|
||||
total_known_message_count?: number;
|
||||
user_message_offset?: number;
|
||||
loaded_event_count?: number;
|
||||
}
|
||||
|
||||
export interface WebuiThreadPersistedPayload {
|
||||
@@ -1550,8 +1572,13 @@ export interface WebuiThreadPersistedPayload {
|
||||
savedAt?: string;
|
||||
/** Cheap server revision used for application-managed conditional revalidation. */
|
||||
revision?: string;
|
||||
messages: UIMessage[];
|
||||
/** 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;
|
||||
fork_boundary_event_index?: number;
|
||||
/** Turn ids backed by an explicit persisted ``turn_end`` event. */
|
||||
completed_turn_ids?: string[];
|
||||
has_pending_tool_calls?: boolean;
|
||||
|
||||
@@ -81,7 +81,12 @@ describe("webui API helpers", () => {
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ deleted: true, key: "websocket:chat-1", messages: [] }),
|
||||
json: async () => ({
|
||||
schemaVersion: 3,
|
||||
deleted: true,
|
||||
key: "websocket:chat-1",
|
||||
messages: [],
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -95,7 +100,7 @@ describe("webui API helpers", () => {
|
||||
await fetchWebuiThread("tok", "websocket:chat-1");
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread",
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread?projection=events",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok" },
|
||||
credentials: "same-origin",
|
||||
@@ -111,7 +116,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&projection=events",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok" },
|
||||
credentials: "same-origin",
|
||||
@@ -136,7 +141,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?projection=events",
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
Authorization: "Bearer tok",
|
||||
@@ -147,6 +152,22 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects malformed canonical thread events at the HTTP boundary", async () => {
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
schemaVersion: 3,
|
||||
projection: "events",
|
||||
events: [{ event: "file_edit", chat_id: "chat-1", edits: [{ tool: "edit_file" }] }],
|
||||
}),
|
||||
} as Response);
|
||||
|
||||
await expect(fetchWebuiThread("tok", "websocket:chat-1")).rejects.toThrow(
|
||||
"Invalid WebUI thread projection event: file_edit",
|
||||
);
|
||||
});
|
||||
|
||||
it("fetches deferred trace details with encoded session and ref", async () => {
|
||||
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectThreadEvents } from "@/lib/thread-event-projection";
|
||||
import type { ThreadProjectionEvent, UIMessage } from "@/lib/types";
|
||||
import projectionFixture from "./fixtures/live-replay-event-projection.json";
|
||||
|
||||
interface ProjectionFixtureCase {
|
||||
name: string;
|
||||
transcript: Array<Record<string, unknown>>;
|
||||
expected: Array<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
const cases = (
|
||||
projectionFixture as unknown as { cases: ProjectionFixtureCase[] }
|
||||
).cases;
|
||||
|
||||
const SEMANTIC_MESSAGE_FIELDS = [
|
||||
"role",
|
||||
"content",
|
||||
"kind",
|
||||
"traces",
|
||||
"toolEvents",
|
||||
"fileEdits",
|
||||
"images",
|
||||
"media",
|
||||
"cliApps",
|
||||
"mcpPresets",
|
||||
"sessionMentions",
|
||||
"reasoning",
|
||||
"latencyMs",
|
||||
"source",
|
||||
"turnId",
|
||||
"turnPhase",
|
||||
"turnSeq",
|
||||
] as const satisfies ReadonlyArray<keyof UIMessage>;
|
||||
|
||||
function fixtureEvents(records: Array<Record<string, unknown>>): ThreadProjectionEvent[] {
|
||||
return records.flatMap((record, index) => {
|
||||
if (record.event === "user") {
|
||||
return [{
|
||||
...record,
|
||||
event: "user_message" as const,
|
||||
starts_turn: true,
|
||||
projection_id: `fixture-${index}`,
|
||||
} as unknown as ThreadProjectionEvent];
|
||||
}
|
||||
return [{
|
||||
...record,
|
||||
projection_id: `fixture-${index}`,
|
||||
} as unknown as ThreadProjectionEvent];
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeProjection(messages: UIMessage[]): Array<Record<string, unknown>> {
|
||||
const segmentAliases = new Map<string, string>();
|
||||
return messages.map((message) => {
|
||||
const row: Record<string, unknown> = {};
|
||||
for (const field of SEMANTIC_MESSAGE_FIELDS) {
|
||||
const value = message[field];
|
||||
if (value !== undefined && value !== null) row[field] = value;
|
||||
}
|
||||
if (message.activitySegmentId) {
|
||||
let alias = segmentAliases.get(message.activitySegmentId);
|
||||
if (!alias) {
|
||||
alias = `segment-${segmentAliases.size + 1}`;
|
||||
segmentAliases.set(message.activitySegmentId, alias);
|
||||
}
|
||||
row.activitySegmentId = alias;
|
||||
}
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
describe("canonical thread event projection", () => {
|
||||
it.each(cases)("projects persisted $name events", (fixtureCase) => {
|
||||
const messages = projectThreadEvents(fixtureEvents(fixtureCase.transcript));
|
||||
expect(normalizeProjection(messages)).toEqual(fixtureCase.expected);
|
||||
});
|
||||
});
|
||||
@@ -3539,7 +3539,7 @@ describe("useNanobotStream", () => {
|
||||
|
||||
});
|
||||
|
||||
describe("live/replay projection before canonical-event revision migration", () => {
|
||||
describe("live canonical event projection", () => {
|
||||
it.each(PROJECTION_FIXTURE_CASES)("matches the shared $name fixture", (fixtureCase) => {
|
||||
// Keep client-only elapsed-time estimates out of the transport contract.
|
||||
const clock = vi.spyOn(Date, "now").mockReturnValue(0);
|
||||
|
||||
@@ -568,6 +568,75 @@ describe("useSessions", () => {
|
||||
expect(result.current.messages[2]!.content).toBe("summary");
|
||||
});
|
||||
|
||||
it("projects canonical transcript events with the live event reducer", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
projection: "events",
|
||||
events: [
|
||||
{
|
||||
event: "user_message",
|
||||
chat_id: "chat-event-history",
|
||||
text: "explain",
|
||||
starts_turn: true,
|
||||
projection_id: "history-user",
|
||||
turn_id: "turn-history",
|
||||
turn_phase: "user",
|
||||
turn_seq: 1,
|
||||
},
|
||||
{
|
||||
event: "reasoning_delta",
|
||||
chat_id: "chat-event-history",
|
||||
text: "thinking",
|
||||
projection_id: "history-reasoning",
|
||||
turn_id: "turn-history",
|
||||
turn_phase: "reasoning",
|
||||
turn_seq: 2,
|
||||
},
|
||||
{
|
||||
event: "reasoning_end",
|
||||
chat_id: "chat-event-history",
|
||||
projection_id: "history-reasoning-end",
|
||||
turn_id: "turn-history",
|
||||
turn_phase: "reasoning",
|
||||
turn_seq: 3,
|
||||
},
|
||||
{
|
||||
event: "delta",
|
||||
chat_id: "chat-event-history",
|
||||
text: "answer",
|
||||
projection_id: "history-answer",
|
||||
turn_id: "turn-history",
|
||||
turn_phase: "answer",
|
||||
turn_seq: 4,
|
||||
},
|
||||
{
|
||||
event: "turn_end",
|
||||
chat_id: "chat-event-history",
|
||||
projection_id: "history-end",
|
||||
latency_ms: 25,
|
||||
turn_id: "turn-history",
|
||||
turn_phase: "complete",
|
||||
turn_seq: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSessionHistory("websocket:chat-event-history"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
|
||||
expect(result.current.messages).toHaveLength(2);
|
||||
expect(result.current.messages[1]).toMatchObject({
|
||||
role: "assistant",
|
||||
content: "answer",
|
||||
reasoning: "thinking",
|
||||
latencyMs: 25,
|
||||
turnId: "turn-history",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a cached transcript immediately while revalidating it", async () => {
|
||||
const cached = {
|
||||
schemaVersion: 3,
|
||||
|
||||
Reference in new issue
Block a user