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): visibility package — approve imports everything, contents inventory, honest cards

Ruben Lütke90a1acf0b788
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx
new file mode 100644
index 0000000000..c5dae0ae64
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.test.tsx
@@ -0,0 +1,206 @@
+/**
+ * ContentsPanel tests — the database inventory.
+ *
+ * Pins that the tab actually lists the stored items (not just counts), that
+ * "Load more" appends the next page instead of replacing it, and that an empty
+ * store points the user at the Sources tab rather than looking broken.
+ */
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+
+import { ContentsPanel } from "@/components/ultrawiki/ContentsPanel";
+import type { UltraWikiItem, UltraWikiStatus } from "@/lib/ultrawikiApi";
+
+function status(overrides: Partial<UltraWikiStatus> = {}): UltraWikiStatus {
+ return {
+ enabled: true,
+ started: true,
+ db_backend: "sqlite",
+ backend_in_use: "sqlite",
+ slots: {},
+ counts: {
+ captured: 1,
+ keyword_indexed: 0,
+ embedded: 0,
+ distilled: 2,
+ failed: 0,
+ total: 3,
+ },
+ pipeline: { running: true, state: "idle", processed: {} },
+ sources: [
+ {
+ id: "src-docs",
+ connector: "local-folder",
+ label: "My documents",
+ consent: "approved",
+ enabled: true,
+ areas: [],
+ counts: null,
+ sync_state: null,
+ last_sync_at: null,
+ last_error: null,
+ },
+ ],
+ jobs: [],
+ search_legs: {},
+ degradations: [],
+ ...overrides,
+ };
+}
+
+function item(index: number): UltraWikiItem {
+ return {
+ id: index,
+ source_id: "src-docs",
+ title: `Note ${index}`,
+ state: "distilled",
+ permalink: `file:///notes/${index}.md`,
+ timestamp_utc: "2026-07-01T08:00:00Z",
+ ingested_at: new Date(Date.now() - 2 * 60_000).toISOString(),
+ updated_at: "2026-07-25T08:00:00Z",
+ };
+}
+
+/** Records every /items request so the test can assert on the paging. */
+function installItemsMock(pages: { items: UltraWikiItem[]; total: number }[]) {
+ const seen: string[] = [];
+ let call = 0;
+ const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
+ const url = String(input);
+ seen.push(url);
+ const page = pages[Math.min(call, pages.length - 1)];
+ call += 1;
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => ({
+ items: page.items,
+ total: page.total,
+ limit: 50,
+ offset: 0,
+ }),
+ } as Response;
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return { fetchMock, seen };
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("ContentsPanel", () => {
+ it("lists the stored items with their source, stage and load time", async () => {
+ installItemsMock([{ items: [item(1), item(2)], total: 2 }]);
+
+ render(<ContentsPanel status={status()} />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-item-1")).toBeDefined();
+ });
+ const row = screen.getByTestId("ultrawiki-item-1");
+ expect(row.textContent).toContain("Note 1");
+ // The source is shown by its LABEL, not its generated id.
+ expect(row.textContent).toContain("My documents");
+ expect(row.textContent).toContain("distilled");
+ expect(row.textContent).toContain("2 min ago");
+ // The title links back to where the item came from.
+ const link = row.querySelector("a");
+ expect(link?.getAttribute("href")).toBe("file:///notes/1.md");
+ // The header states what the whole store holds.
+ expect(screen.getByTestId("ultrawiki-contents-total").textContent).toContain(
+ "3",
+ );
+ });
+
+ it("appends the next page instead of replacing the first", async () => {
+ const { seen } = installItemsMock([
+ { items: [item(1), item(2)], total: 4 },
+ { items: [item(3), item(4)], total: 4 },
+ ]);
+
+ render(<ContentsPanel status={status()} />);
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-contents-load-more")).toBeDefined();
+ });
+
+ fireEvent.click(screen.getByTestId("ultrawiki-contents-load-more"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-item-4")).toBeDefined();
+ });
+ // The first page is still there — this is a page APPEND, not a swap.
+ expect(screen.getByTestId("ultrawiki-item-1")).toBeDefined();
+ expect(seen[1]).toContain("offset=2");
+ expect(
+ screen.getByTestId("ultrawiki-contents-showing").textContent,
+ ).toContain("4");
+ });
+
+ it("re-queries from the top when a filter changes", async () => {
+ const { seen } = installItemsMock([
+ { items: [item(1)], total: 1 },
+ { items: [], total: 0 },
+ ]);
+
+ render(<ContentsPanel status={status()} />);
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-item-1")).toBeDefined();
+ });
+
+ fireEvent.change(screen.getByTestId("ultrawiki-contents-state-filter"), {
+ target: { value: "failed" },
+ });
+
+ await waitFor(() => {
+ expect(seen.some((url) => url.includes("state=failed"))).toBe(true);
+ });
+ const filtered = seen.find((url) => url.includes("state=failed")) ?? "";
+ expect(filtered).toContain("offset=0");
+ });
+
+ it("points an empty store at the Sources tab", async () => {
+ installItemsMock([{ items: [], total: 0 }]);
+ const onOpenSources = vi.fn();
+
+ render(
+ <ContentsPanel
+ status={status({ counts: { total: 0 } })}
+ onOpenSources={onOpenSources}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-contents-empty")).toBeDefined();
+ });
+ fireEvent.click(screen.getByTestId("ultrawiki-contents-open-sources"));
+ expect(onOpenSources).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a failed load instead of showing an empty table", async () => {
+ const fetchMock = vi.fn(async () => {
+ throw new Error("network down");
+ });
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+
+ render(<ContentsPanel status={status()} />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-contents-error")).toBeDefined();
+ });
+ expect(
+ screen.getByTestId("ultrawiki-contents-error").textContent,
+ ).toContain("network down");
+ expect(screen.queryByTestId("ultrawiki-contents-empty")).toBeNull();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
new file mode 100644
index 0000000000..c1472d74bb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
@@ -0,0 +1,299 @@
+/**
+ * Contents tab — the inventory of what is actually IN the UltraWiki database.
+ *
+ * Every other surface answers "how many": counts per stage, a funnel, a job
+ * summary. None of them answered the question the maintainer actually asked
+ * while looking at the live app — "what is even in there?". This lists the
+ * items themselves, newest-ingested first, filterable by source and pipeline
+ * stage, each row linking out to where it came from.
+ *
+ * Paging is explicit ("Load more") rather than infinite scroll: the total is
+ * shown honestly next to what is loaded, so a store with 40 000 items reads as
+ * 40 000 items and not as an endless list.
+ */
+import { useCallback, useEffect, useState } from "react";
+import { AlertCircle, Database, ExternalLink, Loader2 } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { formatRelativeTime } from "@/components/ultrawiki/relativeTime";
+import {
+ fetchUltraWikiItems,
+ type UltraWikiItem,
+ type UltraWikiStatus,
+} from "@/lib/ultrawikiApi";
+
+const PAGE_SIZE = 50;
+
+/** Mirrors jarvis/ultrawiki/types.py::ItemState (AP-4: never retyped). */
+const STATE_FILTERS = [
+ ["captured", "ultrawiki.progress.stage_captured"],
+ ["keyword_indexed", "ultrawiki.progress.stage_keyword_indexed"],
+ ["embedded", "ultrawiki.progress.stage_embedded"],
+ ["distilled", "ultrawiki.progress.stage_distilled"],
+ ["failed", "ultrawiki.progress.stage_failed"],
+] as const;
+
+export function ContentsPanel({
+ status,
+ onOpenSources,
+}: {
+ status: UltraWikiStatus;
+ onOpenSources?: () => void;
+}): JSX.Element {
+ const t = useT();
+ const [sourceId, setSourceId] = useState("");
+ const [state, setState] = useState("");
+ const [rows, setRows] = useState<UltraWikiItem[]>([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState("");
+
+ const sourceLabels = new Map(
+ status.sources.map((source) => [source.id, source.label]),
+ );
+
+ const load = useCallback(
+ async (offset: number) => {
+ setLoading(true);
+ setError("");
+ try {
+ const page = await fetchUltraWikiItems({
+ sourceId: sourceId || undefined,
+ state: state || undefined,
+ limit: PAGE_SIZE,
+ offset,
+ });
+ // offset 0 is a fresh filter run; anything else appends a page.
+ setRows((current) =>
+ offset === 0 ? page.items : [...current, ...page.items],
+ );
+ setTotal(page.total);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [sourceId, state],
+ );
+
+ useEffect(() => {
+ void load(0);
+ }, [load]);
+
+ const stageChips = STATE_FILTERS.map(([key, labelKey]) => ({
+ key,
+ label: t(labelKey),
+ value: status.counts[key] ?? 0,
+ }));
+
+ return (
+ <div className="space-y-3 p-4" data-testid="ultrawiki-contents-panel">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="flex items-center gap-1.5 text-sm font-medium text-foreground">
+ <Database className="h-3.5 w-3.5" aria-hidden />
+ {t("ultrawiki.contents.title")}
+ </h3>
+ <span
+ className="rounded-full border border-primary/40 bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-foreground"
+ data-testid="ultrawiki-contents-total"
+ >
+ {t("ultrawiki.contents.total").replace(
+ "{0}",
+ String(status.counts.total ?? 0),
+ )}
+ </span>
+ {stageChips.map((chip) => (
+ <span
+ key={chip.key}
+ className={cn(
+ "rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground",
+ chip.key === "failed" &&
+ chip.value > 0 &&
+ "border-destructive/40 text-destructive",
+ )}
+ data-testid={`ultrawiki-contents-chip-${chip.key}`}
+ >
+ {chip.label} {chip.value}
+ </span>
+ ))}
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <label className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ {t("ultrawiki.contents.filter_source")}
+ <select
+ value={sourceId}
+ onChange={(e) => setSourceId(e.target.value)}
+ className="rounded-lg border border-border bg-background px-2 py-1 text-xs text-foreground"
+ data-testid="ultrawiki-contents-source-filter"
+ >
+ <option value="">{t("ultrawiki.contents.all_sources")}</option>
+ {status.sources.map((source) => (
+ <option key={source.id} value={source.id}>
+ {source.label}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ {t("ultrawiki.contents.filter_state")}
+ <select
+ value={state}
+ onChange={(e) => setState(e.target.value)}
+ className="rounded-lg border border-border bg-background px-2 py-1 text-xs text-foreground"
+ data-testid="ultrawiki-contents-state-filter"
+ >
+ <option value="">{t("ultrawiki.contents.all_states")}</option>
+ {STATE_FILTERS.map(([key, labelKey]) => (
+ <option key={key} value={key}>
+ {t(labelKey)}
+ </option>
+ ))}
+ </select>
+ </label>
+ </div>
+
+ {error && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-2.5 text-xs text-destructive"
+ data-testid="ultrawiki-contents-error"
+ >
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
+ {t("ultrawiki.contents.load_failed").replace("{0}", error)}
+ </div>
+ )}
+
+ {rows.length === 0 && !loading && !error ? (
+ <div
+ className="rounded-lg border border-dashed border-border/70 bg-card/30 p-4 text-xs text-muted-foreground"
+ data-testid="ultrawiki-contents-empty"
+ >
+ <p>{t("ultrawiki.contents.empty")}</p>
+ {onOpenSources && (
+ <button
+ type="button"
+ onClick={onOpenSources}
+ className="mt-1 underline underline-offset-2 hover:text-foreground"
+ data-testid="ultrawiki-contents-open-sources"
+ >
+ {t("ultrawiki.contents.open_sources")}
+ </button>
+ )}
+ </div>
+ ) : (
+ <div className="overflow-x-auto rounded-xl border border-border">
+ <table className="w-full text-left text-xs">
+ <thead className="bg-card/60 text-[10px] uppercase tracking-wider text-muted-foreground">
+ <tr>
+ <th className="px-3 py-2 font-normal">
+ {t("ultrawiki.contents.col_title")}
+ </th>
+ <th className="px-3 py-2 font-normal">
+ {t("ultrawiki.contents.col_source")}
+ </th>
+ <th className="px-3 py-2 font-normal">
+ {t("ultrawiki.contents.col_state")}
+ </th>
+ <th className="px-3 py-2 font-normal">
+ {t("ultrawiki.contents.col_loaded")}
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((item) => (
+ <tr
+ key={item.id}
+ className="border-t border-border/60"
+ data-testid={`ultrawiki-item-${item.id}`}
+ >
+ <td className="max-w-[22rem] px-3 py-2">
+ {item.permalink ? (
+ <a
+ href={item.permalink}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-foreground underline-offset-2 hover:underline"
+ >
+ <span className="truncate">{item.title}</span>
+ <ExternalLink
+ className="h-3 w-3 shrink-0 text-muted-foreground"
+ aria-hidden
+ />
+ </a>
+ ) : (
+ <span className="truncate text-foreground">
+ {item.title}
+ </span>
+ )}
+ </td>
+ <td className="px-3 py-2 text-muted-foreground">
+ {sourceLabels.get(item.source_id) ?? item.source_id}
+ </td>
+ <td className="px-3 py-2">
+ <span
+ className={cn(
+ "rounded-full border px-1.5 py-0.5 text-[10px]",
+ item.state === "failed"
+ ? "border-destructive/40 bg-destructive/10 text-destructive"
+ : "border-border text-muted-foreground",
+ )}
+ data-state={item.state}
+ >
+ {item.state}
+ </span>
+ </td>
+ <td className="px-3 py-2 text-muted-foreground">
+ {t("ultrawiki.contents.loaded_ago").replace(
+ "{0}",
+ formatRelativeTime(item.ingested_at, t),
+ )}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-center gap-3">
+ {rows.length > 0 && (
+ <span
+ className="text-[11px] text-muted-foreground"
+ data-testid="ultrawiki-contents-showing"
+ >
+ {t("ultrawiki.contents.showing")
+ .replace("{0}", String(rows.length))
+ .replace("{1}", String(total))}
+ </span>
+ )}
+ {rows.length < total && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => void load(rows.length)}
+ disabled={loading}
+ data-testid="ultrawiki-contents-load-more"
+ >
+ {loading && (
+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />
+ )}
+ {t("ultrawiki.contents.load_more")}
+ </Button>
+ )}
+ {loading && rows.length === 0 && (
+ <span
+ className="flex items-center gap-1.5 text-[11px] text-muted-foreground"
+ data-testid="ultrawiki-contents-loading"
+ >
+ <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
+ {t("ultrawiki.contents.loading")}
+ </span>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx
index 014681f46e..191a36cb07 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx
@@ -1,9 +1,12 @@
/**
- * SourcesPanel tests — the consent gate.
+ * SourcesPanel tests — the consent gate and what approval actually DOES.
*
- * Pins that Approve is an explicit POST to the approve route and that a
- * pending source exposes NO sync control at all (the backend would refuse
- * the sync; the UI must not dangle a dead button).
+ * Pins that Approve is an explicit POST to the approve route, that a pending
+ * source exposes NO sync control at all (the backend would refuse the sync;
+ * the UI must not dangle a dead button), and the visibility half: a running
+ * import shows its phase and ticking item count, a finished one says how much
+ * is stored, a notice is rendered as prominently as an error, and a
+ * plugin-bridge card is identifiable as the integration it actually is.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
@@ -92,8 +95,10 @@ describe("SourcesPanel — consent gate", () => {
it("fires the approve POST for a pending source and reports the change", async () => {
const fetchMock = installFetchMock({
"/api/ultrawiki/sources/src-pending/approve": () => ({
- ...PENDING,
- consent: "approved",
+ source: { ...PENDING, consent: "approved" },
+ job_id: "job-1",
+ auto_sync: true,
+ detail: "Importing everything this source holds.",
}),
});
const onChanged = vi.fn();
@@ -161,3 +166,229 @@ describe("SourcesPanel — consent gate", () => {
});
});
});
+
+describe("SourcesPanel — approve imports everything", () => {
+ it("approves with auto-import and reports the started job", async () => {
+ const fetchMock = installFetchMock({
+ "/api/ultrawiki/sources/src-pending/approve": () => ({
+ source: { ...PENDING, consent: "approved" },
+ job_id: "job-7",
+ auto_sync: true,
+ detail: "Importing everything this source holds.",
+ }),
+ });
+ renderWithClient(
+ <SourcesPanel sources={[PENDING]} onChanged={vi.fn()} />,
+ );
+
+ // The button no longer promises a bare flag flip.
+ const approve = screen.getByTestId("uw-source-approve-src-pending");
+ expect(approve.textContent).toContain("import everything");
+
+ fireEvent.click(approve);
+
+ await waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/ultrawiki/sources/src-pending/approve",
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+ // No auto_sync=false query: the default IS the import.
+ const [url] = fetchMock.mock.calls[0] as [string];
+ expect(url).not.toContain("auto_sync");
+ });
+
+ it("shows the running import with its phase, item count and a cancel button", async () => {
+ const fetchMock = installFetchMock({
+ "/api/ultrawiki/jobs/job-7/cancel": () => ({
+ job_id: "job-7",
+ cancel_requested: true,
+ }),
+ });
+ const importing = source({
+ id: "src-importing",
+ label: "Importing folder",
+ consent: "approved",
+ active_job: {
+ job_id: "job-7",
+ source_id: "src-importing",
+ mode: "backfill",
+ status: "running",
+ phase: "importing",
+ started_at: 0,
+ ended_at: null,
+ chunks: 2,
+ items: 412,
+ new: 400,
+ changed: 10,
+ unchanged: 2,
+ tombstoned: 0,
+ error: "",
+ },
+ });
+
+ renderWithClient(
+ <SourcesPanel sources={[importing]} onChanged={vi.fn()} />,
+ );
+
+ const progress = screen.getByTestId("uw-source-progress-src-importing");
+ expect(progress).toBeDefined();
+ expect(
+ screen.getByTestId("uw-source-progress-items-src-importing").textContent,
+ ).toContain("412");
+ // The phase is the honest "what is it doing", not just "running".
+ expect(progress.textContent).toContain("Importing");
+ // The reassurance the design asks for: this is a COPY.
+ expect(progress.textContent).toContain("COPIED");
+ // A running import hides the finished summary and blocks a second sync.
+ expect(screen.queryByTestId("uw-source-summary-src-importing")).toBeNull();
+ expect(
+ screen
+ .getByTestId("uw-source-sync-src-importing")
+ .hasAttribute("disabled"),
+ ).toBe(true);
+
+ fireEvent.click(screen.getByTestId("uw-source-cancel-src-importing"));
+ await waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/ultrawiki/jobs/job-7/cancel",
+ expect.objectContaining({ method: "POST" }),
+ );
+ });
+ });
+
+ it("replaces the ambiguous 'Never synced' with what is actually stored", () => {
+ installFetchMock({});
+ const done = source({
+ id: "src-done",
+ consent: "approved",
+ counts: {
+ captured: 0,
+ keyword_indexed: 0,
+ embedded: 0,
+ distilled: 120,
+ failed: 0,
+ total: 120,
+ },
+ last_outcome: {
+ finished_at: new Date(Date.now() - 5 * 60_000).toISOString(),
+ status: "done",
+ mode: "backfill",
+ new: 120,
+ changed: 0,
+ unchanged: 0,
+ tombstoned: 0,
+ },
+ });
+
+ renderWithClient(<SourcesPanel sources={[done]} onChanged={vi.fn()} />);
+
+ const summary = screen.getByTestId("uw-source-summary-src-done");
+ expect(summary.textContent).toContain("120");
+ expect(summary.textContent).toContain("5 min ago");
+ });
+});
+
+describe("SourcesPanel — honest error and notice surfaces", () => {
+ it("renders a notice as its own prominent box, not as a failure", () => {
+ installFetchMock({});
+ const noticed = source({
+ id: "src-bridge",
+ connector: "plugin-bridge",
+ label: "GitHub",
+ consent: "approved",
+ integration_id: "plugin:github",
+ last_notice:
+ "This integration is connected, but its pull adapter is not built yet - nothing was imported.",
+ });
+
+ renderWithClient(<SourcesPanel sources={[noticed]} onChanged={vi.fn()} />);
+
+ const notice = screen.getByTestId("ultrawiki-source-notice-src-bridge");
+ expect(notice.textContent).toContain("pull adapter is not built yet");
+ // A notice is NOT an error: no alert box, and it says so.
+ expect(screen.queryByTestId("ultrawiki-source-error-src-bridge")).toBeNull();
+ expect(notice.getAttribute("role")).not.toBe("alert");
+ });
+
+ it("renders a sync failure as an alert", () => {
+ installFetchMock({});
+ const failed = source({
+ id: "src-broken",
+ consent: "approved",
+ last_error: "FileNotFoundError: the vault folder is gone",
+ });
+
+ renderWithClient(<SourcesPanel sources={[failed]} onChanged={vi.fn()} />);
+
+ const error = screen.getByTestId("ultrawiki-source-error-src-broken");
+ expect(error.getAttribute("role")).toBe("alert");
+ expect(error.textContent).toContain("the vault folder is gone");
+ });
+});
+
+describe("SourcesPanel — bridge sources carry a real identity", () => {
+ it("names the card after the integration and says where it comes from", () => {
+ installFetchMock({});
+ const bridge = source({
+ id: "src-gh",
+ connector: "plugin-bridge",
+ label: "GitHub",
+ consent: "approved",
+ integration_id: "plugin:github",
+ });
+
+ renderWithClient(<SourcesPanel sources={[bridge]} onChanged={vi.fn()} />);
+
+ const card = screen.getByTestId("ultrawiki-source-src-gh");
+ expect(card.textContent).toContain("GitHub");
+ const subtitle = screen.getByTestId("uw-source-bridge-src-gh");
+ expect(subtitle.textContent).toContain("plugins / MCP bridge");
+ expect(subtitle.textContent).toContain("plugin:github");
+ });
+
+ it("registers a bridge source under the picked candidate's label", async () => {
+ const created: unknown[] = [];
+ const fetchMock = installFetchMock({
+ "/api/ultrawiki/areas": () => ({ areas: [], total: 0 }),
+ "/api/ultrawiki/bridge/candidates": () => ({
+ candidates: [
+ {
+ id: "plugin:github",
+ kind: "plugin",
+ label: "GitHub",
+ detail: "connected marketplace plugin; pull adapter pending",
+ },
+ ],
+ total: 1,
+ }),
+ "/api/ultrawiki/sources": (init) => {
+ created.push(JSON.parse(String(init?.body ?? "{}")));
+ return { id: "src-new" };
+ },
+ });
+ renderWithClient(<SourcesPanel sources={[]} onChanged={vi.fn()} />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-add-source-toggle"));
+ fireEvent.change(screen.getByTestId("ultrawiki-connector-select"), {
+ target: { value: "plugin-bridge" },
+ });
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-bridge-plugin:github")).toBeDefined();
+ });
+ fireEvent.click(screen.getByTestId("ultrawiki-bridge-plugin:github"));
+ fireEvent.click(screen.getByTestId("ultrawiki-create-source"));
+
+ await waitFor(() => {
+ expect(created).toHaveLength(1);
+ });
+ expect(fetchMock).toHaveBeenCalled();
+ // The integration's own name — never the generic bridge label, which made
+ // every bridge card look identical.
+ expect(created[0]).toMatchObject({
+ connector: "plugin-bridge",
+ label: "GitHub",
+ config: { integration_id: "plugin:github" },
+ });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
index 498f5ad4ad..e20ab59df3 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
@@ -1,28 +1,38 @@
/**
* Connected-sources panel (design doc 04 "Sources view").
*
- * Consent is THE gate: every source starts as `pending`, the Approve button
- * is an explicit user action with a short scope description, and a source
- * without approved consent shows NO sync control at all — the backend would
- * refuse the sync anyway (`service.start_sync`), the UI just does not dangle
- * a dead button. Per source: consent badge, per-stage backlog counts, last
- * sync / last error, Approve / Revoke / Sync now.
+ * Consent is THE gate: every source starts as `pending`, and a source without
+ * approved consent shows NO sync control at all — the backend would refuse the
+ * sync anyway (`service.start_sync`), the UI just does not dangle a dead
+ * button. What approval MEANS is now visible: approving imports everything the
+ * source holds right away, the card shows that import running (phase, items
+ * pulled so far, cancel), and once it is done it says how much is in the store
+ * and when it last ran — instead of the ambiguous "Approved / Never synced"
+ * pair that told the user nothing about whether anything had happened.
*
- * "Add source": connector picker over the five built-ins, a path field for
- * the folder-shaped connectors, area assignment, and — for the
- * plugin-bridge — the connected-integration candidates from
- * `GET /api/ultrawiki/bridge/candidates`, with a "pull adapter pending"
- * candidate marked honestly (registering it works, a sync finds nothing yet).
+ * Errors and notices are deliberately different things and look different: an
+ * error (red) means the sync FAILED, a notice (amber) means it ran fine and had
+ * nothing to import — today that is a plugin-bridge integration whose pull
+ * adapter is not built yet.
+ *
+ * "Add source": connector picker over the five built-ins, a path field for the
+ * folder-shaped connectors, area assignment, and — for the plugin-bridge — the
+ * connected-integration candidates from `GET /api/ultrawiki/bridge/candidates`.
+ * A bridge source is named after the integration the user picked ("GitHub"),
+ * never after the generic bridge, so the list is readable.
*/
import { useState } from "react";
import {
+ AlertCircle,
Check,
FolderOpen,
+ Info,
Loader2,
Plus,
RefreshCw,
ShieldCheck,
ShieldOff,
+ XCircle,
} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
@@ -30,9 +40,11 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useEventStore } from "@/store/events";
+import { formatRelativeTime } from "@/components/ultrawiki/relativeTime";
import {
ULTRAWIKI_CONNECTOR_IDS,
approveUltraWikiSource,
+ cancelUltraWikiJob,
createUltraWikiSource,
fetchUltraWikiAreas,
fetchUltraWikiBridgeCandidates,
@@ -53,6 +65,9 @@ const CONNECTOR_LABEL_KEY: Record<UltraWikiConnectorId, string> = {
/** Connectors that read a user-chosen folder (config key `root`). */
const PATH_CONNECTORS: readonly string[] = ["obsidian-vault", "local-folder"];
+/** The generic integration gateway — its cards carry the integration's name. */
+const BRIDGE_CONNECTOR = "plugin-bridge";
+
const CONSENT_BADGE: Record<
string,
{ labelKey: string; className: string }
@@ -151,7 +166,18 @@ export function SourcesPanel({
source={source}
busy={busySource === source.id}
onApprove={() =>
- void run(source.id, () => approveUltraWikiSource(source.id))
+ void run(source.id, async () => {
+ const result = await approveUltraWikiSource(source.id);
+ // The backend's detail is the honest explanation whenever no
+ // import could start (mode off, connector gone) — a situation
+ // the UI cannot enumerate for itself.
+ pushToast(
+ "success",
+ result.job_id
+ ? t("ultrawiki.sources.import_started")
+ : result.detail,
+ );
+ })
}
onRevoke={() =>
void run(source.id, () => revokeUltraWikiSource(source.id))
@@ -162,6 +188,9 @@ export function SourcesPanel({
pushToast("success", t("ultrawiki.sources.sync_started"));
})
}
+ onCancelJob={(jobId) =>
+ void run(source.id, () => cancelUltraWikiJob(jobId))
+ }
/>
))}
</ul>
@@ -176,17 +205,26 @@ function SourceCard({
onApprove,
onRevoke,
onSync,
+ onCancelJob,
}: {
source: UltraWikiSource;
busy: boolean;
onApprove: () => void;
onRevoke: () => void;
onSync: () => void;
+ onCancelJob: (jobId: string) => void;
}): JSX.Element {
const t = useT();
const consent = String(source.consent);
const badge = CONSENT_BADGE[consent] ?? CONSENT_BADGE.pending;
const approved = consent === "approved";
+ const activeJob = source.active_job ?? null;
+ const storedItems = source.counts?.total ?? 0;
+ // The persisted outcome wins over `last_sync_at`: it is the moment a run
+ // actually FINISHED, and it survives a restart.
+ const lastFinished =
+ source.last_outcome?.finished_at ?? source.last_sync_at ?? null;
+ const lastFinishedText = formatRelativeTime(lastFinished, t);
return (
<li
@@ -214,6 +252,21 @@ function SourceCard({
</span>
</div>
+ {source.connector === BRIDGE_CONNECTOR && (
+ <p
+ className="mt-0.5 text-[11px] text-muted-foreground"
+ data-testid={`uw-source-bridge-${source.id}`}
+ >
+ {t("ultrawiki.sources.bridge_via")}
+ {source.integration_id
+ ? ` · ${t("ultrawiki.sources.integration").replace(
+ "{0}",
+ source.integration_id,
+ )}`
+ : ""}
+ </p>
+ )}
+
{source.counts && (
<dl className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-[11px] text-muted-foreground">
{STAGE_KEYS.map(([key, labelKey]) => {
@@ -237,35 +290,117 @@ function SourceCard({
</dl>
)}
- <div className="mt-1.5 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-muted-foreground">
- <span>
- {source.last_sync_at
- ? t("ultrawiki.sources.last_sync").replace(
+ {activeJob ? (
+ <div
+ className="mt-2 rounded-lg border border-primary/30 bg-primary/5 p-2.5"
+ data-testid={`uw-source-progress-${source.id}`}
+ >
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11px]">
+ <Loader2
+ className="h-3.5 w-3.5 shrink-0 animate-spin text-primary"
+ aria-hidden
+ />
+ <span
+ className="font-medium text-foreground"
+ data-phase={activeJob.phase ?? "queued"}
+ >
+ {t(`ultrawiki.sources.phase_${activeJob.phase ?? "queued"}`)}
+ </span>
+ <span
+ className="text-muted-foreground"
+ data-testid={`uw-source-progress-items-${source.id}`}
+ >
+ {t("ultrawiki.sources.import_items").replace(
"{0}",
- source.last_sync_at,
- )
- : t("ultrawiki.sources.never_synced")}
- </span>
- {source.areas.length > 0 && (
- <span>
- {t("ultrawiki.sources.areas").replace(
- "{0}",
- source.areas.join(", "),
- )}
- </span>
- )}
- {source.last_error && (
- <span
- className="text-destructive"
- data-testid={`ultrawiki-source-error-${source.id}`}
+ String(activeJob.items ?? 0),
+ )}
+ </span>
+ <button
+ type="button"
+ onClick={() => onCancelJob(activeJob.job_id)}
+ disabled={busy}
+ data-testid={`uw-source-cancel-${source.id}`}
+ className="ml-auto inline-flex items-center gap-1 rounded-md border border-border px-1.5 py-0.5 text-foreground hover:bg-muted disabled:opacity-50"
+ >
+ <XCircle className="h-3 w-3" aria-hidden />
+ {t("ultrawiki.sources.cancel_import")}
+ </button>
+ </div>
+ {/* The connector streams — there is no total to divide by, so the
+ bar is deliberately indeterminate and the ticking item count
+ carries the real information. */}
+ <div
+ className="mt-2 h-1.5 w-full overflow-hidden rounded-full bg-primary/15"
+ role="progressbar"
+ aria-label={t("ultrawiki.sources.importing")}
>
- {t("ultrawiki.sources.last_error").replace(
- "{0}",
- source.last_error,
- )}
+ <div className="h-full w-1/3 animate-pulse rounded-full bg-primary" />
+ </div>
+ <p className="mt-1.5 text-[11px] leading-relaxed text-muted-foreground">
+ {t("ultrawiki.sources.copy_reassurance")}
+ </p>
+ </div>
+ ) : (
+ approved && (
+ <p
+ className="mt-2 text-[11px] text-foreground"
+ data-testid={`uw-source-summary-${source.id}`}
+ >
+ {storedItems > 0
+ ? t("ultrawiki.sources.fully_imported").replace(
+ "{0}",
+ String(storedItems),
+ )
+ : t("ultrawiki.sources.nothing_imported_yet")}
+ {lastFinishedText
+ ? ` · ${t("ultrawiki.sources.last_sync_relative").replace(
+ "{0}",
+ lastFinishedText,
+ )}`
+ : ""}
+ </p>
+ )
+ )}
+
+ {source.areas.length > 0 && (
+ <p className="mt-1 text-[11px] text-muted-foreground">
+ {t("ultrawiki.sources.areas").replace("{0}", source.areas.join(", "))}
+ </p>
+ )}
+
+ {/* Errors and notices are big enough to read: the old one-line grey text
+ hid both a dead source and a "connected but nothing to import yet"
+ integration behind the same tiny sentence. */}
+ {source.last_error && (
+ <div
+ role="alert"
+ className="mt-2 flex items-start gap-2 rounded-lg border border-destructive/50 bg-destructive/10 p-2.5 text-xs text-destructive"
+ data-testid={`ultrawiki-source-error-${source.id}`}
+ >
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
+ <span className="min-w-0">
+ <strong className="block font-medium">
+ {t("ultrawiki.sources.error_label")}
+ </strong>
+ {source.last_error}
</span>
- )}
- </div>
+ </div>
+ )}
+
+ {source.last_notice && (
+ <div
+ className="mt-2 flex items-start gap-2 rounded-lg border border-[#ffb84d]/50 bg-[#ffb84d]/10 p-2.5 text-xs text-[#ffb84d]"
+ data-testid={`ultrawiki-source-notice-${source.id}`}
+ >
+ <Info className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
+ <span className="min-w-0">
+ <strong className="block font-medium">
+ {t("ultrawiki.sources.notice_label")}
+ </strong>
+ {source.last_notice}
+ </span>
+ </div>
+ )}
<div className="mt-2 flex flex-wrap items-center gap-2">
{!approved && (
@@ -280,7 +415,7 @@ function SourceCard({
) : (
<ShieldCheck className="mr-1 h-3.5 w-3.5" aria-hidden />
)}
- {t("ultrawiki.sources.approve")}
+ {t("ultrawiki.sources.approve_import")}
</Button>
)}
{approved && (
@@ -290,7 +425,7 @@ function SourceCard({
variant="outline"
size="sm"
onClick={onSync}
- disabled={busy}
+ disabled={busy || Boolean(activeJob)}
data-testid={`uw-source-sync-${source.id}`}
>
<RefreshCw
@@ -348,10 +483,20 @@ function AddSourceForm({
queryKey: ["ultrawiki", "bridge-candidates"],
queryFn: fetchUltraWikiBridgeCandidates,
staleTime: 5_000,
- enabled: connector === "plugin-bridge",
+ enabled: connector === BRIDGE_CONNECTOR,
});
const needsPath = PATH_CONNECTORS.includes(connector);
+ const candidates = bridgeQuery.data?.candidates ?? [];
+ const selectedCandidate =
+ candidates.find((candidate) => candidate.id === integrationId) ?? null;
+ // A bridge card is named after the INTEGRATION the user picked. Falling back
+ // to the connector's own name produced a list of identical "Connected
+ // integration" rows nobody could tell apart.
+ const defaultLabel =
+ connector === BRIDGE_CONNECTOR && selectedCandidate
+ ? selectedCandidate.label
+ : t(CONNECTOR_LABEL_KEY[connector]);
function toggleArea(id: string) {
setSelectedAreas((current) =>
@@ -367,13 +512,13 @@ function AddSourceForm({
setError("");
const config: Record<string, unknown> = {};
if (needsPath && rootPath.trim()) config.root = rootPath.trim();
- if (connector === "plugin-bridge" && integrationId) {
+ if (connector === BRIDGE_CONNECTOR && integrationId) {
config.integration_id = integrationId;
}
try {
await createUltraWikiSource({
connector,
- label: label.trim() || t(CONNECTOR_LABEL_KEY[connector]),
+ label: label.trim() || defaultLabel,
config,
areas: selectedAreas,
});
@@ -431,7 +576,7 @@ function AddSourceForm({
type="text"
value={label}
onChange={(e) => setLabel(e.target.value)}
- placeholder={t(CONNECTOR_LABEL_KEY[connector])}
+ placeholder={defaultLabel}
className={inputCls}
/>
</label>
@@ -455,7 +600,7 @@ function AddSourceForm({
</label>
)}
- {connector === "plugin-bridge" && (
+ {connector === BRIDGE_CONNECTOR && (
<div>
<span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground">
{t("ultrawiki.sources.bridge_label")}
@@ -469,13 +614,13 @@ function AddSourceForm({
<p className="text-xs text-destructive">
{t("ultrawiki.sources.bridge_load_failed")}
</p>
- ) : (bridgeQuery.data?.candidates ?? []).length === 0 ? (
+ ) : candidates.length === 0 ? (
<p className="text-xs text-muted-foreground">
{t("ultrawiki.sources.bridge_empty")}
</p>
) : (
<ul className="space-y-1.5">
- {(bridgeQuery.data?.candidates ?? []).map((candidate) => {
+ {candidates.map((candidate) => {
const selected = integrationId === candidate.id;
// The backend states adapter readiness inside `detail`; mark
// "pull adapter pending" honestly instead of hiding it.
@@ -576,7 +721,7 @@ function AddSourceForm({
type="submit"
disabled={
submitting ||
- (connector === "plugin-bridge" && !integrationId) ||
+ (connector === BRIDGE_CONNECTOR && !integrationId) ||
(needsPath && !rootPath.trim())
}
data-testid="ultrawiki-create-source"
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/relativeTime.ts b/jarvis/ui/web/frontend/src/components/ultrawiki/relativeTime.ts
new file mode 100644
index 0000000000..330972836d
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/relativeTime.ts
@@ -0,0 +1,59 @@
+/**
+ * "last sync 4 min ago" instead of "2026-07-25T14:03:11Z".
+ *
+ * The raw ISO stamp is what the Sources card used to print, and nobody reads a
+ * timestamp as "recently". The formatter returns an i18n KEY plus its one
+ * placeholder value rather than a finished sentence, so every locale keeps its
+ * own wording (and its own plural rules) instead of an English string being
+ * assembled here.
+ */
+
+/** An i18n key under `ultrawiki.time.*` plus the value for its `{0}`. */
+export interface RelativeTimeParts {
+ key: string;
+ value: string;
+}
+
+const MINUTE_MS = 60_000;
+const HOUR_MS = 60 * MINUTE_MS;
+const DAY_MS = 24 * HOUR_MS;
+
+/**
+ * `null` for an absent or unparseable stamp — the caller then says "never"
+ * rather than inventing a moment. A stamp in the future (clock skew between a
+ * server and this browser) reads as "just now", never as a negative age.
+ */
+export function relativeTimeParts(
+ stamp: string | number | null | undefined,
+ now: number = Date.now(),
+): RelativeTimeParts | null {
+ if (stamp === null || stamp === undefined || stamp === "") return null;
+ const parsed =
+ typeof stamp === "number" ? stamp * 1000 : Date.parse(String(stamp));
+ if (!Number.isFinite(parsed)) return null;
+ const age = Math.max(0, now - parsed);
+ if (age < MINUTE_MS) return { key: "ultrawiki.time.just_now", value: "" };
+ if (age < HOUR_MS) {
+ return {
+ key: "ultrawiki.time.minutes",
+ value: String(Math.floor(age / MINUTE_MS)),
+ };
+ }
+ if (age < DAY_MS) {
+ return {
+ key: "ultrawiki.time.hours",
+ value: String(Math.floor(age / HOUR_MS)),
+ };
+ }
+ return { key: "ultrawiki.time.days", value: String(Math.floor(age / DAY_MS)) };
+}
+
+/** Convenience wrapper: resolve the parts through a translate function. */
+export function formatRelativeTime(
+ stamp: string | number | null | undefined,
+ t: (key: string) => string,
+ now: number = Date.now(),
+): string {
+ const parts = relativeTimeParts(stamp, now);
+ return parts === null ? "" : t(parts.key).replace("{0}", parts.value);
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 186c1a3141..f926f76787 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2730,7 +2730,8 @@
"loading": "UltraWiki-Status wird geladen…",
"status_unavailable": "UltraWiki-Status nicht verfügbar — läuft das Backend?",
"embedding_dead": "Der Embedding-Slot ist nicht bereit ({0}). Stichwort- und Zeit-Antworten funktionieren weiter; die semantische Suche pausiert, bis der Slot repariert ist.",
- "open_settings": "Einstellungen öffnen"
+ "open_settings": "Einstellungen öffnen",
+ "tab_contents": "Inhalte"
},
"progress": {
"title": "Import-Pipeline",
@@ -2786,7 +2787,25 @@
"connector_local_folder": "Lokaler Ordner",
"connector_conversations": "Unterhaltungen mit {name}",
"connector_normal_wiki": "Eingebautes Wiki",
- "connector_plugin_bridge": "Verbundene Integration (Plugins / MCP)"
+ "connector_plugin_bridge": "Verbundene Integration (Plugins / MCP)",
+ "approve_import": "Freigeben & alles importieren",
+ "import_started": "Import gestartet – alles, was diese Quelle enthält, wird kopiert.",
+ "importing": "Importiere",
+ "import_items": "{0} Einträge bisher importiert",
+ "cancel_import": "Import abbrechen",
+ "copy_reassurance": "Alles wird in deinen privaten Wissensspeicher KOPIERT. An der Quelle wird nichts geändert, verschoben oder gelöscht.",
+ "fully_imported": "Vollständig importiert: {0} Einträge",
+ "nothing_imported_yet": "Noch nichts importiert",
+ "last_sync_relative": "letzte Synchronisierung {0}",
+ "error_label": "Synchronisierung fehlgeschlagen",
+ "notice_label": "Hinweis",
+ "bridge_via": "über Plugins / MCP-Brücke",
+ "integration": "Integration: {0}",
+ "phase_queued": "Wartet auf den Start",
+ "phase_reading": "Quelle wird gelesen",
+ "phase_importing": "Importiere",
+ "phase_reconciling": "Prüfe auf entfernte Einträge",
+ "phase_finished": "Wird abgeschlossen"
},
"ask": {
"placeholder": "Frag dein Wissen…",
@@ -2917,6 +2936,31 @@
"link": "Dieses Projekt verbinden",
"already_linked": "Eine Supabase-Verbindung ist bereits gespeichert.",
"save_anyway": "Trotzdem speichern"
+ },
+ "contents": {
+ "title": "Gespeicherte Inhalte",
+ "total": "{0} Einträge gespeichert",
+ "filter_source": "Quelle",
+ "filter_state": "Stufe",
+ "all_sources": "Alle Quellen",
+ "all_states": "Alle Stufen",
+ "col_title": "Eintrag",
+ "col_source": "Quelle",
+ "col_state": "Stufe",
+ "col_loaded": "Geladen",
+ "loaded_ago": "{0}",
+ "showing": "{0} von {1} werden angezeigt",
+ "load_more": "Mehr laden",
+ "loading": "Inhalte werden geladen…",
+ "load_failed": "Die Inhalte konnten nicht geladen werden: {0}",
+ "empty": "Es ist noch nichts gespeichert. Gib eine Quelle frei, dann wird alles importiert, was sie enthält.",
+ "open_sources": "Quellen öffnen"
+ },
+ "time": {
+ "just_now": "gerade eben",
+ "minutes": "vor {0} Min.",
+ "hours": "vor {0} Std.",
+ "days": "vor {0} Tg."
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index beb77a056e..2c05609ecc 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2731,7 +2731,8 @@
"loading": "Loading UltraWiki status…",
"status_unavailable": "UltraWiki status is unavailable — is the backend running?",
"embedding_dead": "The embedding slot is not ready ({0}). Keyword and time-based answers still work; semantic search is paused until the slot is fixed.",
- "open_settings": "Open settings"
+ "open_settings": "Open settings",
+ "tab_contents": "Contents"
},
"progress": {
"title": "Import pipeline",
@@ -2787,7 +2788,25 @@
"connector_local_folder": "Local folder",
"connector_conversations": "Conversations with {name}",
"connector_normal_wiki": "Built-in wiki",
- "connector_plugin_bridge": "Connected integration (plugins / MCP)"
+ "connector_plugin_bridge": "Connected integration (plugins / MCP)",
+ "approve_import": "Approve & import everything",
+ "import_started": "Import started - everything this source holds is being copied in.",
+ "importing": "Importing",
+ "import_items": "{0} items imported so far",
+ "cancel_import": "Cancel import",
+ "copy_reassurance": "Everything is COPIED into your private knowledge store. Nothing is changed, moved, or deleted at the source.",
+ "fully_imported": "Fully imported: {0} items",
+ "nothing_imported_yet": "Nothing imported yet",
+ "last_sync_relative": "last sync {0}",
+ "error_label": "Sync failed",
+ "notice_label": "Heads-up",
+ "bridge_via": "via plugins / MCP bridge",
+ "integration": "Integration: {0}",
+ "phase_queued": "Waiting to start",
+ "phase_reading": "Reading the source",
+ "phase_importing": "Importing",
+ "phase_reconciling": "Checking for removed items",
+ "phase_finished": "Finishing up"
},
"ask": {
"placeholder": "Ask your knowledge…",
@@ -2918,6 +2937,31 @@
"link": "Connect this project",
"already_linked": "A Supabase connection is already saved.",
"save_anyway": "Save anyway"
+ },
+ "contents": {
+ "title": "Stored contents",
+ "total": "{0} items stored",
+ "filter_source": "Source",
+ "filter_state": "Stage",
+ "all_sources": "All sources",
+ "all_states": "All stages",
+ "col_title": "Item",
+ "col_source": "Source",
+ "col_state": "Stage",
+ "col_loaded": "Loaded",
+ "loaded_ago": "{0}",
+ "showing": "Showing {0} of {1}",
+ "load_more": "Load more",
+ "loading": "Loading contents…",
+ "load_failed": "Could not load the contents: {0}",
+ "empty": "Nothing is stored yet. Approve a source and it imports everything it holds.",
+ "open_sources": "Open Sources"
+ },
+ "time": {
+ "just_now": "just now",
+ "minutes": "{0} min ago",
+ "hours": "{0} h ago",
+ "days": "{0} d ago"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 912b7ad6f2..5e4fc688fc 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2730,7 +2730,8 @@
"loading": "Cargando el estado de UltraWiki…",
"status_unavailable": "El estado de UltraWiki no está disponible — ¿está funcionando el backend?",
"embedding_dead": "La ranura de embeddings no está lista ({0}). Las respuestas por palabras clave y por fecha siguen funcionando; la búsqueda semántica queda en pausa hasta arreglar la ranura.",
- "open_settings": "Abrir ajustes"
+ "open_settings": "Abrir ajustes",
+ "tab_contents": "Contenido"
},
"progress": {
"title": "Canal de importación",
@@ -2786,7 +2787,25 @@
"connector_local_folder": "Carpeta local",
"connector_conversations": "Conversaciones con {name}",
"connector_normal_wiki": "Wiki integrado",
- "connector_plugin_bridge": "Integración conectada (plugins / MCP)"
+ "connector_plugin_bridge": "Integración conectada (plugins / MCP)",
+ "approve_import": "Aprobar e importar todo",
+ "import_started": "Importación iniciada: se está copiando todo lo que contiene esta fuente.",
+ "importing": "Importando",
+ "import_items": "{0} elementos importados hasta ahora",
+ "cancel_import": "Cancelar la importación",
+ "copy_reassurance": "Todo se COPIA en tu almacén de conocimiento privado. En la fuente no se cambia, mueve ni elimina nada.",
+ "fully_imported": "Importado por completo: {0} elementos",
+ "nothing_imported_yet": "Todavía no se ha importado nada",
+ "last_sync_relative": "última sincronización {0}",
+ "error_label": "La sincronización falló",
+ "notice_label": "Aviso",
+ "bridge_via": "a través de plugins / puente MCP",
+ "integration": "Integración: {0}",
+ "phase_queued": "Esperando para empezar",
+ "phase_reading": "Leyendo la fuente",
+ "phase_importing": "Importando",
+ "phase_reconciling": "Comprobando elementos eliminados",
+ "phase_finished": "Finalizando"
},
"ask": {
"placeholder": "Pregunta a tu conocimiento…",
@@ -2917,6 +2936,31 @@
"link": "Conectar este proyecto",
"already_linked": "Ya hay una conexión de Supabase guardada.",
"save_anyway": "Guardar de todos modos"
+ },
+ "contents": {
+ "title": "Contenido almacenado",
+ "total": "{0} elementos almacenados",
+ "filter_source": "Fuente",
+ "filter_state": "Etapa",
+ "all_sources": "Todas las fuentes",
+ "all_states": "Todas las etapas",
+ "col_title": "Elemento",
+ "col_source": "Fuente",
+ "col_state": "Etapa",
+ "col_loaded": "Cargado",
+ "loaded_ago": "{0}",
+ "showing": "Mostrando {0} de {1}",
+ "load_more": "Cargar más",
+ "loading": "Cargando el contenido…",
+ "load_failed": "No se pudo cargar el contenido: {0}",
+ "empty": "Todavía no hay nada almacenado. Aprueba una fuente y se importará todo lo que contenga.",
+ "open_sources": "Abrir Fuentes"
+ },
+ "time": {
+ "just_now": "justo ahora",
+ "minutes": "hace {0} min",
+ "hours": "hace {0} h",
+ "days": "hace {0} d"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index 79601d99fc..aaf6d73d3b 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -38,6 +38,17 @@ export const ULTRAWIKI_ACTIVE_JOB_STATUSES: readonly string[] = [
"running",
];
+// Mirrors jarvis/ultrawiki/service.py::SYNC_PHASES — WHAT a running job is
+// doing, where `status` only says whether it is doing anything at all.
+export const ULTRAWIKI_SYNC_PHASES = [
+ "queued",
+ "reading",
+ "importing",
+ "reconciling",
+ "finished",
+] as const;
+export type UltraWikiSyncPhase = (typeof ULTRAWIKI_SYNC_PHASES)[number];
+
// Mirrors jarvis/ultrawiki/connectors/__init__.py::builtin_connectors().
export const ULTRAWIKI_CONNECTOR_IDS = [
"obsidian-vault",
@@ -57,17 +68,40 @@ export interface UltraWikiCounts {
total: number;
}
+/**
+ * What the last FINISHED sync of a source did — persisted in `uw_sync_state`,
+ * so it survives a restart (the job registry does not). `null` means no sync
+ * has ever finished, which is NOT the same as one that found nothing.
+ */
+export interface UltraWikiLastOutcome {
+ finished_at: string;
+ status: UltraWikiJobStatus | string;
+ mode: string;
+ new: number;
+ changed: number;
+ unchanged: number;
+ tombstoned: number;
+}
+
export interface UltraWikiSource {
id: string;
connector: string;
label: string;
+ /** The integration behind a plugin-bridge source ("plugin:github"). */
+ integration_id?: string;
consent: UltraWikiConsent | string;
enabled: boolean;
areas: string[];
counts: Partial<UltraWikiCounts> | null;
sync_state: Record<string, unknown> | null;
+ /** The run currently importing from this source, if any. */
+ active_job?: UltraWikiJob | null;
+ last_outcome?: UltraWikiLastOutcome | null;
last_sync_at: string | null;
+ /** The sync FAILED — red. */
last_error: string | null;
+ /** The sync worked but had nothing to import — amber, not an error. */
+ last_notice?: string | null;
}
export interface UltraWikiJob {
@@ -75,9 +109,13 @@ export interface UltraWikiJob {
source_id: string;
mode: string;
status: UltraWikiJobStatus | string;
+ /** One of ULTRAWIKI_SYNC_PHASES. */
+ phase?: UltraWikiSyncPhase | string;
started_at: number;
ended_at: number | null;
chunks: number;
+ /** Items pulled so far (new + changed + unchanged); tombstones excluded. */
+ items?: number;
new: number;
changed: number;
unchanged: number;
@@ -85,6 +123,29 @@ export interface UltraWikiJob {
error: string;
}
+/** One row of `GET /api/ultrawiki/items` — the stored-contents inventory. */
+export interface UltraWikiItem {
+ id: number;
+ source_id: string;
+ /** The title, or the external id when the connector supplied none. */
+ title: string;
+ state: UltraWikiItemState | string;
+ permalink: string;
+ /** When the item was created AT THE SOURCE. */
+ timestamp_utc: string;
+ /** When UltraWiki stored it (drives the newest-first order). */
+ ingested_at: string;
+ updated_at: string;
+}
+
+export interface UltraWikiItemsPage {
+ items: UltraWikiItem[];
+ /** The UNPAGED total for the active filters. */
+ total: number;
+ limit: number;
+ offset: number;
+}
+
/** One embedding/rerank option row from `GET /api/ultrawiki/providers`. */
export interface UltraWikiProviderOption {
name: string;
@@ -594,11 +655,49 @@ export function createUltraWikiSource(body: {
return postJson<UltraWikiSource>("/api/ultrawiki/sources", body);
}
+/**
+ * Answer of `POST /sources/{id}/approve`. Approving IS the import, so the
+ * answer carries the job that is now pulling everything; `job_id` is null when
+ * none could be started and `detail` says why in plain English. A refused
+ * import never costs the user their approval.
+ */
+export interface UltraWikiApproveResponse {
+ source: UltraWikiSource;
+ job_id: string | null;
+ auto_sync: boolean;
+ detail: string;
+}
+
export function approveUltraWikiSource(
sourceId: string,
-): Promise<UltraWikiSource> {
- return postJson<UltraWikiSource>(
- `/api/ultrawiki/sources/${encodeURIComponent(sourceId)}/approve`,
+ options: { autoSync?: boolean } = {},
+): Promise<UltraWikiApproveResponse> {
+ const query =
+ options.autoSync === false ? "?auto_sync=false" : "";
+ return postJson<UltraWikiApproveResponse>(
+ `/api/ultrawiki/sources/${encodeURIComponent(sourceId)}/approve${query}`,
+ );
+}
+
+/**
+ * One page of the stored inventory. The counts say HOW MANY items exist per
+ * stage; this says WHICH ones — the question "what is even in this database?".
+ */
+export function fetchUltraWikiItems(
+ options: {
+ sourceId?: string;
+ state?: string;
+ limit?: number;
+ offset?: number;
+ } = {},
+): Promise<UltraWikiItemsPage> {
+ const params = new URLSearchParams();
+ if (options.sourceId) params.set("source_id", options.sourceId);
+ if (options.state) params.set("state", options.state);
+ params.set("limit", String(options.limit ?? 50));
+ params.set("offset", String(options.offset ?? 0));
+ return request<UltraWikiItemsPage>(
+ `/api/ultrawiki/items?${params.toString()}`,
);
}
diff --git a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
index 4edbf75ceb..4cfd2b9a4c 100644
--- a/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
+++ b/jarvis/ui/web/frontend/src/views/ultrawiki/UltraWikiPanel.tsx
@@ -7,12 +7,18 @@
* every 4 s while a sync job is active (the wiki health polling idiom).
*
* Layout: honest degradation banner → staged import-progress strip → the
- * three tabs Ask | Sources | Settings. A dead required slot banners the
- * problem and links to the settings tab — the mode is never flipped silently
- * (design doc 04, mode-switch rules).
+ * four tabs Ask | Sources | Contents | Settings. A dead required slot banners
+ * the problem and links to the settings tab — the mode is never flipped
+ * silently (design doc 04, mode-switch rules).
*/
import { useState } from "react";
-import { AlertTriangle, MessageCircleQuestion, Plug, Settings2 } from "lucide-react";
+import {
+ AlertTriangle,
+ Database,
+ MessageCircleQuestion,
+ Plug,
+ Settings2,
+} from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { cn } from "@/lib/utils";
@@ -23,10 +29,11 @@ import {
} from "@/lib/ultrawikiApi";
import { AskPanel } from "@/components/ultrawiki/AskPanel";
import { SourcesPanel } from "@/components/ultrawiki/SourcesPanel";
+import { ContentsPanel } from "@/components/ultrawiki/ContentsPanel";
import { SlotsPanel } from "@/components/ultrawiki/SlotsPanel";
import { ImportProgress } from "@/components/ultrawiki/ImportProgress";
-type UltraTab = "ask" | "sources" | "settings";
+type UltraTab = "ask" | "sources" | "contents" | "settings";
export function UltraWikiPanel(): JSX.Element {
const t = useT();
@@ -36,9 +43,11 @@ export function UltraWikiPanel(): JSX.Element {
queryKey: ["ultrawiki", "status"],
queryFn: fetchUltraWikiStatus,
staleTime: 2_000,
- // Poll every few seconds while a sync job runs, calmly otherwise.
+ // While an import runs its item counter is what the source cards show
+ // ticking, so the poll tightens to a couple of seconds; at rest it stays
+ // calm (the status probe walks credentials in a worker thread).
refetchInterval: (query) =>
- hasActiveUltraWikiJobs(query.state.data?.jobs) ? 4_000 : 30_000,
+ hasActiveUltraWikiJobs(query.state.data?.jobs) ? 2_000 : 30_000,
});
const status = statusQuery.data ?? null;
@@ -131,6 +140,13 @@ export function UltraWikiPanel(): JSX.Element {
label={t("ultrawiki.panel.tab_sources")}
testId="ultrawiki-tab-sources"
/>
+ <UltraTabButton
+ active={tab === "contents"}
+ onClick={() => setTab("contents")}
+ icon={<Database className="h-3.5 w-3.5" aria-hidden />}
+ label={t("ultrawiki.panel.tab_contents")}
+ testId="ultrawiki-tab-contents"
+ />
<UltraTabButton
active={tab === "settings"}
onClick={() => setTab("settings")}
@@ -152,6 +168,12 @@ export function UltraWikiPanel(): JSX.Element {
{tab === "sources" && (
<SourcesPanel sources={status.sources} onChanged={refetch} />
)}
+ {tab === "contents" && (
+ <ContentsPanel
+ status={status}
+ onOpenSources={() => setTab("sources")}
+ />
+ )}
{tab === "settings" && (
<SlotsPanel status={status} onChanged={refetch} />
)}
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 1c9150dbc5..32d6e35e5f 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -1211,14 +1211,30 @@ async def create_source(body: CreateSourceBody, request: Request) -> dict[str, A
@router.post(
"/sources/{source_id}/approve",
- summary="Approve an UltraWiki source",
+ summary="Approve an UltraWiki source and import everything it holds",
openapi_extra={"x-jarvis-dangerous": True},
)
-async def approve_source(source_id: str, request: Request) -> dict[str, Any]:
- """Grant consent for one source — THE gate before any byte is pulled."""
+async def approve_source(
+ source_id: str,
+ request: Request,
+ auto_sync: bool = Query(
+ default=True,
+ description=(
+ "Start the full import immediately (the default). Pass false to "
+ "grant consent only and sync later."
+ ),
+ ),
+) -> dict[str, Any]:
+ """Grant consent for one source — THE gate before any byte is pulled.
+
+ Approval is what the consent contract asks for, so it also STARTS the full
+ import: the answer carries the ``job_id`` of the run that is now pulling
+ everything the source holds (``null`` when none could be started, with
+ ``detail`` saying why). A refused import never fails the approval.
+ """
service = _service(request)
try:
- return await service.approve_source(source_id)
+ return await service.approve_source(source_id, auto_sync=bool(auto_sync))
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
@@ -1399,6 +1415,87 @@ async def cancel_job(job_id: str, request: Request) -> dict[str, Any]:
return {"job_id": job_id, "cancel_requested": True}
+# ---------------------------------------------------------------------------
+# Stored contents — the inventory of what is actually in the database
+# ---------------------------------------------------------------------------
+
+
+class UltraWikiItemRow(BaseModel):
+ """One stored item as the inventory view lists it."""
+
+ id: int
+ source_id: str
+ #: The item's title, or its external id when the connector supplied none —
+ #: never an empty line the user cannot identify.
+ title: str
+ state: str
+ permalink: str
+ #: When the item was created AT THE SOURCE.
+ timestamp_utc: str
+ #: When UltraWiki first stored it (drives the newest-first order).
+ ingested_at: str
+ updated_at: str
+
+
+class UltraWikiItemsPage(BaseModel):
+ """One page of the inventory plus the unpaged total."""
+
+ items: list[UltraWikiItemRow]
+ total: int
+ limit: int
+ offset: int
+
+
[email protected]("/items", summary="List the items stored in the UltraWiki database")
+async def list_items(
+ request: Request,
+ source_id: str = Query(default="", description="Only items of this source"),
+ state: str = Query(
+ default="", description="Only items in this pipeline state"
+ ),
+ limit: int = Query(default=50, ge=1, le=200),
+ offset: int = Query(default=0, ge=0),
+ include_deleted: bool = Query(
+ default=False,
+ description="Also list items that were tombstoned after a full refresh",
+ ),
+) -> UltraWikiItemsPage:
+ """Newest-first inventory of what UltraWiki actually holds, with filters.
+
+ The counts elsewhere say HOW MANY items exist per stage; this says WHICH
+ ones — the question a user asking "what is even in this database?" is
+ actually asking. Tombstoned rows stay out unless asked for: they no longer
+ take part in answers.
+ """
+ service = _service(request)
+ store = await _store_of(service)
+ wanted_state = state.strip()
+ if wanted_state:
+ from jarvis.ultrawiki.types import ItemState # noqa: PLC0415 — lazy (AP-26)
+
+ if wanted_state not in {member.value for member in ItemState}:
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"unknown state {wanted_state!r} (one of: "
+ f"{', '.join(member.value for member in ItemState)})"
+ ),
+ )
+ rows, total = await store.list_items(
+ source_id=source_id.strip() or None,
+ state=wanted_state or None,
+ limit=limit,
+ offset=offset,
+ include_deleted=bool(include_deleted),
+ )
+ return UltraWikiItemsPage(
+ items=[UltraWikiItemRow(**row) for row in rows],
+ total=total,
+ limit=limit,
+ offset=offset,
+ )
+
+
# ---------------------------------------------------------------------------
# Areas
# ---------------------------------------------------------------------------
diff --git a/jarvis/ultrawiki/schema.sql b/jarvis/ultrawiki/schema.sql
index ebe59c0f54..ae4ee887be 100644
--- a/jarvis/ultrawiki/schema.sql
+++ b/jarvis/ultrawiki/schema.sql
@@ -31,6 +31,11 @@ CREATE TABLE IF NOT EXISTS uw_areas (
created_at TEXT NOT NULL
);
+-- last_error vs last_notice: an ERROR means the sync failed and the source is
+-- broken until the cause is fixed; a NOTICE means the sync ran fine but had
+-- nothing to import (today: a plugin-bridge integration whose pull adapter is
+-- not built yet). Keeping them apart is what lets the UI colour one red and
+-- the other amber instead of making a healthy source look broken.
CREATE TABLE IF NOT EXISTS uw_sources (
id TEXT PRIMARY KEY,
connector TEXT NOT NULL,
@@ -42,16 +47,28 @@ CREATE TABLE IF NOT EXISTS uw_sources (
enabled INTEGER NOT NULL DEFAULT 1,
created_at TEXT NOT NULL,
last_sync_at TEXT,
- last_error TEXT
+ last_error TEXT,
+ last_notice TEXT
);
+-- The last_* outcome block survives restarts, so a card can say "fully
+-- imported: N items, last sync <when>" instead of the ambiguous "Approved /
+-- Never synced" pair. The live job registry is in-memory and empty after a
+-- restart; this is the durable half of the same story.
CREATE TABLE IF NOT EXISTS uw_sync_state (
source_id TEXT PRIMARY KEY
REFERENCES uw_sources(id) ON DELETE CASCADE,
cursor TEXT,
backfill_checkpoint TEXT,
backfill_complete_at TEXT,
- last_success_at TEXT
+ last_success_at TEXT,
+ last_outcome_at TEXT,
+ last_outcome_status TEXT,
+ last_outcome_mode TEXT,
+ last_new INTEGER NOT NULL DEFAULT 0,
+ last_changed INTEGER NOT NULL DEFAULT 0,
+ last_unchanged INTEGER NOT NULL DEFAULT 0,
+ last_tombstoned INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS uw_items (
diff --git a/jarvis/ultrawiki/service.py b/jarvis/ultrawiki/service.py
index 769ac8f383..3f4b0978ec 100644
--- a/jarvis/ultrawiki/service.py
+++ b/jarvis/ultrawiki/service.py
@@ -51,9 +51,11 @@ log = logging.getLogger(__name__)
__all__ = [
"SYNC_CHUNK_SIZE",
+ "BRIDGE_ADAPTER_PENDING_NOTICE",
"JOB_ACTIVE_STATUSES",
"JOB_TERMINAL_STATUSES",
"PIPELINE_STATES",
+ "SYNC_PHASES",
"SyncAlreadyRunningError",
"SyncJob",
"UltraWikiService",
@@ -70,9 +72,33 @@ PIPELINE_STATES: tuple[str, ...] = (
"paused",
)
+#: The phases one sync job walks through, in order. Same five-layer drift
+#: discipline as :data:`PIPELINE_STATES`: the TypeScript union in
+#: ``src/lib/ultrawikiApi.ts`` and the progress labels derive from THIS list.
+SYNC_PHASES: tuple[str, ...] = (
+ "queued",
+ "reading",
+ "importing",
+ "reconciling",
+ "finished",
+)
+
#: Items per ``upsert_items`` transaction / sync-state checkpoint.
SYNC_CHUNK_SIZE = 200
+#: What a plugin-bridge source is told when its integration has no pull
+#: adapter yet: the sync really ran, it really imported nothing, and that is
+#: not the user's fault or a broken credential.
+BRIDGE_ADAPTER_PENDING_NOTICE = (
+ "This integration is connected, but its pull adapter is not built yet - "
+ "nothing was imported. The source stays approved and will import "
+ "automatically once the adapter ships."
+)
+
+#: The connector id of the generic integration bridge (its "no adapter yet"
+#: state is the only one that produces the notice above).
+_BRIDGE_CONNECTOR_ID = "plugin-bridge"
+
#: The default local sources :meth:`UltraWikiService.activate` registers —
#: source id == connector id for these singletons.
_DEFAULT_SOURCES: tuple[tuple[str, str], ...] = (
@@ -95,6 +121,31 @@ def _counts_dict(counts: PipelineCounts) -> dict[str, int]:
return {**dataclasses.asdict(counts), "total": counts.total}
+def _last_outcome_of(sync_state: Any) -> dict[str, Any] | None:
+ """What the last FINISHED sync of a source did, or ``None``.
+
+ ``None`` means "no sync has ever finished for this source" — deliberately
+ not a zero-filled block, which would be indistinguishable from an import
+ that ran and found nothing. The live job registry is in-memory and empty
+ after a restart, so this persisted block is what keeps a card from falling
+ back to "Approved / Never synced" for a fully imported source.
+ """
+ if not isinstance(sync_state, dict):
+ return None
+ finished_at = sync_state.get("last_outcome_at")
+ if not finished_at:
+ return None
+ return {
+ "finished_at": str(finished_at),
+ "status": str(sync_state.get("last_outcome_status") or ""),
+ "mode": str(sync_state.get("last_outcome_mode") or ""),
+ "new": int(sync_state.get("last_new") or 0),
+ "changed": int(sync_state.get("last_changed") or 0),
+ "unchanged": int(sync_state.get("last_unchanged") or 0),
+ "tombstoned": int(sync_state.get("last_tombstoned") or 0),
+ }
+
+
# ---------------------------------------------------------------------------
# Bounded in-module sync-job registry (mirror of cu_run_registry.py)
# ---------------------------------------------------------------------------
@@ -132,6 +183,9 @@ class SyncJob:
source_id: str
mode: str # "backfill" | "incremental"
status: str = "queued"
+ #: One of :data:`SYNC_PHASES` — WHAT the job is doing, where ``status``
+ #: says whether it is doing anything at all.
+ phase: str = "queued"
started_at: float = field(default_factory=time.time)
ended_at: float | None = None
chunks: int = 0
@@ -143,6 +197,16 @@ class SyncJob:
#: The asyncio.Task while the job is active; cleared when it ends.
task: Any = None
+ @property
+ def items(self) -> int:
+ """Items pulled from the source so far.
+
+ Tombstones are excluded: nothing was PULLED for a row that only
+ disappeared at the origin, so counting them would inflate the live
+ "imported N so far" number the card shows.
+ """
+ return self.new + self.changed + self.unchanged
+
def snapshot(self) -> dict[str, Any]:
"""JSON-safe public view (never exposes the task)."""
return {
@@ -150,9 +214,11 @@ class SyncJob:
"source_id": self.source_id,
"mode": self.mode,
"status": self.status,
+ "phase": self.phase,
"started_at": self.started_at,
"ended_at": self.ended_at,
"chunks": self.chunks,
+ "items": self.items,
"new": self.new,
"changed": self.changed,
"unchanged": self.unchanged,
@@ -566,11 +632,27 @@ class UltraWikiService:
@staticmethod
def _source_summary(row: dict[str, Any]) -> dict[str, Any]:
+ """One source's card payload — including whether anything is happening.
+
+ The three fields that make the difference between "Approved / Never
+ synced" and a card a user can read: ``active_job`` (a run in flight,
+ with its phase and the items pulled so far), ``last_outcome`` (what the
+ last finished run did, restart-proof), and ``last_notice`` (it ran, it
+ worked, it had nothing to import — distinct from ``last_error``).
+ """
counts = row.get("counts")
+ source_id = str(row.get("id") or "")
+ active = _active_job_for(source_id)
+ config = row.get("config") or {}
return {
"id": row.get("id"),
"connector": row.get("connector"),
"label": row.get("label"),
+ # The integration behind a plugin-bridge source, so the card can
+ # name it instead of showing an opaque generated source id.
+ "integration_id": str(config.get("integration_id") or "")
+ if isinstance(config, dict)
+ else "",
"consent": row.get("consent"),
"enabled": row.get("enabled"),
"areas": row.get("areas", []),
@@ -578,8 +660,11 @@ class UltraWikiService:
if isinstance(counts, PipelineCounts)
else counts,
"sync_state": row.get("sync_state"),
+ "active_job": active.snapshot() if active is not None else None,
+ "last_outcome": _last_outcome_of(row.get("sync_state")),
"last_sync_at": row.get("last_sync_at"),
"last_error": row.get("last_error"),
+ "last_notice": row.get("last_notice"),
}
def _embedding_slot_status(self) -> dict[str, Any]:
@@ -800,7 +885,7 @@ class UltraWikiService:
await store.upsert_source(
source_id,
connector=connector_id,
- label=label,
+ label=self._resolve_label(connector_id, label, config),
config=dict(config or {}),
areas=list(area_ids or []),
)
@@ -808,8 +893,118 @@ class UltraWikiService:
assert source is not None
return source
- async def approve_source(self, source_id: str) -> dict[str, Any]:
- return await self._set_consent(source_id, ConsentState.APPROVED)
+ @staticmethod
+ def _resolve_label(
+ connector_id: str, label: str, config: dict[str, Any] | None
+ ) -> str:
+ """The name the card carries — the INTEGRATION's, for bridge sources.
+
+ A plugin-bridge source registered under the bridge's own generic name
+ produced a list of identical "Connected Integrations" cards nobody
+ could tell apart. When the caller supplied no real name, the label of
+ the chosen candidate ("GitHub", "Notion", ...) is used instead. The
+ lookup is best-effort: a broken registry keeps the caller's label.
+ """
+ chosen = str(label or "").strip()
+ if connector_id != _BRIDGE_CONNECTOR_ID:
+ return chosen
+ integration_id = str((config or {}).get("integration_id") or "").strip()
+ if not integration_id:
+ return chosen
+ generic = {
+ "",
+ _BRIDGE_CONNECTOR_ID,
+ integration_id.lower(),
+ "connected integration",
+ "connected integrations",
+ }
+ if chosen.lower() not in generic:
+ return chosen
+ try:
+ from jarvis.ultrawiki.connectors import ( # noqa: PLC0415 — lazy (AP-26)
+ plugin_bridge,
+ )
+
+ candidate = next(
+ (
+ row
+ for row in plugin_bridge.list_candidates()
+ if row.get("id") == integration_id
+ ),
+ None,
+ )
+ except Exception: # noqa: BLE001 — naming is decoration, never a failure
+ log.debug("bridge label lookup failed", exc_info=True)
+ return chosen
+ if candidate is None:
+ return chosen
+ return str(candidate.get("label") or "").strip() or chosen
+
+ async def approve_source(
+ self, source_id: str, *, auto_sync: bool = True
+ ) -> dict[str, Any]:
+ """Grant consent and, by default, import everything the source holds.
+
+ Approving used to only flip a flag: the card said "Approved", stayed on
+ "Never synced", and the user had no way to tell that a second, separate
+ click was still owed. Consent is the gate, so the moment it is granted
+ the natural next step is the FULL import — started here as a normal
+ sync job the user can watch and cancel. ``auto_sync=False`` keeps the
+ old consent-only behaviour for callers that drive their own sync.
+
+ Returns ``{"source", "job_id", "auto_sync", "detail"}``; ``job_id`` is
+ ``None`` whenever no import could be started, and ``detail`` says why
+ in plain English. A refused import NEVER fails the approval — consent
+ was granted and must stay granted.
+ """
+ source = await self._set_consent(source_id, ConsentState.APPROVED)
+ job_id: str | None = None
+ detail = ""
+ if auto_sync:
+ job_id, detail = await self._start_import_after_approval(source)
+ return {
+ "source": source,
+ "job_id": job_id,
+ "auto_sync": bool(auto_sync),
+ "detail": detail,
+ }
+
+ async def _start_import_after_approval(
+ self, source: dict[str, Any]
+ ) -> tuple[str | None, str]:
+ """``(job_id, honest English detail)`` — never raises."""
+ source_id = str(source.get("id") or "")
+ active = _active_job_for(source_id)
+ if active is not None:
+ return active.job_id, (
+ "An import for this source is already running - it keeps going."
+ )
+ try:
+ connector = self._build_connector(str(source.get("connector") or ""))
+ except ValueError as exc:
+ return None, f"Consent was granted, but no import could start: {exc}"
+ if not bool(
+ getattr(getattr(connector, "capabilities", None), "backfill", False)
+ ):
+ return None, (
+ "Consent was granted. This source type cannot read its whole "
+ "history, so nothing was imported automatically."
+ )
+ try:
+ job_id = await self.start_sync(source_id, full=True)
+ except SyncAlreadyRunningError as exc:
+ return exc.job_id, (
+ "An import for this source is already running - it keeps going."
+ )
+ except ValueError as exc:
+ # Mode off, source disabled, connector missing — all honest
+ # refusals the user can fix; the consent itself stands.
+ return None, f"Consent was granted, but no import could start: {exc}"
+ return job_id, (
+ "Importing everything this source holds into your private "
+ "knowledge store. Everything is COPIED - nothing is changed or "
+ "removed at the source."
+ )
async def revoke_source(self, source_id: str) -> dict[str, Any]:
return await self._set_consent(source_id, ConsentState.REVOKED)
@@ -936,6 +1131,7 @@ class UltraWikiService:
source_id = job.source_id
ctx = self._connector_context(source)
job.status = "running"
+ job.phase = "reading"
checkpoint = sync_state.get("backfill_checkpoint")
# Delete-reconcile needs the COMPLETE yielded-id set, which only a
# backfill running from the very beginning can provide.
@@ -969,6 +1165,7 @@ class UltraWikiService:
getattr(getattr(connector, "capabilities", None), "deletes", False)
)
if full_backfill and deletes_capable:
+ job.phase = "reconciling"
job.tombstoned += await store.reconcile_deletes(
source_id, yielded_ids
)
@@ -986,10 +1183,17 @@ class UltraWikiService:
else:
await store.set_sync_state(source_id, last_success_at=now)
await store.set_source_status(
- source_id, last_sync_at=now, last_error=None
+ source_id,
+ last_sync_at=now,
+ last_error=None,
+ last_notice=self._import_notice_for(source, job),
)
+ await self._record_outcome(store, job, "done", now)
job.status = "done"
except asyncio.CancelledError:
+ # No outcome is recorded here: a cancelled run has no outcome to
+ # report, and shutdown cancels every job right before the store
+ # closes — writing on this path would race that close.
job.status = "cancelled"
raise
except Exception as exc: # noqa: BLE001 — the job records, never crashes callers
@@ -1000,12 +1204,62 @@ class UltraWikiService:
job.error = f"{type(exc).__name__}: {exc}"
try:
await store.set_source_status(source_id, last_error=job.error)
+ await self._record_outcome(store, job, "failed", _iso_now())
except Exception: # noqa: BLE001 — best-effort bookkeeping
log.debug("sync error bookkeeping failed", exc_info=True)
finally:
job.ended_at = time.time()
+ job.phase = "finished"
job.task = None
+ @staticmethod
+ async def _record_outcome(
+ store: Any, job: SyncJob, status: str, finished_at: str
+ ) -> None:
+ """Persist the finished job's totals; a failure here never fails the job."""
+ try:
+ await store.record_sync_outcome(
+ job.source_id,
+ status=status,
+ mode=job.mode,
+ finished_at=finished_at,
+ new=job.new,
+ changed=job.changed,
+ unchanged=job.unchanged,
+ tombstoned=job.tombstoned,
+ )
+ except Exception: # noqa: BLE001 — bookkeeping, never the work itself
+ log.debug("sync outcome bookkeeping failed", exc_info=True)
+
+ @staticmethod
+ def _import_notice_for(source: dict[str, Any], job: SyncJob) -> str | None:
+ """The amber "it worked, there was nothing to take" line, or ``None``.
+
+ A plugin-bridge source whose integration has no pull adapter yet syncs
+ successfully and imports zero items. Until now that left only a log
+ line, so the card showed a green "Approved" source that never grew and
+ gave the user nothing to act on. ``None`` CLEARS any previous notice —
+ the moment an adapter ships and items arrive, the line disappears.
+ """
+ if job.items > 0:
+ return None
+ if str(source.get("connector") or "") != _BRIDGE_CONNECTOR_ID:
+ return None
+ integration_id = str((source.get("config") or {}).get("integration_id") or "")
+ if not integration_id:
+ return None
+ try:
+ from jarvis.ultrawiki.connectors import ( # noqa: PLC0415 — lazy (AP-26)
+ plugin_bridge,
+ )
+
+ if plugin_bridge.has_pull_adapter(integration_id):
+ return None
+ except Exception: # noqa: BLE001 — an unreadable registry states nothing
+ log.debug("pull-adapter probe failed", exc_info=True)
+ return None
+ return BRIDGE_ADAPTER_PENDING_NOTICE
+
async def _flush_chunk(
self,
job: SyncJob,
@@ -1015,6 +1269,7 @@ class UltraWikiService:
) -> int | None:
store = self._require_store()
counts = await store.upsert_items(source_id, items)
+ job.phase = "importing"
job.chunks += 1
job.new += counts.new
job.changed += counts.changed
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index 758061445c..5c8bbb2fe0 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -268,6 +268,38 @@ def _placeholders(count: int) -> str:
return ",".join("?" * count)
+#: Projection of :meth:`UltraStore.list_items` — the inventory view's row.
+#: An item whose connector supplied no title is listed under its external id
+#: rather than as a blank line the user cannot identify.
+_ITEM_LIST_COLUMNS = (
+ "id, source_id, state, permalink, timestamp_utc,"
+ " COALESCE(NULLIF(title, ''), external_id) AS title,"
+ " created_at AS ingested_at, updated_at"
+)
+
+
+def _item_filter_sql(
+ *,
+ source_id: str | None,
+ state: str | None,
+ include_deleted: bool,
+ mark: str = "?",
+) -> tuple[str, list[Any]]:
+ """``(WHERE clause, params)`` for the item inventory, shared by both
+ backends (``mark`` is the driver's placeholder style)."""
+ clauses: list[str] = []
+ params: list[Any] = []
+ if not include_deleted:
+ clauses.append("deleted_at IS NULL")
+ if source_id:
+ clauses.append(f"source_id = {mark}")
+ params.append(source_id)
+ if state:
+ clauses.append(f"state = {mark}")
+ params.append(state)
+ return (f" WHERE {' AND '.join(clauses)}" if clauses else ""), params
+
+
def _counts_from_pairs(pairs: Iterable[tuple[str, int]]) -> PipelineCounts:
by_state = {state.value: 0 for state in ItemState}
for state_value, count in pairs:
@@ -278,6 +310,34 @@ def _counts_from_pairs(pairs: Iterable[tuple[str, int]]) -> PipelineCounts:
_UNSET: Any = object()
+#: Columns added AFTER the first shipped schema. They are declared in
+#: ``schema.sql`` (and in :meth:`PostgresStore.ddl_statements`) so a fresh
+#: database gets them from the CREATE, and appended here for databases that
+#: already exist. SQLite has no ``ADD COLUMN IF NOT EXISTS``, so the existing
+#: columns are read from ``PRAGMA table_info`` first — the pattern of
+#: ``jarvis/missions/event_store.py``.
+_ADDITIVE_COLUMNS: tuple[tuple[str, str, str], ...] = (
+ ("uw_sources", "last_notice", "TEXT"),
+ ("uw_sync_state", "last_outcome_at", "TEXT"),
+ ("uw_sync_state", "last_outcome_status", "TEXT"),
+ ("uw_sync_state", "last_outcome_mode", "TEXT"),
+ ("uw_sync_state", "last_new", "INTEGER NOT NULL DEFAULT 0"),
+ ("uw_sync_state", "last_changed", "INTEGER NOT NULL DEFAULT 0"),
+ ("uw_sync_state", "last_unchanged", "INTEGER NOT NULL DEFAULT 0"),
+ ("uw_sync_state", "last_tombstoned", "INTEGER NOT NULL DEFAULT 0"),
+)
+
+#: The persisted per-source outcome of the last finished sync.
+_OUTCOME_COLUMNS: tuple[str, ...] = (
+ "last_outcome_at",
+ "last_outcome_status",
+ "last_outcome_mode",
+ "last_new",
+ "last_changed",
+ "last_unchanged",
+ "last_tombstoned",
+)
+
# ---------------------------------------------------------------------------
# SQLite reference backend
@@ -322,8 +382,27 @@ class UltraStore:
)
await run_migrations(conn, directory=_MIGRATIONS_DIR)
+ await self._apply_column_migrations(conn)
self._conn = conn
+ @staticmethod
+ async def _apply_column_migrations(conn: aiosqlite.Connection) -> None:
+ """Append the :data:`_ADDITIVE_COLUMNS` an older database still lacks."""
+ known: dict[str, set[str]] = {}
+ for table, column, declaration in _ADDITIVE_COLUMNS:
+ if table not in known:
+ cur = await conn.execute(f"PRAGMA table_info({table})") # noqa: S608 — table names are code-owned literals
+ rows = await cur.fetchall()
+ await cur.close()
+ known[table] = {str(row[1]) for row in rows}
+ if column in known[table]:
+ continue
+ await conn.execute(
+ f"ALTER TABLE {table} ADD COLUMN {column} {declaration}" # noqa: S608 — code-owned literals
+ )
+ known[table].add(column)
+ log.info("UltraStore migration applied — added %s.%s", table, column)
+
async def close(self) -> None:
async with self._lock:
if self._conn is not None:
@@ -434,6 +513,7 @@ class UltraStore:
"created_at": row["created_at"],
"last_sync_at": row["last_sync_at"],
"last_error": row["last_error"],
+ "last_notice": row["last_notice"],
}
async def get_source(self, source_id: str) -> dict[str, Any] | None:
@@ -490,8 +570,16 @@ class UltraStore:
*,
last_sync_at: str | None = _UNSET,
last_error: str | None = _UNSET,
+ last_notice: str | None = _UNSET,
) -> None:
- """Partial update of the per-source sync status columns."""
+ """Partial update of the per-source sync status columns.
+
+ ``last_error`` and ``last_notice`` are deliberately separate: an error
+ means the sync failed, a notice means it ran fine and had nothing to
+ import. Writing a notice into the error column would make a healthy
+ source look broken (and the next successful sync would silently erase
+ it along with the real errors).
+ """
sets: list[str] = []
params: list[Any] = []
if last_sync_at is not _UNSET:
@@ -500,6 +588,9 @@ class UltraStore:
if last_error is not _UNSET:
sets.append("last_error = ?")
params.append(last_error)
+ if last_notice is not _UNSET:
+ sets.append("last_notice = ?")
+ params.append(last_notice)
if not sets:
return
params.append(source_id)
@@ -709,6 +800,42 @@ class UltraStore:
)
return None if row is None else self._item_row_to_dict(row)
+ async def list_items(
+ self,
+ *,
+ source_id: str | None = None,
+ state: ItemState | str | None = None,
+ limit: int = 50,
+ offset: int = 0,
+ include_deleted: bool = False,
+ ) -> tuple[list[dict[str, Any]], int]:
+ """One page of the stored inventory + the unpaged total.
+
+ Newest-INGESTED first (``created_at``), not newest-authored: the
+ question this answers is "what did the last import actually put in
+ here", and a decade-old note imported a minute ago belongs at the top.
+ Tombstoned rows stay out unless ``include_deleted`` asks for them —
+ they are no longer part of what the store answers from.
+ """
+ coerced = _coerce_state(state).value if state else None
+ where, params = _item_filter_sql(
+ source_id=source_id, state=coerced, include_deleted=include_deleted
+ )
+ conn = await self._ensure_open()
+ total_row = await self._fetchone(
+ conn,
+ f"SELECT count(*) AS n FROM uw_items{where}", # noqa: S608 — placeholders only
+ params,
+ )
+ total = int(total_row["n"]) if total_row is not None else 0
+ rows = await self._fetchall(
+ conn,
+ f"SELECT {_ITEM_LIST_COLUMNS} FROM uw_items{where}" # noqa: S608 — code-owned projection + placeholders
+ " ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?",
+ [*params, max(0, int(limit)), max(0, int(offset))],
+ )
+ return [dict(row) for row in rows], total
+
async def claim_batch(
self,
target_state: ItemState | str,
@@ -1425,6 +1552,47 @@ class UltraStore:
[*updates.values(), source_id],
)
+ async def record_sync_outcome(
+ self,
+ source_id: str,
+ *,
+ status: str,
+ mode: str,
+ finished_at: str,
+ new: int = 0,
+ changed: int = 0,
+ unchanged: int = 0,
+ tombstoned: int = 0,
+ ) -> None:
+ """Persist what the last finished sync of *source_id* actually did.
+
+ The live job registry is in-memory and empty after a restart, so
+ without this the card falls back to "Approved / Never synced" for a
+ source that holds thousands of imported items. Written as one block —
+ a half-written outcome would be worse than none.
+ """
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT OR IGNORE INTO uw_sync_state (source_id) VALUES (?)",
+ (source_id,),
+ )
+ await conn.execute(
+ "UPDATE uw_sync_state SET last_outcome_at = ?,"
+ " last_outcome_status = ?, last_outcome_mode = ?, last_new = ?,"
+ " last_changed = ?, last_unchanged = ?, last_tombstoned = ?"
+ " WHERE source_id = ?",
+ (
+ finished_at,
+ status,
+ mode,
+ int(new),
+ int(changed),
+ int(unchanged),
+ int(tombstoned),
+ source_id,
+ ),
+ )
+
# -- areas ---------------------------------------------------------------
async def upsert_area(
@@ -1571,12 +1739,26 @@ class PostgresStore:
" consent TEXT NOT NULL DEFAULT 'pending'"
f" CHECK (consent IN ({consents})),"
" enabled BOOLEAN NOT NULL DEFAULT TRUE,"
- " created_at TEXT NOT NULL, last_sync_at TEXT, last_error TEXT)",
+ " created_at TEXT NOT NULL, last_sync_at TEXT, last_error TEXT,"
+ " last_notice TEXT)",
"CREATE TABLE IF NOT EXISTS uw_sync_state ("
" source_id TEXT PRIMARY KEY"
" REFERENCES uw_sources(id) ON DELETE CASCADE,"
" cursor TEXT, backfill_checkpoint TEXT,"
- " backfill_complete_at TEXT, last_success_at TEXT)",
+ " backfill_complete_at TEXT, last_success_at TEXT,"
+ " last_outcome_at TEXT, last_outcome_status TEXT,"
+ " last_outcome_mode TEXT,"
+ " last_new INTEGER NOT NULL DEFAULT 0,"
+ " last_changed INTEGER NOT NULL DEFAULT 0,"
+ " last_unchanged INTEGER NOT NULL DEFAULT 0,"
+ " last_tombstoned INTEGER NOT NULL DEFAULT 0)",
+ # The same additive columns for databases created before the
+ # visibility package. Postgres HAS `ADD COLUMN IF NOT EXISTS`, so
+ # the SQLite pragma dance is unnecessary here.
+ *(
+ f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} {declaration}"
+ for table, column, declaration in _ADDITIVE_COLUMNS
+ ),
"CREATE TABLE IF NOT EXISTS uw_items ("
" id BIGSERIAL PRIMARY KEY,"
" source_id TEXT NOT NULL REFERENCES uw_sources(id) ON DELETE CASCADE,"
@@ -1773,6 +1955,7 @@ class PostgresStore:
"created_at": row["created_at"],
"last_sync_at": row["last_sync_at"],
"last_error": row["last_error"],
+ "last_notice": row.get("last_notice"),
}
async def get_source(self, source_id: str) -> dict[str, Any] | None:
@@ -1828,6 +2011,7 @@ class PostgresStore:
*,
last_sync_at: str | None = _UNSET,
last_error: str | None = _UNSET,
+ last_notice: str | None = _UNSET,
) -> None:
conn = await self._ensure_open()
if last_sync_at is not _UNSET:
@@ -1840,6 +2024,11 @@ class PostgresStore:
"UPDATE uw_sources SET last_error = %s WHERE id = %s",
(last_error, source_id),
)
+ if last_notice is not _UNSET:
+ await conn.execute(
+ "UPDATE uw_sources SET last_notice = %s WHERE id = %s",
+ (last_notice, source_id),
+ )
async def delete_source(self, source_id: str, *, purge: bool) -> None:
if not purge:
@@ -2007,6 +2196,38 @@ class PostgresStore:
)
return None if row is None else self._item_row_to_dict(row)
+ async def list_items(
+ self,
+ *,
+ source_id: str | None = None,
+ state: ItemState | str | None = None,
+ limit: int = 50,
+ offset: int = 0,
+ include_deleted: bool = False,
+ ) -> tuple[list[dict[str, Any]], int]:
+ """Postgres twin of the SQLite inventory page (same ordering + total)."""
+ coerced = _coerce_state(state).value if state else None
+ where, params = _item_filter_sql(
+ source_id=source_id,
+ state=coerced,
+ include_deleted=include_deleted,
+ mark="%s",
+ )
+ conn = await self._ensure_open()
+ total_row = await self._fetchone(
+ conn,
+ f"SELECT count(*) AS n FROM uw_items{where}", # noqa: S608 — placeholders only
+ params,
+ )
+ total = int(total_row["n"]) if total_row is not None else 0
+ rows = await self._fetchall(
+ conn,
+ f"SELECT {_ITEM_LIST_COLUMNS} FROM uw_items{where}" # noqa: S608 — code-owned projection + placeholders
+ " ORDER BY created_at DESC, id DESC LIMIT %s OFFSET %s",
+ [*params, max(0, int(limit)), max(0, int(offset))],
+ )
+ return [dict(row) for row in rows], total
+
async def claim_batch(
self,
target_state: ItemState | str,
@@ -2591,6 +2812,42 @@ class PostgresStore:
(value, source_id),
)
+ async def record_sync_outcome(
+ self,
+ source_id: str,
+ *,
+ status: str,
+ mode: str,
+ finished_at: str,
+ new: int = 0,
+ changed: int = 0,
+ unchanged: int = 0,
+ tombstoned: int = 0,
+ ) -> None:
+ """Postgres twin of the SQLite outcome write (same one-block contract)."""
+ async with self._txn() as conn:
+ await conn.execute(
+ "INSERT INTO uw_sync_state (source_id) VALUES (%s)"
+ " ON CONFLICT (source_id) DO NOTHING",
+ (source_id,),
+ )
+ await conn.execute(
+ "UPDATE uw_sync_state SET last_outcome_at = %s,"
+ " last_outcome_status = %s, last_outcome_mode = %s, last_new = %s,"
+ " last_changed = %s, last_unchanged = %s, last_tombstoned = %s"
+ " WHERE source_id = %s",
+ (
+ finished_at,
+ status,
+ mode,
+ int(new),
+ int(changed),
+ int(unchanged),
+ int(tombstoned),
+ source_id,
+ ),
+ )
+
async def upsert_area(
self, area_id: str, name: str, *, is_default: bool = False
) -> None:
diff --git a/tests/unit/ultrawiki/test_service.py b/tests/unit/ultrawiki/test_service.py
index 811be470ea..30394ab95c 100644
--- a/tests/unit/ultrawiki/test_service.py
+++ b/tests/unit/ultrawiki/test_service.py
@@ -251,8 +251,9 @@ async def test_approved_sync_ingests_with_checkpoints_and_cursor(service, monkey
source = await service.add_source("fake-conn", "Fake Source")
source_id = source["id"]
- approved = await service.approve_source(source_id)
- assert approved["consent"] == "approved"
+ approved = await service.approve_source(source_id, auto_sync=False)
+ assert approved["source"]["consent"] == "approved"
+ assert approved["job_id"] is None # auto_sync=False imports nothing
job_id = await service.start_sync(source_id)
snap = await wait_for_job(service, job_id)
@@ -303,7 +304,7 @@ async def test_cancel_job_mid_stream_stops_the_sync(service, monkeypatch):
)
source = await service.add_source("blocking-conn", "Blocked Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
job_id = await service.start_sync(source["id"])
await asyncio.wait_for(reached.wait(), timeout=5.0)
@@ -336,7 +337,7 @@ async def test_shutdown_leaves_no_stray_tasks(service, monkeypatch):
assert pipeline_task is not None and not pipeline_task.done()
source = await service.add_source("blocking-conn", "Blocked Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
job_id = await service.start_sync(source["id"])
await asyncio.wait_for(reached.wait(), timeout=5.0)
sync_task = service._sync_tasks[job_id]
@@ -379,7 +380,7 @@ async def test_export_style_source_reingests_on_every_backfill(service, monkeypa
{"export-conn": lambda: ExportFileConnector(make_items(5), calls)},
)
source = await service.add_source("export-conn", "Export File")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
first = await wait_for_job(service, await service.start_sync(source["id"]))
assert (first["mode"], first["new"]) == ("backfill", 5)
@@ -402,7 +403,7 @@ async def test_full_refresh_resets_the_cursor_and_reconciles_deletes(
source = await service.add_source("fake-conn", "Fake Source")
source_id = source["id"]
- await service.approve_source(source_id)
+ await service.approve_source(source_id, auto_sync=False)
await wait_for_job(service, await service.start_sync(source_id))
store = service._require_store()
assert (await store.counts_for_source(source_id)).total == 3
@@ -441,7 +442,7 @@ async def test_second_sync_of_one_source_is_refused_with_the_active_job(
{"blocking-conn": lambda: BlockingConnector(make_items(3), gate, reached)},
)
source = await service.add_source("blocking-conn", "Blocked Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
job_id = await service.start_sync(source["id"])
await asyncio.wait_for(reached.wait(), timeout=5.0)
@@ -476,7 +477,7 @@ async def test_pipeline_state_is_idle_once_an_approved_source_is_drained(
):
patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector([], [])})
source = await service.add_source("fake-conn", "Empty Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
status = await service.status()
assert status["pipeline"]["state"] == "idle"
assert "processed" in status["pipeline"]
@@ -487,7 +488,7 @@ async def test_pipeline_state_is_paused_when_the_embedding_slot_blocks(
):
patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(2), [])})
source = await service.add_source("fake-conn", "Fake Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
await wait_for_job(service, await service.start_sync(source["id"]))
# Drive the keyword stage so the backlog sits at the embedding gate.
store = service._require_store()
@@ -510,7 +511,7 @@ async def test_pipeline_state_is_processing_with_a_claimable_backlog(
):
patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(4), [])})
source = await service.add_source("fake-conn", "Fake Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
await wait_for_job(service, await service.start_sync(source["id"]))
status = await service.status()
@@ -550,7 +551,7 @@ async def test_status_reports_the_credential_behind_a_ready_slot(service, monkey
async def test_requeue_failed_is_exposed_and_scoped(service, monkeypatch):
patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(2), [])})
source = await service.add_source("fake-conn", "Fake Source")
- await service.approve_source(source["id"])
+ await service.approve_source(source["id"], auto_sync=False)
await wait_for_job(service, await service.start_sync(source["id"]))
store = service._require_store()
for item in await store.claim_batch("keyword_indexed", limit=10):
@@ -597,3 +598,235 @@ async def test_postgres_degradation_never_leaks_the_password(tmp_path, monkeypat
assert status["backend"]["in_use"] == "sqlite"
finally:
await svc.shutdown()
+
+
+# ---------------------------------------------------------------------------
+# Approve = import everything
+# ---------------------------------------------------------------------------
+
+
+async def test_approve_starts_the_full_import_immediately(service, monkeypatch):
+ """Approving IS the import — the click that used to only flip a flag."""
+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(6), [])})
+ source = await service.add_source("fake-conn", "Fake Source")
+
+ approved = await service.approve_source(source["id"])
+
+ assert approved["source"]["consent"] == "approved"
+ assert approved["auto_sync"] is True
+ assert approved["job_id"]
+ assert "COPIED" in approved["detail"] # nothing is removed at the origin
+ snap = await wait_for_job(service, approved["job_id"])
+ assert (snap["status"], snap["new"]) == ("done", 6)
+ # A full refresh, so deletions are detectable from the very first import.
+ assert snap["mode"] == "backfill"
+ store = service._require_store()
+ assert (await store.counts_for_source(source["id"])).total == 6
+
+
+async def test_approve_without_auto_sync_only_grants_consent(service, monkeypatch):
+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(3), [])})
+ source = await service.add_source("fake-conn", "Fake Source")
+
+ approved = await service.approve_source(source["id"], auto_sync=False)
+
+ assert approved["source"]["consent"] == "approved"
+ assert approved["job_id"] is None
+ assert service.list_jobs() == []
+ store = service._require_store()
+ assert (await store.counts_for_source(source["id"])).total == 0
+
+
+async def test_approve_keeps_consent_when_no_import_can_start(service, monkeypatch):
+ """A refused import must never cost the user their approval."""
+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector([], [])})
+ source = await service.add_source("fake-conn", "Fake Source")
+ service._cfg.ultrawiki.enabled = False # start_sync refuses while off
+
+ approved = await service.approve_source(source["id"])
+
+ assert approved["source"]["consent"] == "approved"
+ assert approved["job_id"] is None
+ assert "Consent was granted" in approved["detail"]
+ assert "disabled" in approved["detail"]
+
+
+# ---------------------------------------------------------------------------
+# Per-source progress: the live job and the restart-proof last outcome
+# ---------------------------------------------------------------------------
+
+
+async def test_source_summary_carries_the_last_outcome_after_a_sync(
+ service, monkeypatch
+):
+ patch_connectors(monkeypatch, {"fake-conn": lambda: FakeConnector(make_items(4), [])})
+ source = await service.add_source("fake-conn", "Fake Source")
+ approved = await service.approve_source(source["id"])
+ await wait_for_job(service, approved["job_id"])
+
+ status = await service.status()
+ row = next(s for s in status["sources"] if s["id"] == source["id"])
+
+ assert row["active_job"] is None # the run finished
+ outcome = row["last_outcome"]
+ assert outcome["status"] == "done"
+ assert outcome["mode"] == "backfill"
+ assert outcome["new"] == 4
+ assert outcome["finished_at"]
+ assert row["last_notice"] is None
+
+
+async def test_source_summary_reports_the_running_job_with_its_phase(
+ service, monkeypatch
+):
+ gate = asyncio.Event()
+ reached = asyncio.Event()
+ patch_connectors(
+ monkeypatch,
+ {"blocking-conn": lambda: BlockingConnector(make_items(250), gate, reached)},
+ )
+ source = await service.add_source("blocking-conn", "Blocked Source")
+ approved = await service.approve_source(source["id"])
+ await asyncio.wait_for(reached.wait(), timeout=5.0)
+
+ status = await service.status()
+ row = next(s for s in status["sources"] if s["id"] == source["id"])
+ active = row["active_job"]
+
+ assert active["job_id"] == approved["job_id"]
+ assert active["status"] == "running"
+ assert active["phase"] == "importing"
+ # Items PULLED so far — the ticking number the progress bar shows.
+ assert active["items"] == 200
+ assert row["last_outcome"] is None # nothing has finished yet
+
+ gate.set()
+ await wait_for_job(service, approved["job_id"])
+
+
+async def test_a_failed_sync_records_an_honest_outcome(service, monkeypatch):
+ class ExplodingConnector:
+ id = "boom-conn"
+ label = "Exploding Connector"
+ auth = AuthKind.NONE
+ capabilities = ConnectorCapabilities(
+ backfill=True, incremental=IncrementalMode.NONE, deletes=False
+ )
+
+ async def backfill(self, ctx, checkpoint=None):
+ raise RuntimeError("the export file is corrupt")
+ yield # pragma: no cover — makes this an async generator
+
+ async def incremental(self, ctx, cursor=None):
+ return
+ yield # pragma: no cover — makes this an async generator
+
+ patch_connectors(monkeypatch, {"boom-conn": ExplodingConnector})
+ source = await service.add_source("boom-conn", "Boom")
+ approved = await service.approve_source(source["id"])
+ await wait_for_job(service, approved["job_id"])
+
+ row = next(
+ s for s in (await service.status())["sources"] if s["id"] == source["id"]
+ )
+ assert row["last_outcome"]["status"] == "failed"
+ assert "corrupt" in row["last_error"]
+
+
+# ---------------------------------------------------------------------------
+# Plugin bridge: real names, and the honest "no pull adapter yet" notice
+# ---------------------------------------------------------------------------
+
+
+def patch_bridge_candidates(
+ monkeypatch: pytest.MonkeyPatch, candidates: list[dict[str, str]]
+) -> None:
+ from jarvis.ultrawiki.connectors import plugin_bridge
+
+ monkeypatch.setattr(plugin_bridge, "list_candidates", lambda: list(candidates))
+
+
+async def test_bridge_source_is_named_after_the_integration(service, monkeypatch):
+ """A list of identical 'Connected Integrations' cards told nobody anything."""
+ patch_bridge_candidates(
+ monkeypatch,
+ [{"id": "plugin:github", "kind": "plugin", "label": "GitHub", "detail": ""}],
+ )
+
+ source = await service.add_source(
+ "plugin-bridge", "", config={"integration_id": "plugin:github"}
+ )
+
+ assert source["label"] == "GitHub"
+
+
+async def test_a_real_bridge_label_is_never_overwritten(service, monkeypatch):
+ patch_bridge_candidates(
+ monkeypatch,
+ [{"id": "plugin:github", "kind": "plugin", "label": "GitHub", "detail": ""}],
+ )
+
+ source = await service.add_source(
+ "plugin-bridge", "Work repos", config={"integration_id": "plugin:github"}
+ )
+
+ assert source["label"] == "Work repos"
+
+
+async def test_a_bridge_sync_without_a_pull_adapter_records_an_honest_notice(
+ service, monkeypatch
+):
+ """Zero imported items used to leave nothing but a log line."""
+ from jarvis.ultrawiki.service import BRIDGE_ADAPTER_PENDING_NOTICE
+
+ patch_bridge_candidates(
+ monkeypatch,
+ [{"id": "mcp:filesystem", "kind": "mcp", "label": "Filesystem", "detail": ""}],
+ )
+ source = await service.add_source(
+ "plugin-bridge", "", config={"integration_id": "mcp:filesystem"}
+ )
+ approved = await service.approve_source(source["id"])
+ await wait_for_job(service, approved["job_id"])
+
+ row = next(
+ s for s in (await service.status())["sources"] if s["id"] == source["id"]
+ )
+ assert row["last_notice"] == BRIDGE_ADAPTER_PENDING_NOTICE
+ # It is a NOTICE, not an error: the sync itself was healthy.
+ assert row["last_error"] is None
+ assert row["last_outcome"]["status"] == "done"
+ assert row["integration_id"] == "mcp:filesystem"
+
+
+async def test_the_notice_disappears_once_the_adapter_ships(service, monkeypatch):
+ from jarvis.ultrawiki.connectors import plugin_bridge
+
+ patch_bridge_candidates(
+ monkeypatch,
+ [{"id": "mcp:filesystem", "kind": "mcp", "label": "Filesystem", "detail": ""}],
+ )
+ source = await service.add_source(
+ "plugin-bridge", "", config={"integration_id": "mcp:filesystem"}
+ )
+ first = await service.approve_source(source["id"])
+ await wait_for_job(service, first["job_id"])
+ assert (await service._require_store().get_source(source["id"]))["last_notice"]
+
+ async def adapter(ctx, checkpoint=None):
+ yield RawItem(
+ external_id="doc-1",
+ body="the adapter shipped",
+ permalink="mcp://filesystem/doc-1",
+ timestamp_utc="2026-07-25T09:00:00Z",
+ title="Doc 1",
+ )
+
+ plugin_bridge.register_pull_adapter("mcp:filesystem", adapter)
+ try:
+ await wait_for_job(service, await service.start_sync(source["id"]))
+ finally:
+ plugin_bridge.unregister_pull_adapter("mcp:filesystem")
+
+ source_row = await service._require_store().get_source(source["id"])
+ assert source_row["last_notice"] is None
diff --git a/tests/unit/ultrawiki/test_store.py b/tests/unit/ultrawiki/test_store.py
index 87d37152bd..16f1e621fc 100644
--- a/tests/unit/ultrawiki/test_store.py
+++ b/tests/unit/ultrawiki/test_store.py
@@ -865,3 +865,164 @@ async def test_postgres_open_bounds_the_connect_attempt(monkeypatch):
# An unreachable host must fail fast into the SQLite fallback, never hang
# the startup path waiting on the OS default timeout.
assert seen["connect_timeout"] == store_mod.PG_CONNECT_TIMEOUT_S
+
+
+# ---------------------------------------------------------------------------
+# The inventory view (list_items) — what is actually IN the database
+# ---------------------------------------------------------------------------
+
+
+async def test_list_items_pages_newest_ingested_first(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(i) for i in range(5)])
+
+ first, total = await store.list_items(limit=2)
+ second, total_again = await store.list_items(limit=2, offset=2)
+
+ assert total == total_again == 5
+ assert len(first) == len(second) == 2
+ # One batch shares an ingest timestamp, so `id DESC` is what actually
+ # orders it — the newest row of the batch has to come first either way.
+ ids = [row["id"] for row in (*first, *second)]
+ assert ids == sorted(ids, reverse=True)
+ assert set(first[0]) == {
+ "id",
+ "source_id",
+ "state",
+ "permalink",
+ "timestamp_utc",
+ "title",
+ "ingested_at",
+ "updated_at",
+ }
+
+
+async def test_list_items_filters_by_source_and_state(store):
+ await add_source(store, "src1")
+ await add_source(store, "src2")
+ await store.upsert_items("src1", [make_item(i) for i in range(3)])
+ await store.upsert_items("src2", [make_item(10 + i) for i in range(2)])
+ claimed = await store.claim_batch(ItemState.KEYWORD_INDEXED, limit=1)
+ await index_keyword(store, claimed[0])
+
+ only_src2, total_src2 = await store.list_items(source_id="src2")
+ indexed, indexed_total = await store.list_items(state=ItemState.KEYWORD_INDEXED)
+ captured, captured_total = await store.list_items(state="captured")
+
+ assert total_src2 == 2
+ assert {row["source_id"] for row in only_src2} == {"src2"}
+ assert indexed_total == 1 and len(indexed) == 1
+ assert indexed[0]["id"] == claimed[0]["id"]
+ assert captured_total == 4
+
+
+async def test_list_items_excludes_tombstones_unless_asked(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(i) for i in range(3)])
+ await store.upsert_items("src1", [make_item(1, deleted=True)])
+
+ live, live_total = await store.list_items()
+ with_deleted, deleted_total = await store.list_items(include_deleted=True)
+
+ assert live_total == 2
+ assert deleted_total == 3
+ assert len(live) == 2 and len(with_deleted) == 3
+
+
+async def test_list_items_falls_back_to_the_external_id_for_untitled_rows(store):
+ await add_source(store)
+ await store.upsert_items("src1", [make_item(0, title="")])
+
+ rows, _total = await store.list_items()
+
+ assert rows[0]["title"] == "ext-0000"
+
+
+async def test_list_items_rejects_an_unknown_state(store):
+ await add_source(store)
+ with pytest.raises(ValueError, match="unknown item state"):
+ await store.list_items(state="not-a-state")
+
+
+# ---------------------------------------------------------------------------
+# Per-source visibility: the notice column and the persisted sync outcome
+# ---------------------------------------------------------------------------
+
+
+async def test_notice_and_error_are_separate_columns(store):
+ await add_source(store)
+ await store.set_source_status(
+ "src1", last_error="the folder vanished", last_notice="nothing to import"
+ )
+
+ source = await store.get_source("src1")
+ assert source["last_error"] == "the folder vanished"
+ assert source["last_notice"] == "nothing to import"
+
+ # A later healthy sync clears the error without touching the notice.
+ await store.set_source_status("src1", last_error=None)
+ source = await store.get_source("src1")
+ assert source["last_error"] is None
+ assert source["last_notice"] == "nothing to import"
+
+
+async def test_sync_outcome_survives_a_store_reopen(tmp_path):
+ """The job registry is in-memory; the outcome must not be."""
+ db_path = tmp_path / "ultrawiki.db"
+ first = UltraStore(db_path)
+ await add_source(first)
+ await first.record_sync_outcome(
+ "src1",
+ status="done",
+ mode="backfill",
+ finished_at="2026-07-25T09:00:00Z",
+ new=7,
+ changed=2,
+ unchanged=1,
+ tombstoned=3,
+ )
+ await first.close()
+
+ reopened = UltraStore(db_path)
+ try:
+ state = await reopened.get_sync_state("src1")
+ finally:
+ await reopened.close()
+
+ assert state["last_outcome_at"] == "2026-07-25T09:00:00Z"
+ assert state["last_outcome_status"] == "done"
+ assert state["last_outcome_mode"] == "backfill"
+ assert (state["last_new"], state["last_changed"]) == (7, 2)
+ assert (state["last_unchanged"], state["last_tombstoned"]) == (1, 3)
+
+
+async def test_additive_columns_are_added_to_a_pre_existing_database(tmp_path):
+ """A database created before the visibility package must gain the columns.
+
+ The pre-package shape is recreated by DROPping the new columns, which is
+ exactly what an older install's file looks like on disk.
+ """
+ import aiosqlite
+
+ db_path = tmp_path / "ultrawiki.db"
+ seeded = UltraStore(db_path)
+ await add_source(seeded)
+ await seeded.close()
+
+ async with aiosqlite.connect(db_path) as conn:
+ await conn.execute("ALTER TABLE uw_sources DROP COLUMN last_notice")
+ await conn.execute("ALTER TABLE uw_sync_state DROP COLUMN last_new")
+ await conn.commit()
+
+ upgraded = UltraStore(db_path)
+ try:
+ source = await upgraded.get_source("src1")
+ await upgraded.record_sync_outcome(
+ "src1", status="done", mode="backfill", finished_at="2026-07-25T09:00:00Z", new=4
+ )
+ state = await upgraded.get_sync_state("src1")
+ finally:
+ await upgraded.close()
+
+ assert source["last_notice"] is None
+ assert state["last_new"] == 4
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index 29505b4b00..e86b5b97cc 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -136,7 +136,11 @@ def _activate(env) -> dict:
def _approve_and_sync_folder(env) -> tuple[str, str]:
- """Register + approve + sync a local-folder source; returns (source_id, job_id)."""
+ """Register + approve a local-folder source; returns (source_id, job_id).
+
+ Approving IS the import: the approve answer carries the job id of the full
+ sync it started, so no second call is needed to get data flowing.
+ """
docs = env.tmp / "docs"
docs.mkdir(exist_ok=True)
(docs / "alpha.md").write_text(
@@ -158,11 +162,10 @@ def _approve_and_sync_folder(env) -> tuple[str, str]:
approved = env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")
assert approved.status_code == 200, approved.text
- assert approved.json()["consent"] == "approved"
-
- synced = env.client.post(f"/api/ultrawiki/sources/{source_id}/sync")
- assert synced.status_code == 201, synced.text
- return source_id, synced.json()["job_id"]
+ body = approved.json()
+ assert body["source"]["consent"] == "approved"
+ assert body["job_id"], body
+ return source_id, body["job_id"]
def _wait_for_job(env, job_id: str, timeout_s: float = 10.0) -> dict:
@@ -654,9 +657,9 @@ def test_cancel_of_a_running_job_succeeds(env, monkeypatch) -> None:
)
assert created.status_code == 201, created.text
source_id = created.json()["id"]
- env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")
+ # Approving starts the full import itself — that job is the one to cancel.
job_id = env.client.post(
- f"/api/ultrawiki/sources/{source_id}/sync"
+ f"/api/ultrawiki/sources/{source_id}/approve"
).json()["job_id"]
deadline = time.monotonic() + 5.0
@@ -1086,3 +1089,136 @@ def test_a_dead_model_catalog_degrades_instead_of_500ing(env, monkeypatch) -> No
body = response.json()
assert body["models"] == []
assert "RuntimeError" in body["reason"]
+
+
+# ---------------------------------------------------------------------------
+# Approve = import everything (the core visibility fix)
+# ---------------------------------------------------------------------------
+
+
+def test_approve_answers_with_the_import_it_started(env) -> None:
+ """The approve click used to only flip a flag and leave "Never synced"."""
+ _activate(env)
+ docs = env.tmp / "auto"
+ docs.mkdir(exist_ok=True)
+ (docs / "one.md").write_text("# One\n\nA single note.", encoding="utf-8")
+ source_id = env.client.post(
+ "/api/ultrawiki/sources",
+ json={
+ "connector": "local-folder",
+ "label": "Auto",
+ "config": {"root": str(docs)},
+ },
+ ).json()["id"]
+
+ response = env.client.post(f"/api/ultrawiki/sources/{source_id}/approve")
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["source"]["consent"] == "approved"
+ assert body["auto_sync"] is True
+ assert body["job_id"]
+ assert body["detail"]
+ snapshot = _wait_for_job(env, body["job_id"])
+ assert (snapshot["status"], snapshot["new"]) == ("done", 1)
+
+
+def test_approve_with_auto_sync_false_pulls_nothing(env) -> None:
+ _activate(env)
+ response = env.client.post(
+ "/api/ultrawiki/sources/normal-wiki/approve", params={"auto_sync": "false"}
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["source"]["consent"] == "approved"
+ assert body["job_id"] is None
+ assert body["auto_sync"] is False
+ assert env.client.get("/api/ultrawiki/jobs").json()["total"] == 0
+
+
+def test_status_carries_the_per_source_outcome_after_the_auto_import(env) -> None:
+ _activate(env)
+ source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ row = next(
+ source
+ for source in env.client.get("/api/ultrawiki/status").json()["sources"]
+ if source["id"] == source_id
+ )
+
+ assert row["active_job"] is None
+ assert row["last_outcome"]["status"] == "done"
+ assert row["last_outcome"]["new"] == 2
+ assert row["last_outcome"]["finished_at"]
+ assert row["last_notice"] is None
+
+
+# ---------------------------------------------------------------------------
+# The contents view — WHICH items are in the database, not just how many
+# ---------------------------------------------------------------------------
+
+
+def test_items_lists_the_stored_inventory(env) -> None:
+ _activate(env)
+ source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ response = env.client.get("/api/ultrawiki/items")
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["total"] == 2
+ assert (body["limit"], body["offset"]) == (50, 0)
+ row = body["items"][0]
+ assert row["source_id"] == source_id
+ assert row["state"] == "captured"
+ assert row["permalink"]
+ assert row["ingested_at"] and row["updated_at"]
+ assert {item["title"] for item in body["items"]} == {"alpha", "beta"}
+
+
+def test_items_filter_by_source_and_state(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+
+ distilled = env.client.get(
+ "/api/ultrawiki/items", params={"state": "distilled"}
+ ).json()
+ captured = env.client.get(
+ "/api/ultrawiki/items", params={"state": "captured"}
+ ).json()
+ elsewhere = env.client.get(
+ "/api/ultrawiki/items", params={"source_id": "normal-wiki"}
+ ).json()
+
+ assert distilled["total"] == 2
+ assert captured["total"] == 0
+ assert elsewhere["total"] == 0
+
+
+def test_items_paginate_with_an_honest_total(env) -> None:
+ _activate(env)
+ _source_id, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ first = env.client.get("/api/ultrawiki/items", params={"limit": 1}).json()
+ second = env.client.get(
+ "/api/ultrawiki/items", params={"limit": 1, "offset": 1}
+ ).json()
+
+ assert first["total"] == second["total"] == 2 # the total is UNPAGED
+ assert len(first["items"]) == len(second["items"]) == 1
+ assert first["items"][0]["id"] != second["items"][0]["id"]
+
+
+def test_items_reject_an_unknown_state(env) -> None:
+ _activate(env)
+ response = env.client.get(
+ "/api/ultrawiki/items", params={"state": "half-embedded"}
+ )
+ assert response.status_code == 400
+ assert "half-embedded" in response.json()["detail"]