feat(webui): search loaded message text in Ctrl+K

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-25 21:03:35 +08:00
1 parent 8af6313c56
commit e821144c7e
22 files changed
+396 -23

No files matched your search

@@ -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([]);
});
});
+49 -1
View File
@@ -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", {
+26
View File
@@ -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);