Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(search): frontend search client, hook + shared result components

cyh0eeebe5e1a84
diff --git a/ui/src/components/workbench/search/SearchResultGroup.tsx b/ui/src/components/workbench/search/SearchResultGroup.tsx
new file mode 100644
index 000000000..0d69b226a
--- /dev/null
+++ b/ui/src/components/workbench/search/SearchResultGroup.tsx
@@ -0,0 +1,45 @@
+import { Folder } from 'lucide-react';
+
+import type { MessageSearchMatch, MessageSearchSession } from '../../../context/ApiContext';
+import { SearchResultRow } from './SearchResultRow';
+
+type SearchResultGroupProps = {
+ session: MessageSearchSession;
+ // ``id`` of the currently keyboard-highlighted match (palette navigation).
+ selectedId?: string;
+ onSelect?: (match: MessageSearchMatch) => void;
+};
+
+// A session group: a muted header (folder glyph + "project · session" label +
+// match count) followed by its matching rows. Presentational — selection state
+// and navigation are passed through from the consumer.
+export const SearchResultGroup: React.FC<SearchResultGroupProps> = ({
+ session,
+ selectedId,
+ onSelect,
+}) => {
+ const projectLabel = session.project_name || session.project_id || '—';
+ const sessionLabel = session.title || session.session_id;
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center gap-1.5 px-2.5 py-1.5">
+ <Folder className="size-[13px] shrink-0 text-muted" />
+ <span className="min-w-0 flex-1 truncate font-mono text-[11px] font-bold text-muted">
+ {projectLabel} · {sessionLabel}
+ </span>
+ <span className="shrink-0 font-mono text-[10px] text-muted">{session.matches.length}</span>
+ </div>
+ <div className="flex flex-col">
+ {session.matches.map((match) => (
+ <SearchResultRow
+ key={match.id}
+ match={match}
+ selected={selectedId === match.id}
+ onSelect={onSelect ? () => onSelect(match) : undefined}
+ />
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/search/SearchResultRow.tsx b/ui/src/components/workbench/search/SearchResultRow.tsx
new file mode 100644
index 000000000..cccf5f94e
--- /dev/null
+++ b/ui/src/components/workbench/search/SearchResultRow.tsx
@@ -0,0 +1,54 @@
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import type { MessageSearchMatch } from '../../../context/ApiContext';
+import { formatRelativeTime } from '../../../lib/relativeTime';
+import { Snippet } from './Snippet';
+
+type SearchResultRowProps = {
+ match: MessageSearchMatch;
+ // Keyboard-highlighted row (palette arrow navigation in P3); paints a
+ // mint-soft background + mint ring so the active hit reads clearly.
+ selected?: boolean;
+ onSelect?: () => void;
+};
+
+// One matching message: a role chip (YOU / AGENT), the highlighted snippet, and
+// a muted relative timestamp. Presentational + reusable by both the desktop
+// palette and the mobile page — navigation is wired by the consumer via
+// ``onSelect``.
+export const SearchResultRow: React.FC<SearchResultRowProps> = ({ match, selected, onSelect }) => {
+ const { t } = useTranslation();
+ const isUser = match.author === 'user';
+
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ aria-current={selected ? 'true' : undefined}
+ className={clsx(
+ 'flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left transition',
+ selected
+ ? 'bg-mint-soft ring-1 ring-inset ring-mint/40'
+ : 'hover:bg-foreground/[0.04]',
+ )}
+ >
+ <span
+ className={clsx(
+ 'shrink-0 rounded-md px-2 py-0.5 font-mono text-[9px] font-bold uppercase tracking-wider',
+ isUser
+ ? 'bg-cyan-soft text-cyan'
+ : 'bg-mint-soft text-mint',
+ )}
+ >
+ {isUser ? t('workbench.search.roleYou') : t('workbench.search.roleAgent')}
+ </span>
+ <span className="min-w-0 flex-1">
+ <Snippet snippet={match.snippet} />
+ </span>
+ <span className="shrink-0 font-mono text-[10px] text-muted">
+ {formatRelativeTime(match.created_at, t)}
+ </span>
+ </button>
+ );
+};
diff --git a/ui/src/components/workbench/search/Snippet.tsx b/ui/src/components/workbench/search/Snippet.tsx
new file mode 100644
index 000000000..ee6fcebdd
--- /dev/null
+++ b/ui/src/components/workbench/search/Snippet.tsx
@@ -0,0 +1,26 @@
+import type { MessageSnippet } from '../../../context/ApiContext';
+
+type SnippetProps = {
+ snippet: MessageSnippet;
+};
+
+// A single, truncated line of message text with the matched term highlighted.
+// The server pre-splits the window into prefix / match / suffix, so this is
+// purely presentational. The <mark> uses the design's gold highlight
+// (bg-gold/10 + text-gold — the Badge "warning" tone; there is no gold-soft
+// token) with a small radius, no underline. When ``match`` is empty (leading
+// context only) we render just the prefix.
+export const Snippet: React.FC<SnippetProps> = ({ snippet }) => {
+ const { prefix, match, suffix } = snippet;
+ return (
+ <span className="block truncate text-[12.5px] leading-relaxed text-foreground">
+ {prefix}
+ {match && (
+ <mark className="rounded-md bg-gold/10 px-1 font-medium text-gold no-underline">
+ {match}
+ </mark>
+ )}
+ {match ? suffix : ''}
+ </span>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index b6efa0b57..565d57401 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -183,7 +183,12 @@ export type ApiContextType = {
/** Counts of resources permanently reclaimed when archiving this session
* (bound tasks/watches + active runs) — drives the irreversible-confirm dialog. */
getArchivePreview: (sessionId: string) => Promise<{ tasks: number; watches: number; runs: number; queued: number }>;
- listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
+ listSessionMessages: (sessionId: string, params?: { afterId?: string; beforeId?: string; aroundId?: string; limit?: number; tail?: boolean; cache?: boolean }) => Promise<{ messages: WorkbenchMessage[]; next_after_id: string | null; next_before_id?: string | null }>;
+ // Full-text search over message content across all sessions. Backed by the
+ // non-cached GET /api/search/messages (the query string varies per keystroke,
+ // so caching would only bloat the read cache). Results group matches by
+ // session, sessions ordered most-recent-match first.
+ searchMessages: (q: string, opts?: { limit?: number }) => Promise<MessageSearchResult>;
sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;
cancelSession: (
@@ -518,6 +523,44 @@ export type WorkbenchMessage = {
read_at: string | null;
};
+// One highlighted message-content hit from GET /api/search/messages, split by
+// the server so the UI never has to locate the match: ``prefix`` + ``match`` +
+// ``suffix`` reconstruct a window of the message text, with ``match`` the part
+// to highlight (empty when the snippet is just leading context).
+export type MessageSnippet = {
+ prefix: string;
+ match: string;
+ suffix: string;
+};
+
+// A single matching message within a session group. ``type`` is the coarse
+// chat role the row chip renders ('user' → YOU, otherwise AGENT); ``source``
+// carries provenance (harness/user/agent) like WorkbenchMessage.
+export type MessageSearchMatch = {
+ id: string;
+ author: string;
+ source: string | null;
+ type: 'user' | 'result' | string;
+ created_at: string;
+ snippet: MessageSnippet;
+};
+
+// Matches grouped by their session, with enough session/project context to
+// render a group header and (in P3/P4) navigate into the chat at the match.
+export type MessageSearchSession = {
+ session_id: string;
+ title: string | null;
+ project_id: string | null;
+ project_name: string | null;
+ matches: MessageSearchMatch[];
+};
+
+export type MessageSearchResult = {
+ sessions: MessageSearchSession[];
+ total: number;
+ session_count: number;
+};
+
export type WorkbenchSessionBootstrap = {
session: WorkbenchSession;
agents: VibeAgentBrief[];
@@ -1696,6 +1739,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const search = new URLSearchParams();
if (params?.afterId) search.set('after_id', params.afterId);
if (params?.beforeId) search.set('before_id', params.beforeId);
+ if (params?.aroundId) search.set('around_id', params.aroundId);
if (params?.limit) search.set('limit', String(params.limit));
if (params?.tail) search.set('tail', '1');
const qs = search.toString();
@@ -1703,6 +1747,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const path = qs ? `${base}?${qs}` : base;
return params?.cache === false ? getJson(path) : getCachedJson(path);
},
+ searchMessages: (q, opts) => {
+ const search = new URLSearchParams();
+ search.set('q', q);
+ if (opts?.limit) search.set('limit', String(opts.limit));
+ return getJson(`/api/search/messages?${search.toString()}`);
+ },
sendSessionMessage: (sessionId, payload) =>
postJson(`/api/sessions/${encodeURIComponent(sessionId)}/messages`, payload),
markSessionRead: (sessionId, untilMessageId) =>
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 75e1a002e..18a40507d 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -627,6 +627,10 @@
"harness": "Harness",
"vaults": "Vaults"
},
+ "search": {
+ "roleYou": "You",
+ "roleAgent": "Agent"
+ },
"inbox": {
"eyebrow": "Inbox",
"title": "Inbox",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 59d1a61a7..56adc2981 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -627,6 +627,10 @@
"harness": "Harness",
"vaults": "Vaults"
},
+ "search": {
+ "roleYou": "你",
+ "roleAgent": "助手"
+ },
"inbox": {
"eyebrow": "收件箱",
"title": "收件箱",
diff --git a/ui/src/lib/useMessageSearch.ts b/ui/src/lib/useMessageSearch.ts
new file mode 100644
index 000000000..1eba8ad0f
--- /dev/null
+++ b/ui/src/lib/useMessageSearch.ts
@@ -0,0 +1,82 @@
+import { useEffect, useRef, useState } from 'react';
+
+import { useApi, type MessageSearchResult } from '../context/ApiContext';
+
+export type UseMessageSearchOptions = {
+ // Minimum trimmed query length before a request fires. Below this the hook
+ // stays idle (results null, not loading) so an empty/near-empty palette
+ // doesn't hammer the endpoint. Defaults to 1.
+ minLength?: number;
+ // Debounce window in ms — the query must stop changing this long before a
+ // request is sent. Defaults to 200.
+ debounceMs?: number;
+};
+
+export type UseMessageSearchState = {
+ results: MessageSearchResult | null;
+ loading: boolean;
+ error: string | null;
+};
+
+// Debounced message-content search shared by the desktop command palette (P3)
+// and the mobile search page (P4). Trims the query, gates on ``minLength``,
+// debounces, and tags every request with a monotonic sequence so a slow
+// earlier response can never clobber a newer one (out-of-order safety).
+export function useMessageSearch(
+ query: string,
+ opts?: UseMessageSearchOptions,
+): UseMessageSearchState {
+ const { searchMessages } = useApi();
+ const minLength = opts?.minLength ?? 1;
+ const debounceMs = opts?.debounceMs ?? 200;
+
+ const [results, setResults] = useState<MessageSearchResult | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ // Bumped on every fired request; a resolved response only commits if it is
+ // still the latest. Survives re-renders so stale in-flight calls are ignored.
+ const seqRef = useRef(0);
+
+ useEffect(() => {
+ const trimmed = query.trim();
+
+ // Below the threshold: clear to the idle state and skip the request. Bump
+ // the seq so any in-flight response from a longer prior query is dropped.
+ if (trimmed.length < minLength) {
+ seqRef.current += 1;
+ setResults(null);
+ setLoading(false);
+ setError(null);
+ return;
+ }
+
+ setLoading(true);
+ setError(null);
+
+ const timer = window.setTimeout(() => {
+ const seq = (seqRef.current += 1);
+ searchMessages(trimmed)
+ .then((res) => {
+ if (seq !== seqRef.current) return;
+ setResults(res);
+ setLoading(false);
+ })
+ .catch((err: unknown) => {
+ if (seq !== seqRef.current) return;
+ setResults(null);
+ setError(err instanceof Error ? err.message : String(err));
+ setLoading(false);
+ });
+ }, debounceMs);
+
+ // A new query (or unmount) cancels the pending debounce; bumping the seq
+ // also invalidates any request that already left the gate.
+ return () => {
+ window.clearTimeout(timer);
+ seqRef.current += 1;
+ };
+ }, [query, minLength, debounceMs, searchMessages]);
+
+ return { results, loading, error };
+}