Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): search loaded message text in Ctrl+K
chengyongrue821144c7eb4
diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxindex e9908dd1d..caf6b33aa 100644--- a/webui/browser/fixture.tsx+++ b/webui/browser/fixture.tsx@@ -40,6 +40,7 @@ import { MobileChatLayoutFixture } from "./mobile-chat-layout-fixture";import { ThemeToggleFixture } from "./theme-toggle-fixture";import { DisplayMathFixture } from "./display-math-fixture";import { AttachmentLayoutFixture } from "./attachment-layout-fixture";+import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";const history: UIMessage[] = [{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },@@ -213,7 +214,9 @@ if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi()if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();await initializeI18n();createRoot(document.getElementById("root")!).render(<TooltipProvider>- {parameters.get("case") === "attachments"+ {parameters.get("case") === "loaded-session-search"+ ? <LoadedSessionSearchFixture />+ : parameters.get("case") === "attachments"? <AttachmentLayoutFixture />: parameters.get("case") === "theme-toggle"? <ClientProvider client={railClient} token="fixture"><ThemeToggleFixture /></ClientProvider>diff --git a/webui/browser/loaded-session-search-fixture.tsx b/webui/browser/loaded-session-search-fixture.tsxnew file mode 100644index 000000000..d104fe8f1--- /dev/null+++ b/webui/browser/loaded-session-search-fixture.tsx@@ -0,0 +1,42 @@+import { useEffect, useState } from "react";+import { SessionSearchDialog } from "@/components/SessionSearchDialog";+import { useAppViewport } from "@/hooks/useAppViewport";+import { ThreadMessageCache } from "@/lib/thread-message-cache";+import { ThreadTranscript } from "@/lib/thread-transcript";+import type { ChatSummary } from "@/lib/types";++const sessions: ChatSummary[] = Array.from({ length: 1000 }, (_, index) => ({+ key: `websocket:topic-${index}`, chatId: `topic-${index}`, channel: "websocket",+ title: `Topic ${index}`, preview: `Preview ${index}`, createdAt: null, updatedAt: null,+}));++export function LoadedSessionSearchFixture() {+ useAppViewport();+ const [open, setOpen] = useState(false);+ const [selected, setSelected] = useState<string | null>(null);+ const [cache] = useState(() => {+ const value = new ThreadMessageCache(() => false);+ value.set("topic-1", new ThreadTranscript([+ { id: "user", role: "user", content: "我们讨论权限与配对", createdAt: 1 },+ { id: "answer", role: "assistant", content: `${"Earlier notes. ".repeat(500)}Use Full Access at 25% in session_history.py`, createdAt: 2 },+ ]).save());+ return value;+ });+ useEffect(() => {+ const shortcut = (event: KeyboardEvent) => {+ if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "k") {+ event.preventDefault();+ setOpen(true);+ }+ };+ window.addEventListener("keydown", shortcut);+ return () => window.removeEventListener("keydown", shortcut);+ }, []);+ return <main className="h-[100dvh] bg-background p-6 text-foreground">+ <button onClick={() => setOpen(true)}>Search</button>+ <textarea aria-label="Draft" defaultValue="Keep this unsent draft" className="block" />+ <output aria-label="Selected topic">{selected}</output>+ <SessionSearchDialog open={open} onOpenChange={setOpen} sessions={sessions}+ activeKey={selected} loading={false} messageCache={cache} onSelect={setSelected} />+ </main>;+}diff --git a/webui/browser/loaded-session-search.spec.ts b/webui/browser/loaded-session-search.spec.tsnew file mode 100644index 000000000..d6dced1a6--- /dev/null+++ b/webui/browser/loaded-session-search.spec.ts@@ -0,0 +1,37 @@+import { expect, test } from "@playwright/test";++for (const viewport of [{ width: 1280, height: 800 }, { width: 390, height: 844 }]) {+ test(`searches only loaded body text without requests at ${viewport.width}px`, async ({ page }) => {+ await page.setViewportSize(viewport);+ const apiRequests: string[] = [];+ const errors: string[] = [];+ page.on("request", (request) => { if (new URL(request.url()).pathname.startsWith("/api/")) apiRequests.push(request.url()); });+ page.on("pageerror", (error) => errors.push(error.message));+ await page.goto("/browser/fixture.html?case=loaded-session-search");+ await page.getByRole("button", { name: "Search", exact: true }).waitFor();+ await page.keyboard.press("Control+k");+ const dialog = page.getByRole("dialog", { name: "Search", exact: true });+ const input = dialog.getByRole("textbox", { name: "Search", exact: true });+ await expect(dialog.getByRole("button")).toHaveCount(24);+ for (const query of ["权限", "full access", "25%", "session_history.py"]) {+ await input.fill(query);+ await expect(dialog.getByRole("button")).toHaveCount(1);+ await expect(dialog.getByText("Topic 1", { exact: true })).toBeVisible();+ await expect(dialog.getByText(query === "权限" ? "我们讨论权限与配对" : /Use Full Access at 25%/)).toBeVisible();+ }+ await input.fill("unloaded server content");+ await expect(dialog.getByText("No matching topics.")).toBeVisible();+ await input.fill("权限");+ const box = await dialog.boundingBox();+ expect(box).not.toBeNull();+ expect(box!.x).toBeGreaterThanOrEqual(0);+ expect(box!.x + box!.width).toBeLessThanOrEqual(viewport.width);+ await dialog.screenshot({ path: test.info().outputPath(`loaded-search-${viewport.width}.png`) });+ await input.press("Enter");+ await expect(dialog).not.toBeVisible();+ await expect(page.getByLabel("Selected topic")).toHaveText("websocket:topic-1");+ await expect(page.getByRole("textbox", { name: "Draft" })).toHaveValue("Keep this unsent draft");+ expect(apiRequests).toEqual([]);+ expect(errors).toEqual([]);+ });+}diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex a95fedef3..3b48fda9f 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -2958,6 +2958,7 @@ function Shell({activeKey={activeKey}loading={loading}titleOverrides={sidebarState.title_overrides}+ messageCache={threadMessageCache}onSelect={onSelectSearchResult}/></Suspense>diff --git a/webui/src/components/SessionSearchDialog.tsx b/webui/src/components/SessionSearchDialog.tsxindex 5a4ff6cfa..62cea5ab2 100644--- a/webui/src/components/SessionSearchDialog.tsx+++ b/webui/src/components/SessionSearchDialog.tsx@@ -1,4 +1,4 @@-import { type KeyboardEvent, useEffect, useMemo, useRef, useState } from "react";+import { type KeyboardEvent, useDeferredValue, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";import { Search } from "lucide-react";import { useTranslation } from "react-i18next";@@ -9,6 +9,8 @@ import {DialogTitle,} from "@/components/ui/dialog";import { deriveTitle, visibleSessionPreview } from "@/lib/format";+import { findLoadedMessagePreview } from "@/lib/loaded-message-search";+import type { ThreadMessageCache } from "@/lib/thread-message-cache";import { cn } from "@/lib/utils";import type { ChatSummary } from "@/lib/types";@@ -18,11 +20,19 @@ interface SessionSearchDialogProps {activeKey: string | null;loading: boolean;titleOverrides?: Record<string, string>;+ messageCache?: ThreadMessageCache;onOpenChange: (open: boolean) => void;onSelect: (key: string) => void;}+interface SessionSearchResult {+ session: ChatSummary;+ preview?: string;+}+const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};+const noSubscription = () => () => {};+const noRevision = () => 0;export function SessionSearchDialog({open,@@ -30,6 +40,7 @@ export function SessionSearchDialog({activeKey,loading,titleOverrides = EMPTY_TITLE_OVERRIDES,+ messageCache,onOpenChange,onSelect,}: SessionSearchDialogProps) {@@ -41,19 +52,31 @@ export function SessionSearchDialog({const [query, setQuery] = useState("");const [highlightedIndex, setHighlightedIndex] = useState(0);+ const messageRevision = useSyncExternalStore(+ open && messageCache ? messageCache.subscribe : noSubscription,+ messageCache?.getRevision ?? noRevision,+ );const normalizedQuery = query.trim().toLowerCase();+ const searchQuery = useDeferredValue(normalizedQuery);+ const searchRevision = useDeferredValue(messageRevision);+ const searchPending = searchQuery !== normalizedQuery || searchRevision !== messageRevision;const searchableSessions = useMemo(() => sessions.map((session) => ({session,text: [titleOverrides[session.key], session.title, visibleSessionPreview(session.preview)].filter(Boolean).join(" ").toLowerCase(),})), [sessions, titleOverrides]);- const sessionResults = useMemo(() => {+ const sessionResults = useMemo<SessionSearchResult[]>(() => {if (!open) return [];- if (!normalizedQuery) return sessions;- const terms = normalizedQuery.split(/\s+/).filter(Boolean);- return searchableSessions.filter(({ text }) => terms.every((term) => text.includes(term)))- .map(({ session }) => session);- }, [normalizedQuery, open, sessions, searchableSessions]);+ if (!searchQuery) return sessions.map((session) => ({ session }));+ const terms = searchQuery.split(/\s+/).filter(Boolean);+ return searchableSessions.flatMap(({ session, text }) => {+ if (terms.every((term) => text.includes(term))) return [{ session }];+ const preview = messageCache && findLoadedMessagePreview(+ messageCache.readLoadedMessages(session.chatId), searchQuery,+ );+ return preview === undefined ? [] : [{ session, preview }];+ });+ }, [searchQuery, open, sessions, searchableSessions, messageCache, searchRevision]);const itemCount = sessionResults.length;const rowHeight = 64;const windowStart = Math.max(0, Math.min(itemCount - 1, Math.floor(scrollTop / rowHeight) - 4));@@ -99,6 +122,7 @@ export function SessionSearchDialog({}, [highlightedIndex, open]);const handleSelect = (key: string) => {+ if (searchPending) return;onOpenChange(false);onSelect(key);};@@ -119,10 +143,11 @@ export function SessionSearchDialog({return;}if (event.key === "Enter") {+ event.preventDefault();+ if (searchPending) return;const highlighted = sessionResults[highlightedIndex];if (!highlighted) return;- event.preventDefault();- handleSelect(highlighted.key);+ handleSelect(highlighted.session.key);}};@@ -167,6 +192,7 @@ export function SessionSearchDialog({ref={scrollRef}onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}data-testid="session-search-scroll"+ aria-busy={searchPending}className="min-h-0 flex-1 overflow-y-auto overscroll-contain p-2.5 scrollbar-thin scrollbar-track-transparent"><section>@@ -185,12 +211,12 @@ export function SessionSearchDialog({) : (<ul><li aria-hidden style={{ height: windowStart * rowHeight }} />- {sessionResults.slice(windowStart, windowEnd).map((session, offset) => {+ {sessionResults.slice(windowStart, windowEnd).map(({ session, preview: matchPreview }, offset) => {const index = windowStart + offset;const title = titleOverrides[session.key]?.trim() ||session.title?.trim() ||deriveTitle(session.preview, t("chat.newChat"));- const preview = visibleSessionPreview(session.preview);+ const preview = matchPreview ?? visibleSessionPreview(session.preview);const showPreview =preview.length > 0 &&preview.toLowerCase() !== title.trim().toLowerCase();@@ -203,6 +229,7 @@ export function SessionSearchDialog({itemRefs.current[index] = node;}}type="button"+ disabled={searchPending}onClick={() => handleSelect(session.key)}onMouseEnter={() => setHighlightedIndex(index)}aria-current={active ? "page" : undefined}diff --git a/webui/src/components/thread/ThreadShell.tsx b/webui/src/components/thread/ThreadShell.tsxindex 2dc6a5449..9aca6fd18 100644--- a/webui/src/components/thread/ThreadShell.tsx+++ b/webui/src/components/thread/ThreadShell.tsx@@ -627,6 +627,15 @@ export function ThreadShell({!hideHeader && !session && !loading && !!onTemporaryChatEnabledChange;const promptNavigation = usePromptHistory(historyKey, historyVersion, displayMessages);const updateNavigationMessages = promptNavigation.updateMessages;+ useEffect(() => {+ if (!chatId || !messagesReady) return;+ messageCacheRef.current.setLoadedMessages(chatId, promptNavigation.window+ ? [displayMessages, promptNavigation.window.messages] : [displayMessages]);+ }, [chatId, messagesReady, displayMessages, promptNavigation.window]);+ useEffect(() => {+ const cache = messageCacheRef.current;+ return () => { if (chatId) cache.deleteLoadedMessages(chatId); };+ }, [chatId]);const loadTraceDetails = useCallback(async (refs: string[]) => {const details = await loadBodyTraceDetails(refs);diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 6b6f990d6..f2b03e51d 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -444,7 +444,7 @@"collapse": "Collapse sidebar","newChat": "New topic","searchAria": "Search",- "searchPlaceholder": "Search",+ "searchPlaceholder": "Search loaded content","searchResults": "Results","noSearchResults": "No matching topics.","recent": "Recent topics",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 80046cea9..68143c2db 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -444,7 +444,7 @@"collapse": "Contraer barra lateral","newChat": "Nuevo tema","searchAria": "Buscar",- "searchPlaceholder": "Buscar",+ "searchPlaceholder": "Buscar en el contenido cargado","searchResults": "Resultados","noSearchResults": "No hay temas coincidentes.","recent": "Temas recientes",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 8205ae4ab..5fc3a7581 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -444,7 +444,7 @@"collapse": "Réduire la barre latérale","newChat": "Nouveau sujet","searchAria": "Rechercher",- "searchPlaceholder": "Rechercher",+ "searchPlaceholder": "Rechercher dans le contenu chargé","searchResults": "Résultats","noSearchResults": "Aucun sujet correspondant.","recent": "Sujets récents",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex aff99b2ab..22457511c 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -444,7 +444,7 @@"collapse": "Ciutkan sidebar","newChat": "Topik baru","searchAria": "Cari",- "searchPlaceholder": "Cari",+ "searchPlaceholder": "Cari di konten yang sudah dimuat","searchResults": "Hasil","noSearchResults": "Tidak ada topik yang cocok.","recent": "Topik terbaru",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex f05480e57..f302e1acd 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -444,7 +444,7 @@"collapse": "サイドバーを閉じる","newChat": "新しいトピック","searchAria": "検索",- "searchPlaceholder": "検索",+ "searchPlaceholder": "読み込み済みの内容を検索","searchResults": "検索結果","noSearchResults": "一致するトピックはありません。","recent": "最近のトピック",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 3cbafdbae..8ffda3546 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -444,7 +444,7 @@"collapse": "사이드바 접기","newChat": "새 주제","searchAria": "검색",- "searchPlaceholder": "검색",+ "searchPlaceholder": "불러온 내용 검색","searchResults": "결과","noSearchResults": "일치하는 주제가 없습니다.","recent": "최근 주제",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex afb7daede..8e4d57223 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -444,7 +444,7 @@"collapse": "Recolher barra lateral","newChat": "Novo tópico","searchAria": "Buscar",- "searchPlaceholder": "Buscar",+ "searchPlaceholder": "Buscar no conteúdo carregado","searchResults": "Resultados","noSearchResults": "Nenhum tópico encontrado.","recent": "Tópicos recentes",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex 197838ce3..e4aece2f1 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -444,7 +444,7 @@"collapse": "Thu gọn thanh bên","newChat": "Chủ đề mới","searchAria": "Tìm kiếm",- "searchPlaceholder": "Tìm kiếm",+ "searchPlaceholder": "Tìm trong nội dung đã tải","searchResults": "Kết quả","noSearchResults": "Không có chủ đề phù hợp.","recent": "Chủ đề gần đây",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 1f2be2185..3ad522b71 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -444,7 +444,7 @@"collapse": "收起侧边栏","newChat": "新建话题","searchAria": "搜索",- "searchPlaceholder": "搜索",+ "searchPlaceholder": "搜索已加载内容","searchResults": "搜索结果","noSearchResults": "没有匹配的话题。","recent": "最近话题",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex f4fbdf5cc..511c10f9f 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -444,7 +444,7 @@"collapse": "收合側邊欄","newChat": "新增話題","searchAria": "搜尋",- "searchPlaceholder": "搜尋",+ "searchPlaceholder": "搜尋已載入內容","searchResults": "搜尋結果","noSearchResults": "沒有符合的話題。","recent": "最近話題",diff --git a/webui/src/lib/loaded-message-search.ts b/webui/src/lib/loaded-message-search.tsnew file mode 100644index 000000000..a74ec33b6--- /dev/null+++ b/webui/src/lib/loaded-message-search.ts@@ -0,0 +1,47 @@+import { projectWebuiThreadMessages } from "./thread-display-projection";+import type { LoadedThreadMessages } from "./thread-message-cache";+import type { UIMessage } from "./types";++// Message objects and arrays are immutable; eviction also releases these weak entries.+const visibleMessages = new WeakMap<UIMessage[], UIMessage[]>();+const foldedContent = new WeakMap<UIMessage, string>();++function excerpt(text: string, folded: string, index: number): string {+ if (text.length !== folded.length) {+ let offset = 0;+ let original = 0;+ for (const char of text) {+ if (offset >= index) break;+ offset += char.toLowerCase().length;+ original += char.length;+ }+ index = original;+ }+ const start = Math.max(0, index - 48);+ const end = Math.min(text.length, Math.max(index + 112, start + 160));+ return `${start ? "…" : ""}${text.slice(start, end).replace(/\s+/g, " ").trim()}${end < text.length ? "…" : ""}`;+}++/** Find a literal substring in received user/answer text, never load history. */+export function findLoadedMessagePreview(groups: LoadedThreadMessages, query: string): string | undefined {+ for (const group of groups) {+ let visible = visibleMessages.get(group);+ if (!visible) {+ visible = projectWebuiThreadMessages(group);+ visibleMessages.set(group, visible);+ }+ for (let index = visible.length - 1; index >= 0; index--) {+ const message = visible[index];+ if ((message.role !== "user" && message.role !== "assistant")+ || (message.kind && message.kind !== "message") || message.activityKind) continue;+ let folded = foldedContent.get(message);+ if (folded === undefined) {+ folded = message.content.toLowerCase();+ foldedContent.set(message, folded);+ }+ const match = folded.indexOf(query);+ if (match >= 0) return excerpt(message.content, folded, match);+ }+ }+ return undefined;+}diff --git a/webui/src/lib/memory-lru-cache.ts b/webui/src/lib/memory-lru-cache.tsindex 06514881d..81086a84b 100644--- a/webui/src/lib/memory-lru-cache.ts+++ b/webui/src/lib/memory-lru-cache.ts@@ -18,6 +18,11 @@ export class MemoryLruCache<T> {return entry.value;}+ /** Read without making a background observer retain an otherwise old entry. */+ peek(key: string): T | undefined {+ return this.entries.get(key)?.value;+ }+set(key: string, value: T): void {this.delete(key);const bytes = this.estimate(value);diff --git a/webui/src/lib/thread-message-cache.ts b/webui/src/lib/thread-message-cache.tsindex 60cec0b68..a39572d66 100644--- a/webui/src/lib/thread-message-cache.ts+++ b/webui/src/lib/thread-message-cache.ts@@ -1,8 +1,15 @@import type { ThreadTranscriptSnapshot } from "./thread-transcript";import { MemoryLruCache } from "./memory-lru-cache";+import type { UIMessage } from "./types";++export type LoadedThreadMessages = readonly UIMessage[][];/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */export class ThreadMessageCache extends MemoryLruCache<ThreadTranscriptSnapshot> {+ private loaded = new Map<string, LoadedThreadMessages>();+ private listeners = new Set<() => void>();+ private revision = 0;+ private updating = false;constructor(isPinned: (key: string) => boolean,@@ -11,4 +18,54 @@ export class ThreadMessageCache extends MemoryLruCache<ThreadTranscriptSnapshot>) {super(maxBytes, maxEntries, (key) => !isPinned(key));}++ readonly subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => { this.listeners.delete(listener); };+ };++ readonly getRevision = (): number => this.revision;++ readLoadedMessages(key: string): LoadedThreadMessages {+ const mounted = this.loaded.get(key);+ if (mounted) return mounted;+ const saved = this.peek(key);+ return saved ? [saved.projection.messages] : [];+ }++ setLoadedMessages(key: string, messages: LoadedThreadMessages): void {+ this.loaded.set(key, messages);+ this.changed();+ }++ deleteLoadedMessages(key: string): void {+ if (this.loaded.delete(key)) this.changed();+ }++ override set(key: string, value: ThreadTranscriptSnapshot): void {+ this.updating = true;+ try {+ super.set(key, value);+ } finally {+ this.updating = false;+ this.changed();+ }+ }++ override delete(key: string): void {+ const existed = this.peek(key) !== undefined;+ super.delete(key);+ if (existed) this.changed();+ }++ override clear(): void {+ super.clear();+ this.changed();+ }++ private changed(): void {+ if (this.updating) return;+ this.revision++;+ for (const listener of this.listeners) listener();+ }}diff --git a/webui/src/tests/loaded-message-search.test.ts b/webui/src/tests/loaded-message-search.test.tsnew file mode 100644index 000000000..b36829bfd--- /dev/null+++ b/webui/src/tests/loaded-message-search.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from "vitest";++import { findLoadedMessagePreview } from "@/lib/loaded-message-search";+import { ThreadMessageCache } from "@/lib/thread-message-cache";+import { ThreadTranscript } from "@/lib/thread-transcript";+import type { UIMessage } from "@/lib/types";++function message(content: string, role: UIMessage["role"] = "assistant"): UIMessage {+ return { id: content, role, content, createdAt: 1 };+}++describe("loaded message search", () => {+ it("finds literal Chinese, code and multiword substrings, not words across messages", () => {+ const groups = [[message("我们讨论权限与配对", "user"), message("Use session_history.py at 25% with Full Access")]];+ for (const query of ["权限", "配对", "session_history.py", "25%", "full access"]) {+ expect(findLoadedMessagePreview(groups, query)?.toLowerCase()).toContain(query);+ }+ expect(findLoadedMessagePreview(groups, "full use")).toBeUndefined();+ expect(findLoadedMessagePreview(groups, "配对 use")).toBeUndefined();+ expect(findLoadedMessagePreview(groups, "session.history")).toBeUndefined();+ });++ it("uses visible user/answer text and bounds excerpts around a late match", () => {+ const groups = [[+ message("tool-only", "tool"),+ { ...message(""), reasoning: "reasoning-only" },+ { ...message("trace-only"), kind: "trace" as const },+ { ...message("/model hidden-preset", "user"), turnId: "command" },+ { ...message("hidden-reply"), turnId: "command" },+ message(`${"旧内容\n".repeat(500)}Visible TOKEN-42 ${"后续内容".repeat(100)}`),+ ]];+ for (const query of ["tool-only", "reasoning-only", "trace-only", "hidden-preset", "hidden-reply"]) {+ expect(findLoadedMessagePreview(groups, query)).toBeUndefined();+ }+ const preview = findLoadedMessagePreview(groups, "token-42")!;+ expect(preview).toContain("Visible TOKEN-42");+ expect(preview).toMatch(/^….*…$/);+ expect(preview.length).toBeLessThanOrEqual(162);+ });++ it("keeps original excerpt offsets when lowercasing expands Unicode characters", () => {+ const text = `${"İ".repeat(200)} CamelCaseTarget ${"tail".repeat(80)}`;+ expect(findLoadedMessagePreview([[message(text)]], "camelcasetarget")).toContain("CamelCaseTarget");+ });+});++describe("loaded message ownership", () => {+ it("searches cached snapshots without changing LRU eviction order", () => {+ const cache = new ThreadMessageCache(() => false, 100_000, 2);+ cache.set("old", new ThreadTranscript([message("old needle")]).save());+ cache.set("recent", new ThreadTranscript([message("recent needle")]).save());+ expect(findLoadedMessagePreview(cache.readLoadedMessages("old"), "needle")).toBe("old needle");+ cache.set("next", new ThreadTranscript([message("next needle")]).save());+ expect(cache.readLoadedMessages("old")).toEqual([]);+ expect(findLoadedMessagePreview(cache.readLoadedMessages("recent"), "needle")).toBe("recent needle");+ });++ it("uses mounted messages and already-loaded navigation pages instead of stale snapshots", () => {+ const cache = new ThreadMessageCache(() => false);+ cache.set("chat", new ThreadTranscript([message("replaced answer")]).save());+ cache.setLoadedMessages("chat", [[message("current answer")], [message("loaded older page")]]);+ expect(findLoadedMessagePreview(cache.readLoadedMessages("chat"), "replaced")).toBeUndefined();+ expect(findLoadedMessagePreview(cache.readLoadedMessages("chat"), "current")).toBe("current answer");+ expect(findLoadedMessagePreview(cache.readLoadedMessages("chat"), "older")).toBe("loaded older page");+ cache.set("chat", new ThreadTranscript([message("current answer")]).save());+ cache.deleteLoadedMessages("chat");+ expect(findLoadedMessagePreview(cache.readLoadedMessages("chat"), "current")).toBe("current answer");+ cache.delete("chat");+ expect(cache.readLoadedMessages("chat")).toEqual([]);+ });+});diff --git a/webui/src/tests/session-search-dialog.test.tsx b/webui/src/tests/session-search-dialog.test.tsxindex dcc83b44c..a59b71b9e 100644--- a/webui/src/tests/session-search-dialog.test.tsx+++ b/webui/src/tests/session-search-dialog.test.tsx@@ -4,7 +4,9 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { SessionSearchDialog } from "@/components/SessionSearchDialog";import { useAppViewport } from "@/hooks/useAppViewport";-import type { ChatSummary } from "@/lib/types";+import { ThreadMessageCache } from "@/lib/thread-message-cache";+import { ThreadTranscript } from "@/lib/thread-transcript";+import type { ChatSummary, UIMessage } from "@/lib/types";function session(index: number): ChatSummary {return {@@ -117,6 +119,52 @@ describe("SessionSearchDialog", () => {expect(screen.queryByText("Model chat")).not.toBeInTheDocument();});+ it("finds cached body substrings with a bounded preview and no data requests", () => {+ const fetch = vi.fn();+ vi.stubGlobal("fetch", fetch);+ const cache = new ThreadMessageCache(() => false);+ const body: UIMessage = {+ id: "answer", role: "assistant", createdAt: 1,+ content: `${"Earlier content. ".repeat(1000)}权限配置 Full Access 25% session_history.py`,+ };+ cache.set("chat-1", new ThreadTranscript([body]).save());+ const onSelect = vi.fn();+ render(<SessionSearchDialog open sessions={[session(1), session(2)]}+ activeKey={null} loading={false} messageCache={cache}+ onOpenChange={() => {}} onSelect={onSelect} />);+ expect(screen.getByPlaceholderText("Search loaded content")).toBeInTheDocument();+ const input = screen.getByRole("textbox", { name: "Search" });+ for (const query of ["权限", "full access", "25%", "session_history.py"]) {+ fireEvent.change(input, { target: { value: query } });+ expect(screen.getByText("Chat 1")).toBeInTheDocument();+ expect(screen.queryByText("Chat 2")).not.toBeInTheDocument();+ expect(screen.getByText(/权限配置 Full Access/).textContent!.length).toBeLessThanOrEqual(162);+ }+ fireEvent.change(input, { target: { value: "uncached server content" } });+ expect(screen.getByText("No matching topics.")).toBeInTheDocument();+ fireEvent.change(input, { target: { value: "权限" } });+ fireEvent.keyDown(input, { key: "Enter" });+ expect(onSelect).toHaveBeenCalledWith("websocket:chat-1");+ expect(fetch).not.toHaveBeenCalled();+ });++ it("updates an open query for streamed messages and cache eviction without duplicate sessions", () => {+ const cache = new ThreadMessageCache(() => false, 100_000, 1);+ const body = (content: string): UIMessage => ({ id: "answer", role: "assistant", content, createdAt: 1 });+ cache.set("chat-1", new ThreadTranscript([body("Cached needle")]).save());+ render(<SessionSearchDialog open sessions={[session(1), session(2)]}+ activeKey={null} loading={false} messageCache={cache}+ onOpenChange={() => {}} onSelect={() => {}} />);+ fireEvent.change(screen.getByRole("textbox", { name: "Search" }), { target: { value: "needle" } });+ expect(screen.getByText("Chat 1")).toBeInTheDocument();+ act(() => cache.setLoadedMessages("chat-2", [[body("Streaming needle"), body("Another needle")]]));+ expect(screen.getAllByText("Chat 2")).toHaveLength(1);+ act(() => cache.set("chat-2", new ThreadTranscript([body("Streaming needle")]).save()));+ expect(screen.queryByText("Chat 1")).not.toBeInTheDocument();+ act(() => cache.setLoadedMessages("chat-2", [[body("Replacement answer")]]));+ expect(screen.queryByText("Chat 2")).not.toBeInTheDocument();+ });+it("keeps keyboard navigation scrollable through long result lists", () => {const scrollIntoView = vi.fn();Object.defineProperty(HTMLElement.prototype, "scrollIntoView", {diff --git a/webui/src/tests/thread-shell.test.tsx b/webui/src/tests/thread-shell.test.tsxindex e6f4653be..b8c7997ad 100644--- a/webui/src/tests/thread-shell.test.tsx+++ b/webui/src/tests/thread-shell.test.tsx@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import { preloadMarkdownText } from "@/components/MarkdownText";import { ThreadCameraController } from "@/components/thread/thread-camera";import { ThreadShell } from "@/components/thread/ThreadShell";+import { SessionSearchDialog } from "@/components/SessionSearchDialog";import i18n from "@/i18n";import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";@@ -482,6 +483,31 @@ describe("ThreadShell", () => {);});+ it("publishes received and live body text to local search without search-driven reads", async () => {+ const client = makeClient();+ const cache = new ThreadMessageCache(() => false);+ const chatId = "loaded-search";+ const fetch = vi.fn(async (input: RequestInfo | URL) => String(input).includes("/webui-thread")+ ? httpJson(transcriptFromSimpleMessages([{ role: "assistant", content: "Seeded history" }]))+ : new Response(null, { status: 404 }));+ vi.stubGlobal("fetch", fetch);+ render(wrap(client, <>+ <ThreadShell session={session(chatId)} title="Loaded topic" messageCache={cache} onToggleSidebar={() => {}} />+ <SessionSearchDialog open sessions={[session(chatId)]} activeKey={null} loading={false}+ messageCache={cache} onOpenChange={() => {}} onSelect={() => {}} />+ </>));+ const dialog = await screen.findByRole("dialog", { name: "Search" });+ const input = within(dialog).getByRole("textbox", { name: "Search" });+ fireEvent.change(input, { target: { value: "seeded history" } });+ await within(dialog).findByText("Seeded history");+ const readsBeforeSearch = fetch.mock.calls.length;+ fireEvent.change(input, { target: { value: "fresh needle" } });+ expect(within(dialog).getByText("No matching topics.")).toBeInTheDocument();+ act(() => client._emitChat(chatId, { event: "message", chat_id: chatId, text: "Fresh needle from the live stream" }));+ await within(dialog).findByText("Fresh needle from the live stream");+ expect(fetch).toHaveBeenCalledTimes(readsBeforeSearch);+ });+it.each(["callback", "cached return"] as const)("keeps closed answer segments in order after %s", async (path) => {const client = makeClient();const messageCache = new ThreadMessageCache(() => false);