DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(knowledge): give MarginNote 4 libraries a frontend
Bingxi Zhao (Frank)2af5ba7abf2f
diff --git a/web/components/knowledge/CreateKbModal.tsx b/web/components/knowledge/CreateKbModal.tsxindex 541468591..9f17b78c0 100644--- a/web/components/knowledge/CreateKbModal.tsx+++ b/web/components/knowledge/CreateKbModal.tsx@@ -12,6 +12,7 @@ import {Loader2,Plus,Server,+ Smartphone,} from "lucide-react";import Modal from "@/components/common/Modal";import { useImaConnection } from "@/hooks/useImaConnection";@@ -36,6 +37,7 @@ import FileDropZone from "./FileDropZone";import ImaConnectionFields from "./ImaConnectionFields";const OBSIDIAN_SOURCE = "obsidian";+const MARGINNOTE4_SOURCE = "marginnote4";const LIGHTRAG_SERVER_PROVIDER = "lightrag-server";const EXAMPLE_INDEX_PATH = "/Users/you/knowledge_bases/my-kb";const EXAMPLE_VAULT_PATH = "/Users/you/Documents/MyVault";@@ -72,6 +74,8 @@ interface CreateKbModalProps {apiKey?: string;mode?: string;}) => Promise<void>;+ /** Connect a MarginNote 4 library (its Add-on pushes objects in; no index). */+ onConnectMarginNote4: (params: { name: string }) => Promise<void>;/** Connect a Tencent IMA knowledge base (retrieval only, no local index). */onConnectIma: (params: {name: string;@@ -96,6 +100,7 @@ export default function CreateKbModal({onConnectLinkedFolder,onConnectObsidian,onConnectLightRagServer,+ onConnectMarginNote4,onConnectIma,onConfigureProvider,initialMode = "new",@@ -125,6 +130,7 @@ export default function CreateKbModal({const [submitting, setSubmitting] = useState(false);const [error, setError] = useState<string | null>(null);const linkIsObsidian = linkSource === OBSIDIAN_SOURCE;+ const linkIsMarginNote = linkSource === MARGINNOTE4_SOURCE;const linkIsIma = linkSource === IMA_PROVIDER;const imaConnection = useImaConnection({name,@@ -223,6 +229,7 @@ export default function CreateKbModal({return !providerUnavailable && selection.validFiles.length > 0;}if (linkIsIma) return imaConnection.canSubmit;+ if (linkIsMarginNote) return true;if (!trimmedPath) return false;if (linkIsObsidian) return true;// An engine index must pass the probe before it can be linked.@@ -294,6 +301,8 @@ export default function CreateKbModal({apiKey: imaConnection.submittedApiKey,knowledgeBaseId: imaConnection.knowledgeBaseId,});+ } else if (linkIsMarginNote) {+ await onConnectMarginNote4({ name: trimmed });} else if (linkIsObsidian) {await onConnectObsidian({ name: trimmed, vaultPath: trimmedPath });} else {@@ -316,7 +325,7 @@ export default function CreateKbModal({? isLightRagServer? t("Connect"): t("Create")- : linkIsObsidian || linkIsIma+ : linkIsObsidian || linkIsIma || linkIsMarginNote? t("Connect"): t("Link");@@ -423,6 +432,7 @@ export default function CreateKbModal({setLinkSource={handleLinkSourceChange}linkIsObsidian={linkIsObsidian}linkIsIma={linkIsIma}+ linkIsMarginNote={linkIsMarginNote}folderPath={folderPath}setFolderPath={setFolderPath}submitting={submitting}@@ -845,6 +855,7 @@ function LinkModeFields({setLinkSource,linkIsObsidian,linkIsIma,+ linkIsMarginNote,folderPath,setFolderPath,submitting,@@ -859,6 +870,7 @@ function LinkModeFields({setLinkSource: (id: string) => void;linkIsObsidian: boolean;linkIsIma: boolean;+ linkIsMarginNote: boolean;folderPath: string;setFolderPath: (value: string) => void;submitting: boolean;@@ -876,7 +888,8 @@ function LinkModeFields({</label><div className="grid gap-2 sm:grid-cols-2">{providers.map((p) => {- const selected = !linkIsObsidian && linkSource === p.id;+ const selected =+ !linkIsObsidian && !linkIsMarginNote && linkSource === p.id;const enabled = linkSourceEnabled(p);const disabled = submitting || !enabled;return (@@ -947,11 +960,44 @@ function LinkModeFields({)}</span></button>++ {/* MarginNote 4 — filled by its Add-on, not by a path on this disk. */}+ <button+ type="button"+ disabled={submitting}+ onClick={() => setLinkSource(MARGINNOTE4_SOURCE)}+ className={`group flex flex-col gap-1 rounded-2xl border p-3 text-left transition-colors disabled:opacity-50 ${+ linkIsMarginNote+ ? "border-[var(--primary)] bg-[var(--primary)]/5"+ : "border-[var(--border)] hover:border-[var(--ring)]"+ }`}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="flex items-center gap-1.5 text-[13px] font-medium text-[var(--foreground)]">+ <Smartphone className="h-3.5 w-3.5" />+ {t("MarginNote 4")}+ </span>+ {linkIsMarginNote && (+ <Check className="h-3.5 w-3.5 text-[var(--primary)]" />+ )}+ </div>+ <span className="text-[11.5px] leading-snug text-[var(--muted-foreground)]">+ {t(+ "Notes, excerpts and cards pushed in by the MarginNote 4 add-on.",+ )}+ </span>+ </button></div></div>{linkIsIma ? (connectionForm+ ) : linkIsMarginNote ? (+ <p className="rounded-lg border border-[var(--border)] bg-[var(--muted)]/40 px-3 py-2 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "The library starts empty. Pair a device from its Devices tab, then enter the token in the MarginNote 4 add-on to start syncing.",+ )}+ </p>) : (<><div>diff --git a/web/components/knowledge/KbMarginNoteDevicesSection.tsx b/web/components/knowledge/KbMarginNoteDevicesSection.tsxnew file mode 100644index 000000000..55ebab587--- /dev/null+++ b/web/components/knowledge/KbMarginNoteDevicesSection.tsx@@ -0,0 +1,278 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ AlertTriangle,+ Check,+ Copy,+ Loader2,+ Plus,+ Smartphone,+ Trash2,+} from "lucide-react";+import {+ getMarginNote4Status,+ listMarginNote4Devices,+ pairMarginNote4Device,+ revokeMarginNote4Device,+ type MarginNoteDevice,+ type MarginNoteLibraryStatus,+ type MarginNotePairing,+} from "@/lib/marginnote4-api";+import {+ formatKnowledgeTimestamp,+ type KnowledgeBase,+} from "@/lib/knowledge-helpers";++/**+ * Devices paired to a connected MarginNote 4 library.+ *+ * The library has no documents of its own — this is where its content comes+ * from. Pairing mints a token the MN4 add-on presents on every sync; the server+ * keeps only a hash, so the plaintext is shown here once and never again.+ */+export default function KbMarginNoteDevicesSection({+ kb,+}: {+ kb: KnowledgeBase;+}) {+ const { t } = useTranslation();+ const [devices, setDevices] = useState<MarginNoteDevice[] | null>(null);+ const [status, setStatus] = useState<MarginNoteLibraryStatus | null>(null);+ const [deviceName, setDeviceName] = useState("");+ const [pairing, setPairing] = useState(false);+ const [issued, setIssued] = useState<MarginNotePairing | null>(null);+ const [copied, setCopied] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const load = useCallback(async () => {+ try {+ const [list, summary] = await Promise.all([+ listMarginNote4Devices(kb.name),+ getMarginNote4Status(kb.name),+ ]);+ setDevices(list);+ setStatus(summary);+ setError(null);+ } catch (err) {+ // An unpaired library has no store yet, which is not an error state —+ // report the failure but still render the empty case below.+ setDevices([]);+ setStatus(null);+ setError(err instanceof Error ? err.message : String(err));+ }+ }, [kb.name]);++ useEffect(() => {+ void load();+ }, [load]);++ const handlePair = async () => {+ if (pairing) return;+ setPairing(true);+ setError(null);+ try {+ const result = await pairMarginNote4Device({+ kbName: kb.name,+ deviceName: deviceName.trim(),+ });+ setIssued(result);+ setCopied(false);+ setDeviceName("");+ await load();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setPairing(false);+ }+ };++ const handleRevoke = async (deviceId: string) => {+ setError(null);+ try {+ await revokeMarginNote4Device({ kbName: kb.name, deviceId });+ if (issued?.device_id === deviceId) setIssued(null);+ await load();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ }+ };++ const handleCopy = async () => {+ if (!issued) return;+ try {+ await navigator.clipboard.writeText(+ `${issued.device_id}:${issued.token}`,+ );+ setCopied(true);+ } catch {+ // Clipboard permission denied — the value stays selectable on screen.+ }+ };++ const active = (devices || []).filter((device) => device.active);++ return (+ <div className="space-y-6">+ <section className="space-y-3">+ <div>+ <div className="text-[13px] font-medium text-[var(--foreground)]">+ {t("MarginNote 4 devices")}+ </div>+ <p className="mt-0.5 text-[11.5px] leading-relaxed text-[var(--muted-foreground)]">+ {t(+ "Pair a device to get a token, then paste it into the MarginNote 4 add-on. The add-on pushes notes, excerpts, cards and mindmap nodes into this library.",+ )}+ </p>+ </div>++ <dl className="grid gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3 sm:grid-cols-2">+ <Field label={t("Synced objects")}>+ {status ? status.objects.toLocaleString() : "—"}+ </Field>+ <Field label={t("Active devices")}>+ {devices ? active.length.toLocaleString() : "—"}+ </Field>+ </dl>+ </section>++ <section className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <div>+ <div className="text-[12.5px] font-medium text-[var(--foreground)]">+ {t("Pair a device")}+ </div>+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">+ {t("A name only helps you tell your devices apart later.")}+ </p>+ </div>+ <div className="flex gap-2">+ <input+ value={deviceName}+ onChange={(event) => setDeviceName(event.target.value)}+ disabled={pairing}+ placeholder={t("My iPad")}+ className="w-full rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[12.5px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--foreground)]/25 disabled:opacity-50"+ />+ <button+ type="button"+ onClick={() => void handlePair()}+ disabled={pairing}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--primary)] px-3 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {pairing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Plus className="h-3.5 w-3.5" />+ )}+ {t("Pair device")}+ </button>+ </div>++ {issued && (+ <div className="space-y-2 rounded-lg border border-amber-300 bg-amber-50 p-3 dark:border-amber-900/60 dark:bg-amber-950/20">+ <div className="flex items-center gap-1.5 text-[12px] font-medium text-amber-800 dark:text-amber-300">+ <AlertTriangle className="h-3.5 w-3.5 shrink-0" />+ {t("Copy this now — it is not shown again.")}+ </div>+ <div className="flex items-center gap-2">+ <code className="min-w-0 flex-1 select-all break-all rounded-md bg-[var(--background)] px-2 py-1.5 font-mono text-[11px] text-[var(--foreground)]">+ {issued.device_id}:{issued.token}+ </code>+ <button+ type="button"+ onClick={() => void handleCopy()}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"+ >+ {copied ? (+ <Check className="h-3 w-3" />+ ) : (+ <Copy className="h-3 w-3" />+ )}+ {copied ? t("Copied") : t("Copy")}+ </button>+ </div>+ </div>+ )}+ </section>++ {error && (+ <div className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-[12px] text-red-700 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300">+ {error}+ </div>+ )}++ <section className="space-y-3">+ <div className="text-[12.5px] font-medium text-[var(--foreground)]">+ {t("Paired devices")}+ </div>+ {devices === null ? (+ <div className="flex items-center gap-2 text-[12px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("Loading…")}+ </div>+ ) : devices.length === 0 ? (+ <div className="rounded-lg border border-dashed border-[var(--border)] px-3 py-6 text-center text-[12px] text-[var(--muted-foreground)]">+ {t("No devices paired yet.")}+ </div>+ ) : (+ <ul className="divide-y divide-[var(--border)] overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--background)]">+ {devices.map((device) => (+ <li+ key={device.device_id}+ className="flex items-center gap-3 px-3 py-2.5"+ >+ <Smartphone className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="truncate text-[12.5px] font-medium text-[var(--foreground)]">+ {device.device_name || t("Unnamed device")}+ </span>+ {!device.active && (+ <span className="inline-flex shrink-0 items-center rounded-full bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">+ {t("Revoked")}+ </span>+ )}+ </div>+ <div className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">+ {device.device_kind} · {t("Last seen")}{" "}+ {formatKnowledgeTimestamp(device.last_seen) || "—"}+ </div>+ </div>+ {device.active && (+ <button+ type="button"+ onClick={() => void handleRevoke(device.device_id)}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md border border-red-200 bg-red-50 px-2.5 py-1 text-[12px] font-medium text-red-700 transition-colors hover:bg-red-100 dark:border-red-900 dark:bg-red-950/30 dark:text-red-300"+ >+ <Trash2 className="h-3 w-3" />+ {t("Revoke")}+ </button>+ )}+ </li>+ ))}+ </ul>+ )}+ </section>+ </div>+ );+}++function Field({+ label,+ children,+}: {+ label: string;+ children: React.ReactNode;+}) {+ return (+ <div>+ <dt className="text-[10.5px] font-medium uppercase tracking-wide text-[var(--muted-foreground)]">+ {label}+ </dt>+ <dd className="mt-0.5 text-[12.5px] text-[var(--foreground)]">+ {children}+ </dd>+ </div>+ );+}diff --git a/web/components/knowledge/KbSettingsSection.tsx b/web/components/knowledge/KbSettingsSection.tsxindex 9a760f3ec..1b23e6088 100644--- a/web/components/knowledge/KbSettingsSection.tsx+++ b/web/components/knowledge/KbSettingsSection.tsx@@ -4,6 +4,7 @@ import { useTranslation } from "react-i18next";import { Star, Trash2 } from "lucide-react";import {formatKnowledgeTimestamp,+ isMarginNoteKb,providerUsesEmbeddingMetadata,type KnowledgeBase,} from "@/lib/knowledge-helpers";@@ -21,8 +22,15 @@ export default function KbSettingsSection({}: KbSettingsSectionProps) {const { t } = useTranslation();const meta = kb.metadata || {};- const provider = kb.statistics?.rag_provider || "llamaindex";- const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);+ // A MarginNote library runs no engine and no embedding, and its `path` is+ // a name rather than a folder that exists — reporting the ordinary fields+ // described a pipeline and a directory it never has.+ const isMarginNote = isMarginNoteKb(kb);+ const provider = isMarginNote+ ? t("MarginNote 4")+ : kb.statistics?.rag_provider || "llamaindex";+ const pageIndexProvider =+ isMarginNote || !providerUsesEmbeddingMetadata(provider);const embeddingLabel = meta.embedding_model? typeof meta.embedding_dim === "number"? `${meta.embedding_model} · ${meta.embedding_dim}${t("d")}`@@ -51,13 +59,25 @@ export default function KbSettingsSection({)}<Field label={t("Created")}>{created || "—"}</Field><Field label={t("Updated")}>{updated || "—"}</Field>- <Field label={t("Last indexed")}>{lastIndexed || "—"}</Field>- {kb.path && (- <Field label={t("On-disk path")} className="sm:col-span-2">- <span className="font-mono text-[10.5px] text-[var(--muted-foreground)]">- {kb.path}- </span>- </Field>+ {!isMarginNote && (+ <Field label={t("Last indexed")}>{lastIndexed || "—"}</Field>+ )}+ {isMarginNote ? (+ meta.db_path && (+ <Field label={t("Synced store")} className="sm:col-span-2">+ <span className="font-mono text-[10.5px] text-[var(--muted-foreground)]">+ {meta.db_path}+ </span>+ </Field>+ )+ ) : (+ kb.path && (+ <Field label={t("On-disk path")} className="sm:col-span-2">+ <span className="font-mono text-[10.5px] text-[var(--muted-foreground)]">+ {kb.path}+ </span>+ </Field>+ ))}</dl></section>@@ -94,9 +114,13 @@ export default function KbSettingsSection({{t("Danger zone")}</div><p className="mt-0.5 text-[11.5px] text-red-700/80 dark:text-red-300/80">- {t(- "Deleting a knowledge base permanently removes its raw documents and index versions.",- )}+ {isMarginNote+ ? t(+ "Deleting this library removes its synced objects and unpairs every device. Nothing in MarginNote 4 itself is touched.",+ )+ : t(+ "Deleting a knowledge base permanently removes its raw documents and index versions.",+ )}</p></div><buttondiff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex e6a606b50..793238011 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -10,14 +10,18 @@ import {Loader2,RefreshCw,Settings as SettingsIcon,+ Smartphone,Star,Upload,} from "lucide-react";import type { KnowledgeUploadPolicy } from "@/lib/knowledge-api";import {formatKnowledgeTimestamp,+ isMarginNoteKb,+ kbDetailSections,providerUsesEmbeddingMetadata,resolveKbStatus,+ type KbDetailSection,type KnowledgeBase,} from "@/lib/knowledge-helpers";import type { TaskState } from "@/hooks/useKnowledgeProgress";@@ -27,8 +31,7 @@ import KbFilesTab from "./KbFilesTab";import KbDocumentsSection from "./KbDocumentsSection";import KbIndexVersionsSection from "./KbIndexVersionsSection";import KbSettingsSection from "./KbSettingsSection";--type DetailSection = "files" | "add" | "versions" | "settings";+import KbMarginNoteDevicesSection from "./KbMarginNoteDevicesSection";interface KnowledgeBaseDetailProps {kb: KnowledgeBase | null;@@ -49,19 +52,19 @@ interface KnowledgeBaseDetailProps {onBack?: () => void;}-const SECTIONS: {- key: DetailSection;- label: string;- Icon: typeof FileText;-}[] = [- { key: "files", label: "Files", Icon: FileText },- { key: "add", label: "Add documents", Icon: Upload },- { key: "versions", label: "Index versions", Icon: Layers },- { key: "settings", label: "Settings", Icon: SettingsIcon },-];+const SECTION_CHROME: Record<+ KbDetailSection,+ { label: string; Icon: typeof FileText }+> = {+ files: { label: "Files", Icon: FileText },+ add: { label: "Add documents", Icon: Upload },+ versions: { label: "Index versions", Icon: Layers },+ devices: { label: "Devices", Icon: Smartphone },+ settings: { label: "Settings", Icon: SettingsIcon },+};/** Sections that fill the detail body edge-to-edge (no max-w wrapper). */-const FULL_BLEED_SECTIONS = new Set<DetailSection>(["files"]);+const FULL_BLEED_SECTIONS = new Set<KbDetailSection>(["files"]);export default function KnowledgeBaseDetail({kb,@@ -78,7 +81,7 @@ export default function KnowledgeBaseDetail({onBack,}: KnowledgeBaseDetailProps) {const { t } = useTranslation();- const [section, setSection] = useState<DetailSection>("files");+ const [section, setSection] = useState<KbDetailSection>("files");const [retrySubmitting, setRetrySubmitting] = useState(false);if (!kb) {@@ -109,8 +112,14 @@ export default function KnowledgeBaseDetail({}const meta = kb.metadata || {};- const provider = kb.statistics?.rag_provider || "llamaindex";- const pageIndexProvider = !providerUsesEmbeddingMetadata(provider);+ const isMarginNote = isMarginNoteKb(kb);+ // A MarginNote library records no engine and no embedding: defaulting to+ // "llamaindex · Default embedding" here described a pipeline it never runs.+ const provider = isMarginNote+ ? t("MarginNote 4")+ : kb.statistics?.rag_provider || "llamaindex";+ const pageIndexProvider =+ isMarginNote || !providerUsesEmbeddingMetadata(provider);const embeddingLabel = meta.embedding_model? typeof meta.embedding_dim === "number"? `${meta.embedding_model} · ${meta.embedding_dim}${t("d")}`@@ -124,7 +133,8 @@ export default function KnowledgeBaseDetail({(task?.kind === "reindex" || task?.kind === "retry") &&task.executing === true;const status = resolveKbStatus(kb);- const canRetry = status === "error" && !kb.read_only;+ // Nothing to re-run: its content arrives from the add-on, not an index.+ const canRetry = status === "error" && !kb.read_only && !isMarginNote;const handleRetry = async () => {if (!canRetry || retrySubmitting || isReindexingLocally) return;@@ -136,7 +146,11 @@ export default function KnowledgeBaseDetail({}};- const fullBleed = FULL_BLEED_SECTIONS.has(section);+ const sections = kbDetailSections(kb);+ // Switching to a KB without the selected section (a MarginNote library has+ // no Files tab) falls back to its first, instead of rendering nothing.+ const activeSection = sections.includes(section) ? section : sections[0];+ const fullBleed = FULL_BLEED_SECTIONS.has(activeSection);return (<main className="flex h-full flex-1 flex-col overflow-hidden bg-[var(--background)]">@@ -207,8 +221,9 @@ export default function KnowledgeBaseDetail({{/* Section nav */}<nav className="-mb-3 mt-3 flex gap-1 overflow-x-auto">- {SECTIONS.map(({ key, label, Icon }) => {- const active = section === key;+ {sections.map((key) => {+ const { label, Icon } = SECTION_CHROME[key];+ const active = activeSection === key;return (<buttonkey={key}@@ -230,12 +245,12 @@ export default function KnowledgeBaseDetail({{/* Body */}<div className="min-h-0 flex-1 overflow-hidden">- {section === "files" ? (+ {activeSection === "files" ? (<KbFilesTab key={kb.name} kb={kb} task={task} />) : (<div className="h-full overflow-y-auto px-6 py-5"><div className={fullBleed ? "" : "mx-auto max-w-3xl"}>- {section === "add" && (+ {activeSection === "add" && (<KbDocumentsSectionkb={kb}uploadPolicy={uploadPolicy}@@ -250,7 +265,7 @@ export default function KnowledgeBaseDetail({}/>)}- {section === "versions" && (+ {activeSection === "versions" && (<KbIndexVersionsSectionkb={kb}task={task}@@ -263,7 +278,10 @@ export default function KnowledgeBaseDetail({}/>)}- {section === "settings" && (+ {activeSection === "devices" && (+ <KbMarginNoteDevicesSection key={kb.name} kb={kb} />+ )}+ {activeSection === "settings" && (<KbSettingsSectionkb={kb}onSetDefault={() =>diff --git a/web/components/knowledge/KnowledgePage.tsx b/web/components/knowledge/KnowledgePage.tsxindex c06d602b8..e817bcd12 100644--- a/web/components/knowledge/KnowledgePage.tsx+++ b/web/components/knowledge/KnowledgePage.tsx@@ -39,6 +39,7 @@ export default function KnowledgePage() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectMarginNote4,connectIma,} = useKnowledgeBases();@@ -306,6 +307,7 @@ export default function KnowledgePage() {onConnectLinkedFolder={connectLinkedFolder}onConnectObsidian={connectObsidian}onConnectLightRagServer={connectLightRagServer}+ onConnectMarginNote4={connectMarginNote4}onConnectIma={connectIma}initialMode={createPreset?.mode}initialSource={createPreset?.source}diff --git a/web/hooks/useKnowledgeBases.ts b/web/hooks/useKnowledgeBases.tsindex 25879eb28..8679fbc63 100644--- a/web/hooks/useKnowledgeBases.ts+++ b/web/hooks/useKnowledgeBases.ts@@ -5,6 +5,7 @@ import {connectImaKnowledgeBase as connectImaApi,connectLightRagServer as connectLightRagServerApi,connectLinkedFolder as connectLinkedFolderApi,+ connectMarginNote4Library as connectMarginNote4Api,connectObsidianVault as connectObsidianApi,createKnowledgeBase as createKbApi,deleteKnowledgeBase as deleteKbApi,@@ -342,6 +343,15 @@ export function useKnowledgeBases() {[load],);+ const connectMarginNote4 = useCallback(+ async (params: { name: string }) => {+ await connectMarginNote4Api(params);+ invalidateKnowledgeCaches();+ await load({ force: true, showSpinner: false });+ },+ [load],+ );+const connectIma = useCallback(async (params: {name: string;@@ -379,6 +389,7 @@ export function useKnowledgeBases() {connectObsidian,connectLinkedFolder,connectLightRagServer,+ connectMarginNote4,connectIma,};}diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsindex 3d3b16881..73b788570 100644--- a/web/lib/knowledge-api.ts+++ b/web/lib/knowledge-api.ts@@ -597,7 +597,7 @@ export interface KnowledgeTaskResponse {noop?: boolean;}-async function readErrorDetail(+export async function readErrorDetail(res: Response,fallback: string,): Promise<string> {@@ -669,6 +669,34 @@ export async function connectObsidianVault(payload: {};}+export async function connectMarginNote4Library(payload: {+ name: string;+ description?: string;+}): Promise<{ status: string; name: string; db_path?: string }> {+ const res = await apiFetch(apiUrl("/api/v1/knowledge/connect-marginnote4"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ // `db_path` is deliberately not sent: leaving it blank keeps one rule for+ // where the store lives (derived from the name), which is what lets the+ // pairing endpoints, the Add-on's syncs and the capability binding agree.+ body: JSON.stringify({+ name: payload.name,+ description: payload.description ?? "",+ }),+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, "Failed to connect MarginNote 4 library"),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as {+ status: string;+ name: string;+ db_path?: string;+ };+}+export interface LinkedFolderProbe {/** Whether the folder holds a ready index for the chosen engine. */ok: boolean;diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 400195563..e58e51189 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -114,6 +114,8 @@ export interface KnowledgeBase {type?: string;/** Absolute path of a connected Obsidian vault (when type === "obsidian"). */vault_path?: string;+ /** SQLite store of a connected MarginNote 4 library (when type === "marginnote4"). */+ db_path?: string;/** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "gemini" | "kimi" | "opencode" | "mimo" | "partner". */agent_kind?: string;/** Bound partner id when agent_kind === "partner". */@@ -211,9 +213,44 @@ export const formatKnowledgeTimestamp = (value?: string): string | null => {return parsed ? parsed.toLocaleString() : value || null;};+export const MARGINNOTE4_KB_TYPE = "marginnote4";++/**+ * A connected MarginNote 4 library.+ *+ * It owns no documents and no index: the Add-on pushes objects into its own+ * store and the MarginNote tools read them, so the file, add-documents and+ * index-version surfaces have nothing to act on.+ */+export const isMarginNoteKb = (kb: KnowledgeBase): boolean =>+ kb.metadata?.type === MARGINNOTE4_KB_TYPE;++export const KB_DETAIL_SECTIONS = [+ "files",+ "add",+ "versions",+ "devices",+ "settings",+] as const;++export type KbDetailSection = (typeof KB_DETAIL_SECTIONS)[number];++/**+ * The detail sections a KB has something to show in.+ *+ * A MarginNote library owns no raw files and builds no index, so files /+ * add-documents / index-versions would all render empty against it; what it+ * does have is the devices that feed it. Every other KB has the reverse.+ */+export const kbDetailSections = (kb: KnowledgeBase): KbDetailSection[] =>+ isMarginNoteKb(kb)+ ? ["devices", "settings"]+ : KB_DETAIL_SECTIONS.filter((section) => section !== "devices");+/** The retrieval engine a KB is bound to. Connected vaults badge by source. */export const kbProvider = (kb: KnowledgeBase): string => {if (kb.metadata?.type === "obsidian") return "obsidian";+ if (isMarginNoteKb(kb)) return MARGINNOTE4_KB_TYPE;return ((kb.statistics?.rag_provider as string | undefined) ||(kb.metadata?.rag_provider as string | undefined) ||diff --git a/web/lib/marginnote4-api.ts b/web/lib/marginnote4-api.tsnew file mode 100644index 000000000..f8a644894--- /dev/null+++ b/web/lib/marginnote4-api.ts@@ -0,0 +1,107 @@+import { apiFetch, apiUrl } from "@/lib/api";+import { readErrorDetail } from "@/lib/knowledge-api";++/**+ * Device bridge for a connected MarginNote 4 library.+ *+ * A library holds no documents of its own: the MN4 Add-on pushes notes,+ * excerpts, cards and mindmap nodes into it, authenticating with a token this+ * module hands out at pairing time. Every call names the library through+ * `X-MN4-KB`, which is what makes that token findable by the Add-on's later+ * syncs — the backend resolves one store from that same name (see+ * `capabilities/marginnote4/store.resolve_db_path`).+ *+ * Shapes are the wire shapes, matching the router's `DeviceInfo` /+ * `PairResponse` rather than restating them in another casing.+ */++const BASE = "/api/v1/marginnote4";++export interface MarginNoteDevice {+ device_id: string;+ device_name: string;+ device_kind: string;+ paired_at: string;+ last_seen: string;+ active: boolean;+}++/** Returned once, at pairing. The server keeps only a hash of `token`. */+export interface MarginNotePairing {+ device_id: string;+ token: string;+ device_name: string;+ device_kind: string;+}++export interface MarginNoteLibraryStatus {+ status: string;+ devices: number;+ objects: number;+}++const libraryHeaders = (kbName: string): HeadersInit => ({+ "Content-Type": "application/json",+ "X-MN4-KB": kbName,+});++export async function pairMarginNote4Device(payload: {+ kbName: string;+ deviceName: string;+ deviceKind?: string;+}): Promise<MarginNotePairing> {+ const res = await apiFetch(apiUrl(`${BASE}/pair`), {+ method: "POST",+ headers: libraryHeaders(payload.kbName),+ body: JSON.stringify({+ device_name: payload.deviceName,+ device_kind: payload.deviceKind || "macos",+ }),+ });+ if (!res.ok) {+ throw new Error(await readErrorDetail(res, "Failed to pair the device"));+ }+ return (await res.json()) as MarginNotePairing;+}++export async function listMarginNote4Devices(+ kbName: string,+): Promise<MarginNoteDevice[]> {+ const res = await apiFetch(apiUrl(`${BASE}/devices`), {+ headers: libraryHeaders(kbName),+ cache: "no-store",+ });+ if (!res.ok) {+ throw new Error(await readErrorDetail(res, "Failed to load paired devices"));+ }+ const data = await res.json();+ return Array.isArray(data) ? (data as MarginNoteDevice[]) : [];+}++export async function revokeMarginNote4Device(payload: {+ kbName: string;+ deviceId: string;+}): Promise<void> {+ const res = await apiFetch(+ apiUrl(`${BASE}/devices/${encodeURIComponent(payload.deviceId)}`),+ { method: "DELETE", headers: libraryHeaders(payload.kbName) },+ );+ if (!res.ok) {+ throw new Error(await readErrorDetail(res, "Failed to revoke the device"));+ }+}++export async function getMarginNote4Status(+ kbName: string,+): Promise<MarginNoteLibraryStatus> {+ const res = await apiFetch(apiUrl(`${BASE}/status`), {+ headers: libraryHeaders(kbName),+ cache: "no-store",+ });+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, "Failed to load the library status"),+ );+ }+ return (await res.json()) as MarginNoteLibraryStatus;+}diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex 741c9122c..f8f60dba9 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -1301,6 +1301,27 @@"Retry indexing from the documents already stored in this knowledge base.": "Retry indexing from the documents already stored in this knowledge base.","Re-index": "Re-index","Re-indexing…": "Re-indexing…",+ "Synced store": "Synced store",+ "Deleting this library removes its synced objects and unpairs every device. Nothing in MarginNote 4 itself is touched.": "Deleting this library removes its synced objects and unpairs every device. Nothing in MarginNote 4 itself is touched.",+ "MarginNote 4": "MarginNote 4",+ "Notes, excerpts and cards pushed in by the MarginNote 4 add-on.": "Notes, excerpts and cards pushed in by the MarginNote 4 add-on.",+ "The library starts empty. Pair a device from its Devices tab, then enter the token in the MarginNote 4 add-on to start syncing.": "The library starts empty. Pair a device from its Devices tab, then enter the token in the MarginNote 4 add-on to start syncing.",+ "Devices": "Devices",+ "MarginNote 4 devices": "MarginNote 4 devices",+ "Pair a device to get a token, then paste it into the MarginNote 4 add-on. The add-on pushes notes, excerpts, cards and mindmap nodes into this library.": "Pair a device to get a token, then paste it into the MarginNote 4 add-on. The add-on pushes notes, excerpts, cards and mindmap nodes into this library.",+ "Synced objects": "Synced objects",+ "Active devices": "Active devices",+ "Pair a device": "Pair a device",+ "A name only helps you tell your devices apart later.": "A name only helps you tell your devices apart later.",+ "My iPad": "My iPad",+ "Pair device": "Pair device",+ "Copy this now — it is not shown again.": "Copy this now — it is not shown again.",+ "Paired devices": "Paired devices",+ "No devices paired yet.": "No devices paired yet.",+ "Unnamed device": "Unnamed device",+ "Revoked": "Revoked",+ "Last seen": "Last seen",+ "Revoke": "Revoke","Starting to process documents with {{provider}} provider...": "Starting to process documents with {{provider}} provider...","Found {{count}} documents, starting to process...": "Found {{count}} documents, starting to process...","No documents found to process": "No documents found to process",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex afb9b8bdb..f87305cb1 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -1421,6 +1421,27 @@"Retry indexing from the documents already stored in this knowledge base.": "使用此知识库中已经保存的文档重试索引。","Re-index": "重建索引","Re-indexing…": "正在重建索引…",+ "Synced store": "同步存储",+ "Deleting this library removes its synced objects and unpairs every device. Nothing in MarginNote 4 itself is touched.": "删除这个库会清掉已同步的条目并解除所有设备配对。MarginNote 4 里的内容不受影响。",+ "MarginNote 4": "MarginNote 4",+ "Notes, excerpts and cards pushed in by the MarginNote 4 add-on.": "由 MarginNote 4 插件推送进来的笔记、摘录和卡片。",+ "The library starts empty. Pair a device from its Devices tab, then enter the token in the MarginNote 4 add-on to start syncing.": "库创建后是空的。在它的「设备」页配对一台设备,把令牌填进 MarginNote 4 插件即可开始同步。",+ "Devices": "设备",+ "MarginNote 4 devices": "MarginNote 4 设备",+ "Pair a device to get a token, then paste it into the MarginNote 4 add-on. The add-on pushes notes, excerpts, cards and mindmap nodes into this library.": "配对设备可得到一个令牌,把它粘贴进 MarginNote 4 插件。插件会把笔记、摘录、卡片和脑图节点推送到这个库。",+ "Synced objects": "已同步条目",+ "Active devices": "生效设备",+ "Pair a device": "配对设备",+ "A name only helps you tell your devices apart later.": "名称只是方便你以后区分设备。",+ "My iPad": "我的 iPad",+ "Pair device": "配对",+ "Copy this now — it is not shown again.": "现在就复制——它不会再次显示。",+ "Paired devices": "已配对设备",+ "No devices paired yet.": "还没有配对任何设备。",+ "Unnamed device": "未命名设备",+ "Revoked": "已吊销",+ "Last seen": "最近活跃",+ "Revoke": "吊销","Starting to process documents with {{provider}} provider...": "正在使用 {{provider}} 引擎处理文档…","Found {{count}} documents, starting to process...": "找到 {{count}} 个文档,开始处理…","No documents found to process": "没有找到可处理的文档",diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.tsindex ea9e66be1..58a5996eb 100644--- a/web/tests/knowledge-helpers.test.ts+++ b/web/tests/knowledge-helpers.test.ts@@ -2,7 +2,10 @@ import test from "node:test";import assert from "node:assert/strict";import {+ isMarginNoteKb,kbCanReindex,+ kbDetailSections,+ kbProvider,providerUsesEmbeddingMetadata,resolveKnowledgeIndexFailure,taskFailureMessage,@@ -193,3 +196,30 @@ test("engine status follows the credential and install state", () => {"unavailable",);});++test("a MarginNote library shows devices instead of files and index versions", () => {+ // It owns no raw documents and builds no index, so those three sections+ // would render empty against it; what it does have is the devices that+ // push objects into it.+ const marginNote: KnowledgeBase = {+ name: "MN4",+ metadata: { type: "marginnote4", db_path: "/data/mn4/MN4.db" },+ };+ assert.deepEqual(kbDetailSections(marginNote), ["devices", "settings"]);+ assert.equal(isMarginNoteKb(marginNote), true);+ assert.equal(kbProvider(marginNote), "marginnote4");+});++test("an ordinary knowledge base has no devices section", () => {+ const indexed: KnowledgeBase = {+ name: "Papers",+ statistics: { rag_provider: "llamaindex" },+ };+ assert.deepEqual(kbDetailSections(indexed), [+ "files",+ "add",+ "versions",+ "settings",+ ]);+ assert.equal(isMarginNoteKb(indexed), false);+});diff --git a/web/tests/marginnote4-api.test.ts b/web/tests/marginnote4-api.test.tsnew file mode 100644index 000000000..7c98450a4--- /dev/null+++ b/web/tests/marginnote4-api.test.ts@@ -0,0 +1,140 @@+import assert from "node:assert/strict";+import test from "node:test";++import { connectMarginNote4Library } from "../lib/knowledge-api";+import {+ getMarginNote4Status,+ listMarginNote4Devices,+ pairMarginNote4Device,+ revokeMarginNote4Device,+} from "../lib/marginnote4-api";++function jsonResponse(status: number, body: unknown): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { "Content-Type": "application/json" },+ });+}++function stubFetch(+ handler: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>,+): () => void {+ const original = globalThis.fetch;+ (globalThis as { fetch: typeof fetch }).fetch = handler;+ return () => {+ (globalThis as { fetch: typeof fetch }).fetch = original;+ };+}++const header = (init: RequestInit | undefined, name: string): string | null =>+ new Headers(init?.headers).get(name);++test("every device-bridge call names its library through X-MN4-KB", async () => {+ // The backend derives one SQLite store from this name, so a call that omits+ // it pairs a device into a library the add-on's syncs never look at.+ const calls: { input: string; method: string; kb: string | null }[] = [];+ const restore = stubFetch(async (input, init) => {+ calls.push({+ input: String(input),+ method: init?.method || "GET",+ kb: header(init, "X-MN4-KB"),+ });+ if (String(input).endsWith("/devices") && (init?.method || "GET") === "GET")+ return jsonResponse(200, []);+ return jsonResponse(200, {+ status: "ok",+ devices: 0,+ objects: 0,+ device_id: "d1",+ token: "t1",+ device_name: "",+ device_kind: "macos",+ });+ });+ try {+ await pairMarginNote4Device({ kbName: "My Lib", deviceName: "iPad" });+ await listMarginNote4Devices("My Lib");+ await revokeMarginNote4Device({ kbName: "My Lib", deviceId: "d1" });+ await getMarginNote4Status("My Lib");++ assert.deepEqual(+ calls.map((c) => [c.method, c.input, c.kb]),+ [+ ["POST", "/api/v1/marginnote4/pair", "My Lib"],+ ["GET", "/api/v1/marginnote4/devices", "My Lib"],+ ["DELETE", "/api/v1/marginnote4/devices/d1", "My Lib"],+ ["GET", "/api/v1/marginnote4/status", "My Lib"],+ ],+ );+ } finally {+ restore();+ }+});++test("pairing sends the device name and returns the one-time token", async () => {+ let body: unknown = null;+ const restore = stubFetch(async (_input, init) => {+ body = JSON.parse(String(init?.body));+ return jsonResponse(200, {+ device_id: "dev-1",+ token: "secret",+ device_name: "iPad",+ device_kind: "macos",+ });+ });+ try {+ const pairing = await pairMarginNote4Device({+ kbName: "Lib",+ deviceName: "iPad",+ });+ assert.deepEqual(body, { device_name: "iPad", device_kind: "macos" });+ assert.equal(pairing.token, "secret");+ } finally {+ restore();+ }+});++test("a device id is escaped into the revoke path", async () => {+ let url = "";+ const restore = stubFetch(async (input) => {+ url = String(input);+ return jsonResponse(200, { status: "revoked" });+ });+ try {+ await revokeMarginNote4Device({ kbName: "Lib", deviceId: "a/b?c" });+ assert.equal(url, "/api/v1/marginnote4/devices/a%2Fb%3Fc");+ } finally {+ restore();+ }+});++test("a failed call surfaces the server's detail", async () => {+ const restore = stubFetch(async () =>+ jsonResponse(501, { detail: "pairing and sync would resolve differently" }),+ );+ try {+ await assert.rejects(+ pairMarginNote4Device({ kbName: "Lib", deviceName: "" }),+ /resolve differently/,+ );+ } finally {+ restore();+ }+});++test("connecting a library never pins db_path", async () => {+ // Leaving it blank is what keeps one rule for where the store lives, so+ // pairing, the add-on's syncs and the capability binding cannot disagree.+ let body: Record<string, unknown> = {};+ const restore = stubFetch(async (_input, init) => {+ body = JSON.parse(String(init?.body));+ return jsonResponse(200, { status: "connected", name: "Lib" });+ });+ try {+ await connectMarginNote4Library({ name: "Lib" });+ assert.deepEqual(body, { name: "Lib", description: "" });+ assert.equal("db_path" in body, false);+ } finally {+ restore();+ }+});