fix(webui): preserve oversized turn history with record pagination (#6586)
This commit is contained in:
1 parent
5c1083df7f
commit
3c61bcfdf0
34 files changed
+3466
-380
No files matched your search
@@ -385,6 +385,10 @@ function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet
|
||||
case "stream_end":
|
||||
case "reasoning_end":
|
||||
if (value.text !== undefined && typeof value.text !== "string") break;
|
||||
if (value.text_from_seq !== undefined && (
|
||||
!Number.isSafeInteger(value.text_from_seq) || Number(value.text_from_seq) < 0
|
||||
|| !Number.isSafeInteger(value.turn_seq) || Number(value.text_from_seq) > Number(value.turn_seq)
|
||||
)) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "context_compaction":
|
||||
if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break;
|
||||
@@ -421,6 +425,21 @@ export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPay
|
||||
if (value.projection !== "events" || !Array.isArray(value.events)) {
|
||||
throw new Error("Invalid WebUI thread events");
|
||||
}
|
||||
if (isRecord(value.page) && value.page.history_generation != null
|
||||
&& (typeof value.page.history_generation !== "string" || !value.page.history_generation)) {
|
||||
throw new Error("Invalid WebUI thread history generation");
|
||||
}
|
||||
if (isRecord(value.page) && value.page.record_range !== undefined) {
|
||||
const range = value.page.record_range;
|
||||
if (!isRecord(range) || !Number.isSafeInteger(range.turn) || Number(range.turn) < 0
|
||||
|| !Number.isSafeInteger(range.start) || Number(range.start) < 0
|
||||
|| !Number.isSafeInteger(range.end) || Number(range.end) <= Number(range.start)) {
|
||||
throw new Error("Invalid WebUI thread record range");
|
||||
}
|
||||
}
|
||||
if (isRecord(value.page) && value.page.recovered_answers !== undefined && typeof value.page.recovered_answers !== "boolean") {
|
||||
throw new Error("Invalid WebUI thread answer recovery");
|
||||
}
|
||||
const graphs = new Map<string, ContextGraph>();
|
||||
if (value.context_graphs !== undefined) {
|
||||
if (!isRecord(value.context_graphs)) throw new Error("Invalid context graph dictionary");
|
||||
|
||||
@@ -28,16 +28,16 @@ export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): {
|
||||
completedTurnIds: string[];
|
||||
snapshot: CanonicalRunSnapshot;
|
||||
} {
|
||||
const messages = projectThreadEvents(body.events);
|
||||
const suppliedCompletionIds = Array.isArray(body.completed_turn_ids) ? body.completed_turn_ids : null;
|
||||
// The older protocol-1 host may omit active_turn_id. Its explicit pending
|
||||
// flag still confirms idle; a missing flag cannot establish completion.
|
||||
const snapshot = canonicalRunSnapshot(
|
||||
messages,
|
||||
body.has_pending_tool_calls !== false,
|
||||
typeof body.active_turn_id === "string" ? body.active_turn_id : null,
|
||||
suppliedCompletionIds !== null,
|
||||
);
|
||||
// User identities and explicit completion are wire facts, not rendered messages.
|
||||
const snapshot: CanonicalRunSnapshot = {
|
||||
observedTurnIds: Array.from(new Set(body.events.flatMap((event) => (
|
||||
event.event === "user_message" && event.turn_id ? [event.turn_id] : []
|
||||
)))),
|
||||
hasPendingToolCalls: body.has_pending_tool_calls !== false,
|
||||
activeTurnId: typeof body.active_turn_id === "string" ? body.active_turn_id : null,
|
||||
completionIdsProvided: suppliedCompletionIds !== null,
|
||||
};
|
||||
const completedTurnIds = suppliedCompletionIds?.filter(
|
||||
(turnId) => typeof turnId === "string" && turnId.length > 0,
|
||||
) ?? [];
|
||||
@@ -47,7 +47,7 @@ export function persistedCanonicalRunState(body: WebuiThreadPersistedPayload): {
|
||||
completedTurnIds.push(...body.events.flatMap((event) => (
|
||||
event.event === "turn_end" && event.turn_id ? [event.turn_id] : []
|
||||
)));
|
||||
completedTurnIds.push(...completedAssistantTurnIds(messages));
|
||||
completedTurnIds.push(...completedAssistantTurnIds(projectThreadEvents(body.events)));
|
||||
}
|
||||
return { completedTurnIds: Array.from(new Set(completedTurnIds)), snapshot };
|
||||
}
|
||||
@@ -17,7 +17,7 @@ interface ChatRecord {
|
||||
effectiveStartedAt: number | null;
|
||||
anonymousActive: boolean;
|
||||
turns: Map<string, TurnRecord>;
|
||||
/** Closed turns permit late inputs, messages, completions and idle. */
|
||||
/** Lifecycle tombstones permit late content without reopening ownership. */
|
||||
closed: Set<string>;
|
||||
/** Canonical fences discard every frame with a matching top-level turn id. */
|
||||
fenced: Set<string>;
|
||||
@@ -45,6 +45,7 @@ export type RunObservation = Readonly<{
|
||||
chatId: string;
|
||||
turnId: string | null;
|
||||
systemCommand?: boolean;
|
||||
lifecycleSignal?: boolean;
|
||||
}> & (
|
||||
| { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } }
|
||||
| { kind: "status"; activity: "running" | "idle"; startedAt?: number }
|
||||
@@ -57,14 +58,14 @@ type Command =
|
||||
| ({ kind: "written" | "reject" } & TurnRef)
|
||||
| { kind: "transport-lost" }
|
||||
| { kind: "local-stop" | "forget"; chatId: string }
|
||||
| { kind: "fence"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "fence" | "settle-fragment-lifecycle"; chatId: string; completedTurnIds: readonly string[] }
|
||||
| { kind: "restore-pending"; chatId: string; generation: number; turnId: string | null };
|
||||
|
||||
export type RunEffect =
|
||||
| { kind: "run-status"; chatId: string; state: RunState }
|
||||
| { kind: "completion"; chatId: string }
|
||||
| ({ kind: "discard-send" } & TurnRef)
|
||||
| { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] };
|
||||
| { kind: "prune-inbound" | "prune-lifecycle-inbound"; chatId: string; turnIds: readonly string[] };
|
||||
|
||||
interface ObservationResult {
|
||||
forward: "normal" | "without-owner" | "drop";
|
||||
@@ -209,6 +210,9 @@ export class ClientRunLedger {
|
||||
case "fence":
|
||||
this.fence(command.chatId, command.completedTurnIds, effects);
|
||||
break;
|
||||
case "settle-fragment-lifecycle":
|
||||
this.settleFragmentLifecycle(command.chatId, command.completedTurnIds, effects);
|
||||
break;
|
||||
default: {
|
||||
const unhandled: never = command;
|
||||
throw new Error(`Unexpected run command: ${unhandled}`);
|
||||
@@ -228,12 +232,15 @@ export class ClientRunLedger {
|
||||
let chat = this.chats.get(chatId);
|
||||
const effects: RunEffect[] = [];
|
||||
if (turnId !== null && chat?.fenced.has(turnId)) return { forward: "drop", effects };
|
||||
if (
|
||||
turnId && chat?.closed.has(turnId)
|
||||
&& observation.kind !== "admission" && observation.kind !== "input"
|
||||
&& observation.kind !== "message" && observation.kind !== "completed"
|
||||
&& !(observation.kind === "status" && observation.activity === "idle")
|
||||
) return { forward: "drop", effects };
|
||||
if (turnId && chat?.closed.has(turnId)) {
|
||||
if (observation.lifecycleSignal || observation.kind === "recovery" || observation.kind === "rejection"
|
||||
|| (observation.kind === "status" && observation.activity === "running")) {
|
||||
return { forward: "drop", effects };
|
||||
}
|
||||
// Content delivery is independent of lifecycle ownership. In particular,
|
||||
// delta/stream_end may arrive after an explicit canonical completion.
|
||||
if (observation.kind === "activity" || observation.kind === "progress") return { forward: "normal", effects };
|
||||
}
|
||||
|
||||
let forward: ObservationResult["forward"] = "normal";
|
||||
if ((observation.kind === "admission" || observation.kind === "input") && observation.owner?.turnId) {
|
||||
@@ -456,7 +463,21 @@ export class ClientRunLedger {
|
||||
|
||||
private rememberClosed(chat: ChatRecord, turnId: string): void {
|
||||
chat.closed.add(turnId);
|
||||
this.trimTerminalSet(chat.closed);
|
||||
this.trimTerminalSet(chat.closed, chat.latestTurnId);
|
||||
}
|
||||
|
||||
private settleFragmentLifecycle(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
for (const turnId of turnIds) {
|
||||
if (!turnId) continue;
|
||||
const chat = this.ensureChat(chatId);
|
||||
this.rememberClosed(chat, turnId);
|
||||
this.settle(chatId, turnId, effects);
|
||||
if (chat.latestTurnId === turnId) {
|
||||
chat.anonymousActive = false;
|
||||
chat.effectiveStartedAt = null;
|
||||
}
|
||||
}
|
||||
effects.push({ kind: "prune-lifecycle-inbound", chatId, turnIds });
|
||||
}
|
||||
|
||||
private fence(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||
@@ -470,10 +491,10 @@ export class ClientRunLedger {
|
||||
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||
}
|
||||
|
||||
private trimTerminalSet(turnIds: Set<string>): void {
|
||||
private trimTerminalSet(turnIds: Set<string>, retainedTurnId?: string | null): void {
|
||||
for (const oldest of turnIds) {
|
||||
if (turnIds.size <= COMPLETED_TURN_FENCE_MAX) break;
|
||||
turnIds.delete(oldest);
|
||||
if (oldest !== retainedTurnId) turnIds.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -200,7 +200,7 @@ function runObservation(event: InboundEvent): RunObservation | null {
|
||||
case "stream_end":
|
||||
return { ...base, kind: "activity" };
|
||||
case "retry_status":
|
||||
return { ...base, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" };
|
||||
return { ...base, lifecycleSignal: true, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" };
|
||||
case "recovery_state":
|
||||
// Supersession resolves the old recovery, not the new user turn that caused it.
|
||||
return event.status === "recovered" && event.reason === "superseded"
|
||||
@@ -435,6 +435,16 @@ export class NanobotClient {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Settle explicit fragment completions without claiming coverage of live content. */
|
||||
settleFragmentRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
||||
this.applyRunEffects(this.runs.transition({ kind: "settle-fragment-lifecycle", chatId, completedTurnIds }));
|
||||
}
|
||||
|
||||
/** Whether a mounted transcript owns delivery for this chat. */
|
||||
hasTranscript(chatId: string): boolean {
|
||||
return this.transcriptHandlers.has(chatId);
|
||||
}
|
||||
|
||||
/** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */
|
||||
getGoalState(chatId: string): GoalStateWsPayload | undefined {
|
||||
return this.goalStateByChatId.get(chatId);
|
||||
@@ -469,7 +479,8 @@ export class NanobotClient {
|
||||
&& frame.turn_id === effect.turnId
|
||||
));
|
||||
break;
|
||||
case "prune-inbound": {
|
||||
case "prune-inbound":
|
||||
case "prune-lifecycle-inbound": {
|
||||
const pending = this.pendingInboundByChat.get(effect.chatId);
|
||||
if (!pending) break;
|
||||
const turnIds = new Set(effect.turnIds);
|
||||
@@ -477,6 +488,8 @@ export class NanobotClient {
|
||||
!("turn_id" in event)
|
||||
|| typeof event.turn_id !== "string"
|
||||
|| !turnIds.has(event.turn_id)
|
||||
|| (effect.kind === "prune-lifecycle-inbound"
|
||||
&& event.event !== "goal_status" && event.event !== "recovery_state" && event.event !== "retry_status")
|
||||
));
|
||||
if (remaining.length > 0) this.pendingInboundByChat.set(effect.chatId, remaining);
|
||||
else this.pendingInboundByChat.delete(effect.chatId);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { toMediaAttachment } from "@/lib/media";
|
||||
import { ThreadProjectionIndex } from "./thread-projection-index";
|
||||
import {
|
||||
mergeToolProgressEvents,
|
||||
mergeToolProgressTraceLines,
|
||||
@@ -51,6 +52,9 @@ export interface ThreadProjectionOptions {
|
||||
/** First sequence of a coalesced batch; event.turn_seq is its last contribution. */
|
||||
startSeq?: number;
|
||||
effects?: ThreadProjectionEffects;
|
||||
index?: ThreadProjectionIndex;
|
||||
/** Scratch replay owns these collections and does not expose intermediate states. */
|
||||
mutableCollections?: boolean;
|
||||
}
|
||||
|
||||
export function turnFieldsFromEvent(
|
||||
@@ -90,7 +94,18 @@ function findStreamingAssistantIndex(
|
||||
closedStreamIds: ReadonlySet<string>,
|
||||
turn: UIMessageTurnFields = {},
|
||||
streamId?: string,
|
||||
lookup?: ThreadProjectionIndex,
|
||||
): number | null {
|
||||
if (streamId && lookup) {
|
||||
let target: number | null = null;
|
||||
for (const index of lookup.answer("")) {
|
||||
const row = prev[index];
|
||||
if (index > lookup.lastUser && row.kind !== "trace" && row.isStreaming
|
||||
&& !closedStreamIds.has(row.id) && matchesTurn(row, turn)
|
||||
&& (target === null || index > target)) target = index;
|
||||
}
|
||||
return target;
|
||||
}
|
||||
for (let i = prev.length - 1; i >= 0; i -= 1) {
|
||||
const m = prev[i];
|
||||
if (m.kind === "trace") continue;
|
||||
@@ -440,9 +455,10 @@ export function clearThreadProjectionActivity(
|
||||
|
||||
export function closeThreadProjectionAnswer(
|
||||
state: ThreadProjectionState,
|
||||
mutableCollections = false,
|
||||
): ThreadProjectionState {
|
||||
if (!state.activeAssistantId) return state;
|
||||
const closedAssistantIds = new Set(state.closedAssistantIds);
|
||||
const closedAssistantIds = mutableCollections ? state.closedAssistantIds : new Set(state.closedAssistantIds);
|
||||
closedAssistantIds.add(state.activeAssistantId);
|
||||
return {
|
||||
...state,
|
||||
@@ -479,7 +495,7 @@ function turnFieldsForProjection(
|
||||
if (!alias) {
|
||||
const suffix = event.projection_id || event.created_at_ms || state.messages.length;
|
||||
alias = `${rawTurnId}:replay:${suffix}`;
|
||||
state.turnAliases.set(rawTurnId, alias);
|
||||
state.turnAliases = new Map(state.turnAliases).set(rawTurnId, alias);
|
||||
}
|
||||
return { ...fields, turnId: alias };
|
||||
}
|
||||
@@ -499,9 +515,11 @@ function detachedProjectionActivitySegment(state: ThreadProjectionState): string
|
||||
function activeAssistantIndex(
|
||||
state: ThreadProjectionState,
|
||||
turn: UIMessageTurnFields,
|
||||
lookup?: ThreadProjectionIndex,
|
||||
): number | null {
|
||||
if (!state.activeAssistantId) return null;
|
||||
const index = state.messages.findIndex((message) => message.id === state.activeAssistantId);
|
||||
const index = lookup ? lookup.position(state.activeAssistantId) ?? -1
|
||||
: state.messages.findIndex((message) => message.id === state.activeAssistantId);
|
||||
if (index < 0) {
|
||||
state.activeAssistantId = null;
|
||||
state.mergeReasoning = false;
|
||||
@@ -529,14 +547,21 @@ function answerStreamIndex(
|
||||
state: ThreadProjectionState,
|
||||
turn: UIMessageTurnFields,
|
||||
streamId?: string,
|
||||
lookup?: ThreadProjectionIndex,
|
||||
): number | null {
|
||||
if (streamId) {
|
||||
if (streamId && lookup) {
|
||||
let target: number | null = null;
|
||||
for (const index of lookup.answer(streamId)) {
|
||||
if (matchesTurn(state.messages[index], turn) && (target === null || index > target)) target = index;
|
||||
}
|
||||
if (target !== null) return target;
|
||||
} else if (streamId) {
|
||||
for (let index = state.messages.length - 1; index >= 0; index--) {
|
||||
const message = state.messages[index];
|
||||
if (message.role === "assistant" && message.streamId === streamId && matchesTurn(message, turn)) return index;
|
||||
}
|
||||
}
|
||||
const active = activeAssistantIndex(state, turn);
|
||||
const active = activeAssistantIndex(state, turn, lookup);
|
||||
if (active !== null && (!streamId || !state.messages[active].streamId || state.messages[active].streamId === streamId)) {
|
||||
return active;
|
||||
}
|
||||
@@ -544,7 +569,7 @@ function answerStreamIndex(
|
||||
if (placeholder !== null && (!streamId || !state.messages[placeholder].streamId || state.messages[placeholder].streamId === streamId)) {
|
||||
return placeholder;
|
||||
}
|
||||
return findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn, streamId);
|
||||
return findStreamingAssistantIndex(state.messages, state.closedAssistantIds, turn, streamId, lookup);
|
||||
}
|
||||
|
||||
function appendAnswerText(
|
||||
@@ -555,10 +580,10 @@ function appendAnswerText(
|
||||
const turn = turnFieldsForProjection(state, event, "answer");
|
||||
const streamKey = answerStreamKey(turn, event.stream_id);
|
||||
if (streamKey && state.closedAnswerStreamIds.has(streamKey)) return;
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id);
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id, options.index);
|
||||
if (targetIndex !== null && state.closedAssistantIds.has(state.messages[targetIndex].id)) targetIndex = null;
|
||||
if (targetIndex === null) {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
const id = projectionMessageId(event, options);
|
||||
state.messages = [
|
||||
...state.messages,
|
||||
@@ -583,7 +608,10 @@ function appendAnswerText(
|
||||
...(event.response_sources !== undefined ? { responseSources: event.response_sources } : {}),
|
||||
...(event.response_input_ids !== undefined ? { responseInputIds: event.response_input_ids } : {}),
|
||||
};
|
||||
state.closedAssistantIds.delete(merged.id);
|
||||
if (state.closedAssistantIds.has(merged.id)) {
|
||||
state.closedAssistantIds = new Set(state.closedAssistantIds);
|
||||
state.closedAssistantIds.delete(merged.id);
|
||||
}
|
||||
state.activeAssistantId = merged.id;
|
||||
state.mergeReasoning = false;
|
||||
state.messages = replaceMessageAt(state.messages, targetIndex, merged);
|
||||
@@ -633,9 +661,9 @@ function attachProjectedReasoning(
|
||||
|
||||
if (state.fileEditSegmentId || activeAssistantBeforeContinuation) {
|
||||
if (activeAssistantBeforeContinuation && !state.activeAssistantId) {
|
||||
state.closedAssistantIds.add(activeAssistantBeforeContinuation);
|
||||
state.closedAssistantIds = new Set(state.closedAssistantIds).add(activeAssistantBeforeContinuation);
|
||||
}
|
||||
const closed = closeThreadProjectionAnswer(state);
|
||||
const closed = closeThreadProjectionAnswer(state, options.mutableCollections);
|
||||
Object.assign(state, clearThreadProjectionActivity(closed));
|
||||
}
|
||||
for (let index = state.messages.length - 1; index >= 0; index -= 1) {
|
||||
@@ -721,7 +749,7 @@ function projectToolActivity(
|
||||
event: Extract<ThreadProjectionEvent, { event: "message" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
const structuredEvents = normalizeToolProgressEvents(event.tool_events);
|
||||
const visibleEvents = filterCoveredFileEditToolEvents(state.messages, structuredEvents);
|
||||
const structuredLines = toolTraceLinesFromEvents(visibleEvents);
|
||||
@@ -802,7 +830,7 @@ function projectFileEdits(
|
||||
event: Extract<ThreadProjectionEvent, { event: "file_edit" }>,
|
||||
options: ThreadProjectionOptions,
|
||||
): void {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
const normalized = mergeFileEdits(undefined, event.edits);
|
||||
if (normalized.length === 0) return;
|
||||
const turn = turnFieldsForProjection(state, event, "activity");
|
||||
@@ -854,13 +882,20 @@ export function projectThreadEvent(
|
||||
event: ThreadProjectionEvent,
|
||||
options: ThreadProjectionOptions,
|
||||
): ThreadProjectionState {
|
||||
const state: ThreadProjectionState = {
|
||||
...previous,
|
||||
closedAssistantIds: new Set(previous.closedAssistantIds),
|
||||
closedAnswerStreamIds: new Set(previous.closedAnswerStreamIds),
|
||||
closedTurnIds: new Set(previous.closedTurnIds),
|
||||
turnAliases: new Map(previous.turnAliases),
|
||||
};
|
||||
if (!options.index) return reduceThreadEvent(previous, event, options);
|
||||
options.index.sync(previous.messages);
|
||||
const effects = options.effects ?? { bodyWrites: new Set<string>(), consumed: new Set<string>() };
|
||||
const state = reduceThreadEvent(previous, event, { ...options, effects });
|
||||
options.index?.sync(state.messages, effects);
|
||||
return state;
|
||||
}
|
||||
|
||||
function reduceThreadEvent(
|
||||
previous: ThreadProjectionState,
|
||||
event: ThreadProjectionEvent,
|
||||
options: ThreadProjectionOptions,
|
||||
): ThreadProjectionState {
|
||||
const state: ThreadProjectionState = { ...previous };
|
||||
|
||||
if (event.event === "model_request") {
|
||||
if (!event.turn_id || state.closedTurnIds.has(event.turn_id)) return state;
|
||||
@@ -973,14 +1008,24 @@ export function projectThreadEvent(
|
||||
const mergeNext = event.resuming === true && event.merge_next === true;
|
||||
const streamKey = answerStreamKey(turn, event.stream_id);
|
||||
const wireClosed = streamKey !== undefined && state.closedAnswerStreamIds.has(streamKey);
|
||||
if (streamKey && !mergeNext) state.closedAnswerStreamIds.add(streamKey);
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id);
|
||||
if (streamKey && !mergeNext && !wireClosed) {
|
||||
if (!options.mutableCollections) state.closedAnswerStreamIds = new Set(state.closedAnswerStreamIds);
|
||||
state.closedAnswerStreamIds.add(streamKey);
|
||||
}
|
||||
let targetIndex = answerStreamIndex(state, turn, event.stream_id, options.index);
|
||||
let text = event.text;
|
||||
// Older completed records can span a hosted tool. Their snapshots already
|
||||
// use rewritten text; live streams now end before the tool starts.
|
||||
if (options.persisted && event.stream_id && typeof text === "string") {
|
||||
let offset = 0;
|
||||
for (let index = 0; index < (targetIndex ?? state.messages.length); index++) {
|
||||
const positions = options.index?.answer(event.stream_id);
|
||||
if (positions) {
|
||||
for (const index of positions) {
|
||||
if (index < (targetIndex ?? state.messages.length) && matchesTurn(state.messages[index], turn)) {
|
||||
offset += state.messages[index].content.length;
|
||||
}
|
||||
}
|
||||
} else for (let index = 0; index < (targetIndex ?? state.messages.length); index++) {
|
||||
const row = state.messages[index];
|
||||
if (row.streamId === event.stream_id && matchesTurn(row, turn)) offset += row.content.length;
|
||||
}
|
||||
@@ -1026,7 +1071,7 @@ export function projectThreadEvent(
|
||||
if (wasClosed || wireClosed) return state;
|
||||
if (targetIndex !== null) state.activeAssistantId = state.messages[targetIndex].id;
|
||||
state.mergeReasoning = mergeNext && state.activeAssistantId !== null;
|
||||
if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
if (!mergeNext) Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -1050,7 +1095,7 @@ export function projectThreadEvent(
|
||||
}
|
||||
|
||||
if (event.event === "context_compaction") {
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
if (event.phase === "succeeded") {
|
||||
state.modelRequests = new Map(Array.from(state.modelRequests, ([turn, request]) =>
|
||||
[turn, { ...request, contextSnapshots: [] }]));
|
||||
@@ -1135,7 +1180,7 @@ export function projectThreadEvent(
|
||||
return state;
|
||||
}
|
||||
const activeId = state.activeAssistantId;
|
||||
Object.assign(state, closeThreadProjectionAnswer(state));
|
||||
Object.assign(state, closeThreadProjectionAnswer(state, options.mutableCollections));
|
||||
if (activeId) {
|
||||
state.messages = state.messages.filter((message) => {
|
||||
if (message.id !== activeId) return true;
|
||||
@@ -1189,23 +1234,28 @@ export function projectThreadEvent(
|
||||
turn.turnId,
|
||||
);
|
||||
state.activeAssistantId = null;
|
||||
state.closedAssistantIds.clear();
|
||||
state.closedAnswerStreamIds.clear();
|
||||
state.closedAssistantIds = new Set();
|
||||
state.closedAnswerStreamIds = new Set();
|
||||
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);
|
||||
if (state.turnAliases.has(event.turn_id)) {
|
||||
state.turnAliases = new Map(state.turnAliases);
|
||||
state.turnAliases.delete(event.turn_id);
|
||||
} else state.closedTurnIds = new Set(state.closedTurnIds).add(event.turn_id);
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
export function projectThreadEvents(events: ThreadProjectionEvent[]): UIMessage[] {
|
||||
let state = createThreadProjectionState();
|
||||
const lookup = new ThreadProjectionIndex();
|
||||
events.forEach((event, index) => {
|
||||
state = projectThreadEvent(state, event, {
|
||||
createId: () => `history-${index}`,
|
||||
now: 0,
|
||||
persisted: true,
|
||||
index: lookup,
|
||||
mutableCollections: true,
|
||||
});
|
||||
});
|
||||
return state.messages.map((row) => {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import type { ThreadProjectionEvent, WebuiThreadPersistedPayload } from "./types";
|
||||
|
||||
function isAnswer(event: ThreadProjectionEvent): boolean {
|
||||
return event.event === "delta" || event.event === "stream_end"
|
||||
|| (event.event === "message" && event.kind !== "tool_hint" && event.kind !== "progress" && event.kind !== "reasoning");
|
||||
}
|
||||
|
||||
/** Coalesce continuous raw ranges; canonical recovery replaces stored answers, not other activities. */
|
||||
export function joinThreadFragments(
|
||||
previous: readonly WebuiThreadPersistedPayload[],
|
||||
current: WebuiThreadPersistedPayload,
|
||||
): { pages: WebuiThreadPersistedPayload[]; body: WebuiThreadPersistedPayload; withdrawn: ThreadProjectionEvent[] } {
|
||||
const range = current.page?.record_range;
|
||||
if (!range) return { pages: [...previous], body: current, withdrawn: [] };
|
||||
const same = (page: WebuiThreadPersistedPayload) => page.page?.record_range?.turn === range.turn
|
||||
&& page.page.history_generation === current.page?.history_generation;
|
||||
const ordered = [...previous.filter(same), current].sort((a, b) => {
|
||||
const left = a.page!.record_range!;
|
||||
const right = b.page!.record_range!;
|
||||
return left.start - right.start || right.end - left.end;
|
||||
});
|
||||
const groups: WebuiThreadPersistedPayload[][] = [];
|
||||
for (const page of ordered) {
|
||||
const group = groups.at(-1);
|
||||
const end = group ? Math.max(...group.map((item) => item.page!.record_range!.end)) : -1;
|
||||
if (!group || page.page!.record_range!.start > end) groups.push([page]);
|
||||
else group.push(page);
|
||||
}
|
||||
|
||||
const recovered = ordered.some((page) => page.page?.recovered_answers === true);
|
||||
const withdrawn: ThreadProjectionEvent[] = [];
|
||||
const latestEvents = new Map(current.events.map((event) => [event.projection_id, event]));
|
||||
let selected: WebuiThreadPersistedPayload | undefined;
|
||||
const pages = groups.map((group) => {
|
||||
const first = group[0];
|
||||
const last = group.reduce((a, b) => a.page!.record_range!.end >= b.page!.record_range!.end ? a : b);
|
||||
const events: ThreadProjectionEvent[] = [];
|
||||
const seen = new Set<string>();
|
||||
const completed = new Set<string>();
|
||||
let boundary: number | undefined;
|
||||
for (const page of group) {
|
||||
for (const turn of page.completed_turn_ids ?? []) completed.add(turn);
|
||||
for (const [index, event] of page.events.entries()) {
|
||||
if (boundary === undefined && page.fork_boundary_event_index === index) boundary = events.length;
|
||||
if (recovered && !page.page?.recovered_answers && isAnswer(event)) {
|
||||
if (page !== current) withdrawn.push(event);
|
||||
continue;
|
||||
}
|
||||
if (event.projection_id && seen.has(event.projection_id)) continue;
|
||||
if (event.projection_id) seen.add(event.projection_id);
|
||||
events.push(event.projection_id ? latestEvents.get(event.projection_id) ?? event : event);
|
||||
}
|
||||
if (boundary === undefined && page.fork_boundary_event_index === page.events.length) boundary = events.length;
|
||||
}
|
||||
const start = first.page!.record_range!.start;
|
||||
const end = last.page!.record_range!.end;
|
||||
const complete = start === 0 && events.some((event) => event.event === "turn_end");
|
||||
const merged: WebuiThreadPersistedPayload = {
|
||||
...first,
|
||||
events,
|
||||
completed_turn_ids: [...completed],
|
||||
page: { ...first.page!, after_cursor: last.page!.after_cursor, has_more_after: last.page!.has_more_after,
|
||||
record_range: { turn: range.turn, start, end }, truncated_oversized_turn: !complete,
|
||||
...(recovered ? { recovered_answers: true } : {}) },
|
||||
};
|
||||
if (boundary === undefined) delete merged.fork_boundary_event_index;
|
||||
else merged.fork_boundary_event_index = boundary;
|
||||
if (group.includes(current)) selected = merged;
|
||||
return merged;
|
||||
});
|
||||
const group = selected!;
|
||||
const body = { ...current, events: group.events, completed_turn_ids: group.completed_turn_ids,
|
||||
page: { ...current.page!, before_cursor: group.page!.before_cursor, has_more_before: group.page!.has_more_before,
|
||||
user_message_offset: group.page!.user_message_offset, after_cursor: group.page!.after_cursor,
|
||||
has_more_after: group.page!.has_more_after, record_range: group.page!.record_range,
|
||||
truncated_oversized_turn: group.page!.truncated_oversized_turn, recovered_answers: group.page!.recovered_answers } };
|
||||
if (group.fork_boundary_event_index === undefined) delete body.fork_boundary_event_index;
|
||||
else body.fork_boundary_event_index = group.fork_boundary_event_index;
|
||||
return { pages: [...previous.filter((page) => !same(page)), ...pages], body, withdrawn };
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { UIMessage } from "./types";
|
||||
import type { ThreadProjectionEffects } from "./thread-event-projection";
|
||||
|
||||
/** Owned by one projector, never shared with its immutable checkpoints. */
|
||||
export class ThreadProjectionIndex {
|
||||
private messages: UIMessage[] | null = null;
|
||||
private ids = new Map<string, number>();
|
||||
private answers = new Map<string, Set<number>>();
|
||||
lastUser = -1;
|
||||
|
||||
position(id: string): number | undefined { return this.ids.get(id); }
|
||||
answer(stream: string): ReadonlySet<number> { return this.answers.get(stream) ?? new Set(); }
|
||||
|
||||
private record(row: UIMessage, index: number, remove = false): void {
|
||||
if (!remove) this.ids.set(row.id, index);
|
||||
if (row.role === "user" && !remove) this.lastUser = index;
|
||||
if (row.role !== "assistant") return;
|
||||
const key = row.streamId ?? "";
|
||||
const positions = this.answers.get(key) ?? new Set<number>();
|
||||
if (remove) positions.delete(index);
|
||||
else positions.add(index);
|
||||
if (positions.size) this.answers.set(key, positions);
|
||||
else this.answers.delete(key);
|
||||
}
|
||||
|
||||
sync(messages: UIMessage[], effects?: ThreadProjectionEffects): void {
|
||||
if (messages === this.messages) return;
|
||||
const previous = this.messages;
|
||||
if (!previous || !effects || effects.consumed.size || messages.length < previous.length) {
|
||||
this.ids.clear();
|
||||
this.answers.clear();
|
||||
this.lastUser = -1;
|
||||
messages.forEach((row, index) => this.record(row, index));
|
||||
} else {
|
||||
for (const id of effects.bodyWrites) {
|
||||
const index = this.ids.get(id);
|
||||
if (index === undefined) continue;
|
||||
if (messages[index].streamId !== previous[index].streamId) {
|
||||
this.record(previous[index], index, true);
|
||||
this.record(messages[index], index);
|
||||
}
|
||||
}
|
||||
for (let index = previous.length; index < messages.length; index++) this.record(messages[index], index);
|
||||
}
|
||||
this.messages = messages;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import { persistedCanonicalRunState } from "./canonical-run-snapshot";
|
||||
import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint";
|
||||
import { hasPendingAgentActivity } from "./activity-timeline";
|
||||
import { reconcileModelRequest } from "./model-request";
|
||||
import { joinThreadFragments } from "./thread-page-fragments";
|
||||
import { ThreadProjectionIndex } from "./thread-projection-index";
|
||||
import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types";
|
||||
|
||||
type Ranges = Array<[number, number]>;
|
||||
@@ -19,8 +21,21 @@ interface TextSource {
|
||||
through: number;
|
||||
end: number | null;
|
||||
snapshot: boolean;
|
||||
certified: boolean;
|
||||
members: Ranges;
|
||||
}
|
||||
interface LiveContribution {
|
||||
event: ThreadProjectionEvent;
|
||||
now: number;
|
||||
revision: number;
|
||||
startSeq?: number;
|
||||
sideChannel?: boolean;
|
||||
}
|
||||
interface PendingFragmentGap {
|
||||
turn: number;
|
||||
oldEnd: number;
|
||||
front: number;
|
||||
}
|
||||
interface Unit {
|
||||
rows: Set<string>;
|
||||
sources: Set<string>;
|
||||
@@ -63,13 +78,17 @@ export interface ThreadTranscriptSnapshot extends ThreadCheckpoint {
|
||||
knownTurns: Set<string>;
|
||||
paging: ThreadPaging;
|
||||
revision: number;
|
||||
fragments: WebuiThreadPersistedPayload[];
|
||||
live: LiveContribution[];
|
||||
historyGeneration: string | null;
|
||||
pendingFragmentGap: PendingFragmentGap | null;
|
||||
withdrawnSources: Set<string>;
|
||||
}
|
||||
|
||||
function addRange(ranges: Ranges, first: number, last = first): void {
|
||||
let start = first;
|
||||
let end = last;
|
||||
let index = 0;
|
||||
while (index < ranges.length && ranges[index][1] + 1 < start) index++;
|
||||
let index = rangeAt(ranges, start - 1);
|
||||
const from = index;
|
||||
while (index < ranges.length && ranges[index][0] <= end + 1) {
|
||||
start = Math.min(start, ranges[index][0]);
|
||||
@@ -78,8 +97,20 @@ function addRange(ranges: Ranges, first: number, last = first): void {
|
||||
}
|
||||
ranges.splice(from, index - from, [start, end]);
|
||||
}
|
||||
function rangeAt(ranges: Ranges, seq: number): number {
|
||||
let low = 0;
|
||||
let high = ranges.length;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >>> 1;
|
||||
if (ranges[mid][1] < seq) low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
function contains(ranges: Ranges | undefined, seq: number): boolean {
|
||||
return ranges?.some(([first, last]) => first <= seq && seq <= last) === true;
|
||||
if (!ranges) return false;
|
||||
const index = rangeAt(ranges, seq);
|
||||
return index < ranges.length && ranges[index][0] <= seq;
|
||||
}
|
||||
function mergeMembers(target: Members, source: Members): void {
|
||||
for (const [turn, ranges] of source) {
|
||||
@@ -91,6 +122,19 @@ function mergeMembers(target: Members, source: Members): void {
|
||||
function copyMembers(value: Members): Members {
|
||||
return new Map(Array.from(value, ([key, ranges]) => [key, ranges.map(([a, b]) => [a, b])]));
|
||||
}
|
||||
function mergeCoveredMembers(target: Members, members: Members, coverage: Members): void {
|
||||
for (const [turn, ranges] of members) {
|
||||
const covered = coverage.get(turn) ?? [];
|
||||
for (const [first, last] of ranges) {
|
||||
for (let index = rangeAt(covered, first); index < covered.length && covered[index][0] <= last; index++) {
|
||||
const [a, b] = covered[index];
|
||||
const kept = target.get(turn) ?? [];
|
||||
addRange(kept, Math.max(first, a), Math.min(last, b));
|
||||
target.set(turn, kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function copyText(value: TextSource): TextSource {
|
||||
return { ...value, members: value.members.map(([a, b]) => [a, b]) };
|
||||
}
|
||||
@@ -111,12 +155,62 @@ function coversText(certificate: TextSource, text: TextSource): boolean {
|
||||
return certificate.snapshot && certificate.after !== null && sameWire(certificate, text)
|
||||
&& text.members.every(([first, last]) => first > certificate.after! && last <= certificate.through);
|
||||
}
|
||||
function sourcesOverlap(candidate: Unit, retained: Unit): boolean {
|
||||
if (Array.from(candidate.sources).some((key) => !key.startsWith("text:") && retained.sources.has(key))) return true;
|
||||
return candidate.text.some((left) => retained.text.some((right) => sameWire(left, right)
|
||||
&& ((left.phase === "answer" && left.stream !== "")
|
||||
// Ordered canonical ends identify reset buffers even when attachment missed a prior end.
|
||||
|| right.members.some(([first, last]) => last > (left.after ?? -1) && first <= (left.end ?? Infinity)))));
|
||||
function matchUnits(candidates: Set<Unit>, retained: Set<Unit>): {
|
||||
byOld: Map<Unit, Set<Unit>>; byNew: Map<Unit, Set<Unit>>;
|
||||
} {
|
||||
const sources = new Map<string, Unit>();
|
||||
type Interval = { unit: Unit; start: number; end: number; maxEnd: number };
|
||||
const wires = new Map<string, Interval[]>();
|
||||
const wireKey = (text: TextSource) => JSON.stringify([text.turn, text.phase, text.stream]);
|
||||
for (const unit of candidates) {
|
||||
for (const source of unit.sources) if (!source.startsWith("text:")) sources.set(source, unit);
|
||||
for (const text of unit.text) {
|
||||
const key = wireKey(text);
|
||||
const intervals = wires.get(key) ?? [];
|
||||
const namedAnswer = text.phase === "answer" && text.stream !== "";
|
||||
intervals.push({ unit, start: namedAnswer ? -Infinity : text.after ?? -1,
|
||||
end: namedAnswer ? Infinity : text.end ?? Infinity, maxEnd: -Infinity });
|
||||
wires.set(key, intervals);
|
||||
}
|
||||
}
|
||||
for (const intervals of wires.values()) {
|
||||
intervals.sort((a, b) => a.start - b.start);
|
||||
let max = -Infinity;
|
||||
for (const interval of intervals) interval.maxEnd = max = Math.max(max, interval.end);
|
||||
}
|
||||
const byOld = new Map<Unit, Set<Unit>>();
|
||||
const byNew = new Map<Unit, Set<Unit>>();
|
||||
for (const old of retained) {
|
||||
const matches = new Set<Unit>();
|
||||
for (const source of old.sources) {
|
||||
const unit = sources.get(source);
|
||||
if (unit) matches.add(unit);
|
||||
}
|
||||
for (const text of old.text) {
|
||||
const intervals = wires.get(wireKey(text));
|
||||
if (!intervals) continue;
|
||||
for (const [first, last] of text.members) {
|
||||
let low = 0;
|
||||
let high = intervals.length;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >>> 1;
|
||||
if (intervals[mid].start < last) low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
for (let i = low - 1; i >= 0 && intervals[i].maxEnd >= first; i--) {
|
||||
if (intervals[i].end >= first) matches.add(intervals[i].unit);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!matches.size) continue;
|
||||
byOld.set(old, matches);
|
||||
for (const unit of matches) {
|
||||
const previous = byNew.get(unit) ?? new Set<Unit>();
|
||||
previous.add(old);
|
||||
byNew.set(unit, previous);
|
||||
}
|
||||
}
|
||||
return { byOld, byNew };
|
||||
}
|
||||
function unitPosition(unit: Unit | undefined, turn: string): number | null {
|
||||
if (!unit) return null;
|
||||
@@ -127,7 +221,11 @@ function unitPosition(unit: Unit | undefined, turn: string): number | null {
|
||||
return positions.length ? Math.min(...positions) : null;
|
||||
}
|
||||
|
||||
/** One received projection and accepted history frontier. HTTP replay is scratch only. */
|
||||
/** One received projection and accepted history frontier. HTTP replay is scratch only.
|
||||
* Record ranges identify stored pages; text_from_seq identifies the live text a
|
||||
* stored end replaces, scoped to its turn, phase and stream. Neither range
|
||||
* implies that intervening tools or the rest of the turn have been loaded.
|
||||
*/
|
||||
export class ThreadTranscript {
|
||||
projection: ThreadProjectionState;
|
||||
sideChannelTurnIds = new Set<string>();
|
||||
@@ -135,14 +233,25 @@ export class ThreadTranscript {
|
||||
private units = new Set<Unit>();
|
||||
private byRow = new Map<string, Unit>();
|
||||
private bySource = new Map<string, Unit>();
|
||||
private projectionIndex = new ThreadProjectionIndex();
|
||||
private historyReplay: { events: ThreadProjectionEvent[]; generation: string | null; owner: ThreadTranscript } | null = null;
|
||||
private installed: Members = new Map();
|
||||
private textCoverage: TextSource[] = [];
|
||||
private boundaries = new Map<string, number>();
|
||||
private knownTurns = new Set<string>();
|
||||
private fragments: WebuiThreadPersistedPayload[] = [];
|
||||
private live: LiveContribution[] = [];
|
||||
private historyGeneration: string | null = null;
|
||||
private pendingFragmentGap: PendingFragmentGap | null = null;
|
||||
private withdrawnSources = new Set<string>();
|
||||
fragmentCompletedTurnIds: string[] = [];
|
||||
private readonly recordLiveContributions: boolean;
|
||||
private revision = 0;
|
||||
private order = 0;
|
||||
|
||||
constructor(messages: UIMessage[] = [], saved?: ThreadTranscriptSnapshot) {
|
||||
constructor(messages: UIMessage[] = [], saved?: ThreadTranscriptSnapshot,
|
||||
options: { recordLiveContributions?: boolean } = {}) {
|
||||
this.recordLiveContributions = options.recordLiveContributions !== false;
|
||||
const checkpoint = saved ? copyThreadCheckpoint(saved) : createThreadCheckpoint(messages);
|
||||
this.projection = checkpoint.projection;
|
||||
this.sideChannelTurnIds = checkpoint.sideChannelTurnIds;
|
||||
@@ -151,6 +260,11 @@ export class ThreadTranscript {
|
||||
this.textCoverage = saved.textCoverage.map(copyText);
|
||||
this.boundaries = new Map(saved.boundaries);
|
||||
this.knownTurns = new Set(saved.knownTurns);
|
||||
this.fragments = [...saved.fragments];
|
||||
this.live = this.recordLiveContributions ? [...saved.live] : [];
|
||||
this.historyGeneration = saved.historyGeneration;
|
||||
this.pendingFragmentGap = saved.pendingFragmentGap ? { ...saved.pendingFragmentGap } : null;
|
||||
this.withdrawnSources = new Set(saved.withdrawnSources);
|
||||
this.paging = { ...saved.paging, loading: false, loadingOlder: false };
|
||||
this.revision = saved.revision;
|
||||
for (const unit of saved.units) this.installUnit({ ...unit, rows: new Set(unit.rows),
|
||||
@@ -162,6 +276,7 @@ export class ThreadTranscript {
|
||||
|
||||
get messages(): UIMessage[] { return this.projection.messages; }
|
||||
get modelRequests() { return this.projection.modelRequests; }
|
||||
get hasPendingFragmentGap(): boolean { return this.pendingFragmentGap !== null; }
|
||||
|
||||
private installUnit(unit: Unit): void {
|
||||
this.order = Math.max(this.order, unit.order + 1);
|
||||
@@ -171,6 +286,7 @@ export class ThreadTranscript {
|
||||
}
|
||||
|
||||
rejectTurn(turn: string): void {
|
||||
this.live = this.live.filter((entry) => entry.event.turn_id !== turn);
|
||||
for (const unit of this.units) if (unit.members.has(turn) || unit.sources.has(`user:${turn}`)) {
|
||||
this.units.delete(unit);
|
||||
for (const id of unit.rows) this.byRow.delete(id);
|
||||
@@ -217,7 +333,8 @@ export class ThreadTranscript {
|
||||
const phase = event.event.startsWith("reasoning") ? "reasoning" : "answer";
|
||||
const stream = event.stream_id ?? "";
|
||||
const boundaryKey = JSON.stringify([turn, phase, stream]);
|
||||
let after = phase === "answer" && stream ? 0
|
||||
let after = "text_from_seq" in event && event.text_from_seq !== undefined ? event.text_from_seq - 1
|
||||
: phase === "answer" && stream ? 0
|
||||
: this.boundaries.get(boundaryKey) ?? (this.knownTurns.has(turn) ? 0 : null);
|
||||
if (after !== null && after >= seq) {
|
||||
after = this.knownTurns.has(turn) ? 0 : null;
|
||||
@@ -233,6 +350,7 @@ export class ThreadTranscript {
|
||||
const text: TextSource = { turn, phase, stream, after, through: seq, end,
|
||||
snapshot: event.event.endsWith("end") && typeof event.text === "string"
|
||||
&& (phase === "answer" || event.text.length > 0),
|
||||
certified: "text_from_seq" in event && event.text_from_seq !== undefined,
|
||||
members: copyMembers(members).get(turn)! };
|
||||
return { source: `text:${textKey(text)}`, members, text };
|
||||
}
|
||||
@@ -248,6 +366,7 @@ export class ThreadTranscript {
|
||||
|
||||
project(event: ThreadProjectionEvent, options: {
|
||||
createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number;
|
||||
contributions?: ThreadProjectionEvent[]; sourceRevision?: number; mutableCollections?: boolean;
|
||||
}): UIMessage[] {
|
||||
if (!options.persisted && event.event === "user_message" && !event.provenance?.session_message) {
|
||||
event = { turn_seq: 0, ...event };
|
||||
@@ -289,6 +408,10 @@ export class ThreadTranscript {
|
||||
const targets = projection.messages.filter((row) => destinations.has(this.byRow.get(row.id)!));
|
||||
const scratchState = { ...copyThreadCheckpoint(this, targets).projection,
|
||||
activeAssistantId: null, mergeReasoning: false, activitySegmentId: null, fileEditSegmentId: null };
|
||||
// Sequence ordering proves this belongs before the installed completion,
|
||||
// rather than a new execution that happens to reuse its transport id.
|
||||
scratchState.closedTurnIds.delete(event.turn_id!);
|
||||
scratchState.turnAliases.delete(event.turn_id!);
|
||||
const scratch = projectThreadEvent(scratchState, event, { ...options, effects });
|
||||
const updates = new Map(scratch.messages.map((row) => [row.id, row]));
|
||||
const targetIds = new Set(targets.map((row) => row.id));
|
||||
@@ -308,10 +431,9 @@ export class ThreadTranscript {
|
||||
}
|
||||
const before = index < 0 ? lastInTurn + 1 : index;
|
||||
projection = { ...projection, messages: [...messages.slice(0, before), ...additions, ...messages.slice(before)],
|
||||
closedAssistantIds: scratch.closedAssistantIds, closedAnswerStreamIds: scratch.closedAnswerStreamIds,
|
||||
closedTurnIds: scratch.closedTurnIds };
|
||||
closedAssistantIds: scratch.closedAssistantIds, closedAnswerStreamIds: scratch.closedAnswerStreamIds };
|
||||
} else {
|
||||
projection = projectThreadEvent(projection, event, { ...options, effects });
|
||||
projection = projectThreadEvent(projection, event, { ...options, effects, index: this.projectionIndex });
|
||||
}
|
||||
if (event.event === "user_message" && projection.messages === this.messages) return this.messages;
|
||||
this.projection = projection;
|
||||
@@ -322,7 +444,8 @@ export class ThreadTranscript {
|
||||
const unit = this.byRow.get(id);
|
||||
if (unit) connected.add(unit);
|
||||
}
|
||||
const revision = options.persisted ? 0 : ++this.revision;
|
||||
const revision = options.persisted ? 0 : options.sourceRevision ?? ++this.revision;
|
||||
this.revision = Math.max(this.revision, revision);
|
||||
const unit: Unit = { rows: new Set(), sources: new Set([source]), members,
|
||||
text: text ? [text] : [], introduced: revision, order: this.order++, received: revision };
|
||||
for (const previous of connected) {
|
||||
@@ -336,7 +459,11 @@ export class ThreadTranscript {
|
||||
if (prior.end !== null) matching.end = Math.max(matching.end ?? 0, prior.end);
|
||||
for (const [first, last] of prior.members) addRange(matching.members, first, last);
|
||||
if (prior.snapshot) {
|
||||
matching.through = matching.snapshot ? Math.max(matching.through, prior.through) : prior.through;
|
||||
if (!matching.snapshot || prior.through > matching.through) {
|
||||
matching.through = prior.through;
|
||||
matching.after = prior.after;
|
||||
matching.certified = prior.certified;
|
||||
}
|
||||
matching.snapshot = true;
|
||||
} else if (!matching.snapshot) matching.through = Math.max(matching.through, prior.through);
|
||||
} else unit.text.push(copyText(prior));
|
||||
@@ -355,6 +482,10 @@ export class ThreadTranscript {
|
||||
const key = JSON.stringify([text.turn, text.phase, text.stream]);
|
||||
this.boundaries.set(key, Math.max(text.end, this.boundaries.get(key) ?? 0));
|
||||
}
|
||||
if (!options.persisted && this.recordLiveContributions) for (const contribution of options.contributions ?? [event]) {
|
||||
this.live.push({ event: contribution, now: options.now, revision,
|
||||
startSeq: contribution.turn_seq ?? options.startSeq, sideChannel: options.sideChannel });
|
||||
}
|
||||
return this.messages;
|
||||
}
|
||||
|
||||
@@ -370,9 +501,10 @@ export class ThreadTranscript {
|
||||
if (unit.text.length === 0 && Array.from(unit.sources).every((source) => candidate.bySource.has(source))) return true;
|
||||
if (unit.members.size === 0) return false;
|
||||
const represented = copyMembers(candidate.installed);
|
||||
for (const text of unit.text) {
|
||||
if (Array.from(candidate.units).some((other) => other.text.some((certificate) => coversText(certificate, text)))) {
|
||||
mergeMembers(represented, new Map([[text.turn, text.members]]));
|
||||
for (const text of unit.text) for (const certificate of candidate.textCoverage) {
|
||||
if (certificate.after !== null && sameWire(certificate, text)) {
|
||||
mergeCoveredMembers(represented, new Map([[text.turn, text.members]]),
|
||||
new Map([[text.turn, [[certificate.after + 1, certificate.through]]]]));
|
||||
}
|
||||
}
|
||||
return Array.from(unit.members).every(([turn, ranges]) => ranges.every(([first, last]) =>
|
||||
@@ -380,60 +512,216 @@ export class ThreadTranscript {
|
||||
|
||||
}
|
||||
|
||||
private stageFragment(joined: ReturnType<typeof joinThreadFragments>, read: ThreadRead,
|
||||
gap: PendingFragmentGap | null): true {
|
||||
const page = joined.body.page!;
|
||||
this.fragments = joined.pages;
|
||||
// The visible projection is retained until admission, including across cache restore.
|
||||
for (const event of joined.withdrawn) this.withdrawnSources.add(this.describe(event).source);
|
||||
this.pendingFragmentGap = gap;
|
||||
this.historyGeneration = page.history_generation ?? this.historyGeneration;
|
||||
this.paging = { ...this.paging, loading: false, loadingOlder: false, error: null, olderError: null,
|
||||
beforeCursor: page.before_cursor ?? null, hasMoreBefore: page.has_more_before === true, truncated: true,
|
||||
version: this.paging.version + (read.kind === "older" ? 0 : 1),
|
||||
lineage: this.paging.lineage + (read.kind === "older" ? 0 : 1) };
|
||||
return true;
|
||||
}
|
||||
|
||||
private projectHistory(events: ThreadProjectionEvent[], generation: string | null): ThreadTranscript {
|
||||
const previous = this.historyReplay;
|
||||
const reuse = previous?.generation === generation && events.length >= previous.events.length
|
||||
&& previous.events.every((event, index) => event === events[index]
|
||||
|| JSON.stringify(event) === JSON.stringify(events[index]));
|
||||
const candidate = new ThreadTranscript([], undefined, { recordLiveContributions: false });
|
||||
if (reuse) {
|
||||
const owner = previous.owner;
|
||||
candidate.projection = copyThreadCheckpoint(owner).projection;
|
||||
candidate.units = new Set(owner.units);
|
||||
candidate.byRow = new Map(owner.byRow);
|
||||
candidate.bySource = new Map(owner.bySource);
|
||||
candidate.boundaries = new Map(owner.boundaries);
|
||||
candidate.knownTurns = new Set(owner.knownTurns);
|
||||
candidate.order = owner.order;
|
||||
}
|
||||
for (let index = reuse ? previous.events.length : 0; index < events.length; index++) {
|
||||
candidate.project(events[index], { createId: () => `history-${index}`, now: 0, persisted: true, mutableCollections: true });
|
||||
}
|
||||
// Only canonical replay is reusable; live overlays and admission never enter this cache.
|
||||
this.historyReplay = { events, generation, owner: candidate };
|
||||
return candidate;
|
||||
}
|
||||
|
||||
accept(body: WebuiThreadPersistedPayload | null, read: ThreadRead): boolean {
|
||||
this.fragmentCompletedTurnIds = [];
|
||||
if (read.kind === "older" && (read.lineage !== this.paging.lineage || read.before !== this.paging.beforeCursor)) return false;
|
||||
// An initial network read may have started just before its cached seed was installed.
|
||||
if (read.kind !== "older" && read.lineage !== this.paging.lineage
|
||||
&& !(read.kind === "initial" && read.lineage === 0 && this.paging.lineage === 1)) return false;
|
||||
if (read.kind === "older" && !body?.page) {
|
||||
this.finishRead(read, "Earlier history did not include a page cursor");
|
||||
return false;
|
||||
}
|
||||
const candidate = new ThreadTranscript();
|
||||
for (const [index, event] of (body?.events ?? []).entries()) candidate.project(event,
|
||||
{ createId: () => `history-${index}`, now: 0, persisted: true });
|
||||
for (const unit of candidate.units) mergeMembers(candidate.installed, unit.members);
|
||||
const overlaps = new Set(Array.from(this.units).filter((old) =>
|
||||
Array.from(candidate.units).some((unit) => sourcesOverlap(unit, old))));
|
||||
const firstOverlap = this.messages.findIndex((row) => overlaps.has(this.byRow.get(row.id)!));
|
||||
const windowRows = new Set(this.messages.slice(Math.max(0, firstOverlap)).map((row) => row.id));
|
||||
const received = Array.from(this.units).filter((unit) => unit.received > 0
|
||||
&& Array.from(unit.rows).some((id) => windowRows.has(id)));
|
||||
if (read.kind === "older" && body?.page?.has_more_before === true
|
||||
&& (!body.page.before_cursor || body.page.before_cursor === read.before)) {
|
||||
this.finishRead(read, "Earlier history cursor did not advance");
|
||||
return false;
|
||||
}
|
||||
const generation = body?.page?.history_generation ?? null;
|
||||
const replacedHistory = generation !== null && this.historyGeneration !== null
|
||||
&& generation !== this.historyGeneration;
|
||||
if (replacedHistory && (read.kind === "older" || this.live.length > 0 || this.revision > read.revision)) {
|
||||
this.finishRead(read, "History changed during loading");
|
||||
return false;
|
||||
}
|
||||
const incoming = body?.page?.record_range;
|
||||
const pending = this.pendingFragmentGap;
|
||||
if (pending && (!incoming || incoming.turn !== pending.turn
|
||||
|| (read.kind === "older" && incoming.end !== pending.front))) {
|
||||
this.finishRead(read, "Could not bridge the missing history records");
|
||||
return false;
|
||||
}
|
||||
const prior = incoming && !replacedHistory ? this.fragments.filter((page) =>
|
||||
(page.page?.history_generation ?? null) === generation && page.page?.record_range?.turn === incoming.turn) : [];
|
||||
const priorEnd = prior.length ? Math.max(...prior.map((page) => page.page!.record_range!.end)) : null;
|
||||
if (read.kind !== "older" && incoming && priorEnd !== null && incoming.end < priorEnd) {
|
||||
this.finishRead(read, "History changed during loading");
|
||||
return false;
|
||||
}
|
||||
const joined = incoming && body ? joinThreadFragments(replacedHistory ? [] : this.fragments, body) : null;
|
||||
if (joined) body = joined.body;
|
||||
const groupRange = joined?.body.page?.record_range;
|
||||
const gap = pending ?? (read.kind !== "older" && incoming && priorEnd !== null && incoming.start > priorEnd
|
||||
? { turn: incoming.turn, oldEnd: priorEnd, front: incoming.start } : null);
|
||||
const hasGap = !!gap && !!groupRange && groupRange.start > gap.oldEnd;
|
||||
const replaceWindow = hasGap && !pending && this.live.length === 0
|
||||
&& Array.from(this.units).every((unit) => unit.received === 0);
|
||||
if (hasGap && !replaceWindow && joined && groupRange && gap) {
|
||||
const page = body!.page!;
|
||||
if (!page.has_more_before || !page.before_cursor || page.before_cursor === read.before) {
|
||||
this.finishRead(read, "Could not bridge the missing history records");
|
||||
return false;
|
||||
}
|
||||
return this.stageFragment(joined, read, { ...gap, front: groupRange.start });
|
||||
}
|
||||
const canonical = body ? persistedCanonicalRunState(body) : null;
|
||||
const completed = new Set(canonical?.completedTurnIds);
|
||||
const protectedUnits = received.filter((unit) => !this.unitCovered(unit, candidate)
|
||||
|| (unit.text.length > 0 && (body?.page?.truncated_oversized_turn
|
||||
|| unit.text.some((text) => !completed.has(text.turn)))));
|
||||
const completeSnapshot = !body?.page?.truncated_oversized_turn && (!joined || groupRange?.start === 0);
|
||||
let candidate = this.projectHistory(body?.events ?? [], generation);
|
||||
const durableText = new Map<string, TextSource>();
|
||||
for (const unit of candidate.units) {
|
||||
mergeMembers(candidate.installed, unit.members);
|
||||
for (const text of unit.text) if (text.snapshot && text.after !== null
|
||||
&& (text.certified || (completeSnapshot && completed.has(text.turn)))) {
|
||||
const previous = durableText.get(textKey(text));
|
||||
if (!previous || text.through > previous.through) durableText.set(textKey(text), copyText(text));
|
||||
}
|
||||
}
|
||||
const durableMembers = joined ? candidate.installed : null;
|
||||
candidate.textCoverage = Array.from(durableText.values());
|
||||
// Rebuild a fragment only when it has unpersisted contributions. Those
|
||||
// events join the same projection as history, rather than a second overlay.
|
||||
if (joined && body) {
|
||||
const turns = new Set(body.events.map((event) => event.turn_id));
|
||||
const remaining = this.live.filter(({ event }) => event.turn_id && event.turn_seq !== undefined
|
||||
&& turns.has(event.turn_id) && !candidate.represented(event));
|
||||
if (remaining.length) {
|
||||
const replay: Array<{ event: ThreadProjectionEvent; live?: LiveContribution }> = body.events.map((event) => ({ event }));
|
||||
for (const entry of remaining) {
|
||||
const { event } = entry;
|
||||
let position = replay.findIndex((item) => item.event.turn_id === event.turn_id
|
||||
&& item.event.turn_seq !== undefined && item.event.turn_seq > event.turn_seq!);
|
||||
if (position < 0) {
|
||||
position = replay.findIndex((item) => item.event.event === "user_message"
|
||||
&& (this.bySource.get(this.describe(item.event).source)?.introduced ?? 0) > entry.revision);
|
||||
if (position < 0) position = replay.length;
|
||||
}
|
||||
replay.splice(position, 0, { event, live: entry });
|
||||
}
|
||||
candidate = new ThreadTranscript();
|
||||
for (const [index, item] of replay.entries()) candidate.project(item.event, item.live
|
||||
? { createId: () => `live-${item.live!.revision}-${index}`, now: item.live.now,
|
||||
startSeq: item.live.startSeq, sideChannel: item.live.sideChannel, sourceRevision: item.live.revision }
|
||||
: { createId: () => `history-${index}`, now: 0, persisted: true });
|
||||
for (const unit of candidate.units) mergeMembers(candidate.installed, unit.members);
|
||||
candidate.textCoverage = Array.from(durableText.values());
|
||||
}
|
||||
}
|
||||
// Canonical recovery may replace an unfinished stream with a final message.
|
||||
if (durableMembers && completeSnapshot) for (const event of body?.events ?? []) {
|
||||
if (event.event !== "message" || event.kind !== undefined || !event.turn_id || !completed.has(event.turn_id)) continue;
|
||||
const unit = candidate.bySource.get(this.describe(event).source);
|
||||
if (unit) mergeMembers(durableMembers, unit.members);
|
||||
}
|
||||
// An unknown-left end may overwrite an unpersisted live buffer. Stage the
|
||||
// fragment before admission, keeping the visible projection until its prefix arrives.
|
||||
const overwritesLive = joined && candidate.live.some(({ event }) => {
|
||||
if ((event.event !== "delta" && event.event !== "reasoning_delta") || !event.turn_id
|
||||
|| event.turn_seq === undefined || contains(durableMembers?.get(event.turn_id), event.turn_seq)) return false;
|
||||
return body?.events.some((end) => {
|
||||
if (end.turn_id !== event.turn_id || end.turn_seq === undefined || end.turn_seq <= event.turn_seq!) return false;
|
||||
if (event.event === "delta" && end.event === "message" && end.kind === undefined) return true;
|
||||
if (end.event !== "stream_end" && end.event !== "reasoning_end") return false;
|
||||
return (end.stream_id ?? "") === (event.stream_id ?? "")
|
||||
&& ((event.event === "delta" && end.event === "stream_end" && typeof end.text === "string")
|
||||
|| (event.event === "reasoning_delta" && end.event === "reasoning_end" && !!end.text));
|
||||
});
|
||||
});
|
||||
if (overwritesLive && joined && groupRange) {
|
||||
return this.stageFragment(joined, read, groupRange.start > 0
|
||||
? { turn: groupRange.turn, oldEnd: 0, front: groupRange.start } : null);
|
||||
}
|
||||
const withdrawnSources = new Set([...this.withdrawnSources, ...(joined?.withdrawn ?? []).map((event) => this.describe(event).source)]);
|
||||
const withdrawn = new Set(Array.from(withdrawnSources).flatMap((source) => {
|
||||
const unit = this.bySource.get(source);
|
||||
return unit ? [unit] : [];
|
||||
}));
|
||||
const matches = matchUnits(candidate.units, this.units);
|
||||
const overlaps = new Set([...withdrawn, ...matches.byOld.keys()]);
|
||||
const firstOverlap = this.messages.findIndex((row) => overlaps.has(this.byRow.get(row.id)!));
|
||||
const windowRows = new Set(this.messages.slice(Math.max(0, firstOverlap)).map((row) => row.id));
|
||||
const received = replacedHistory ? [] : Array.from(this.units).filter((unit) => unit.received > 0
|
||||
&& Array.from(unit.rows).some((id) => windowRows.has(id)));
|
||||
const protectedUnits = received.filter((unit) => !this.unitCovered(unit, candidate));
|
||||
const newTail = read.empty && protectedUnits.length > 0
|
||||
&& protectedUnits.every((unit) => unit.received > read.revision);
|
||||
const appendedInputs = this.messages.filter((row) => row.role === "user" && row.turnId
|
||||
&& this.byRow.get(row.id)!.introduced > read.revision);
|
||||
const appendedTurns = new Set(appendedInputs.map((row) => row.turnId!));
|
||||
const appendedInputUnits = new Set(appendedInputs.map((row) => this.byRow.get(row.id)!));
|
||||
const reset = read.kind === "latest" && overlaps.size === 0
|
||||
const reset = replacedHistory || replaceWindow || (read.kind === "latest" && overlaps.size === 0
|
||||
&& !body?.page?.truncated_oversized_turn
|
||||
&& protectedUnits.every((unit) => unit.introduced > read.revision
|
||||
&& (appendedInputUnits.has(unit) || (unit.members.size > 0
|
||||
&& Array.from(unit.members.keys()).every((turn) => appendedTurns.has(turn)))));
|
||||
&& Array.from(unit.members.keys()).every((turn) => appendedTurns.has(turn))))));
|
||||
if (read.kind !== "older" && this.messages.length > 0 && overlaps.size === 0 && !newTail && !reset) {
|
||||
this.finishRead(read);
|
||||
return false;
|
||||
}
|
||||
const held = new Set<Unit>();
|
||||
for (const unit of candidate.units) {
|
||||
if (protectedUnits.some((old) => sourcesOverlap(unit, old))) held.add(unit);
|
||||
for (const old of protectedUnits) for (const turn of old.members.keys()) {
|
||||
const at = unitPosition(unit, turn);
|
||||
const protectedStarts = new Map<string, number>();
|
||||
for (const old of protectedUnits) {
|
||||
for (const unit of matches.byOld.get(old) ?? []) held.add(unit);
|
||||
for (const turn of old.members.keys()) {
|
||||
const start = unitPosition(old, turn);
|
||||
if (at !== null && start !== null && at >= start) held.add(unit);
|
||||
if (start !== null) protectedStarts.set(turn, Math.min(start, protectedStarts.get(turn) ?? Infinity));
|
||||
}
|
||||
}
|
||||
for (const unit of candidate.units) for (const turn of unit.members.keys()) {
|
||||
const start = protectedStarts.get(turn);
|
||||
const at = start === undefined ? null : unitPosition(unit, turn);
|
||||
if (at !== null && at >= start!) held.add(unit);
|
||||
}
|
||||
const rows = candidate.messages;
|
||||
let cut = rows.findIndex((row) => held.has(candidate.byRow.get(row.id)!));
|
||||
if (cut < 0) cut = rows.length;
|
||||
const lastRow = new Map<Unit, number>();
|
||||
rows.forEach((row, index) => lastRow.set(candidate.byRow.get(row.id)!, index));
|
||||
// A whole source can straddle several rows: never install only part of it.
|
||||
for (let changed = true; changed;) {
|
||||
changed = false;
|
||||
for (let index = 0; index < cut; index++) {
|
||||
const unit = candidate.byRow.get(rows[index].id)!;
|
||||
if (rows.slice(cut).some((row) => unit.rows.has(row.id))) { cut = index; changed = true; break; }
|
||||
if (lastRow.get(unit)! >= cut) { cut = index; changed = true; break; }
|
||||
}
|
||||
}
|
||||
const admittedRows = rows.slice(0, cut);
|
||||
@@ -443,21 +731,17 @@ export class ThreadTranscript {
|
||||
if (unit.rows.size === 0 && unit.order < cutOrder && !held.has(unit)) admitted.add(unit);
|
||||
}
|
||||
if (read.kind === "older" && Array.from(candidate.units).some((unit) => !admitted.has(unit)
|
||||
&& !Array.from(this.units).some((old) => sourcesOverlap(unit, old)))) {
|
||||
&& !matches.byNew.has(unit))) {
|
||||
this.finishRead(read, "Could not place earlier history");
|
||||
return false;
|
||||
}
|
||||
if (read.kind === "older" && body?.page?.has_more_before === true
|
||||
&& (!body.page.before_cursor || body.page.before_cursor === read.before)) {
|
||||
this.finishRead(read, "Earlier history cursor did not advance");
|
||||
return false;
|
||||
}
|
||||
const fullyAdopt = protectedUnits.length === 0 && cut === rows.length
|
||||
&& !body?.page?.truncated_oversized_turn
|
||||
&& (this.messages.length === 0 || reset || overlaps.size > 0);
|
||||
const replaced = new Set<Unit>();
|
||||
for (const old of this.units) if ((reset && !protectedUnits.includes(old)) || Array.from(admitted)
|
||||
.some((unit) => sourcesOverlap(unit, old) && (old.received === 0 || this.unitCovered(old, candidate)))) replaced.add(old);
|
||||
for (const old of this.units) if ((reset && !protectedUnits.includes(old))
|
||||
|| ((withdrawn.has(old) || Array.from(matches.byOld.get(old) ?? []).some((unit) => admitted.has(unit)))
|
||||
&& (old.received === 0 || this.unitCovered(old, candidate)))) replaced.add(old);
|
||||
const previousCount = this.messages.length;
|
||||
const firstReplaced = this.messages.findIndex((row) => replaced.has(this.byRow.get(row.id)!));
|
||||
const prefix = read.kind !== "older" && !reset && firstReplaced > 0
|
||||
@@ -467,8 +751,8 @@ export class ThreadTranscript {
|
||||
if (keepSuffix) for (const [index, row] of this.messages.entries()) {
|
||||
const old = this.byRow.get(row.id)!;
|
||||
if (!replaced.has(old)) continue;
|
||||
for (const unit of admitted) {
|
||||
if (!anchors.has(unit) && sourcesOverlap(unit, old)) anchors.set(unit, index);
|
||||
for (const unit of matches.byOld.get(old) ?? []) {
|
||||
if (admitted.has(unit) && !anchors.has(unit)) anchors.set(unit, index);
|
||||
}
|
||||
}
|
||||
const segments = new Map<string, string>();
|
||||
@@ -497,15 +781,26 @@ export class ThreadTranscript {
|
||||
for (const [turn, snapshot] of candidate.modelRequests) {
|
||||
modelRequests.set(turn, reconcileModelRequest(modelRequests.get(turn), snapshot));
|
||||
}
|
||||
this.projection = fullyAdopt && read.kind !== "older"
|
||||
const oldActive = this.projection.activeAssistantId;
|
||||
const activeReplaced = !!joined && !!oldActive && replaced.has(this.byRow.get(oldActive)!);
|
||||
const adoptProjection = (fullyAdopt || replacedHistory) && read.kind !== "older";
|
||||
this.projection = adoptProjection
|
||||
? { ...candidate.projection, messages: nextMessages, modelRequests,
|
||||
activitySegmentId: candidate.projection.activitySegmentId
|
||||
? segments.get(candidate.projection.activitySegmentId) ?? null : null,
|
||||
fileEditSegmentId: candidate.projection.fileEditSegmentId
|
||||
? segments.get(candidate.projection.fileEditSegmentId) ?? null : null,
|
||||
closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]),
|
||||
closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) }
|
||||
: { ...this.projection, messages: nextMessages, modelRequests };
|
||||
closedTurnIds: new Set([...(replacedHistory ? [] : this.projection.closedTurnIds), ...candidate.projection.closedTurnIds]),
|
||||
closedAnswerStreamIds: new Set([...(replacedHistory ? [] : this.projection.closedAnswerStreamIds), ...candidate.projection.closedAnswerStreamIds]) }
|
||||
: { ...this.projection, messages: nextMessages, modelRequests,
|
||||
...(activeReplaced ? {
|
||||
activeAssistantId: candidate.projection.activeAssistantId,
|
||||
mergeReasoning: candidate.projection.mergeReasoning,
|
||||
activitySegmentId: candidate.projection.activitySegmentId
|
||||
? segments.get(candidate.projection.activitySegmentId) ?? null : null,
|
||||
fileEditSegmentId: candidate.projection.fileEditSegmentId
|
||||
? segments.get(candidate.projection.fileEditSegmentId) ?? null : null,
|
||||
} : {}) };
|
||||
if (fullyAdopt && read.kind !== "older") {
|
||||
const retained = new Set(prefix.map((row) => row.id));
|
||||
for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit);
|
||||
@@ -516,29 +811,37 @@ export class ThreadTranscript {
|
||||
for (const key of unit.sources) this.bySource.delete(key);
|
||||
}
|
||||
for (const unit of admitted) this.installUnit(unit);
|
||||
this.withdrawnSources = new Set(Array.from(withdrawnSources).filter((source) => withdrawn.has(this.bySource.get(source)!)));
|
||||
const retainedMembers: Members = new Map();
|
||||
for (const unit of this.units) mergeMembers(retainedMembers, unit.members);
|
||||
const installed: Members = new Map();
|
||||
for (const [turn, ranges] of this.installed) {
|
||||
const kept: Ranges = [];
|
||||
for (const [first, last] of ranges) for (const [a, b] of retainedMembers.get(turn) ?? []) {
|
||||
if (first <= b && a <= last) addRange(kept, Math.max(first, a), Math.min(last, b));
|
||||
}
|
||||
if (kept.length) installed.set(turn, kept);
|
||||
}
|
||||
mergeCoveredMembers(installed, this.installed, retainedMembers);
|
||||
const certificates = new Map(this.textCoverage
|
||||
.filter((text) => this.bySource.has(`text:${textKey(text)}`))
|
||||
.map((text) => [textKey(text), text]));
|
||||
for (const unit of admitted) {
|
||||
mergeMembers(installed, unit.members);
|
||||
for (const text of unit.text) if (text.snapshot && text.after !== null) {
|
||||
const previous = certificates.get(textKey(text));
|
||||
if (!previous || text.through > previous.through) certificates.set(textKey(text), copyText(text));
|
||||
if (durableMembers) mergeCoveredMembers(installed, unit.members, durableMembers);
|
||||
else mergeMembers(installed, unit.members);
|
||||
for (const text of unit.text) {
|
||||
const evidence = durableText.get(textKey(text));
|
||||
if (!evidence?.snapshot || evidence.after === null) continue;
|
||||
const previous = certificates.get(textKey(evidence));
|
||||
if (!previous || evidence.through > previous.through) certificates.set(textKey(evidence), copyText(evidence));
|
||||
}
|
||||
}
|
||||
this.installed = installed;
|
||||
this.textCoverage = Array.from(certificates.values());
|
||||
if (fullyAdopt && read.kind !== "older") {
|
||||
const confirmedInputs = new Set<string>();
|
||||
for (const event of body?.events ?? []) {
|
||||
if (event.event !== "user_message" || !admitted.has(candidate.bySource.get(candidate.describe(event).source)!)) continue;
|
||||
if (event.input_id) confirmedInputs.add(`id:${event.input_id}`);
|
||||
if (event.provenance?.session_message?.message_id) confirmedInputs.add(`message:${event.provenance.session_message.message_id}`);
|
||||
}
|
||||
this.live = this.live.filter(({ event }) => !(event.event === "user_message"
|
||||
&& ((event.input_id && confirmedInputs.has(`id:${event.input_id}`))
|
||||
|| (event.provenance?.session_message?.message_id && confirmedInputs.has(`message:${event.provenance.session_message.message_id}`))))
|
||||
&& !this.represented(event));
|
||||
if (adoptProjection) {
|
||||
this.boundaries = new Map(candidate.boundaries);
|
||||
this.knownTurns = new Set(candidate.knownTurns);
|
||||
}
|
||||
@@ -550,12 +853,16 @@ export class ThreadTranscript {
|
||||
this.boundaries.set(key, Math.max(end, this.boundaries.get(key) ?? 0));
|
||||
}
|
||||
}
|
||||
this.projection.closedTurnIds = new Set(this.projection.closedTurnIds);
|
||||
this.projection.closedAssistantIds = new Set(this.projection.closedAssistantIds);
|
||||
this.projection.closedAnswerStreamIds = new Set(this.projection.closedAnswerStreamIds);
|
||||
for (const event of body?.events ?? []) {
|
||||
if (event.event === "turn_end" && event.turn_id && event.turn_seq !== undefined
|
||||
&& contains(this.installed.get(event.turn_id), event.turn_seq)) this.projection.closedTurnIds.add(event.turn_id);
|
||||
}
|
||||
const admittedRowIds = new Set(admittedRows.map((row) => row.id));
|
||||
for (const id of candidate.projection.closedAssistantIds) {
|
||||
if (admittedRows.some((row) => row.id === id)) this.projection.closedAssistantIds.add(id);
|
||||
if (admittedRowIds.has(id)) this.projection.closedAssistantIds.add(id);
|
||||
}
|
||||
const admittedStreams = new Set(admittedRows.filter((row) => row.streamId)
|
||||
.map((row) => JSON.stringify([row.turnId ?? "", row.streamId])));
|
||||
@@ -600,6 +907,10 @@ export class ThreadTranscript {
|
||||
if (forkRows && boundary !== undefined) for (const [index, event] of (body?.events ?? []).slice(0, boundary).entries()) {
|
||||
forkRows.project(event, { createId: () => `boundary-${index}`, now: 0, persisted: true });
|
||||
}
|
||||
if (reset) this.fragments = [];
|
||||
if (joined) this.fragments = joined.pages;
|
||||
if (pending && !hasGap) this.pendingFragmentGap = null;
|
||||
if (generation !== null) this.historyGeneration = generation;
|
||||
this.paging = { ...this.paging, loading: false, loadingOlder: false, error: null,
|
||||
olderError: read.kind !== "older" && !reset
|
||||
&& (preserveFrontier || this.paging.beforeCursor === page?.before_cursor) ? this.paging.olderError : null,
|
||||
@@ -620,6 +931,7 @@ export class ThreadTranscript {
|
||||
activeTurnId: body?.active_turn_id ?? null,
|
||||
}),
|
||||
};
|
||||
if (joined && admitted.size === candidate.units.size) this.fragmentCompletedTurnIds = [...completed];
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -634,11 +946,14 @@ export class ThreadTranscript {
|
||||
const scratch = new ThreadTranscript();
|
||||
events.forEach((event, index) => scratch.project(event,
|
||||
{ createId: () => `detail:${ref}:${index}`, now: 0, persisted: true }));
|
||||
const unit = this.byRow.get(target.id)!;
|
||||
const previous = this.byRow.get(target.id)!;
|
||||
const unit = { ...previous, rows: new Set(previous.rows) };
|
||||
this.units.delete(previous);
|
||||
unit.rows.delete(target.id);
|
||||
this.byRow.delete(target.id);
|
||||
const replacements = scratch.messages.map((row) => ({ ...row, activitySegmentId: target.activitySegmentId }));
|
||||
for (const row of replacements) { unit.rows.add(row.id); this.byRow.set(row.id, unit); }
|
||||
for (const row of replacements) unit.rows.add(row.id);
|
||||
this.installUnit(unit);
|
||||
this.projection = { ...this.projection, messages: this.messages.flatMap((row) => row === target ? replacements : [row]) };
|
||||
}
|
||||
|
||||
@@ -648,6 +963,9 @@ export class ThreadTranscript {
|
||||
members: copyMembers(unit.members), text: unit.text.map(copyText) })),
|
||||
installed: copyMembers(this.installed), textCoverage: this.textCoverage.map(copyText),
|
||||
boundaries: new Map(this.boundaries), knownTurns: new Set(this.knownTurns),
|
||||
paging: { ...this.paging }, revision: this.revision };
|
||||
paging: { ...this.paging }, revision: this.revision, fragments: [...this.fragments], live: [...this.live],
|
||||
historyGeneration: this.historyGeneration,
|
||||
pendingFragmentGap: this.pendingFragmentGap ? { ...this.pendingFragmentGap } : null,
|
||||
withdrawnSources: new Set(this.withdrawnSources) };
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -1595,6 +1595,8 @@ export type InboundEvent =
|
||||
chat_id: string;
|
||||
stream_id?: string;
|
||||
text?: string;
|
||||
/** Inclusive first turn sequence covered by this stream's cumulative text. */
|
||||
text_from_seq?: number;
|
||||
/** Lightweight provenance for proactive streamed assistant messages. */
|
||||
source?: UIMessageSource;
|
||||
response_sources?: ResponseSource[];
|
||||
@@ -1614,8 +1616,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;
|
||||
text_from_seq?: number;
|
||||
} & InboundTurnMetadata)
|
||||
| { event: "pairing_changed" }
|
||||
| {
|
||||
@@ -1762,7 +1764,17 @@ export interface OutboundMcpPresetMention {
|
||||
brand_color?: string | null;
|
||||
}
|
||||
|
||||
export interface WebuiThreadRecordRange {
|
||||
turn: number;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface WebuiThreadPagePayload {
|
||||
history_generation?: string | null;
|
||||
record_range?: WebuiThreadRecordRange;
|
||||
/** The fragment includes the canonical replacement for this turn's stored answers. */
|
||||
recovered_answers?: boolean;
|
||||
before_cursor?: string | null;
|
||||
has_more_before?: boolean;
|
||||
after_cursor?: string | null;
|
||||
|
||||
Reference in new issue
Block a user