perf(webui): revalidate prompt summaries and bound navigation work

This commit is contained in:
Xubin Ren committed 2026-10-18 17:13:18 +08:00
1 parent bf1eada575
commit f9a3e55b64
12 files changed
+235 -42

No files matched your search

+1 -1
View File
@@ -60,7 +60,7 @@ The WebUI is served by the WebSocket channel on port `8765` by default. The gate
On wide conversation panes, the left message rail lists all saved prompts independently of the loaded message page. Scroll the rail to browse, hover to preview, and click to jump directly to a prompt; its edges fade without extending the conversation layout. The header's message navigation also supports searching the prompt summaries. Both lists render a visible window rather than thousands of controls. Older compatible hosts without `webui.prompt-navigation.v1` retain navigation within already-loaded messages.
Jumping reads a bounded page near the selected prompt, not every earlier answer. Browsing keeps at most three server pages, supports scrolling backward and forward, and the bottom arrow returns to the live conversation. A failed read leaves the current content intact and offers retry. The navigation index is a rebuildable, bounded summary cache over the WebUI display transcript; it does not change the SQLite session schema, agent context, configuration, or chat data. On first access to a long uncached conversation, building the summaries requires reading its transcript segments in a worker thread; later accesses reuse unchanged segment summaries.
Jumping reads a bounded page near the selected prompt, not every earlier answer. Browsing keeps at most three server pages, supports scrolling backward and forward, and the bottom arrow returns to the live conversation. A failed read leaves the current content intact and offers retry. The navigation index is a rebuildable, bounded summary cache over the WebUI display transcript; it does not change the SQLite session schema, agent context, configuration, or chat data. On first access to a long uncached conversation, building the summaries requires reading its transcript segments in a worker thread; later accesses reuse unchanged segment summaries. Unchanged directories use conditional requests without a response body. Changed directories transfer only the changed suffix when a previous snapshot is still cached; after a restart or cache eviction, the host sends a complete directory. These caches are held in memory and do not create another persistent chat store.
## Sharing access
+44 -3
View File
@@ -12,11 +12,12 @@ import shutil
import threading
import time
import uuid
from collections import OrderedDict
from dataclasses import dataclass
from datetime import datetime
from functools import lru_cache
from pathlib import Path
from typing import Any, Callable, Mapping, NamedTuple, Sequence, TypedDict, cast
from typing import Any, Callable, Mapping, NamedTuple, NotRequired, Sequence, TypedDict, cast
from urllib.parse import unquote, urlparse
from loguru import logger
@@ -2590,12 +2591,14 @@ class PromptSummary(TypedDict):
@lru_cache(maxsize=64)
def _chunk_prompt_summaries(path: Path, identity: tuple[int, int, int], start: int) -> tuple[PromptSummary, ...]:
del identity # Part of the cache key, not the contents of the summary.
# Stored records use compact JSON. A normal chunk already fits the page byte
# budget, so do not serialize all answer/tool bodies again just to count them.
check_turn_bytes = identity[2] > _MAX_TRANSCRIPT_PAGE_BYTES
result: list[PromptSummary] = []
turns = _split_transcript_turns(_read_transcript_file(path))
for ordinal, raw_turn in enumerate(turns, start):
turn, _ = _compact_completed_stream_deltas(raw_turn)
if len(turn) > _MAX_TRANSCRIPT_PAGE_RECORDS or _records_bytes(turn) > _MAX_TRANSCRIPT_PAGE_BYTES:
if len(turn) > _MAX_TRANSCRIPT_PAGE_RECORDS or (check_turn_bytes and _records_bytes(turn) > _MAX_TRANSCRIPT_PAGE_BYTES):
turn = _trim_oversized_turn(
turn, max_records=_MAX_TRANSCRIPT_PAGE_RECORDS,
max_bytes=_MAX_TRANSCRIPT_PAGE_BYTES,
@@ -2654,3 +2657,41 @@ def build_prompt_index(session_key: str) -> list[PromptSummary]:
result.extend(_chunk_prompt_summaries(path, (stat.st_ino, stat.st_mtime_ns, stat.st_size), start))
start += count
return result
# Short-lived response snapshots share the chunk summaries; they do not retain
# full transcripts or write another durable representation of the conversation.
_PROMPT_SNAPSHOTS: OrderedDict[tuple[Path, str], tuple[PromptSummary, ...]] = OrderedDict()
_PROMPT_SNAPSHOT_LOCK = threading.Lock()
class PromptIndexResponse(TypedDict):
prompts: Sequence[PromptSummary]
replaceFrom: int
revision: NotRequired[str | None]
def prompt_index_response(session_key: str, previous_revision: str | None) -> PromptIndexResponse:
path = webui_transcript_path(session_key)
revision = webui_transcript_revision(session_key)
with _PROMPT_SNAPSHOT_LOCK:
previous = _PROMPT_SNAPSHOTS.get((path, previous_revision)) if previous_revision else None
current = _PROMPT_SNAPSHOTS.get((path, revision)) if revision else None
if current is None:
current = tuple(build_prompt_index(session_key))
# Do not label a read made across an append/rotation as one stable revision.
if revision != webui_transcript_revision(session_key):
return {"prompts": current, "replaceFrom": 0}
if revision:
with _PROMPT_SNAPSHOT_LOCK:
_PROMPT_SNAPSHOTS[path, revision] = current
_PROMPT_SNAPSHOTS.move_to_end((path, revision))
while len(_PROMPT_SNAPSHOTS) > 8:
_PROMPT_SNAPSHOTS.popitem(last=False)
replace_from = 0
if previous is not None:
for old, new in zip(previous, current):
if old != new:
break
replace_from += 1
return {"prompts": current[replace_from:], "replaceFrom": replace_from, "revision": revision}
+13 -3
View File
@@ -1042,7 +1042,7 @@ class GatewayHTTPHandler:
return {"sessions": cleaned}
def _handle_prompt_index_get(self, request: WsRequest, key: str) -> Response:
from nanobot.webui.transcript import build_prompt_index
from nanobot.webui.transcript import prompt_index_response, webui_transcript_revision
if not self.check_api_token(request):
return _http_error(401, "Unauthorized")
@@ -1051,10 +1051,20 @@ class GatewayHTTPHandler:
return _http_error(400, "invalid session key")
if not _is_websocket_channel_session_key(decoded_key):
return _http_error(404, "session not found")
revision = webui_transcript_revision(decoded_key)
etag = _quoted_etag(revision) if revision else None
if etag and _etag_matches(_case_insensitive_header(request.headers, "If-None-Match"), etag):
return _http_response(b"", status=304, extra_headers=[*_NO_STORE_HEADERS, ("ETag", etag)])
query = _parse_query(request.path)
data = prompt_index_response(decoded_key, _query_first(query, "since"))
headers = list(_NO_STORE_HEADERS)
response_revision = data.get("revision")
if response_revision:
headers.append(("ETag", _quoted_etag(response_revision)))
return _http_json_response(
{"prompts": build_prompt_index(decoded_key)},
dict(data),
accept_encoding=_combined_list_header(request.headers, "Accept-Encoding"),
extra_headers=list(_NO_STORE_HEADERS),
extra_headers=headers,
)
async def _handle_webui_thread_get_async(self, request: WsRequest, key: str) -> Response:
+35
View File
@@ -80,6 +80,12 @@ async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path,
transcript.append_transcript_object("websocket:test", {"event": "user", "chat_id": "test", "text": "hello"})
response = await gateway.http._dispatch_session_routes(Request(path + "/prompts", headers), path + "/prompts")
prompt = json.loads(response.body)["prompts"][0]
revision = json.loads(response.body)["revision"]
revalidate = Headers([("Authorization", "Bearer test-token"), ("If-None-Match", f'"{revision}"')])
unchanged = await gateway.http._dispatch_session_routes(Request(path + "/prompts", revalidate), path + "/prompts")
assert unchanged.status_code == 304 and not unchanged.body
denied = await gateway.http._dispatch_session_routes(Request(path + "/prompts", Headers([("If-None-Match", f'"{revision}"')])), path + "/prompts")
assert denied.status_code == 401
current = await gateway.http._dispatch_session_routes(Request(path + "?after=" + prompt["cursor"], headers), path)
legacy = await gateway.http._dispatch_session_routes(Request(path + "?direction=latest&limit=40", headers), path)
assert current.status_code == legacy.status_code == 200
@@ -87,3 +93,32 @@ async def test_navigation_public_routes_auth_validation_and_old_reads(tmp_path,
invalid = await gateway.http._dispatch_session_routes(Request(path + "?after=bad", headers), path)
assert invalid.status_code == 400
assert "webui.prompt-navigation.v1" in webui_contract()["capabilities"]
def test_summary_deltas_rebuild_after_append_rewrite_eviction_and_delete(tmp_path, monkeypatch):
monkeypatch.setattr("nanobot.config.paths.get_data_dir", lambda: tmp_path)
key = "websocket:index-delta"
for i in range(100):
transcript.append_transcript_object(key, {"event": "user", "text": f"question {i}", "turn_id": f"t{i}"})
transcript.append_transcript_object(key, {"event": "turn_end", "turn_id": f"t{i}"})
initial = transcript.prompt_index_response(key, None)
assert len(initial["prompts"]) == 100
transcript.append_transcript_object(key, {"event": "user", "text": "next", "turn_id": "next"})
appended = transcript.prompt_index_response(key, initial["revision"])
assert appended["replaceFrom"] == 100
assert len(appended["prompts"]) == 1
assert [*initial["prompts"], *appended["prompts"]] == transcript.build_prompt_index(key)
# A late answer changes the last preview; it must replace that prompt, not append it.
transcript.append_transcript_object(key, {"event": "message", "text": "answer", "turn_id": "next"})
changed = transcript.prompt_index_response(key, appended["revision"])
assert changed["replaceFrom"] == 100
assert changed["prompts"][0]["answerPreview"] == "answer"
transcript.delete_webui_transcript(key)
transcript.append_transcript_object(key, {"event": "user", "text": "replacement"})
replaced = transcript.prompt_index_response(key, changed["revision"])
assert replaced["replaceFrom"] == 0
assert len(replaced["prompts"]) == 1
transcript._PROMPT_SNAPSHOTS.clear() # Restart/eviction sends a complete response.
assert transcript.prompt_index_response(key, replaced["revision"])["replaceFrom"] == 0
transcript.delete_webui_transcript(key)
assert transcript.prompt_index_response(key, replaced["revision"])["prompts"] == ()
+32 -3
View File
@@ -1,4 +1,4 @@
import { useState } from "react";
import { useEffect, useState } from "react";
import { createRoot } from "react-dom/client";
import { MessageBubble } from "@/components/MessageBubble";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
@@ -6,6 +6,8 @@ import { ThreadViewport } from "@/components/thread/ThreadViewport";
import { usePromptHistory } from "@/hooks/usePromptHistory";
import { ClientProvider } from "@/providers/ClientProvider";
import { NanobotClient } from "@/lib/nanobot-client";
import { fetchWebuiThread } from "@/lib/api";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initializeI18n } from "@/i18n";
@@ -56,9 +58,36 @@ const railHistory: UIMessage[] = Array.from({ length: 5 }, (_, index) => [
{ id: `a${1995 + index}`, role: "assistant" as const, content: "A synthetic answer.\n\n".repeat(8), createdAt: index + 1 },
]).flat();
function RailFixture() {
const navigation = usePromptHistory("websocket:rail", 1, railHistory);
const [messages, setMessages] = useState(parameters.has("real") ? [] : railHistory);
const [version, setVersion] = useState(1);
const [streaming, setStreaming] = useState(false);
useEffect(() => {
if (!parameters.has("real")) return;
const controller = new AbortController();
void fetchWebuiThread("fixture", "websocket:rail", { limit: 40, signal: controller.signal }).then((page) => {
if (page && !controller.signal.aborted) setMessages(projectThreadEvents(page.events));
});
return () => controller.abort();
}, []);
useEffect(() => {
if (!streaming) return;
let count = 0;
const user: UIMessage = { id: "stream-user", role: "user", content: "Streaming question", createdAt: Date.now() };
const timer = window.setInterval(() => {
count++;
setMessages((current) => [...current.filter((message) => message.id !== "stream-user" && message.id !== "stream-answer"), user,
{ id: "stream-answer", role: "assistant", content: "Streaming text. ".repeat(count), createdAt: user.createdAt + 1, isStreaming: count < 120 }]);
if (count === 120) setStreaming(false);
}, 16);
return () => window.clearInterval(timer);
}, [streaming]);
const navigation = usePromptHistory(messages.length ? "websocket:rail" : null, version, messages);
return <main style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
<ThreadViewport messages={railHistory} isStreaming={false} conversationKey="websocket:rail"
{parameters.has("real") && <div>
<button onClick={() => setVersion((value) => value + 1)}>Refresh index</button>
<button onClick={() => setStreaming(true)} disabled={streaming}>{streaming ? "Streaming" : "Simulate stream"}</button>
</div>}
<ThreadViewport messages={messages} isStreaming={streaming} conversationKey="websocket:rail"
navigation={parameters.has("short") ? undefined : navigation}
composer={<div style={{ height: 100, border: "1px solid #ddd", borderRadius: 20, padding: 20 }}>Message nanobot</div>} />
</main>;
+3 -3
View File
@@ -46,18 +46,18 @@ test("complete rail scrolls independently, jumps to unloaded history and returns
await expect(first).toBeFocused();
await first.press("Enter");
await expect(body.getByText("Question 0", { exact: true })).toBeInViewport();
expect(reads).toEqual(["?limit=40&after=0"]);
expect(reads).toEqual(["?limit=24&after=0"]);
await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0);
for (const after of [10, 20, 30, 40]) {
await body.hover();
await page.mouse.wheel(0, 10000);
await expect.poll(() => reads.some((query) => query === `?limit=40&after=${after}`)).toBe(true);
await expect.poll(() => reads.some((query) => query === `?limit=24&after=${after}`)).toBe(true);
await expect(body.getByText(`Question ${after + 9}`, { exact: true })).toBeAttached();
}
expect(await body.locator("[data-user-prompt-id]").count()).toBeLessThanOrEqual(30);
await body.hover();
await page.mouse.wheel(0, -100000);
await expect.poll(() => reads.some((query) => query.startsWith("?limit=40&before="))).toBe(true);
await expect.poll(() => reads.some((query) => query.startsWith("?limit=24&before="))).toBe(true);
await page.getByRole("button", { name: "Scroll to bottom" }).click();
await expect(body.getByText("Question 1999", { exact: true })).toBeVisible();
await expect(rail.locator('[aria-current="location"]')).toBeInViewport();
+25 -12
View File
@@ -1,10 +1,10 @@
import { type RefObject, useEffect, useMemo, useRef, useState } from "react";
import { memo, type RefObject, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { MarkdownText } from "@/components/MarkdownText";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { cn } from "@/lib/utils";
import type { UIMessage } from "@/lib/types";
import { type PromptAnchor, promptTop, userPromptAnchors } from "./promptNavigation";
import { type PromptAnchor, userPromptAnchors } from "./promptNavigation";
interface PromptRailProps {
bottomOffset: number;
@@ -19,9 +19,12 @@ const EDGE = 20;
const WIDTHS = [28, 22, 16, 11];
/** Complete logical list; only the visible markers and one preview are mounted. */
export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, scrollRef }: PromptRailProps) {
export const PromptRail = memo(function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, scrollRef }: PromptRailProps) {
const { t } = useTranslation();
const anchors = useMemo(() => prompts ?? userPromptAnchors(messages), [prompts, messages]);
const anchorPositions = useMemo(() => new Map(anchors.map((anchor, index) => [anchor.id, index])), [anchors]);
// Assistant token updates do not change which user elements need observation.
const userIds = messages.filter((message) => message.role === "user").map((message) => message.id).join("\n");
const railRef = useRef<HTMLDivElement>(null);
const inside = useRef(false);
const [height, setHeight] = useState(300);
@@ -49,6 +52,7 @@ export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, sc
// Measure only mounted messages, not the complete navigation index.
let positions: { id: string; top: number }[] = [];
let frame = 0;
let dirty = false;
const update = () => {
const cursor = scroller.scrollTop + 96;
let low = 0;
@@ -61,16 +65,25 @@ export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, sc
setActiveId(positions[Math.max(0, high)]?.id ?? null);
};
const measure = () => {
const scrollerTop = scroller.getBoundingClientRect().top;
const scrollTop = scroller.scrollTop;
positions = Array.from(scroller.querySelectorAll<HTMLElement>("[data-user-prompt-id]"),
(element) => ({ id: element.dataset.userPromptId!, top: promptTop(scroller, element) - 16 }));
(element) => {
const top = element.getBoundingClientRect().top;
return { id: element.dataset.userPromptId!, top: (scrollerTop || top ? top - scrollerTop + scrollTop : element.offsetTop) - 16 };
});
update();
};
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(update);
if (frame) return;
frame = requestAnimationFrame(() => {
frame = 0;
if (dirty) { dirty = false; measure(); }
else update();
});
};
measure();
const observer = new ResizeObserver(measure);
const observer = new ResizeObserver(() => { dirty = true; schedule(); });
observer.observe(scroller);
if (scroller.firstElementChild) observer.observe(scroller.firstElementChild);
scroller.addEventListener("scroll", schedule, { passive: true });
@@ -79,17 +92,17 @@ export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, sc
observer.disconnect();
scroller.removeEventListener("scroll", schedule);
};
}, [messages, scrollRef]);
}, [userIds, scrollRef]);
useEffect(() => {
if (inside.current) return;
const rail = railRef.current;
const index = anchors.findIndex((item) => item.id === activeId);
if (rail && index >= 0) {
const index = activeId ? anchorPositions.get(activeId) : undefined;
if (rail && index !== undefined) {
rail.scrollTop = Math.max(0, padding + index * GAP - height / 2);
setScrollTop(rail.scrollTop);
}
}, [activeId, anchors, height, padding]);
}, [activeId, anchorPositions, height, padding]);
if (anchors.length < 2) return null;
const preview = focused === null ? undefined : anchors[focused];
@@ -148,4 +161,4 @@ export function PromptRail({ bottomOffset, messages, prompts, onJumpToPrompt, sc
</div> : null}
</div> : null}
</div>;
}
});
+20 -9
View File
@@ -5,7 +5,7 @@ import { projectThreadEvents } from "@/lib/thread-event-projection";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { isModelCommandText } from "@/lib/format";
import { isSystemCommandTurnId } from "@/lib/nanobot-client";
import type { UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import type { PromptIndex, UIMessage, WebuiThreadPersistedPayload } from "@/lib/types";
import { type PromptAnchor, userPromptAnchors } from "@/components/thread/promptNavigation";
interface HistoryPage {
@@ -38,6 +38,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
const { client, getToken, webuiCapabilities } = useClient();
const enabled = !!key && webuiCapabilities.includes("webui.prompt-navigation.v1");
const [index, setIndex] = useState<{ key: string; prompts: PromptAnchor[] } | null>(null);
const indexSnapshot = useRef<PromptIndex>();
const [pages, setPages] = useState<HistoryPage[]>([]);
const [target, setTarget] = useState<PromptHistoryNavigation["target"]>(null);
const [loading, setLoading] = useState(false);
@@ -63,6 +64,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
scope.current = { key, client };
latest();
setIndex(null);
indexSnapshot.current = undefined;
setIndexError(null);
return () => request.current?.abort();
}, [key, client, enabled, latest]);
@@ -70,9 +72,11 @@ export function usePromptHistory(key: string | null, version: number, messages:
useEffect(() => {
if (!enabled || !key) return;
const controller = new AbortController();
void fetchPromptIndex(getToken(), key, controller.signal).then((items) => {
void fetchPromptIndex(getToken(), key, controller.signal, indexSnapshot.current).then((snapshot) => {
if (controller.signal.aborted) return;
setIndex({ key, prompts: items.filter((item) => !isSystemCommandTurnId(item.turnId) && !isModelCommandText(item.preview)).map((item, position) => ({ ...item, index: position,
if (snapshot === indexSnapshot.current) { setIndexError(null); return; }
indexSnapshot.current = snapshot;
setIndex({ key, prompts: snapshot.prompts.filter((item) => !isSystemCommandTurnId(item.turnId) && !isModelCommandText(item.preview)).map((item, position) => ({ ...item, index: position,
label: item.preview.replace(/\s+/g, " ").slice(0, 80) || `Prompt ${position + 1}`,
})) });
setIndexError(null);
@@ -83,17 +87,24 @@ export function usePromptHistory(key: string | null, version: number, messages:
return () => controller.abort();
}, [client, enabled, getToken, key, version, refresh]);
const indexedIds = useMemo(() => new Set(index?.prompts.map((prompt) => prompt.id)), [index]);
const localCache = useRef<{ index: typeof index; users: UIMessage[]; prompts: PromptAnchor[] }>();
const prompts = useMemo(() => {
if (!enabled) return userPromptAnchors(messages);
if (!currentScope || index?.key !== key) return [];
// Keep live prompts and legacy prompts backfilled by the history reader
// navigable, even when they have no persisted transcript cursor yet.
const ids = new Set(index.prompts.map((prompt) => prompt.id));
const local = userPromptAnchors(messages).filter((prompt) => !ids.has(prompt.id));
if (!local.length) return index.prompts;
return [...index.prompts, ...local].sort((a, b) => a.createdAt - b.createdAt)
const users = messages.filter((message) => message.role === "user" && !indexedIds.has(message.id));
if (!users.length) return index.prompts;
const cached = localCache.current;
if (cached?.index === index && users.length === cached.users.length
&& users.every((user, position) => user === cached.users[position])) return cached.prompts;
const local = userPromptAnchors(messages).filter((prompt) => !indexedIds.has(prompt.id));
const merged = [...index.prompts, ...local].sort((a, b) => a.createdAt - b.createdAt)
.map((prompt, position) => ({ ...prompt, index: position }));
}, [currentScope, enabled, index, key, messages]);
localCache.current = { index, users, prompts: merged };
return merged;
}, [currentScope, enabled, index, indexedIds, key, messages]);
const updateMessages = useCallback((update: (messages: UIMessage[]) => UIMessage[]) => {
setPages((current) => current.map((page) => ({ ...page, messages: update(page.messages) })));
@@ -109,7 +120,7 @@ export function usePromptHistory(key: string | null, version: number, messages:
retry.current = () => { void read(cursor, direction, id); };
try {
const body = await fetchWebuiThread(getToken(), key, {
[direction]: cursor, limit: 40, signal: controller.signal,
[direction]: cursor, limit: 24, signal: controller.signal,
});
if (controller.signal.aborted) return;
if (!body) throw new Error("History is no longer available");
+15 -5
View File
@@ -21,7 +21,7 @@ import type {
ModelConfigurationUpdate,
NetworkSafetySettingsUpdate,
PairingPayload,
PromptSummary,
PromptIndex,
ProviderCreationUpdate,
ProviderModelsPayload,
ProviderOAuthCompletionResult,
@@ -438,14 +438,22 @@ export async function fetchWebuiThread(
return parseWebuiThreadPayload(await res.json());
}
export async function fetchPromptIndex(token: string, key: string, signal: AbortSignal): Promise<PromptSummary[]> {
const res = await fetchWithTimeout(`/api/sessions/${encodeURIComponent(key)}/webui-thread/prompts`, {
headers: { Authorization: `Bearer ${token}` }, credentials: "same-origin", cache: "no-store", signal,
export async function fetchPromptIndex(token: string, key: string, signal: AbortSignal, cached?: PromptIndex): Promise<PromptIndex> {
const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
const query = cached?.revision ? `?since=${encodeURIComponent(cached.revision)}` : "";
if (cached?.revision) headers["If-None-Match"] = `"${cached.revision}"`;
const res = await fetchWithTimeout(`/api/sessions/${encodeURIComponent(key)}/webui-thread/prompts${query}`, {
headers, credentials: "same-origin", cache: "no-store", signal,
});
if (res.status === 304 && cached) return cached;
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
const body: unknown = await res.json();
if (!isRecord(body) || !Array.isArray(body.prompts)) throw new Error("Invalid prompt index");
return body.prompts.map((item: unknown) => {
const replaceFrom = body.replaceFrom ?? 0;
if (typeof replaceFrom !== "number" || !Number.isSafeInteger(replaceFrom)
|| replaceFrom < 0 || replaceFrom > (cached?.prompts.length ?? 0)
|| (body.revision != null && typeof body.revision !== "string")) throw new Error("Invalid prompt index revision");
const prompts = body.prompts.map((item: unknown) => {
if (!isRecord(item) || typeof item.id !== "string" || typeof item.preview !== "string"
|| typeof item.answerPreview !== "string" || typeof item.cursor !== "string" || typeof item.turnId !== "string"
|| typeof item.createdAt !== "number" || !Number.isFinite(item.createdAt)) {
@@ -454,6 +462,8 @@ export async function fetchPromptIndex(token: string, key: string, signal: Abort
return { id: item.id, preview: item.preview, answerPreview: item.answerPreview,
cursor: item.cursor, createdAt: item.createdAt, turnId: item.turnId };
});
return { prompts: [...(cached?.prompts.slice(0, replaceFrom) ?? []), ...prompts],
revision: typeof body.revision === "string" ? body.revision : undefined };
}
export async function fetchWebuiThreadTraceDetail(
+5
View File
@@ -1705,6 +1705,11 @@ export interface PromptSummary {
turnId: string;
}
export interface PromptIndex {
prompts: PromptSummary[];
revision?: string;
}
export interface WebuiThreadPersistedPayload {
schemaVersion: number;
sessionKey?: string;
+21
View File
@@ -24,6 +24,7 @@ import {
fetchMarketplaceSkillTrends,
fetchNanobotFeatures,
fetchProviderModels,
fetchPromptIndex,
fetchSessionAutomations,
fetchSettingsUsage,
fetchSidebarState,
@@ -124,6 +125,26 @@ describe("webui API helpers", () => {
);
});
it("revalidates prompt summaries and replaces only the changed suffix", async () => {
const prompt = { id: "u1", preview: "question", answerPreview: "", cursor: "cursor", turnId: "t1", createdAt: 1 };
const cached = { revision: "first", prompts: [prompt] };
const signal = new AbortController().signal;
vi.mocked(fetch).mockResolvedValueOnce({ status: 304 } as Response);
await expect(fetchPromptIndex("tok", "websocket:chat-1", signal, cached)).resolves.toBe(cached);
expect(fetch).toHaveBeenLastCalledWith("/api/sessions/websocket%3Achat-1/webui-thread/prompts?since=first",
expect.objectContaining({ headers: { Authorization: "Bearer tok", "If-None-Match": '"first"' }, cache: "no-store" }));
vi.mocked(fetch).mockResolvedValueOnce({ ok: true, json: async () => ({
revision: "second", replaceFrom: 1, prompts: [{ ...prompt, id: "u2" }],
}) } as Response);
const appended = await fetchPromptIndex("tok", "websocket:chat-1", signal, cached);
expect(appended.prompts.map((item) => item.id)).toEqual(["u1", "u2"]);
expect(appended.prompts[0]).toBe(prompt);
vi.mocked(fetch).mockResolvedValueOnce({ ok: true, json: async () => ({ revision: "third", replaceFrom: 1, prompts: [] }) } as Response);
expect((await fetchPromptIndex("tok", "websocket:chat-1", signal, appended)).prompts).toEqual([prompt]);
vi.mocked(fetch).mockResolvedValueOnce({ ok: true, json: async () => ({ replaceFrom: 2, prompts: [] }) } as Response);
await expect(fetchPromptIndex("tok", "websocket:chat-1", signal, cached)).rejects.toThrow("Invalid prompt index revision");
});
it("revalidates a cached WebUI thread and reuses it on 304", async () => {
const cached = {
schemaVersion: 3,
+21 -3
View File
@@ -24,7 +24,7 @@ function wrapper(enabled = true) {
webuiCapabilities={enabled ? ["webui.prompt-navigation.v1"] : []}>{children}</ClientProvider>;
}
beforeEach(() => {
vi.mocked(api.fetchPromptIndex).mockReset().mockResolvedValue(index);
vi.mocked(api.fetchPromptIndex).mockReset().mockResolvedValue({ prompts: index, revision: "first" });
vi.mocked(api.fetchWebuiThread).mockReset().mockImplementation(async (_token, _key, options) => {
if (typeof options === "string") throw new Error("expected page options");
return page(Number(options?.after ?? Number(options?.before) - 1));
@@ -48,7 +48,7 @@ it("loads the complete index without bodies, reads bounded windows and leaves li
await act(async () => result.current.older());
expect(result.current.window?.userMessageOffset).toBe(505);
expect(result.current.window?.messages).toHaveLength(6);
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "506", limit: 40 }));
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith("test", "a", expect.objectContaining({ before: "506", limit: 24 }));
act(() => result.current.latest());
expect(result.current.window).toBeNull();
expect(latest).toHaveLength(1);
@@ -88,7 +88,7 @@ it("does not request new endpoints from an older compatible host", () => {
});
it("keeps legacy backfilled and newly sent prompts navigable without a transcript cursor", async () => {
vi.mocked(api.fetchPromptIndex).mockResolvedValue([]);
vi.mocked(api.fetchPromptIndex).mockResolvedValue({ prompts: [] });
const { result, rerender } = renderHook(({ messages }) => usePromptHistory("a", 1, messages), {
wrapper: wrapper(), initialProps: { messages: latest },
});
@@ -98,3 +98,21 @@ it("keeps legacy backfilled and newly sent prompts navigable without a transcrip
act(() => result.current.jump("live-user"));
expect(api.fetchWebuiThread).not.toHaveBeenCalled();
});
it("reuses the full directory during token updates and conditional revalidation", async () => {
const user: UIMessage = { id: "live", role: "user", content: "new question", createdAt: 2001 };
const { result, rerender } = renderHook(({ version, messages }) => usePromptHistory("a", version, messages), {
wrapper: wrapper(), initialProps: { version: 1, messages: [...latest, user] },
});
await waitFor(() => expect(result.current.prompts).toHaveLength(2001));
const anchors = result.current.prompts;
for (let chunk = 0; chunk < 100; chunk++) {
rerender({ version: 1, messages: [...latest, user, { id: "answer", role: "assistant", content: String(chunk), createdAt: 2002 }] });
expect(result.current.prompts).toBe(anchors);
}
expect(api.fetchPromptIndex).toHaveBeenCalledTimes(1);
rerender({ version: 2, messages: [...latest, user] });
await waitFor(() => expect(api.fetchPromptIndex).toHaveBeenCalledTimes(2));
expect(api.fetchPromptIndex).toHaveBeenLastCalledWith("test", "a", expect.any(AbortSignal), { prompts: index, revision: "first" });
expect(result.current.prompts).toBe(anchors);
});