Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Report search index warming state so cold-start searches retry (#2021)

Andrew Mikofalvy7c15743d6269
diff --git a/.changeset/search-server-readiness-signal.md b/.changeset/search-server-readiness-signal.md
new file mode 100644
index 000000000..f810908a5
--- /dev/null
+++ b/.changeset/search-server-readiness-signal.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Make `/api/search` report when its index is still warming, so cold-start searches retry instead of returning false-empty results.
+
+Right after the server boots, the workspace search index is still being built from the on-disk file walk. A search arriving in that window previously either blocked or came back empty as if nothing matched. The search endpoint now answers immediately with a `ready: false` signal while the index is warming, and `ready: true` once it is built.
+
+The `search` MCP tool surfaces this: instead of reporting "no matches" during warm-up, it tells the agent the index is still building and to wait a couple of seconds before retrying (or fall back to `exec` grep). The command palette shows its "Preparing search" status and polls until the index is ready, so results appear without retyping. This complements the earlier client-side cold-load fix by closing the same race at the server for every consumer.
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index f5ca75d96..cd3ae1923 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -40,6 +40,7 @@ const installedAgentStates = {
};
const workspaceValue = { rootPath: '/workspace' };
let pageListLoading = false;
+const COMMAND_PALETTE_POLL_GRACE_MS = 1400;
mock.module('@lingui/react/macro', () => ({
Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
@@ -428,6 +429,103 @@ describe('CommandPalette DOM behavior', () => {
);
expect(screen.queryByTestId('command-palette-search-preparing')).toBeNull();
});
+
+ test('server warming (ready:false) shows the preparing state and polls until the index is ready', async () => {
+ let searchCalls = 0;
+ globalThis.fetch = mock((input: unknown) => {
+ if (input === '/api/search') {
+ searchCalls += 1;
+ const body =
+ searchCalls >= 2
+ ? { results: [{ kind: 'page', path: 'arch', title: 'Arch' }], ready: true }
+ : { results: [], ready: false };
+ return Promise.resolve(new Response(JSON.stringify(body), { status: 200 }));
+ }
+ return Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 }));
+ }) as never;
+
+ await renderPalette({ bridge: null });
+ await setQuery('arch');
+
+ await waitFor(() =>
+ expect(screen.getByTestId('command-palette-search-preparing')).not.toBeNull(),
+ );
+ expect(screen.queryByText('Search failed.')).toBeNull();
+
+ await waitFor(() => expect(searchCalls).toBeGreaterThanOrEqual(2), { timeout: 3000 });
+ await waitFor(() =>
+ expect(screen.queryByTestId('command-palette-search-preparing')).toBeNull(),
+ );
+ });
+
+ test('closing the palette mid-warming stops the poll (no further /api/search calls)', async () => {
+ globalThis.fetch = mock((input: unknown) => {
+ if (input === '/api/search') {
+ return Promise.resolve(
+ new Response(JSON.stringify({ results: [], ready: false }), { status: 200 }),
+ );
+ }
+ return Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 }));
+ }) as never;
+
+ const { CommandPalette } = await import('./CommandPalette');
+ const onOpenChange = mock(() => {});
+ const { rerender } = render(
+ <CommandPalette bridge={null} open={true} onOpenChange={onOpenChange} />,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ await setQuery('arch');
+ await waitFor(() =>
+ expect(screen.getByTestId('command-palette-search-preparing')).not.toBeNull(),
+ );
+
+ const fetchMock = globalThis.fetch as unknown as { mock: { calls: unknown[][] } };
+ const searchCalls = () =>
+ fetchMock.mock.calls.filter((call) => call[0] === '/api/search').length;
+ const callsAtClose = searchCalls();
+
+ rerender(<CommandPalette bridge={null} open={false} onOpenChange={onOpenChange} />);
+
+ await new Promise((resolve) => setTimeout(resolve, COMMAND_PALETTE_POLL_GRACE_MS));
+ expect(searchCalls()).toBe(callsAtClose);
+ });
+
+ test('a transient error while warming keeps polling and recovers, never showing "Search failed."', async () => {
+ let call = 0;
+ globalThis.fetch = mock((input: unknown) => {
+ if (input === '/api/search') {
+ call += 1;
+ if (call === 1) {
+ return Promise.resolve(
+ new Response(JSON.stringify({ results: [], ready: false }), { status: 200 }),
+ );
+ }
+ if (call === 2) return Promise.reject(new Error('network blip'));
+ return Promise.resolve(
+ new Response(
+ JSON.stringify({
+ results: [{ kind: 'page', path: 'arch', title: 'Arch' }],
+ ready: true,
+ }),
+ { status: 200 },
+ ),
+ );
+ }
+ return Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 }));
+ }) as never;
+
+ await renderPalette({ bridge: null });
+ await setQuery('arch');
+ await waitFor(() =>
+ expect(screen.getByTestId('command-palette-search-preparing')).not.toBeNull(),
+ );
+
+ await waitFor(() => expect(call).toBeGreaterThanOrEqual(3), { timeout: 3000 });
+ expect(screen.queryByText('Search failed.')).toBeNull();
+ await waitFor(() =>
+ expect(screen.queryByTestId('command-palette-search-preparing')).toBeNull(),
+ );
+ });
});
describe('NavigationItem path subtitle', () => {
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index a6754a77c..0e1239c19 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -87,6 +87,8 @@ import { buildHandoffInput, useHandoffDispatch } from './handoff/useHandoffDispa
import { useInstalledAgents } from './handoff/useInstalledAgents';
const COMMAND_PALETTE_SEARCH_TIMEOUT_MS = 3000;
+const COMMAND_PALETTE_SEARCH_WARMING_POLL_MS = 600;
+const COMMAND_PALETTE_SEARCH_MAX_WARMING_POLLS = 20;
export const runWithToast = (
fn: () => Promise<void>,
@@ -233,6 +235,7 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
'idle',
);
const [searchTruncated, setSearchTruncated] = useState(false);
+ const [searchIndexWarming, setSearchIndexWarming] = useState(false);
const [isSemanticMode, setIsSemanticMode] = useState(false);
const [semanticResults, setSemanticResults] = useState<WorkspaceSearchEntry[]>([]);
const [semanticFiredQuery, setSemanticFiredQuery] = useState<string | null>(null);
@@ -430,38 +433,76 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
setSearchResults([]);
setSearchStatus('idle');
setSearchTruncated(false);
+ setSearchIndexWarming(false);
return;
}
- const controller = new AbortController();
+ let cancelled = false;
+ let everWarming = false;
+ let warmingPolls = 0;
+ let activeController: AbortController | null = null;
+ let timeoutTimer: number | undefined;
+ let retryTimer: number | undefined;
setSearchStatus('loading');
- let timedOut = false;
- const timeout = window.setTimeout(() => {
- timedOut = true;
- controller.abort();
+
+ const scheduleWarmingRetry = (): boolean => {
+ if (cancelled || warmingPolls >= COMMAND_PALETTE_SEARCH_MAX_WARMING_POLLS) return false;
+ warmingPolls += 1;
+ retryTimer = window.setTimeout(run, COMMAND_PALETTE_SEARCH_WARMING_POLL_MS);
+ return true;
+ };
+
+ const settleErrorOrRetry = () => {
+ if (cancelled) return;
+ if (everWarming && scheduleWarmingRetry()) return;
setSearchResults([]);
setSearchStatus('error');
setSearchTruncated(false);
- }, COMMAND_PALETTE_SEARCH_TIMEOUT_MS);
+ setSearchIndexWarming(false);
+ };
- void fetchWorkspaceSearchEntries(trimmedDeferredQuery, { signal: controller.signal })
- .then(({ entries, truncated }) => {
- window.clearTimeout(timeout);
- setSearchResults(entries);
- setSearchTruncated(truncated);
- setSearchStatus('success');
- })
- .catch((error: unknown) => {
- window.clearTimeout(timeout);
- if (error instanceof Error && error.name === 'AbortError' && !timedOut) return;
- setSearchResults([]);
- setSearchStatus('error');
- setSearchTruncated(false);
- });
+ function run() {
+ const controller = new AbortController();
+ activeController = controller;
+ timeoutTimer = window.setTimeout(() => {
+ controller.abort();
+ settleErrorOrRetry();
+ }, COMMAND_PALETTE_SEARCH_TIMEOUT_MS);
+
+ void fetchWorkspaceSearchEntries(trimmedDeferredQuery, { signal: controller.signal })
+ .then(({ entries, truncated, ready }) => {
+ window.clearTimeout(timeoutTimer);
+ if (cancelled) return;
+ if (!ready) {
+ if (!everWarming) {
+ everWarming = true;
+ setSearchResults([]);
+ setSearchTruncated(false);
+ setSearchIndexWarming(true);
+ setSearchStatus('success');
+ }
+ if (!scheduleWarmingRetry()) setSearchIndexWarming(false);
+ return;
+ }
+ setSearchResults(entries);
+ setSearchTruncated(truncated);
+ setSearchIndexWarming(false);
+ setSearchStatus('success');
+ })
+ .catch((error: unknown) => {
+ window.clearTimeout(timeoutTimer);
+ if (cancelled) return;
+ if (error instanceof Error && error.name === 'AbortError') return;
+ settleErrorOrRetry();
+ });
+ }
+ run();
return () => {
- window.clearTimeout(timeout);
- controller.abort();
+ cancelled = true;
+ window.clearTimeout(timeoutTimer);
+ window.clearTimeout(retryTimer);
+ activeController?.abort();
};
}, [open, trimmedDeferredQuery, inExclusiveMode, pagesLoading]);
@@ -497,13 +538,17 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
searchStatus,
});
const showNavigation = !inExclusiveMode && visibleSearchResults.length > 0;
+ const showSearchPreparing =
+ !inExclusiveMode &&
+ trimmedDeferredQuery !== '' &&
+ (pagesLoading || searchIndexWarming) &&
+ !showNavigation;
const showSearchLoading =
!inExclusiveMode &&
trimmedDeferredQuery !== '' &&
searchStatus === 'loading' &&
- !showNavigation;
- const showSearchPreparing =
- !inExclusiveMode && trimmedDeferredQuery !== '' && pagesLoading && !showNavigation;
+ !showNavigation &&
+ !showSearchPreparing;
const showCreateFile =
!inExclusiveMode && matchesCommandQuery(t`New file`, deferredQuery, ['create file']);
const showCreateFolder =
diff --git a/packages/app/src/components/command-palette-search.ts b/packages/app/src/components/command-palette-search.ts
index 9965aa86c..54a08d215 100644
--- a/packages/app/src/components/command-palette-search.ts
+++ b/packages/app/src/components/command-palette-search.ts
@@ -209,11 +209,13 @@ interface WorkspaceSearchApiResponse {
score?: number;
}>;
truncated?: boolean;
+ ready?: boolean;
}
export interface WorkspaceSearchFetchResult {
entries: WorkspaceSearchEntry[];
truncated: boolean;
+ ready: boolean;
}
function toWorkspaceSearchEntry(
@@ -241,7 +243,7 @@ export async function fetchWorkspaceSearchEntries(
options: { signal?: AbortSignal; limit?: number; semantic?: boolean } = {},
): Promise<WorkspaceSearchFetchResult> {
const normalizedQuery = query.trim();
- if (!normalizedQuery) return { entries: [], truncated: false };
+ if (!normalizedQuery) return { entries: [], truncated: false, ready: true };
const response = await fetch('/api/search', {
method: 'POST',
@@ -265,7 +267,7 @@ export async function fetchWorkspaceSearchEntries(
const payload = (await response.json()) as WorkspaceSearchApiResponse;
const entries = (payload.results ?? []).map(toWorkspaceSearchEntry).filter((entry) => !!entry);
- return { entries, truncated: payload.truncated === true };
+ return { entries, truncated: payload.truncated === true, ready: payload.ready !== false };
}
export function matchesCommandQuery(
diff --git a/packages/core/src/schemas/api/tags-search.ts b/packages/core/src/schemas/api/tags-search.ts
index e8eb088da..367bc5a1c 100644
--- a/packages/core/src/schemas/api/tags-search.ts
+++ b/packages/core/src/schemas/api/tags-search.ts
@@ -216,6 +216,7 @@ export const SearchSuccessSchema = z
elapsedMs: z.number().nonnegative(),
semantic: SearchSemanticStatusSchema.optional(),
truncated: z.boolean().optional(),
+ ready: z.boolean().optional(),
})
.loose() satisfies StandardSchemaV1;
export type SearchSuccess = z.infer<typeof SearchSuccessSchema>;
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 212d4ca9f..6a19eed21 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -10426,6 +10426,15 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
source: SearchSource;
}): Promise<SearchSuccess> {
const startedAt = performance.now();
+ if (isSearchCorpusWarming()) {
+ return {
+ query: params.query,
+ intent: params.intent,
+ results: [],
+ elapsedMs: Math.max(0, performance.now() - startedAt),
+ ready: false,
+ };
+ }
const { corpus, truncated } = await getWorkspaceSearchCorpus();
const semantic = await resolveSemantic(
params.query,
@@ -10473,6 +10482,7 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
intent: params.intent,
results: entries,
elapsedMs: Math.max(0, performance.now() - startedAt),
+ ready: true,
...(semanticStatus ? { semantic: semanticStatus } : {}),
...(truncated ? { truncated: true } : {}),
};
@@ -10560,6 +10570,24 @@ export function createApiExtension(options: ApiExtensionOptions): Extension {
.join('');
}
+ let bootIndexReady = ready === undefined;
+ ready?.then(
+ () => {
+ bootIndexReady = true;
+ },
+ (err: unknown) => {
+ bootIndexReady = true;
+ log.warn(
+ { err, handler: 'search' },
+ '[api] ready gate rejected — search serves the partial index',
+ );
+ },
+ );
+
+ function isSearchCorpusWarming(): boolean {
+ return !bootIndexReady;
+ }
+
async function getWorkspaceSearchCorpus(): Promise<{
corpus: WorkspaceSearchCorpus;
truncated: boolean;
diff --git a/packages/server/src/api-search.test.ts b/packages/server/src/api-search.test.ts
index e2ff3a7bd..70a4775d9 100644
--- a/packages/server/src/api-search.test.ts
+++ b/packages/server/src/api-search.test.ts
@@ -702,3 +702,117 @@ describe('GET /api/search — dot-path searchability', () => {
}
});
});
+
+describe('GET /api/search — cold-start readiness', () => {
+ async function onRequest(ext: ReturnType<typeof createApiExtension>, url: string) {
+ const req = makeReq('GET', url);
+ const { res, captured } = makeRes();
+ await (
+ ext as {
+ onRequest: (ctx: { request: IncomingMessage; response: ServerResponse }) => Promise<void>;
+ }
+ ).onRequest({ request: req, response: res });
+ return captured;
+ }
+
+ test('answers ready:false with empty results while the boot index is warming, then ready:true with results once the boot gate resolves', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-search-warming-'));
+ try {
+ mkdirSync(join(dir, 'architecture'), { recursive: true });
+ writeFileSync(join(dir, 'architecture/overview.md'), '# System Overview\n', 'utf-8');
+ const fileIndex = buildFileIndex(dir);
+
+ let resolveReady: () => void = () => {};
+ const ready = new Promise<void>((resolve) => {
+ resolveReady = resolve;
+ });
+ const ext = createApiExtension({
+ hocuspocus: {} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],
+ sessionManager: {} as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],
+ contentDir: dir,
+ serverInstanceId: 'test-server',
+ getFileIndex: () => fileIndex,
+ ready,
+ });
+
+ const warming = JSON.parse((await onRequest(ext, '/api/search?query=overview')).body) as {
+ ready?: boolean;
+ results?: unknown[];
+ };
+ expect(warming.ready).toBe(false);
+ expect(warming.results).toEqual([]);
+
+ resolveReady();
+ await ready;
+ await new Promise((r) => setTimeout(r, 0));
+
+ const captured = await onRequest(ext, '/api/search?query=overview');
+ expect(captured.status).toBe(200);
+ const settled = JSON.parse(captured.body) as {
+ ready?: boolean;
+ results?: Array<{ path: string }>;
+ };
+ expect(settled.ready).toBe(true);
+ expect(settled.results?.some((row) => row.path === 'architecture/overview')).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('a rejected boot gate flips to ready so search does not warm forever (degraded boot)', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-search-rejected-gate-'));
+ try {
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n', 'utf-8');
+ const fileIndex = buildFileIndex(dir);
+
+ let rejectReady: (err: Error) => void = () => {};
+ const ready = new Promise<void>((_resolve, reject) => {
+ rejectReady = reject;
+ });
+ ready.catch(() => {});
+ const ext = createApiExtension({
+ hocuspocus: {} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],
+ sessionManager: {} as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],
+ contentDir: dir,
+ serverInstanceId: 'test-server',
+ getFileIndex: () => fileIndex,
+ ready,
+ });
+
+ rejectReady(new Error('init failed'));
+ await new Promise((r) => setTimeout(r, 0));
+
+ const body = JSON.parse((await onRequest(ext, '/api/search?query=guide')).body) as {
+ ready?: boolean;
+ results?: Array<{ path: string }>;
+ };
+ expect(body.ready).toBe(true);
+ expect(body.results?.some((row) => row.path === 'guide')).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test('without a boot gate (test/library harness), search is ready immediately', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-search-nogate-'));
+ try {
+ writeFileSync(join(dir, 'guide.md'), '# Guide\n', 'utf-8');
+ const fileIndex = buildFileIndex(dir);
+ const ext = createApiExtension({
+ hocuspocus: {} as unknown as Parameters<typeof createApiExtension>[0]['hocuspocus'],
+ sessionManager: {} as unknown as Parameters<typeof createApiExtension>[0]['sessionManager'],
+ contentDir: dir,
+ serverInstanceId: 'test-server',
+ getFileIndex: () => fileIndex,
+ });
+ const body = JSON.parse((await onRequest(ext, '/api/search?query=guide')).body) as {
+ ready?: boolean;
+ results?: Array<{ path: string }>;
+ };
+ expect(body.ready).toBe(true);
+ expect(body.results?.some((row) => row.path === 'guide')).toBe(true);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/server/src/mcp/tools/search.test.ts b/packages/server/src/mcp/tools/search.test.ts
index 50f21bec0..abcb5d5d3 100644
--- a/packages/server/src/mcp/tools/search.test.ts
+++ b/packages/server/src/mcp/tools/search.test.ts
@@ -448,3 +448,40 @@ describe('search MCP tool — error paths', () => {
expect(text).toContain('Query is too long');
});
});
+
+describe('search MCP tool — cold-start warming', () => {
+ test('ready:false surfaces a retry hint (not "No matches") and propagates ready:false', async () => {
+ mockFetchOk({ ok: true, query: 'arch', intent: 'full_text', results: [], ready: false });
+ const { server, registered } = makeFakeServer();
+ register(server, {
+ resolveCwd: async () => '/tmp/proj',
+ config: DEFAULT_CONFIG,
+ serverUrl: 'http://localhost:1234',
+ });
+ const tool = expectOneRegisteredTool(registered);
+ const result = await tool.handler({ query: 'arch', cwd: '/tmp/proj' });
+
+ const text = result.content?.find((c) => c.type === 'text')?.text ?? '';
+ expect(text).toContain('still warming');
+ expect(text).not.toContain('No matches');
+ const structured = result.structuredContent as { ready?: unknown; resultCount: number };
+ expect(structured.ready).toBe(false);
+ expect(structured.resultCount).toBe(0);
+ });
+
+ test('ready:true serves results with no warming text and omits the ready flag', async () => {
+ mockFetchOk({ ok: true, query: 'arch', intent: 'full_text', results: [], ready: true });
+ const { server, registered } = makeFakeServer();
+ register(server, {
+ resolveCwd: async () => '/tmp/proj',
+ config: DEFAULT_CONFIG,
+ serverUrl: 'http://localhost:1234',
+ });
+ const tool = expectOneRegisteredTool(registered);
+ const result = await tool.handler({ query: 'arch', cwd: '/tmp/proj' });
+
+ const text = result.content?.find((c) => c.type === 'text')?.text ?? '';
+ expect(text).not.toContain('still warming');
+ expect((result.structuredContent as { ready?: unknown }).ready).toBeUndefined();
+ });
+});
diff --git a/packages/server/src/mcp/tools/search.ts b/packages/server/src/mcp/tools/search.ts
index 27d720c40..0cafe54b0 100644
--- a/packages/server/src/mcp/tools/search.ts
+++ b/packages/server/src/mcp/tools/search.ts
@@ -25,6 +25,8 @@ export const DESCRIPTION = [
'',
'Returns scored `page`, `folder`, and name-only `file` hits, each with a `signals` breakdown (lexical / fullText / recency / vector); markdown `page` hits also carry a body snippet (`file` hits never do — name-only). `exec`-grep covers every content occurrence and needs no server.',
'',
+ 'Cold start: right after the server boots, the response may carry `ready: false` with an empty `results` while the index is still building. That empty set is NOT authoritative — wait ~2-3 seconds, then retry (agents have no built-in delay, so do not retry in immediate succession). If it is still `ready: false` after 2-3 retries (e.g. a very large workspace), fall back to `exec("grep ...")` rather than polling further. Once `ready` is true/omitted the results are complete.',
+ '',
'**Parameters:**',
'- `query` — Free-form; tokenized across title, name, path segments, and (with `full_text`) body.',
'- `intent` (optional) — `omnibar` searches title/path/folders only (fast); `full_text` includes body. Default `full_text`.',
@@ -99,6 +101,7 @@ const OutputSchema = outputSchemaWithText({
results: z.array(SearchResultRowSchema),
elapsedMs: z.number().nullable(),
semantic: SearchSemanticStatusSchema.optional(),
+ ready: z.literal(false).optional(),
});
type SearchKind = 'page' | 'folder' | 'file';
@@ -126,6 +129,7 @@ interface SearchApiResponse {
results?: SearchApiRow[];
elapsedMs?: number;
semantic?: SearchApiSemanticStatus;
+ ready?: boolean;
[key: string]: unknown;
}
@@ -155,6 +159,7 @@ interface SearchStructuredResult {
results: SearchResultRow[];
elapsedMs: number | null;
semantic?: SearchSemanticStatus;
+ ready?: false;
}
function isSearchKind(value: unknown): value is SearchKind {
@@ -292,6 +297,7 @@ export function register(server: ServerInstance, deps: SearchDeps): void {
});
const semantic = normalizeSemanticStatus(result.semantic);
+ const ready = result.ready !== false;
const structured: SearchStructuredResult = {
cwd,
query: args.query,
@@ -300,12 +306,14 @@ export function register(server: ServerInstance, deps: SearchDeps): void {
results: rows,
elapsedMs: typeof result.elapsedMs === 'number' ? result.elapsedMs : null,
...(semantic ? { semantic } : {}),
+ ...(ready ? {} : { ready: false }),
};
const header = `## Search results for "${args.query}" (${rows.length} hit${rows.length === 1 ? '' : 's'}, intent: ${intent})`;
const semanticNote = formatSemanticNote(semantic);
- const resultsText =
- rows.length === 0
+ const resultsText = !ready
+ ? `The workspace search index is still warming — results for "${args.query}" are not ready yet. Wait ~2-3 seconds, then retry; if it is still warming after 2-3 retries, use \`exec("grep ...")\` for an index-free search instead.`
+ : rows.length === 0
? `No matches for "${args.query}".`
: `${header}\n\n${formatResultsBlock(rows)}`;
const text = semanticNote ? `${resultsText}\n${semanticNote}` : resultsText;