Multiplayer agent harness for work.
Full-text chat search: a ⌘K palette over every visible conversation (#509)
Regan Belldb3ee653d053
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex c853dff91..9eb2e5afe 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -802,6 +802,22 @@ const apiRoutes: readonly WebRoute[] = [);},},+ {+ method: "GET",+ path: "/api/search",+ handle: async (c) => {+ const { res, url, user } = c;+ const q = url.searchParams.get("q") ?? "";+ const limit = url.searchParams.get("limit");+ return relayCore(+ res,+ "GET",+ `/v1/sessions/search?principalId=${encodeURIComponent(user)}&q=${encodeURIComponent(q)}${+ limit ? `&limit=${encodeURIComponent(limit)}` : ""+ }`,+ );+ },+ },{method: "GET",path: "/api/sessions",diff --git a/plugins/web-ui/src/main.ts b/plugins/web-ui/src/main.tsindex e5f0e3dc0..6aa30383b 100644--- a/plugins/web-ui/src/main.ts+++ b/plugins/web-ui/src/main.ts@@ -1,6 +1,7 @@import "dockview-core/dist/styles/dockview.css";import "./shell.css";import { bootSafely } from "./shell";+import { registerChatSearchHotkey } from "./search";import { closeFormMenus } from "./ui";import { allConversations } from "./conversations";import { closeOpenSessionMenu, renderList, sessionsState } from "./sessions";@@ -37,4 +38,5 @@ document.addEventListener("keydown", (e) => {closeFormMenus();});+registerChatSearchHotkey();void bootSafely();diff --git a/plugins/web-ui/src/search.ts b/plugins/web-ui/src/search.tsnew file mode 100644index 000000000..9bf4cc2ed--- /dev/null+++ b/plugins/web-ui/src/search.ts@@ -0,0 +1,327 @@+/** Chat search — a ⌘K palette over every conversation the viewer can see.+ *+ * Results come from the core's Postgres full-text index and are grouped by+ * session, newest first. Enter opens the selected conversation; ⌘/Ctrl+Enter+ * (or the pinned bottom row) pipes the query to QM as the prompt of a new+ * chat, so a fruitless search becomes a question.+ */+import { html, nothing, render, type TemplateResult } from "lit";+import { CornerDownLeft, Search } from "lucide";+import { api, type CoreSession } from "./core-bridge";+import { mainConversation } from "./conversations";+import { recencyGroup } from "./session-list";+import { openSession, refreshSessions, sessionsState, sessionTitle } from "./sessions";+import { icon } from "./ui";++interface ChatSearchHit {+ sessionId: string;+ title: string | null;+ scopeId: string;+ channelName?: string;+ surface?: string;+ seq: number;+ entryType: string;+ author?: string;+ snippet: string;+ createdAt: number;+}++const MIN_QUERY_LEN = 2;+const DEBOUNCE_MS = 150;+const isMac = /Mac|iP(hone|ad|od)/.test(navigator.platform);+export const SEARCH_HOTKEY_LABEL = isMac ? "⌘K" : "Ctrl+K";++const searchState = {+ open: false,+ query: "",+ hits: [] as ChatSearchHit[],+ loading: false,+ /** Selection over hits (0..hits.length-1) plus the trailing ask-QM row. */+ sel: 0,+};++let host: HTMLDivElement | null = null;+let debounceTimer: ReturnType<typeof setTimeout> | null = null;+let inflight: AbortController | null = null;+let fetchSeq = 0;++export function registerChatSearchHotkey(): void {+ document.addEventListener("keydown", (e) => {+ if (e.key.toLowerCase() === "k" && (isMac ? e.metaKey : e.ctrlKey) && !e.altKey && !e.shiftKey) {+ e.preventDefault();+ if (searchState.open) closeChatSearch();+ else openChatSearch();+ }+ });+}++export function openChatSearch(): void {+ if (searchState.open) return;+ searchState.open = true;+ searchState.query = "";+ searchState.hits = [];+ searchState.loading = false;+ searchState.sel = 0;+ draw();+ requestAnimationFrame(() => host?.querySelector<HTMLInputElement>(".chat-search-input")?.focus());+}++function closeChatSearch(): void {+ if (!searchState.open) return;+ searchState.open = false;+ if (debounceTimer) clearTimeout(debounceTimer);+ debounceTimer = null;+ inflight?.abort();+ inflight = null;+ draw();+}++function ensureHost(): HTMLDivElement {+ if (!host) {+ host = document.createElement("div");+ host.className = "chat-search-host";+ document.body.appendChild(host);+ }+ return host;+}++function draw(): void {+ render(searchState.open ? paletteTpl() : nothing, ensureHost());+}++function rowCount(): number {+ return searchState.hits.length + (askRowShown() ? 1 : 0);+}++function askRowShown(): boolean {+ return searchState.query.trim().length > 0;+}++function clampSel(): void {+ searchState.sel = Math.max(0, Math.min(searchState.sel, rowCount() - 1));+}++function onQueryInput(e: InputEvent): void {+ searchState.query = (e.currentTarget as HTMLInputElement).value;+ searchState.sel = 0;+ if (debounceTimer) clearTimeout(debounceTimer);+ const q = searchState.query.trim();+ if (q.length < MIN_QUERY_LEN) {+ inflight?.abort();+ inflight = null;+ searchState.hits = [];+ searchState.loading = false;+ draw();+ return;+ }+ searchState.loading = true;+ draw();+ debounceTimer = setTimeout(() => void runSearch(q), DEBOUNCE_MS);+}++async function runSearch(q: string): Promise<void> {+ inflight?.abort();+ const ctl = new AbortController();+ inflight = ctl;+ const seq = ++fetchSeq;+ try {+ const r = await api<{ hits: ChatSearchHit[] }>(`/api/search?q=${encodeURIComponent(q)}`, { signal: ctl.signal });+ if (seq !== fetchSeq || !searchState.open) return;+ searchState.hits = groupHitsBySession(r.hits ?? []);+ } catch {+ if (seq !== fetchSeq || ctl.signal.aborted) return;+ searchState.hits = [];+ }+ searchState.loading = false;+ clampSel();+ draw();+}++/** Cluster hits by session (sessions ordered by their newest hit) so a+ * conversation never fragments into repeated group headers. */+function groupHitsBySession(hits: ChatSearchHit[]): ChatSearchHit[] {+ const order: string[] = [];+ const bySession = new Map<string, ChatSearchHit[]>();+ for (const hit of hits) {+ const list = bySession.get(hit.sessionId);+ if (list) list.push(hit);+ else {+ order.push(hit.sessionId);+ bySession.set(hit.sessionId, [hit]);+ }+ }+ return order.flatMap((id) => bySession.get(id)!);+}++function onPaletteKeydown(e: KeyboardEvent): void {+ if (e.key === "Escape") {+ e.preventDefault();+ closeChatSearch();+ return;+ }+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {+ e.preventDefault();+ const count = rowCount();+ if (!count) return;+ searchState.sel = (searchState.sel + (e.key === "ArrowDown" ? 1 : count - 1)) % count;+ draw();+ scrollSelectedIntoView();+ return;+ }+ if (e.key === "Enter") {+ e.preventDefault();+ if (e.metaKey || e.ctrlKey) return void askQm();+ const hit = searchState.hits[searchState.sel];+ if (hit) return void openHit(hit);+ if (askRowShown() && searchState.sel === searchState.hits.length) return void askQm();+ }+}++function scrollSelectedIntoView(): void {+ host?.querySelector(".chat-search-row.selected")?.scrollIntoView({ block: "nearest" });+}++async function openHit(hit: ChatSearchHit): Promise<void> {+ const find = (): CoreSession | undefined => sessionsState.list.find((s) => s.id === hit.sessionId);+ let session = find();+ if (!session) {+ await refreshSessions({ silent: true });+ session = find();+ }+ if (!session) return;+ closeChatSearch();+ await openSession(session);+}++function askQm(): void {+ const q = searchState.query.trim();+ if (!q) return;+ closeChatSearch();+ const conv = mainConversation();+ conv.newChat();+ void conv.state.agent?.prompt(q);+}++function highlight(text: string): TemplateResult {+ const terms = searchState.query+ .toLowerCase()+ .split(/[^\p{L}\p{N}]+/u)+ .filter(Boolean);+ if (!terms.length) return html`${text}`;+ const re = new RegExp(`(${terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})`, "giu");+ const parts = text.split(re);+ return html`${parts.map((part, i) => (i % 2 ? html`<mark>${part}</mark>` : html`${part}`))}`;+}++function hitTitle(hit: ChatSearchHit): string {+ if (hit.title?.trim()) return hit.title;+ const session = sessionsState.list.find((s) => s.id === hit.sessionId);+ return session ? sessionTitle(session) : (hit.channelName ?? "Untitled chat");+}++function resultRows(): TemplateResult[] {+ const rows: TemplateResult[] = [];+ let lastSession: string | null = null;+ searchState.hits.forEach((hit, i) => {+ if (hit.sessionId !== lastSession) {+ lastSession = hit.sessionId;+ rows.push(+ html`<div class="chat-search-group"><b>${hitTitle(hit)}</b><span>${recencyGroup(hit.createdAt)}</span></div>`,+ );+ }+ rows.push(html`+ <button+ type="button"+ class="chat-search-row ${i === searchState.sel ? "selected" : ""}"+ @click=${() => void openHit(hit)}+ @pointermove=${() => {+ if (searchState.sel !== i) {+ searchState.sel = i;+ draw();+ }+ }}+ >+ <span class="chat-search-who ${hit.entryType === "user" ? "user" : "agent"}"+ >${(hit.entryType === "user" ? (hit.author ?? "You") : "QM").slice(0, 1).toUpperCase()}</span+ >+ <span class="chat-search-text">+ <span class="chat-search-snippet">${highlight(hit.snippet)}</span>+ <span class="chat-search-meta"+ >${hit.entryType === "user" ? (hit.author ?? "you") : "agent"} ·+ ${new Date(hit.createdAt).toLocaleDateString()}</span+ >+ </span>+ </button>+ `);+ });+ return rows;+}++function askRow(): TemplateResult {+ const i = searchState.hits.length;+ return html`+ <button+ type="button"+ class="chat-search-row chat-search-ask ${searchState.sel === i ? "selected" : ""}"+ @click=${() => askQm()}+ @pointermove=${() => {+ if (searchState.sel !== i) {+ searchState.sel = i;+ draw();+ }+ }}+ >+ <span class="chat-search-who ask">+</span>+ <span class="chat-search-text">+ <span class="chat-search-snippet">Ask QM in a new chat: <b>“${searchState.query.trim()}”</b></span>+ <span class="chat-search-meta">starts a fresh session with this as the prompt</span>+ </span>+ <span class="chat-search-kbd">${isMac ? "⌘" : "Ctrl"}${icon(CornerDownLeft, 11)}</span>+ </button>+ `;+}++function paletteTpl(): TemplateResult {+ const q = searchState.query.trim();+ let body: TemplateResult;+ if (q.length < MIN_QUERY_LEN) {+ body = html`<div class="chat-search-empty">Search every chat you can see — messages, not just titles.</div>`;+ } else if (searchState.loading && !searchState.hits.length) {+ body = html`<div class="chat-search-empty">Searching…</div>`;+ } else if (!searchState.hits.length) {+ body = html`<div class="chat-search-empty">No messages match “${q}”.</div>`;+ } else {+ body = html`${resultRows()}`;+ }+ return html`+ <div+ class="chat-search-overlay"+ @pointerdown=${(e: PointerEvent) => {+ if (e.target === e.currentTarget) closeChatSearch();+ }}+ >+ <div class="chat-search-palette" role="dialog" aria-label="Search chats" @keydown=${onPaletteKeydown}>+ <div class="chat-search-inputrow">+ ${icon(Search, 16)}+ <input+ class="chat-search-input"+ type="text"+ placeholder="Search all chats…"+ autocomplete="off"+ spellcheck="false"+ .value=${searchState.query}+ @input=${onQueryInput}+ />+ <span class="chat-search-kbd">esc</span>+ </div>+ <div class="chat-search-results">${body}</div>+ ${askRowShown() ? html`<div class="chat-search-askbar">${askRow()}</div>` : nothing}+ <div class="chat-search-foot">+ <span><span class="chat-search-kbd">↑↓</span> navigate</span>+ <span><span class="chat-search-kbd">↵</span> open chat</span>+ <span><span class="chat-search-kbd">${isMac ? "⌘↵" : "Ctrl+↵"}</span> ask QM in a new chat</span>+ </div>+ </div>+ </div>+ `;+}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 76586e33c..8f0fb15b9 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -7169,3 +7169,179 @@ h3.ambient-field-label {.qm-tooltip.visible {opacity: 1;}++/* ===== Chat search palette (⌘K) ===== */+.section-label.recents-label > span:first-child {+ flex: 1;+}+.chat-search-open {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ padding: 0;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--muted-foreground);+ cursor: pointer;+}+.chat-search-open:hover,+.chat-search-open:focus-visible {+ background: color-mix(in srgb, var(--foreground) 8%, transparent);+ color: var(--foreground);+}+.chat-search-overlay {+ position: fixed;+ inset: 0;+ z-index: 220;+ display: flex;+ justify-content: center;+ align-items: flex-start;+ padding-top: clamp(48px, 12vh, 120px);+ background: color-mix(in srgb, var(--foreground) 32%, transparent);+}+.chat-search-palette {+ display: flex;+ flex-direction: column;+ width: min(640px, calc(100vw - 32px));+ max-height: min(480px, calc(100vh - 96px));+ overflow: hidden;+ border: 1px solid var(--border);+ border-radius: 14px;+ background: var(--background);+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);+}+.chat-search-inputrow {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 13px 16px;+ border-bottom: 1px solid var(--border);+ color: var(--muted-foreground);+}+.chat-search-input {+ flex: 1;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--foreground);+ font: inherit;+ font-size: 15px;+}+.chat-search-results {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 6px;+}+.chat-search-group {+ display: flex;+ justify-content: space-between;+ gap: 8px;+ padding: 8px 10px 2px;+ font-size: 12px;+ color: var(--muted-foreground);+}+.chat-search-group b {+ overflow: hidden;+ font-weight: 600;+ color: var(--foreground);+ text-overflow: ellipsis;+ white-space: nowrap;+}+.chat-search-row {+ display: flex;+ align-items: flex-start;+ gap: 10px;+ width: 100%;+ padding: 8px 10px;+ border: 0;+ border-radius: 8px;+ background: transparent;+ color: inherit;+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.chat-search-row.selected {+ background: color-mix(in srgb, var(--primary) 10%, transparent);+}+.chat-search-who {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ width: 22px;+ height: 22px;+ margin-top: 1px;+ border-radius: 6px;+ font-size: 11px;+ font-weight: 600;+}+.chat-search-who.user {+ background: color-mix(in srgb, var(--foreground) 10%, transparent);+ color: var(--muted-foreground);+}+.chat-search-who.agent,+.chat-search-who.ask {+ background: var(--primary);+ color: var(--primary-foreground);+}+.chat-search-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+}+.chat-search-snippet {+ display: -webkit-box;+ overflow: hidden;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+}+.chat-search-snippet mark {+ border-radius: 3px;+ padding: 0 1px;+ background: color-mix(in srgb, var(--primary) 22%, transparent);+ color: inherit;+}+.chat-search-meta {+ margin-top: 1px;+ font-size: 11.5px;+ color: var(--muted-foreground);+}+.chat-search-askbar {+ flex-shrink: 0;+ padding: 4px 6px;+ border-top: 1px solid var(--border);+}+.chat-search-ask {+ border-radius: 8px;+}+.chat-search-empty {+ padding: 26px 16px;+ color: var(--muted-foreground);+ text-align: center;+}+.chat-search-foot {+ display: flex;+ gap: 14px;+ padding: 8px 14px;+ border-top: 1px solid var(--border);+ font-size: 12px;+ color: var(--muted-foreground);+}+.chat-search-kbd {+ display: inline-flex;+ align-items: center;+ gap: 2px;+ padding: 1px 5px;+ border: 1px solid var(--border);+ border-bottom-width: 2px;+ border-radius: 5px;+ font-family: ui-monospace, Menlo, monospace;+ font-size: 11px;+ color: var(--muted-foreground);+}diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 4fa01dc1f..55ea14cdc 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -14,6 +14,7 @@ import {Plus,RefreshCw,Rocket,+ Search,ShieldCheck,type IconNode,} from "lucide";@@ -61,6 +62,8 @@ import {import { openCronById, renderCronsPage, resetActiveCron, routeCronsHistory } from "./crons";import { renderFiles } from "./files";import { setScopedSession } from "./session-scope";+import { openChatSearch, SEARCH_HOTKEY_LABEL } from "./search";+import { hideTooltip, showTooltip } from "./tooltip";import { clearConnectorNotice, noteConnectorResult, renderConnectors, resetKeychainState } from "./connectors";import { renderDeploys } from "./deploys";import { renderMemory, resetMemoryState } from "./memory";@@ -543,6 +546,21 @@ export function renderSidebarTop(): void {${html`<div class="section-label recents-label"><span>Sessions</span>+ <button+ class="chat-search-open"+ type="button"+ aria-label="Search chats"+ @click=${() => {+ hideTooltip();+ openChatSearch();+ }}+ @mouseenter=${(e: Event) => showTooltip(e.currentTarget as Element, `Search chats · ${SEARCH_HOTKEY_LABEL}`)}+ @mouseleave=${(e: Event) => hideTooltip(e.currentTarget as Element)}+ @focus=${(e: Event) => showTooltip(e.currentTarget as Element, `Search chats · ${SEARCH_HOTKEY_LABEL}`)}+ @blur=${(e: Event) => hideTooltip(e.currentTarget as Element)}+ >+ ${icon(Search, 13)}+ </button><buttonclass="web-only-toggle ${sessionsState.webOnly ? "on" : ""}"type="button"diff --git a/src/api/app-sessions.ts b/src/api/app-sessions.tsindex 9b95e4a45..d77f39bee 100644--- a/src/api/app-sessions.ts+++ b/src/api/app-sessions.ts@@ -3,6 +3,7 @@ import { orgId as orgIdOf } from "../config.ts";import { parseScopeId, scopeId } from "../types.ts";import { fileArtifactId } from "../files/file-artifact-store.ts";import { transcriptEntries, windowedTranscript } from "../sessions/session-store.ts";+import { SEARCH_HIT_LIMIT, searchSnippet, searchTerms } from "../sessions/entry-search.ts";import { supportsProcessSessions } from "../sandbox/sandbox.ts";import { processIsGone } from "../sandbox/process-poll.ts";import { cronRef, deployRef, encodeRef, fileRef, skillRef } from "../acl/resource-ref.ts";@@ -14,7 +15,7 @@ import { MAX_ATTACHMENT_BYTES, mimeFromName, safeAttachmentName } from "../core/import { projectIdFromGroupRef, projectScopeId } from "../projects/project-store.ts";import type { App, AppDeps } from "./app-types.ts";-import { toFileItem, type ScopeDeployment } from "./app-types.ts";+import { toFileItem, type ScopeDeployment, type SessionSearchHit } from "./app-types.ts";import type { AppHelpers } from "./app-helpers.ts";export function createSessionMethods(@@ -29,6 +30,7 @@ export function createSessionMethods(| "uploadFileForViewer"| "openFileForViewer"| "listSessions"+ | "searchSessions"| "sessionBackground"| "readSessionBackgroundOutput"| "listContexts"@@ -210,6 +212,32 @@ export function createSessionMethods(}));},+ async searchSessions(principalId, query, limit = SEARCH_HIT_LIMIT): Promise<SessionSearchHit[]> {+ const capped = Math.max(1, Math.min(limit, 100));+ const hits = await deps.sessions.searchEntries(principalId, query, capped);+ if (!hits.length) return [];+ const visible = new Map((await sessionsForViewer(principalId)).map((s) => [s.id, s]));+ const terms = searchTerms(query);+ return hits.flatMap((hit) => {+ const session = visible.get(hit.sessionId);+ if (!session) return [];+ return [+ {+ sessionId: hit.sessionId,+ title: session.title ?? null,+ scopeId: session.scopeId,+ ...(session.channelName ? { channelName: session.channelName } : {}),+ ...(session.surface ? { surface: session.surface } : {}),+ seq: hit.seq,+ entryType: hit.type,+ ...(hit.author ? { author: hit.author } : {}),+ snippet: searchSnippet(hit.text, terms),+ createdAt: hit.createdAt,+ },+ ];+ });+ },+async sessionBackground(sessionId, viewer) {const session = (await sessionsForViewer(viewer)).find((s) => s.id === sessionId);if (!session) return null;diff --git a/src/api/app-types.ts b/src/api/app-types.tsindex a33bee60a..fcfb52cc8 100644--- a/src/api/app-types.ts+++ b/src/api/app-types.ts@@ -217,6 +217,19 @@ interface TranscriptWindow {beforeSeq?: number;}+export interface SessionSearchHit {+ sessionId: string;+ title: string | null;+ scopeId: string;+ channelName?: string;+ surface?: string;+ seq: number;+ entryType: string;+ author?: string;+ snippet: string;+ createdAt: number;+}+export interface App {turn(req: TurnRequest): Promise<TurnResult>;getApproval(requestId: string, viewer?: string): Promise<(PendingApprovalRecord & { requestId: string }) | null>;@@ -268,6 +281,7 @@ export interface App {seq: number,): Promise<{ entry: SessionEntry } | null>;listSessions(principalId: string): Promise<Session[]>;+ searchSessions(principalId: string, query: string, limit?: number): Promise<SessionSearchHit[]>;sessionBackground(sessionId: string, viewer: string): Promise<SessionBackgroundView | null>;readSessionBackgroundOutput(sessionId: string,diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 81771f981..b982bff14 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -461,6 +461,16 @@ async function listSessions(ctx: ApiCtx): Promise<void> {return sendJson(res, 200, { sessions: await app.listSessions(principalId) });}+async function searchSessions(ctx: ApiCtx): Promise<void> {+ const { res, app, url } = ctx;+ const principalId = url.searchParams.get("principalId");+ if (!principalId) return sendJson(res, 400, { error: "bad_request", message: "principalId required" });+ const query = url.searchParams.get("q") ?? "";+ const rawLimit = Number(url.searchParams.get("limit") ?? "");+ const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? rawLimit : undefined;+ return sendJson(res, 200, { hits: await app.searchSessions(principalId, query, limit) });+}+async function listContexts(ctx: ApiCtx): Promise<void> {const { res, app, url } = ctx;const principalId = url.searchParams.get("principalId");@@ -1390,6 +1400,7 @@ export async function postSoul(ctx: ApiCtx): Promise<void> {export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "POST", path: "/v1/session-cap", auth: "source", handle: sessionCapability },+ { method: "GET", path: "/v1/sessions/search", auth: "source", handle: searchSessions },{ method: "POST", path: "/v1/sessions/:id/title", auth: "source", handle: regenerateSessionTitle },{ method: "POST", path: "/v1/sessions/:id/fork", auth: "source", handle: forkSession },{ method: "GET", path: "/v1/sessions/:id/approvals", auth: "source", handle: listSessionApprovals },diff --git a/src/api/user-scoped-routes.ts b/src/api/user-scoped-routes.tsindex 2cc5fc156..8915b7a2f 100644--- a/src/api/user-scoped-routes.ts+++ b/src/api/user-scoped-routes.ts@@ -9,6 +9,7 @@ function pat(method: string, template: string, field?: Field): Rule {}const USER_SCOPED: Rule[] = [+ pat("GET", "/v1/sessions/search", { in: "query", name: "principalId" }),pat("GET", "/v1/sessions/:id", { in: "query", name: "viewer" }),pat("GET", "/v1/sessions/:id/entries/:seq", { in: "query", name: "viewer" }),pat("GET", "/v1/sessions/:id/approvals", { in: "query", name: "viewer" }),diff --git a/src/sessions/entry-search.ts b/src/sessions/entry-search.tsnew file mode 100644index 000000000..d45264afb--- /dev/null+++ b/src/sessions/entry-search.ts@@ -0,0 +1,66 @@+import type { SessionEntry } from "../types.ts";++export const SEARCH_HIT_LIMIT = 40;+const MAX_TERMS = 8;++/** Lowercased alphanumeric terms, in query order — the shared tokenizer for both stores. */+export function searchTerms(query: string): string[] {+ return query+ .toLowerCase()+ .split(/[^\p{L}\p{N}]+/u)+ .filter(Boolean)+ .slice(0, MAX_TERMS);+}++/** A `to_tsquery('simple', …)` expression: every term required, last-token-friendly prefix match. */+export function tsPrefixQuery(query: string): string | null {+ const terms = searchTerms(query);+ if (!terms.length) return null;+ return terms.map((t) => `${t}:*`).join(" & ");+}++/** The searchable text of an entry payload — mirrors the Postgres `entry_search_text` function. */+export function entrySearchText(payload: unknown): string | null {+ if (typeof payload === "string") return payload;+ const text = (payload as { text?: unknown } | null)?.text;+ return typeof text === "string" ? text : null;+}++export function entrySearchAuthor(entry: Pick<SessionEntry, "type" | "payload">): string | undefined {+ if (entry.type !== "user") return undefined;+ const name = (entry.payload as { name?: unknown } | null)?.name;+ return typeof name === "string" && name.trim() ? name.trim() : undefined;+}++/** In-memory mirror of the tsquery semantics: every term prefix-matches some word. */+export function matchesSearchTerms(text: string, terms: readonly string[]): boolean {+ if (!terms.length) return false;+ const words = text.toLowerCase().split(/[^\p{L}\p{N}]+/u);+ return terms.every((term) => words.some((w) => w.startsWith(term)));+}++/** First occurrence of `term` in `lower` that starts at a word boundary —+ * matching the word-prefix semantics of the search itself, so the snippet+ * window centers on the text that actually caused the hit. */+function wordPrefixIndex(lower: string, term: string): number {+ for (let i = lower.indexOf(term); i >= 0; i = lower.indexOf(term, i + 1)) {+ if (i === 0 || !/[\p{L}\p{N}]/u.test(lower[i - 1]!)) return i;+ }+ return -1;+}++/** One-line snippet centered on the first matching term. */+export function searchSnippet(text: string, terms: readonly string[], max = 240): string {+ const oneLine = text.replace(/\s+/g, " ").trim();+ if (oneLine.length <= max) return oneLine;+ const lower = oneLine.toLowerCase();+ let at = -1;+ for (const t of terms) {+ const i = wordPrefixIndex(lower, t);+ if (i >= 0 && (at < 0 || i < at)) at = i;+ }+ if (at < 0) at = 0;+ const start = Math.max(0, Math.min(at - Math.floor(max / 3), oneLine.length - max));+ const clip = oneLine.slice(start, start + max);+ return `${start > 0 ? "…" : ""}${clip}${start + max < oneLine.length ? "…" : ""}`;+}diff --git a/src/sessions/memory-session-store.ts b/src/sessions/memory-session-store.tsindex b8ae7a1f8..eeb3ef070 100644--- a/src/sessions/memory-session-store.ts+++ b/src/sessions/memory-session-store.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import type { Session, SessionEntry, ScopeId } from "../types.ts";import type {AttributedTurn,+ EntrySearchHit,CronGroupSummary,GetEntriesOptions,GetTapeOptions,@@ -19,6 +20,7 @@ import type {StoreOptions,TapeRecord,} from "./session-store.ts";+import { entrySearchAuthor, entrySearchText, matchesSearchTerms, searchTerms } from "./entry-search.ts";import {cronIdOf,isOverheardEntry,@@ -357,6 +359,34 @@ export function createMemorySessionStore(opts: StoreOptions = {}): SessionStorereturn log.filter((e) => e.seq >= win.validFromSeq && (win.validToSeq === null || e.seq < win.validToSeq));},+ async searchEntries(principalId, query, limit = 40): Promise<EntrySearchHit[]> {+ const terms = searchTerms(query);+ if (!terms.length) return [];+ const searchable = new Set(["user", "assistant", "text"]);+ const hits: EntrySearchHit[] = [];+ for (const sessionId of participants.get(principalId) ?? []) {+ const win = windows.get(sessionId)?.get(principalId);+ if (!win) continue;+ for (const e of entries.get(sessionId) ?? []) {+ if (!searchable.has(e.type)) continue;+ if (e.seq < win.validFromSeq || (win.validToSeq !== null && e.seq >= win.validToSeq)) continue;+ const text = entrySearchText(e.payload);+ if (!text || !matchesSearchTerms(text, terms)) continue;+ const author = entrySearchAuthor(e);+ hits.push({+ sessionId,+ seq: e.seq,+ type: e.type,+ ...(author ? { author } : {}),+ text,+ createdAt: e.createdAt,+ });+ }+ }+ hits.sort((a, b) => b.createdAt - a.createdAt || idDesc(a.sessionId, b.sessionId) || b.seq - a.seq);+ return hits.slice(0, Math.max(1, Math.min(limit, 200)));+ },+async listAll() {return [...sessions.values()];},diff --git a/src/sessions/postgres-session-store.ts b/src/sessions/postgres-session-store.tsindex 4d09f340c..a5118845b 100644--- a/src/sessions/postgres-session-store.ts+++ b/src/sessions/postgres-session-store.ts@@ -4,6 +4,7 @@ import { jsonbSafeStringify } from "../util/text.ts";import type { Session, SessionEntry, SessionType, ScopeId } from "../types.ts";import type {AttributedTurn,+ EntrySearchHit,CronGroupSummary,DistinctScope,GetEntriesOptions,@@ -26,6 +27,7 @@ import type {StoreOptions,TapeRecord,} from "./session-store.ts";+import { tsPrefixQuery } from "./entry-search.ts";import {LEGACY_CRON_ID_PATTERN,legacyOriginPattern,@@ -257,6 +259,19 @@ export function createPostgresSessionStore(connectionString: string, opts: StoreON sessions(scope_id, (COALESCE(last_activity, created_at)) DESC, id DESC)`,`CREATE INDEX IF NOT EXISTS session_entries_user_ts ON session_entries(created_at) WHERE type = 'user'`,`CREATE INDEX IF NOT EXISTS session_entries_session_created ON session_entries(session_id, created_at DESC)`,+ `CREATE OR REPLACE FUNCTION entry_search_text(payload text) RETURNS text+ LANGUAGE plpgsql IMMUTABLE PARALLEL UNSAFE AS $entry_search_text$+ DECLARE j json;+ BEGIN+ j := replace(payload, '\\u0000', '')::json;+ RETURN CASE WHEN json_typeof(j -> 'text') = 'string' THEN j ->> 'text'+ WHEN json_typeof(j) = 'string' THEN j #>> '{}'+ ELSE NULL END;+ EXCEPTION WHEN others THEN RETURN NULL;+ END $entry_search_text$`,+ `CREATE INDEX IF NOT EXISTS session_entries_search_fts+ ON session_entries USING GIN (to_tsvector('simple', COALESCE(entry_search_text(payload), '')))+ WHERE type IN ('user', 'assistant', 'text')`,`DELETE FROM session_entries WHERE session_id IN (SELECT id FROM sessions WHERE type IN ('channel','group') AND thread_ref ~ '^[a-z0-9_]+/[^:/]+$')`,`DELETE FROM participants WHERE session_id IN (SELECT id FROM sessions WHERE type IN ('channel','group') AND thread_ref ~ '^[a-z0-9_]+/[^:/]+$')`,`DELETE FROM session_leases WHERE session_id IN (SELECT id FROM sessions WHERE type IN ('channel','group') AND thread_ref ~ '^[a-z0-9_]+/[^:/]+$')`,@@ -719,6 +734,39 @@ export function createPostgresSessionStore(connectionString: string, opts: Storereturn rows.map(rowToEntry);},+ async searchEntries(principalId, query, limit = 40): Promise<EntrySearchHit[]> {+ const ts = tsPrefixQuery(query);+ if (!ts) return [];+ const rows = await q(+ `SELECT e.session_id, e.seq, e.type, e.created_at,+ entry_search_text(e.payload) AS text,+ (SELECT CASE WHEN e.type = 'user' AND json_typeof(j -> 'name') = 'string' THEN j ->> 'name' END+ FROM (SELECT safe_json(replace(e.payload, '\\u0000', '')) AS j) _) AS author+ FROM session_entries e+ JOIN participants p ON p.session_id = e.session_id AND p.principal_id = $1+ WHERE e.type IN ('user', 'assistant', 'text')+ AND ${withinParticipantWindow("e", "p")}+ AND to_tsvector('simple', COALESCE(entry_search_text(e.payload), '')) @@ to_tsquery('simple', $2)+ ORDER BY e.created_at DESC, e.session_id, e.seq DESC+ LIMIT $3`,+ [principalId, ts, Math.max(1, Math.min(limit, 200))],+ );+ return rows.flatMap((r) => {+ const text = (r.text as string | null) ?? "";+ if (!text.trim()) return [];+ return [+ {+ sessionId: r.session_id as string,+ seq: Number(r.seq),+ type: r.type as EntrySearchHit["type"],+ ...(r.author ? { author: r.author as string } : {}),+ text,+ createdAt: Number(r.created_at),+ },+ ];+ });+ },+async listAll(): Promise<Session[]> {const rows = await q("SELECT * FROM sessions");return rows.map(rowToSession);diff --git a/src/sessions/session-store.ts b/src/sessions/session-store.tsindex eff31acfb..89c52ddf1 100644--- a/src/sessions/session-store.ts+++ b/src/sessions/session-store.ts@@ -270,6 +270,15 @@ export interface DistinctScope {channelName?: string;}+export interface EntrySearchHit {+ sessionId: string;+ seq: number;+ type: EntryType;+ author?: string;+ text: string;+ createdAt: number;+}+export interface SessionSummary {id: string;type: SessionType;@@ -461,6 +470,8 @@ export interface SessionStore {visibleEntries(sessionId: string, principalId: string): Promise<SessionEntry[]>;+ searchEntries(principalId: string, query: string, limit?: number): Promise<EntrySearchHit[]>;+listAll(): Promise<Session[]>;sessionsByThreadRefs(threadRefs: readonly string[]): Promise<SessionRef[]>;diff --git a/test/entry-search.test.ts b/test/entry-search.test.tsnew file mode 100644index 000000000..eb48d1b61--- /dev/null+++ b/test/entry-search.test.ts@@ -0,0 +1,58 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import {+ entrySearchAuthor,+ entrySearchText,+ matchesSearchTerms,+ searchSnippet,+ searchTerms,+ tsPrefixQuery,+} from "../src/sessions/entry-search.ts";++test("searchTerms tokenizes to lowercase alphanumerics", () => {+ assert.deepEqual(searchTerms("Memo-Board refresh!"), ["memo", "board", "refresh"]);+ assert.deepEqual(searchTerms(" "), []);+ assert.equal(searchTerms("a b c d e f g h i j").length, 8, "terms are capped");+});++test("tsPrefixQuery builds an AND-of-prefixes tsquery", () => {+ assert.equal(tsPrefixQuery("memo board"), "memo:* & board:*");+ assert.equal(tsPrefixQuery("!!!"), null);+});++test("matchesSearchTerms mirrors prefix semantics", () => {+ assert.ok(matchesSearchTerms("Refreshed the memo board data", ["memo", "boar"]));+ assert.ok(!matchesSearchTerms("Refreshed the memo board data", ["memo", "missing"]));+ assert.ok(!matchesSearchTerms("emoboard", ["memo"]), "prefix, not substring");+ assert.ok(!matchesSearchTerms("anything", []));+});++test("entrySearchText reads string payloads and payload.text", () => {+ assert.equal(entrySearchText("plain"), "plain");+ assert.equal(entrySearchText({ text: "hello" }), "hello");+ assert.equal(entrySearchText({ other: 1 }), null);+ assert.equal(entrySearchText(null), null);+});++test("entrySearchAuthor only reads user entries", () => {+ assert.equal(entrySearchAuthor({ type: "user", payload: { name: "josh" } }), "josh");+ assert.equal(entrySearchAuthor({ type: "assistant", payload: { name: "x" } }), undefined);+ assert.equal(entrySearchAuthor({ type: "user", payload: {} }), undefined);+});++test("searchSnippet clips long text around the first match", () => {+ const text = `${"a ".repeat(300)}needle in the middle ${"b ".repeat(300)}`;+ const snip = searchSnippet(text, ["needle"]);+ assert.ok(snip.includes("needle"), "match survives the clip");+ assert.ok(snip.length <= 244, "snippet is bounded");+ assert.ok(snip.startsWith("…") && snip.endsWith("…"));+ assert.equal(searchSnippet("short text", ["short"]), "short text");+});++test("searchSnippet anchors on a word-prefix match, not a mid-word substring", () => {+ // "art" appears mid-word ("smart") long before the real word-prefix hit ("artichoke").+ const filler = "x".repeat(300);+ const text = `a smart plan ${filler} we planted artichoke rows ${filler}`;+ const snip = searchSnippet(text, ["art"]);+ assert.ok(snip.includes("artichoke"), `snippet should contain the prefix hit: ${snip}`);+});diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex 1d7a5b674..68f63507b 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -1272,6 +1272,44 @@ test("pg participant view: pin/color are per-participant, survive re-add, and classert.equal(cleared.color ?? null, null, "null clears the color");});+test("pg search: full-text over entries with prefix match, window ACL, and type filter", { skip }, async () => {+ const s = createPostgresSessionStore(URL!);+ const scope = scopeId("personal", "USRCH");+ const sess = await s.getOrCreateByThread("srch-1", "dm", scope);+ await s.addParticipant(sess.id, "USRCH", undefined, { includeHistory: true });++ const att = await s.acquireLease(sess.id);+ const lease = att.lease!;+ await s.append(lease, {+ type: "user",+ payload: { text: "can you refresh the memo board data?", name: "josh" },+ scopeLabel: scope,+ });+ await s.append(lease, {+ type: "assistant",+ payload: { text: "Done — pushed the memo board refresh." },+ scopeLabel: scope,+ });+ await s.append(lease, { type: "tool_call", payload: { text: "memo board tool noise" }, scopeLabel: scope });+ // A latecomer joins without history, then one more message lands.+ await s.addParticipant(sess.id, "ULATE");+ await s.append(lease, { type: "user", payload: { text: "memo board postscript" }, scopeLabel: scope });+ await s.releaseLease(lease);++ const hits = await s.searchEntries("USRCH", "memo boar");+ assert.equal(hits.length, 3, "prefix terms match user and assistant text; tool calls are ignored");+ assert.equal(hits[0]!.text, "memo board postscript", "newest first");+ assert.equal(hits[2]!.author, "josh", "user hits carry the author");++ const late = await s.searchEntries("ULATE", "memo");+ assert.equal(late.length, 1, "a latecomer only searches inside their window");+ assert.equal(late[0]!.text, "memo board postscript");++ assert.deepEqual(await s.searchEntries("UNONE", "memo"), [], "a non-participant sees nothing");+ assert.deepEqual(await s.searchEntries("USRCH", " !! "), [], "an unusable query is empty, not an error");+ assert.deepEqual(await s.searchEntries("USRCH", "memo missing"), [], "every term must match");+});+test("pg deleteSessionIfEmpty: an expired lease forfeits, and the stale holder cannot orphan entries",{ skip },diff --git a/test/session-search.test.ts b/test/session-search.test.tsnew file mode 100644index 000000000..88fb4202a--- /dev/null+++ b/test/session-search.test.ts@@ -0,0 +1,118 @@+import "./support/auto-fake-sprites.ts";++import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { buildApp } from "../src/wiring.ts";+import { testConfig } from "./support/test-config.ts";+import { createMemorySessionStore } from "../src/sessions/memory-session-store.ts";+import type { SessionStore } from "../src/sessions/session-store.ts";+import { scopeId } from "../src/types.ts";++async function seed(sessions: SessionStore, threadRef: string, principal: string, texts: string[]): Promise<string> {+ const s = await sessions.getOrCreateByThread(threadRef, "dm", scopeId("personal", principal));+ await sessions.addParticipant(s.id, principal, undefined, { includeHistory: true });+ const { lease } = await sessions.acquireLease(s.id);+ for (const [i, text] of texts.entries()) {+ await sessions.append(lease!, {+ type: i % 2 === 0 ? "user" : "assistant",+ payload: i % 2 === 0 ? { text, name: "josh" } : { text },+ scopeLabel: scopeId("personal", principal),+ });+ }+ await sessions.releaseLease(lease!);+ return s.id;+}++test("memory store: searchEntries matches user and assistant text, newest first", async () => {+ const store = createMemorySessionStore();+ const id = await seed(store, "web:U1:a", "U1", [+ "can you refresh the memo board?",+ "Done — the memo board refresh is pushed.",+ "unrelated chatter",+ ]);++ const hits = await store.searchEntries("U1", "memo board");+ assert.equal(hits.length, 2);+ assert.equal(hits[0]!.sessionId, id);+ assert.equal(hits[0]!.type, "assistant", "assistant reply is found too");+ assert.equal(hits[1]!.author, "josh", "user hits carry the author");+ assert.ok(hits[0]!.createdAt >= hits[1]!.createdAt, "newest first");++ assert.deepEqual(await store.searchEntries("U1", "memo missing"), [], "every term must match");+ assert.deepEqual(await store.searchEntries("U1", " "), [], "blank query matches nothing");+ assert.equal((await store.searchEntries("U1", "memo"))[0]!.text.includes("memo"), true);+});++test("memory store: search respects participant visibility windows and identity", async () => {+ const store = createMemorySessionStore();+ const s = await store.getOrCreateByThread("web:U1:w", "dm", scopeId("personal", "U1"));+ await store.addParticipant(s.id, "U1", undefined, { includeHistory: true });+ const { lease } = await store.acquireLease(s.id);+ await store.append(lease!, {+ type: "user",+ payload: { text: "secret prelude" },+ scopeLabel: scopeId("personal", "U1"),+ });+ // U2 joins WITHOUT history — the prelude is outside their window.+ await store.addParticipant(s.id, "U2");+ await store.append(lease!, {+ type: "user",+ payload: { text: "shared secret plans" },+ scopeLabel: scopeId("personal", "U1"),+ });+ await store.releaseLease(lease!);++ const u2 = await store.searchEntries("U2", "secret");+ assert.equal(u2.length, 1, "U2 sees only the post-join message");+ assert.equal(u2[0]!.text, "shared secret plans");++ assert.deepEqual(await store.searchEntries("U3", "secret"), [], "a non-participant sees nothing");+ assert.equal((await store.searchEntries("U1", "secret")).length, 2, "a full-history participant sees both");+});++test("memory store: search ignores non-conversational entry types", async () => {+ const store = createMemorySessionStore();+ const s = await store.getOrCreateByThread("web:U1:t", "dm", scopeId("personal", "U1"));+ await store.addParticipant(s.id, "U1", undefined, { includeHistory: true });+ const { lease } = await store.acquireLease(s.id);+ await store.append(lease!, {+ type: "tool_call",+ payload: { text: "grep zanzibar" },+ scopeLabel: scopeId("personal", "U1"),+ });+ await store.append(lease!, {+ type: "text",+ payload: { text: "zanzibar itinerary" },+ scopeLabel: scopeId("personal", "U1"),+ });+ await store.releaseLease(lease!);++ const hits = await store.searchEntries("U1", "zanzibar");+ assert.equal(hits.length, 1, "tool calls are not searched");+ assert.equal(hits[0]!.type, "text");+});++test("app.searchSessions decorates hits with session metadata and enforces visibility", async () => {+ const dataDir = mkdtempSync(join(tmpdir(), "search-"));+ const { app, sessions } = buildApp(testConfig({ dataDir }));++ const id = await seed(sessions, "web:U1:hit", "U1", [+ "let's plan the zanzibar trip",+ "Zanzibar it is — I drafted an itinerary.",+ ]);+ await sessions.updateTitle(id, "Trip planning");+ await seed(sessions, "web:U2:other", "U2", ["zanzibar for U2 only"]);++ const hits = await app.searchSessions("U1", "zanzibar");+ assert.equal(hits.length, 2, "only U1's own conversation is searched");+ assert.ok(hits.every((h) => h.sessionId === id));+ assert.equal(hits[0]!.title, "Trip planning");+ assert.equal(typeof hits[0]!.seq, "number");+ assert.ok(hits[0]!.snippet.toLowerCase().includes("zanzibar"));+ assert.equal(hits[1]!.author, "josh");++ assert.deepEqual(await app.searchSessions("U1", ""), [], "empty query is empty, not an error");+});