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.

fix(ultrawiki): keep the wiki mode people chose across a restart

Ruben Lütke343816fe180b
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.test.tsx
new file mode 100644
index 0000000000..0a7375db60
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.test.tsx
@@ -0,0 +1,133 @@
+/**
+ * UltraModeSwitch — the one-time wizard stays one-time (regression).
+ *
+ * The gate used to be `status.slots.embedding.provider`, which only exists
+ * once the UltraWiki service is running. Every restart therefore looked like
+ * a fresh install: the wizard reopened, asking again for the storage backend
+ * and — the expensive part — the embedding model, whose re-pick re-embeds the
+ * whole corpus. The gate is now the backend's `configured` flag, answered
+ * from the stored config and true from the first `/status` of a session.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { UltraModeSwitch } from "@/components/ultrawiki/UltraModeSwitch";
+import type { UltraWikiStatus } from "@/lib/ultrawikiApi";
+
+const activateSpy = vi.fn(async () => ({ ok: true, next_steps: "" }));
+
+vi.mock("@/lib/ultrawikiApi", async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return {
+ ...actual,
+ activateUltraWiki: (...args: unknown[]) => activateSpy(...(args as [])),
+ deactivateUltraWiki: async () => ({ ok: true }),
+ };
+});
+
+// The wizard is lazy-loaded; a stub keeps this test about the GATE.
+vi.mock("@/components/ultrawiki/ActivationWizard", () => ({
+ ActivationWizard: () => <div data-testid="wizard-stub" />,
+}));
+
+function status(overrides: Partial<UltraWikiStatus>): UltraWikiStatus {
+ return {
+ enabled: false,
+ configured: true,
+ started: false,
+ db_backend: "sqlite",
+ backend_in_use: "",
+ slots: {
+ embedding: {
+ provider: "gemini",
+ model: "gemini-embedding-001",
+ ready: true,
+ reason: "",
+ },
+ },
+ counts: {},
+ pipeline: { running: false, processed: {} },
+ sources: [],
+ jobs: [],
+ search_legs: {},
+ degradations: [],
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ cleanup();
+ activateSpy.mockClear();
+});
+
+describe("UltraModeSwitch — the activation wizard", () => {
+ it("re-activates with the stored choices instead of reopening the wizard", async () => {
+ render(<UltraModeSwitch status={status({})} onModeChanged={() => {}} />);
+
+ fireEvent.click(screen.getByTestId("wiki-mode-ultra"));
+
+ await waitFor(() => {
+ expect(activateSpy).toHaveBeenCalledTimes(1);
+ });
+ // Only the provider travels: every other stored value — model above all —
+ // stays exactly as the user picked it, so nothing is re-embedded.
+ expect(activateSpy).toHaveBeenCalledWith({ embedding_provider: "gemini" });
+ expect(screen.queryByTestId("wizard-stub")).toBeNull();
+ });
+
+ it("still re-activates when the service has not reported its slots yet", async () => {
+ // What a booting backend answers: the mode and the stored choices are
+ // known, the live readiness probes are not.
+ render(
+ <UltraModeSwitch
+ status={status({
+ slots: {
+ embedding: {
+ provider: "gemini",
+ model: "gemini-embedding-001",
+ ready: false,
+ reason: "the UltraWiki service has not started yet",
+ },
+ },
+ })}
+ onModeChanged={() => {}}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("wiki-mode-ultra"));
+
+ await waitFor(() => {
+ expect(activateSpy).toHaveBeenCalledTimes(1);
+ });
+ expect(screen.queryByTestId("wizard-stub")).toBeNull();
+ });
+
+ it("opens the wizard on a genuinely unconfigured install", async () => {
+ render(
+ <UltraModeSwitch
+ status={status({ configured: false, slots: {} })}
+ onModeChanged={() => {}}
+ />,
+ );
+
+ fireEvent.click(screen.getByTestId("wiki-mode-ultra"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("wizard-stub")).toBeDefined();
+ });
+ expect(activateSpy).not.toHaveBeenCalled();
+ });
+
+ it("asks again instead of opening the wizard when the status is unknown", async () => {
+ const onModeChanged = vi.fn();
+ render(<UltraModeSwitch status={null} onModeChanged={onModeChanged} />);
+
+ fireEvent.click(screen.getByTestId("wiki-mode-ultra"));
+
+ await waitFor(() => {
+ expect(onModeChanged).toHaveBeenCalled();
+ });
+ expect(screen.queryByTestId("wizard-stub")).toBeNull();
+ expect(activateSpy).not.toHaveBeenCalled();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.tsx
index c074efad5c..ea55aadbb8 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/UltraModeSwitch.tsx
@@ -51,17 +51,41 @@ export function UltraModeSwitch({
const enabled = status?.enabled === true;
// "Configured before" = an embedding provider was ever chosen; only then can
- // activation succeed without the wizard's one-time slot choices.
+ // activation succeed without the wizard's one-time slot choices. The backend
+ // answers this from the stored config (`configured`), which survives a
+ // restart and is already true while the service is still starting. The slot
+ // fallback only covers a backend older than that field — deriving the answer
+ // from the slot report alone is what reopened the wizard on every restart
+ // and offered to re-embed a corpus that was already embedded.
const configuredProvider = status?.slots?.embedding?.provider ?? "";
+ const configured =
+ status?.configured === undefined
+ ? configuredProvider !== ""
+ : status.configured === true;
+ // `null` = the backend has not answered yet (the app is still booting after
+ // the in-app Restart). That is NOT "never configured", so the click asks
+ // again instead of walking a returning user through a one-time wizard.
+ const statusKnown = status !== null;
async function switchToUltra() {
if (enabled || pending) return;
- if (!configuredProvider) {
+ if (!statusKnown) {
+ pushToast("error", t("ultrawiki.mode.status_unknown"));
+ onModeChanged();
+ return;
+ }
+ // The provider name has to come along for the re-activation POST, so a
+ // backend that claims `configured` without naming one still gets the
+ // wizard rather than a 400.
+ if (!configured || !configuredProvider) {
setWizardOpen(true);
return;
}
setPending(true);
try {
+ // Re-activate with the STORED choices — no model, no storage backend, so
+ // the backend keeps every value the user picked the first time and the
+ // corpus is never re-embedded for switching modes back and forth.
await activateUltraWiki({ embedding_provider: configuredProvider });
pushToast("success", t("ultrawiki.mode.activated"));
onModeChanged();
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 3082acf562..400ee91ce2 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2974,7 +2974,11 @@
"deactivate_title": "Zurück zum normalen Wiki wechseln?",
"deactivate_body": "Es wird nichts gelöscht: Jedes aufgenommene Element, jedes Embedding und jede Quelle bleibt auf der Festplatte. Der Ultra-Modus pausiert nur — beim Wiedereinschalten geht es genau dort weiter, wo du aufgehört hast.",
"deactivate_confirm": "Zu Normal wechseln",
- "cancel": "Abbrechen"
+ "cancel": "Abbrechen",
+ "status_unknown": "Der Wiki-Modus ist noch nicht lesbar — die App startet gerade. Es wird erneut versucht.",
+ "probing": "Es wird geprüft, welcher Wiki-Modus aktiv ist…",
+ "probe_stalled": "Der Wiki-Modus ist weiterhin nicht lesbar — das Backend antwortet nicht. Es wurde nichts geändert; dein Modus und seine Einstellungen bleiben erhalten.",
+ "probe_retry": "Erneut prüfen"
},
"panel": {
"tab_ask": "Fragen",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index ae14fb8406..a913abcc7d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2975,7 +2975,11 @@
"deactivate_title": "Switch back to the normal wiki?",
"deactivate_body": "Nothing is deleted: every ingested item, embedding, and source stays on disk. Ultra mode only pauses, and switching it back on picks up exactly where you left off.",
"deactivate_confirm": "Switch to Normal",
- "cancel": "Cancel"
+ "cancel": "Cancel",
+ "status_unknown": "The wiki mode is not readable yet — the app is still starting. Trying again.",
+ "probing": "Checking which wiki mode is active…",
+ "probe_stalled": "The wiki mode is still not readable — the backend has not answered. Nothing was changed; your mode and its settings are safe.",
+ "probe_retry": "Check again"
},
"panel": {
"tab_ask": "Ask",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index c5f9740cc8..e18fe2876e 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2974,7 +2974,11 @@
"deactivate_title": "¿Volver al wiki normal?",
"deactivate_body": "No se borra nada: cada elemento ingerido, cada embedding y cada fuente permanecen en el disco. El modo Ultra solo se pausa, y al reactivarlo continúa exactamente donde lo dejaste.",
"deactivate_confirm": "Cambiar a Normal",
- "cancel": "Cancelar"
+ "cancel": "Cancelar",
+ "status_unknown": "El modo del wiki aún no se puede leer — la aplicación todavía está arrancando. Se vuelve a intentar.",
+ "probing": "Comprobando qué modo del wiki está activo…",
+ "probe_stalled": "El modo del wiki sigue sin poder leerse — el backend no responde. No se cambió nada; tu modo y sus ajustes siguen intactos.",
+ "probe_retry": "Comprobar de nuevo"
},
"panel": {
"tab_ask": "Preguntar",
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index df6b0d5331..21135983dd 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -440,6 +440,16 @@ export interface UltraWikiSearchLeg {
export interface UltraWikiStatus {
enabled: boolean;
+ /**
+ * Has the one-time activation wizard ever completed on this install?
+ * Answered from the stored config (`jarvis/ui/web/ultrawiki_routes.py::
+ * _is_configured`), so it is the same answer while the app is still
+ * booting. NEVER derive this from `slots.embedding.provider`: the slot
+ * report needs the running service, and reading its emptiness as "never
+ * configured" is what reopened the wizard after every restart.
+ * Optional so an older backend simply reads as "unknown" here.
+ */
+ configured?: boolean;
started: boolean;
db_backend: string;
backend_in_use: string;
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.mode-persistence.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.mode-persistence.test.tsx
new file mode 100644
index 0000000000..9e6e1f4b9d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/WikiView.mode-persistence.test.tsx
@@ -0,0 +1,191 @@
+/**
+ * WikiView — the Wiki mode has to survive a restart (regression).
+ *
+ * Two failures shared one root: an UNANSWERED status was read as "Ultra is
+ * off". After the in-app Restart the window is back before the backend is,
+ * the poll-safe fetcher swallows that as a successful `null`, and with no
+ * retry and no interval the section stayed on the normal wiki for the rest of
+ * the session — on installs whose config said `[ultrawiki] enabled = true`.
+ * Clicking Ultra then reopened the ONE-TIME activation wizard, because the
+ * same empty answer also carried no configured embedding slot.
+ *
+ * These tests pin the honest behavior: unknown renders NEITHER body, keeps
+ * asking, and lands on the mode the backend actually reports.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { WikiView } from "@/views/WikiView";
+import type { WikiTreeResponse } from "@/lib/wikiApi";
+import type { UltraWikiStatus } from "@/lib/ultrawikiApi";
+
+vi.mock("@/hooks/useWikiLive", () => ({
+ useWikiLive: () => ({ connected: true, lastEventAt: null }),
+}));
+
+vi.mock("@/views/ultrawiki/UltraWikiPanel", () => ({
+ UltraWikiPanel: () => <div data-testid="ultrawiki-panel-stub" />,
+}));
+
+function renderWithClient(node: React.ReactNode) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, gcTime: 0, staleTime: 0 } },
+ });
+ return render(
+ <QueryClientProvider client={client}>{node}</QueryClientProvider>,
+ );
+}
+
+const EMPTY_TREE: WikiTreeResponse = {
+ ok: true,
+ vault_root: "wiki/obsidian-vault",
+ folders: [],
+ stats: { total_pages: 0, total_links: 0, last_curator_run: null },
+};
+
+function ultraStatus(enabled: boolean): UltraWikiStatus {
+ return {
+ enabled,
+ configured: true,
+ started: enabled,
+ db_backend: "sqlite",
+ backend_in_use: enabled ? "sqlite" : "",
+ slots: {
+ embedding: {
+ provider: "gemini",
+ model: "gemini-embedding-001",
+ ready: true,
+ reason: "",
+ },
+ },
+ counts: {},
+ pipeline: { running: false, processed: {} },
+ sources: [],
+ jobs: [],
+ search_legs: { keyword: { available: true } },
+ degradations: [],
+ };
+}
+
+/**
+ * `statusAnswer` is read per request, so a test can have the backend answer
+ * with a 503 first (still booting) and a real payload afterwards.
+ */
+function installFetchMock(statusAnswer: () => UltraWikiStatus | "unavailable") {
+ const routes: Record<string, () => unknown> = {
+ "/api/wiki/tree": () => EMPTY_TREE,
+ "/api/wiki/health": () => ({ ok: false }),
+ "/api/setup/obsidian/status": () => ({
+ installed: true,
+ config_exists: true,
+ vault_registered: true,
+ recommended_action: "ok",
+ }),
+ "/api/setup/state": () => ({ obsidian_setup_seen: true }),
+ };
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ if (url.startsWith("/api/ultrawiki/status")) {
+ const answer = statusAnswer();
+ if (answer === "unavailable") {
+ // Exactly what a still-booting backend gives the window: not an
+ // exception the caller can see, just an unusable response.
+ return { ok: false, status: 503, statusText: "Service Unavailable" } as Response;
+ }
+ return { ok: true, status: 200, statusText: "OK", json: async () => answer } as Response;
+ }
+ const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const prefix of prefixes) {
+ if (url.startsWith(prefix)) {
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => routes[prefix](),
+ } as Response;
+ }
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return fetchMock;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe("WikiView — the mode survives a restart", () => {
+ it("does NOT fall back to the normal wiki while the status is unknown", async () => {
+ installFetchMock(() => "unavailable");
+ renderWithClient(<WikiView />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("wiki-mode-probe")).toBeDefined();
+ });
+ // The bug: the normal wiki's own body rendered here, on an Ultra install.
+ expect(screen.queryByTestId("wiki-empty-state")).toBeNull();
+ expect(screen.queryByTestId("wiki-health-strip")).toBeNull();
+ expect(screen.queryByTestId("ultrawiki-panel-stub")).toBeNull();
+ });
+
+ it("lands on Ultra once the backend answers, without a reload", async () => {
+ let booting = true;
+ installFetchMock(() => (booting ? "unavailable" : ultraStatus(true)));
+ renderWithClient(<WikiView />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("wiki-mode-probe")).toBeDefined();
+ });
+
+ // The backend finishes starting; the section must reach Ultra on its own.
+ booting = false;
+ await waitFor(
+ () => {
+ expect(screen.getByTestId("ultrawiki-panel-stub")).toBeDefined();
+ },
+ { timeout: 8_000 },
+ );
+ expect(screen.queryByTestId("wiki-mode-probe")).toBeNull();
+ expect(
+ screen.getByTestId("wiki-mode-toggle").getAttribute("data-mode"),
+ ).toBe("ultra");
+ }, 12_000);
+
+ it("keeps the confirmed mode when a later poll comes back empty", async () => {
+ let answered = false;
+ installFetchMock(() => {
+ if (!answered) {
+ answered = true;
+ return ultraStatus(true);
+ }
+ return "unavailable";
+ });
+ renderWithClient(<WikiView />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-panel-stub")).toBeDefined();
+ });
+
+ // A blip must not flip the section back to the normal wiki behind the
+ // user's back — the last CONFIRMED answer stands.
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(screen.getByTestId("ultrawiki-panel-stub")).toBeDefined();
+ expect(screen.queryByTestId("wiki-empty-state")).toBeNull();
+ });
+
+ it("renders the normal wiki when the backend actually says the mode is off", async () => {
+ installFetchMock(() => ultraStatus(false));
+ renderWithClient(<WikiView />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("wiki-empty-state")).toBeDefined();
+ });
+ expect(screen.queryByTestId("wiki-mode-probe")).toBeNull();
+ expect(screen.queryByTestId("ultrawiki-panel-stub")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
index 3c3676565e..e4c19531ec 100644
--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
@@ -75,6 +75,32 @@ function installFetchMock(
}),
} as Response;
}
+ // Which mode owns the Wiki section. These tests are about the NORMAL wiki
+ // body, and that body only renders once the backend has actually said the
+ // mode is off — an unanswered status renders neither body, because
+ // guessing "off" is what dropped Ultra installs back into the normal wiki
+ // after every restart (WikiView.mode-persistence.test.tsx).
+ if (url.startsWith("/api/ultrawiki/status")) {
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({
+ enabled: false,
+ configured: false,
+ started: false,
+ db_backend: "sqlite",
+ backend_in_use: "",
+ slots: {},
+ counts: {},
+ pipeline: { running: false, processed: {} },
+ sources: [],
+ jobs: [],
+ search_legs: {},
+ degradations: [],
+ }),
+ } as Response;
+ }
for (const prefix of Object.keys(routes)) {
if (url.startsWith(prefix)) {
const body = routes[prefix]();
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.tsx b/jarvis/ui/web/frontend/src/views/WikiView.tsx
index 1ecd98d88d..2dd3fd07c6 100644
--- a/jarvis/ui/web/frontend/src/views/WikiView.tsx
+++ b/jarvis/ui/web/frontend/src/views/WikiView.tsx
@@ -43,7 +43,10 @@ import { BacklinksPanel } from "@/components/wiki/BacklinksPanel";
import { ObsidianStatus } from "@/components/wiki/ObsidianStatus";
import { ObsidianSetupDialog } from "@/components/wiki/ObsidianSetupDialog";
import { UltraModeSwitch } from "@/components/ultrawiki/UltraModeSwitch";
-import { fetchUltraWikiStatus } from "@/lib/ultrawikiApi";
+import {
+ fetchUltraWikiStatus,
+ type UltraWikiStatus,
+} from "@/lib/ultrawikiApi";
import type { ObsidianStatus as ObsidianStatusType } from "@/types/setup";
// Agent C owns WikiGraph. Lazy import so the graph bundle (~120 KB minified)
@@ -106,14 +109,41 @@ export function WikiView(): JSX.Element {
});
// UltraWiki mode (D-5): `GET /api/ultrawiki/status` → `enabled` is the one
- // source of truth for which body this section renders. `null` = backend
- // unreachable → the normal wiki stands.
+ // source of truth for which body this section renders.
+ //
+ // `null` means the backend has not answered YET — it does not mean the mode
+ // is off. Reading it as off is how the in-app Restart dropped people who run
+ // Ultra back into the normal wiki: the window reloads while the backend is
+ // still coming up, the poll-safe fetcher swallows that as a successful
+ // `null`, and with no retry and no interval the section stayed wrong for the
+ // rest of the session. So: keep asking until it answers once, and until then
+ // render neither body rather than the wrong one.
const ultraStatusQuery = useQuery({
queryKey: ["ultrawiki", "status"],
queryFn: fetchUltraWikiStatus,
staleTime: 5_000,
+ refetchInterval: (query) => (query.state.data == null ? 3_000 : false),
});
- const ultraEnabled = ultraStatusQuery.data?.enabled === true;
+ // The last CONFIRMED answer. A later blip must not flip the section back to
+ // the normal wiki behind the user's back either.
+ const [lastKnownUltra, setLastKnownUltra] = useState<UltraWikiStatus | null>(
+ null,
+ );
+ const [unansweredProbes, setUnansweredProbes] = useState(0);
+ const ultraProbe = ultraStatusQuery.data;
+ const ultraProbeAt = ultraStatusQuery.dataUpdatedAt;
+ useEffect(() => {
+ if (ultraProbe) {
+ setLastKnownUltra(ultraProbe);
+ setUnansweredProbes(0);
+ } else if (ultraProbeAt > 0) {
+ setUnansweredProbes((n) => n + 1);
+ }
+ }, [ultraProbe, ultraProbeAt]);
+
+ const ultraStatus = ultraProbe ?? lastKnownUltra;
+ const ultraModeKnown = ultraStatus != null;
+ const ultraEnabled = ultraStatus?.enabled === true;
// When a slug is selected (via tree click, graph click, or wikilink),
// automatically swap to the page tab.
@@ -210,14 +240,16 @@ export function WikiView(): JSX.Element {
// the header counts that store. It used to read "31 pages · 732 wikilinks"
// above a screen reporting 4 712 items, which is two different corpora
// described as one and the first thing that made the section unreadable.
- const ultraProgress = ultraStatusQuery.data?.progress ?? null;
+ const ultraProgress = ultraStatus?.progress ?? null;
const ultraSubtitle = ultraProgress
? t("ultrawiki.panel.header_subtitle")
.replace("{0}", ultraProgress.total.toLocaleString("en-US").replace(/,/g, " "))
- .replace("{1}", String(ultraStatusQuery.data?.sources.length ?? 0))
+ .replace("{1}", String(ultraStatus?.sources.length ?? 0))
: t("ultrawiki.panel.loading");
- const subtitle = ultraEnabled
+ const subtitle = !ultraModeKnown
+ ? t("ultrawiki.mode.probing")
+ : ultraEnabled
? ultraSubtitle
: treeQuery.isLoading
? t("wiki_view.loading_vault")
@@ -237,14 +269,16 @@ export function WikiView(): JSX.Element {
</div>
<div className="flex shrink-0 items-center gap-3 pt-4">
<UltraModeSwitch
- status={ultraStatusQuery.data ?? null}
+ status={ultraStatus}
onModeChanged={() => void ultraStatusQuery.refetch()}
/>
{/* The vault pill belongs to the vault. In Ultra mode nothing on
screen comes from Obsidian, and "Obsidian: connected" over a
store it is not answering from reads as a claim about THIS
- screen. It returns the moment the switch goes back to Normal. */}
- {!ultraEnabled && (
+ screen. It returns the moment the switch goes back to Normal.
+ While the mode is still unknown it stays out too — the pill
+ would be the only thing on screen making a claim. */}
+ {ultraModeKnown && !ultraEnabled && (
<ObsidianStatus
onOpenSetup={(s) => {
setSetupHint(s);
@@ -255,7 +289,15 @@ export function WikiView(): JSX.Element {
</div>
</div>
- {ultraEnabled ? (
+ {!ultraModeKnown ? (
+ // Which mode owns this section is not known yet. Showing the normal
+ // wiki here would be a claim, not a placeholder — and the wrong one
+ // for everyone running Ultra.
+ <ModeProbe
+ unansweredProbes={unansweredProbes}
+ onRetry={() => void ultraStatusQuery.refetch()}
+ />
+ ) : ultraEnabled ? (
// Ultra mode owns the entire body below the header (D-5 either-or);
// the normal wiki surfaces stay untouched, ready for the switch back.
<Suspense fallback={<GraphSkeleton />}>
@@ -770,6 +812,52 @@ function EmptyState() {
);
}
+/**
+ * Shown while `GET /api/ultrawiki/status` has not answered once — typically
+ * the few seconds after the in-app Restart, when the window is already back
+ * but the backend is still coming up.
+ *
+ * It waits quietly at first because that is the normal case, and only says
+ * something once the silence has lasted long enough to be a real problem.
+ * Rendering the normal wiki instead would be a claim about which mode owns
+ * this section, and the wrong one for every Ultra install.
+ */
+function ModeProbe({
+ unansweredProbes,
+ onRetry,
+}: {
+ unansweredProbes: number;
+ onRetry: () => void;
+}): JSX.Element {
+ const t = useT();
+ // ~3 polls at 3 s: past a slow-but-normal start, into "this is not coming".
+ const stalled = unansweredProbes >= 3;
+ return (
+ <div
+ className="flex flex-1 items-center justify-center p-6"
+ data-testid="wiki-mode-probe"
+ data-stalled={stalled ? "true" : "false"}
+ >
+ <div className="max-w-md rounded-xl border border-border bg-card/40 px-6 py-5 text-center">
+ <p className="text-sm text-muted-foreground">
+ {t(stalled ? "ultrawiki.mode.probe_stalled" : "ultrawiki.mode.probing")}
+ </p>
+ {stalled && (
+ <button
+ type="button"
+ onClick={onRetry}
+ data-testid="wiki-mode-probe-retry"
+ className="mt-3 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-foreground transition-colors hover:bg-secondary"
+ >
+ <RefreshCw className="h-3 w-3" aria-hidden />
+ {t("ultrawiki.mode.probe_retry")}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
function GraphSkeleton() {
return (
<div
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 94ee81b82a..457baab04d 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -223,6 +223,56 @@ def _apply_live(request: Request, values: dict[str, str], *, enabled: bool | Non
log.debug("in-memory ultrawiki.enabled update skipped: %s", exc)
+def _is_configured(uw: Any) -> bool:
+ """Has the one-time activation wizard ever been completed on this install?
+
+ The single question the Normal/Ultra switch needs before deciding between
+ "re-activate with the stored choices" and "walk the user through the
+ wizard". It is answered from the CONFIG alone — the embedding slot is the
+ one choice activation cannot proceed without, and once written it survives
+ every restart.
+
+ Deliberately NOT derived from the live slot report: that one also probes
+ credentials and only exists once the service is wired, so during boot it
+ is empty. A client reading emptiness as "never configured" is exactly how
+ a restart reopened the one-time wizard on an install that had been running
+ Ultra for weeks, and offered to re-embed a corpus it had already embedded.
+ Configured and ready are different questions; this answers only the first.
+ """
+ return bool(str(getattr(uw, "embedding_provider", "") or "").strip())
+
+
+def _slots_from_config(uw: Any) -> dict[str, Any]:
+ """The stored slot choices, without asking the (not yet wired) service.
+
+ Same shape as the live report minus everything that needs a probe: no
+ ``ready``/``reason``/``available``, because a booting app genuinely does
+ not know those yet and inventing them would be the dishonesty this whole
+ payload exists to avoid.
+ """
+
+ def slot(provider_key: str, model_key: str) -> dict[str, Any]:
+ return {
+ "provider": str(getattr(uw, provider_key, "") or "").strip(),
+ "model": str(getattr(uw, model_key, "") or "").strip(),
+ "ready": False,
+ "reason": "the UltraWiki service has not started yet",
+ }
+
+ return {
+ "embedding": slot("embedding_provider", "embedding_model"),
+ "distill": slot("distill_provider", "distill_model"),
+ "rerank": slot("rerank_provider", "rerank_model"),
+ "storage": {
+ "configured": str(getattr(uw, "db_backend", "sqlite") or "sqlite"),
+ "in_use": "",
+ "ready": False,
+ "reason": "the store has not been opened yet",
+ "vector": {},
+ },
+ }
+
+
def _search_legs(cfg: Any) -> dict[str, Any]:
"""Honest per-leg availability report (keyword / vector / rerank).
@@ -330,10 +380,16 @@ async def get_status(request: Request) -> dict[str, Any]:
if service is None:
return {
"enabled": enabled,
+ # Whether the wizard has ever run. Answered from the config, so it
+ # is the SAME answer before and after the service wires itself —
+ # see _is_configured for the restart bug that demanded it.
+ "configured": _is_configured(uw),
"started": False,
"db_backend": configured_backend,
"backend_in_use": "",
- "slots": {},
+ # The stored choices, not an empty dict: a booting app still knows
+ # what the user picked, and saying otherwise reopens the wizard.
+ "slots": _slots_from_config(uw),
"reembed": {},
"counts": {},
# Same shape as a live answer, so no client has to special-case a
@@ -370,6 +426,7 @@ async def get_status(request: Request) -> dict[str, Any]:
}
return {
"enabled": bool(data.get("enabled", enabled)),
+ "configured": _is_configured(uw),
"started": started,
"db_backend": str(backend.get("configured") or configured_backend),
"backend_in_use": str(backend.get("in_use") or ""),
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index bf02f7340c..dfa26e5d71 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -629,7 +629,10 @@ def test_routes_are_honest_while_the_service_is_unwired(env) -> None:
assert status.status_code == 200
body = status.json()
assert body["started"] is False
- assert body["slots"] == {}
+ # The stored CHOICES are still known (they live in the config, not in
+ # the service), and nothing claims to be ready.
+ assert body["slots"]["embedding"]["ready"] is False
+ assert body["slots"]["storage"]["ready"] is False
assert body["sources"] == []
assert body["pipeline"]["running"] is False
assert body["pipeline"]["state"] == "paused"
@@ -640,6 +643,58 @@ def test_routes_are_honest_while_the_service_is_unwired(env) -> None:
env.server.app.state.ultrawiki = env.service
+def test_status_reports_the_stored_choices_while_the_service_is_unwired(
+ env,
+) -> None:
+ """A restart must not look like a fresh install.
+
+ The window comes back before the backend finishes starting, so the very
+ first `/status` of a session is answered with `app.state.ultrawiki` still
+ `None`. When that answer carried no slots, the Normal/Ultra switch read
+ "never configured" and reopened the ONE-TIME activation wizard on an
+ install that had been running Ultra for weeks — offering to re-pick the
+ embedding model, which re-embeds the whole corpus.
+ """
+ _activate(env)
+ env.server.app.state.ultrawiki = None
+ try:
+ body = env.client.get("/api/ultrawiki/status").json()
+ # The mode itself survives: it is read from the config, not the service.
+ assert body["enabled"] is True
+ # And so does the answer the wizard gate depends on.
+ assert body["configured"] is True
+ assert body["slots"]["embedding"]["provider"] == "gemini"
+ assert body["slots"]["embedding"]["model"] == "fake-embed"
+ assert body["slots"]["storage"]["configured"] == "sqlite"
+ finally:
+ env.server.app.state.ultrawiki = env.service
+
+
+def test_status_reports_not_configured_before_the_first_activation(env) -> None:
+ """The flag is a real answer in both directions — a fresh install still
+ gets the wizard."""
+ body = env.client.get("/api/ultrawiki/status").json()
+ assert body["configured"] is False
+ assert body["enabled"] is False
+
+
+def test_status_keeps_reporting_configured_after_switching_back_to_normal(
+ env,
+) -> None:
+ """Deactivating is not un-configuring (D-9).
+
+ Switching to Normal and back must re-activate with the stored choices,
+ never walk the user through the one-time wizard again.
+ """
+ _activate(env)
+ assert env.client.post("/api/ultrawiki/deactivate").status_code == 200
+
+ body = env.client.get("/api/ultrawiki/status").json()
+ assert body["enabled"] is False
+ assert body["configured"] is True
+ assert body["slots"]["embedding"]["provider"] == "gemini"
+
+
# ---------------------------------------------------------------------------
# Sync: one at a time, and the full refresh
# ---------------------------------------------------------------------------