perf(webui): revalidate prompt summaries and bound navigation work
This commit is contained in:
1 parent
bf1eada575
commit
f9a3e55b64
12 files changed
+235
-42
No files matched your search
@@ -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>;
|
||||
}
|
||||
});
|
||||
@@ -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
@@ -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(
|
||||
|
||||
@@ -1705,6 +1705,11 @@ export interface PromptSummary {
|
||||
turnId: string;
|
||||
}
|
||||
|
||||
export interface PromptIndex {
|
||||
prompts: PromptSummary[];
|
||||
revision?: string;
|
||||
}
|
||||
|
||||
export interface WebuiThreadPersistedPayload {
|
||||
schemaVersion: number;
|
||||
sessionKey?: string;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
Reference in new issue
Block a user