Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-7754: feat: local search index for web and desktop (#8891)

Jiayuan Zhang3d2592a9a2e4
diff --git a/.env.example b/.env.example
index 0868943f29..a38c4c89a6 100644
--- a/.env.example
+++ b/.env.example
@@ -215,6 +215,11 @@ MULTICA_CODEX_WORKDIR=
# process with the env var set.
MULTICA_FEATURE_FLAGS_FILE=
+# Web/Desktop keep a local search index per workspace and sync it through
+# /api/search-index. On by default; turning it off makes clients stop syncing
+# and search through the server again:
+# FF_LOCAL_SEARCH_INDEX=off
+
# Workspace subscription Checkout/Portal/entitlement proxying is fail-closed;
# enable it only after multica-cloud billing.subscriptions is configured:
# FF_BILLING_WORKSPACE_SUBSCRIPTIONS=true
diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts
index 0735b1a715..9f0312abf0 100644
--- a/e2e/fixtures.ts
+++ b/e2e/fixtures.ts
@@ -335,6 +335,62 @@ export class TestApiClient {
await this.authedFetch(`/api/issues/${id}`, { method: "DELETE" });
}
+ async createComment(issueId: string, content: string) {
+ const res = await this.authedFetch(`/api/issues/${issueId}/comments`, {
+ method: "POST",
+ body: JSON.stringify({ content }),
+ });
+ if (!res.ok) {
+ throw new Error(`create comment failed: ${res.status} ${await res.text()}`);
+ }
+ return (await res.json()) as { id: string };
+ }
+
+ /** Adds an existing user to this client's workspace and returns the member id. */
+ async addMemberByEmail(email: string, role: "admin" | "member" = "member"): Promise<string> {
+ if (!this.workspaceId) throw new Error("Cannot add a member before a workspace is selected");
+ const client = new pg.Client(DATABASE_URL);
+ await client.connect();
+ try {
+ const result = await client.query(
+ `INSERT INTO member (workspace_id, user_id, role)
+ SELECT $1, id, $3 FROM "user" WHERE email = $2
+ RETURNING id`,
+ [this.workspaceId, email, role],
+ );
+ if (result.rowCount !== 1) throw new Error(`No user with email ${email}`);
+ return result.rows[0].id as string;
+ } finally {
+ await client.end();
+ }
+ }
+
+ async removeMember(memberId: string) {
+ const res = await this.authedFetch(`/api/workspaces/${this.workspaceId}/members/${memberId}`, {
+ method: "DELETE",
+ });
+ if (!res.ok) {
+ throw new Error(`remove member failed: ${res.status} ${await res.text()}`);
+ }
+ }
+
+ /** Deletes this client's workspace; only for workspaces a test created. */
+ async deleteWorkspace() {
+ if (!this.workspaceId) return;
+ await this.authedFetch(`/api/workspaces/${this.workspaceId}`, { method: "DELETE" });
+ }
+
+ /** Server-side issue search, for comparing against what the UI shows. */
+ async searchIssues(q: string, opts: { includeClosed?: boolean; limit?: number } = {}) {
+ const params = new URLSearchParams({ q, limit: String(opts.limit ?? 20) });
+ if (opts.includeClosed) params.set("include_closed", "true");
+ const res = await this.authedFetch(`/api/issues/search?${params}`);
+ if (!res.ok) {
+ throw new Error(`search issues failed: ${res.status} ${await res.text()}`);
+ }
+ return (await res.json()) as { issues: { id: string; identifier: string; title: string }[] };
+ }
+
async updateIssue(id: string, updates: Record<string, unknown>) {
const res = await this.authedFetch(`/api/issues/${id}`, {
method: "PUT",
diff --git a/e2e/local-search.spec.ts b/e2e/local-search.spec.ts
new file mode 100644
index 0000000000..213b7007f0
--- /dev/null
+++ b/e2e/local-search.spec.ts
@@ -0,0 +1,144 @@
+import { expect, test, type Page, type Response } from "@playwright/test";
+import { TestApiClient } from "./fixtures";
+import { createTestApi, loginAsDefault, openWorkspaceMenu } from "./helpers";
+
+// Web search answers from the local search index once it has synced
+// (MUL-7754): results match server search, follow writes made elsewhere, and
+// no server search request is sent while typing.
+
+const SEARCH_PLACEHOLDER = "Type a command or search...";
+
+function isSearchIndexChanges(res: Response): boolean {
+ return res.url().includes("/api/search-index/changes") && res.ok();
+}
+
+async function openSearch(page: Page) {
+ await page.keyboard.press("ControlOrMeta+k");
+ await expect(page.getByPlaceholder(SEARCH_PLACEHOLDER)).toBeVisible();
+}
+
+async function search(page: Page, query: string) {
+ const input = page.getByPlaceholder(SEARCH_PLACEHOLDER);
+ await input.fill("");
+ await input.fill(query);
+}
+
+function searchIndexDatabases(page: Page): Promise<string[]> {
+ return page.evaluate(async () =>
+ (await indexedDB.databases())
+ .map((db) => db.name ?? "")
+ .filter((name) => name.startsWith("multica-search-index:")),
+ );
+}
+
+/** Identifiers of the listed issues, in the order the palette shows them. */
+async function visibleIdentifiers(page: Page, candidates: string[]): Promise<string[]> {
+ const texts = await page.getByRole("option").allInnerTexts();
+ return texts
+ .map((text) => candidates.find((identifier) => new RegExp(`\\b${identifier}\\b`).test(text)))
+ .filter((identifier): identifier is string => identifier !== undefined);
+}
+
+test.describe("Local search index", () => {
+ let api: TestApiClient;
+
+ test.beforeEach(async () => {
+ api = await createTestApi();
+ });
+
+ test.afterEach(async () => {
+ await api.cleanup();
+ });
+
+ test("answers from the local index with server ranking and follows remote writes", async ({ page }) => {
+ const token = `lsi${Date.now().toString(36)}`;
+ const exact = await api.createIssue(`${token} release plan`);
+ await api.createIssue(`plan the ${token} release`);
+ const spread = await api.createIssue(`${token} notes`, { description: "release plan draft" });
+ const commented = await api.createIssue("unrelated title");
+ await api.createComment(commented.id, `${token} release plan in one comment`);
+ await api.createComment(spread.id, "another remark");
+
+ const serverSearches: string[] = [];
+ page.on("request", (req) => {
+ if (/\/api\/(issues|projects)\/search/.test(req.url())) serverSearches.push(req.url());
+ });
+
+ const synced = page.waitForResponse(isSearchIndexChanges, { timeout: 45_000 });
+ await loginAsDefault(page);
+ await synced;
+ // The worker reports readiness right after its first catch-up completes.
+ await page.waitForTimeout(500);
+
+ await openSearch(page);
+ const query = `${token} release plan`;
+ await search(page, query);
+ const server = await api.searchIssues(query);
+ const expected = server.issues.map((issue) => issue.identifier);
+ expect(server.issues[0]?.title).toBe(exact.title);
+ expect(expected).toHaveLength(4);
+ await expect.poll(() => visibleIdentifiers(page, expected)).toEqual(expected);
+ expect(serverSearches).toEqual([]);
+
+ // A write made elsewhere reaches the local copy through the change log.
+ const caughtUp = page.waitForResponse(isSearchIndexChanges, { timeout: 30_000 });
+ const fresh = await api.createIssue(`${token} fresh arrival`);
+ await caughtUp;
+ await search(page, `${token} fresh`);
+ await expect(page.getByRole("option").filter({ hasText: `${token} fresh arrival` })).toBeVisible();
+
+ const removed = page.waitForResponse(isSearchIndexChanges, { timeout: 30_000 });
+ await api.deleteIssue(fresh.id);
+ await removed;
+ await search(page, `${token} fresh`);
+ await expect(page.getByRole("option").filter({ hasText: `${token} fresh arrival` })).toHaveCount(0);
+
+ expect(serverSearches).toEqual([]);
+ });
+
+ test("deletes the local copy on logout", async ({ page }) => {
+ const synced = page.waitForResponse(isSearchIndexChanges, { timeout: 45_000 });
+ await loginAsDefault(page);
+ await synced;
+ await expect.poll(() => searchIndexDatabases(page)).toHaveLength(1);
+
+ await openWorkspaceMenu(page);
+ await page.getByRole("menuitem", { name: "Log out" }).click();
+ await page.waitForURL("**/login", { timeout: 10_000, waitUntil: "domcontentloaded" });
+
+ await expect.poll(() => searchIndexDatabases(page)).toEqual([]);
+ });
+
+ test("deletes a workspace's local copy when the user is removed from it", async ({ page }) => {
+ const run = Date.now().toString(36);
+ const owner = new TestApiClient();
+ await owner.login(`e2e-owner-${run}@multica.ai`, "E2E Owner");
+ const shared = await owner.ensureWorkspace(`E2E Shared ${run}`, `e2e-shared-${run}`);
+ await owner.markUserOnboarded();
+ await owner.createIssue(`shared ${run} issue`);
+ try {
+ const memberId = await owner.addMemberByEmail(api.getEmail());
+ await loginAsDefault(page);
+
+ const synced = page.waitForResponse(isSearchIndexChanges, { timeout: 45_000 });
+ await page.goto(`/${shared.slug}/issues`, { waitUntil: "domcontentloaded" });
+ await synced;
+ const sharedCopy = (names: string[]) => names.some((name) => name.endsWith(`:${shared.id}`));
+ await expect.poll(async () => sharedCopy(await searchIndexDatabases(page))).toBe(true);
+
+ await owner.removeMember(memberId);
+
+ // The client relocates to a workspace the user still has; the removed
+ // workspace's copy must not survive on the device. A read that fails
+ // mid-navigation counts as "still there", so polling continues until a
+ // successful read confirms the deletion.
+ const unreadable = [`multica-search-index:unreadable:${shared.id}`];
+ await expect
+ .poll(async () => sharedCopy(await searchIndexDatabases(page).catch(() => unreadable)), { timeout: 20_000 })
+ .toBe(false);
+ } finally {
+ await owner.cleanup();
+ await owner.deleteWorkspace();
+ }
+ });
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 28e6089071..b7bd302160 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -1,3 +1,4 @@
+import type { ZodType } from "zod";
import type { IssueWakeup, IssueWakeupInput, IssueWakeupSummaryRow, PausedWakeup, SystemWakeup, WakeupRun, WorkspaceSystemWakeup } from "../types/issue-wakeup";
import type { WorkspaceWakeupPage, WorkspaceWakeupFilters } from "../types/issue-wakeup";
import { WorkspaceWakeupPageSchema, IssueWakeupSchema, IssueWakeupSummaryRowSchema, PausedWakeupSchema, SystemWakeupSchema, WakeupRunSchema, WorkspaceSystemWakeupSchema } from "./schemas";
@@ -15,6 +16,9 @@ import type {
ListIssuesResponse,
SearchIssuesResponse,
SearchProjectsResponse,
+ SearchIndexManifest,
+ SearchIndexSnapshotPage,
+ SearchIndexChanges,
UpdateMeRequest,
CreateMemberRequest,
UpdateMemberRequest,
@@ -332,6 +336,9 @@ import {
RuntimeUsageListSchema,
SearchIssuesResponseSchema,
SearchProjectsResponseSchema,
+ SearchIndexManifestSchema,
+ SearchIndexSnapshotPageSchema,
+ SearchIndexChangesSchema,
SquadSchema,
SquadListSchema,
SquadMemberStatusListResponseSchema,
@@ -520,6 +527,12 @@ export interface LoginResponse {
user: User;
}
+function parseSearchIndexResponse<T>(raw: unknown, schema: ZodType, endpoint: string): T {
+ const parsed = parseWithFallback<T | null>(raw, schema, null, { endpoint });
+ if (parsed === null) throw new Error(`Malformed response from ${endpoint}`);
+ return parsed;
+}
+
export class ApiError extends Error {
readonly status: number;
readonly statusText: string;
@@ -1236,6 +1249,48 @@ export class ApiClient {
});
}
+ // Local search index sync (MUL-7754). Each call names its workspace so a
+ // request issued for one workspace cannot be answered for whichever one the
+ // tab has switched to since. A body that fails its schema rejects rather
+ // than degrading: an empty page would be applied to the local copy as truth.
+ async getSearchIndexManifest(params: { workspaceSlug: string; signal?: AbortSignal }): Promise<SearchIndexManifest> {
+ const raw = await this.fetch<unknown>("/api/search-index/manifest", {
+ headers: { "X-Workspace-Slug": params.workspaceSlug },
+ signal: params.signal,
+ });
+ return parseSearchIndexResponse<SearchIndexManifest>(raw, SearchIndexManifestSchema, "GET /api/search-index/manifest");
+ }
+
+ async getSearchIndexSnapshot(params: {
+ workspaceSlug: string;
+ afterNumber: number;
+ limit?: number;
+ signal?: AbortSignal;
+ }): Promise<SearchIndexSnapshotPage> {
+ const search = new URLSearchParams({ after_number: String(params.afterNumber) });
+ if (params.limit !== undefined) search.set("limit", String(params.limit));
+ const raw = await this.fetch<unknown>(`/api/search-index/snapshot?${search}`, {
+ headers: { "X-Workspace-Slug": params.workspaceSlug },
+ signal: params.signal,
+ });
+ return parseSearchIndexResponse<SearchIndexSnapshotPage>(raw, SearchIndexSnapshotPageSchema, "GET /api/search-index/snapshot");
+ }
+
+ async getSearchIndexChanges(params: {
+ workspaceSlug: string;
+ cursor: string;
+ limit?: number;
+ signal?: AbortSignal;
+ }): Promise<SearchIndexChanges> {
+ const raw = await this.fetch<unknown>("/api/search-index/changes", {
+ method: "POST",
+ headers: { "X-Workspace-Slug": params.workspaceSlug },
+ body: JSON.stringify({ cursor: params.cursor, limit: params.limit }),
+ signal: params.signal,
+ });
+ return parseSearchIndexResponse<SearchIndexChanges>(raw, SearchIndexChangesSchema, "POST /api/search-index/changes");
+ }
+
/**
* Fetch one issue by UUID **or** by bare identifier ("MUL-123"): the server
* resolves `PREFIX-NUMBER` against the workspace's own prefix through the
diff --git a/packages/core/api/schema.test.ts b/packages/core/api/schema.test.ts
index 0769fe17b8..beee178890 100644
--- a/packages/core/api/schema.test.ts
+++ b/packages/core/api/schema.test.ts
@@ -532,6 +532,60 @@ describe("ApiClient schema fallback", () => {
});
});
+ // Local search index sync applies whatever these return to the local copy,
+ // so a malformed body rejects instead of degrading to an empty page.
+ describe("search index sync", () => {
+ it("sends the workspace slug and parses a snapshot page", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ issues: [],
+ comments: [{ id: "c1", issue_id: "i1", content: "hi", created_at: "2026-01-01T00:00:00.5Z" }],
+ projects: [],
+ next_after_number: 200,
+ done: false,
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ const page = await client.getSearchIndexSnapshot({ workspaceSlug: "acme", afterNumber: 0, limit: 200 });
+
+ expect(page.comments).toHaveLength(1);
+ expect(page.done).toBe(false);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(String(url)).toBe("https://api.example.test/api/search-index/snapshot?after_number=0&limit=200");
+ expect((init as RequestInit).headers).toMatchObject({ "X-Workspace-Slug": "acme" });
+ });
+
+ it("rejects malformed manifest, snapshot, and changes bodies", async () => {
+ const client = new ApiClient("https://api.example.test");
+
+ stubFetchJson({ cursor: "", issue_count: 0, comment_count: 0, project_count: 0, text_bytes: 0 });
+ await expect(client.getSearchIndexManifest({ workspaceSlug: "acme" })).rejects.toThrow(/Malformed response/);
+
+ stubFetchJson({ issues: "nope", comments: [], projects: [], next_after_number: 0, done: true });
+ await expect(client.getSearchIndexSnapshot({ workspaceSlug: "acme", afterNumber: 0 })).rejects.toThrow(
+ /Malformed response/,
+ );
+
+ stubFetchJson({ issues: [], comments: [], projects: [], cursor: "c2", has_more: false });
+ await expect(client.getSearchIndexChanges({ workspaceSlug: "acme", cursor: "c1" })).rejects.toThrow(
+ /Malformed response/,
+ );
+ });
+
+ it("surfaces an expired cursor as a 410 ApiError", async () => {
+ stubFetchJson({ error: "search index cursor expired; rebuild the local index" }, 410);
+ const client = new ApiClient("https://api.example.test");
+ const err = await client.getSearchIndexChanges({ workspaceSlug: "acme", cursor: "c1" }).catch((e) => e);
+ expect(err).toBeInstanceOf(ApiError);
+ expect((err as ApiError).status).toBe(410);
+ });
+ });
+
describe("listAutopilots", () => {
const baseAutopilot = {
id: "ap-1",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 8526df45c9..f21c39d81f 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -1431,6 +1431,53 @@ export const EMPTY_SEARCH_PROJECTS_RESPONSE: SearchProjectsResponse = {
projects: [],
};
+// Local search index sync (MUL-7754). Callers reject a response that fails
+// these schemas instead of degrading to an empty value: an empty snapshot page
+// or change set would be applied to the local copy as truth.
+const SearchIndexIssueSchema = IssueSchema.extend({
+ search_updated_at: z.string(),
+}).loose();
+
+const SearchIndexProjectSchema = ProjectSchema.extend({
+ search_updated_at: z.string(),
+}).loose();
+
+const SearchIndexCommentSchema = z.object({
+ id: z.string().min(1),
+ issue_id: z.string().min(1),
+ content: z.string(),
+ created_at: z.string(),
+}).loose();
+
+export const SearchIndexManifestSchema = z.object({
+ cursor: z.string().min(1),
+ issue_count: z.number(),
+ comment_count: z.number(),
+ project_count: z.number(),
+ text_bytes: z.number(),
+}).loose();
+
+export const SearchIndexSnapshotPageSchema = z.object({
+ issues: z.array(SearchIndexIssueSchema),
+ comments: z.array(SearchIndexCommentSchema),
+ projects: z.array(SearchIndexProjectSchema),
+ next_after_number: z.number(),
+ done: z.boolean(),
+}).loose();
+
+export const SearchIndexChangesSchema = z.object({
+ issues: z.array(SearchIndexIssueSchema),
+ comments: z.array(SearchIndexCommentSchema),
+ projects: z.array(SearchIndexProjectSchema),
+ deleted: z.object({
+ issues: z.array(z.string()),
+ comments: z.array(z.string()),
+ projects: z.array(z.string()),
+ }).loose(),
+ cursor: z.string().min(1),
+ has_more: z.boolean(),
+}).loose();
+
const IssueAssigneeGroupSchema = z.object({
id: z.string(),
assignee_type: z.string().nullable(),
diff --git a/packages/core/package.json b/packages/core/package.json
index 85e0de7761..b6301e6430 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -85,6 +85,7 @@
"./squads/stores": "./squads/stores/index.ts",
"./permissions": "./permissions/index.ts",
"./search/cancelled-rank": "./search/cancelled-rank.ts",
+ "./search-index": "./search-index/index.ts",
"./projects": "./projects/index.ts",
"./projects/queries": "./projects/queries.ts",
"./projects/mutations": "./projects/mutations.ts",
diff --git a/packages/core/platform/session-cleanup.ts b/packages/core/platform/session-cleanup.ts
index f81ee3ebc2..992eba79b1 100644
--- a/packages/core/platform/session-cleanup.ts
+++ b/packages/core/platform/session-cleanup.ts
@@ -1,5 +1,6 @@
import type { QueryClient } from "@tanstack/react-query";
import { resetAllRegisteredDrafts } from "../drafts/cleanup-registry";
+import { wipeLocalSearchIndex } from "../search-index/instance";
import type { StorageAdapter } from "../types/storage";
import type { Workspace } from "../types";
import { workspaceKeys } from "../workspace/queries";
@@ -68,5 +69,10 @@ export function clearClientSessionData(
// No-op on web (web doesn't write this key).
storage.removeItem("multica_tabs");
+ // The local search index holds a copy of every issue and comment the user
+ // could read. Deleting it is asynchronous; nothing waits on it because the
+ // next session attaches under its own user id either way.
+ void wipeLocalSearchIndex();
+
queryClient.clear();
}
diff --git a/packages/core/realtime/provider.tsx b/packages/core/realtime/provider.tsx
index 39b65b09d6..b7f63824f1 100644
--- a/packages/core/realtime/provider.tsx
+++ b/packages/core/realtime/provider.tsx
@@ -16,8 +16,10 @@ import type { StoreApi, UseBoundStore } from "zustand";
import type { AuthState } from "../auth/store";
import {
getCurrentSlug,
+ getCurrentWsId,
subscribeToCurrentSlug,
} from "../platform/workspace-storage";
+import { useLocalSearchIndexSync } from "../search-index/hooks";
import { createLogger } from "../logger";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
@@ -66,6 +68,7 @@ export function WSProvider({
getCurrentSlug,
() => null,
);
+ const wsId = useSyncExternalStore(subscribeToCurrentSlug, getCurrentWsId, () => null);
const [wsClient, setWsClient] = useState<WSClient | null>(null);
// Depend on identity primitives instead of the object reference so a parent
@@ -124,6 +127,9 @@ export function WSProvider({
// Centralized WS -> store sync (uses state so it re-subscribes when WS changes)
useRealtimeSync(wsClient, stores, onToast);
+ // Keeps this workspace's local search index attached and caught up.
+ useLocalSearchIndexSync(wsClient, user?.id ?? null, wsId, wsSlug);
+
const subscribe = useCallback(
(event: WSEventType, handler: EventHandler) => {
if (!wsClient) return () => {};
diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
index e350d01114..438ef422d4 100644
--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx
@@ -17,8 +17,15 @@ import {
markWorkspaceDeletePending,
unmarkWorkspaceDeletePending,
} from "../workspace/pending-delete";
+import { setApiInstance } from "../api";
+import type { ApiClient } from "../api/client";
+import { forgetLocalSearchIndex } from "../search-index/instance";
import { useRealtimeSync, type RealtimeSyncStores } from "./use-realtime-sync";
+vi.mock("../search-index/instance", () => ({
+ forgetLocalSearchIndex: vi.fn(async () => undefined),
+}));
+
vi.mock("../platform/workspace-storage", () => ({
getCurrentWsId: () => "ws-1",
getCurrentSlug: () => "test-ws",
@@ -432,6 +439,7 @@ describe("useRealtimeSync — workspace:deleted self-initiated suppression", ()
afterEach(() => {
unmarkWorkspaceDeletePending("ws-2");
localStorage.clear();
+ vi.mocked(forgetLocalSearchIndex).mockClear();
});
// getCurrentWsId is mocked to "ws-1" at module level, so deleting "ws-2"
@@ -460,6 +468,7 @@ describe("useRealtimeSync — workspace:deleted self-initiated suppression", ()
// useDeleteWorkspace.onSuccess owns cleanup for self-initiated deletes;
// the handler must not have touched storage.
expect(defaultStorage.getItem("multica_issue_draft:delete-me")).toBe("draft");
+ expect(forgetLocalSearchIndex).not.toHaveBeenCalled();
});
it("still cleans up for a delete initiated elsewhere", () => {
@@ -473,5 +482,34 @@ describe("useRealtimeSync — workspace:deleted self-initiated suppression", ()
dispatchWorkspaceDeleted(ws, "ws-2");
expect(defaultStorage.getItem("multica_issue_draft:delete-me")).toBeNull();
+ // Not the current workspace, but its local search copy must still go.
+ expect(forgetLocalSearchIndex).toHaveBeenCalledWith("ws-2");
+ });
+});
+
+describe("useRealtimeSync — member:removed", () => {
+ afterEach(() => {
+ vi.mocked(forgetLocalSearchIndex).mockClear();
+ });
+
+ const dispatchMemberRemoved = (ws: WSClient, payload: Record<string, string>) => {
+ const call = vi.mocked(ws.on).mock.calls.find(([event]) => event === "member:removed");
+ expect(call).toBeDefined();
+ (call![1] as (p: unknown) => void)(payload);
+ };
+
+ it("destroys the local search copy when this user is removed", async () => {
+ setApiInstance({ listWorkspaces: vi.fn().mockResolvedValue([]) } as unknown as ApiClient);
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const ws = createMockWs();
+ renderHook(() => useRealtimeSync(ws, createStores()), { wrapper: createWrapper(qc) });
+
+ dispatchMemberRemoved(ws, { member_id: "m2", user_id: "someone-else", workspace_id: "ws-1" });
+ expect(forgetLocalSearchIndex).not.toHaveBeenCalled();
+
+ dispatchMemberRemoved(ws, { member_id: "m1", user_id: "u1", workspace_id: "ws-1" });
+ expect(forgetLocalSearchIndex).toHaveBeenCalledWith("ws-1");
+ // Let the relocate lookup settle before the test tears down.
+ await waitFor(() => expect(qc.getQueryData(workspaceKeys.list())).toEqual([]));
});
});
diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.ts
index 937fed3c0c..8ba91ca0f2 100644
--- a/packages/core/realtime/use-realtime-sync.ts
+++ b/packages/core/realtime/use-realtime-sync.ts
@@ -1,6 +1,7 @@
"use client";
import { useEffect, useRef } from "react";
+import { forgetLocalSearchIndex } from "../search-index/instance";
import { useQueryClient, type InfiniteData, type QueryClient } from "@tanstack/react-query";
import type { WSClient } from "../api/ws-client";
import type { StoreApi, UseBoundStore } from "zustand";
@@ -1278,6 +1279,9 @@ export function useRealtimeSync(
// CancelledError + reload combo this guard exists to prevent. This
// handler only serves deletes initiated elsewhere (other user/device).
if (isWorkspaceDeletePending(workspace_id)) return;
+ // Any deleted workspace, not only the current one: its local search
+ // copy must not outlive it.
+ void forgetLocalSearchIndex(workspace_id);
// Event payload has UUID; look up slug from cached workspace list
// since clearWorkspaceStorage keys are namespaced by slug.
const wsList = qc.getQueryData<{ id: string; slug: string }[]>(workspaceKeys.list()) ?? [];
@@ -1291,9 +1295,11 @@ export function useRealtimeSync(
});
const unsubMemberRemoved = ws.on("member:removed", (p) => {
- const { user_id } = p as MemberRemovedPayload;
+ const { user_id, workspace_id } = p as MemberRemovedPayload;
const myUserId = authStore.getState().user?.id;
if (user_id === myUserId) {
+ const lostWsId = workspace_id || getCurrentWsId();
+ if (lostWsId) void forgetLocalSearchIndex(lostWsId);
const slug = getCurrentSlug();
const wsId = getCurrentWsId();
if (slug && wsId) {
diff --git a/packages/core/search-index/client.test.ts b/packages/core/search-index/client.test.ts
new file mode 100644
index 0000000000..025cdda5fe
--- /dev/null
+++ b/packages/core/search-index/client.test.ts
@@ -0,0 +1,193 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { ApiError } from "../api/client";
+import { LocalSearchIndexClient, type SearchIndexApi, type WorkerChannel } from "./client";
+import type { TabMessage, WorkerMessage } from "./protocol";
+import { deleteSearchIndexDatabases, type SearchIndexDatabaseOwner } from "./store";
+
+vi.mock("./store", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./store")>()),
+ deleteSearchIndexDatabases: vi.fn(async () => undefined),
+}));
+
+/** The owners the last deleteSearchIndexDatabases call would delete. */
+function deletedAmong(owners: SearchIndexDatabaseOwner[]): string[] {
+ const shouldDelete = vi.mocked(deleteSearchIndexDatabases).mock.calls.at(-1)![0];
+ return owners.filter(shouldDelete).map((o) => `${o.userId}:${o.workspaceId}`);
+}
+
+const target = { userId: "user", workspaceId: "ws", workspaceSlug: "acme" };
+
+function fakeChannel() {
+ const posted: TabMessage[] = [];
+ let deliver: (message: WorkerMessage) => void = () => undefined;
+ let fail: () => void = () => undefined;
+ const channel: WorkerChannel = {
+ post: (message) => posted.push(message),
+ onMessage: (handler) => {
+ deliver = handler;
+ },
+ onError: (handler) => {
+ fail = handler;
+ },
+ };
+ return { channel, posted, deliver: (m: WorkerMessage) => deliver(m), fail: () => fail() };
+}
+
+function fakeApi(): SearchIndexApi {
+ return {
+ getSearchIndexManifest: vi.fn(async () => ({
+ cursor: "c1",
+ issue_count: 0,
+ comment_count: 0,
+ project_count: 0,
+ text_bytes: 0,
+ })),
+ getSearchIndexSnapshot: vi.fn(),
+ getSearchIndexChanges: vi.fn(async () => {
+ throw new ApiError("workspace not found", 404, "Not Found");
+ }),
+ };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.mocked(deleteSearchIndexDatabases).mockClear();
+});
+
+describe("LocalSearchIndexClient", () => {
+ it("answers null everywhere when no worker can start", async () => {
+ const client = new LocalSearchIndexClient(fakeApi, () => null);
+ client.attach(target);
+ expect(client.isServing()).toBe(false);
+ expect(await client.searchIssues({ q: "anything" })).toBeNull();
+ await expect(client.wipe()).resolves.toBeUndefined();
+ });
+
+ it("searches locally only once the worker reports the workspace is serving", async () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ expect(worker.posted[0]).toEqual({ type: "attach", target });
+ expect(await client.searchIssues({ q: "early" })).toBeNull();
+
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+ expect(client.isServing()).toBe(true);
+
+ const pending = client.searchIssues({ q: "needle", limit: 5, include_closed: true });
+ const request = worker.posted.at(-1);
+ expect(request).toMatchObject({ type: "search", kind: "issues", params: { q: "needle", limit: 5, include_closed: true } });
+ worker.deliver({ type: "search-result", id: (request as { id: number }).id, result: { issues: [] } });
+ expect(await pending).toEqual({ issues: [] });
+ });
+
+ it("gives up on a slow search so the caller can ask the server", async () => {
+ vi.useFakeTimers();
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+
+ const pending = client.searchIssues({ q: "slow" });
+ await vi.advanceTimersByTimeAsync(2_000);
+ expect(await pending).toBeNull();
+ });
+
+ it("ignores serving updates for another workspace and resets on retarget", () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:other", serving: true });
+ expect(client.isServing()).toBe(false);
+
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+ client.attach({ ...target, workspaceId: "ws2", workspaceSlug: "beta" });
+ expect(client.isServing()).toBe(false);
+ });
+
+ it("runs the worker's requests through the API with the workspace slug", async () => {
+ const api = fakeApi();
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(() => api, () => worker.channel);
+ client.attach(target);
+
+ worker.deliver({ type: "fetch", id: 1, op: "manifest", workspaceSlug: "acme", params: {} });
+ worker.deliver({ type: "fetch", id: 2, op: "changes", workspaceSlug: "acme", params: { cursor: "c1", limit: 10 } });
+ await vi.waitFor(() => expect(worker.posted.filter((m) => m.type === "fetch-result")).toHaveLength(2));
+
+ expect(api.getSearchIndexManifest).toHaveBeenCalledWith({ workspaceSlug: "acme" });
+ expect(api.getSearchIndexChanges).toHaveBeenCalledWith({ workspaceSlug: "acme", cursor: "c1", limit: 10 });
+ const results = worker.posted.filter((m) => m.type === "fetch-result");
+ expect(results).toContainEqual(expect.objectContaining({ id: 1, ok: true }));
+ expect(results).toContainEqual(expect.objectContaining({ id: 2, ok: false, status: 404 }));
+ });
+
+ it("stops using a worker that failed", async () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+
+ worker.fail();
+ expect(client.isServing()).toBe(false);
+ expect(await client.searchIssues({ q: "after failure" })).toBeNull();
+ });
+
+ it("stops treating searches as local when the worker cannot answer", async () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+
+ const pending = client.searchIssues({ q: "lost" });
+ const request = worker.posted.at(-1) as { id: number };
+ worker.deliver({ type: "search-result", id: request.id, result: null });
+ expect(await pending).toBeNull();
+ // Back to the debounced server path until the worker reports serving.
+ expect(client.isServing()).toBe(false);
+ });
+
+ it("forgets a workspace through the worker and on disk", async () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+ worker.deliver({ type: "hello" });
+ worker.deliver({ type: "serving", key: "user:ws", serving: true });
+
+ await client.forget("ws");
+
+ expect(worker.posted.at(-1)).toEqual({ type: "forget", workspaceId: "ws" });
+ expect(deletedAmong([
+ { userId: "user", workspaceId: "ws" },
+ { userId: "other", workspaceId: "ws" },
+ { userId: "user", workspaceId: "ws2" },
+ ])).toEqual(["user:ws", "other:ws"]);
+ expect(client.isServing()).toBe(false);
+ });
+
+ it("prunes through the worker when it is up, and on disk otherwise", async () => {
+ const worker = fakeChannel();
+ const client = new LocalSearchIndexClient(fakeApi, () => worker.channel);
+ client.attach(target);
+
+ // Before the worker says hello: the tab prunes itself, sparing what it shows.
+ await client.prune("user", ["ws2"]);
+ expect(deletedAmong([
+ { userId: "user", workspaceId: "ws" },
+ { userId: "user", workspaceId: "ws2" },
+ { userId: "user", workspaceId: "gone" },
+ { userId: "other", workspaceId: "ws2" },
+ ])).toEqual(["user:gone", "other:ws2"]);
+
+ worker.deliver({ type: "hello" });
+ vi.mocked(deleteSearchIndexDatabases).mockClear();
+ await client.prune("user", ["ws", "ws2"]);
+ expect(worker.posted.at(-1)).toEqual({ type: "prune", userId: "user", workspaceIds: ["ws", "ws2"] });
+ expect(deleteSearchIndexDatabases).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/search-index/client.ts b/packages/core/search-index/client.ts
new file mode 100644
index 0000000000..15449b401e
--- /dev/null
+++ b/packages/core/search-index/client.ts
@@ -0,0 +1,317 @@
+import { ApiError } from "../api/client";
+import type {
+ SearchIndexChanges,
+ SearchIndexManifest,
+ SearchIndexSnapshotPage,
+ SearchIssuesResponse,
+ SearchProjectsResponse,
+} from "../types";
+import type { IssueSearchParams } from "./engine";
+import { indexTargetKey, type IndexTarget, type TabMessage, type WorkerMessage } from "./protocol";
+import { deleteAllSearchIndexDatabases, deleteSearchIndexDatabases } from "./store";
+
+/**
+ * Tab-side handle on the local search index worker (MUL-7754). Everything here
+ * degrades to "not available": a platform without workers, a worker that
+ * failed to load, a workspace that is still syncing, or a search that takes
+ * too long all make `searchIssues` resolve to null, and callers use server
+ * search instead.
+ */
+
+/** The API calls the worker delegates to this tab. */
+export interface SearchIndexApi {
+ getSearchIndexManifest(params: { workspaceSlug: string }): Promise<SearchIndexManifest>;
+ getSearchIndexSnapshot(params: { workspaceSlug: string; afterNumber: number; limit?: number }): Promise<SearchIndexSnapshotPage>;
+ getSearchIndexChanges(params: { workspaceSlug: string; cursor: string; limit?: number }): Promise<SearchIndexChanges>;
+}
+
+/** A started worker, reduced to what the client needs. */
+export interface WorkerChannel {
+ post(message: TabMessage): void;
+ onMessage(handler: (message: WorkerMessage) => void): void;
+ onError(handler: () => void): void;
+}
+
+const SEARCH_TIMEOUT_MS = 1500;
+const PING_INTERVAL_MS = 20_000;
+
+export class LocalSearchIndexClient {
+ private channel: WorkerChannel | null = null;
+ private failed = false;
+ private helloReceived = false;
+ private target: IndexTarget | null = null;
+ private serving = false;
+ private nextId = 1;
+ private readonly searches = new Map<number, (result: SearchIssuesResponse | SearchProjectsResponse | null) => void>();
+ private readonly wipes = new Map<number, () => void>();
+
+ constructor(
+ private readonly getApi: () => SearchIndexApi,
+ private readonly startWorker: () => WorkerChannel | null,
+ ) {}
+
+ /** Starts (or retargets) syncing for the workspace this tab shows. */
+ attach(target: IndexTarget): void {
+ const current = this.target;
+ if (
+ current &&
+ indexTargetKey(current) === indexTargetKey(target) &&
+ current.workspaceSlug === target.workspaceSlug
+ ) {
+ return;
+ }
+ if (!current || indexTargetKey(current) !== indexTargetKey(target)) this.serving = false;
+ this.target = target;
+ const channel = this.ensureChannel();
+ channel?.post({ type: "attach", target });
+ requestPersistentStorage();
+ }
+
+ detach(): void {
+ if (!this.target) return;
+ this.target = null;
+ this.serving = false;
+ this.channel?.post({ type: "detach" });
+ }
+
+ /** Something changed on the server; catch up soon. */
+ poke(): void {
+ if (this.target) this.channel?.post({ type: "poke" });
+ }
+
+ /** Whether the attached workspace can currently be searched locally. */
+ isServing(): boolean {
+ return this.serving && this.helloReceived && !this.failed;
+ }
+
+ searchIssues(params: IssueSearchParams): Promise<SearchIssuesResponse | null> {
+ return this.search("issues", params) as Promise<SearchIssuesResponse | null>;
+ }
+
+ searchProjects(params: IssueSearchParams): Promise<SearchProjectsResponse | null> {
+ return this.search("projects", params) as Promise<SearchProjectsResponse | null>;
+ }
+
+ /**
+ * Deletes every local index on this device (logout, session end). Falls
+ * back to deleting the databases from this tab when no worker answers.
+ */
+ async wipe(): Promise<void> {
+ this.target = null;
+ this.serving = false;
+ const channel = this.usableChannel();
+ if (channel) {
+ const id = this.nextId++;
+ const done = new Promise<void>((resolve) => {
+ this.wipes.set(id, resolve);
+ setTimeout(resolve, 5_000);
+ });
+ channel.post({ type: "wipe", id });
+ await done;
+ this.wipes.delete(id);
+ }
+ await deleteAllSearchIndexDatabases().catch(() => undefined);
+ }
+
+ /**
+ * Access to a workspace ended (deleted, removed, left): destroy every local
+ * copy of it now, rather than waiting for a sync that may never run again
+ * because no tab shows that workspace any more.
+ */
+ forget(workspaceId: string): Promise<void> {
+ if (this.target?.workspaceId === workspaceId) {
+ this.target = null;
+ this.serving = false;
+ }
+ // The worker drops the copy from memory and stops syncing it. The tab
+ // deletes the database itself as well: this usually runs just before a
+ // full-page navigation, which may end the worker before its delete does.
+ this.usableChannel()?.post({ type: "forget", workspaceId });
+ return deleteSearchIndexDatabases((owner) => owner.workspaceId === workspaceId).catch(() => undefined);
+ }
+
+ /** Destroys local copies of any workspace (or user) outside this list. */
+ prune(userId: string, workspaceIds: string[]): Promise<void> {
+ const channel = this.usableChannel();
+ if (channel) {
+ channel.post({ type: "prune", userId, workspaceIds });
+ return Promise.resolve();
+ }
+ const keep = new Set(workspaceIds);
+ const shown = this.target;
+ return deleteSearchIndexDatabases(
+ (owner) =>
+ !(owner.userId === userId && keep.has(owner.workspaceId)) &&
+ !(shown && owner.userId === shown.userId && owner.workspaceId === shown.workspaceId),
+ ).catch(() => undefined);
+ }
+
+ private usableChannel(): WorkerChannel | null {
+ return this.helloReceived && !this.failed ? this.channel : null;
+ }
+
+ private search(kind: "issues" | "projects", params: IssueSearchParams) {
+ const channel = this.channel;
+ if (!channel || !this.target || !this.isServing()) return Promise.resolve(null);
+ const id = this.nextId++;
+ return new Promise<SearchIssuesResponse | SearchProjectsResponse | null>((resolve) => {
+ const timer = setTimeout(() => {
+ this.searches.delete(id);
+ resolve(null);
+ }, SEARCH_TIMEOUT_MS);
+ this.searches.set(id, (result) => {
+ clearTimeout(timer);
+ // The worker could not answer (it lost this tab's attachment, or the
+ // copy went stale). Stop treating searches as local, which also
+ // restores the server-search debounce, until it reports serving again.
+ if (result === null) this.serving = false;
+ resolve(result);
+ });
+ const { q, limit, offset, include_closed } = params;
+ channel.post({ type: "search", id, kind, params: { q, limit, offset, include_closed } });
+ });
+ }
+
+ private ensureChannel(): WorkerChannel | null {
+ if (this.channel || this.failed) return this.channel;
+ let channel: WorkerChannel | null = null;
+ try {
+ channel = this.startWorker();
+ } catch {
+ channel = null;
+ }
+ if (!channel) {
+ this.failed = true;
+ return null;
+ }
+ this.channel = channel;
+ channel.onMessage((message) => this.handle(message));
+ channel.onError(() => {
+ this.failed = true;
+ this.serving = false;
+ for (const resolve of this.searches.values()) resolve(null);
+ this.searches.clear();
+ });
+ // Lets the worker tell a live tab from one that closed without pagehide.
+ setInterval(() => this.channel?.post({ type: "ping" }), PING_INTERVAL_MS);
+ if (typeof window !== "undefined") {
+ window.addEventListener("pagehide", () => this.channel?.post({ type: "close" }));
+ // A page restored from the back/forward cache said "close" on the way
+ // out, so the worker forgot it; attach again.
+ window.addEventListener("pageshow", (event) => {
+ if (event.persisted && this.target) this.channel?.post({ type: "attach", target: this.target });
+ });
+ }
+ return channel;
+ }
+
+ private handle(message: WorkerMessage): void {
+ switch (message.type) {
+ case "hello":
+ this.helloReceived = true;
+ return;
+ case "serving":
+ if (this.target && indexTargetKey(this.target) === message.key) this.serving = message.serving;
+ return;
+ case "search-result":
+ this.searches.get(message.id)?.(message.result);
+ this.searches.delete(message.id);
+ return;
+ case "wiped":
+ this.wipes.get(message.id)?.();
+ return;
+ case "fetch":
+ void this.runFetch(message);
+ return;
+ }
+ }
+
+ private async runFetch(message: Extract<WorkerMessage, { type: "fetch" }>): Promise<void> {
+ const api = this.getApi();
+ const { workspaceSlug, params } = message;
+ try {
+ let data: unknown;
+ switch (message.op) {
+ case "manifest":
+ data = await api.getSearchIndexManifest({ workspaceSlug });
+ break;
+ case "snapshot":
+ data = await api.getSearchIndexSnapshot({ workspaceSlug, afterNumber: params.afterNumber ?? 0, limit: params.limit });
+ break;
+ case "changes":
+ data = await api.getSearchIndexChanges({ workspaceSlug, cursor: params.cursor ?? "", limit: params.limit });
+ break;
+ }
+ this.channel?.post({ type: "fetch-result", id: message.id, ok: true, data });
+ } catch (err) {
+ this.channel?.post({
+ type: "fetch-result",
+ id: message.id,
+ ok: false,
+ status: err instanceof ApiError ? err.status : undefined,
+ message: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+}
+
+let persistRequested = false;
+
+/** Asks the browser not to evict the index under storage pressure (best effort). */
+function requestPersistentStorage(): void {
+ if (persistRequested) return;
+ persistRequested = true;
+ const storage = typeof navigator !== "undefined" ? navigator.storage : undefined;
+ void storage?.persist?.().catch(() => false);
+}
+
+/**
+ * Starts the worker: one SharedWorker for every tab of the origin where
+ * available, otherwise a dedicated worker for this tab. The `new URL(...)`
+ * expressions must stay literal so webpack and Vite bundle the worker.
+ */
+export function startSearchIndexWorker(): WorkerChannel | null {
+ if (typeof window === "undefined") return null;
+ if (typeof SharedWorker !== "undefined") {
+ try {
+ const worker = new SharedWorker(new URL("./worker.ts", import.meta.url), {
+ type: "module",
+ name: "multica-search-index",
+ });
+ const port = worker.port;
+ const channel: WorkerChannel = {
+ post: (message) => port.postMessage(message),
+ onMessage: (handler) => {
+ port.onmessage = (event: MessageEvent<WorkerMessage>) => handler(event.data);
+ },
+ onError: (handler) => {
+ worker.onerror = handler;
+ },
+ };
+ port.start();
+ return channel;
+ } catch {
+ // Fall through to a dedicated worker.
+ }
+ }
+ if (typeof Worker !== "undefined") {
+ try {
+ const worker = new Worker(new URL("./worker.ts", import.meta.url), {
+ type: "module",
+ name: "multica-search-index",
+ });
+ return {
+ post: (message) => worker.postMessage(message),
+ onMessage: (handler) => {
+ worker.onmessage = (event: MessageEvent<WorkerMessage>) => handler(event.data);
+ },
+ onError: (handler) => {
+ worker.onerror = handler;
+ },
+ };
+ } catch {
+ return null;
+ }
+ }
+ return null;
+}
diff --git a/packages/core/search-index/engine.test.ts b/packages/core/search-index/engine.test.ts
new file mode 100644
index 0000000000..d793298e00
--- /dev/null
+++ b/packages/core/search-index/engine.test.ts
@@ -0,0 +1,373 @@
+// @vitest-environment node
+import { describe, expect, it } from "vitest";
+import type { SearchIndexComment, SearchIndexIssue, SearchIndexProject } from "../types";
+import {
+ SearchIndexEngine,
+ utf8Length,
+ extractSnippet,
+ splitSearchTerms,
+ timestampMicros,
+ toSearchIssueResult,
+ toSearchProjectResult,
+} from "./engine";
+
+let seq = 0;
+
+function issue(overrides: Partial<SearchIndexIssue> & { title: string }): SearchIndexIssue {
+ seq += 1;
+ const id = overrides.id ?? `00000000-0000-0000-0000-${String(seq).padStart(12, "0")}`;
+ return {
+ id,
+ workspace_id: "ws",
+ number: seq,
+ identifier: `MUL-${overrides.number ?? seq}`,
+ description: null,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "user",
+ parent_issue_id: null,
+ project_id: null,
+ position: 0,
+ stage: null,
+ start_date: null,
+ due_date: null,
+ metadata: {},
+ properties: {},
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ search_updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ } as SearchIndexIssue;
+}
+
+function comment(issueId: string, content: string, createdAt: string, id?: string): SearchIndexComment {
+ seq += 1;
+ return {
+ id: id ?? `c0000000-0000-0000-0000-${String(seq).padStart(12, "0")}`,
+ issue_id: issueId,
+ content,
+ created_at: createdAt,
+ };
+}
+
+function project(overrides: Partial<SearchIndexProject> & { title: string }): SearchIndexProject {
+ seq += 1;
+ return {
+ id: `p0000000-0000-0000-0000-${String(seq).padStart(12, "0")}`,
+ workspace_id: "ws",
+ description: null,
+ icon: null,
+ status: "planned",
+ priority: "none",
+ lead_type: null,
+ lead_id: null,
+ start_date: null,
+ due_date: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ issue_count: 0,
+ done_count: 0,
+ resource_count: 0,
+ search_updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ } as SearchIndexProject;
+}
+
+function engineWith(issues: SearchIndexIssue[], comments: SearchIndexComment[] = []) {
+ const engine = new SearchIndexEngine();
+ issues.forEach((i) => engine.upsertIssue(i));
+ comments.forEach((c) => engine.upsertComment(c));
+ return engine;
+}
+
+describe("SearchIndexEngine.searchIssues ranking", () => {
+ it("orders the relevance tiers the way server search does", () => {
+ const at = (minute: number) => `2026-01-01T00:${String(minute).padStart(2, "0")}:00Z`;
+ const commentAll = issue({ title: "unrelated five", search_updated_at: at(9) });
+ const commentPhrase = issue({ title: "unrelated four", search_updated_at: at(8) });
+ const descAll = issue({ title: "unrelated three", description: "gamma then alpha", search_updated_at: at(7) });
+ const descPhrase = issue({ title: "unrelated two", description: "has alpha gamma inside", search_updated_at: at(6) });
+ const titleAll = issue({ title: "gamma before alpha", search_updated_at: at(5) });
+ const titleContains = issue({ title: "the alpha gamma here", search_updated_at: at(4) });
+ const titleStarts = issue({ title: "alpha gamma first", search_updated_at: at(3) });
+ const titleExact = issue({ title: "Alpha Gamma", search_updated_at: at(2) });
+ const engine = engineWith(
+ [commentAll, commentPhrase, descAll, descPhrase, titleAll, titleContains, titleStarts, titleExact],
+ [
+ comment(commentPhrase.id, "comment says alpha gamma", at(1)),
+ comment(commentAll.id, "gamma and later alpha", at(1)),
+ ],
+ );
+
+ const hits = engine.searchIssues({ q: "alpha gamma", include_closed: true });
+ expect(hits.map((h) => h.id)).toEqual([
+ titleExact.id,
+ titleStarts.id,
+ titleContains.id,
+ titleAll.id,
+ descPhrase.id,
+ descAll.id,
+ commentPhrase.id,
+ commentAll.id,
+ ]);
+ expect(hits.map((h) => h.matchSource)).toEqual([
+ "title",
+ "title",
+ "title",
+ "title",
+ "description",
+ "description",
+ "comment",
+ "comment",
+ ]);
+ });
+
+ it("breaks ties by status, then precise updated_at, then id", () => {
+ const backlog = issue({ title: "tie token", status: "backlog", search_updated_at: "2026-01-01T00:00:00.000009Z" });
+ const inProgress = issue({ title: "tie token", status: "in_progress", search_updated_at: "2026-01-01T00:00:00Z" });
+ const older = issue({ title: "tie token", status: "todo", search_updated_at: "2026-01-01T00:00:00.000001Z" });
+ const newer = issue({ title: "tie token", status: "todo", search_updated_at: "2026-01-01T00:00:00.000002Z" });
+ const sameA = issue({ id: "a0000000-0000-0000-0000-000000000000", title: "tie token", status: "blocked" });
+ const sameB = issue({ id: "b0000000-0000-0000-0000-000000000000", title: "tie token", status: "blocked" });
+ const engine = engineWith([backlog, sameB, older, inProgress, newer, sameA]);
+
+ expect(engine.searchIssues({ q: "tie token" }).map((h) => h.id)).toEqual([
+ inProgress.id,
+ newer.id,
+ older.id,
+ sameA.id,
+ sameB.id,
+ backlog.id,
+ ]);
+ });
+
+ it("puts an exact identifier or bare number first, even without a text match", () => {
+ const target = issue({ title: "no text overlap", number: 4242, identifier: "MUL-4242" });
+ const textHit = issue({ title: "mentions 4242 in the title" });
+ const engine = engineWith([textHit, target]);
+
+ const byIdentifier = engine.searchIssues({ q: "mul-4242" });
+ expect(byIdentifier.map((h) => h.id)).toEqual([target.id]);
+ expect(byIdentifier[0]!.matchSource).toBe("comment");
+
+ expect(engine.searchIssues({ q: "4242" }).map((h) => h.id)).toEqual([target.id, textHit.id]);
+ });
+
+ it("demotes cancelled issues unless the query targets them directly", () => {
+ const cancelled = issue({ title: "billing export", status: "cancelled" });
+ const live = issue({ title: "old billing export job", status: "done" });
+ const engine = engineWith([cancelled, live]);
+
+ expect(engine.searchIssues({ q: "billing", include_closed: true }).map((h) => h.id)).toEqual([live.id, cancelled.id]);
+ expect(engine.searchIssues({ q: "Billing Export", include_closed: true }).map((h) => h.id)).toEqual([
+ cancelled.id,
+ live.id,
+ ]);
+ });
+
+ it("drops terminal statuses unless include_closed, keeping unknown custom keys", () => {
+ const open = issue({ title: "closure probe open" });
+ const done = issue({ title: "closure probe done", status: "done" });
+ const customDone = issue({ title: "closure probe shipped", status: "shipped", status_category: "done" });
+ const customClosed = issue({ title: "closure probe dropped", status: "dropped", status_category: "closed" });
+ const unknownKey = issue({ title: "closure probe legacy", status: "legacy_key" });
+ const engine = engineWith([open, done, customDone, customClosed, unknownKey]);
+
+ expect(new Set(engine.searchIssues({ q: "closure probe" }).map((h) => h.id))).toEqual(
+ new Set([open.id, unknownKey.id]),
+ );
+ expect(engine.searchIssues({ q: "closure probe", include_closed: true })).toHaveLength(5);
+ });
+
+ it("lets terms spread across title, description and different comments", () => {
+ const spread = issue({ title: "north part", description: "south part" });
+ const partial = issue({ title: "north only" });
+ const engine = engineWith(
+ [spread, partial],
+ [comment(spread.id, "east part", "2026-01-01T00:00:00Z"), comment(partial.id, "east part", "2026-01-01T00:00:00Z")],
+ );
+
+ const hits = engine.searchIssues({ q: "north south east" });
+ expect(hits.map((h) => h.id)).toEqual([spread.id]);
+ // No single comment holds every term, so there is no comment snippet.
+ expect(hits[0]!.snippetCommentId).toBeNull();
+ });
+
+ it("ranks all terms in one comment above terms split across comments", () => {
+ const same = issue({ title: "same comment" });
+ const split = issue({ title: "split comments" });
+ const at = "2026-01-01T00:00:00Z";
+ const sameComment = comment(same.id, "red and blue", at);
+ const engine = engineWith(
+ [split, same],
+ [sameComment, comment(split.id, "red", at), comment(split.id, "blue", at)],
+ );
+
+ const hits = engine.searchIssues({ q: "blue red" });
+ expect(hits.map((h) => h.id)).toEqual([same.id, split.id]);
+ expect(hits[0]!.snippetCommentId).toBe(sameComment.id);
+ });
+
+ it("picks the latest matching comment for the snippet", () => {
+ const target = issue({ title: "snippet source" });
+ const older = comment(target.id, "needle older", "2026-01-01T00:00:00.000001Z");
+ const newer = comment(target.id, "needle newer", "2026-01-01T00:00:00.000002Z");
+ const unrelated = comment(target.id, "nothing here", "2026-01-02T00:00:00Z");
+ const engine = engineWith([target], [newer, unrelated, older]);
+
+ expect(engine.searchIssues({ q: "needle" })[0]!.snippetCommentId).toBe(newer.id);
+ });
+
+ it("treats LIKE wildcards in the query as literal text", () => {
+ const percent = issue({ title: "load 100% done" });
+ const underscore = issue({ title: "a_b" });
+ const decoy = issue({ title: "load 1000 done axb" });
+ const engine = engineWith([percent, underscore, decoy]);
+
+ expect(engine.searchIssues({ q: "100%" }).map((h) => h.id)).toEqual([percent.id]);
+ // The server compares exact titles against the escaped phrase, so a title
+ // with "_" never reaches the exact tier; it still starts with the phrase.
+ const underscoreHits = engine.searchIssues({ q: "a_b" });
+ expect(underscoreHits.map((h) => h.id)).toEqual([underscore.id]);
+ });
+
+ it("matches case-insensitively and splits on full-width spaces", () => {
+ const target = issue({ title: "搜索 性能 Optimization" });
+ const engine = engineWith([target]);
+
+ expect(splitSearchTerms("搜索 optimization")).toEqual(["搜索", "optimization"]);
+ expect(engine.searchIssues({ q: "OPTIMIZATION" }).map((h) => h.id)).toEqual([target.id]);
+ expect(engine.searchIssues({ q: "optimization 搜索" }).map((h) => h.id)).toEqual([target.id]);
+ });
+
+ it("applies limit and offset after ranking, capped at 50", () => {
+ const issues = Array.from({ length: 60 }, (_, i) =>
+ issue({ title: `paged ${i}`, search_updated_at: `2026-01-01T00:00:${String(i).padStart(2, "0")}Z` }),
+ );
+ const engine = engineWith(issues);
+
+ expect(engine.searchIssues({ q: "paged" })).toHaveLength(20);
+ expect(engine.searchIssues({ q: "paged", limit: 500 })).toHaveLength(50);
+ const second = engine.searchIssues({ q: "paged", limit: 5, offset: 5 });
+ expect(second.map((h) => h.id)).toEqual(issues.slice(50, 55).reverse().map((i) => i.id));
+ });
+
+ it("forgets deleted issues and comments", () => {
+ const target = issue({ title: "keeper" });
+ const doomed = comment(target.id, "vanishing phrase", "2026-01-01T00:00:00Z");
+ const engine = engineWith([target], [doomed]);
+ expect(engine.searchIssues({ q: "vanishing" })).toHaveLength(1);
+
+ engine.deleteComment(doomed.id);
+ expect(engine.searchIssues({ q: "vanishing" })).toHaveLength(0);
+ engine.upsertComment(comment(target.id, "orphan text", "2026-01-01T00:00:00Z"));
+ engine.deleteIssues([target.id]);
+ expect(engine.searchIssues({ q: "keeper" })).toHaveLength(0);
+ expect(engine.size.comments).toBe(0);
+ });
+});
+
+describe("toSearchIssueResult", () => {
+ it("returns the server row shape with comment and description snippets", () => {
+ const record = issue({ title: "Snippet row", description: "The description mentions a Needle once." });
+ const matched = comment(record.id, "A comment with the needle inside", "2026-01-01T00:00:00Z");
+ const row = toSearchIssueResult(record, { id: record.id, matchSource: "comment", snippetCommentId: matched.id }, "needle", matched);
+
+ expect(row).not.toHaveProperty("search_updated_at");
+ expect(row.match_source).toBe("comment");
+ expect(row.matched_comment_snippet).toBe("A comment with the needle inside");
+ expect(row.matched_snippet).toBe(row.matched_comment_snippet);
+ expect(row.matched_description_snippet).toBe("The description mentions a Needle once.");
+ });
+
+ it("omits snippets that do not apply", () => {
+ const record = issue({ title: "needle in title", description: "nothing" });
+ const row = toSearchIssueResult(record, { id: record.id, matchSource: "title", snippetCommentId: null }, "needle", null);
+ expect(row.matched_snippet).toBeUndefined();
+ expect(row.matched_comment_snippet).toBeUndefined();
+ expect(row.matched_description_snippet).toBeUndefined();
+ });
+});
+
+describe("extractSnippet", () => {
+ it("centres on the match and marks cut ends", () => {
+ const content = `${"a".repeat(100)}needle${"b".repeat(100)}`;
+ expect(extractSnippet(content, "NEEDLE")).toBe(`...${"a".repeat(40)}needle${"b".repeat(80)}...`);
+ });
+
+ it("counts code points, not UTF-16 units", () => {
+ const content = `${"字".repeat(50)}搜索${"😀".repeat(100)}`;
+ expect(extractSnippet(content, "搜索")).toBe(`...${"字".repeat(40)}搜索${"😀".repeat(80)}...`);
+ });
+
+ it("falls back to the earliest word, then to the leading text", () => {
+ expect(extractSnippet("first beta then alpha", "alpha beta")).toBe("first beta then alpha");
+ const long = "x".repeat(130);
+ expect(extractSnippet(long, "missing")).toBe(`${"x".repeat(120)}...`);
+ expect(extractSnippet("short", "missing")).toBe("short");
+ });
+});
+
+describe("SearchIndexEngine.searchProjects", () => {
+ it("ranks title tiers above description and demotes cancelled projects", () => {
+ const exact = project({ title: "Roadmap" });
+ const starts = project({ title: "Roadmap 2027" });
+ const contains = project({ title: "The roadmap refresh" });
+ const described = project({ title: "Planning", description: "covers the roadmap" });
+ const cancelled = project({ title: "Old roadmap", status: "cancelled" });
+ const completed = project({ title: "Roadmap done", status: "completed" });
+ const engine = new SearchIndexEngine();
+ [cancelled, described, contains, starts, exact, completed].forEach((p) => engine.upsertProject(p));
+
+ expect(engine.searchProjects({ q: "roadmap" }).map((h) => h.id)).toEqual([
+ exact.id,
+ starts.id,
+ contains.id,
+ described.id,
+ ]);
+ const all = engine.searchProjects({ q: "roadmap", include_closed: true });
+ expect(all.map((h) => h.id).at(-1)).toBe(cancelled.id);
+ expect(all.find((h) => h.id === described.id)?.matchSource).toBe("description");
+
+ const row = toSearchProjectResult(described, { id: described.id, matchSource: "description" }, "roadmap");
+ expect(row.matched_snippet).toBe("covers the roadmap");
+ expect(row).not.toHaveProperty("search_updated_at");
+ });
+});
+
+describe("timestampMicros", () => {
+ it("keeps sub-millisecond order", () => {
+ expect(timestampMicros("2026-01-01T00:00:00.000002Z")).toBeGreaterThan(timestampMicros("2026-01-01T00:00:00.000001Z"));
+ expect(timestampMicros("2026-01-01T00:00:00.1Z")).toBe(timestampMicros("2026-01-01T00:00:00.100000Z"));
+ expect(timestampMicros("2026-01-01T08:00:00+08:00")).toBe(timestampMicros("2026-01-01T00:00:00Z"));
+ });
+});
+
+describe("text budget accounting", () => {
+ it("counts UTF-8 bytes the way the server's text_bytes does", () => {
+ expect(utf8Length("abc")).toBe(3);
+ expect(utf8Length("é")).toBe(2);
+ expect(utf8Length("搜索")).toBe(6);
+ expect(utf8Length("😀")).toBe(4);
+ });
+
+ it("follows upserts, updates, and deletes", () => {
+ const engine = new SearchIndexEngine();
+ const record = issue({ title: "abc", description: "搜索" });
+ engine.upsertIssue(record);
+ engine.upsertComment(comment(record.id, "hello", "2026-01-01T00:00:00Z", "c-1"));
+ engine.upsertProject(project({ title: "p", description: "é" }));
+ expect(engine.textBytes).toBe(3 + 6 + 5 + 1 + 2);
+
+ engine.upsertIssue({ ...record, title: "abcd", description: null });
+ expect(engine.textBytes).toBe(4 + 5 + 1 + 2);
+
+ engine.deleteIssues([record.id]);
+ expect(engine.textBytes).toBe(1 + 2);
+ engine.clear();
+ expect(engine.textBytes).toBe(0);
+ });
+});
diff --git a/packages/core/search-index/engine.ts b/packages/core/search-index/engine.ts
new file mode 100644
index 0000000000..865a5f3948
--- /dev/null
+++ b/packages/core/search-index/engine.ts
@@ -0,0 +1,588 @@
+// Import only dependency-free modules: this file runs inside the search index
+// worker, and the issues/search barrels pull in React and the API client.
+import { BUILT_IN_STATUS_CATEGORY, normalizeIssueStatusCategory } from "../issues/config/status";
+import type {
+ SearchIndexComment,
+ SearchIndexIssue,
+ SearchIndexProject,
+ SearchIssueResult,
+ SearchProjectResult,
+} from "../types";
+
+/**
+ * In-memory search over one workspace's local index (MUL-7754).
+ *
+ * Matching and ranking mirror the server's `/api/issues/search` and
+ * `/api/projects/search` (buildSearchQuery / buildProjectSearchQuery in
+ * server/internal/handler) so a local result list is the one the server would
+ * return. Only lowercased text lives here; full records are read back from the
+ * store for the page being returned, which keeps memory close to one copy of
+ * the text.
+ */
+
+export const DEFAULT_SEARCH_LIMIT = 20;
+export const MAX_SEARCH_LIMIT = 50;
+
+export interface IssueSearchParams {
+ q: string;
+ limit?: number;
+ offset?: number;
+ include_closed?: boolean;
+}
+
+export type ProjectSearchParams = IssueSearchParams;
+
+export interface IssueHit {
+ id: string;
+ matchSource: SearchIssueResult["match_source"];
+ /** Latest comment containing the phrase (or every term), for the snippet. */
+ snippetCommentId: string | null;
+}
+
+export interface ProjectHit {
+ id: string;
+ matchSource: SearchProjectResult["match_source"];
+}
+
+interface IssueEntry {
+ id: string;
+ number: number;
+ status: string;
+ terminal: boolean;
+ title: string;
+ description: string;
+ updatedAt: number;
+ bytes: number;
+}
+
+interface CommentEntry {
+ id: string;
+ issueId: string;
+ content: string;
+ createdAt: number;
+ bytes: number;
+}
+
+interface ProjectEntry {
+ id: string;
+ status: string;
+ title: string;
+ description: string;
+ updatedAt: number;
+ bytes: number;
+}
+
+/** UTF-8 length without encoding, the measure the server's text_bytes uses. */
+export function utf8Length(s: string): number {
+ let bytes = 0;
+ for (let i = 0; i < s.length; i++) {
+ const code = s.charCodeAt(i);
+ if (code < 0x80) bytes += 1;
+ else if (code < 0x800) bytes += 2;
+ else if (code >= 0xd800 && code <= 0xdbff && i + 1 < s.length) {
+ // A surrogate pair is one 4-byte code point.
+ bytes += 4;
+ i++;
+ } else bytes += 3;
+ }
+ return bytes;
+}
+
+// Go's unicode.IsSpace, which the server splits terms on.
+const SEARCH_SPACE = /[\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]+/;
+
+export function splitSearchTerms(q: string): string[] {
+ return q.split(SEARCH_SPACE).filter((term) => term !== "");
+}
+
+/**
+ * The server compares exact titles against the LIKE-escaped phrase, so a title
+ * containing `_`, `%` or `\` never counts as an exact match. Kept on purpose.
+ */
+function escapeLike(s: string): string {
+ return s.replace(/\\/g, "\\\\").replace(/%/g, "\\%").replace(/_/g, "\\_");
+}
+
+/**
+ * Microseconds since the epoch from an RFC 3339 timestamp, keeping the
+ * sub-millisecond digits the server orders by (Date only keeps milliseconds).
+ */
+export function timestampMicros(value: string): number {
+ const match = /^(.*?)(?:\.(\d+))?(Z|[+-]\d{2}:\d{2})$/.exec(value);
+ if (!match) {
+ const ms = Date.parse(value);
+ return Number.isNaN(ms) ? 0 : ms * 1000;
+ }
+ const seconds = Date.parse(`${match[1]}${match[3]}`);
+ if (Number.isNaN(seconds)) return 0;
+ const fraction = (match[2] ?? "").slice(0, 6).padEnd(6, "0");
+ return seconds * 1000 + Number(fraction);
+}
+
+const STATUS_RANK: Record<string, number> = {
+ in_progress: 0,
+ in_review: 1,
+ todo: 2,
+ blocked: 3,
+ backlog: 4,
+ done: 5,
+ cancelled: 6,
+};
+
+function isTerminal(issue: Pick<SearchIndexIssue, "status" | "status_category">): boolean {
+ // Unknown legacy keys stay searchable, matching the server, which only
+ // excludes keys it resolves to a terminal category.
+ const category =
+ (issue.status_category ? normalizeIssueStatusCategory(issue.status_category) : null) ??
+ (Object.hasOwn(BUILT_IN_STATUS_CATEGORY, issue.status)
+ ? BUILT_IN_STATUS_CATEGORY[issue.status as keyof typeof BUILT_IN_STATUS_CATEGORY]
+ : null);
+ return category === "done" || category === "closed";
+}
+
+/** Server parseQueryNumber: "MUL-123" or a bare "123". */
+function parseQueryNumber(query: string): number | null {
+ const q = query.trim();
+ const match = /^[a-z]+-(\d+)$/i.exec(q) ?? /^(\d+)$/.exec(q);
+ if (!match) return null;
+ const n = Number.parseInt(match[1]!, 10);
+ return Number.isInteger(n) && n > 0 ? n : null;
+}
+
+export class SearchIndexEngine {
+ private readonly issues = new Map<string, IssueEntry>();
+ private readonly comments = new Map<string, CommentEntry>();
+ private readonly projects = new Map<string, ProjectEntry>();
+
+ private bytes = 0;
+
+ get size(): { issues: number; comments: number; projects: number } {
+ return { issues: this.issues.size, comments: this.comments.size, projects: this.projects.size };
+ }
+
+ /**
+ * UTF-8 bytes of every title, description, and comment held, counted the
+ * way the manifest's text_bytes is, so the memory budget can be enforced as
+ * the workspace grows and not only when the copy is first built.
+ */
+ get textBytes(): number {
+ return this.bytes;
+ }
+
+ clear(): void {
+ this.issues.clear();
+ this.comments.clear();
+ this.projects.clear();
+ this.bytes = 0;
+ }
+
+ upsertIssue(issue: SearchIndexIssue): void {
+ const description = issue.description ?? "";
+ const entry: IssueEntry = {
+ id: issue.id,
+ number: issue.number,
+ status: issue.status,
+ terminal: isTerminal(issue),
+ title: issue.title.toLowerCase(),
+ description: description.toLowerCase(),
+ updatedAt: timestampMicros(issue.search_updated_at || issue.updated_at),
+ bytes: utf8Length(issue.title) + utf8Length(description),
+ };
+ this.bytes += entry.bytes - (this.issues.get(issue.id)?.bytes ?? 0);
+ this.issues.set(issue.id, entry);
+ }
+
+ upsertComment(comment: SearchIndexComment): void {
+ const entry: CommentEntry = {
+ id: comment.id,
+ issueId: comment.issue_id,
+ content: comment.content.toLowerCase(),
+ createdAt: timestampMicros(comment.created_at),
+ bytes: utf8Length(comment.content),
+ };
+ this.bytes += entry.bytes - (this.comments.get(comment.id)?.bytes ?? 0);
+ this.comments.set(comment.id, entry);
+ }
+
+ upsertProject(project: SearchIndexProject): void {
+ const description = project.description ?? "";
+ const entry: ProjectEntry = {
+ id: project.id,
+ status: project.status,
+ title: project.title.toLowerCase(),
+ description: description.toLowerCase(),
+ updatedAt: timestampMicros(project.search_updated_at || project.updated_at),
+ bytes: utf8Length(project.title) + utf8Length(description),
+ };
+ this.bytes += entry.bytes - (this.projects.get(project.id)?.bytes ?? 0);
+ this.projects.set(project.id, entry);
+ }
+
+ /** Removes the issues and every comment on them. */
+ deleteIssues(ids: readonly string[]): void {
+ if (ids.length === 0) return;
+ const doomed = new Set(ids);
+ for (const id of doomed) {
+ this.bytes -= this.issues.get(id)?.bytes ?? 0;
+ this.issues.delete(id);
+ }
+ for (const [id, comment] of this.comments) {
+ if (doomed.has(comment.issueId)) {
+ this.bytes -= comment.bytes;
+ this.comments.delete(id);
+ }
+ }
+ }
+
+ deleteComment(id: string): void {
+ this.bytes -= this.comments.get(id)?.bytes ?? 0;
+ this.comments.delete(id);
+ }
+
+ deleteProject(id: string): void {
+ this.bytes -= this.projects.get(id)?.bytes ?? 0;
+ this.projects.delete(id);
+ }
+
+ searchIssues(params: IssueSearchParams): IssueHit[] {
+ const phrase = params.q.toLowerCase();
+ if (phrase === "") return [];
+ const terms = splitSearchTerms(phrase);
+ const multi = terms.length > 1;
+ const number = parseQueryNumber(params.q);
+ const escapedPhrase = escapeLike(phrase);
+
+ // One pass over the comments, keeping per-issue flags and the latest
+ // comment that can supply a snippet.
+ interface CommentAgg {
+ phrase: boolean;
+ terms: boolean[];
+ allTerms: boolean;
+ snippet: CommentEntry | null;
+ }
+ const byIssue = new Map<string, CommentAgg>();
+ // Reused per comment: this loop runs over every comment in the workspace.
+ const termHits = terms.map(() => false);
+ for (const comment of this.comments.values()) {
+ const content = comment.content;
+ const hasPhrase = content.includes(phrase);
+ let anyTerm = false;
+ let allTerms = multi;
+ if (multi) {
+ for (let i = 0; i < terms.length; i++) {
+ const hit = content.includes(terms[i]!);
+ termHits[i] = hit;
+ if (hit) anyTerm = true;
+ else allTerms = false;
+ }
+ }
+ if (!hasPhrase && !anyTerm) continue;
+ let agg = byIssue.get(comment.issueId);
+ if (!agg) {
+ agg = { phrase: false, terms: terms.map(() => false), allTerms: false, snippet: null };
+ byIssue.set(comment.issueId, agg);
+ }
+ agg.phrase ||= hasPhrase;
+ if (multi) {
+ for (let i = 0; i < terms.length; i++) {
+ if (termHits[i]) agg.terms[i] = true;
+ }
+ }
+ agg.allTerms ||= allTerms;
+ if (hasPhrase || allTerms) {
+ const current = agg.snippet;
+ if (
+ !current ||
+ comment.createdAt > current.createdAt ||
+ (comment.createdAt === current.createdAt && comment.id > current.id)
+ ) {
+ agg.snippet = comment;
+ }
+ }
+ }
+
+ const { offset, limit } = page(params);
+ // Only the requested page is needed, so keep the best offset+limit
+ // candidates instead of sorting every match (tens of thousands for a
+ // common word in a large workspace).
+ const top = new TopK<IssueCandidate>(offset + limit, compareIssueCandidates);
+ const titleTerms = terms.map(() => false);
+ const descriptionTerms = terms.map(() => false);
+ for (const issue of this.issues.values()) {
+ if (!params.include_closed && issue.terminal) continue;
+ const title = issue.title;
+ const titleExact = title === escapedPhrase;
+ const titleStartsWith = title.startsWith(phrase);
+ const titlePhrase = title.includes(phrase);
+ let titleAllTerms = multi;
+ if (multi) {
+ for (let i = 0; i < terms.length; i++) {
+ titleTerms[i] = title.includes(terms[i]!);
+ if (!titleTerms[i]) titleAllTerms = false;
+ }
+ }
+ // Once the title matched, it outranks anything the description could
+ // add, so the server never evaluates the description; neither do we.
+ const titleMatched = titlePhrase || titleAllTerms;
+ const description = issue.description;
+ const descriptionPhrase = !titleMatched && description.includes(phrase);
+ let descriptionAllTerms = multi;
+ if (multi) {
+ for (let i = 0; i < terms.length; i++) {
+ descriptionTerms[i] = !titleMatched && description.includes(terms[i]!);
+ if (!descriptionTerms[i]) descriptionAllTerms = false;
+ }
+ }
+ const numberExact = number !== null && issue.number === number;
+ const comments = byIssue.get(issue.id);
+ const commentPhrase = comments?.phrase ?? false;
+
+ let eligible = titlePhrase || descriptionPhrase || commentPhrase || numberExact;
+ if (!eligible && multi) {
+ eligible = true;
+ for (let i = 0; i < terms.length; i++) {
+ if (!(titleTerms[i] || descriptionTerms[i] || (comments?.terms[i] ?? false))) {
+ eligible = false;
+ break;
+ }
+ }
+ }
+ if (!eligible) continue;
+
+ let relevance = 9;
+ if (numberExact) relevance = 0;
+ else if (titleExact) relevance = 1;
+ else if (titleStartsWith) relevance = 2;
+ else if (titlePhrase) relevance = 3;
+ else if (titleAllTerms) relevance = 4;
+ else if (descriptionPhrase) relevance = 5;
+ else if (descriptionAllTerms) relevance = 6;
+ else if (commentPhrase) relevance = 7;
+ else if (multi && comments?.allTerms) relevance = 8;
+
+ const candidate: IssueCandidate = {
+ id: issue.id,
+ cancelledRank: issue.status === "cancelled" && !(titleExact || numberExact) ? 1 : 0,
+ relevance,
+ statusRank: STATUS_RANK[issue.status] ?? 7,
+ updatedAt: issue.updatedAt,
+ matchSource: titleMatched ? "title" : descriptionPhrase || descriptionAllTerms ? "description" : "comment",
+ snippetCommentId: comments?.snippet?.id ?? null,
+ };
+ top.offer(candidate);
+ }
+
+ return top
+ .sorted()
+ .slice(offset)
+ .map((c) => ({ id: c.id, matchSource: c.matchSource, snippetCommentId: c.snippetCommentId }));
+ }
+
+ searchProjects(params: ProjectSearchParams): ProjectHit[] {
+ const phrase = params.q.toLowerCase();
+ if (phrase === "") return [];
+ const terms = splitSearchTerms(phrase);
+ const multi = terms.length > 1;
+ const escapedPhrase = escapeLike(phrase);
+
+ interface Candidate {
+ hit: ProjectHit;
+ cancelledRank: number;
+ relevance: number;
+ updatedAt: number;
+ }
+ const candidates: Candidate[] = [];
+ for (const project of this.projects.values()) {
+ if (!params.include_closed && (project.status === "completed" || project.status === "cancelled")) continue;
+ const { title, description } = project;
+ const titlePhrase = title.includes(phrase);
+ const titleAllTerms = multi && terms.every((term) => title.includes(term));
+ const descriptionPhrase = description.includes(phrase);
+ const eligible =
+ titlePhrase ||
+ descriptionPhrase ||
+ (multi && terms.every((term) => title.includes(term) || description.includes(term)));
+ if (!eligible) continue;
+
+ const titleExact = title === escapedPhrase;
+ let relevance = 5;
+ if (titleExact) relevance = 0;
+ else if (title.startsWith(phrase)) relevance = 1;
+ else if (titlePhrase) relevance = 2;
+ else if (titleAllTerms) relevance = 3;
+ else if (descriptionPhrase) relevance = 4;
+
+ candidates.push({
+ hit: { id: project.id, matchSource: titlePhrase || titleAllTerms ? "title" : "description" },
+ cancelledRank: project.status === "cancelled" && !titleExact ? 1 : 0,
+ relevance,
+ updatedAt: project.updatedAt,
+ });
+ }
+
+ // The server has no final tie-breaker here; the id keeps local order stable.
+ candidates.sort(
+ (a, b) =>
+ a.cancelledRank - b.cancelledRank ||
+ a.relevance - b.relevance ||
+ b.updatedAt - a.updatedAt ||
+ (a.hit.id < b.hit.id ? -1 : a.hit.id > b.hit.id ? 1 : 0),
+ );
+ const { offset, limit } = page(params);
+ return candidates.slice(offset, offset + limit).map((c) => c.hit);
+ }
+}
+
+interface IssueCandidate extends IssueHit {
+ cancelledRank: number;
+ relevance: number;
+ statusRank: number;
+ updatedAt: number;
+}
+
+function compareIssueCandidates(a: IssueCandidate, b: IssueCandidate): number {
+ return (
+ a.cancelledRank - b.cancelledRank ||
+ a.relevance - b.relevance ||
+ a.statusRank - b.statusRank ||
+ b.updatedAt - a.updatedAt ||
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
+ );
+}
+
+/** Keeps the `capacity` smallest items under `compare`, in order. */
+class TopK<T> {
+ private readonly items: T[] = [];
+
+ constructor(
+ private readonly capacity: number,
+ private readonly compare: (a: T, b: T) => number,
+ ) {}
+
+ offer(item: T): void {
+ const items = this.items;
+ if (items.length === this.capacity && this.compare(item, items[items.length - 1]!) >= 0) return;
+ let lo = 0;
+ let hi = items.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (this.compare(items[mid]!, item) <= 0) lo = mid + 1;
+ else hi = mid;
+ }
+ items.splice(lo, 0, item);
+ if (items.length > this.capacity) items.pop();
+ }
+
+ sorted(): T[] {
+ return this.items;
+ }
+}
+
+function page(params: IssueSearchParams): { offset: number; limit: number } {
+ const limit =
+ params.limit !== undefined && params.limit > 0 ? Math.min(params.limit, MAX_SEARCH_LIMIT) : DEFAULT_SEARCH_LIMIT;
+ const offset = params.offset !== undefined && params.offset > 0 ? params.offset : 0;
+ return { offset, limit };
+}
+
+/**
+ * Port of the server's extractSnippet: up to ~120 code points around the
+ * first case-insensitive occurrence of the query (or, for several words, of the
+ * earliest word).
+ */
+export function extractSnippet(content: string, query: string): string {
+ const runes = Array.from(content);
+ const lowerRunes = Array.from(content.toLowerCase());
+ const queryRunes = Array.from(query.toLowerCase());
+
+ let idx = findRunes(lowerRunes, queryRunes);
+ let matchLen = queryRunes.length;
+ if (idx < 0) {
+ const terms = splitSearchTerms(query.toLowerCase());
+ if (terms.length > 1) {
+ let earliest = -1;
+ let earliestLen = 0;
+ for (const term of terms) {
+ const termRunes = Array.from(term);
+ const pos = findRunes(lowerRunes, termRunes);
+ if (pos >= 0 && (earliest < 0 || pos < earliest)) {
+ earliest = pos;
+ earliestLen = termRunes.length;
+ }
+ }
+ if (earliest >= 0) {
+ idx = earliest;
+ matchLen = earliestLen;
+ }
+ }
+ }
+
+ if (idx < 0) {
+ return runes.length > 120 ? `${runes.slice(0, 120).join("")}...` : content;
+ }
+ const start = Math.max(idx - 40, 0);
+ const end = Math.min(idx + matchLen + 80, runes.length);
+ let snippet = runes.slice(start, end).join("");
+ if (start > 0) snippet = `...${snippet}`;
+ if (end < runes.length) snippet = `${snippet}...`;
+ return snippet;
+}
+
+function findRunes(haystack: string[], needle: string[]): number {
+ if (needle.length === 0 || haystack.length < needle.length) return -1;
+ outer: for (let i = 0; i <= haystack.length - needle.length; i++) {
+ for (let j = 0; j < needle.length; j++) {
+ if (haystack[i + j] !== needle[j]) continue outer;
+ }
+ return i;
+ }
+ return -1;
+}
+
+/** Server `descriptionContains`: the phrase, or (for several words) every word. */
+function descriptionContains(description: string, query: string, terms: string[]): boolean {
+ if (description === "") return false;
+ const lower = description.toLowerCase();
+ if (lower.includes(query.toLowerCase())) return true;
+ return terms.length > 1 && terms.every((term) => lower.includes(term.toLowerCase()));
+}
+
+/** Builds the response row the server would return for one hit. */
+export function toSearchIssueResult(
+ issue: SearchIndexIssue,
+ hit: IssueHit,
+ q: string,
+ snippetComment: SearchIndexComment | null,
+): SearchIssueResult {
+ // The index keeps a precise timestamp for ranking; the result carries the
+ // same fields as a server search row.
+ const { search_updated_at: _searchUpdatedAt, ...rest } = issue;
+ const result: SearchIssueResult = { ...rest, match_source: hit.matchSource };
+ if (snippetComment && snippetComment.content !== "") {
+ const snippet = extractSnippet(snippetComment.content, q);
+ result.matched_comment_snippet = snippet;
+ if (hit.matchSource === "comment") result.matched_snippet = snippet;
+ }
+ const description = issue.description ?? "";
+ if (
+ (hit.matchSource === "description" || descriptionContains(description, q, splitSearchTerms(q))) &&
+ description !== ""
+ ) {
+ result.matched_description_snippet = extractSnippet(description, q);
+ }
+ return result;
+}
+
+export function toSearchProjectResult(
+ project: SearchIndexProject,
+ hit: ProjectHit,
+ q: string,
+): SearchProjectResult {
+ const { search_updated_at: _searchUpdatedAt, ...rest } = project;
+ const result: SearchProjectResult = { ...rest, match_source: hit.matchSource };
+ const description = project.description ?? "";
+ if (hit.matchSource === "description" && description !== "") {
+ result.matched_snippet = extractSnippet(description, q);
+ }
+ return result;
+}
diff --git a/packages/core/search-index/hooks.ts b/packages/core/search-index/hooks.ts
new file mode 100644
index 0000000000..7f67d7bc9a
--- /dev/null
+++ b/packages/core/search-index/hooks.ts
@@ -0,0 +1,70 @@
+import { useEffect } from "react";
+import { useQuery } from "@tanstack/react-query";
+import type { WSClient } from "../api/ws-client";
+import type { WSEventType } from "../types";
+import { workspaceListOptions } from "../workspace/queries";
+import { getLocalSearchIndex } from "./instance";
+
+/** Server events after which the local copy is likely behind. */
+const SEARCH_INDEX_EVENTS: WSEventType[] = [
+ "issue:created",
+ "issue:updated",
+ "issue:deleted",
+ "issue_metadata:changed",
+ "issue_properties:changed",
+ "comment:created",
+ "comment:updated",
+ "comment:deleted",
+ "project:created",
+ "project:updated",
+ "project:deleted",
+];
+
+/**
+ * Keeps the local search index attached to the workspace this tab shows and
+ * nudges it to catch up after realtime events, reconnects, and returning to
+ * the tab. The worker also catches up on its own every few minutes.
+ */
+export function useLocalSearchIndexSync(
+ wsClient: WSClient | null,
+ userId: string | null,
+ workspaceId: string | null,
+ workspaceSlug: string | null,
+): void {
+ useEffect(() => {
+ if (!userId || !workspaceId || !workspaceSlug) return;
+ const index = getLocalSearchIndex();
+ index.attach({ userId, workspaceId, workspaceSlug });
+ return () => index.detach();
+ }, [userId, workspaceId, workspaceSlug]);
+
+ // Membership is the only access boundary, so the workspace list says which
+ // copies may stay on this device. This catches every way access can end,
+ // including ones this client never saw an event for (removed while offline,
+ // deleted from another device).
+ const { data: workspaces } = useQuery({ ...workspaceListOptions(), enabled: !!userId });
+ useEffect(() => {
+ if (!userId || !workspaces) return;
+ void getLocalSearchIndex().prune(
+ userId,
+ workspaces.map((workspace) => workspace.id),
+ );
+ }, [userId, workspaces]);
+
+ useEffect(() => {
+ if (!wsClient) return;
+ const poke = () => getLocalSearchIndex().poke();
+ const unsubscribes = SEARCH_INDEX_EVENTS.map((event) => wsClient.on(event, poke));
+ unsubscribes.push(wsClient.onReconnect(poke));
+ return () => unsubscribes.forEach((unsubscribe) => unsubscribe());
+ }, [wsClient]);
+
+ useEffect(() => {
+ if (typeof document === "undefined") return;
+ const onVisible = () => {
+ if (document.visibilityState === "visible") getLocalSearchIndex().poke();
+ };
+ document.addEventListener("visibilitychange", onVisible);
+ return () => document.removeEventListener("visibilitychange", onVisible);
+ }, []);
+}
diff --git a/packages/core/search-index/host.test.ts b/packages/core/search-index/host.test.ts
new file mode 100644
index 0000000000..7b26b6f33e
--- /dev/null
+++ b/packages/core/search-index/host.test.ts
@@ -0,0 +1,267 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { SearchIndexHost, type PortLike } from "./host";
+import type { IndexTarget, TabMessage, WorkerMessage } from "./protocol";
+import { MemoryIndexStore, type SearchIndexDatabaseOwner } from "./store";
+import { FakeServer, issueRecord } from "./testing";
+
+const target: IndexTarget = { userId: "user", workspaceId: "ws", workspaceSlug: "acme" };
+
+/** A tab that answers the worker's fetch requests from a fake server. */
+class FakeTab implements PortLike {
+ received: WorkerMessage[] = [];
+ send!: (message: TabMessage) => void;
+ answer = true;
+ failWith: number | null = null;
+
+ constructor(private readonly server: FakeServer) {}
+
+ postMessage(message: WorkerMessage): void {
+ this.received.push(message);
+ if (message.type !== "fetch" || !this.answer) return;
+ const { op, params } = message;
+ void (async () => {
+ if (this.failWith !== null) {
+ this.send({ type: "fetch-result", id: message.id, ok: false, status: this.failWith, message: "denied" });
+ return;
+ }
+ const data =
+ op === "manifest"
+ ? await this.server.manifest()
+ : op === "snapshot"
+ ? await this.server.snapshot(params.afterNumber ?? 0, params.limit ?? 200)
+ : await this.server.changes(params.cursor ?? "");
+ this.send({ type: "fetch-result", id: message.id, ok: true, data });
+ })();
+ }
+
+ last<T extends WorkerMessage["type"]>(type: T): Extract<WorkerMessage, { type: T }> | undefined {
+ return this.received.filter((m) => m.type === type).at(-1) as Extract<WorkerMessage, { type: T }> | undefined;
+ }
+}
+
+function setup(
+ server: FakeServer,
+ options: { releaseDelayMs?: number; portTimeoutMs?: number; now?: () => number } = {},
+) {
+ const stores = new Map<string, MemoryIndexStore>();
+ // Databases on "disk": every store ever created, by user:workspace key.
+ const deleteDatabases = vi.fn(async (shouldDelete: (owner: SearchIndexDatabaseOwner) => boolean) => {
+ for (const key of [...stores.keys()]) {
+ const [userId, workspaceId] = key.split(":") as [string, string];
+ if (shouldDelete({ userId, workspaceId })) {
+ await stores.get(key)!.destroy();
+ stores.delete(key);
+ }
+ }
+ });
+ const host = new SearchIndexHost({
+ createStore: (t) => {
+ const key = `${t.userId}:${t.workspaceId}`;
+ const store = stores.get(key) ?? new MemoryIndexStore();
+ stores.set(key, store);
+ return store;
+ },
+ deleteDatabases,
+ indexOptions: { syncDebounceMs: 0, pollIntervalMs: 60 * 60 * 1000, retryBaseMs: 60 * 60 * 1000 },
+ releaseDelayMs: options.releaseDelayMs ?? 60_000,
+ portTimeoutMs: options.portTimeoutMs,
+ fetchTimeoutMs: 50,
+ now: options.now,
+ });
+ const connect = () => {
+ const tab = new FakeTab(server);
+ tab.send = host.connect(tab);
+ return tab;
+ };
+ return { host, stores, deleteDatabases, connect };
+}
+
+async function settle(): Promise<void> {
+ for (let i = 0; i < 20; i++) await new Promise((resolve) => setTimeout(resolve, 1));
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+describe("SearchIndexHost", () => {
+ it("syncs through an attached tab and answers its searches", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Hosted issue") });
+ const { connect } = setup(server);
+ const tab = connect();
+
+ expect(tab.received[0]).toEqual({ type: "hello" });
+ tab.send({ type: "attach", target });
+ await settle();
+
+ expect(tab.received.filter((m) => m.type === "fetch").every((m) => m.type === "fetch" && m.workspaceSlug === "acme")).toBe(true);
+ expect(tab.last("serving")).toEqual({ type: "serving", key: "user:ws", serving: true });
+
+ tab.send({ type: "search", id: 7, kind: "issues", params: { q: "hosted" } });
+ await settle();
+ const result = tab.last("search-result");
+ expect(result?.id).toBe(7);
+ expect(result?.result && "issues" in result.result ? result.result.issues.map((i) => i.id) : null).toEqual(["issue-1"]);
+ });
+
+ it("asks another tab when the one it asked goes silent", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Failover issue") });
+ let now = 1_000;
+ const { connect } = setup(server, { now: () => now });
+ const silent = connect();
+ silent.answer = false;
+ const live = connect();
+ live.send({ type: "attach", target });
+ now += 1;
+ // The silent tab was active most recently, so it is asked first.
+ silent.send({ type: "attach", target });
+ await settle();
+ await new Promise((resolve) => setTimeout(resolve, 120));
+ await settle();
+
+ expect(silent.received.some((m) => m.type === "fetch")).toBe(true);
+ expect(live.last("serving")?.serving).toBe(true);
+ });
+
+ it("does not retry a request the server rejected", async () => {
+ const server = new FakeServer();
+ const { connect } = setup(server);
+ const first = connect();
+ first.failWith = 404;
+ const second = connect();
+ first.send({ type: "attach", target });
+ second.send({ type: "attach", target });
+ await settle();
+
+ // Both tabs would answer, but a server rejection must not fall through to
+ // the other tab.
+ const asked = [first, second].filter((tab) => tab.received.some((m) => m.type === "fetch"));
+ expect(asked).toHaveLength(1);
+ });
+
+ it("frees an index a while after its last tab leaves", async () => {
+ vi.useFakeTimers();
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Released") });
+ const { connect } = setup(server, { releaseDelayMs: 1_000 });
+ const tab = connect();
+ tab.send({ type: "attach", target });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(tab.last("serving")?.serving).toBe(true);
+
+ tab.send({ type: "detach" });
+ await vi.advanceTimersByTimeAsync(2_000);
+ tab.send({ type: "attach", target });
+ // A fresh index reloads from the store before it can serve again.
+ expect(tab.last("serving")?.serving).toBe(false);
+ await vi.advanceTimersByTimeAsync(10);
+ expect(tab.last("serving")?.serving).toBe(true);
+ });
+
+ it("wipes every index on request", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Secret") });
+ const { connect, stores } = setup(server);
+ const tab = connect();
+ tab.send({ type: "attach", target });
+ await settle();
+ const store = stores.get("user:ws");
+
+ tab.send({ type: "wipe", id: 3 });
+ await settle();
+ expect(tab.last("wiped")).toEqual({ type: "wiped", id: 3 });
+ expect(store?.destroyed).toBe(true);
+ expect(stores.size).toBe(0);
+
+ tab.send({ type: "search", id: 4, kind: "issues", params: { q: "secret" } });
+ await settle();
+ expect(tab.last("search-result")?.result).toBeNull();
+ });
+
+ it("restores a tab the sweep dropped once it speaks again", async () => {
+ vi.useFakeTimers();
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Needle") });
+ const { connect } = setup(server, { portTimeoutMs: 1_000, releaseDelayMs: 1_000 });
+ const tab = connect();
+ tab.send({ type: "attach", target });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(tab.last("serving")?.serving).toBe(true);
+
+ // Frozen in the background: silent past the timeout, index released.
+ await vi.advanceTimersByTimeAsync(4_000);
+ tab.send({ type: "ping" });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(tab.last("serving")).toEqual({ type: "serving", key: "user:ws", serving: true });
+
+ tab.send({ type: "search", id: 77, kind: "issues", params: { q: "needle" } });
+ await vi.advanceTimersByTimeAsync(10);
+ expect(tab.last("search-result")).toMatchObject({ id: 77, result: { issues: [{ id: "issue-1" }] } });
+ });
+
+ it("does not restore a tab that said it was closing until it attaches again", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Closing") });
+ const { connect } = setup(server);
+ const tab = connect();
+ tab.send({ type: "attach", target });
+ await settle();
+ tab.send({ type: "close" });
+ const servingBefore = tab.received.filter((m) => m.type === "serving").length;
+
+ tab.send({ type: "ping" });
+ await settle();
+ expect(tab.received.filter((m) => m.type === "serving").length).toBe(servingBefore);
+
+ // Restored from the back/forward cache: the client attaches again.
+ tab.send({ type: "attach", target });
+ await settle();
+ expect(tab.last("serving")?.serving).toBe(true);
+ });
+
+ it("forgets every copy of a workspace, even while a tab shows it", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Gone soon") });
+ const { connect, stores } = setup(server);
+ const tab = connect();
+ tab.send({ type: "attach", target });
+ await settle();
+ const store = stores.get("user:ws")!;
+
+ tab.send({ type: "forget", workspaceId: "ws" });
+ await settle();
+ expect(store.destroyed).toBe(true);
+ expect(stores.has("user:ws")).toBe(false);
+ expect(tab.last("serving")).toEqual({ type: "serving", key: "user:ws", serving: false });
+
+ tab.send({ type: "search", id: 9, kind: "issues", params: { q: "gone" } });
+ await settle();
+ expect(tab.last("search-result")?.result).toBeNull();
+ });
+
+ it("prunes copies outside the user's workspaces but keeps ones a tab shows", async () => {
+ const server = new FakeServer();
+ const { connect, stores } = setup(server, { releaseDelayMs: 60_000 });
+ const shown = connect();
+ shown.send({ type: "attach", target: { userId: "user", workspaceId: "joined-just-now", workspaceSlug: "new" } });
+ const left = connect();
+ left.send({ type: "attach", target: { userId: "user", workspaceId: "left", workspaceSlug: "left" } });
+ left.send({ type: "detach" });
+ const kept = connect();
+ kept.send({ type: "attach", target });
+ kept.send({ type: "detach" });
+ await settle();
+ // Databases with no index in memory: another user's, and a workspace the
+ // user is no longer in.
+ stores.set("someone-else:ws", new MemoryIndexStore());
+ stores.set("user:removed-offline", new MemoryIndexStore());
+
+ shown.send({ type: "prune", userId: "user", workspaceIds: ["ws"] });
+ await settle();
+
+ expect([...stores.keys()].sort()).toEqual(["user:joined-just-now", "user:ws"]);
+ });
+});
diff --git a/packages/core/search-index/host.ts b/packages/core/search-index/host.ts
new file mode 100644
index 0000000000..b8f1379186
--- /dev/null
+++ b/packages/core/search-index/host.ts
@@ -0,0 +1,329 @@
+import type { SearchIndexChanges, SearchIndexManifest, SearchIndexSnapshotPage } from "../types";
+import { indexTargetKey, type FetchOp, type IndexTarget, type TabMessage, type WorkerMessage } from "./protocol";
+import type { IndexStore, SearchIndexDatabaseOwner } from "./store";
+import { IndexFetchError, WorkspaceIndex, type IndexFetcher, type WorkspaceIndexOptions } from "./sync";
+
+/**
+ * Runs inside the search index worker (MUL-7754). A SharedWorker hosts every
+ * tab of the origin; a dedicated worker hosts one. Tabs attach to the
+ * workspace they show, and the host keeps one WorkspaceIndex per attached
+ * (user, workspace), released a minute after its last tab leaves.
+ *
+ * The worker has no credentials: it asks an attached tab to run each request
+ * through the tab's API client, so authentication, session renewal, and
+ * workspace headers stay where they already work.
+ */
+
+export interface PortLike {
+ postMessage(message: WorkerMessage): void;
+}
+
+export interface SearchIndexHostDeps {
+ createStore(target: IndexTarget): IndexStore;
+ /** Deletes the stored indexes on this origin that `shouldDelete` selects. */
+ deleteDatabases(shouldDelete: (owner: SearchIndexDatabaseOwner) => boolean): Promise<void>;
+ indexOptions?: Partial<WorkspaceIndexOptions>;
+ /** Wait before freeing an index no tab is attached to. */
+ releaseDelayMs?: number;
+ /** How long a tab has to answer a request before another tab is asked. */
+ fetchTimeoutMs?: number;
+ /** A tab silent for this long is treated as closed. */
+ portTimeoutMs?: number;
+ now?: () => number;
+}
+
+interface PortEntry {
+ port: PortLike;
+ target: IndexTarget | null;
+ lastSeen: number;
+ /**
+ * What the port was attached to when a sweep dropped it. A tab the browser
+ * froze in the background stays silent past the timeout while another tab
+ * keeps the worker alive; its next message restores the attachment.
+ */
+ suspended: IndexTarget | null;
+}
+
+interface IndexEntry {
+ index: WorkspaceIndex;
+ target: IndexTarget;
+ slug: string;
+ ports: Set<PortEntry>;
+ releaseTimer: ReturnType<typeof setTimeout> | null;
+}
+
+interface PendingFetch {
+ entry: PortEntry;
+ resolve: (data: unknown) => void;
+ reject: (err: Error) => void;
+ timer: ReturnType<typeof setTimeout>;
+}
+
+class PortGoneError extends Error {}
+
+export class SearchIndexHost {
+ private readonly ports = new Map<PortLike, PortEntry>();
+ private readonly indexes = new Map<string, IndexEntry>();
+ private readonly pending = new Map<number, PendingFetch>();
+ private nextFetchId = 1;
+ private readonly releaseDelayMs: number;
+ private readonly fetchTimeoutMs: number;
+ private readonly portTimeoutMs: number;
+ private readonly now: () => number;
+ private sweepTimer: ReturnType<typeof setInterval> | null = null;
+
+ constructor(private readonly deps: SearchIndexHostDeps) {
+ this.releaseDelayMs = deps.releaseDelayMs ?? 60_000;
+ this.fetchTimeoutMs = deps.fetchTimeoutMs ?? 60_000;
+ this.portTimeoutMs = deps.portTimeoutMs ?? 10 * 60_000;
+ this.now = deps.now ?? (() => Date.now());
+ }
+
+ /** Registers a tab's port and returns the handler for its messages. */
+ connect(port: PortLike): (message: TabMessage) => void {
+ const entry: PortEntry = { port, target: null, lastSeen: this.now(), suspended: null };
+ this.ports.set(port, entry);
+ this.sweepTimer ??= setInterval(() => this.sweep(), Math.min(this.portTimeoutMs, 60_000));
+ port.postMessage({ type: "hello" });
+ return (message) => this.handle(entry, message);
+ }
+
+ disconnect(port: PortLike): void {
+ const entry = this.ports.get(port);
+ if (!entry) return;
+ this.ports.delete(port);
+ this.detach(entry);
+ for (const [id, pending] of this.pending) {
+ if (pending.entry === entry) {
+ clearTimeout(pending.timer);
+ this.pending.delete(id);
+ pending.reject(new PortGoneError("tab closed"));
+ }
+ }
+ }
+
+ private handle(entry: PortEntry, message: TabMessage): void {
+ entry.lastSeen = this.now();
+ if (!this.ports.has(entry.port)) {
+ if (message.type === "close") return;
+ this.ports.set(entry.port, entry);
+ const suspended = entry.suspended;
+ entry.suspended = null;
+ if (suspended && message.type !== "attach" && message.type !== "detach") this.attach(entry, suspended);
+ }
+ switch (message.type) {
+ case "attach":
+ this.attach(entry, message.target);
+ return;
+ case "detach":
+ this.detach(entry);
+ return;
+ case "close":
+ this.disconnect(entry.port);
+ return;
+ case "poke":
+ if (entry.target) this.indexes.get(indexTargetKey(entry.target))?.index.requestSync();
+ return;
+ case "ping":
+ return;
+ case "search":
+ void this.search(entry, message.id, message.kind, message.params);
+ return;
+ case "fetch-result": {
+ const pending = this.pending.get(message.id);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ this.pending.delete(message.id);
+ if (message.ok) pending.resolve(message.data);
+ else pending.reject(new IndexFetchError(message.message, message.status));
+ return;
+ }
+ case "wipe":
+ void this.wipe(entry, message.id);
+ return;
+ case "forget":
+ void this.forget(message.workspaceId);
+ return;
+ case "prune":
+ void this.prune(message.userId, message.workspaceIds);
+ return;
+ }
+ }
+
+ private attach(entry: PortEntry, target: IndexTarget): void {
+ const key = indexTargetKey(target);
+ if (entry.target && indexTargetKey(entry.target) !== key) this.detach(entry);
+ entry.target = target;
+ let indexEntry = this.indexes.get(key);
+ if (!indexEntry) {
+ const created: IndexEntry = {
+ index: null as unknown as WorkspaceIndex,
+ target,
+ slug: target.workspaceSlug,
+ ports: new Set(),
+ releaseTimer: null,
+ };
+ created.index = new WorkspaceIndex(key, this.deps.createStore(target), this.fetcherFor(key), {
+ ...this.deps.indexOptions,
+ onChange: () => this.broadcastServing(key),
+ });
+ indexEntry = created;
+ this.indexes.set(key, indexEntry);
+ void indexEntry.index.start();
+ }
+ // A renamed workspace keeps its id; later requests use the new slug.
+ indexEntry.slug = target.workspaceSlug;
+ if (indexEntry.releaseTimer) {
+ clearTimeout(indexEntry.releaseTimer);
+ indexEntry.releaseTimer = null;
+ }
+ indexEntry.ports.add(entry);
+ entry.port.postMessage({ type: "serving", key, serving: indexEntry.index.isServing() });
+ indexEntry.index.requestSync();
+ }
+
+ private detach(entry: PortEntry): void {
+ if (!entry.target) return;
+ const key = indexTargetKey(entry.target);
+ entry.target = null;
+ const indexEntry = this.indexes.get(key);
+ if (!indexEntry) return;
+ indexEntry.ports.delete(entry);
+ if (indexEntry.ports.size === 0 && !indexEntry.releaseTimer) {
+ indexEntry.releaseTimer = setTimeout(() => {
+ if (indexEntry.ports.size > 0) return;
+ this.indexes.delete(key);
+ void indexEntry.index.dispose();
+ }, this.releaseDelayMs);
+ }
+ }
+
+ private async search(
+ entry: PortEntry,
+ id: number,
+ kind: "issues" | "projects",
+ params: Parameters<WorkspaceIndex["searchIssues"]>[0],
+ ): Promise<void> {
+ const indexEntry = entry.target ? this.indexes.get(indexTargetKey(entry.target)) : undefined;
+ let result = null;
+ try {
+ if (indexEntry) {
+ result =
+ kind === "issues" ? await indexEntry.index.searchIssues(params) : await indexEntry.index.searchProjects(params);
+ }
+ } catch {
+ // The tab falls back to server search.
+ result = null;
+ }
+ entry.port.postMessage({ type: "search-result", id, result });
+ }
+
+ private async wipe(entry: PortEntry, id: number): Promise<void> {
+ await this.destroyIndexes(() => true);
+ await this.deps.deleteDatabases(() => true).catch(() => undefined);
+ entry.port.postMessage({ type: "wiped", id });
+ }
+
+ /** Destroys every copy of a workspace, in memory and on disk. */
+ private async forget(workspaceId: string): Promise<void> {
+ await this.destroyIndexes((indexEntry) => indexEntry.target.workspaceId === workspaceId);
+ await this.deps.deleteDatabases((owner) => owner.workspaceId === workspaceId).catch(() => undefined);
+ }
+
+ /**
+ * Keeps only this user's copies of the listed workspaces. A copy a tab is
+ * still showing survives even if the list lacks it: the list can be a
+ * cached one from before the user joined that workspace.
+ */
+ private async prune(userId: string, workspaceIds: string[]): Promise<void> {
+ const keep = new Set(workspaceIds.map((workspaceId) => indexTargetKey({ userId, workspaceId })));
+ for (const [key, indexEntry] of this.indexes) {
+ if (indexEntry.ports.size > 0) keep.add(key);
+ }
+ await this.destroyIndexes((indexEntry) => !keep.has(indexTargetKey(indexEntry.target)));
+ await this.deps.deleteDatabases((owner) => !keep.has(indexTargetKey(owner))).catch(() => undefined);
+ }
+
+ private async destroyIndexes(select: (indexEntry: IndexEntry) => boolean): Promise<void> {
+ const doomed: IndexEntry[] = [];
+ for (const [key, indexEntry] of this.indexes) {
+ if (!select(indexEntry)) continue;
+ this.indexes.delete(key);
+ if (indexEntry.releaseTimer) clearTimeout(indexEntry.releaseTimer);
+ for (const port of indexEntry.ports) {
+ port.target = null;
+ port.port.postMessage({ type: "serving", key, serving: false });
+ }
+ doomed.push(indexEntry);
+ }
+ await Promise.all(doomed.map((indexEntry) => indexEntry.index.dispose(true).catch(() => undefined)));
+ }
+
+ private broadcastServing(key: string): void {
+ const indexEntry = this.indexes.get(key);
+ if (!indexEntry) return;
+ const serving = indexEntry.index.isServing();
+ for (const port of indexEntry.ports) port.port.postMessage({ type: "serving", key, serving });
+ }
+
+ private fetcherFor(key: string): IndexFetcher {
+ const request = async <T>(op: FetchOp, params: { afterNumber?: number; cursor?: string; limit?: number }) =>
+ (await this.requestFromTab(key, op, params)) as T;
+ return {
+ manifest: () => request<SearchIndexManifest>("manifest", {}),
+ snapshot: (afterNumber, limit) => request<SearchIndexSnapshotPage>("snapshot", { afterNumber, limit }),
+ changes: (cursor, limit) => request<SearchIndexChanges>("changes", { cursor, limit }),
+ };
+ }
+
+ /** Asks the most recently active attached tab; moves on if it has gone away. */
+ private async requestFromTab(
+ key: string,
+ op: FetchOp,
+ params: { afterNumber?: number; cursor?: string; limit?: number },
+ ): Promise<unknown> {
+ const indexEntry = this.indexes.get(key);
+ const candidates = indexEntry ? [...indexEntry.ports].sort((a, b) => b.lastSeen - a.lastSeen) : [];
+ for (const entry of candidates) {
+ if (!this.ports.has(entry.port) || !entry.target || indexTargetKey(entry.target) !== key) continue;
+ try {
+ return await this.send(entry, op, indexEntry!.slug, params);
+ } catch (err) {
+ if (err instanceof PortGoneError) continue;
+ throw err;
+ }
+ }
+ throw new Error("no tab is attached to this workspace");
+ }
+
+ private send(
+ entry: PortEntry,
+ op: FetchOp,
+ workspaceSlug: string,
+ params: { afterNumber?: number; cursor?: string; limit?: number },
+ ): Promise<unknown> {
+ const id = this.nextFetchId++;
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.pending.delete(id);
+ reject(new PortGoneError("tab did not answer"));
+ }, this.fetchTimeoutMs);
+ this.pending.set(id, { entry, resolve, reject, timer });
+ entry.port.postMessage({ type: "fetch", id, op, workspaceSlug, params });
+ });
+ }
+
+ /**
+ * Frees ports whose tab went silent: closed without pagehide, or frozen in
+ * the background. A frozen tab that speaks again is restored in `handle`.
+ */
+ private sweep(): void {
+ const cutoff = this.now() - this.portTimeoutMs;
+ for (const entry of [...this.ports.values()]) {
+ if (entry.lastSeen >= cutoff) continue;
+ const target = entry.target;
+ this.disconnect(entry.port);
+ entry.suspended = target;
+ }
+ }
+}
diff --git a/packages/core/search-index/index.ts b/packages/core/search-index/index.ts
new file mode 100644
index 0000000000..0b6d49076e
--- /dev/null
+++ b/packages/core/search-index/index.ts
@@ -0,0 +1,9 @@
+export {
+ forgetLocalSearchIndex,
+ getLocalSearchIndex,
+ isLocalSearchReady,
+ searchIssues,
+ searchProjects,
+ wipeLocalSearchIndex,
+} from "./instance";
+export { useLocalSearchIndexSync } from "./hooks";
diff --git a/packages/core/search-index/instance.ts b/packages/core/search-index/instance.ts
new file mode 100644
index 0000000000..fa8eb6ecd7
--- /dev/null
+++ b/packages/core/search-index/instance.ts
@@ -0,0 +1,43 @@
+import { api } from "../api";
+import type { SearchIssuesResponse, SearchProjectsResponse } from "../types";
+import { LocalSearchIndexClient, startSearchIndexWorker } from "./client";
+
+let client: LocalSearchIndexClient | null = null;
+
+/** The tab-wide local search index (MUL-7754). */
+export function getLocalSearchIndex(): LocalSearchIndexClient {
+ client ??= new LocalSearchIndexClient(() => api, startSearchIndexWorker);
+ return client;
+}
+
+type SearchParams = Parameters<typeof api.searchIssues>[0];
+
+/**
+ * Issue search that answers from the local index when it can and asks the
+ * server otherwise. Results have the server's shape and order either way.
+ */
+export async function searchIssues(params: SearchParams): Promise<SearchIssuesResponse> {
+ const local = await getLocalSearchIndex().searchIssues(params);
+ return local ?? api.searchIssues(params);
+}
+
+/** Project search with the same local-first behavior as `searchIssues`. */
+export async function searchProjects(params: SearchParams): Promise<SearchProjectsResponse> {
+ const local = await getLocalSearchIndex().searchProjects(params);
+ return local ?? api.searchProjects(params);
+}
+
+/** Whether searches in this tab are currently answered locally. */
+export function isLocalSearchReady(): boolean {
+ return getLocalSearchIndex().isServing();
+}
+
+/** Destroys this device's local copies of a workspace the user can no longer read. */
+export function forgetLocalSearchIndex(workspaceId: string): Promise<void> {
+ return getLocalSearchIndex().forget(workspaceId);
+}
+
+/** Deletes every local search index on this device. */
+export function wipeLocalSearchIndex(): Promise<void> {
+ return getLocalSearchIndex().wipe();
+}
diff --git a/packages/core/search-index/protocol.ts b/packages/core/search-index/protocol.ts
new file mode 100644
index 0000000000..4bb4915442
--- /dev/null
+++ b/packages/core/search-index/protocol.ts
@@ -0,0 +1,46 @@
+import type { SearchIssuesResponse, SearchProjectsResponse } from "../types";
+import type { IssueSearchParams } from "./engine";
+
+/** Messages between a tab and the search index worker (MUL-7754). */
+
+export interface IndexTarget {
+ userId: string;
+ workspaceId: string;
+ /** Sent with every request the tab makes on the worker's behalf. */
+ workspaceSlug: string;
+}
+
+export function indexTargetKey(target: Pick<IndexTarget, "userId" | "workspaceId">): string {
+ return `${target.userId}:${target.workspaceId}`;
+}
+
+export type FetchOp = "manifest" | "snapshot" | "changes";
+
+export type TabMessage =
+ | { type: "attach"; target: IndexTarget }
+ | { type: "detach" }
+ /** The tab is going away (pagehide); forget its port. */
+ | { type: "close" }
+ | { type: "poke" }
+ | { type: "ping" }
+ | { type: "search"; id: number; kind: "issues" | "projects"; params: IssueSearchParams }
+ | { type: "fetch-result"; id: number; ok: true; data: unknown }
+ | { type: "fetch-result"; id: number; ok: false; status?: number; message: string }
+ | { type: "wipe"; id: number }
+ /** Access to the workspace ended (deleted, removed, left): destroy its copies. */
+ | { type: "forget"; workspaceId: string }
+ /** The user's current workspaces: destroy copies of any other workspace or user. */
+ | { type: "prune"; userId: string; workspaceIds: string[] };
+
+export type WorkerMessage =
+ | { type: "hello" }
+ | { type: "serving"; key: string; serving: boolean }
+ | {
+ type: "fetch";
+ id: number;
+ op: FetchOp;
+ workspaceSlug: string;
+ params: { afterNumber?: number; cursor?: string; limit?: number };
+ }
+ | { type: "search-result"; id: number; result: SearchIssuesResponse | SearchProjectsResponse | null }
+ | { type: "wiped"; id: number };
diff --git a/packages/core/search-index/store.ts b/packages/core/search-index/store.ts
new file mode 100644
index 0000000000..24e1751097
--- /dev/null
+++ b/packages/core/search-index/store.ts
@@ -0,0 +1,338 @@
+import type { SearchIndexComment, SearchIndexIssue, SearchIndexProject } from "../types";
+
+/**
+ * Persistence for one workspace's local search index (MUL-7754): IndexedDB in
+ * browsers and Electron, an in-memory implementation for tests.
+ *
+ * Every write that advances the catch-up cursor carries the records it covers
+ * in the same transaction, so a crash or a closed tab can never leave a cursor
+ * ahead of the data.
+ */
+
+/** Bump to discard every local copy, e.g. after changing what a record holds. */
+export const SEARCH_INDEX_SCHEMA_VERSION = 1;
+
+const DB_PREFIX = "multica-search-index";
+
+export interface IndexMeta {
+ schemaVersion: number;
+ /** Catch-up cursor; set once the copy is complete. */
+ cursor: string | null;
+ /** Progress of an unfinished bootstrap, so a reload resumes it. */
+ bootstrap: { cursor: string; afterNumber: number } | null;
+ /** When the workspace last exceeded the memory budget, in epoch ms. */
+ tooLargeAt: number | null;
+}
+
+export function emptyIndexMeta(): IndexMeta {
+ return { schemaVersion: SEARCH_INDEX_SCHEMA_VERSION, cursor: null, bootstrap: null, tooLargeAt: null };
+}
+
+export interface IndexBatch {
+ issues?: SearchIndexIssue[];
+ comments?: SearchIndexComment[];
+ projects?: SearchIndexProject[];
+ /** Deleting an issue also deletes its comments. */
+ deletedIssues?: string[];
+ deletedComments?: string[];
+ deletedProjects?: string[];
+ meta?: IndexMeta;
+}
+
+export interface IndexRecords {
+ issues: SearchIndexIssue[];
+ comments: SearchIndexComment[];
+ projects: SearchIndexProject[];
+}
+
+export interface IndexStore {
+ readMeta(): Promise<IndexMeta | null>;
+ loadAll(): Promise<IndexRecords>;
+ /** Applies the batch atomically. */
+ write(batch: IndexBatch): Promise<void>;
+ /** Drops every record and replaces the meta. */
+ reset(meta: IndexMeta): Promise<void>;
+ getIssues(ids: string[]): Promise<Map<string, SearchIndexIssue>>;
+ getComments(ids: string[]): Promise<Map<string, SearchIndexComment>>;
+ getProjects(ids: string[]): Promise<Map<string, SearchIndexProject>>;
+ /** Deletes the underlying database. The store is unusable afterwards. */
+ destroy(): Promise<void>;
+}
+
+export function searchIndexDatabaseName(userId: string, workspaceId: string): string {
+ return `${DB_PREFIX}:${userId}:${workspaceId}`;
+}
+
+const META_KEY = "state";
+
+function requestResult<T>(request: IDBRequest<T>): Promise<T> {
+ return new Promise((resolve, reject) => {
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+}
+
+function transactionDone(tx: IDBTransaction): Promise<void> {
+ return new Promise((resolve, reject) => {
+ tx.oncomplete = () => resolve();
+ tx.onerror = () => reject(tx.error);
+ tx.onabort = () => reject(tx.error ?? new Error("IndexedDB transaction aborted"));
+ });
+}
+
+export class IdbIndexStore implements IndexStore {
+ private db: Promise<IDBDatabase> | null = null;
+ private destroyed = false;
+
+ constructor(private readonly name: string) {}
+
+ private open(): Promise<IDBDatabase> {
+ // A write racing a logout wipe must not recreate the deleted database.
+ if (this.destroyed) return Promise.reject(new Error("search index store was destroyed"));
+ if (!this.db) {
+ this.db = new Promise((resolve, reject) => {
+ const request = indexedDB.open(this.name, 1);
+ request.onupgradeneeded = () => {
+ const db = request.result;
+ db.createObjectStore("meta");
+ db.createObjectStore("issues", { keyPath: "id" });
+ db.createObjectStore("comments", { keyPath: "id" }).createIndex("issue_id", "issue_id");
+ db.createObjectStore("projects", { keyPath: "id" });
+ };
+ request.onsuccess = () => {
+ const db = request.result;
+ // Another context deleting the database (logout wipe) must not be
+ // blocked by this connection.
+ db.onversionchange = () => {
+ db.close();
+ this.db = null;
+ };
+ resolve(db);
+ };
+ request.onerror = () => reject(request.error);
+ request.onblocked = () => reject(new Error("IndexedDB open blocked"));
+ });
+ this.db.catch(() => {
+ this.db = null;
+ });
+ }
+ return this.db;
+ }
+
+ async readMeta(): Promise<IndexMeta | null> {
+ const db = await this.open();
+ const meta = await requestResult(db.transaction("meta").objectStore("meta").get(META_KEY));
+ return (meta as IndexMeta | undefined) ?? null;
+ }
+
+ async loadAll(): Promise<IndexRecords> {
+ const db = await this.open();
+ const tx = db.transaction(["issues", "comments", "projects"]);
+ const [issues, comments, projects] = await Promise.all([
+ requestResult(tx.objectStore("issues").getAll()),
+ requestResult(tx.objectStore("comments").getAll()),
+ requestResult(tx.objectStore("projects").getAll()),
+ ]);
+ return {
+ issues: issues as SearchIndexIssue[],
+ comments: comments as SearchIndexComment[],
+ projects: projects as SearchIndexProject[],
+ };
+ }
+
+ async write(batch: IndexBatch): Promise<void> {
+ const db = await this.open();
+ const tx = db.transaction(["meta", "issues", "comments", "projects"], "readwrite");
+ const done = transactionDone(tx);
+ const issues = tx.objectStore("issues");
+ const comments = tx.objectStore("comments");
+ const projects = tx.objectStore("projects");
+ batch.issues?.forEach((record) => issues.put(record));
+ batch.comments?.forEach((record) => comments.put(record));
+ batch.projects?.forEach((record) => projects.put(record));
+ batch.deletedComments?.forEach((id) => comments.delete(id));
+ batch.deletedProjects?.forEach((id) => projects.delete(id));
+ const byIssue = comments.index("issue_id");
+ batch.deletedIssues?.forEach((id) => {
+ issues.delete(id);
+ const cursor = byIssue.openKeyCursor(IDBKeyRange.only(id));
+ cursor.onsuccess = () => {
+ const current = cursor.result;
+ if (!current) return;
+ comments.delete(current.primaryKey);
+ current.continue();
+ };
+ });
+ if (batch.meta) tx.objectStore("meta").put(batch.meta, META_KEY);
+ await done;
+ }
+
+ async reset(meta: IndexMeta): Promise<void> {
+ const db = await this.open();
+ const tx = db.transaction(["meta", "issues", "comments", "projects"], "readwrite");
+ const done = transactionDone(tx);
+ tx.objectStore("issues").clear();
+ tx.objectStore("comments").clear();
+ tx.objectStore("projects").clear();
+ tx.objectStore("meta").put(meta, META_KEY);
+ await done;
+ }
+
+ getIssues(ids: string[]): Promise<Map<string, SearchIndexIssue>> {
+ return this.getMany<SearchIndexIssue>("issues", ids);
+ }
+
+ getComments(ids: string[]): Promise<Map<string, SearchIndexComment>> {
+ return this.getMany<SearchIndexComment>("comments", ids);
+ }
+
+ getProjects(ids: string[]): Promise<Map<string, SearchIndexProject>> {
+ return this.getMany<SearchIndexProject>("projects", ids);
+ }
+
+ private async getMany<T extends { id: string }>(store: string, ids: string[]): Promise<Map<string, T>> {
+ const out = new Map<string, T>();
+ if (ids.length === 0) return out;
+ const db = await this.open();
+ const objectStore = db.transaction(store).objectStore(store);
+ const records = await Promise.all(ids.map((id) => requestResult(objectStore.get(id))));
+ for (const record of records) {
+ if (record) out.set((record as T).id, record as T);
+ }
+ return out;
+ }
+
+ async destroy(): Promise<void> {
+ this.destroyed = true;
+ const pending = this.db;
+ this.db = null;
+ if (pending) {
+ try {
+ (await pending).close();
+ } catch {
+ // Never opened; nothing to close.
+ }
+ }
+ await deleteDatabase(this.name);
+ }
+}
+
+function deleteDatabase(name: string): Promise<void> {
+ return new Promise((resolve, reject) => {
+ const request = indexedDB.deleteDatabase(name);
+ request.onsuccess = () => resolve();
+ request.onerror = () => reject(request.error);
+ // A connection in another context will close on versionchange; the
+ // deletion completes once it does.
+ request.onblocked = () => undefined;
+ });
+}
+
+/** The (user, workspace) a local search index database belongs to. */
+export interface SearchIndexDatabaseOwner {
+ userId: string;
+ workspaceId: string;
+}
+
+function parseSearchIndexDatabaseName(name: string): SearchIndexDatabaseOwner | null {
+ const [prefix, userId, workspaceId, ...rest] = name.split(":");
+ if (prefix !== DB_PREFIX || !userId || !workspaceId || rest.length > 0) return null;
+ return { userId, workspaceId };
+}
+
+/**
+ * Deletes the local search index databases on this origin that `shouldDelete`
+ * selects. A name this version cannot parse is always deleted.
+ */
+export async function deleteSearchIndexDatabases(
+ shouldDelete: (owner: SearchIndexDatabaseOwner) => boolean,
+): Promise<void> {
+ if (typeof indexedDB === "undefined" || typeof indexedDB.databases !== "function") return;
+ const databases = await indexedDB.databases();
+ await Promise.all(
+ databases
+ .map((db) => db.name)
+ .filter((name): name is string => !!name && name.startsWith(`${DB_PREFIX}:`))
+ .filter((name) => {
+ const owner = parseSearchIndexDatabaseName(name);
+ return owner === null || shouldDelete(owner);
+ })
+ .map((name) => deleteDatabase(name).catch(() => undefined)),
+ );
+}
+
+/** Deletes every local search index database on this origin. */
+export function deleteAllSearchIndexDatabases(): Promise<void> {
+ return deleteSearchIndexDatabases(() => true);
+}
+
+export class MemoryIndexStore implements IndexStore {
+ meta: IndexMeta | null = null;
+ readonly issues = new Map<string, SearchIndexIssue>();
+ readonly comments = new Map<string, SearchIndexComment>();
+ readonly projects = new Map<string, SearchIndexProject>();
+ destroyed = false;
+
+ async readMeta(): Promise<IndexMeta | null> {
+ return this.meta ? { ...this.meta } : null;
+ }
+
+ async loadAll(): Promise<IndexRecords> {
+ return {
+ issues: [...this.issues.values()],
+ comments: [...this.comments.values()],
+ projects: [...this.projects.values()],
+ };
+ }
+
+ async write(batch: IndexBatch): Promise<void> {
+ batch.issues?.forEach((record) => this.issues.set(record.id, record));
+ batch.comments?.forEach((record) => this.comments.set(record.id, record));
+ batch.projects?.forEach((record) => this.projects.set(record.id, record));
+ batch.deletedComments?.forEach((id) => this.comments.delete(id));
+ batch.deletedProjects?.forEach((id) => this.projects.delete(id));
+ for (const id of batch.deletedIssues ?? []) {
+ this.issues.delete(id);
+ for (const [commentId, comment] of this.comments) {
+ if (comment.issue_id === id) this.comments.delete(commentId);
+ }
+ }
+ if (batch.meta) this.meta = { ...batch.meta };
+ }
+
+ async reset(meta: IndexMeta): Promise<void> {
+ this.issues.clear();
+ this.comments.clear();
+ this.projects.clear();
+ this.meta = { ...meta };
+ }
+
+ async getIssues(ids: string[]) {
+ return pick(this.issues, ids);
+ }
+
+ async getComments(ids: string[]) {
+ return pick(this.comments, ids);
+ }
+
+ async getProjects(ids: string[]) {
+ return pick(this.projects, ids);
+ }
+
+ async destroy(): Promise<void> {
+ this.destroyed = true;
+ this.meta = null;
+ this.issues.clear();
+ this.comments.clear();
+ this.projects.clear();
+ }
+}
+
+function pick<T>(source: Map<string, T>, ids: string[]): Map<string, T> {
+ const out = new Map<string, T>();
+ for (const id of ids) {
+ const record = source.get(id);
+ if (record) out.set(id, record);
+ }
+ return out;
+}
diff --git a/packages/core/search-index/sync.test.ts b/packages/core/search-index/sync.test.ts
new file mode 100644
index 0000000000..d1ad549e4d
--- /dev/null
+++ b/packages/core/search-index/sync.test.ts
@@ -0,0 +1,229 @@
+// @vitest-environment node
+import { afterEach, describe, expect, it } from "vitest";
+import { MemoryIndexStore, SEARCH_INDEX_SCHEMA_VERSION } from "./store";
+import { IndexFetchError, WorkspaceIndex, type WorkspaceIndexOptions } from "./sync";
+import { FakeServer, commentRecord, issueRecord } from "./testing";
+
+let clock = 1_000_000;
+const indexes: WorkspaceIndex[] = [];
+
+function makeIndex(server: FakeServer, store = new MemoryIndexStore(), options: Partial<WorkspaceIndexOptions> = {}) {
+ const index = new WorkspaceIndex("user:ws", store, server, {
+ pollIntervalMs: 60 * 60 * 1000,
+ syncDebounceMs: 60 * 60 * 1000,
+ retryBaseMs: 60 * 60 * 1000,
+ now: () => clock,
+ ...options,
+ });
+ indexes.push(index);
+ return { index, store };
+}
+
+async function started(index: WorkspaceIndex): Promise<void> {
+ await index.start();
+}
+
+afterEach(async () => {
+ await Promise.all(indexes.splice(0).map((index) => index.dispose()));
+});
+
+describe("WorkspaceIndex", () => {
+ it("bootstraps page by page, then serves searches with server-shaped rows", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Alpha issue", "desc one") });
+ server.apply({ kind: "issue", record: issueRecord(2, "Beta issue") });
+ server.apply({ kind: "issue", record: issueRecord(3, "Gamma issue") });
+ server.apply({ kind: "comment", record: commentRecord("c1", "issue-3", "mentions alpha too") });
+ const { index, store } = makeIndex(server);
+
+ expect(await index.searchIssues({ q: "alpha" })).toBeNull();
+ await started(index);
+
+ expect(server.calls).toEqual(["manifest", "snapshot", "snapshot", "changes"]);
+ expect(index.isServing()).toBe(true);
+ expect(store.meta).toMatchObject({ schemaVersion: SEARCH_INDEX_SCHEMA_VERSION, cursor: "c4", bootstrap: null });
+ const result = await index.searchIssues({ q: "alpha" });
+ expect(result?.issues.map((i) => [i.id, i.match_source])).toEqual([
+ ["issue-1", "title"],
+ ["issue-3", "comment"],
+ ]);
+ expect(result?.issues[1]).toMatchObject({ matched_comment_snippet: "mentions alpha too" });
+ expect(result?.issues[0]).not.toHaveProperty("search_updated_at");
+ });
+
+ it("applies catch-up upserts and deletes, including an issue's comments", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Keep me") });
+ server.apply({ kind: "issue", record: issueRecord(2, "Delete me") });
+ server.apply({ kind: "comment", record: commentRecord("c1", "issue-2", "orphaned needle") });
+ const { index, store } = makeIndex(server);
+ await started(index);
+
+ server.apply({ kind: "issue", record: issueRecord(1, "Keep me renamed") });
+ server.apply({ kind: "delete-issue", id: "issue-2" });
+ server.apply({ kind: "issue", record: issueRecord(3, "Brand new") });
+ await index.sync();
+
+ expect((await index.searchIssues({ q: "renamed" }))?.issues.map((i) => i.id)).toEqual(["issue-1"]);
+ expect((await index.searchIssues({ q: "needle" }))?.issues).toEqual([]);
+ expect((await index.searchIssues({ q: "brand" }))?.issues.map((i) => i.id)).toEqual(["issue-3"]);
+ expect(store.comments.size).toBe(0);
+ expect(store.meta?.cursor).toBe(`c${server.version}`);
+ });
+
+ it("resumes an interrupted bootstrap without starting over", async () => {
+ const server = new FakeServer();
+ for (let n = 1; n <= 5; n++) server.apply({ kind: "issue", record: issueRecord(n, `Issue ${n}`) });
+ const { index, store } = makeIndex(server);
+ // Fail the second page.
+ const originalSnapshot = server.snapshot.bind(server);
+ let pages = 0;
+ server.snapshot = async (after, limit) => {
+ pages += 1;
+ if (pages === 2) throw new Error("network down");
+ return originalSnapshot(after, limit);
+ };
+ await started(index);
+ expect(store.meta?.bootstrap).toEqual({ cursor: "c5", afterNumber: 2 });
+ expect(index.isServing()).toBe(false);
+
+ await index.sync();
+ expect(server.calls.filter((c) => c === "manifest")).toHaveLength(1);
+ expect(store.issues.size).toBe(5);
+ expect(index.isServing()).toBe(true);
+ });
+
+ it("declines a workspace over the memory budget and rechecks it later", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Huge") });
+ server.textBytes = 10_000;
+ const { index, store } = makeIndex(server, undefined, { maxTextBytes: 1_000, tooLargeRecheckMs: 1_000 });
+ await started(index);
+
+ expect(index.currentState).toBe("too_large");
+ expect(server.calls).toEqual(["manifest"]);
+ expect(store.meta?.tooLargeAt).toBe(clock);
+
+ await index.sync();
+ expect(server.calls).toEqual(["manifest"]);
+
+ clock += 2_000;
+ server.textBytes = 10;
+ await index.sync();
+ expect(index.isServing()).toBe(true);
+ });
+
+ it("rebuilds from a fresh manifest when the cursor expired", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Before pruning") });
+ const { index } = makeIndex(server, undefined, { retryBaseMs: 0 });
+ await started(index);
+
+ server.failNext.changes = new IndexFetchError("expired", 410);
+ await index.sync();
+ // The rebuild is scheduled immediately; let it run.
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ await index.sync();
+
+ expect(server.calls.filter((c) => c === "manifest")).toHaveLength(2);
+ expect(index.isServing()).toBe(true);
+ });
+
+ it("drops the local copy when the workspace is no longer accessible", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Private title") });
+ const { index, store } = makeIndex(server);
+ await started(index);
+
+ server.failNext.changes = new IndexFetchError("workspace not found", 404);
+ await index.sync();
+
+ expect(index.currentState).toBe("unavailable");
+ expect(store.issues.size).toBe(0);
+ expect(store.meta?.cursor).toBeNull();
+ expect(await index.searchIssues({ q: "private" })).toBeNull();
+ });
+
+ it("keeps serving through brief failures, then defers to the server", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Steady") });
+ const { index } = makeIndex(server, undefined, { staleAfterMs: 1_000 });
+ await started(index);
+
+ server.failNext.changes = new Error("offline");
+ clock += 10;
+ await index.sync();
+ expect(index.isServing()).toBe(true);
+
+ clock += 2_000;
+ expect(index.isServing()).toBe(false);
+ expect(await index.searchIssues({ q: "steady" })).toBeNull();
+
+ await index.sync();
+ expect(index.isServing()).toBe(true);
+ });
+
+ it("reloads from the store when another context advanced the copy", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Shared db") });
+ const store = new MemoryIndexStore();
+ const { index } = makeIndex(server, store);
+ await started(index);
+
+ // Another tab's worker caught up and wrote to the same database.
+ server.apply({ kind: "issue", record: issueRecord(2, "Written elsewhere") });
+ await store.write({ issues: [server.issues.get("issue-2")!], meta: { ...store.meta!, cursor: `c${server.version}` } });
+
+ await index.sync();
+ expect((await index.searchIssues({ q: "elsewhere" }))?.issues.map((i) => i.id)).toEqual(["issue-2"]);
+ });
+
+ it("drops the copy when catch-up grows it past the memory budget", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Small") });
+ const { index, store } = makeIndex(server, undefined, { maxTextBytes: 1_000, tooLargeRecheckMs: 60_000 });
+ await started(index);
+ expect(index.isServing()).toBe(true);
+
+ server.apply({ kind: "issue", record: issueRecord(2, "Large", "x".repeat(2_000)) });
+ await index.sync();
+
+ expect(index.currentState).toBe("too_large");
+ expect(index.isServing()).toBe(false);
+ expect(await index.searchIssues({ q: "small" })).toBeNull();
+ expect(store.issues.size).toBe(0);
+ expect(store.meta).toMatchObject({ cursor: null, tooLargeAt: clock });
+
+ // Not re-downloaded on every sync; measured again after the recheck window.
+ const callsBefore = server.calls.length;
+ await index.sync();
+ expect(server.calls.length).toBe(callsBefore);
+ });
+
+ it("drops a stored copy that is already over the budget when it loads", async () => {
+ const server = new FakeServer();
+ server.apply({ kind: "issue", record: issueRecord(1, "Grew", "y".repeat(2_000)) });
+ const store = new MemoryIndexStore();
+ const first = makeIndex(server, store);
+ await started(first.index);
+ await first.index.dispose();
+
+ // The budget shrank (or the copy predates the check): the next load declines it.
+ const { index } = makeIndex(server, store, { maxTextBytes: 1_000 });
+ await started(index);
+ expect(index.currentState).toBe("too_large");
+ expect(store.issues.size).toBe(0);
+ });
+
+ it("stops a bootstrap whose pages outgrow the manifest estimate", async () => {
+ const server = new FakeServer();
+ for (let n = 1; n <= 4; n++) server.apply({ kind: "issue", record: issueRecord(n, `Page ${n}`, "z".repeat(600)) });
+ server.textBytes = 10; // an estimate far below what the pages carry
+ const { index, store } = makeIndex(server, undefined, { maxTextBytes: 1_000 });
+ await started(index);
+
+ expect(index.currentState).toBe("too_large");
+ expect(server.calls.filter((c) => c === "snapshot")).toHaveLength(1);
+ expect(store.issues.size).toBe(0);
+ });
+});
diff --git a/packages/core/search-index/sync.ts b/packages/core/search-index/sync.ts
new file mode 100644
index 0000000000..d6202e77e9
--- /dev/null
+++ b/packages/core/search-index/sync.ts
@@ -0,0 +1,385 @@
+import type {
+ SearchIndexChanges,
+ SearchIndexComment,
+ SearchIndexIssue,
+ SearchIndexManifest,
+ SearchIndexProject,
+ SearchIndexSnapshotPage,
+ SearchIssuesResponse,
+ SearchProjectsResponse,
+} from "../types";
+import {
+ SearchIndexEngine,
+ toSearchIssueResult,
+ toSearchProjectResult,
+ type IssueSearchParams,
+ type ProjectSearchParams,
+} from "./engine";
+import { SEARCH_INDEX_SCHEMA_VERSION, emptyIndexMeta, type IndexMeta, type IndexStore } from "./store";
+
+/**
+ * Keeps one workspace's local search index in step with the server
+ * (MUL-7754): a first full copy through the manifest and snapshot pages, then
+ * catch-up through the change log. Answers searches only while the copy is
+ * complete and recently confirmed current; otherwise callers use server search.
+ */
+
+/**
+ * Largest workspace (UTF-8 bytes of titles, descriptions, and comments) kept in
+ * memory. Local search holds roughly one copy of this text; a 150 MB workspace
+ * measured about 185 MB of worker heap and 10–25 ms per query.
+ */
+export const DEFAULT_MAX_TEXT_BYTES = 500 * 1024 * 1024;
+
+const SNAPSHOT_PAGE_SIZE = 200;
+const CHANGES_PAGE_SIZE = 500;
+
+export interface IndexFetcher {
+ manifest(): Promise<SearchIndexManifest>;
+ snapshot(afterNumber: number, limit: number): Promise<SearchIndexSnapshotPage>;
+ changes(cursor: string, limit: number): Promise<SearchIndexChanges>;
+}
+
+/** Thrown by fetchers for an HTTP error response. */
+export class IndexFetchError extends Error {
+ constructor(
+ message: string,
+ readonly status?: number,
+ ) {
+ super(message);
+ this.name = "IndexFetchError";
+ }
+}
+
+/** The copy outgrew the memory budget; it is dropped and server search takes over. */
+class OverBudgetError extends Error {}
+
+export type IndexState =
+ | "idle"
+ | "loading"
+ | "bootstrapping"
+ | "ready"
+ | "too_large"
+ | "unavailable"
+ | "disposed";
+
+export interface WorkspaceIndexOptions {
+ maxTextBytes: number;
+ /** A workspace over budget is measured again after this long. */
+ tooLargeRecheckMs: number;
+ /** After losing access (or the kill switch), wait this long before trying again. */
+ unavailableRetryMs: number;
+ /** Catch up at least this often while attached. */
+ pollIntervalMs: number;
+ /** Local results stop being served when the last good catch-up is this old and later ones failed. */
+ staleAfterMs: number;
+ /** Coalesces bursts of change notifications. */
+ syncDebounceMs: number;
+ retryBaseMs: number;
+ retryMaxMs: number;
+ now: () => number;
+ /** Returns [0, 1); spreads retries so clients rejected together do not return together. */
+ random: () => number;
+ /**
+ * Serializes syncs of the same workspace across contexts (dedicated workers
+ * in several tabs share one database).
+ */
+ withLock: <T>(name: string, fn: () => Promise<T>) => Promise<T>;
+ /** Called whenever whether the index can serve searches may have changed. */
+ onChange?: () => void;
+}
+
+export const defaultWorkspaceIndexOptions = (): WorkspaceIndexOptions => ({
+ maxTextBytes: DEFAULT_MAX_TEXT_BYTES,
+ tooLargeRecheckMs: 24 * 60 * 60 * 1000,
+ unavailableRetryMs: 60 * 60 * 1000,
+ pollIntervalMs: 5 * 60 * 1000,
+ staleAfterMs: 10 * 60 * 1000,
+ syncDebounceMs: 2_000,
+ retryBaseMs: 5_000,
+ retryMaxMs: 5 * 60 * 1000,
+ now: () => Date.now(),
+ random: () => Math.random(),
+ withLock: (_name, fn) => fn(),
+});
+
+export class WorkspaceIndex {
+ private readonly engine = new SearchIndexEngine();
+ private readonly options: WorkspaceIndexOptions;
+ private state: IndexState = "idle";
+ /** Cursor the in-memory engine reflects; differs from the store's when another context advanced it. */
+ private loadedCursor: string | null = null;
+ private lastSyncOkAt: number | null = null;
+ private lastErrorAt: number | null = null;
+ private failures = 0;
+ private running: Promise<void> | null = null;
+ private rerun = false;
+ private timer: ReturnType<typeof setTimeout> | null = null;
+ private pollTimer: ReturnType<typeof setInterval> | null = null;
+
+ constructor(
+ readonly key: string,
+ private readonly store: IndexStore,
+ private readonly fetcher: IndexFetcher,
+ options: Partial<WorkspaceIndexOptions> = {},
+ ) {
+ this.options = { ...defaultWorkspaceIndexOptions(), ...options };
+ }
+
+ get currentState(): IndexState {
+ return this.state;
+ }
+
+ /** Loads the stored copy and starts syncing and polling; resolves after the first sync. */
+ start(): Promise<void> {
+ if (this.state !== "idle") return Promise.resolve();
+ this.setState("loading");
+ this.pollTimer = setInterval(() => this.requestSync(), this.options.pollIntervalMs);
+ return this.sync();
+ }
+
+ /** Asks for a catch-up soon; bursts collapse into one run. */
+ requestSync(): void {
+ if (this.state === "disposed" || this.timer) return;
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ void this.sync();
+ }, this.options.syncDebounceMs);
+ }
+
+ /** Runs one sync now, or once more after the one in flight. */
+ sync(): Promise<void> {
+ if (this.state === "disposed") return Promise.resolve();
+ if (this.running) {
+ this.rerun = true;
+ return this.running;
+ }
+ this.running = (async () => {
+ try {
+ do {
+ this.rerun = false;
+ await this.options.withLock(`multica-search-index:${this.key}`, () => this.syncOnce());
+ } while (this.rerun && this.state !== "disposed");
+ } finally {
+ this.running = null;
+ }
+ })();
+ return this.running;
+ }
+
+ /** True when a search can be answered locally with current data. */
+ isServing(): boolean {
+ if (this.state !== "ready" || this.lastSyncOkAt === null) return false;
+ if (this.lastErrorAt === null || this.lastErrorAt <= this.lastSyncOkAt) return true;
+ return this.options.now() - this.lastSyncOkAt < this.options.staleAfterMs;
+ }
+
+ async searchIssues(params: IssueSearchParams): Promise<SearchIssuesResponse | null> {
+ if (!this.isServing()) return null;
+ const hits = this.engine.searchIssues(params);
+ const snippetIds = hits.map((hit) => hit.snippetCommentId).filter((id): id is string => id !== null);
+ const [issues, comments] = await Promise.all([
+ this.store.getIssues(hits.map((hit) => hit.id)),
+ this.store.getComments(snippetIds),
+ ]);
+ const results = [];
+ for (const hit of hits) {
+ const issue = issues.get(hit.id);
+ // Deleted between the scan and the read; the next search drops it too.
+ if (!issue) continue;
+ const comment = hit.snippetCommentId ? (comments.get(hit.snippetCommentId) ?? null) : null;
+ results.push(toSearchIssueResult(issue, hit, params.q, comment));
+ }
+ return { issues: results };
+ }
+
+ async searchProjects(params: ProjectSearchParams): Promise<SearchProjectsResponse | null> {
+ if (!this.isServing()) return null;
+ const hits = this.engine.searchProjects(params);
+ const projects = await this.store.getProjects(hits.map((hit) => hit.id));
+ const results = [];
+ for (const hit of hits) {
+ const project = projects.get(hit.id);
+ if (project) results.push(toSearchProjectResult(project, hit, params.q));
+ }
+ return { projects: results };
+ }
+
+ /** Stops syncing and releases memory. The stored copy stays unless `destroy`. */
+ async dispose(destroy = false): Promise<void> {
+ this.setState("disposed");
+ if (this.timer) clearTimeout(this.timer);
+ if (this.pollTimer) clearInterval(this.pollTimer);
+ this.timer = null;
+ this.pollTimer = null;
+ this.engine.clear();
+ if (destroy) await this.store.destroy();
+ }
+
+ private setState(state: IndexState): void {
+ if (this.state === state || this.state === "disposed") return;
+ this.state = state;
+ this.options.onChange?.();
+ }
+
+ private async syncOnce(): Promise<void> {
+ if (this.state === "disposed") return;
+ try {
+ let meta = await this.store.readMeta();
+ if (!meta || meta.schemaVersion !== SEARCH_INDEX_SCHEMA_VERSION) {
+ meta = emptyIndexMeta();
+ await this.store.reset(meta);
+ this.forgetLoaded();
+ }
+ if (this.state === "unavailable" && this.lastErrorAt !== null) {
+ if (this.options.now() - this.lastErrorAt < this.options.unavailableRetryMs) return;
+ }
+ if (!meta.cursor) {
+ if (meta.tooLargeAt !== null && this.options.now() - meta.tooLargeAt < this.options.tooLargeRecheckMs) {
+ this.setState("too_large");
+ return;
+ }
+ meta = await this.bootstrap(meta);
+ if (!meta.cursor) return;
+ } else if (this.loadedCursor !== meta.cursor) {
+ await this.reloadFromStore();
+ this.checkBudget();
+ this.loadedCursor = meta.cursor;
+ }
+ this.setState("ready");
+ await this.catchUp(meta);
+ this.lastSyncOkAt = this.options.now();
+ this.failures = 0;
+ this.options.onChange?.();
+ } catch (err) {
+ if (err instanceof OverBudgetError) await this.declineTooLarge();
+ else await this.handleFailure(err);
+ this.options.onChange?.();
+ }
+ }
+
+ private async bootstrap(meta: IndexMeta): Promise<IndexMeta> {
+ let progress = meta.bootstrap;
+ if (progress) {
+ // Resume: pages written before the interruption are already stored.
+ await this.reloadFromStore();
+ this.checkBudget();
+ } else {
+ const manifest = await this.fetcher.manifest();
+ if (manifest.text_bytes > this.options.maxTextBytes) throw new OverBudgetError();
+ progress = { cursor: manifest.cursor, afterNumber: 0 };
+ await this.store.reset({ ...emptyIndexMeta(), bootstrap: progress });
+ this.forgetLoaded();
+ }
+ this.setState("bootstrapping");
+
+ for (;;) {
+ if (this.state === "disposed") return meta;
+ const page = await this.fetcher.snapshot(progress.afterNumber, SNAPSHOT_PAGE_SIZE);
+ const next: IndexMeta = page.done
+ ? { ...emptyIndexMeta(), cursor: progress.cursor }
+ : { ...emptyIndexMeta(), bootstrap: { cursor: progress.cursor, afterNumber: page.next_after_number } };
+ await this.store.write({ issues: page.issues, comments: page.comments, projects: page.projects, meta: next });
+ this.applyUpserts(page.issues, page.comments, page.projects);
+ this.checkBudget();
+ if (page.done) {
+ this.loadedCursor = progress.cursor;
+ return next;
+ }
+ progress = next.bootstrap!;
+ }
+ }
+
+ private async catchUp(meta: IndexMeta): Promise<void> {
+ let cursor = meta.cursor!;
+ for (;;) {
+ if (this.state === "disposed") return;
+ const changes = await this.fetcher.changes(cursor, CHANGES_PAGE_SIZE);
+ await this.store.write({
+ issues: changes.issues,
+ comments: changes.comments,
+ projects: changes.projects,
+ deletedIssues: changes.deleted.issues,
+ deletedComments: changes.deleted.comments,
+ deletedProjects: changes.deleted.projects,
+ meta: { ...emptyIndexMeta(), cursor: changes.cursor },
+ });
+ this.engine.deleteIssues(changes.deleted.issues);
+ changes.deleted.comments.forEach((id) => this.engine.deleteComment(id));
+ changes.deleted.projects.forEach((id) => this.engine.deleteProject(id));
+ this.applyUpserts(changes.issues, changes.comments, changes.projects);
+ this.checkBudget();
+ cursor = changes.cursor;
+ this.loadedCursor = cursor;
+ if (!changes.has_more) return;
+ }
+ }
+
+ private applyUpserts(issues: SearchIndexIssue[], comments: SearchIndexComment[], projects: SearchIndexProject[]): void {
+ issues.forEach((issue) => this.engine.upsertIssue(issue));
+ comments.forEach((comment) => this.engine.upsertComment(comment));
+ projects.forEach((project) => this.engine.upsertProject(project));
+ }
+
+ private async reloadFromStore(): Promise<void> {
+ const records = await this.store.loadAll();
+ this.engine.clear();
+ this.applyUpserts(records.issues, records.comments, records.projects);
+ }
+
+ /**
+ * The manifest only sizes the first copy; a workspace keeps growing after
+ * that, so every load and every applied batch is measured again.
+ */
+ private checkBudget(): void {
+ if (this.engine.textBytes > this.options.maxTextBytes) throw new OverBudgetError();
+ }
+
+ /** Drops the copy and serves nothing until the workspace is measured again. */
+ private async declineTooLarge(): Promise<void> {
+ await this.store.reset({ ...emptyIndexMeta(), tooLargeAt: this.options.now() }).catch(() => undefined);
+ this.forgetLoaded();
+ this.setState("too_large");
+ }
+
+ private forgetLoaded(): void {
+ this.engine.clear();
+ this.loadedCursor = null;
+ }
+
+ private async handleFailure(err: unknown): Promise<void> {
+ if (this.state === "disposed") return;
+ this.lastErrorAt = this.options.now();
+ const status = err instanceof IndexFetchError ? err.status : undefined;
+ if (status === 410) {
+ // Retention pruning passed our snapshot: rebuild from a fresh manifest.
+ await this.store.reset(emptyIndexMeta()).catch(() => undefined);
+ this.forgetLoaded();
+ this.setState("loading");
+ this.scheduleRetry(0);
+ return;
+ }
+ if (status === 403 || status === 404) {
+ // Membership was lost, the workspace is gone, or the server turned the
+ // index off. Keep nothing on disk; try again much later.
+ await this.store.reset(emptyIndexMeta()).catch(() => undefined);
+ this.forgetLoaded();
+ this.setState("unavailable");
+ return;
+ }
+ // Transient: network, a busy server (503 while it sheds bootstrap load),
+ // or no tab to run the request. Back off exponentially with jitter.
+ this.failures += 1;
+ const backoff = Math.min(this.options.retryBaseMs * 2 ** (this.failures - 1), this.options.retryMaxMs);
+ this.scheduleRetry(backoff * (0.5 + this.options.random()));
+ }
+
+ private scheduleRetry(delay: number): void {
+ if (this.state === "disposed") return;
+ if (this.timer) clearTimeout(this.timer);
+ this.timer = setTimeout(() => {
+ this.timer = null;
+ void this.sync();
+ }, delay);
+ }
+}
diff --git a/packages/core/search-index/testing.ts b/packages/core/search-index/testing.ts
new file mode 100644
index 0000000000..50b12f3b32
--- /dev/null
+++ b/packages/core/search-index/testing.ts
@@ -0,0 +1,140 @@
+import type {
+ SearchIndexChanges,
+ SearchIndexComment,
+ SearchIndexIssue,
+ SearchIndexManifest,
+ SearchIndexSnapshotPage,
+} from "../types";
+import type { IndexFetcher } from "./sync";
+
+// Shared fixtures for the search index tests.
+
+export function issueRecord(number: number, title: string, description: string | null = null): SearchIndexIssue {
+ return {
+ id: `issue-${number}`,
+ workspace_id: "ws",
+ number,
+ identifier: `MUL-${number}`,
+ title,
+ description,
+ status: "todo",
+ priority: "none",
+ assignee_type: null,
+ assignee_id: null,
+ creator_type: "member",
+ creator_id: "user",
+ parent_issue_id: null,
+ project_id: null,
+ position: 0,
+ stage: null,
+ start_date: null,
+ due_date: null,
+ metadata: {},
+ properties: {},
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ search_updated_at: `2026-01-01T00:00:00.00000${number % 10}Z`,
+ } as SearchIndexIssue;
+}
+
+export function commentRecord(id: string, issueId: string, content: string): SearchIndexComment {
+ return { id, issue_id: issueId, content, created_at: "2026-01-01T00:00:00Z" };
+}
+
+export type Change =
+ | { kind: "issue"; record: SearchIndexIssue }
+ | { kind: "comment"; record: SearchIndexComment }
+ | { kind: "delete-issue"; id: string }
+ | { kind: "delete-comment"; id: string };
+
+/** A server with a numbered change log; cursors are "c<version>". */
+export class FakeServer implements IndexFetcher {
+ issues = new Map<string, SearchIndexIssue>();
+ comments = new Map<string, SearchIndexComment>();
+ log: Change[] = [];
+ textBytes = 100;
+ calls: string[] = [];
+ failNext: Partial<Record<"manifest" | "snapshot" | "changes", Error>> = {};
+
+ get version(): number {
+ return this.log.length;
+ }
+
+ apply(change: Change): void {
+ this.log.push(change);
+ if (change.kind === "issue") this.issues.set(change.record.id, change.record);
+ if (change.kind === "comment") this.comments.set(change.record.id, change.record);
+ if (change.kind === "delete-issue") {
+ this.issues.delete(change.id);
+ for (const [id, comment] of this.comments) {
+ if (comment.issue_id === change.id) this.comments.delete(id);
+ }
+ }
+ if (change.kind === "delete-comment") this.comments.delete(change.id);
+ }
+
+ private take(op: "manifest" | "snapshot" | "changes"): void {
+ this.calls.push(op);
+ const err = this.failNext[op];
+ if (err) {
+ delete this.failNext[op];
+ throw err;
+ }
+ }
+
+ async manifest(): Promise<SearchIndexManifest> {
+ this.take("manifest");
+ return {
+ cursor: `c${this.version}`,
+ issue_count: this.issues.size,
+ comment_count: this.comments.size,
+ project_count: 0,
+ text_bytes: this.textBytes,
+ };
+ }
+
+ async snapshot(afterNumber: number, limit: number): Promise<SearchIndexSnapshotPage> {
+ this.take("snapshot");
+ const page = [...this.issues.values()]
+ .filter((i) => i.number > afterNumber)
+ .sort((a, b) => a.number - b.number)
+ .slice(0, Math.min(limit, 2));
+ const ids = new Set(page.map((i) => i.id));
+ return {
+ issues: page,
+ comments: [...this.comments.values()].filter((c) => ids.has(c.issue_id)),
+ projects: [],
+ next_after_number: page.at(-1)?.number ?? afterNumber,
+ done: page.length < 2,
+ };
+ }
+
+ async changes(cursor: string): Promise<SearchIndexChanges> {
+ this.take("changes");
+ const from = Number(cursor.slice(1));
+ const out: SearchIndexChanges = {
+ issues: [],
+ comments: [],
+ projects: [],
+ deleted: { issues: [], comments: [], projects: [] },
+ cursor: `c${this.version}`,
+ has_more: false,
+ };
+ for (const change of this.log.slice(from)) {
+ if (change.kind === "issue") {
+ const live = this.issues.get(change.record.id);
+ if (live) out.issues.push(live);
+ else out.deleted.issues.push(change.record.id);
+ } else if (change.kind === "comment") {
+ const live = this.comments.get(change.record.id);
+ if (live) out.comments.push(live);
+ else out.deleted.comments.push(change.record.id);
+ } else if (change.kind === "delete-issue") {
+ out.deleted.issues.push(change.id);
+ } else {
+ out.deleted.comments.push(change.id);
+ }
+ }
+ return out;
+ }
+}
diff --git a/packages/core/search-index/worker.ts b/packages/core/search-index/worker.ts
new file mode 100644
index 0000000000..e0480e4bda
--- /dev/null
+++ b/packages/core/search-index/worker.ts
@@ -0,0 +1,41 @@
+// Entry point of the local search index worker (MUL-7754). Loaded as a
+// SharedWorker where the platform supports one, otherwise as a dedicated
+// Worker per tab; both speak the protocol in ./protocol.
+import { SearchIndexHost, type PortLike } from "./host";
+import type { TabMessage } from "./protocol";
+import { IdbIndexStore, deleteSearchIndexDatabases, searchIndexDatabaseName } from "./store";
+
+interface LockManagerLike {
+ request<T>(name: string, callback: () => Promise<T>): Promise<T>;
+}
+
+interface MessagePortLike extends PortLike {
+ onmessage: ((event: MessageEvent<TabMessage>) => void) | null;
+ start?(): void;
+}
+
+const locks = (globalThis.navigator as { locks?: LockManagerLike } | undefined)?.locks;
+
+const host = new SearchIndexHost({
+ createStore: (target) => new IdbIndexStore(searchIndexDatabaseName(target.userId, target.workspaceId)),
+ deleteDatabases: deleteSearchIndexDatabases,
+ indexOptions: {
+ withLock: locks ? (name, fn) => locks.request(name, fn) : (_name, fn) => fn(),
+ },
+});
+
+function listen(port: MessagePortLike): void {
+ const handle = host.connect(port);
+ port.onmessage = (event) => handle(event.data);
+ port.start?.();
+}
+
+const scope = globalThis as unknown as {
+ onconnect?: ((event: MessageEvent) => void) | null;
+};
+
+if ("onconnect" in scope) {
+ scope.onconnect = (event) => listen(event.ports[0] as unknown as MessagePortLike);
+} else {
+ listen(globalThis as unknown as MessagePortLike);
+}
diff --git a/packages/core/types/api.ts b/packages/core/types/api.ts
index e1fbf7cfee..8fb02b9f99 100644
--- a/packages/core/types/api.ts
+++ b/packages/core/types/api.ts
@@ -548,6 +548,60 @@ export interface SearchProjectsResponse {
projects: SearchProjectResult[];
}
+// Local search index sync (MUL-7754): GET /api/search-index/manifest,
+// GET /api/search-index/snapshot, POST /api/search-index/changes.
+
+/** Issue as the local search index stores it: a search row without match fields. */
+export interface SearchIndexIssue extends Issue {
+ /** Sub-second `updated_at`, which server search breaks ranking ties with. */
+ search_updated_at: string;
+}
+
+/** Project as the local index stores it. Issue and resource counts are not synced. */
+export interface SearchIndexProject extends Project {
+ search_updated_at: string;
+}
+
+export interface SearchIndexComment {
+ id: string;
+ issue_id: string;
+ content: string;
+ /** Sub-second RFC 3339 timestamp. */
+ created_at: string;
+}
+
+export interface SearchIndexManifest {
+ /** Opaque catch-up cursor for the snapshot the new copy starts from. */
+ cursor: string;
+ issue_count: number;
+ comment_count: number;
+ project_count: number;
+ /** UTF-8 bytes of every title, description, and live comment. */
+ text_bytes: number;
+}
+
+export interface SearchIndexSnapshotPage {
+ issues: SearchIndexIssue[];
+ comments: SearchIndexComment[];
+ /** Every project, on the first page only. */
+ projects: SearchIndexProject[];
+ next_after_number: number;
+ done: boolean;
+}
+
+export interface SearchIndexChanges {
+ issues: SearchIndexIssue[];
+ comments: SearchIndexComment[];
+ projects: SearchIndexProject[];
+ deleted: {
+ issues: string[];
+ comments: string[];
+ projects: string[];
+ };
+ cursor: string;
+ has_more: boolean;
+}
+
export interface UpdateMeRequest {
name?: string;
avatar_url?: string;
diff --git a/packages/core/workspace/mutations.test.tsx b/packages/core/workspace/mutations.test.tsx
index e60930c933..c70b86e1f7 100644
--- a/packages/core/workspace/mutations.test.tsx
+++ b/packages/core/workspace/mutations.test.tsx
@@ -9,11 +9,17 @@ import { setApiInstance } from "../api";
import type { ApiClient } from "../api/client";
import { defaultStorage } from "../platform/storage";
import type { Workspace, WorkspaceMcpServer } from "../types";
+import { forgetLocalSearchIndex } from "../search-index/instance";
import {
useCreateWorkspace,
useDeleteWorkspace,
+ useLeaveWorkspace,
useUpdateWorkspaceMcpServer,
} from "./mutations";
+
+vi.mock("../search-index/instance", () => ({
+ forgetLocalSearchIndex: vi.fn(async () => undefined),
+}));
import { agentMcpServersOptions, workspaceKeys } from "./queries";
import {
isWorkspaceDeletePending,
@@ -132,6 +138,7 @@ describe("useDeleteWorkspace", () => {
unmarkWorkspaceDeletePending("ws-2");
localStorage.clear();
vi.restoreAllMocks();
+ vi.mocked(forgetLocalSearchIndex).mockClear();
});
it("leaves the list cache untouched while the DELETE is pending (no optimistic removal)", async () => {
@@ -196,6 +203,7 @@ describe("useDeleteWorkspace", () => {
expect(defaultStorage.getItem("multica_issue_draft:delete-me")).toBeNull();
expect(defaultStorage.getItem("multica_issue_draft:keep-me")).toBe("draft");
+ expect(forgetLocalSearchIndex).toHaveBeenCalledWith("ws-2");
});
it("leaves storage and cache untouched when the DELETE fails", async () => {
@@ -214,6 +222,8 @@ describe("useDeleteWorkspace", () => {
// No optimistic write happened, so there is nothing to roll back.
expect(defaultStorage.getItem("multica_issue_draft:delete-me")).toBe("draft");
expect(cachedList().map((w) => w.id)).toEqual(["ws-1", "ws-2"]);
+ // The workspace still exists, so its local search copy stays.
+ expect(forgetLocalSearchIndex).not.toHaveBeenCalled();
});
it("keeps the self-initiated marker after success and lifts it after failure", async () => {
@@ -355,3 +365,26 @@ describe("useUpdateWorkspaceMcpServer", () => {
expect(listAgentMcpServers).toHaveBeenCalledWith("agent-1");
});
});
+
+describe("useLeaveWorkspace", () => {
+ afterEach(() => {
+ vi.mocked(forgetLocalSearchIndex).mockClear();
+ });
+
+ it("destroys the local search copy only after the server confirms", async () => {
+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const leaveWorkspace = vi.fn().mockRejectedValueOnce(new Error("nope")).mockResolvedValueOnce(undefined);
+ setApiInstance({ leaveWorkspace, listWorkspaces: vi.fn().mockResolvedValue([]) } as unknown as ApiClient);
+ const { result } = renderHook(() => useLeaveWorkspace(), { wrapper: createWrapper(qc) });
+
+ await act(async () => {
+ await expect(result.current.mutateAsync("ws-3")).rejects.toThrow("nope");
+ });
+ expect(forgetLocalSearchIndex).not.toHaveBeenCalled();
+
+ await act(async () => {
+ await result.current.mutateAsync("ws-3");
+ });
+ expect(forgetLocalSearchIndex).toHaveBeenCalledWith("ws-3");
+ });
+});
diff --git a/packages/core/workspace/mutations.ts b/packages/core/workspace/mutations.ts
index 2eee3e44aa..02ab3a0255 100644
--- a/packages/core/workspace/mutations.ts
+++ b/packages/core/workspace/mutations.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { forgetLocalSearchIndex } from "../search-index/instance";
import type { Workspace } from "../types";
import { api } from "../api";
import { defaultStorage } from "../platform/storage";
@@ -44,6 +45,9 @@ export function useLeaveWorkspace() {
const qc = useQueryClient();
return useMutation({
mutationFn: (workspaceId: string) => api.leaveWorkspace(workspaceId),
+ onSuccess: (_data, workspaceId) => {
+ void forgetLocalSearchIndex(workspaceId);
+ },
onSettled: () => {
qc.invalidateQueries({ queryKey: workspaceKeys.list() });
},
@@ -74,8 +78,9 @@ export function useDeleteWorkspace() {
// `${key}:${slug}` namespace — a failed DELETE means the workspace still
// exists and its drafts/view state must survive. The realtime handler
// skips self-initiated deletes, so cleanup has to happen here.
- onSuccess: (_data, _workspaceId, ctx) => {
+ onSuccess: (_data, workspaceId, ctx) => {
if (ctx?.slug) clearWorkspaceStorage(defaultStorage, ctx.slug);
+ void forgetLocalSearchIndex(workspaceId);
},
// The workspace still exists after a failed DELETE, so a later external
// delete of the same ID must be handled by the realtime handler again.
diff --git a/packages/views/editor/extensions/mention-suggestion.tsx b/packages/views/editor/extensions/mention-suggestion.tsx
index 186733409f..95618b2125 100644
--- a/packages/views/editor/extensions/mention-suggestion.tsx
+++ b/packages/views/editor/extensions/mention-suggestion.tsx
@@ -19,7 +19,7 @@ import { workspaceKeys } from "@multica/core/workspace/queries";
import { useAuthStore } from "@multica/core/auth";
import { canAssignAgentToIssue } from "@multica/core/permissions";
import { isAgentRuntimeBound } from "@multica/core/agents";
-import { api } from "@multica/core/api";
+import { searchIssues, searchProjects } from "@multica/core/search-index";
import {
isIssueDirectHit,
isProjectDirectHit,
@@ -306,13 +306,13 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
try {
if (includeProjectSearch) {
const [issues, projects] = await Promise.all([
- api.searchIssues({
+ searchIssues({
q,
limit: SERVER_CONTEXT_SEARCH_LIMIT,
include_closed: true,
signal: controller.signal,
}),
- api.searchProjects({
+ searchProjects({
q,
limit: SERVER_CONTEXT_SEARCH_LIMIT,
include_closed: true,
@@ -326,7 +326,7 @@ export const MentionList = forwardRef<MentionListRef, MentionListProps>(
]);
}
} else {
- const res = await api.searchIssues({
+ const res = await searchIssues({
q,
limit: SERVER_ISSUE_SEARCH_LIMIT,
include_closed: true,
diff --git a/packages/views/modals/issue-picker-modal.tsx b/packages/views/modals/issue-picker-modal.tsx
index 8d15fdae5a..6c8170b641 100644
--- a/packages/views/modals/issue-picker-modal.tsx
+++ b/packages/views/modals/issue-picker-modal.tsx
@@ -5,7 +5,7 @@ import { useWorkspaceId } from "@multica/core/hooks";
import { useIssueStatuses } from "@multica/core/issue-statuses/hooks";
import { useState, useEffect, useCallback, useRef } from "react";
import type { Issue } from "@multica/core/types";
-import { api } from "@multica/core/api";
+import { searchIssues } from "@multica/core/search-index";
import {
Command,
CommandDialog,
@@ -87,7 +87,7 @@ export function IssuePickerModal({
const controller = new AbortController();
abortRef.current = controller;
try {
- const res = await api.searchIssues({
+ const res = await searchIssues({
q: q.trim(),
limit: 20,
include_closed: true,
diff --git a/packages/views/modals/mark-duplicate-issue.tsx b/packages/views/modals/mark-duplicate-issue.tsx
index 8b86db0ec0..026ce369e9 100644
--- a/packages/views/modals/mark-duplicate-issue.tsx
+++ b/packages/views/modals/mark-duplicate-issue.tsx
@@ -3,7 +3,8 @@
import { useMemo } from "react";
import { useQueries, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
-import { api, errorCode } from "@multica/core/api";
+import { errorCode } from "@multica/core/api";
+import { searchIssues } from "@multica/core/search-index";
import { useWorkspaceId } from "@multica/core/hooks";
import {
issueDetailOptions,
@@ -60,7 +61,7 @@ export function MarkDuplicateIssueModal({
const title = issue?.title.trim() ?? "";
const { data: sameTitle } = useQuery({
queryKey: [...issueKeys.all(wsId), "duplicate-candidates", issueId, title],
- queryFn: () => api.searchIssues({ q: title, limit: SUGGESTION_LIMIT, include_closed: true }),
+ queryFn: () => searchIssues({ q: title, limit: SUGGESTION_LIMIT, include_closed: true }),
enabled: title !== "",
staleTime: 60_000,
});
diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsx
index a6545f6f0c..b31e80905c 100644
--- a/packages/views/search/search-command.tsx
+++ b/packages/views/search/search-command.tsx
@@ -27,7 +27,7 @@ import type {
SearchIssueResult,
SearchProjectResult,
} from "@multica/core/types";
-import { api } from "@multica/core/api";
+import { isLocalSearchReady, searchIssues, searchProjects } from "@multica/core/search-index";
import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";
import {
openCreateIssueWithPreference,
@@ -630,18 +630,21 @@ export function SearchCommand() {
}
setIsLoading(true);
+ // The debounce spares the server a request per keystroke; the local index
+ // answers in milliseconds, so it searches on every keystroke.
+ const delay = isLocalSearchReady() ? 0 : 300;
debounceRef.current = setTimeout(async () => {
const controller = new AbortController();
abortRef.current = controller;
try {
const [issueRes, projectRes] = await Promise.all([
- api.searchIssues({
+ searchIssues({
q: q.trim(),
limit: 20,
include_closed: true,
signal: controller.signal,
}),
- api.searchProjects({
+ searchProjects({
q: q.trim(),
limit: 10,
include_closed: true,
@@ -665,7 +668,7 @@ export function SearchCommand() {
setIsLoading(false);
}
}
- }, 300);
+ }, delay);
}, []);
const handleValueChange = useCallback(
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index b960628142..088c1f31db 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "563_search_index_change_changed_at_index": "idx_search_index_change_changed_at",
+ "562_search_index_change_workspace_index": "idx_search_index_change_workspace_xid",
"552_agent_task_history_page_index": "idx_agent_task_queue_history_page",
"535_github_pr_address_index": "idx_github_pull_request_pr_owner_repo",
"539_task_supplement_request_index": "task_supplement_task_request_uidx",
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 5c7f3567b7..6f6773cf89 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -825,6 +825,9 @@ func main() {
// not fit). Crash recovery, occurrence-level idempotency, lease
// theft, and retry are all reused from the manager + sys_cron_executions
// — there is no separate goroutine for scheduled Autopilot anymore.
+ if err := schedulerMgr.Register(scheduler.SearchIndexChangePruneJob(queries)); err != nil {
+ slog.Warn("scheduler: failed to register search index change prune job", "error", err)
+ }
if err := schedulerMgr.Register(scheduler.IssueWakeupJob(&service.IssueWakeupService{Tasks: taskSvc})); err != nil {
slog.Error("scheduler: register issue wakeups", "error", err)
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index bb6ef22848..4aaf9eadba 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1984,6 +1984,16 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Assignee frequency
r.Get("/api/assignee-frequency", h.GetAssigneeFrequency)
+ // Local search index sync for Web/Desktop (MUL-7754). Human clients
+ // only: agents search through /api/issues/search.
+ r.Route("/api/search-index", func(r chi.Router) {
+ r.Use(handler.RequireHumanActor)
+ r.Use(h.RequireLocalSearchIndex)
+ r.Get("/manifest", h.GetSearchIndexManifest)
+ r.Get("/snapshot", h.GetSearchIndexSnapshot)
+ r.Post("/changes", h.ListSearchIndexChanges)
+ })
+
// Issues
r.Route("/api/issues", func(r chi.Router) {
r.Get("/limit-usage", h.GetIssueLimitUsage)
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index 7c97c3b0f8..ca8e9c5d8c 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -30,6 +30,11 @@ const (
// either way. Turning it off stops new intake and triage runs but leaves
// existing Triage issues workable.
TriageV1 = "triage_v1"
+ // LocalSearchIndex gates the sync endpoints behind Web/Desktop local search
+ // (MUL-7754). On by default. Turning it off (FF_LOCAL_SEARCH_INDEX=off)
+ // makes those endpoints answer 404, so clients stop syncing and search
+ // through the server again without a client release.
+ LocalSearchIndex = "local_search_index"
// agentBuilderCompat is no longer a release flag. Keep publishing the key
// as enabled so installed desktop clients that still gate the AI creation
// entry on this config decision receive the permanently enabled behavior.
@@ -69,6 +74,10 @@ func TriageV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, TriageV1, false)
}
+func LocalSearchIndexEnabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, LocalSearchIndex, true)
+}
+
func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {
out := make(map[string]bool, len(frontendPublicFlags)+3)
for _, key := range frontendPublicFlags {
diff --git a/server/internal/handler/search_index.go b/server/internal/handler/search_index.go
new file mode 100644
index 0000000000..913eea615e
--- /dev/null
+++ b/server/internal/handler/search_index.go
@@ -0,0 +1,608 @@
+package handler
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgconn"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/logger"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Local search index sync (MUL-7754).
+//
+// Web and Desktop keep a per-workspace copy of issue, comment, and project text
+// and search it locally. A client bootstraps with GET /manifest (which pins the
+// snapshot the copy starts from) followed by GET /snapshot pages, then catches
+// up with POST /changes. Catch-up reads search_index_change (migration 561):
+// an entity is returned when its latest write committed in the target snapshot
+// but not in the snapshot the client already holds. Comparing xids against
+// pg_snapshot values is exact under any commit order and is not held back by
+// long-running transactions elsewhere in the database.
+//
+// Every read runs on the primary: a replica would hand out a snapshot and rows
+// from different points in time, and the difference would be lost silently.
+const (
+ searchIndexSnapshotDefaultLimit = 200
+ searchIndexSnapshotMaxLimit = 500
+ searchIndexChangesDefaultLimit = 500
+ searchIndexChangesMaxLimit = 1000
+ // A pg_snapshot lists every in-progress xid, so its text grows with write
+ // concurrency. This bounds a cursor far above any realistic snapshot.
+ searchIndexCursorMaxBytes = 256 << 10
+ searchIndexCursorVersion = 1
+ searchIndexStatementLimit = 15 * time.Second
+)
+
+// searchIndexBootstrapSlots bounds the manifest and snapshot reads one API
+// process runs at once. Every client builds its first copy with these, and they
+// all start together right after a release or an outage; without a bound that
+// herd would take most of the connection pool. Callers that cannot get a slot
+// soon answer 503 with Retry-After, and clients back off with jitter.
+var searchIndexBootstrapSlots = make(chan struct{}, 4)
+
+const searchIndexBootstrapWait = 2 * time.Second
+
+func acquireSearchIndexBootstrapSlot(ctx context.Context) (release func(), ok bool) {
+ timer := time.NewTimer(searchIndexBootstrapWait)
+ defer timer.Stop()
+ select {
+ case searchIndexBootstrapSlots <- struct{}{}:
+ return func() { <-searchIndexBootstrapSlots }, true
+ case <-timer.C:
+ return nil, false
+ case <-ctx.Done():
+ return nil, false
+ }
+}
+
+func writeSearchIndexBusy(w http.ResponseWriter) {
+ w.Header().Set("Retry-After", "5")
+ writeError(w, http.StatusServiceUnavailable, "search index is busy; retry later")
+}
+
+var pgSnapshotTextRe = regexp.MustCompile(`^[0-9]{1,20}:[0-9]{1,20}:([0-9]{1,20}(,[0-9]{1,20})*)?$`)
+
+// validPGSnapshotText applies pg_snapshot's own input rules. Postgres only
+// checks them when a plan happens to evaluate the cast, which an empty range
+// can skip, so a bad cursor must be rejected here.
+func validPGSnapshotText(s string) bool {
+ if !pgSnapshotTextRe.MatchString(s) {
+ return false
+ }
+ parts := strings.SplitN(s, ":", 3)
+ xmin, err := strconv.ParseUint(parts[0], 10, 64)
+ if err != nil || xmin == 0 {
+ return false
+ }
+ xmax, err := strconv.ParseUint(parts[1], 10, 64)
+ if err != nil || xmin > xmax {
+ return false
+ }
+ if parts[2] == "" {
+ return true
+ }
+ last := xmin
+ for _, raw := range strings.Split(parts[2], ",") {
+ xip, err := strconv.ParseUint(raw, 10, 64)
+ if err != nil || xip < last || xip >= xmax {
+ return false
+ }
+ last = xip
+ }
+ return true
+}
+
+// searchIndexCursor is opaque to clients. Since is the snapshot whose changes
+// the client already holds. Target and the After* keyset are set only while a
+// catch-up spans several pages; once it completes, Target becomes the next
+// Since.
+type searchIndexCursor struct {
+ Version int `json:"v"`
+ Since string `json:"s"`
+ Target string `json:"t,omitempty"`
+ AfterXid string `json:"x,omitempty"`
+ AfterType string `json:"e,omitempty"`
+ AfterID string `json:"i,omitempty"`
+}
+
+func encodeSearchIndexCursor(c searchIndexCursor) string {
+ c.Version = searchIndexCursorVersion
+ raw, _ := json.Marshal(c)
+ return base64.RawURLEncoding.EncodeToString(raw)
+}
+
+func decodeSearchIndexCursor(s string) (searchIndexCursor, error) {
+ var c searchIndexCursor
+ if s == "" || len(s) > searchIndexCursorMaxBytes {
+ return c, errors.New("invalid cursor")
+ }
+ raw, err := base64.RawURLEncoding.DecodeString(s)
+ if err != nil {
+ return c, errors.New("invalid cursor")
+ }
+ if err := json.Unmarshal(raw, &c); err != nil || c.Version != searchIndexCursorVersion {
+ return c, errors.New("invalid cursor")
+ }
+ if !validPGSnapshotText(c.Since) {
+ return c, errors.New("invalid cursor")
+ }
+ if c.Target == "" {
+ if c.AfterXid != "" || c.AfterType != "" || c.AfterID != "" {
+ return c, errors.New("invalid cursor")
+ }
+ return c, nil
+ }
+ if !validPGSnapshotText(c.Target) {
+ return c, errors.New("invalid cursor")
+ }
+ if _, err := strconv.ParseUint(c.AfterXid, 10, 64); err != nil {
+ return c, errors.New("invalid cursor")
+ }
+ switch c.AfterType {
+ case "issue", "comment", "project":
+ default:
+ return c, errors.New("invalid cursor")
+ }
+ if _, err := parseUUIDStrict(c.AfterID); err != nil {
+ return c, errors.New("invalid cursor")
+ }
+ return c, nil
+}
+
+func parseUUIDStrict(s string) (pgtype.UUID, error) {
+ var u pgtype.UUID
+ if err := u.Scan(s); err != nil {
+ return u, err
+ }
+ if !u.Valid {
+ return u, errors.New("invalid uuid")
+ }
+ return u, nil
+}
+
+// SearchIndexIssue is the issue record a client indexes: the same shape the
+// search endpoint returns, plus the sub-second updated_at that server-side
+// ranking breaks ties with (IssueResponse.UpdatedAt is second-precision).
+type SearchIndexIssue struct {
+ IssueResponse
+ SearchUpdatedAt string `json:"search_updated_at"`
+}
+
+// SearchIndexProject is the project search result shape without the issue and
+// resource counts, which change without a project write and are not shown in
+// search results.
+type SearchIndexProject struct {
+ ProjectResponse
+ SearchUpdatedAt string `json:"search_updated_at"`
+}
+
+type SearchIndexComment struct {
+ ID string `json:"id"`
+ IssueID string `json:"issue_id"`
+ Content string `json:"content"`
+ CreatedAt string `json:"created_at"`
+}
+
+type SearchIndexManifestResponse struct {
+ Cursor string `json:"cursor"`
+ IssueCount int64 `json:"issue_count"`
+ CommentCount int64 `json:"comment_count"`
+ ProjectCount int64 `json:"project_count"`
+ // TextBytes totals the UTF-8 bytes of every title, description, and live
+ // comment, so a client can decline a workspace its memory budget cannot hold.
+ TextBytes int64 `json:"text_bytes"`
+}
+
+type SearchIndexSnapshotResponse struct {
+ Issues []SearchIndexIssue `json:"issues"`
+ Comments []SearchIndexComment `json:"comments"`
+ Projects []SearchIndexProject `json:"projects"`
+ NextAfterNumber int32 `json:"next_after_number"`
+ Done bool `json:"done"`
+}
+
+type SearchIndexDeleted struct {
+ Issues []string `json:"issues"`
+ Comments []string `json:"comments"`
+ Projects []string `json:"projects"`
+}
+
+type SearchIndexChangesResponse struct {
+ Issues []SearchIndexIssue `json:"issues"`
+ Comments []SearchIndexComment `json:"comments"`
+ Projects []SearchIndexProject `json:"projects"`
+ Deleted SearchIndexDeleted `json:"deleted"`
+ Cursor string `json:"cursor"`
+ HasMore bool `json:"has_more"`
+}
+
+// RequireLocalSearchIndex answers 404 while the local_search_index kill switch
+// is off. Clients treat that like an older server without these endpoints and
+// keep using server search.
+func (h *Handler) RequireLocalSearchIndex(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if !featureflags.LocalSearchIndexEnabled(r.Context(), h.FeatureFlags) {
+ writeError(w, http.StatusNotFound, "local search index is disabled")
+ return
+ }
+ next.ServeHTTP(w, r)
+ })
+}
+
+// runSearchIndexRead runs fn in a read-only REPEATABLE READ transaction, so the
+// snapshot returned by pg_current_snapshot() is exactly the one fn reads under.
+func (h *Handler) runSearchIndexRead(ctx context.Context, fn func(q *db.Queries) error) error {
+ tx, err := h.TxStarter.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin search index tx: %w", err)
+ }
+ defer func() { _ = tx.Rollback(context.Background()) }()
+ // Must be the first statement: the isolation level cannot change once the
+ // transaction has taken its snapshot.
+ if _, err := tx.Exec(ctx, "SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY"); err != nil {
+ return fmt.Errorf("set search index isolation: %w", err)
+ }
+ timeoutMs := int(searchIndexStatementLimit / time.Millisecond)
+ if _, err := tx.Exec(ctx, fmt.Sprintf("SET LOCAL statement_timeout = %d", timeoutMs)); err != nil {
+ return fmt.Errorf("set search index statement_timeout: %w", err)
+ }
+ if err := fn(h.Queries.WithTx(tx)); err != nil {
+ return err
+ }
+ return tx.Commit(ctx)
+}
+
+func (h *Handler) writeSearchIndexError(w http.ResponseWriter, r *http.Request, op string, err error) {
+ if isSearchStatementTimeout(err) {
+ writeError(w, http.StatusServiceUnavailable, "search index read timed out; please retry")
+ return
+ }
+ slog.Warn("search index read failed", append(logger.RequestAttrs(r), "op", op, "error", err)...)
+ writeError(w, http.StatusInternalServerError, "failed to read search index")
+}
+
+// GetSearchIndexManifest returns the snapshot a new local copy starts from and
+// the size of the text it would hold.
+func (h *Handler) GetSearchIndexManifest(w http.ResponseWriter, r *http.Request) {
+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")
+ if !ok {
+ return
+ }
+ release, ok := acquireSearchIndexBootstrapSlot(r.Context())
+ if !ok {
+ writeSearchIndexBusy(w)
+ return
+ }
+ defer release()
+ var row db.GetSearchIndexManifestRow
+ err := h.runSearchIndexRead(r.Context(), func(q *db.Queries) error {
+ var err error
+ row, err = q.GetSearchIndexManifest(r.Context(), wsUUID)
+ return err
+ })
+ if err != nil {
+ h.writeSearchIndexError(w, r, "manifest", err)
+ return
+ }
+ writeJSON(w, http.StatusOK, SearchIndexManifestResponse{
+ Cursor: encodeSearchIndexCursor(searchIndexCursor{Since: row.Snapshot}),
+ IssueCount: row.IssueCount,
+ CommentCount: row.CommentCount,
+ ProjectCount: row.ProjectCount,
+ TextBytes: row.IssueBytes + row.CommentBytes + row.ProjectBytes,
+ })
+}
+
+// GetSearchIndexSnapshot returns one page of issues ordered by number, every
+// live comment on those issues, and (on the first page) every project.
+func (h *Handler) GetSearchIndexSnapshot(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")
+ if !ok {
+ return
+ }
+ afterNumber := int64(0)
+ if raw := r.URL.Query().Get("after_number"); raw != "" {
+ v, err := strconv.ParseInt(raw, 10, 32)
+ if err != nil || v < 0 {
+ writeError(w, http.StatusBadRequest, "invalid after_number")
+ return
+ }
+ afterNumber = v
+ }
+ limit := searchIndexSnapshotDefaultLimit
+ if raw := r.URL.Query().Get("limit"); raw != "" {
+ v, err := strconv.Atoi(raw)
+ if err != nil || v <= 0 {
+ writeError(w, http.StatusBadRequest, "invalid limit")
+ return
+ }
+ limit = min(v, searchIndexSnapshotMaxLimit)
+ }
+ release, ok := acquireSearchIndexBootstrapSlot(ctx)
+ if !ok {
+ writeSearchIndexBusy(w)
+ return
+ }
+ defer release()
+
+ var (
+ issues []db.Issue
+ comments []db.ListSearchIndexCommentsByIssuesRow
+ projects []db.Project
+ )
+ err := h.runSearchIndexRead(ctx, func(q *db.Queries) error {
+ var err error
+ issues, err = q.ListSearchIndexIssuesPage(ctx, db.ListSearchIndexIssuesPageParams{
+ WorkspaceID: wsUUID,
+ AfterNumber: int32(afterNumber),
+ PageLimit: int32(limit),
+ })
+ if err != nil {
+ return err
+ }
+ if len(issues) > 0 {
+ ids := make([]pgtype.UUID, len(issues))
+ for i, is := range issues {
+ ids[i] = is.ID
+ }
+ comments, err = q.ListSearchIndexCommentsByIssues(ctx, db.ListSearchIndexCommentsByIssuesParams{
+ WorkspaceID: wsUUID,
+ IssueIds: ids,
+ })
+ if err != nil {
+ return err
+ }
+ }
+ if afterNumber == 0 {
+ projects, err = q.ListSearchIndexProjects(ctx, wsUUID)
+ }
+ return err
+ })
+ if err != nil {
+ h.writeSearchIndexError(w, r, "snapshot", err)
+ return
+ }
+
+ resp := SearchIndexSnapshotResponse{
+ Issues: h.searchIndexIssues(ctx, wsUUID, issues),
+ Comments: make([]SearchIndexComment, 0, len(comments)),
+ Projects: searchIndexProjects(projects),
+ NextAfterNumber: int32(afterNumber),
+ Done: len(issues) < limit,
+ }
+ for _, c := range comments {
+ resp.Comments = append(resp.Comments, searchIndexComment(c.ID, c.IssueID, c.Content, c.CreatedAt))
+ }
+ if n := len(issues); n > 0 {
+ resp.NextAfterNumber = issues[n-1].Number
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+// ListSearchIndexChanges returns the entities written after the cursor's
+// snapshot: live rows as upserts, missing rows (and comment tombstones) as
+// deletions. Returns 410 when retention pruning may have dropped a change the
+// cursor has not seen; the client must then rebuild its copy.
+func (h *Handler) ListSearchIndexChanges(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ wsUUID, ok := parseUUIDOrBadRequest(w, h.resolveWorkspaceID(r), "workspace_id")
+ if !ok {
+ return
+ }
+ var req struct {
+ Cursor string `json:"cursor"`
+ Limit int `json:"limit"`
+ }
+ if err := json.NewDecoder(io.LimitReader(r.Body, searchIndexCursorMaxBytes+1024)).Decode(&req); err != nil {
+ writeError(w, http.StatusBadRequest, "invalid request body")
+ return
+ }
+ cur, err := decodeSearchIndexCursor(req.Cursor)
+ if err != nil {
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return
+ }
+ limit := searchIndexChangesDefaultLimit
+ if req.Limit > 0 {
+ limit = min(req.Limit, searchIndexChangesMaxLimit)
+ }
+
+ var (
+ pruned bool
+ target = cur.Target
+ changes []db.ListSearchIndexChangesRow
+ issues []db.Issue
+ comments []db.ListSearchIndexCommentsByIDsRow
+ projects []db.Project
+ )
+ err = h.runSearchIndexRead(ctx, func(q *db.Queries) error {
+ var err error
+ if pruned, err = q.SearchIndexSinceIsPruned(ctx, cur.Since); err != nil || pruned {
+ return err
+ }
+ if target == "" {
+ if target, err = q.GetSearchIndexCurrentSnapshot(ctx); err != nil {
+ return err
+ }
+ }
+ params := db.ListSearchIndexChangesParams{
+ WorkspaceID: wsUUID,
+ SinceSnapshot: cur.Since,
+ TargetSnapshot: target,
+ AfterXid: "0",
+ AfterType: "",
+ AfterID: pgtype.UUID{Valid: true},
+ PageLimit: int32(limit + 1),
+ }
+ if cur.Target != "" {
+ params.AfterXid = cur.AfterXid
+ params.AfterType = cur.AfterType
+ params.AfterID, _ = parseUUIDStrict(cur.AfterID)
+ }
+ if changes, err = q.ListSearchIndexChanges(ctx, params); err != nil {
+ return err
+ }
+ if len(changes) > limit {
+ changes = changes[:limit]
+ }
+ var issueIDs, commentIDs, projectIDs []pgtype.UUID
+ for _, c := range changes {
+ switch c.EntityType {
+ case "issue":
+ issueIDs = append(issueIDs, c.EntityID)
+ case "comment":
+ commentIDs = append(commentIDs, c.EntityID)
+ case "project":
+ projectIDs = append(projectIDs, c.EntityID)
+ }
+ }
+ if len(issueIDs) > 0 {
+ if issues, err = q.ListSearchIndexIssuesByIDs(ctx, db.ListSearchIndexIssuesByIDsParams{WorkspaceID: wsUUID, Ids: issueIDs}); err != nil {
+ return err
+ }
+ }
+ if len(commentIDs) > 0 {
+ if comments, err = q.ListSearchIndexCommentsByIDs(ctx, db.ListSearchIndexCommentsByIDsParams{WorkspaceID: wsUUID, Ids: commentIDs}); err != nil {
+ return err
+ }
+ }
+ if len(projectIDs) > 0 {
+ if projects, err = q.ListSearchIndexProjectsByIDs(ctx, db.ListSearchIndexProjectsByIDsParams{WorkspaceID: wsUUID, Ids: projectIDs}); err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == "22P02" {
+ // A syntactically valid snapshot the server still rejects, e.g.
+ // xmin greater than xmax.
+ writeError(w, http.StatusBadRequest, "invalid cursor")
+ return
+ }
+ h.writeSearchIndexError(w, r, "changes", err)
+ return
+ }
+ if pruned {
+ writeError(w, http.StatusGone, "search index cursor expired; rebuild the local index")
+ return
+ }
+
+ resp := SearchIndexChangesResponse{
+ Issues: h.searchIndexIssues(ctx, wsUUID, issues),
+ Comments: []SearchIndexComment{},
+ Projects: searchIndexProjects(projects),
+ Deleted: SearchIndexDeleted{
+ Issues: []string{},
+ Comments: []string{},
+ Projects: []string{},
+ },
+ }
+ liveIssues := make(map[pgtype.UUID]bool, len(issues))
+ for _, is := range issues {
+ liveIssues[is.ID] = true
+ }
+ liveProjects := make(map[pgtype.UUID]bool, len(projects))
+ for _, p := range projects {
+ liveProjects[p.ID] = true
+ }
+ liveComments := make(map[pgtype.UUID]bool, len(comments))
+ for _, c := range comments {
+ if c.DeletedAt.Valid {
+ continue
+ }
+ liveComments[c.ID] = true
+ resp.Comments = append(resp.Comments, searchIndexComment(c.ID, c.IssueID, c.Content, c.CreatedAt))
+ }
+ for _, c := range changes {
+ switch c.EntityType {
+ case "issue":
+ if !liveIssues[c.EntityID] {
+ resp.Deleted.Issues = append(resp.Deleted.Issues, uuidToString(c.EntityID))
+ }
+ case "comment":
+ if !liveComments[c.EntityID] {
+ resp.Deleted.Comments = append(resp.Deleted.Comments, uuidToString(c.EntityID))
+ }
+ case "project":
+ if !liveProjects[c.EntityID] {
+ resp.Deleted.Projects = append(resp.Deleted.Projects, uuidToString(c.EntityID))
+ }
+ }
+ }
+
+ if n := len(changes); n == limit {
+ // A full page may have more behind it. Keep the target snapshot fixed
+ // until the keyset runs dry, then promote it to the next Since.
+ last := changes[n-1]
+ resp.HasMore = true
+ resp.Cursor = encodeSearchIndexCursor(searchIndexCursor{
+ Since: cur.Since,
+ Target: target,
+ AfterXid: last.ChangeXid,
+ AfterType: last.EntityType,
+ AfterID: uuidToString(last.EntityID),
+ })
+ } else {
+ resp.Cursor = encodeSearchIndexCursor(searchIndexCursor{Since: target})
+ }
+ writeJSON(w, http.StatusOK, resp)
+}
+
+func (h *Handler) searchIndexIssues(ctx context.Context, wsUUID pgtype.UUID, issues []db.Issue) []SearchIndexIssue {
+ out := make([]SearchIndexIssue, 0, len(issues))
+ if len(issues) == 0 {
+ return out
+ }
+ prefix := h.getIssuePrefix(ctx, wsUUID)
+ var originals []pgtype.UUID
+ for _, is := range issues {
+ originals = appendDuplicateOriginal(originals, is.Status, is.DuplicateOfIssueID)
+ }
+ fill := h.newStatusCategoryFiller(ctx, wsUUID, originals...)
+ for _, is := range issues {
+ resp := issueToResponse(is, prefix)
+ fill(&resp)
+ out = append(out, SearchIndexIssue{
+ IssueResponse: resp,
+ SearchUpdatedAt: is.UpdatedAt.Time.UTC().Format(time.RFC3339Nano),
+ })
+ }
+ return out
+}
+
+func searchIndexProjects(projects []db.Project) []SearchIndexProject {
+ out := make([]SearchIndexProject, 0, len(projects))
+ for _, p := range projects {
+ out = append(out, SearchIndexProject{
+ ProjectResponse: projectToResponse(p),
+ SearchUpdatedAt: p.UpdatedAt.Time.UTC().Format(time.RFC3339Nano),
+ })
+ }
+ return out
+}
+
+func searchIndexComment(id, issueID pgtype.UUID, content string, createdAt pgtype.Timestamptz) SearchIndexComment {
+ return SearchIndexComment{
+ ID: uuidToString(id),
+ IssueID: uuidToString(issueID),
+ Content: content,
+ CreatedAt: createdAt.Time.UTC().Format(time.RFC3339Nano),
+ }
+}
diff --git a/server/internal/handler/search_index_test.go b/server/internal/handler/search_index_test.go
new file mode 100644
index 0000000000..9041c69b18
--- /dev/null
+++ b/server/internal/handler/search_index_test.go
@@ -0,0 +1,395 @@
+package handler
+
+import (
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "sort"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+// searchIndexWorkspace creates an isolated workspace so manifest and snapshot
+// totals are not affected by rows other tests leave in the shared workspace.
+func searchIndexWorkspace(t *testing.T, prefix string) string {
+ t.Helper()
+ token := fmt.Sprintf("%d", time.Now().UnixNano())
+ wsID := dbfx.Workspace(t, "Search index "+token, "search-index-"+token, testutil.Cols{"issue_prefix": prefix})
+ // Registered before any fixture row, so it runs after their cleanups and
+ // also removes the change rows those deletes log.
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM search_index_change WHERE workspace_id = $1`, wsID)
+ })
+ return wsID
+}
+
+func searchIndexRequest(method, path, wsID string, body any) *http.Request {
+ req := newRequest(method, path, body)
+ req.Header.Set("X-Workspace-ID", wsID)
+ return req
+}
+
+func searchIndexManifest(t *testing.T, wsID string) SearchIndexManifestResponse {
+ t.Helper()
+ return testutil.Decode[SearchIndexManifestResponse](t, testHandler.GetSearchIndexManifest,
+ searchIndexRequest(http.MethodGet, "/api/search-index/manifest", wsID, nil), http.StatusOK)
+}
+
+func searchIndexChanges(t *testing.T, wsID, cursor string, limit int) SearchIndexChangesResponse {
+ t.Helper()
+ return testutil.Decode[SearchIndexChangesResponse](t, testHandler.ListSearchIndexChanges,
+ searchIndexRequest(http.MethodPost, "/api/search-index/changes", wsID, map[string]any{"cursor": cursor, "limit": limit}),
+ http.StatusOK)
+}
+
+func issueIDs(issues []SearchIndexIssue) []string {
+ out := make([]string, 0, len(issues))
+ for _, is := range issues {
+ out = append(out, is.ID)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func commentIDs(comments []SearchIndexComment) []string {
+ out := make([]string, 0, len(comments))
+ for _, c := range comments {
+ out = append(out, c.ID)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func sortedIDs(ids ...string) []string {
+ out := append([]string(nil), ids...)
+ sort.Strings(out)
+ return out
+}
+
+func assertIDs(t *testing.T, label string, got, want []string) {
+ t.Helper()
+ if fmt.Sprint(got) != fmt.Sprint(sortedIDs(want...)) {
+ t.Fatalf("%s = %v, want %v", label, got, sortedIDs(want...))
+ }
+}
+
+func TestSearchIndexBootstrapThenCatchUp(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ wsID := searchIndexWorkspace(t, "SIX")
+ first := dbfx.Issue(t, "First indexed issue", testutil.Cols{"workspace_id": wsID, "description": "alpha body"})
+ second := dbfx.Issue(t, "Second indexed issue", testutil.Cols{"workspace_id": wsID, "description": nil})
+ liveComment := dbfx.Comment(t, first, "first comment", testutil.Cols{"workspace_id": wsID})
+ editedComment := dbfx.Comment(t, first, "comment to edit", testutil.Cols{"workspace_id": wsID})
+ dbfx.Comment(t, first, "", testutil.Cols{"workspace_id": wsID, "deleted_at": time.Now()})
+ project := dbfx.Project(t, "Indexed project", testutil.Cols{"workspace_id": wsID, "description": "project body"})
+
+ manifest := searchIndexManifest(t, wsID)
+ if manifest.IssueCount != 2 || manifest.CommentCount != 2 || manifest.ProjectCount != 1 {
+ t.Fatalf("manifest counts = %+v, want 2 issues, 2 live comments, 1 project", manifest)
+ }
+ wantBytes := int64(len("First indexed issue") + len("alpha body") + len("Second indexed issue") +
+ len("first comment") + len("comment to edit") + len("Indexed project") + len("project body"))
+ if manifest.TextBytes != wantBytes {
+ t.Fatalf("manifest text_bytes = %d, want %d", manifest.TextBytes, wantBytes)
+ }
+
+ page := testutil.Decode[SearchIndexSnapshotResponse](t, testHandler.GetSearchIndexSnapshot,
+ searchIndexRequest(http.MethodGet, "/api/search-index/snapshot?limit=1", wsID, nil), http.StatusOK)
+ assertIDs(t, "first page issues", issueIDs(page.Issues), []string{first})
+ assertIDs(t, "first page comments", commentIDs(page.Comments), []string{liveComment, editedComment})
+ if len(page.Projects) != 1 || page.Projects[0].ID != project {
+ t.Fatalf("first page projects = %+v, want %s", page.Projects, project)
+ }
+ if page.Done || page.NextAfterNumber != 1 {
+ t.Fatalf("first page done=%v next=%d, want more after number 1", page.Done, page.NextAfterNumber)
+ }
+ if page.Issues[0].Identifier != "SIX-1" || page.Issues[0].SearchUpdatedAt == "" {
+ t.Fatalf("issue record = %+v, want identifier SIX-1 and a precise updated_at", page.Issues[0])
+ }
+
+ page = testutil.Decode[SearchIndexSnapshotResponse](t, testHandler.GetSearchIndexSnapshot,
+ searchIndexRequest(http.MethodGet, "/api/search-index/snapshot?after_number=1&limit=1", wsID, nil), http.StatusOK)
+ assertIDs(t, "second page issues", issueIDs(page.Issues), []string{second})
+ if len(page.Projects) != 0 {
+ t.Fatalf("projects belong to the first page only, got %d", len(page.Projects))
+ }
+ page = testutil.Decode[SearchIndexSnapshotResponse](t, testHandler.GetSearchIndexSnapshot,
+ searchIndexRequest(http.MethodGet, "/api/search-index/snapshot?after_number=2&limit=1", wsID, nil), http.StatusOK)
+ if !page.Done || len(page.Issues) != 0 {
+ t.Fatalf("last page = %+v, want done with no issues", page)
+ }
+
+ // Nothing was written after the manifest snapshot.
+ quiet := searchIndexChanges(t, wsID, manifest.Cursor, 100)
+ if len(quiet.Issues)+len(quiet.Comments)+len(quiet.Projects)+len(quiet.Deleted.Issues)+len(quiet.Deleted.Comments) != 0 || quiet.HasMore {
+ t.Fatalf("changes right after the manifest = %+v, want none", quiet)
+ }
+
+ dbfx.Exec(t, `UPDATE issue SET title = 'First indexed issue renamed' WHERE id = $1`, first)
+ dbfx.Exec(t, `UPDATE comment SET content = 'comment edited' WHERE id = $1`, editedComment)
+ dbfx.Exec(t, `UPDATE comment SET content = '', deleted_at = now() WHERE id = $1`, liveComment)
+ laterComment := dbfx.Comment(t, second, "comment on a doomed issue", testutil.Cols{"workspace_id": wsID})
+ dbfx.Exec(t, `DELETE FROM issue WHERE id = $1`, second)
+ third := dbfx.Issue(t, "Third indexed issue", testutil.Cols{"workspace_id": wsID})
+ dbfx.Exec(t, `UPDATE project SET title = 'Indexed project renamed' WHERE id = $1`, project)
+
+ changes := searchIndexChanges(t, wsID, quiet.Cursor, 100)
+ assertIDs(t, "upserted issues", issueIDs(changes.Issues), []string{first, third})
+ assertIDs(t, "upserted comments", commentIDs(changes.Comments), []string{editedComment})
+ assertIDs(t, "deleted issues", sortedIDs(changes.Deleted.Issues...), []string{second})
+ // The tombstone and the comment cascaded away with its issue both count as deleted.
+ assertIDs(t, "deleted comments", sortedIDs(changes.Deleted.Comments...), []string{liveComment, laterComment})
+ if len(changes.Projects) != 1 || changes.Projects[0].Title != "Indexed project renamed" {
+ t.Fatalf("upserted projects = %+v, want the renamed project", changes.Projects)
+ }
+ for _, is := range changes.Issues {
+ if is.ID == first && is.Title != "First indexed issue renamed" {
+ t.Fatalf("upserted issue carries stale title %q", is.Title)
+ }
+ }
+
+ settled := searchIndexChanges(t, wsID, changes.Cursor, 100)
+ if len(settled.Issues)+len(settled.Comments)+len(settled.Deleted.Issues)+len(settled.Deleted.Comments) != 0 {
+ t.Fatalf("second catch-up = %+v, want nothing new", settled)
+ }
+}
+
+func TestSearchIndexChangesPagesThroughKeyset(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ wsID := searchIndexWorkspace(t, "SIP")
+ issue := dbfx.Issue(t, "Paged issue", testutil.Cols{"workspace_id": wsID})
+ cursor := searchIndexManifest(t, wsID).Cursor
+
+ var want []string
+ for i := 0; i < 5; i++ {
+ want = append(want, dbfx.Comment(t, issue, fmt.Sprintf("paged comment %d", i), testutil.Cols{"workspace_id": wsID}))
+ }
+
+ seen := map[string]int{}
+ for pages := 0; ; pages++ {
+ if pages > 5 {
+ t.Fatal("catch-up did not terminate")
+ }
+ resp := searchIndexChanges(t, wsID, cursor, 2)
+ for _, c := range resp.Comments {
+ seen[c.ID]++
+ }
+ cursor = resp.Cursor
+ if !resp.HasMore {
+ break
+ }
+ }
+ for _, id := range want {
+ if seen[id] != 1 {
+ t.Fatalf("comment %s delivered %d times across pages, want once (seen=%v)", id, seen[id], seen)
+ }
+ }
+}
+
+func TestSearchIndexChangesScopeToWorkspace(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ wsID := searchIndexWorkspace(t, "SIA")
+ otherWS := searchIndexWorkspace(t, "SIB")
+ cursor := searchIndexManifest(t, wsID).Cursor
+ dbfx.Issue(t, "Other workspace issue", testutil.Cols{"workspace_id": otherWS})
+
+ resp := searchIndexChanges(t, wsID, cursor, 100)
+ if len(resp.Issues) != 0 || len(resp.Deleted.Issues) != 0 {
+ t.Fatalf("changes leaked another workspace: %+v", resp)
+ }
+}
+
+// A writer that took its xid before the reader's snapshot but committed after
+// it must still be delivered by the next catch-up. A watermark such as
+// updated_at or the snapshot xmin alone would skip or stall on it.
+func TestSearchIndexChangesDeliverLateCommits(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ wsID := searchIndexWorkspace(t, "SIL")
+ issue := dbfx.Issue(t, "Late commit issue", testutil.Cols{"workspace_id": wsID})
+ cursor := searchIndexManifest(t, wsID).Cursor
+
+ slow, err := testPool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin slow writer: %v", err)
+ }
+ defer slow.Rollback(ctx)
+ var lateID string
+ if err := slow.QueryRow(ctx, `
+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type)
+ VALUES ($1, $2, 'member', $3, 'late comment', 'comment') RETURNING id
+ `, issue, wsID, testUserID).Scan(&lateID); err != nil {
+ t.Fatalf("insert late comment: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM comment WHERE id = $1`, lateID) })
+ early := dbfx.Comment(t, issue, "early comment", testutil.Cols{"workspace_id": wsID})
+
+ first := searchIndexChanges(t, wsID, cursor, 100)
+ assertIDs(t, "comments before the slow commit", commentIDs(first.Comments), []string{early})
+
+ if err := slow.Commit(ctx); err != nil {
+ t.Fatalf("commit slow writer: %v", err)
+ }
+ second := searchIndexChanges(t, wsID, first.Cursor, 100)
+ assertIDs(t, "comments after the slow commit", commentIDs(second.Comments), []string{lateID})
+}
+
+func TestSearchIndexChangesExpireAfterPruning(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ wsID := searchIndexWorkspace(t, "SIE")
+ cursor := searchIndexManifest(t, wsID).Cursor
+
+ var previous *string
+ _ = testPool.QueryRow(ctx, `SELECT pruned_through_xid::text FROM search_index_prune_mark`).Scan(&previous)
+ t.Cleanup(func() {
+ if previous == nil {
+ testPool.Exec(context.Background(), `DELETE FROM search_index_prune_mark`)
+ return
+ }
+ testPool.Exec(context.Background(), `UPDATE search_index_prune_mark SET pruned_through_xid = $1::xid8`, *previous)
+ })
+ dbfx.Exec(t, `
+ INSERT INTO search_index_prune_mark (singleton, pruned_through_xid)
+ VALUES (TRUE, pg_current_xact_id())
+ ON CONFLICT (singleton) DO UPDATE SET pruned_through_xid = EXCLUDED.pruned_through_xid
+ `)
+
+ testutil.Call(t, testHandler.ListSearchIndexChanges,
+ searchIndexRequest(http.MethodPost, "/api/search-index/changes", wsID, map[string]any{"cursor": cursor})).
+ Want(http.StatusGone)
+}
+
+func TestSearchIndexChangesRejectInvalidCursors(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ encode := func(v any) string {
+ raw, _ := json.Marshal(v)
+ return base64.RawURLEncoding.EncodeToString(raw)
+ }
+ for name, cursor := range map[string]string{
+ "not base64": "%%%",
+ "wrong version": encode(map[string]any{"v": 9, "s": "1:1:"}),
+ "malformed since": encode(map[string]any{"v": 1, "s": "1;DROP TABLE"}),
+ "xmin above xmax": encode(map[string]any{"v": 1, "s": "9:3:"}),
+ "zero xmin": encode(map[string]any{"v": 1, "s": "0:3:"}),
+ "xip below xmin": encode(map[string]any{"v": 1, "s": "3:9:1"}),
+ "unsorted xips": encode(map[string]any{"v": 1, "s": "3:9:5,4"}),
+ "partial keyset": encode(map[string]any{"v": 1, "s": "1:1:", "x": "5"}),
+ "bad keyset type": encode(map[string]any{"v": 1, "s": "1:1:", "t": "1:2:", "x": "1", "e": "user", "i": "00000000-0000-0000-0000-000000000000"}),
+ "missing keyset id": encode(map[string]any{"v": 1, "s": "1:1:", "t": "1:2:", "x": "1", "e": "issue"}),
+ } {
+ t.Run(name, func(t *testing.T) {
+ testutil.Call(t, testHandler.ListSearchIndexChanges,
+ newRequest(http.MethodPost, "/api/search-index/changes", map[string]any{"cursor": cursor})).
+ Want(http.StatusBadRequest)
+ })
+ }
+}
+
+func TestSearchIndexTriggersIgnoreUnsearchableCommentUpdates(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ wsID := searchIndexWorkspace(t, "SIR")
+ issue := dbfx.Issue(t, "Revision issue", testutil.Cols{"workspace_id": wsID})
+ comment := dbfx.Comment(t, issue, "revised", testutil.Cols{"workspace_id": wsID})
+ cursor := searchIndexManifest(t, wsID).Cursor
+
+ dbfx.Exec(t, `UPDATE comment SET revision = revision + 1 WHERE id = $1`, comment)
+ resp := searchIndexChanges(t, wsID, cursor, 100)
+ if len(resp.Comments) != 0 {
+ t.Fatalf("a revision bump changes nothing searchable, got %+v", resp.Comments)
+ }
+}
+
+func TestDeleteWorkspace_ClearsSearchIndexChanges(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ const slug = "handler-tests-delete-search-index"
+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)
+ var wsID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO workspace (name, slug, description) VALUES ('Search Index Teardown', $1, '') RETURNING id
+ `, slug).Scan(&wsID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM search_index_change WHERE workspace_id = $1`, wsID)
+ testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, wsID)
+ })
+ if _, err := testPool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, wsID, testUserID); err != nil {
+ t.Fatalf("create owner member: %v", err)
+ }
+ issue := dbfx.Issue(t, "Teardown issue", testutil.Cols{"workspace_id": wsID})
+ dbfx.Comment(t, issue, "teardown comment", testutil.Cols{"workspace_id": wsID})
+ if n := dbfx.Count(t, `SELECT count(*) FROM search_index_change WHERE workspace_id = $1`, wsID); n == 0 {
+ t.Fatal("writes should have logged search index changes")
+ }
+
+ w := httptest.NewRecorder()
+ testHandler.DeleteWorkspace(w, withURLParam(newRequest(http.MethodDelete, "/api/workspaces/"+wsID, nil), "id", wsID))
+ if w.Code != http.StatusNoContent {
+ t.Fatalf("DeleteWorkspace: expected 204, got %d: %s", w.Code, w.Body.String())
+ }
+ if n := dbfx.Count(t, `SELECT count(*) FROM search_index_change WHERE workspace_id = $1`, wsID); n != 0 {
+ t.Fatalf("workspace teardown left %d search index change rows", n)
+ }
+}
+
+func TestRequireLocalSearchIndexHonorsKillSwitch(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ guarded := testHandler.RequireLocalSearchIndex(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+
+ testutil.Call(t, guarded.ServeHTTP, newRequest(http.MethodGet, "/api/search-index/manifest", nil)).Want(http.StatusOK)
+
+ withFeatureFlag(t, testHandler, featureflags.LocalSearchIndex, false)
+ testutil.Call(t, guarded.ServeHTTP, newRequest(http.MethodGet, "/api/search-index/manifest", nil)).Want(http.StatusNotFound)
+}
+
+func TestSearchIndexBootstrapReadsShedLoadWhenSaturated(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ wsID := searchIndexWorkspace(t, "SIS")
+ // Occupy every slot, as a fleet of clients bootstrapping at once would.
+ for i := 0; i < cap(searchIndexBootstrapSlots); i++ {
+ searchIndexBootstrapSlots <- struct{}{}
+ }
+ t.Cleanup(func() {
+ for i := 0; i < cap(searchIndexBootstrapSlots); i++ {
+ <-searchIndexBootstrapSlots
+ }
+ })
+
+ resp := testutil.Call(t, testHandler.GetSearchIndexManifest,
+ searchIndexRequest(http.MethodGet, "/api/search-index/manifest", wsID, nil)).Want(http.StatusServiceUnavailable)
+ if resp.Header().Get("Retry-After") == "" {
+ t.Fatal("a shed request must tell the client when to retry")
+ }
+ testutil.Call(t, testHandler.GetSearchIndexSnapshot,
+ searchIndexRequest(http.MethodGet, "/api/search-index/snapshot", wsID, nil)).Want(http.StatusServiceUnavailable)
+}
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index d0a685d58c..425658cc80 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -1251,6 +1251,12 @@ func (h *Handler) DeleteWorkspace(w http.ResponseWriter, r *http.Request) {
name: "delete comments",
run: func() error { return qtx.DeleteWorkspaceComments(ctx, requester.WorkspaceID) },
},
+ {
+ // Teardown mode keeps the triggers from logging the deletes above
+ // and below; this clears what normal writes logged before.
+ name: "delete search index changes",
+ run: func() error { return qtx.DeleteWorkspaceSearchIndexChanges(ctx, requester.WorkspaceID) },
+ },
// Keep source-context object intents after the workspace row is gone.
// They are the durable retry ledger for an upload that began before the
// workspace lock but completed after this transaction's immediate object
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 75049d9488..584c7d0887 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -116,6 +116,8 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"quick_action": workspaceDelete,
"runtime_profile": workspaceDelete,
"schema_migrations": workspaceDeleteKeep,
+ "search_index_change": workspaceDelete,
+ "search_index_prune_mark": workspaceDeleteKeep,
"seat_capacity_outbox": workspaceDeleteSettle,
"skill": workspaceDelete,
"skill_file": workspaceDelete,
diff --git a/server/internal/scheduler/jobs_search_index.go b/server/internal/scheduler/jobs_search_index.go
new file mode 100644
index 0000000000..9602524468
--- /dev/null
+++ b/server/internal/scheduler/jobs_search_index.go
@@ -0,0 +1,76 @@
+package scheduler
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// JobNamePruneSearchIndexChanges is the canonical name used in audit rows.
+// Stable across releases — do not rename without a migration.
+const JobNamePruneSearchIndexChanges = "prune_search_index_changes"
+
+const (
+ // SearchIndexChangeRetention bounds how long a local search index can stay
+ // offline and still catch up; an older client rebuilds its copy (the changes
+ // endpoint answers 410 once pruning passes its snapshot).
+ SearchIndexChangeRetention = 30 * 24 * time.Hour
+
+ searchIndexPruneBatchSize = 5000
+ // Caps one run at 1M rows so a backlog drains over several ticks instead of
+ // one unbounded run.
+ searchIndexPruneMaxBatches = 200
+)
+
+// SearchIndexChangePruneJob drops search_index_change rows older than the
+// retention window (MUL-7754). Rows are one per entity, so the table would
+// otherwise grow with every issue, comment, and project ever written.
+func SearchIndexChangePruneJob(queries *db.Queries) JobSpec {
+ return JobSpec{
+ Name: JobNamePruneSearchIndexChanges,
+ Cadence: time.Hour,
+ CatchUpMode: CatchUpLatestOnly,
+ CatchUpWindow: 24 * time.Hour,
+ RunTimeout: 10 * time.Minute,
+ StaleTimeout: 15 * time.Minute,
+ HeartbeatInterval: 30 * time.Second,
+ AllowStaleReentry: true,
+ MaxAttempts: 3,
+ RetryBackoff: []time.Duration{time.Minute, 5 * time.Minute},
+ Scopes: StaticScopes(ScopeGlobal),
+ Handler: makeSearchIndexChangePruneHandler(queries),
+ }
+}
+
+func makeSearchIndexChangePruneHandler(queries *db.Queries) Handler {
+ return func(ctx context.Context, in HandlerInput) (HandlerResult, error) {
+ cutoff := in.PlanTime.Add(-SearchIndexChangeRetention)
+ var total int64
+ for batch := 0; batch < searchIndexPruneMaxBatches; batch++ {
+ deleted, err := queries.PruneSearchIndexChanges(ctx, db.PruneSearchIndexChangesParams{
+ Cutoff: pgtype.Timestamptz{Time: cutoff, Valid: true},
+ BatchSize: searchIndexPruneBatchSize,
+ })
+ if err != nil {
+ return HandlerResult{RowsAffected: total}, fmt.Errorf("prune search index changes: %w", err)
+ }
+ total += deleted
+ if deleted < searchIndexPruneBatchSize {
+ break
+ }
+ if in.Heartbeat != nil {
+ if err := in.Heartbeat(ctx); err != nil {
+ return HandlerResult{RowsAffected: total}, err
+ }
+ }
+ }
+ return HandlerResult{
+ RowsAffected: total,
+ Result: map[string]any{"cutoff": cutoff.UTC().Format(time.RFC3339)},
+ }, nil
+ }
+}
diff --git a/server/internal/scheduler/jobs_search_index_test.go b/server/internal/scheduler/jobs_search_index_test.go
new file mode 100644
index 0000000000..790021e02e
--- /dev/null
+++ b/server/internal/scheduler/jobs_search_index_test.go
@@ -0,0 +1,82 @@
+package scheduler
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestSearchIndexChangePruneJobRemovesExpiredRowsAndRaisesMark(t *testing.T) {
+ pool := integrationPool(t)
+ ctx := context.Background()
+
+ var previousMark *string
+ _ = pool.QueryRow(ctx, `SELECT pruned_through_xid::text FROM search_index_prune_mark`).Scan(&previousMark)
+ t.Cleanup(func() {
+ if previousMark == nil {
+ pool.Exec(context.Background(), `DELETE FROM search_index_prune_mark`)
+ return
+ }
+ pool.Exec(context.Background(), `UPDATE search_index_prune_mark SET pruned_through_xid = $1::xid8`, *previousMark)
+ })
+
+ workspaceID := uuid.New()
+ expiredID, freshID := uuid.New(), uuid.New()
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM search_index_change WHERE workspace_id = $1`, workspaceID)
+ })
+ planTime := time.Now().UTC().Truncate(time.Hour)
+ var expiredXid string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)
+ VALUES ('comment', $1, $2, pg_current_xact_id(), $3)
+ RETURNING change_xid::text
+ `, expiredID, workspaceID, planTime.Add(-SearchIndexChangeRetention-time.Hour)).Scan(&expiredXid); err != nil {
+ t.Fatalf("insert expired change: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)
+ VALUES ('comment', $1, $2, pg_current_xact_id(), $3)
+ `, freshID, workspaceID, planTime.Add(-time.Hour)); err != nil {
+ t.Fatalf("insert fresh change: %v", err)
+ }
+
+ job := SearchIndexChangePruneJob(db.New(pool))
+ result, err := job.Handler(ctx, HandlerInput{Job: &job, Scope: ScopeGlobal, PlanTime: planTime})
+ if err != nil {
+ t.Fatalf("prune: %v", err)
+ }
+ if result.RowsAffected < 1 {
+ t.Fatalf("prune removed %d rows, want at least the expired one", result.RowsAffected)
+ }
+
+ var remaining []uuid.UUID
+ rows, err := pool.Query(ctx, `SELECT entity_id FROM search_index_change WHERE workspace_id = $1`, workspaceID)
+ if err != nil {
+ t.Fatalf("list remaining: %v", err)
+ }
+ for rows.Next() {
+ var id uuid.UUID
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan remaining: %v", err)
+ }
+ remaining = append(remaining, id)
+ }
+ if len(remaining) != 1 || remaining[0] != freshID {
+ t.Fatalf("remaining = %v, want only the fresh row %s", remaining, freshID)
+ }
+
+ var covered bool
+ if err := pool.QueryRow(ctx, `
+ SELECT pruned_through_xid >= $1::xid8 FROM search_index_prune_mark WHERE singleton
+ `, expiredXid).Scan(&covered); err != nil {
+ t.Fatalf("read prune mark: %v", err)
+ }
+ if !covered {
+ t.Fatalf("prune mark must cover the pruned xid %s", expiredXid)
+ }
+}
diff --git a/server/migrations/561_search_index_change.down.sql b/server/migrations/561_search_index_change.down.sql
new file mode 100644
index 0000000000..428624364c
--- /dev/null
+++ b/server/migrations/561_search_index_change.down.sql
@@ -0,0 +1,10 @@
+SET LOCAL lock_timeout = '2s';
+SET LOCAL statement_timeout = '10s';
+
+DROP TRIGGER IF EXISTS trg_project_search_index_change ON project;
+DROP TRIGGER IF EXISTS trg_comment_update_search_index_change ON comment;
+DROP TRIGGER IF EXISTS trg_comment_search_index_change ON comment;
+DROP TRIGGER IF EXISTS trg_issue_search_index_change ON issue;
+DROP FUNCTION IF EXISTS record_search_index_change();
+DROP TABLE IF EXISTS search_index_prune_mark;
+DROP TABLE IF EXISTS search_index_change;
diff --git a/server/migrations/561_search_index_change.up.sql b/server/migrations/561_search_index_change.up.sql
new file mode 100644
index 0000000000..079b1bcee5
--- /dev/null
+++ b/server/migrations/561_search_index_change.up.sql
@@ -0,0 +1,95 @@
+-- Local search index change log (MUL-7754).
+--
+-- Web and Desktop keep a per-workspace copy of issue, comment, and project text
+-- for instant search. Clients catch up by asking which entities changed since
+-- the database snapshot they last synced to. `updated_at` cannot answer that:
+-- issues and comments are hard-deleted (including cascaded comment deletes), and
+-- a timestamp is assigned before commit, so a late-committing writer would be
+-- skipped. Triggers record one row per entity with the xid of its latest write;
+-- readers compare that xid against pg_snapshot values, which is exact under any
+-- commit order. This is the same trigger-populated dirty-key shape as migration
+-- 077, and it covers every write path (API, CLI, daemon, agents) at once.
+--
+-- One row per entity keeps the table bounded: later writes overwrite the xid.
+-- Rows carry no content; readers join to the live tables, so a missing row (or
+-- a tombstoned comment) means "deleted". No foreign keys: workspace deletion
+-- sweeps this table explicitly and skips the triggers via the teardown flag.
+--
+-- The runner sends this file as one implicit transaction. CREATE TRIGGER takes a
+-- short SHARE ROW EXCLUSIVE lock on issue/comment/project, so bound the wait and
+-- retry on the next start rather than queue writers behind it.
+SET LOCAL lock_timeout = '2s';
+SET LOCAL statement_timeout = '10s';
+
+CREATE TABLE IF NOT EXISTS search_index_change (
+ entity_type TEXT NOT NULL CHECK (entity_type IN ('issue', 'comment', 'project')),
+ entity_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ change_xid xid8 NOT NULL,
+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ PRIMARY KEY (entity_type, entity_id)
+);
+
+-- Highest xid removed by retention pruning. A client whose snapshot could still
+-- be missing a pruned change must rebuild its copy instead of catching up.
+CREATE TABLE IF NOT EXISTS search_index_prune_mark (
+ singleton BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK (singleton),
+ pruned_through_xid xid8 NOT NULL
+);
+
+-- Keep this function trivial: it runs inside every issue/comment/project write,
+-- so an error here would fail the user's write. All inputs are NOT NULL columns.
+CREATE OR REPLACE FUNCTION record_search_index_change()
+RETURNS TRIGGER LANGUAGE plpgsql AS $function$
+DECLARE
+ changed_id UUID;
+ changed_workspace_id UUID;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ changed_id := OLD.id;
+ changed_workspace_id := OLD.workspace_id;
+ ELSE
+ changed_id := NEW.id;
+ changed_workspace_id := NEW.workspace_id;
+ END IF;
+
+ INSERT INTO search_index_change (entity_type, entity_id, workspace_id, change_xid, changed_at)
+ VALUES (TG_ARGV[0], changed_id, changed_workspace_id, pg_current_xact_id(), now())
+ ON CONFLICT (entity_type, entity_id) DO UPDATE
+ SET workspace_id = EXCLUDED.workspace_id,
+ change_xid = EXCLUDED.change_xid,
+ changed_at = EXCLUDED.changed_at;
+ RETURN NULL;
+END
+$function$;
+
+-- Every issue column is part of the indexed search result, so any update counts.
+DROP TRIGGER IF EXISTS trg_issue_search_index_change ON issue;
+CREATE TRIGGER trg_issue_search_index_change
+AFTER INSERT OR UPDATE OR DELETE ON issue
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION record_search_index_change('issue');
+
+-- Comments only contribute their text and placement; resolve/revision bumps do
+-- not change what search can match.
+DROP TRIGGER IF EXISTS trg_comment_search_index_change ON comment;
+CREATE TRIGGER trg_comment_search_index_change
+AFTER INSERT OR DELETE ON comment
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION record_search_index_change('comment');
+
+DROP TRIGGER IF EXISTS trg_comment_update_search_index_change ON comment;
+CREATE TRIGGER trg_comment_update_search_index_change
+AFTER UPDATE OF content, deleted_at, issue_id, created_at ON comment
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION record_search_index_change('comment');
+
+DROP TRIGGER IF EXISTS trg_project_search_index_change ON project;
+CREATE TRIGGER trg_project_search_index_change
+AFTER INSERT OR UPDATE OR DELETE ON project
+FOR EACH ROW
+WHEN (current_setting('multica.workspace_teardown', true) IS DISTINCT FROM 'on')
+EXECUTE FUNCTION record_search_index_change('project');
diff --git a/server/migrations/562_search_index_change_workspace_index.down.sql b/server/migrations/562_search_index_change_workspace_index.down.sql
new file mode 100644
index 0000000000..0621808fbf
--- /dev/null
+++ b/server/migrations/562_search_index_change_workspace_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_search_index_change_workspace_xid;
diff --git a/server/migrations/562_search_index_change_workspace_index.up.sql b/server/migrations/562_search_index_change_workspace_index.up.sql
new file mode 100644
index 0000000000..20b8c00ec0
--- /dev/null
+++ b/server/migrations/562_search_index_change_workspace_index.up.sql
@@ -0,0 +1,4 @@
+-- Serves the catch-up read: one workspace, an xid range, ordered by the keyset
+-- (change_xid, entity_type, entity_id) the client pages through.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_search_index_change_workspace_xid
+ ON search_index_change (workspace_id, change_xid, entity_type, entity_id);
diff --git a/server/migrations/563_search_index_change_changed_at_index.down.sql b/server/migrations/563_search_index_change_changed_at_index.down.sql
new file mode 100644
index 0000000000..4337c952f6
--- /dev/null
+++ b/server/migrations/563_search_index_change_changed_at_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_search_index_change_changed_at;
diff --git a/server/migrations/563_search_index_change_changed_at_index.up.sql b/server/migrations/563_search_index_change_changed_at_index.up.sql
new file mode 100644
index 0000000000..35e409dff6
--- /dev/null
+++ b/server/migrations/563_search_index_change_changed_at_index.up.sql
@@ -0,0 +1,3 @@
+-- Serves retention pruning, which deletes the oldest rows in bounded batches.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_search_index_change_changed_at
+ ON search_index_change (changed_at);
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index d8dd0c6fa6..2cd4893996 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -1361,6 +1361,19 @@ type RuntimeProfile struct {
RuntimeType string `json:"runtime_type"`
}
+type SearchIndexChange struct {
+ EntityType string `json:"entity_type"`
+ EntityID pgtype.UUID `json:"entity_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ChangeXid pgtype.Uint64 `json:"change_xid"`
+ ChangedAt pgtype.Timestamptz `json:"changed_at"`
+}
+
+type SearchIndexPruneMark struct {
+ Singleton bool `json:"singleton"`
+ PrunedThroughXid pgtype.Uint64 `json:"pruned_through_xid"`
+}
+
type SeatCapacityOutbox struct {
WorkspaceID pgtype.UUID `json:"workspace_id"`
OperationToken pgtype.UUID `json:"operation_token"`
diff --git a/server/pkg/db/generated/search_index.sql.go b/server/pkg/db/generated/search_index.sql.go
new file mode 100644
index 0000000000..ac7e999a34
--- /dev/null
+++ b/server/pkg/db/generated/search_index.sql.go
@@ -0,0 +1,501 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: search_index.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const deleteWorkspaceSearchIndexChanges = `-- name: DeleteWorkspaceSearchIndexChanges :exec
+DELETE FROM search_index_change WHERE workspace_id = $1
+`
+
+func (q *Queries) DeleteWorkspaceSearchIndexChanges(ctx context.Context, workspaceID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteWorkspaceSearchIndexChanges, workspaceID)
+ return err
+}
+
+const getSearchIndexCurrentSnapshot = `-- name: GetSearchIndexCurrentSnapshot :one
+SELECT pg_current_snapshot()::text AS snapshot
+`
+
+func (q *Queries) GetSearchIndexCurrentSnapshot(ctx context.Context) (string, error) {
+ row := q.db.QueryRow(ctx, getSearchIndexCurrentSnapshot)
+ var snapshot string
+ err := row.Scan(&snapshot)
+ return snapshot, err
+}
+
+const getSearchIndexManifest = `-- name: GetSearchIndexManifest :one
+
+WITH ws AS (SELECT $1::uuid AS id)
+SELECT
+ pg_current_snapshot()::text AS snapshot,
+ (SELECT count(*) FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_count,
+ (SELECT COALESCE(sum(octet_length(i.title) + COALESCE(octet_length(i.description), 0)), 0)
+ FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_bytes,
+ (SELECT count(*) FROM comment c, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_count,
+ (SELECT COALESCE(sum(octet_length(c.content)), 0) FROM comment c, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_bytes,
+ (SELECT count(*) FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_count,
+ (SELECT COALESCE(sum(octet_length(p.title) + COALESCE(octet_length(p.description), 0)), 0)
+ FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_bytes
+`
+
+type GetSearchIndexManifestRow struct {
+ Snapshot string `json:"snapshot"`
+ IssueCount int64 `json:"issue_count"`
+ IssueBytes int64 `json:"issue_bytes"`
+ CommentCount int64 `json:"comment_count"`
+ CommentBytes int64 `json:"comment_bytes"`
+ ProjectCount int64 `json:"project_count"`
+ ProjectBytes int64 `json:"project_bytes"`
+}
+
+// Local search index sync (MUL-7754). Web and Desktop copy the issue, comment,
+// and project text of a workspace, then catch up through search_index_change.
+// Snapshots are exchanged as pg_snapshot text; see migration 561.
+// Taken before any snapshot page, so every write the pages might miss is newer
+// than this snapshot and reaches the client through the change log. The byte
+// totals let the client reject a workspace too large for its memory budget
+// before downloading it; octet_length reads the stored length, so TOASTed
+// bodies are not decompressed.
+func (q *Queries) GetSearchIndexManifest(ctx context.Context, workspaceID pgtype.UUID) (GetSearchIndexManifestRow, error) {
+ row := q.db.QueryRow(ctx, getSearchIndexManifest, workspaceID)
+ var i GetSearchIndexManifestRow
+ err := row.Scan(
+ &i.Snapshot,
+ &i.IssueCount,
+ &i.IssueBytes,
+ &i.CommentCount,
+ &i.CommentBytes,
+ &i.ProjectCount,
+ &i.ProjectBytes,
+ )
+ return i, err
+}
+
+const listSearchIndexChanges = `-- name: ListSearchIndexChanges :many
+SELECT entity_type, entity_id, change_xid::text AS change_xid
+FROM search_index_change
+WHERE workspace_id = $1
+ AND change_xid >= pg_snapshot_xmin(($2::text)::pg_snapshot)
+ AND change_xid < pg_snapshot_xmax(($3::text)::pg_snapshot)
+ AND NOT pg_visible_in_snapshot(change_xid, ($2::text)::pg_snapshot)
+ AND pg_visible_in_snapshot(change_xid, ($3::text)::pg_snapshot)
+ AND (change_xid, entity_type, entity_id)
+ > (($4::text)::xid8, $5::text, $6::uuid)
+ORDER BY change_xid, entity_type, entity_id
+LIMIT $7
+`
+
+type ListSearchIndexChangesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ SinceSnapshot string `json:"since_snapshot"`
+ TargetSnapshot string `json:"target_snapshot"`
+ AfterXid string `json:"after_xid"`
+ AfterType string `json:"after_type"`
+ AfterID pgtype.UUID `json:"after_id"`
+ PageLimit int32 `json:"page_limit"`
+}
+
+type ListSearchIndexChangesRow struct {
+ EntityType string `json:"entity_type"`
+ EntityID pgtype.UUID `json:"entity_id"`
+ ChangeXid string `json:"change_xid"`
+}
+
+// Changes committed in the target snapshot but not in the since snapshot, in
+// keyset order. An entity rewritten after the target snapshot carries a newer
+// xid, drops out of this range, and is returned by the next catch-up instead.
+func (q *Queries) ListSearchIndexChanges(ctx context.Context, arg ListSearchIndexChangesParams) ([]ListSearchIndexChangesRow, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexChanges,
+ arg.WorkspaceID,
+ arg.SinceSnapshot,
+ arg.TargetSnapshot,
+ arg.AfterXid,
+ arg.AfterType,
+ arg.AfterID,
+ arg.PageLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListSearchIndexChangesRow{}
+ for rows.Next() {
+ var i ListSearchIndexChangesRow
+ if err := rows.Scan(&i.EntityType, &i.EntityID, &i.ChangeXid); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexCommentsByIDs = `-- name: ListSearchIndexCommentsByIDs :many
+SELECT id, issue_id, content, created_at, deleted_at
+FROM comment
+WHERE workspace_id = $1 AND id = ANY($2::uuid[])
+`
+
+type ListSearchIndexCommentsByIDsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ids []pgtype.UUID `json:"ids"`
+}
+
+type ListSearchIndexCommentsByIDsRow struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Content string `json:"content"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ DeletedAt pgtype.Timestamptz `json:"deleted_at"`
+}
+
+// Tombstoned comments are returned so the caller can report them as deleted.
+func (q *Queries) ListSearchIndexCommentsByIDs(ctx context.Context, arg ListSearchIndexCommentsByIDsParams) ([]ListSearchIndexCommentsByIDsRow, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexCommentsByIDs, arg.WorkspaceID, arg.Ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListSearchIndexCommentsByIDsRow{}
+ for rows.Next() {
+ var i ListSearchIndexCommentsByIDsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.IssueID,
+ &i.Content,
+ &i.CreatedAt,
+ &i.DeletedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexCommentsByIssues = `-- name: ListSearchIndexCommentsByIssues :many
+SELECT id, issue_id, content, created_at
+FROM comment
+WHERE workspace_id = $1
+ AND issue_id = ANY($2::uuid[])
+ AND deleted_at IS NULL
+`
+
+type ListSearchIndexCommentsByIssuesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueIds []pgtype.UUID `json:"issue_ids"`
+}
+
+type ListSearchIndexCommentsByIssuesRow struct {
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ Content string `json:"content"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+func (q *Queries) ListSearchIndexCommentsByIssues(ctx context.Context, arg ListSearchIndexCommentsByIssuesParams) ([]ListSearchIndexCommentsByIssuesRow, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexCommentsByIssues, arg.WorkspaceID, arg.IssueIds)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListSearchIndexCommentsByIssuesRow{}
+ for rows.Next() {
+ var i ListSearchIndexCommentsByIssuesRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.IssueID,
+ &i.Content,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexIssuesByIDs = `-- name: ListSearchIndexIssuesByIDs :many
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id FROM issue
+WHERE workspace_id = $1 AND id = ANY($2::uuid[])
+`
+
+type ListSearchIndexIssuesByIDsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ids []pgtype.UUID `json:"ids"`
+}
+
+func (q *Queries) ListSearchIndexIssuesByIDs(ctx context.Context, arg ListSearchIndexIssuesByIDsParams) ([]Issue, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexIssuesByIDs, arg.WorkspaceID, arg.Ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Issue{}
+ for rows.Next() {
+ var i Issue
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ &i.Revision,
+ &i.LastActivityAt,
+ &i.TriageState,
+ &i.DuplicateOfIssueID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexIssuesPage = `-- name: ListSearchIndexIssuesPage :many
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at, start_date, metadata, stage, properties, revision, last_activity_at, triage_state, duplicate_of_issue_id FROM issue
+WHERE workspace_id = $1 AND number > $2
+ORDER BY number
+LIMIT $3
+`
+
+type ListSearchIndexIssuesPageParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ AfterNumber int32 `json:"after_number"`
+ PageLimit int32 `json:"page_limit"`
+}
+
+// Pages by the unique (workspace_id, number) index.
+func (q *Queries) ListSearchIndexIssuesPage(ctx context.Context, arg ListSearchIndexIssuesPageParams) ([]Issue, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexIssuesPage, arg.WorkspaceID, arg.AfterNumber, arg.PageLimit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Issue{}
+ for rows.Next() {
+ var i Issue
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.ProjectID,
+ &i.OriginType,
+ &i.OriginID,
+ &i.FirstExecutedAt,
+ &i.StartDate,
+ &i.Metadata,
+ &i.Stage,
+ &i.Properties,
+ &i.Revision,
+ &i.LastActivityAt,
+ &i.TriageState,
+ &i.DuplicateOfIssueID,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexProjects = `-- name: ListSearchIndexProjects :many
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+WHERE workspace_id = $1
+ORDER BY id
+`
+
+func (q *Queries) ListSearchIndexProjects(ctx context.Context, workspaceID pgtype.UUID) ([]Project, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexProjects, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Project{}
+ for rows.Next() {
+ var i Project
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listSearchIndexProjectsByIDs = `-- name: ListSearchIndexProjectsByIDs :many
+SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date FROM project
+WHERE workspace_id = $1 AND id = ANY($2::uuid[])
+`
+
+type ListSearchIndexProjectsByIDsParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Ids []pgtype.UUID `json:"ids"`
+}
+
+func (q *Queries) ListSearchIndexProjectsByIDs(ctx context.Context, arg ListSearchIndexProjectsByIDsParams) ([]Project, error) {
+ rows, err := q.db.Query(ctx, listSearchIndexProjectsByIDs, arg.WorkspaceID, arg.Ids)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Project{}
+ for rows.Next() {
+ var i Project
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Icon,
+ &i.Status,
+ &i.LeadType,
+ &i.LeadID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Priority,
+ &i.StartDate,
+ &i.DueDate,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const pruneSearchIndexChanges = `-- name: PruneSearchIndexChanges :one
+WITH doomed AS (
+ SELECT sic.entity_type, sic.entity_id
+ FROM search_index_change sic
+ WHERE sic.changed_at < $1
+ ORDER BY sic.changed_at
+ LIMIT $2
+ FOR UPDATE SKIP LOCKED
+), deleted AS (
+ DELETE FROM search_index_change c
+ USING doomed d
+ WHERE c.entity_type = d.entity_type
+ AND c.entity_id = d.entity_id
+ AND c.changed_at < $1
+ RETURNING c.change_xid
+), marked AS (
+ INSERT INTO search_index_prune_mark (singleton, pruned_through_xid)
+ SELECT TRUE, deleted.change_xid FROM deleted ORDER BY deleted.change_xid DESC LIMIT 1
+ ON CONFLICT (singleton) DO UPDATE
+ SET pruned_through_xid = GREATEST(search_index_prune_mark.pruned_through_xid, EXCLUDED.pruned_through_xid)
+ RETURNING 1
+)
+SELECT count(*)::bigint AS deleted_count FROM deleted
+`
+
+type PruneSearchIndexChangesParams struct {
+ Cutoff pgtype.Timestamptz `json:"cutoff"`
+ BatchSize int32 `json:"batch_size"`
+}
+
+// Deletes one bounded batch of rows older than the cutoff and raises the prune
+// mark to the highest xid removed, in the same statement.
+func (q *Queries) PruneSearchIndexChanges(ctx context.Context, arg PruneSearchIndexChangesParams) (int64, error) {
+ row := q.db.QueryRow(ctx, pruneSearchIndexChanges, arg.Cutoff, arg.BatchSize)
+ var deleted_count int64
+ err := row.Scan(&deleted_count)
+ return deleted_count, err
+}
+
+const searchIndexSinceIsPruned = `-- name: SearchIndexSinceIsPruned :one
+SELECT EXISTS (
+ SELECT 1 FROM search_index_prune_mark
+ WHERE singleton
+ AND pruned_through_xid >= pg_snapshot_xmin(($1::text)::pg_snapshot)
+) AS pruned
+`
+
+// True when retention pruning may have removed a change the client has not
+// seen yet: a pruned xid at or above the snapshot's xmin could be one it has
+// not consumed.
+func (q *Queries) SearchIndexSinceIsPruned(ctx context.Context, sinceSnapshot string) (bool, error) {
+ row := q.db.QueryRow(ctx, searchIndexSinceIsPruned, sinceSnapshot)
+ var pruned bool
+ err := row.Scan(&pruned)
+ return pruned, err
+}
diff --git a/server/pkg/db/queries/search_index.sql b/server/pkg/db/queries/search_index.sql
new file mode 100644
index 0000000000..8db9dfba63
--- /dev/null
+++ b/server/pkg/db/queries/search_index.sql
@@ -0,0 +1,114 @@
+-- Local search index sync (MUL-7754). Web and Desktop copy the issue, comment,
+-- and project text of a workspace, then catch up through search_index_change.
+-- Snapshots are exchanged as pg_snapshot text; see migration 561.
+
+-- name: GetSearchIndexManifest :one
+-- Taken before any snapshot page, so every write the pages might miss is newer
+-- than this snapshot and reaches the client through the change log. The byte
+-- totals let the client reject a workspace too large for its memory budget
+-- before downloading it; octet_length reads the stored length, so TOASTed
+-- bodies are not decompressed.
+WITH ws AS (SELECT @workspace_id::uuid AS id)
+SELECT
+ pg_current_snapshot()::text AS snapshot,
+ (SELECT count(*) FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_count,
+ (SELECT COALESCE(sum(octet_length(i.title) + COALESCE(octet_length(i.description), 0)), 0)
+ FROM issue i, ws WHERE i.workspace_id = ws.id)::bigint AS issue_bytes,
+ (SELECT count(*) FROM comment c, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_count,
+ (SELECT COALESCE(sum(octet_length(c.content)), 0) FROM comment c, ws
+ WHERE c.workspace_id = ws.id AND c.deleted_at IS NULL)::bigint AS comment_bytes,
+ (SELECT count(*) FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_count,
+ (SELECT COALESCE(sum(octet_length(p.title) + COALESCE(octet_length(p.description), 0)), 0)
+ FROM project p, ws WHERE p.workspace_id = ws.id)::bigint AS project_bytes;
+
+-- name: GetSearchIndexCurrentSnapshot :one
+SELECT pg_current_snapshot()::text AS snapshot;
+
+-- name: ListSearchIndexIssuesPage :many
+-- Pages by the unique (workspace_id, number) index.
+SELECT * FROM issue
+WHERE workspace_id = @workspace_id AND number > @after_number
+ORDER BY number
+LIMIT @page_limit;
+
+-- name: ListSearchIndexIssuesByIDs :many
+SELECT * FROM issue
+WHERE workspace_id = @workspace_id AND id = ANY(@ids::uuid[]);
+
+-- name: ListSearchIndexCommentsByIssues :many
+SELECT id, issue_id, content, created_at
+FROM comment
+WHERE workspace_id = @workspace_id
+ AND issue_id = ANY(@issue_ids::uuid[])
+ AND deleted_at IS NULL;
+
+-- name: ListSearchIndexCommentsByIDs :many
+-- Tombstoned comments are returned so the caller can report them as deleted.
+SELECT id, issue_id, content, created_at, deleted_at
+FROM comment
+WHERE workspace_id = @workspace_id AND id = ANY(@ids::uuid[]);
+
+-- name: ListSearchIndexProjects :many
+SELECT * FROM project
+WHERE workspace_id = @workspace_id
+ORDER BY id;
+
+-- name: ListSearchIndexProjectsByIDs :many
+SELECT * FROM project
+WHERE workspace_id = @workspace_id AND id = ANY(@ids::uuid[]);
+
+-- name: SearchIndexSinceIsPruned :one
+-- True when retention pruning may have removed a change the client has not
+-- seen yet: a pruned xid at or above the snapshot's xmin could be one it has
+-- not consumed.
+SELECT EXISTS (
+ SELECT 1 FROM search_index_prune_mark
+ WHERE singleton
+ AND pruned_through_xid >= pg_snapshot_xmin((@since_snapshot::text)::pg_snapshot)
+) AS pruned;
+
+-- name: ListSearchIndexChanges :many
+-- Changes committed in the target snapshot but not in the since snapshot, in
+-- keyset order. An entity rewritten after the target snapshot carries a newer
+-- xid, drops out of this range, and is returned by the next catch-up instead.
+SELECT entity_type, entity_id, change_xid::text AS change_xid
+FROM search_index_change
+WHERE workspace_id = @workspace_id
+ AND change_xid >= pg_snapshot_xmin((@since_snapshot::text)::pg_snapshot)
+ AND change_xid < pg_snapshot_xmax((@target_snapshot::text)::pg_snapshot)
+ AND NOT pg_visible_in_snapshot(change_xid, (@since_snapshot::text)::pg_snapshot)
+ AND pg_visible_in_snapshot(change_xid, (@target_snapshot::text)::pg_snapshot)
+ AND (change_xid, entity_type, entity_id)
+ > ((@after_xid::text)::xid8, @after_type::text, @after_id::uuid)
+ORDER BY change_xid, entity_type, entity_id
+LIMIT @page_limit;
+
+-- name: PruneSearchIndexChanges :one
+-- Deletes one bounded batch of rows older than the cutoff and raises the prune
+-- mark to the highest xid removed, in the same statement.
+WITH doomed AS (
+ SELECT sic.entity_type, sic.entity_id
+ FROM search_index_change sic
+ WHERE sic.changed_at < @cutoff
+ ORDER BY sic.changed_at
+ LIMIT @batch_size
+ FOR UPDATE SKIP LOCKED
+), deleted AS (
+ DELETE FROM search_index_change c
+ USING doomed d
+ WHERE c.entity_type = d.entity_type
+ AND c.entity_id = d.entity_id
+ AND c.changed_at < @cutoff
+ RETURNING c.change_xid
+), marked AS (
+ INSERT INTO search_index_prune_mark (singleton, pruned_through_xid)
+ SELECT TRUE, deleted.change_xid FROM deleted ORDER BY deleted.change_xid DESC LIMIT 1
+ ON CONFLICT (singleton) DO UPDATE
+ SET pruned_through_xid = GREATEST(search_index_prune_mark.pruned_through_xid, EXCLUDED.pruned_through_xid)
+ RETURNING 1
+)
+SELECT count(*)::bigint AS deleted_count FROM deleted;
+
+-- name: DeleteWorkspaceSearchIndexChanges :exec
+DELETE FROM search_index_change WHERE workspace_id = $1;