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

fix: harden ingest and scheduled import flows

nash_su0677983b1914
diff --git a/src-tauri/src/commands/codex_cli.rs b/src-tauri/src/commands/codex_cli.rs
index ba5d5cd0..212afeb1 100644
--- a/src-tauri/src/commands/codex_cli.rs
+++ b/src-tauri/src/commands/codex_cli.rs
@@ -34,7 +34,9 @@ pub struct DetectResult {
error: Option<String>,
}
-const CODEX_SPAWN_TIMEOUT: Duration = Duration::from_secs(10 * 60);
+const DEFAULT_CODEX_SPAWN_TIMEOUT_MINUTES: u64 = 10;
+const MIN_CODEX_SPAWN_TIMEOUT_MINUTES: u64 = 1;
+const MAX_CODEX_SPAWN_TIMEOUT_MINUTES: u64 = 240;
const STDERR_LIMIT_BYTES: usize = 1024 * 1024;
const STDOUT_LIMIT_BYTES: usize = 1024 * 1024;
@@ -138,6 +140,7 @@ pub async fn codex_cli_spawn(
model: String,
prompt: String,
isolate_local_config: bool,
+ timeout_minutes: Option<u64>,
) -> Result<(), String> {
if prompt.trim().is_empty() {
return Err("No prompt to send to codex CLI".to_string());
@@ -192,13 +195,15 @@ pub async fn codex_cli_spawn(
let timed_out = Arc::new(AtomicBool::new(false));
let timeout_flag = Arc::clone(&timed_out);
let timeout_stream_id = stream_id.clone();
+ let timeout_minutes = codex_spawn_timeout_minutes(timeout_minutes);
+ let timeout_duration = Duration::from_secs(timeout_minutes * 60);
let app_for_task = app.clone();
let stream_id_task = stream_id.clone();
let topic = format!("codex-cli:{stream_id}");
let done_topic = format!("codex-cli:{stream_id}:done");
tokio::spawn(async move {
- tokio::time::sleep(CODEX_SPAWN_TIMEOUT).await;
+ tokio::time::sleep(timeout_duration).await;
if let Some(mut child) = timeout_children.lock().await.remove(&timeout_stream_id) {
timeout_flag.store(true, Ordering::SeqCst);
let _ = child.start_kill();
@@ -251,7 +256,7 @@ pub async fn codex_cli_spawn(
if !stderr_text.is_empty() {
stderr_text.push('\n');
}
- stderr_text.push_str("Codex CLI timed out after 10 minutes.");
+ stderr_text.push_str(&format!("Codex CLI timed out after {timeout_minutes} minutes."));
} else if stderr_text.len() >= STDERR_LIMIT_BYTES {
stderr_text.push_str("\n[stderr truncated]");
}
@@ -278,6 +283,12 @@ pub async fn codex_cli_spawn(
Ok(())
}
+fn codex_spawn_timeout_minutes(value: Option<u64>) -> u64 {
+ value
+ .unwrap_or(DEFAULT_CODEX_SPAWN_TIMEOUT_MINUTES)
+ .clamp(MIN_CODEX_SPAWN_TIMEOUT_MINUTES, MAX_CODEX_SPAWN_TIMEOUT_MINUTES)
+}
+
fn build_codex_cli_args(model: &str, isolate_local_config: bool) -> Vec<String> {
let mut args = vec!["-a".to_string(), "never".to_string(), "exec".to_string()];
@@ -342,6 +353,20 @@ mod tests {
assert!(std::str::from_utf8(out.as_bytes()).is_ok());
}
+ #[test]
+ fn codex_spawn_timeout_minutes_defaults_and_clamps() {
+ assert_eq!(
+ codex_spawn_timeout_minutes(None),
+ DEFAULT_CODEX_SPAWN_TIMEOUT_MINUTES
+ );
+ assert_eq!(codex_spawn_timeout_minutes(Some(0)), MIN_CODEX_SPAWN_TIMEOUT_MINUTES);
+ assert_eq!(codex_spawn_timeout_minutes(Some(42)), 42);
+ assert_eq!(
+ codex_spawn_timeout_minutes(Some(999)),
+ MAX_CODEX_SPAWN_TIMEOUT_MINUTES
+ );
+ }
+
#[test]
fn codex_args_do_not_isolate_local_config_by_default() {
let args = build_codex_cli_args("gpt-5", false);
diff --git a/src/components/settings/preset-resolver.test.ts b/src/components/settings/preset-resolver.test.ts
index 71a70eb2..da551da6 100644
--- a/src/components/settings/preset-resolver.test.ts
+++ b/src/components/settings/preset-resolver.test.ts
@@ -120,6 +120,32 @@ describe("resolveConfig", () => {
expect(resolved.localCliIsolation).toBe(true)
})
+ it("carries Codex CLI timeout only for the Codex CLI preset", () => {
+ const codexPreset: LlmPreset = {
+ id: "codex-cli",
+ label: "Codex CLI",
+ provider: "codex-cli",
+ defaultModel: "gpt-5",
+ }
+ const claudePreset: LlmPreset = {
+ id: "claude-code-cli",
+ label: "Claude Code CLI",
+ provider: "claude-code",
+ defaultModel: "sonnet",
+ }
+
+ expect(resolveConfig(
+ codexPreset,
+ { codexCliTimeoutMinutes: 9999 },
+ fallbackConfig(),
+ ).codexCliTimeoutMinutes).toBe(240)
+ expect(resolveConfig(
+ claudePreset,
+ { codexCliTimeoutMinutes: 45 },
+ fallbackConfig(),
+ ).codexCliTimeoutMinutes).toBeUndefined()
+ })
+
it("does not apply local CLI isolation to hosted providers", () => {
const preset: LlmPreset = {
id: "openai",
diff --git a/src/components/settings/preset-resolver.ts b/src/components/settings/preset-resolver.ts
index 644c335d..ac894da7 100644
--- a/src/components/settings/preset-resolver.ts
+++ b/src/components/settings/preset-resolver.ts
@@ -20,6 +20,10 @@ export function resolveConfig(
ov.maxContextSize ?? preset.suggestedContextSize ?? fallback.maxContextSize
const reasoning = ov.reasoning ?? { mode: "auto" as const }
const localCliIsolation = ov.localCliIsolation === true
+ const codexCliTimeoutMinutes =
+ typeof ov.codexCliTimeoutMinutes === "number" && Number.isFinite(ov.codexCliTimeoutMinutes)
+ ? Math.max(1, Math.min(240, Math.floor(ov.codexCliTimeoutMinutes)))
+ : undefined
if (preset.provider === "custom") {
return {
@@ -75,6 +79,7 @@ export function resolveConfig(
maxContextSize,
reasoning,
localCliIsolation,
+ codexCliTimeoutMinutes: preset.provider === "codex-cli" ? codexCliTimeoutMinutes : undefined,
}
}
diff --git a/src/components/settings/sections/llm-provider-section.tsx b/src/components/settings/sections/llm-provider-section.tsx
index 87527345..30993801 100644
--- a/src/components/settings/sections/llm-provider-section.tsx
+++ b/src/components/settings/sections/llm-provider-section.tsx
@@ -129,6 +129,7 @@ function PresetRow({
const context = ov.maxContextSize ?? preset.suggestedContextSize ?? 131072
const reasoning = ov.reasoning ?? { mode: "auto" as const }
const localCliIsolation = ov.localCliIsolation === true
+ const codexCliTimeoutMinutes = Math.max(1, Math.min(240, ov.codexCliTimeoutMinutes ?? 10))
const isLocalCliProvider = preset.provider === "claude-code" || preset.provider === "codex-cli"
const [testState, setTestState] = useState<ProviderTestState>({ kind: "idle" })
const hasConfig = !!apiKey || !!ov.baseUrl || !!ov.model || !!ov.azureApiVersion || !!ov.azureModelFamily
@@ -353,6 +354,35 @@ function PresetRow({
</div>
)}
+ {preset.provider === "codex-cli" && (
+ <div className="space-y-2 rounded-md border p-3">
+ <Label>{t("settings.sections.llm.codexCliTimeout")}</Label>
+ <div className="flex items-center gap-2">
+ <Input
+ type="number"
+ min={1}
+ max={240}
+ className="w-28"
+ value={codexCliTimeoutMinutes}
+ onChange={(e) => {
+ const n = Number(e.target.value)
+ onChange({
+ codexCliTimeoutMinutes: Number.isFinite(n)
+ ? Math.max(1, Math.min(240, Math.floor(n)))
+ : undefined,
+ })
+ }}
+ />
+ <span className="text-xs text-muted-foreground">
+ {t("settings.sections.llm.codexCliTimeoutUnit")}
+ </span>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ {t("settings.sections.llm.codexCliTimeoutHint")}
+ </p>
+ </div>
+ )}
+
{needsApiKey && (
<div className="space-y-2">
<Label>{t("settings.apiKey")}</Label>
diff --git a/src/components/settings/sections/scheduled-import-section.tsx b/src/components/settings/sections/scheduled-import-section.tsx
index 506d9d8d..3e194a2e 100644
--- a/src/components/settings/sections/scheduled-import-section.tsx
+++ b/src/components/settings/sections/scheduled-import-section.tsx
@@ -7,7 +7,11 @@ 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 { scanAndImport } from "@/lib/scheduled-import"
+import {
+ isProjectManagedScheduledImportPath,
+ resolveImportPath,
+ scanAndImport,
+} from "@/lib/scheduled-import"
interface Props {
draft: SettingsDraft
@@ -49,6 +53,14 @@ export function ScheduledImportSection({ draft, setDraft }: Props) {
const lastScanDate = scheduledImportConfig.lastScan
? new Date(scheduledImportConfig.lastScan).toLocaleString()
: t("settings.sections.scheduledImport.never", { defaultValue: "Never" })
+ const managedPathSelected = Boolean(
+ project &&
+ draft.scheduledImportPath &&
+ isProjectManagedScheduledImportPath(
+ project.path,
+ resolveImportPath(project.path, draft.scheduledImportPath),
+ ),
+ )
return (
<div className="space-y-6">
@@ -118,9 +130,17 @@ export function ScheduledImportSection({ draft, setDraft }: Props) {
<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.",
+ "Choose an external folder outside the current LLM Wiki project. Project folders are already handled by source folder monitoring.",
})}
</p>
+ {managedPathSelected && (
+ <p className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-xs text-amber-900 dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-200">
+ {t("settings.sections.scheduledImport.managedPathWarning", {
+ defaultValue:
+ "This path is inside the current LLM Wiki project and is already managed by source folder monitoring. Pick an external folder to avoid duplicate scans.",
+ })}
+ </p>
+ )}
</div>
<div className="space-y-2">
@@ -156,7 +176,7 @@ export function ScheduledImportSection({ draft, setDraft }: Props) {
variant="outline"
size="sm"
onClick={handleManualScan}
- disabled={!draft.scheduledImportEnabled || !draft.scheduledImportPath || isScanning}
+ disabled={!draft.scheduledImportEnabled || !draft.scheduledImportPath || managedPathSelected || isScanning}
>
{isScanning ? (
<RefreshCw className="mr-2 h-4 w-4 animate-spin" />
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 953fd669..b0896260 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -276,6 +276,9 @@
"localCliIsolationHint": "Optional for Claude Code and Codex CLI. When enabled, LLM Wiki asks the CLI to ignore user-level rules/config/MCP/tools where supported. This is configuration isolation, not a process sandbox: the CLI still uses your local login credentials and network access. Leave off if you intentionally rely on your local CLI setup.",
"localCliIsolationOn": "Isolation on: user CLI rules, MCP/tools, and persisted sessions are disabled where the CLI supports it. Local credentials and network access are still controlled by the CLI itself.",
"localCliIsolationOff": "Isolation off: this provider can use your normal local CLI configuration.",
+ "codexCliTimeout": "Codex CLI timeout",
+ "codexCliTimeoutUnit": "minutes",
+ "codexCliTimeoutHint": "Overall timeout for one Codex CLI request. Raise this for long PDF ingest or slower local/network sessions.",
"testConnection": "Test connection",
"testFunction": "Test function",
"testingConnection": "Testing connection…",
@@ -452,7 +455,8 @@
"description": "Automatically monitor a directory and import new or modified files at regular intervals.",
"enable": "Enable scheduled import",
"directory": "Monitor Directory",
- "directoryHelp": "Relative path from project root (e.g., 'raw', 'docs/input'). Files in this directory will be automatically imported. Defaults to 'raw'.",
+ "directoryHelp": "Choose an external folder outside the current LLM Wiki project. Project folders such as raw, raw/sources, wiki, and .llm-wiki are skipped because source folder monitoring already handles them.",
+ "managedPathWarning": "This path is inside the current LLM Wiki project and is already managed by source folder monitoring. Pick an external folder to avoid duplicate scans.",
"privacyNotice": "Files from the selected directory may be copied into this project and sent to your configured LLM during ingest. Removed files are not automatically deleted from the project.",
"browse": "Browse",
"selectDirectory": "Select Directory to Monitor",
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 273a211e..3a6f18d0 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -276,6 +276,9 @@
"localCliIsolationHint": "仅用于 Claude Code 和 Codex CLI。开启后,LLM Wiki 会让 CLI 尽量忽略用户级 rules / config / MCP / tools。这是配置隔离,不是进程沙箱:CLI 仍会使用你的本机登录凭据和网络能力。若你有意依赖本机 CLI 配置,请保持关闭。",
"localCliIsolationOn": "隔离已开启:在 CLI 支持的范围内禁用用户规则、MCP/tools 和持久会话。本机凭据和网络访问仍由 CLI 自身控制。",
"localCliIsolationOff": "隔离已关闭:该 Provider 可以使用你平时的本地 CLI 配置。",
+ "codexCliTimeout": "Codex CLI 超时时间",
+ "codexCliTimeoutUnit": "分钟",
+ "codexCliTimeoutHint": "单次 Codex CLI 请求的总超时时间。长 PDF 摄取或较慢的本地 / 网络会话可适当调大。",
"testConnection": "测试连接",
"testFunction": "测试功能",
"testingConnection": "正在测试连接…",
@@ -452,7 +455,8 @@
"description": "自动监控指定目录,按固定间隔导入新增或修改的文件。",
"enable": "启用定时导入",
"directory": "监控目录",
- "directoryHelp": "相对于项目根目录的路径(如 'raw'、'docs/input')。该目录中的文件将被自动导入。默认为 'raw'。",
+ "directoryHelp": "请选择当前 LLM Wiki 项目之外的外部文件夹。raw、raw/sources、wiki、.llm-wiki 等项目内部目录会被跳过,因为资料文件夹监控已经负责这些内容。",
+ "managedPathWarning": "该路径位于当前 LLM Wiki 项目内部,已经由资料文件夹监控负责。请选择外部文件夹,避免重复扫描。",
"privacyNotice": "所选目录中的文件可能会被复制到当前项目,并在提取时发送给你配置的 LLM。源目录中删除文件不会自动删除项目内已导入内容。",
"browse": "浏览",
"selectDirectory": "选择监控目录",
diff --git a/src/lib/codex-cli-transport.test.ts b/src/lib/codex-cli-transport.test.ts
index e04fffc5..86889453 100644
--- a/src/lib/codex-cli-transport.test.ts
+++ b/src/lib/codex-cli-transport.test.ts
@@ -244,6 +244,55 @@ describe("streamCodexCli", () => {
expect(callbacks.onError).not.toHaveBeenCalled()
})
+ it("passes the configured Codex CLI timeout to the Rust transport", async () => {
+ const callbacks = {
+ onToken: vi.fn(),
+ onDone: vi.fn(),
+ onError: vi.fn(),
+ }
+
+ const stream = streamCodexCli(
+ {
+ provider: "codex-cli",
+ apiKey: "",
+ model: "gpt-5.1-codex-mini",
+ ollamaUrl: "",
+ customEndpoint: "",
+ maxContextSize: 128000,
+ codexCliTimeoutMinutes: 45,
+ },
+ [{ role: "user", content: "Analyze this source." }],
+ callbacks,
+ )
+
+ await vi.waitFor(() => {
+ expect(tauriMocks.invoke).toHaveBeenCalledWith(
+ "codex_cli_spawn",
+ expect.objectContaining({ timeoutMinutes: 45 }),
+ )
+ })
+
+ const payload = tauriMocks.invoke.mock.calls[0]?.[1] as { streamId: string }
+ tauriMocks.emit(
+ `codex-cli:${payload.streamId}`,
+ JSON.stringify({
+ type: "item.completed",
+ item: { type: "agent_message", text: "timeout-aware analysis" },
+ }),
+ )
+ tauriMocks.emit(`codex-cli:${payload.streamId}:done`, {
+ code: 0,
+ stderr: "",
+ stdout: "",
+ })
+
+ await stream
+
+ expect(callbacks.onToken).toHaveBeenCalledWith("timeout-aware analysis")
+ expect(callbacks.onDone).toHaveBeenCalledTimes(1)
+ expect(callbacks.onError).not.toHaveBeenCalled()
+ })
+
it("does not replay done stdout when a live agent message was already emitted", async () => {
const callbacks = {
onToken: vi.fn(),
diff --git a/src/lib/codex-cli-transport.ts b/src/lib/codex-cli-transport.ts
index cab88be5..36d6cb1d 100644
--- a/src/lib/codex-cli-transport.ts
+++ b/src/lib/codex-cli-transport.ts
@@ -62,6 +62,7 @@ type SpawnPayload = Record<string, unknown> & {
model: string
prompt: string
isolateLocalConfig: boolean
+ timeoutMinutes?: number
}
export async function streamCodexCli(
@@ -198,6 +199,7 @@ export async function streamCodexCli(
model: config.model,
prompt: buildPrompt(messages),
isolateLocalConfig: config.localCliIsolation === true,
+ timeoutMinutes: config.codexCliTimeoutMinutes,
}
await invoke("codex_cli_spawn", payload)
if (aborted || signal?.aborted) {
diff --git a/src/lib/ingest-parse.test.ts b/src/lib/ingest-parse.test.ts
index ae0c8d69..d59eb006 100644
--- a/src/lib/ingest-parse.test.ts
+++ b/src/lib/ingest-parse.test.ts
@@ -24,6 +24,9 @@ import {
stampGeneratedFrontmatterDates,
stampGeneratedLogDate,
buildGenerationPrompt,
+ sourceSummaryMediaRefsForExternalMarkdown,
+ aggregatePathsNeedingRepair,
+ filterAggregateRepairOutput,
} from "./ingest"
// ── Happy paths ─────────────────────────────────────────────────────
@@ -87,6 +90,61 @@ describe("parseFileBlocks — canonical shapes", () => {
})
})
+describe("source summary media refs", () => {
+ it("rewrites generated media refs so wiki/sources pages work in external Markdown apps", () => {
+ const input = [
+ "![Chart](media/report/001-chart.png)",
+ "![Table](./media/report/table%201.png)",
+ '<img src="media/report/raw.png" />',
+ "![Already relative](../media/report/keep.png)",
+ ].join("\n")
+
+ expect(sourceSummaryMediaRefsForExternalMarkdown(input)).toBe([
+ "![Chart](../media/report/001-chart.png)",
+ "![Table](../media/report/table%201.png)",
+ '<img src="../media/report/raw.png" />',
+ "![Already relative](../media/report/keep.png)",
+ ].join("\n"))
+ })
+})
+
+describe("aggregate repair targeting", () => {
+ it("requests missing aggregate pages and aggregate pages dropped by truncation warnings", () => {
+ expect(aggregatePathsNeedingRepair(
+ ["wiki/index.md", "wiki/log.md"],
+ ['FILE block "wiki/overview.md" was not closed before end of stream — likely truncation.'],
+ )).toEqual(["wiki/overview.md"])
+
+ expect(aggregatePathsNeedingRepair(
+ ["wiki/index.md", "wiki/overview.md", "wiki/log.md"],
+ [],
+ )).toEqual([])
+ })
+
+ it("filters aggregate repair output to the requested aggregate paths only", () => {
+ const raw = [
+ "---FILE: wiki/overview.md---",
+ "# Overview",
+ "---END FILE---",
+ "",
+ "---FILE: wiki/sources/should-not-touch.md---",
+ "# Stray Source Summary",
+ "---END FILE---",
+ "",
+ "---FILE: wiki/entities/stray.md---",
+ "# Stray Entity",
+ "---END FILE---",
+ ].join("\n")
+
+ const filtered = filterAggregateRepairOutput(raw, ["wiki/overview.md"])
+
+ expect(filtered.text).toContain("---FILE: wiki/overview.md---")
+ expect(filtered.text).not.toContain("should-not-touch")
+ expect(filtered.text).not.toContain("wiki/entities/stray.md")
+ expect(filtered.warnings.join("\n")).toContain("Dropped 2 non-aggregate")
+ })
+})
+
// ── H1: CRLF normalization ─────────────────────────────────────────
describe("parseFileBlocks — H1: CRLF line endings", () => {
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 0b277c7c..4d704bc9 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -50,6 +50,7 @@ const INGEST_GENERATION_TOKENS_256K = 24_576
const INGEST_GENERATION_TOKENS_512K = 32_768
const REVIEW_STAGE_MIN_SIGNAL_CHARS = 10_000
const REVIEW_STAGE_MIN_FILE_BLOCKS = 4
+const AGGREGATE_WIKI_PATHS = ["wiki/index.md", "wiki/overview.md", "wiki/log.md"] as const
function appendSavedImageRefsForCaption(content: string, images: SavedImage[]): string {
if (images.length === 0) return content
@@ -139,6 +140,17 @@ function stripWikiMediaAbsPaths(projectPath: string, content: string): string {
return content.split(`${projectPath}/wiki/media/`).join("media/")
}
+export function sourceSummaryMediaRefsForExternalMarkdown(content: string): string {
+ return content
+ .replace(/(\]\()\.?\/?media\//g, "$1../media/")
+ .replace(/(\bsrc=["'])\.?\/?media\//gi, "$1../media/")
+}
+
+function toSourceSummaryImageRef(relPath: string): string {
+ const normalized = relPath.replace(/^\.\//, "")
+ return normalized.startsWith("media/") ? `../${normalized}` : relPath
+}
+
function encodeMarkdownPathSegment(segment: string): string {
return encodeURIComponent(segment).replace(/[!'()*]/g, (char) =>
`%${char.charCodeAt(0).toString(16).toUpperCase()}`,
@@ -923,7 +935,7 @@ async function autoIngestImpl(
// ── Step 3: Write files ───────────────────────────────────────
activity.updateItem(activityId, { detail: "Writing files..." })
await migrateLegacySourceSummaryIfSafe(pp, sourceIdentity, sourceSummaryPath)
- const { writtenPaths, warnings: writeWarnings, hardFailures } = await writeFileBlocks(
+ const writeResult = await writeFileBlocks(
pp,
generation,
llmConfig,
@@ -931,6 +943,90 @@ async function autoIngestImpl(
sourceSummaryPath,
signal,
)
+ const writtenPaths = writeResult.writtenPaths
+ const writeWarnings = writeResult.warnings
+ const hardFailures = writeResult.hardFailures
+
+ const aggregateRepairPaths = aggregatePathsNeedingRepair(writtenPaths, writeWarnings)
+ const repairableAggregatePaths = aggregateRepairPaths.filter((path) =>
+ isAggregateRepairSafe(path, index, overview, llmConfig.maxContextSize),
+ )
+ const skippedAggregatePaths = aggregateRepairPaths.filter((path) =>
+ !repairableAggregatePaths.includes(path),
+ )
+ if (skippedAggregatePaths.length > 0) {
+ writeWarnings.push(
+ `Skipped aggregate repair for ${skippedAggregatePaths.join(", ")} because the existing file is too large to safely regenerate without truncating existing entries.`,
+ )
+ }
+ if (repairableAggregatePaths.length > 0 && !signal?.aborted) {
+ activity.updateItem(activityId, {
+ detail: `Repairing aggregate wiki files: ${repairableAggregatePaths.join(", ")}`,
+ })
+ let aggregateRepairOutput = ""
+ try {
+ await streamChat(
+ llmConfig,
+ [
+ {
+ role: "system",
+ content: buildAggregateRepairPrompt(
+ repairableAggregatePaths,
+ purpose,
+ index,
+ overview,
+ sourceIdentity,
+ analysis,
+ sourceContext,
+ generation,
+ llmConfig.maxContextSize,
+ ),
+ },
+ {
+ role: "user",
+ content: "Emit the requested aggregate FILE blocks now. Start immediately with `---FILE:`.",
+ },
+ ],
+ {
+ onToken: (token) => { aggregateRepairOutput += token },
+ onDone: () => {},
+ onError: (err) => {
+ writeWarnings.push(`Aggregate repair failed: ${err.message}`)
+ },
+ },
+ signal,
+ {
+ temperature: 0.1,
+ reasoning: { mode: "off" },
+ max_tokens: computeIngestReviewMaxTokens(llmConfig.maxContextSize),
+ },
+ )
+ if (signal?.aborted) throw new Error("Ingest cancelled")
+ if (aggregateRepairOutput.trim()) {
+ const filteredRepair = filterAggregateRepairOutput(
+ aggregateRepairOutput,
+ repairableAggregatePaths,
+ )
+ writeWarnings.push(...filteredRepair.warnings)
+ const repairResult = await writeFileBlocks(
+ pp,
+ filteredRepair.text,
+ llmConfig,
+ sourceIdentity,
+ sourceSummaryPath,
+ signal,
+ )
+ writtenPaths.push(...repairResult.writtenPaths)
+ writeWarnings.push(...repairResult.warnings)
+ hardFailures.push(...repairResult.hardFailures)
+ }
+ } catch (err) {
+ if (signal?.aborted) throw err
+ writeWarnings.push(
+ `Aggregate repair failed: ${err instanceof Error ? err.message : String(err)}`,
+ )
+ }
+ }
// Surface parser / writer warnings to the activity panel so users
// don't have to open devtools to find out a block was dropped.
@@ -1109,6 +1205,52 @@ function isListingPath(relativePath: string): boolean {
)
}
+export function aggregatePathsNeedingRepair(writtenPaths: string[], warnings: string[]): string[] {
+ const written = new Set(writtenPaths.map((path) => normalizePath(path)))
+ const warningText = warnings.join("\n")
+ return AGGREGATE_WIKI_PATHS.filter((path) =>
+ !written.has(path) || warningText.includes(`"${path}"`),
+ )
+}
+
+export function filterAggregateRepairOutput(text: string, allowedPaths: string[]): {
+ text: string
+ warnings: string[]
+} {
+ const allowed = new Set(allowedPaths.map((path) => normalizePath(path)))
+ const { blocks, warnings } = parseFileBlocks(text)
+ const kept = blocks.filter((block) => allowed.has(normalizePath(block.path)))
+ const dropped = blocks.filter((block) => !allowed.has(normalizePath(block.path)))
+ if (dropped.length > 0) {
+ warnings.push(
+ `Dropped ${dropped.length} non-aggregate block(s) from aggregate repair output: ${dropped.map((block) => block.path).join(", ")}`,
+ )
+ }
+ return {
+ text: kept
+ .map((block) => `---FILE: ${block.path}---\n${block.content.trimEnd()}\n---END FILE---`)
+ .join("\n\n"),
+ warnings,
+ }
+}
+
+function aggregateRepairSectionCap(maxContextSize: number | undefined): number {
+ const { maxCtx } = computeContextBudget(maxContextSize)
+ return Math.max(4_000, Math.floor(maxCtx * 0.12))
+}
+
+function isAggregateRepairSafe(
+ path: string,
+ index: string,
+ overview: string,
+ maxContextSize: number | undefined,
+): boolean {
+ const cap = aggregateRepairSectionCap(maxContextSize)
+ if (path === "wiki/index.md") return index.length <= cap
+ if (path === "wiki/overview.md") return overview.length <= cap
+ return true
+}
+
function canonicalizeSourcesField(content: string, sourceIdentity: string): string {
if (!/^---\n/.test(content)) return content
@@ -1373,6 +1515,9 @@ async function writeFileBlocks(
if (!isLogPath(relativePath) && !isListingPath(relativePath)) {
content = canonicalizeSourcesField(content, sourceFileName)
}
+ if (sourceSummaryPath && relativePath === sourceSummaryPath) {
+ content = sourceSummaryMediaRefsForExternalMarkdown(content)
+ }
if (
projectSchemaRouting &&
@@ -1831,6 +1976,62 @@ function buildReviewSuggestionPrompt(
].filter(Boolean).join("\n")
}
+function buildAggregateRepairPrompt(
+ paths: string[],
+ purpose: string,
+ index: string,
+ overview: string,
+ sourceIdentity: string,
+ analysis: string,
+ sourceContext: string,
+ generation: string,
+ maxContextSize: number | undefined,
+): string {
+ const sectionCap = aggregateRepairSectionCap(maxContextSize)
+ const today = currentWikiDate()
+ return [
+ "You are repairing aggregate wiki files after an ingest generation.",
+ "Do not output chain-of-thought, hidden reasoning, or explanatory preamble.",
+ "",
+ languageRule(sourceContext),
+ "",
+ "Generate ONLY the requested aggregate FILE blocks listed below.",
+ "Do not generate entity, concept, source summary, query, comparison, or synthesis pages.",
+ "",
+ "Requested paths:",
+ ...paths.map((path) => `- ${path}`),
+ "",
+ "Rules:",
+ `- Use today's date ${today} for log entries and frontmatter dates.`,
+ "- For wiki/index.md: output the complete updated index, preserving existing entries and adding the new source-derived entries.",
+ "- For wiki/overview.md: output the complete updated overview, reflecting the full wiki plus this new source.",
+ "- For wiki/log.md: output only the new log entry to append, format `## [YYYY-MM-DD] ingest | Title`.",
+ "- Output only FILE blocks. Nothing else.",
+ "",
+ "FILE block template:",
+ "```",
+ "---FILE: wiki/path.md---",
+ "(complete file content, or just the new log entry for wiki/log.md)",
+ "---END FILE---",
+ "```",
+ "",
+ purpose ? `## Wiki Purpose\n${trimLongText(purpose, Math.floor(sectionCap * 0.5))}` : "",
+ index ? `## Current Wiki Index\n${trimLongText(index, sectionCap)}` : "",
+ overview ? `## Current Overview\n${trimLongText(overview, sectionCap)}` : "",
+ "",
+ `## Source\n${sourceIdentity}`,
+ "",
+ "## Stage 1 Analysis",
+ trimLongText(analysis, sectionCap),
+ "",
+ "## Source Context",
+ trimLongText(sourceContext, sectionCap),
+ "",
+ "## First Generation Output",
+ trimLongText(generation, sectionCap),
+ ].filter(Boolean).join("\n")
+}
+
function getStore() {
return useChatStore.getState()
}
@@ -2415,7 +2616,13 @@ async function injectImagesIntoSourceSummary(
// by image content (e.g. "find the chart with revenue data")
// never matches because alt text was empty.
const captionsBySha = await loadCaptionCache(pp)
- const newSection = buildImageMarkdownSection(savedImages as never, captionsBySha)
+ const newSection = buildImageMarkdownSection(
+ savedImages.map((img) => ({
+ ...img,
+ relPath: toSourceSummaryImageRef(img.relPath),
+ })) as never,
+ captionsBySha,
+ )
const marker = "<!-- llm-wiki:embedded-images -->"
const wrapped = `\n\n${marker}\n${newSection.trim()}\n${marker}\n`
if (existing) {
diff --git a/src/lib/markdown-image-resolver.test.ts b/src/lib/markdown-image-resolver.test.ts
index 7d0bf7ec..60b08f1c 100644
--- a/src/lib/markdown-image-resolver.test.ts
+++ b/src/lib/markdown-image-resolver.test.ts
@@ -223,6 +223,9 @@ describe("resolveMarkdownImageSrc", () => {
expect(resolveMarkdownImageSrc("media/slug/img-1.png", PROJECT)).toBe(
"tauri-asset:/Users/me/MyWiki/wiki/media/slug/img-1.png",
)
+ expect(resolveMarkdownImageSrc("../media/slug/img-1.png", PROJECT)).toBe(
+ "tauri-asset:/Users/me/MyWiki/wiki/media/slug/img-1.png",
+ )
})
it("keeps `media/` refs wiki-root-relative even WITH a currentFileDir set", () => {
@@ -240,6 +243,15 @@ describe("resolveMarkdownImageSrc", () => {
).toBe(
"tauri-asset:/Users/me/MyWiki/wiki/media/易配置平台2.0培训-1/001-abc.jpg",
)
+ expect(
+ resolveMarkdownImageSrc(
+ "../media/易配置平台2.0培训-1/001-abc.jpg",
+ PROJECT,
+ `${PROJECT}/wiki/sources`,
+ ),
+ ).toBe(
+ "tauri-asset:/Users/me/MyWiki/wiki/media/易配置平台2.0培训-1/001-abc.jpg",
+ )
})
it("decodes percent-encoded CJK paths so the disk path is literal UTF-8", () => {
diff --git a/src/lib/markdown-image-resolver.ts b/src/lib/markdown-image-resolver.ts
index 5cf017a9..579eb9f6 100644
--- a/src/lib/markdown-image-resolver.ts
+++ b/src/lib/markdown-image-resolver.ts
@@ -137,18 +137,19 @@ export function resolveMarkdownImageSrc(
// that case we keep the raw value rather than crash the renderer.
const cleaned = decodePathSrc(stripped)
- // Generated-wiki convention takes precedence: ingest always emits
+ // Generated-wiki convention takes precedence: ingest normally emits
// embedded images as `media/<source-slug>/img-N.png` — a path
- // relative to the project's `wiki/` ROOT, regardless of which
- // wiki subdirectory the page lives in (`wiki/sources/foo.md`,
- // `wiki/concepts/bar.md`, …). If we let `currentFileDir` win for
- // these, a page in `wiki/sources/` would resolve `media/…` to
- // `wiki/sources/media/…` — one level too deep — and the image
- // 404s. So a `media/`-prefixed src is ALWAYS wiki-root-relative,
- // never file-relative. File-relative refs use `../assets/…` /
- // `./x.png` / bare names and never start with `media/`, so this
- // doesn't steal any of those cases.
- const isGeneratedMediaRef = cleaned.startsWith("media/")
+ // relative to the project's `wiki/` ROOT. Source-summary pages are
+ // written one level deeper (`wiki/sources/*.md`), so we persist those
+ // refs as `../media/...` for external Markdown apps such as Obsidian.
+ // Treat both forms as wiki-root media refs; otherwise call sites that
+ // do not know the current file dir (chat/search snippets) would resolve
+ // `../media/...` against `<project>/wiki/` and escape to `<project>/media`.
+ const isGeneratedMediaRef =
+ cleaned.startsWith("media/") || cleaned.startsWith("../media/")
+ const wikiRootMediaPath = cleaned.startsWith("../media/")
+ ? cleaned.slice("../".length)
+ : cleaned
// Preferred path: resolve relative to the markdown file's own
// directory, exactly like Obsidian. This is what makes
@@ -169,6 +170,6 @@ export function resolveMarkdownImageSrc(
// generated wiki content use this convention (`media/<slug>/…`)
// so the path is stable regardless of page depth, and callers
// without a file context (chat replies) rely on it too.
- const absolute = collapsePath(`${pp}/wiki/${cleaned}`)
+ const absolute = collapsePath(`${pp}/wiki/${wikiRootMediaPath}`)
return isInsideProject(absolute, pp) ? convertFileSrc(absolute) : rawSrc
}
diff --git a/src/lib/scheduled-import.test.ts b/src/lib/scheduled-import.test.ts
index afc9fb37..d0493882 100644
--- a/src/lib/scheduled-import.test.ts
+++ b/src/lib/scheduled-import.test.ts
@@ -38,6 +38,7 @@ vi.mock("@/lib/project-store", () => ({
}))
import {
+ isProjectManagedScheduledImportPath,
resolveImportPath,
scheduledImportDestinationForFile,
scanAndImport,
@@ -92,6 +93,28 @@ describe("scheduled import path handling", () => {
expect(dest).toBe(`${projectPath}/raw/sources/source.md`)
})
+ it("detects scheduled import paths managed by the project itself", () => {
+ expect(isProjectManagedScheduledImportPath(projectPath, projectPath)).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, `${projectPath}/raw/sources`),
+ ).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, `${projectPath}/raw`),
+ ).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, `${projectPath}/wiki`),
+ ).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, `${projectPath}/.llm-wiki`),
+ ).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, "/Users/me"),
+ ).toBe(true)
+ expect(
+ isProjectManagedScheduledImportPath(projectPath, "/Users/me/inbox"),
+ ).toBe(false)
+ })
+
it("sanitizes Windows-unsafe destination path segments with a stable suffix", () => {
const dest = scheduledImportDestinationForFile(
projectPath,
@@ -182,6 +205,13 @@ describe("scanAndImport failure handling", () => {
expect(mocks.writeFileAtomic).not.toHaveBeenCalled()
})
+ it("does not leave the scanner locked after a managed project path is skipped", async () => {
+ await scanAndImport(project, `${project.path}/raw/sources`)
+ await scanAndImport(project, "/Users/me/inbox")
+
+ expect(mocks.listDirectory).toHaveBeenCalledWith("/Users/me/inbox")
+ })
+
it("continues scanning when one file is locked or unreadable", async () => {
mocks.listDirectory.mockResolvedValueOnce([
{ name: "locked.pdf", path: "/Users/me/inbox/locked.pdf", is_dir: false },
diff --git a/src/lib/scheduled-import.ts b/src/lib/scheduled-import.ts
index 0fccc10f..e11ad72e 100644
--- a/src/lib/scheduled-import.ts
+++ b/src/lib/scheduled-import.ts
@@ -20,6 +20,7 @@ import {
enqueueSourceIngest,
isIngestableSourcePath,
} from "@/lib/source-lifecycle"
+import { useActivityStore } from "@/stores/activity-store"
interface ImportDb {
files: Record<string, string>
@@ -48,6 +49,7 @@ const EMPTY_DB: ImportDb = {
let scanTimer: ReturnType<typeof setInterval> | null = null
let scanning = false
let activeRunId = 0
+const managedPathWarningKeys = new Set<string>()
const DB_PATH = ".llm-wiki/scheduled-import-db.json"
const LEGACY_DB_DIR = ".llm-wiki-imported"
@@ -114,6 +116,35 @@ function projectSubpath(projectPath: string, relPath: string): string {
return `${normalizePath(projectPath)}/${relPath}`
}
+export function isProjectManagedScheduledImportPath(
+ projectPath: string,
+ importPath: string,
+): boolean {
+ const project = normalizePath(projectPath).replace(/\/+$/, "")
+ const root = normalizePath(importPath).replace(/\/+$/, "")
+ return (
+ root === project ||
+ isPathInside(project, root) ||
+ isPathInside(root, projectSubpath(project, "raw")) ||
+ isPathInside(root, projectSubpath(project, "raw/sources")) ||
+ isPathInside(root, projectSubpath(project, "wiki")) ||
+ isPathInside(root, projectSubpath(project, ".llm-wiki"))
+ )
+}
+
+function notifyManagedScheduledImportPath(project: WikiProject, importRoot: string): void {
+ const key = `${project.id}:${normalizePath(importRoot)}`
+ if (managedPathWarningKeys.has(key)) return
+ managedPathWarningKeys.add(key)
+ useActivityStore.getState().addItem({
+ type: "ingest",
+ title: "Scheduled import skipped",
+ status: "error",
+ detail: `Scheduled import path is inside or contains the current LLM Wiki project: ${importRoot}. Choose an external folder; project sources are handled by source folder monitoring.`,
+ filesWritten: [],
+ })
+}
+
function stableSuffix(input: string): string {
let hash = 2166136261
for (let i = 0; i < input.length; i += 1) {
@@ -301,11 +332,21 @@ export async function scanAndImport(
importPath: string,
options: ScanOptions = {},
): Promise<void> {
- if (!importPath || scanning) return
+ if (!importPath) return
- scanning = true
const projectPath = normalizePath(project.path)
const importRoot = resolveImportPath(projectPath, importPath)
+ if (isProjectManagedScheduledImportPath(projectPath, importRoot)) {
+ console.warn(
+ `[scheduled-import] skipped self-referential path "${importRoot}". Use source folder monitoring for project sources instead.`,
+ )
+ notifyManagedScheduledImportPath(project, importRoot)
+ return
+ }
+
+ if (scanning) return
+
+ scanning = true
try {
if (!isCurrentRun(project.id, options.runId)) {
diff --git a/src/stores/wiki-store.ts b/src/stores/wiki-store.ts
index 6cd18ff3..cc67a10b 100644
--- a/src/stores/wiki-store.ts
+++ b/src/stores/wiki-store.ts
@@ -34,6 +34,8 @@ interface LlmConfig {
* such controls. Default false preserves existing advanced-user setups.
*/
localCliIsolation?: boolean
+ /** Codex CLI provider only. Overall subprocess timeout in minutes. */
+ codexCliTimeoutMinutes?: number
}
export type SearchProvider = "tavily" | "serpapi" | "searxng" | "ollama" | "none"
@@ -283,6 +285,7 @@ export interface ProviderOverride {
maxContextSize?: number
reasoning?: ReasoningConfig
localCliIsolation?: boolean
+ codexCliTimeoutMinutes?: number
}
export type ProviderConfigs = Record<string, ProviderOverride>