feat(webui): inspect file context in a live graph sidebar (#6562)

* feat(webui): inspect file context in a live graph sidebar

* refactor(webui): place preview controls in the shared sidebar header

* fix(webui): synchronize npm lockfile for graph dependencies

* fix(webui): preserve compacted context and refine graph inspection

* fix(context): harden provenance, request usage, and drawer lifecycle

* fix(webui): align source skeleton and browser fixtures

* perf(context): reuse source analysis and capture request graphs once

* perf(webui): compact graph history and render graph motion on canvas

* fix(webui): remove redundant context sidebar header

* style(webui): clarify context replay icon

* perf(webui): pace context replay on an adaptive timeline

* feat(webui): briefly reveal labels for new context nodes

* fix(webui): reveal new labels only for loaded context files

* fix(webui): restart graph animation clock after idle

* fix(webui): reveal labels when replay reverses node exit

* refactor(context): project file-use facts without retention tracking

* refactor(context): observe file reads outside agent execution

* fix(webui): animate context sidebar closing

* refactor(context): remove unused graph and usage panel code

* refactor(context): isolate prompt observation from execution metadata

* fix(webui): clarify cache rate and show context token usage

* fix(webui): abbreviate context token counts in thousands

* fix(webui): omit token unit from context usage details

* fix(webui): restore large source preview highlighting and panel elevation

* fix(webui): distinguish modifier scrolling from keyboard focus

* fix(webui): align preview tab and panel corner radii

* fix(webui): attach file tabs to the header divider

* fix(webui): use one action to toggle file preview mode

* fix(webui): use hover hint for context replay

* fix(webui): share composer layout between graph and file sidebars

* fix(webui): align sidebar bottom with composer surface

* fix(webui): restore mobile graph drawing and touch file details

* test(webui): align legacy cache assertions with current label

* perf(context): retain source analysis and bound graph animation work

* style(webui): add light elevation to user messages

* test(webui): await lazy graph scene before replay assertions

* fix(webui): align preview skeleton and browser contracts
This commit is contained in:
chengyongru authored and GitHub committed 2026-11-05 17:09:20 +08:00
1 parent 2b44088413
commit 519ed81132
132 files changed
+4673 -1159

No files matched your search

+59 -8
View File
@@ -1,3 +1,4 @@
import { isContextGraph, isContextInspection } from "@/lib/context-graph";
import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";
import type {
ApiServicePayload,
@@ -10,6 +11,7 @@ import type {
ChannelConnectPayload,
ChannelValidationPayload,
ChatSummary,
ContextGraph,
CliAppsPayload,
FilePreviewPayload,
FileReferenceMetadata,
@@ -315,7 +317,7 @@ function isProjectionTraceDetail(value: unknown): boolean {
&& value.traceCount >= 0;
}
function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
function parseThreadProjectionEvent(value: unknown, validatedGraphs: ReadonlySet<unknown> = new Set()): ThreadProjectionEvent {
if (!isRecord(value) || typeof value.event !== "string" || typeof value.chat_id !== "string") {
throw new Error("Invalid WebUI thread event");
}
@@ -383,11 +385,13 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
if (value.text !== undefined && typeof value.text !== "string") break;
return value as unknown as ThreadProjectionEvent;
case "context_compaction":
if (value.context_snapshot !== undefined && !isContextInspection(value.context_snapshot, (graph): graph is ContextGraph => validatedGraphs.has(graph) || isContextGraph(graph))) break;
if (typeof value.compaction_id !== "string" || !value.compaction_id
|| !isCompactionPhase(value.phase)
|| (value.reason !== undefined && !isCompactionReason(value.reason))) break;
return value as unknown as ThreadProjectionEvent;
case "model_request": {
if (value.context_graph !== undefined && !validatedGraphs.has(value.context_graph) && !isContextGraph(value.context_graph)) break;
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
@@ -395,6 +399,7 @@ function parseThreadProjectionEvent(value: unknown): ThreadProjectionEvent {
|| !Number.isSafeInteger(value.sequence) || Number(value.sequence) < 0
|| !["started", "completed", "failed", "cancelled"].includes(String(value.phase))
|| (value.usage !== undefined && !isUsage(value.usage))
|| (value.request_usage != null && !isUsage(value.request_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;
@@ -413,12 +418,57 @@ export function parseWebuiThreadPayload(value: unknown): WebuiThreadPersistedPay
if (value.projection !== "events" || !Array.isArray(value.events)) {
throw new Error("Invalid WebUI thread events");
}
const events = value.events.map(parseThreadProjectionEvent);
return {
...value,
projection: "events",
events,
} as unknown as WebuiThreadPersistedPayload;
const graphs = new Map<string, ContextGraph>();
if (value.context_graphs !== undefined) {
if (!isRecord(value.context_graphs)) throw new Error("Invalid context graph dictionary");
const table = { nodes: value.context_graph_nodes, edges: value.context_graph_edges };
if (!isContextGraph(table)) throw new Error("Invalid context graph entity table");
const resolveIndex = <T,>(entries: readonly T[], index: unknown): T => {
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0 || index >= entries.length) {
throw new Error("Unknown context graph entity reference");
}
return entries[index];
};
for (const [key, descriptor] of Object.entries(value.context_graphs)) {
if (!isRecord(descriptor) || !Array.isArray(descriptor.nodes) || !Array.isArray(descriptor.edges)) {
throw new Error("Invalid context graph dictionary entry");
}
const nodes = descriptor.nodes.map((index: unknown) => resolveIndex(table.nodes, index));
const paths = new Set(nodes.map((node) => node.path));
const edges = descriptor.edges.map((index: unknown) => {
const edge = resolveIndex(table.edges, index);
if (!paths.has(edge.source) || !paths.has(edge.target)) throw new Error("Invalid context graph edge reference");
return edge;
});
graphs.set(key, { nodes, edges });
}
}
const validatedGraphs = new Set(graphs.values());
const resolveGraph = (key: unknown): ContextGraph => {
const graph = typeof key === "string" ? graphs.get(key) : undefined;
if (!graph) throw new Error("Unknown context graph reference");
return graph;
};
const events = value.events.map((raw) => {
if (!isRecord(raw)) return parseThreadProjectionEvent(raw);
const event = { ...raw };
if (event.context_graph_ref !== undefined) {
if (event.context_graph !== undefined) throw new Error("Ambiguous context graph reference");
event.context_graph = resolveGraph(event.context_graph_ref);
delete event.context_graph_ref;
}
if (isRecord(event.context_snapshot) && event.context_snapshot.graph_ref !== undefined) {
if (event.context_snapshot.graph !== undefined) throw new Error("Ambiguous context graph reference");
const { graph_ref, ...snapshot } = event.context_snapshot;
event.context_snapshot = { ...snapshot, graph: resolveGraph(graph_ref) };
}
return parseThreadProjectionEvent(event, validatedGraphs);
});
const body: Record<string, unknown> = { ...value, projection: "events", events };
delete body.context_graphs;
delete body.context_graph_nodes;
delete body.context_graph_edges;
return body as unknown as WebuiThreadPersistedPayload;
}
function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDetailPayload {
@@ -432,7 +482,7 @@ function parseWebuiThreadTraceDetailPayload(value: unknown): WebuiThreadTraceDet
}
return {
message_id: value.message_id,
events: value.events.map(parseThreadProjectionEvent),
events: value.events.map((event) => parseThreadProjectionEvent(event)),
};
}
@@ -450,6 +500,7 @@ export async function fetchWebuiThread(
if (options?.before) params.set("before", options.before);
if (options?.after) params.set("after", options.after);
params.set("include_model_requests", "1");
params.set("context_graph_encoding", "references-v1");
const query = params.toString();
const suffix = query ? `?${query}` : "";
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
+100
View File
@@ -0,0 +1,100 @@
import type { ContextGraph, ContextGraphNode } from "@/lib/types";
import { forceCollide, forceLink, forceManyBody, forceSimulation, forceX, forceY, type SimulationNodeDatum } from "d3-force";
export interface GraphPosition { x: number; y: number }
export interface GraphParticle extends SimulationNodeDatum { path: string; radius: number; x: number; y: number }
// Obsidian display settings: center 0.52, repel 10, link strength 1, distance 250.
// Use 0.36 world units per reference unit to fit the compact panel.
const GRAPH_SCALE = 0.36;
const CENTER_STRENGTH = (Math.pow(0.01, 1 - 0.52) - 0.01) / 0.99;
/** Keep mutable simulation particles separate from immutable request snapshots. */
export function createGraphSimulation(graph: ContextGraph, previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {
const simulation = forceSimulation<GraphParticle>()
.alphaDecay(1 - Math.pow(0.001, 1 / 300)).velocityDecay(0.4)
// Force order matters: each force reads velocities written by the previous one.
.force("x", forceX<GraphParticle>(width / 2).strength(CENTER_STRENGTH))
.force("y", forceY<GraphParticle>(height / 2).strength(CENTER_STRENGTH))
.force("link", forceLink<GraphParticle, { source: string; target: string }>().id((node) => node.path).distance(250 * GRAPH_SCALE))
.force("charge", forceManyBody<GraphParticle>().strength(-Math.pow(10, 3) * GRAPH_SCALE ** 2))
.force("collision", forceCollide<GraphParticle>().radius(60 * GRAPH_SCALE).strength(0.5));
updateGraphSimulation(simulation, graph, previous, width, height);
return simulation;
}
export function updateGraphSimulation(simulation: ReturnType<typeof forceSimulation<GraphParticle>>, graph: ContextGraph,
previous: ReadonlyMap<string, GraphPosition>, width: number, height: number) {
const existing = new Map(simulation.nodes().map((node) => [node.path, node]));
const placed = new Map<string, GraphPosition>(existing);
const addedCount = graph.nodes.filter((node) => !existing.has(node.path)).length;
const area = (60 * GRAPH_SCALE) ** 2 * addedCount;
const outerRadius = Math.max(0, ...[...existing.values()].map((node) => Math.hypot(node.x - width / 2, node.y - height / 2)));
const ringWidth = Math.sqrt(area / Math.PI + outerRadius ** 2) - outerRadius;
const spread = Math.sqrt(area);
const adjacent = new Map<string, string[]>();
for (const edge of graph.edges) {
const sources = adjacent.get(edge.source) ?? [];
sources.push(edge.target); adjacent.set(edge.source, sources);
const targets = adjacent.get(edge.target) ?? [];
targets.push(edge.source); adjacent.set(edge.target, targets);
}
const nodes = graph.nodes.map((node): GraphParticle => {
const retained = existing.get(node.path);
if (retained) return retained;
const neighbours = (adjacent.get(node.path) ?? [])
.map((path) => placed.get(path)).filter((point): point is GraphPosition => !!point);
let position = previous.get(node.path);
if (!position && neighbours.length) position = {
x: neighbours.reduce((sum, point) => sum + point.x, 0) / neighbours.length + (Math.random() - 0.5) * spread,
y: neighbours.reduce((sum, point) => sum + point.y, 0) / neighbours.length + (Math.random() - 0.5) * spread,
};
if (!position) {
const angle = Math.random() * Math.PI * 2;
const radius = outerRadius + Math.sqrt(Math.random()) * ringWidth;
position = { x: width / 2 + Math.cos(angle) * radius, y: height / 2 + Math.sin(angle) * radius };
}
placed.set(node.path, position);
return { path: node.path, radius: 60 * GRAPH_SCALE, ...position };
});
const link = simulation.force<ReturnType<typeof forceLink<GraphParticle, { source: string; target: string }>>>("link")!;
// Clear old links before removing particles; D3 initializes forces inside nodes().
link.links([]);
simulation.nodes(nodes);
link.links(graph.edges.map((edge) => ({ ...edge })));
simulation.force<ReturnType<typeof forceCollide<GraphParticle>>>("collision")!.radius((node) => node.radius);
simulation.force<ReturnType<typeof forceX<GraphParticle>>>("x")!.x(width / 2);
simulation.force<ReturnType<typeof forceY<GraphParticle>>>("y")!.y(height / 2);
}
/** Preserve the simulation steps while bounding work per animated frame. */
export function advanceGraphSimulation(simulation: ReturnType<typeof createGraphSimulation>, elapsedMs: number, budgetMs = 8) {
// Advance physical time independently of painting cadence, but never spend an
// unbounded frame catching up after a hidden tab or a busy main thread.
const steps = Math.max(1, Math.floor(Math.min(elapsedMs, 100) * 240 / 1000));
const deadline = performance.now() + budgetMs;
for (let step = 0; step < steps; step++) {
if (simulation.alpha() <= simulation.alphaMin() && simulation.alphaTarget() === 0) break;
simulation.tick();
if (performance.now() >= deadline) break;
}
}
/** Finish the same finite layout in short slices without painting intermediate positions. */
export function startGraphSettlement(simulation: ReturnType<typeof createGraphSimulation>) {
simulation.stop().alpha(1).alphaTarget(0);
let remaining = Math.ceil(Math.log(simulation.alphaMin()) / Math.log(1 - simulation.alphaDecay()));
return (budgetMs = 4) => {
const deadline = performance.now() + budgetMs;
do { simulation.tick(); remaining--; } while (remaining > 0 && performance.now() < deadline);
if (remaining > 0) return false;
for (const node of simulation.nodes()) { node.vx = 0; node.vy = 0; }
simulation.alpha(0);
return true;
};
}
export function nodeRadius(node: ContextGraphNode): number {
return node.state === "discovered" ? 3.5 : Math.max(4, Math.min(12.5, Math.sqrt(node.tokens) * 0.215));
}
+47
View File
@@ -0,0 +1,47 @@
import type { ContextGraph, ContextGraphNode, ContextInspection, ContextSnapshot, UIMessage, UIModelRequestSnapshot } from "@/lib/types";
export function isContextGraph(value: unknown): value is ContextGraph {
if (!value || typeof value !== "object") return false;
const graph = value as Record<string, unknown>;
if (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) return false;
if (!graph.nodes.every((n: unknown) => {
if (!n || typeof n !== "object") return false;
const node = n as Record<string, unknown>;
return typeof node.path === "string" && typeof node.name === "string"
&& (node.state === "loaded" || node.state === "discovered")
&& typeof node.tokens === "number" && Number.isFinite(node.tokens) && node.tokens >= 0;
})) return false;
const paths = new Set(graph.nodes.map((n: ContextGraphNode) => n.path));
return graph.edges.every((e: unknown) => {
if (!e || typeof e !== "object") return false;
const edge = e as Record<string, unknown>;
return typeof edge.source === "string" && typeof edge.target === "string"
&& paths.has(edge.source) && paths.has(edge.target);
});
}
export function isContextInspection(value: unknown, validateGraph: typeof isContextGraph = isContextGraph): value is ContextInspection {
return typeof value === "object" && value !== null
&& "graph" in value && validateGraph(value.graph)
&& "estimated_tokens" in value && typeof value.estimated_tokens === "number"
&& Number.isFinite(value.estimated_tokens) && value.estimated_tokens >= 0
&& "context_window_tokens" in value && typeof value.context_window_tokens === "number"
&& Number.isFinite(value.context_window_tokens) && value.context_window_tokens > 0;
}
export function composerContextSnapshots(
messages: UIMessage[], requests: ReadonlyMap<string, UIModelRequestSnapshot>,
): ContextSnapshot[] {
const boundary = messages.filter((message) => message.compaction?.phase === "succeeded").at(-1);
const baseline = boundary?.compaction?.contextSnapshot;
const snapshots = Array.from(requests.entries()).sort((a, b) => a[1].createdAt - b[1].createdAt)
.flatMap(([turnId, request]) => (request.contextSnapshots ?? []).filter((snapshot) => {
if (!boundary) return true;
if (turnId === boundary.turnId) {
return snapshot.turnSeq !== undefined && boundary.compaction?.turnSeq !== undefined
&& snapshot.turnSeq > boundary.compaction.turnSeq;
}
return request.createdAt > boundary.createdAt;
}));
return [...(baseline ? [baseline] : []), ...snapshots];
}
+10 -2
View File
@@ -2,7 +2,7 @@ import type { UIMessage, UIModelRequestSnapshot } from "@/lib/types";
export type ComposerUsageSnapshot = Pick<UIMessage,
"id" | "turnId" | "createdAt" | "completedAt" | "usage" | "roundUsages" | "contextWindowTokens"
> & { compacted?: boolean };
> & { compacted?: boolean; estimatedContextTokens?: number };
export function reconcileModelRequest(
current: UIModelRequestSnapshot | undefined,
@@ -44,12 +44,20 @@ export function composerUsageSnapshots(
const compactionSeq = compactions.get(row.turnId!);
const compacted = compactions.has(row.turnId!) && !(snapshot.usageTurnSeq !== undefined
&& compactionSeq !== undefined && snapshot.usageTurnSeq > compactionSeq);
if (compacted) {
const baseline = messages.filter((message) => message.turnId === row.turnId
&& message.compaction?.phase === "succeeded").at(-1)?.compaction?.contextSnapshot;
return [{ id: row.id, turnId: row.turnId, createdAt: row.createdAt, compacted: true,
estimatedContextTokens: baseline?.estimatedTokens, contextWindowTokens: baseline?.contextWindowTokens }];
}
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 }];
return [{ id: row.id, createdAt: row.createdAt, compacted: true,
estimatedContextTokens: row.compaction.contextSnapshot?.estimatedTokens,
contextWindowTokens: row.compaction.contextSnapshot?.contextWindowTokens }];
}
if (row.role !== "assistant" || row.kind === "trace" || row.isStreaming) return [];
return [row];
+22
View File
@@ -0,0 +1,22 @@
import type { HTMLAttributes } from "react";
const MODIFIER_KEYS = new Set(["Shift", "Control", "Alt", "Meta", "CapsLock"]);
/** Preserve keyboard focus cues without treating Shift + wheel as navigation. */
export const surfaceFocusProps = {
onFocusCapture(event) {
if (event.target !== event.currentTarget) return;
if (event.currentTarget.matches(":focus-visible")) event.currentTarget.dataset.keyboardFocus = "true";
else delete event.currentTarget.dataset.keyboardFocus;
},
onBlurCapture(event) {
if (event.target === event.currentTarget) delete event.currentTarget.dataset.keyboardFocus;
},
onPointerDownCapture(event) {
delete event.currentTarget.dataset.keyboardFocus;
},
onKeyDownCapture(event) {
if (event.target === event.currentTarget && !MODIFIER_KEYS.has(event.key)
&& !event.ctrlKey && !event.metaKey && !event.altKey) event.currentTarget.dataset.keyboardFocus = "true";
},
} satisfies HTMLAttributes<HTMLElement>;
+14
View File
@@ -885,6 +885,11 @@ export function projectThreadEvent(
...(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 } : {}),
...(event.context_graph ? { contextSnapshots: [
...(previousRequest?.contextSnapshots ?? []).filter((s) => s.id !== event.request_id),
{ id: event.request_id, turnSeq: event.turn_seq, graph: event.context_graph, usage: event.request_usage === undefined
? (event.phase === "completed" ? event.round_usages?.at(-1) : undefined) : event.request_usage ?? undefined, contextWindowTokens: event.context_window_tokens },
] } : {}),
};
state.modelRequests = new Map(state.modelRequests).set(event.turn_id, modelRequest);
return state;
@@ -1024,6 +1029,10 @@ export function projectThreadEvent(
if (event.event === "context_compaction") {
Object.assign(state, closeThreadProjectionAnswer(state));
if (event.phase === "succeeded") {
state.modelRequests = new Map(Array.from(state.modelRequests, ([turn, request]) =>
[turn, { ...request, contextSnapshots: [] }]));
}
const id = `compaction-${event.compaction_id}`;
const existing = state.messages.findIndex((message) => message.id === id);
const message: UIMessage = {
@@ -1037,6 +1046,11 @@ export function projectThreadEvent(
phase: event.phase,
turnSeq: event.turn_seq,
reason: event.reason,
...(event.context_snapshot ? { contextSnapshot: {
id, graph: event.context_snapshot.graph,
estimatedTokens: event.context_snapshot.estimated_tokens,
contextWindowTokens: event.context_snapshot.context_window_tokens,
} } : {}),
...(!options.persisted ? { announce: true } : {}),
},
...positionedTurnFields(state.messages[existing], turnFieldsForProjection(state, event, "activity"), options),
+33 -1
View File
@@ -8,6 +8,7 @@ type Role = "user" | "assistant" | "tool" | "system";
type MessageKind = "message" | "trace" | "compaction";
export interface UIContextCompaction extends ContextCompaction {
contextSnapshot?: ContextSnapshot;
/** Lifecycle event sequence, independent of the row's display position. */
turnSeq?: number;
/** Live wire transitions announce; hydrated transcript rows stay silent. */
@@ -183,7 +184,35 @@ export interface UIMessage {
}
/** Turn-owned telemetry, not a transcript row or body-history source. */
export interface ContextGraphNode {
path: string;
name: string;
state: "loaded" | "discovered";
tokens: number;
}
export interface ContextGraph {
nodes: ContextGraphNode[];
edges: { source: string; target: string }[];
}
export interface ContextInspection {
graph: ContextGraph;
estimated_tokens: number;
context_window_tokens: number;
}
export interface ContextSnapshot {
turnSeq?: number;
estimatedTokens?: number;
id: string;
graph: ContextGraph;
usage?: TurnUsage;
contextWindowTokens?: number;
}
export interface UIModelRequestSnapshot {
contextSnapshots?: ContextSnapshot[];
runId: string;
sequence: number;
turnSeq?: number;
@@ -1546,7 +1575,8 @@ export type InboundEvent =
/** Optional structured payload on progress frames (channel-specific). */
agent_ui?: AgentUIBlob;
} & InboundTurnMetadata)
| (NotificationEvent & InboundTurnMetadata)
| (Exclude<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata)
| (Extract<NotificationEvent, { event: "context_compaction" }> & InboundTurnMetadata & { context_snapshot?: ContextInspection })
| ({
event: "file_edit";
chat_id: string;
@@ -1603,6 +1633,8 @@ export type InboundEvent =
}
| ({
event: "model_request";
request_usage?: TurnUsage | null;
context_graph?: ContextGraph;
chat_id: string;
request_id: string;
run_id: string;
+49 -2
View File
@@ -1,7 +1,54 @@
import { MemoryLruCache } from "./memory-lru-cache";
import { parseWebuiThreadPayload } from "./api";
import { readReloadCache, removeReloadCache, writeReloadCache } from "./reload-cache";
import type { WebuiThreadPersistedPayload } from "./types";
import type { ContextGraph, WebuiThreadPersistedPayload } from "./types";
/** Persist shared graph entities instead of expanding them in every replay frame. */
function reloadPayload(body: WebuiThreadPersistedPayload): unknown {
function table<T extends object>(key: (value: T) => string) {
const values: T[] = [];
const identities = new Map<T, number>();
const keys = new Map<string, number>();
return { values, index(value: T): number {
const known = identities.get(value);
if (known !== undefined) return known;
const valueKey = key(value);
let index = keys.get(valueKey);
if (index === undefined) {
index = values.length;
values.push(value);
keys.set(valueKey, index);
}
identities.set(value, index);
return index;
} };
}
const nodes = table<ContextGraph["nodes"][number]>((node) => JSON.stringify([node.path, node.name, node.tokens, node.state]));
const edges = table<ContextGraph["edges"][number]>((edge) => JSON.stringify([edge.source, edge.target]));
const references = new Map<ContextGraph, string>();
const graphs: Record<string, { nodes: number[]; edges: number[] }> = {};
const reference = (graph: ContextGraph): string => {
const known = references.get(graph);
if (known !== undefined) return known;
const key = String(references.size);
references.set(graph, key);
graphs[key] = { nodes: graph.nodes.map(nodes.index), edges: graph.edges.map(edges.index) };
return key;
};
const events = body.events.map((event) => {
if (event.event === "model_request" && event.context_graph) {
const { context_graph, ...rest } = event;
return { ...rest, context_graph_ref: reference(context_graph) };
}
if (event.event === "context_compaction" && event.context_snapshot) {
const { graph, ...snapshot } = event.context_snapshot;
return { ...event, context_snapshot: { ...snapshot, graph_ref: reference(graph) } };
}
return event;
});
return references.size ? { ...body, events, context_graphs: graphs,
context_graph_nodes: nodes.values, context_graph_edges: edges.values } : body;
}
/** Bounded canonical replay cache; the most recent snapshot also survives tab reloads. */
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
@@ -32,7 +79,7 @@ export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload
override set(key: string, body: WebuiThreadPersistedPayload): void {
super.set(key, body);
if (super.get(key)) writeReloadCache("thread", { key, body });
if (super.get(key)) writeReloadCache("thread", { key, body: reloadPayload(body) });
for (const listener of this.listeners.get(key) ?? []) listener(body);
}