Commit 059cac284 for llama.cpp
commit 059cac2848cfa564f9657e09045ee75ebee9d6f8
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Fri Nov 20 16:20:00 2026 +0100
ui: search message content and Discover models from the search dialog (#32670)
* ui: search message content and Discover models from the search dialog
The search dialog matched chat titles only. It now also scans what was
said in each chat (content, reasoning, tool calls and results, attachment
names and text), newest chat first, stopping at the first match per chat
and after 20 chats, and shows a snippet around the match. Ids, timestamps
and base64 payloads are not searched.
With Discover on, it also lists matching catalog models and, once typing
settles, Hugging Face repos; picking one opens Discover on that repo.
Assisted-by: Claude (Opus 5.5 Medium)
* ui: keep the search dialog one width whatever it lists
The shared dialog sizes itself to its content from md up, so the search
was narrow while empty and widened as results came in. It now takes the
full max-w-2xl there, less a margin on narrower windows.
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte
index 077a6583e..9a241af28 100644
--- a/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte
+++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSearch.svelte
@@ -1,8 +1,23 @@
<script lang="ts">
import * as Dialog from '@ggml-org/llama-ui/ui/dialog';
- import { ArrowDown, ArrowUp, CornerDownLeft, MessageSquare, Pin, X } from '@lucide/svelte';
- import { ActionIcon, KeyboardShortcutInfo } from '#lib/components/app/index.ts';
import {
+ ArrowDown,
+ ArrowUp,
+ CornerDownLeft,
+ Loader2,
+ MessageSquare,
+ Pin,
+ X
+ } from '@lucide/svelte';
+ import { ActionIcon, KeyboardShortcutInfo, ModelOrgAvatar } from '#lib/components/app/index.ts';
+ import {
+ CONVERSATION_SEARCH_CONTENT_DEBOUNCE_MS,
+ CONVERSATION_SEARCH_CONTENT_LIMIT,
+ CONVERSATION_SEARCH_HUB_DEBOUNCE_MS,
+ CONVERSATION_SEARCH_HUB_LIMIT,
+ CONVERSATION_SEARCH_MATCH_LIMIT,
+ CONVERSATION_SEARCH_RECENT_LIMIT,
+ DISCOVER_ICON,
ICON_CLASS_DEFAULT,
ICON_CLASS_SM,
ICON_CLASS_XS,
@@ -10,11 +25,25 @@
SIDEBAR_FOOTER_ITEMS
} from '#lib/constants/index.ts';
import { KeyboardKey, SidebarAction } from '#lib/enums/index.ts';
+ import { useDebouncedSearch } from '#lib/hooks/use-debounced-search.svelte.ts';
+ import {
+ type ConversationContentMatch,
+ ConversationSearchService,
+ HuggingFaceService
+ } from '#lib/services/index.ts';
import { RouterService } from '#lib/services/router.service.ts';
- import { conversationsStore, deviceStore, uiStore } from '#lib/stores/index.ts';
- import { formatRelativeTime, isIMEComposing } from '#lib/utils/index.ts';
+ import {
+ conversationsStore,
+ deviceStore,
+ modelsDiscoverStore,
+ uiStore
+ } from '#lib/stores/index.ts';
+ import type { DatabaseConversation } from '#lib/types/database.js';
+ import type { HfModelInfo } from '#lib/types/huggingface.js';
+ import type { ConversationSearchSnippet } from '#lib/utils/conversation-search.ts';
+ import { formatRelativeTime, isIMEComposing, orgOf } from '#lib/utils/index.ts';
import { goto } from '$app/navigation';
- import type { Component } from 'svelte';
+ import { type Component, untrack } from 'svelte';
interface Props {
open: boolean;
@@ -30,46 +59,192 @@
keys?: string[];
label: string;
meta?: string;
+ /** Org whose avatar stands in for the icon, e.g. a Hub model's base org. */
+ org?: string;
pinned?: boolean;
+ /** Where the query matched, shown under the label */
+ snippet?: ConversationSearchSnippet;
run: () => void;
}
interface SearchSection {
entries: SearchEntry[];
+ /** Results still on their way; the section shows while they load. */
+ loading?: boolean;
title: string;
}
- /** Recent chats shown before typing, so the actions stay in view below them. */
- const RECENT_LIMIT = 5;
- /** Matches kept while typing; the rest stays reachable by typing more. */
- const MATCH_LIMIT = 50;
-
let query = $state('');
let highlighted = $state(0);
let inputRef = $state<HTMLInputElement | null>(null);
const needle = $derived(query.trim().toLowerCase());
- const limit = $derived(needle ? MATCH_LIMIT : RECENT_LIMIT);
+ const limit = $derived(
+ needle ? CONVERSATION_SEARCH_MATCH_LIMIT : CONVERSATION_SEARCH_RECENT_LIMIT
+ );
function matches(label: string): boolean {
return !needle || label.toLowerCase().includes(needle);
}
- const chatEntries = $derived.by((): SearchEntry[] =>
- conversationsStore.conversations
- .filter((conversation) => matches(conversation.name))
- .sort((a, b) => b.lastModified - a.lastModified)
- .slice(0, limit)
- .map((conversation) => ({
- icon: MessageSquare,
- id: `chat-${conversation.id}`,
- label: conversation.name,
- meta: formatRelativeTime(conversation.lastModified),
- pinned: conversation.pinned,
- run: () => close(() => goto(RouterService.chat(conversation.id)))
- }))
+ function chatEntry(
+ conversation: DatabaseConversation,
+ snippet?: ConversationSearchSnippet
+ ): SearchEntry {
+ return {
+ icon: MessageSquare,
+ id: `chat-${conversation.id}`,
+ label: conversation.name,
+ meta: formatRelativeTime(conversation.lastModified),
+ pinned: conversation.pinned,
+ run: () => close(() => goto(RouterService.chat(conversation.id))),
+ snippet
+ };
+ }
+
+ const recentConversations = $derived(
+ [...conversationsStore.conversations].sort((a, b) => b.lastModified - a.lastModified)
+ );
+
+ const titleMatches = $derived(
+ recentConversations.filter((conversation) => matches(conversation.name))
+ );
+
+ const chatEntries = $derived(
+ titleMatches.slice(0, limit).map((conversation) => chatEntry(conversation))
+ );
+
+ // chats found by what was said in them, not by their title; scanned once typing settles
+ let contentMatches = $state.raw<ConversationContentMatch[]>([]);
+
+ const contentSearch = useDebouncedSearch({
+ canRun: () => open,
+ debounceMs: CONVERSATION_SEARCH_CONTENT_DEBOUNCE_MS,
+ getQuery: () => query.trim(),
+ run: async (term, _signal, isCurrent) => {
+ // a chat already listed by its title is not scanned again
+ const byTitle = new Set(titleMatches.map((conversation) => conversation.id));
+
+ try {
+ const found = await ConversationSearchService.searchContent(
+ recentConversations.filter((conversation) => !byTitle.has(conversation.id)),
+ term,
+ { isCurrent, limit: CONVERSATION_SEARCH_CONTENT_LIMIT }
+ );
+
+ if (isCurrent()) contentMatches = found;
+ } catch {
+ if (isCurrent()) contentMatches = [];
+ }
+ }
+ });
+
+ const contentEntries = $derived(
+ needle
+ ? contentMatches.map(({ conversation, snippet }) => ({
+ ...chatEntry(conversation, snippet),
+ id: `message-${conversation.id}`
+ }))
+ : []
+ );
+
+ // Discover data: the catalog suggestions, and Hugging Face matches once typing settles
+ const isDiscoverEnabled = $derived(uiStore.isDiscoverEnabled);
+
+ // the catalog loads once a session; opening the search asks for it if it has not yet.
+ // untracked: fetch() toggles its loading flag synchronously
+ $effect(() => {
+ if (open && isDiscoverEnabled) untrack(() => void modelsDiscoverStore.fetch());
+ });
+
+ /** A Hub repo as a result; picking it opens Discover on that repo. */
+ function modelEntry(model: HfModelInfo, section: string): SearchEntry {
+ const range = modelsDiscoverStore.cachedSizeRangeFor(model.id);
+
+ return {
+ icon: DISCOVER_ICON,
+ id: `${section}-${model.id}`,
+ label: model.id,
+ meta: range
+ ? HuggingFaceService.formatSizeRange(range.min, range.max)
+ : `${HuggingFaceService.formatDownloads(model.downloads)} downloads`,
+ // the model's own org, the way the model cards show it
+ org: orgOf(HuggingFaceService.getBaseModels(model)[0]) || orgOf(model.id),
+ run: () => close(() => uiStore.openModelsDiscover(model.id))
+ };
+ }
+
+ const suggestedEntries = $derived.by((): SearchEntry[] =>
+ isDiscoverEnabled && needle
+ ? modelsDiscoverStore.catalogModels
+ .filter((model) => matches(model.id))
+ .slice(0, limit)
+ .map((model) => modelEntry(model, 'suggested'))
+ : []
);
+ // the dialog keeps its own results: the Discover search stays as it was
+ let hubResults = $state.raw<HfModelInfo[]>([]);
+
+ const hubSearch = useDebouncedSearch({
+ canRun: () => open && isDiscoverEnabled,
+ debounceMs: CONVERSATION_SEARCH_HUB_DEBOUNCE_MS,
+ getQuery: () => query.trim(),
+ run: async (term, _signal, isCurrent) => {
+ try {
+ const results = await HuggingFaceService.searchByQuery(term, {
+ limit: CONVERSATION_SEARCH_HUB_LIMIT
+ });
+
+ if (isCurrent()) hubResults = modelsDiscoverStore.baseOrgFirst(results);
+ } catch {
+ // offline or rate limited: the local results stand on their own
+ if (isCurrent()) hubResults = [];
+ }
+ }
+ });
+
+ $effect(() => {
+ const term = query.trim();
+ const isOpen = open;
+ const withHub = isDiscoverEnabled;
+
+ untrack(() => {
+ if (!isOpen || !term) {
+ contentSearch.cancel();
+ hubSearch.cancel();
+ contentMatches = [];
+ hubResults = [];
+
+ return;
+ }
+
+ contentSearch.setLoading(true);
+ contentSearch.run(term);
+
+ if (!withHub) {
+ hubSearch.cancel();
+ hubResults = [];
+
+ return;
+ }
+
+ hubSearch.setLoading(true);
+ hubSearch.run(term);
+ });
+ });
+
+ // a suggestion that matches is listed once, under the suggestions
+ const hubEntries = $derived.by((): SearchEntry[] => {
+ if (!needle) return [];
+
+ const suggested = new Set(suggestedEntries.map((entry) => entry.label));
+
+ return hubResults
+ .filter((model) => !suggested.has(model.id))
+ .map((model) => modelEntry(model, 'hub'));
+ });
+
const actionEntries = $derived.by((): SearchEntry[] =>
// every sidebar action the sidebar shows but Search itself, which is what opened this
// dialog, and the models manager on a phone, which picks its models in the selector
@@ -91,11 +266,23 @@
.filter((entry) => matches(entry.label))
);
+ // your own chats first; the Hub answers last, so it comes last and never moves a row above it
const sections = $derived<SearchSection[]>(
[
{ entries: chatEntries, title: needle ? 'Chats' : 'Recents' },
- { entries: actionEntries, title: 'Actions' }
- ].filter((section) => section.entries.length > 0)
+ {
+ entries: contentEntries,
+ loading: contentSearch.isSearching && !!needle,
+ title: 'In messages'
+ },
+ { entries: suggestedEntries, title: 'Suggested models' },
+ { entries: actionEntries, title: 'Actions' },
+ {
+ entries: hubEntries,
+ loading: hubSearch.isSearching && !!needle,
+ title: 'On Hugging Face'
+ }
+ ].filter((section) => section.entries.length > 0 || section.loading)
);
const entries = $derived(sections.flatMap((section) => section.entries));
@@ -197,8 +384,12 @@
.reduce((total, previous) => total + previous.entries.length, 0)}
<div class="flex flex-col gap-0.5 {sectionIndex > 0 ? 'mt-3' : ''}" role="group">
- <p class="px-2.5 pt-1 pb-1.5 text-label-sm text-muted-foreground">
+ <p class="flex items-center gap-1.5 px-2.5 pt-1 pb-1.5 text-label-sm text-muted-foreground">
{section.title}
+
+ {#if section.loading}
+ <Loader2 aria-label="Searching" class="{ICON_CLASS_XS} animate-spin" />
+ {/if}
</p>
{#each section.entries as entry, entryIndex (entry.id)}
@@ -218,9 +409,25 @@
tabindex={-1}
type="button"
>
- <entry.icon class="{ICON_CLASS_DEFAULT} shrink-0 text-muted-foreground" />
+ {#if entry.org && HuggingFaceService.isEnabled()}
+ <ModelOrgAvatar class="shrink-0" org={entry.org} size="size-icon-md" />
+ {:else}
+ <entry.icon class="{ICON_CLASS_DEFAULT} shrink-0 text-muted-foreground" />
+ {/if}
+
+ {#if entry.snippet}
+ <span class="flex min-w-0 flex-1 flex-col">
+ <span class="truncate">{entry.label}</span>
- <span class="min-w-0 flex-1 truncate">{entry.label}</span>
+ <span class="truncate text-caption text-muted-foreground">
+ {entry.snippet.before}<mark class="bg-transparent font-medium text-foreground"
+ >{entry.snippet.match}</mark
+ >{entry.snippet.after}
+ </span>
+ </span>
+ {:else}
+ <span class="min-w-0 flex-1 truncate">{entry.label}</span>
+ {/if}
{#if entry.pinned}
<Pin aria-label="Pinned" class="{ICON_CLASS_SM} shrink-0 text-muted-foreground" />
@@ -263,7 +470,7 @@
<!-- like every dialog, a phone shows it full screen -->
<Dialog.Root onOpenChange={handleOpenChange} {open}>
<Dialog.Content
- class="top-[12%] flex h-[min(36rem,76dvh)]! w-full max-w-2xl! translate-y-0 flex-col gap-0 overflow-hidden rounded-xl p-0"
+ class="top-[12%] flex h-[min(36rem,76dvh)]! w-full max-w-2xl! md:w-[calc(100%-2rem)] translate-y-0 flex-col gap-0 overflow-hidden rounded-xl p-0"
onOpenAutoFocus={(event) => {
event.preventDefault();
inputRef?.focus();
diff --git a/ui/apps/chat/src/lib/constants/conversation-search.constants.ts b/ui/apps/chat/src/lib/constants/conversation-search.constants.ts
new file mode 100644
index 000000000..ab988cd28
--- /dev/null
+++ b/ui/apps/chat/src/lib/constants/conversation-search.constants.ts
@@ -0,0 +1,28 @@
+/**
+ * Search dialog constants: how many results each section keeps and how long typing settles
+ * before the slower searches (message content, Hugging Face) run.
+ */
+
+/** Recent chats shown before typing, so the actions stay in view below them. */
+export const CONVERSATION_SEARCH_RECENT_LIMIT = 5;
+
+/** Title matches kept while typing; the rest stays reachable by typing more. */
+export const CONVERSATION_SEARCH_MATCH_LIMIT = 50;
+
+/** Chats matched by their messages; the scan stops once this many are found, newest first. */
+export const CONVERSATION_SEARCH_CONTENT_LIMIT = 20;
+
+/** Pause after typing before the messages are scanned. */
+export const CONVERSATION_SEARCH_CONTENT_DEBOUNCE_MS = 150;
+
+/** Characters kept before the match in a snippet. */
+export const CONVERSATION_SEARCH_SNIPPET_LEAD = 24;
+
+/** Snippet length, the match included. */
+export const CONVERSATION_SEARCH_SNIPPET_MAX_CHARS = 120;
+
+/** Hugging Face matches kept: Discover lists the rest. */
+export const CONVERSATION_SEARCH_HUB_LIMIT = 8;
+
+/** Pause after typing before Hugging Face is asked, as long as the Discover search waits. */
+export const CONVERSATION_SEARCH_HUB_DEBOUNCE_MS = 300;
diff --git a/ui/apps/chat/src/lib/constants/index.ts b/ui/apps/chat/src/lib/constants/index.ts
index 46feb4a6d..e014d457d 100644
--- a/ui/apps/chat/src/lib/constants/index.ts
+++ b/ui/apps/chat/src/lib/constants/index.ts
@@ -16,6 +16,7 @@ export * from './auto-scroll.constants';
export * from './context-gauge-dial.constants';
export * from './context-gauge-popup.constants';
export * from './conversation-import.constants';
+export * from './conversation-search.constants';
export * from './binary-detection.constants';
export * from './content-detection.constants';
export * from './tool-call-args.constants';
diff --git a/ui/apps/chat/src/lib/services/conversation-search.service.ts b/ui/apps/chat/src/lib/services/conversation-search.service.ts
new file mode 100644
index 000000000..bd96a40d0
--- /dev/null
+++ b/ui/apps/chat/src/lib/services/conversation-search.service.ts
@@ -0,0 +1,70 @@
+/**
+ * ConversationSearchService - the search dialog's message search
+ *
+ * Scans the messages of each conversation, newest conversation first, and stops at the first
+ * matching message of a conversation and once enough conversations matched, so a common word
+ * does not read the whole database. What a message offers to the search lives in utils/conversation-search.
+ */
+
+import { DatabaseService } from './database.service';
+import type { DatabaseConversation } from '#lib/types/database.js';
+import {
+ type ConversationSearchSnippet,
+ findMessageMatch,
+ matchSnippet
+} from '#lib/utils/conversation-search.ts';
+
+export interface ConversationContentMatch {
+ conversation: DatabaseConversation;
+ messageId: string;
+ snippet: ConversationSearchSnippet;
+}
+
+export interface ConversationContentSearchOptions {
+ /** Matches to find before the scan stops */
+ limit: number;
+ /** Checked between conversations; false stops the scan, its result is then dropped */
+ isCurrent?: () => boolean;
+}
+
+export class ConversationSearchService {
+ /**
+ * Conversations whose messages contain `query`, case-insensitively, in the order given.
+ * Pass `conversations` newest first: the scan stops after `limit` matches.
+ */
+ static async searchContent(
+ conversations: DatabaseConversation[],
+ query: string,
+ { isCurrent = () => true, limit }: ConversationContentSearchOptions
+ ): Promise<ConversationContentMatch[]> {
+ const needle = query.trim().toLowerCase();
+
+ if (!needle || limit <= 0) return [];
+
+ return DatabaseService.readOnly(async ({ messages }) => {
+ const found: ConversationContentMatch[] = [];
+
+ for (const conversation of conversations) {
+ if (found.length >= limit || !isCurrent()) break;
+
+ const message = await messages
+ .where('convId')
+ .equals(conversation.id)
+ .filter((row) => findMessageMatch(row, needle) !== null)
+ .first();
+ // only the one message that matched is read twice
+ const match = message && findMessageMatch(message, needle);
+
+ if (!message || !match) continue;
+
+ found.push({
+ conversation,
+ messageId: message.id,
+ snippet: matchSnippet(match.text, match.at, needle.length)
+ });
+ }
+
+ return found;
+ });
+ }
+}
diff --git a/ui/apps/chat/src/lib/services/index.ts b/ui/apps/chat/src/lib/services/index.ts
index 04b522538..c9b93d19a 100644
--- a/ui/apps/chat/src/lib/services/index.ts
+++ b/ui/apps/chat/src/lib/services/index.ts
@@ -307,6 +307,10 @@ export { SandboxService } from './sandbox.service';
* @see utils/search-chats - parameter parsing, matching and formatting
*/
export { SearchChatsService } from './search-chats.service';
+export {
+ type ConversationContentMatch,
+ ConversationSearchService
+} from './conversation-search.service';
/**
* **RouterService** — Dynamic route URL construction utility
diff --git a/ui/apps/chat/src/lib/stores/models-discover/index.svelte.ts b/ui/apps/chat/src/lib/stores/models-discover/index.svelte.ts
index c7acb104c..f3be36643 100644
--- a/ui/apps/chat/src/lib/stores/models-discover/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/models-discover/index.svelte.ts
@@ -36,12 +36,35 @@ class ModelsDiscoverStore {
private catalog: HfCatalogEntry[] = [];
/** Repo id -> size range, for catalog rows and lazily measured search rows. */
private catalogSizeRanges = new SvelteMap<string, ModelsDiscoverSizeRange>();
- private defaultModels: HfModelInfo[] = [];
+ private defaultModels = $state.raw<HfModelInfo[]>([]);
private fetched = false;
private searchRequestId = 0;
/** In-flight `sizeRange()` lookups, keyed by repo id. */
private sizeRangePending = new Map<string, Promise<ModelsDiscoverSizeRange | undefined>>();
+ /** The curated catalog repos as they land, whatever a search shows right now. */
+ get catalogModels(): HfModelInfo[] {
+ return this.defaultModels;
+ }
+
+ /**
+ * Repos published by their base model's own org first (e.g. `Qwen/Qwen3-8B-GGUF`
+ * ahead of third-party quants of `Qwen/Qwen3-8B`); the hub's order holds otherwise.
+ * Every Hub search ranks its results this way.
+ */
+ baseOrgFirst(models: HfModelInfo[]): HfModelInfo[] {
+ // org names are case-insensitive on the hub, and base_model tags are not always canonical
+ const isBaseOrg = (model: HfModelInfo) => {
+ const org = orgOf(model.id).toLowerCase();
+
+ return HuggingFaceService.getBaseModels(model).some(
+ (base) => orgOf(base).toLowerCase() === org
+ );
+ };
+
+ return [...models.filter(isBaseOrg), ...models.filter((model) => !isBaseOrg(model))];
+ }
+
/**
* Cached size range for a repo, without measuring: the synchronous part of
* `sizeRange()`, for rendering a row before its measurement resolves.
@@ -102,7 +125,10 @@ class ModelsDiscoverStore {
this.catalogSizeRanges.set(build.repo, this.sizeRangeFor(build, tree));
// the catalog repo id, not the HF response `id`, drives selection
- this.defaultModels.push({ ...info, id: build.repo, modelId: build.repo });
+ this.defaultModels = [
+ ...this.defaultModels,
+ { ...info, id: build.repo, modelId: build.repo }
+ ];
}
// show what has landed, unless a search owns the list right now
@@ -181,23 +207,6 @@ class ModelsDiscoverStore {
return request;
}
- /**
- * Repos published by their base model's own org first (e.g. `Qwen/Qwen3-8B-GGUF`
- * ahead of third-party quants of `Qwen/Qwen3-8B`); the hub's order holds otherwise.
- */
- private baseOrgFirst(models: HfModelInfo[]): HfModelInfo[] {
- // org names are case-insensitive on the hub, and base_model tags are not always canonical
- const isBaseOrg = (model: HfModelInfo) => {
- const org = orgOf(model.id).toLowerCase();
-
- return HuggingFaceService.getBaseModels(model).some(
- (base) => orgOf(base).toLowerCase() === org
- );
- };
-
- return [...models.filter(isBaseOrg), ...models.filter((model) => !isBaseOrg(model))];
- }
-
/**
* Sizes the catalog lists under this repo. Never empty: an entry with no parsable
* size contributes the build's own.
diff --git a/ui/apps/chat/src/lib/utils/conversation-search.ts b/ui/apps/chat/src/lib/utils/conversation-search.ts
new file mode 100644
index 000000000..4c75e15c7
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/conversation-search.ts
@@ -0,0 +1,116 @@
+/**
+ * Matching for the search dialog's message search: which text of a message is searched and the
+ * snippet shown for a match. No IndexedDB access here, the service feeds it messages.
+ */
+
+import {
+ CONVERSATION_SEARCH_SNIPPET_LEAD,
+ CONVERSATION_SEARCH_SNIPPET_MAX_CHARS
+} from '#lib/constants/index.ts';
+import type { DatabaseMessage } from '#lib/types/database.js';
+
+export interface ConversationSearchSnippet {
+ /** Text before the match, with a leading `...` when cut */
+ before: string;
+ match: string;
+ /** Text after the match, with a trailing `...` when cut */
+ after: string;
+}
+
+/** Tool call names and arguments, without the call ids */
+function toolCallTexts(toolCalls: string): string[] {
+ try {
+ const parsed: unknown = JSON.parse(toolCalls);
+
+ if (!Array.isArray(parsed)) return [];
+
+ return parsed.flatMap((call) => {
+ const fn = call?.function;
+
+ if (!fn) return [];
+
+ return [fn.name, fn.arguments].filter(
+ (value): value is string => typeof value === 'string' && value !== ''
+ );
+ });
+ } catch {
+ return [];
+ }
+}
+
+/**
+ * Every text a person could remember from a message, in reading order: reasoning, the content,
+ * tool calls and the names and text of attachments. Ids, timestamps and base64 payloads are left out.
+ */
+export function searchableTexts(message: DatabaseMessage): string[] {
+ const texts: string[] = [];
+
+ if (message.isSynthetic) return texts;
+
+ if (message.reasoningContent) texts.push(message.reasoningContent);
+ else if (message.thinking) texts.push(message.thinking);
+
+ if (typeof message.content === 'string' && message.content) texts.push(message.content);
+
+ if (message.toolCalls) texts.push(...toolCallTexts(message.toolCalls));
+
+ for (const extra of message.extra ?? []) {
+ if (extra.name) texts.push(extra.name);
+
+ if ('content' in extra && typeof extra.content === 'string' && extra.content) {
+ texts.push(extra.content);
+ }
+ }
+
+ return texts;
+}
+
+/** First match of `needle` (already lowercased) in the message's text, or null */
+export function findMessageMatch(
+ message: DatabaseMessage,
+ needle: string
+): { at: number; text: string } | null {
+ if (!needle) return null;
+
+ for (const text of searchableTexts(message)) {
+ const lower = text.toLowerCase();
+ const at = lower.indexOf(needle);
+
+ // lowercasing can change the length (e.g. U+0130), then the offset does not map back
+ if (at !== -1) return { at: lower.length === text.length ? at : -1, text };
+ }
+
+ return null;
+}
+
+/** A one-line excerpt around the match, cut to `maxChars` with the match in it */
+export function matchSnippet(
+ text: string,
+ at: number,
+ length: number,
+ maxChars: number = CONVERSATION_SEARCH_SNIPPET_MAX_CHARS
+): ConversationSearchSnippet {
+ const flat = (value: string) => value.replace(/\s+/g, ' ');
+
+ if (at < 0) {
+ const whole = flat(text).trim();
+
+ return {
+ after: whole.length > maxChars ? `${whole.slice(0, maxChars)}...` : whole,
+ before: '',
+ match: ''
+ };
+ }
+
+ const lead = Math.min(at, CONVERSATION_SEARCH_SNIPPET_LEAD);
+ const start = at - lead;
+ const end = Math.min(text.length, start + Math.max(maxChars, lead + length));
+ const before = flat(text.slice(start, at)).trimStart();
+ const after = flat(text.slice(at + length, end)).trimEnd();
+
+ return {
+ after: end < text.length ? `${after}...` : after,
+ before: start > 0 ? `...${before}` : before,
+ match: flat(text.slice(at, at + length))
+ };
+}
diff --git a/ui/apps/chat/tests/client/conversation-search.service.svelte.test.ts b/ui/apps/chat/tests/client/conversation-search.service.svelte.test.ts
new file mode 100644
index 000000000..6a8565c38
--- /dev/null
+++ b/ui/apps/chat/tests/client/conversation-search.service.svelte.test.ts
@@ -0,0 +1,92 @@
+// IndexedDB side of the search dialog's message search: order, the stop at `limit` and staleness.
+// Matching and snippets are covered by tests/unit/conversation-search.test.ts.
+
+import { MessageRole, MessageType } from '#lib/enums/index.ts';
+import { ConversationSearchService } from '#lib/services/conversation-search.service.ts';
+import { DatabaseService } from '#lib/services/database.service.ts';
+import type { DatabaseConversation, ExportedConversation } from '#lib/types/database.js';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+function makeConversation(
+ id: string,
+ turns: [MessageRole, string][],
+ lastModified: number
+): ExportedConversation {
+ const messages = turns.map(([role, content], i) => ({
+ children: i + 1 < turns.length ? [`${id}-m${i + 1}`] : [],
+ content,
+ convId: id,
+ id: `${id}-m${i}`,
+ parent: i === 0 ? null : `${id}-m${i - 1}`,
+ role,
+ timestamp: lastModified + i,
+ type: MessageType.TEXT
+ }));
+
+ return {
+ conv: { currNode: messages.at(-1)!.id, id, lastModified, name: id },
+ messages
+ } as unknown as ExportedConversation;
+}
+
+let newestFirst: DatabaseConversation[] = [];
+
+beforeEach(async () => {
+ await DatabaseService.importConversations([
+ makeConversation(
+ 'old',
+ [
+ [MessageRole.USER, 'what is the weather?'],
+ [MessageRole.TOOL, 'Lisbon: sunny'],
+ [MessageRole.ASSISTANT, 'It is sunny in Lisbon.']
+ ],
+ 1000
+ ),
+ makeConversation('new', [[MessageRole.USER, 'Is it sunny tomorrow?']], 2000),
+ makeConversation('other', [[MessageRole.USER, 'recipe for bread']], 3000)
+ ]);
+
+ newestFirst = (await DatabaseService.getAllConversations()).sort(
+ (a, b) => b.lastModified - a.lastModified
+ );
+});
+
+afterEach(async () => {
+ const conversations = await DatabaseService.getAllConversations();
+
+ await DatabaseService.bulkDeleteConversations(conversations.map((conv) => conv.id));
+});
+
+describe('ConversationSearchService.searchContent', () => {
+ it('returns each matching chat once, in the order given', async () => {
+ const found = await ConversationSearchService.searchContent(newestFirst, 'SUNNY', {
+ limit: 10
+ });
+
+ expect(found.map((match) => match.conversation.id)).toEqual(['new', 'old']);
+ expect(found[0].snippet.match).toBe('sunny');
+ });
+
+ it('stops at the limit', async () => {
+ const found = await ConversationSearchService.searchContent(newestFirst, 'sunny', { limit: 1 });
+
+ expect(found.map((match) => match.conversation.id)).toEqual(['new']);
+ });
+
+ it('stops once the search is stale', async () => {
+ const found = await ConversationSearchService.searchContent(newestFirst, 'sunny', {
+ isCurrent: () => false,
+ limit: 10
+ });
+
+ expect(found).toEqual([]);
+ });
+
+ it('finds tool output', async () => {
+ const found = await ConversationSearchService.searchContent(newestFirst, 'lisbon: sun', {
+ limit: 10
+ });
+
+ expect(found.map((match) => match.conversation.id)).toEqual(['old']);
+ });
+});
diff --git a/ui/apps/chat/tests/unit/conversation-search.test.ts b/ui/apps/chat/tests/unit/conversation-search.test.ts
new file mode 100644
index 000000000..86f6a59c2
--- /dev/null
+++ b/ui/apps/chat/tests/unit/conversation-search.test.ts
@@ -0,0 +1,91 @@
+import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts';
+import type { DatabaseMessage } from '#lib/types/database.js';
+import { findMessageMatch, matchSnippet, searchableTexts } from '#lib/utils/conversation-search.ts';
+import { describe, expect, it } from 'vitest';
+
+function message(fields: Partial<DatabaseMessage>): DatabaseMessage {
+ return {
+ children: [],
+ content: '',
+ convId: 'conv',
+ id: 'msg',
+ parent: null,
+ role: MessageRole.ASSISTANT,
+ timestamp: 0,
+ type: MessageType.TEXT,
+ ...fields
+ } as DatabaseMessage;
+}
+
+describe('searchableTexts', () => {
+ it('reads reasoning, content, tool calls and attachments, but no ids or payloads', () => {
+ const texts = searchableTexts(
+ message({
+ content: 'the answer',
+ extra: [
+ { content: 'notes inside', name: 'notes.txt', type: AttachmentType.TEXT },
+ { base64Url: 'data:image/png;base64,QUJD', name: 'cat.png', type: AttachmentType.IMAGE }
+ ] as DatabaseMessage['extra'],
+ reasoningContent: 'thinking it over',
+ toolCalls: JSON.stringify([
+ { function: { arguments: '{"q":"weather"}', name: 'web_search' }, id: 'call_secret' }
+ ])
+ })
+ );
+
+ expect(texts).toEqual([
+ 'thinking it over',
+ 'the answer',
+ 'web_search',
+ '{"q":"weather"}',
+ 'notes.txt',
+ 'notes inside',
+ 'cat.png'
+ ]);
+ expect(texts.join(' ')).not.toContain('call_secret');
+ expect(texts.join(' ')).not.toContain('QUJD');
+ });
+
+ it('skips synthetic messages and tolerates broken tool call JSON', () => {
+ expect(searchableTexts(message({ content: 'cwd changed', isSynthetic: true }))).toEqual([]);
+ expect(searchableTexts(message({ content: 'ok', toolCalls: '{not json' }))).toEqual(['ok']);
+ });
+});
+
+describe('findMessageMatch', () => {
+ it('matches case-insensitively and reports where', () => {
+ expect(findMessageMatch(message({ content: 'Plan a trip to Paris' }), 'paris')).toEqual({
+ at: 15,
+ text: 'Plan a trip to Paris'
+ });
+ });
+
+ it('finds tool output and reasoning', () => {
+ const tool = message({ content: 'sunny, 21C', role: MessageRole.TOOL });
+ const reasoning = message({ reasoningContent: 'user wants Lisbon' });
+
+ expect(findMessageMatch(tool, 'sunny')).not.toBeNull();
+ expect(findMessageMatch(reasoning, 'lisbon')).not.toBeNull();
+ expect(findMessageMatch(tool, 'rain')).toBeNull();
+ });
+});
+
+describe('matchSnippet', () => {
+ it('keeps short text whole', () => {
+ expect(matchSnippet('find me here', 5, 2)).toEqual({
+ after: ' here',
+ before: 'find ',
+ match: 'me'
+ });
+ });
+
+ it('cuts long text around the match on one line', () => {
+ const text = `${'a'.repeat(100)}\n\nneedle\n${'b'.repeat(200)}`;
+ const snippet = matchSnippet(text, 102, 6, 40);
+
+ expect(snippet.match).toBe('needle');
+ expect(snippet.before.startsWith('...')).toBe(true);
+ expect(snippet.after.endsWith('...')).toBe(true);
+ expect(snippet.before + snippet.match + snippet.after).not.toContain('\n');
+ });
+});