Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ultrawiki): connect every capability-slot provider from inside the app

Ruben Lütkeb4fb9b719cb8
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index fa0df46d72..b4f4e83e88 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2154,13 +2154,35 @@ class UltraWikiConfig(BaseModel):
enabled: bool = False
db_backend: str = "sqlite" # "sqlite" (universal floor) | "postgres"
+ # The named storage preset behind ``db_backend`` — "sqlite" | "supabase" |
+ # "neon" | "postgres". Presentation only (jarvis.ultrawiki.provider_catalog
+ # maps it back to db_backend): it selects the card's help text, dashboard
+ # link and connect flow. Deliberately NOT a second functional enum, so the
+ # store keeps exactly two code paths (AP-4 / BUG-008).
+ storage_provider: str = "sqlite"
embedding_provider: str = "" # "ollama" | "gemini" | "openai" | "voyage" | "mistral" | "cohere"
embedding_model: str = ""
distill_provider: str = "" # empty = key-aware brain chain decides
distill_model: str = ""
- rerank_provider: str = "" # empty = rerank stage honestly skipped
+ rerank_provider: str = "" # "llm" | "voyage" | "cohere"; empty = stage skipped
+ rerank_model: str = "" # only for rerank_provider="llm"; empty = cheap tier
ollama_endpoint: str = "http://localhost:11434"
+ # -- ranking knobs (design: UltraWiki ranking pipeline, 2026-07-25) ------
+ # The absolute 0-10 relevance floor an UNSOLICITED surface (context
+ # injection, volunteered voice answers) must clear. Explicit searches --
+ # the Ask view, the REST route, the CLI -- never apply it: the user asked
+ # and sees the evidence. 0 disables the floor everywhere.
+ rerank_min_score: float = 4.0
+ # Per-leg RRF weights: score(d) = sum(weight / (60 + rank)). 1.0 each is
+ # the article's default; 0 silences a leg without removing it.
+ rrf_keyword_weight: float = 1.0
+ rrf_vector_weight: float = 1.0
+ # Age decay on the fused score: 0.5 ** (age_days / half_life). Stale
+ # answers lose when relevance is otherwise equal. 0 disables the decay
+ # (the epsilon-sized recency tiebreak still settles exact ties).
+ recency_half_life_days: float = 180.0
+
class WikiContextConfig(BaseModel):
"""Configuration for the wiki context injector (B5 Agent C).
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 7413baf470..d157b4ee70 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -721,14 +721,36 @@ def set_wiki_vault_root(vault_root: str, *, path: Path = DEFAULT_CONFIG_FILE) ->
#: lives in the secret chain under ``ultrawiki_db_url`` (AP-12).
ULTRAWIKI_SLOT_KEYS = (
"db_backend",
+ # Which named storage preset the user picked (sqlite / supabase / neon /
+ # postgres). Presentation over ``db_backend``: it decides the card's help
+ # text, dashboard link and connect flow, never how the store opens.
+ "storage_provider",
"embedding_provider",
"embedding_model",
"distill_provider",
"distill_model",
"rerank_provider",
+ "rerank_model",
+ # Ranking knobs of the read path (design: UltraWiki ranking pipeline).
+ "rerank_min_score",
+ "rrf_keyword_weight",
+ "rrf_vector_weight",
+ "recency_half_life_days",
"ollama_endpoint",
)
+#: Slot keys whose value is a NUMBER, not a string. They are written as TOML
+#: floats so a hand-read jarvis.toml shows ``rerank_min_score = 4.0`` rather
+#: than a quoted string that only happens to parse.
+ULTRAWIKI_NUMERIC_SLOT_KEYS = frozenset(
+ {
+ "rerank_min_score",
+ "rrf_keyword_weight",
+ "rrf_vector_weight",
+ "recency_half_life_days",
+ }
+)
+
def set_ultrawiki_enabled(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist the UltraWiki mode switch to ``[ultrawiki] enabled``.
@@ -759,6 +781,15 @@ def set_ultrawiki_slot(key: str, value: str, *, path: Path = DEFAULT_CONFIG_FILE
f"unknown [ultrawiki] slot key {key!r} "
f"(allowed: {', '.join(ULTRAWIKI_SLOT_KEYS)})"
)
+ if key in ULTRAWIKI_NUMERIC_SLOT_KEYS:
+ try:
+ numeric = float(value)
+ except (TypeError, ValueError) as exc:
+ raise ValueError(
+ f"[ultrawiki] {key} must be a number, got {value!r}"
+ ) from exc
+ _patch_table(path, "ultrawiki", key, numeric)
+ return
_patch_table(path, "ultrawiki", key, str(value))
diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
index b4eaf60df9..5f21691ec2 100644
--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/ApiKeysStep.test.tsx
@@ -1,4 +1,4 @@
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx
new file mode 100644
index 0000000000..9f2e22cab7
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.test.tsx
@@ -0,0 +1,303 @@
+/**
+ * SlotsPanel tests — the settings surface must let a user CONNECT, not just
+ * choose.
+ *
+ * The defect these guard against: the panel used to render provider dropdowns
+ * with no credential field anywhere, and told the user to go to the API-Keys
+ * view, which has no field for these slots either. So the assertions here are
+ * mostly about the presence of a real, writable credential input on the card
+ * of a provider that needs one — plus the two rules that make the slots safe:
+ * the storage preset must post a NAME (not the internal backend enum), and an
+ * embedding change must still pass through the re-embed warning.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";
+import { useEventStore } from "@/store/events";
+import type {
+ UltraWikiCatalog,
+ UltraWikiCatalogRow,
+ UltraWikiStatus,
+} from "@/lib/ultrawikiApi";
+
+function renderWithClient(node: React.ReactNode) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
+ });
+ return render(
+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,
+ );
+}
+
+function row(overrides: Partial<UltraWikiCatalogRow>): UltraWikiCatalogRow {
+ return {
+ id: "x",
+ slot: "embedding",
+ label: "X",
+ auth_mode: "api_key",
+ secret_keys: [],
+ dashboard_url: null,
+ credential_help: "help text",
+ default_model: "",
+ supports_base_url: false,
+ default_base_url: null,
+ recommended: false,
+ caution: null,
+ db_backend: null,
+ connection_hint: null,
+ ready: false,
+ reason: "",
+ selected: false,
+ secrets_set: {},
+ secret_shared_with: {},
+ ...overrides,
+ };
+}
+
+const CATALOG: UltraWikiCatalog = {
+ slots: {
+ storage: [
+ row({
+ id: "sqlite",
+ slot: "storage",
+ label: "SQLite — local file",
+ auth_mode: "none",
+ db_backend: "sqlite",
+ ready: true,
+ selected: true,
+ recommended: true,
+ }),
+ row({
+ id: "supabase",
+ slot: "storage",
+ label: "Supabase",
+ auth_mode: "managed_link",
+ secret_keys: ["ultrawiki_db_url", "supabase_access_token"],
+ db_backend: "postgres",
+ reason: "no connection string is saved yet",
+ secrets_set: { ultrawiki_db_url: false, supabase_access_token: false },
+ secret_shared_with: { ultrawiki_db_url: [], supabase_access_token: [] },
+ }),
+ row({
+ id: "neon",
+ slot: "storage",
+ label: "Neon",
+ auth_mode: "connection_string",
+ secret_keys: ["ultrawiki_db_url"],
+ db_backend: "postgres",
+ secrets_set: { ultrawiki_db_url: false },
+ secret_shared_with: { ultrawiki_db_url: [] },
+ }),
+ ],
+ embedding: [
+ row({
+ id: "ollama",
+ slot: "embedding",
+ label: "Ollama (local)",
+ auth_mode: "none",
+ default_model: "bge-m3",
+ supports_base_url: true,
+ default_base_url: "http://localhost:11434",
+ ready: true,
+ selected: true,
+ }),
+ row({
+ id: "voyage",
+ slot: "embedding",
+ label: "Voyage AI",
+ secret_keys: ["voyage_api_key"],
+ default_model: "voyage-3.5",
+ reason: "No Voyage AI API key is configured",
+ secrets_set: { voyage_api_key: false },
+ secret_shared_with: { voyage_api_key: [] },
+ }),
+ ],
+ distill: [
+ row({
+ id: "gemini",
+ slot: "distill",
+ label: "Google Gemini",
+ secret_keys: ["gemini_api_key"],
+ ready: true,
+ secrets_set: { gemini_api_key: true },
+ secret_shared_with: { gemini_api_key: ["Google Gemini"] },
+ }),
+ ],
+ rerank: [
+ row({
+ id: "llm",
+ slot: "rerank",
+ label: "Your chat providers",
+ auth_mode: "none",
+ ready: true,
+ }),
+ row({
+ id: "cohere",
+ slot: "rerank",
+ label: "Cohere",
+ secret_keys: ["cohere_api_key"],
+ secrets_set: { cohere_api_key: false },
+ secret_shared_with: { cohere_api_key: [] },
+ }),
+ ],
+ },
+ selected: {
+ storage: "sqlite",
+ embedding: "ollama",
+ distill: "",
+ rerank: "",
+ },
+ models: { embedding: "bge-m3", distill: "" },
+ ollama_endpoint: "http://localhost:11434",
+};
+
+const STATUS: UltraWikiStatus = {
+ enabled: true,
+ started: true,
+ db_backend: "sqlite",
+ backend_in_use: "sqlite",
+ slots: {},
+ counts: {},
+ pipeline: { running: false, processed: {} },
+ sources: [],
+ jobs: [],
+ search_legs: {},
+ degradations: [],
+};
+
+let putBodies: unknown[] = [];
+
+function installFetchMock(overrides: Record<string, () => Response> = {}) {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ for (const [prefix, make] of Object.entries(overrides)) {
+ if (url.startsWith(prefix)) return make();
+ }
+ if (url.startsWith("/api/ultrawiki/catalog")) {
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => CATALOG,
+ } as Response;
+ }
+ if (url.startsWith("/api/ultrawiki/settings")) {
+ putBodies.push(JSON.parse(String(init?.body ?? "{}")));
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({
+ ok: true,
+ changed: [],
+ persisted: true,
+ reembed_started: false,
+ }),
+ } as Response;
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ },
+ );
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return fetchMock;
+}
+
+describe("SlotsPanel", () => {
+ beforeEach(() => {
+ putBodies = [];
+ useEventStore.setState({ toasts: [] });
+ installFetchMock();
+ });
+
+ afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ });
+
+ it("gives every credentialed provider a key field on its own card", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ // Voyage embeddings and Cohere rerank were listed but unreachable before:
+ // no input existed anywhere in the app for either key.
+ await waitFor(() => {
+ expect(screen.getByLabelText("Enter voyage_api_key")).toBeDefined();
+ });
+ expect(screen.getByLabelText("Enter cohere_api_key")).toBeDefined();
+ // Neon's connection string is entered here too, not in a different view.
+ expect(screen.getByLabelText("Enter ultrawiki_db_url")).toBeDefined();
+ });
+
+ it("shows no key field for a keyless local provider", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ await screen.findByTestId("ultrawiki-card-embedding-ollama");
+ // Ollama runs without credentials; a password box there would be a lie.
+ expect(screen.queryByLabelText("Enter ollama_api_key")).toBeNull();
+ });
+
+ it("posts the storage preset NAME, never the internal backend enum", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ fireEvent.click(await screen.findByTestId("ultrawiki-use-storage-neon"));
+ await waitFor(() => expect(putBodies).toHaveLength(1));
+ // The two-value db_backend is derived server-side, so the UI cannot
+ // desync from it (AP-4 / BUG-008).
+ expect(putBodies[0]).toEqual({ storage_provider: "neon" });
+ });
+
+ it("surfaces the honest not-ready reason on the card", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ const reason = await screen.findByTestId(
+ "ultrawiki-reason-embedding-voyage",
+ );
+ expect(reason.textContent).toContain("No Voyage AI API key is configured");
+ });
+
+ it("warns before re-embedding when the embedding provider changes", async () => {
+ installFetchMock({
+ "/api/ultrawiki/settings": () =>
+ ({
+ ok: false,
+ status: 409,
+ statusText: "Conflict",
+ json: async () => ({
+ detail: { message: "vector spaces differ", vector_items: 412 },
+ }),
+ }) as Response,
+ });
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ fireEvent.click(await screen.findByTestId("ultrawiki-use-embedding-voyage"));
+ // The corpus is re-embedded from scratch, so the count is named BEFORE
+ // anything is dropped (D-3).
+ const dialog = await screen.findByTestId("ultrawiki-reembed-dialog");
+ expect(dialog.textContent).toContain("412");
+ });
+
+ it("offers the guided Supabase sign-in instead of a raw URI box", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ const connect = await screen.findByTestId("ultrawiki-supabase-connect");
+ expect(connect).toBeDefined();
+ // The Supabase card must NOT render the bare connection-string field: the
+ // pooler hostname is not derivable, so hand-typing it is a trap.
+ const links = screen.getAllByRole("link", { name: /supabase/i });
+ expect(links.length).toBeGreaterThan(0);
+ });
+
+ it("treats automatic distillation and rerank-off as real choices", async () => {
+ renderWithClient(<SlotsPanel status={STATUS} onChanged={() => {}} />);
+ const auto = await screen.findByTestId("ultrawiki-card-distill-auto");
+ expect(auto.getAttribute("data-selected")).toBe("true");
+ expect(
+ screen.getByTestId("ultrawiki-card-rerank-off").getAttribute(
+ "data-selected",
+ ),
+ ).toBe("true");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
index 48f8ac5105..7c7d24a862 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SlotsPanel.tsx
@@ -1,17 +1,35 @@
/**
- * UltraWiki capability-slot settings (design doc 04, decision D-2) — the
- * provider-slot cards modeled on the API-Keys section: current value, honest
- * ready/reason state, a real-call Test button per slot
- * (`POST /api/ultrawiki/test/{slot}`), and guarded changes via
- * `PUT /api/ultrawiki/settings`.
+ * UltraWiki capability-slot settings — the four slots (storage, embedding,
+ * distillation, rerank) rendered as provider CARDS, in the same visual and
+ * behavioural language as the API-Keys view.
*
- * The embedding change is the deliberate one (D-3): when vectors already
- * exist the backend answers 409 with the vector count, and this panel shows
- * the re-embed warning dialog before resending with `confirm_reembed=true`.
- * The Postgres connection string is a secret (`ultrawiki_db_url`) and is
- * never entered here — the card links to the API-Keys view instead.
+ * What changed and why (2026-07-25): the previous version showed a dropdown
+ * per slot and, for anything needing a credential, the sentence "add it in the
+ * API-Keys view". That view has no field for these slots, so Voyage, Mistral,
+ * Cohere and every Postgres store were listed but impossible to connect from
+ * inside the app — the exact out-of-app setup step the in-app-recoverable
+ * mandate forbids (§3, AP-23). Every provider now carries its credential
+ * widget on its own card, using the SAME `ApiKeyForm` component the API-Keys
+ * view uses, so the two screens cannot drift apart.
+ *
+ * Slot rules that are deliberate, not incidental:
+ *
+ * - **Embedding has no automatic option and no cross-provider fallback (D-3).**
+ * The (provider, model) pair pins the vector space of the whole corpus, so
+ * changing it re-embeds everything — the backend answers 409 with the vector
+ * count and this panel shows the warning dialog before confirming.
+ * - **Distillation and rerank DO cross provider families (AP-22)** and default
+ * to "automatic" / "off": leaving them unset is a working configuration, not
+ * an unfinished one.
+ * - **Storage always has a working floor.** SQLite needs nothing; a cloud
+ * preset that is not connected yet degrades to it with an honest line rather
+ * than breaking the wiki.
+ * - **The relevance floor lives on the rerank slot**, with the stage that
+ * produces the grade it gates on. It governs only what UltraWiki volunteers
+ * unasked; an explicit search always shows everything.
*/
import { useState } from "react";
+import { useQuery } from "@tanstack/react-query";
import {
Boxes,
Database,
@@ -29,17 +47,23 @@ import {
SettingsField,
settingsInputCls,
} from "@/views/settings/SettingsBlock";
+import { SupabaseConnect } from "@/components/ultrawiki/SupabaseConnect";
+import {
+ StateChip,
+ UltraProviderCard,
+} from "@/components/ultrawiki/UltraProviderCard";
import {
+ fetchUltraWikiCatalog,
reembedGateOf,
testUltraWikiSlot,
updateUltraWikiSettings,
+ type UltraWikiCatalog,
type UltraWikiSettingsBody,
+ type UltraWikiSlotName,
type UltraWikiSlotTestResult,
type UltraWikiStatus,
} from "@/lib/ultrawikiApi";
-type SlotName = "embedding" | "distill" | "rerank" | "storage";
-
export function SlotsPanel({
status,
onChanged,
@@ -49,7 +73,12 @@ export function SlotsPanel({
}): JSX.Element {
const t = useT();
const pushToast = useEventStore((s) => s.pushToast);
- const setActiveSection = useEventStore((s) => s.setActiveSection);
+
+ const catalogQuery = useQuery({
+ queryKey: ["ultrawiki", "catalog"],
+ queryFn: fetchUltraWikiCatalog,
+ staleTime: 5_000,
+ });
const [pending, setPending] = useState(false);
const [reembedGate, setReembedGate] = useState<{
@@ -57,22 +86,11 @@ export function SlotsPanel({
vectorItems: number;
} | null>(null);
- // Local edits fall back to the server state until the user touches them
- // (the WikiProviderCard controlled-value idiom).
- const [dbBackend, setDbBackend] = useState<string | null>(null);
- const [embeddingProvider, setEmbeddingProvider] = useState<string | null>(
- null,
- );
- const [embeddingModel, setEmbeddingModel] = useState<string | null>(null);
- const [distillProvider, setDistillProvider] = useState<string | null>(null);
- const [rerankProvider, setRerankProvider] = useState<string | null>(null);
-
- const slots = status.slots;
- const dbValue = dbBackend ?? status.db_backend ?? "sqlite";
- const embeddingValue = embeddingProvider ?? slots.embedding?.provider ?? "";
- const embeddingModelValue = embeddingModel ?? slots.embedding?.model ?? "";
- const distillValue = distillProvider ?? slots.distill?.provider ?? "";
- const rerankValue = rerankProvider ?? slots.rerank?.provider ?? "";
+ const catalog = catalogQuery.data ?? null;
+ const refresh = () => {
+ void catalogQuery.refetch();
+ onChanged();
+ };
async function apply(body: UltraWikiSettingsBody) {
setPending(true);
@@ -84,25 +102,17 @@ export function SlotsPanel({
? t("ultrawiki.slots.reembed_started")
: t("ultrawiki.slots.applied"),
);
- setDbBackend(null);
- setEmbeddingProvider(null);
- setEmbeddingModel(null);
- setDistillProvider(null);
- setRerankProvider(null);
- onChanged();
+ refresh();
} catch (e) {
- // The guarded embedding change: 409 carries the vector count; surface
- // the warning dialog instead of a bare error (D-3).
+ // The guarded embedding change: 409 carries the vector count, so the
+ // user is warned about the re-embed BEFORE it starts (D-3).
const gate = reembedGateOf(e);
if (gate) {
setReembedGate({ body, vectorItems: gate.vector_items });
} else {
pushToast(
"error",
- t("ultrawiki.slots.apply_failed").replace(
- "{0}",
- (e as Error).message,
- ),
+ t("ultrawiki.slots.apply_failed").replace("{0}", (e as Error).message),
);
}
} finally {
@@ -110,331 +120,581 @@ export function SlotsPanel({
}
}
+ if (catalogQuery.isLoading) {
+ return (
+ <div
+ className="p-6 text-sm text-muted-foreground"
+ data-testid="ultrawiki-slots-loading"
+ >
+ {t("ultrawiki.slots.loading")}
+ </div>
+ );
+ }
+
+ if (!catalog) {
+ return (
+ <div className="p-4">
+ <div
+ role="alert"
+ className="rounded-md border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive"
+ data-testid="ultrawiki-slots-unavailable"
+ >
+ {t("ultrawiki.slots.catalog_unavailable")}
+ </div>
+ </div>
+ );
+ }
+
+ const shared = { catalog, status, pending, apply, refresh };
+
return (
<div className="space-y-4 p-4" data-testid="ultrawiki-slots-panel">
<h3 className="text-sm font-medium text-foreground">
{t("ultrawiki.slots.title")}
</h3>
- {/* Storage */}
- <SettingsBlock
- icon={Database}
- title={t("ultrawiki.slots.storage_title")}
- description={t("ultrawiki.slots.storage_desc")}
- headerRight={<SlotTestControl slot="storage" />}
- >
- <div className="space-y-3">
- <SettingsField label={t("ultrawiki.slots.storage_title")}>
- <select
- value={dbValue}
- onChange={(e) => setDbBackend(e.target.value)}
- className={settingsInputCls}
- data-testid="ultrawiki-storage-select"
+ <StorageSection {...shared} />
+ <EmbeddingSection {...shared} />
+ <DistillSection {...shared} />
+ <RerankSection {...shared} />
+
+ {reembedGate && (
+ <ReembedDialog
+ vectorItems={reembedGate.vectorItems}
+ onCancel={() => setReembedGate(null)}
+ onConfirm={() => {
+ const body = { ...reembedGate.body, confirm_reembed: true };
+ setReembedGate(null);
+ void apply(body);
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+interface SectionProps {
+ catalog: UltraWikiCatalog;
+ status: UltraWikiStatus;
+ pending: boolean;
+ apply: (body: UltraWikiSettingsBody) => Promise<void>;
+ refresh: () => void;
+}
+
+// ---------------------------------------------------------------------------
+// Storage
+// ---------------------------------------------------------------------------
+
+function StorageSection({
+ catalog,
+ status,
+ pending,
+ apply,
+ refresh,
+}: SectionProps): JSX.Element {
+ const t = useT();
+ const rows = catalog.slots.storage ?? [];
+ return (
+ <SettingsBlock
+ icon={Database}
+ title={t("ultrawiki.slots.storage_title")}
+ description={t("ultrawiki.slots.storage_desc")}
+ headerRight={<SlotTestControl slot="storage" />}
+ >
+ <div className="space-y-3">
+ {status.backend_in_use && (
+ <p className="text-[11px] text-muted-foreground">
+ {t("ultrawiki.slots.in_use").replace("{0}", status.backend_in_use)}
+ </p>
+ )}
+ <CardGrid>
+ {rows.map((row) => (
+ <UltraProviderCard
+ key={row.id}
+ row={row}
+ busy={pending}
+ onSelect={() => void apply({ storage_provider: row.id })}
+ onCredentialChanged={refresh}
+ footer={
+ row.connection_hint ? (
+ <p className="break-all font-mono text-[10px] text-muted-foreground">
+ {row.connection_hint}
+ </p>
+ ) : undefined
+ }
>
- <option value="sqlite">
- {t("ultrawiki.slots.storage_sqlite")}
- </option>
- <option value="postgres">
- {t("ultrawiki.slots.storage_postgres")}
- </option>
- </select>
- </SettingsField>
- {status.backend_in_use && (
- <p className="text-[11px] text-muted-foreground">
- {t("ultrawiki.slots.in_use").replace(
- "{0}",
- status.backend_in_use,
+ {row.id === "supabase" && (
+ <SupabaseConnect row={row} onChanged={refresh} />
)}
- </p>
- )}
- {dbValue === "postgres" && (
- <div className="space-y-2 rounded-lg border border-border/60 bg-muted/20 p-3 text-xs text-muted-foreground">
- {/* Connection strings are secrets (AP-2/AP-12): saved as
- 'ultrawiki_db_url' via the secrets surface, never typed here. */}
- <p>{t("ultrawiki.slots.storage_postgres_hint")}</p>
- <Button
- variant="outline"
- size="sm"
- onClick={() => setActiveSection("apikeys")}
- data-testid="ultrawiki-open-apikeys"
- >
- {t("ultrawiki.slots.open_api_keys")}
- </Button>
- </div>
- )}
- <ApplyButton
- pending={pending}
- onClick={() => void apply({ db_backend: dbValue })}
- testId="ultrawiki-storage-apply"
- />
- </div>
- </SettingsBlock>
-
- {/* Embedding */}
- <SettingsBlock
- icon={Boxes}
- title={t("ultrawiki.slots.embedding_title")}
- description={t("ultrawiki.slots.embedding_desc")}
- headerRight={<SlotTestControl slot="embedding" />}
- >
- <div className="space-y-3">
- <SlotHealthLine
- ready={slots.embedding?.ready}
- reason={slots.embedding?.reason}
- current={
- slots.embedding?.provider
- ? `${slots.embedding.provider}${slots.embedding.model ? ` · ${slots.embedding.model}` : ""}`
- : ""
- }
+ </UltraProviderCard>
+ ))}
+ </CardGrid>
+ {/* A store change only takes effect when the store is reopened; saying
+ so beats a user wondering why their pages are still in SQLite. */}
+ <p className="text-[11px] text-muted-foreground">
+ {t("ultrawiki.slots.storage_restart_hint")}
+ </p>
+ </div>
+ </SettingsBlock>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Embedding
+// ---------------------------------------------------------------------------
+
+function EmbeddingSection({
+ catalog,
+ status,
+ pending,
+ apply,
+ refresh,
+}: SectionProps): JSX.Element {
+ const t = useT();
+ const rows = catalog.slots.embedding ?? [];
+ const [model, setModel] = useState<string | null>(null);
+ const [endpoint, setEndpoint] = useState<string | null>(null);
+ const modelValue = model ?? catalog.models.embedding;
+ const endpointValue = endpoint ?? catalog.ollama_endpoint;
+
+ return (
+ <SettingsBlock
+ icon={Boxes}
+ title={t("ultrawiki.slots.embedding_title")}
+ description={t("ultrawiki.slots.embedding_desc")}
+ headerRight={<SlotTestControl slot="embedding" />}
+ >
+ <div className="space-y-3">
+ <SlotProvenance slot="embedding" via={status.slots.embedding?.via} />
+ <CardGrid>
+ {rows.map((row) => (
+ <UltraProviderCard
+ key={row.id}
+ row={row}
+ busy={pending}
+ // The model travels WITH the provider switch: applying them
+ // separately would trigger the expensive re-embed twice.
+ onSelect={() =>
+ void apply({
+ embedding_provider: row.id,
+ embedding_model: row.default_model,
+ })
+ }
+ onCredentialChanged={refresh}
+ >
+ {row.selected && (
+ <div className="space-y-3">
+ <SettingsField label={t("ultrawiki.slots.model_label")}>
+ <input
+ type="text"
+ value={modelValue}
+ onChange={(e) => setModel(e.target.value)}
+ placeholder={row.default_model}
+ className={settingsInputCls}
+ data-testid="ultrawiki-embedding-model-input"
+ />
+ </SettingsField>
+ {row.supports_base_url && (
+ <SettingsField label={t("ultrawiki.slots.server_url_label")}>
+ <input
+ type="url"
+ value={endpointValue}
+ onChange={(e) => setEndpoint(e.target.value)}
+ placeholder={row.default_base_url ?? ""}
+ className={settingsInputCls}
+ data-testid="ultrawiki-ollama-endpoint-input"
+ />
+ </SettingsField>
+ )}
+ <Button
+ size="sm"
+ disabled={pending}
+ onClick={() =>
+ void apply({
+ embedding_provider: row.id,
+ embedding_model: modelValue,
+ ...(row.supports_base_url
+ ? { ollama_endpoint: endpointValue }
+ : {}),
+ })
+ }
+ data-testid="ultrawiki-embedding-apply"
+ >
+ {pending && (
+ <Loader2
+ className="mr-1 h-3.5 w-3.5 animate-spin"
+ aria-hidden
+ />
+ )}
+ {t("ultrawiki.slots.save_model")}
+ </Button>
+ </div>
+ )}
+ </UltraProviderCard>
+ ))}
+ </CardGrid>
+ <p className="text-[11px] text-muted-foreground">
+ {t("ultrawiki.slots.embedding_lock_hint")}
+ </p>
+ </div>
+ </SettingsBlock>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Distillation
+// ---------------------------------------------------------------------------
+
+function DistillSection({
+ catalog,
+ status,
+ pending,
+ apply,
+ refresh,
+}: SectionProps): JSX.Element {
+ const t = useT();
+ const rows = catalog.slots.distill ?? [];
+ const [model, setModel] = useState<string | null>(null);
+ const modelValue = model ?? catalog.models.distill;
+ const automatic = !catalog.selected.distill;
+
+ return (
+ <SettingsBlock
+ icon={FlaskConical}
+ title={t("ultrawiki.slots.distill_title")}
+ description={t("ultrawiki.slots.distill_desc")}
+ headerRight={<SlotTestControl slot="distill" />}
+ >
+ <div className="space-y-3">
+ <SlotProvenance slot="distill" via={status.slots.distill?.via} />
+ <CardGrid>
+ <SlotDefaultCard
+ selected={automatic}
+ busy={pending}
+ title={t("ultrawiki.slots.distill_auto")}
+ body={t("ultrawiki.slots.distill_auto_desc")}
+ onSelect={() => void apply({ distill_provider: "" })}
+ testId="ultrawiki-card-distill-auto"
/>
- <div className="grid gap-4 sm:grid-cols-2">
- <SettingsField label={t("ultrawiki.slots.provider_label")}>
- <select
- value={embeddingValue}
- onChange={(e) => {
- setEmbeddingProvider(e.target.value);
- setEmbeddingModel("");
- }}
- className={settingsInputCls}
- data-testid="ultrawiki-embedding-select"
- >
- {(slots.embedding?.available ?? []).map((option) => (
- <option key={option.name} value={option.name}>
- {option.name}
- {!option.ready
- ? ` (${t("ultrawiki.slots.not_ready_suffix")})`
- : ""}
- </option>
- ))}
- </select>
- </SettingsField>
- <SettingsField label={t("ultrawiki.slots.model_label")}>
- <input
- type="text"
- value={embeddingModelValue}
- onChange={(e) => setEmbeddingModel(e.target.value)}
- placeholder={t(
- "ultrawiki.slots.model_default_placeholder",
- ).replace(
- "{0}",
- (slots.embedding?.available ?? []).find(
- (o) => o.name === embeddingValue,
- )?.default_model ?? "",
- )}
- className={settingsInputCls}
- data-testid="ultrawiki-embedding-model-input"
- />
- </SettingsField>
- </div>
- <ApplyButton
- pending={pending}
- onClick={() =>
- void apply({
- embedding_provider: embeddingValue,
- embedding_model: embeddingModelValue,
- })
+ {rows.map((row) => (
+ <UltraProviderCard
+ key={row.id}
+ row={row}
+ busy={pending}
+ onSelect={() => void apply({ distill_provider: row.id })}
+ onCredentialChanged={refresh}
+ >
+ {row.selected && (
+ <div className="space-y-2">
+ <SettingsField label={t("ultrawiki.slots.model_label")}>
+ <input
+ type="text"
+ value={modelValue}
+ onChange={(e) => setModel(e.target.value)}
+ placeholder={
+ row.default_model ||
+ t("ultrawiki.slots.model_cheap_default")
+ }
+ className={settingsInputCls}
+ data-testid="ultrawiki-distill-model-input"
+ />
+ </SettingsField>
+ <Button
+ size="sm"
+ disabled={pending}
+ onClick={() =>
+ void apply({
+ distill_provider: row.id,
+ distill_model: modelValue,
+ })
+ }
+ data-testid="ultrawiki-distill-apply"
+ >
+ {t("ultrawiki.slots.save_model")}
+ </Button>
+ </div>
+ )}
+ </UltraProviderCard>
+ ))}
+ </CardGrid>
+ </div>
+ </SettingsBlock>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Rerank
+// ---------------------------------------------------------------------------
+
+function RerankSection({
+ catalog,
+ status,
+ pending,
+ apply,
+ refresh,
+}: SectionProps): JSX.Element {
+ const t = useT();
+ const rows = catalog.slots.rerank ?? [];
+ const off = !catalog.selected.rerank;
+ const [rerankModel, setRerankModel] = useState<string | null>(null);
+ const [floor, setFloor] = useState<string | null>(null);
+ const rerankModelValue = rerankModel ?? status.slots.rerank?.model ?? "";
+ const floorValue =
+ floor ?? String(status.slots.rerank?.ranking?.rerank_min_score ?? 4);
+
+ return (
+ <SettingsBlock
+ icon={ListOrdered}
+ title={t("ultrawiki.slots.rerank_title")}
+ description={t("ultrawiki.slots.rerank_desc")}
+ headerRight={<SlotTestControl slot="rerank" />}
+ >
+ <div className="space-y-3">
+ <SlotProvenance slot="rerank" via={status.slots.rerank?.via} />
+ <CardGrid>
+ <SlotDefaultCard
+ selected={off}
+ busy={pending}
+ title={t("ultrawiki.slots.rerank_off")}
+ body={t("ultrawiki.slots.rerank_off_desc")}
+ onSelect={() =>
+ void apply({ rerank_provider: "", rerank_model: "" })
}
- testId="ultrawiki-embedding-apply"
- />
- </div>
- </SettingsBlock>
-
- {/* Distillation */}
- <SettingsBlock
- icon={FlaskConical}
- title={t("ultrawiki.slots.distill_title")}
- description={t("ultrawiki.slots.distill_desc")}
- headerRight={<SlotTestControl slot="distill" />}
- >
- <div className="space-y-3">
- <SlotHealthLine
- ready={slots.distill?.ready}
- reason={slots.distill?.reason}
- current={slots.distill?.provider ?? ""}
+ testId="ultrawiki-card-rerank-off"
/>
- <SettingsField label={t("ultrawiki.slots.provider_label")}>
- <select
- value={distillValue}
- onChange={(e) => setDistillProvider(e.target.value)}
- className={settingsInputCls}
- data-testid="ultrawiki-distill-select"
+ {rows.map((row) => (
+ <UltraProviderCard
+ key={row.id}
+ row={row}
+ busy={pending}
+ onSelect={() =>
+ void apply({
+ rerank_provider: row.id,
+ // The vendor cross-encoders pin their own model; only the
+ // chat-graded backend takes one from the user.
+ rerank_model: row.id === "llm" ? rerankModelValue : "",
+ })
+ }
+ onCredentialChanged={refresh}
>
- <option value="">{t("ultrawiki.slots.distill_auto")}</option>
- {(slots.distill?.chain ?? [])
- .filter((name) => name !== "")
- .map((name) => (
- <option key={name} value={name}>
- {name}
- </option>
- ))}
- {!(slots.distill?.chain ?? []).includes("ollama") && (
- <option value="ollama">ollama</option>
+ {row.selected && row.id === "llm" && (
+ <div className="space-y-2">
+ <SettingsField label={t("ultrawiki.slots.model_label")}>
+ <input
+ type="text"
+ value={rerankModelValue}
+ onChange={(e) => setRerankModel(e.target.value)}
+ placeholder={t("ultrawiki.slots.rerank_model_placeholder")}
+ className={settingsInputCls}
+ data-testid="ultrawiki-rerank-model-input"
+ />
+ </SettingsField>
+ <Button
+ size="sm"
+ disabled={pending}
+ onClick={() =>
+ void apply({
+ rerank_provider: row.id,
+ rerank_model: rerankModelValue,
+ })
+ }
+ data-testid="ultrawiki-rerank-apply"
+ >
+ {t("ultrawiki.slots.save_model")}
+ </Button>
+ </div>
)}
- </select>
+ </UltraProviderCard>
+ ))}
+ </CardGrid>
+
+ {/* The relevance floor lives with the stage that produces the grade it
+ gates on. Explicit searches always show everything; this only
+ governs what UltraWiki volunteers on its own. */}
+ <div className="space-y-2 rounded-lg border border-border/60 bg-muted/20 p-3">
+ <SettingsField label={t("ultrawiki.slots.floor_label")}>
+ <input
+ type="number"
+ min={0}
+ max={10}
+ step={0.5}
+ value={floorValue}
+ onChange={(e) => setFloor(e.target.value)}
+ className={settingsInputCls}
+ data-testid="ultrawiki-rerank-floor-input"
+ />
</SettingsField>
<p className="text-[11px] text-muted-foreground">
- {(slots.distill?.chain ?? []).length > 0
- ? t("ultrawiki.slots.distill_chain").replace(
- "{0}",
- (slots.distill?.chain ?? []).join(", "),
- )
- : t("ultrawiki.slots.distill_chain_empty")}
+ {t("ultrawiki.slots.floor_hint")}
</p>
- <ApplyButton
- pending={pending}
- onClick={() => void apply({ distill_provider: distillValue })}
- testId="ultrawiki-distill-apply"
- />
- </div>
- </SettingsBlock>
-
- {/* Rerank */}
- <SettingsBlock
- icon={ListOrdered}
- title={t("ultrawiki.slots.rerank_title")}
- description={t("ultrawiki.slots.rerank_desc")}
- headerRight={<SlotTestControl slot="rerank" />}
- >
- <div className="space-y-3">
- <SlotHealthLine
- ready={slots.rerank?.ready}
- reason={slots.rerank?.reason}
- current={slots.rerank?.provider ?? ""}
- />
- <SettingsField label={t("ultrawiki.slots.provider_label")}>
- <select
- value={rerankValue}
- onChange={(e) => setRerankProvider(e.target.value)}
- className={settingsInputCls}
- data-testid="ultrawiki-rerank-select"
- >
- <option value="">{t("ultrawiki.slots.rerank_off")}</option>
- {(slots.rerank?.available ?? []).map((option) => (
- <option key={option.name} value={option.name}>
- {option.name}
- {!option.ready
- ? ` (${t("ultrawiki.slots.not_ready_suffix")})`
- : ""}
- </option>
- ))}
- </select>
- </SettingsField>
- <ApplyButton
- pending={pending}
- onClick={() => void apply({ rerank_provider: rerankValue })}
- testId="ultrawiki-rerank-apply"
- />
- </div>
- </SettingsBlock>
-
- {reembedGate && (
- <div
- className="fixed inset-0 z-[70] flex items-center justify-center bg-background/80 backdrop-blur-sm"
- role="dialog"
- aria-modal="true"
- aria-labelledby="ultrawiki-reembed-title"
- data-testid="ultrawiki-reembed-dialog"
- onClick={(e) => {
- if (e.target === e.currentTarget) setReembedGate(null);
- }}
- >
- <div
- className="w-full max-w-md rounded-2xl border border-border bg-card p-6 shadow-2xl"
- onClick={(e) => e.stopPropagation()}
+ <Button
+ size="sm"
+ disabled={pending}
+ onClick={() => void apply({ rerank_min_score: Number(floorValue) })}
+ data-testid="ultrawiki-rerank-floor-apply"
>
- <h2
- id="ultrawiki-reembed-title"
- className="text-base font-semibold text-foreground"
- >
- {t("ultrawiki.slots.reembed_title")}
- </h2>
- <p className="mt-2 text-sm leading-relaxed text-muted-foreground">
- {t("ultrawiki.slots.reembed_body").replace(
- "{0}",
- String(reembedGate.vectorItems),
- )}
- </p>
- <div className="mt-4 flex justify-end gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => setReembedGate(null)}
- >
- {t("ultrawiki.mode.cancel")}
- </Button>
- <Button
- size="sm"
- onClick={() => {
- const body = {
- ...reembedGate.body,
- confirm_reembed: true,
- };
- setReembedGate(null);
- void apply(body);
- }}
- data-testid="ultrawiki-reembed-confirm"
- >
- {t("ultrawiki.slots.reembed_confirm").replace(
- "{0}",
- String(reembedGate.vectorItems),
- )}
- </Button>
- </div>
- </div>
+ {t("ultrawiki.slots.apply")}
+ </Button>
</div>
- )}
- </div>
+ </div>
+ </SettingsBlock>
);
}
-function ApplyButton({
- pending,
- onClick,
+// ---------------------------------------------------------------------------
+// Shared pieces
+// ---------------------------------------------------------------------------
+
+function CardGrid({ children }: { children: React.ReactNode }): JSX.Element {
+ return <div className="grid gap-3 lg:grid-cols-2">{children}</div>;
+}
+
+/**
+ * Key-free provenance: WHICH credential or endpoint actually makes this slot
+ * work right now. With cross-family fallback chains, the provider a user
+ * picked and the one answering can differ — saying so turns "why is this
+ * still working / not working" into a one-line answer.
+ */
+function SlotProvenance({
+ slot,
+ via,
+}: {
+ slot: UltraWikiSlotName;
+ via: string | undefined;
+}): JSX.Element | null {
+ const t = useT();
+ if (!via) return null;
+ return (
+ <p
+ className="text-[11px] text-muted-foreground"
+ data-testid={`ultrawiki-slot-via-${slot}`}
+ >
+ {t("ultrawiki.slots.via").replace("{0}", via)}
+ </p>
+ );
+}
+
+/**
+ * The "no provider" card — Automatic for distillation, Off for rerank.
+ *
+ * A first-class card rather than an empty dropdown entry, because for both
+ * slots it is a legitimate and often correct choice: distillation without a
+ * pin uses whatever credential the user actually has, and search works fine
+ * with the plain fusion order.
+ */
+function SlotDefaultCard({
+ selected,
+ busy,
+ title,
+ body,
+ onSelect,
testId,
}: {
- pending: boolean;
- onClick: () => void;
+ selected: boolean;
+ busy: boolean;
+ title: string;
+ body: string;
+ onSelect: () => void;
testId: string;
}): JSX.Element {
const t = useT();
return (
- <Button size="sm" onClick={onClick} disabled={pending} data-testid={testId}>
- {pending && (
- <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />
+ <div
+ onClick={() => {
+ if (!selected) onSelect();
+ }}
+ data-testid={testId}
+ data-selected={selected ? "true" : "false"}
+ className={cn(
+ "card-outline space-y-3 p-4 transition-colors",
+ selected
+ ? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"
+ : "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]",
)}
- {t(pending ? "ultrawiki.slots.applying" : "ultrawiki.slots.apply")}
- </Button>
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-display text-sm font-semibold tracking-tight">
+ {title}
+ </span>
+ {selected && (
+ <StateChip tone="active">
+ {t("ultrawiki.card.chip_in_use")}
+ </StateChip>
+ )}
+ </div>
+ </div>
+ <Button
+ size="sm"
+ variant={selected ? "secondary" : "outline"}
+ disabled={selected || busy}
+ onClick={onSelect}
+ >
+ {t(selected ? "ultrawiki.card.in_use" : "ultrawiki.card.use")}
+ </Button>
+ </div>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">{body}</p>
+ </div>
);
}
-/** Current value + honest ready/reason line (calm when ready, amber when not). */
-function SlotHealthLine({
- ready,
- reason,
- current,
+function ReembedDialog({
+ vectorItems,
+ onCancel,
+ onConfirm,
}: {
- ready: boolean | undefined;
- reason: string | undefined;
- current: string;
-}): JSX.Element | null {
+ vectorItems: number;
+ onCancel: () => void;
+ onConfirm: () => void;
+}): JSX.Element {
const t = useT();
- if (!current && !reason) return null;
return (
- <div className="space-y-0.5 text-[11px]">
- {current && (
- <p className="text-muted-foreground">
- {t("ultrawiki.slots.current").replace("{0}", current)}
+ <div
+ className="fixed inset-0 z-[70] flex items-center justify-center bg-background/80 backdrop-blur-sm"
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="ultrawiki-reembed-title"
+ data-testid="ultrawiki-reembed-dialog"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) onCancel();
+ }}
+ >
+ <div
+ className="w-full max-w-md rounded-2xl border border-border bg-card p-6 shadow-2xl"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <h2
+ id="ultrawiki-reembed-title"
+ className="text-base font-semibold text-foreground"
+ >
+ {t("ultrawiki.slots.reembed_title")}
+ </h2>
+ <p className="mt-2 text-sm leading-relaxed text-muted-foreground">
+ {t("ultrawiki.slots.reembed_body").replace("{0}", String(vectorItems))}
</p>
- )}
- {ready === false && reason && (
- <p className="text-[#ffb84d]">{reason}</p>
- )}
+ <div className="mt-4 flex justify-end gap-2">
+ <Button variant="outline" size="sm" onClick={onCancel}>
+ {t("ultrawiki.mode.cancel")}
+ </Button>
+ <Button
+ size="sm"
+ onClick={onConfirm}
+ data-testid="ultrawiki-reembed-confirm"
+ >
+ {t("ultrawiki.slots.reembed_confirm").replace(
+ "{0}",
+ String(vectorItems),
+ )}
+ </Button>
+ </div>
+ </div>
</div>
);
}
-/** Per-slot real-call Test button + result chip (ApiKeysView test idiom). */
-function SlotTestControl({ slot }: { slot: SlotName }): JSX.Element {
+/** Per-slot real-call Test button + result chip (the API-Keys test idiom). */
+function SlotTestControl({ slot }: { slot: UltraWikiSlotName }): JSX.Element {
const t = useT();
const [testing, setTesting] = useState(false);
const [result, setResult] = useState<UltraWikiSlotTestResult | null>(null);
@@ -465,7 +725,9 @@ function SlotTestControl({ slot }: { slot: SlotName }): JSX.Element {
data-testid={`ultrawiki-test-result-${slot}`}
data-ok={result.ok ? "true" : "false"}
>
- {t(result.ok ? "ultrawiki.slots.test_ok" : "ultrawiki.slots.test_failed")}
+ {t(
+ result.ok ? "ultrawiki.slots.test_ok" : "ultrawiki.slots.test_failed",
+ )}
{" · "}
{result.detail}
</span>
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx
new file mode 100644
index 0000000000..1f6e12418e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SupabaseConnect.tsx
@@ -0,0 +1,242 @@
+/**
+ * The guided Supabase link inside the UltraWiki storage card.
+ *
+ * Three steps, in the order a person actually does them:
+ *
+ * 1. **Sign in** — the button opens the Supabase access-token page in the
+ * user's own browser, where they are already logged in. They create a
+ * token and paste it once. That is the browser login: Jarvis never asks
+ * for a Supabase password and never sees the session.
+ * 2. **Pick a project** — Jarvis lists the projects the token can see, so
+ * the user recognises their own project by name instead of hunting for a
+ * twenty-character reference id.
+ * 3. **Database password** — the one piece Supabase deliberately never
+ * returns over its API. Jarvis asks Supabase for the real pooler host,
+ * assembles the connection string, and tests it before saving anything.
+ *
+ * Why not assemble the string from the project ref alone: the region prefix in
+ * a Supavisor hostname (`aws-1-eu-central-2.pooler.supabase.com`) is not
+ * derivable from the ref. Guessing it yields a host that does not resolve, and
+ * the user sees a connection error with no visible cause.
+ */
+import { useState } from "react";
+import { CheckCircle2, ExternalLink, Loader2, RefreshCw } from "lucide-react";
+
+import { ApiKeyForm } from "@/components/ApiKeyForm";
+import { Button } from "@/components/ui/button";
+import { useT } from "@/i18n";
+import { useEventStore } from "@/store/events";
+import {
+ SettingsField,
+ settingsInputCls,
+} from "@/views/settings/SettingsBlock";
+import {
+ fetchSupabaseProjects,
+ linkSupabaseProject,
+ supabaseLinkProbeFailureOf,
+ type SupabaseProject,
+ type UltraWikiCatalogRow,
+} from "@/lib/ultrawikiApi";
+
+const TOKENS_URL = "https://supabase.com/dashboard/account/tokens";
+
+export function SupabaseConnect({
+ row,
+ onChanged,
+}: {
+ row: UltraWikiCatalogRow;
+ onChanged: () => void;
+}): JSX.Element {
+ const t = useT();
+ const pushToast = useEventStore((s) => s.pushToast);
+
+ const tokenSaved = Boolean(row.secrets_set["supabase_access_token"]);
+ const linked = Boolean(row.secrets_set["ultrawiki_db_url"]);
+
+ const [projects, setProjects] = useState<SupabaseProject[] | null>(null);
+ const [loading, setLoading] = useState(false);
+ const [projectRef, setProjectRef] = useState("");
+ const [password, setPassword] = useState("");
+ const [linking, setLinking] = useState(false);
+ // Set when the connection probe failed: keeps the offer to save anyway
+ // visible with the reason, instead of a toast the user cannot re-read.
+ const [probeFailure, setProbeFailure] = useState<string | null>(null);
+
+ async function loadProjects() {
+ setLoading(true);
+ setProbeFailure(null);
+ try {
+ const response = await fetchSupabaseProjects();
+ setProjects(response.projects);
+ if (response.projects.length === 1) setProjectRef(response.projects[0].ref);
+ if (response.projects.length === 0) {
+ pushToast("warning", t("ultrawiki.supabase.no_projects"));
+ }
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function link(saveAnyway: boolean) {
+ if (!projectRef || !password) return;
+ setLinking(true);
+ try {
+ const result = await linkSupabaseProject({
+ project_ref: projectRef,
+ db_password: password,
+ save_anyway: saveAnyway,
+ });
+ setPassword("");
+ setProbeFailure(null);
+ pushToast(
+ result.probe_ok ? "success" : "warning",
+ result.probe_ok ? result.probe_detail : result.detail,
+ );
+ onChanged();
+ } catch (e) {
+ const failure = supabaseLinkProbeFailureOf(e);
+ if (failure) {
+ setProbeFailure(failure.message || failure.probe_detail);
+ } else {
+ pushToast("error", (e as Error).message);
+ }
+ } finally {
+ setLinking(false);
+ }
+ }
+
+ return (
+ <div className="space-y-3" data-testid="ultrawiki-supabase-connect">
+ {/* Step 1 — the browser login. */}
+ {!tokenSaved ? (
+ <div className="space-y-2 rounded-lg border border-border/60 bg-muted/20 p-3">
+ <p className="text-[11px] font-medium text-foreground">
+ {t("ultrawiki.supabase.step1_title")}
+ </p>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {t("ultrawiki.supabase.step1_body")}
+ </p>
+ <Button size="sm" variant="outline" asChild>
+ <a href={TOKENS_URL} target="_blank" rel="noreferrer">
+ <ExternalLink className="mr-1 h-3.5 w-3.5" aria-hidden />
+ {t("ultrawiki.supabase.open_login")}
+ </a>
+ </Button>
+ <ApiKeyForm
+ secretKey="supabase_access_token"
+ dashboardUrl={TOKENS_URL}
+ configured={false}
+ sharedWith={row.secret_shared_with["supabase_access_token"] ?? []}
+ onChanged={onChanged}
+ />
+ </div>
+ ) : (
+ <div className="space-y-2 rounded-lg border border-border/60 bg-muted/20 p-3">
+ <p className="flex items-center gap-1.5 text-[11px] text-emerald-600">
+ <CheckCircle2 className="h-3.5 w-3.5" aria-hidden />
+ {t("ultrawiki.supabase.signed_in")}
+ </p>
+
+ {/* Step 2 — pick the project by NAME. */}
+ <div className="flex flex-wrap items-end gap-2">
+ <div className="min-w-[14rem] flex-1">
+ <SettingsField label={t("ultrawiki.supabase.project_label")}>
+ <select
+ value={projectRef}
+ onChange={(e) => setProjectRef(e.target.value)}
+ disabled={!projects || projects.length === 0}
+ className={settingsInputCls}
+ data-testid="ultrawiki-supabase-project"
+ >
+ <option value="">
+ {projects === null
+ ? t("ultrawiki.supabase.load_first")
+ : t("ultrawiki.supabase.choose_project")}
+ </option>
+ {(projects ?? []).map((project) => (
+ <option key={project.ref} value={project.ref}>
+ {project.name}
+ {project.region ? ` · ${project.region}` : ""}
+ </option>
+ ))}
+ </select>
+ </SettingsField>
+ </div>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void loadProjects()}
+ disabled={loading}
+ data-testid="ultrawiki-supabase-load"
+ >
+ {loading ? (
+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />
+ ) : (
+ <RefreshCw className="mr-1 h-3.5 w-3.5" aria-hidden />
+ )}
+ {t("ultrawiki.supabase.load_projects")}
+ </Button>
+ </div>
+
+ {/* Step 3 — the only thing Supabase will not hand over. */}
+ <SettingsField label={t("ultrawiki.supabase.password_label")}>
+ <input
+ type="password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ placeholder={t("ultrawiki.supabase.password_placeholder")}
+ className={settingsInputCls}
+ data-testid="ultrawiki-supabase-password"
+ />
+ </SettingsField>
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {t("ultrawiki.supabase.password_hint")}
+ </p>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <Button
+ size="sm"
+ onClick={() => void link(false)}
+ disabled={linking || !projectRef || !password}
+ data-testid="ultrawiki-supabase-link"
+ >
+ {linking && (
+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />
+ )}
+ {t("ultrawiki.supabase.link")}
+ </Button>
+ {linked && (
+ <span className="text-[11px] text-emerald-600">
+ {t("ultrawiki.supabase.already_linked")}
+ </span>
+ )}
+ </div>
+
+ {/* The probe refused: nothing was saved. Show why, and offer the
+ override for a database only reachable over a VPN. */}
+ {probeFailure && (
+ <div
+ className="space-y-2 rounded-md border border-[#ffb84d]/40 bg-[#ffb84d]/10 p-2"
+ data-testid="ultrawiki-supabase-probe-failed"
+ >
+ <p className="text-[11px] leading-relaxed text-[#ffb84d]">
+ {probeFailure}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void link(true)}
+ disabled={linking}
+ data-testid="ultrawiki-supabase-save-anyway"
+ >
+ {t("ultrawiki.supabase.save_anyway")}
+ </Button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx
new file mode 100644
index 0000000000..aebd2fb34a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraProviderCard.tsx
@@ -0,0 +1,198 @@
+/**
+ * One provider card inside an UltraWiki capability slot.
+ *
+ * Deliberately the same visual language as the API-Keys view's `ProviderCard`
+ * (`card-outline`, the primary ring on the active card, the state chip, the
+ * `ApiKeyForm` credential widget, a footer separated from the body): the two
+ * screens do the same job — pick a provider, give it a credential, verify it —
+ * so they must not look like two different products.
+ *
+ * The credential widget is literally `ApiKeyForm`, not a copy of it. That is
+ * the point of this rewrite: the old settings cards had no credential input at
+ * all and told the user to go to the API-Keys view, which has no field for
+ * these slots either. Sharing the component means the entry, the reveal
+ * toggle, the shared-key delete warning and the "get your key" link behave
+ * identically here and there, forever.
+ */
+import type { ReactNode } from "react";
+import { Sparkles } from "lucide-react";
+
+import { ApiKeyForm } from "@/components/ApiKeyForm";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import type { UltraWikiCatalogRow } from "@/lib/ultrawikiApi";
+
+const STATE_CHIP_TONE = {
+ active: "border-primary/40 bg-primary/15 text-primary font-semibold",
+ ready: "border-emerald-500/30 bg-emerald-500/10 text-emerald-600",
+ missing: "border-destructive/30 bg-destructive/10 text-destructive",
+ neutral: "border-border bg-muted text-muted-foreground",
+} as const;
+
+export function StateChip({
+ tone,
+ children,
+}: {
+ tone: keyof typeof STATE_CHIP_TONE;
+ children: ReactNode;
+}): JSX.Element {
+ return (
+ <span
+ className={cn(
+ "inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-medium",
+ STATE_CHIP_TONE[tone],
+ )}
+ >
+ {children}
+ </span>
+ );
+}
+
+export function UltraProviderCard({
+ row,
+ busy,
+ onSelect,
+ onCredentialChanged,
+ children,
+ footer,
+}: {
+ row: UltraWikiCatalogRow;
+ busy: boolean;
+ /** Switch this slot to this provider. */
+ onSelect: () => void;
+ /** A credential was saved or deleted — refetch the catalog. */
+ onCredentialChanged: () => void;
+ /** Slot-specific body (model input, connect wizard, server URL). */
+ children?: ReactNode;
+ /** Slot-specific footer under the separator (a test result, a hint). */
+ footer?: ReactNode;
+}): JSX.Element {
+ const t = useT();
+ const keyless = row.auth_mode === "none";
+
+ // A card click selects, EXCEPT on an interactive child — clicking into the
+ // password box or the trash icon must never also flip the provider. Same
+ // guard as the API-Keys card, and for the same reason it was added there.
+ function handleCardActivate(e: React.MouseEvent<HTMLDivElement>) {
+ const target = e.target as HTMLElement | null;
+ if (
+ target &&
+ (target.closest("input") ||
+ target.closest("button") ||
+ target.closest("a") ||
+ target.closest("select") ||
+ target.closest("label"))
+ ) {
+ return;
+ }
+ if (!row.selected) onSelect();
+ }
+
+ return (
+ <div
+ onClick={handleCardActivate}
+ title={
+ row.selected
+ ? t("ultrawiki.card.in_use_tooltip")
+ : t("ultrawiki.card.click_to_use")
+ }
+ data-testid={`ultrawiki-card-${row.slot}-${row.id}`}
+ data-selected={row.selected ? "true" : "false"}
+ className={cn(
+ "card-outline space-y-3 p-4 transition-colors",
+ row.selected
+ ? "border-primary bg-primary/[0.06] ring-1 ring-primary/30"
+ : "cursor-pointer hover:border-primary/40 hover:bg-primary/[0.02]",
+ )}
+ >
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-display text-sm font-semibold tracking-tight">
+ {row.label}
+ </span>
+ <CardStatusChip row={row} />
+ {row.recommended && (
+ <span className="inline-flex items-center gap-1 rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[10px] font-medium text-primary">
+ <Sparkles aria-hidden="true" className="h-2.5 w-2.5" />
+ {t("ultrawiki.card.recommended")}
+ </span>
+ )}
+ {row.caution && (
+ <span
+ className="rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-600 dark:text-amber-400"
+ title={row.caution}
+ >
+ {t("ultrawiki.card.not_recommended")}
+ </span>
+ )}
+ </div>
+ <p className="mt-0.5 text-[11px] text-muted-foreground">
+ <code className="font-mono">{row.id}</code>
+ {" · "}
+ <span>{t(`ultrawiki.card.auth_${row.auth_mode}`)}</span>
+ </p>
+ </div>
+ <Button
+ size="sm"
+ variant={row.selected ? "secondary" : "outline"}
+ disabled={row.selected || busy}
+ onClick={onSelect}
+ data-testid={`ultrawiki-use-${row.slot}-${row.id}`}
+ >
+ {t(row.selected ? "ultrawiki.card.in_use" : "ultrawiki.card.use")}
+ </Button>
+ </div>
+
+ {/* The honest reason line. Amber, not red: a provider without a key is
+ not broken, it is simply not set up — and for every slot but the
+ embedding one, Jarvis keeps working without it. */}
+ {!row.ready && row.reason && (
+ <p
+ className="text-[11px] leading-relaxed text-[#ffb84d]"
+ data-testid={`ultrawiki-reason-${row.slot}-${row.id}`}
+ >
+ {row.reason}
+ </p>
+ )}
+
+ {/* A managed_link provider owns its own multi-step flow (Supabase: browser
+ login → project pick → password), so the card shows the explanation
+ and hands the credential UI to `children`. Rendering the default key
+ boxes here as well would ask for two secrets the user should never
+ type by hand. */}
+ {keyless || row.auth_mode === "managed_link" ? (
+ <p className="text-[11px] leading-relaxed text-muted-foreground">
+ {row.credential_help}
+ </p>
+ ) : (
+ row.secret_keys.map((secretKey) => (
+ <ApiKeyForm
+ key={secretKey}
+ secretKey={secretKey}
+ dashboardUrl={row.dashboard_url}
+ configured={Boolean(row.secrets_set[secretKey])}
+ sharedWith={row.secret_shared_with[secretKey] ?? []}
+ credentialHelp={row.credential_help}
+ onChanged={onCredentialChanged}
+ />
+ ))
+ )}
+
+ {children}
+
+ {footer && (
+ <div className="border-t border-border/60 pt-2.5">{footer}</div>
+ )}
+ </div>
+ );
+}
+
+/** In use → active; usable → ready; otherwise "needs setup". */
+function CardStatusChip({ row }: { row: UltraWikiCatalogRow }): JSX.Element {
+ const t = useT();
+ if (row.selected) return <StateChip tone="active">{t("ultrawiki.card.chip_in_use")}</StateChip>;
+ if (row.ready) return <StateChip tone="ready">{t("ultrawiki.card.chip_ready")}</StateChip>;
+ return <StateChip tone="neutral">{t("ultrawiki.card.chip_needs_setup")}</StateChip>;
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index fec5dabe04..bebd02fa56 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2679,7 +2679,12 @@
"pipeline_running": "Pipeline läuft",
"pipeline_idle": "Pipeline wartet",
"cancel": "Abbrechen",
- "cancel_failed": "Job konnte nicht abgebrochen werden: {0}"
+ "cancel_failed": "Job konnte nicht abgebrochen werden: {0}",
+ "state_waiting_for_sources": "Wartet auf freigegebene Quellen — es wird noch nichts gelesen.",
+ "state_processing": "Verarbeitet ({0} offen)",
+ "state_paused": "Pausiert",
+ "state_idle": "Bereit — alles verarbeitet",
+ "open_sources": "Quellen öffnen"
},
"sources": {
"title": "Verbundene Quellen",
@@ -2732,31 +2737,32 @@
"leg_vector_on": "Semantische Suche: an",
"leg_vector_off": "Semantische Suche: aus — {0}",
"leg_rerank_on": "Rerank: an",
- "leg_rerank_off": "Rerank: aus"
+ "grade_hint": "Wie gut das deine Frage beantwortet - benotet von 0 bis 10 durch das Rerank-Modell.",
+ "context_toggle": "Umgebenden Zusammenhang anzeigen ({0})",
+ "leg_rerank_off": "Rerank: aus",
+ "via": "über {0}",
+ "nothing_ingested_title": "Es wurde noch nichts eingelesen, deshalb gibt es nichts zu durchsuchen.",
+ "nothing_ingested_step_approve": "Öffne „Quellen“ und gib eine Quelle frei, die gelesen werden soll.",
+ "nothing_ingested_step_sync": "Starte dort „Jetzt synchronisieren“ und sieh zu, wie sich die Importleiste füllt.",
+ "nothing_ingested_note": "Die Stichwortsuche funktioniert Sekunden nach der ersten Synchronisierung; semantische Antworten wachsen, während die Hintergrundverarbeitung einbettet und destilliert."
},
"slots": {
"title": "Fähigkeits-Slots",
"storage_title": "Speicher",
"storage_desc": "Wo der Wissensspeicher liegt.",
- "storage_sqlite": "SQLite — lokale Datei, keine Einrichtung",
- "storage_postgres": "PostgreSQL — über gespeicherte Verbindungszeichenfolge",
- "storage_postgres_hint": "Die Verbindungszeichenfolge ist ein Geheimnis. Speichere sie als 'ultrawiki_db_url' in der API-Keys-Ansicht; hier wird sie nie eingegeben.",
- "open_api_keys": "API-Keys öffnen",
"in_use": "In Benutzung: {0}",
"embedding_title": "Embedding-Modell",
"embedding_desc": "Wandelt Text in Vektoren für die semantische Suche um. Ein Wechsel bettet alles neu ein.",
- "provider_label": "Anbieter",
"model_label": "Modell",
- "model_default_placeholder": "Anbieter-Standard ({0})",
"distill_title": "Destillations-Modell",
"distill_desc": "Fasst aufgenommene Elemente im Hintergrund zusammen. Gilt nur für neue Arbeit.",
"distill_auto": "Automatisch — erster bereiter Chat-Anbieter",
- "distill_chain": "Bereite Chat-Anbieter: {0}",
- "distill_chain_empty": "Kein Chat-Anbieter mit gültigen Zugangsdaten gefunden.",
"rerank_title": "Rerank (optional)",
"rerank_desc": "Sortiert die fusionierten Treffer neu; die Suche funktioniert auch ohne.",
"rerank_off": "Aus",
- "not_ready_suffix": "nicht bereit",
+ "rerank_model_placeholder": "Standard der Kette (schnelles, günstiges Modell)",
+ "floor_label": "Relevanzschwelle (0-10)",
+ "floor_hint": "Gilt nur, wenn Jarvis von sich aus etwas einbringt - in Sprachantworten oder als Hintergrund für eine Chat-Antwort. Treffer mit einer schlechteren Note bleiben weg, und Jarvis sagt lieber, dass er nichts hat, als etwas Schwaches anzubieten. Suchen, die du hier eintippst, zeigen immer alles. 0 schaltet die Schwelle ab.",
"apply": "Übernehmen",
"applying": "Wird übernommen…",
"applied": "Slot-Einstellungen übernommen.",
@@ -2769,7 +2775,17 @@
"testing": "Teste…",
"test_ok": "OK",
"test_failed": "Fehlgeschlagen",
- "current": "Aktuell: {0}"
+ "current": "Aktuell: {0}",
+ "via": "Über: {0}",
+ "loading": "Anbieterliste wird geladen…",
+ "catalog_unavailable": "Die Anbieterliste konnte nicht geladen werden. Die App startet möglicherweise noch — versuche es gleich noch einmal.",
+ "save_model": "Modell speichern",
+ "server_url_label": "Server-URL",
+ "storage_restart_hint": "Eine Änderung am Speicher greift beim nächsten Start von Jarvis. Es wird nichts gelöscht, und bis dahin antwortet der bisherige Speicher weiter.",
+ "embedding_lock_hint": "Dieser Slot hat absichtlich keinen automatischen Ersatz: Anbieter und Modell zusammen legen den Vektorraum deines gesamten Gedächtnisses fest, deshalb wechselt Jarvis ihn nie unbemerkt.",
+ "distill_auto_desc": "Nutzt den Chat-Anbieter, für den du bereits gültige Zugangsdaten hast, und geht zum nächsten weiter, wenn dieser gedrosselt ist oder kein Guthaben mehr hat. Die sichere Voreinstellung.",
+ "rerank_off_desc": "Die Suche funktioniert trotzdem: Die Treffer behalten die Reihenfolge, auf die sich Stichwort- und Bedeutungssuche geeinigt haben. Schalte einen Reranker ein, wenn präzise Fragen schärfere Antworten brauchen.",
+ "model_cheap_default": "Standard der Kette (schnelles, günstiges Modell)"
},
"wizard": {
"title": "Ultra-Modus einschalten",
@@ -2808,6 +2824,38 @@
"back": "Zurück",
"next": "Weiter",
"close": "Schließen"
+ },
+ "card": {
+ "recommended": "Empfohlen",
+ "not_recommended": "Hinweis",
+ "use": "Verwenden",
+ "in_use": "In Benutzung",
+ "in_use_tooltip": "Dieser Anbieter wird für diesen Slot gerade verwendet.",
+ "click_to_use": "Klicken, um diesen Anbieter für diesen Slot zu verwenden.",
+ "chip_in_use": "in Benutzung",
+ "chip_ready": "bereit",
+ "chip_needs_setup": "einrichten",
+ "auth_none": "Keine Zugangsdaten nötig",
+ "auth_api_key": "API-Schlüssel",
+ "auth_connection_string": "Verbindungszeichenfolge",
+ "auth_managed_link": "Geführte Anmeldung"
+ },
+ "supabase": {
+ "step1_title": "1. Bei Supabase anmelden",
+ "step1_body": "Öffnet Supabase in deinem Browser, wo du bereits angemeldet bist. Erstelle dort ein Zugriffs-Token und füge es unten ein — Jarvis liest damit nur deine Projektliste und die Verbindungsdaten.",
+ "open_login": "Supabase-Anmeldung öffnen",
+ "signed_in": "Bei Supabase angemeldet.",
+ "project_label": "Projekt",
+ "choose_project": "Projekt auswählen…",
+ "load_first": "Lade zuerst deine Projekte",
+ "load_projects": "Projekte laden",
+ "no_projects": "Dieses Supabase-Konto hat noch keine Projekte.",
+ "password_label": "Datenbank-Passwort",
+ "password_placeholder": "Das Datenbank-Passwort deines Projekts",
+ "password_hint": "Das Einzige, was Supabase über seine Schnittstelle nie herausgibt. Du findest es unter Project Settings → Database und kannst es dort auch neu setzen. Jarvis testet die Verbindung, bevor irgendetwas gespeichert wird.",
+ "link": "Dieses Projekt verbinden",
+ "already_linked": "Eine Supabase-Verbindung ist bereits gespeichert.",
+ "save_anyway": "Trotzdem speichern"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index f7fe51271f..bc085c10cb 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2680,7 +2680,12 @@
"pipeline_running": "Pipeline running",
"pipeline_idle": "Pipeline idle",
"cancel": "Cancel",
- "cancel_failed": "Could not cancel the job: {0}"
+ "cancel_failed": "Could not cancel the job: {0}",
+ "state_waiting_for_sources": "Waiting for approved sources — nothing is being read yet.",
+ "state_processing": "Processing ({0} pending)",
+ "state_paused": "Paused",
+ "state_idle": "Idle — everything is processed",
+ "open_sources": "Open Sources"
},
"sources": {
"title": "Connected sources",
@@ -2733,31 +2738,32 @@
"leg_vector_on": "Semantic search: on",
"leg_vector_off": "Semantic search: off — {0}",
"leg_rerank_on": "Rerank: on",
- "leg_rerank_off": "Rerank: off"
+ "grade_hint": "How well this answers your question, graded 0-10 by the rerank model.",
+ "context_toggle": "Show surrounding context ({0})",
+ "leg_rerank_off": "Rerank: off",
+ "via": "via {0}",
+ "nothing_ingested_title": "Nothing has been ingested yet, so there is nothing to search.",
+ "nothing_ingested_step_approve": "Open Sources and approve a source you want read.",
+ "nothing_ingested_step_sync": "Press Sync on that source and watch the import strip fill up.",
+ "nothing_ingested_note": "Keyword search works seconds after the first sync; semantic answers grow as the background pipeline embeds and distills."
},
"slots": {
"title": "Capability slots",
"storage_title": "Storage",
"storage_desc": "Where the knowledge store lives.",
- "storage_sqlite": "SQLite — local file, zero setup",
- "storage_postgres": "PostgreSQL — via saved connection string",
- "storage_postgres_hint": "The connection string is a secret. Save it as 'ultrawiki_db_url' in the API-Keys view; it is never entered here.",
- "open_api_keys": "Open API-Keys",
"in_use": "In use: {0}",
"embedding_title": "Embedding model",
"embedding_desc": "Turns text into vectors for semantic search. Changing it re-embeds everything.",
- "provider_label": "Provider",
"model_label": "Model",
- "model_default_placeholder": "Provider default ({0})",
"distill_title": "Distillation model",
"distill_desc": "Summarizes ingested items in the background. Applies to new work only.",
"distill_auto": "Automatic — first ready chat provider",
- "distill_chain": "Ready chat providers: {0}",
- "distill_chain_empty": "No credential-ready chat provider found.",
"rerank_title": "Rerank (optional)",
"rerank_desc": "Re-orders the fused hits; search works without it.",
"rerank_off": "Off",
- "not_ready_suffix": "not ready",
+ "rerank_model_placeholder": "Chain default (a cheap fast model)",
+ "floor_label": "Relevance floor (0-10)",
+ "floor_hint": "Only applies when Jarvis brings something up on its own - in voice answers or as background for a chat reply. Results graded below this are left out, and Jarvis says it has nothing instead of volunteering a weak match. Searches you type here always show everything. 0 turns the floor off.",
"apply": "Apply",
"applying": "Applying…",
"applied": "Slot settings applied.",
@@ -2770,7 +2776,17 @@
"testing": "Testing…",
"test_ok": "OK",
"test_failed": "Failed",
- "current": "Current: {0}"
+ "current": "Current: {0}",
+ "via": "Via: {0}",
+ "loading": "Loading the provider list…",
+ "catalog_unavailable": "The provider list could not be loaded. The app may still be starting — try again in a moment.",
+ "save_model": "Save model",
+ "server_url_label": "Server URL",
+ "storage_restart_hint": "A storage change takes effect the next time Jarvis starts. Nothing is deleted, and the current store keeps answering until then.",
+ "embedding_lock_hint": "This slot has no automatic fallback on purpose: the provider and model together define the vector space of your whole memory, so Jarvis never switches it silently.",
+ "distill_auto_desc": "Uses whichever chat provider you already have a working credential for, and moves on to the next one if it is rate limited or out of credit. The safe default.",
+ "rerank_off_desc": "Search still works: results keep the order the keyword and semantic legs agreed on. Turn a reranker on for sharper answers to precise questions.",
+ "model_cheap_default": "Chain default (a cheap fast model)"
},
"wizard": {
"title": "Turn on Ultra mode",
@@ -2809,6 +2825,38 @@
"back": "Back",
"next": "Next",
"close": "Close"
+ },
+ "card": {
+ "recommended": "Recommended",
+ "not_recommended": "Note",
+ "use": "Use this",
+ "in_use": "In use",
+ "in_use_tooltip": "This provider is currently in use for this slot.",
+ "click_to_use": "Click to use this provider for this slot.",
+ "chip_in_use": "in use",
+ "chip_ready": "ready",
+ "chip_needs_setup": "needs setup",
+ "auth_none": "No credential needed",
+ "auth_api_key": "API key",
+ "auth_connection_string": "Connection string",
+ "auth_managed_link": "Guided sign-in"
+ },
+ "supabase": {
+ "step1_title": "1. Sign in to Supabase",
+ "step1_body": "Opens Supabase in your browser, where you are already signed in. Create an access token there and paste it below — Jarvis only uses it to read your project list and connection details.",
+ "open_login": "Open Supabase sign-in",
+ "signed_in": "Signed in to Supabase.",
+ "project_label": "Project",
+ "choose_project": "Choose a project…",
+ "load_first": "Load your projects first",
+ "load_projects": "Load projects",
+ "no_projects": "This Supabase account has no projects yet.",
+ "password_label": "Database password",
+ "password_placeholder": "Your project's database password",
+ "password_hint": "The one thing Supabase never hands out over its API. Find it under Project Settings → Database, or reset it there. Jarvis tests the connection before saving anything.",
+ "link": "Connect this project",
+ "already_linked": "A Supabase connection is already saved.",
+ "save_anyway": "Save anyway"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index f90fd5e75e..377e1da34f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2689,7 +2689,12 @@
"pipeline_running": "Canal en marcha",
"pipeline_idle": "Canal en espera",
"cancel": "Cancelar",
- "cancel_failed": "No se pudo cancelar el trabajo: {0}"
+ "cancel_failed": "No se pudo cancelar el trabajo: {0}",
+ "state_waiting_for_sources": "Esperando fuentes aprobadas: todavía no se lee nada.",
+ "state_processing": "Procesando ({0} pendientes)",
+ "state_paused": "En pausa",
+ "state_idle": "Inactivo: todo está procesado",
+ "open_sources": "Abrir Fuentes"
},
"sources": {
"title": "Fuentes conectadas",
@@ -2742,31 +2747,32 @@
"leg_vector_on": "Búsqueda semántica: activada",
"leg_vector_off": "Búsqueda semántica: desactivada — {0}",
"leg_rerank_on": "Rerank: activado",
- "leg_rerank_off": "Rerank: desactivado"
+ "grade_hint": "Qué tan bien responde esto a tu pregunta, calificado de 0 a 10 por el modelo de reordenación.",
+ "context_toggle": "Mostrar el contexto circundante ({0})",
+ "leg_rerank_off": "Rerank: desactivado",
+ "via": "mediante {0}",
+ "nothing_ingested_title": "Todavía no se ha importado nada, así que no hay nada que buscar.",
+ "nothing_ingested_step_approve": "Abre «Fuentes» y aprueba una fuente que quieras que se lea.",
+ "nothing_ingested_step_sync": "Pulsa «Sincronizar ahora» en esa fuente y observa cómo se llena la barra de importación.",
+ "nothing_ingested_note": "La búsqueda por palabras clave funciona segundos después de la primera sincronización; las respuestas semánticas crecen mientras el proceso en segundo plano genera vectores y resúmenes."
},
"slots": {
"title": "Ranuras de capacidades",
"storage_title": "Almacenamiento",
"storage_desc": "Dónde vive el almacén de conocimiento.",
- "storage_sqlite": "SQLite — archivo local, sin configuración",
- "storage_postgres": "PostgreSQL — mediante cadena de conexión guardada",
- "storage_postgres_hint": "La cadena de conexión es un secreto. Guárdala como 'ultrawiki_db_url' en la vista API-Keys; aquí nunca se introduce.",
- "open_api_keys": "Abrir API-Keys",
"in_use": "En uso: {0}",
"embedding_title": "Modelo de embeddings",
"embedding_desc": "Convierte el texto en vectores para la búsqueda semántica. Cambiarlo vuelve a incrustar todo.",
- "provider_label": "Proveedor",
"model_label": "Modelo",
- "model_default_placeholder": "Predeterminado del proveedor ({0})",
"distill_title": "Modelo de destilación",
"distill_desc": "Resume los elementos ingeridos en segundo plano. Solo aplica al trabajo nuevo.",
"distill_auto": "Automático — primer proveedor de chat listo",
- "distill_chain": "Proveedores de chat listos: {0}",
- "distill_chain_empty": "No se encontró ningún proveedor de chat con credenciales válidas.",
"rerank_title": "Rerank (opcional)",
"rerank_desc": "Reordena los resultados fusionados; la búsqueda funciona sin él.",
"rerank_off": "Desactivado",
- "not_ready_suffix": "no listo",
+ "rerank_model_placeholder": "Predeterminado de la cadena (un modelo rápido y barato)",
+ "floor_label": "Umbral de relevancia (0-10)",
+ "floor_hint": "Solo se aplica cuando Jarvis aporta algo por su cuenta: en respuestas de voz o como contexto de una respuesta de chat. Los resultados con una nota inferior se descartan, y Jarvis prefiere decir que no tiene nada antes que ofrecer una coincidencia débil. Las búsquedas que escribes aquí siempre lo muestran todo. 0 desactiva el umbral.",
"apply": "Aplicar",
"applying": "Aplicando…",
"applied": "Ajustes de ranuras aplicados.",
@@ -2779,7 +2785,17 @@
"testing": "Probando…",
"test_ok": "OK",
"test_failed": "Falló",
- "current": "Actual: {0}"
+ "current": "Actual: {0}",
+ "via": "Mediante: {0}",
+ "loading": "Cargando la lista de proveedores…",
+ "catalog_unavailable": "No se pudo cargar la lista de proveedores. Puede que la aplicación aún esté arrancando: inténtalo de nuevo en un momento.",
+ "save_model": "Guardar modelo",
+ "server_url_label": "URL del servidor",
+ "storage_restart_hint": "Un cambio de almacenamiento surte efecto la próxima vez que arranque Jarvis. No se borra nada y, hasta entonces, el almacén actual sigue respondiendo.",
+ "embedding_lock_hint": "Esta ranura no tiene alternativa automática a propósito: el proveedor y el modelo juntos definen el espacio vectorial de toda tu memoria, así que Jarvis nunca lo cambia en silencio.",
+ "distill_auto_desc": "Usa el proveedor de chat para el que ya tengas una credencial válida y pasa al siguiente si está limitado o sin saldo. La opción segura por defecto.",
+ "rerank_off_desc": "La búsqueda sigue funcionando: los resultados mantienen el orden en el que coincidieron la búsqueda por palabras clave y la semántica. Activa un reranker para respuestas más precisas.",
+ "model_cheap_default": "Valor por defecto de la cadena (modelo rápido y barato)"
},
"wizard": {
"title": "Activar el modo Ultra",
@@ -2818,6 +2834,38 @@
"back": "Atrás",
"next": "Siguiente",
"close": "Cerrar"
+ },
+ "card": {
+ "recommended": "Recomendado",
+ "not_recommended": "Aviso",
+ "use": "Usar este",
+ "in_use": "En uso",
+ "in_use_tooltip": "Este proveedor se está usando para esta ranura.",
+ "click_to_use": "Haz clic para usar este proveedor en esta ranura.",
+ "chip_in_use": "en uso",
+ "chip_ready": "listo",
+ "chip_needs_setup": "configurar",
+ "auth_none": "No necesita credenciales",
+ "auth_api_key": "Clave de API",
+ "auth_connection_string": "Cadena de conexión",
+ "auth_managed_link": "Inicio de sesión guiado"
+ },
+ "supabase": {
+ "step1_title": "1. Inicia sesión en Supabase",
+ "step1_body": "Abre Supabase en tu navegador, donde ya has iniciado sesión. Crea allí un token de acceso y pégalo abajo: Jarvis solo lo usa para leer tu lista de proyectos y los datos de conexión.",
+ "open_login": "Abrir el inicio de sesión de Supabase",
+ "signed_in": "Sesión iniciada en Supabase.",
+ "project_label": "Proyecto",
+ "choose_project": "Elige un proyecto…",
+ "load_first": "Carga primero tus proyectos",
+ "load_projects": "Cargar proyectos",
+ "no_projects": "Esta cuenta de Supabase todavía no tiene proyectos.",
+ "password_label": "Contraseña de la base de datos",
+ "password_placeholder": "La contraseña de la base de datos de tu proyecto",
+ "password_hint": "Lo único que Supabase nunca entrega por su API. Está en Project Settings → Database, y allí también puedes restablecerla. Jarvis prueba la conexión antes de guardar nada.",
+ "link": "Conectar este proyecto",
+ "already_linked": "Ya hay una conexión de Supabase guardada.",
+ "save_anyway": "Guardar de todos modos"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index 3f1fef292a..56fbacb2bf 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -91,6 +91,8 @@ export interface UltraWikiProviderOption {
ready: boolean;
reason: string;
default_model?: string;
+ /** One-line English explanation of what this option is. */
+ detail?: string;
}
export interface UltraWikiDbBackendOption {
@@ -107,13 +109,28 @@ export interface UltraWikiProviders {
db_backends: UltraWikiDbBackendOption[];
}
+/**
+ * Live ranking knobs of the read path — mirrors
+ * jarvis/ultrawiki/search.py::ranking_settings.
+ */
+export interface UltraWikiRanking {
+ keyword_weight: number;
+ vector_weight: number;
+ recency_half_life_days: number;
+ /** Absolute 0-10 relevance floor for UNSOLICITED surfaces; 0 = off. */
+ rerank_min_score: number;
+}
+
export interface UltraWikiSlotStatus {
provider: string;
model?: string;
ready: boolean;
reason: string;
+ via?: string;
available?: UltraWikiProviderOption[];
chain?: string[];
+ /** Only on the rerank slot: the knobs that slot governs. */
+ ranking?: Partial<UltraWikiRanking>;
}
export interface UltraWikiStorageSlot {
@@ -124,6 +141,34 @@ export interface UltraWikiStorageSlot {
vector?: { ready?: boolean; reason?: string };
}
+// Mirrors jarvis/ultrawiki/service.py::PIPELINE_STATES — five-layer anti-drift
+// discipline (AP-4 / BUG-008): never retype these values elsewhere.
+export type UltraWikiPipelineState =
+ | "waiting_for_sources"
+ | "idle"
+ | "processing"
+ | "paused";
+
+export const ULTRAWIKI_PIPELINE_STATES: readonly UltraWikiPipelineState[] = [
+ "waiting_for_sources",
+ "idle",
+ "processing",
+ "paused",
+];
+
+export interface UltraWikiPipeline {
+ /**
+ * The worker LOOP is alive — NOT the same as work being done. Reporting this
+ * alone read as "something is already pulling my data" on a fresh activation
+ * with zero approved sources; `state` is what the UI shows.
+ */
+ running: boolean;
+ state?: UltraWikiPipelineState | string;
+ /** One honest English sentence: what is happening, or what blocks it. */
+ reason?: string;
+ processed: Record<string, number>;
+}
+
export interface UltraWikiSearchLeg {
available: boolean;
backend?: string;
@@ -144,7 +189,7 @@ export interface UltraWikiStatus {
storage?: UltraWikiStorageSlot;
};
counts: Partial<UltraWikiCounts>;
- pipeline: { running: boolean; processed: Record<string, number> };
+ pipeline: UltraWikiPipeline;
sources: UltraWikiSource[];
jobs: UltraWikiJob[];
search_legs: {
@@ -164,8 +209,13 @@ export interface UltraWikiSearchHit {
snippet: string;
permalink: string;
timestamp_utc: string;
+ /** ORDINAL fused rank score (RRF) — comparable between hits, never absolute. */
score: number;
matched_by: string[];
+ /** ABSOLUTE 0-10 relevance grade; null when the rerank stage did not run. */
+ rerank_score: number | null;
+ /** Neighbouring evidence pulled back in after ranking; may be empty. */
+ context: string[];
}
export interface UltraWikiSearchResponse {
@@ -181,6 +231,7 @@ export interface UltraWikiActivateBody {
distill_provider?: string;
distill_model?: string;
rerank_provider?: string;
+ rerank_model?: string;
areas?: string[];
}
@@ -206,14 +257,117 @@ export interface UltraWikiDeactivateResponse {
export interface UltraWikiSettingsBody {
db_backend?: string;
+ /**
+ * The named storage preset (sqlite / supabase / neon / postgres). Send this
+ * rather than `db_backend`: the backend derives the two-value functional
+ * enum from the preset, so the UI never has to mirror it (AP-4).
+ */
+ storage_provider?: string;
embedding_provider?: string;
embedding_model?: string;
distill_provider?: string;
distill_model?: string;
rerank_provider?: string;
+ /** Only meaningful for rerank_provider="llm"; empty = cheap chain default. */
+ rerank_model?: string;
+ ollama_endpoint?: string;
+ /** Ranking knobs — see UltraWikiRanking. Sent only when the user edits one. */
+ rerank_min_score?: number;
+ rrf_keyword_weight?: number;
+ rrf_vector_weight?: number;
+ recency_half_life_days?: number;
confirm_reembed?: boolean;
}
+// Mirrors jarvis/ultrawiki/provider_catalog.py::SlotName / UltraWikiAuthMode —
+// five-layer anti-drift discipline (AP-4 / BUG-008): never retype these.
+export const ULTRAWIKI_SLOT_NAMES = [
+ "storage",
+ "embedding",
+ "distill",
+ "rerank",
+] as const;
+export type UltraWikiSlotName = (typeof ULTRAWIKI_SLOT_NAMES)[number];
+
+export type UltraWikiAuthMode =
+ | "none"
+ | "api_key"
+ | "connection_string"
+ | "managed_link";
+
+/**
+ * One provider row of `GET /api/ultrawiki/catalog`: the declared spec plus the
+ * live truth about THIS machine (which credential slots hold a value, which
+ * other Jarvis surfaces share them, whether the provider's own probe passes).
+ */
+export interface UltraWikiCatalogRow {
+ id: string;
+ slot: UltraWikiSlotName;
+ label: string;
+ auth_mode: UltraWikiAuthMode;
+ secret_keys: string[];
+ dashboard_url: string | null;
+ credential_help: string;
+ default_model: string;
+ supports_base_url: boolean;
+ default_base_url: string | null;
+ recommended: boolean;
+ caution: string | null;
+ db_backend: string | null;
+ connection_hint: string | null;
+ ready: boolean;
+ reason: string;
+ selected: boolean;
+ secrets_set: Record<string, boolean>;
+ secret_shared_with: Record<string, string[]>;
+}
+
+export interface UltraWikiCatalog {
+ slots: Record<UltraWikiSlotName, UltraWikiCatalogRow[]>;
+ selected: Record<UltraWikiSlotName, string>;
+ models: { embedding: string; distill: string };
+ ollama_endpoint: string;
+}
+
+export interface SupabaseProject {
+ ref: string;
+ name: string;
+ region: string;
+ status: string;
+}
+
+export interface SupabaseProjectsResponse {
+ projects: SupabaseProject[];
+ total: number;
+ tokens_url: string;
+}
+
+export interface SupabaseLinkBody {
+ project_ref: string;
+ db_password: string;
+ pool_mode?: "transaction" | "session";
+ save_anyway?: boolean;
+}
+
+export interface SupabaseLinkResponse {
+ ok: boolean;
+ project_ref: string;
+ endpoint: {
+ host: string;
+ port: number;
+ user: string;
+ database: string;
+ mode: string;
+ };
+ note: string;
+ probe_ok: boolean;
+ probe_detail: string;
+ persisted: boolean;
+ restart_required: boolean;
+ detail: string;
+ persist_error?: string;
+}
+
export interface UltraWikiSettingsResponse {
ok: boolean;
changed: string[];
@@ -323,6 +477,52 @@ export function fetchUltraWikiProviders(): Promise<UltraWikiProviders> {
return request<UltraWikiProviders>("/api/ultrawiki/providers");
}
+export function fetchUltraWikiCatalog(): Promise<UltraWikiCatalog> {
+ return request<UltraWikiCatalog>("/api/ultrawiki/catalog");
+}
+
+export function fetchSupabaseProjects(): Promise<SupabaseProjectsResponse> {
+ return request<SupabaseProjectsResponse>(
+ "/api/ultrawiki/storage/supabase/projects",
+ );
+}
+
+export function linkSupabaseProject(
+ body: SupabaseLinkBody,
+): Promise<SupabaseLinkResponse> {
+ return postJson<SupabaseLinkResponse>(
+ "/api/ultrawiki/storage/supabase/link",
+ body,
+ );
+}
+
+/**
+ * The 409 payload of a refused Supabase link — the connection probe failed and
+ * nothing was saved. Carries the sanitized reason plus the offer to save
+ * anyway, for the user whose database is only reachable over a VPN.
+ */
+export function supabaseLinkProbeFailureOf(error: unknown): {
+ message: string;
+ probe_detail: string;
+ can_save_anyway: boolean;
+} | null {
+ if (!(error instanceof UltraWikiApiError) || error.status !== 409) return null;
+ const detail = error.detail;
+ if (
+ detail &&
+ typeof detail === "object" &&
+ (detail as { can_save_anyway?: unknown }).can_save_anyway === true
+ ) {
+ const d = detail as { message?: unknown; probe_detail?: unknown };
+ return {
+ message: String(d.message ?? ""),
+ probe_detail: String(d.probe_detail ?? ""),
+ can_save_anyway: true,
+ };
+ }
+ return null;
+}
+
export function activateUltraWiki(
body: UltraWikiActivateBody,
): Promise<UltraWikiActivateResponse> {
@@ -376,14 +576,35 @@ export function revokeUltraWikiSource(
);
}
+/**
+ * Start a sync. `full` clears the resume checkpoint and the incremental
+ * cursor so everything is re-read — the only mode in which deletions are
+ * detected (an incremental run cannot see a file that no longer exists).
+ */
export function startUltraWikiSync(
sourceId: string,
-): Promise<{ job_id: string; status: string; source_id: string }> {
- return postJson<{ job_id: string; status: string; source_id: string }>(
+ options: { full?: boolean } = {},
+): Promise<{
+ job_id: string;
+ status: string;
+ source_id: string;
+ full?: boolean;
+}> {
+ return postJson(
`/api/ultrawiki/sources/${encodeURIComponent(sourceId)}/sync`,
+ { full: Boolean(options.full) },
);
}
+/** Return dead-lettered items to the pipeline (after fixing what broke). */
+export function requeueUltraWikiFailed(
+ sourceId?: string,
+): Promise<{ ok: boolean; requeued: number; source_id: string; detail: string }> {
+ return postJson("/api/ultrawiki/pipeline/requeue-failed", {
+ source_id: sourceId ?? "",
+ });
+}
+
export function cancelUltraWikiJob(
jobId: string,
): Promise<{ job_id: string; cancel_requested: boolean }> {
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 9155971986..c77ed89817 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import asyncio
import dataclasses
import logging
+import math
import re
import time
from typing import Any
@@ -35,13 +36,35 @@ _MODE_OFF_DETAIL = "UltraWiki mode is off — the normal wiki answers today."
#: The flat ``[ultrawiki]`` slot keys the settings surface may change.
_SLOT_KEYS = (
"db_backend",
+ "storage_provider",
"embedding_provider",
"embedding_model",
"distill_provider",
"distill_model",
"rerank_provider",
+ "rerank_model",
+ "ollama_endpoint",
)
+#: Numeric ranking knobs of the read path (design: UltraWiki ranking
+#: pipeline). Kept apart from the provider slots above because they are
+#: floats, not names — and because an out-of-range value must be refused here
+#: rather than silently ranking nonsense.
+_RANKING_KEYS = (
+ "rerank_min_score",
+ "rrf_keyword_weight",
+ "rrf_vector_weight",
+ "recency_half_life_days",
+)
+
+#: Inclusive bounds per ranking knob.
+_RANKING_BOUNDS: dict[str, tuple[float, float]] = {
+ "rerank_min_score": (0.0, 10.0), # the shared 0-10 relevance scale
+ "rrf_keyword_weight": (0.0, 10.0),
+ "rrf_vector_weight": (0.0, 10.0),
+ "recency_half_life_days": (0.0, 36500.0), # a century is "effectively off"
+}
+
_SLUG_RE = re.compile(r"[^a-z0-9]+")
__all__ = ["router"]
@@ -108,7 +131,40 @@ def _slugify(name: str) -> str:
return _SLUG_RE.sub("-", name.lower()).strip("-") or "area"
-def _persist_slots(values: dict[str, str]) -> tuple[bool, str]:
+def _ranking_changes(body: Any, uw: Any) -> dict[str, float]:
+ """Validated, actually-changing numeric ranking knobs.
+
+ Bounds are enforced HERE rather than clamped later: a rejected 400 tells
+ the user their value was refused, while a silent clamp would leave the UI
+ showing a number the ranking does not use.
+ """
+ changes: dict[str, float] = {}
+ for key in _RANKING_KEYS:
+ raw = getattr(body, key, None)
+ if raw is None:
+ continue
+ try:
+ value = float(raw)
+ except (TypeError, ValueError) as exc:
+ raise HTTPException(
+ status_code=400, detail=f"{key} must be a number, got {raw!r}"
+ ) from exc
+ low, high = _RANKING_BOUNDS[key]
+ if not math.isfinite(value) or not (low <= value <= high):
+ raise HTTPException(
+ status_code=400,
+ detail=f"{key} must be between {low} and {high}, got {value}",
+ )
+ try:
+ current = float(getattr(uw, key))
+ except (TypeError, ValueError, AttributeError):
+ current = None # unset or unreadable — treat as a change
+ if current is None or current != value:
+ changes[key] = value
+ return changes
+
+
+def _persist_slots(values: dict[str, Any]) -> tuple[bool, str]:
"""Persist ``[ultrawiki]`` slot keys FIRST (AP-7 atomic writer).
Best-effort like the wiki-provider route: a read-only/locked TOML must not
@@ -160,7 +216,11 @@ def _apply_live(request: Request, values: dict[str, str], *, enabled: bool | Non
def _search_legs(cfg: Any) -> dict[str, Any]:
- """Honest per-leg availability report (keyword / vector / rerank)."""
+ """Honest per-leg availability report (keyword / vector / rerank).
+
+ BLOCKING: the leg probes walk credentials and may touch a local endpoint.
+ Callers go through :func:`_search_legs_async`.
+ """
try:
from jarvis.ultrawiki import search as search_mod # noqa: PLC0415 — lazy
@@ -169,6 +229,11 @@ def _search_legs(cfg: Any) -> dict[str, Any]:
return {"error": f"search-leg probe failed ({type(exc).__name__})"}
+async def _search_legs_async(cfg: Any) -> dict[str, Any]:
+ """The leg report off the event loop (which also serves voice and chat)."""
+ return await asyncio.to_thread(_search_legs, cfg)
+
+
# ---------------------------------------------------------------------------
# Status + providers
# ---------------------------------------------------------------------------
@@ -190,10 +255,18 @@ async def get_status(request: Request) -> dict[str, Any]:
"backend_in_use": "",
"slots": {},
"counts": {},
- "pipeline": {"running": False, "processed": {}},
+ "pipeline": {
+ "running": False,
+ "state": "paused",
+ "reason": (
+ "UltraWiki is not wired yet — the app is still starting, or "
+ "its init failed. Nothing is being read."
+ ),
+ "processed": {},
+ },
"sources": [],
"jobs": [],
- "search_legs": _search_legs(cfg),
+ "search_legs": await _search_legs_async(cfg),
"degradations": [
"the UltraWiki service is not wired — the app is still "
"starting or its init failed"
@@ -220,7 +293,7 @@ async def get_status(request: Request) -> dict[str, Any]:
"pipeline": data.get("pipeline", {}),
"sources": data.get("sources", []),
"jobs": data.get("jobs", []),
- "search_legs": _search_legs(cfg),
+ "search_legs": await _search_legs_async(cfg),
"degradations": data.get("degradations", []),
}
@@ -279,6 +352,276 @@ async def list_providers(request: Request) -> dict[str, Any]:
return await asyncio.to_thread(_probe)
[email protected]("/catalog", summary="UltraWiki provider catalog with credential state")
+async def get_catalog(request: Request) -> dict[str, Any]:
+ """Every selectable provider per slot, with its live credential + readiness state.
+
+ This is what the settings cards render: for each of storage, embedding,
+ distill and rerank it returns the declared providers
+ (:mod:`jarvis.ultrawiki.provider_catalog`) enriched with the truth about
+ THIS machine — which credential slots hold a value, which other Jarvis
+ surfaces read the same slot (so a delete can warn before it disables
+ them), and whether the provider's own probe says it is usable.
+
+ Credential probes walk the OS keyring, so the whole enrichment runs in a
+ worker thread; the route body itself never blocks the event loop.
+ """
+ cfg = _config(request)
+ uw = getattr(cfg, "ultrawiki", None)
+ selected = {
+ "storage": str(getattr(uw, "storage_provider", "") or "").strip()
+ or ("postgres" if str(getattr(uw, "db_backend", "") or "") == "postgres" else "sqlite"),
+ "embedding": str(getattr(uw, "embedding_provider", "") or "").strip(),
+ "distill": str(getattr(uw, "distill_provider", "") or "").strip(),
+ "rerank": str(getattr(uw, "rerank_provider", "") or "").strip(),
+ }
+
+ def _probe() -> dict[str, Any]:
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.ui.web.provider_spec import ( # noqa: PLC0415 — lazy
+ secret_slot_consumers,
+ )
+ from jarvis.ultrawiki import embeddings as embeddings_mod # noqa: PLC0415
+ from jarvis.ultrawiki import provider_catalog # noqa: PLC0415
+ from jarvis.ultrawiki import rerank as rerank_mod # noqa: PLC0415
+
+ def _secret_present(slot: str) -> bool:
+ try:
+ return bool(get_secret(slot))
+ except Exception: # noqa: BLE001 — a locked keyring reads as absent
+ return False
+
+ # Live readiness per slot, keyed by provider id. Each source is the
+ # provider's OWN probe (AP-21: capability, never a name check).
+ embedding_ready = {
+ str(row.get("name")): row
+ for row in embeddings_mod.available_backends(cfg)
+ }
+ rerank_ready = {
+ str(row.get("name")): row for row in rerank_mod.available_rerankers(cfg)
+ }
+ try:
+ from jarvis.brain.provider_registry import ( # noqa: PLC0415 — lazy
+ BrainProviderRegistry,
+ )
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy
+ credential_ready_wiki_providers,
+ )
+
+ distill_chain = set(
+ credential_ready_wiki_providers(
+ available=set(BrainProviderRegistry().available()), config=cfg
+ )
+ )
+ except Exception as exc: # noqa: BLE001 — the catalog must never 500
+ log.debug("distill chain probe failed: %s", exc, exc_info=True)
+ distill_chain = set()
+
+ db_url_present = _secret_present("ultrawiki_db_url")
+
+ def _readiness(spec: Any) -> tuple[bool, str]:
+ if spec.slot == "embedding":
+ row = embedding_ready.get(spec.id)
+ if row is None:
+ return False, "this backend is not installed in this build"
+ return bool(row.get("ready")), str(row.get("reason") or "")
+ if spec.slot == "rerank":
+ row = rerank_ready.get(spec.id)
+ if row is None:
+ return False, "this backend is not installed in this build"
+ return bool(row.get("ready")), str(row.get("reason") or "")
+ if spec.slot == "distill":
+ if spec.id in distill_chain:
+ return True, ""
+ return False, (
+ "no usable credential for this provider — save its key "
+ "below, or leave the slot on Automatic and Jarvis uses "
+ "whichever provider you do have"
+ )
+ # storage
+ if spec.db_backend == "sqlite":
+ return True, ""
+ if db_url_present:
+ return True, ""
+ return False, (
+ "no connection string is saved yet — connect below and the "
+ "local SQLite store keeps answering meanwhile"
+ )
+
+ def _row(spec: Any) -> dict[str, Any]:
+ ready, reason = _readiness(spec)
+ return {
+ "id": spec.id,
+ "slot": spec.slot,
+ "label": spec.label,
+ "auth_mode": spec.auth_mode,
+ "secret_keys": list(spec.secret_keys),
+ "dashboard_url": spec.dashboard_url,
+ "credential_help": spec.credential_help,
+ "default_model": spec.default_model,
+ "supports_base_url": spec.supports_base_url,
+ "default_base_url": spec.default_base_url,
+ "recommended": spec.recommended,
+ "caution": spec.caution,
+ "db_backend": spec.db_backend,
+ "connection_hint": spec.connection_hint,
+ "ready": ready,
+ "reason": reason,
+ "selected": selected.get(spec.slot) == spec.id,
+ "secrets_set": {
+ key: _secret_present(key) for key in spec.secret_keys
+ },
+ "secret_shared_with": {
+ key: secret_slot_consumers(key) for key in spec.secret_keys
+ },
+ }
+
+ return {
+ slot: [_row(spec) for spec in provider_catalog.catalog_for_slot(slot)]
+ for slot in provider_catalog.SLOT_NAMES
+ }
+
+ slots = await asyncio.to_thread(_probe)
+ return {
+ "slots": slots,
+ "selected": selected,
+ "models": {
+ "embedding": str(getattr(uw, "embedding_model", "") or ""),
+ "distill": str(getattr(uw, "distill_model", "") or ""),
+ },
+ "ollama_endpoint": str(
+ getattr(uw, "ollama_endpoint", "") or "http://localhost:11434"
+ ),
+ }
+
+
+# ---------------------------------------------------------------------------
+# Storage — the guided Supabase link
+# ---------------------------------------------------------------------------
+
+
+ "/storage/supabase/projects", summary="List the linked Supabase account's projects"
+)
+async def list_supabase_projects(request: Request) -> dict[str, Any]:
+ """Projects visible to the saved Supabase access token (409 when unlinked)."""
+ from jarvis.core.config import get_secret # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.ultrawiki import supabase_link # noqa: PLC0415 — lazy
+
+ token = await asyncio.to_thread(get_secret, "supabase_access_token")
+ if not token:
+ raise HTTPException(
+ status_code=409,
+ detail=(
+ "No Supabase access token is saved. Open the Supabase tokens "
+ "page from the storage card, create a token, and paste it in."
+ ),
+ )
+ try:
+ projects = await supabase_link.list_projects(token)
+ except supabase_link.SupabaseLinkError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+ return {
+ "projects": [p.as_dict() for p in projects],
+ "total": len(projects),
+ "tokens_url": supabase_link.SUPABASE_TOKENS_URL,
+ }
+
+
+class SupabaseLinkBody(BaseModel):
+ """Finish the Supabase link: which project, and its database password."""
+
+ project_ref: str = Field(min_length=1)
+ db_password: str = Field(min_length=1)
+ #: "transaction" (the default, right for a long-lived app pool) or "session".
+ pool_mode: str = "transaction"
+ #: Save even when the connection probe fails. Off by default — a string
+ #: that cannot connect is normally a mistake worth catching here rather
+ #: than as a silent SQLite fallback three restarts later. On for the user
+ #: who knows their network blocks the probe (VPN-only database, firewall).
+ save_anyway: bool = False
+
+
+ "/storage/supabase/link",
+ summary="Link a Supabase project as the UltraWiki store",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def link_supabase_project(
+ body: SupabaseLinkBody, request: Request
+) -> dict[str, Any]:
+ """Assemble, probe and save the Supabase connection string.
+
+ Reads the project's real pooler host from Supabase (guessing the region
+ prefix would produce a string that fails for invisible reasons), adds the
+ password the user supplied, probes the connection, and only then writes the
+ credential and flips the storage slot to Postgres. A failing probe answers
+ 409 with the sanitized reason and saves nothing unless ``save_anyway``.
+ """
+ from jarvis.core.config import get_secret, set_secret # noqa: PLC0415 — lazy
+ from jarvis.ultrawiki import supabase_link # noqa: PLC0415 — lazy
+
+ token = await asyncio.to_thread(get_secret, "supabase_access_token")
+ if not token:
+ raise HTTPException(
+ status_code=409, detail="No Supabase access token is saved."
+ )
+ try:
+ endpoint, note = await supabase_link.resolve_endpoint(
+ token, body.project_ref.strip(), mode=body.pool_mode
+ )
+ conn_str = supabase_link.build_connection_string(endpoint, body.db_password)
+ except supabase_link.SupabaseLinkError as exc:
+ raise HTTPException(status_code=502, detail=str(exc)) from exc
+
+ from jarvis.ultrawiki.store import PostgresStore # noqa: PLC0415 — lazy
+
+ probe_ok, probe_detail = await PostgresStore.connect_test(conn_str)
+ if not probe_ok and not body.save_anyway:
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "message": (
+ f"{note} The connection could not be established, so "
+ f"nothing was saved: {probe_detail}"
+ ),
+ "probe_detail": probe_detail,
+ "endpoint": endpoint.as_dict(),
+ "can_save_anyway": True,
+ },
+ )
+
+ if not await asyncio.to_thread(set_secret, "ultrawiki_db_url", conn_str):
+ raise HTTPException(
+ status_code=500,
+ detail=(
+ "The connection string could not be stored in this machine's "
+ "credential store."
+ ),
+ )
+ values = {"db_backend": "postgres", "storage_provider": "supabase"}
+ persisted, persist_error = _persist_slots(values)
+ _apply_live(request, values)
+ response: dict[str, Any] = {
+ "ok": True,
+ "project_ref": body.project_ref.strip(),
+ "endpoint": endpoint.as_dict(),
+ "note": note,
+ "probe_ok": probe_ok,
+ "probe_detail": probe_detail,
+ "persisted": persisted,
+ "restart_required": True,
+ "detail": (
+ "Supabase is linked. The store switches over on the next app "
+ "restart; until then the current store keeps answering and "
+ "nothing is lost."
+ ),
+ }
+ if persist_error:
+ response["persist_error"] = persist_error
+ return response
+
+
# ---------------------------------------------------------------------------
# Activation / deactivation / settings
# ---------------------------------------------------------------------------
@@ -293,6 +636,7 @@ class ActivateBody(BaseModel):
distill_provider: str = ""
distill_model: str = ""
rerank_provider: str = ""
+ rerank_model: str = ""
areas: list[str] = Field(default_factory=list)
@@ -348,20 +692,43 @@ async def activate_mode(body: ActivateBody, request: Request) -> dict[str, Any]:
values: dict[str, str] = {"embedding_provider": provider}
if db_backend:
values["db_backend"] = db_backend
- for key in ("embedding_model", "distill_provider", "distill_model"):
+ for key in ("embedding_model", "distill_provider", "distill_model", "rerank_model"):
value = str(getattr(body, key) or "").strip()
if value:
values[key] = value
if rerank_provider:
values["rerank_provider"] = rerank_provider
- # Persist FIRST (the disk is the source of truth), then live-apply — the
- # same discipline as PUT /api/settings/wiki-provider.
+ # Ordering matters. The slot values go to disk and into the live config
+ # FIRST (the disk is the source of truth — the PUT
+ # /api/settings/wiki-provider discipline), because the store must open
+ # against the chosen backend. The MODE SWITCH is flipped LAST, only after
+ # the one step that can actually fail — activate() opens the store and
+ # seeds areas + sources. Enabling first meant a failed activation left the
+ # mode ON with no store behind it: the whole Wiki section switched to a
+ # broken Ultra view the user could not get out of.
slots_persisted, slots_error = _persist_slots(values)
+ _apply_live(request, values)
+
+ try:
+ result = await service.activate({"areas": list(body.areas or [])})
+ except Exception as exc: # noqa: BLE001 — the mode stays OFF and untouched
+ log.exception("UltraWiki activation failed; the mode stays off")
+ raise HTTPException(
+ status_code=500,
+ detail=(
+ "UltraWiki could not be activated "
+ f"({type(exc).__name__}: {exc}). The mode stays off and the "
+ "normal wiki keeps answering; your slot choices were saved."
+ ),
+ ) from exc
+
enabled_persisted, enabled_error = _persist_enabled(True)
- _apply_live(request, values, enabled=True)
+ _apply_live(request, {}, enabled=True)
+ # The pipeline only starts while the mode is on, so it is started here —
+ # after the flip, never before it.
+ await service.ensure_started()
- result = await service.activate({"areas": list(body.areas or [])})
response: dict[str, Any] = {
"ok": True,
"enabled": True,
@@ -418,11 +785,26 @@ class UpdateSettingsBody(BaseModel):
"""Slot changes; an embedding change needs confirm_reembed once vectors exist."""
db_backend: str | None = None
+ #: The named storage preset (sqlite / supabase / neon / postgres). When it
+ #: is sent without an explicit ``db_backend``, the functional backend is
+ #: derived from the preset — the UI picks a NAME, never an internal enum.
+ storage_provider: str | None = None
embedding_provider: str | None = None
embedding_model: str | None = None
distill_provider: str | None = None
distill_model: str | None = None
rerank_provider: str | None = None
+ #: Only meaningful for rerank_provider="llm" — empty lets the provider
+ #: chain pick each family's cheap router-tier model.
+ rerank_model: str | None = None
+ ollama_endpoint: str | None = None
+ #: Ranking knobs of the read path. Absolute 0-10 relevance floor for
+ #: unsolicited surfaces, per-leg fusion weights, and the age-decay half
+ #: life in days (0 = no decay).
+ rerank_min_score: float | None = None
+ rrf_keyword_weight: float | None = None
+ rrf_vector_weight: float | None = None
+ recency_half_life_days: float | None = None
confirm_reembed: bool = False
@@ -436,15 +818,36 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
re-embeds the corpus after explicit confirmation."""
service = _service(request)
uw = _uw_cfg(request)
- changes: dict[str, str] = {}
- for key in _SLOT_KEYS:
- value = getattr(body, key)
- if value is None:
- continue
- value = str(value).strip()
- if value != str(getattr(uw, key, "") or "").strip():
- changes[key] = value
- if not changes:
+
+ incoming: dict[str, str] = {
+ key: str(getattr(body, key)).strip()
+ for key in _SLOT_KEYS
+ if getattr(body, key) is not None
+ }
+ # A storage preset is a NAME the user picked; the functional two-value
+ # backend is derived from it so the UI never has to know the internal enum
+ # (and cannot desync from it). An explicit db_backend still wins.
+ preset = incoming.get("storage_provider")
+ if preset:
+ from jarvis.ultrawiki import provider_catalog # noqa: PLC0415 — lazy (AP-26)
+
+ if provider_catalog.get_provider_spec("storage", preset) is None:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown storage provider {preset!r} (available: "
+ f"{[s.id for s in provider_catalog.STORAGE_PROVIDERS]})"
+ ),
+ )
+ incoming.setdefault("db_backend", provider_catalog.storage_backend_of(preset))
+
+ changes = {
+ key: value
+ for key, value in incoming.items()
+ if value != str(getattr(uw, key, "") or "").strip()
+ }
+ ranking_changes = _ranking_changes(body, uw)
+ if not changes and not ranking_changes:
return {"ok": True, "changed": [], "persisted": True, "reembed_started": False}
if "db_backend" in changes and changes["db_backend"] not in ("sqlite", "postgres"):
@@ -498,8 +901,9 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
},
)
- persisted, persist_error = _persist_slots(changes)
- _apply_live(request, changes)
+ applied: dict[str, Any] = {**changes, **ranking_changes}
+ persisted, persist_error = _persist_slots(applied)
+ _apply_live(request, applied)
reembed_started = False
if embedding_change:
store = await _store_of(service)
@@ -510,7 +914,7 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
reembed_started = vector_items > 0
response: dict[str, Any] = {
"ok": True,
- "changed": sorted(changes),
+ "changed": sorted(applied),
"persisted": persisted,
"reembed_started": reembed_started,
}
@@ -522,7 +926,14 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st
@router.post(
"/test/{slot}",
summary="Test one UltraWiki capability slot",
- openapi_extra={"x-jarvis-dangerous": True},
+ openapi_extra={
+ "x-jarvis-dangerous": True,
+ # A real provider call: the embedding path allows 120 s read timeout
+ # (a cold local Ollama model load is slow), and distillation is a full
+ # LLM round trip. The CLI's default client timeout would give up long
+ # before the slot does and report a failure that never happened.
+ "x-jarvis-timeout-seconds": 120,
+ },
)
async def test_slot(slot: str, request: Request) -> dict[str, Any]:
"""Run one real minimal call against a slot (embedding, distill, rerank, or storage)."""
@@ -584,15 +995,28 @@ async def test_slot(slot: str, request: Request) -> dict[str, Any]:
"rerank is not configured or not ready — the fusion order "
"stands (optional stage)",
)
+ # A real grading call over two obviously-unequal documents: it proves
+ # the provider answers AND that the 0-10 scale arrives, which is what
+ # the relevance floor depends on.
try:
- await reranker.rerank(
- "test query",
- ["first test document", "second test document"],
- top_k=1,
+ pairs = await reranker.rerank(
+ "what is the invoice total?",
+ [
+ "The invoice total is 1,240 EUR, due on the 30th.",
+ "sounds good, thanks!",
+ ],
+ top_k=2,
)
except Exception as exc: # noqa: BLE001 — a test reports, never 500s
return _result(False, f"{type(exc).__name__}: {exc}")
- return _result(True, f"reranked two test documents with {reranker.name}")
+ if not pairs:
+ return _result(False, f"{reranker.name} graded no document")
+ best_index, best_score = pairs[0]
+ return _result(
+ True,
+ f"{reranker.name} graded 2 documents; best is #{best_index} "
+ f"at {best_score:.1f}/10",
+ )
if slot == "storage":
service = _service(request)
@@ -711,22 +1135,54 @@ async def delete_source(
return {"ok": True, "deleted": source_id, "purged": bool(purge)}
+class SyncBody(BaseModel):
+ """Sync options. ``full`` is the FULL REFRESH: it clears the resume
+ checkpoint and the incremental cursor so the connector re-reads everything
+ from scratch — the only mode in which deleted items can be detected and
+ tombstoned (a delete is invisible to an incremental run)."""
+
+ full: bool = False
+
+
@router.post(
"/sources/{source_id}/sync",
status_code=201,
summary="Start a sync for one UltraWiki source",
openapi_extra={"x-jarvis-dangerous": True},
)
-async def start_sync(source_id: str, request: Request) -> dict[str, Any]:
- """Start a backfill/incremental sync job for one approved source (201 with the job id)."""
+async def start_sync(
+ source_id: str, request: Request, body: SyncBody | None = None
+) -> dict[str, Any]:
+ """Start a sync job for one approved source; full=true re-reads everything."""
service = _service(request)
+ full = bool(body.full) if body is not None else False
+ from jarvis.ultrawiki.service import ( # noqa: PLC0415 — lazy (AP-26)
+ SyncAlreadyRunningError,
+ )
+
try:
- job_id = await service.start_sync(source_id)
+ job_id = await service.start_sync(source_id, full=full)
+ except SyncAlreadyRunningError as exc:
+ # 409 with the ACTIVE job id, so a caller can watch or cancel it
+ # instead of piling a second interleaving sync onto the same source.
+ raise HTTPException(
+ status_code=409,
+ detail={
+ "message": str(exc),
+ "source_id": exc.source_id,
+ "job_id": exc.job_id,
+ },
+ ) from exc
except ValueError as exc:
message = str(exc)
status_code = 404 if message.startswith("unknown source") else 409
raise HTTPException(status_code=status_code, detail=message) from exc
- return {"job_id": job_id, "status": "queued", "source_id": source_id}
+ return {
+ "job_id": job_id,
+ "status": "queued",
+ "source_id": source_id,
+ "full": full,
+ }
@router.get("/bridge/candidates", summary="List plugin-bridge candidates")
@@ -738,6 +1194,45 @@ async def list_bridge_candidates() -> dict[str, Any]:
return {"candidates": candidates, "total": len(candidates)}
+# ---------------------------------------------------------------------------
+# Pipeline recovery
+# ---------------------------------------------------------------------------
+
+
+class RequeueFailedBody(BaseModel):
+ """Scope of a requeue; ``source_id`` empty means every source."""
+
+ source_id: str = ""
+
+
+ "/pipeline/requeue-failed",
+ summary="Retry UltraWiki items that gave up",
+ openapi_extra={"x-jarvis-dangerous": True},
+)
+async def requeue_failed(
+ request: Request, body: RequeueFailedBody | None = None
+) -> dict[str, Any]:
+ """Return dead-lettered items to the pipeline (they retry from their last completed stage)."""
+ service = _service(request)
+ source_id = (body.source_id.strip() if body is not None else "") or None
+ try:
+ moved = await service.requeue_failed(source_id)
+ except ValueError as exc:
+ raise HTTPException(status_code=404, detail=str(exc)) from exc
+ return {
+ "ok": True,
+ "requeued": moved,
+ "source_id": source_id or "",
+ "detail": (
+ f"{moved} item(s) will be picked up again from their last completed "
+ "stage. Items whose cause is still broken will simply pause there."
+ if moved
+ else "No item was in the failed state — nothing to requeue."
+ ),
+ }
+
+
# ---------------------------------------------------------------------------
# Sync jobs
# ---------------------------------------------------------------------------
@@ -832,17 +1327,11 @@ async def search_ultrawiki(
) -> dict[str, Any]:
"""Fused keyword + vector search, best hits first, each with its citation permalink."""
service = _require_active(request)
- try:
- results = await service.search(q, k=k, area_id=area)
- except AttributeError:
- # The service delegates to jarvis.ultrawiki.search.search(); until
- # that wrapper lands this route calls the hybrid entry point directly.
- from jarvis.ultrawiki import search as search_mod # noqa: PLC0415
-
- store = await _store_of(service)
- results = await search_mod.hybrid_search(
- store, _config(request), q, k=k, area_id=area
- )
+ # The service owns the retrieval delegation (jarvis.ultrawiki.search).
+ # An AttributeError raised INSIDE the search path must surface as the bug
+ # it is, not be swallowed by a compatibility fallback for a wrapper that
+ # has long since landed.
+ results = await service.search(q, k=k, area_id=area)
rows = [
dataclasses.asdict(hit) if dataclasses.is_dataclass(hit) else dict(hit)
for hit in results
diff --git a/jarvis/ultrawiki/embeddings.py b/jarvis/ultrawiki/embeddings.py
index d4c966c623..26e42aa8ed 100644
--- a/jarvis/ultrawiki/embeddings.py
+++ b/jarvis/ultrawiki/embeddings.py
@@ -44,6 +44,7 @@ __all__ = [
"EMBEDDING_BACKENDS",
"DEFAULT_MODELS",
"available_backends",
+ "credential_source",
]
@@ -94,6 +95,16 @@ class _HttpEmbedding:
def __init__(self, *, transport: httpx.BaseTransport | None = None) -> None:
self._transport = transport
+ def credential_source(self) -> str:
+ """Honest, KEY-FREE provenance of what satisfies this backend.
+
+ The settings and Ask surfaces show users which credential or endpoint
+ is actually carrying semantic search ("via your saved Gemini API key"),
+ so a downloader can tell WHY a slot is live. It names the secret slot or
+ endpoint — never the value, and never a truncated value.
+ """
+ return ""
+
def _async_client(self) -> httpx.AsyncClient:
return httpx.AsyncClient(timeout=_EMBED_TIMEOUT, transport=self._transport)
@@ -152,6 +163,9 @@ class OllamaEmbedding(_HttpEmbedding):
super().__init__(transport=transport)
self._endpoint = (endpoint or _DEFAULT_OLLAMA_ENDPOINT).rstrip("/")
+ def credential_source(self) -> str:
+ return f"local Ollama endpoint {self._endpoint} (no key, nothing leaves this machine)"
+
def ready(self) -> tuple[bool, str]:
url = f"{self._endpoint}/api/version"
try:
@@ -188,10 +202,19 @@ class GeminiEmbedding(_HttpEmbedding):
name = "gemini"
_BASE = "https://generativelanguage.googleapis.com/v1beta"
+ _KEY_LABEL = "Gemini"
def _key(self) -> str | None:
return get_secret_any(_GEMINI_KEY_CANDIDATES)
+ def credential_source(self) -> str:
+ # Report WHICH of the accepted slots answered — a user with only
+ # GOOGLE_API_KEY set should see that, not a generic "Gemini key".
+ for slot, env in _GEMINI_KEY_CANDIDATES:
+ if get_secret(slot, env_fallback=env):
+ return f"your saved {self._KEY_LABEL} API key ({slot})"
+ return ""
+
def ready(self) -> tuple[bool, str]:
if self._key():
return True, ""
@@ -242,12 +265,21 @@ class _OpenAIShapedEmbedding(_HttpEmbedding):
def _key(self) -> str | None:
return get_secret(self._SECRET_SLOT)
+ def credential_source(self) -> str:
+ if self._key():
+ return f"your saved {self._KEY_LABEL} API key ({self._SECRET_SLOT})"
+ return ""
+
def ready(self) -> tuple[bool, str]:
if self._key():
return True, ""
+ # Place-neutral on purpose: this line is read on the UltraWiki
+ # settings card (where the key field now sits), in CLI output, and in
+ # logs. It used to send the user to the API-Keys view, which has no
+ # field for this slot -- a dead end dressed up as an instruction.
return False, (
- f"No {self._KEY_LABEL} API key is configured - save "
- f"{self._SECRET_SLOT} in the API-Keys view or set the "
+ f"No {self._KEY_LABEL} API key is configured - enter "
+ f"{self._SECRET_SLOT} on this provider's card, or set the "
f"{self._SECRET_SLOT.upper()} environment variable."
)
@@ -315,6 +347,9 @@ class CohereEmbedding(_HttpEmbedding):
def _key(self) -> str | None:
return get_secret("cohere_api_key")
+ def credential_source(self) -> str:
+ return "your saved Cohere API key (cohere_api_key)" if self._key() else ""
+
def ready(self) -> tuple[bool, str]:
if self._key():
return True, ""
@@ -379,6 +414,23 @@ DEFAULT_MODELS: dict[str, str] = {
}
+def credential_source(name: str, cfg: Any) -> str:
+ """Key-free provenance of one backend's credential/endpoint, or ``""``.
+
+ Asks the ADAPTER (AP-21: no provider-name special-casing out here), so a
+ new backend supplies its own honest phrase and this function never grows a
+ branch. Never raises and never returns any part of a secret value.
+ """
+ factory = EMBEDDING_BACKENDS.get(name)
+ if factory is None:
+ return ""
+ try:
+ return str(factory(cfg).credential_source() or "")
+ except Exception: # noqa: BLE001 — provenance is decoration, never a failure
+ log.debug("embedding backend %s provenance probe failed", name, exc_info=True)
+ return ""
+
+
def available_backends(cfg: Any) -> list[dict[str, Any]]:
"""Readiness report over every registered backend, via ``ready()`` only.
diff --git a/jarvis/ultrawiki/provider_catalog.py b/jarvis/ultrawiki/provider_catalog.py
new file mode 100644
index 0000000000..4098bf9cb9
--- /dev/null
+++ b/jarvis/ultrawiki/provider_catalog.py
@@ -0,0 +1,487 @@
+"""Declarative catalog of every UltraWiki capability-slot provider.
+
+The sibling of :mod:`jarvis.ui.web.provider_spec` for the four UltraWiki slots
+(storage, embedding, distill, rerank). Same doctrine, same reason to exist: the
+settings UI must not hardcode provider knowledge, and there must be exactly ONE
+place that answers "which providers exist for this slot, what credential do
+they need, and where does the user get it".
+
+Why this module had to exist (2026-07-25 gap): the backend registries
+(:mod:`jarvis.ultrawiki.embeddings`, :mod:`jarvis.ultrawiki.rerank`,
+:class:`jarvis.ultrawiki.store.PostgresStore`) already spoke to Voyage, Mistral,
+Cohere and any Postgres server — but the desktop app offered no field to enter
+their credentials, and the settings cards pointed at an API-Keys view that has
+no such card either. The capability was reachable only by hand-editing a config
+file or exporting an environment variable, which the in-app-recoverable mandate
+(§3 of the repo charter, AP-23) forbids. This catalog is what the UI renders
+credential widgets from, so every listed provider is genuinely connectable.
+
+Design rules kept here:
+
+* **No behavior gating on a provider NAME (AP-21).** Everything in a spec is
+ presentation + credential plumbing; the runtime still resolves backends
+ through the registries. ``recommended``/``caution`` are badges only.
+* **Credentials never live in this module** — only the *slot name* under which
+ :func:`jarvis.core.config.get_secret` stores them (AP-12).
+* **Storage presets are presentation over one functional value.** Supabase,
+ Neon and "any Postgres" all resolve to ``db_backend="postgres"`` plus the
+ ``ultrawiki_db_url`` connection string; the preset only decides which help
+ text, dashboard link and connect flow the card shows. Keeping the functional
+ enum at two values (``sqlite`` | ``postgres``) avoids a fresh multi-layer
+ enum-drift surface (AP-4 / BUG-008).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal
+
+__all__ = [
+ "SlotName",
+ "UltraWikiAuthMode",
+ "UltraWikiProviderSpec",
+ "SLOT_NAMES",
+ "STORAGE_PROVIDERS",
+ "EMBEDDING_PROVIDERS",
+ "RERANK_PROVIDERS",
+ "DISTILL_PROVIDERS",
+ "catalog_for_slot",
+ "get_provider_spec",
+ "storage_backend_of",
+ "all_secret_keys",
+]
+
+SlotName = Literal["storage", "embedding", "distill", "rerank"]
+
+#: How a provider is connected.
+#:
+#: ``none`` — runs locally, no credential at all (SQLite, Ollama).
+#: ``api_key`` — one secret slot holds a plain API key.
+#: ``connection_string`` — one secret slot holds a full Postgres URI.
+#: ``managed_link`` — a guided flow assembles the credential for the user
+#: (Supabase: browser login → project pick → password).
+UltraWikiAuthMode = Literal["none", "api_key", "connection_string", "managed_link"]
+
+SLOT_NAMES: tuple[SlotName, ...] = ("storage", "embedding", "distill", "rerank")
+
+
+@dataclass(frozen=True, slots=True)
+class UltraWikiProviderSpec:
+ """One selectable provider inside one UltraWiki capability slot."""
+
+ id: str
+ slot: SlotName
+ label: str
+ auth_mode: UltraWikiAuthMode
+ #: Secret-chain slot names this provider reads, in precedence order. Empty
+ #: for keyless local providers. These MUST be present in the wizard secret
+ #: allowlist, otherwise the UI can render a field the API refuses to save.
+ secret_keys: tuple[str, ...]
+ #: Where the user generates the credential (opened in their browser).
+ dashboard_url: str | None
+ #: Plain-English "which credential, and what it is for".
+ credential_help: str
+ #: Current sensible default model, surfaced as the input placeholder.
+ default_model: str = ""
+ #: True when the card exposes an editable server URL (local providers).
+ supports_base_url: bool = False
+ default_base_url: str | None = None
+ #: Presentation-only badges — never gate a code path on these (AP-21).
+ recommended: bool = False
+ caution: str | None = None
+ #: Storage only: the functional ``[ultrawiki] db_backend`` value this
+ #: preset resolves to. ``None`` for every non-storage slot.
+ db_backend: str | None = None
+ #: Storage only: a one-line shape hint for the connection string.
+ connection_hint: str | None = None
+
+
+# ---------------------------------------------------------------------------
+# Storage — where the knowledge store lives
+# ---------------------------------------------------------------------------
+#
+# SQLite is the universal floor (§3: a headless python:3.11-slim VPS with no
+# credential store must still boot into a working UltraWiki). Every cloud
+# preset below is an OPTIONAL upgrade for multi-device access and degrades back
+# to SQLite with an honest message when its connection string is missing or the
+# server is unreachable (see UltraWikiService._open_store).
+
+STORAGE_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (
+ UltraWikiProviderSpec(
+ id="sqlite",
+ slot="storage",
+ label="SQLite — local file",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ db_backend="sqlite",
+ recommended=True,
+ credential_help=(
+ "A single file under the Jarvis data directory. Zero setup, works "
+ "offline on every operating system, and nothing leaves this "
+ "machine. Pick a cloud store below only when you want the same "
+ "memory on several devices."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="supabase",
+ slot="storage",
+ label="Supabase",
+ auth_mode="managed_link",
+ # The access token drives the guided link flow; the assembled URI is
+ # what the store actually connects with.
+ secret_keys=("ultrawiki_db_url", "supabase_access_token"),
+ dashboard_url="https://supabase.com/dashboard/account/tokens",
+ db_backend="postgres",
+ connection_hint=(
+ "postgresql://postgres.<project-ref>:<password>"
+ "@<region>.pooler.supabase.com:6543/postgres"
+ ),
+ credential_help=(
+ "Hosted Postgres with a generous free tier. Connect signs you in "
+ "through your browser, lists your projects, and builds the "
+ "connection string for you — you only supply the database "
+ "password, which Supabase never hands back over its API."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="neon",
+ slot="storage",
+ label="Neon",
+ auth_mode="connection_string",
+ secret_keys=("ultrawiki_db_url",),
+ dashboard_url="https://console.neon.tech/",
+ db_backend="postgres",
+ connection_hint=(
+ "postgresql://<user>:<password>@<endpoint>.neon.tech/<db>?sslmode=require"
+ ),
+ credential_help=(
+ "Serverless Postgres that scales to zero when idle. Copy the "
+ "pooled connection string from the Neon console — it already "
+ "contains the password — and paste it below."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="postgres",
+ slot="storage",
+ label="Any Postgres server",
+ auth_mode="connection_string",
+ secret_keys=("ultrawiki_db_url",),
+ dashboard_url=None,
+ db_backend="postgres",
+ connection_hint="postgresql://<user>:<password>@<host>:5432/<database>",
+ credential_help=(
+ "Your own Postgres, AWS RDS, Google Cloud SQL, Azure Database, "
+ "Railway, Render — anything that speaks Postgres. Paste the full "
+ "connection string. Install the pgvector extension for semantic "
+ "search; without it keyword search still works."
+ ),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Embedding — the vector space of the whole corpus
+# ---------------------------------------------------------------------------
+#
+# Mirrors jarvis.ultrawiki.embeddings.EMBEDDING_BACKENDS one-to-one. Deliberate
+# design rule D-3: this slot has NO cross-family fallback, because the
+# (backend, model) pair pins the vector space — crossing families mid-ingest
+# would mix incompatible vectors. A dead backend pauses the embed stage
+# honestly instead.
+
+EMBEDDING_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (
+ UltraWikiProviderSpec(
+ id="ollama",
+ slot="embedding",
+ label="Ollama (local)",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ default_model="bge-m3",
+ supports_base_url=True,
+ default_base_url="http://localhost:11434",
+ recommended=True,
+ credential_help=(
+ "Embeds fully on your own machine — no API key, no cloud account, "
+ "no per-item cost, and no text ever leaves your network. Install "
+ "Ollama and pull an embedding model (ollama pull bge-m3). Point "
+ "the server URL at another machine to share one Ollama box."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="gemini",
+ slot="embedding",
+ label="Google Gemini",
+ auth_mode="api_key",
+ secret_keys=("gemini_api_key",),
+ dashboard_url="https://aistudio.google.com/app/apikey",
+ default_model="gemini-embedding-001",
+ credential_help=(
+ "The same Google AI Studio key as the Gemini brain (starts with "
+ "AIza or AQ.) — no second key needed. Billed per token on your AI "
+ "Studio project."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="openai",
+ slot="embedding",
+ label="OpenAI",
+ auth_mode="api_key",
+ secret_keys=("openai_api_key",),
+ dashboard_url="https://platform.openai.com/api-keys",
+ default_model="text-embedding-3-small",
+ credential_help=(
+ "The same OpenAI key as the GPT brain (starts with sk-). "
+ "text-embedding-3-small is inexpensive and strong for this job."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="voyage",
+ slot="embedding",
+ label="Voyage AI",
+ auth_mode="api_key",
+ secret_keys=("voyage_api_key",),
+ dashboard_url="https://dash.voyageai.com/api-keys",
+ default_model="voyage-3.5",
+ credential_help=(
+ "A retrieval-specialised embedding provider — usually the best "
+ "search quality per euro here. The same key also powers the "
+ "Voyage reranker below."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="mistral",
+ slot="embedding",
+ label="Mistral",
+ auth_mode="api_key",
+ secret_keys=("mistral_api_key",),
+ dashboard_url="https://console.mistral.ai/api-keys",
+ default_model="mistral-embed",
+ credential_help=(
+ "European provider (data processed in the EU). One model, "
+ "mistral-embed, billed per token on your Mistral account."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="cohere",
+ slot="embedding",
+ label="Cohere",
+ auth_mode="api_key",
+ secret_keys=("cohere_api_key",),
+ dashboard_url="https://dashboard.cohere.com/api-keys",
+ default_model="embed-v4.0",
+ credential_help=(
+ "Strong multilingual embeddings — a good pick when your notes mix "
+ "languages. The same key also powers the Cohere reranker below."
+ ),
+ ),
+)
+
+
+# ---------------------------------------------------------------------------
+# Rerank — optional last retrieval stage
+# ---------------------------------------------------------------------------
+#
+# Mirrors jarvis.ultrawiki.rerank.RERANK_BACKENDS. Skipping this stage is a
+# first-class outcome, not a failure: without a reranker the fusion order
+# stands and search keeps working.
+
+RERANK_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (
+ # Leads and carries the recommendation because it is the only rerank
+ # option that works for an arbitrary downloader: it grades through the
+ # key-aware cross-family chat chain, so a cloud key, a subscription CLI or
+ # a purely local Ollama all satisfy it (§3, AP-22). The vendor
+ # cross-encoders below are faster but each needs its own paid account.
+ UltraWikiProviderSpec(
+ id="llm",
+ slot="rerank",
+ label="Your chat providers (no extra account)",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ recommended=True,
+ credential_help=(
+ "Grades the best candidates with the chat providers you already "
+ "have — a cloud key, a subscription CLI, or a local Ollama model "
+ "offline. Needs no extra account and no second key. Slightly "
+ "slower than a dedicated reranker, which barely matters because "
+ "the stage only re-scores a handful of results."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="voyage",
+ slot="rerank",
+ label="Voyage AI",
+ auth_mode="api_key",
+ secret_keys=("voyage_api_key",),
+ dashboard_url="https://dash.voyageai.com/api-keys",
+ default_model="rerank-2.5",
+ credential_help=(
+ "A dedicated cross-encoder: lower latency than grading with a chat "
+ "model, at the cost of a paid single-vendor account. The same "
+ "Voyage key as the embedding slot — one key covers both."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="cohere",
+ slot="rerank",
+ label="Cohere",
+ auth_mode="api_key",
+ secret_keys=("cohere_api_key",),
+ dashboard_url="https://dashboard.cohere.com/api-keys",
+ default_model="rerank-v3.5",
+ credential_help=(
+ "Cohere's rerank model, strong across languages. The same Cohere "
+ "key as the embedding slot — one key covers both."
+ ),
+ ),
+)
+
+#: Rerank models are pinned by the backend, not chosen in the settings card —
+#: except ``llm``, whose model comes from whichever chat provider the chain
+#: reaches. Kept as an explicit statement so a future "model" input on this
+#: slot has to justify itself rather than appear by copy-paste.
+RERANK_MODEL_IS_USER_CHOSEN = False
+
+
+# ---------------------------------------------------------------------------
+# Distillation — the chat model that normalises each captured item
+# ---------------------------------------------------------------------------
+#
+# Unlike embeddings, this slot DOES cross provider families (AP-22): it runs
+# through the shared wiki provider chain, so a 429 or a dead key moves on to
+# whatever other credential the user has. The catalog rows below exist so the
+# card can offer the key field inline; leaving the slot empty ("Automatic")
+# lets the chain pick, which is the honest default.
+
+DISTILL_PROVIDERS: tuple[UltraWikiProviderSpec, ...] = (
+ UltraWikiProviderSpec(
+ id="gemini",
+ slot="distill",
+ label="Google Gemini",
+ auth_mode="api_key",
+ secret_keys=("gemini_api_key",),
+ dashboard_url="https://aistudio.google.com/app/apikey",
+ default_model="gemini-3.5-flash",
+ recommended=True,
+ credential_help=(
+ "Google AI Studio key (AIza / AQ.). A fast flash model is exactly "
+ "right here — distillation is a high-volume background job, not a "
+ "reasoning task."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="openai",
+ slot="distill",
+ label="OpenAI",
+ auth_mode="api_key",
+ secret_keys=("openai_api_key",),
+ dashboard_url="https://platform.openai.com/api-keys",
+ credential_help="OpenAI API key (sk-), shared with the GPT brain.",
+ ),
+ UltraWikiProviderSpec(
+ id="claude-api",
+ slot="distill",
+ label="Claude (API key)",
+ auth_mode="api_key",
+ secret_keys=("anthropic_api_key",),
+ dashboard_url="https://console.anthropic.com/settings/keys",
+ credential_help="Anthropic API key (sk-ant-), shared with the Claude brain.",
+ ),
+ UltraWikiProviderSpec(
+ id="openrouter",
+ slot="distill",
+ label="OpenRouter",
+ auth_mode="api_key",
+ secret_keys=("openrouter_api_key",),
+ dashboard_url="https://openrouter.ai/keys",
+ credential_help=(
+ "OpenRouter API key (sk-or-). One key reaches many models — handy "
+ "when you want a cheap model for this background job."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="grok",
+ slot="distill",
+ label="xAI Grok",
+ auth_mode="api_key",
+ secret_keys=("grok_api_key",),
+ dashboard_url="https://console.x.ai/",
+ credential_help="xAI API key (xai-), shared with the Grok brain.",
+ ),
+ UltraWikiProviderSpec(
+ id="nvidia",
+ slot="distill",
+ label="NVIDIA NIM",
+ auth_mode="api_key",
+ secret_keys=("nvidia_api_key",),
+ dashboard_url="https://build.nvidia.com/settings/api-keys",
+ credential_help=(
+ "NVIDIA API key (nvapi-) from build.nvidia.com. The free tier is "
+ "slow to first token, which matters little for a background job."
+ ),
+ ),
+ UltraWikiProviderSpec(
+ id="ollama",
+ slot="distill",
+ label="Ollama (local)",
+ auth_mode="none",
+ secret_keys=(),
+ dashboard_url=None,
+ supports_base_url=True,
+ default_base_url="http://localhost:11434",
+ credential_help=(
+ "Distills on your own machine — no key, no cost, nothing leaves "
+ "your network. Slower than a hosted flash model, but this runs in "
+ "the background so latency barely matters."
+ ),
+ ),
+)
+
+
+_BY_SLOT: dict[str, tuple[UltraWikiProviderSpec, ...]] = {
+ "storage": STORAGE_PROVIDERS,
+ "embedding": EMBEDDING_PROVIDERS,
+ "distill": DISTILL_PROVIDERS,
+ "rerank": RERANK_PROVIDERS,
+}
+
+
+def catalog_for_slot(slot: str) -> tuple[UltraWikiProviderSpec, ...]:
+ """Every declared provider for ``slot`` (empty tuple when unknown)."""
+ return _BY_SLOT.get(slot, ())
+
+
+def get_provider_spec(slot: str, provider_id: str) -> UltraWikiProviderSpec | None:
+ """One spec by (slot, id). ``None`` when either is unknown."""
+ for spec in catalog_for_slot(slot):
+ if spec.id == provider_id:
+ return spec
+ return None
+
+
+def storage_backend_of(preset_id: str) -> str:
+ """The functional ``db_backend`` a storage preset resolves to.
+
+ Unknown presets fall back to ``"sqlite"`` — the universal floor is always
+ a safe answer, and an unknown preset means an older or newer config than
+ this build knows about, not a reason to refuse to open a store.
+ """
+ spec = get_provider_spec("storage", preset_id)
+ return spec.db_backend or "sqlite" if spec else "sqlite"
+
+
+def all_secret_keys() -> set[str]:
+ """Every secret slot any UltraWiki provider reads.
+
+ Used by the test that pins these against the wizard allowlist: a catalog
+ entry the secrets API would refuse to save is a dead field in the UI, which
+ is exactly the defect this module was written to end.
+ """
+ return {
+ key
+ for specs in _BY_SLOT.values()
+ for spec in specs
+ for key in spec.secret_keys
+ }
diff --git a/jarvis/ultrawiki/rerank.py b/jarvis/ultrawiki/rerank.py
index d4830c3846..abafe7a9cf 100644
--- a/jarvis/ultrawiki/rerank.py
+++ b/jarvis/ultrawiki/rerank.py
@@ -1,11 +1,29 @@
-"""UltraWiki rerank backends — thin httpx adapters for Voyage and Cohere.
+"""UltraWiki rerank backends — the LLM chain plus Voyage and Cohere adapters.
Rerank is an OPTIONAL retrieval stage (design doc 03): a small scoring model
re-scores the fused top-N candidates against the actual question. When no
rerank-capable provider is configured or the configured one is not ready, the
caller skips the stage honestly and the fusion order stands — never a brick.
-Adapters are plain HTTP (no SDKs); credentials resolve through
+**Scores are absolute, on a 0-10 scale, for EVERY backend.** That is the whole
+point of the stage (Cerebras: "it gives each document a score from zero to ten,
+and we keep the top ten"): RRF fusion is ordinal and can never say "nothing
+here is relevant", while a 0-10 grade can. Every unsolicited surface gates on
+that number (``[ultrawiki].rerank_min_score``), so the scale must not depend on
+which backend answered — the vendor adapters normalize their native 0-1
+relevance by x10 (AP-21: gate on the capability, never on the provider name).
+
+Three backends:
+
+- ``llm`` — the universal one. Grades through the key-aware, cross-family wiki
+ provider chain (identical to :mod:`jarvis.ultrawiki.distill`), so it runs on
+ whatever the install actually holds: a cloud key, a subscription CLI, or a
+ purely local Ollama with no network at all. This is what keeps the stage
+ alive for an arbitrary downloader (§3, AP-22).
+- ``voyage`` / ``cohere`` — dedicated cross-encoder APIs for installs that hold
+ one of those keys; lower latency, but a paid single-vendor path.
+
+Vendor adapters are plain HTTP (no SDKs); credentials resolve through
:func:`jarvis.core.config.get_secret`. ``ready()`` is a credential-presence
probe only (AP-21): never raises, never performs a paid call. A failing rerank
call raises :class:`RerankError`; the retrieval path catches it and falls back
@@ -26,10 +44,14 @@ log = logging.getLogger(__name__)
__all__ = [
"RerankError",
+ "LLMReranker",
"VoyageReranker",
"CohereReranker",
"RERANK_BACKENDS",
"DEFAULT_RERANK_MODELS",
+ "MAX_SCORE",
+ "build_rerank_prompt",
+ "parse_rerank_scores",
"available_rerankers",
"resolve_reranker",
]
@@ -40,15 +62,30 @@ class RerankError(RuntimeError):
skips the stage and keeps the fusion order."""
+#: The one relevance scale every backend reports on (Cerebras: zero to ten).
+MAX_SCORE = 10.0
+
_RERANK_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=10.0, pool=5.0)
-#: Sensible current default model per backend.
+#: Sensible current default model per backend. The LLM backend has no fixed
+#: default — the provider chain picks each family's cheap router-tier model.
DEFAULT_RERANK_MODELS: dict[str, str] = {
+ "llm": "",
"voyage": "rerank-2.5",
"cohere": "rerank-v3.5",
}
+def _to_scale(value: Any) -> float:
+ """Vendor 0-1 relevance -> the shared 0-10 grade, clamped."""
+ return round(min(max(float(value) * MAX_SCORE, 0.0), MAX_SCORE), 4)
+
+
+def _clamp_score(value: Any) -> float:
+ """An already-0-10 grade, clamped (a model may answer 11 or -1)."""
+ return round(min(max(float(value), 0.0), MAX_SCORE), 4)
+
+
class _HttpReranker:
"""Shared httpx plumbing; ``transport`` is injectable for offline tests."""
@@ -72,9 +109,11 @@ class _HttpReranker:
def ready(self) -> tuple[bool, str]:
if self._key():
return True, ""
+ # Place-neutral: the key field lives on this provider's own settings
+ # card now, not in the API-Keys view (which has no slot for it).
return False, (
- f"No {self._KEY_LABEL} API key is configured - save "
- f"{self._SECRET_SLOT} in the API-Keys view or set the "
+ f"No {self._KEY_LABEL} API key is configured - enter "
+ f"{self._SECRET_SLOT} on this provider's card, or set the "
f"{self._SECRET_SLOT.upper()} environment variable."
)
@@ -140,7 +179,8 @@ class VoyageReranker(_HttpReranker):
def _parse(self, data: Any) -> list[tuple[int, float]]:
return [
- (int(row["index"]), float(row["relevance_score"])) for row in data["data"]
+ (int(row["index"]), _to_scale(row["relevance_score"]))
+ for row in data["data"]
]
@@ -162,19 +202,288 @@ class CohereReranker(_HttpReranker):
def _parse(self, data: Any) -> list[tuple[int, float]]:
return [
- (int(row["index"]), float(row["relevance_score"]))
+ (int(row["index"]), _to_scale(row["relevance_score"]))
for row in data["results"]
]
-#: name -> factory(cfg). cfg is unused today (keys ride the secret chain) but
-#: keeps the registry shape identical to the embedding slot.
+# ---------------------------------------------------------------------------
+# LLM reranker — the universal backend
+# ---------------------------------------------------------------------------
+
+#: Candidate text is truncated before grading: a relevance judgement needs the
+#: opening of a document, not its full body, and 20 untruncated candidates
+#: would dominate a cheap model's context window.
+_DOC_TRUNCATE_CHARS = 700
+_DOC_TRUNCATION_MARKER = " […]"
+
+_LLM_TIMEOUT_S = 45.0
+
+_LLM_SYSTEM_PROMPT = (
+ "You are a precise relevance grader inside a personal memory search "
+ "engine. You grade how well each candidate document answers ONE question. "
+ "You answer with STRICT minified JSON only - no prose, no markdown fences, "
+ "no keys beyond the requested ones. You grade what is written, you never "
+ "invent content a candidate does not contain."
+)
+
+
+def _truncate_document(text: str) -> str:
+ flat = " ".join(str(text or "").split())
+ if len(flat) <= _DOC_TRUNCATE_CHARS:
+ return flat
+ return flat[:_DOC_TRUNCATE_CHARS] + _DOC_TRUNCATION_MARKER
+
+
+def build_rerank_prompt(query: str, documents: list[str]) -> str:
+ """The grading prompt: XML-tagged sections, strict-JSON contract.
+
+ Candidates are numbered so the model answers with indices instead of
+ echoing text back — cheaper, and it cannot rename a document.
+ """
+ candidates = "\n".join(
+ f"[{index}] {_truncate_document(text)}"
+ for index, text in enumerate(documents)
+ )
+ return (
+ "<task>\n"
+ "Grade how well each candidate answers the question below.\n"
+ "</task>\n"
+ f"<question>{' '.join(str(query).split())}</question>\n"
+ f"<candidates>\n{candidates}\n</candidates>\n"
+ "<scale>\n"
+ "10 = directly and completely answers the question\n"
+ "7-9 = answers it, or contains the decisive fact\n"
+ "4-6 = related and useful background, but does not answer it\n"
+ "1-3 = same topic area only, or a near-duplicate wording that "
+ "answers a DIFFERENT question\n"
+ "0 = unrelated, or pure filler with no information\n"
+ "</scale>\n"
+ "<output_format>\n"
+ "Return STRICT minified JSON on a single line, one entry per "
+ "candidate, in any order:\n"
+ '{"scores":[{"i":0,"score":7},{"i":1,"score":0}]}\n'
+ "Rules: no markdown fences; no additional keys; no commentary; \"i\" is\n"
+ "the candidate number shown in brackets; \"score\" is an integer 0-10.\n"
+ "Grade every candidate, including the ones you score 0.\n"
+ "</output_format>"
+ )
+
+
+def parse_rerank_scores(text: str, *, count: int) -> list[tuple[int, float]]:
+ """Salvage ``(index, score)`` pairs out of a model's grading answer.
+
+ Out-of-range indices, duplicates, and unparseable entries are dropped;
+ candidates the model never mentioned simply do not appear (the caller
+ appends them below the graded ones, keeping fusion order among them).
+ Raises :class:`RerankError` when nothing usable could be salvaged, which
+ lets the provider chain try the next family.
+ """
+ from jarvis.ultrawiki.distill import extract_json_object # noqa: PLC0415 — lazy (AP-26)
+
+ extracted = extract_json_object(text)
+ if extracted is None:
+ raise RerankError("llm: grading output holds no parseable JSON object")
+ _, parsed = extracted
+ rows = parsed.get("scores")
+ if not isinstance(rows, (list, tuple)):
+ raise RerankError("llm: grading JSON has no 'scores' array")
+ pairs: list[tuple[int, float]] = []
+ seen: set[int] = set()
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ try:
+ index = int(row["i"])
+ score = _clamp_score(row["score"])
+ except (KeyError, TypeError, ValueError):
+ continue
+ if index < 0 or index >= count or index in seen:
+ continue
+ seen.add(index)
+ pairs.append((index, score))
+ if not pairs:
+ raise RerankError("llm: grading output scored no candidate")
+ pairs.sort(key=lambda pair: (-pair[1], pair[0]))
+ return pairs
+
+
+class LLMReranker:
+ """Grades candidates through the key-aware, cross-family provider chain.
+
+ The universal backend: it needs no rerank-specific vendor account, only a
+ chat provider the install already has — including a purely local Ollama on
+ a headless box. Model resolution mirrors :mod:`jarvis.ultrawiki.distill`:
+ an explicit ``[ultrawiki].rerank_model`` applies to the configured leading
+ provider, every other credential-ready family follows with its own cheap
+ router-tier model.
+ """
+
+ name = "llm"
+
+ def __init__(
+ self,
+ cfg: Any = None,
+ *,
+ registry: Any = None,
+ timeout_s: float = _LLM_TIMEOUT_S,
+ ) -> None:
+ self._cfg = cfg
+ self._registry = registry
+ self._timeout_s = timeout_s
+
+ # -- chain ---------------------------------------------------------------
+
+ def _build_registry(self) -> Any:
+ if self._registry is None:
+ from jarvis.brain.provider_registry import ( # noqa: PLC0415 — lazy (AP-26)
+ BrainProviderRegistry,
+ )
+
+ self._registry = BrainProviderRegistry()
+ return self._registry
+
+ def _chain(self) -> list[tuple[str, str | None]]:
+ """Ordered ``(provider, model)`` attempts; empty when nothing is ready."""
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy (AP-26)
+ build_wiki_provider_chain,
+ credential_ready_wiki_providers,
+ )
+
+ cfg = self._cfg
+ ultrawiki = getattr(cfg, "ultrawiki", None)
+ configured = str(getattr(ultrawiki, "rerank_model", "") or "").strip()
+ # An explicit rerank PROVIDER cannot be named here: "llm" IS the slot
+ # value. The chain therefore leads with the distill provider when set
+ # (same tier of work, same cheap models), else the brain primary.
+ lead = str(getattr(ultrawiki, "distill_provider", "") or "").strip()
+ if not lead:
+ brain = getattr(cfg, "brain", None)
+ lead = str(getattr(brain, "primary", "") or "")
+ available = set(self._build_registry().available())
+ credential_ready = credential_ready_wiki_providers(
+ available=available, config=cfg
+ )
+ return build_wiki_provider_chain(
+ primary=lead,
+ model_override=configured,
+ available=available,
+ credential_ready=credential_ready,
+ )
+
+ def credential_source(self) -> str:
+ """Key-free provenance: which family would actually grade (the HTTP
+ adapters' twin, so the settings card can say where this runs)."""
+ try:
+ chain = self._chain()
+ except Exception: # noqa: BLE001 — provenance is decoration, never a failure
+ return ""
+ if not chain:
+ return ""
+ provider, model = chain[0]
+ suffix = f" ({model})" if model else ""
+ return f"your configured {provider} chat provider{suffix}"
+
+ def ready(self) -> tuple[bool, str]:
+ """Credential-presence probe only (AP-21) — never a paid call."""
+ try:
+ chain = self._chain()
+ except Exception as exc: # noqa: BLE001 — a broken probe reports, never raises
+ log.debug("llm rerank chain probe failed", exc_info=True)
+ return False, f"provider chain probe failed ({type(exc).__name__})"
+ if chain:
+ return True, ""
+ return False, (
+ "No credential-ready chat provider is available to grade results - "
+ "save any provider key in the API-Keys view, connect a "
+ "subscription CLI, or run a local Ollama model."
+ )
+
+ # -- grading -------------------------------------------------------------
+
+ async def rerank(
+ self, query: str, documents: list[str], top_k: int
+ ) -> list[tuple[int, float]]:
+ """Grade ``documents`` 0-10 against ``query``; best first, at most
+ ``top_k`` entries."""
+ if not documents:
+ return []
+ from jarvis.brain.streaming import aggregate # noqa: PLC0415 — lazy (AP-26)
+ from jarvis.core.protocols import ( # noqa: PLC0415 — lazy (AP-26)
+ BrainMessage,
+ BrainRequest,
+ )
+ from jarvis.memory.wiki.provider_chain import ( # noqa: PLC0415 — lazy (AP-26)
+ complete_with_fallback,
+ )
+
+ chain = self._chain()
+ if not chain:
+ raise RerankError("llm: no credential-ready provider to grade with")
+
+ count = len(documents)
+
+ def _validate(agg: Any) -> str | None:
+ """A transport success whose text holds no usable grades is
+ unusable output — the chain then tries the next family."""
+ try:
+ parse_rerank_scores(getattr(agg, "text", "") or "", count=count)
+ except RerankError as exc:
+ return str(exc)
+ return None
+
+ request = BrainRequest(
+ messages=(
+ BrainMessage(
+ role="user", content=build_rerank_prompt(query, documents)
+ ),
+ ),
+ system=_LLM_SYSTEM_PROMPT,
+ temperature=0.0, # grading, not creativity
+ max_tokens=1200,
+ stream=True,
+ )
+ result = await complete_with_fallback(
+ registry=self._build_registry(),
+ chain=chain,
+ request=request,
+ timeout_s=self._timeout_s,
+ label="UltraWikiReranker",
+ aggregate=aggregate,
+ validate=_validate,
+ )
+ if result is None:
+ raise RerankError(
+ "llm: no configured provider returned usable relevance grades"
+ )
+ agg, provider = result
+ pairs = parse_rerank_scores(getattr(agg, "text", "") or "", count=count)
+ log.debug("reranked %d candidates via provider %s", count, provider)
+ return pairs[: max(0, int(top_k))]
+
+
+#: name -> factory(cfg). ``llm`` leads: it is the backend that works with
+#: whatever credential the install actually holds (§3, AP-22), while the vendor
+#: adapters need one specific paid account. cfg is unused by the HTTP adapters
+#: (their keys ride the secret chain) but keeps one registry shape.
RERANK_BACKENDS: dict[str, Callable[[Any], Any]] = {
+ "llm": lambda cfg: LLMReranker(cfg),
"voyage": lambda cfg: VoyageReranker(),
"cohere": lambda cfg: CohereReranker(),
}
+#: One-line English explanation per backend for the settings surface.
+RERANK_DETAILS: dict[str, str] = {
+ "llm": (
+ "Grades results with the chat providers you already have — cloud key, "
+ "subscription CLI, or a local Ollama model offline. No extra account."
+ ),
+ "voyage": "Dedicated Voyage AI reranking model — needs a Voyage API key.",
+ "cohere": "Dedicated Cohere reranking model — needs a Cohere API key.",
+}
+
+
def available_rerankers(cfg: Any) -> list[dict[str, Any]]:
"""Readiness report over every rerank backend, via ``ready()`` only."""
rows: list[dict[str, Any]] = []
@@ -190,6 +499,7 @@ def available_rerankers(cfg: Any) -> list[dict[str, Any]]:
"ready": usable,
"reason": reason,
"default_model": DEFAULT_RERANK_MODELS.get(name, ""),
+ "detail": RERANK_DETAILS.get(name, ""),
}
)
return rows
diff --git a/jarvis/ultrawiki/supabase_link.py b/jarvis/ultrawiki/supabase_link.py
new file mode 100644
index 0000000000..1f8ee9515f
--- /dev/null
+++ b/jarvis/ultrawiki/supabase_link.py
@@ -0,0 +1,308 @@
+"""Guided Supabase link flow for the UltraWiki storage slot.
+
+The problem this solves: a Postgres store needs a connection string, and
+Supabase — the most common free hosted Postgres — spreads the pieces of that
+string across three dashboard pages. Asking a user to hand-assemble
+``postgresql://postgres.<ref>:<password>@<region>.pooler.supabase.com:6543/postgres``
+is exactly the kind of out-of-app setup step the in-app-recoverable mandate
+(§3, AP-23) exists to prevent, and the region prefix in that hostname is not
+derivable from the project ref — guessing it produces a string that fails to
+connect for reasons the user cannot see.
+
+So Jarvis asks Supabase instead. With a personal access token the user creates
+in their already-signed-in browser, this module:
+
+1. lists the user's projects (``GET /v1/projects``),
+2. reads the project's REAL pooler host/port/user
+ (``GET /v1/projects/{ref}/config/database/pooler``), falling back to the
+ documented direct-connection shape when that config is unavailable,
+3. assembles the connection string once the user supplies the database
+ password — the one piece Supabase deliberately never returns over its API.
+
+Everything is plain httpx (no SDK), so it behaves identically on Windows,
+macOS and a headless Linux box. Nothing here writes a secret: the caller saves
+the assembled URI through :func:`jarvis.core.config.set_secret` under
+``ultrawiki_db_url`` (AP-12), and the token itself rides the same chain under
+``supabase_access_token``.
+
+Honesty rule for every function below: no exception escapes with a credential
+in its message, and a failure says which step failed in plain words.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any
+from urllib.parse import quote
+
+import httpx
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "SUPABASE_API_BASE",
+ "SUPABASE_TOKENS_URL",
+ "SupabaseLinkError",
+ "SupabaseProject",
+ "PoolerEndpoint",
+ "build_connection_string",
+ "direct_endpoint_for",
+ "list_projects",
+ "pooler_endpoint",
+ "resolve_endpoint",
+]
+
+SUPABASE_API_BASE = "https://api.supabase.com"
+
+#: Where the user creates the personal access token. Opened in their browser
+#: by the Connect button — they are already signed in there, which is what
+#: makes this a browser login rather than a copy-paste chore.
+SUPABASE_TOKENS_URL = "https://supabase.com/dashboard/account/tokens"
+
+#: The Management API is a control-plane API: fast, but a cold project or a
+#: throttled account can take a few seconds.
+_TIMEOUT = httpx.Timeout(connect=5.0, read=20.0, write=10.0, pool=5.0)
+
+#: Transaction mode (6543) is the right default for a long-lived application
+#: pool; session mode (5432) exists for tools that need session state.
+_POOL_MODE_PORTS: dict[str, int] = {"transaction": 6543, "session": 5432}
+
+
+class SupabaseLinkError(RuntimeError):
+ """A Management-API step failed. Message is safe to show the user."""
+
+
+@dataclass(frozen=True, slots=True)
+class SupabaseProject:
+ """One project row, trimmed to what the picker needs."""
+
+ ref: str
+ name: str
+ region: str
+ status: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {
+ "ref": self.ref,
+ "name": self.name,
+ "region": self.region,
+ "status": self.status,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class PoolerEndpoint:
+ """Everything but the password, as Supabase itself reports it."""
+
+ host: str
+ port: int
+ user: str
+ database: str
+ #: "transaction" | "session" | "direct" — what the user is connecting to.
+ mode: str
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "host": self.host,
+ "port": self.port,
+ "user": self.user,
+ "database": self.database,
+ "mode": self.mode,
+ }
+
+
+def _headers(token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {token}", "Accept": "application/json"}
+
+
+async def _get_json(
+ token: str,
+ path: str,
+ *,
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> Any:
+ """GET one Management-API path, mapping every failure to a plain message.
+
+ HTTP 401/403 is by far the most common real failure (an expired or
+ mistyped token), so it gets its own sentence instead of a bare status code.
+ """
+ url = f"{SUPABASE_API_BASE}{path}"
+ try:
+ async with httpx.AsyncClient(timeout=_TIMEOUT, transport=transport) as client:
+ response = await client.get(url, headers=_headers(token))
+ response.raise_for_status()
+ return response.json()
+ except httpx.HTTPStatusError as exc:
+ status = exc.response.status_code
+ if status in (401, 403):
+ raise SupabaseLinkError(
+ "Supabase rejected the access token. Create a fresh personal "
+ "access token and connect again."
+ ) from exc
+ if status == 404:
+ raise SupabaseLinkError(
+ "Supabase has no such project, or this token cannot see it."
+ ) from exc
+ raise SupabaseLinkError(
+ f"Supabase answered HTTP {status} for this request."
+ ) from exc
+ except httpx.HTTPError as exc:
+ raise SupabaseLinkError(
+ f"Could not reach the Supabase API ({type(exc).__name__}). "
+ "Check this machine's internet connection."
+ ) from exc
+ except ValueError as exc: # body was not JSON
+ raise SupabaseLinkError(
+ "The Supabase API returned something that is not valid JSON."
+ ) from exc
+
+
+async def list_projects(
+ token: str, *, transport: httpx.AsyncBaseTransport | None = None
+) -> list[SupabaseProject]:
+ """Every project the token can see, newest-usable first.
+
+ Active projects sort ahead of paused/inactive ones so the picker's first
+ entry is a project that can actually accept a connection.
+ """
+ if not token.strip():
+ raise SupabaseLinkError("No Supabase access token is saved yet.")
+ data = await _get_json(token, "/v1/projects", transport=transport)
+ if not isinstance(data, list):
+ raise SupabaseLinkError(
+ "The Supabase project list had an unexpected shape."
+ )
+ projects = [
+ SupabaseProject(
+ ref=str(row.get("id") or row.get("ref") or "").strip(),
+ name=str(row.get("name") or "").strip() or "(unnamed project)",
+ region=str(row.get("region") or "").strip(),
+ status=str(row.get("status") or "").strip(),
+ )
+ for row in data
+ if isinstance(row, dict)
+ ]
+ projects = [p for p in projects if p.ref]
+ projects.sort(key=lambda p: (p.status.upper() != "ACTIVE_HEALTHY", p.name.lower()))
+ return projects
+
+
+def direct_endpoint_for(ref: str) -> PoolerEndpoint:
+ """The documented direct-connection shape, derivable from the ref alone.
+
+ Used when the pooler config is unavailable. Worth knowing before you rely
+ on it: Supabase serves the direct host over IPv6 only unless the project
+ has the IPv4 add-on, so on an IPv4-only network the pooler is the endpoint
+ that actually connects. The caller says which one it used.
+ """
+ return PoolerEndpoint(
+ host=f"db.{ref}.supabase.co",
+ port=5432,
+ user="postgres",
+ database="postgres",
+ mode="direct",
+ )
+
+
+def _endpoint_from_row(row: dict[str, Any], ref: str, mode: str) -> PoolerEndpoint | None:
+ host = str(row.get("db_host") or "").strip()
+ if not host:
+ return None
+ try:
+ port = int(row.get("db_port") or _POOL_MODE_PORTS.get(mode, 6543))
+ except (TypeError, ValueError):
+ port = _POOL_MODE_PORTS.get(mode, 6543)
+ return PoolerEndpoint(
+ host=host,
+ # A pooler row reports the port of ITS own mode; when the user asked
+ # for the other mode the host is identical and only the port differs
+ # (documented Supavisor behaviour), so honour the requested mode.
+ port=_POOL_MODE_PORTS.get(mode, port),
+ user=str(row.get("db_user") or f"postgres.{ref}").strip(),
+ database=str(row.get("db_name") or "postgres").strip(),
+ mode=mode,
+ )
+
+
+async def pooler_endpoint(
+ token: str,
+ ref: str,
+ *,
+ mode: str = "transaction",
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> PoolerEndpoint | None:
+ """The project's real pooler endpoint, or ``None`` when unavailable.
+
+ ``None`` is not an error: some projects and some token scopes simply do not
+ expose this config, and the caller then falls back to the direct endpoint.
+ The Management API has returned both a bare object and a list of per-mode
+ rows over its lifetime, so both shapes are accepted.
+ """
+ if mode not in _POOL_MODE_PORTS:
+ mode = "transaction"
+ try:
+ data = await _get_json(
+ token, f"/v1/projects/{ref}/config/database/pooler", transport=transport
+ )
+ except SupabaseLinkError:
+ # An unreadable pooler config must not sink the whole link flow.
+ log.debug("supabase pooler config unavailable for %s", ref, exc_info=True)
+ return None
+ rows: list[dict[str, Any]]
+ if isinstance(data, dict):
+ rows = [data]
+ elif isinstance(data, list):
+ rows = [row for row in data if isinstance(row, dict)]
+ else:
+ return None
+ for row in rows:
+ endpoint = _endpoint_from_row(row, ref, mode)
+ if endpoint is not None:
+ return endpoint
+ return None
+
+
+async def resolve_endpoint(
+ token: str,
+ ref: str,
+ *,
+ mode: str = "transaction",
+ transport: httpx.AsyncBaseTransport | None = None,
+) -> tuple[PoolerEndpoint, str]:
+ """The endpoint to connect with, plus a plain note about which one it is.
+
+ Returns the pooler endpoint when Supabase reports one, otherwise the direct
+ endpoint with a note naming the IPv4 caveat — so a later connection failure
+ is diagnosable from what the UI already told the user.
+ """
+ endpoint = await pooler_endpoint(token, ref, mode=mode, transport=transport)
+ if endpoint is not None:
+ return endpoint, (
+ f"Using the Supabase {endpoint.mode} pooler at {endpoint.host}."
+ )
+ fallback = direct_endpoint_for(ref)
+ return fallback, (
+ "Supabase did not report a pooler for this project, so the direct "
+ f"connection {fallback.host} is used. Note that the direct host is "
+ "IPv6-only unless your project has the IPv4 add-on."
+ )
+
+
+def build_connection_string(endpoint: PoolerEndpoint, password: str) -> str:
+ """Assemble the Postgres URI. Percent-encodes user and password.
+
+ Supabase passwords may legally contain ``@``, ``:``, ``/`` and ``#``, every
+ one of which changes how a URI parses. Encoding both credential parts is
+ what keeps "my password has a slash in it" from turning into an
+ unresolvable-host error three layers down.
+ """
+ if not password:
+ raise SupabaseLinkError("The database password is required.")
+ user = quote(endpoint.user, safe="")
+ secret = quote(password, safe="")
+ database = endpoint.database or "postgres"
+ return (
+ f"postgresql://{user}:{secret}@{endpoint.host}:{endpoint.port}/{database}"
+ "?sslmode=require"
+ )
diff --git a/tests/unit/ultrawiki/test_embeddings.py b/tests/unit/ultrawiki/test_embeddings.py
index bf119f0195..e5d600dd95 100644
--- a/tests/unit/ultrawiki/test_embeddings.py
+++ b/tests/unit/ultrawiki/test_embeddings.py
@@ -302,7 +302,17 @@ def test_keyed_backend_ready_without_key_is_false_and_honest(no_secrets, backend
usable, reason = backend_class().ready()
assert usable is False
assert reason # never an empty reason on a not-ready verdict
- assert "API-Keys" in reason # in-app recovery hint (recoverable in-app rule)
+ # The reason must name BOTH recovery paths, because the two kinds of
+ # install fix this differently: a desktop user types the credential into
+ # the slot named here, a headless VPS exports the environment variable.
+ # (Asserted by slot + env var rather than by the name of a UI screen —
+ # that literal went stale the moment the key field moved onto the
+ # provider's own card.)
+ backend = backend_class()
+ slot = backend._SECRET_SLOT if hasattr(backend, "_SECRET_SLOT") else ""
+ if slot:
+ assert slot in reason
+ assert slot.upper() in reason
@pytest.mark.parametrize(
diff --git a/tests/unit/ultrawiki/test_provider_catalog.py b/tests/unit/ultrawiki/test_provider_catalog.py
new file mode 100644
index 0000000000..2a636142d0
--- /dev/null
+++ b/tests/unit/ultrawiki/test_provider_catalog.py
@@ -0,0 +1,131 @@
+"""Invariants of the UltraWiki provider catalog.
+
+The catalog exists because the settings UI used to list providers it gave the
+user no way to connect. These tests pin the properties that keep that defect
+from coming back — above all: every credential field the catalog tells the UI
+to render must be a slot the secrets API will actually accept.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.core.config_writer import ULTRAWIKI_SLOT_KEYS
+from jarvis.setup.wizard import SECRETS
+from jarvis.ultrawiki import embeddings as embeddings_mod
+from jarvis.ultrawiki import provider_catalog as catalog
+from jarvis.ultrawiki import rerank as rerank_mod
+
+
+def test_every_catalog_secret_slot_is_writable_through_the_secrets_api():
+ """A rendered key field the API refuses to save is a dead end.
+
+ ``POST /api/secrets/{key}`` gates on the wizard allowlist, so a catalog
+ entry naming a slot outside it would render an input box whose Save button
+ always 404s — the exact shape of the bug this catalog was written to fix.
+ """
+ allowlisted = {spec.key for spec in SECRETS}
+ unwritable = catalog.all_secret_keys() - allowlisted
+ assert not unwritable, (
+ f"catalog references secret slots the secrets API cannot write: "
+ f"{sorted(unwritable)}"
+ )
+
+
+def test_embedding_catalog_matches_the_backend_registry():
+ """Presentation and runtime must agree on which embedding providers exist.
+
+ A catalog row without a backend is an option that silently does nothing; a
+ backend without a catalog row is a capability the user cannot reach.
+ """
+ catalog_ids = {spec.id for spec in catalog.EMBEDDING_PROVIDERS}
+ assert catalog_ids == set(embeddings_mod.EMBEDDING_BACKENDS)
+
+
+def test_rerank_catalog_matches_the_backend_registry():
+ catalog_ids = {spec.id for spec in catalog.RERANK_PROVIDERS}
+ assert catalog_ids == set(rerank_mod.RERANK_BACKENDS)
+
+
+def test_embedding_default_models_match_the_backend_defaults():
+ """The placeholder the card shows is the model the backend really uses."""
+ for spec in catalog.EMBEDDING_PROVIDERS:
+ assert spec.default_model == embeddings_mod.DEFAULT_MODELS[spec.id], spec.id
+
+
[email protected]("slot", catalog.SLOT_NAMES)
+def test_every_slot_has_providers_and_unique_ids(slot):
+ specs = catalog.catalog_for_slot(slot)
+ assert specs, f"slot {slot} has no providers"
+ ids = [spec.id for spec in specs]
+ assert len(ids) == len(set(ids)), f"duplicate provider ids in slot {slot}: {ids}"
+ for spec in specs:
+ assert spec.slot == slot
+ assert spec.label.strip()
+ assert spec.credential_help.strip()
+
+
+def test_a_credentialed_provider_always_names_its_secret_slot():
+ """An api_key/connection_string card with no slot renders an inert field."""
+ for slot in catalog.SLOT_NAMES:
+ for spec in catalog.catalog_for_slot(slot):
+ if spec.auth_mode in ("api_key", "connection_string", "managed_link"):
+ assert spec.secret_keys, f"{slot}/{spec.id} declares no secret slot"
+ else:
+ assert spec.auth_mode == "none"
+
+
+def test_storage_presets_resolve_to_the_two_functional_backends_only():
+ """Named presets stay presentation; the store keeps exactly two code paths.
+
+ Guards against the enum-drift class (AP-4 / BUG-008): adding "Supabase" as
+ a THIRD functional backend value would have to be mirrored through Python,
+ SQL, Pydantic, TS and the UI. It resolves to ``postgres`` instead.
+ """
+ for spec in catalog.STORAGE_PROVIDERS:
+ assert spec.db_backend in ("sqlite", "postgres"), spec.id
+ assert catalog.storage_backend_of("sqlite") == "sqlite"
+ assert catalog.storage_backend_of("supabase") == "postgres"
+ assert catalog.storage_backend_of("neon") == "postgres"
+ assert catalog.storage_backend_of("postgres") == "postgres"
+
+
+def test_an_unknown_storage_preset_degrades_to_the_local_floor():
+ """A config from a newer build must not leave the store without a backend."""
+ assert catalog.storage_backend_of("some-future-cloud") == "sqlite"
+ assert catalog.storage_backend_of("") == "sqlite"
+
+
+def test_storage_provider_is_a_writable_config_slot():
+ """The preset has to survive a restart, so the writer must accept the key."""
+ assert "storage_provider" in ULTRAWIKI_SLOT_KEYS
+
+
+def test_only_non_storage_slots_leave_db_backend_unset():
+ for slot in ("embedding", "distill", "rerank"):
+ for spec in catalog.catalog_for_slot(slot):
+ assert spec.db_backend is None, f"{slot}/{spec.id}"
+
+
+def test_get_provider_spec_is_slot_scoped():
+ """Voyage exists in two slots; a lookup must not cross them."""
+ assert catalog.get_provider_spec("rerank", "voyage") is not None
+ assert catalog.get_provider_spec("embedding", "voyage") is not None
+ assert catalog.get_provider_spec("rerank", "mistral") is None
+ assert catalog.get_provider_spec("storage", "voyage") is None
+ assert catalog.get_provider_spec("nonsense", "voyage") is None
+
+
+def test_at_most_one_recommended_provider_per_slot():
+ """Two recommendations is the same as none — the badge must stay a signal."""
+ for slot in catalog.SLOT_NAMES:
+ recommended = [s.id for s in catalog.catalog_for_slot(slot) if s.recommended]
+ assert len(recommended) <= 1, f"slot {slot} recommends {recommended}"
+
+
+def test_local_providers_carry_a_base_url_default():
+ """A local provider without a reachable default is unconfigurable by click."""
+ for slot in catalog.SLOT_NAMES:
+ for spec in catalog.catalog_for_slot(slot):
+ if spec.supports_base_url:
+ assert spec.default_base_url, f"{slot}/{spec.id}"
diff --git a/tests/unit/ultrawiki/test_rerank.py b/tests/unit/ultrawiki/test_rerank.py
index f76697b409..1c3e9003bc 100644
--- a/tests/unit/ultrawiki/test_rerank.py
+++ b/tests/unit/ultrawiki/test_rerank.py
@@ -1,7 +1,9 @@
"""Offline unit tests for the UltraWiki rerank backends.
HTTP rides ``httpx.MockTransport`` through the injectable ``transport``
-parameter; secrets are monkeypatched at the rerank module's import site.
+parameter; secrets are monkeypatched at the rerank module's import site. The
+LLM backend's provider chain is stubbed, never probed — a test must never
+assert against the host's live credentials.
"""
from __future__ import annotations
@@ -15,11 +17,15 @@ import pytest
import jarvis.ultrawiki.rerank as rr
from jarvis.ultrawiki.rerank import (
DEFAULT_RERANK_MODELS,
+ MAX_SCORE,
RERANK_BACKENDS,
CohereReranker,
+ LLMReranker,
RerankError,
VoyageReranker,
available_rerankers,
+ build_rerank_prompt,
+ parse_rerank_scores,
resolve_reranker,
)
@@ -36,6 +42,18 @@ def fake_secrets(monkeypatch):
monkeypatch.setattr(rr, "get_secret", lambda key, env_fallback=None: FAKE_KEY)
+def dead_llm_chain(monkeypatch):
+ """No credential-ready chat provider — the LLM backend reports not ready."""
+ monkeypatch.setattr(LLMReranker, "_chain", lambda self: [])
+
+
+def live_llm_chain(monkeypatch):
+ """One credential-ready provider family, host-independent."""
+ monkeypatch.setattr(LLMReranker, "_chain", lambda self: [("fakeprovider", "cheap")])
+
+
def _json_handler(payload, captured, status=200):
def handler(request: httpx.Request) -> httpx.Response:
captured.append(request)
@@ -68,7 +86,8 @@ async def test_voyage_rerank_posts_payload_and_parses_index_score_pairs(fake_sec
result = await backend.rerank("what broke?", ["a", "b", "c"], top_k=2)
- assert result == [(2, 0.91), (0, 0.42)]
+ # vendor 0-1 relevance is normalized onto the shared 0-10 grade
+ assert result == [(2, 9.1), (0, 4.2)]
request = captured[0]
assert str(request.url) == "https://api.voyageai.com/v1/rerank"
assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"
@@ -89,7 +108,7 @@ async def test_cohere_rerank_posts_top_n_payload_and_parses_results(fake_secrets
result = await backend.rerank("who is Alice?", ["x", "y"], top_k=1)
- assert result == [(1, 0.88)]
+ assert result == [(1, 8.8)]
request = captured[0]
assert str(request.url) == "https://api.cohere.com/v2/rerank"
assert request.headers["authorization"] == f"Bearer {FAKE_KEY}"
@@ -138,10 +157,15 @@ async def test_rerank_without_key_raises_rerank_error(no_secrets):
@pytest.mark.parametrize("backend_class", [VoyageReranker, CohereReranker])
def test_ready_without_key_is_false_with_honest_reason(no_secrets, backend_class):
- usable, reason = backend_class().ready()
+ backend = backend_class()
+ usable, reason = backend.ready()
assert usable is False
assert reason
- assert "API-Keys" in reason # in-app recovery hint
+ # Names both recovery paths: the credential slot a desktop user fills in
+ # on the provider's card, and the environment variable a headless install
+ # exports instead.
+ assert backend._SECRET_SLOT in reason
+ assert backend._SECRET_SLOT.upper() in reason
@pytest.mark.parametrize("backend_class", [VoyageReranker, CohereReranker])
@@ -155,11 +179,15 @@ def test_ready_with_key_is_true(fake_secrets, backend_class):
def test_registry_and_default_models_cover_the_same_backends():
- assert set(RERANK_BACKENDS) == {"voyage", "cohere"}
- assert set(DEFAULT_RERANK_MODELS) == {"voyage", "cohere"}
+ assert set(RERANK_BACKENDS) == {"llm", "voyage", "cohere"}
+ assert set(DEFAULT_RERANK_MODELS) == {"llm", "voyage", "cohere"}
+ # the universal backend leads the dropdown
+ assert next(iter(RERANK_BACKENDS)) == "llm"
-def test_available_rerankers_without_keys_reports_all_not_ready(no_secrets):
+def test_available_rerankers_without_keys_reports_all_not_ready(
+ no_secrets, dead_llm_chain
+):
rows = available_rerankers(SimpleNamespace())
assert [row["name"] for row in rows] == list(RERANK_BACKENDS)
@@ -167,6 +195,19 @@ def test_available_rerankers_without_keys_reports_all_not_ready(no_secrets):
assert row["ready"] is False
assert row["reason"]
assert row["default_model"] == DEFAULT_RERANK_MODELS[row["name"]]
+ assert row["detail"] # every option explains itself in the UI
+
+
+def test_available_rerankers_reports_llm_ready_on_a_keyless_but_local_install(
+ no_secrets, live_llm_chain
+):
+ """The universality guarantee (§3/AP-22): an install with no rerank-vendor
+ account at all still has a working rerank option."""
+ rows = {row["name"]: row for row in available_rerankers(SimpleNamespace())}
+
+ assert rows["llm"]["ready"] is True
+ assert rows["voyage"]["ready"] is False
+ assert rows["cohere"]["ready"] is False
def test_resolve_reranker_unconfigured_returns_none_for_honest_skip(fake_secrets):
@@ -188,3 +229,177 @@ def test_resolve_reranker_ready_provider_returns_backend(fake_secrets):
cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="cohere"))
backend = resolve_reranker(cfg)
assert isinstance(backend, CohereReranker)
+
+
+def test_resolve_reranker_llm_needs_no_vendor_key(no_secrets, live_llm_chain):
+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="llm"))
+ assert isinstance(resolve_reranker(cfg), LLMReranker)
+
+
+def test_resolve_reranker_llm_without_any_provider_skips_honestly(
+ no_secrets, dead_llm_chain
+):
+ cfg = SimpleNamespace(ultrawiki=SimpleNamespace(rerank_provider="llm"))
+ assert resolve_reranker(cfg) is None
+
+
+# ----------------------------------------------------------------------
+# LLM backend — prompt, parsing, chain
+# ----------------------------------------------------------------------
+
+
+def test_rerank_prompt_numbers_candidates_and_pins_the_zero_to_ten_scale():
+ prompt = build_rerank_prompt("who paid the invoice?", ["first doc", "second doc"])
+
+ assert "[0] first doc" in prompt
+ assert "[1] second doc" in prompt
+ assert "<question>who paid the invoice?</question>" in prompt
+ assert "10 = directly and completely answers" in prompt
+ assert '{"scores":[{"i":0,"score":7}' in prompt # strict-JSON contract
+
+
+def test_rerank_prompt_truncates_long_candidates():
+ prompt = build_rerank_prompt("q", ["x" * 5000])
+
+ assert len(prompt) < 2500
+ assert "[…]" in prompt
+
+
+def test_parse_rerank_scores_sorts_by_grade_and_keeps_indices():
+ pairs = parse_rerank_scores(
+ '{"scores":[{"i":0,"score":3},{"i":2,"score":9},{"i":1,"score":7}]}',
+ count=3,
+ )
+
+ assert pairs == [(2, 9.0), (1, 7.0), (0, 3.0)]
+
+
+def test_parse_rerank_scores_survives_fences_and_prose():
+ text = 'Sure! Here you go:\n```json\n{"scores":[{"i":1,"score":8}]}\n```'
+
+ assert parse_rerank_scores(text, count=2) == [(1, 8.0)]
+
+
+def test_parse_rerank_scores_drops_out_of_range_duplicate_and_junk_entries():
+ pairs = parse_rerank_scores(
+ '{"scores":[{"i":0,"score":5},{"i":0,"score":9},{"i":99,"score":10},'
+ '{"i":1,"score":"nope"},{"nope":true},{"i":1,"score":6}]}',
+ count=2,
+ )
+
+ assert pairs == [(1, 6.0), (0, 5.0)]
+
+
+def test_parse_rerank_scores_clamps_out_of_scale_grades():
+ pairs = parse_rerank_scores(
+ '{"scores":[{"i":0,"score":42},{"i":1,"score":-5}]}', count=2
+ )
+
+ assert pairs == [(0, MAX_SCORE), (1, 0.0)]
+
+
+ "text",
+ ["not json at all", '{"nothing":"useful"}', '{"scores":[]}', '{"scores":"eight"}'],
+)
+def test_parse_rerank_scores_rejects_unusable_output(text):
+ with pytest.raises(RerankError):
+ parse_rerank_scores(text, count=2)
+
+
+def test_llm_ready_without_a_chain_names_the_in_app_recovery(dead_llm_chain):
+ usable, reason = LLMReranker(SimpleNamespace()).ready()
+
+ assert usable is False
+ assert "API-Keys" in reason
+ assert "Ollama" in reason # the offline path is spelled out
+
+
+def test_llm_ready_with_a_chain_is_true(live_llm_chain):
+ assert LLMReranker(SimpleNamespace()).ready() == (True, "")
+
+
+def test_llm_ready_never_raises_when_the_chain_probe_explodes(monkeypatch):
+ def boom(self):
+ raise RuntimeError("registry on fire")
+
+ monkeypatch.setattr(LLMReranker, "_chain", boom)
+ usable, reason = LLMReranker(SimpleNamespace()).ready()
+
+ assert usable is False
+ assert "probe failed" in reason
+
+
+async def test_llm_rerank_grades_through_the_provider_chain(monkeypatch, live_llm_chain):
+ seen: dict = {}
+
+ async def fake_complete(**kwargs):
+ seen.update(kwargs)
+ graded = '{"scores":[{"i":1,"score":9},{"i":0,"score":2}]}'
+ return SimpleNamespace(text=graded), "fakeprovider"
+
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.complete_with_fallback", fake_complete
+ )
+ backend = LLMReranker(SimpleNamespace(), registry=object())
+
+ pairs = await backend.rerank("who broke the build?", ["doc a", "doc b"], top_k=2)
+
+ assert pairs == [(1, 9.0), (0, 2.0)]
+ assert seen["chain"] == [("fakeprovider", "cheap")]
+ assert seen["request"].temperature == 0.0 # grading, not creativity
+
+
+async def test_llm_rerank_respects_top_k(monkeypatch, live_llm_chain):
+ async def fake_complete(**kwargs):
+ return (
+ SimpleNamespace(
+ text='{"scores":[{"i":0,"score":9},{"i":1,"score":8},{"i":2,"score":7}]}'
+ ),
+ "fakeprovider",
+ )
+
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.complete_with_fallback", fake_complete
+ )
+
+ pairs = await LLMReranker(SimpleNamespace(), registry=object()).rerank(
+ "q", ["a", "b", "c"], top_k=2
+ )
+
+ assert pairs == [(0, 9.0), (1, 8.0)]
+
+
+async def test_llm_rerank_validator_rejects_unusable_output_so_the_chain_advances(
+ monkeypatch, live_llm_chain
+):
+ """A transport success carrying no grades must not end the chain — the
+ next provider family gets its turn (the distill validator idiom)."""
+ captured: dict = {}
+
+ async def fake_complete(**kwargs):
+ captured.update(kwargs)
+ return None # the chain exhausted itself
+
+ monkeypatch.setattr(
+ "jarvis.memory.wiki.provider_chain.complete_with_fallback", fake_complete
+ )
+ backend = LLMReranker(SimpleNamespace(), registry=object())
+
+ with pytest.raises(RerankError, match="usable relevance grades"):
+ await backend.rerank("q", ["a"], top_k=1)
+
+ validate = captured["validate"]
+ assert validate(SimpleNamespace(text="I think document one is nice")) is not None
+ assert validate(SimpleNamespace(text='{"scores":[{"i":0,"score":4}]}')) is None
+
+
+async def test_llm_rerank_without_a_chain_raises_rather_than_calling_out(
+ dead_llm_chain,
+):
+ with pytest.raises(RerankError, match="no credential-ready provider"):
+ await LLMReranker(SimpleNamespace()).rerank("q", ["a"], top_k=1)
+
+
+async def test_llm_rerank_empty_documents_short_circuits(live_llm_chain):
+ assert await LLMReranker(SimpleNamespace()).rerank("q", [], top_k=3) == []
diff --git a/tests/unit/ultrawiki/test_supabase_link.py b/tests/unit/ultrawiki/test_supabase_link.py
new file mode 100644
index 0000000000..147a14e039
--- /dev/null
+++ b/tests/unit/ultrawiki/test_supabase_link.py
@@ -0,0 +1,181 @@
+"""The guided Supabase link flow, driven fully offline through MockTransport.
+
+What matters here is not "does httpx work" but the three judgement calls the
+module makes on the user's behalf: it must use the host Supabase REPORTS
+(never a guessed region prefix), it must survive an unreadable pooler config
+instead of dying, and it must produce a URI that still parses when the
+database password contains URI punctuation.
+"""
+
+from __future__ import annotations
+
+import json
+from urllib.parse import unquote, urlsplit
+
+import httpx
+import pytest
+
+from jarvis.ultrawiki import supabase_link
+
+
+def _transport(routes: dict[str, tuple[int, object]]) -> httpx.MockTransport:
+ """MockTransport answering by path; unmapped paths 404."""
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ status, payload = routes.get(request.url.path, (404, {"message": "nope"}))
+ return httpx.Response(status, content=json.dumps(payload).encode())
+
+ return httpx.MockTransport(handler)
+
+
+PROJECTS_PATH = "/v1/projects"
+POOLER_PATH = "/v1/projects/abcdefghijklmnopqrst/config/database/pooler"
+
+
+async def test_list_projects_puts_healthy_projects_first():
+ transport = _transport(
+ {
+ PROJECTS_PATH: (
+ 200,
+ [
+ {
+ "id": "paused1",
+ "name": "Zeta archive",
+ "region": "eu-central-1",
+ "status": "INACTIVE",
+ },
+ {
+ "id": "live1",
+ "name": "Memory store",
+ "region": "eu-central-1",
+ "status": "ACTIVE_HEALTHY",
+ },
+ ],
+ )
+ }
+ )
+ projects = await supabase_link.list_projects("tok", transport=transport)
+ assert [p.ref for p in projects] == ["live1", "paused1"]
+ assert projects[0].name == "Memory store"
+
+
+async def test_a_rejected_token_says_so_in_plain_words():
+ transport = _transport({PROJECTS_PATH: (401, {"message": "unauthorized"})})
+ with pytest.raises(supabase_link.SupabaseLinkError) as excinfo:
+ await supabase_link.list_projects("stale-token", transport=transport)
+ message = str(excinfo.value)
+ assert "access token" in message.lower()
+ # The failing credential must never be echoed back into a UI string.
+ assert "stale-token" not in message
+
+
+async def test_an_empty_token_never_reaches_the_network():
+ with pytest.raises(supabase_link.SupabaseLinkError):
+ await supabase_link.list_projects(" ", transport=_transport({}))
+
+
+async def test_resolve_uses_the_host_supabase_reports_not_a_guessed_region():
+ """The region prefix in a pooler hostname is not derivable from the ref.
+
+ This is the whole reason the link flow calls the Management API instead of
+ string-building: an invented ``aws-0-<region>`` prefix yields a host that
+ does not resolve, and the user sees a connection error with no cause.
+ """
+ transport = _transport(
+ {
+ POOLER_PATH: (
+ 200,
+ [
+ {
+ "db_host": "aws-1-eu-central-2.pooler.supabase.com",
+ "db_port": 6543,
+ "db_user": "postgres.abcdefghijklmnopqrst",
+ "db_name": "postgres",
+ "pool_mode": "transaction",
+ }
+ ],
+ )
+ }
+ )
+ endpoint, note = await supabase_link.resolve_endpoint(
+ "tok", "abcdefghijklmnopqrst", transport=transport
+ )
+ assert endpoint.host == "aws-1-eu-central-2.pooler.supabase.com"
+ assert endpoint.port == 6543
+ assert endpoint.mode == "transaction"
+ assert "pooler" in note
+
+
+async def test_session_mode_keeps_the_reported_host_and_switches_the_port():
+ transport = _transport(
+ {
+ POOLER_PATH: (
+ 200,
+ {
+ "db_host": "aws-1-eu-central-2.pooler.supabase.com",
+ "db_port": 6543,
+ "db_user": "postgres.abcdefghijklmnopqrst",
+ "db_name": "postgres",
+ },
+ )
+ }
+ )
+ endpoint, _note = await supabase_link.resolve_endpoint(
+ "tok", "abcdefghijklmnopqrst", mode="session", transport=transport
+ )
+ assert endpoint.host == "aws-1-eu-central-2.pooler.supabase.com"
+ assert endpoint.port == 5432
+
+
+async def test_an_unreadable_pooler_config_falls_back_instead_of_failing():
+ """Some projects and token scopes expose no pooler config at all.
+
+ That is a normal state, not an outage — the flow degrades to the direct
+ host and names the IPv4 caveat so a later failure is diagnosable.
+ """
+ transport = _transport({POOLER_PATH: (403, {"message": "forbidden"})})
+ endpoint, note = await supabase_link.resolve_endpoint(
+ "tok", "abcdefghijklmnopqrst", transport=transport
+ )
+ assert endpoint.host == "db.abcdefghijklmnopqrst.supabase.co"
+ assert endpoint.mode == "direct"
+ assert "IPv6" in note
+
+
+async def test_a_nonsense_pool_mode_falls_back_to_transaction():
+ transport = _transport({POOLER_PATH: (404, {})})
+ endpoint, _ = await supabase_link.resolve_endpoint(
+ "tok", "abcdefghijklmnopqrst", mode="wat", transport=transport
+ )
+ # Fell through to direct, but the mode normalisation must not have raised.
+ assert endpoint.mode == "direct"
+
+
+def test_a_password_with_uri_punctuation_still_parses():
+ """Supabase passwords may contain @ : / # — all URI-significant.
+
+ Without percent-encoding, "p@ss/word" turns the host into "ss" and the
+ failure surfaces as an unresolvable hostname three layers away from the
+ input box that caused it.
+ """
+ endpoint = supabase_link.PoolerEndpoint(
+ host="aws-1-eu-central-2.pooler.supabase.com",
+ port=6543,
+ user="postgres.abcdefghijklmnopqrst",
+ database="postgres",
+ mode="transaction",
+ )
+ uri = supabase_link.build_connection_string(endpoint, "p@ss/w#rd:1")
+ parts = urlsplit(uri)
+ assert parts.hostname == "aws-1-eu-central-2.pooler.supabase.com"
+ assert parts.port == 6543
+ assert unquote(parts.password or "") == "p@ss/w#rd:1"
+ assert unquote(parts.username or "") == "postgres.abcdefghijklmnopqrst"
+ assert parts.path == "/postgres"
+ assert "sslmode=require" in parts.query
+
+
+def test_an_empty_password_is_refused_before_a_broken_uri_is_built():
+ endpoint = supabase_link.direct_endpoint_for("abcdefghijklmnopqrst")
+ with pytest.raises(supabase_link.SupabaseLinkError):
+ supabase_link.build_connection_string(endpoint, "")
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index 8faa552616..40303d9f0f 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -15,6 +15,7 @@ monkeypatched at the module seams the routes import through.
from __future__ import annotations
+import asyncio
import time
from pathlib import Path
from types import SimpleNamespace
@@ -188,6 +189,10 @@ def _drive_pipeline(env) -> None:
env.cfg,
embedding_backend_factory=lambda: FakeEmbeddingBackend(),
distill_fn=fake_distill,
+ # The injected distiller brings its own provider: the production
+ # credential-chain gate must not run, or this test would pass or
+ # fail depending on which keys the host happens to hold (AP-23).
+ distill_ready_fn=lambda: (True, ""),
)
for _ in range(8):
if await worker.run_once() == 0:
@@ -312,6 +317,11 @@ def test_search_returns_fused_hits_after_inline_pipeline(env) -> None:
assert hit["permalink"]
assert "keyword" in hit["matched_by"]
assert hit["score"] > 0
+ # Five-layer parity (AP-4): the SearchResult dataclass fields reach the
+ # payload verbatim. The rerank stage is off here, so the absolute grade is
+ # honestly null rather than a fabricated number.
+ assert hit["rerank_score"] is None
+ assert isinstance(hit["context"], list)
# ---------------------------------------------------------------------------
@@ -364,6 +374,109 @@ def test_update_settings_without_changes_is_noop(env) -> None:
}
+# ---------------------------------------------------------------------------
+# Ranking settings (rerank slot + the knobs it governs)
+# ---------------------------------------------------------------------------
+
+
+def test_llm_rerank_provider_is_accepted_and_persisted(env) -> None:
+ """The universal backend must be selectable without any vendor key."""
+ _activate(env)
+
+ response = env.client.put(
+ "/api/ultrawiki/settings",
+ json={"rerank_provider": "llm", "rerank_model": "some-cheap-model"},
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["changed"] == ["rerank_model", "rerank_provider"]
+ assert env.cfg.ultrawiki.rerank_provider == "llm"
+ assert env.cfg.ultrawiki.rerank_model == "some-cheap-model"
+ toml = env.toml.read_text(encoding="utf-8")
+ assert 'rerank_provider = "llm"' in toml
+ assert 'rerank_model = "some-cheap-model"' in toml
+
+
+def test_unknown_rerank_provider_is_refused(env) -> None:
+ _activate(env)
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"rerank_provider": "not-a-backend"}
+ )
+ assert response.status_code == 400
+ assert "not-a-backend" in response.json()["detail"]
+
+
+def test_ranking_knobs_persist_as_numbers(env) -> None:
+ _activate(env)
+
+ response = env.client.put(
+ "/api/ultrawiki/settings",
+ json={
+ "rerank_min_score": 6.5,
+ "rrf_keyword_weight": 2,
+ "recency_half_life_days": 0,
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ assert response.json()["changed"] == [
+ "recency_half_life_days",
+ "rerank_min_score",
+ "rrf_keyword_weight",
+ ]
+ assert env.cfg.ultrawiki.rerank_min_score == 6.5
+ assert env.cfg.ultrawiki.recency_half_life_days == 0
+ toml = env.toml.read_text(encoding="utf-8")
+ # Numbers, not quoted strings that merely happen to parse.
+ assert "rerank_min_score = 6.5" in toml
+ assert "rrf_keyword_weight = 2.0" in toml
+
+
+ ("payload", "needle"),
+ [
+ ({"rerank_min_score": 11}, "between 0.0 and 10.0"),
+ ({"rerank_min_score": -1}, "between 0.0 and 10.0"),
+ ({"rrf_vector_weight": 999}, "between 0.0 and 10.0"),
+ ],
+)
+def test_out_of_range_ranking_knobs_are_refused(env, payload, needle) -> None:
+ """Refused, never clamped: a silently corrected value would leave the UI
+ showing a number the ranking does not actually use."""
+ _activate(env)
+ response = env.client.put("/api/ultrawiki/settings", json=payload)
+
+ assert response.status_code == 400
+ assert needle in response.json()["detail"]
+ # Nothing was written on the way to the rejection.
+ assert "rerank_min_score" not in env.toml.read_text(encoding="utf-8")
+
+
+def test_status_reports_the_rerank_slot_with_its_ranking_knobs(env) -> None:
+ """The knobs ride along with the slot they govern, so the settings card
+ can show what the ranking actually does. (That the `llm` backend is
+ OFFERED is a rerank-registry property, covered in
+ tests/unit/ultrawiki/test_rerank.py — this fixture stubs the backend
+ probe out to stay offline.)"""
+ _activate(env)
+ slot = env.client.get("/api/ultrawiki/status").json()["slots"]["rerank"]
+
+ assert slot["ranking"]["rerank_min_score"] == 4.0
+ assert slot["ranking"]["keyword_weight"] == 1.0
+ assert slot["ranking"]["vector_weight"] == 1.0
+ assert slot["ranking"]["recency_half_life_days"] == 180.0
+ assert slot["model"] == "" # honest empty, not a fabricated default
+
+
+def test_status_reflects_a_changed_relevance_floor(env) -> None:
+ _activate(env)
+ env.client.put("/api/ultrawiki/settings", json={"rerank_min_score": 7})
+
+ slot = env.client.get("/api/ultrawiki/status").json()["slots"]["rerank"]
+
+ assert slot["ranking"]["rerank_min_score"] == 7.0
+
+
# ---------------------------------------------------------------------------
# Areas + providers + deactivation
# ---------------------------------------------------------------------------
@@ -417,9 +530,482 @@ def test_dangerous_routes_carry_the_flag(env) -> None:
assert operation.get("x-jarvis-dangerous") is True, (path, method)
+def test_slot_test_route_declares_a_long_cli_timeout(env) -> None:
+ """A real provider call outlives the CLI's default client timeout."""
+ spec = env.server.app.openapi()
+ operation = spec["paths"]["/api/ultrawiki/test/{slot}"]["post"]
+ assert operation.get("x-jarvis-timeout-seconds") == 120
+
+
+# ---------------------------------------------------------------------------
+# Unwired service — every route stays honest instead of crashing
+# ---------------------------------------------------------------------------
+
+
+def test_routes_are_honest_while_the_service_is_unwired(env) -> None:
+ env.server.app.state.ultrawiki = None
+ try:
+ sources = env.client.get("/api/ultrawiki/sources")
+ assert sources.status_code == 503
+ assert "not wired" in sources.json()["detail"]
+
+ # /status is the honesty surface: it ALWAYS answers, degraded.
+ status = env.client.get("/api/ultrawiki/status")
+ assert status.status_code == 200
+ body = status.json()
+ assert body["started"] is False
+ assert body["slots"] == {}
+ assert body["sources"] == []
+ assert body["pipeline"]["running"] is False
+ assert body["pipeline"]["state"] == "paused"
+ assert body["pipeline"]["reason"]
+ assert any("not wired" in line for line in body["degradations"])
+ assert "search_legs" in body
+ finally:
+ env.server.app.state.ultrawiki = env.service
+
+
+# ---------------------------------------------------------------------------
+# Sync: one at a time, and the full refresh
+# ---------------------------------------------------------------------------
+
+
+def test_second_sync_of_one_source_is_409_with_the_active_job(env) -> None:
+ _activate(env)
+ source_id, job_id = _approve_and_sync_folder(env)
+ # The first job may already be done on a fast machine — assert on whichever
+ # of the two honest answers applies, never on a race.
+ second = env.client.post(f"/api/ultrawiki/sources/{source_id}/sync")
+ if second.status_code == 409:
+ detail = second.json()["detail"]
+ assert detail["job_id"] == job_id
+ assert detail["source_id"] == source_id
+ assert "already running" in detail["message"]
+ else:
+ assert second.status_code == 201, second.text
+ _wait_for_job(env, job_id)
+
+
+def test_full_refresh_is_requested_through_the_body(env) -> None:
+ _activate(env)
+ source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ plain = env.client.post(f"/api/ultrawiki/sources/{source_id}/sync")
+ assert plain.status_code == 201, plain.text
+ assert plain.json()["full"] is False
+ _wait_for_job(env, plain.json()["job_id"])
+
+ full = env.client.post(
+ f"/api/ultrawiki/sources/{source_id}/sync", json={"full": True}
+ )
+ assert full.status_code == 201, full.text
+ assert full.json()["full"] is True
+ snapshot = _wait_for_job(env, full.json()["job_id"])
+ assert snapshot["status"] == "done"
+ assert snapshot["mode"] == "backfill"
+
+
+# ---------------------------------------------------------------------------
+# Cancelling a live job
+# ---------------------------------------------------------------------------
+
+
+def test_cancel_of_a_running_job_succeeds(env, monkeypatch) -> None:
+ """A live job cancels; a job without a live task answers 409."""
+ _activate(env)
+
+ import jarvis.ultrawiki.connectors as connectors_mod
+ from jarvis.ultrawiki.types import (
+ AuthKind,
+ ConnectorCapabilities,
+ IncrementalMode,
+ RawItem,
+ )
+
+ class SlowConnector:
+ id = "slow-conn"
+ label = "Slow Connector"
+ auth = AuthKind.NONE
+ capabilities = ConnectorCapabilities(
+ backfill=True, incremental=IncrementalMode.NONE, deletes=False
+ )
+
+ async def backfill(self, ctx, checkpoint=None):
+ yield RawItem(
+ external_id="slow-1",
+ body="first item",
+ permalink="fake://slow/1",
+ timestamp_utc="2026-01-01T00:00:00Z",
+ title="Slow 1",
+ )
+ await asyncio.sleep(30) # cancelled long before this returns
+
+ async def incremental(self, ctx, cursor=None):
+ return
+ yield # pragma: no cover — makes this an async generator
+
+ registry = dict(connectors_mod.discover_connectors())
+ registry["slow-conn"] = SlowConnector
+ monkeypatch.setattr(connectors_mod, "discover_connectors", lambda: registry)
+
+ created = env.client.post(
+ "/api/ultrawiki/sources", json={"connector": "slow-conn", "label": "Slow"}
+ )
+ assert created.status_code == 201, created.text
+ source_id = created.json()["id"]
+ env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")
+ job_id = env.client.post(
+ f"/api/ultrawiki/sources/{source_id}/sync"
+ ).json()["job_id"]
+
+ deadline = time.monotonic() + 5.0
+ while time.monotonic() < deadline:
+ if env.client.get(f"/api/ultrawiki/jobs/{job_id}").json()["status"] == "running":
+ break
+ time.sleep(0.02)
+
+ cancelled = env.client.post(f"/api/ultrawiki/jobs/{job_id}/cancel")
+ assert cancelled.status_code == 200, cancelled.text
+ assert cancelled.json() == {"job_id": job_id, "cancel_requested": True}
+
+ snapshot = _wait_for_job(env, job_id)
+ assert snapshot["status"] == "cancelled"
+ # Terminal now: a second cancel is refused honestly.
+ assert env.client.post(f"/api/ultrawiki/jobs/{job_id}/cancel").status_code == 409
+
+
+def test_cancel_of_a_job_without_a_live_task_is_409(env) -> None:
+ """The narrow window where a job is registered but has no task yet."""
+ job = uw_service_mod.SyncJob(
+ job_id="pending-job", source_id="whatever", mode="backfill"
+ )
+ job.status = "queued"
+ job.task = None
+ uw_service_mod._register_job(job) # noqa: SLF001 — the registry is module state
+ try:
+ response = env.client.post("/api/ultrawiki/jobs/pending-job/cancel")
+ assert response.status_code == 409
+ assert "no live task" in response.json()["detail"]
+ finally:
+ uw_service_mod.clear_jobs()
+
+
+# ---------------------------------------------------------------------------
+# Dead-letter recovery
+# ---------------------------------------------------------------------------
+
+
+def test_requeue_failed_returns_dead_lettered_items(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ async def _fail_everything() -> None:
+ store = env.service._store # noqa: SLF001 — deliberate test seam
+ for item in await store.claim_batch("keyword_indexed", limit=10):
+ await store.mark_failed(item["id"], "the distill provider was dead")
+
+ env.client.portal.call(_fail_everything)
+ assert env.client.get("/api/ultrawiki/status").json()["counts"]["failed"] == 2
+
+ response = env.client.post("/api/ultrawiki/pipeline/requeue-failed")
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["requeued"] == 2
+ assert body["detail"]
+ counts = env.client.get("/api/ultrawiki/status").json()["counts"]
+ assert counts["failed"] == 0
+ assert counts["captured"] == 2 # nothing was indexed yet, so they restart
+
+ # Nothing left to requeue is an honest zero, not an error.
+ again = env.client.post("/api/ultrawiki/pipeline/requeue-failed")
+ assert again.status_code == 200
+ assert again.json()["requeued"] == 0
+
+
+def test_requeue_failed_is_dangerous_and_scoped(env) -> None:
+ spec = env.server.app.openapi()
+ operation = spec["paths"]["/api/ultrawiki/pipeline/requeue-failed"]["post"]
+ assert operation.get("x-jarvis-dangerous") is True
+
+ _activate(env)
+ response = env.client.post(
+ "/api/ultrawiki/pipeline/requeue-failed", json={"source_id": "no-such-source"}
+ )
+ assert response.status_code == 404
+
+
+# ---------------------------------------------------------------------------
+# Honest pipeline state on the status surface
+# ---------------------------------------------------------------------------
+
+
+def test_status_reports_waiting_for_sources_after_a_fresh_activation(env) -> None:
+ """The maintainer report: a fresh activation must not claim to be working."""
+ _activate(env)
+ pipeline = env.client.get("/api/ultrawiki/status").json()["pipeline"]
+ assert pipeline["state"] == "waiting_for_sources"
+ assert "approve" in pipeline["reason"].lower()
+
+
+def test_status_reports_processing_once_items_are_queued(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ pipeline = env.client.get("/api/ultrawiki/status").json()["pipeline"]
+ assert pipeline["state"] in ("processing", "paused")
+ assert "2" in pipeline["reason"]
+
+
+def test_status_reports_idle_once_everything_is_processed(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+ pipeline = env.client.get("/api/ultrawiki/status").json()["pipeline"]
+ assert pipeline["state"] == "idle"
+
+
+# ---------------------------------------------------------------------------
+# Activation ordering (a failed activation must not leave the mode on)
+# ---------------------------------------------------------------------------
+
+
+def test_failed_activation_leaves_the_mode_off(env, monkeypatch) -> None:
+ async def _explode(_payload=None):
+ raise RuntimeError("the store could not be opened")
+
+ monkeypatch.setattr(env.service, "activate", _explode)
+ response = env.client.post(
+ "/api/ultrawiki/activate",
+ json={"embedding_provider": "gemini", "embedding_model": "fake-embed"},
+ )
+ assert response.status_code == 500
+ assert "could not be activated" in response.json()["detail"]
+ # The mode switch never flipped — neither live nor on disk.
+ assert env.cfg.ultrawiki.enabled is False
+ assert "enabled = true" not in env.toml.read_text(encoding="utf-8")
+ # Search still answers with the mode-off message, not a broken Ultra view.
+ assert env.client.get("/api/ultrawiki/search", params={"q": "x"}).status_code == 409
+
+
def test_router_import_line_exists_in_server_source() -> None:
import jarvis.ui.web.server as server_mod
source = Path(server_mod.__file__).read_text(encoding="utf-8")
assert "from .ultrawiki_routes import router as ultrawiki_router" in source
assert "app.include_router(ultrawiki_router)" in source
+
+
+# ---------------------------------------------------------------------------
+# Provider catalog + the guided Supabase link
+# ---------------------------------------------------------------------------
+
+
+def test_catalog_lists_every_slot_with_a_connectable_credential_field(env) -> None:
+ """The regression guard for the defect this surface was built to fix.
+
+ Before the catalog existed the settings cards offered providers with no way
+ to enter their credential, and pointed at an API-Keys view that had no field
+ for them either. Every row must now name the secret slot the UI can write,
+ and that slot must be one the secrets API actually accepts.
+ """
+ from jarvis.ui.web.provider_routes import ALLOWED_SECRET_KEYS
+
+ response = env.client.get("/api/ultrawiki/catalog")
+ assert response.status_code == 200, response.text
+ slots = response.json()["slots"]
+ assert set(slots) == {"storage", "embedding", "distill", "rerank"}
+ for slot, rows in slots.items():
+ assert rows, f"slot {slot} rendered no providers"
+ for row in rows:
+ for key in row["secret_keys"]:
+ assert key in ALLOWED_SECRET_KEYS, (slot, row["id"], key)
+ assert key in row["secrets_set"]
+ assert key in row["secret_shared_with"]
+
+
+def test_catalog_marks_the_configured_provider_as_selected(env) -> None:
+ _activate(env)
+ body = env.client.get("/api/ultrawiki/catalog").json()
+ assert body["selected"]["embedding"] == "gemini"
+ embedding = {row["id"]: row for row in body["slots"]["embedding"]}
+ assert embedding["gemini"]["selected"] is True
+ assert embedding["openai"]["selected"] is False
+ # Readiness comes from the provider's own probe, not from being selected.
+ assert embedding["gemini"]["ready"] is True
+ assert embedding["openai"]["ready"] is False
+ assert embedding["openai"]["reason"]
+ assert body["models"]["embedding"] == "fake-embed"
+
+
+def test_catalog_storage_defaults_to_the_local_floor(env) -> None:
+ body = env.client.get("/api/ultrawiki/catalog").json()
+ storage = {row["id"]: row for row in body["slots"]["storage"]}
+ assert body["selected"]["storage"] == "sqlite"
+ assert storage["sqlite"]["ready"] is True
+ # A cloud preset with no saved connection string is honest about it and
+ # says the local store keeps answering — never a bare failure.
+ assert storage["supabase"]["ready"] is False
+ assert "connection string" in storage["supabase"]["reason"]
+
+
+def test_selecting_a_storage_preset_derives_the_functional_backend(env) -> None:
+ """The UI picks a NAME; the two-value backend enum is derived server-side."""
+ _activate(env)
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"storage_provider": "neon"}
+ )
+ assert response.status_code == 200, response.text
+ assert set(response.json()["changed"]) == {"storage_provider", "db_backend"}
+ assert env.cfg.ultrawiki.db_backend == "postgres"
+ assert env.cfg.ultrawiki.storage_provider == "neon"
+ persisted = env.toml.read_text(encoding="utf-8")
+ assert 'storage_provider = "neon"' in persisted
+ assert 'db_backend = "postgres"' in persisted
+
+
+def test_switching_back_to_sqlite_restores_the_local_backend(env) -> None:
+ _activate(env)
+ env.client.put("/api/ultrawiki/settings", json={"storage_provider": "neon"})
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"storage_provider": "sqlite"}
+ )
+ assert response.status_code == 200, response.text
+ assert env.cfg.ultrawiki.db_backend == "sqlite"
+
+
+def test_an_unknown_storage_preset_is_refused(env) -> None:
+ response = env.client.put(
+ "/api/ultrawiki/settings", json={"storage_provider": "dropbox"}
+ )
+ assert response.status_code == 400
+ assert "dropbox" in response.json()["detail"]
+
+
+def test_supabase_projects_need_a_token_first(env, monkeypatch) -> None:
+ """Unlinked is a 409 with an instruction, never a 500 or an empty list.
+
+ The empty keyring is stubbed rather than assumed: a developer machine that
+ happens to hold a real Supabase token would otherwise turn this unit test
+ into a live API call against that person's own account.
+ """
+ monkeypatch.setattr("jarvis.core.config.get_secret", lambda *_a, **_kw: None)
+ response = env.client.get("/api/ultrawiki/storage/supabase/projects")
+ assert response.status_code == 409
+ assert "token" in response.json()["detail"].lower()
+
+
+def _stub_supabase(monkeypatch, *, probe_ok: bool, probe_detail: str) -> dict[str, str]:
+ """Wire an offline Supabase link: saved token, fixed endpoint, fixed probe.
+
+ Returns the dict that captures every secret write, so a test can assert
+ that a refused link wrote nothing at all.
+ """
+ from jarvis.ultrawiki import supabase_link
+
+ monkeypatch.setattr(
+ "jarvis.core.config.get_secret",
+ lambda key, **_kw: "sbp_token" if key == "supabase_access_token" else None,
+ )
+
+ async def fake_resolve(token, ref, *, mode="transaction", transport=None):
+ return (
+ supabase_link.PoolerEndpoint(
+ host="aws-1-eu-central-2.pooler.supabase.com",
+ port=6543,
+ user=f"postgres.{ref}",
+ database="postgres",
+ mode="transaction",
+ ),
+ "Using the Supabase transaction pooler.",
+ )
+
+ async def fake_connect_test(conn_str):
+ return probe_ok, probe_detail
+
+ monkeypatch.setattr(supabase_link, "resolve_endpoint", fake_resolve)
+ monkeypatch.setattr(
+ "jarvis.ultrawiki.store.PostgresStore.connect_test",
+ staticmethod(fake_connect_test),
+ )
+ written: dict[str, str] = {}
+
+ def fake_set_secret(key, value):
+ written[key] = value
+ return True
+
+ monkeypatch.setattr("jarvis.core.config.set_secret", fake_set_secret)
+ return written
+
+
+def test_supabase_link_saves_nothing_when_the_connection_fails(env, monkeypatch) -> None:
+ """A string that cannot connect must not become the configured store.
+
+ Saving it anyway would flip db_backend to postgres and then degrade back to
+ SQLite on every boot — a silent downgrade the user never asked for and
+ cannot see.
+ """
+ written = _stub_supabase(
+ monkeypatch, probe_ok=False, probe_detail="Connection failed: timeout"
+ )
+ response = env.client.post(
+ "/api/ultrawiki/storage/supabase/link",
+ json={"project_ref": "abcdefghijklmnopqrst", "db_password": "hunter2"},
+ )
+ assert response.status_code == 409, response.text
+ detail = response.json()["detail"]
+ assert detail["can_save_anyway"] is True
+ assert "timeout" in detail["probe_detail"]
+ assert written == {}
+ assert env.cfg.ultrawiki.db_backend == "sqlite"
+
+
+def test_supabase_link_can_be_forced_past_an_unreachable_probe(env, monkeypatch) -> None:
+ """A database only reachable over the user's VPN must still be linkable."""
+ written = _stub_supabase(
+ monkeypatch, probe_ok=False, probe_detail="Connection failed: timeout"
+ )
+ response = env.client.post(
+ "/api/ultrawiki/storage/supabase/link",
+ json={
+ "project_ref": "abcdefghijklmnopqrst",
+ "db_password": "hunter2",
+ "save_anyway": True,
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["probe_ok"] is False
+ assert "ultrawiki_db_url" in written
+ assert env.cfg.ultrawiki.db_backend == "postgres"
+
+
+def test_supabase_link_stores_the_uri_and_flips_the_slot(env, monkeypatch) -> None:
+ written = _stub_supabase(
+ monkeypatch,
+ probe_ok=True,
+ probe_detail="Connected: PostgreSQL 16; pgvector is available",
+ )
+ response = env.client.post(
+ "/api/ultrawiki/storage/supabase/link",
+ json={"project_ref": "abcdefghijklmnopqrst", "db_password": "p@ss/word"},
+ )
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["probe_ok"] is True
+ assert body["endpoint"]["host"] == "aws-1-eu-central-2.pooler.supabase.com"
+ # The credential is the connection string, stored under the store's own
+ # secret slot — never in the TOML (AP-12) — with the password encoded.
+ assert "ultrawiki_db_url" in written
+ assert written["ultrawiki_db_url"].startswith("postgresql://")
+ assert "p%40ss%2Fword" in written["ultrawiki_db_url"]
+ assert "p@ss/word" not in env.toml.read_text(encoding="utf-8")
+ assert env.cfg.ultrawiki.db_backend == "postgres"
+ assert env.cfg.ultrawiki.storage_provider == "supabase"
+
+
+def test_supabase_link_is_flagged_dangerous(env) -> None:
+ spec = env.server.app.openapi()
+ operation = spec["paths"]["/api/ultrawiki/storage/supabase/link"]["post"]
+ assert operation.get("x-jarvis-dangerous") is True