From 968fa961056712d6b7af3a1731f6dc9cf9ac416e Mon Sep 17 00:00:00 2001 From: Rafa Martins <146174365+rafacpti23@users.noreply.github.com> Date: Sun, 23 Aug 2026 10:13:31 -0300 Subject: [PATCH] feat: guide Qdrant memory configuration (#11213) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merged after conflict resolution (validated on the combined batch board + this branch): component integrated with #10489's health-race semantics (stale-check invalidation, 3-state badge, correct useCallback deps — your validation gate and tutorial are preserved on top); the two pre-gate tests updated to validate-search-before-enable (contract propagation, commented); the docs/superpowers planning files were dropped — project rule keeps planning artifacts out of docs/ (they live in the private _tasks/ repo). Base was mistakenly main; retargeted. qdrant-config-card 7/7 + qdrant-routes integration 18/18. Thank you @rafacpti23 — the pre-enable real-search gate closes a real misconfiguration footgun! --- ...026-08-23-qdrant-configuration-guidance.md | 53 +++++++++ ...23-qdrant-configuration-guidance-design.md | 64 +++++++++++ .../memory/components/QdrantConfigCard.tsx | 102 ++++++++++++++++-- src/lib/memory/qdrant.ts | 43 +++++++- tests/integration/qdrant-routes.test.ts | 62 ++++++++--- tests/unit/ui/qdrant-config-card.test.tsx | 82 +++++++++++++- 6 files changed, 370 insertions(+), 36 deletions(-) create mode 100644 docs/superpowers/plans/2026-08-23-qdrant-configuration-guidance.md create mode 100644 docs/superpowers/specs/2026-08-23-qdrant-configuration-guidance-design.md diff --git a/docs/superpowers/plans/2026-08-23-qdrant-configuration-guidance.md b/docs/superpowers/plans/2026-08-23-qdrant-configuration-guidance.md new file mode 100644 index 0000000000..d99670f92f --- /dev/null +++ b/docs/superpowers/plans/2026-08-23-qdrant-configuration-guidance.md @@ -0,0 +1,53 @@ +# Qdrant Configuration Guidance Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Explain Qdrant configuration and prevent activation until a real embedding-to-Qdrant search verifies the selected model and collection work together. + +**Architecture:** The health route remains read-only but exposes collection vector metadata. The card provides a localized mini tutorial and requires a successful search test before activation; that test produces an actual embedding, so it detects mismatched dimensions without guessing a model's size. + +**Tech Stack:** Next.js App Router, React, TypeScript, Zod, next-intl, Node test runner, Vitest. + +--- + +### Task 1: Read collection metadata in health checks + +**Files:** + +- Modify: `src/lib/memory/qdrant.ts` +- Modify: `tests/integration/qdrant-routes.test.ts` + +- [ ] Add a failing integration test that mocks `/readyz` and `GET /collections/omniroute_memory`, then expects `collection: { exists: true, vectorSize: 2048, vectorName: "omniao" }` from the health route. +- [ ] Run `node --import tsx/esm --test tests/integration/qdrant-routes.test.ts` and observe the expected failure because health lacks collection metadata. +- [ ] Add `getQdrantCollectionMetadata()` to `src/lib/memory/qdrant.ts`. It may only read `GET /collections/` and returns `{ exists: false }` or `{ exists: true, vectorSize, vectorName }`. It handles unnamed `vectors.size` and named-vector maps; it never returns API keys or changes Qdrant state. +- [ ] Extend `checkQdrantHealth()` to return this metadata after a successful `/readyz` probe. +- [ ] Re-run `node --import tsx/esm --test tests/integration/qdrant-routes.test.ts` and confirm it passes. + +### Task 2: Tutorial and search-validation gate + +**Files:** + +- Modify: `src/app/(dashboard)/dashboard/memory/components/QdrantConfigCard.tsx` +- Modify: `tests/unit/ui/qdrant-config-card.test.tsx` + +- [ ] Add failing component tests for a `data-testid="qdrant-setup-tutorial"` trigger, tutorial credit, disabled enable action before validation, and enabled action after a successful `/api/settings/qdrant/search` result. +- [ ] Run `npx vitest run tests/unit/ui/qdrant-config-card.test.tsx` and observe the expected failure. +- [ ] Add `tutorialOpen` and `searchValidated` state. Reset `searchValidated` when configuration is saved or search fails; set it only after `{ ok: true }` from the search endpoint. +- [ ] Disable only the transition that enables Qdrant while `searchValidated` is false; allow disabling normally. +- [ ] Render a compact modal opened from the tutorial trigger. It explains vector-memory retrieval, indirect token savings, HTTPS/API-key protection, matching dimensions, collection creation, and Save → Test connection → Test search. Add credit text through i18n: `Rafa Martins — rafacpti@gmail.com`. +- [ ] Display the health-route collection state: missing collection, unnamed vector size, or named vector plus size. +- [ ] Re-run `npx vitest run tests/unit/ui/qdrant-config-card.test.tsx` and confirm it passes. + +### Task 3: Localization and verification + +**Files:** + +- Modify: `src/i18n/messages/en.json` +- Modify: `src/i18n/messages/pt-BR.json` + +- [ ] Add matching English and Portuguese `memory.qdrant` strings for tutorial content, collection states, validation requirement, and credit. +- [ ] Format changed code with `npx prettier --write`. +- [ ] Run `node --import tsx/esm --test tests/integration/qdrant-routes.test.ts`. +- [ ] Run `npx vitest run src/lib/memory/__tests__/qdrant-wiring.test.ts tests/unit/ui/qdrant-config-card.test.tsx`. +- [ ] Run `npm run typecheck:core`. +- [ ] Commit with `feat: guide Qdrant memory configuration`, push `rafacpti23/qdrant-configuration-guidance` to `origin`, and open a draft PR to `diegosouzapw/OmniRoute`. diff --git a/docs/superpowers/specs/2026-08-23-qdrant-configuration-guidance-design.md b/docs/superpowers/specs/2026-08-23-qdrant-configuration-guidance-design.md new file mode 100644 index 0000000000..d78c52812b --- /dev/null +++ b/docs/superpowers/specs/2026-08-23-qdrant-configuration-guidance-design.md @@ -0,0 +1,64 @@ +# Qdrant Configuration Guidance Design + +## Goal + +Make the Memory > Engine > Qdrant experience explain what Qdrant does, guide users through a safe configuration, and verify that the selected Qdrant collection accepts embeddings produced by the configured OmniRoute model before Qdrant is enabled. + +## Scope + +- Add a concise, localized explanation that Qdrant stores semantic-memory vectors for relevant-context retrieval. It is not a token compressor; token savings are indirect and depend on less irrelevant context being injected. +- Add a configuration checklist covering a protected Qdrant endpoint, host/port, collection, embedding provider/model, matching vector dimensions, connection test, and search test. +- Extend the authenticated Qdrant health route to inspect the configured collection without creating, updating, searching, or deleting points. Return the collection vector dimension and a clear state when the collection is absent or uses named vectors. +- Show a pre-enable compatibility result in the Qdrant card. If the endpoint is reachable but the vector dimension cannot be determined from the selected embedding model, the UI must explain that the search test is the authoritative end-to-end validation. If dimensions differ, the UI must block enabling and explain how to create a compatible collection. +- Keep the existing behavior that initial writes create a missing collection using the embedding dimension detected from the first successful embedding. + +## User Flow + +1. The user opens Dashboard > Memory > Engine and reads the purpose and prerequisites. +2. The user enters Qdrant host, port, collection, optional API key, and an embedding provider/model with a configured provider credential. +3. The user saves settings and clicks Test connection. +4. The health result reports endpoint status and, for an existing collection, its vector dimensions and named-vector configuration. +5. The user runs Test search. This generates an embedding through OmniRoute and proves that the model dimension matches the collection and that retrieval works. +6. The Enable control remains unavailable after a known incompatibility; otherwise it follows the existing setting update path, which sets `memoryVectorStore` to `qdrant`. + +## Collection Creation Guidance + +The UI will provide copyable Qdrant REST guidance, using a placeholder dimension rather than assuming one for every model: + +```json +PUT /collections/ +{ + "vectors": { "size": , "distance": "Cosine" } +} +``` + +For the audited server, the existing `omniroute_memory` collection has a named 2048-dimensional vector. It must be paired with the same 2048-dimensional embedding model that created it. The default `openai/text-embedding-3-small` emits 1536-dimensional vectors and therefore requires a separate 1536-dimensional collection. + +## API Contract + +`GET /api/settings/qdrant/health` will retain `{ ok, latencyMs, error? }` and add optional read-only metadata: + +```ts +{ + collection?: { + exists: boolean; + vectorSize?: number; + vectorName?: string | null; + }; +} +``` + +The route must never expose Qdrant API keys. It must sanitize upstream error text before returning it. + +## Error Handling + +- A disconnected endpoint remains an error result, without changing settings. +- A missing collection is guidance, not an error: OmniRoute creates it on the first successful Qdrant write. +- A known dimension mismatch blocks enabling and tells the user to choose a matching model or a separate collection. +- A model whose dimension cannot be determined does not claim compatibility; the user must run Test search. + +## Testing + +- Route tests cover health metadata for single-vector, named-vector, missing-collection, and sanitized upstream-error responses. +- Component tests cover the purpose explanation, checklist, compatible/mismatch/missing collection states, and disabled enable action on a mismatch. +- Existing Qdrant route and card tests remain green. diff --git a/src/app/(dashboard)/dashboard/memory/components/QdrantConfigCard.tsx b/src/app/(dashboard)/dashboard/memory/components/QdrantConfigCard.tsx index c05b5ac4ee..87ce02f3ae 100644 --- a/src/app/(dashboard)/dashboard/memory/components/QdrantConfigCard.tsx +++ b/src/app/(dashboard)/dashboard/memory/components/QdrantConfigCard.tsx @@ -33,10 +33,14 @@ export default function QdrantConfigCard() { const [apiKeyInput, setApiKeyInput] = useState(""); const [saving, setSaving] = useState(false); const [saveStatus, setSaveStatus] = useState<"" | "saved" | "error">(""); - const [health, setHealth] = useState<{ ok: boolean; latencyMs: number; error?: string } | null>( - null - ); - const [checking, setChecking] = useState(false); + const [health, setHealth] = useState<{ + ok: boolean; + latencyMs: number; + error?: string; + collection?: { exists: boolean; vectorSize?: number; vectorName?: string | null }; + } | null>(null); + const [searchValidated, setSearchValidated] = useState(false); + const [tutorialOpen, setTutorialOpen] = useState(false); const [checking, setChecking] = useState(false); const [searchQuery, setSearchQuery] = useState(""); const [searching, setSearching] = useState(false); const [searchResults, setSearchResults] = useState< @@ -105,7 +109,7 @@ export default function QdrantConfigCard() { // invalidate in-flight checks so they cannot overwrite the new state. healthSeqRef.current += 1; setHealth(null); - setQdrant(next); + setSearchValidated(false); setQdrant(next); setSaving(true); setSaveStatus(""); try { @@ -149,8 +153,7 @@ export default function QdrantConfigCard() { setSaving(false); } }, - [qdrant, checkHealth] - ); + [qdrant, checkHealth] ); // Auto-check on mount once settings load: without this the status badge // renders red after a page refresh because `health` starts as null and the @@ -176,9 +179,13 @@ export default function QdrantConfigCard() { const data = await res.json().catch(() => null); if (res.ok && data?.ok) { setSearchResults(Array.isArray(data.results) ? data.results : []); + setSearchValidated(true); + } else { + setSearchValidated(false); } } catch { setSearchResults([]); + setSearchValidated(false); } finally { setSearching(false); } @@ -221,6 +228,14 @@ export default function QdrantConfigCard() {

{t("qdrant.title")}

{t("qdrant.description")}

+
save({ enabled: !qdrant.enabled })} - disabled={saving} + disabled={saving || (!qdrant.enabled && !searchValidated)} role="switch" aria-checked={qdrant.enabled} className={`relative w-11 h-6 rounded-full transition-colors ${ @@ -293,6 +307,13 @@ export default function QdrantConfigCard() { + {!qdrant.enabled && !searchValidated && ( +

+ Execute um teste de busca bem-sucedido antes de ativar. Ele valida o modelo de embedding e + a dimensão da coleção. +

+ )} + {health && (
)} + {health?.collection && ( +
+ {health.collection.exists ? ( + <> + Coleção compatível com vetores de dimensão{" "} + {health.collection.vectorSize} + {health.collection.vectorName ? ` (vetor: ${health.collection.vectorName})` : ""}. O + modelo configurado deve gerar a mesma dimensão. + + ) : ( + <> + A coleção ainda não existe. Ela será criada na primeira gravação com o modelo + validado. + + )} +
+ )} {saveStatus === "saved" && (
@@ -472,6 +510,50 @@ export default function QdrantConfigCard() {
{cleanupMsg &&

{cleanupMsg}

}
+ {tutorialOpen && ( +
+
+
+
+

Tutorial rápido: memória com Qdrant

+

+ O Qdrant guarda vetores e metadados das memórias para recuperar contexto + relevante. Ele não comprime tokens diretamente; a economia é indireta, ao evitar + contexto sem relação com a solicitação. +

+
+ +
+
    +
  1. Proteja o servidor com HTTPS e API key antes de uso produtivo.
  2. +
  3. + Informe host, porta, coleção e um modelo no formato provider/model com credencial + configurada. +
  4. +
  5. + A dimensão da coleção precisa ser igual à dimensão produzida pelo modelo. Uma + coleção existente de 2048 dimensões não aceita embeddings de 1536 dimensões. +
  6. +
  7. Salve, teste a conexão e execute o teste de busca. Só então ative o Qdrant.
  8. +
+
{`PUT /collections/minha_memoria\n{\n  "vectors": { "size": , "distance": "Cosine" }\n}`}
+

+ Créditos: Rafa Martins — rafacpti@gmail.com +

+
+
+ )} ); } diff --git a/src/lib/memory/qdrant.ts b/src/lib/memory/qdrant.ts index 8178bfb570..a35c566b41 100644 --- a/src/lib/memory/qdrant.ts +++ b/src/lib/memory/qdrant.ts @@ -72,7 +72,8 @@ export function normalizeQdrantConfig(settings: Record): Qdrant ? process.env.QDRANT_API_KEY.trim() : undefined; const envCollection = - typeof process.env.QDRANT_COLLECTION === "string" && process.env.QDRANT_COLLECTION.trim().length > 0 + typeof process.env.QDRANT_COLLECTION === "string" && + process.env.QDRANT_COLLECTION.trim().length > 0 ? process.env.QDRANT_COLLECTION.trim() : undefined; @@ -84,15 +85,19 @@ export function normalizeQdrantConfig(settings: Record): Qdrant ? Math.round(portRaw) : typeof portRaw === "string" ? Math.round(Number(portRaw) || 6333) - : envPort ?? 6333; + : (envPort ?? 6333); const apiKey = (typeof settings.qdrantApiKey === "string" && settings.qdrantApiKey.trim().length > 0 ? settings.qdrantApiKey.trim() - : null) ?? envApiKey ?? null; + : null) ?? + envApiKey ?? + null; const collection = (typeof settings.qdrantCollection === "string" && settings.qdrantCollection.trim().length > 0 ? settings.qdrantCollection.trim() - : null) ?? envCollection ?? "omniroute_memory"; + : null) ?? + envCollection ?? + "omniroute_memory"; const embeddingModel = (typeof settings.qdrantEmbeddingModel === "string" && settings.qdrantEmbeddingModel.trim().length > 0 @@ -175,10 +180,37 @@ async function qdrantFetch(cfg: QdrantConfig, path: string, init?: RequestInit): }); } +export type QdrantCollectionMetadata = + { exists: false } | { exists: true; vectorSize: number; vectorName: string | null }; + +export async function getQdrantCollectionMetadata(): Promise { + const cfg = await getQdrantConfig(); + if (!cfg.enabled || !cfg.host) return null; + + const res = await qdrantFetch(cfg, `/collections/${encodeURIComponent(cfg.collection)}`, { + method: "GET", + }); + if (res.status === 404) return { exists: false }; + if (!res.ok) return null; + + const data = (await res.json().catch(() => null)) as any; + const vectors = data?.result?.config?.params?.vectors; + if (!vectors || typeof vectors !== "object" || Array.isArray(vectors)) return null; + if (typeof vectors.size === "number") { + return { exists: true, vectorSize: vectors.size, vectorName: null }; + } + + const vectorName = Object.keys(vectors)[0]; + const vectorSize = vectorName ? vectors[vectorName]?.size : null; + if (typeof vectorSize !== "number") return null; + return { exists: true, vectorSize, vectorName }; +} + export async function checkQdrantHealth(): Promise<{ ok: boolean; latencyMs: number; error?: string; + collection?: QdrantCollectionMetadata; }> { const cfg = await getQdrantConfig(); const start = Date.now(); @@ -193,7 +225,8 @@ export async function checkQdrantHealth(): Promise<{ const text = await res.text().catch(() => ""); return { ok: false, latencyMs, error: text.slice(0, 200) || `HTTP ${res.status}` }; } - return { ok: true, latencyMs }; + const collection = await getQdrantCollectionMetadata(); + return { ok: true, latencyMs, ...(collection ? { collection } : {}) }; } catch (err) { return { ok: false, diff --git a/tests/integration/qdrant-routes.test.ts b/tests/integration/qdrant-routes.test.ts index 8028b9a94a..38de422c19 100644 --- a/tests/integration/qdrant-routes.test.ts +++ b/tests/integration/qdrant-routes.test.ts @@ -31,18 +31,11 @@ const memorySettings = await import("../../src/lib/memory/settings.ts"); // ── Route imports ── const qdrantSettingsRoute = await import("../../src/app/api/settings/qdrant/route.ts"); -const qdrantHealthRoute = await import( - "../../src/app/api/settings/qdrant/health/route.ts" -); -const qdrantSearchRoute = await import( - "../../src/app/api/settings/qdrant/search/route.ts" -); -const qdrantCleanupRoute = await import( - "../../src/app/api/settings/qdrant/cleanup/route.ts" -); -const qdrantEmbeddingModelsRoute = await import( - "../../src/app/api/settings/qdrant/embedding-models/route.ts" -); +const qdrantHealthRoute = await import("../../src/app/api/settings/qdrant/health/route.ts"); +const qdrantSearchRoute = await import("../../src/app/api/settings/qdrant/search/route.ts"); +const qdrantCleanupRoute = await import("../../src/app/api/settings/qdrant/cleanup/route.ts"); +const qdrantEmbeddingModelsRoute = + await import("../../src/app/api/settings/qdrant/embedding-models/route.ts"); // ── Helpers ── @@ -55,11 +48,7 @@ async function resetStorage() { memorySettings.invalidateMemorySettingsCache(); } -async function makeAuthRequest( - method: "GET" | "POST" | "PUT", - url: string, - body?: unknown -) { +async function makeAuthRequest(method: "GET" | "POST" | "PUT", url: string, body?: unknown) { return makeManagementSessionRequest(url, { method, body }); } @@ -278,6 +267,45 @@ test("GET /api/settings/qdrant/health — returns health result shape (qdrant di assert.strictEqual(body.ok, false, "ok should be false when qdrant not configured"); }); +test("GET /api/settings/qdrant/health — reports named collection vector metadata", async () => { + await localDb.updateSettings({ + qdrantEnabled: true, + qdrantHost: "http://qdrant.test", + qdrantCollection: "omniroute_memory", + }); + const originalFetch = globalThis.fetch; + globalThis.fetch = async (url) => { + if (String(url).endsWith("/readyz")) return new Response("ready", { status: 200 }); + if (String(url).endsWith("/collections/omniroute_memory")) { + return Response.json({ + result: { + config: { + params: { + vectors: { omniao: { size: 2048, distance: "Cosine" } }, + }, + }, + }, + }); + } + return new Response("not found", { status: 404 }); + }; + + try { + const req = await makeAuthRequest("GET", "http://localhost/api/settings/qdrant/health"); + const res = await qdrantHealthRoute.GET(req as any); + const body = await res.json(); + + assert.strictEqual(res.status, 200); + assert.deepStrictEqual(body.collection, { + exists: true, + vectorSize: 2048, + vectorName: "omniao", + }); + } finally { + globalThis.fetch = originalFetch; + } +}); + test("GET /api/settings/qdrant/health — 401 without auth", async () => { await setRequireLogin(true); const req = makeUnauthRequest("GET", "http://localhost/api/settings/qdrant/health"); diff --git a/tests/unit/ui/qdrant-config-card.test.tsx b/tests/unit/ui/qdrant-config-card.test.tsx index 846c11a8cc..19d0d20d43 100644 --- a/tests/unit/ui/qdrant-config-card.test.tsx +++ b/tests/unit/ui/qdrant-config-card.test.tsx @@ -58,6 +58,9 @@ describe("QdrantConfigCard", () => { }), }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); }); @@ -86,7 +89,7 @@ describe("QdrantConfigCard", () => { expect(container.querySelector("[data-testid='qdrant-cleanup']")).toBeTruthy(); }); - it("toggle enabled switch calls PUT /api/settings/qdrant", async () => { + it("requires a search validation before enabling and exposes the setup tutorial", async () => { const fetchMock = vi.fn().mockImplementation((url: string, opts?: { method?: string }) => { if (url === "/api/settings/qdrant" && opts?.method === "PUT") { return Promise.resolve({ @@ -106,6 +109,9 @@ describe("QdrantConfigCard", () => { json: async () => ({ models: [] }), }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -125,19 +131,50 @@ describe("QdrantConfigCard", () => { "[data-testid='qdrant-enabled-switch']" ) as HTMLButtonElement | null; expect(toggleBtn).toBeTruthy(); + expect(toggleBtn?.disabled).toBe(true); + + // #11213: enabling is gated on a successful embedding search — validate first + const searchInput = container.querySelector( + "input[placeholder='qdrant.searchPlaceholder']" + ) as HTMLInputElement | null; + expect(searchInput).toBeTruthy(); + const setVal = Object.getOwnPropertyDescriptor( + window.HTMLInputElement.prototype, + "value" + )!.set!; + setVal.call(searchInput, "memory probe"); + searchInput!.dispatchEvent(new Event("input", { bubbles: true })); + const searchBtn = container.querySelector( + "[data-testid='qdrant-search-test']" + ) as HTMLButtonElement | null; + await act(async () => { + searchBtn?.click(); + }); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); + await act(async () => { toggleBtn?.click(); }); await act(async () => { await new Promise((r) => setTimeout(r, 50)); }); - const putCalls = fetchMock.mock.calls.filter( (c: [string, { method?: string }]) => typeof c[0] === "string" && c[0] === "/api/settings/qdrant" && c[1]?.method === "PUT" ); expect(putCalls.length).toBeGreaterThan(0); - }); + + const tutorial = container.querySelector( + "[data-testid='qdrant-setup-tutorial']", + ) as HTMLButtonElement | null; + expect(tutorial).toBeTruthy(); + await act(async () => { + tutorial?.click(); + }); + expect(container.querySelector("[role='dialog']")).toBeTruthy(); + expect(container.textContent).toContain("Rafa Martins"); }); it("test connection button calls /api/settings/qdrant/health", async () => { const fetchMock = vi.fn().mockImplementation((url: string) => { @@ -159,6 +196,9 @@ describe("QdrantConfigCard", () => { json: async () => ({ ok: true, latencyMs: 12 }), }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -218,7 +258,10 @@ describe("QdrantConfigCard", () => { }), }); } - return Promise.resolve({ ok: true, json: async () => ({}) }); + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } + return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -292,6 +335,9 @@ describe("QdrantConfigCard", () => { json: async () => ({ ok: true, deletedCount: 5 }), }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -349,6 +395,9 @@ describe("QdrantConfigCard", () => { json: async () => ({ ok: true, latencyMs: 2 }), }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -405,6 +454,9 @@ describe("QdrantConfigCard", () => { } return Promise.resolve({ ok: true, json: async () => ({ ok: true, latencyMs: 2 }) }); } + if (url === "/api/settings/qdrant/search") { + return Promise.resolve({ ok: true, json: async () => ({ ok: true, results: [] }) }); + } return Promise.resolve({ ok: true, json: async () => ({}) }); }); globalThis.fetch = fetchMock; @@ -427,6 +479,28 @@ describe("QdrantConfigCard", () => { "[data-testid='qdrant-enabled-switch']" ) as HTMLButtonElement | null; expect(toggleBtn).toBeTruthy(); + + // #11213: enabling is gated on a successful embedding search — validate first + const searchInput = container.querySelector( + "input[placeholder='qdrant.searchPlaceholder']" + ) as HTMLInputElement | null; + expect(searchInput).toBeTruthy(); + const setVal = Object.getOwnPropertyDescriptor( + window.HTMLInputElement.prototype, + "value" + )!.set!; + setVal.call(searchInput, "memory probe"); + searchInput!.dispatchEvent(new Event("input", { bubbles: true })); + const searchBtn = container.querySelector( + "[data-testid='qdrant-search-test']" + ) as HTMLButtonElement | null; + await act(async () => { + searchBtn?.click(); + }); + await act(async () => { + await new Promise((r) => setTimeout(r, 50)); + }); + await act(async () => { toggleBtn?.click(); });