Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

feat: add scheduled directory import

skfan135f097c527410d
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rs
index 544efc18..877634dc 100644
--- a/src-tauri/src/commands/fs.rs
+++ b/src-tauri/src/commands/fs.rs
@@ -1301,6 +1301,27 @@ pub async fn file_exists(path: String) -> Result<bool, String> {
.map_err(|e| format!("file_exists blocking task join error: {e}"))?
}
+/// Get the last modified timestamp of a file in milliseconds since Unix epoch.
+/// Returns 0 if the file doesn't exist or metadata can't be read.
+#[tauri::command]
+pub async fn get_file_modified_time(path: String) -> Result<u64, String> {
+ tauri::async_runtime::spawn_blocking(move || {
+ run_guarded("get_file_modified_time", || {
+ let metadata = fs::metadata(&path)
+ .map_err(|e| format!("Failed to get metadata for '{}': {}", path, e))?;
+ let modified = metadata
+ .modified()
+ .map_err(|e| format!("Failed to get modified time for '{}': {}", path, e))?;
+ let duration = modified
+ .duration_since(std::time::UNIX_EPOCH)
+ .map_err(|e| format!("Time error for '{}': {}", path, e))?;
+ Ok(duration.as_millis() as u64)
+ })
+ })
+ .await
+ .map_err(|e| format!("get_file_modified_time blocking task join error: {e}"))?
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 207cee6a..d772ad4d 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -86,6 +86,7 @@ pub fn run() {
commands::fs::find_related_wiki_pages,
commands::fs::create_directory,
commands::fs::file_exists,
+ commands::fs::get_file_modified_time,
commands::fs::read_file_as_base64,
commands::project::create_project,
commands::project::open_project,
diff --git a/src/App.tsx b/src/App.tsx
index e4f63f5e..0713d6db 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,7 +5,7 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useReviewStore } from "@/stores/review-store"
import { useChatStore } from "@/stores/chat-store"
import { listDirectory, openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadActivePresetId, loadProxyConfig, loadScheduledImportConfig } from "@/lib/project-store"
import { loadReviewItems, loadChatHistory } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -226,6 +226,10 @@ function App() {
if (savedProxy) {
useWikiStore.getState().setProxyConfig(savedProxy)
}
+ const savedScheduledImport = await loadScheduledImportConfig()
+ if (savedScheduledImport) {
+ useWikiStore.getState().setScheduledImportConfig(savedScheduledImport)
+ }
const savedLang = await loadLanguage()
if (savedLang) {
await i18n.changeLanguage(savedLang)
@@ -277,6 +281,16 @@ function App() {
console.error("Failed to restore dedup queue:", err)
)
})
+ // Start scheduled import if enabled
+ const scheduledImportConfig = useWikiStore.getState().scheduledImportConfig
+ if (scheduledImportConfig.enabled && scheduledImportConfig.path && scheduledImportConfig.interval > 0) {
+ import("@/lib/scheduled-import").then(({ startScheduledImport }) => {
+ startScheduledImport(proj.path, scheduledImportConfig)
+ }).catch((err) =>
+ console.error("Failed to start scheduled import:", err)
+ )
+ }
+
// Notify local clip server of the current project + all recent projects
fetch("http://127.0.0.1:19827/project", {
method: "POST",
@@ -350,6 +364,11 @@ function App() {
}
async function handleSwitchProject() {
+ // Stop scheduled import before switching projects
+ import("@/lib/scheduled-import").then(({ stopScheduledImport }) => {
+ stopScheduledImport()
+ }).catch(() => {})
+
// Clear all per-project state BEFORE flipping back to the welcome screen
// so old data cannot leak in via any async render pass.
const { resetProjectState } = await import("@/lib/reset-project-state")
diff --git a/src/commands/fs.ts b/src/commands/fs.ts
index bc0ac9e5..2b2bb8de 100644
--- a/src/commands/fs.ts
+++ b/src/commands/fs.ts
@@ -50,6 +50,10 @@ export async function fileExists(path: string): Promise<boolean> {
return invoke<boolean>("file_exists", { path })
}
+export async function getFileModifiedTime(path: string): Promise<number> {
+ return invoke<number>("get_file_modified_time", { path })
+}
+
/** Mirror of `commands::fs::FileBase64` (Rust side). */
export interface FileBase64 {
base64: string
diff --git a/src/components/settings/sections/scheduled-import-section.tsx b/src/components/settings/sections/scheduled-import-section.tsx
new file mode 100644
index 00000000..62c284b5
--- /dev/null
+++ b/src/components/settings/sections/scheduled-import-section.tsx
@@ -0,0 +1,191 @@
+import { useState, useEffect, useCallback } from "react"
+import { useTranslation } from "react-i18next"
+import { open } from "@tauri-apps/plugin-dialog"
+import { Input } from "@/components/ui/input"
+import { Label } from "@/components/ui/label"
+import { Button } from "@/components/ui/button"
+import { Folder, Play, RefreshCw } from "lucide-react"
+import type { SettingsDraft, DraftSetter } from "../settings-types"
+import { useWikiStore } from "@/stores/wiki-store"
+import { startScheduledImport, stopScheduledImport, scanAndImport } from "@/lib/scheduled-import"
+
+interface Props {
+ draft: SettingsDraft
+ setDraft: DraftSetter
+}
+
+export function ScheduledImportSection({ draft, setDraft }: Props) {
+ const { t } = useTranslation()
+ const project = useWikiStore((s) => s.project)
+ const scheduledImportConfig = useWikiStore((s) => s.scheduledImportConfig)
+ const [isScanning, setIsScanning] = useState(false)
+
+ const handleSelectDirectory = async () => {
+ const selected = await open({
+ directory: true,
+ title: t("settings.sections.scheduledImport.selectDirectory", {
+ defaultValue: "Select Directory to Monitor",
+ }),
+ })
+
+ if (selected && typeof selected === "string") {
+ setDraft("scheduledImportPath", selected)
+ }
+ }
+
+ const handleManualScan = useCallback(async () => {
+ if (!project || !draft.scheduledImportPath || isScanning) return
+
+ setIsScanning(true)
+ try {
+ await scanAndImport(project.path, draft.scheduledImportPath)
+ } catch (err) {
+ console.error("[Scheduled Import] Manual scan failed:", err)
+ } finally {
+ setIsScanning(false)
+ }
+ }, [project, draft.scheduledImportPath, isScanning])
+
+ // Start/stop scheduled import when config changes
+ useEffect(() => {
+ if (!project) return
+
+ if (draft.scheduledImportEnabled && draft.scheduledImportPath && draft.scheduledImportInterval > 0) {
+ startScheduledImport(project.path, {
+ enabled: true,
+ path: draft.scheduledImportPath,
+ interval: draft.scheduledImportInterval,
+ lastScan: scheduledImportConfig.lastScan,
+ })
+ } else {
+ stopScheduledImport()
+ }
+
+ return () => {
+ stopScheduledImport()
+ }
+ }, [project, draft.scheduledImportEnabled, draft.scheduledImportPath, draft.scheduledImportInterval])
+
+ const lastScanDate = scheduledImportConfig.lastScan
+ ? new Date(scheduledImportConfig.lastScan).toLocaleString()
+ : t("settings.sections.scheduledImport.never", { defaultValue: "Never" })
+
+ return (
+ <div className="space-y-6">
+ <div>
+ <h2 className="text-xl font-semibold">
+ {t("settings.sections.scheduledImport.title", {
+ defaultValue: "Scheduled Import",
+ })}
+ </h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t("settings.sections.scheduledImport.description", {
+ defaultValue:
+ "Automatically monitor a directory and import new or modified files at regular intervals.",
+ })}
+ </p>
+ </div>
+
+ <label className="flex items-center gap-2">
+ <input
+ type="checkbox"
+ checked={draft.scheduledImportEnabled}
+ onChange={(e) => setDraft("scheduledImportEnabled", e.target.checked)}
+ className="h-4 w-4"
+ />
+ <span className="text-sm">
+ {t("settings.sections.scheduledImport.enable", {
+ defaultValue: "Enable scheduled import",
+ })}
+ </span>
+ </label>
+
+ <div className="space-y-2">
+ <Label>
+ {t("settings.sections.scheduledImport.directory", {
+ defaultValue: "Monitor Directory",
+ })}
+ </Label>
+ <div className="flex gap-2">
+ <Input
+ value={draft.scheduledImportPath}
+ onChange={(e) => setDraft("scheduledImportPath", e.target.value)}
+ placeholder="/path/to/monitor"
+ disabled={!draft.scheduledImportEnabled}
+ className="flex-1"
+ />
+ <Button
+ variant="outline"
+ size="icon"
+ onClick={handleSelectDirectory}
+ disabled={!draft.scheduledImportEnabled}
+ title={t("settings.sections.scheduledImport.browse", {
+ defaultValue: "Browse",
+ })}
+ >
+ <Folder className="h-4 w-4" />
+ </Button>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.scheduledImport.directoryHelp", {
+ defaultValue:
+ "Files in this directory (and subdirectories) will be automatically imported. New files are copied to sources; modified files are re-ingested.",
+ })}
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="scheduled-import-interval">
+ {t("settings.sections.scheduledImport.interval", {
+ defaultValue: "Scan Interval (minutes)",
+ })}
+ </Label>
+ <Input
+ id="scheduled-import-interval"
+ type="number"
+ min={1}
+ max={1440}
+ value={draft.scheduledImportInterval}
+ onChange={(e) => {
+ const val = parseInt(e.target.value, 10)
+ if (!isNaN(val) && val >= 1) {
+ setDraft("scheduledImportInterval", val)
+ }
+ }}
+ disabled={!draft.scheduledImportEnabled}
+ className="w-32"
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.scheduledImport.intervalHelp", {
+ defaultValue: "How often to check for changes. Minimum: 1 minute.",
+ })}
+ </p>
+ </div>
+
+ <div className="flex items-center gap-4">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleManualScan}
+ disabled={!draft.scheduledImportEnabled || !draft.scheduledImportPath || isScanning}
+ >
+ {isScanning ? (
+ <RefreshCw className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Play className="mr-2 h-4 w-4" />
+ )}
+ {isScanning
+ ? t("settings.sections.scheduledImport.scanning", { defaultValue: "Scanning..." })
+ : t("settings.sections.scheduledImport.scanNow", { defaultValue: "Scan Now" })}
+ </Button>
+
+ <span className="text-xs text-muted-foreground">
+ {t("settings.sections.scheduledImport.lastScan", {
+ defaultValue: "Last scan: {{time}}",
+ time: lastScanDate,
+ })}
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index aae8b94d..2b8f28f4 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -52,6 +52,11 @@ export interface SettingsDraft {
proxyUrl: string
proxyBypassLocal: boolean
+ // Scheduled Import
+ scheduledImportEnabled: boolean
+ scheduledImportPath: string
+ scheduledImportInterval: number // minutes
+
// UI
uiLanguage: string
}
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index 99d2f74a..d78baf2b 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -10,6 +10,7 @@ import {
Network,
History,
Wrench,
+ Clock,
} from "lucide-react"
import { useTranslation } from "react-i18next"
import { invoke } from "@tauri-apps/api/core"
@@ -27,6 +28,7 @@ import { WebSearchSection } from "./sections/web-search-section"
import { OutputSection } from "./sections/output-section"
import { InterfaceSection } from "./sections/interface-section"
import { NetworkSection } from "./sections/network-section"
+import { ScheduledImportSection } from "./sections/scheduled-import-section"
import { ChangelogSection } from "./sections/changelog-section"
import { MaintenanceSection } from "./sections/maintenance-section"
import { AboutSection } from "./sections/about-section"
@@ -37,6 +39,7 @@ type CategoryId =
| "multimodal"
| "web-search"
| "network"
+ | "scheduled-import"
| "output"
| "interface"
| "maintenance"
@@ -58,6 +61,7 @@ const CATEGORIES: Category[] = [
{ id: "multimodal", labelKey: "settings.categories.multimodal", icon: ImageIcon },
{ id: "web-search", labelKey: "settings.categories.webSearch", icon: Globe },
{ id: "network", labelKey: "settings.categories.network", icon: Network },
+ { id: "scheduled-import", labelKey: "settings.categories.scheduledImport", icon: Clock },
{ id: "output", labelKey: "settings.categories.output", icon: Languages },
{ id: "interface", labelKey: "settings.categories.interface", icon: Palette },
{ id: "maintenance", labelKey: "settings.categories.maintenance", icon: Wrench },
@@ -72,6 +76,7 @@ function initialDraft(
multimodal: ReturnType<typeof useWikiStore.getState>["multimodalConfig"],
outputLanguage: ReturnType<typeof useWikiStore.getState>["outputLanguage"],
proxy: ReturnType<typeof useWikiStore.getState>["proxyConfig"],
+ scheduledImport: ReturnType<typeof useWikiStore.getState>["scheduledImportConfig"],
maxHistoryMessages: number,
uiLanguage: string,
): SettingsDraft {
@@ -105,6 +110,9 @@ function initialDraft(
proxyEnabled: proxy.enabled,
proxyUrl: proxy.url,
proxyBypassLocal: proxy.bypassLocal,
+ scheduledImportEnabled: scheduledImport.enabled,
+ scheduledImportPath: scheduledImport.path,
+ scheduledImportInterval: scheduledImport.interval,
uiLanguage,
}
}
@@ -123,6 +131,8 @@ export function SettingsView() {
const setOutputLanguage = useWikiStore((s) => s.setOutputLanguage)
const proxyConfig = useWikiStore((s) => s.proxyConfig)
const setProxyConfig = useWikiStore((s) => s.setProxyConfig)
+ const scheduledImportConfig = useWikiStore((s) => s.scheduledImportConfig)
+ const setScheduledImportConfig = useWikiStore((s) => s.setScheduledImportConfig)
const maxHistoryMessages = useChatStore((s) => s.maxHistoryMessages)
const setMaxHistoryMessages = useChatStore((s) => s.setMaxHistoryMessages)
// Drives the red dot next to the "About" row in the settings
@@ -145,6 +155,7 @@ export function SettingsView() {
multimodalConfig,
outputLanguage,
proxyConfig,
+ scheduledImportConfig,
maxHistoryMessages,
i18n.language,
),
@@ -167,6 +178,7 @@ export function SettingsView() {
multimodalConfig,
outputLanguage,
proxyConfig,
+ scheduledImportConfig,
maxHistoryMessages,
prev.uiLanguage,
),
@@ -178,6 +190,7 @@ export function SettingsView() {
multimodalConfig,
outputLanguage,
proxyConfig,
+ scheduledImportConfig,
maxHistoryMessages,
])
@@ -193,6 +206,7 @@ export function SettingsView() {
saveMultimodalConfig,
saveOutputLanguage,
saveProxyConfig,
+ saveScheduledImportConfig,
} = await import("@/lib/project-store")
const newLlm = {
@@ -258,6 +272,16 @@ export function SettingsView() {
} catch (err) {
console.warn("[proxy] live update failed; restart will still apply:", err)
}
+
+ const newScheduledImport = {
+ enabled: draft.scheduledImportEnabled,
+ path: draft.scheduledImportPath,
+ interval: draft.scheduledImportInterval,
+ lastScan: scheduledImportConfig.lastScan,
+ }
+ setScheduledImportConfig(newScheduledImport)
+ await saveScheduledImportConfig(newScheduledImport)
+
setMaxHistoryMessages(draft.maxHistoryMessages)
if (draft.uiLanguage !== i18n.language) {
@@ -274,6 +298,8 @@ export function SettingsView() {
setEmbeddingConfig,
setOutputLanguage,
setProxyConfig,
+ setScheduledImportConfig,
+ scheduledImportConfig,
setMaxHistoryMessages,
outputLanguage,
])
@@ -293,6 +319,8 @@ export function SettingsView() {
return <WebSearchSection draft={draft} setDraft={setDraft} />
case "network":
return <NetworkSection draft={draft} setDraft={setDraft} />
+ case "scheduled-import":
+ return <ScheduledImportSection draft={draft} setDraft={setDraft} />
case "output":
return <OutputSection draft={draft} setDraft={setDraft} />
case "interface":
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 3d13c3cc..bbc938ba 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -108,6 +108,7 @@
"multimodal": "Image Captioning",
"webSearch": "Web Search",
"network": "Network",
+ "scheduledImport": "Scheduled Import",
"output": "Output",
"interface": "Interface",
"maintenance": "Maintenance",
@@ -196,6 +197,21 @@
"bypassLocal": "Bypass proxy for local addresses (recommended)",
"bypassLocalHelp": "Requests to localhost, 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, and *.local don't go through the proxy. Keep this on if you use Ollama / LM Studio / other local or LAN-deployed LLMs."
},
+ "scheduledImport": {
+ "title": "Scheduled Import",
+ "description": "Automatically monitor a directory and import new or modified files at regular intervals.",
+ "enable": "Enable scheduled import",
+ "directory": "Monitor Directory",
+ "directoryHelp": "Files in this directory (and subdirectories) will be automatically imported. New files are copied to sources; modified files are re-ingested.",
+ "browse": "Browse",
+ "selectDirectory": "Select Directory to Monitor",
+ "interval": "Scan Interval (minutes)",
+ "intervalHelp": "How often to check for changes. Minimum: 1 minute.",
+ "scanNow": "Scan Now",
+ "scanning": "Scanning...",
+ "lastScan": "Last scan: {{time}}",
+ "never": "Never"
+ },
"output": {
"title": "Output Preferences",
"description": "Controls for generated content — language, conversation history length.",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index fd5b06f4..d09216aa 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -108,6 +108,7 @@
"multimodal": "图片描述",
"webSearch": "网页搜索",
"network": "网络",
+ "scheduledImport": "定时导入",
"output": "输出偏好",
"interface": "界面",
"maintenance": "维护",
@@ -196,6 +197,21 @@
"bypassLocal": "本地地址不走代理(推荐)",
"bypassLocalHelp": "对 localhost、127.0.0.0/8、10.0.0.0/8、172.16.0.0/12、192.168.0.0/16 以及 *.local 的请求会绕过代理。如果你用 Ollama / LM Studio 或局域网内的 LLM 服务,请保持开启。"
},
+ "scheduledImport": {
+ "title": "定时导入",
+ "description": "自动监控指定目录,按固定间隔导入新增或修改的文件。",
+ "enable": "启用定时导入",
+ "directory": "监控目录",
+ "directoryHelp": "该目录(含子目录)中的文件将被自动导入。新文件会复制到 sources;修改过的文件会重新摄入。",
+ "browse": "浏览",
+ "selectDirectory": "选择监控目录",
+ "interval": "扫描间隔(分钟)",
+ "intervalHelp": "检查变更的频率。最小值:1 分钟。",
+ "scanNow": "立即扫描",
+ "scanning": "扫描中...",
+ "lastScan": "上次扫描:{{time}}",
+ "never": "从未"
+ },
"output": {
"title": "输出偏好",
"description": "影响生成内容的语言、对话历史长度等参数。",
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index 278d2dae..41d7b19b 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -1,6 +1,6 @@
import { load } from "@tauri-apps/plugin-store"
import type { WikiProject } from "@/types/wiki"
-import type { LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProviderConfigs, ProxyConfig } from "@/stores/wiki-store"
+import type { LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProviderConfigs, ProxyConfig, ScheduledImportConfig } from "@/stores/wiki-store"
const STORE_NAME = "app-state.json"
const RECENT_PROJECTS_KEY = "recentProjects"
@@ -133,6 +133,19 @@ export async function loadProxyConfig(): Promise<ProxyConfig | null> {
return (await store.get<ProxyConfig>(PROXY_CONFIG_KEY)) ?? null
}
+const SCHEDULED_IMPORT_KEY = "scheduledImportConfig"
+
+export async function saveScheduledImportConfig(config: ScheduledImportConfig): Promise<void> {
+ const store = await getStore()
+ await store.set(SCHEDULED_IMPORT_KEY, config)
+ await store.save()
+}
+
+export async function loadScheduledImportConfig(): Promise<ScheduledImportConfig | null> {
+ const store = await getStore()
+ return (await store.get<ScheduledImportConfig>(SCHEDULED_IMPORT_KEY)) ?? null
+}
+
export async function removeFromRecentProjects(
path: string
): Promise<void> {
diff --git a/src/lib/scheduled-import.ts b/src/lib/scheduled-import.ts
new file mode 100644
index 00000000..8af03928
--- /dev/null
+++ b/src/lib/scheduled-import.ts
@@ -0,0 +1,246 @@
+import { listDirectory, copyFile, preprocessFile, getFileModifiedTime } from "@/commands/fs"
+import { enqueueIngest } from "@/lib/ingest-queue"
+import { normalizePath, getFileName } from "@/lib/path-utils"
+import { hasUsableLlm } from "@/lib/has-usable-llm"
+import { useWikiStore, type ScheduledImportConfig } from "@/stores/wiki-store"
+import type { FileNode } from "@/types/wiki"
+
+// Supported file extensions for import
+const IMPORTABLE_EXTENSIONS = new Set([
+ "md", "mdx", "txt", "rtf", "pdf",
+ "html", "htm", "xml",
+ "doc", "docx", "xls", "xlsx", "ppt", "pptx",
+ "odt", "ods", "odp", "epub", "pages", "numbers", "key",
+ "json", "jsonl", "csv", "tsv", "yaml", "yml", "ndjson",
+ "py", "js", "ts", "jsx", "tsx", "rs", "go", "java",
+ "c", "cpp", "h", "rb", "php", "swift", "sql", "sh",
+])
+
+let scanTimer: ReturnType<typeof setInterval> | null = null
+let scanning = false
+
+interface FileChange {
+ type: "new" | "modified"
+ sourcePath: string // absolute path in monitored directory
+ fileName: string
+}
+
+/**
+ * Get all files recursively from a directory tree (FileNode structure).
+ */
+function collectFiles(nodes: FileNode[], prefix: string = ""): Array<{ name: string; path: string }> {
+ const files: Array<{ name: string; path: string }> = []
+ for (const node of nodes) {
+ if (node.is_dir && node.children) {
+ files.push(...collectFiles(node.children, `${prefix}${node.name}/`))
+ } else if (!node.is_dir) {
+ files.push({ name: `${prefix}${node.name}`, path: node.path })
+ }
+ }
+ return files
+}
+
+/**
+ * Check if a file has an importable extension.
+ */
+function isImportableFile(fileName: string): boolean {
+ const ext = fileName.split(".").pop()?.toLowerCase() ?? ""
+ return IMPORTABLE_EXTENSIONS.has(ext)
+}
+
+/**
+ * Build a map of existing sources: fileName -> lastModifiedTime.
+ * We match by base filename (without directory prefix) since sources
+ * are flat in raw/sources/.
+ */
+async function buildExistingSourcesMap(projectPath: string): Promise<Map<string, { path: string; modified: number }>> {
+ const pp = normalizePath(projectPath)
+ const map = new Map<string, { path: string; modified: number }>()
+
+ try {
+ const tree = await listDirectory(`${pp}/raw/sources`)
+ const files = collectFiles(tree)
+
+ for (const file of files) {
+ const baseName = getFileName(file.path) || file.name
+ try {
+ const modified = await getFileModifiedTime(file.path)
+ map.set(baseName, { path: file.path, modified })
+ } catch {
+ // Can't get modified time, skip
+ }
+ }
+ } catch {
+ // sources directory may not exist yet
+ }
+
+ return map
+}
+
+/**
+ * Detect changes between monitored directory and existing sources.
+ */
+async function detectChanges(
+ monitoredPath: string,
+ existingSources: Map<string, { path: string; modified: number }>,
+): Promise<FileChange[]> {
+ const changes: FileChange[] = []
+
+ try {
+ const tree = await listDirectory(monitoredPath)
+ const files = collectFiles(tree)
+
+ for (const file of files) {
+ if (!isImportableFile(file.name)) continue
+
+ const baseName = getFileName(file.path) || file.name
+ const existing = existingSources.get(baseName)
+
+ if (!existing) {
+ // New file
+ changes.push({
+ type: "new",
+ sourcePath: file.path,
+ fileName: baseName,
+ })
+ } else {
+ // Check if modified
+ try {
+ const sourceModified = await getFileModifiedTime(file.path)
+ if (sourceModified > existing.modified) {
+ changes.push({
+ type: "modified",
+ sourcePath: file.path,
+ fileName: baseName,
+ })
+ }
+ } catch {
+ // Can't compare, skip
+ }
+ }
+ }
+ } catch (err) {
+ console.error("[Scheduled Import] Failed to scan monitored directory:", err)
+ }
+
+ return changes
+}
+
+/**
+ * Execute a scan: detect changes and import modified/new files.
+ */
+export async function scanAndImport(projectPath: string, importPath: string): Promise<void> {
+ if (scanning) {
+ console.log("[Scheduled Import] Scan already in progress, skipping")
+ return
+ }
+
+ const pp = normalizePath(projectPath)
+ const ip = normalizePath(importPath)
+
+ scanning = true
+ console.log(`[Scheduled Import] Starting scan of ${ip}`)
+
+ try {
+ const existingSources = await buildExistingSourcesMap(pp)
+ const changes = await detectChanges(ip, existingSources)
+
+ if (changes.length === 0) {
+ console.log("[Scheduled Import] No changes detected")
+ return
+ }
+
+ console.log(`[Scheduled Import] Found ${changes.length} changes`)
+
+ const llmConfig = useWikiStore.getState().llmConfig
+ const hasLlm = hasUsableLlm(llmConfig)
+
+ for (const change of changes) {
+ try {
+ // Copy file to sources directory
+ const destPath = `${pp}/raw/sources/${change.fileName}`
+ await copyFile(change.sourcePath, destPath)
+
+ // Preprocess the file
+ preprocessFile(destPath).catch(() => {})
+
+ // Enqueue for ingest if LLM is configured
+ if (hasLlm) {
+ const project = useWikiStore.getState().project
+ if (project) {
+ await enqueueIngest(project.id, destPath)
+ }
+ }
+
+ console.log(`[Scheduled Import] ${change.type === "new" ? "Imported" : "Updated"}: ${change.fileName}`)
+ } catch (err) {
+ console.error(`[Scheduled Import] Failed to process ${change.fileName}:`, err)
+ }
+ }
+
+ // Update last scan time
+ const config = useWikiStore.getState().scheduledImportConfig
+ useWikiStore.getState().setScheduledImportConfig({
+ ...config,
+ lastScan: Date.now(),
+ })
+
+ // Refresh file tree
+ const { listDirectory: listDir } = await import("@/commands/fs")
+ const tree = await listDir(pp)
+ useWikiStore.getState().setFileTree(tree)
+ useWikiStore.getState().bumpDataVersion()
+
+ } catch (err) {
+ console.error("[Scheduled Import] Scan failed:", err)
+ } finally {
+ scanning = false
+ }
+}
+
+/**
+ * Start the scheduled import timer.
+ */
+export function startScheduledImport(projectPath: string, config: ScheduledImportConfig): void {
+ stopScheduledImport()
+
+ if (!config.enabled || !config.path || config.interval <= 0) {
+ return
+ }
+
+ const pp = normalizePath(projectPath)
+ const ip = normalizePath(config.path)
+
+ console.log(`[Scheduled Import] Starting with interval ${config.interval} minutes`)
+
+ // Run first scan immediately
+ scanAndImport(pp, ip).catch((err) => {
+ console.error("[Scheduled Import] Initial scan failed:", err)
+ })
+
+ // Set up interval
+ const intervalMs = config.interval * 60 * 1000
+ scanTimer = setInterval(() => {
+ scanAndImport(pp, ip).catch((err) => {
+ console.error("[Scheduled Import] Scheduled scan failed:", err)
+ })
+ }, intervalMs)
+}
+
+/**
+ * Stop the scheduled import timer.
+ */
+export function stopScheduledImport(): void {
+ if (scanTimer) {
+ clearInterval(scanTimer)
+ scanTimer = null
+ console.log("[Scheduled Import] Stopped")
+ }
+}
+
+/**
+ * Check if scheduled import is currently running.
+ */
+export function isScanning(): boolean {
+ return scanning
+}
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index ff5891cc..6c9dbcdb 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -87,6 +87,13 @@ interface ProxyConfig {
bypassLocal: boolean
}
+interface ScheduledImportConfig {
+ enabled: boolean
+ path: string // 监控目录的绝对路径
+ interval: number // 扫描间隔(分钟)
+ lastScan: number | null // 上次扫描时间戳
+}
+
interface MultimodalConfig {
enabled: boolean
/** Reuse `llmConfig` for caption calls. When true, the fields
@@ -177,6 +184,7 @@ interface WikiState {
multimodalConfig: MultimodalConfig
outputLanguage: OutputLanguage
proxyConfig: ProxyConfig
+ scheduledImportConfig: ScheduledImportConfig
dataVersion: number
setProject: (project: WikiProject | null) => void
@@ -194,6 +202,7 @@ interface WikiState {
setMultimodalConfig: (config: MultimodalConfig) => void
setOutputLanguage: (lang: OutputLanguage) => void
setProxyConfig: (config: ProxyConfig) => void
+ setScheduledImportConfig: (config: ScheduledImportConfig) => void
bumpDataVersion: () => void
}
@@ -262,6 +271,13 @@ export const useWikiStore = create<WikiState>((set) => ({
bypassLocal: true,
},
+ scheduledImportConfig: {
+ enabled: false,
+ path: "",
+ interval: 60,
+ lastScan: null,
+ },
+
setLlmConfig: (llmConfig) => set({ llmConfig }),
setProviderConfigs: (providerConfigs) => set({ providerConfigs }),
setActivePresetId: (activePresetId) => set({ activePresetId }),
@@ -270,7 +286,8 @@ export const useWikiStore = create<WikiState>((set) => ({
setMultimodalConfig: (multimodalConfig) => set({ multimodalConfig }),
setOutputLanguage: (outputLanguage) => set({ outputLanguage }),
setProxyConfig: (proxyConfig) => set({ proxyConfig }),
+ setScheduledImportConfig: (scheduledImportConfig) => set({ scheduledImportConfig }),
bumpDataVersion: () => set((state) => ({ dataVersion: state.dataVersion + 1 })),
}))
-export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProxyConfig }
+export type { WikiState, LlmConfig, SearchApiConfig, EmbeddingConfig, MultimodalConfig, OutputLanguage, ProxyConfig, ScheduledImportConfig }