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: monitor source changes across recent projects

nash_suc80e802d6588
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rs
index 796c75c0..00b7b3cb 100644
--- a/src-tauri/src/api_server.rs
+++ b/src-tauri/src/api_server.rs
@@ -2531,6 +2531,7 @@ fn handle_rescan(app: &AppHandle, project_id: &str) -> ApiResponse {
project.id.clone(),
project.path.clone(),
source_watch_config,
+ None,
) {
Ok(result) => ok(json!({ "ok": true, "projectId": project.id, "result": result })),
Err(e) => err(500, e),
diff --git a/src-tauri/src/commands/file_sync.rs b/src-tauri/src/commands/file_sync.rs
index 5b7791f8..7811a59b 100644
--- a/src-tauri/src/commands/file_sync.rs
+++ b/src-tauri/src/commands/file_sync.rs
@@ -332,12 +332,17 @@ pub fn rescan_project_files(
project_id: String,
project_path: String,
source_watch_config: Option<SourceWatchConfig>,
+ watch_roots_only: Option<bool>,
) -> Result<FileChangeRescanResult, String> {
run_guarded("rescan_project_files", || {
let root = PathBuf::from(project_path);
let source_watch_config = normalize_source_watch_config(source_watch_config);
ensure_sync_dir(&root)?;
- enqueue_rescan_changes(&root, &project_id, &source_watch_config)?;
+ if watch_roots_only.unwrap_or(false) {
+ enqueue_startup_rescan_changes(&root, &project_id, &source_watch_config)?;
+ } else {
+ enqueue_rescan_changes(&root, &project_id, &source_watch_config)?;
+ }
let changed_tasks = process_queue(&app, &root, &project_id)?;
let queue = with_queue_lock(&root, || read_queue(&root))?;
emit_queue(&app, &project_id, &queue);
@@ -348,6 +353,31 @@ pub fn rescan_project_files(
})
}
+#[tauri::command]
+pub fn invalidate_project_file_snapshot_paths(
+ project_path: String,
+ paths: Vec<String>,
+) -> Result<(), String> {
+ run_guarded("invalidate_project_file_snapshot_paths", || {
+ let root = PathBuf::from(project_path);
+ let rels = paths
+ .iter()
+ .map(|path| {
+ normalize_rel_path(Path::new(path))
+ .ok_or_else(|| format!("invalid project-relative snapshot path: {path}"))
+ })
+ .collect::<Result<Vec<_>, _>>()?;
+ with_queue_lock(&root, || {
+ let mut snapshot = read_snapshot(&root)?;
+ for rel in rels {
+ snapshot.files.remove(&rel);
+ }
+ snapshot.updated_at = now_ms();
+ write_snapshot(&root, &snapshot)
+ })
+ })
+}
+
#[tauri::command]
pub fn get_file_change_queue(project_path: String) -> Result<FileChangeQueue, String> {
run_guarded("get_file_change_queue", || {
@@ -1525,6 +1555,34 @@ mod tests {
let _ = fs::remove_dir_all(root);
}
+ #[test]
+ fn invalidating_snapshot_paths_makes_existing_files_detectable_again() {
+ let root = temp_root("invalidate-snapshot");
+ let rel = "raw/sources/retry.md";
+ fs::write(root.join(rel), "retry me").unwrap();
+ ensure_sync_dir(&root).unwrap();
+ sync_snapshot_paths(&root, BTreeSet::from([rel.to_string()])).unwrap();
+
+ invalidate_project_file_snapshot_paths(
+ root.to_string_lossy().to_string(),
+ vec![rel.to_string()],
+ )
+ .unwrap();
+ enqueue_rescan_changes_for_prefixes(
+ &root,
+ "p1",
+ &["raw/sources"],
+ &default_watch_config(),
+ )
+ .unwrap();
+
+ let queue = read_queue(&root).unwrap();
+ assert!(queue.tasks.iter().any(|task| {
+ task.path == rel && task.kind == FileChangeKind::Created
+ }));
+ let _ = fs::remove_dir_all(root);
+ }
+
#[test]
fn startup_rescan_scans_watch_roots_without_full_project_walk() {
let root = temp_root("startup-prefixes");
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 870155c9..e66522b0 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -694,6 +694,7 @@ pub fn run() {
commands::file_sync::start_project_file_watcher,
commands::file_sync::stop_project_file_watcher,
commands::file_sync::rescan_project_files,
+ commands::file_sync::invalidate_project_file_snapshot_paths,
commands::file_sync::get_file_change_queue,
commands::file_sync::retry_file_change_task,
commands::file_sync::ignore_file_change_task,
diff --git a/src/App.tsx b/src/App.tsx
index 071e8dd9..84446998 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -9,7 +9,7 @@ import { useLintStore } from "@/stores/lint-store"
import { useChatStore } from "@/stores/chat-store"
import { BASE_FONT_SIZE_PX, useZoomStore } from "@/stores/zoom-store"
import { openProject } from "@/commands/fs"
-import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMineruConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadCustomLlmPresets, loadActivePresetId, loadTaskModelRouting, loadProjectLlmOverride, loadProxyConfig, loadScheduledImportConfig, saveScheduledImportConfig, loadSourceWatchConfig, loadApiConfig, loadGeneralConfig, loadZoomLevel } from "@/lib/project-store"
+import { getLastProject, getRecentProjects, saveLastProject, loadLlmConfig, loadLanguage, loadSearchApiConfig, loadEmbeddingConfig, loadMineruConfig, loadMultimodalConfig, loadOutputLanguage, loadProviderConfigs, loadCustomLlmPresets, loadActivePresetId, loadTaskModelRouting, loadProjectLlmOverride, loadProxyConfig, loadScheduledImportConfig, saveScheduledImportConfig, loadSourceWatchAllProjects, loadSourceWatchConfig, loadApiConfig, loadGeneralConfig, loadZoomLevel } from "@/lib/project-store"
import { loadReviewItems, loadLintItems, loadChatHistory, loadChatPreferences } from "@/lib/persist"
import { setupAutoSave } from "@/lib/auto-save"
import { startClipWatcher } from "@/lib/clip-watcher"
@@ -503,10 +503,31 @@ function App() {
)
})
// Start project source watch if enabled
- import("@/lib/project-file-sync").then(async ({ startProjectFileSync, stopProjectFileSync }) => {
- const config = await loadSourceWatchConfig(proj.id)
+ import("@/lib/project-file-sync").then(async ({
+ startAllProjectFileSync,
+ startProjectFileSync,
+ stopAllProjectFileSync,
+ stopProjectFileSync,
+ }) => {
+ const [configResult, allProjectsResult] = await Promise.allSettled([
+ loadSourceWatchConfig(proj.id),
+ loadSourceWatchAllProjects(),
+ ])
+ const config = configResult.status === "fulfilled"
+ ? configResult.value
+ : DEFAULT_SOURCE_WATCH_CONFIG
+ const allProjects = allProjectsResult.status === "fulfilled"
+ ? allProjectsResult.value
+ : false
+ if (configResult.status === "rejected") {
+ console.error("Failed to load project source watch config:", configResult.reason)
+ }
+ if (allProjectsResult.status === "rejected") {
+ console.error("Failed to load all-project source watch setting:", allProjectsResult.reason)
+ }
if (!isCurrentProject(proj)) return
useWikiStore.getState().setSourceWatchConfig(config)
+ useWikiStore.getState().setSourceWatchAllProjects(allProjects)
if (config.enabled) {
startProjectFileSync(proj, config).catch((err) =>
console.error("Failed to start project file sync:", err)
@@ -514,6 +535,11 @@ function App() {
} else {
stopProjectFileSync().catch(() => {})
}
+ if (allProjects) {
+ startAllProjectFileSync(proj)
+ } else {
+ stopAllProjectFileSync()
+ }
}).catch((err) => console.error("Failed to configure project file sync:", err))
// Notify local clip server of the current project + all recent projects
fetch("http://127.0.0.1:19827/project", {
@@ -588,6 +614,9 @@ function App() {
}
async function handleSwitchProject() {
+ import("@/lib/project-file-sync").then(({ stopAllProjectFileSync }) => {
+ stopAllProjectFileSync()
+ }).catch(() => {})
// Stop scheduled import before switching projects
import("@/lib/scheduled-import").then(({ stopScheduledImport }) => {
stopScheduledImport()
diff --git a/src/commands/file-sync.ts b/src/commands/file-sync.ts
index 205be6ce..1d52a3f2 100644
--- a/src/commands/file-sync.ts
+++ b/src/commands/file-sync.ts
@@ -57,14 +57,23 @@ export function rescanProjectFiles(
projectId: string,
projectPath: string,
sourceWatchConfig?: SourceWatchConfig,
+ watchRootsOnly = false,
): Promise<FileChangeRescanResult> {
return invoke<FileChangeRescanResult>("rescan_project_files", {
projectId,
projectPath,
sourceWatchConfig: normalizeSourceWatchConfig(sourceWatchConfig),
+ watchRootsOnly,
})
}
+export function invalidateProjectFileSnapshotPaths(
+ projectPath: string,
+ paths: string[],
+): Promise<void> {
+ return invoke<void>("invalidate_project_file_snapshot_paths", { projectPath, paths })
+}
+
export function getFileChangeQueue(projectPath: string): Promise<FileChangeQueue> {
return invoke<FileChangeQueue>("get_file_change_queue", { projectPath })
}
diff --git a/src/components/settings/sections/source-watch-section.tsx b/src/components/settings/sections/source-watch-section.tsx
index 0a92cf29..e0c33731 100644
--- a/src/components/settings/sections/source-watch-section.tsx
+++ b/src/components/settings/sections/source-watch-section.tsx
@@ -106,6 +106,28 @@ export function SourceWatchSection({ draft, setDraft, projectReady }: Props) {
</div>
</label>
+ <label className="flex items-start gap-3">
+ <input
+ type="checkbox"
+ checked={draft.sourceWatchAllProjects}
+ onChange={(event) => setDraft("sourceWatchAllProjects", event.target.checked)}
+ className="mt-1 h-4 w-4"
+ />
+ <div className="space-y-1">
+ <div className="text-sm font-semibold">
+ {t("settings.sections.sourceWatch.allProjects", {
+ defaultValue: "Monitor all recent projects",
+ })}
+ </div>
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {t("settings.sections.sourceWatch.allProjectsDescription", {
+ defaultValue:
+ "Keep watching source folders for every recent project that has monitoring enabled. Background changes are queued for that project and run when it is opened.",
+ })}
+ </p>
+ </div>
+ </label>
+
<label className="block space-y-1.5">
<span className="text-sm font-semibold">
{t("settings.sections.sourceWatch.parsingConcurrency", {
diff --git a/src/components/settings/settings-types.ts b/src/components/settings/settings-types.ts
index 8c0b3ef2..2a75aad4 100644
--- a/src/components/settings/settings-types.ts
+++ b/src/components/settings/settings-types.ts
@@ -81,6 +81,7 @@ export interface SettingsDraft {
// Source folder auto watch
sourceWatchConfig: SourceWatchConfig
+ sourceWatchAllProjects: boolean
// MinerU PDF parsing
mineruEnabled: boolean
diff --git a/src/components/settings/settings-view.tsx b/src/components/settings/settings-view.tsx
index f8ce46d2..cbae6547 100644
--- a/src/components/settings/settings-view.tsx
+++ b/src/components/settings/settings-view.tsx
@@ -25,7 +25,13 @@ import { useWikiStore } from "@/stores/wiki-store"
import { useChatStore } from "@/stores/chat-store"
import { useUpdateStore, hasAvailableUpdate } from "@/stores/update-store"
import { useZoomStore } from "@/stores/zoom-store"
-import { loadSourceWatchConfig, saveLanguage, saveTheme, loadTheme } from "@/lib/project-store"
+import {
+ loadSourceWatchAllProjects,
+ loadSourceWatchConfig,
+ saveLanguage,
+ saveTheme,
+ loadTheme,
+} from "@/lib/project-store"
import { applyTheme, type AppTheme } from "@/lib/theme"
import type { SettingsDraft, DraftSetter } from "./settings-types"
import { normalizeSourceWatchConfig } from "@/lib/source-watch-config"
@@ -98,6 +104,7 @@ function initialDraft(
proxy: ReturnType<typeof useWikiStore.getState>["proxyConfig"],
scheduledImport: ReturnType<typeof useWikiStore.getState>["scheduledImportConfig"],
sourceWatch: ReturnType<typeof useWikiStore.getState>["sourceWatchConfig"],
+ sourceWatchAllProjects: boolean,
mineru: ReturnType<typeof useWikiStore.getState>["mineruConfig"],
apiConfig: ReturnType<typeof useWikiStore.getState>["apiConfig"],
generalConfig: ReturnType<typeof useWikiStore.getState>["generalConfig"],
@@ -162,6 +169,7 @@ function initialDraft(
scheduledImportPath: displayPath,
scheduledImportInterval: scheduledImport.interval,
sourceWatchConfig: normalizeSourceWatchConfig(sourceWatch),
+ sourceWatchAllProjects,
mineruEnabled: mineru.enabled,
mineruBackend: mineru.backend || "cloud",
mineruLocalEndpoint:
@@ -207,6 +215,8 @@ export function SettingsView() {
const setScheduledImportConfig = useWikiStore((s) => s.setScheduledImportConfig)
const sourceWatchConfig = useWikiStore((s) => s.sourceWatchConfig)
const setSourceWatchConfig = useWikiStore((s) => s.setSourceWatchConfig)
+ const sourceWatchAllProjects = useWikiStore((s) => s.sourceWatchAllProjects)
+ const setSourceWatchAllProjects = useWikiStore((s) => s.setSourceWatchAllProjects)
const mineruConfig = useWikiStore((s) => s.mineruConfig)
const setMineruConfig = useWikiStore((s) => s.setMineruConfig)
const apiConfig = useWikiStore((s) => s.apiConfig)
@@ -238,6 +248,7 @@ export function SettingsView() {
proxyConfig,
scheduledImportConfig,
sourceWatchConfig,
+ sourceWatchAllProjects,
mineruConfig,
apiConfig,
generalConfig,
@@ -259,23 +270,31 @@ export function SettingsView() {
useEffect(() => {
let cancelled = false
- loadSourceWatchConfig(project?.id).then((config) => {
+ Promise.allSettled([
+ loadSourceWatchConfig(project?.id),
+ loadSourceWatchAllProjects(),
+ ]).then(([configResult, allProjectsResult]) => {
if (cancelled) return
+ const config = configResult.status === "fulfilled"
+ ? configResult.value
+ : normalizeSourceWatchConfig()
+ const allProjects = allProjectsResult.status === "fulfilled"
+ ? allProjectsResult.value
+ : false
const normalized = normalizeSourceWatchConfig(config)
setSourceWatchConfig(normalized)
+ setSourceWatchAllProjects(allProjects)
setIngestWorkerLimit(normalized.ingestConcurrency)
- setDraftState((prev) => ({ ...prev, sourceWatchConfig: normalized }))
- }).catch(() => {
- if (cancelled) return
- const fallback = normalizeSourceWatchConfig()
- setSourceWatchConfig(fallback)
- setIngestWorkerLimit(fallback.ingestConcurrency)
- setDraftState((prev) => ({ ...prev, sourceWatchConfig: fallback }))
+ setDraftState((prev) => ({
+ ...prev,
+ sourceWatchConfig: normalized,
+ sourceWatchAllProjects: allProjects,
+ }))
})
return () => {
cancelled = true
}
- }, [project?.id, setSourceWatchConfig])
+ }, [project?.id, setSourceWatchAllProjects, setSourceWatchConfig])
// Resync draft from store if it changes out-of-band (e.g. project switch).
// IMPORTANT: keep the current draft.uiLanguage instead of re-reading
@@ -297,6 +316,7 @@ export function SettingsView() {
proxyConfig,
scheduledImportConfig,
sourceWatchConfig,
+ sourceWatchAllProjects,
mineruConfig,
apiConfig,
generalConfig,
@@ -315,6 +335,7 @@ export function SettingsView() {
proxyConfig,
scheduledImportConfig,
sourceWatchConfig,
+ sourceWatchAllProjects,
mineruConfig,
apiConfig,
generalConfig,
@@ -347,6 +368,7 @@ export function SettingsView() {
saveScheduledImportConfig,
loadScheduledImportConfig,
saveSourceWatchConfig,
+ saveSourceWatchAllProjects,
saveMineruConfig,
loadMineruConfig,
saveApiConfig,
@@ -454,6 +476,7 @@ export function SettingsView() {
setOutputLanguage(draft.outputLanguage as typeof outputLanguage)
setProxyConfig(newProxy)
setSourceWatchConfig(newSourceWatch)
+ setSourceWatchAllProjects(draft.sourceWatchAllProjects)
setIngestWorkerLimit(newSourceWatch.ingestConcurrency)
setScheduledImportConfig(newScheduledImport)
setMaxHistoryMessages(draft.maxHistoryMessages)
@@ -468,8 +491,14 @@ export function SettingsView() {
await saveOutputLanguage(draft.outputLanguage as typeof outputLanguage, project?.id)
await saveProxyConfig(newProxy)
await saveSourceWatchConfig(newSourceWatch, project?.id)
+ await saveSourceWatchAllProjects(draft.sourceWatchAllProjects)
if (project) {
- const { startProjectFileSync, stopProjectFileSync } = await import("@/lib/project-file-sync")
+ const {
+ startAllProjectFileSync,
+ startProjectFileSync,
+ stopAllProjectFileSync,
+ stopProjectFileSync,
+ } = await import("@/lib/project-file-sync")
if (newSourceWatch.enabled) {
await startProjectFileSync(project, newSourceWatch).catch((err) =>
console.error("Failed to start project file sync:", err)
@@ -477,6 +506,11 @@ export function SettingsView() {
} else {
await stopProjectFileSync()
}
+ if (draft.sourceWatchAllProjects) {
+ startAllProjectFileSync(project)
+ } else {
+ stopAllProjectFileSync()
+ }
}
// Apply the proxy env vars LIVE so the next outbound request
// picks them up — no app restart needed. tauri-plugin-http
@@ -557,6 +591,7 @@ export function SettingsView() {
persistedOutputLanguage,
persistedProxy,
persistedSourceWatch,
+ persistedSourceWatchAllProjects,
persistedScheduledImport,
persistedMineru,
persistedApi,
@@ -569,6 +604,7 @@ export function SettingsView() {
loadOutputLanguage(project?.id),
loadProxyConfig(),
loadSourceWatchConfig(project?.id),
+ loadSourceWatchAllProjects(),
project ? loadScheduledImportConfig(project.path) : Promise.resolve(null),
loadMineruConfig(),
loadApiConfig(),
@@ -581,6 +617,9 @@ export function SettingsView() {
setOutputLanguage((resultValue(persistedOutputLanguage, null) ?? outputLanguage) as typeof outputLanguage)
setProxyConfig(resultValue(persistedProxy, null) ?? proxyConfig)
setSourceWatchConfig(resultValue(persistedSourceWatch, sourceWatchConfig))
+ setSourceWatchAllProjects(
+ resultValue(persistedSourceWatchAllProjects, sourceWatchAllProjects),
+ )
setScheduledImportConfig(resultValue(persistedScheduledImport, null) ?? scheduledImportConfig)
setMaxHistoryMessages(maxHistoryMessages)
setMineruConfig(resultValue(persistedMineru, null) ?? mineruConfig)
@@ -601,6 +640,7 @@ export function SettingsView() {
outputLanguage,
proxyConfig,
sourceWatchConfig,
+ sourceWatchAllProjects,
scheduledImportConfig,
mineruConfig,
apiConfig,
@@ -613,6 +653,7 @@ export function SettingsView() {
setProxyConfig,
setScheduledImportConfig,
setSourceWatchConfig,
+ setSourceWatchAllProjects,
setMineruConfig,
setApiConfig,
setGeneralConfig,
diff --git a/src/i18n/en.json b/src/i18n/en.json
index b62b9e4e..e17dcd3b 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -764,6 +764,8 @@
"description": "Monitor raw/sources for external changes and choose which files are allowed into automatic ingest.",
"enable": "Monitor project source folder",
"enableDescription": "Refreshes the Sources view and indexes allowed new or modified files under raw/sources.",
+ "allProjects": "Monitor all recent projects",
+ "allProjectsDescription": "Keep watching source folders for every recent project that has monitoring enabled. Background changes are queued for that project and run when it is opened.",
"autoIngest": "Auto-ingest allowed source files",
"autoIngestDescription": "When disabled, external changes still refresh the file tree but do not create ingest tasks.",
"persistExtractedMarkdown": "Keep parsed Markdown",
diff --git a/src/i18n/it.json b/src/i18n/it.json
index 201c2551..8332a01a 100644
--- a/src/i18n/it.json
+++ b/src/i18n/it.json
@@ -764,6 +764,8 @@
"description": "Controlla raw/sources per intercettare modifiche esterne e scegli quali file possono entrare nell'elaborazione automatica.",
"enable": "Monitora la cartella fonti del progetto",
"enableDescription": "Aggiorna la vista Fonti e indicizza i file consentiti nuovi o modificati sotto raw/sources.",
+ "allProjects": "Monitora tutti i progetti recenti",
+ "allProjectsDescription": "Controlla le cartelle delle fonti di tutti i progetti recenti con il monitoraggio attivo. Le modifiche in background vengono accodate nel progetto corrispondente ed eseguite quando viene aperto.",
"autoIngest": "Elabora automaticamente i file sorgente consentiti",
"autoIngestDescription": "Se disattivo, le modifiche esterne aggiornano comunque l'albero dei file ma non creano attività di elaborazione.",
"persistExtractedMarkdown": "Conserva il Markdown estratto",
diff --git a/src/i18n/ru.json b/src/i18n/ru.json
index 227d5724..eaf78d53 100644
--- a/src/i18n/ru.json
+++ b/src/i18n/ru.json
@@ -764,6 +764,8 @@
"description": "Отслеживайте изменения в raw/sources и выбирайте файлы, которым разрешено автоматически попадать в обработку.",
"enable": "Отслеживать папку источников проекта",
"enableDescription": "Обновляет представление «Источники» и индексирует разрешённые новые или изменённые файлы в raw/sources.",
+ "allProjects": "Отслеживать все недавние проекты",
+ "allProjectsDescription": "Проверять папки источников всех недавних проектов, где включён мониторинг. Фоновые изменения добавляются в очередь соответствующего проекта и выполняются после его открытия.",
"autoIngest": "Автоматически обрабатывать разрешённые файлы источников",
"autoIngestDescription": "Если выключено, внешние изменения по-прежнему обновляют дерево файлов, но не создают задачи обработки.",
"persistExtractedMarkdown": "Сохранять извлечённый Markdown",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 594f548b..89595bc8 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -764,6 +764,8 @@
"description": "监控 raw/sources 的外部变化,并选择哪些文件允许自动进入提取队列。",
"enable": "监控项目资料文件夹",
"enableDescription": "刷新原始资料列表,并为 raw/sources 下允许的新文件或修改文件建立提取任务。",
+ "allProjects": "监控所有最近项目",
+ "allProjectsDescription": "持续检查最近项目列表中所有已启用资料监控的项目。后台发现的变化会写入对应项目的队列,并在打开该项目后执行。",
"autoIngest": "自动提取允许的原始资料文件",
"autoIngestDescription": "关闭后,外部变化仍会刷新文件树,但不会创建提取任务。",
"persistExtractedMarkdown": "保留解析后的 Markdown",
diff --git a/src/lib/ingest-queue.test.ts b/src/lib/ingest-queue.test.ts
index 10742f5b..8fbb7ef8 100644
--- a/src/lib/ingest-queue.test.ts
+++ b/src/lib/ingest-queue.test.ts
@@ -54,6 +54,7 @@ import {
enqueueIngest,
enqueueBatch,
enqueueInactiveProjectBatch,
+ discardInactiveProjectTasksForSources,
retryTask,
retryTasks,
retryAllFailedTasks,
@@ -198,6 +199,50 @@ describe("ingest-queue — enqueue & basic processing", () => {
)
})
+ it("discards persisted tasks for deleted inactive-project sources", async () => {
+ mockReadFile.mockImplementation(async (path: string) => {
+ if (path === `${TEST_PATH_B}/.llm-wiki/ingest-queue.json`) {
+ return JSON.stringify([
+ {
+ id: "remove-me",
+ projectId: TEST_ID_B,
+ sourcePath: "raw/sources/old.pdf",
+ folderContext: "",
+ status: "pending",
+ addedAt: 1,
+ error: null,
+ retryCount: 0,
+ autoStart: true,
+ },
+ {
+ id: "keep-me",
+ projectId: TEST_ID_B,
+ sourcePath: "raw/sources/current.pdf",
+ folderContext: "",
+ status: "pending",
+ addedAt: 2,
+ error: null,
+ retryCount: 0,
+ autoStart: true,
+ },
+ ])
+ }
+ throw new Error("ENOENT")
+ })
+
+ await expect(discardInactiveProjectTasksForSources(
+ TEST_ID_B,
+ TEST_PATH_B,
+ ["raw/sources/old.pdf"],
+ )).resolves.toBe(1)
+
+ const lastWrite = mockWriteFile.mock.calls[mockWriteFile.mock.calls.length - 1]
+ const persisted = JSON.parse(String(lastWrite?.[1])) as Array<{
+ id: string
+ }>
+ expect(persisted.map((task) => task.id)).toEqual(["keep-me"])
+ })
+
it("enqueueIngest adds a pending task and triggers processing", async () => {
mockAutoIngest.mockResolvedValue(["wiki/sources/foo.md"])
diff --git a/src/lib/ingest-queue.ts b/src/lib/ingest-queue.ts
index f166f5ea..e1ee842d 100644
--- a/src/lib/ingest-queue.ts
+++ b/src/lib/ingest-queue.ts
@@ -388,6 +388,53 @@ export async function enqueueInactiveProjectBatch(
return written ? ids : []
}
+/**
+ * Remove persisted ingest work for deleted sources in an inactive project.
+ * If the project becomes active while the background scan is running, defer
+ * to the in-memory queue instead of overwriting its newer disk snapshot.
+ */
+export async function discardInactiveProjectTasksForSources(
+ projectId: string,
+ projectPath: string,
+ sourcePaths: readonly string[],
+): Promise<number> {
+ if (sourcePaths.length === 0) return 0
+ if (currentProjectId === projectId) return discardTasksForSources(sourcePaths)
+
+ const pp = normalizePath(projectPath)
+ const normalizedSources = sourcePaths.map((sourcePath) => {
+ const normalized = normalizePath(sourcePath)
+ return normalized.startsWith(`${pp}/`) ? normalized.slice(pp.length + 1) : normalized
+ })
+ let removed = 0
+ const operation = inactiveQueueWrite.then(async () => {
+ if (currentProjectId === projectId) {
+ removed = await discardTasksForSources(normalizedSources)
+ return
+ }
+ const persisted = await loadQueue(pp, projectId)
+ if (currentProjectId === projectId) {
+ removed = await discardTasksForSources(normalizedSources)
+ return
+ }
+ const retained = persisted.filter((task) => {
+ const matches = task.projectId === projectId && normalizedSources.some((sourcePath) =>
+ normalizeSourcePathForQueue(task.sourcePath) === normalizeSourcePathForQueue(sourcePath)
+ )
+ if (matches) removed += 1
+ return !matches
+ })
+ if (removed > 0) {
+ await writeFile(queueFilePath(pp), JSON.stringify(retained, null, 2))
+ }
+ })
+ inactiveQueueWrite = operation.catch((err) => {
+ console.warn("[Ingest Queue] Failed to discard inactive-project tasks:", err)
+ })
+ await operation
+ return removed
+}
+
/**
* Retry a failed or cancelled task. Only valid for stopped tasks in the
* active project's queue.
diff --git a/src/lib/project-file-sync.test.ts b/src/lib/project-file-sync.test.ts
index ac7de743..49b9196f 100644
--- a/src/lib/project-file-sync.test.ts
+++ b/src/lib/project-file-sync.test.ts
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => {
}),
emit: (event: string, payload: unknown) => listeners[event]?.({ payload }),
stopProjectFileWatcher: vi.fn(async () => undefined),
+ invalidateProjectFileSnapshotPaths: vi.fn(async () => undefined),
rescanProjectFiles: vi.fn(async (projectId: string): Promise<{
queue: {
version: number
@@ -84,6 +85,25 @@ const mocks = vi.hoisted(() => {
deleteFile: vi.fn(async () => undefined),
findRelatedWikiPages: vi.fn(async () => []),
enqueueBatch: vi.fn(async () => []),
+ enqueueInactiveProjectBatch: vi.fn(async () => []),
+ discardInactiveProjectTasksForSources: vi.fn(async () => 0),
+ getRecentProjects: vi.fn(async (): Promise<Array<{
+ id: string
+ name: string
+ path: string
+ }>> => []),
+ loadSourceWatchConfig: vi.fn(async () => ({
+ enabled: true,
+ autoIngest: true,
+ persistExtractedMarkdown: false,
+ parsingConcurrency: 2,
+ ingestConcurrency: 1,
+ includeExtensions: ["md", "pdf"],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ })),
removeFromIngestCache: vi.fn(async () => undefined),
moveIngestCacheEntry: vi.fn(async () => undefined),
removePageEmbedding: vi.fn(async () => undefined),
@@ -99,6 +119,7 @@ vi.mock("@tauri-apps/api/event", () => ({
}))
vi.mock("@/commands/file-sync", () => ({
+ invalidateProjectFileSnapshotPaths: mocks.invalidateProjectFileSnapshotPaths,
rescanProjectFiles: mocks.rescanProjectFiles,
startProjectFileWatcher: mocks.startProjectFileWatcher,
stopProjectFileWatcher: mocks.stopProjectFileWatcher,
@@ -116,6 +137,13 @@ vi.mock("@/commands/fs", () => ({
vi.mock("@/lib/ingest-queue", () => ({
enqueueBatch: mocks.enqueueBatch,
+ enqueueInactiveProjectBatch: mocks.enqueueInactiveProjectBatch,
+ discardInactiveProjectTasksForSources: mocks.discardInactiveProjectTasksForSources,
+}))
+
+vi.mock("@/lib/project-store", () => ({
+ getRecentProjects: mocks.getRecentProjects,
+ loadSourceWatchConfig: mocks.loadSourceWatchConfig,
}))
vi.mock("@/lib/ingest-cache", () => ({
@@ -163,7 +191,26 @@ describe("project file sync", () => {
}))
const { useWikiStore } = await import("@/stores/wiki-store")
const { useFileSyncStore } = await import("@/stores/file-sync-store")
- await import("@/lib/project-file-sync").then((m) => m.stopProjectFileSync())
+ await import("@/lib/project-file-sync").then((m) => {
+ m.stopAllProjectFileSync()
+ return m.stopProjectFileSync()
+ })
+ mocks.getRecentProjects.mockResolvedValue([])
+ mocks.loadSourceWatchConfig.mockResolvedValue({
+ enabled: true,
+ autoIngest: true,
+ persistExtractedMarkdown: false,
+ parsingConcurrency: 2,
+ ingestConcurrency: 1,
+ includeExtensions: ["md", "pdf"],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ })
+ mocks.enqueueInactiveProjectBatch.mockResolvedValue([])
+ mocks.invalidateProjectFileSnapshotPaths.mockResolvedValue(undefined)
+ mocks.discardInactiveProjectTasksForSources.mockResolvedValue(0)
useWikiStore.getState().setProject(null)
useWikiStore.getState().setLlmConfig({
provider: "openai",
@@ -851,4 +898,185 @@ describe("project file sync", () => {
})
expect(mocks.listDirectory.mock.calls.filter(([path]) => path === "/tmp/a/wiki")).toHaveLength(1)
})
+
+ it("monitors enabled inactive projects and queues their source changes separately", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const active = { id: "A", name: "A", path: "/tmp/a" }
+ const inactive = { id: "B", name: "B", path: "/tmp/b" }
+ mocks.getRecentProjects.mockResolvedValue([active, inactive])
+ mocks.rescanProjectFiles.mockImplementation(async (projectId: string) => ({
+ queue: { version: 1, tasks: [] },
+ changedTasks: projectId === "B" ? [{
+ id: "background-created",
+ projectId: "B",
+ path: "raw/sources/chapter 2.pdf",
+ kind: "created" as const,
+ status: "done" as const,
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ }] : [],
+ }))
+
+ startAllProjectFileSync(active)
+
+ await vi.waitFor(() => {
+ expect(mocks.enqueueInactiveProjectBatch).toHaveBeenCalledWith(
+ "B",
+ "/tmp/b",
+ [{ sourcePath: "raw/sources/chapter 2.pdf", folderContext: "" }],
+ )
+ })
+ expect(mocks.rescanProjectFiles).not.toHaveBeenCalledWith(
+ "A",
+ expect.anything(),
+ expect.anything(),
+ expect.anything(),
+ )
+ expect(mocks.rescanProjectFiles).toHaveBeenCalledWith(
+ "B",
+ "/tmp/b",
+ expect.objectContaining({ enabled: true }),
+ true,
+ )
+ stopAllProjectFileSync()
+ })
+
+ it("skips inactive projects whose source monitoring is disabled", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const active = { id: "A", name: "A", path: "/tmp/a" }
+ const inactive = { id: "B", name: "B", path: "/tmp/b" }
+ mocks.getRecentProjects.mockResolvedValue([inactive])
+ mocks.loadSourceWatchConfig.mockResolvedValue({
+ enabled: false,
+ autoIngest: true,
+ persistExtractedMarkdown: false,
+ parsingConcurrency: 2,
+ ingestConcurrency: 1,
+ includeExtensions: ["pdf"],
+ excludeExtensions: [],
+ excludeDirs: [],
+ excludeGlobs: [],
+ maxFileSizeMb: 100,
+ })
+
+ startAllProjectFileSync(active)
+ await vi.waitFor(() => expect(mocks.loadSourceWatchConfig).toHaveBeenCalledWith("B"))
+
+ expect(mocks.rescanProjectFiles).not.toHaveBeenCalled()
+ expect(mocks.enqueueInactiveProjectBatch).not.toHaveBeenCalled()
+ stopAllProjectFileSync()
+ })
+
+ it("removes stale inactive ingest tasks when a source is deleted", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const active = { id: "A", name: "A", path: "/tmp/a" }
+ const inactive = { id: "B", name: "B", path: "/tmp/b" }
+ mocks.getRecentProjects.mockResolvedValue([inactive])
+ mocks.rescanProjectFiles.mockResolvedValue({
+ queue: { version: 1, tasks: [] },
+ changedTasks: [{
+ id: "background-deleted",
+ projectId: "B",
+ path: "raw/sources/old.pdf",
+ kind: "deleted",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ }],
+ })
+
+ startAllProjectFileSync(active)
+ await vi.waitFor(() => {
+ expect(mocks.discardInactiveProjectTasksForSources).toHaveBeenCalledWith(
+ "B",
+ "/tmp/b",
+ ["raw/sources/old.pdf"],
+ )
+ })
+ expect(mocks.enqueueInactiveProjectBatch).not.toHaveBeenCalled()
+ stopAllProjectFileSync()
+ })
+
+ it("invalidates the background snapshot when inactive enqueue persistence fails", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const active = { id: "A", name: "A", path: "/tmp/a" }
+ const inactive = { id: "B", name: "B", path: "/tmp/b" }
+ mocks.getRecentProjects.mockResolvedValue([inactive])
+ mocks.rescanProjectFiles.mockResolvedValue({
+ queue: { version: 1, tasks: [] },
+ changedTasks: [{
+ id: "background-created",
+ projectId: "B",
+ path: "raw/sources/retry.pdf",
+ kind: "created",
+ status: "done",
+ createdAt: 1,
+ updatedAt: 1,
+ retryCount: 0,
+ needsRerun: false,
+ }],
+ })
+ mocks.enqueueInactiveProjectBatch.mockRejectedValueOnce(new Error("disk full"))
+
+ startAllProjectFileSync(active)
+ await vi.waitFor(() => {
+ expect(mocks.invalidateProjectFileSnapshotPaths).toHaveBeenCalledWith(
+ "/tmp/b",
+ ["raw/sources/retry.pdf"],
+ )
+ })
+ stopAllProjectFileSync()
+ })
+
+ it("deduplicates recent projects that point to the same path", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const active = { id: "A", name: "A", path: "/tmp/a" }
+ mocks.getRecentProjects.mockResolvedValue([
+ { id: "B", name: "B", path: "/tmp/shared" },
+ { id: "C", name: "C", path: "/tmp/shared" },
+ ])
+
+ startAllProjectFileSync(active)
+ await vi.waitFor(() => expect(mocks.rescanProjectFiles).toHaveBeenCalledTimes(1))
+ expect(mocks.rescanProjectFiles).toHaveBeenCalledWith(
+ "B",
+ "/tmp/shared",
+ expect.anything(),
+ true,
+ )
+ stopAllProjectFileSync()
+ })
+
+ it("immediately rescans for the latest active project after a switch", async () => {
+ const { startAllProjectFileSync, stopAllProjectFileSync } = await import("@/lib/project-file-sync")
+ const projectA = { id: "A", name: "A", path: "/tmp/a" }
+ const projectB = { id: "B", name: "B", path: "/tmp/b" }
+ let releaseFirstScan: (() => void) | undefined
+ const firstScan = new Promise<void>((resolve) => {
+ releaseFirstScan = resolve
+ })
+ mocks.getRecentProjects.mockResolvedValue([projectA, projectB])
+ mocks.rescanProjectFiles.mockImplementationOnce(async () => {
+ await firstScan
+ return { queue: { version: 1, tasks: [] }, changedTasks: [] }
+ })
+
+ startAllProjectFileSync(projectA)
+ await vi.waitFor(() => expect(mocks.rescanProjectFiles).toHaveBeenCalledTimes(1))
+ startAllProjectFileSync(projectB)
+ releaseFirstScan?.()
+
+ await vi.waitFor(() => expect(mocks.rescanProjectFiles).toHaveBeenCalledTimes(2))
+ expect(mocks.rescanProjectFiles).toHaveBeenLastCalledWith(
+ "A",
+ "/tmp/a",
+ expect.anything(),
+ true,
+ )
+ stopAllProjectFileSync()
+ })
})
diff --git a/src/lib/project-file-sync.ts b/src/lib/project-file-sync.ts
index c04635fd..5933b66c 100644
--- a/src/lib/project-file-sync.ts
+++ b/src/lib/project-file-sync.ts
@@ -1,6 +1,7 @@
import { listen, type UnlistenFn } from "@tauri-apps/api/event"
import { readFile } from "@/commands/fs"
import {
+ invalidateProjectFileSnapshotPaths,
rescanProjectFiles,
startProjectFileWatcher,
stopProjectFileWatcher,
@@ -16,11 +17,17 @@ import {
cleanupDeletedWikiPages,
deleteSourceFiles,
enqueueSourceIngest,
+ folderContextForSourcePath,
isIngestableSourcePath,
migrateSourcePath,
} from "@/lib/source-lifecycle"
+import {
+ discardInactiveProjectTasksForSources,
+ enqueueInactiveProjectBatch,
+} from "@/lib/ingest-queue"
import { isPathAllowedBySourceWatch, normalizeSourceWatchConfig } from "@/lib/source-watch-config"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
+import { getRecentProjects, loadSourceWatchConfig } from "@/lib/project-store"
let unlistenQueue: UnlistenFn | null = null
let unlistenChanged: UnlistenFn | null = null
@@ -30,6 +37,11 @@ let pendingRefreshPaths = new Set<string>()
let pendingChangeTasks = new Map<string, FileChangeTask>()
let activeSourceWatchConfig = normalizeSourceWatchConfig()
let handledChangeTaskKeys = new Set<string>()
+let allProjectsTimer: ReturnType<typeof setInterval> | null = null
+let allProjectsRunId = 0
+let allProjectsScanning = false
+let allProjectsActiveProject: WikiProject | null = null
+const ALL_PROJECTS_SCAN_INTERVAL_MS = 60_000
export async function startProjectFileSync(
project: WikiProject,
@@ -107,6 +119,66 @@ export async function stopProjectFileSync(): Promise<void> {
}
}
+export function startAllProjectFileSync(activeProject: WikiProject): void {
+ stopAllProjectFileSync()
+ allProjectsActiveProject = activeProject
+ const runId = ++allProjectsRunId
+ void scanInactiveProjects(activeProject, runId)
+ allProjectsTimer = setInterval(() => {
+ void scanInactiveProjects(activeProject, runId)
+ }, ALL_PROJECTS_SCAN_INTERVAL_MS)
+}
+
+export function stopAllProjectFileSync(): void {
+ allProjectsRunId += 1
+ allProjectsActiveProject = null
+ if (allProjectsTimer) {
+ clearInterval(allProjectsTimer)
+ allProjectsTimer = null
+ }
+}
+
+async function scanInactiveProjects(activeProject: WikiProject, runId: number): Promise<void> {
+ if (allProjectsScanning || runId !== allProjectsRunId) return
+ allProjectsScanning = true
+ try {
+ const recents = await getRecentProjects()
+ const seen = new Set<string>([activeProject.id])
+ const seenPaths = new Set<string>([normalizePath(activeProject.path)])
+ for (const project of recents) {
+ if (runId !== allProjectsRunId) return
+ const projectPath = normalizePath(project.path)
+ if (seen.has(project.id) || seenPaths.has(projectPath)) continue
+ seen.add(project.id)
+ seenPaths.add(projectPath)
+ try {
+ const config = normalizeSourceWatchConfig(await loadSourceWatchConfig(project.id))
+ if (!config.enabled) continue
+ const result = await rescanProjectFiles(
+ project.id,
+ projectPath,
+ config,
+ true,
+ )
+ if (runId !== allProjectsRunId) return
+ if (result.changedTasks.length > 0) {
+ const paths = [...new Set(result.changedTasks.map((task) => task.path))]
+ await processFileChangeBatch(project, paths, result.changedTasks, config, false)
+ }
+ } catch (err) {
+ console.warn(`[file-sync] failed to scan inactive project ${project.path}:`, err)
+ }
+ }
+ } finally {
+ allProjectsScanning = false
+ const latestProject = allProjectsActiveProject
+ const latestRunId = allProjectsRunId
+ if (runId !== latestRunId && latestProject && allProjectsTimer) {
+ void scanInactiveProjects(latestProject, latestRunId)
+ }
+ }
+}
+
export async function rescanProjectFileSync(
project: WikiProject,
sourceWatchConfig?: SourceWatchConfig,
@@ -171,6 +243,8 @@ async function processFileChangeBatch(
project: WikiProject,
paths: string[],
tasks: FileChangeTask[],
+ sourceWatchConfig: SourceWatchConfig = activeSourceWatchConfig,
+ refreshActiveProject = true,
): Promise<void> {
for (const task of tasks) {
handledChangeTaskKeys.add(changeTaskKey(task))
@@ -178,11 +252,17 @@ async function processFileChangeBatch(
if (handledChangeTaskKeys.size > 4096) {
handledChangeTaskKeys = new Set([...handledChangeTaskKeys].slice(-2048))
}
+ if (!refreshActiveProject) {
+ const deletedSources = tasks
+ .filter((task) => task.kind === "deleted" && isRawSourcePathForCascade(task.path))
+ .map((task) => task.path)
+ await discardInactiveProjectTasksForSources(project.id, project.path, deletedSources)
+ }
const movedTaskIds = await migrateUnchangedSourceMoves(project, tasks)
const remainingTasks = tasks.filter((task) => !movedTaskIds.has(task.id))
await cleanupDeletedFiles(project, remainingTasks)
- await enqueueRawSourceChanges(project, remainingTasks)
- await refreshAfterFileChanges(project, paths)
+ await enqueueRawSourceChanges(project, remainingTasks, sourceWatchConfig, refreshActiveProject)
+ if (refreshActiveProject) await refreshAfterFileChanges(project, paths)
}
async function migrateUnchangedSourceMoves(
@@ -253,8 +333,13 @@ async function refreshAfterFileChanges(project: WikiProject, relativePaths: stri
}
}
-async function enqueueRawSourceChanges(project: WikiProject, tasks: FileChangeTask[]): Promise<void> {
- const config = normalizeSourceWatchConfig(activeSourceWatchConfig)
+async function enqueueRawSourceChanges(
+ project: WikiProject,
+ tasks: FileChangeTask[],
+ sourceWatchConfig: SourceWatchConfig,
+ activeProject: boolean,
+): Promise<void> {
+ const config = normalizeSourceWatchConfig(sourceWatchConfig)
if (!config.enabled || !config.autoIngest) return
const candidates = tasks
@@ -268,9 +353,29 @@ async function enqueueRawSourceChanges(project: WikiProject, tasks: FileChangeTa
if (paths.length === 0) return
try {
- await enqueueSourceIngest(project, paths, useWikiStore.getState().llmConfig)
+ if (activeProject) {
+ await enqueueSourceIngest(project, paths, useWikiStore.getState().llmConfig, {
+ parsingConcurrency: config.parsingConcurrency,
+ })
+ } else {
+ await enqueueInactiveProjectBatch(
+ project.id,
+ project.path,
+ paths.map((sourcePath) => ({
+ sourcePath,
+ folderContext: folderContextForSourcePath(sourcePath),
+ })),
+ )
+ }
} catch (err) {
console.error("[file-sync] failed to enqueue raw source ingest:", err)
+ if (!activeProject) {
+ try {
+ await invalidateProjectFileSnapshotPaths(project.path, paths)
+ } catch (invalidateErr) {
+ console.error("[file-sync] failed to schedule background ingest retry:", invalidateErr)
+ }
+ }
}
}
diff --git a/src/lib/project-store-source-watch.test.ts b/src/lib/project-store-source-watch.test.ts
new file mode 100644
index 00000000..f1c99059
--- /dev/null
+++ b/src/lib/project-store-source-watch.test.ts
@@ -0,0 +1,36 @@
+import { beforeEach, describe, expect, it, vi } from "vitest"
+
+const storage = vi.hoisted(() => new Map<string, unknown>())
+const save = vi.hoisted(() => vi.fn(async () => undefined))
+
+vi.mock("@tauri-apps/plugin-store", () => ({
+ load: vi.fn(async () => ({
+ get: async <T>(key: string) => storage.get(key) as T | undefined,
+ set: async (key: string, value: unknown) => {
+ storage.set(key, value)
+ },
+ save,
+ })),
+}))
+
+describe("source watch all-projects persistence", () => {
+ beforeEach(() => {
+ storage.clear()
+ save.mockClear()
+ })
+
+ it("defaults off and round-trips the global option", async () => {
+ const {
+ loadSourceWatchAllProjects,
+ saveSourceWatchAllProjects,
+ } = await import("./project-store")
+
+ expect(await loadSourceWatchAllProjects()).toBe(false)
+ await saveSourceWatchAllProjects(true)
+ expect(await loadSourceWatchAllProjects()).toBe(true)
+ expect(save).toHaveBeenCalledTimes(1)
+
+ await saveSourceWatchAllProjects(false)
+ expect(await loadSourceWatchAllProjects()).toBe(false)
+ })
+})
diff --git a/src/lib/project-store.ts b/src/lib/project-store.ts
index c86825c4..d6603825 100644
--- a/src/lib/project-store.ts
+++ b/src/lib/project-store.ts
@@ -408,6 +408,7 @@ const OUTPUT_LANGUAGE_KEY = "outputLanguage"
const PROJECT_OUTPUT_LANGUAGE_KEY = "projectOutputLanguages"
const PROJECT_FILE_SYNC_KEY = "projectFileSyncEnabled"
const SOURCE_WATCH_CONFIG_KEY = "sourceWatchConfig"
+const SOURCE_WATCH_ALL_PROJECTS_KEY = "sourceWatchAllProjects"
export async function saveOutputLanguage(lang: OutputLanguage, projectId?: string): Promise<void> {
const store = await getStore()
@@ -472,6 +473,17 @@ export async function loadSourceWatchConfig(projectId?: string): Promise<SourceW
return normalizeSourceWatchConfig({ enabled: legacyEnabled })
}
+export async function saveSourceWatchAllProjects(enabled: boolean): Promise<void> {
+ const store = await getStore()
+ await store.set(SOURCE_WATCH_ALL_PROJECTS_KEY, enabled)
+ await store.save()
+}
+
+export async function loadSourceWatchAllProjects(): Promise<boolean> {
+ const store = await getStore()
+ return (await store.get<boolean>(SOURCE_WATCH_ALL_PROJECTS_KEY)) === true
+}
+
// ── Update-check persistence ──────────────────────────────────────────────
// Small slice of state the UI-layer update store hydrates from on boot.
// Only fields that should persist across launches: the user's "enable
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index cbf64f3e..0cfb56d9 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -441,6 +441,7 @@ interface WikiState {
proxyConfig: ProxyConfig
scheduledImportConfig: ScheduledImportConfig
sourceWatchConfig: SourceWatchConfig
+ sourceWatchAllProjects: boolean
mineruConfig: MineruConfig
apiConfig: ApiConfig
generalConfig: GeneralConfig
@@ -472,6 +473,7 @@ interface WikiState {
setProxyConfig: (config: ProxyConfig) => void
setScheduledImportConfig: (config: ScheduledImportConfig) => void
setSourceWatchConfig: (config: SourceWatchConfig) => void
+ setSourceWatchAllProjects: (enabled: boolean) => void
setMineruConfig: (config: MineruConfig) => void
setApiConfig: (config: ApiConfig) => void
setGeneralConfig: (config: GeneralConfig) => void
@@ -632,6 +634,7 @@ export const useWikiStore = create<WikiState>((set) => ({
},
sourceWatchConfig: DEFAULT_SOURCE_WATCH_CONFIG,
+ sourceWatchAllProjects: false,
mineruConfig: {
enabled: false,
backend: "cloud",
@@ -682,6 +685,7 @@ export const useWikiStore = create<WikiState>((set) => ({
setProxyConfig: (proxyConfig) => set({ proxyConfig }),
setScheduledImportConfig: (scheduledImportConfig) => set({ scheduledImportConfig }),
setSourceWatchConfig: (sourceWatchConfig) => set({ sourceWatchConfig }),
+ setSourceWatchAllProjects: (sourceWatchAllProjects) => set({ sourceWatchAllProjects }),
setMineruConfig: (mineruConfig) => set({ mineruConfig }),
setApiConfig: (apiConfig) => set({ apiConfig }),
setGeneralConfig: (generalConfig) => set({ generalConfig }),