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): open a stored item, and prove the import is complete

Ruben Lütked6cde405a1da
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
index c1472d74bb..c990751c6f 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ContentsPanel.tsx
@@ -18,6 +18,7 @@ import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { formatRelativeTime } from "@/components/ultrawiki/relativeTime";
+import { ItemDetailDialog } from "@/components/ultrawiki/ItemDetailDialog";
import {
fetchUltraWikiItems,
type UltraWikiItem,
@@ -83,6 +84,10 @@ export function ContentsPanel({
void load(0);
}, [load]);
+ // Which row is opened for inspection. A list of titles cannot answer "is
+ // the real content in there?" — only opening one can.
+ const [openItemId, setOpenItemId] = useState<number | null>(null);
+
const stageChips = STATE_FILTERS.map(([key, labelKey]) => ({
key,
label: t(labelKey),
@@ -207,28 +212,38 @@ export function ContentsPanel({
{rows.map((item) => (
<tr
key={item.id}
- className="border-t border-border/60"
+ className="cursor-pointer border-t border-border/60 hover:bg-primary/[0.04]"
+ onClick={() => setOpenItemId(item.id)}
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"
+ {/* The title opens what is STORED; the arrow goes to the
+ source. Two different questions, two different targets —
+ so the link stops the row's click. */}
+ <span className="inline-flex items-center gap-1">
+ <button
+ type="button"
+ className="truncate text-left text-foreground underline-offset-2 hover:underline"
+ data-testid={`ultrawiki-item-open-${item.id}`}
>
- <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>
- )}
+ </button>
+ {item.permalink && (
+ <a
+ href={item.permalink}
+ target="_blank"
+ rel="noreferrer"
+ onClick={(e) => e.stopPropagation()}
+ aria-label={t("ultrawiki.item.open_source")}
+ title={t("ultrawiki.item.open_source")}
+ >
+ <ExternalLink
+ className="h-3 w-3 shrink-0 text-muted-foreground hover:text-primary"
+ aria-hidden
+ />
+ </a>
+ )}
+ </span>
</td>
<td className="px-3 py-2 text-muted-foreground">
{sourceLabels.get(item.source_id) ?? item.source_id}
@@ -294,6 +309,13 @@ export function ContentsPanel({
</span>
)}
</div>
+ {openItemId !== null && (
+ <ItemDetailDialog
+ itemId={openItemId}
+ onClose={() => setOpenItemId(null)}
+ />
+ )}
+
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ItemDetailDialog.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ItemDetailDialog.tsx
new file mode 100644
index 0000000000..37ae2cf172
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ItemDetailDialog.tsx
@@ -0,0 +1,287 @@
+/**
+ * "Show me what is actually stored" — one item, opened.
+ *
+ * The inventory answers WHICH items exist. The maintainer's next question,
+ * looking at a list of 4 689 rows, was the obvious one: *is the real content
+ * in there, or just a title and a link?* A stage badge saying "distilled"
+ * cannot answer that — it is a claim about a row you cannot see.
+ *
+ * So this shows both halves, and keeps them visibly separate:
+ *
+ * - **As captured** — the raw text exactly as it was read from the source, so
+ * nothing has to be taken on trust. If a connector mangled an encoding or
+ * truncated a body, it is visible here and nowhere else.
+ * - **What Jarvis made of it** — the derived documents: the normalised text,
+ * the distillation (question / summary / resolution / entities), and whether
+ * a vector exists. That last flag is what turns the "embedded" badge from a
+ * promise into a fact.
+ *
+ * Nothing is summarised or prettified on the way to the screen: the point of
+ * the view is that it is the database, not a story about the database.
+ */
+import { useEffect, useState } from "react";
+import { ExternalLink, Loader2, X } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import {
+ fetchUltraWikiItemDetail,
+ type UltraWikiItemDetail,
+ type UltraWikiItemDocument,
+} from "@/lib/ultrawikiApi";
+
+export function ItemDetailDialog({
+ itemId,
+ onClose,
+}: {
+ itemId: number;
+ onClose: () => void;
+}): JSX.Element {
+ const t = useT();
+ const [detail, setDetail] = useState<UltraWikiItemDetail | null>(null);
+ const [error, setError] = useState("");
+
+ useEffect(() => {
+ let cancelled = false;
+ setDetail(null);
+ setError("");
+ fetchUltraWikiItemDetail(itemId)
+ .then((data) => {
+ if (!cancelled) setDetail(data);
+ })
+ .catch((e: Error) => {
+ if (!cancelled) setError(e.message);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [itemId]);
+
+ // Escape closes: this is a read-only inspector, so there is nothing to lose
+ // by leaving it and no reason to make the user aim for the X.
+ useEffect(() => {
+ function onKey(e: KeyboardEvent) {
+ if (e.key === "Escape") onClose();
+ }
+ document.addEventListener("keydown", onKey);
+ return () => document.removeEventListener("keydown", onKey);
+ }, [onClose]);
+
+ return (
+ <div
+ className="fixed inset-0 z-[70] flex items-center justify-center bg-background/80 p-4 backdrop-blur-sm"
+ role="dialog"
+ aria-modal="true"
+ aria-label={t("ultrawiki.item.title")}
+ data-testid="ultrawiki-item-dialog"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) onClose();
+ }}
+ >
+ <div className="flex max-h-[86vh] w-full max-w-3xl flex-col overflow-hidden rounded-2xl border border-border bg-card shadow-2xl">
+ <div className="flex items-start justify-between gap-3 border-b border-border px-5 py-3">
+ <div className="min-w-0">
+ <h2 className="truncate text-sm font-semibold text-foreground">
+ {detail?.title || t("ultrawiki.item.title")}
+ </h2>
+ {detail && (
+ <p className="mt-0.5 truncate text-[11px] text-muted-foreground">
+ {detail.source_id}
+ {" · "}
+ <code className="font-mono">{detail.external_id}</code>
+ {detail.timestamp_utc ? ` · ${detail.timestamp_utc}` : ""}
+ </p>
+ )}
+ </div>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={onClose}
+ aria-label={t("common.close")}
+ data-testid="ultrawiki-item-close"
+ >
+ <X className="h-4 w-4" aria-hidden />
+ </Button>
+ </div>
+
+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">
+ {error && (
+ <p
+ role="alert"
+ className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive"
+ data-testid="ultrawiki-item-error"
+ >
+ {error}
+ </p>
+ )}
+
+ {!detail && !error && (
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
+ {t("ultrawiki.item.loading")}
+ </p>
+ )}
+
+ {detail && (
+ <div className="space-y-5">
+ <div className="flex flex-wrap items-center gap-2">
+ <StageBadge state={detail.state} />
+ {detail.author && (
+ <span className="text-[11px] text-muted-foreground">
+ {detail.author}
+ </span>
+ )}
+ {detail.permalink && (
+ <a
+ href={detail.permalink}
+ target="_blank"
+ rel="noreferrer"
+ className="inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-primary"
+ >
+ <ExternalLink className="h-3 w-3" aria-hidden />
+ {t("ultrawiki.item.open_source")}
+ </a>
+ )}
+ </div>
+
+ {detail.last_error && (
+ <p className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-[11px] text-destructive">
+ {detail.last_error}
+ </p>
+ )}
+
+ <Section title={t("ultrawiki.item.as_captured")}>
+ <pre
+ className="max-h-72 overflow-auto whitespace-pre-wrap break-words rounded-lg border border-border/60 bg-muted/20 p-3 font-mono text-[11px] leading-relaxed text-foreground"
+ data-testid="ultrawiki-item-body"
+ >
+ {detail.body || t("ultrawiki.item.empty_body")}
+ </pre>
+ </Section>
+
+ <Section
+ title={t("ultrawiki.item.derived")}
+ hint={
+ // "Nothing derived yet" and "we could not read the
+ // derivations" look identical on screen and mean opposite
+ // things — one is normal progress, the other is a defect.
+ // Saying which is what caught a swallowed AttributeError
+ // that had turned every item into a silent "nothing yet".
+ detail.documents_error
+ ? t("ultrawiki.item.derived_error").replace(
+ "{0}",
+ detail.documents_error,
+ )
+ : detail.documents.length === 0
+ ? t("ultrawiki.item.derived_none")
+ : undefined
+ }
+ >
+ <div className="space-y-3">
+ {detail.documents.map((doc) => (
+ <DocumentBlock key={doc.id} doc={doc} />
+ ))}
+ </div>
+ </Section>
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Section({
+ title,
+ hint,
+ children,
+}: {
+ title: string;
+ hint?: string;
+ children: React.ReactNode;
+}): JSX.Element {
+ return (
+ <section className="space-y-1.5">
+ <h3 className="text-[10px] uppercase tracking-wider text-muted-foreground">
+ {title}
+ </h3>
+ {hint ? (
+ <p className="text-[11px] leading-relaxed text-muted-foreground">{hint}</p>
+ ) : (
+ children
+ )}
+ </section>
+ );
+}
+
+function DocumentBlock({ doc }: { doc: UltraWikiItemDocument }): JSX.Element {
+ const t = useT();
+ const distill = doc.distill ?? null;
+ return (
+ <div
+ className="rounded-lg border border-border/60 bg-muted/10 p-3"
+ data-testid={`ultrawiki-item-doc-${doc.id}`}
+ >
+ <div className="mb-2 flex flex-wrap items-center gap-2">
+ <span className="rounded-full border border-border bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">
+ {doc.doc_type}
+ </span>
+ <span
+ className={cn(
+ "rounded-full border px-2 py-0.5 text-[10px]",
+ doc.has_vector
+ ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-600"
+ : "border-border bg-muted text-muted-foreground",
+ )}
+ data-testid={`ultrawiki-item-vector-${doc.id}`}
+ >
+ {t(doc.has_vector ? "ultrawiki.item.has_vector" : "ultrawiki.item.no_vector")}
+ </span>
+ </div>
+
+ {/* The distillation, field by field. Rendered as labelled rows rather
+ than dumped JSON: this is the part a person reads to decide whether
+ the summary actually captured the item. */}
+ {distill && typeof distill === "object" && (
+ <dl className="mb-2 space-y-1">
+ {Object.entries(distill)
+ .filter(([, value]) => value !== null && value !== "" )
+ .map(([key, value]) => (
+ <div key={key} className="grid grid-cols-[7rem_1fr] gap-2">
+ <dt className="text-[10px] uppercase tracking-wide text-muted-foreground">
+ {key}
+ </dt>
+ <dd className="min-w-0 break-words text-[11px] leading-relaxed text-foreground">
+ {Array.isArray(value) ? value.join(", ") : String(value)}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ )}
+
+ <pre className="max-h-48 overflow-auto whitespace-pre-wrap break-words rounded border border-border/40 bg-background/60 p-2 font-mono text-[10px] leading-relaxed text-muted-foreground">
+ {doc.text}
+ </pre>
+ </div>
+ );
+}
+
+function StageBadge({ state }: { state: string }): JSX.Element {
+ const t = useT();
+ return (
+ <span
+ className={cn(
+ "rounded-full border px-2 py-0.5 text-[10px]",
+ state === "failed"
+ ? "border-destructive/40 bg-destructive/10 text-destructive"
+ : state === "distilled" || state === "embedded"
+ ? "border-emerald-500/30 bg-emerald-500/10 text-emerald-600"
+ : "border-border bg-muted text-muted-foreground",
+ )}
+ data-testid="ultrawiki-item-state"
+ >
+ {t(`ultrawiki.progress.stage_${state}`)}
+ </span>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ReconcileStrip.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ReconcileStrip.tsx
new file mode 100644
index 0000000000..2697ec58d2
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ReconcileStrip.tsx
@@ -0,0 +1,152 @@
+/**
+ * "Is everything really in there?" — the completeness proof, per source.
+ *
+ * A total cannot answer that question. "4 689 items" is equally consistent
+ * with *all of it* and with *as much as we managed before something quietly
+ * stopped*, and the maintainer asked precisely because the number alone gave
+ * no way to tell.
+ *
+ * So this compares two independently produced numbers: how many items the last
+ * finished import actually READ (new + changed + unchanged, counted by the
+ * sync run) against how many the store HOLDS for that source. Agreement is a
+ * real check — the two are produced by different code paths at different
+ * times — and disagreement prints the gap instead of a reassuring total.
+ *
+ * Four verdicts, because "not complete" has genuinely different causes: never
+ * imported, ended early, stored fewer than were read, or fine.
+ */
+import { useEffect, useState } from "react";
+import { AlertTriangle, CheckCircle2, Loader2, MinusCircle } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { useT } from "@/i18n";
+import { formatRelativeTime } from "@/components/ultrawiki/relativeTime";
+import {
+ fetchUltraWikiReconcile,
+ type UltraWikiReconcile,
+ type UltraWikiReconcileRow,
+} from "@/lib/ultrawikiApi";
+
+const VERDICT_STYLE: Record<string, { icon: typeof CheckCircle2; tone: string }> = {
+ complete: { icon: CheckCircle2, tone: "text-emerald-500" },
+ short: { icon: AlertTriangle, tone: "text-[#ffb84d]" },
+ incomplete: { icon: AlertTriangle, tone: "text-[#ffb84d]" },
+ never_imported: { icon: MinusCircle, tone: "text-muted-foreground" },
+};
+
+export function ReconcileStrip({
+ refreshKey,
+}: {
+ /** Bumped by the parent after an import, so the proof re-runs. */
+ refreshKey?: number;
+}): JSX.Element | null {
+ const t = useT();
+ // Plain state + effect rather than react-query on purpose: the Contents tab
+ // renders without a QueryClientProvider, and a strip that reports on the
+ // data must not dictate how its host is mounted.
+ const [data, setData] = useState<UltraWikiReconcile | null>(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ fetchUltraWikiReconcile()
+ .then((result) => {
+ if (!cancelled) setData(result);
+ })
+ .catch(() => {
+ // A failed check must not replace the inventory with an error — it
+ // simply says nothing, and the counts below still stand.
+ if (!cancelled) setData(null);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [refreshKey]);
+
+ if (loading) {
+ return (
+ <p className="flex items-center gap-2 text-[11px] text-muted-foreground">
+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
+ {t("ultrawiki.reconcile.checking")}
+ </p>
+ );
+ }
+ // Defensive on the SHAPE, not just on the error: this strip sits above the
+ // inventory, so an unexpected payload must make it disappear quietly rather
+ // than take the whole Contents tab down with it.
+ const rows = Array.isArray(data?.sources) ? data.sources : [];
+ if (!data || rows.length === 0) return null;
+
+ return (
+ <div
+ className={cn(
+ "rounded-xl border px-4 py-3",
+ data.all_complete
+ ? "border-emerald-500/30 bg-emerald-500/[0.05]"
+ : "border-[#ffb84d]/30 bg-[#ffb84d]/[0.05]",
+ )}
+ data-testid="ultrawiki-reconcile"
+ data-all-complete={data.all_complete ? "true" : "false"}
+ >
+ <p
+ className={cn(
+ "text-sm font-medium",
+ data.all_complete ? "text-emerald-500" : "text-[#ffb84d]",
+ )}
+ >
+ {data.all_complete
+ ? t("ultrawiki.reconcile.all_complete").replace(
+ "{0}",
+ String(data.total_stored ?? 0),
+ )
+ : t("ultrawiki.reconcile.partial")
+ .replace("{0}", String(data.complete ?? 0))
+ .replace("{1}", String(data.total_sources ?? rows.length))}
+ </p>
+ <ul className="mt-2 space-y-1.5">
+ {rows.map((row) => (
+ <ReconcileRow key={row.source_id} row={row} />
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+function ReconcileRow({ row }: { row: UltraWikiReconcileRow }): JSX.Element {
+ const t = useT();
+ const style = VERDICT_STYLE[row.verdict] ?? VERDICT_STYLE.never_imported;
+ const Icon = style.icon;
+ return (
+ <li
+ className="flex items-start gap-2"
+ data-testid={`ultrawiki-reconcile-${row.source_id}`}
+ data-verdict={row.verdict}
+ >
+ <Icon className={cn("mt-0.5 h-3.5 w-3.5 shrink-0", style.tone)} aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="text-[11px] text-foreground">
+ <span className="font-medium">{row.label}</span>
+ {" — "}
+ {row.detail}
+ </p>
+ {row.verdict !== "never_imported" && (
+ // The raw numbers, because the sentence above is a conclusion and
+ // this is the evidence it was drawn from.
+ <p className="text-[10px] text-muted-foreground">
+ {t("ultrawiki.reconcile.numbers")
+ .replace("{0}", String(row.read))
+ .replace("{1}", String(row.new))
+ .replace("{2}", String(row.changed))
+ .replace("{3}", String(row.unchanged))
+ .replace("{4}", String(row.stored))}
+ {row.finished_at ? ` · ${formatRelativeTime(row.finished_at, t)}` : ""}
+ </p>
+ )}
+ </div>
+ </li>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 27ffa2b7cc..21a38865cc 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -3010,6 +3010,24 @@
"empty": "In dieser Version werden keine Quellen angeboten.",
"selected": "Ausgewählt",
"choose": "Quelle auswählen"
+ },
+ "item": {
+ "title": "Gespeicherter Eintrag",
+ "loading": "Gespeicherter Datensatz wird geladen…",
+ "open_source": "Beim Ursprung öffnen",
+ "as_captured": "So aufgenommen",
+ "empty_body": "Dieser Eintrag wurde ohne Text gespeichert.",
+ "derived": "Was Jarvis daraus gemacht hat",
+ "derived_none": "Noch nichts abgeleitet. Zusammenfassungen und Vektoren entstehen im Hintergrund; über Stichwörter ist der Eintrag bereits findbar.",
+ "has_vector": "Vektor gespeichert",
+ "no_vector": "noch kein Vektor",
+ "derived_error": "Die abgeleiteten Dokumente konnten nicht gelesen werden ({0}). Der aufgenommene Text oben ist davon nicht betroffen."
+ },
+ "reconcile": {
+ "checking": "Wird geprüft, ob alles angekommen ist…",
+ "all_complete": "Alles Gelesene ist in der Datenbank — {0} Einträge.",
+ "partial": "{0} von {1} Quellen vollständig angekommen.",
+ "numbers": "gelesen {0} · {1} neu · {2} geändert · {3} unverändert · {4} gespeichert"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 65beec603e..9bac5ea7a4 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -3011,6 +3011,24 @@
"empty": "This build offers no source types.",
"selected": "Selected",
"choose": "Pick a source type"
+ },
+ "item": {
+ "title": "Stored item",
+ "loading": "Loading the stored record…",
+ "open_source": "Open at the source",
+ "as_captured": "As captured",
+ "empty_body": "This item was stored without any text.",
+ "derived": "What Jarvis made of it",
+ "derived_none": "Nothing derived yet. Summaries and vectors are added in the background; the item is already keyword-searchable.",
+ "has_vector": "vector stored",
+ "no_vector": "no vector yet",
+ "derived_error": "The derived documents could not be read ({0}). The captured text above is unaffected."
+ },
+ "reconcile": {
+ "checking": "Checking that everything landed…",
+ "all_complete": "Everything that was read is in the database — {0} item(s).",
+ "partial": "{0} of {1} source(s) fully landed.",
+ "numbers": "read {0} · {1} new · {2} changed · {3} unchanged · {4} stored"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 0e4a0a6c4c..3902880097 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -3010,6 +3010,24 @@
"empty": "Esta versión no ofrece ningún tipo de origen.",
"selected": "Seleccionado",
"choose": "Elige un tipo de origen"
+ },
+ "item": {
+ "title": "Elemento almacenado",
+ "loading": "Cargando el registro almacenado…",
+ "open_source": "Abrir en el origen",
+ "as_captured": "Tal como se capturó",
+ "empty_body": "Este elemento se guardó sin texto.",
+ "derived": "Lo que Jarvis hizo con ello",
+ "derived_none": "Todavía no se ha derivado nada. Los resúmenes y los vectores se crean en segundo plano; el elemento ya se encuentra por palabras.",
+ "has_vector": "vector guardado",
+ "no_vector": "aún sin vector",
+ "derived_error": "No se pudieron leer los documentos derivados ({0}). El texto capturado de arriba no se ve afectado."
+ },
+ "reconcile": {
+ "checking": "Comprobando que todo llegó…",
+ "all_complete": "Todo lo leído está en la base de datos: {0} elementos.",
+ "partial": "{0} de {1} fuentes llegaron completas.",
+ "numbers": "leídos {0} · {1} nuevos · {2} cambiados · {3} sin cambios · {4} guardados"
}
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index 307352e58e..f59abf38e1 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -187,6 +187,71 @@ export interface UltraWikiItem {
updated_at: string;
}
+/**
+ * One derived document of an item — what UltraWiki MADE of the raw text.
+ * `has_vector` is what turns the "embedded" badge from a claim into a fact.
+ */
+export interface UltraWikiItemDocument {
+ id: number;
+ doc_type: "raw" | "summary" | "burst" | string;
+ text: string;
+ distill: Record<string, unknown> | null;
+ has_vector: boolean;
+ created_at: string | null;
+}
+
+/** `GET /api/ultrawiki/items/{id}` — the full record behind one inventory row. */
+export interface UltraWikiItemDetail {
+ id: number;
+ source_id: string;
+ external_id: string;
+ title: string;
+ /** The text EXACTLY as captured, so nothing has to be taken on trust. */
+ body: string;
+ permalink: string;
+ timestamp_utc: string;
+ author: string;
+ thread_key: string;
+ state: UltraWikiItemState | string;
+ areas: string[];
+ content_hash: string;
+ attempt_count: number;
+ last_error: string;
+ deleted_at: string | null;
+ created_at: string | null;
+ updated_at: string | null;
+ documents: UltraWikiItemDocument[];
+ documents_error: string;
+}
+
+/**
+ * Mirrors `GET /api/ultrawiki/reconcile`. `verdict` is the honest four-way
+ * answer to "is everything in there?" — a count alone cannot tell "all of it"
+ * from "as much as we managed".
+ */
+export interface UltraWikiReconcileRow {
+ source_id: string;
+ label: string;
+ verdict: "complete" | "short" | "incomplete" | "never_imported" | string;
+ detail: string;
+ stored: number;
+ read: number;
+ new: number;
+ changed: number;
+ unchanged: number;
+ tombstoned: number;
+ finished_at: string | null;
+ last_error: string;
+}
+
+export interface UltraWikiReconcile {
+ sources: UltraWikiReconcileRow[];
+ total_stored: number;
+ all_complete: boolean;
+ complete: number;
+ total_sources: number;
+}
+
export interface UltraWikiItemsPage {
items: UltraWikiItem[];
/** The UNPAGED total for the active filters. */
@@ -678,6 +743,20 @@ export function syncAllUltraWikiSources(): Promise<UltraWikiSyncAllResponse> {
return postJson<UltraWikiSyncAllResponse>("/api/ultrawiki/sources/sync-all");
}
+/** Everything stored about one item — the raw text AND what was derived. */
+export function fetchUltraWikiItemDetail(
+ itemId: number,
+): Promise<UltraWikiItemDetail> {
+ return request<UltraWikiItemDetail>(
+ `/api/ultrawiki/items/${encodeURIComponent(String(itemId))}`,
+ );
+}
+
+/** Per-source proof that everything the last import read actually landed. */
+export function fetchUltraWikiReconcile(): Promise<UltraWikiReconcile> {
+ return request<UltraWikiReconcile>("/api/ultrawiki/reconcile");
+}
+
/**
* The selectable models for one slot's provider, in the exact shape the
* API-Keys model picker consumes — so the slots get THAT picker (searchable,
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index f043d6e541..75299e41b9 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -1617,6 +1617,148 @@ async def list_items(
)
[email protected]("/items/{item_id}", summary="Read one stored item in full")
+async def get_item(item_id: int, request: Request) -> dict[str, Any]:
+ """Everything UltraWiki holds about one item — including the stored text.
+
+ The inventory answers "which items are in there"; this answers "what does
+ it actually KNOW about this one". Both halves matter: the raw text as
+ captured (so a user can confirm nothing was mangled on the way in) AND the
+ derived documents with their distillation and vector state (so "distilled"
+ stops being a badge with nothing behind it).
+ """
+ service = _service(request)
+ store = await _store_of(service)
+ item = await store.get_item(item_id)
+ if item is None:
+ raise HTTPException(status_code=404, detail=f"unknown item {item_id}")
+
+ documents: list[dict[str, Any]] = []
+ try:
+ rows = await store.item_documents(item_id)
+ except Exception as exc: # noqa: BLE001 — a missing derivation is not a 500
+ log.debug("item documents unavailable for %s", item_id, exc_info=True)
+ rows = []
+ documents_error = f"{type(exc).__name__}"
+ else:
+ documents_error = ""
+ for row in rows:
+ distill: Any = None
+ raw = row.get("distill_json")
+ if raw:
+ try:
+ import json # noqa: PLC0415 — lazy, only on the detail path
+
+ distill = json.loads(raw)
+ except (TypeError, ValueError):
+ # Keep the unparsed text rather than dropping it: a broken
+ # distillation is still evidence of what happened.
+ distill = {"raw": str(raw)[:2000]}
+ documents.append(
+ {
+ "id": row.get("id"),
+ "doc_type": row.get("doc_type"),
+ "text": str(row.get("text_norm") or ""),
+ "distill": distill,
+ "has_vector": bool(row.get("has_vector")),
+ "created_at": row.get("created_at"),
+ }
+ )
+
+ return {
+ "id": item.get("id"),
+ "source_id": item.get("source_id"),
+ "external_id": item.get("external_id"),
+ "title": item.get("title") or "",
+ # The text EXACTLY as it was captured — the point of the whole view.
+ "body": item.get("body_raw") or "",
+ "permalink": item.get("permalink") or "",
+ "timestamp_utc": item.get("timestamp_utc") or "",
+ "author": item.get("author_raw") or "",
+ "thread_key": item.get("thread_key") or "",
+ "state": item.get("state") or "",
+ "areas": item.get("areas") or [],
+ "content_hash": item.get("content_hash") or "",
+ "attempt_count": item.get("attempt_count") or 0,
+ "last_error": item.get("last_error") or "",
+ "deleted_at": item.get("deleted_at"),
+ "created_at": item.get("created_at"),
+ "updated_at": item.get("updated_at"),
+ "documents": documents,
+ "documents_error": documents_error,
+ }
+
+
[email protected]("/reconcile", summary="Did everything that was read actually land?")
+async def reconcile_sources(request: Request) -> dict[str, Any]:
+ """Per-source proof that the last import is fully in the database.
+
+ "It says 4 689 items — but is that everything?" is a fair question that no
+ count alone can answer, because a count cannot distinguish "all of it" from
+ "as much as we managed". The last finished run reports exactly how many
+ items it READ (new + changed + unchanged); the store reports how many it
+ HOLDS for that source. When the stored number covers the read number,
+ everything the connector handed over is in the database — and when it does
+ not, the difference is the honest answer instead of a reassuring total.
+ """
+ service = _service(request)
+ status = await service.status()
+ rows: list[dict[str, Any]] = []
+ for source in status.get("sources", []):
+ counts = dict(source.get("counts") or {})
+ stored = int(counts.get("total") or 0)
+ outcome = dict(source.get("last_outcome") or {})
+ finished = bool(outcome)
+ read = (
+ int(outcome.get("new") or 0)
+ + int(outcome.get("changed") or 0)
+ + int(outcome.get("unchanged") or 0)
+ )
+ if not finished:
+ verdict, detail = "never_imported", "This source has never been read."
+ elif outcome.get("status") != "done":
+ verdict = "incomplete"
+ detail = (
+ f"The last import ended as '{outcome.get('status')}', so it may "
+ "not have read everything."
+ )
+ elif stored >= read:
+ verdict = "complete"
+ detail = (
+ f"All {read} item(s) the last import read are in the database."
+ )
+ else:
+ verdict = "short"
+ detail = (
+ f"The last import read {read} item(s) but only {stored} are "
+ "stored — {0} are missing.".replace("{0}", str(read - stored))
+ )
+ rows.append(
+ {
+ "source_id": source.get("id"),
+ "label": source.get("label") or source.get("id"),
+ "verdict": verdict,
+ "detail": detail,
+ "stored": stored,
+ "read": read,
+ "new": int(outcome.get("new") or 0),
+ "changed": int(outcome.get("changed") or 0),
+ "unchanged": int(outcome.get("unchanged") or 0),
+ "tombstoned": int(outcome.get("tombstoned") or 0),
+ "finished_at": outcome.get("finished_at"),
+ "last_error": source.get("last_error") or "",
+ }
+ )
+ complete = [r for r in rows if r["verdict"] == "complete"]
+ return {
+ "sources": rows,
+ "total_stored": sum(r["stored"] for r in rows),
+ "all_complete": bool(rows) and len(complete) == len(rows),
+ "complete": len(complete),
+ "total_sources": len(rows),
+ }
+
+
# ---------------------------------------------------------------------------
# Areas
# ---------------------------------------------------------------------------
diff --git a/jarvis/ultrawiki/store.py b/jarvis/ultrawiki/store.py
index 5c8bbb2fe0..b2b0263f38 100644
--- a/jarvis/ultrawiki/store.py
+++ b/jarvis/ultrawiki/store.py
@@ -800,6 +800,33 @@ class UltraStore:
)
return None if row is None else self._item_row_to_dict(row)
+ async def item_documents(self, item_id: int) -> list[dict[str, Any]]:
+ """The derived documents of one item, with their embedding state.
+
+ What a user means by "show me what is actually stored": not the raw
+ text they already have at the source, but what UltraWiki MADE of it —
+ the normalised document, the distillation, and whether it carries a
+ vector. Without this, "distilled" is a badge with nothing behind it.
+ """
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT d.id, d.doc_type, d.text_norm, d.distill_json,"
+ " d.distill_version, d.created_at,"
+ " EXISTS (SELECT 1 FROM uw_embeddings e WHERE e.document_id = d.id)"
+ " AS has_vector"
+ " FROM uw_documents d WHERE d.item_id = ?"
+ " ORDER BY d.id",
+ (item_id,),
+ )
+ # `_fetchall` hands back aiosqlite.Row, which has no .get() — mapping
+ # each row through dict() first is what keeps this from raising an
+ # AttributeError the caller would only ever see as "no documents".
+ return [
+ {**dict(row), "has_vector": bool(dict(row).get("has_vector"))}
+ for row in rows
+ ]
+
async def list_items(
self,
*,
@@ -2196,6 +2223,24 @@ class PostgresStore:
)
return None if row is None else self._item_row_to_dict(row)
+ async def item_documents(self, item_id: int) -> list[dict[str, Any]]:
+ """Postgres twin of :meth:`UltraStore.item_documents`."""
+ conn = await self._ensure_open()
+ rows = await self._fetchall(
+ conn,
+ "SELECT d.id, d.doc_type, d.text_norm, d.distill_json,"
+ " d.distill_version, d.created_at,"
+ " EXISTS (SELECT 1 FROM uw_embeddings e WHERE e.document_id = d.id)"
+ " AS has_vector"
+ " FROM uw_documents d WHERE d.item_id = %s"
+ " ORDER BY d.id",
+ (item_id,),
+ )
+ return [
+ {**dict(row), "has_vector": bool(dict(row).get("has_vector"))}
+ for row in rows
+ ]
+
async def list_items(
self,
*,
diff --git a/tests/unit/ultrawiki/test_reconcile.py b/tests/unit/ultrawiki/test_reconcile.py
new file mode 100644
index 0000000000..d8c00a4199
--- /dev/null
+++ b/tests/unit/ultrawiki/test_reconcile.py
@@ -0,0 +1,195 @@
+"""The completeness verdict — "is everything really in there?".
+
+A total cannot answer that question: "4 689 items" is equally consistent with
+*all of it* and with *as much as we managed before something quietly stopped*.
+The verdict compares two independently produced numbers — what the last
+finished run READ against what the store HOLDS — so agreement is evidence and
+disagreement prints the gap.
+
+These pin the four outcomes, because "not complete" has genuinely different
+causes and a user acts differently on each.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web.ultrawiki_routes import reconcile_sources
+
+
+class _Service:
+ """Only the one method the route uses."""
+
+ def __init__(self, sources: list[dict[str, Any]]) -> None:
+ self._sources = sources
+
+ async def status(self) -> dict[str, Any]:
+ return {"sources": self._sources}
+
+
+def client_for():
+ """A tiny app around the route — no store, no pipeline, no network."""
+
+ def _build(sources: list[dict[str, Any]]) -> TestClient:
+ app = FastAPI()
+ app.state.ultrawiki = _Service(sources)
+ app.get("/reconcile")(reconcile_sources)
+ return TestClient(app)
+
+ return _build
+
+
+def _source(**overrides: Any) -> dict[str, Any]:
+ base: dict[str, Any] = {
+ "id": "normal-wiki",
+ "label": "Built-in Wiki",
+ "counts": {"total": 60},
+ "last_outcome": {
+ "status": "done",
+ "new": 60,
+ "changed": 0,
+ "unchanged": 0,
+ "tombstoned": 0,
+ "finished_at": "2026-07-25T18:08:31Z",
+ },
+ "last_error": "",
+ }
+ base.update(overrides)
+ return base
+
+
+def test_a_fully_landed_source_says_so_with_its_numbers(client_for):
+ body = client_for([_source()]).get("/reconcile").json()
+ row = body["sources"][0]
+ assert row["verdict"] == "complete"
+ assert row["read"] == 60
+ assert row["stored"] == 60
+ assert "All 60 item(s)" in row["detail"]
+ assert body["all_complete"] is True
+ assert body["total_stored"] == 60
+
+
+def test_read_counts_every_item_the_run_saw_not_just_the_new_ones(client_for):
+ """A re-import is mostly `unchanged`, and those items ARE in the database.
+
+ Counting only `new` would report a healthy second sync as having lost
+ everything — the most alarming possible way to be wrong.
+ """
+ body = (
+ client_for(
+ [
+ _source(
+ counts={"total": 60},
+ last_outcome={
+ "status": "done",
+ "new": 2,
+ "changed": 3,
+ "unchanged": 55,
+ "tombstoned": 0,
+ "finished_at": "2026-07-25T19:00:00Z",
+ },
+ )
+ ]
+ )
+ .get("/reconcile")
+ .json()
+ )
+ row = body["sources"][0]
+ assert row["read"] == 60
+ assert row["verdict"] == "complete"
+
+
+def test_a_source_that_stored_fewer_than_it_read_prints_the_gap(client_for):
+ body = (
+ client_for(
+ [
+ _source(
+ counts={"total": 40},
+ last_outcome={
+ "status": "done",
+ "new": 60,
+ "changed": 0,
+ "unchanged": 0,
+ "tombstoned": 0,
+ "finished_at": "2026-07-25T18:08:31Z",
+ },
+ )
+ ]
+ )
+ .get("/reconcile")
+ .json()
+ )
+ row = body["sources"][0]
+ assert row["verdict"] == "short"
+ # The number, not a shrug: 20 items are unaccounted for.
+ assert "20 are missing" in row["detail"]
+ assert body["all_complete"] is False
+
+
+def test_a_run_that_ended_early_is_not_reported_as_complete(client_for):
+ """A cancelled or failed run may simply not have reached the rest.
+
+ Its stored count can look right while half the source was never read, so
+ the verdict must follow the run's own status, not the arithmetic.
+ """
+ body = (
+ client_for(
+ [
+ _source(
+ counts={"total": 60},
+ last_outcome={
+ "status": "cancelled",
+ "new": 60,
+ "changed": 0,
+ "unchanged": 0,
+ "tombstoned": 0,
+ "finished_at": "2026-07-25T18:08:31Z",
+ },
+ )
+ ]
+ )
+ .get("/reconcile")
+ .json()
+ )
+ row = body["sources"][0]
+ assert row["verdict"] == "incomplete"
+ assert "cancelled" in row["detail"]
+
+
+def test_a_never_imported_source_is_its_own_verdict(client_for):
+ """The exact state that left this knowledge base empty for days."""
+ body = client_for([_source(counts={}, last_outcome=None)]).get("/reconcile").json()
+ row = body["sources"][0]
+ assert row["verdict"] == "never_imported"
+ assert row["read"] == 0
+ assert row["stored"] == 0
+ assert body["all_complete"] is False
+
+
+def test_the_summary_counts_only_the_sources_that_are_complete(client_for):
+ body = (
+ client_for(
+ [
+ _source(id="a", label="A"),
+ _source(id="b", label="B", counts={}, last_outcome=None),
+ ]
+ )
+ .get("/reconcile")
+ .json()
+ )
+ assert body["complete"] == 1
+ assert body["total_sources"] == 2
+ assert body["all_complete"] is False
+
+
+def test_no_sources_is_not_reported_as_all_complete(client_for):
+ """An empty install must not claim a clean bill of health."""
+ body = client_for([]).get("/reconcile").json()
+ assert body["sources"] == []
+ assert body["all_complete"] is False
+ assert body["total_stored"] == 0
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index 3a5a10b476..f31b78b7f0 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -1076,6 +1076,64 @@ def test_an_unknown_slot_is_a_404(env) -> None:
assert env.client.get("/api/ultrawiki/models/nonsense").status_code == 404
+def test_one_item_can_be_read_in_full_including_its_stored_text(env) -> None:
+ """The inventory says WHICH items exist; this says what is actually in one.
+
+ A stage badge reading "distilled" is a claim about a row the user cannot
+ see. Opening the record has to show the captured text itself — otherwise
+ "is the real content in there?" stays unanswerable from the app.
+ """
+ _activate(env)
+ _, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+ _drive_pipeline(env)
+
+ listed = env.client.get("/api/ultrawiki/items").json()
+ assert listed["total"] >= 1
+
+ bodies = []
+ for row in listed["items"]:
+ response = env.client.get(f"/api/ultrawiki/items/{row['id']}")
+ assert response.status_code == 200, response.text
+ bodies.append(response.json())
+
+ for body in bodies:
+ # The text EXACTLY as captured — the whole point of the view.
+ assert body["body"].strip()
+ assert body["permalink"]
+ assert body["content_hash"]
+ assert isinstance(body["documents"], list)
+
+ # At least one item must carry what was DERIVED from it, so "embedded"
+ # stops being a badge with nothing behind it. Not EVERY item: the staged
+ # pipeline advances items independently, and asserting on all of them
+ # would pin scheduling order rather than the contract.
+ derived = [doc for body in bodies for doc in body["documents"]]
+ assert derived, "a driven pipeline must leave at least one derived document"
+ assert all("has_vector" in doc for doc in derived)
+ assert any(doc["text"].strip() for doc in derived)
+
+
+def test_an_unknown_item_is_a_404_not_an_empty_record(env) -> None:
+ _activate(env)
+ assert env.client.get("/api/ultrawiki/items/999999").status_code == 404
+
+
+def test_reconcile_confirms_the_import_landed(env) -> None:
+ _activate(env)
+ _, job_id = _approve_and_sync_folder(env)
+ _wait_for_job(env, job_id)
+
+ body = env.client.get("/api/ultrawiki/reconcile").json()
+ folder = next(r for r in body["sources"] if r["source_id"].startswith("local-folder"))
+ assert folder["verdict"] == "complete"
+ assert folder["read"] == folder["stored"] == 2
+ # The default sources were registered but never synced by this test, so the
+ # summary must NOT claim everything landed.
+ assert body["all_complete"] is False
+ assert any(r["verdict"] == "never_imported" for r in body["sources"])
+
+
def test_a_dead_model_catalog_degrades_instead_of_500ing(env, monkeypatch) -> None:
"""A settings screen must render even when a provider catalog is down."""
import jarvis.ui.web.provider_routes as provider_routes