DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(knowledge): expose linked folder sync controls
XZH2992a7e73fd4
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pyindex 794385ace..b2e706f09 100644--- a/deeptutor/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -195,6 +195,7 @@ class LinkedFolderInfo(BaseModel):path: stradded_at: strfile_count: int+ last_sync: str | None = Noneclass SupportedFileTypesInfo(BaseModel):diff --git a/tests/knowledge/test_linked_folder_sync.py b/tests/knowledge/test_linked_folder_sync.pyindex a4e8ed353..f79c8d4aa 100644--- a/tests/knowledge/test_linked_folder_sync.py+++ b/tests/knowledge/test_linked_folder_sync.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Path+from deeptutor.api.routers.knowledge import LinkedFolderInfofrom deeptutor.knowledge.manager import KnowledgeBaseManager@@ -49,6 +50,9 @@ def test_update_folder_sync_state_persists_to_disk(tmp_path: Path) -> None:assert "last_sync" in folderassert str(doc) in folder["synced_files"]+ info = LinkedFolderInfo(**folder)+ assert info.last_sync == folder["last_sync"]+def test_update_folder_sync_state_unknown_folder_writes_nothing(tmp_path: Path) -> None:manager, metadata_file, _folder_id, doc = _manager_with_linked_folder(tmp_path)diff --git a/web/components/knowledge/KbLinkedFoldersSection.tsx b/web/components/knowledge/KbLinkedFoldersSection.tsxnew file mode 100644index 000000000..4c08d4de9--- /dev/null+++ b/web/components/knowledge/KbLinkedFoldersSection.tsx@@ -0,0 +1,368 @@+"use client";++import { useCallback, useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ FolderSync,+ Loader2,+ Plus,+ RefreshCw,+ Trash2,+} from "lucide-react";+import {+ linkFolder,+ listLinkedFolders,+ syncLinkedFolder,+ unlinkFolder,+ type LinkedFolderInfo,+} from "@/features/knowledge/api/sources";+import { useKnowledgeProgress } from "@/hooks/useKnowledgeProgress";+import { formatKnowledgeTimestamp } from "@/lib/knowledge-helpers";++interface KbLinkedFoldersSectionProps {+ kbName: string;+ readOnly?: boolean;+}++export default function KbLinkedFoldersSection({+ kbName,+ readOnly = false,+}: KbLinkedFoldersSectionProps) {+ const { t } = useTranslation();+ const [folders, setFolders] = useState<LinkedFolderInfo[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);+ const [notice, setNotice] = useState<string | null>(null);+ const [showForm, setShowForm] = useState(false);+ const [pathInput, setPathInput] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [removingId, setRemovingId] = useState<string | null>(null);+ const [syncingId, setSyncingId] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ try {+ const list = await listLinkedFolders(kbName);+ setFolders(list);+ setError(null);+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setLoading(false);+ }+ }, [kbName]);++ const handleTaskComplete = useCallback(() => {+ void refresh();+ }, [refresh]);++ const { startTask, tasksByKb, progressByKb } = useKnowledgeProgress({+ onComplete: handleTaskComplete,+ });+ const task = tasksByKb[kbName];+ const progress = progressByKb[kbName];++ useEffect(() => {+ let active = true;+ void (async () => {+ await refresh();+ if (!active) return;+ })();+ return () => {+ active = false;+ };+ }, [refresh]);++ const handleLink = async () => {+ const folderPath = pathInput.trim();+ if (!folderPath || readOnly) return;++ setSubmitting(true);+ setError(null);+ setNotice(null);+ try {+ await linkFolder(kbName, folderPath);+ setPathInput("");+ setShowForm(false);+ setNotice(t("Folder linked."));+ await refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSubmitting(false);+ }+ };++ const handleUnlink = async (folderId: string) => {+ if (readOnly) return;+ setRemovingId(folderId);+ setError(null);+ setNotice(null);+ try {+ await unlinkFolder(kbName, folderId);+ setNotice(t("Folder unlinked."));+ await refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setRemovingId(null);+ }+ };++ const handleSync = async (folder: LinkedFolderInfo) => {+ setSyncingId(folder.id);+ setError(null);+ setNotice(null);+ try {+ const result = await syncLinkedFolder(kbName, folder.id);+ if (result.file_count === 0) {+ setNotice(t("No new or modified files to sync."));+ } else if (result.task_id) {+ startTask({+ kbName,+ taskId: result.task_id,+ kind: "folder_sync",+ label: t("Syncing {{count}} changed file(s).", {+ count: result.file_count,+ }),+ seed: {+ stage: "processing",+ message: t("Syncing {{count}} changed file(s).", {+ count: result.file_count,+ }),+ },+ });+ } else {+ setNotice(+ t("Sync started for {{count}} changed file(s).", {+ count: result.file_count,+ }),+ );+ }+ await refresh();+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSyncingId(null);+ }+ };++ if (loading) {+ return (+ <div className="flex items-center justify-center py-10">+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />+ </div>+ );+ }++ const percent =+ typeof progress?.percent === "number"+ ? progress.percent+ : typeof progress?.progress_percent === "number"+ ? progress.progress_percent+ : null;++ return (+ <div className="space-y-5">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="text-[13px] font-medium text-[var(--foreground)]">+ {t("Linked folders")}+ </div>+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">+ {t(+ "Keep a local folder as a source. Uploads copy files once; links remember the source for manual synchronization.",+ )}+ </p>+ </div>+ {!readOnly && (+ <button+ type="button"+ onClick={() => setShowForm((value) => !value)}+ className="inline-flex shrink-0 items-center gap-1.5 rounded-md bg-[var(--primary)] px-2.5 py-1 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"+ >+ <Plus className="h-3 w-3" />+ {t("Link folder")}+ </button>+ )}+ </div>++ {error && (+ <div className="rounded-md border border-red-200 bg-red-50/60 p-2.5 text-[11.5px] text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300">+ {error}+ </div>+ )}+ {notice && !error && (+ <div className="rounded-md border border-emerald-200 bg-emerald-50/60 p-2.5 text-[11.5px] text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/20 dark:text-emerald-300">+ {notice}+ </div>+ )}++ {showForm && !readOnly && (+ <form+ className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3"+ onSubmit={(event) => {+ event.preventDefault();+ void handleLink();+ }}+ >+ <label className="block">+ <span className="mb-1 block text-[11px] font-medium text-[var(--muted-foreground)]">+ {t("Folder path")}+ </span>+ <input+ type="text"+ value={pathInput}+ aria-label={t("Folder path")}+ onChange={(event) => setPathInput(event.target.value)}+ placeholder={t("~/Documents/research-notes")}+ className="w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1.5 font-mono text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]"+ />+ </label>+ <div className="flex items-center gap-2">+ <button+ type="submit"+ disabled={submitting || !pathInput.trim()}+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-50"+ >+ {submitting && <Loader2 className="h-3 w-3 animate-spin" />}+ {t("Link")}+ </button>+ <button+ type="button"+ onClick={() => setShowForm(false)}+ className="rounded-md px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ >+ {t("Cancel")}+ </button>+ </div>+ </form>+ )}++ {folders.length === 0 ? (+ <div className="rounded-lg border border-dashed border-[var(--border)] py-8 text-center">+ <FolderSync className="mx-auto mb-2 h-6 w-6 text-[var(--muted-foreground)]" />+ <p className="text-[12px] text-[var(--muted-foreground)]">+ {t(+ 'No linked folders yet. Click "Link folder" to keep a local source in sync.',+ )}+ </p>+ </div>+ ) : (+ <div className="space-y-2">+ {folders.map((folder) => (+ <FolderCard+ key={folder.id}+ folder={folder}+ busy={syncingId === folder.id || removingId === folder.id}+ syncing={syncingId === folder.id}+ removing={removingId === folder.id}+ readOnly={readOnly}+ onSync={() => void handleSync(folder)}+ onUnlink={() => void handleUnlink(folder.id)}+ />+ ))}+ </div>+ )}++ {task && (task.executing || task.error) && (+ <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <div className="flex items-center gap-2 text-[12px] font-medium text-[var(--foreground)]">+ {task.executing && (+ <Loader2 className="h-3 w-3 animate-spin text-[var(--muted-foreground)]" />+ )}+ {task.executing ? task.label : task.error}+ </div>+ {task.executing && percent !== null && (+ <div className="mt-2 h-1 rounded-full bg-[var(--muted)]">+ <div+ className="h-1 rounded-full bg-[var(--primary)] transition-[width]"+ style={{ width: `${Math.max(0, Math.min(100, percent))}%` }}+ />+ </div>+ )}+ </div>+ )}+ </div>+ );+}++function FolderCard({+ folder,+ busy,+ syncing,+ removing,+ readOnly,+ onSync,+ onUnlink,+}: {+ folder: LinkedFolderInfo;+ busy: boolean;+ syncing: boolean;+ removing: boolean;+ readOnly: boolean;+ onSync: () => void;+ onUnlink: () => void;+}) {+ const { t } = useTranslation();+ const lastSync = formatKnowledgeTimestamp(folder.last_sync ?? undefined);++ return (+ <div className="flex items-start justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <FolderSync className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />+ <span+ className="truncate font-mono text-[12.5px] text-[var(--foreground)]"+ title={folder.path}+ >+ {folder.path}+ </span>+ </div>+ <div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--muted-foreground)]">+ <span>+ {t("Files")}: {folder.file_count}+ </span>+ <span>+ {t("Added")}: {formatKnowledgeTimestamp(folder.added_at)}+ </span>+ {lastSync && (+ <span>+ {t("Last synced")}: {lastSync}+ </span>+ )}+ </div>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ <button+ type="button"+ onClick={onSync}+ disabled={busy}+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[11.5px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-50"+ >+ {syncing ? (+ <Loader2 className="h-3 w-3 animate-spin" />+ ) : (+ <RefreshCw className="h-3 w-3" />+ )}+ {syncing ? t("Syncing…") : t("Sync now")}+ </button>+ {!readOnly && (+ <button+ type="button"+ onClick={onUnlink}+ disabled={busy}+ title={t("Unlink folder")}+ aria-label={t("Unlink folder")}+ className="rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-600 disabled:opacity-50"+ >+ {removing ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : (+ <Trash2 className="h-3.5 w-3.5" />+ )}+ </button>+ )}+ </div>+ </div>+ );+}diff --git a/web/components/knowledge/KnowledgeBaseDetail.tsx b/web/components/knowledge/KnowledgeBaseDetail.tsxindex 2390c7c43..68076ee40 100644--- a/web/components/knowledge/KnowledgeBaseDetail.tsx+++ b/web/components/knowledge/KnowledgeBaseDetail.tsx@@ -6,6 +6,7 @@ import {ArrowLeft,Database,FileText,+ FolderSync,Github,Globe,Layers,@@ -38,6 +39,7 @@ import KbDocumentsSection from "./KbDocumentsSection";import KbIndexVersionsSection from "./KbIndexVersionsSection";import KbSettingsSection from "./KbSettingsSection";import KbGitHubSourcesSection from "./KbGitHubSourcesSection";+import KbLinkedFoldersSection from "./KbLinkedFoldersSection";import KbWebSourcesSection from "./KbWebSourcesSection";import KbMarginNoteDevicesSection from "./KbMarginNoteDevicesSection";import KnowledgeEngineIcon, {@@ -76,6 +78,7 @@ const SECTION_CHROME: Record<> = {files: { label: "Files", Icon: FileText },add: { label: "Add documents", Icon: Upload },+ folders: { label: "Linked folders", Icon: FolderSync },github: { label: "GitHub", Icon: Github },web: { label: "Web", Icon: Globe },versions: { label: "Index versions", Icon: Layers },@@ -317,6 +320,13 @@ export default function KnowledgeBaseDetail({{activeSection === "github" && (<KbGitHubSourcesSection kbName={kb.name} />)}+ {activeSection === "folders" && (+ <KbLinkedFoldersSection+ key={kb.name}+ kbName={kb.name}+ readOnly={kb.read_only === true}+ />+ )}{activeSection === "web" && (<KbWebSourcesSection kbName={kb.name} />)}diff --git a/web/contracts/generated/api.ts b/web/contracts/generated/api.tsindex d72678dfe..415226906 100644--- a/web/contracts/generated/api.ts+++ b/web/contracts/generated/api.ts@@ -10957,6 +10957,8 @@ export interface components {readonly file_count: number;/** Id */readonly id: string;+ /** Last Sync */+ readonly last_sync?: string | null;/** Path */readonly path: string;};diff --git a/web/contracts/schema/openapi.json b/web/contracts/schema/openapi.jsonindex c103168fc..a26d75719 100644--- a/web/contracts/schema/openapi.json+++ b/web/contracts/schema/openapi.json@@ -4482,6 +4482,17 @@"title": "Id","type": "string"},+ "last_sync": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "title": "Last Sync"+ },"path": {"title": "Path","type": "string"diff --git a/web/features/knowledge/api/client.ts b/web/features/knowledge/api/client.tsindex bb5bf400d..95edd179b 100644--- a/web/features/knowledge/api/client.ts+++ b/web/features/knowledge/api/client.ts@@ -838,6 +838,98 @@ export async function connectLinkedFolder(payload: {};}+export interface LinkedFolderInfo {+ id: string;+ path: string;+ added_at: string;+ file_count: number;+ /** Server timestamp of the last completed sync; null before the first sync. */+ last_sync?: string | null;+}++export interface FolderSyncResult {+ message: string;+ folder_path?: string;+ new_files?: number;+ modified_files?: number;+ file_count: number;+ task_id?: string;+}++export async function listLinkedFolders(+ kbName: string,+): Promise<LinkedFolderInfo[]> {+ const res = await apiFetch(+ apiUrl(`/api/knowledge-bases/${encodeURIComponent(kbName)}/linked-folders`),+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(+ res,+ `Failed to list linked folders (${res.status})`,+ ),+ );+ }+ return (await res.json()) as LinkedFolderInfo[];+}++export async function linkFolder(+ kbName: string,+ folderPath: string,+): Promise<LinkedFolderInfo> {+ const res = await apiFetch(+ apiUrl(`/api/knowledge-bases/${encodeURIComponent(kbName)}/link-folder`),+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ folder_path: folderPath }),+ },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to link folder (${res.status})`),+ );+ }+ invalidateKnowledgeCaches();+ return (await res.json()) as LinkedFolderInfo;+}++export async function unlinkFolder(+ kbName: string,+ folderId: string,+): Promise<void> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/linked-folders/${encodeURIComponent(folderId)}`,+ ),+ { method: "DELETE" },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Failed to unlink folder (${res.status})`),+ );+ }+ invalidateKnowledgeCaches();+}++export async function syncLinkedFolder(+ kbName: string,+ folderId: string,+): Promise<FolderSyncResult> {+ const res = await apiFetch(+ apiUrl(+ `/api/knowledge-bases/${encodeURIComponent(kbName)}/sync-folder/${encodeURIComponent(folderId)}`,+ ),+ { method: "POST" },+ );+ if (!res.ok) {+ throw new Error(+ await readErrorDetail(res, `Folder sync failed (${res.status})`),+ );+ }+ return (await res.json()) as FolderSyncResult;+}+export interface LightRagServerProbe {/** Reachable, a LightRAG server, and (if required) the API key is accepted. */ok: boolean;diff --git a/web/features/knowledge/api/sources.ts b/web/features/knowledge/api/sources.tsindex b6803ed77..d38a72580 100644--- a/web/features/knowledge/api/sources.ts+++ b/web/features/knowledge/api/sources.ts@@ -1,19 +1,25 @@export {addGitHubSource,addWebSource,+ linkFolder,listGitHubSources,+ listLinkedFolders,listWebSources,removeGitHubSource,removeWebSource,syncGitHubSources,+ syncLinkedFolder,syncWebSources,+ unlinkFolder,} from "./client";export type {AddGitHubSourcePayload,AddWebSourcePayload,+ FolderSyncResult,GitHubSource,GitHubSyncResult,+ LinkedFolderInfo,WebSource,WebSyncResult,WebSyncSourceResult,diff --git a/web/features/knowledge/model/types.ts b/web/features/knowledge/model/types.tsindex eb495bed3..9f01eb32e 100644--- a/web/features/knowledge/model/types.ts+++ b/web/features/knowledge/model/types.ts@@ -17,7 +17,9 @@ export type {LightRagConfig,LightRagServerConfig,LightRagServerProbe,+ FolderSyncResult,LinkedFolderProbe,+ LinkedFolderInfo,LlamaIndexConfig,ModelKindOptions,ModelOption,diff --git a/web/hooks/useKnowledgeProgress.ts b/web/hooks/useKnowledgeProgress.tsindex eac068927..5107f0b97 100644--- a/web/hooks/useKnowledgeProgress.ts+++ b/web/hooks/useKnowledgeProgress.ts@@ -9,7 +9,7 @@ import {} from "@/lib/knowledge-helpers";import { useTranslation } from "react-i18next";-export type TaskKind = "create" | "upload" | "reindex" | "retry";+export type TaskKind = "create" | "upload" | "folder_sync" | "reindex" | "retry";export interface TaskState {taskId: string;diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 121e0475f..457fb4bf1 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -318,6 +318,7 @@ export const isMarginNoteKb = (kb: KnowledgeBase): boolean =>export const KB_DETAIL_SECTIONS = ["files","add",+ "folders","github","web","versions",diff --git a/web/locales/en/app.json b/web/locales/en/app.jsonindex d889f4458..9fe71ed3d 100644--- a/web/locales/en/app.json+++ b/web/locales/en/app.json@@ -3016,6 +3016,19 @@"Send to Notebook": "Send to Notebook","Build Mastery Path": "Build Mastery Path","Add source": "Add source",+ "Linked folders": "Linked folders",+ "Keep a local folder as a source. Uploads copy files once; links remember the source for manual synchronization.": "Keep a local folder as a source. Uploads copy files once; links remember the source for manual synchronization.",+ "Link folder": "Link folder",+ "Folder linked.": "Folder linked.",+ "Folder unlinked.": "Folder unlinked.",+ "No new or modified files to sync.": "No new or modified files to sync.",+ "Syncing {{count}} changed file(s).": "Syncing {{count}} changed file(s).",+ "Sync started for {{count}} changed file(s).": "Sync started for {{count}} changed file(s).",+ "No linked folders yet. Click \"Link folder\" to keep a local source in sync.": "No linked folders yet. Click \"Link folder\" to keep a local source in sync.",+ "Last synced": "Last synced",+ "Sync now": "Sync now",+ "Syncing…": "Syncing…",+ "Unlink folder": "Unlink folder","Remove source": "Remove source","Transcript": "Transcript","{{count}} passages available to the companion": "{{count}} passages available to the companion",diff --git a/web/locales/zh/app.json b/web/locales/zh/app.jsonindex 9afc4322d..836d1fcad 100644--- a/web/locales/zh/app.json+++ b/web/locales/zh/app.json@@ -3016,6 +3016,19 @@"Send to Notebook": "发送到 Notebook","Build Mastery Path": "生成精通之路","Add source": "添加资料",+ "Linked folders": "关联文件夹",+ "Keep a local folder as a source. Uploads copy files once; links remember the source for manual synchronization.": "将本地文件夹保留为资料来源。上传只复制一次;关联会记住来源,便于手动同步。",+ "Link folder": "关联文件夹",+ "Folder linked.": "文件夹已关联。",+ "Folder unlinked.": "文件夹已解除关联。",+ "No new or modified files to sync.": "没有需要同步的新文件或修改。",+ "Syncing {{count}} changed file(s).": "正在同步 {{count}} 个有变化的文件。",+ "Sync started for {{count}} changed file(s).": "已开始同步 {{count}} 个有变化的文件。",+ "No linked folders yet. Click \"Link folder\" to keep a local source in sync.": "还没有关联文件夹。点击「关联文件夹」,让本地来源保持同步。",+ "Last synced": "上次同步",+ "Sync now": "立即同步",+ "Syncing…": "正在同步…",+ "Unlink folder": "解除文件夹关联","Remove source": "移除资料","Transcript": "转写文本","{{count}} passages available to the companion": "AI 伙伴可读取 {{count}} 个段落",diff --git a/web/tests/kb-linked-folders.spec.tsx b/web/tests/kb-linked-folders.spec.tsxnew file mode 100644index 000000000..e37de93cf--- /dev/null+++ b/web/tests/kb-linked-folders.spec.tsx@@ -0,0 +1,118 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import KbLinkedFoldersSection from "@/components/knowledge/KbLinkedFoldersSection";++const api = vi.hoisted(() => ({+ list: vi.fn(),+ link: vi.fn(),+ unlink: vi.fn(),+ sync: vi.fn(),+ startTask: vi.fn(),+}));++vi.mock("@/features/knowledge/api/sources", () => ({+ listLinkedFolders: api.list,+ linkFolder: api.link,+ unlinkFolder: api.unlink,+ syncLinkedFolder: api.sync,+}));++vi.mock("@/hooks/useKnowledgeProgress", () => ({+ useKnowledgeProgress: () => ({+ startTask: api.startTask,+ tasksByKb: {},+ progressByKb: {},+ }),+}));++vi.mock("react-i18next", () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++const folder = {+ id: "folder-1",+ path: "/tmp/research-notes",+ added_at: "2026-09-09T12:00:00",+ file_count: 4,+ last_sync: null,+};++beforeEach(() => {+ api.list.mockReset().mockResolvedValue([]);+ api.link.mockReset().mockResolvedValue(folder);+ api.unlink.mockReset().mockResolvedValue(undefined);+ api.sync.mockReset().mockResolvedValue({+ message: "No new or modified files to sync",+ file_count: 0,+ });+ api.startTask.mockReset();+});++afterEach(cleanup);++it("links a folder and refreshes the list", async () => {+ api.list.mockResolvedValueOnce([]).mockResolvedValueOnce([folder]);++ render(<KbLinkedFoldersSection kbName="kb" />);+ fireEvent.click(await screen.findByRole("button", { name: "Link folder" }));+ fireEvent.change(screen.getByLabelText("Folder path"), {+ target: { value: "/tmp/research-notes" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^Link$/ }));++ await waitFor(() => expect(api.link).toHaveBeenCalledWith("kb", "/tmp/research-notes"));+ await waitFor(() => expect(screen.getByText("/tmp/research-notes")).toBeVisible());+ expect(screen.getByText("Folder linked.")).toBeVisible();+});++it("reports a completed no-op sync", async () => {+ api.list.mockResolvedValue([folder]);++ render(<KbLinkedFoldersSection kbName="kb" />);+ fireEvent.click(await screen.findByRole("button", { name: "Sync now" }));++ expect(await screen.findByText("No new or modified files to sync.")).toBeVisible();+ expect(api.sync).toHaveBeenCalledWith("kb", "folder-1");+});++it("shows the last successful sync time", async () => {+ api.list.mockResolvedValue([+ { ...folder, last_sync: "2026-09-09T12:00:00" },+ ]);++ render(<KbLinkedFoldersSection kbName="kb" />);++ expect(+ await screen.findByText((_, element) =>+ Boolean(element?.textContent?.startsWith("Last synced:")),+ ),+ ).toBeVisible();+});++it("unlinks a folder and refreshes the list", async () => {+ api.list.mockResolvedValue([folder]);++ render(<KbLinkedFoldersSection kbName="kb" />);+ fireEvent.click(await screen.findByRole("button", { name: "Unlink folder" }));++ await waitFor(() => expect(api.unlink).toHaveBeenCalledWith("kb", "folder-1"));+ expect(await screen.findByText("Folder unlinked.")).toBeVisible();+});++it("streams a changed-folder sync through the shared task hook", async () => {+ api.list.mockResolvedValue([folder]);+ api.sync.mockResolvedValue({+ message: "Syncing 2 files from linked folder",+ file_count: 2,+ task_id: "folder-task",+ });++ render(<KbLinkedFoldersSection kbName="kb" />);+ fireEvent.click(await screen.findByRole("button", { name: "Sync now" }));++ await waitFor(() =>+ expect(api.startTask).toHaveBeenCalledWith(+ expect.objectContaining({ kbName: "kb", taskId: "folder-task" }),+ ),+ );+});diff --git a/web/tests/knowledge-helpers.test.ts b/web/tests/knowledge-helpers.test.tsindex 82b804ac5..6a2720663 100644--- a/web/tests/knowledge-helpers.test.ts+++ b/web/tests/knowledge-helpers.test.ts@@ -253,6 +253,7 @@ test("an ordinary knowledge base has no devices section", () => {assert.deepEqual(kbDetailSections(indexed), ["files","add",+ "folders","github","web","versions",