fix(webui): update usage and tool progress during active turns (#6553)
* fix(webui): stream model status and usage during active turns * fix(webui): keep live rounds and active-run status consistent * fix(webui): reuse existing run indicators without extra status text * fix(webui): preserve live activity and batch durable delivery Cancel and drain sibling tools when progress notifications fail, retain balanced checkpoints, and keep model telemetry separate from answer provenance. Group-commit already queued activity at the channel delivery boundary while preserving FIFO, generation ownership, per-envelope admission, and commit-before-fanout semantics. Isolate invalid members without dropping valid neighboring events. Retain tool detail lazy grouping and cover scheduling, cancellation, persistence, encoding failures, and projection regressions. * test(webui): separate standard-library imports in batch regression * test: tighten live execution checks and clarify contracts * refactor: remove redundant live execution comments * refactor: settle tool results through one output path
This commit is contained in:
1 parent
006a535537
commit
8ff04aad2b
52 files changed
+2065
-211
No files matched your search
@@ -387,6 +387,19 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|
||||
|| !isCompactionPhase(value.phase)
|
||||
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
case "model_request": {
|
||||
const isUsage = (usage: unknown) => isRecord(usage)
|
||||
&& Object.values(usage).every((count) => typeof count === "number" && Number.isFinite(count) && count >= 0);
|
||||
if (typeof value.request_id !== "string" || !value.request_id
|
||||
|| typeof value.run_id !== "string" || !value.run_id
|
||||
|| !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0
|
||||
|| !["started", "completed", "failed", "cancelled"].includes(String(value.phase))
|
||||
|| (value.usage !== undefined && !isUsage(value.usage))
|
||||
|| (value.round_usages !== undefined && (!Array.isArray(value.round_usages) || !value.round_usages.every(isUsage)))
|
||||
|| (value.context_window_tokens !== undefined && (typeof value.context_window_tokens !== "number"
|
||||
|| !Number.isFinite(value.context_window_tokens) || value.context_window_tokens < 0))) break;
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
}
|
||||
case "turn_end":
|
||||
return value as unknown as ThreadProjectionEvent;
|
||||
}
|
||||
@@ -436,6 +449,7 @@ export async function fetchWebuiThread(
|
||||
if (options?.direction) params.set("direction", options.direction);
|
||||
if (options?.before) params.set("before", options.before);
|
||||
if (options?.after) params.set("after", options.after);
|
||||
params.set("include_model_requests", "1");
|
||||
const query = params.toString();
|
||||
const suffix = query ? `?${query}` : "";
|
||||
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types";
|
||||
|
||||
export type ComposerUsageSnapshot = Pick<UIMessage,
|
||||
"id" | "turnId" | "createdAt" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"
|
||||
> & { compacted?: boolean };
|
||||
|
||||
export function reconcileModelRequest(
|
||||
current: UIModelRequestSnapshot | undefined,
|
||||
incoming: UIModelRequestSnapshot,
|
||||
): UIModelRequestSnapshot {
|
||||
if (!current) return incoming;
|
||||
if ((current.ended && !incoming.ended) || current.retiredRunIds.includes(incoming.runId)) return current;
|
||||
if (current.turnSeq !== undefined && incoming.turnSeq !== undefined) {
|
||||
if (incoming.turnSeq < current.turnSeq
|
||||
|| (incoming.turnSeq === current.turnSeq && !(incoming.ended && !current.ended))) return current;
|
||||
} else if (current.runId === incoming.runId) {
|
||||
if (incoming.sequence < current.sequence
|
||||
|| (incoming.sequence === current.sequence && !(incoming.ended && !current.ended))) return current;
|
||||
} else if (!incoming.retiredRunIds.includes(current.runId)) return current;
|
||||
return { ...incoming, retiredRunIds: Array.from(new Set([
|
||||
...current.retiredRunIds, ...incoming.retiredRunIds,
|
||||
...(current.runId !== incoming.runId ? [current.runId] : []),
|
||||
])) };
|
||||
}
|
||||
|
||||
/** Select one authoritative usage snapshot per turn, independent of text rows. */
|
||||
export function composerUsageSnapshots(
|
||||
messages: UIMessage[],
|
||||
snapshots: ReadonlyMap<string, UIModelRequestSnapshot>,
|
||||
): ComposerUsageSnapshot[] {
|
||||
const lastRows = new Map<string, number>();
|
||||
const compactions = new Map<string, number | undefined>();
|
||||
messages.forEach((row, index) => {
|
||||
if (!row.turnId) return;
|
||||
lastRows.set(row.turnId, index);
|
||||
if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {
|
||||
compactions.set(row.turnId, row.compaction.turnSeq);
|
||||
}
|
||||
});
|
||||
const rows = messages.flatMap((row, index): ComposerUsageSnapshot[] => {
|
||||
const snapshot = row.turnId ? snapshots.get(row.turnId) : undefined;
|
||||
if (snapshot) {
|
||||
if (lastRows.get(row.turnId!) !== index) return [];
|
||||
const compactionSeq = compactions.get(row.turnId!);
|
||||
const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined
|
||||
&& compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq);
|
||||
return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted,
|
||||
completedAt: snapshot.completedAt ?? row.completedAt, usage: snapshot.usage,
|
||||
roundUsages: snapshot.roundUsages, contextWindowTokens: snapshot.contextWindowTokens }];
|
||||
}
|
||||
if (row.kind === "compaction" && row.compaction?.phase === "succeeded") {
|
||||
return [{ id: row.id, createdAt: row.createdAt, compacted: true }];
|
||||
}
|
||||
if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return [];
|
||||
return [row];
|
||||
});
|
||||
// Proactive requests can precede any body. They need usage, not placeholder rows.
|
||||
const unanchored = Array.from(snapshots, ([turnId, snapshot]) => ({
|
||||
id: `model-request:${turnId}`, turnId, ...snapshot,
|
||||
})).filter((snapshot) => !lastRows.has(snapshot.turnId))
|
||||
.sort((left, right) => left.createdAt - right.createdAt);
|
||||
if (!unanchored.length) return rows;
|
||||
const result: ComposerUsageSnapshot[] = [];
|
||||
let index = 0;
|
||||
for (const row of rows) {
|
||||
while (index < unanchored.length && unanchored[index].createdAt <= row.createdAt) {
|
||||
result.push(unanchored[index++]);
|
||||
}
|
||||
result.push(row);
|
||||
}
|
||||
return [...result, ...unanchored.slice(index)];
|
||||
}
|
||||
@@ -19,6 +19,7 @@ export function copyThreadCheckpoint(
|
||||
projection: {
|
||||
...checkpoint.projection,
|
||||
messages,
|
||||
modelRequests: new Map(checkpoint.projection.modelRequests),
|
||||
closedAssistantIds: new Set(checkpoint.projection.closedAssistantIds),
|
||||
closedAnswerStreamIds: new Set(checkpoint.projection.closedAnswerStreamIds),
|
||||
closedTurnIds: new Set(checkpoint.projection.closedTurnIds),
|
||||
|
||||
@@ -10,6 +10,7 @@ import type {
|
||||
ToolProgressEvent,
|
||||
UIFileEdit,
|
||||
UIMessage,
|
||||
UIModelRequestSnapshot,
|
||||
UITurnPhase,
|
||||
} from "@/lib/types";
|
||||
|
||||
@@ -21,6 +22,7 @@ const FILE_EDIT_TOOL_NAMES = new Set(["write_file", "edit_file", "apply_patch"])
|
||||
|
||||
export interface ThreadProjectionState {
|
||||
messages: UIMessage[];
|
||||
modelRequests: ReadonlyMap<string, UIModelRequestSnapshot>;
|
||||
activeAssistantId: string | null;
|
||||
closedAssistantIds: Set<string>;
|
||||
/** Completed wire identities also fence late deltas for textless ends. */
|
||||
@@ -399,6 +401,7 @@ export function createThreadProjectionState(
|
||||
): ThreadProjectionState {
|
||||
return {
|
||||
messages,
|
||||
modelRequests: new Map(),
|
||||
activeAssistantId: null,
|
||||
closedAssistantIds: new Set(),
|
||||
closedAnswerStreamIds: new Set(),
|
||||
@@ -418,6 +421,7 @@ export function resetThreadProjectionCursor(
|
||||
): ThreadProjectionState {
|
||||
return {
|
||||
...createThreadProjectionState(messages),
|
||||
modelRequests: state.modelRequests,
|
||||
activitySegmentCounter: state.activitySegmentCounter,
|
||||
closedTurnIds: new Set(state.closedTurnIds),
|
||||
turnAliases: new Map(state.turnAliases),
|
||||
@@ -727,9 +731,9 @@ function projectToolActivity(
|
||||
: event.text
|
||||
? [event.text]
|
||||
: [];
|
||||
if (lines.length === 0) return;
|
||||
|
||||
const deferredDetail = event.trace_detail;
|
||||
if (lines.length === 0 && !deferredDetail) return;
|
||||
|
||||
const segmentId = ensureProjectionActivitySegment(state);
|
||||
const turn = turnFieldsForProjection(state, event, "activity");
|
||||
const last = state.messages[state.messages.length - 1];
|
||||
@@ -780,7 +784,7 @@ function projectToolActivity(
|
||||
id,
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: lines[lines.length - 1],
|
||||
content: lines[lines.length - 1] ?? "",
|
||||
traces: lines,
|
||||
...(visibleEvents.length ? { toolEvents: visibleEvents } : {}),
|
||||
...(deferredDetail ? { traceDetail: deferredDetail } : {}),
|
||||
@@ -857,6 +861,35 @@ export function projectThreadEvent(
|
||||
turnAliases: new Map(previous.turnAliases),
|
||||
};
|
||||
|
||||
if (event.event === "model_request") {
|
||||
if (!event.turn_id || state.closedTurnIds.has(event.turn_id)) return state;
|
||||
const previousRequest = state.modelRequests.get(event.turn_id);
|
||||
if (previousRequest?.ended
|
||||
|| previousRequest?.retiredRunIds.includes(event.run_id)
|
||||
|| (previousRequest?.runId === event.run_id && event.sequence <= previousRequest.sequence)
|
||||
|| (previousRequest?.turnSeq !== undefined && event.turn_seq !== undefined
|
||||
&& event.turn_seq <= previousRequest.turnSeq)) return state;
|
||||
const modelRequest: UIModelRequestSnapshot = {
|
||||
...previousRequest,
|
||||
createdAt: previousRequest?.createdAt ?? projectionCreatedAt(event, options),
|
||||
runId: event.run_id,
|
||||
sequence: event.sequence,
|
||||
turnSeq: event.turn_seq,
|
||||
...((event.phase === "completed" || event.phase === "failed")
|
||||
&& (event.usage?.request_count ?? 0) > (
|
||||
previousRequest?.runId === event.run_id ? previousRequest.usage?.request_count ?? 0 : 0
|
||||
) ? { usageTurnSeq: event.turn_seq } : {}),
|
||||
retiredRunIds: previousRequest && previousRequest.runId !== event.run_id
|
||||
? [...previousRequest.retiredRunIds, previousRequest.runId]
|
||||
: previousRequest?.retiredRunIds ?? [],
|
||||
...(event.usage !== undefined ? { usage: event.usage } : {}),
|
||||
...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),
|
||||
...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),
|
||||
};
|
||||
state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest);
|
||||
return state;
|
||||
}
|
||||
|
||||
if (event.event === "user_message") {
|
||||
if (event.provenance?.session_message) {
|
||||
const messageId = event.provenance.session_message.message_id?.trim();
|
||||
@@ -1002,6 +1035,7 @@ export function projectThreadEvent(
|
||||
compaction: {
|
||||
id: event.compaction_id,
|
||||
phase: event.phase,
|
||||
turnSeq: event.turn_seq,
|
||||
reason: event.reason,
|
||||
...(!options.persisted ? { announce: true } : {}),
|
||||
},
|
||||
@@ -1089,6 +1123,18 @@ export function projectThreadEvent(
|
||||
state.activitySegmentId = null;
|
||||
state.fileEditSegmentId = null;
|
||||
state.messages = finalizeStreamedTurn(state.messages);
|
||||
const modelRequests = new Map(state.modelRequests);
|
||||
for (const [turnId, snapshot] of modelRequests) {
|
||||
if (turn.turnId && turnId !== turn.turnId) continue;
|
||||
modelRequests.set(turnId, { ...snapshot, ended: true,
|
||||
turnSeq: event.turn_seq ?? snapshot.turnSeq,
|
||||
...(!options.persisted ? { completedAt: options.now } : {}),
|
||||
...(event.usage !== undefined ? { usage: event.usage } : {}),
|
||||
...(event.round_usages !== undefined ? { roundUsages: event.round_usages.slice(-8) } : {}),
|
||||
...(event.context_window_tokens !== undefined ? { contextWindowTokens: event.context_window_tokens } : {}),
|
||||
});
|
||||
}
|
||||
state.modelRequests = modelRequests;
|
||||
const latencyMs = typeof event.latency_ms === "number" && event.latency_ms >= 0
|
||||
? Math.round(event.latency_ms)
|
||||
: undefined;
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
import { persistedCanonicalRunState } from "./canonical-run-snapshot";
|
||||
import { copyThreadCheckpoint, createThreadCheckpoint, type ThreadCheckpoint } from "./thread-checkpoint";
|
||||
import { hasPendingAgentActivity } from "./activity-timeline";
|
||||
import { reconcileModelRequest } from "./model-request";
|
||||
import type { ThreadProjectionEvent, UIMessage, WebuiThreadPersistedPayload } from "./types";
|
||||
|
||||
type Ranges = Array<[number, number]>;
|
||||
@@ -159,6 +160,7 @@ export class ThreadTranscript {
|
||||
}
|
||||
|
||||
get messages(): UIMessage[] { return this.projection.messages; }
|
||||
get modelRequests() { return this.projection.modelRequests; }
|
||||
|
||||
private installUnit(unit: Unit): void {
|
||||
this.order = Math.max(this.order, unit.order + 1);
|
||||
@@ -246,6 +248,11 @@ export class ThreadTranscript {
|
||||
project(event: ThreadProjectionEvent, options: {
|
||||
createId: () => string; now: number; persisted?: boolean; sideChannel?: boolean; startSeq?: number;
|
||||
}): UIMessage[] {
|
||||
// Telemetry never contributes body sources, memberships, or admission barriers.
|
||||
if (event.event === "model_request") {
|
||||
this.projection = projectThreadEvent(this.projection, event, options);
|
||||
return this.messages;
|
||||
}
|
||||
if (!options.persisted && this.represented(event)) return this.messages;
|
||||
if (!event.projection_id && (!event.turn_id || event.turn_seq === undefined)) {
|
||||
event = { ...event, projection_id: options.createId() };
|
||||
@@ -478,15 +485,19 @@ export class ThreadTranscript {
|
||||
}
|
||||
if (keepSuffix) nextMessages.push(...this.messages.slice(previous)
|
||||
.filter((row) => !replaced.has(this.byRow.get(row.id)!)));
|
||||
const modelRequests = new Map(this.modelRequests);
|
||||
for (const [turn, snapshot] of candidate.modelRequests) {
|
||||
modelRequests.set(turn, reconcileModelRequest(modelRequests.get(turn), snapshot));
|
||||
}
|
||||
this.projection = fullyAdopt && read.kind !== "older"
|
||||
? { ...candidate.projection, messages: nextMessages,
|
||||
? { ...candidate.projection, messages: nextMessages, modelRequests,
|
||||
activitySegmentId: candidate.projection.activitySegmentId
|
||||
? segments.get(candidate.projection.activitySegmentId) ?? null : null,
|
||||
fileEditSegmentId: candidate.projection.fileEditSegmentId
|
||||
? segments.get(candidate.projection.fileEditSegmentId) ?? null : null,
|
||||
closedTurnIds: new Set([...this.projection.closedTurnIds, ...candidate.projection.closedTurnIds]),
|
||||
closedAnswerStreamIds: new Set([...this.projection.closedAnswerStreamIds, ...candidate.projection.closedAnswerStreamIds]) }
|
||||
: { ...this.projection, messages: nextMessages };
|
||||
: { ...this.projection, messages: nextMessages, modelRequests };
|
||||
if (fullyAdopt && read.kind !== "older") {
|
||||
const retained = new Set(prefix.map((row) => row.id));
|
||||
for (const unit of this.units) if (!Array.from(unit.rows).some((id) => retained.has(id))) replaced.add(unit);
|
||||
@@ -559,6 +570,11 @@ export class ThreadTranscript {
|
||||
.filter((key) => retainedStreams.has(key)));
|
||||
const retainedTurns = new Set(Array.from(this.units).flatMap((unit) => Array.from(unit.members.keys())));
|
||||
for (const row of nextMessages) if (row.turnId) retainedTurns.add(row.turnId);
|
||||
for (const [turn, snapshot] of modelRequests) {
|
||||
if (reset && snapshot.ended && !retainedTurns.has(turn) && !candidate.modelRequests.has(turn)) {
|
||||
modelRequests.delete(turn);
|
||||
} else retainedTurns.add(turn);
|
||||
}
|
||||
const retainedRows = new Set(nextMessages.map((row) => row.id));
|
||||
const retainedBoundaries = new Set(Array.from(this.units).flatMap((unit) => unit.text
|
||||
.map((text) => JSON.stringify([text.turn, text.phase, text.stream]))));
|
||||
|
||||
@@ -8,6 +8,8 @@ type Role = "user" | "assistant" | "tool" | "system";
|
||||
type MessageKind = "message" | "trace" | "compaction";
|
||||
|
||||
export interface UIContextCompaction extends ContextCompaction {
|
||||
/** Lifecycle event sequence, independent of the row's display position. */
|
||||
turnSeq?: number;
|
||||
/** Live wire transitions announce; hydrated transcript rows stay silent. */
|
||||
announce?: boolean;
|
||||
}
|
||||
@@ -180,6 +182,22 @@ export interface UIMessage {
|
||||
deliveryErrorKind?: MessageDeliveryErrorKind;
|
||||
}
|
||||
|
||||
/** Turn-owned telemetry, not a transcript row or body-history source. */
|
||||
export interface UIModelRequestSnapshot {
|
||||
runId: string;
|
||||
sequence: number;
|
||||
turnSeq?: number;
|
||||
retiredRunIds: string[];
|
||||
createdAt: number;
|
||||
completedAt?: number;
|
||||
/** Last turn sequence reporting fresh context usage. */
|
||||
usageTurnSeq?: number;
|
||||
ended?: boolean;
|
||||
usage?: TurnUsage;
|
||||
roundUsages?: RoundUsage[];
|
||||
contextWindowTokens?: number;
|
||||
}
|
||||
|
||||
export interface UICliAppAttachment {
|
||||
name: string;
|
||||
display_name?: string;
|
||||
@@ -1583,6 +1601,17 @@ export type InboundEvent =
|
||||
fallback?: boolean;
|
||||
reauth_provider?: string;
|
||||
}
|
||||
| ({
|
||||
event: "model_request";
|
||||
chat_id: string;
|
||||
request_id: string;
|
||||
run_id: string;
|
||||
sequence: number;
|
||||
phase: "started" | "completed" | "failed" | "cancelled";
|
||||
usage?: TurnUsage;
|
||||
round_usages?: RoundUsage[];
|
||||
context_window_tokens?: number;
|
||||
} & InboundTurnMetadata)
|
||||
| ({
|
||||
event: "turn_end";
|
||||
chat_id: string;
|
||||
@@ -1650,6 +1679,7 @@ export type InboundEvent =
|
||||
};
|
||||
|
||||
type ThreadProjectionEventName =
|
||||
| "model_request"
|
||||
| "user_message"
|
||||
| "message"
|
||||
| "file_edit"
|
||||
|
||||
Reference in new issue
Block a user