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): export-import connector — the standards-based universal on-ramp

Ruben Lütkead8af23d82cc
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorBrand.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorBrand.tsx
index 1c28ad70a8..313f9afa6b 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorBrand.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorBrand.tsx
@@ -14,11 +14,17 @@
* the point: it should look like something to fix, not like a design.
*
* Built-in connectors have no vendor and must not borrow one. Their brand token
- * is one of the neutral names (`vault`, `folder`, `chat`, `wiki`) and resolves
- * to one of our own icons.
+ * is one of the neutral names (`vault`, `folder`, `chat`, `wiki`, `archive`)
+ * and resolves to one of our own icons.
*/
import { useState } from "react";
-import { BookOpen, FolderOpen, MessageSquare, Vault } from "lucide-react";
+import {
+ BookOpen,
+ FileArchive,
+ FolderOpen,
+ MessageSquare,
+ Vault,
+} from "lucide-react";
import type { LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
@@ -41,6 +47,7 @@ const NEUTRAL_ICONS: Record<string, LucideIcon | undefined> = {
folder: FolderOpen,
chat: MessageSquare,
wiki: BookOpen,
+ archive: FileArchive,
};
/** Which tier a mark resolved to — also exposed as `data-brand-tier`, so a
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorPicker.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorPicker.test.tsx
index 90893df101..e143ac176c 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorPicker.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ConnectorPicker.test.tsx
@@ -41,6 +41,17 @@ const ROSTER = {
connector: "local-folder",
integration_id: "",
},
+ {
+ id: "export-import",
+ kind: "builtin",
+ label: "Export file import",
+ label_key: "ultrawiki.sources.connector_export_import",
+ brand: "archive",
+ status: "available",
+ description_key: "ultrawiki.connectors.export_import",
+ connector: "export-import",
+ integration_id: "",
+ },
{
id: "github",
kind: "bridge",
@@ -76,8 +87,8 @@ const ROSTER = {
integration_id: "plugin:acme_notes",
},
],
- total: 4,
- builtin: 1,
+ total: 5,
+ builtin: 2,
bridge: 3,
};
@@ -187,6 +198,36 @@ describe("ConnectorPicker — only the curated roster renders", () => {
expect(monogram.getAttribute("data-brand-tier")).toBe("monogram");
expect(monogram.textContent).toBe("A");
});
+
+ it("offers the export on-ramp as a selectable, vendor-free built-in", async () => {
+ const onSelect = mountPicker([candidate({})]);
+
+ await waitFor(() => {
+ expect(screen.getByTestId("uw-picker-export-import")).toBeDefined();
+ });
+ const tile = screen.getByTestId("uw-picker-export-import");
+ // It belongs to no vendor: our own glyph, never a borrowed mark.
+ expect(
+ screen
+ .getByTestId("uw-picker-brand-export-import")
+ .getAttribute("data-brand-tier"),
+ ).toBe("neutral");
+ // A built-in is always "connected" — there is nothing to connect.
+ expect(tile.getAttribute("data-connected")).toBe("true");
+ expect(
+ screen
+ .getByTestId("uw-picker-badge-export-import")
+ .getAttribute("data-status"),
+ ).toBe("available");
+
+ fireEvent.click(tile);
+ expect(onSelect.mock.calls[0][0]).toMatchObject({
+ key: "export-import",
+ connector: "export-import",
+ integrationId: "",
+ connected: true,
+ });
+ });
});
describe("ConnectorPicker — honest status", () => {
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.test.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.test.tsx
new file mode 100644
index 0000000000..95d3e6bf62
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.test.tsx
@@ -0,0 +1,246 @@
+/**
+ * ExportPreview tests — "what does 'import everything' actually mean?".
+ *
+ * The two properties this control exists for: the file can get onto the
+ * machine at all (upload, which then fills the path), and the user can see
+ * what is inside it BEFORE creating a source. The honesty half is pinned too:
+ * a lower-bound count says so, a failed read shows the backend's own sentence
+ * instead of a generic error, and formats that share a label are merged
+ * rather than rendered as "3,214 mails - 1 mails".
+ */
+import { useState } from "react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { ExportPreview, formatBytes } from "@/components/ultrawiki/ExportPreview";
+
+function Harness({ initial = "" }: { initial?: string }): JSX.Element {
+ const [path, setPath] = useState(initial);
+ return (
+ <>
+ <ExportPreview path={path} onPathChange={setPath} />
+ <span data-testid="harness-path">{path}</span>
+ </>
+ );
+}
+
+const REPORT = {
+ path: "/drop/takeout.zip",
+ exists: true,
+ is_dir: false,
+ formats: {
+ mbox: { files: 2, items_estimate: 3214, exact: true },
+ // A loose .eml shares the "mails" label — the two must be merged.
+ eml: { files: 1, items_estimate: 4, exact: true },
+ ics: { files: 1, items_estimate: 122, exact: true },
+ whatsapp: { files: 8, items_estimate: 96, exact: true },
+ },
+ unknown: [{ extension: ".dll", files: 41 }],
+ unreadable: [{ path: "scan.pdf", reason: "the PDF is password protected" }],
+ archives: { files: 1, entries: 12, max_depth: 2, budget_exhausted: false },
+ total_bytes: 1024 * 1024 * 3,
+ files_seen: 55,
+ items_estimate: 3436,
+ unknown_files: 41,
+ truncated: false,
+ notes: [],
+};
+
+function installFetchMock(
+ routes: Record<string, (init?: RequestInit) => unknown>,
+ failing: string[] = [],
+) {
+ const fetchMock = vi.fn(
+ async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ for (const prefix of failing) {
+ if (url.startsWith(prefix)) {
+ return {
+ ok: false,
+ status: 404,
+ statusText: "Not Found",
+ json: async () => ({ detail: "nothing exists at '/nope'" }),
+ } as Response;
+ }
+ }
+ const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);
+ for (const prefix of prefixes) {
+ if (url.startsWith(prefix)) {
+ return {
+ ok: true,
+ status: 200,
+ statusText: "OK",
+ json: async () => routes[prefix](init),
+ } as Response;
+ }
+ }
+ throw new Error(`unexpected fetch ${url}`);
+ },
+ );
+ (globalThis as unknown as { fetch: typeof fetch }).fetch =
+ fetchMock as unknown as typeof fetch;
+ return fetchMock;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.restoreAllMocks();
+});
+
+describe("ExportPreview — see what is in it before importing", () => {
+ it("reports the formats it found in one readable line", async () => {
+ const fetchMock = installFetchMock({
+ "/api/ultrawiki/export/preview": () => REPORT,
+ });
+ render(<Harness initial="/drop/takeout.zip" />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-export-preview"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-report")).toBeDefined();
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ "/api/ultrawiki/export/preview",
+ expect.objectContaining({ method: "POST" }),
+ );
+ const report = screen.getByTestId("ultrawiki-export-report");
+ // Two mail formats, ONE "mails" segment carrying their sum.
+ expect(report.textContent).toContain("3,218 mails");
+ expect(screen.queryByTestId("uw-export-count-eml")).toBeNull();
+ expect(report.textContent).toContain("122 calendar events");
+ expect(report.textContent).toContain("96 chat days");
+ // The skipped half is stated, not hidden.
+ expect(report.textContent).toContain("41 unrecognised files skipped");
+ expect(report.textContent).toContain("1 files could not be read");
+ expect(report.textContent).toContain("1 archives (12 entries)");
+ expect(report.textContent).toContain("3 MB in total");
+ });
+
+ it("says so when the numbers are only a lower bound", async () => {
+ installFetchMock({
+ "/api/ultrawiki/export/preview": () => ({
+ ...REPORT,
+ truncated: true,
+ formats: { mbox: { files: 1, items_estimate: 5000, exact: false } },
+ notes: ["More than 5000 files were found; the preview stopped there."],
+ }),
+ });
+ render(<Harness initial="/drop/huge" />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-export-preview"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-truncated")).toBeDefined();
+ });
+ // A "~" in front of an inexact count, and the backend's own sentence.
+ expect(screen.getByTestId("ultrawiki-export-report").textContent).toContain(
+ "~5,000 mails",
+ );
+ expect(screen.getByTestId("ultrawiki-export-report").textContent).toContain(
+ "the preview stopped there",
+ );
+ });
+
+ it("shows the backend's reason when the path cannot be read", async () => {
+ installFetchMock({}, ["/api/ultrawiki/export/preview"]);
+ render(<Harness initial="/nope" />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-export-preview"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-error")).toBeDefined();
+ });
+ expect(screen.getByTestId("ultrawiki-export-error").textContent).toContain(
+ "nothing exists at '/nope'",
+ );
+ expect(screen.queryByTestId("ultrawiki-export-report")).toBeNull();
+ });
+
+ it("cannot preview an empty path", () => {
+ installFetchMock({});
+ render(<Harness />);
+ expect(
+ screen.getByTestId("ultrawiki-export-preview").hasAttribute("disabled"),
+ ).toBe(true);
+ });
+
+ it("drops a stale report when the path is edited", async () => {
+ installFetchMock({ "/api/ultrawiki/export/preview": () => REPORT });
+ render(<Harness initial="/drop/takeout.zip" />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-export-preview"));
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-report")).toBeDefined();
+ });
+
+ fireEvent.change(screen.getByTestId("ultrawiki-export-path-input"), {
+ target: { value: "/drop/something-else.zip" },
+ });
+
+ // A report about the previous path would be a confident wrong answer.
+ expect(screen.queryByTestId("ultrawiki-export-report")).toBeNull();
+ });
+});
+
+describe("ExportPreview — getting the file here in the first place", () => {
+ it("uploads a file and fills the path with where it landed", async () => {
+ const fetchMock = installFetchMock({
+ "/api/ultrawiki/export/upload": () => ({
+ path: "/data/ultrawiki/uploads/abc123/takeout.zip",
+ name: "takeout.zip",
+ size: 4096,
+ detail: "The file is on this machine.",
+ }),
+ });
+ render(<Harness />);
+
+ const file = new File(["archive bytes"], "takeout.zip", {
+ type: "application/zip",
+ });
+ fireEvent.change(screen.getByTestId("ultrawiki-export-upload-input"), {
+ target: { files: [file] },
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("harness-path").textContent).toBe(
+ "/data/ultrawiki/uploads/abc123/takeout.zip",
+ );
+ });
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe("/api/ultrawiki/export/upload");
+ expect(init.method).toBe("POST");
+ // No Content-Type header: the browser has to set the multipart boundary.
+ expect(init.headers).toBeUndefined();
+ expect(init.body).toBeInstanceOf(FormData);
+ expect(screen.getByTestId("ultrawiki-export-uploaded").textContent).toContain(
+ "takeout.zip",
+ );
+ // The path is now previewable.
+ expect(
+ screen.getByTestId("ultrawiki-export-preview").hasAttribute("disabled"),
+ ).toBe(false);
+ });
+
+ it("reports a refused upload instead of leaving a dead field", async () => {
+ installFetchMock({}, ["/api/ultrawiki/export/upload"]);
+ render(<Harness />);
+
+ fireEvent.change(screen.getByTestId("ultrawiki-export-upload-input"), {
+ target: { files: [new File(["x"], "../escape.zip")] },
+ });
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-error")).toBeDefined();
+ });
+ expect(screen.getByTestId("harness-path").textContent).toBe("");
+ });
+});
+
+describe("formatBytes", () => {
+ it("renders a size a person can read", () => {
+ expect(formatBytes(0)).toBe("0 B");
+ expect(formatBytes(2048)).toBe("2 KB");
+ expect(formatBytes(1024 * 1024 * 3)).toBe("3 MB");
+ expect(formatBytes(1024 * 1024 * 1024 * 2.5)).toBe("2.5 GB");
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.tsx
new file mode 100644
index 0000000000..a4becec659
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/ExportPreview.tsx
@@ -0,0 +1,325 @@
+/**
+ * The export-import add-flow: get the file here, then look inside it.
+ *
+ * Two problems this solves, both of which the plain path field could not:
+ *
+ * • The file is usually not on the machine running Jarvis. "Type the full
+ * path to your Takeout archive" is a non-starter on a headless server and
+ * unfriendly even on a desktop, so the upload control streams it over and
+ * fills the path field with wherever it landed.
+ * • "Approve & import everything" is a big button to press blind. The
+ * preview answers what "everything" IS — how many mails, events, chat
+ * days and table chunks were found, and how many files will be skipped as
+ * unrecognised — BEFORE the source is created.
+ *
+ * The preview is deliberately read-only and changes nothing: consent still
+ * starts pending, and approval is still the one gate before a byte is read.
+ * Where the backend says its own count is a lower bound (`truncated`), that
+ * sentence is shown rather than smoothed over.
+ */
+import { useRef, useState } from "react";
+import { FileUp, Loader2, ScanSearch } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import { useT, useUiLanguage } from "@/i18n";
+import { localeForUiLanguage } from "@/components/runs/format";
+import {
+ previewUltraWikiExport,
+ uploadUltraWikiExport,
+ type UltraWikiExportPreview,
+} from "@/lib/ultrawikiApi";
+
+/** One "3,214 mails" segment of the found-line. */
+export interface ExportSummarySegment {
+ key: string;
+ label: string;
+ count: number;
+ exact: boolean;
+}
+
+const BYTE_UNITS = ["B", "KB", "MB", "GB", "TB"] as const;
+
+export function formatBytes(bytes: number): string {
+ let value = Math.max(0, bytes);
+ let unit = 0;
+ while (value >= 1024 && unit < BYTE_UNITS.length - 1) {
+ value /= 1024;
+ unit += 1;
+ }
+ const rounded = value >= 100 || unit === 0 ? Math.round(value) : Number(value.toFixed(1));
+ return `${rounded} ${BYTE_UNITS[unit]}`;
+}
+
+/**
+ * Thousands grouping follows the app's UI LANGUAGE, never the browser's or
+ * the machine's locale — the trap `components/runs/format.ts` documents: on a
+ * German-locale machine running the English UI, a bare `toLocaleString()`
+ * renders 3214 as "3.214", which an English reader parses as three-point-two.
+ */
+function counter(language: string): (value: number) => string {
+ const locale = localeForUiLanguage(language);
+ return (value: number) => value.toLocaleString(locale);
+}
+
+/**
+ * Fold the report into the segments the found-line renders.
+ *
+ * Formats that share a label are merged (an mbox and a loose `.eml` are both
+ * "mails"): showing "3,214 mails - 1 mails" would read as a bug, not as
+ * detail.
+ */
+export function summarizeExportPreview(
+ report: UltraWikiExportPreview,
+ t: (key: string) => string,
+): ExportSummarySegment[] {
+ const byLabel = new Map<string, ExportSummarySegment>();
+ for (const [format, row] of Object.entries(report.formats ?? {})) {
+ const items = Number(row?.items_estimate ?? 0);
+ if (items <= 0) continue;
+ const label = t(`ultrawiki.export.format_${format}`);
+ const existing = byLabel.get(label);
+ if (existing) {
+ existing.count += items;
+ existing.exact = existing.exact && row?.exact !== false;
+ continue;
+ }
+ byLabel.set(label, {
+ key: format,
+ label,
+ count: items,
+ exact: row?.exact !== false,
+ });
+ }
+ return [...byLabel.values()].sort((a, b) => b.count - a.count);
+}
+
+export function ExportPreview({
+ path,
+ onPathChange,
+}: {
+ path: string;
+ onPathChange: (path: string) => void;
+}): JSX.Element {
+ const t = useT();
+ const fileInput = useRef<HTMLInputElement | null>(null);
+ const [uploading, setUploading] = useState("");
+ const [uploaded, setUploaded] = useState("");
+ const [previewing, setPreviewing] = useState(false);
+ const [report, setReport] = useState<UltraWikiExportPreview | null>(null);
+ const [error, setError] = useState("");
+
+ const inputCls =
+ "w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/40";
+
+ async function handleUpload(file: File) {
+ setError("");
+ setReport(null);
+ setUploaded("");
+ setUploading(file.name);
+ try {
+ const result = await uploadUltraWikiExport(file);
+ onPathChange(result.path);
+ setUploaded(t("ultrawiki.export.uploaded").replace("{0}", result.name));
+ } catch (err) {
+ setError(
+ t("ultrawiki.export.upload_failed").replace(
+ "{0}",
+ (err as Error).message,
+ ),
+ );
+ } finally {
+ setUploading("");
+ if (fileInput.current) fileInput.current.value = "";
+ }
+ }
+
+ async function handlePreview() {
+ const target = path.trim();
+ if (!target) return;
+ setError("");
+ setPreviewing(true);
+ try {
+ setReport(await previewUltraWikiExport(target));
+ } catch (err) {
+ setReport(null);
+ setError(
+ t("ultrawiki.export.preview_failed").replace(
+ "{0}",
+ (err as Error).message,
+ ),
+ );
+ } finally {
+ setPreviewing(false);
+ }
+ }
+
+ return (
+ <div className="space-y-2" data-testid="ultrawiki-export-panel">
+ <label className="block">
+ <span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground">
+ {t("ultrawiki.export.path_label")}
+ </span>
+ <input
+ type="text"
+ value={path}
+ onChange={(e) => {
+ onPathChange(e.target.value);
+ setReport(null);
+ }}
+ className={inputCls}
+ data-testid="ultrawiki-export-path-input"
+ />
+ <span className="mt-1 block text-[11px] text-muted-foreground">
+ {t("ultrawiki.export.path_hint")}
+ </span>
+ </label>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <label
+ className="inline-flex cursor-pointer items-center gap-1.5 rounded-lg border border-border px-2.5 py-1.5 text-[11px] text-foreground hover:bg-secondary/30"
+ data-testid="ultrawiki-export-upload-label"
+ >
+ <FileUp className="h-3.5 w-3.5" aria-hidden />
+ {t("ultrawiki.export.upload_button")}
+ <input
+ ref={fileInput}
+ type="file"
+ className="sr-only"
+ data-testid="ultrawiki-export-upload-input"
+ aria-label={t("ultrawiki.export.upload_label")}
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) void handleUpload(file);
+ }}
+ />
+ </label>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => void handlePreview()}
+ disabled={previewing || !path.trim()}
+ data-testid="ultrawiki-export-preview"
+ >
+ {previewing ? (
+ <Loader2 className="mr-1 h-3.5 w-3.5 animate-spin" aria-hidden />
+ ) : (
+ <ScanSearch className="mr-1 h-3.5 w-3.5" aria-hidden />
+ )}
+ {t("ultrawiki.export.preview_button")}
+ </Button>
+ {uploading && (
+ <span
+ className="inline-flex items-center gap-1.5 text-[11px] text-muted-foreground"
+ data-testid="ultrawiki-export-uploading"
+ >
+ <Loader2 className="h-3 w-3 animate-spin" aria-hidden />
+ {t("ultrawiki.export.uploading").replace("{0}", uploading)}
+ </span>
+ )}
+ {!uploading && uploaded && (
+ <span
+ className="text-[11px] text-muted-foreground"
+ data-testid="ultrawiki-export-uploaded"
+ >
+ {uploaded}
+ </span>
+ )}
+ </div>
+
+ {error && (
+ <p
+ className="text-[11px] text-destructive"
+ role="alert"
+ data-testid="ultrawiki-export-error"
+ >
+ {error}
+ </p>
+ )}
+
+ {report && <ExportReport report={report} />}
+ </div>
+ );
+}
+
+function ExportReport({
+ report,
+}: {
+ report: UltraWikiExportPreview;
+}): JSX.Element {
+ const t = useT();
+ const count = counter(useUiLanguage());
+ const segments = summarizeExportPreview(report, t);
+ const extras: string[] = [];
+ if (report.unknown_files > 0) {
+ extras.push(
+ t("ultrawiki.export.unknown_skipped").replace(
+ "{0}",
+ count(report.unknown_files),
+ ),
+ );
+ }
+ if (report.unreadable.length > 0) {
+ extras.push(
+ t("ultrawiki.export.unreadable").replace(
+ "{0}",
+ count(report.unreadable.length),
+ ),
+ );
+ }
+ if (report.archives.files > 0) {
+ extras.push(
+ t("ultrawiki.export.archives")
+ .replace("{0}", count(report.archives.files))
+ .replace("{1}", count(report.archives.entries)),
+ );
+ }
+ extras.push(
+ t("ultrawiki.export.total_size").replace("{0}", formatBytes(report.total_bytes)),
+ );
+
+ return (
+ <div
+ className="rounded-lg border border-border bg-card/40 p-2.5"
+ data-testid="ultrawiki-export-report"
+ >
+ {segments.length === 0 ? (
+ <p className="text-[11px] text-muted-foreground">
+ {t("ultrawiki.export.nothing_found")}
+ </p>
+ ) : (
+ <p className="text-xs text-foreground">
+ <span className="text-muted-foreground">
+ {t("ultrawiki.export.found")}{" "}
+ </span>
+ {segments.map((segment, index) => (
+ <span key={segment.key} data-testid={`uw-export-count-${segment.key}`}>
+ {index > 0 && <span className="text-muted-foreground"> · </span>}
+ <span className="font-medium">
+ {segment.exact ? "" : "~"}
+ {count(segment.count)}
+ </span>{" "}
+ {segment.label}
+ </span>
+ ))}
+ </p>
+ )}
+ <p className="mt-1 text-[11px] text-muted-foreground">
+ {extras.join(" · ")}
+ </p>
+ {report.truncated && (
+ <p
+ className="mt-1 text-[11px] text-[#ffb84d]"
+ data-testid="ultrawiki-export-truncated"
+ >
+ {t("ultrawiki.export.truncated")}
+ </p>
+ )}
+ {report.notes.map((note) => (
+ <p key={note} className="mt-1 text-[11px] text-muted-foreground">
+ {note}
+ </p>
+ ))}
+ </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 ec191dbdc1..b4c143eb03 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.test.tsx
@@ -471,3 +471,136 @@ describe("SourcesPanel — bridge sources carry a real identity", () => {
});
});
});
+
+describe("SourcesPanel — the dropped-export add flow", () => {
+ function installExportPickerMock(
+ created: unknown[],
+ extra: Record<string, (init?: RequestInit) => unknown> = {},
+ ) {
+ return installFetchMock({
+ "/api/ultrawiki/areas": () => ({ areas: [], total: 0 }),
+ "/api/ultrawiki/connectors": () => ({
+ connectors: [
+ {
+ id: "export-import",
+ kind: "builtin",
+ label: "Export file import",
+ label_key: "ultrawiki.sources.connector_export_import",
+ brand: "archive",
+ status: "available",
+ description_key: "ultrawiki.connectors.export_import",
+ connector: "export-import",
+ integration_id: "",
+ },
+ ],
+ total: 1,
+ builtin: 1,
+ bridge: 0,
+ }),
+ "/api/ultrawiki/bridge/candidates": () => ({
+ candidates: [],
+ total: 0,
+ connected: 0,
+ }),
+ "/api/ultrawiki/sources": (init) => {
+ created.push(JSON.parse(String(init?.body ?? "{}")));
+ return { id: "src-export" };
+ },
+ ...extra,
+ });
+ }
+
+ it("swaps in the upload + preview controls when the export tile is picked", async () => {
+ installExportPickerMock([]);
+ renderWithClient(<SourcesPanel sources={[]} onChanged={vi.fn()} />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-add-source-toggle"));
+ await waitFor(() => {
+ expect(screen.getByTestId("uw-picker-export-import")).toBeDefined();
+ });
+ // A dropped export is not a vault root: the folder field must not appear.
+ expect(screen.queryByTestId("ultrawiki-export-panel")).toBeNull();
+
+ fireEvent.click(screen.getByTestId("uw-picker-export-import"));
+
+ expect(screen.getByTestId("ultrawiki-export-panel")).toBeDefined();
+ expect(screen.getByTestId("ultrawiki-export-upload-input")).toBeDefined();
+ expect(screen.getByTestId("ultrawiki-export-preview")).toBeDefined();
+ expect(screen.queryByTestId("ultrawiki-path-input")).toBeNull();
+ // Nothing can be registered until there is something to read.
+ expect(
+ screen.getByTestId("ultrawiki-create-source").hasAttribute("disabled"),
+ ).toBe(true);
+ });
+
+ it("shows the found-formats report before the source is created", async () => {
+ const created: unknown[] = [];
+ installExportPickerMock(created, {
+ "/api/ultrawiki/export/preview": () => ({
+ path: "/drop/takeout.zip",
+ exists: true,
+ is_dir: false,
+ formats: {
+ mbox: { files: 2, items_estimate: 3214, exact: true },
+ ics: { files: 1, items_estimate: 122, exact: true },
+ },
+ unknown: [{ extension: ".dll", files: 41 }],
+ unreadable: [],
+ archives: { files: 1, entries: 9, max_depth: 1, budget_exhausted: false },
+ total_bytes: 2048,
+ files_seen: 12,
+ items_estimate: 3336,
+ unknown_files: 41,
+ truncated: false,
+ notes: [],
+ }),
+ });
+ renderWithClient(<SourcesPanel sources={[]} onChanged={vi.fn()} />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-add-source-toggle"));
+ await waitFor(() => {
+ expect(screen.getByTestId("uw-picker-export-import")).toBeDefined();
+ });
+ fireEvent.click(screen.getByTestId("uw-picker-export-import"));
+ fireEvent.change(screen.getByTestId("ultrawiki-export-path-input"), {
+ target: { value: "/drop/takeout.zip" },
+ });
+ fireEvent.click(screen.getByTestId("ultrawiki-export-preview"));
+
+ await waitFor(() => {
+ expect(screen.getByTestId("ultrawiki-export-report")).toBeDefined();
+ });
+ const report = screen.getByTestId("ultrawiki-export-report");
+ expect(report.textContent).toContain("3,214 mails");
+ expect(report.textContent).toContain("122 calendar events");
+ expect(report.textContent).toContain("41 unrecognised files skipped");
+ // A preview registers nothing — consent still starts at the same gate.
+ expect(created).toHaveLength(0);
+ });
+
+ it("registers the source with the export path under its own config key", async () => {
+ const created: unknown[] = [];
+ installExportPickerMock(created);
+ renderWithClient(<SourcesPanel sources={[]} onChanged={vi.fn()} />);
+
+ fireEvent.click(screen.getByTestId("ultrawiki-add-source-toggle"));
+ await waitFor(() => {
+ expect(screen.getByTestId("uw-picker-export-import")).toBeDefined();
+ });
+ fireEvent.click(screen.getByTestId("uw-picker-export-import"));
+ fireEvent.change(screen.getByTestId("ultrawiki-export-path-input"), {
+ target: { value: "/drop/takeout.zip" },
+ });
+ fireEvent.click(screen.getByTestId("ultrawiki-create-source"));
+
+ await waitFor(() => {
+ expect(created).toHaveLength(1);
+ });
+ expect(created[0]).toMatchObject({
+ connector: "export-import",
+ label: "Export file",
+ // `path`, not `root`: an export file is not a folder to walk as a vault.
+ config: { path: "/drop/takeout.zip" },
+ });
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
index d708bb37a2..da95735c6d 100644
--- a/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/ultrawiki/SourcesPanel.tsx
@@ -20,6 +20,9 @@
* brand mark — plus a path field for the folder-shaped connectors and area
* assignment. A bridge source is named after the integration the user picked
* ("GitHub"), never after the generic bridge, so the list stays readable.
+ * Picking the dropped-export tile swaps that path field for `ExportPreview`,
+ * which can also upload the file and report what is inside it before the
+ * source exists — consent semantics are untouched either way.
*/
import { useState } from "react";
import {
@@ -46,6 +49,7 @@ import {
connectorLabel,
type ConnectorOption,
} from "@/components/ultrawiki/ConnectorPicker";
+import { ExportPreview } from "@/components/ultrawiki/ExportPreview";
import {
approveUltraWikiSource,
cancelUltraWikiJob,
@@ -59,6 +63,14 @@ import {
/** Connectors that read a user-chosen folder (config key `root`). */
const PATH_CONNECTORS: readonly string[] = ["obsidian-vault", "local-folder"];
+/**
+ * The dropped-export connector. It also takes a path, but under its own
+ * config key (`path`) and through its own control: an export needs to be
+ * uploaded and looked inside BEFORE it is registered, which a bare text field
+ * cannot do.
+ */
+const EXPORT_CONNECTOR = "export-import";
+
/** The generic integration gateway — its cards carry the integration's name. */
const BRIDGE_CONNECTOR = "plugin-bridge";
@@ -473,6 +485,7 @@ function AddSourceForm({
const [option, setOption] = useState<ConnectorOption | null>(null);
const [label, setLabel] = useState("");
const [rootPath, setRootPath] = useState("");
+ const [exportPath, setExportPath] = useState("");
const [selectedAreas, setSelectedAreas] = useState<string[]>([]);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState("");
@@ -484,6 +497,7 @@ function AddSourceForm({
});
const needsPath = Boolean(option && PATH_CONNECTORS.includes(option.connector));
+ const isExport = option?.connector === EXPORT_CONNECTOR;
// 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.
@@ -504,6 +518,7 @@ function AddSourceForm({
setError("");
const config: Record<string, unknown> = {};
if (needsPath && rootPath.trim()) config.root = rootPath.trim();
+ if (isExport && exportPath.trim()) config.path = exportPath.trim();
if (option.connector === BRIDGE_CONNECTOR && option.integrationId) {
config.integration_id = option.integrationId;
}
@@ -548,10 +563,12 @@ function AddSourceForm({
selectedKey={option?.key ?? ""}
onSelect={(picked) => {
setOption(picked);
- // The path belongs to the folder connector it was typed for;
- // carrying it over to a different source type would silently point
- // the new one at an unrelated folder.
+ // A path belongs to the connector it was typed for; carrying it
+ // over to a different source type would silently point the new one
+ // at an unrelated folder. The two path kinds are kept apart for
+ // the same reason — an export file is not a vault root.
if (!PATH_CONNECTORS.includes(picked.connector)) setRootPath("");
+ if (picked.connector !== EXPORT_CONNECTOR) setExportPath("");
}}
/>
</div>
@@ -590,6 +607,10 @@ function AddSourceForm({
</label>
)}
+ {isExport && (
+ <ExportPreview path={exportPath} onPathChange={setExportPath} />
+ )}
+
<div>
<span className="mb-1.5 block text-[10px] uppercase tracking-wider text-muted-foreground">
{t("ultrawiki.sources.areas_label")}
@@ -635,7 +656,12 @@ function AddSourceForm({
<Button
size="sm"
type="submit"
- disabled={submitting || !option || (needsPath && !rootPath.trim())}
+ disabled={
+ submitting ||
+ !option ||
+ (needsPath && !rootPath.trim()) ||
+ (isExport && !exportPath.trim())
+ }
data-testid="ultrawiki-create-source"
>
{submitting && (
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 063b9e8f46..892f256d35 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2710,38 +2710,38 @@
"result_error": "Discord nicht erreichbar, bitte später erneut versuchen."
},
"ultrawiki": {
- "explore": {
- "tab": "Entdecken",
- "loading": "Wissensbestand wird gelesen …",
- "error": "Der Wissensbestand konnte nicht gelesen werden.",
- "entities_title": "Begriffe",
- "entities_count": "{0} Begriffe",
- "moments_title": "Momente",
- "moments_count": "{0} Momente",
- "graph_title": "Verbindungen",
- "search_placeholder": "Begriff suchen …",
- "no_search_hits": "Kein Begriff passt zu „{0}“.",
- "mentions": "{0}×",
- "mentions_long": "{0} Erwähnungen",
- "period": "{0} bis {1}",
- "neighbors": "Taucht auf mit",
- "no_neighbors": "Kommt bisher immer allein vor.",
- "shared": "{0} gemeinsame Momente",
- "back": "Zurück zur Übersicht",
- "open_source": "Beleg öffnen",
- "source_prefix": "aus",
- "min_mentions": "Ab {0} Erwähnungen",
- "graph_shown": "{0} von {1} Begriffen",
- "graph_hint": "Weniger häufige Begriffe sind ausgeblendet — Regler nach links für alle.",
- "graph_empty": "Kein Begriff wird oft genug erwähnt. Stell den Regler auf 1.",
- "moments_of": "Momente mit {0}",
- "empty": {
- "no_sources": "Es ist noch keine Quelle verbunden. Verbinde zuerst eine Quelle, dann kann Jarvis etwas wissen.",
- "nothing_imported": "Eine Quelle ist verbunden, aber es wurde noch nichts geholt. Starte den Import bei den Quellen.",
- "nothing_distilled": "Es liegen Einträge da, aber noch keiner wurde ausgewertet. Dafür braucht es ein eingerichtetes Sprachmodell in den Einstellungen.",
- "no_entities": "Die Einträge wurden ausgewertet, aber es kamen keine Namen oder Orte darin vor. Die Momente unten kannst du trotzdem durchblättern."
- }
- },
+ "explore": {
+ "tab": "Entdecken",
+ "loading": "Wissensbestand wird gelesen …",
+ "error": "Der Wissensbestand konnte nicht gelesen werden.",
+ "entities_title": "Begriffe",
+ "entities_count": "{0} Begriffe",
+ "moments_title": "Momente",
+ "moments_count": "{0} Momente",
+ "graph_title": "Verbindungen",
+ "search_placeholder": "Begriff suchen …",
+ "no_search_hits": "Kein Begriff passt zu „{0}“.",
+ "mentions": "{0}×",
+ "mentions_long": "{0} Erwähnungen",
+ "period": "{0} bis {1}",
+ "neighbors": "Taucht auf mit",
+ "no_neighbors": "Kommt bisher immer allein vor.",
+ "shared": "{0} gemeinsame Momente",
+ "back": "Zurück zur Übersicht",
+ "open_source": "Beleg öffnen",
+ "source_prefix": "aus",
+ "min_mentions": "Ab {0} Erwähnungen",
+ "graph_shown": "{0} von {1} Begriffen",
+ "graph_hint": "Weniger häufige Begriffe sind ausgeblendet — Regler nach links für alle.",
+ "graph_empty": "Kein Begriff wird oft genug erwähnt. Stell den Regler auf 1.",
+ "moments_of": "Momente mit {0}",
+ "empty": {
+ "no_sources": "Es ist noch keine Quelle verbunden. Verbinde zuerst eine Quelle, dann kann Jarvis etwas wissen.",
+ "nothing_imported": "Eine Quelle ist verbunden, aber es wurde noch nichts geholt. Starte den Import bei den Quellen.",
+ "nothing_distilled": "Es liegen Einträge da, aber noch keiner wurde ausgewertet. Dafür braucht es ein eingerichtetes Sprachmodell in den Einstellungen.",
+ "no_entities": "Die Einträge wurden ausgewertet, aber es kamen keine Namen oder Orte darin vor. Die Momente unten kannst du trotzdem durchblättern."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
@@ -2764,27 +2764,31 @@
"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",
"tab_contents": "Inhalte",
- "tab_check": "Prüfen"
+ "tab_check": "Prüfen",
+ "tab_overview": "Überblick",
+ "header_subtitle": "{0} Einträge aus {1} Quelle(n)"
},
"progress": {
"title": "Import-Pipeline",
- "stage_captured": "Erfasst",
- "stage_keyword_indexed": "Stichwort-durchsuchbar",
- "stage_embedded": "Eingebettet",
- "stage_distilled": "Destilliert",
- "stage_failed": "Fehlgeschlagen",
+ "stage_captured": "Wartet auf Indexierung",
+ "stage_keyword_indexed": "Wartet auf die Bedeutungssuche",
+ "stage_embedded": "Wartet auf eine Zusammenfassung",
+ "stage_distilled": "Fertig verarbeitet",
+ "stage_failed": "Nicht verarbeitbar",
"pipeline_running": "Pipeline läuft",
"pipeline_idle": "Pipeline wartet",
"cancel": "Abbrechen",
"cancel_failed": "Job konnte nicht abgebrochen werden: {0}",
- "retry_failed": "Fehlgeschlagene erneut versuchen",
+ "retry_failed": "{0} fehlgeschlagene erneut versuchen",
"retry_failed_done": "{0} Eintrag/Einträge erneut eingereiht - sie machen an ihrer letzten fertigen Stufe weiter.",
"retry_failed_error": "Neuversuch konnte nicht starten: {0}",
"state_waiting_for_sources": "Wartet auf freigegebene Quellen — es wird noch nichts gelesen.",
- "state_processing": "Verarbeitet ({0} offen)",
+ "state_processing": "Arbeitet — noch {0}",
"state_paused": "Pausiert",
"state_idle": "Bereit — alles verarbeitet",
- "open_sources": "Quellen öffnen"
+ "open_sources": "Quellen öffnen",
+ "stored": "gespeichert",
+ "searchable": "durchsuchbar"
},
"sources": {
"title": "Verbundene Quellen",
@@ -2823,6 +2827,7 @@
"connector_local_folder": "Lokaler Ordner",
"connector_conversations": "Unterhaltungen mit {name}",
"connector_normal_wiki": "Eingebautes Wiki",
+ "connector_export_import": "Exportdatei",
"connector_plugin_bridge": "Verbundene Integration (Plugins / MCP)",
"approve_import": "Freigeben & alles importieren",
"import_started": "Import gestartet – alles, was diese Quelle enthält, wird kopiert.",
@@ -3009,7 +3014,8 @@
"action_sync_all": "Jetzt importieren",
"action_open_sources": "Quellen öffnen",
"action_open_settings": "Einstellungen öffnen",
- "action_enable_mode": "Einschalten"
+ "action_enable_mode": "Einschalten",
+ "action_unknown": "Diese Version kennt diese Aktion noch nicht."
},
"connectors": {
"obsidian_vault": "Jede Notiz in einem Obsidian-Tresor auf diesem Gerät.",
@@ -3029,7 +3035,40 @@
"dropbox": "Dokumente und Dateien in Dropbox.",
"airtable": "Datensätze aus deinen Bases und Tabellen.",
"discord": "Nachrichten aus den Servern und Kanälen, denen du folgst.",
- "telegram": "Nachrichten aus deinen Chats und Kanälen."
+ "telegram": "Nachrichten aus deinen Chats und Kanälen.",
+ "export_import": "Jeder Export, den du schon hast – Takeout, WhatsApp-Chats, Mail-Archive, PDFs."
+ },
+ "export": {
+ "path_label": "Exportdatei oder -ordner",
+ "path_hint": "Ein Pfad auf diesem Gerät. Lade die Datei unten hoch, wenn sie noch nicht hier liegt.",
+ "upload_label": "Oder von hier aus hochladen",
+ "upload_button": "Datei auswählen",
+ "uploading": "{0} wird hochgeladen …",
+ "uploaded": "{0} hochgeladen.",
+ "upload_failed": "Der Upload ist fehlgeschlagen: {0}",
+ "preview_button": "Nachsehen, was drin ist",
+ "previewing": "Wird durchgesehen …",
+ "preview_failed": "Dieser Pfad konnte nicht gelesen werden: {0}",
+ "found": "Gefunden:",
+ "nothing_found": "Unter diesem Pfad wurde nichts Importierbares gefunden.",
+ "unknown_skipped": "{0} nicht erkannte Dateien übersprungen",
+ "unreadable": "{0} Dateien konnten nicht gelesen werden",
+ "archives": "{0} Archive ({1} Einträge)",
+ "total_size": "{0} insgesamt",
+ "truncated": "Das ist ein großer Datenbestand, die Zahlen sind daher eine Untergrenze – der Import selbst liest alles.",
+ "format_mbox": "E-Mails",
+ "format_eml": "E-Mails",
+ "format_ics": "Kalendertermine",
+ "format_vcard": "Kontakte",
+ "format_whatsapp": "Chat-Tage",
+ "format_csv": "Tabellenabschnitte",
+ "format_tsv": "Tabellenabschnitte",
+ "format_jsonl": "Datensatzabschnitte",
+ "format_json": "Datendateien",
+ "format_pdf": "PDF-Dokumente",
+ "format_html": "Webseiten",
+ "format_markdown": "Notizen",
+ "format_text": "Textdateien"
},
"picker": {
"builtin_group": "Auf diesem Gerät",
@@ -3063,6 +3102,50 @@
"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"
+ },
+ "overview": {
+ "eyebrow_verdict": "Kann ich es nutzen?",
+ "eyebrow_sources": "Woher es kommt",
+ "eyebrow_activity": "Was passiert ist",
+ "eyebrow_problems": "Braucht dich",
+ "headline_done": "Bereit für Fragen.",
+ "headline_working": "Bereit für Fragen — und füllt sich noch.",
+ "headline_stalled": "Bereit für Fragen, aber die Warteschlange steht.",
+ "headline_notready": "Noch nicht bereit für Fragen.",
+ "headline_empty": "Noch nichts gespeichert.",
+ "detail_done": "Alle {0} Einträge sind durchsuchbar und zusammengefasst.",
+ "detail_working": "{0} von {1} werden noch {2}. Alles andere ist schon durchsuchbar — du musst nicht warten.",
+ "detail_stalled": "{0} von {1} werden noch {2} — aber im Moment arbeitet nichts daran.",
+ "detail_notready": "Unten muss erst etwas geklärt werden, bevor Fragen beantwortet werden können. Die Liste darunter sagt, was.",
+ "detail_empty": "Füge eine Quelle hinzu, dann landen ihre Inhalte hier. Gelesen wird nichts, bevor du es erlaubst.",
+ "step_indexing": "indexiert",
+ "step_embedding": "für die Bedeutungssuche vorbereitet",
+ "step_summarising": "zusammengefasst",
+ "step_processing": "verarbeitet",
+ "items_label": "Einträge",
+ "band_summarised": "zusammengefasst",
+ "band_usable": "durchsuchbar, noch in Arbeit",
+ "band_arriving": "gerade angekommen",
+ "band_failed": "nicht verarbeitbar",
+ "manage_sources": "Quellen verwalten",
+ "no_sources": "Es ist noch nichts verbunden, also gibt es nichts zu lesen.",
+ "add_first_source": "Erste Quelle hinzufügen",
+ "import_now": "Jetzt importieren",
+ "import_started": "Import von {0} läuft.",
+ "row_read": "Zuletzt gelesen {0}",
+ "row_importing": "Wird gerade importiert",
+ "row_pending": "Wartet auf deine Freigabe — vorher wird nichts gelesen",
+ "row_never": "Freigegeben, aber noch nie gelesen",
+ "row_empty": "Erfolgreich gelesen, hat aber nichts geliefert",
+ "activity_empty": "Noch keine Importe. Der erste erscheint hier, sobald er läuft.",
+ "activity_note": "Von vor dem letzten Start der App bleibt pro Quelle nur der jüngste Lauf erhalten.",
+ "act_new": "+{0} neu",
+ "act_changed": "{0} geändert",
+ "act_unchanged": "{0} unverändert",
+ "act_running": "läuft",
+ "no_problems": "Nichts braucht deine Aufmerksamkeit.",
+ "all_checks": "Alle Prüfungen",
+ "waiting": "Warte auf die Antwort des Wissensspeichers…"
}
},
"edit_menu": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index ec4e0a0814..7a2cb2473d 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2711,38 +2711,38 @@
"result_error": "Couldn't reach Discord, please try again later."
},
"ultrawiki": {
- "explore": {
- "tab": "Explore",
- "loading": "Reading the knowledge base …",
- "error": "The knowledge base could not be read.",
- "entities_title": "Topics",
- "entities_count": "{0} topics",
- "moments_title": "Moments",
- "moments_count": "{0} moments",
- "graph_title": "Connections",
- "search_placeholder": "Search a topic …",
- "no_search_hits": "No topic matches “{0}”.",
- "mentions": "{0}×",
- "mentions_long": "{0} mentions",
- "period": "{0} to {1}",
- "neighbors": "Appears with",
- "no_neighbors": "Has only ever appeared on its own.",
- "shared": "{0} shared moments",
- "back": "Back to the overview",
- "open_source": "Open the evidence",
- "source_prefix": "from",
- "min_mentions": "From {0} mentions",
- "graph_shown": "{0} of {1} topics",
- "graph_hint": "Rarer topics are hidden — move the slider left to show all.",
- "graph_empty": "No topic is mentioned often enough. Set the slider to 1.",
- "moments_of": "Moments involving {0}",
- "empty": {
- "no_sources": "No source is connected yet. Connect one first, then Jarvis has something to know.",
- "nothing_imported": "A source is connected but nothing has been fetched yet. Start the import under Sources.",
- "nothing_distilled": "Entries are stored but none has been analysed yet. That needs a language model configured in the settings.",
- "no_entities": "The entries were analysed but named no people or places. You can still browse the moments below."
- }
- },
+ "explore": {
+ "tab": "Explore",
+ "loading": "Reading the knowledge base …",
+ "error": "The knowledge base could not be read.",
+ "entities_title": "Topics",
+ "entities_count": "{0} topics",
+ "moments_title": "Moments",
+ "moments_count": "{0} moments",
+ "graph_title": "Connections",
+ "search_placeholder": "Search a topic …",
+ "no_search_hits": "No topic matches “{0}”.",
+ "mentions": "{0}×",
+ "mentions_long": "{0} mentions",
+ "period": "{0} to {1}",
+ "neighbors": "Appears with",
+ "no_neighbors": "Has only ever appeared on its own.",
+ "shared": "{0} shared moments",
+ "back": "Back to the overview",
+ "open_source": "Open the evidence",
+ "source_prefix": "from",
+ "min_mentions": "From {0} mentions",
+ "graph_shown": "{0} of {1} topics",
+ "graph_hint": "Rarer topics are hidden — move the slider left to show all.",
+ "graph_empty": "No topic is mentioned often enough. Set the slider to 1.",
+ "moments_of": "Moments involving {0}",
+ "empty": {
+ "no_sources": "No source is connected yet. Connect one first, then Jarvis has something to know.",
+ "nothing_imported": "A source is connected but nothing has been fetched yet. Start the import under Sources.",
+ "nothing_distilled": "Entries are stored but none has been analysed yet. That needs a language model configured in the settings.",
+ "no_entities": "The entries were analysed but named no people or places. You can still browse the moments below."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
@@ -2765,27 +2765,31 @@
"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",
"tab_contents": "Contents",
- "tab_check": "Check"
+ "tab_check": "Check",
+ "tab_overview": "Overview",
+ "header_subtitle": "{0} items from {1} source(s)"
},
"progress": {
"title": "Import pipeline",
- "stage_captured": "Captured",
- "stage_keyword_indexed": "Keyword-searchable",
- "stage_embedded": "Embedded",
- "stage_distilled": "Distilled",
- "stage_failed": "Failed",
+ "stage_captured": "Waiting to be indexed",
+ "stage_keyword_indexed": "Waiting for meaning search",
+ "stage_embedded": "Waiting for a summary",
+ "stage_distilled": "Fully processed",
+ "stage_failed": "Could not be processed",
"pipeline_running": "Pipeline running",
"pipeline_idle": "Pipeline idle",
"cancel": "Cancel",
"cancel_failed": "Could not cancel the job: {0}",
- "retry_failed": "Retry failed items",
+ "retry_failed": "Retry {0} failed",
"retry_failed_done": "{0} item(s) queued again - they resume from their last completed stage.",
"retry_failed_error": "Retry did not start: {0}",
"state_waiting_for_sources": "Waiting for approved sources — nothing is being read yet.",
- "state_processing": "Processing ({0} pending)",
+ "state_processing": "Working — {0} left",
"state_paused": "Paused",
"state_idle": "Idle — everything is processed",
- "open_sources": "Open Sources"
+ "open_sources": "Open Sources",
+ "stored": "stored",
+ "searchable": "searchable"
},
"sources": {
"title": "Connected sources",
@@ -2824,6 +2828,7 @@
"connector_local_folder": "Local folder",
"connector_conversations": "Conversations with {name}",
"connector_normal_wiki": "Built-in wiki",
+ "connector_export_import": "Export file",
"connector_plugin_bridge": "Connected integration (plugins / MCP)",
"approve_import": "Approve & import everything",
"import_started": "Import started - everything this source holds is being copied in.",
@@ -3010,7 +3015,8 @@
"action_sync_all": "Import now",
"action_open_sources": "Open sources",
"action_open_settings": "Open settings",
- "action_enable_mode": "Turn on"
+ "action_enable_mode": "Turn on",
+ "action_unknown": "This build does not know that action yet."
},
"connectors": {
"obsidian_vault": "Every note in an Obsidian vault on this machine.",
@@ -3030,7 +3036,40 @@
"dropbox": "Documents and files kept in Dropbox.",
"airtable": "Records from your bases and tables.",
"discord": "Messages from the servers and channels you follow.",
- "telegram": "Messages from your chats and channels."
+ "telegram": "Messages from your chats and channels.",
+ "export_import": "Any export you already have - Takeout, WhatsApp chats, mail archives, PDFs."
+ },
+ "export": {
+ "path_label": "Export file or folder",
+ "path_hint": "A path on this machine. Upload the file below if it is not here yet.",
+ "upload_label": "Or upload it from here",
+ "upload_button": "Choose a file",
+ "uploading": "Uploading {0}...",
+ "uploaded": "Uploaded {0}.",
+ "upload_failed": "The upload failed: {0}",
+ "preview_button": "See what is in it",
+ "previewing": "Looking through it...",
+ "preview_failed": "That path could not be read: {0}",
+ "found": "Found:",
+ "nothing_found": "Nothing importable was found at that path.",
+ "unknown_skipped": "{0} unrecognised files skipped",
+ "unreadable": "{0} files could not be read",
+ "archives": "{0} archives ({1} entries)",
+ "total_size": "{0} in total",
+ "truncated": "This is a large drop, so the numbers are a lower bound - the import itself reads everything.",
+ "format_mbox": "mails",
+ "format_eml": "mails",
+ "format_ics": "calendar events",
+ "format_vcard": "contacts",
+ "format_whatsapp": "chat days",
+ "format_csv": "table chunks",
+ "format_tsv": "table chunks",
+ "format_jsonl": "record chunks",
+ "format_json": "data files",
+ "format_pdf": "PDF documents",
+ "format_html": "web pages",
+ "format_markdown": "notes",
+ "format_text": "text files"
},
"picker": {
"builtin_group": "On this machine",
@@ -3064,6 +3103,50 @@
"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"
+ },
+ "overview": {
+ "eyebrow_verdict": "Can I use it?",
+ "eyebrow_sources": "Where it comes from",
+ "eyebrow_activity": "What happened",
+ "eyebrow_problems": "Needs you",
+ "headline_done": "Ready to answer.",
+ "headline_working": "Ready to answer — and still filling up.",
+ "headline_stalled": "Ready to answer, but the queue is standing still.",
+ "headline_notready": "Not ready to answer yet.",
+ "headline_empty": "Nothing stored yet.",
+ "detail_done": "All {0} items are searchable and summarised.",
+ "detail_working": "{0} of {1} are still {2}. Everything else can be searched right now — you do not have to wait.",
+ "detail_stalled": "{0} of {1} are still {2} — but nothing is processing them right now.",
+ "detail_notready": "Something below has to be sorted out before questions can be answered. The list underneath says what.",
+ "detail_empty": "Add a source and its contents land here. Nothing is read before you approve it.",
+ "step_indexing": "being indexed",
+ "step_embedding": "being prepared for meaning search",
+ "step_summarising": "being summarised",
+ "step_processing": "being processed",
+ "items_label": "items",
+ "band_summarised": "summarised",
+ "band_usable": "searchable, still working",
+ "band_arriving": "just arrived",
+ "band_failed": "could not be processed",
+ "manage_sources": "Manage sources",
+ "no_sources": "Nothing is connected yet, so there is nothing to read from.",
+ "add_first_source": "Add your first source",
+ "import_now": "Import now",
+ "import_started": "Importing from {0}.",
+ "row_read": "Last read {0}",
+ "row_importing": "Importing right now",
+ "row_pending": "Waiting for your approval — nothing is read until then",
+ "row_never": "Approved, but never read yet",
+ "row_empty": "Read successfully, but it delivered nothing",
+ "activity_empty": "No imports yet. The first one shows up here the moment it runs.",
+ "activity_note": "From before the last app start, only the most recent run per source is kept.",
+ "act_new": "+{0} new",
+ "act_changed": "{0} changed",
+ "act_unchanged": "{0} unchanged",
+ "act_running": "running",
+ "no_problems": "Nothing needs your attention.",
+ "all_checks": "All checks",
+ "waiting": "Waiting for the knowledge base to answer…"
}
},
"edit_menu": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 6f3860527f..58f9ff0e6f 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2710,38 +2710,38 @@
"result_error": "No se pudo llegar a Discord, inténtalo de nuevo más tarde."
},
"ultrawiki": {
- "explore": {
- "tab": "Explorar",
- "loading": "Leyendo la base de conocimiento …",
- "error": "No se pudo leer la base de conocimiento.",
- "entities_title": "Temas",
- "entities_count": "{0} temas",
- "moments_title": "Momentos",
- "moments_count": "{0} momentos",
- "graph_title": "Conexiones",
- "search_placeholder": "Buscar un tema …",
- "no_search_hits": "Ningún tema coincide con «{0}».",
- "mentions": "{0}×",
- "mentions_long": "{0} menciones",
- "period": "{0} a {1}",
- "neighbors": "Aparece junto a",
- "no_neighbors": "Hasta ahora siempre aparece solo.",
- "shared": "{0} momentos compartidos",
- "back": "Volver al resumen",
- "open_source": "Abrir la evidencia",
- "source_prefix": "de",
- "min_mentions": "Desde {0} menciones",
- "graph_shown": "{0} de {1} temas",
- "graph_hint": "Los temas menos frecuentes están ocultos: mueve el control a la izquierda para verlos todos.",
- "graph_empty": "Ningún tema se menciona lo suficiente. Pon el control en 1.",
- "moments_of": "Momentos con {0}",
- "empty": {
- "no_sources": "Todavía no hay ninguna fuente conectada. Conecta una primero y Jarvis tendrá algo que saber.",
- "nothing_imported": "Hay una fuente conectada pero aún no se ha traído nada. Inicia la importación en Fuentes.",
- "nothing_distilled": "Hay entradas guardadas pero ninguna se ha analizado todavía. Para eso hace falta un modelo de lenguaje configurado en los ajustes.",
- "no_entities": "Las entradas se analizaron pero no mencionaron personas ni lugares. Aun así puedes hojear los momentos de abajo."
- }
- },
+ "explore": {
+ "tab": "Explorar",
+ "loading": "Leyendo la base de conocimiento …",
+ "error": "No se pudo leer la base de conocimiento.",
+ "entities_title": "Temas",
+ "entities_count": "{0} temas",
+ "moments_title": "Momentos",
+ "moments_count": "{0} momentos",
+ "graph_title": "Conexiones",
+ "search_placeholder": "Buscar un tema …",
+ "no_search_hits": "Ningún tema coincide con «{0}».",
+ "mentions": "{0}×",
+ "mentions_long": "{0} menciones",
+ "period": "{0} a {1}",
+ "neighbors": "Aparece junto a",
+ "no_neighbors": "Hasta ahora siempre aparece solo.",
+ "shared": "{0} momentos compartidos",
+ "back": "Volver al resumen",
+ "open_source": "Abrir la evidencia",
+ "source_prefix": "de",
+ "min_mentions": "Desde {0} menciones",
+ "graph_shown": "{0} de {1} temas",
+ "graph_hint": "Los temas menos frecuentes están ocultos: mueve el control a la izquierda para verlos todos.",
+ "graph_empty": "Ningún tema se menciona lo suficiente. Pon el control en 1.",
+ "moments_of": "Momentos con {0}",
+ "empty": {
+ "no_sources": "Todavía no hay ninguna fuente conectada. Conecta una primero y Jarvis tendrá algo que saber.",
+ "nothing_imported": "Hay una fuente conectada pero aún no se ha traído nada. Inicia la importación en Fuentes.",
+ "nothing_distilled": "Hay entradas guardadas pero ninguna se ha analizado todavía. Para eso hace falta un modelo de lenguaje configurado en los ajustes.",
+ "no_entities": "Las entradas se analizaron pero no mencionaron personas ni lugares. Aun así puedes hojear los momentos de abajo."
+ }
+ },
"mode": {
"normal": "Normal",
"ultra": "Ultra",
@@ -2764,27 +2764,31 @@
"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",
"tab_contents": "Contenido",
- "tab_check": "Comprobar"
+ "tab_check": "Comprobar",
+ "tab_overview": "Resumen",
+ "header_subtitle": "{0} elementos de {1} fuente(s)"
},
"progress": {
"title": "Canal de importación",
- "stage_captured": "Capturado",
- "stage_keyword_indexed": "Buscable por palabras clave",
- "stage_embedded": "Con embeddings",
- "stage_distilled": "Destilado",
- "stage_failed": "Fallido",
+ "stage_captured": "Esperando indexación",
+ "stage_keyword_indexed": "Esperando la búsqueda por significado",
+ "stage_embedded": "Esperando un resumen",
+ "stage_distilled": "Totalmente procesado",
+ "stage_failed": "No se pudo procesar",
"pipeline_running": "Canal en marcha",
"pipeline_idle": "Canal en espera",
"cancel": "Cancelar",
"cancel_failed": "No se pudo cancelar el trabajo: {0}",
- "retry_failed": "Reintentar elementos fallidos",
+ "retry_failed": "Reintentar {0} fallidos",
"retry_failed_done": "{0} elemento(s) en cola de nuevo - continúan desde su última etapa completada.",
"retry_failed_error": "El reintento no pudo iniciarse: {0}",
"state_waiting_for_sources": "Esperando fuentes aprobadas: todavía no se lee nada.",
- "state_processing": "Procesando ({0} pendientes)",
+ "state_processing": "Trabajando: quedan {0}",
"state_paused": "En pausa",
"state_idle": "Inactivo: todo está procesado",
- "open_sources": "Abrir Fuentes"
+ "open_sources": "Abrir Fuentes",
+ "stored": "guardados",
+ "searchable": "buscables"
},
"sources": {
"title": "Fuentes conectadas",
@@ -2823,6 +2827,7 @@
"connector_local_folder": "Carpeta local",
"connector_conversations": "Conversaciones con {name}",
"connector_normal_wiki": "Wiki integrado",
+ "connector_export_import": "Archivo de exportación",
"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.",
@@ -3009,7 +3014,8 @@
"action_sync_all": "Importar ahora",
"action_open_sources": "Abrir fuentes",
"action_open_settings": "Abrir ajustes",
- "action_enable_mode": "Activar"
+ "action_enable_mode": "Activar",
+ "action_unknown": "Esta versión aún no conoce esa acción."
},
"connectors": {
"obsidian_vault": "Cada nota de un almacén de Obsidian en este equipo.",
@@ -3029,7 +3035,40 @@
"dropbox": "Documentos y archivos guardados en Dropbox.",
"airtable": "Registros de tus bases y tablas.",
"discord": "Mensajes de los servidores y canales que sigues.",
- "telegram": "Mensajes de tus chats y canales."
+ "telegram": "Mensajes de tus chats y canales.",
+ "export_import": "Cualquier exportación que ya tengas: Takeout, chats de WhatsApp, archivos de correo, PDF."
+ },
+ "export": {
+ "path_label": "Archivo o carpeta de exportación",
+ "path_hint": "Una ruta de este equipo. Sube el archivo abajo si todavía no está aquí.",
+ "upload_label": "O súbelo desde aquí",
+ "upload_button": "Elegir un archivo",
+ "uploading": "Subiendo {0}…",
+ "uploaded": "{0} subido.",
+ "upload_failed": "La subida ha fallado: {0}",
+ "preview_button": "Ver qué contiene",
+ "previewing": "Revisando el contenido…",
+ "preview_failed": "No se ha podido leer esa ruta: {0}",
+ "found": "Encontrado:",
+ "nothing_found": "No se ha encontrado nada importable en esa ruta.",
+ "unknown_skipped": "{0} archivos no reconocidos omitidos",
+ "unreadable": "{0} archivos no se han podido leer",
+ "archives": "{0} archivos comprimidos ({1} entradas)",
+ "total_size": "{0} en total",
+ "truncated": "Es un conjunto grande, así que las cifras son un mínimo: la importación en sí lo lee todo.",
+ "format_mbox": "correos",
+ "format_eml": "correos",
+ "format_ics": "eventos de calendario",
+ "format_vcard": "contactos",
+ "format_whatsapp": "días de chat",
+ "format_csv": "bloques de tabla",
+ "format_tsv": "bloques de tabla",
+ "format_jsonl": "bloques de registros",
+ "format_json": "archivos de datos",
+ "format_pdf": "documentos PDF",
+ "format_html": "páginas web",
+ "format_markdown": "notas",
+ "format_text": "archivos de texto"
},
"picker": {
"builtin_group": "En este equipo",
@@ -3063,6 +3102,50 @@
"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"
+ },
+ "overview": {
+ "eyebrow_verdict": "¿Puedo usarlo?",
+ "eyebrow_sources": "De dónde viene",
+ "eyebrow_activity": "Qué ha pasado",
+ "eyebrow_problems": "Necesita tu atención",
+ "headline_done": "Listo para responder.",
+ "headline_working": "Listo para responder, y todavía llenándose.",
+ "headline_stalled": "Listo para responder, pero la cola está parada.",
+ "headline_notready": "Todavía no puede responder.",
+ "headline_empty": "Aún no hay nada guardado.",
+ "detail_done": "Los {0} elementos son buscables y están resumidos.",
+ "detail_working": "{0} de {1} siguen {2}. Todo lo demás ya se puede buscar: no hace falta esperar.",
+ "detail_stalled": "{0} de {1} siguen {2}, pero ahora mismo nada los está procesando.",
+ "detail_notready": "Hay algo que resolver antes de poder responder preguntas. La lista de abajo dice qué.",
+ "detail_empty": "Añade una fuente y su contenido aparecerá aquí. Nada se lee antes de que lo apruebes.",
+ "step_indexing": "siendo indexados",
+ "step_embedding": "preparándose para la búsqueda por significado",
+ "step_summarising": "siendo resumidos",
+ "step_processing": "siendo procesados",
+ "items_label": "elementos",
+ "band_summarised": "resumidos",
+ "band_usable": "buscables, aún en proceso",
+ "band_arriving": "recién llegados",
+ "band_failed": "no se pudieron procesar",
+ "manage_sources": "Gestionar fuentes",
+ "no_sources": "Todavía no hay nada conectado, así que no hay de dónde leer.",
+ "add_first_source": "Añade tu primera fuente",
+ "import_now": "Importar ahora",
+ "import_started": "Importando desde {0}.",
+ "row_read": "Leída {0}",
+ "row_importing": "Importando ahora mismo",
+ "row_pending": "Esperando tu aprobación: hasta entonces no se lee nada",
+ "row_never": "Aprobada, pero nunca leída",
+ "row_empty": "Se leyó correctamente, pero no aportó nada",
+ "activity_empty": "Todavía no hay importaciones. La primera aparecerá aquí en cuanto se ejecute.",
+ "activity_note": "De antes del último arranque de la app solo se conserva la ejecución más reciente de cada fuente.",
+ "act_new": "+{0} nuevos",
+ "act_changed": "{0} cambiados",
+ "act_unchanged": "{0} sin cambios",
+ "act_running": "en curso",
+ "no_problems": "No hay nada que necesite tu atención.",
+ "all_checks": "Todas las comprobaciones",
+ "waiting": "Esperando la respuesta de la base de conocimiento…"
}
},
"edit_menu": {
diff --git a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
index f59abf38e1..7110f96b6a 100644
--- a/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/ultrawikiApi.ts
@@ -55,6 +55,7 @@ export const ULTRAWIKI_CONNECTOR_IDS = [
"local-folder",
"jarvis-conversations",
"normal-wiki",
+ "export-import",
"plugin-bridge",
] as const;
export type UltraWikiConnectorId = (typeof ULTRAWIKI_CONNECTOR_IDS)[number];
@@ -81,6 +82,7 @@ export const ULTRAWIKI_NEUTRAL_BRANDS = [
"folder",
"chat",
"wiki",
+ "archive",
] as const;
export type UltraWikiNeutralBrand =
(typeof ULTRAWIKI_NEUTRAL_BRANDS)[number];
@@ -331,6 +333,37 @@ export const ULTRAWIKI_PIPELINE_STATES: readonly UltraWikiPipelineState[] = [
"paused",
];
+/**
+ * Mirrors jarvis/ultrawiki/progress.py — the ONE cumulative reading of the
+ * corpus, computed in Python and never re-derived here.
+ *
+ * The counts it is built from are mutually exclusive buckets (an item sits in
+ * exactly one `state`). Adding them up in the client is what produced
+ * "Keyword-searchable 0" on a corpus where every item was keyword-searchable,
+ * and a checklist that reported "Everything is processed" over an import
+ * strip reporting 3 237 pending. Read these fields; do not recompute them.
+ */
+export interface UltraWikiProgress {
+ state: "empty" | "working" | "done";
+ /** Every live item, whatever stage it is in. */
+ total: number;
+ /** Items proven past the keyword index — findable by exact words now. */
+ searchable: number;
+ /** Items that reached the last stage and carry a summary. */
+ summarised: number;
+ /** The ONE backlog number. Every surface quotes this, none re-adds it. */
+ waiting: number;
+ /** Dead-lettered. Never counted as searchable: the stage it died at is
+ * no longer recoverable from the counts, so it would be a guess. */
+ failed: number;
+ /** What the biggest waiting bucket is queued FOR, or null when idle. */
+ next_step: "indexing" | "embedding" | "summarising" | null;
+ waiting_by_bucket: Partial<Record<UltraWikiItemState, number>>;
+ buckets: Partial<UltraWikiCounts>;
+ /** Nested, outermost first: stored ⊇ searchable ⊇ summarised. */
+ milestones: { id: "stored" | "searchable" | "summarised"; reached: number; share: number }[];
+}
+
export interface UltraWikiPipeline {
/**
* The worker LOOP is alive — NOT the same as work being done. Reporting this
@@ -364,6 +397,7 @@ export interface UltraWikiStatus {
storage?: UltraWikiStorageSlot;
};
counts: Partial<UltraWikiCounts>;
+ progress?: UltraWikiProgress;
pipeline: UltraWikiPipeline;
sources: UltraWikiSource[];
jobs: UltraWikiJob[];
@@ -546,6 +580,9 @@ export interface UltraWikiHealth {
overall: UltraWikiCheckState;
/** Can the user get answers RIGHT NOW (a backlog does not make this false). */
usable: boolean;
+ /** The same numbers `/status` reports, shipped with the verdict so the
+ * overview never captions a check from a second calculation. */
+ progress?: UltraWikiProgress;
checks: UltraWikiHealthCheck[];
}
@@ -958,6 +995,93 @@ export function fetchUltraWikiBridgeCandidates(): Promise<{
}>("/api/ultrawiki/bridge/candidates");
}
+// Mirrors jarvis/ultrawiki/connectors/export_import.py::EXPORT_FORMATS —
+// five-layer anti-drift discipline (AP-4): the preview renders one label per
+// id (`ultrawiki.export.format_<id>`), pinned by
+// tests/unit/ultrawiki/test_export_import.py.
+export const ULTRAWIKI_EXPORT_FORMATS = [
+ "mbox",
+ "eml",
+ "ics",
+ "vcard",
+ "whatsapp",
+ "csv",
+ "tsv",
+ "jsonl",
+ "json",
+ "pdf",
+ "html",
+ "markdown",
+ "text",
+] as const;
+export type UltraWikiExportFormat = (typeof ULTRAWIKI_EXPORT_FORMATS)[number];
+
+/** One detected format in a preview: how many files, how many items. */
+export interface UltraWikiExportFormatRow {
+ files: number;
+ items_estimate: number;
+ /** False when a scan budget ran out — the number is then a lower bound. */
+ exact: boolean;
+}
+
+/**
+ * `POST /api/ultrawiki/export/preview` — what a drop actually holds, before
+ * anything is imported. `truncated` is the honesty flag: a very large drop
+ * reports a lower bound rather than pretending a partial count is the total.
+ */
+export interface UltraWikiExportPreview {
+ path: string;
+ exists: boolean;
+ is_dir: boolean;
+ formats: Partial<Record<UltraWikiExportFormat | string, UltraWikiExportFormatRow>>;
+ unknown: { extension: string; files: number }[];
+ unreadable: { path: string; reason: string }[];
+ archives: {
+ files: number;
+ entries: number;
+ max_depth: number;
+ budget_exhausted: boolean;
+ };
+ total_bytes: number;
+ files_seen: number;
+ items_estimate: number;
+ unknown_files: number;
+ truncated: boolean;
+ /** Honest English sentences about anything that limited the pass. */
+ notes: string[];
+}
+
+export function previewUltraWikiExport(
+ path: string,
+): Promise<UltraWikiExportPreview> {
+ return postJson<UltraWikiExportPreview>("/api/ultrawiki/export/preview", {
+ path,
+ });
+}
+
+export interface UltraWikiExportUpload {
+ /** Where the file landed — this is what the source's `path` config gets. */
+ path: string;
+ name: string;
+ size: number;
+ detail: string;
+}
+
+/**
+ * Stream a dropped export file to the machine running Jarvis. No
+ * `Content-Type` header on purpose: the browser sets the multipart boundary.
+ */
+export function uploadUltraWikiExport(
+ file: File,
+): Promise<UltraWikiExportUpload> {
+ const form = new FormData();
+ form.append("file", file, file.name);
+ return request<UltraWikiExportUpload>("/api/ultrawiki/export/upload", {
+ method: "POST",
+ body: form,
+ });
+}
+
/** The curated roster the picker renders — product data, not install state. */
export function fetchUltraWikiConnectors(): Promise<{
connectors: UltraWikiConnectorSpec[];
diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.py
index 75299e41b9..1fddc4013c 100644
--- a/jarvis/ui/web/ultrawiki_routes.py
+++ b/jarvis/ui/web/ultrawiki_routes.py
@@ -22,9 +22,11 @@ import logging
import math
import re
import time
+import uuid
+from pathlib import Path
from typing import Any
-from fastapi import APIRouter, HTTPException, Query, Request
+from fastapi import APIRouter, File, HTTPException, Query, Request, UploadFile
from pydantic import BaseModel, Field
log = logging.getLogger(__name__)
@@ -1447,6 +1449,194 @@ async def list_bridge_candidates() -> dict[str, Any]:
}
+# ---------------------------------------------------------------------------
+# Export files — look before you import, and get the file here in the first place
+# ---------------------------------------------------------------------------
+
+#: Hard ceiling for one dropped export. Streamed in fixed chunks, so this
+#: bounds DISK usage; memory stays at one chunk no matter how big the file is.
+_MAX_EXPORT_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024
+
+_UPLOAD_CHUNK_BYTES = 1024 * 1024
+
+#: Characters that turn a "filename" into a path, a Windows alternate data
+#: stream, or a wildcard. A dropped file is stored under its OWN name, so the
+#: name has to be a name — such an upload is refused, never silently renamed.
+_UNSAFE_NAME_CHARS = frozenset('\\/:*?"<>|\x00')
+
+_MAX_UPLOAD_NAME_CHARS = 200
+
+
+def _safe_upload_name(raw: str) -> str:
+ """The client's filename, or a 400 explaining why it was refused.
+
+ Deliberately a REJECTION rather than a sanitisation: silently rewriting
+ ``../../secrets.zip`` to ``secrets.zip`` would store the file somewhere
+ the caller did not ask for and report success, which is exactly how a
+ traversal attempt becomes an invisible one.
+ """
+ name = (raw or "").strip()
+ if not name:
+ raise HTTPException(status_code=400, detail="the upload has no filename")
+ if len(name) > _MAX_UPLOAD_NAME_CHARS:
+ raise HTTPException(
+ status_code=400,
+ detail=f"the filename is longer than {_MAX_UPLOAD_NAME_CHARS} characters",
+ )
+ if (
+ name in (".", "..")
+ or set(name) & _UNSAFE_NAME_CHARS
+ or any(ord(char) < 32 for char in name)
+ or Path(name).name != name
+ ):
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ f"refusing the filename {name!r}: an upload is stored under its "
+ "own name, so the name may not contain a path, a drive letter, "
+ "or a control character"
+ ),
+ )
+ return name
+
+
+def _discard_upload(directory: Path) -> None:
+ """Remove a partial upload's folder; a failed cleanup is never fatal."""
+ import shutil # noqa: PLC0415 — lazy, only on the failure path
+
+ shutil.rmtree(directory, ignore_errors=True)
+
+
+class PreviewExportBody(BaseModel):
+ """Which file or folder to inspect. Read-only — nothing is imported."""
+
+ path: str = Field(min_length=1)
+
+
+ "/export/preview", summary="Report what an export file or folder holds"
+)
+async def preview_export(
+ body: PreviewExportBody, request: Request
+) -> dict[str, Any]:
+ """Detect the formats in a drop and count what is inside — before importing.
+
+ "Approve and import everything" is a big button to press blind. This
+ answers what "everything" IS first: how many mails, events, chats and
+ rows were found, and which files will be skipped as unrecognised. It only
+ reads — no source is registered, no byte is stored.
+
+ The counts are exact when the pass could afford to be; a very large drop
+ reports ``truncated`` and drops ``exact`` on the affected formats rather
+ than presenting a partial number as the whole truth.
+ """
+ from jarvis.ultrawiki.connectors import export_import # noqa: PLC0415 — lazy
+
+ target = body.path.strip()
+ if not target:
+ raise HTTPException(status_code=400, detail="a path is required")
+ # Walks the filesystem and reads bytes to count records — never on the
+ # event loop, which also serves voice and chat.
+ report = await asyncio.to_thread(export_import.scan_export, target)
+ if not report.get("exists"):
+ raise HTTPException(
+ status_code=404,
+ detail=f"nothing exists at {target!r} on this machine",
+ )
+ return report
+
+
+ "/export/upload",
+ summary="Upload an export file so it can be imported",
+ openapi_extra={
+ # It writes the uploaded bytes to this machine's disk.
+ "x-jarvis-dangerous": True,
+ # A multi-gigabyte Takeout archive over a slow link takes minutes; the
+ # CLI's default client timeout would give up on a transfer that is
+ # working perfectly.
+ "x-jarvis-timeout-seconds": 600,
+ },
+)
+async def upload_export(
+ request: Request,
+ file: UploadFile = File(...), # noqa: B008 — FastAPI dependency default
+) -> dict[str, Any]:
+ """Stream a dropped export file to disk and return the path to import from.
+
+ The alternative — "type the full path to your Takeout archive" — is a
+ non-starter on a machine the user is not sitting at, and unfriendly even
+ on one they are. The bytes go to a fresh folder under the Jarvis data
+ directory in fixed chunks, so a 2 GB archive costs one chunk of memory,
+ and a transfer that exceeds the cap leaves nothing behind.
+ """
+ from jarvis.ultrawiki.connectors import export_import # noqa: PLC0415 — lazy
+
+ name = _safe_upload_name(file.filename or "")
+ data_dir = getattr(getattr(_config(request), "memory", None), "data_dir", None)
+ folder = export_import.uploads_dir(data_dir) / uuid.uuid4().hex
+ target = folder / name
+
+ try:
+ await asyncio.to_thread(folder.mkdir, parents=True, exist_ok=True)
+ except OSError as exc:
+ raise HTTPException(
+ status_code=500,
+ detail=(
+ f"the upload folder could not be created ({type(exc).__name__}) "
+ "— check that the Jarvis data directory is writable"
+ ),
+ ) from exc
+
+ written = 0
+ too_large = False
+ try:
+ handle = await asyncio.to_thread(target.open, "wb")
+ try:
+ while True:
+ chunk = await file.read(_UPLOAD_CHUNK_BYTES)
+ if not chunk:
+ break
+ written += len(chunk)
+ if written > _MAX_EXPORT_UPLOAD_BYTES:
+ too_large = True
+ break
+ await asyncio.to_thread(handle.write, chunk)
+ finally:
+ await asyncio.to_thread(handle.close)
+ except OSError as exc:
+ await asyncio.to_thread(_discard_upload, folder)
+ raise HTTPException(
+ status_code=500,
+ detail=f"the upload could not be written ({type(exc).__name__}: {exc})",
+ ) from exc
+
+ if too_large:
+ await asyncio.to_thread(_discard_upload, folder)
+ raise HTTPException(
+ status_code=413,
+ detail=(
+ "the file is larger than "
+ f"{_MAX_EXPORT_UPLOAD_BYTES // (1024**3)} GB — nothing was "
+ "kept. Point the source at the file on this machine instead, "
+ "which has no size limit at all."
+ ),
+ )
+ if written == 0:
+ await asyncio.to_thread(_discard_upload, folder)
+ raise HTTPException(status_code=400, detail="the uploaded file is empty")
+
+ return {
+ "path": str(target),
+ "name": name,
+ "size": written,
+ "detail": (
+ "The file is on this machine. Preview it to see what it holds, "
+ "then add it as a source."
+ ),
+ }
+
+
# ---------------------------------------------------------------------------
# Pipeline recovery
# ---------------------------------------------------------------------------
diff --git a/jarvis/ultrawiki/connector_catalog.py b/jarvis/ultrawiki/connector_catalog.py
index 3a139f8773..6f2c90edbe 100644
--- a/jarvis/ultrawiki/connector_catalog.py
+++ b/jarvis/ultrawiki/connector_catalog.py
@@ -89,7 +89,7 @@ CONNECTOR_STATUSES: tuple[ConnectorStatus, ...] = ("available", "adapter_pending
#: connector has no vendor and must never borrow one; the frontend maps these
#: to its own icons. Kept as a closed set so a typo cannot silently become a
#: missing logo.
-NEUTRAL_BRANDS: tuple[str, ...] = ("vault", "folder", "chat", "wiki")
+NEUTRAL_BRANDS: tuple[str, ...] = ("vault", "folder", "chat", "wiki", "archive")
@dataclass(frozen=True, slots=True)
@@ -170,6 +170,19 @@ BUILTIN_CONNECTORS: tuple[UltraWikiConnectorSpec, ...] = (
label_key="ultrawiki.sources.connector_normal_wiki",
description_key="ultrawiki.connectors.normal_wiki",
),
+ # The universal on-ramp: whatever export the user already HAS. It is a
+ # built-in rather than a bridge entry because it belongs to no vendor —
+ # the formats are open standards (mbox, iCalendar, vCard, CSV, PDF), and
+ # every service that matters can produce at least one of them.
+ UltraWikiConnectorSpec(
+ id="export-import",
+ kind="builtin",
+ label="Export file import",
+ brand="archive",
+ status="available",
+ label_key="ultrawiki.sources.connector_export_import",
+ description_key="ultrawiki.connectors.export_import",
+ ),
)
diff --git a/jarvis/ultrawiki/connectors/__init__.py b/jarvis/ultrawiki/connectors/__init__.py
index 4cfb008a29..5968949697 100644
--- a/jarvis/ultrawiki/connectors/__init__.py
+++ b/jarvis/ultrawiki/connectors/__init__.py
@@ -66,13 +66,20 @@ def _make_plugin_bridge() -> UWConnector:
return PluginBridgeConnector()
+def _make_export_import() -> UWConnector:
+ from jarvis.ultrawiki.connectors.export_import import ExportImportConnector
+
+ return ExportImportConnector()
+
+
def builtin_connectors() -> dict[str, ConnectorFactory]:
- """The five built-in connectors, keyed by connector id."""
+ """The six built-in connectors, keyed by connector id."""
return {
"obsidian-vault": _make_obsidian_vault,
"local-folder": _make_local_folder,
"jarvis-conversations": _make_jarvis_conversations,
"normal-wiki": _make_normal_wiki,
+ "export-import": _make_export_import,
"plugin-bridge": _make_plugin_bridge,
}
diff --git a/jarvis/ultrawiki/connectors/export_import.py b/jarvis/ultrawiki/connectors/export_import.py
new file mode 100644
index 0000000000..0a0b7499c0
--- /dev/null
+++ b/jarvis/ultrawiki/connectors/export_import.py
@@ -0,0 +1,1953 @@
+"""Export-file import: the standards-based universal on-ramp.
+
+A user (or a company) already HAS their data — a Google Takeout archive, a
+WhatsApp "Export chat" text file, a mail archive, a CSV dump, a folder of
+PDFs. This connector is the door that accepts whatever shape it arrives in:
+point it at one file or one folder, and it detects the formats, says what it
+found, and streams everything in.
+
+Design rules it inherits from the connector contract (design doc 02):
+
+* **Yields :class:`RawItem` only.** No store, no LLM, no embedding.
+* **Nothing blocking runs on the event loop.** The whole detect/parse/walk
+ path is one BLOCKING generator, pulled a batch at a time through
+ ``asyncio.to_thread`` — so a 10 GB mbox costs one batch of items in memory,
+ never the file.
+* **Nothing is extracted to disk.** Zip entries are parsed through
+ ``zipfile`` streams; a nested zip is buffered in memory under an explicit
+ cap rather than written out.
+* **Every skip is counted and logged, never raised.** An encrypted PDF, a
+ binary blob, a zip past the depth limit — the import continues and the
+ reason is on the record.
+
+Resume / checkpoint contract (documented honestly)
+--------------------------------------------------
+
+``backfill(ctx, checkpoint)`` walks in deterministic sorted order and resume
+is **file-granular, not item-granular**. Item ids carry the natural
+identifier of the record (a mail's ``Message-ID``, an event's ``UID``), which
+is what makes a re-import idempotent — but those ids do not sort in the order
+the items are produced, so "skip everything at or before the checkpoint"
+cannot be applied to them the way the local-folder connector applies it to
+paths. Instead the checkpoint's ORIGIN FILE is recovered from the id, every
+file sorting strictly BEFORE it is skipped, and that file itself is re-read
+from its start. The re-read items upsert as ``unchanged`` on
+``(source_id, external_id)``, so the only cost is a little repeated work
+after an interrupted run.
+
+Deletes are not detectable: an export file is a snapshot, and
+``capabilities.deletes`` is therefore ``False``. ``incremental`` is
+:data:`~jarvis.ultrawiki.types.IncrementalMode.NONE` — a re-sync is a full,
+idempotent re-read of the same drop.
+
+Archive scope: **zip only** (``.zip``, plus a ``PK`` magic sniff). Google
+Takeout offers ``.tgz`` as well; tar/gzip support is deliberately NOT here
+because a compressed tar has no central directory, so entries can only be
+reached by decompressing the whole stream in order — which breaks both the
+sorted-order guarantee the checkpoint depends on and the ability to skip an
+entry cheaply. Takeout's zip option covers the same data.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import csv
+import email.utils
+import hashlib
+import io
+import json
+import logging
+import os
+import re
+import zipfile
+from collections.abc import AsyncIterator, Callable, Iterator
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from email import message_from_bytes
+from email.header import decode_header, make_header
+from email.message import Message
+from pathlib import Path
+from typing import IO, Any
+from urllib.parse import quote
+
+from jarvis.ultrawiki.adapters._google import (
+ BODY_CAP,
+ cap_body,
+ strip_html,
+)
+from jarvis.ultrawiki.connectors.local_folder import iso_utc_from_timestamp
+from jarvis.ultrawiki.types import (
+ AuthKind,
+ ConnectorCapabilities,
+ ConnectorContext,
+ IncrementalMode,
+ RawItem,
+)
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "ARCHIVE_FORMAT",
+ "EXPORT_FORMATS",
+ "ExportImportConnector",
+ "ScanReport",
+ "chat_name_from_filename",
+ "detect_format",
+ "scan_export",
+ "uploads_dir",
+]
+
+
+# ---------------------------------------------------------------------------
+# Formats + limits
+# ---------------------------------------------------------------------------
+
+#: Every ITEM-PRODUCING format, in the order a preview report lists them.
+#: Five-layer drift discipline (AP-4): the frontend renders one label per id
+#: and ``tests/unit/ultrawiki/test_export_import.py`` pins the two together.
+EXPORT_FORMATS: tuple[str, ...] = (
+ "mbox",
+ "eml",
+ "ics",
+ "vcard",
+ "whatsapp",
+ "csv",
+ "tsv",
+ "jsonl",
+ "json",
+ "pdf",
+ "html",
+ "markdown",
+ "text",
+)
+
+#: The one container format. Not in :data:`EXPORT_FORMATS` — it yields no
+#: items of its own, only the entries inside it.
+ARCHIVE_FORMAT = "zip"
+
+_EXTENSION_FORMATS: dict[str, str] = {
+ ".mbox": "mbox",
+ ".mbx": "mbox",
+ ".eml": "eml",
+ ".emlx": "eml",
+ ".ics": "ics",
+ ".ical": "ics",
+ ".ifb": "ics",
+ ".vcf": "vcard",
+ ".vcard": "vcard",
+ ".csv": "csv",
+ ".tsv": "tsv",
+ ".tab": "tsv",
+ ".jsonl": "jsonl",
+ ".ndjson": "jsonl",
+ ".json": "json",
+ ".txt": "text",
+ ".text": "text",
+ ".md": "markdown",
+ ".markdown": "markdown",
+ ".html": "html",
+ ".htm": "html",
+ ".xhtml": "html",
+ ".pdf": "pdf",
+ ".zip": ARCHIVE_FORMAT,
+}
+
+#: Nested archives are followed this many levels deep (the outer zip is 1).
+#: A cycle needs a self-containing archive, which the depth limit alone ends.
+MAX_ZIP_DEPTH = 3
+
+#: Total UNCOMPRESSED bytes one run will expand out of archives. The honest
+#: defence against a zip bomb: a 4 GB budget imports any real Takeout and
+#: stops a 42-byte / 4-petabyte archive after one harmless step.
+ZIP_UNCOMPRESSED_BUDGET = 4 * 1024 * 1024 * 1024
+
+#: A nested archive has to be buffered (``zipfile`` needs to seek, and a zip
+#: entry stream cannot), so it is bounded far tighter than the outer one,
+#: which is read straight off disk.
+MAX_BUFFERED_ZIP_BYTES = 256 * 1024 * 1024
+
+#: A PDF also needs random access; the same buffering rule applies inside an
+#: archive. On disk it is opened by path and this cap never applies.
+MAX_BUFFERED_PDF_BYTES = 128 * 1024 * 1024
+
+#: Formats parsed from one whole in-memory string (calendar, contacts, JSON,
+#: HTML). Bigger than this is refused with an honest line rather than an
+#: out-of-memory kill; the streaming formats have no such limit.
+MAX_WHOLE_READ_BYTES = 64 * 1024 * 1024
+
+#: One mail is bounded independently of the mbox around it, so a malformed
+#: file without separators cannot become one unbounded message.
+MAX_MESSAGE_BYTES = 8 * 1024 * 1024
+
+#: Rows/lines per tabular item. Small enough that a chunk is still ONE
+#: retrievable thought, large enough that a 200k-row dump is not 200k items.
+TABULAR_CHUNK_ROWS = 100
+
+#: One line of a JSONL dump never contributes more than this to a chunk.
+MAX_JSONL_LINE_CHARS = 8000
+
+#: Bytes sniffed to detect a format. Enough for every magic number plus a few
+#: WhatsApp lines, cheap enough to do for every file in a preview pass.
+SNIFF_BYTES = 4096
+
+#: Items handed back per worker-thread hop (mirrors the local-folder walk).
+ITEM_BATCH = 32
+
+#: Bytes a PREVIEW pass will read to count records before it starts reporting
+#: estimates instead of exact numbers. A preview must feel instant; an exact
+#: count of a 40 GB mailbox does not.
+SCAN_BYTES_BUDGET = 256 * 1024 * 1024
+
+#: Directory names never walked, on top of every dot-prefixed entry.
+SKIP_DIR_NAMES: frozenset[str] = frozenset({"__MACOSX", "node_modules"})
+
+
+# ---------------------------------------------------------------------------
+# Detection
+# ---------------------------------------------------------------------------
+
+_MAGIC_PREFIXES: tuple[tuple[bytes, str], ...] = (
+ (b"%PDF-", "pdf"),
+ (b"PK\x03\x04", ARCHIVE_FORMAT),
+ (b"BEGIN:VCALENDAR", "ics"),
+ (b"BEGIN:VCARD", "vcard"),
+)
+
+#: An mbox opens with a ``From <envelope> <date>`` separator line, followed
+#: immediately by the first message's headers.
+_MBOX_MAGIC = re.compile(rb"^From \S+[^\r\n]*\r?\n[A-Za-z-]+:")
+
+#: Byte-order mark a Windows exporter leaves in front of a text file.
+_UTF8_BOM = b"\xef\xbb\xbf"
+
+#: Zero-width / bidi marks and narrow spaces that real WhatsApp exports carry
+#: around timestamps; they break every naive line regex.
+_INVISIBLE_RE = re.compile(r"[​-‏‪-‮]")
+_ODD_SPACE_RE = re.compile(r"[   ]")
+
+#: "[dd.mm.yy, hh:mm:ss] Name: text" — the bracketed family (iOS and several
+#: desktop exports), with either separator, either date order, optional
+#: seconds and optional AM/PM.
+_WA_BRACKET_RE = re.compile(
+ r"^\[(?P<a>\d{1,4})[./-](?P<b>\d{1,2})[./-](?P<c>\d{2,4}),?\s+"
+ r"(?P<hh>\d{1,2}):(?P<mm>\d{2})(?::(?P<ss>\d{2}))?\s*"
+ r"(?P<ampm>[AaPp]\.?[Mm]\.?)?\]\s*"
+ r"(?:(?P<author>[^:]{1,80}?):\s)?(?P<text>.*)$"
+)
+
+#: "dd/mm/yy, hh:mm - Name: text" — the dash family (Android and the web
+#: export), same tolerances.
+_WA_DASH_RE = re.compile(
+ r"^(?P<a>\d{1,4})[./-](?P<b>\d{1,2})[./-](?P<c>\d{2,4}),?\s+"
+ r"(?P<hh>\d{1,2}):(?P<mm>\d{2})(?::(?P<ss>\d{2}))?\s*"
+ r"(?P<ampm>[AaPp]\.?[Mm]\.?)?\s+-\s+"
+ r"(?:(?P<author>[^:]{1,80}?):\s)?(?P<text>.*)$"
+)
+
+# The connector word between "WhatsApp Chat" and the contact name is whatever
+# the exporting phone's UI language used. These are matching DATA — the
+# literal tokens a filename must contain to be recognised — not prose, and
+# they are the reason a German or Spanish phone's export still gets a proper
+# chat name instead of the raw filename.
+# i18n-allow: non-English filename tokens WhatsApp itself writes (input vocabulary)
+_WA_FILENAME_RE = re.compile(
+ r"^(?:whatsapp[\s_-]*chat|chat[\s_-]*de[\s_-]*whatsapp"
+ r"|conversa[\s_-]*do[\s_-]*whatsapp|discussion[\s_-]*whatsapp"
+ r"|chat[\s_-]*whatsapp|whatsapp)"
+ r"[\s_-]*(?:with|mit|con|com|avec|de|van|med|z)?[\s_-]*(?P<name>.+)$",
+ re.IGNORECASE,
+)
+
+
+def _normalize_line(text: str) -> str:
+ """Strip the invisible marks a phone export sprinkles around timestamps."""
+ return _ODD_SPACE_RE.sub(" ", _INVISIBLE_RE.sub("", text))
+
+
+def _looks_like_whatsapp(head: bytes) -> bool:
+ """True when the first lines match either WhatsApp message family."""
+ try:
+ text = head.decode("utf-8", errors="replace")
+ except Exception: # noqa: BLE001 — a sniff never raises
+ return False
+ hits = 0
+ for raw in text.splitlines()[:40]:
+ line = _normalize_line(raw)
+ if _WA_BRACKET_RE.match(line) or _WA_DASH_RE.match(line):
+ hits += 1
+ if hits >= 2:
+ return True
+ return False
+
+
+def detect_format(name: str, head: bytes) -> str:
+ """The format id for one file: content magic first, extension second.
+
+ Magic wins because an export's extension lies routinely — a WhatsApp chat
+ and a vCard dump are both ``.txt``, a Takeout mail file has no extension
+ at all. Returns ``""`` for anything unrecognised; the caller counts it as
+ skipped rather than failing the import.
+ """
+ stripped = head
+ if stripped.startswith(_UTF8_BOM):
+ stripped = stripped[len(_UTF8_BOM) :]
+ stripped = stripped.lstrip(b"\r\n \t")
+ for prefix, fmt in _MAGIC_PREFIXES:
+ if stripped[: len(prefix)].upper() == prefix.upper():
+ return fmt
+ if _MBOX_MAGIC.match(stripped):
+ return "mbox"
+ ext_format = _EXTENSION_FORMATS.get(Path(name).suffix.lower(), "")
+ if ext_format in ("", "text", "markdown") and _looks_like_whatsapp(head):
+ return "whatsapp"
+ if not ext_format and head and _is_probably_text(head):
+ # A Takeout mail file has no suffix at all; anything that reads as
+ # text is still worth importing as text rather than being dropped.
+ return "text"
+ return ext_format
+
+
+def _is_probably_text(head: bytes) -> bool:
+ """Cheap binary check: a NUL byte or a high share of control bytes."""
+ if b"\x00" in head:
+ return False
+ sample = head[:1024]
+ if not sample:
+ return False
+ control = sum(1 for byte in sample if byte < 9 or 13 < byte < 32)
+ return control / len(sample) < 0.05
+
+
+def chat_name_from_filename(name: str) -> str:
+ """The chat partner's name out of a WhatsApp export filename.
+
+ ``WhatsApp Chat with Ada.txt`` / ``WhatsApp Chat mit Ada.txt`` ->
+ ``Ada``. Anything the pattern does not cover falls back to the file's own
+ stem, so a renamed export still lands under a readable name instead of an
+ empty thread key.
+ """
+ stem = Path(name).stem.strip()
+ match = _WA_FILENAME_RE.match(stem)
+ if match:
+ found = match.group("name").strip(" -_")
+ if found:
+ return found
+ return stem or name
+
+
+# ---------------------------------------------------------------------------
+# Walk plumbing
+# ---------------------------------------------------------------------------
+
+
+@dataclass(slots=True)
+class ScanReport:
+ """What a walk found — the preview payload AND the import's honest log.
+
+ Both passes fill the same structure so a preview can never promise
+ something the import then reports differently.
+ """
+
+ #: format id -> {"files": int, "items_estimate": int, "exact": bool}
+ formats: dict[str, dict[str, Any]] = field(default_factory=dict)
+ #: lowercase extension -> number of files skipped as unrecognised
+ unknown: dict[str, int] = field(default_factory=dict)
+ #: [{"path": ..., "reason": ...}] — read once, refused honestly
+ unreadable: list[dict[str, str]] = field(default_factory=list)
+ archives: dict[str, Any] = field(
+ default_factory=lambda: {
+ "files": 0,
+ "entries": 0,
+ "max_depth": 0,
+ "budget_exhausted": False,
+ }
+ )
+ total_bytes: int = 0
+ files_seen: int = 0
+ truncated: bool = False
+ notes: list[str] = field(default_factory=list)
+
+ def count_file(self, fmt: str, size: int) -> None:
+ row = self.formats.setdefault(
+ fmt, {"files": 0, "items_estimate": 0, "exact": True}
+ )
+ row["files"] += 1
+ self.files_seen += 1
+ self.total_bytes += max(0, int(size))
+
+ def add_items(self, fmt: str, count: int, *, exact: bool = True) -> None:
+ row = self.formats.setdefault(
+ fmt, {"files": 0, "items_estimate": 0, "exact": True}
+ )
+ row["items_estimate"] += max(0, int(count))
+ if not exact:
+ row["exact"] = False
+
+ def count_unknown(self, name: str, size: int) -> None:
+ suffix = Path(name).suffix.lower() or "(no extension)"
+ self.unknown[suffix] = self.unknown.get(suffix, 0) + 1
+ self.files_seen += 1
+ self.total_bytes += max(0, int(size))
+
+ def refuse(self, path: str, reason: str) -> None:
+ if len(self.unreadable) < 200:
+ self.unreadable.append({"path": path, "reason": reason})
+
+ def note(self, text: str) -> None:
+ if text not in self.notes:
+ self.notes.append(text)
+
+ def as_dict(self) -> dict[str, Any]:
+ """The API payload — formats in the declared order, never dict order."""
+ ordered = {
+ fmt: dict(self.formats[fmt])
+ for fmt in EXPORT_FORMATS
+ if fmt in self.formats
+ }
+ for fmt, row in self.formats.items(): # a format id added later
+ ordered.setdefault(fmt, dict(row))
+ return {
+ "formats": ordered,
+ "unknown": [
+ {"extension": ext, "files": count}
+ for ext, count in sorted(
+ self.unknown.items(), key=lambda pair: (-pair[1], pair[0])
+ )
+ ],
+ "unreadable": list(self.unreadable),
+ "archives": dict(self.archives),
+ "total_bytes": self.total_bytes,
+ "files_seen": self.files_seen,
+ "items_estimate": sum(
+ int(row.get("items_estimate", 0)) for row in self.formats.values()
+ ),
+ "unknown_files": sum(self.unknown.values()),
+ "truncated": self.truncated,
+ "notes": list(self.notes),
+ }
+
+
+@dataclass(slots=True)
+class _Budget:
+ """Remaining uncompressed archive bytes for one walk.
+
+ The default is read through a factory, not baked in at class-definition
+ time: the cap is a module constant a test (or a future setting) must be
+ able to change without the dataclass silently keeping the old value.
+ """
+
+ remaining: int = field(default_factory=lambda: ZIP_UNCOMPRESSED_BUDGET)
+ exhausted: bool = False
+
+ def take(self, size: int) -> bool:
+ if self.exhausted:
+ return False
+ if size > self.remaining:
+ self.exhausted = True
+ return False
+ self.remaining -= max(0, size)
+ return True
+
+
+@dataclass(frozen=True, slots=True)
+class _Entry:
+ """One concrete parseable blob — on disk or inside an archive."""
+
+ #: On-disk file this came from. The RESUME unit (see the module docstring).
+ origin: str
+ #: Full stable key: ``origin`` for a plain file, ``origin!inner/path``
+ #: for an archive entry. Prefixes every ``external_id`` it produces.
+ key: str
+ name: str
+ permalink: str
+ size: int
+ fmt: str
+ timestamp_utc: str
+ #: Opens a FRESH binary stream each call; the caller always closes it.
+ open_binary: Callable[[], IO[bytes]]
+ #: Set only for on-disk files — a seekable original that ``pypdf`` and the
+ #: whole-read parsers can use without buffering.
+ disk_path: Path | None = None
+
+
+def _sorted_disk_files(root: Path) -> list[tuple[str, Path]]:
+ """``(key, path)`` for every non-hidden file under ``root``, sorted by key."""
+ found: list[tuple[str, Path]] = []
+ for dirpath, dirnames, filenames in os.walk(root):
+ dirnames[:] = sorted(
+ name
+ for name in dirnames
+ if not name.startswith(".") and name not in SKIP_DIR_NAMES
+ )
+ base = Path(dirpath)
+ for name in filenames:
+ if name.startswith("."):
+ continue
+ path = base / name
+ found.append((path.relative_to(root).as_posix(), path))
+ found.sort(key=lambda pair: pair[0])
+ return found
+
+
+def _read_head(open_binary: Callable[[], IO[bytes]]) -> bytes:
+ try:
+ with open_binary() as stream:
+ return stream.read(SNIFF_BYTES)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ raise _Unreadable(f"{type(exc).__name__}: {exc}") from exc
+
+
+class _Unreadable(Exception):
+ """One file could not be read. Always caught; never reaches a caller."""
+
+
+def _zip_entry_timestamp(info: zipfile.ZipInfo) -> str:
+ """A zip entry's stored local time as ISO-8601 UTC (zips carry no zone)."""
+ try:
+ moment = datetime(*info.date_time, tzinfo=UTC)
+ except (TypeError, ValueError):
+ return ""
+ return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _walk_entries(
+ root: Path, report: ScanReport, budget: _Budget
+) -> Iterator[_Entry]:
+ """Every parseable blob under ``root``, in deterministic sorted order.
+
+ A generator on purpose: archives stay open exactly as long as the caller
+ is consuming their entries, and nothing is materialised ahead of time.
+ """
+ if root.is_file():
+ pairs = [(root.name, root)]
+ else:
+ pairs = _sorted_disk_files(root)
+ for key, path in pairs:
+ yield from _entries_for_disk_file(path, key, report, budget, depth=0)
+
+
+def _entries_for_disk_file(
+ path: Path, key: str, report: ScanReport, budget: _Budget, *, depth: int
+) -> Iterator[_Entry]:
+ try:
+ size = path.stat().st_size
+ head = _read_head(lambda: path.open("rb"))
+ except (OSError, _Unreadable) as exc:
+ report.refuse(key, f"{type(exc).__name__}: {exc}")
+ return
+ fmt = detect_format(path.name, head)
+ if fmt == ARCHIVE_FORMAT:
+ report.archives["files"] += 1
+ yield from _entries_for_zip(
+ lambda: path.open("rb"),
+ origin=key,
+ prefix="",
+ report=report,
+ budget=budget,
+ depth=depth + 1,
+ label=key,
+ )
+ return
+ if not fmt:
+ report.count_unknown(path.name, size)
+ return
+ report.count_file(fmt, size)
+ yield _Entry(
+ origin=key,
+ key=key,
+ name=path.name,
+ permalink=_file_uri(path),
+ size=size,
+ fmt=fmt,
+ timestamp_utc=_disk_timestamp(path),
+ open_binary=lambda: path.open("rb"),
+ disk_path=path,
+ )
+
+
+def _disk_timestamp(path: Path) -> str:
+ try:
+ return iso_utc_from_timestamp(path.stat().st_mtime)
+ except OSError:
+ return ""
+
+
+def _file_uri(path: Path) -> str:
+ try:
+ return path.resolve().as_uri()
+ except (OSError, ValueError):
+ return f"file:///{quote(path.as_posix().lstrip('/'))}"
+
+
+def _entries_for_zip(
+ open_archive: Callable[[], IO[bytes]],
+ *,
+ origin: str,
+ prefix: str,
+ report: ScanReport,
+ budget: _Budget,
+ depth: int,
+ label: str,
+) -> Iterator[_Entry]:
+ """Walk one archive's entries as streams — nothing is written to disk."""
+ if depth > MAX_ZIP_DEPTH:
+ report.note(
+ f"'{label}' contains archives nested deeper than {MAX_ZIP_DEPTH} "
+ "levels; those were left unread."
+ )
+ return
+ report.archives["max_depth"] = max(report.archives["max_depth"], depth)
+ try:
+ archive = zipfile.ZipFile(open_archive())
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(label, f"{type(exc).__name__}: {exc}")
+ return
+ with archive:
+ try:
+ infos = sorted(archive.infolist(), key=lambda info: info.filename)
+ except (RuntimeError, zipfile.BadZipFile) as exc:
+ report.refuse(label, f"{type(exc).__name__}: {exc}")
+ return
+ base_uri = _zip_base_uri(open_archive, label)
+ for info in infos:
+ if info.is_dir():
+ continue
+ inner = info.filename.replace("\\", "/")
+ parts = [part for part in inner.split("/") if part]
+ if not parts or any(
+ part.startswith(".") or part in SKIP_DIR_NAMES for part in parts
+ ):
+ continue
+ if not budget.take(int(info.file_size)):
+ report.archives["budget_exhausted"] = True
+ report.note(
+ "The archive expands to more than "
+ f"{ZIP_UNCOMPRESSED_BUDGET // (1024**3)} GB; reading "
+ "stopped there so the import cannot be used to fill this "
+ "machine's disk or memory."
+ )
+ return
+ report.archives["entries"] += 1
+ full_inner = f"{prefix}{inner}"
+ key = f"{origin}!{full_inner}"
+ opener = _zip_entry_opener(archive, info, key, report)
+ if opener is None:
+ continue
+ try:
+ head = _read_head(opener)
+ except _Unreadable as exc:
+ report.refuse(key, str(exc))
+ continue
+ fmt = detect_format(parts[-1], head)
+ if fmt == ARCHIVE_FORMAT:
+ buffered = _buffer_zip_entry(
+ archive, info, key, report, MAX_BUFFERED_ZIP_BYTES, "archive"
+ )
+ if buffered is None:
+ continue
+ report.archives["files"] += 1
+ yield from _entries_for_zip(
+ lambda data=buffered: io.BytesIO(data),
+ origin=origin,
+ prefix=f"{full_inner}!",
+ report=report,
+ budget=budget,
+ depth=depth + 1,
+ label=key,
+ )
+ continue
+ if not fmt:
+ report.count_unknown(parts[-1], int(info.file_size))
+ continue
+ report.count_file(fmt, int(info.file_size))
+ yield _Entry(
+ origin=origin,
+ key=key,
+ name=parts[-1],
+ permalink=f"{base_uri}#{quote(full_inner)}",
+ size=int(info.file_size),
+ fmt=fmt,
+ timestamp_utc=_zip_entry_timestamp(info),
+ open_binary=opener,
+ )
+
+
+def _zip_base_uri(open_archive: Callable[[], IO[bytes]], label: str) -> str:
+ """The ``file://`` URI of the archive itself; the label when it has none."""
+ try:
+ probe = open_archive()
+ except OSError:
+ return f"file:///{quote(label)}"
+ try:
+ name = getattr(probe, "name", "")
+ if isinstance(name, str) and name:
+ return _file_uri(Path(name))
+ finally:
+ try:
+ probe.close()
+ except OSError: # pragma: no cover — closing a BytesIO cannot fail
+ pass
+ return f"file:///{quote(label)}"
+
+
+def _zip_entry_opener(
+ archive: zipfile.ZipFile,
+ info: zipfile.ZipInfo,
+ key: str,
+ report: ScanReport,
+) -> Callable[[], IO[bytes]] | None:
+ """A fresh-stream opener for one entry, or ``None`` when it is encrypted."""
+ if info.flag_bits & 0x1:
+ report.refuse(key, "the archive entry is password protected")
+ return None
+
+ def _open() -> IO[bytes]:
+ return archive.open(info, "r")
+
+ return _open
+
+
+def _buffer_zip_entry(
+ archive: zipfile.ZipFile,
+ info: zipfile.ZipInfo,
+ key: str,
+ report: ScanReport,
+ limit: int,
+ what: str,
+) -> bytes | None:
+ """Read one entry into memory under ``limit``; ``None`` when it is bigger.
+
+ Only for the two parsers that genuinely need to seek (a nested archive's
+ central directory, a PDF's cross-reference table). Everything else reads
+ the entry as a stream.
+ """
+ if int(info.file_size) > limit:
+ report.refuse(
+ key,
+ f"the {what} inside the archive is larger than "
+ f"{limit // (1024 * 1024)} MB, which is more than this import "
+ "will hold in memory at once",
+ )
+ return None
+ try:
+ with archive.open(info, "r") as stream:
+ return stream.read(limit + 1)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(key, f"{type(exc).__name__}: {exc}")
+ return None
+
+
+# ---------------------------------------------------------------------------
+# Small shared helpers
+# ---------------------------------------------------------------------------
+
+
+def _hash_id(*parts: str) -> str:
+ digest = hashlib.sha256()
+ for part in parts:
+ digest.update(part.encode("utf-8", errors="replace"))
+ digest.update(b"\x00")
+ return digest.hexdigest()[:24]
+
+
+def _decode_header_value(raw: Any) -> str:
+ """One MIME header as readable text; never raises on a malformed value."""
+ if raw is None:
+ return ""
+ try:
+ return str(make_header(decode_header(str(raw)))).strip()
+ except Exception: # noqa: BLE001 — a broken header degrades to its raw form
+ return str(raw).strip()
+
+
+_SUBJECT_PREFIX_RE = re.compile(
+ r"^\s*(?:re|fw|fwd|aw|wg|sv|vs|antw|rif)\s*(?:\[\d+\])?\s*:\s*",
+ re.IGNORECASE,
+)
+_WHITESPACE_RE = re.compile(r"\s+")
+
+
+def _thread_key_for_subject(subject: str) -> str:
+ """A mail subject folded to its conversation key (``Re:``/``AW:`` gone)."""
+ text = subject
+ for _ in range(8):
+ stripped = _SUBJECT_PREFIX_RE.sub("", text)
+ if stripped == text:
+ break
+ text = stripped
+ return _WHITESPACE_RE.sub(" ", text).strip().lower()
+
+
+def _iso_utc(moment: datetime) -> str:
+ if moment.tzinfo is None:
+ moment = moment.replace(tzinfo=UTC)
+ return moment.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _text_stream(entry: _Entry) -> io.TextIOWrapper:
+ """A UTF-8 text view of an entry's bytes; undecodable bytes are replaced."""
+ return io.TextIOWrapper(
+ entry.open_binary(), encoding="utf-8", errors="replace", newline=""
+ )
+
+
+def _read_whole_text(entry: _Entry, report: ScanReport) -> str | None:
+ """The entry's full text, or ``None`` when it exceeds the whole-read cap."""
+ if entry.size > MAX_WHOLE_READ_BYTES:
+ report.refuse(
+ entry.key,
+ f"this format is parsed as one document and the file is larger "
+ f"than {MAX_WHOLE_READ_BYTES // (1024 * 1024)} MB",
+ )
+ return None
+ try:
+ with entry.open_binary() as stream:
+ raw = stream.read(MAX_WHOLE_READ_BYTES + 1)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return None
+ if len(raw) > MAX_WHOLE_READ_BYTES:
+ report.refuse(
+ entry.key,
+ f"the file is larger than {MAX_WHOLE_READ_BYTES // (1024 * 1024)} MB",
+ )
+ return None
+ return raw.decode("utf-8", errors="replace").lstrip("")
+
+
+def _item(
+ entry: _Entry,
+ *,
+ natural_id: str,
+ body: str,
+ title: str = "",
+ thread_key: str = "",
+ author_raw: str = "",
+ timestamp_utc: str = "",
+ metadata: dict[str, Any] | None = None,
+) -> RawItem:
+ """Assemble one :class:`RawItem` with the shared cap + id conventions."""
+ capped, truncated = cap_body(body)
+ extra = {
+ "format": entry.fmt,
+ "source_file": entry.key,
+ "import_kind": "export-file",
+ }
+ if truncated:
+ extra["truncated"] = True
+ if metadata:
+ extra.update(metadata)
+ external_id = entry.key if not natural_id else f"{entry.key}#{natural_id}"
+ return RawItem(
+ external_id=external_id,
+ body=capped,
+ permalink=entry.permalink,
+ timestamp_utc=timestamp_utc or entry.timestamp_utc,
+ title=title,
+ thread_key=thread_key,
+ author_raw=author_raw,
+ metadata=extra,
+ )
+
+
+class _IdSequencer:
+ """Keeps natural ids unique inside one file without inventing new ones.
+
+ Two calendar events legitimately share a ``UID`` (a recurring series with
+ an override), and a broken export can repeat a ``Message-ID``. The first
+ occurrence keeps the clean id; later ones get an explicit ``~2`` suffix so
+ the second record is stored rather than silently overwriting the first.
+ """
+
+ def __init__(self) -> None:
+ self._seen: dict[str, int] = {}
+
+ def unique(self, natural_id: str) -> str:
+ count = self._seen.get(natural_id, 0) + 1
+ self._seen[natural_id] = count
+ return natural_id if count == 1 else f"{natural_id}~{count}"
+
+
+# ---------------------------------------------------------------------------
+# Per-format parsers — each is a blocking generator over ONE entry
+# ---------------------------------------------------------------------------
+
+
+def _iter_mbox_messages(stream: IO[bytes]) -> Iterator[bytes]:
+ """Split an mbox stream into raw message bytes, one at a time.
+
+ Constant memory: only the current message is buffered, and that buffer is
+ itself bounded by :data:`MAX_MESSAGE_BYTES` so a file WITHOUT separators
+ cannot become one unbounded message. ``>From`` escaping (mboxo/mboxrd) is
+ left exactly as written — unescaping it would corrupt a body that legally
+ contains that text.
+ """
+ buffer: list[bytes] = []
+ size = 0
+ started = False
+ previous_blank = True
+ for line in stream:
+ if previous_blank and line.startswith(b"From "):
+ if started and buffer:
+ yield b"".join(buffer)
+ buffer, size, started = [], 0, True
+ previous_blank = False
+ continue
+ if started and size < MAX_MESSAGE_BYTES:
+ buffer.append(line)
+ size += len(line)
+ previous_blank = not line.strip(b"\r\n")
+ if started and buffer:
+ yield b"".join(buffer)
+
+
+def _mail_body(message: Message) -> str:
+ """The readable text of a mail: ``text/plain`` first, stripped HTML next."""
+ plain: list[str] = []
+ html: list[str] = []
+ for part in message.walk() if message.is_multipart() else [message]:
+ if part.get_content_maintype() == "multipart":
+ continue
+ disposition = str(part.get("Content-Disposition") or "").lower()
+ if "attachment" in disposition:
+ continue
+ subtype = part.get_content_subtype()
+ if subtype not in ("plain", "html"):
+ continue
+ try:
+ payload = part.get_payload(decode=True)
+ except Exception: # noqa: BLE001 — a broken part is not a broken mail
+ payload = None
+ if payload is None:
+ continue
+ charset = part.get_content_charset() or "utf-8"
+ try:
+ text = payload.decode(charset, errors="replace")
+ except (LookupError, AttributeError):
+ text = payload.decode("utf-8", errors="replace")
+ (plain if subtype == "plain" else html).append(text)
+ if plain:
+ return "\n\n".join(plain).strip()
+ return strip_html("\n\n".join(html)) if html else ""
+
+
+def _mail_item(
+ entry: _Entry, raw: bytes, sequencer: _IdSequencer, *, single: bool
+) -> RawItem | None:
+ try:
+ message = message_from_bytes(raw)
+ except Exception: # noqa: BLE001 — one unparseable mail is skipped
+ return None
+ subject = _decode_header_value(message.get("Subject"))
+ sender = _decode_header_value(message.get("From"))
+ recipient = _decode_header_value(message.get("To"))
+ copied = _decode_header_value(message.get("Cc"))
+ date_raw = str(message.get("Date") or "")
+ body_text = _mail_body(message)
+
+ timestamp = ""
+ if date_raw:
+ try:
+ timestamp = _iso_utc(email.utils.parsedate_to_datetime(date_raw))
+ except (TypeError, ValueError, OverflowError):
+ timestamp = ""
+
+ message_id = str(message.get("Message-ID") or "").strip().strip("<>")
+ natural = message_id or _hash_id(subject, sender, date_raw, body_text[:2000])
+
+ header_lines = [f"From: {sender}" if sender else ""]
+ if recipient:
+ header_lines.append(f"To: {recipient}")
+ if copied:
+ header_lines.append(f"Cc: {copied}")
+ if date_raw:
+ header_lines.append(f"Date: {date_raw}")
+ if subject:
+ header_lines.append(f"Subject: {subject}")
+ header = "\n".join(line for line in header_lines if line)
+
+ return _item(
+ entry,
+ # A single .eml file IS the item: its id stays the file key so it
+ # reads like every other one-item file in the inventory.
+ natural_id="" if single else sequencer.unique(natural),
+ body=f"{header}\n\n{body_text}".strip(),
+ title=subject or entry.name,
+ thread_key=_thread_key_for_subject(subject),
+ author_raw=sender,
+ timestamp_utc=timestamp,
+ metadata={"message_id": message_id, "subject": subject},
+ )
+
+
+def _parse_mbox(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ sequencer = _IdSequencer()
+ try:
+ with entry.open_binary() as stream:
+ for raw in _iter_mbox_messages(stream):
+ item = _mail_item(entry, raw, sequencer, single=False)
+ if item is not None:
+ yield item
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+
+
+def _parse_eml(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ try:
+ with entry.open_binary() as stream:
+ raw = stream.read(MAX_MESSAGE_BYTES)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return
+ item = _mail_item(entry, raw, _IdSequencer(), single=True)
+ if item is not None:
+ yield item
+
+
+def _ical_moment(value: Any) -> tuple[str, bool]:
+ """``(ISO-8601 UTC, is_all_day)`` for one icalendar date/datetime value."""
+ from datetime import date as date_cls # noqa: PLC0415 — tiny, local
+
+ if isinstance(value, datetime):
+ return _iso_utc(value), False
+ if isinstance(value, date_cls):
+ return f"{value.isoformat()}T00:00:00Z", True
+ return "", False
+
+
+def _parse_ics(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ try:
+ from icalendar import Calendar # noqa: PLC0415 — lazy (AP-26)
+ except Exception as exc: # noqa: BLE001 — a missing extra is not a crash
+ report.refuse(
+ entry.key,
+ "calendar files need the 'icalendar' package, which is not "
+ f"installed in this build ({type(exc).__name__})",
+ )
+ return
+ text = _read_whole_text(entry, report)
+ if text is None:
+ return
+ try:
+ calendar = Calendar.from_ical(text)
+ except Exception as exc: # noqa: BLE001 — a malformed calendar is skipped
+ report.refuse(entry.key, f"not a readable calendar ({type(exc).__name__})")
+ return
+ sequencer = _IdSequencer()
+ for component in calendar.walk("VEVENT"):
+ item = _ical_event_item(entry, component, sequencer)
+ if item is not None:
+ yield item
+
+
+def _ical_event_item(
+ entry: _Entry, component: Any, sequencer: _IdSequencer
+) -> RawItem | None:
+ def _text(name: str) -> str:
+ try:
+ value = component.get(name)
+ except Exception: # noqa: BLE001 — a broken property is not an event
+ return ""
+ return "" if value is None else str(value).strip()
+
+ def _moment(name: str) -> tuple[str, bool]:
+ try:
+ value = component.get(name)
+ return _ical_moment(getattr(value, "dt", None))
+ except Exception: # noqa: BLE001
+ return "", False
+
+ summary = _text("SUMMARY")
+ description = _text("DESCRIPTION")
+ location = _text("LOCATION")
+ organizer = _text("ORGANIZER")
+ start, all_day = _moment("DTSTART")
+ end, _ = _moment("DTEND")
+
+ attendees: list[str] = []
+ try:
+ raw_attendees = component.get("ATTENDEE")
+ except Exception: # noqa: BLE001
+ raw_attendees = None
+ if raw_attendees is not None:
+ values = raw_attendees if isinstance(raw_attendees, list) else [raw_attendees]
+ attendees = [str(value).replace("MAILTO:", "").strip() for value in values]
+
+ uid = _text("UID")
+ natural = uid or _hash_id(summary, start, location)
+
+ lines = [f"Summary: {summary}" if summary else ""]
+ if start:
+ lines.append(f"Start: {start}")
+ if end:
+ lines.append(f"End: {end}")
+ if all_day:
+ lines.append("All day: yes")
+ if location:
+ lines.append(f"Location: {location}")
+ if organizer:
+ lines.append(f"Organizer: {organizer}")
+ if attendees:
+ lines.append(f"Attendees: {', '.join(attendees[:50])}")
+ body = "\n".join(line for line in lines if line)
+ if description:
+ body = f"{body}\n\n{description}".strip()
+
+ return _item(
+ entry,
+ natural_id=sequencer.unique(natural),
+ body=body,
+ title=summary or "Calendar event",
+ author_raw=organizer,
+ timestamp_utc=start,
+ metadata={"uid": uid, "all_day": all_day, "attendees": attendees[:50]},
+ )
+
+
+#: vCard properties dropped from the body: base64 blobs (unreadable payload)
+#: and the format's own bookkeeping (which says nothing about the person).
+_VCARD_BLOB_PROPERTIES = frozenset(
+ {"PHOTO", "LOGO", "SOUND", "KEY", "VERSION", "PRODID", "REV"}
+)
+_VCARD_MAX_VALUE_CHARS = 2000
+
+
+def _parse_vcard(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ """Parse ``BEGIN:VCARD`` blocks with the stdlib only.
+
+ vCard is a line-folded key/value grammar, not a format that needs a
+ parser library: unfold continuation lines, split each property at its
+ first colon, done. Base64 blobs (photos, keys) are dropped rather than
+ stored as unreadable payload.
+ """
+ text = _read_whole_text(entry, report)
+ if text is None:
+ return
+ sequencer = _IdSequencer()
+ block: list[str] = []
+ inside = False
+ for raw_line in _unfold_vcard_lines(text):
+ line = raw_line.strip()
+ upper = line.upper()
+ if upper == "BEGIN:VCARD":
+ inside, block = True, []
+ continue
+ if upper == "END:VCARD":
+ if inside and block:
+ item = _vcard_item(entry, block, sequencer)
+ if item is not None:
+ yield item
+ inside, block = False, []
+ continue
+ if inside and line:
+ block.append(line)
+ if inside and block: # an export truncated mid-card is still a contact
+ item = _vcard_item(entry, block, sequencer)
+ if item is not None:
+ yield item
+
+
+def _unfold_vcard_lines(text: str) -> Iterator[str]:
+ """vCard line unfolding: a leading space/tab continues the line before."""
+ current = ""
+ for raw in text.splitlines():
+ if raw[:1] in (" ", "\t") and current:
+ current += raw[1:]
+ continue
+ if current:
+ yield current
+ current = raw
+ if current:
+ yield current
+
+
+def _vcard_item(
+ entry: _Entry, block: list[str], sequencer: _IdSequencer
+) -> RawItem | None:
+ name = ""
+ uid = ""
+ lines: list[str] = []
+ for line in block:
+ key, _, value = line.partition(":")
+ prop = key.split(";", 1)[0].strip().upper()
+ value = value.strip()
+ if not prop or not value:
+ continue
+ if prop in _VCARD_BLOB_PROPERTIES:
+ continue
+ if prop == "FN" and not name:
+ name = value
+ elif prop == "UID" and not uid:
+ uid = value
+ lines.append(f"{prop.title()}: {value[:_VCARD_MAX_VALUE_CHARS]}")
+ if not lines:
+ return None
+ natural = uid or _hash_id(name, "\n".join(lines[:20]))
+ return _item(
+ entry,
+ natural_id=sequencer.unique(natural),
+ body="\n".join(lines),
+ title=name or "Contact",
+ author_raw=name,
+ metadata={"uid": uid},
+ )
+
+
+def _parse_tabular(
+ entry: _Entry, report: ScanReport, *, delimiter: str
+) -> Iterator[RawItem]:
+ """Stream a CSV/TSV file as chunks of rows with the header as context.
+
+ The header is repeated in EVERY chunk on purpose: a chunk retrieved on
+ its own has to say what its columns mean, or the values are noise.
+ """
+ try:
+ stream = _text_stream(entry)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return
+ try:
+ reader = csv.reader(stream, delimiter=delimiter)
+ try:
+ header = next(reader)
+ except StopIteration:
+ return
+ header_line = "Columns: " + delimiter.join(header)
+ chunk: list[str] = []
+ first_row = 1
+ row_number = 0
+ for row in reader:
+ row_number += 1
+ chunk.append(delimiter.join(row))
+ if len(chunk) >= TABULAR_CHUNK_ROWS:
+ yield _tabular_item(entry, header_line, chunk, first_row, row_number)
+ chunk = []
+ first_row = row_number + 1
+ if chunk:
+ yield _tabular_item(entry, header_line, chunk, first_row, row_number)
+ except (csv.Error, OSError, UnicodeError, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ finally:
+ try:
+ stream.close()
+ except OSError: # pragma: no cover — closing a wrapper cannot fail
+ pass
+
+
+def _tabular_item(
+ entry: _Entry, header_line: str, rows: list[str], first: int, last: int
+) -> RawItem:
+ return _item(
+ entry,
+ natural_id=f"rows-{first:08d}-{last:08d}",
+ body=f"{header_line}\n\n" + "\n".join(rows),
+ title=f"{entry.name} rows {first}-{last}",
+ metadata={"row_start": first, "row_end": last},
+ )
+
+
+def _parse_jsonl(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ try:
+ stream = _text_stream(entry)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return
+ try:
+ chunk: list[str] = []
+ first_line = 1
+ line_number = 0
+ for raw in stream:
+ line = raw.strip()
+ line_number += 1
+ if not line:
+ continue
+ chunk.append(line[:MAX_JSONL_LINE_CHARS])
+ if len(chunk) >= TABULAR_CHUNK_ROWS:
+ yield _jsonl_item(entry, chunk, first_line, line_number)
+ chunk = []
+ first_line = line_number + 1
+ if chunk:
+ yield _jsonl_item(entry, chunk, first_line, line_number)
+ except (OSError, UnicodeError, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ finally:
+ try:
+ stream.close()
+ except OSError: # pragma: no cover
+ pass
+
+
+def _jsonl_item(
+ entry: _Entry, lines: list[str], first: int, last: int
+) -> RawItem:
+ return _item(
+ entry,
+ natural_id=f"lines-{first:08d}-{last:08d}",
+ body="\n".join(lines),
+ title=f"{entry.name} lines {first}-{last}",
+ metadata={"line_start": first, "line_end": last},
+ )
+
+
+def _parse_json(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ """One JSON document as bounded pretty text.
+
+ A document that does not parse is NOT dropped: it is imported as plain
+ text instead, because a half-valid export is still the user's data and
+ losing it silently would be worse than storing it unpretty.
+ """
+ text = _read_whole_text(entry, report)
+ if text is None:
+ return
+ try:
+ rendered = json.dumps(json.loads(text), indent=2, ensure_ascii=False)
+ except (ValueError, RecursionError):
+ rendered = text
+ yield _item(
+ entry,
+ natural_id="",
+ body=rendered,
+ title=entry.name,
+ )
+
+
+def _parse_text(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ text = _read_whole_text(entry, report)
+ if text is None:
+ return
+ yield _item(entry, natural_id="", body=text, title=_title_for_text(entry, text))
+
+
+def _parse_html(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ markup = _read_whole_text(entry, report)
+ if markup is None:
+ return
+ title = ""
+ match = re.search(r"<title[^>]*>(.*?)</title>", markup, re.IGNORECASE | re.DOTALL)
+ if match:
+ title = strip_html(match.group(1))[:200].strip()
+ yield _item(
+ entry,
+ natural_id="",
+ body=strip_html(markup),
+ title=title or Path(entry.name).stem,
+ )
+
+
+_H1_RE = re.compile(r"^#{1,3} +(.+?)\s*$", re.MULTILINE)
+
+
+def _title_for_text(entry: _Entry, body: str) -> str:
+ match = _H1_RE.search(body[:4000])
+ if match:
+ return match.group(1).strip()[:200]
+ for line in body[:2000].splitlines():
+ stripped = line.strip()
+ if stripped:
+ return stripped[:200]
+ return Path(entry.name).stem
+
+
+def _parse_pdf(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ """Extract a PDF's text page by page, stopping at the body cap.
+
+ Encrypted and structurally broken PDFs are skipped with a reason on the
+ record rather than failing the run — a folder of scans routinely holds
+ one file no extractor can open.
+ """
+ try:
+ from pypdf import PdfReader # noqa: PLC0415 — lazy (AP-26)
+ except Exception as exc: # noqa: BLE001 — a missing extra is not a crash
+ report.refuse(
+ entry.key,
+ "PDF files need the 'pypdf' package, which is not installed in "
+ f"this build ({type(exc).__name__})",
+ )
+ return
+
+ source: Any
+ if entry.disk_path is not None:
+ source = entry.disk_path
+ else:
+ try:
+ with entry.open_binary() as stream:
+ data = stream.read(MAX_BUFFERED_PDF_BYTES + 1)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return
+ if len(data) > MAX_BUFFERED_PDF_BYTES:
+ report.refuse(
+ entry.key,
+ "the PDF inside the archive is larger than "
+ f"{MAX_BUFFERED_PDF_BYTES // (1024 * 1024)} MB",
+ )
+ return
+ source = io.BytesIO(data)
+
+ try:
+ reader = PdfReader(source)
+ if reader.is_encrypted:
+ try:
+ opened = reader.decrypt("")
+ except Exception: # noqa: BLE001 — an unsupported cipher is a skip
+ opened = 0
+ if not opened:
+ report.refuse(entry.key, "the PDF is password protected")
+ return
+ pages = len(reader.pages)
+ except Exception as exc: # noqa: BLE001 — a broken PDF is a skip, not a stop
+ report.refuse(entry.key, f"the PDF could not be opened ({type(exc).__name__})")
+ return
+
+ chunks: list[str] = []
+ length = 0
+ extracted_pages = 0
+ for index in range(pages):
+ if length >= BODY_CAP:
+ break
+ try:
+ text = reader.pages[index].extract_text() or ""
+ except Exception as exc: # noqa: BLE001 — one bad page, not the file
+ log.debug(
+ "%s: page %d could not be extracted: %s",
+ entry.key,
+ index + 1,
+ exc,
+ )
+ continue
+ text = text.strip()
+ if not text:
+ continue
+ extracted_pages += 1
+ chunks.append(f"[page {index + 1}]\n{text}")
+ length += len(text)
+ if not chunks:
+ report.refuse(
+ entry.key,
+ "the PDF holds no extractable text (it is most likely a scan "
+ "without OCR)",
+ )
+ return
+ yield _item(
+ entry,
+ natural_id="",
+ body="\n\n".join(chunks),
+ title=_pdf_title(reader) or Path(entry.name).stem,
+ metadata={"pages": pages, "pages_with_text": extracted_pages},
+ )
+
+
+def _pdf_title(reader: Any) -> str:
+ try:
+ title = (reader.metadata or {}).get("/Title") or ""
+ except Exception: # noqa: BLE001 — broken metadata is not a broken PDF
+ return ""
+ return str(title).strip()[:200]
+
+
+# --- WhatsApp ---------------------------------------------------------------
+
+#: Matched message lines inspected before the file's date order is fixed.
+_WA_ORDER_PROBE_LINES = 500
+
+
+@dataclass(frozen=True, slots=True)
+class _WhatsAppLine:
+ date: str # YYYY-MM-DD
+ time: str # HH:MM
+ author: str
+ text: str
+
+
+def _wa_match(line: str) -> re.Match[str] | None:
+ return _WA_BRACKET_RE.match(line) or _WA_DASH_RE.match(line)
+
+
+def _wa_date_order(matches: list[re.Match[str]]) -> str:
+ """``"dmy"`` or ``"mdy"`` for one file, decided from its own numbers.
+
+ Day-first is the default because it is what most of the world's phones
+ write; a value above 12 in either position is hard evidence and wins over
+ the default.
+ """
+ for match in matches:
+ first, second = int(match.group("a")), int(match.group("b"))
+ if first > 12 and first <= 31:
+ return "dmy"
+ if second > 12 and second <= 31:
+ return "mdy"
+ return "dmy"
+
+
+def _wa_parse_line(match: re.Match[str], order: str) -> _WhatsAppLine | None:
+ a, b, c = int(match.group("a")), int(match.group("b")), int(match.group("c"))
+ if a > 31: # a four-digit year in front: an ISO-ish export
+ year, month, day = a, b, c
+ elif order == "dmy":
+ day, month, year = a, b, c
+ else:
+ month, day, year = a, b, c
+ if year < 100:
+ year += 2000 if year < 70 else 1900
+ hour, minute = int(match.group("hh")), int(match.group("mm"))
+ ampm = (match.group("ampm") or "").lower().replace(".", "")
+ if ampm.startswith("p") and hour < 12:
+ hour += 12
+ elif ampm.startswith("a") and hour == 12:
+ hour = 0
+ try:
+ moment = datetime(year, month, day, hour, minute, tzinfo=UTC)
+ except ValueError:
+ return None
+ return _WhatsAppLine(
+ date=moment.strftime("%Y-%m-%d"),
+ time=moment.strftime("%H:%M"),
+ author=(match.group("author") or "").strip(),
+ text=(match.group("text") or "").strip(),
+ )
+
+
+def _parse_whatsapp(entry: _Entry, report: ScanReport) -> Iterator[RawItem]:
+ """One item per (chat, day) — a day of a conversation is one memory.
+
+ WhatsApp writes local wall-clock times with no zone anywhere in the
+ export, so the timestamps are read as UTC and the item says so in its
+ metadata rather than pretending to a precision the file does not carry.
+ """
+ chat = chat_name_from_filename(entry.name)
+ try:
+ stream = _text_stream(entry)
+ except (OSError, zipfile.BadZipFile, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ return
+ try:
+ yield from _iter_whatsapp_days(entry, stream, chat)
+ except (OSError, UnicodeError, RuntimeError) as exc:
+ report.refuse(entry.key, f"{type(exc).__name__}: {exc}")
+ finally:
+ try:
+ stream.close()
+ except OSError: # pragma: no cover
+ pass
+
+
+def _iter_whatsapp_days(
+ entry: _Entry, stream: Any, chat: str
+) -> Iterator[RawItem]:
+ probe: list[str] = []
+ probe_matches: list[re.Match[str]] = []
+ for raw in stream:
+ line = _normalize_line(raw.rstrip("\r\n"))
+ probe.append(line)
+ match = _wa_match(line)
+ if match is not None:
+ probe_matches.append(match)
+ if len(probe_matches) >= _WA_ORDER_PROBE_LINES:
+ break
+ order = _wa_date_order(probe_matches)
+
+ def _lines() -> Iterator[str]:
+ yield from probe
+ for raw in stream:
+ yield _normalize_line(raw.rstrip("\r\n"))
+
+ current_date = ""
+ first_time = ""
+ buffer: list[str] = []
+ authors: list[str] = []
+ for line in _lines():
+ match = _wa_match(line)
+ if match is None:
+ if buffer: # a wrapped continuation of the previous message
+ buffer[-1] = f"{buffer[-1]}\n{line}"
+ continue
+ parsed = _wa_parse_line(match, order)
+ if parsed is None:
+ continue
+ if parsed.date != current_date:
+ if buffer:
+ yield _whatsapp_item(
+ entry, chat, current_date, first_time, buffer, authors
+ )
+ current_date, first_time = parsed.date, parsed.time
+ buffer, authors = [], []
+ rendered = (
+ f"{parsed.time} {parsed.author}: {parsed.text}"
+ if parsed.author
+ else f"{parsed.time} {parsed.text}"
+ )
+ buffer.append(rendered)
+ if parsed.author and parsed.author not in authors:
+ authors.append(parsed.author)
+ if buffer:
+ yield _whatsapp_item(entry, chat, current_date, first_time, buffer, authors)
+
+
+def _whatsapp_item(
+ entry: _Entry,
+ chat: str,
+ date: str,
+ first_time: str,
+ lines: list[str],
+ authors: list[str],
+) -> RawItem:
+ return _item(
+ entry,
+ natural_id=date,
+ body="\n".join(lines),
+ title=f"{chat} ({date})",
+ thread_key=chat,
+ author_raw=", ".join(authors[:10]),
+ timestamp_utc=f"{date}T{first_time or '00:00'}:00Z",
+ metadata={
+ "chat": chat,
+ "day": date,
+ "messages": len(lines),
+ "participants": authors[:20],
+ # No zone is recorded anywhere in a WhatsApp export.
+ "timezone": "assumed-utc",
+ },
+ )
+
+
+_PARSERS: dict[str, Callable[[_Entry, ScanReport], Iterator[RawItem]]] = {
+ "mbox": _parse_mbox,
+ "eml": _parse_eml,
+ "ics": _parse_ics,
+ "vcard": _parse_vcard,
+ "whatsapp": _parse_whatsapp,
+ "csv": lambda entry, report: _parse_tabular(entry, report, delimiter=","),
+ "tsv": lambda entry, report: _parse_tabular(entry, report, delimiter="\t"),
+ "jsonl": _parse_jsonl,
+ "json": _parse_json,
+ "pdf": _parse_pdf,
+ "html": _parse_html,
+ "markdown": _parse_text,
+ "text": _parse_text,
+}
+
+
+# ---------------------------------------------------------------------------
+# Preview / scan
+# ---------------------------------------------------------------------------
+
+
+def _count_occurrences(entry: _Entry, needle: bytes, remaining: list[int]) -> tuple[int, bool]:
+ """Count ``needle`` at line starts, bounded by a shared byte budget."""
+ total = 0
+ exact = True
+ try:
+ with entry.open_binary() as stream:
+ for line in stream:
+ remaining[0] -= len(line)
+ if line[: len(needle)].upper() == needle:
+ total += 1
+ if remaining[0] <= 0:
+ exact = False
+ break
+ except (OSError, zipfile.BadZipFile, RuntimeError):
+ return total, False
+ return total, exact
+
+
+def _count_mbox_messages(entry: _Entry, remaining: list[int]) -> tuple[int, bool]:
+ """Count mbox separators with the SAME rule the parser splits on.
+
+ A body line that happens to begin with ``From `` is not a separator, so
+ counting every such line would inflate the preview against the import
+ that follows it.
+ """
+ total = 0
+ exact = True
+ previous_blank = True
+ try:
+ with entry.open_binary() as stream:
+ for line in stream:
+ remaining[0] -= len(line)
+ if previous_blank and line.startswith(b"From "):
+ total += 1
+ previous_blank = not line.strip(b"\r\n")
+ if remaining[0] <= 0:
+ exact = False
+ break
+ except (OSError, zipfile.BadZipFile, RuntimeError):
+ return total, False
+ return total, exact
+
+
+def _count_lines(entry: _Entry, remaining: list[int]) -> tuple[int, bool]:
+ total = 0
+ exact = True
+ try:
+ with entry.open_binary() as stream:
+ for line in stream:
+ remaining[0] -= len(line)
+ if line.strip():
+ total += 1
+ if remaining[0] <= 0:
+ exact = False
+ break
+ except (OSError, zipfile.BadZipFile, RuntimeError):
+ return total, False
+ return total, exact
+
+
+def _count_whatsapp_days(entry: _Entry, remaining: list[int]) -> tuple[int, bool]:
+ days: set[str] = set()
+ matches: list[re.Match[str]] = []
+ exact = True
+ try:
+ with entry.open_binary() as stream:
+ for raw in stream:
+ remaining[0] -= len(raw)
+ line = _normalize_line(raw.decode("utf-8", errors="replace").rstrip())
+ match = _wa_match(line)
+ if match is not None:
+ matches.append(match)
+ days.add(f"{match.group('a')}-{match.group('b')}-{match.group('c')}")
+ if remaining[0] <= 0 or len(days) > 20000:
+ exact = False
+ break
+ except (OSError, zipfile.BadZipFile, RuntimeError):
+ return len(days), False
+ return len(days), exact
+
+
+def _estimate_items(
+ entry: _Entry, remaining: list[int]
+) -> tuple[int, bool]:
+ """``(item estimate, exact)`` for one entry, without parsing any body."""
+ fmt = entry.fmt
+ if fmt == "mbox":
+ return _count_mbox_messages(entry, remaining)
+ if fmt == "ics":
+ return _count_occurrences(entry, b"BEGIN:VEVENT", remaining)
+ if fmt == "vcard":
+ return _count_occurrences(entry, b"BEGIN:VCARD", remaining)
+ if fmt == "whatsapp":
+ return _count_whatsapp_days(entry, remaining)
+ if fmt in ("csv", "tsv"):
+ rows, exact = _count_lines(entry, remaining)
+ body_rows = max(0, rows - 1)
+ return -(-body_rows // TABULAR_CHUNK_ROWS), exact
+ if fmt == "jsonl":
+ lines, exact = _count_lines(entry, remaining)
+ return -(-lines // TABULAR_CHUNK_ROWS), exact
+ # eml / json / pdf / html / markdown / text are exactly one item each.
+ return 1, True
+
+
+def scan_export(
+ path: str | Path, *, budget_files: int = 5000
+) -> dict[str, Any]:
+ """Report what a drop holds, without importing anything.
+
+ A cheap streaming pass: it detects each file's format, counts the records
+ inside it, and never materialises a body. Counting still means reading
+ bytes, so the byte budget (:data:`SCAN_BYTES_BUDGET`) and ``budget_files``
+ bound the work — when either runs out the answer says ``truncated`` and
+ the affected formats stop claiming to be ``exact``, instead of quietly
+ reporting a number that is only part of the truth.
+
+ BLOCKING — callers run it through ``asyncio.to_thread``.
+ """
+ root = Path(str(path)).expanduser()
+ report = ScanReport()
+ if not root.exists():
+ report.note("Nothing is at that path.")
+ payload = report.as_dict()
+ payload.update({"path": str(root), "exists": False, "is_dir": False})
+ return payload
+
+ budget = _Budget()
+ remaining = [SCAN_BYTES_BUDGET]
+ walked = 0
+ for entry in _walk_entries(root, report, budget):
+ walked += 1
+ if walked > max(1, int(budget_files)):
+ report.truncated = True
+ report.note(
+ f"More than {budget_files} files were found; the preview "
+ "stopped counting there. The import itself reads everything."
+ )
+ break
+ count, exact = _estimate_items(entry, remaining)
+ if not exact:
+ report.truncated = True
+ report.add_items(entry.fmt, count, exact=exact)
+ if budget.exhausted:
+ report.truncated = True
+ payload = report.as_dict()
+ payload.update({"path": str(root), "exists": True, "is_dir": root.is_dir()})
+ return payload
+
+
+# ---------------------------------------------------------------------------
+# Upload destination
+# ---------------------------------------------------------------------------
+
+
+def uploads_dir(data_dir: str | Path | None = None) -> Path:
+ """The directory dropped export files are streamed into.
+
+ Anchored exactly like :func:`jarvis.ultrawiki.store.resolve_ultrawiki_db_path`
+ so a relative ``memory.data_dir`` ("./data", the default) resolves against
+ the repo root rather than whatever the process CWD happens to be.
+ """
+ from jarvis.core.paths import repo_root # noqa: PLC0415 — lazy (AP-26)
+
+ raw = Path(data_dir) if data_dir is not None else Path("data")
+ directory = raw if raw.is_absolute() else repo_root() / raw
+ return (directory / "ultrawiki" / "uploads").resolve(strict=False)
+
+
+# ---------------------------------------------------------------------------
+# The connector
+# ---------------------------------------------------------------------------
+
+
+def _origin_of(checkpoint: str) -> str:
+ """The on-disk file an ``external_id`` came from (the resume unit).
+
+ Split at the FIRST ``#`` and the FIRST ``!``. A path that itself contains
+ one of those characters therefore yields a SHORTER prefix, which sorts
+ earlier and makes the resume re-read more than it strictly must — the
+ safe direction, since every re-read upserts as unchanged.
+ """
+ head = checkpoint.split("#", 1)[0]
+ return head.split("!", 1)[0]
+
+
+def _drain(iterator: Iterator[RawItem], size: int) -> list[RawItem]:
+ """Pull up to ``size`` items out of the blocking walk (worker thread)."""
+ batch: list[RawItem] = []
+ for item in iterator:
+ batch.append(item)
+ if len(batch) >= size:
+ break
+ return batch
+
+
+class ExportImportConnector:
+ """Import a dropped export file or folder — whatever formats it holds.
+
+ Config keys:
+
+ - ``path`` (required): the file or folder to read. A folder is walked
+ recursively; hidden entries and ``__MACOSX`` are skipped.
+
+ Everything else is detection. See the module docstring for the resume
+ contract and the archive rules.
+ """
+
+ id = "export-import"
+ label = "Export file import"
+ auth = AuthKind.EXPORT_FILE
+ capabilities = ConnectorCapabilities(
+ backfill=True,
+ # An export file is a snapshot: there is no cursor to poll and no
+ # tombstone to detect. Re-importing the same drop is a full,
+ # idempotent re-read.
+ incremental=IncrementalMode.NONE,
+ deletes=False,
+ )
+
+ async def backfill(
+ self, ctx: ConnectorContext, checkpoint: str | None = None
+ ) -> AsyncIterator[RawItem]:
+ root = await asyncio.to_thread(self._resolve_path, ctx)
+ if root is None:
+ return
+ report = ScanReport()
+ iterator = self._iter_items(root, checkpoint, report)
+ try:
+ while True:
+ batch = await asyncio.to_thread(_drain, iterator, ITEM_BATCH)
+ if not batch:
+ break
+ for item in batch:
+ yield item
+ finally:
+ # Closing the blocking generator runs its `finally` blocks, which
+ # is what closes every archive and stream it still holds. Cheap
+ # enough to do inline even on a cancelled sync.
+ iterator.close()
+ self._log_report(ctx, report)
+
+ async def incremental(
+ self, ctx: ConnectorContext, cursor: str | None = None
+ ) -> AsyncIterator[RawItem]:
+ """No incremental mode: a dropped file does not change under us.
+
+ Declared ``IncrementalMode.NONE``, so the scheduler never calls this;
+ it exists to satisfy the protocol and yields nothing.
+ """
+ return
+ yield # pragma: no cover - unreachable, keeps this an async generator
+
+ # ------------------------------------------------------------------
+ # Blocking internals — only ever reached through asyncio.to_thread
+ # ------------------------------------------------------------------
+
+ def _resolve_path(self, ctx: ConnectorContext) -> Path | None:
+ raw = ctx.config.get("path") or ctx.config.get("root")
+ if not raw:
+ log.warning(
+ "%s: source %s has no 'path' configured; yielding nothing",
+ self.id,
+ ctx.source_id,
+ )
+ return None
+ root = Path(str(raw)).expanduser()
+ if not root.exists():
+ log.warning(
+ "%s: %s does not exist; yielding nothing", self.id, root
+ )
+ return None
+ return root
+
+ def _iter_items(
+ self, root: Path, checkpoint: str | None, report: ScanReport
+ ) -> Iterator[RawItem]:
+ resume_origin = _origin_of(checkpoint) if checkpoint else ""
+ budget = _Budget()
+ for entry in _walk_entries(root, report, budget):
+ if resume_origin and entry.origin < resume_origin:
+ continue
+ parser = _PARSERS.get(entry.fmt)
+ if parser is None: # pragma: no cover - detection only emits known ids
+ report.count_unknown(entry.name, entry.size)
+ continue
+ yield from parser(entry, report)
+
+ def _log_report(self, ctx: ConnectorContext, report: ScanReport) -> None:
+ """One honest summary line per run: what was read, what was not.
+
+ The notes and refusals are the WHOLE point on a run that produced
+ nothing — "the archive nests deeper than we follow" is exactly the
+ line a user needs when their import came back empty.
+ """
+ if not (
+ report.files_seen
+ or report.unreadable
+ or report.notes
+ or report.unknown
+ ):
+ return
+ formats = ", ".join(
+ f"{fmt}x{row['files']}" for fmt, row in sorted(report.formats.items())
+ )
+ log.info(
+ "%s: source %s read %d file(s) [%s]; %d skipped as unrecognised, "
+ "%d could not be read",
+ self.id,
+ ctx.source_id,
+ report.files_seen,
+ formats or "none",
+ sum(report.unknown.values()),
+ len(report.unreadable),
+ )
+ for row in report.unreadable[:20]:
+ log.info("%s: skipped %s — %s", self.id, row["path"], row["reason"])
+ for note in report.notes:
+ log.warning("%s: %s", self.id, note)
diff --git a/tests/fixtures/ultrawiki/README.md b/tests/fixtures/ultrawiki/README.md
index 3511540d4d..f25f77e0ed 100644
--- a/tests/fixtures/ultrawiki/README.md
+++ b/tests/fixtures/ultrawiki/README.md
@@ -8,6 +8,15 @@ Tiny, committed source trees the connector tests walk read-only:
default extension filter) and a `.bin` file (excluded by default).
- `wiki_vault/` — a minimal built-in-wiki vault with one page under
`entities/` and one under `concepts/`.
+- `export/` — one tiny real file per format the export-import connector
+ detects: an mbox with two mails, a single `.eml`, an `.ics` with one
+ event, a folded `.vcf` with two contacts, both WhatsApp line families
+ (bracketed and dashed, and the `mit`/`with` filename variants), a `.csv`,
+ a `.jsonl`, a `.json`, a `.md` and an `.html`. Everything here is TEXT on
+ purpose: the archive, the PDF and the binary "unknown format" file are
+ built at test time into `tmp_path` (zips and PDFs are generated by
+ `zipfile` / `pypdf`, so committing them would only add opaque bytes to the
+ history).
Tests that need controlled modification times (cursor round-trips) build
their trees in `tmp_path` instead; these committed trees only pin the
diff --git a/tests/fixtures/ultrawiki/export/calendar/schedule.ics b/tests/fixtures/ultrawiki/export/calendar/schedule.ics
new file mode 100644
index 0000000000..4c5361d7fe
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/calendar/schedule.ics
@@ -0,0 +1,15 @@
+BEGIN:VCALENDAR
+VERSION:2.0
+PRODID:-//Personal Jarvis//Export Import Fixture//EN
+BEGIN:VEVENT
+DTSTAMP:20240104T090000Z
+DTSTART:20240110T140000Z
+DTEND:20240110T150000Z
+SUMMARY:Telescope maintenance review
+LOCATION:Observatory, room 2
+ORGANIZER:MAILTO:[email protected]
+ATTENDEE:MAILTO:[email protected]
+DESCRIPTION:Walk through the maintenance schedule for the coming quarter.
+END:VEVENT
+END:VCALENDAR
diff --git a/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat mit Bruno.txt b/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat mit Bruno.txt
new file mode 100644
index 0000000000..94b631bfa3
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat mit Bruno.txt
@@ -0,0 +1,3 @@
+15/03/2024, 08:30 - Bruno: The upload finished last night.
+15/03/2024, 08:31 - Ada: Perfect, I will index it today.
+16/03/2024, 21:04 - Ada: Indexing done, the observatory log is in.
diff --git a/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat with Ada.txt b/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat with Ada.txt
new file mode 100644
index 0000000000..bc3eb346ff
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/chats/WhatsApp Chat with Ada.txt
@@ -0,0 +1,3 @@
+[01.02.24, 09:12:03] Ada: Morning - did the ledger land?
+[01.02.24, 09:12:40] Bruno: Yes, filed under maintenance.
+[02.02.24, 18:05:11] Ada: Telescope review moved to Thursday.
diff --git a/tests/fixtures/ultrawiki/export/contacts/people.vcf b/tests/fixtures/ultrawiki/export/contacts/people.vcf
new file mode 100644
index 0000000000..0fc0ef8ea1
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/contacts/people.vcf
@@ -0,0 +1,16 @@
+BEGIN:VCARD
+VERSION:3.0
+UID:contact-001
+FN:Ada Lovelace
+N:Lovelace;Ada;;;
+EMAIL;TYPE=WORK:[email protected]
+TEL;TYPE=CELL:+44 20 7946 0000
+ORG:Analytical Engine Works
+END:VCARD
+BEGIN:VCARD
+VERSION:3.0
+FN:Bruno Marek
+EMAIL;TYPE=HOME:[email protected]
+NOTE:Handles the telescope maintenance
+ budget for the observatory.
+END:VCARD
diff --git a/tests/fixtures/ultrawiki/export/mail/inbox.mbox b/tests/fixtures/ultrawiki/export/mail/inbox.mbox
new file mode 100644
index 0000000000..dc8e6ddf04
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/mail/inbox.mbox
@@ -0,0 +1,19 @@
+From [email protected] Mon Jan 01 09:00:00 2024
+Message-ID: <[email protected]>
+From: Ada Lovelace <[email protected]>
+To: Bruno Marek <[email protected]>
+Date: Mon, 01 Jan 2024 09:00:00 +0000
+Subject: Quarterly ledger
+Content-Type: text/plain; charset="utf-8"
+
+The quarterly ledger reconciliation is finished.
+
+From [email protected] Tue Jan 02 11:30:00 2024
+Message-ID: <[email protected]>
+From: Bruno Marek <[email protected]>
+To: Ada Lovelace <[email protected]>
+Date: Tue, 02 Jan 2024 11:30:00 +0000
+Subject: Re: Quarterly ledger
+Content-Type: text/plain; charset="utf-8"
+
+Thanks - I filed it under the telescope maintenance budget.
diff --git a/tests/fixtures/ultrawiki/export/mail/single.eml b/tests/fixtures/ultrawiki/export/mail/single.eml
new file mode 100644
index 0000000000..3e4acd1675
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/mail/single.eml
@@ -0,0 +1,8 @@
+Message-ID: <[email protected]>
+From: Clara Nunes <[email protected]>
+To: Ada Lovelace <[email protected]>
+Date: Wed, 03 Jan 2024 08:15:00 +0000
+Subject: Fwd: Quarterly ledger
+Content-Type: text/plain; charset="utf-8"
+
+Forwarding the ledger note for the archive.
diff --git a/tests/fixtures/ultrawiki/export/notes/readme.md b/tests/fixtures/ultrawiki/export/notes/readme.md
new file mode 100644
index 0000000000..dc01272653
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/notes/readme.md
@@ -0,0 +1,3 @@
+# Telescope maintenance
+
+Notes collected while the observatory dome was closed for servicing.
diff --git a/tests/fixtures/ultrawiki/export/tables/events.jsonl b/tests/fixtures/ultrawiki/export/tables/events.jsonl
new file mode 100644
index 0000000000..4d8f1ef7a1
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/tables/events.jsonl
@@ -0,0 +1,3 @@
+{"event": "ledger_filed", "actor": "ada", "at": "2024-01-01T09:00:00Z"}
+{"event": "budget_moved", "actor": "bruno", "at": "2024-01-02T11:30:00Z"}
+{"event": "review_scheduled", "actor": "ada", "at": "2024-01-10T14:00:00Z"}
diff --git a/tests/fixtures/ultrawiki/export/tables/ledger.csv b/tests/fixtures/ultrawiki/export/tables/ledger.csv
new file mode 100644
index 0000000000..80d97449f6
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/tables/ledger.csv
@@ -0,0 +1,4 @@
+name,email,city
+Ada Lovelace,[email protected],London
+Bruno Marek,[email protected],Krakow
+Clara Nunes,[email protected],Lisbon
diff --git a/tests/fixtures/ultrawiki/export/tables/settings.json b/tests/fixtures/ultrawiki/export/tables/settings.json
new file mode 100644
index 0000000000..543b685929
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/tables/settings.json
@@ -0,0 +1 @@
+{"observatory": {"dome": "closed", "next_service": "2024-04-01"}, "owner": "Ada Lovelace"}
diff --git a/tests/fixtures/ultrawiki/export/web/page.html b/tests/fixtures/ultrawiki/export/web/page.html
new file mode 100644
index 0000000000..85833066f9
--- /dev/null
+++ b/tests/fixtures/ultrawiki/export/web/page.html
@@ -0,0 +1,10 @@
+<!doctype html>
+<html>
+ <head><title>Observatory log</title></head>
+ <body>
+ <h1>Observatory log</h1>
+ <p>The dome was serviced on the tenth&nbsp;of January.</p>
+ <script>console.log("this must not reach the body");</script>
+ <style>body { color: red; }</style>
+ </body>
+</html>
diff --git a/tests/unit/ultrawiki/test_connector_catalog.py b/tests/unit/ultrawiki/test_connector_catalog.py
index a32594a9f8..66440b85d2 100644
--- a/tests/unit/ultrawiki/test_connector_catalog.py
+++ b/tests/unit/ultrawiki/test_connector_catalog.py
@@ -68,6 +68,17 @@ class TestCatalogShape:
shipped = set(builtin_connectors()) - {BRIDGE_CONNECTOR_ID}
assert {spec.id for spec in catalog.BUILTIN_CONNECTORS} == shipped
+ def test_the_export_on_ramp_is_offered_as_a_vendor_free_builtin(self):
+ """It belongs to no vendor: the formats it reads are open standards,
+ so it must carry a neutral glyph rather than borrow a service's mark."""
+ spec = catalog.get_connector("export-import")
+ assert spec is not None
+ assert spec.kind == "builtin"
+ assert spec.brand == "archive"
+ assert spec.brand in catalog.NEUTRAL_BRANDS
+ assert spec.status == "available"
+ assert catalog.as_dict(spec)["connector"] == "export-import"
+
def test_the_bridge_itself_is_not_offered_as_a_card(self):
assert catalog.get_connector(BRIDGE_CONNECTOR_ID) is None
assert not any(
diff --git a/tests/unit/ultrawiki/test_connector_roster.py b/tests/unit/ultrawiki/test_connector_roster.py
index b45ba0e874..49f13afa5e 100644
--- a/tests/unit/ultrawiki/test_connector_roster.py
+++ b/tests/unit/ultrawiki/test_connector_roster.py
@@ -227,6 +227,7 @@ class TestSourceIdentity:
def test_brand_and_kind_are_derived_for_builtins_and_bridges(self):
assert _connector_identity("local-folder", "") == ("folder", "builtin")
assert _connector_identity("obsidian-vault", "") == ("vault", "builtin")
+ assert _connector_identity("export-import", "") == ("archive", "builtin")
assert _connector_identity("plugin-bridge", "plugin:slack") == (
"slack",
"bridge",
diff --git a/tests/unit/ultrawiki/test_connectors.py b/tests/unit/ultrawiki/test_connectors.py
index 5be65d1b27..dc78e75d19 100644
--- a/tests/unit/ultrawiki/test_connectors.py
+++ b/tests/unit/ultrawiki/test_connectors.py
@@ -60,13 +60,14 @@ def _ctx(config: dict) -> ConnectorContext:
class TestRegistry:
- def test_builtin_connectors_expose_five_fresh_factories(self):
+ def test_builtin_connectors_expose_six_fresh_factories(self):
registry = builtin_connectors()
assert set(registry) == {
"obsidian-vault",
"local-folder",
"jarvis-conversations",
"normal-wiki",
+ "export-import",
"plugin-bridge",
}
for name, factory in registry.items():
diff --git a/tests/unit/ultrawiki/test_export_import.py b/tests/unit/ultrawiki/test_export_import.py
new file mode 100644
index 0000000000..012453052d
--- /dev/null
+++ b/tests/unit/ultrawiki/test_export_import.py
@@ -0,0 +1,749 @@
+"""The export-import connector: detection, per-format parsing, archives, limits.
+
+The connector's promise is "drop whatever you have and it goes in", so the
+tests are shaped around the ways that promise breaks:
+
+* a format detected by its EXTENSION when the extension lies (a WhatsApp chat
+ and a vCard dump are both ``.txt``),
+* an archive that must be read without ever touching the disk, and that must
+ not be usable to fill this machine's memory,
+* an interrupted import that has to resume without losing items,
+* and the honest half — an encrypted PDF, an unreadable file and a binary blob
+ are COUNTED and reported, never silently dropped and never fatal.
+
+Everything runs offline against tiny committed fixtures; the archive, the PDFs
+and the binary file are generated into ``tmp_path`` so no opaque bytes live in
+the history.
+"""
+
+from __future__ import annotations
+
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from jarvis.ultrawiki.connectors import builtin_connectors
+from jarvis.ultrawiki.connectors.export_import import (
+ EXPORT_FORMATS,
+ ExportImportConnector,
+ chat_name_from_filename,
+ detect_format,
+ scan_export,
+ uploads_dir,
+)
+from jarvis.ultrawiki.types import (
+ AuthKind,
+ ConnectorContext,
+ IncrementalMode,
+ RawItem,
+ UWConnector,
+)
+
+FIXTURES = Path(__file__).resolve().parents[3] / "tests" / "fixtures" / "ultrawiki" / "export"
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+async def _items(path: Path | str, checkpoint: str | None = None) -> list[RawItem]:
+ connector = ExportImportConnector()
+ ctx = ConnectorContext(source_id="test-export", config={"path": str(path)})
+ return [item async for item in connector.backfill(ctx, checkpoint)]
+
+
+def _by_format(items: list[RawItem], fmt: str) -> list[RawItem]:
+ return [item for item in items if item.metadata.get("format") == fmt]
+
+
+def _one(items: list[RawItem], external_id_suffix: str) -> RawItem:
+ matches = [i for i in items if i.external_id.endswith(external_id_suffix)]
+ assert len(matches) == 1, f"{external_id_suffix} -> {[i.external_id for i in matches]}"
+ return matches[0]
+
+
+def _make_pdf(path: Path, pages: list[str]) -> Path:
+ """A real, tiny PDF written at test time (no binary fixture in git)."""
+ pypdf = pytest.importorskip("pypdf")
+ writer = pypdf.PdfWriter()
+ for text in pages:
+ page = writer.add_blank_page(width=200, height=200)
+ writer.pages[-1] # touch, keeps the intent explicit
+ page.merge_page(_text_page(pypdf, text))
+ with path.open("wb") as handle:
+ writer.write(handle)
+ return path
+
+
+def _text_page(pypdf, text: str):
+ """A one-line text page built through pypdf's own generic object model."""
+ from pypdf.generic import DecodedStreamObject, DictionaryObject, NameObject
+
+ writer = pypdf.PdfWriter()
+ page = writer.add_blank_page(width=200, height=200)
+ content = DecodedStreamObject()
+ content.set_data(
+ f"BT /F1 12 Tf 20 100 Td ({text}) Tj ET".encode("latin-1", errors="replace")
+ )
+ page[NameObject("/Contents")] = writer._add_object(content) # noqa: SLF001
+ font = DictionaryObject()
+ font.update(
+ {
+ NameObject("/Type"): NameObject("/Font"),
+ NameObject("/Subtype"): NameObject("/Type1"),
+ NameObject("/BaseFont"): NameObject("/Helvetica"),
+ }
+ )
+ resources = DictionaryObject()
+ fonts = DictionaryObject()
+ fonts[NameObject("/F1")] = writer._add_object(font) # noqa: SLF001
+ resources[NameObject("/Font")] = fonts
+ page[NameObject("/Resources")] = resources
+ return page
+
+
+# ---------------------------------------------------------------------------
+# Contract + registration
+# ---------------------------------------------------------------------------
+
+
+class TestConnectorContract:
+ def test_it_satisfies_the_connector_protocol(self):
+ connector = ExportImportConnector()
+ assert isinstance(connector, UWConnector)
+ assert connector.id == "export-import"
+ assert connector.auth is AuthKind.EXPORT_FILE
+
+ def test_a_dropped_export_has_no_cursor_and_no_deletes(self):
+ """A snapshot cannot be polled and cannot report a removal."""
+ caps = ExportImportConnector.capabilities
+ assert caps.backfill is True
+ assert caps.incremental is IncrementalMode.NONE
+ assert caps.deletes is False
+
+ def test_it_is_registered_as_a_builtin(self):
+ registry = builtin_connectors()
+ assert "export-import" in registry
+ assert isinstance(registry["export-import"](), ExportImportConnector)
+
+ async def test_incremental_yields_nothing(self):
+ connector = ExportImportConnector()
+ ctx = ConnectorContext(source_id="s", config={"path": str(FIXTURES)})
+ assert [item async for item in connector.incremental(ctx)] == []
+
+ async def test_a_missing_path_yields_nothing_instead_of_raising(self, tmp_path):
+ assert await _items(tmp_path / "not-here") == []
+
+ async def test_no_path_configured_yields_nothing(self):
+ connector = ExportImportConnector()
+ ctx = ConnectorContext(source_id="s", config={})
+ assert [item async for item in connector.backfill(ctx)] == []
+
+
+# ---------------------------------------------------------------------------
+# Detection
+# ---------------------------------------------------------------------------
+
+
+class TestDetection:
+ def test_content_magic_beats_a_lying_extension(self):
+ """An export's extension is routinely wrong; the bytes are not."""
+ assert detect_format("notes.txt", b"BEGIN:VCARD\r\nFN:Ada\r\n") == "vcard"
+ assert detect_format("notes.txt", b"BEGIN:VCALENDAR\r\n") == "ics"
+ assert detect_format("data.txt", b"%PDF-1.7\n%...") == "pdf"
+ assert detect_format("blob", b"PK\x03\x04rest") == "zip"
+
+ def test_a_takeout_mail_file_without_an_extension_is_still_an_mbox(self):
+ head = b"From [email protected] Mon Jan 01 09:00:00 2024\nSubject: hi\n\nbody"
+ assert detect_format("Inbox", head) == "mbox"
+
+ def test_both_whatsapp_line_families_are_recognised_as_chats(self):
+ bracket = b"[01.02.24, 09:12:03] Ada: hi\n[01.02.24, 09:13:00] Bruno: yo\n"
+ dash = b"15/03/2024, 08:30 - Bruno: hi\n15/03/2024, 08:31 - Ada: yo\n"
+ assert detect_format("chat.txt", bracket) == "whatsapp"
+ assert detect_format("chat.txt", dash) == "whatsapp"
+
+ def test_a_plain_text_file_stays_plain_text(self):
+ assert detect_format("notes.txt", b"just some notes\n") == "text"
+ assert detect_format("readme.md", b"# Title\n") == "markdown"
+
+ def test_a_binary_blob_is_not_a_format(self):
+ assert detect_format("image.bin", bytes([0, 1, 2, 3, 0, 255])) == ""
+
+ def test_the_bom_a_windows_exporter_leaves_does_not_hide_the_magic(self):
+ assert detect_format("cal.txt", b"\xef\xbb\xbfBEGIN:VCALENDAR\r\n") == "ics"
+
+ @pytest.mark.parametrize(
+ ("filename", "expected"),
+ [
+ ("WhatsApp Chat with Ada.txt", "Ada"),
+ # i18n-allow: the German filename token WhatsApp itself writes
+ ("WhatsApp Chat mit Bruno Marek.txt", "Bruno Marek"),
+ ("Chat de WhatsApp con Clara.txt", "Clara"),
+ ("some-random-export.txt", "some-random-export"),
+ ],
+ )
+ def test_the_chat_name_comes_out_of_the_filename(self, filename, expected):
+ assert chat_name_from_filename(filename) == expected
+
+
+# ---------------------------------------------------------------------------
+# Per-format parsing
+# ---------------------------------------------------------------------------
+
+
+class TestMail:
+ async def test_an_mbox_yields_one_item_per_message(self):
+ items = _by_format(await _items(FIXTURES / "mail" / "inbox.mbox"), "mbox")
+ assert len(items) == 2
+
+ async def test_a_mail_carries_its_message_id_headers_and_date(self):
+ items = await _items(FIXTURES / "mail" / "inbox.mbox")
+ first = _one(items, "#[email protected]")
+ assert first.title == "Quarterly ledger"
+ assert first.timestamp_utc == "2024-01-01T09:00:00Z"
+ assert first.author_raw == "Ada Lovelace <[email protected]>"
+ assert "To: Bruno Marek <[email protected]>" in first.body
+ assert "The quarterly ledger reconciliation is finished." in first.body
+ assert first.metadata["message_id"] == "[email protected]"
+
+ async def test_a_reply_shares_the_thread_key_of_its_subject(self):
+ items = await _items(FIXTURES / "mail" / "inbox.mbox")
+ keys = {item.thread_key for item in items}
+ assert keys == {"quarterly ledger"}
+
+ async def test_a_single_eml_is_one_item_keyed_by_its_file(self):
+ items = await _items(FIXTURES / "mail" / "single.eml")
+ assert len(items) == 1
+ assert items[0].external_id == "single.eml"
+ assert items[0].thread_key == "quarterly ledger"
+
+ async def test_a_mail_without_a_message_id_still_gets_a_stable_id(self, tmp_path):
+ (tmp_path / "no-id.mbox").write_text(
+ "From [email protected] Mon Jan 01 09:00:00 2024\n"
+ "From: A <[email protected]>\n"
+ "Subject: No identifier\n"
+ "\n"
+ "body text\n",
+ encoding="utf-8",
+ )
+ first = (await _items(tmp_path))[0]
+ second = (await _items(tmp_path))[0]
+ assert first.external_id == second.external_id
+ assert first.external_id.startswith("no-id.mbox#")
+
+
+class TestCalendarAndContacts:
+ async def test_an_ics_event_carries_uid_times_and_attendees(self):
+ items = await _items(FIXTURES / "calendar" / "schedule.ics")
+ assert len(items) == 1
+ event = items[0]
+ assert event.external_id == "schedule.ics#[email protected]"
+ assert event.title == "Telescope maintenance review"
+ assert event.timestamp_utc == "2024-01-10T14:00:00Z"
+ assert "Location: Observatory, room 2" in event.body
+ assert "[email protected]" in event.body
+ assert "Walk through the maintenance schedule" in event.body
+ assert event.metadata["uid"] == "[email protected]"
+
+ async def test_vcards_become_one_item_each_with_unfolded_values(self):
+ items = await _items(FIXTURES / "contacts" / "people.vcf")
+ assert len(items) == 2
+ ada = _one(items, "#contact-001")
+ assert ada.title == "Ada Lovelace"
+ assert "Email: [email protected]" in ada.body
+ bruno = next(i for i in items if i.title == "Bruno Marek")
+ # The folded NOTE (continuation line) must arrive as one value.
+ assert "budget for the observatory" in bruno.body
+
+ async def test_a_vcard_photo_blob_never_reaches_the_body(self, tmp_path):
+ (tmp_path / "one.vcf").write_text(
+ "BEGIN:VCARD\nVERSION:3.0\nFN:Ada\n"
+ "PHOTO;ENCODING=b;TYPE=JPEG:" + ("A" * 500) + "\nEND:VCARD\n",
+ encoding="utf-8",
+ )
+ item = (await _items(tmp_path))[0]
+ assert "AAAA" not in item.body
+ # The format's own bookkeeping is dropped with it: VERSION says
+ # nothing about the person the card describes.
+ assert item.body.strip() == "Fn: Ada"
+
+
+class TestWhatsApp:
+ async def test_the_bracket_family_groups_messages_by_day(self):
+ items = await _items(FIXTURES / "chats" / "WhatsApp Chat with Ada.txt")
+ assert [i.external_id for i in items] == [
+ "WhatsApp Chat with Ada.txt#2024-02-01",
+ "WhatsApp Chat with Ada.txt#2024-02-02",
+ ]
+ assert items[0].thread_key == "Ada"
+ assert items[0].timestamp_utc == "2024-02-01T09:12:00Z"
+ assert items[0].metadata["messages"] == 2
+ assert "09:12 Bruno: Yes, filed under maintenance." in items[0].body
+
+ async def test_the_dash_family_parses_the_same_way(self):
+ # i18n-allow: the fixture's German filename token is the input under test
+ items = await _items(FIXTURES / "chats" / "WhatsApp Chat mit Bruno.txt")
+ assert [i.external_id for i in items] == [
+ "WhatsApp Chat mit Bruno.txt#2024-03-15",
+ "WhatsApp Chat mit Bruno.txt#2024-03-16",
+ ]
+ assert items[0].thread_key == "Bruno"
+
+ async def test_a_day_above_twelve_pins_the_date_order_for_the_file(self, tmp_path):
+ """15/03 can only be day-first, and that decides the ambiguous lines."""
+ (tmp_path / "WhatsApp Chat with X.txt").write_text(
+ "15/03/2024, 08:30 - X: unambiguous, day first\n"
+ "04/03/2024, 09:00 - X: ambiguous, must follow\n",
+ encoding="utf-8",
+ )
+ days = sorted(i.metadata["day"] for i in await _items(tmp_path))
+ assert days == ["2024-03-04", "2024-03-15"]
+
+ async def test_a_month_above_twelve_pins_the_american_order(self, tmp_path):
+ (tmp_path / "WhatsApp Chat with X.txt").write_text(
+ "03/15/2024, 08:30 - X: unambiguous, month first\n"
+ "03/04/2024, 09:00 - X: ambiguous, must follow\n",
+ encoding="utf-8",
+ )
+ days = sorted(i.metadata["day"] for i in await _items(tmp_path))
+ assert days == ["2024-03-04", "2024-03-15"]
+
+ async def test_am_pm_and_invisible_marks_do_not_break_the_match(self, tmp_path):
+ (tmp_path / "WhatsApp Chat with X.txt").write_text(
+ "‎[01.02.24, 1:05:00 PM] X: afternoon\n"
+ "‎[01.02.24, 1:06:00 AM] X: night\n",
+ encoding="utf-8",
+ )
+ item = (await _items(tmp_path))[0]
+ assert "13:05 X: afternoon" in item.body
+ assert "01:06 X: night" in item.body
+
+ async def test_a_wrapped_message_stays_with_its_own_line(self, tmp_path):
+ (tmp_path / "WhatsApp Chat with X.txt").write_text(
+ "[01.02.24, 09:00:00] X: first line\ncontinued here\n"
+ "[01.02.24, 09:01:00] X: second\n",
+ encoding="utf-8",
+ )
+ item = (await _items(tmp_path))[0]
+ assert "09:00 X: first line\ncontinued here" in item.body
+ assert item.metadata["messages"] == 2
+
+
+class TestTabularAndDocuments:
+ async def test_a_csv_repeats_its_header_in_every_chunk(self, tmp_path):
+ rows = "\n".join(f"row{n},value{n}" for n in range(1, 251))
+ (tmp_path / "big.csv").write_text(f"name,value\n{rows}\n", encoding="utf-8")
+ items = await _items(tmp_path)
+ assert [i.external_id for i in items] == [
+ "big.csv#rows-00000001-00000100",
+ "big.csv#rows-00000101-00000200",
+ "big.csv#rows-00000201-00000250",
+ ]
+ for item in items:
+ assert item.body.startswith("Columns: name,value")
+ assert "row101,value101" in items[1].body
+ assert items[2].metadata == {
+ **items[2].metadata,
+ "row_start": 201,
+ "row_end": 250,
+ }
+
+ async def test_a_small_csv_is_one_chunk(self):
+ items = await _items(FIXTURES / "tables" / "ledger.csv")
+ assert len(items) == 1
+ assert "Columns: name,email,city" in items[0].body
+ assert "Clara Nunes,[email protected],Lisbon" in items[0].body
+
+ async def test_a_tsv_is_split_on_tabs(self, tmp_path):
+ (tmp_path / "t.tsv").write_text("a\tb\n1\t2\n", encoding="utf-8")
+ item = (await _items(tmp_path))[0]
+ assert item.body.startswith("Columns: a\tb")
+
+ async def test_jsonl_chunks_by_line_range(self):
+ items = await _items(FIXTURES / "tables" / "events.jsonl")
+ assert len(items) == 1
+ assert items[0].external_id == "events.jsonl#lines-00000001-00000003"
+ assert '"budget_moved"' in items[0].body
+
+ async def test_a_json_document_is_rendered_readably(self):
+ item = (await _items(FIXTURES / "tables" / "settings.json"))[0]
+ assert item.external_id == "settings.json"
+ assert '"next_service": "2024-04-01"' in item.body
+
+ async def test_broken_json_is_imported_as_text_rather_than_lost(self, tmp_path):
+ (tmp_path / "half.json").write_text('{"a": 1, "b":', encoding="utf-8")
+ item = (await _items(tmp_path))[0]
+ assert item.body == '{"a": 1, "b":'
+
+ async def test_markdown_takes_its_title_from_the_first_heading(self):
+ item = (await _items(FIXTURES / "notes" / "readme.md"))[0]
+ assert item.title == "Telescope maintenance"
+ assert "observatory dome" in item.body
+
+ async def test_html_is_stripped_to_text_with_its_title(self):
+ item = (await _items(FIXTURES / "web" / "page.html"))[0]
+ assert item.title == "Observatory log"
+ assert "The dome was serviced on the tenth of January." in item.body
+ assert "console.log" not in item.body
+ assert "color: red" not in item.body
+
+
+class TestPdf:
+ async def test_a_pdf_is_extracted_page_by_page(self, tmp_path):
+ _make_pdf(tmp_path / "report.pdf", ["Ledger page one", "Ledger page two"])
+ items = await _items(tmp_path)
+ assert len(items) == 1
+ assert items[0].external_id == "report.pdf"
+ assert items[0].metadata["pages"] == 2
+ assert "Ledger page one" in items[0].body
+ assert "Ledger page two" in items[0].body
+
+ async def test_an_encrypted_pdf_is_skipped_with_a_reason_not_a_crash(
+ self, tmp_path, caplog
+ ):
+ pypdf = pytest.importorskip("pypdf")
+ _make_pdf(tmp_path / "open.pdf", ["Readable page"])
+ reader = pypdf.PdfReader(str(tmp_path / "open.pdf"))
+ writer = pypdf.PdfWriter()
+ for page in reader.pages:
+ writer.add_page(page)
+ writer.encrypt("a-passphrase-nobody-here-has")
+ with (tmp_path / "locked.pdf").open("wb") as handle:
+ writer.write(handle)
+ (tmp_path / "open.pdf").unlink()
+
+ with caplog.at_level("INFO"):
+ items = await _items(tmp_path)
+ assert items == []
+ assert "password protected" in caplog.text
+
+ async def test_a_pdf_with_no_extractable_text_is_reported_not_stored(
+ self, tmp_path, caplog
+ ):
+ pypdf = pytest.importorskip("pypdf")
+ writer = pypdf.PdfWriter()
+ writer.add_blank_page(width=200, height=200)
+ with (tmp_path / "scan.pdf").open("wb") as handle:
+ writer.write(handle)
+ with caplog.at_level("INFO"):
+ assert await _items(tmp_path) == []
+ assert "no extractable text" in caplog.text
+
+
+# ---------------------------------------------------------------------------
+# Archives
+# ---------------------------------------------------------------------------
+
+
+def _zip_fixture(target: Path, names: list[str]) -> Path:
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
+ for name in names:
+ archive.write(FIXTURES / name, arcname=name)
+ return target
+
+
+class TestArchives:
+ async def test_zip_entries_are_parsed_without_extracting_to_disk(self, tmp_path):
+ _zip_fixture(
+ tmp_path / "takeout.zip",
+ ["mail/inbox.mbox", "calendar/schedule.ics", "notes/readme.md"],
+ )
+ items = await _items(tmp_path)
+ assert len(items) == 4 # 2 mails + 1 event + 1 note
+ assert {i.metadata["format"] for i in items} == {"mbox", "ics", "markdown"}
+ # Nothing was written next to the archive.
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["takeout.zip"]
+
+ async def test_an_entry_id_and_permalink_name_the_archive_and_the_entry(
+ self, tmp_path
+ ):
+ _zip_fixture(tmp_path / "takeout.zip", ["calendar/schedule.ics"])
+ item = (await _items(tmp_path))[0]
+ assert item.external_id == (
+ "takeout.zip!calendar/schedule.ics#[email protected]"
+ )
+ assert item.permalink.endswith("takeout.zip#calendar/schedule.ics")
+ assert item.permalink.startswith("file:///")
+
+ async def test_a_nested_archive_is_followed(self, tmp_path):
+ inner = _zip_fixture(tmp_path / "inner.zip", ["notes/readme.md"])
+ outer = tmp_path / "outer.zip"
+ with zipfile.ZipFile(outer, "w") as archive:
+ archive.write(inner, arcname="bundles/inner.zip")
+ inner.unlink()
+
+ item = (await _items(tmp_path))[0]
+ assert item.external_id == "outer.zip!bundles/inner.zip!notes/readme.md"
+ assert item.title == "Telescope maintenance"
+
+ async def test_nesting_stops_at_the_depth_limit(self, tmp_path, caplog):
+ """A four-deep chain is read three deep and says so."""
+ payload = tmp_path / "build"
+ payload.mkdir()
+ current = payload / "level4.zip"
+ with zipfile.ZipFile(current, "w") as archive:
+ archive.write(FIXTURES / "notes" / "readme.md", arcname="readme.md")
+ for level in (3, 2, 1):
+ nxt = payload / f"level{level}.zip"
+ with zipfile.ZipFile(nxt, "w") as archive:
+ archive.write(current, arcname=current.name)
+ current = nxt
+ drop = tmp_path / "drop"
+ drop.mkdir()
+ current.replace(drop / "level1.zip")
+
+ with caplog.at_level("WARNING"):
+ items = await _items(drop)
+ assert items == []
+ assert "nested deeper than 3" in caplog.text
+
+ async def test_the_uncompressed_budget_stops_an_archive_bomb(
+ self, tmp_path, monkeypatch, caplog
+ ):
+ """A tiny archive that expands enormously is refused, not unpacked."""
+ from jarvis.ultrawiki.connectors import export_import as module
+
+ bomb = tmp_path / "bomb.zip"
+ with zipfile.ZipFile(bomb, "w", zipfile.ZIP_DEFLATED) as archive:
+ archive.writestr("huge.txt", "0" * (4 * 1024 * 1024))
+ assert bomb.stat().st_size < 64 * 1024 # it really is small on disk
+ monkeypatch.setattr(module, "ZIP_UNCOMPRESSED_BUDGET", 1024)
+
+ with caplog.at_level("WARNING"):
+ assert await _items(tmp_path) == []
+ assert "cannot be used to fill this machine" in caplog.text
+
+ async def test_a_broken_archive_is_reported_and_the_walk_continues(
+ self, tmp_path, caplog
+ ):
+ (tmp_path / "corrupt.zip").write_bytes(b"PK\x03\x04 not really a zip")
+ (tmp_path / "ok.md").write_text("# Fine\n\nstill imported", encoding="utf-8")
+ with caplog.at_level("INFO"):
+ items = await _items(tmp_path)
+ assert [i.external_id for i in items] == ["ok.md"]
+ assert "corrupt.zip" in caplog.text
+
+ async def test_mac_metadata_and_hidden_entries_are_skipped(self, tmp_path):
+ with zipfile.ZipFile(tmp_path / "mac.zip", "w") as archive:
+ archive.writestr("__MACOSX/._readme.md", "junk")
+ archive.writestr(".hidden/secret.md", "# hidden")
+ archive.writestr("readme.md", "# Real\n\ncontent")
+ items = await _items(tmp_path)
+ assert [i.external_id for i in items] == ["mac.zip!readme.md"]
+
+
+# ---------------------------------------------------------------------------
+# Limits, honesty, ordering
+# ---------------------------------------------------------------------------
+
+
+class TestLimitsAndHonesty:
+ async def test_a_body_is_capped_and_says_so(self, tmp_path, monkeypatch):
+ from jarvis.ultrawiki.connectors import export_import as module
+
+ (tmp_path / "huge.md").write_text("x" * 2_000_000, encoding="utf-8")
+ item = (await _items(tmp_path))[0]
+ assert len(item.body) <= module.BODY_CAP + 200
+ assert "truncated" in item.body
+ assert item.metadata["truncated"] is True
+
+ async def test_an_unknown_format_is_skipped_and_counted_never_raised(
+ self, tmp_path, caplog
+ ):
+ (tmp_path / "blob.bin").write_bytes(bytes([0, 1, 2, 3] * 64))
+ (tmp_path / "also.dat").write_bytes(bytes([0, 255] * 64))
+ (tmp_path / "keep.md").write_text("# Keep\n\nme", encoding="utf-8")
+ with caplog.at_level("INFO"):
+ items = await _items(tmp_path)
+ assert [i.external_id for i in items] == ["keep.md"]
+ assert "2 skipped as unrecognised" in caplog.text
+
+ async def test_hidden_files_and_folders_are_never_walked(self, tmp_path):
+ (tmp_path / ".hidden.md").write_text("# no", encoding="utf-8")
+ secret = tmp_path / ".git"
+ secret.mkdir()
+ (secret / "config.md").write_text("# no", encoding="utf-8")
+ (tmp_path / "yes.md").write_text("# yes", encoding="utf-8")
+ assert [i.external_id for i in await _items(tmp_path)] == ["yes.md"]
+
+ async def test_every_item_carries_a_permalink_and_a_timestamp(self):
+ for item in await _items(FIXTURES):
+ assert item.permalink.startswith("file:///"), item.external_id
+ assert item.timestamp_utc.endswith("Z"), item.external_id
+
+ async def test_the_walk_order_is_deterministic(self):
+ first = [i.external_id for i in await _items(FIXTURES)]
+ second = [i.external_id for i in await _items(FIXTURES)]
+ assert first == second
+ assert len(first) == len(set(first))
+
+ async def test_a_checkpoint_resumes_after_the_files_before_it(self):
+ every = await _items(FIXTURES)
+ checkpoint = _one(every, "#[email protected]").external_id
+ resumed = [i.external_id for i in await _items(FIXTURES, checkpoint)]
+ # Everything sorting before mail/inbox.mbox is gone...
+ assert not any(i.startswith("calendar/") for i in resumed)
+ assert not any(i.startswith("chats/") for i in resumed)
+ # ...the checkpoint's OWN file is re-read (idempotent upsert), and
+ # everything after it is still delivered.
+ assert checkpoint in resumed
+ assert "notes/readme.md" in resumed
+
+ async def test_a_checkpoint_from_inside_an_archive_resumes_on_the_archive(
+ self, tmp_path
+ ):
+ _zip_fixture(tmp_path / "b-archive.zip", ["calendar/schedule.ics"])
+ (tmp_path / "a-first.md").write_text("# First", encoding="utf-8")
+ (tmp_path / "c-last.md").write_text("# Last", encoding="utf-8")
+ every = [i.external_id for i in await _items(tmp_path)]
+ assert every == [
+ "a-first.md",
+ "b-archive.zip!calendar/schedule.ics#[email protected]",
+ "c-last.md",
+ ]
+ resumed = [i.external_id for i in await _items(tmp_path, every[1])]
+ assert resumed == every[1:]
+
+ async def test_a_single_file_path_imports_just_that_file(self):
+ items = await _items(FIXTURES / "notes" / "readme.md")
+ assert [i.external_id for i in items] == ["readme.md"]
+
+
+# ---------------------------------------------------------------------------
+# The preview pass
+# ---------------------------------------------------------------------------
+
+
+class TestScanExport:
+ def test_the_report_names_every_format_it_found(self):
+ report = scan_export(FIXTURES)
+ assert report["exists"] is True
+ assert report["is_dir"] is True
+ assert report["formats"]["mbox"] == {
+ "files": 1,
+ "items_estimate": 2,
+ "exact": True,
+ }
+ assert report["formats"]["whatsapp"]["files"] == 2
+ assert report["formats"]["whatsapp"]["items_estimate"] == 4
+ assert report["truncated"] is False
+ assert report["total_bytes"] > 0
+
+ async def test_the_preview_estimate_matches_what_the_import_delivers(self):
+ report = scan_export(FIXTURES)
+ assert report["items_estimate"] == len(await _items(FIXTURES))
+
+ def test_formats_are_reported_in_the_declared_order(self):
+ report = scan_export(FIXTURES)
+ order = [fmt for fmt in report["formats"]]
+ assert order == [fmt for fmt in EXPORT_FORMATS if fmt in report["formats"]]
+
+ def test_unknown_extensions_are_counted_with_their_extension(self, tmp_path):
+ for index in range(3):
+ (tmp_path / f"blob{index}.bin").write_bytes(bytes([0, 1, 2, 3]))
+ (tmp_path / "one.dll").write_bytes(bytes([0, 9]))
+ report = scan_export(tmp_path)
+ assert report["unknown"] == [
+ {"extension": ".bin", "files": 3},
+ {"extension": ".dll", "files": 1},
+ ]
+ assert report["unknown_files"] == 4
+
+ def test_a_missing_path_answers_honestly_instead_of_raising(self, tmp_path):
+ report = scan_export(tmp_path / "nowhere")
+ assert report["exists"] is False
+ assert report["formats"] == {}
+ assert report["notes"]
+
+ def test_the_file_budget_marks_the_answer_truncated(self, tmp_path):
+ for index in range(6):
+ (tmp_path / f"note{index}.md").write_text("# n", encoding="utf-8")
+ report = scan_export(tmp_path, budget_files=3)
+ assert report["truncated"] is True
+ assert report["formats"]["markdown"]["files"] <= 4
+ assert any("stopped counting" in note for note in report["notes"])
+
+ def test_an_archive_is_reported_as_the_container_it_is(self, tmp_path):
+ _zip_fixture(tmp_path / "takeout.zip", ["mail/inbox.mbox", "notes/readme.md"])
+ report = scan_export(tmp_path)
+ assert report["archives"]["files"] == 1
+ assert report["archives"]["entries"] == 2
+ assert report["formats"]["mbox"]["items_estimate"] == 2
+ # The archive itself is never an item-producing format.
+ assert "zip" not in report["formats"]
+
+ async def test_the_preview_counts_mbox_separators_exactly_as_the_import_splits(
+ self, tmp_path
+ ):
+ """An unescaped ``From `` after a blank line IS a separator (mbox's own
+ rule — which is why writers escape body lines as ``>From ``). The
+ preview must apply the SAME rule, or it promises a number the import
+ then contradicts."""
+ (tmp_path / "tricky.mbox").write_text(
+ "From [email protected] Mon Jan 01 09:00:00 2024\n"
+ "Subject: One\n"
+ "\n"
+ "From here on the writer forgot to escape the line.\n"
+ "\n"
+ ">From this one it did escape, so it stays in the body.\n",
+ encoding="utf-8",
+ )
+ estimate = scan_export(tmp_path)["formats"]["mbox"]["items_estimate"]
+ assert estimate == len(await _items(tmp_path)) == 2
+
+
+class TestUploadsDir:
+ def test_it_anchors_a_relative_data_dir_at_the_repo_root(self):
+ from jarvis.core.paths import repo_root
+
+ assert uploads_dir("data") == (
+ repo_root() / "data" / "ultrawiki" / "uploads"
+ ).resolve(strict=False)
+
+ def test_an_absolute_data_dir_is_used_as_given(self, tmp_path):
+ assert uploads_dir(tmp_path) == (
+ tmp_path / "ultrawiki" / "uploads"
+ ).resolve(strict=False)
+
+
+class TestFormatParity:
+ """Five-layer discipline (AP-4): the UI renders one label per format id."""
+
+ def test_typescript_mirrors_the_python_format_list(self):
+ import re
+
+ import jarvis
+
+ api_ts = (
+ Path(jarvis.__file__).resolve().parent
+ / "ui" / "web" / "frontend" / "src" / "lib" / "ultrawikiApi.ts"
+ )
+ source = api_ts.read_text(encoding="utf-8")
+ match = re.search(
+ r"const ULTRAWIKI_EXPORT_FORMATS = \[(.*?)\] as const",
+ source,
+ re.DOTALL,
+ )
+ assert match is not None
+ assert re.findall(r'"([^"]+)"', match.group(1)) == list(EXPORT_FORMATS)
+
+ def test_every_format_has_a_label_in_every_locale(self):
+ import json
+
+ import jarvis
+
+ locales = (
+ Path(jarvis.__file__).resolve().parent
+ / "ui" / "web" / "frontend" / "src" / "i18n" / "locales"
+ )
+ for name in ("en", "de", "es"):
+ data = json.loads((locales / f"{name}.json").read_text(encoding="utf-8"))
+ export = data["ultrawiki"]["export"]
+ for fmt in EXPORT_FORMATS:
+ label = export.get(f"format_{fmt}")
+ assert isinstance(label, str) and label.strip(), (
+ f"{name} has no label for the {fmt} format"
+ )
diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.py
index f31b78b7f0..059795609d 100644
--- a/tests/unit/web/test_ultrawiki_routes.py
+++ b/tests/unit/web/test_ultrawiki_routes.py
@@ -38,6 +38,8 @@ DANGEROUS_ROUTES = (
("/api/ultrawiki/sources/{source_id}/approve", "post"),
("/api/ultrawiki/sources/{source_id}/sync", "post"),
("/api/ultrawiki/jobs/{job_id}/cancel", "post"),
+ # It writes the uploaded bytes to this machine's disk.
+ ("/api/ultrawiki/export/upload", "post"),
)
@@ -1370,3 +1372,166 @@ def test_items_reject_an_unknown_state(env) -> None:
)
assert response.status_code == 400
assert "half-embedded" in response.json()["detail"]
+
+
+# ---------------------------------------------------------------------------
+# Export files — preview before importing, and get the file here first
+# ---------------------------------------------------------------------------
+
+
+def test_export_preview_reports_the_formats_it_found(env) -> None:
+ """The answer to "what does 'import everything' actually mean?"."""
+ drop = env.tmp / "drop"
+ drop.mkdir()
+ (drop / "notes.md").write_text("# Note\n\ncontent", encoding="utf-8")
+ (drop / "WhatsApp Chat with Ada.txt").write_text(
+ "[01.02.24, 09:00:00] Ada: hello\n[02.02.24, 09:00:00] Ada: again\n",
+ encoding="utf-8",
+ )
+ (drop / "blob.bin").write_bytes(bytes([0, 1, 2, 3] * 32))
+
+ response = env.client.post(
+ "/api/ultrawiki/export/preview", json={"path": str(drop)}
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["exists"] is True
+ assert body["is_dir"] is True
+ assert body["formats"]["markdown"]["items_estimate"] == 1
+ assert body["formats"]["whatsapp"]["items_estimate"] == 2
+ assert body["unknown"] == [{"extension": ".bin", "files": 1}]
+ assert body["truncated"] is False
+
+
+def test_export_preview_404s_on_a_path_that_is_not_there(env) -> None:
+ response = env.client.post(
+ "/api/ultrawiki/export/preview",
+ json={"path": str(env.tmp / "no-such-export")},
+ )
+ assert response.status_code == 404
+ assert "nothing exists" in response.json()["detail"]
+
+
+def test_export_preview_changes_nothing(env) -> None:
+ """A preview is read-only: no source appears, nothing is imported."""
+ _activate(env)
+ drop = env.tmp / "peek"
+ drop.mkdir()
+ (drop / "notes.md").write_text("# Note", encoding="utf-8")
+ before = env.client.get("/api/ultrawiki/sources").json()["total"]
+
+ env.client.post("/api/ultrawiki/export/preview", json={"path": str(drop)})
+
+ assert env.client.get("/api/ultrawiki/sources").json()["total"] == before
+
+
+def test_export_upload_streams_the_file_and_returns_its_path(env) -> None:
+ payload = b"# Uploaded note\n\nwith a body\n"
+ response = env.client.post(
+ "/api/ultrawiki/export/upload",
+ files={"file": ("takeout.md", payload, "text/markdown")},
+ )
+
+ assert response.status_code == 200, response.text
+ body = response.json()
+ assert body["name"] == "takeout.md"
+ assert body["size"] == len(payload)
+ stored = Path(body["path"])
+ assert stored.read_bytes() == payload
+ # Under the configured data directory, never next to the code.
+ assert "uploads" in stored.parts and str(env.tmp) in str(stored)
+
+
+def test_an_uploaded_file_can_be_previewed_and_imported(env) -> None:
+ """The whole point of the upload: it lands where the connector reads."""
+ _activate(env)
+ uploaded = env.client.post(
+ "/api/ultrawiki/export/upload",
+ files={
+ "file": (
+ "chat.txt",
+ b"[01.02.24, 09:00:00] Ada: hello from the upload\n"
+ b"[01.02.24, 09:01:00] Bruno: and a reply\n",
+ "text/plain",
+ )
+ },
+ ).json()
+
+ preview = env.client.post(
+ "/api/ultrawiki/export/preview", json={"path": uploaded["path"]}
+ )
+ assert preview.status_code == 200, preview.text
+ assert preview.json()["formats"]["whatsapp"]["items_estimate"] == 1
+
+ created = env.client.post(
+ "/api/ultrawiki/sources",
+ json={
+ "connector": "export-import",
+ "label": "Dropped chat",
+ "config": {"path": uploaded["path"]},
+ },
+ )
+ assert created.status_code == 201, created.text
+ # Consent semantics are untouched by the upload/preview detour.
+ assert created.json()["consent"] == "pending"
+
+ approved = env.client.post(
+ f"/api/ultrawiki/sources/{created.json()['id']}/approve"
+ )
+ assert approved.status_code == 200, approved.text
+ snapshot = _wait_for_job(env, approved.json()["job_id"])
+ assert snapshot["status"] == "done", snapshot
+ assert snapshot["new"] == 1
+
+
+def test_export_upload_refuses_a_path_traversal_filename(env) -> None:
+ """Refused, not silently renamed: a rewrite would report success for a
+ file stored somewhere the caller never asked for."""
+ for name in ("../escape.zip", "sub/dir.zip", "C:evil.zip"):
+ response = env.client.post(
+ "/api/ultrawiki/export/upload",
+ files={"file": (name, b"data", "application/zip")},
+ )
+ assert response.status_code == 400, (name, response.text)
+ assert "refusing the filename" in response.json()["detail"]
+
+
+def test_export_upload_refuses_an_empty_file(env) -> None:
+ response = env.client.post(
+ "/api/ultrawiki/export/upload",
+ files={"file": ("empty.zip", b"", "application/zip")},
+ )
+ assert response.status_code == 400
+ assert "empty" in response.json()["detail"]
+
+
+def test_export_upload_enforces_its_size_cap_and_keeps_nothing(
+ env, monkeypatch
+) -> None:
+ from jarvis.ui.web import ultrawiki_routes
+
+ monkeypatch.setattr(ultrawiki_routes, "_MAX_EXPORT_UPLOAD_BYTES", 16)
+ monkeypatch.setattr(ultrawiki_routes, "_UPLOAD_CHUNK_BYTES", 8)
+
+ response = env.client.post(
+ "/api/ultrawiki/export/upload",
+ files={"file": ("big.zip", b"x" * 4096, "application/zip")},
+ )
+
+ assert response.status_code == 413
+ assert "larger than" in response.json()["detail"]
+ # A refused transfer leaves no partial file behind.
+ uploads = env.tmp / "data" / "ultrawiki" / "uploads"
+ assert not uploads.exists() or not any(uploads.rglob("*.zip"))
+
+
+def test_export_preview_is_not_flagged_dangerous(env) -> None:
+ """Reading a path changes nothing, so it must not demand a confirmation."""
+ schema = env.server.app.openapi()
+ operation = schema["paths"]["/api/ultrawiki/export/preview"]["post"]
+ assert "x-jarvis-dangerous" not in operation
+ upload = schema["paths"]["/api/ultrawiki/export/upload"]["post"]
+ assert upload["x-jarvis-dangerous"] is True
+ # A multi-gigabyte transfer must outlive the CLI's default client timeout.
+ assert upload["x-jarvis-timeout-seconds"] == 600