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 provider and import routing

nash_su969e7e8d9e29
diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rs
index 572e53cd..5cf59f50 100644
--- a/src-tauri/src/api_server.rs
+++ b/src-tauri/src/api_server.rs
@@ -1818,11 +1818,29 @@ fn project_llm_config(parsed: &Value, project_id: &str) -> Option<agent::provide
let mut profile = project.get("profile")?.clone();
let profile_object = profile.as_object_mut()?;
let preset_id = project.get("presetId").and_then(Value::as_str)?;
- if let Some(provider) = parsed
+ let provider = parsed
.get("providerConfigs")
.and_then(|value| value.get(preset_id))
- .and_then(Value::as_object)
- {
+ .and_then(Value::as_object);
+ // `customLlmPresets` is the authoritative registry. A stale providerConfigs
+ // entry may survive an interrupted multi-key settings save, so credentials
+ // alone must not resurrect a deleted custom preset.
+ let custom_preset_exists = parsed
+ .get("customLlmPresets")
+ .and_then(Value::as_array)
+ .map(|presets| {
+ presets
+ .iter()
+ .any(|preset| preset.get("id").and_then(Value::as_str) == Some(preset_id))
+ })
+ .unwrap_or(false);
+ // Match resolveProjectLlmConfig in src/lib/llm-task-routing.ts: deleting a
+ // custom preset must make every project that referenced it fall back to
+ // the global config, including projects that are not currently open.
+ if preset_id.starts_with("custom-") && !custom_preset_exists {
+ return global.and_then(|value| serde_json::from_value(value).ok());
+ }
+ if let Some(provider) = provider {
for key in [
"apiKey",
"apiMode",
@@ -2818,4 +2836,49 @@ mod tests {
);
assert!(project_llm_config(&state, "legacy").is_none());
}
+
+ #[test]
+ fn project_llm_config_falls_back_after_custom_preset_is_deleted() {
+ let state = json!({
+ "llmConfig": { "provider": "openai", "apiKey": "global", "model": "gpt-global", "ollamaUrl": "", "customEndpoint": "", "maxContextSize": 1000 },
+ "providerConfigs": {
+ "custom-deleted": { "apiKey": "stale-secret", "model": "stale-model", "baseUrl": "https://old.example/v1" }
+ },
+ "customLlmPresets": [],
+ "projectLlmOverrides": {
+ "project-b": {
+ "enabled": true,
+ "presetId": "custom-deleted",
+ "model": "stale-model",
+ "profile": { "provider": "custom", "model": "stale-model", "ollamaUrl": "", "customEndpoint": "https://old.example/v1", "maxContextSize": 64000 }
+ }
+ }
+ });
+ let config = project_llm_config(&state, "project-b").expect("global fallback");
+ assert_eq!(config.model, "gpt-global");
+ assert_eq!(config.api_key, "global");
+ }
+
+ #[test]
+ fn project_llm_config_uses_registered_custom_preset() {
+ let state = json!({
+ "llmConfig": { "provider": "openai", "apiKey": "global", "model": "gpt-global", "ollamaUrl": "", "customEndpoint": "", "maxContextSize": 1000 },
+ "customLlmPresets": [{ "id": "custom-live", "label": "Live" }],
+ "providerConfigs": {
+ "custom-live": { "apiKey": "live-secret", "model": "live-model", "baseUrl": "https://live.example/v1" }
+ },
+ "projectLlmOverrides": {
+ "project-c": {
+ "enabled": true,
+ "presetId": "custom-live",
+ "model": "",
+ "profile": { "provider": "custom", "model": "old-model", "ollamaUrl": "", "customEndpoint": "https://old.example/v1", "maxContextSize": 64000 }
+ }
+ }
+ });
+ let config = project_llm_config(&state, "project-c").expect("custom config");
+ assert_eq!(config.model, "live-model");
+ assert_eq!(config.api_key, "live-secret");
+ assert_eq!(config.custom_endpoint, "https://live.example/v1");
+ }
}
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsx
index f10a2413..3cfdb881 100644
--- a/src/components/sources/sources-view.tsx
+++ b/src/components/sources/sources-view.tsx
@@ -319,7 +319,7 @@ export function SourcesView() {
<Plus className="mr-1 h-4 w-4" />
{t("sources.importFolder", "Folder")}
</Button>
- <Button size="sm" variant="outline" onClick={() => setUrlDialogOpen(true)} disabled={importing}>
+ <Button size="sm" onClick={() => setUrlDialogOpen(true)} disabled={importing}>
<Link className="mr-1 h-4 w-4" />
{t("sources.importUrls")}
</Button>
diff --git a/src/lib/embedding.test.ts b/src/lib/embedding.test.ts
index 71ed414e..2b7a8d45 100644
--- a/src/lib/embedding.test.ts
+++ b/src/lib/embedding.test.ts
@@ -1197,6 +1197,27 @@ describe("fetchEmbedding (via searchByEmbedding) — auto-halve", () => {
await searchByEmbedding("/tmp/p", "q", cfg, 5)
expect(getLastEmbeddingError()).toBeNull()
})
+
+ it("does not let a concurrent success erase a later failure", async () => {
+ mockEmbeddingFetchInvoke.mockImplementation(async (args) => {
+ const { text } = args as { text: string }
+ if (text === "fails") {
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ throw new Error("concurrent embedding failed")
+ }
+ await new Promise((resolve) => setTimeout(resolve, 15))
+ return [0.1]
+ })
+ await Promise.all([
+ fetchEmbedding("fails", cfg),
+ fetchEmbedding("succeeds", cfg),
+ ])
+ expect(getLastEmbeddingError()).toContain("concurrent embedding failed")
+
+ mockEmbeddingFetchInvoke.mockResolvedValueOnce([0.2])
+ await fetchEmbedding("later sequential success", cfg)
+ expect(getLastEmbeddingError()).toBeNull()
+ })
})
// ── embedPage — replaces page's chunks in LanceDB ──────────────────
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index 258253d3..4cfe4f52 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -38,6 +38,7 @@ import { parseFrontmatter } from "@/lib/frontmatter"
* embed.
*/
let lastEmbeddingError: string | null = null
+let embeddingFailureVersion = 0
const INCREMENTAL_OPTIMIZE_PAGE_THRESHOLD = 20
const incrementalOptimizeCounts = new Map<string, number>()
@@ -47,6 +48,8 @@ export function getLastEmbeddingError(): string | null {
export function resetEmbeddingOptimizeAccountingForTests(): void {
incrementalOptimizeCounts.clear()
+ embeddingFailureVersion = 0
+ lastEmbeddingError = null
}
// ── fetchEmbedding with auto-halve retry ────────────────────────────────
@@ -90,15 +93,19 @@ export async function fetchEmbedding(
maxRetries = 3,
): Promise<number[] | null> {
if (!cfg.endpoint) return null
+ const failureVersionAtStart = embeddingFailureVersion
try {
const embedding = await invoke<number[]>("embedding_fetch", {
text,
cfg,
maxRetries,
})
- lastEmbeddingError = null
+ // Do not let a concurrent success erase an error that completed after
+ // this request began. A later sequential success still clears it.
+ if (embeddingFailureVersion === failureVersionAtStart) lastEmbeddingError = null
return embedding
} catch (err) {
+ embeddingFailureVersion++
lastEmbeddingError = err instanceof Error ? err.message : String(err)
console.warn(`[Embedding] ${lastEmbeddingError}`)
return null
@@ -110,16 +117,17 @@ async function fetchBatchEmbeddings(
cfg: EmbeddingConfig,
): Promise<number[][] | null> {
if (texts.length === 0) return []
+ const failureVersionAtStart = embeddingFailureVersion
try {
const embeddings = await invoke<number[][]>("embedding_fetch_batch", { texts, cfg })
if (embeddings.length !== texts.length) {
throw new Error(`Embedding batch returned ${embeddings.length} vectors for ${texts.length} inputs`)
}
- lastEmbeddingError = null
+ if (embeddingFailureVersion === failureVersionAtStart) lastEmbeddingError = null
return embeddings
} catch (err) {
- lastEmbeddingError = err instanceof Error ? err.message : String(err)
- console.warn(`[Embedding] Batch request failed; retrying inputs individually: ${lastEmbeddingError}`)
+ const message = err instanceof Error ? err.message : String(err)
+ console.warn(`[Embedding] Batch request failed; retrying inputs individually: ${message}`)
return null
}
}
@@ -139,13 +147,19 @@ function createAsyncLimiter(rawLimit: number | undefined): AsyncLimiter {
let active = 0
const waiters: Array<() => void> = []
return async <T>(task: () => Promise<T>): Promise<T> => {
- if (active >= limit) await new Promise<void>((resolve) => waiters.push(resolve))
- active++
+ if (active < limit) {
+ active++
+ } else {
+ // A queued resolver owns the permit transferred by the completing task;
+ // it must not increment active again when it resumes.
+ await new Promise<void>((resolve) => waiters.push(resolve))
+ }
try {
return await task()
} finally {
- active--
- waiters.shift()?.()
+ const next = waiters.shift()
+ if (next) next()
+ else active--
}
}
}
diff --git a/src/lib/llm-task-routing.ts b/src/lib/llm-task-routing.ts
index 3be330fd..72e1f811 100644
--- a/src/lib/llm-task-routing.ts
+++ b/src/lib/llm-task-routing.ts
@@ -17,6 +17,9 @@ export function resolveProjectLlmConfig(
projectOverride: ProjectLlmOverride,
customPresets: CustomLlmPreset[] = [],
): LlmConfig {
+ // Keep this fallback contract aligned with project_llm_config in
+ // src-tauri/src/api_server.rs. Native API/MCP callers resolve the same
+ // persisted override without running this TypeScript code.
if (!projectOverride.enabled || !projectOverride.presetId) return globalConfig
const preset = findLlmPreset(projectOverride.presetId, customPresets)
if (!preset) return globalConfig
diff --git a/src/lib/url-source-import.test.ts b/src/lib/url-source-import.test.ts
index 1e4fcf6c..b4ce3543 100644
--- a/src/lib/url-source-import.test.ts
+++ b/src/lib/url-source-import.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
-import { MAX_BATCH_URLS, parseImportUrls, urlSourceFileName } from "./url-source-import"
+import { MAX_BATCH_URLS, fetchImportUrl, parseImportUrls, urlSourceFileName } from "./url-source-import"
describe("parseImportUrls", () => {
it("normalizes fragments, removes duplicates, and preserves order", () => {
@@ -42,3 +42,45 @@ describe("urlSourceFileName", () => {
.toBe("bad-escape.txt")
})
})
+
+describe("fetchImportUrl", () => {
+ it("blocks a public URL redirect before requesting a private target", async () => {
+ const fetch = async (url: string | URL | Request, init?: RequestInit & { maxRedirections?: number }) => {
+ expect(String(url)).toBe("https://example.com/start")
+ expect(init).toMatchObject({ redirect: "manual", maxRedirections: 0 })
+ return new Response(null, {
+ status: 302,
+ headers: { location: "http://169.254.169.254/latest/meta-data" },
+ })
+ }
+ await expect(fetchImportUrl(fetch as typeof globalThis.fetch, "https://example.com/start", new AbortController().signal))
+ .rejects.toThrow("cannot redirect")
+ })
+
+ it("blocks IPv4-mapped IPv6 private redirect targets", async () => {
+ const fetch = async () => new Response(null, {
+ status: 302,
+ headers: { location: "http://[::ffff:169.254.169.254]/metadata" },
+ })
+ await expect(fetchImportUrl(fetch as typeof globalThis.fetch, "https://example.com", new AbortController().signal))
+ .rejects.toThrow("cannot redirect")
+ })
+
+ it("allows an explicitly requested private URL and follows relative redirects", async () => {
+ const seen: string[] = []
+ const fetch = async (url: string | URL | Request, init?: RequestInit & { maxRedirections?: number }) => {
+ seen.push(String(url))
+ expect(init).toMatchObject({ redirect: "manual", maxRedirections: 0 })
+ return seen.length === 1
+ ? new Response(null, { status: 302, headers: { location: "/page" } })
+ : new Response("ok", { status: 200 })
+ }
+ const response = await fetchImportUrl(
+ fetch as typeof globalThis.fetch,
+ "http://192.168.1.50/start",
+ new AbortController().signal,
+ )
+ expect(await response.text()).toBe("ok")
+ expect(seen).toEqual(["http://192.168.1.50/start", "http://192.168.1.50/page"])
+ })
+})
diff --git a/src/lib/url-source-import.ts b/src/lib/url-source-import.ts
index a3aca2fe..b43f980b 100644
--- a/src/lib/url-source-import.ts
+++ b/src/lib/url-source-import.ts
@@ -7,6 +7,7 @@ import { enqueueSourceIngest, getUniqueDestPath } from "@/lib/source-lifecycle"
import { normalizePath } from "@/lib/path-utils"
export const MAX_BATCH_URLS = 50
+const MAX_REDIRECTS = 10
export interface UrlImportResult {
url: string
@@ -40,6 +41,79 @@ export function parseImportUrls(input: string): string[] {
return [...unique]
}
+function isPrivateNetworkHost(hostname: string): boolean {
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "")
+ if (host === "localhost" || host.endsWith(".localhost") || host.endsWith(".local")) return true
+ if (host === "::" || host === "::1" || /^(?:fc|fd|fe[89ab])/i.test(host)) return true
+ if (host.startsWith("::ffff:")) {
+ const mapped = host.slice(7)
+ if (mapped.includes(".")) return isPrivateNetworkHost(mapped)
+ const groups = mapped.split(":")
+ if (groups.length === 2 && groups.every((group) => /^[0-9a-f]{1,4}$/i.test(group))) {
+ const high = Number.parseInt(groups[0], 16)
+ const low = Number.parseInt(groups[1], 16)
+ return isPrivateNetworkHost(`${high >> 8}.${high & 255}.${low >> 8}.${low & 255}`)
+ }
+ }
+ const parts = host.split(".").map(Number)
+ if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
+ return false
+ }
+ const [a, b] = parts
+ return a === 0
+ || a === 10
+ || a === 127
+ || (a === 100 && b >= 64 && b <= 127)
+ || (a === 169 && b === 254)
+ || (a === 172 && b >= 16 && b <= 31)
+ || (a === 192 && b === 168)
+ || (a === 198 && (b === 18 || b === 19))
+ || a >= 224
+}
+
+function validateHttpUrl(value: string): URL {
+ const parsed = new URL(value)
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ throw new Error(`Unsupported URL scheme: ${value}`)
+ }
+ if (parsed.username || parsed.password) {
+ throw new Error(`URLs with embedded credentials are not allowed: ${value}`)
+ }
+ return parsed
+}
+
+/** @internal Exported for redirect-policy regression tests. */
+export async function fetchImportUrl(
+ fetch: typeof globalThis.fetch,
+ initialUrl: string,
+ signal: AbortSignal,
+): Promise<Response> {
+ let current = validateHttpUrl(initialUrl)
+ const initialIsPrivate = isPrivateNetworkHost(current.hostname)
+ for (let redirects = 0; redirects <= MAX_REDIRECTS; redirects++) {
+ // Tauri plugin-http does not forward the standard `redirect` option to
+ // reqwest. Its transport-specific maxRedirections flag is therefore
+ // required to expose each 3xx response to this policy loop. Native/Node
+ // fetch ignores the extra field and follows `redirect: "manual"`.
+ const requestInit: RequestInit & { maxRedirections: number } = {
+ redirect: "manual",
+ maxRedirections: 0,
+ signal,
+ }
+ const response = await fetch(current.toString(), requestInit)
+ if (![301, 302, 303, 307, 308].includes(response.status)) return response
+ if (redirects === MAX_REDIRECTS) throw new Error(`Too many redirects (maximum ${MAX_REDIRECTS})`)
+ const location = response.headers.get("location")
+ if (!location) throw new Error("Redirect response is missing a Location header")
+ const next = validateHttpUrl(new URL(location, current).toString())
+ if (!initialIsPrivate && isPrivateNetworkHost(next.hostname)) {
+ throw new Error("A public URL cannot redirect to a private or local network address")
+ }
+ current = next
+ }
+ throw new Error(`Too many redirects (maximum ${MAX_REDIRECTS})`)
+}
+
function safeSlug(value: string): string {
const slug = value
.normalize("NFKC")
@@ -96,7 +170,7 @@ export async function importSourceUrls(
const timeout = setTimeout(() => controller.abort(), 60_000)
let response: Response
try {
- response = await fetch(url, { redirect: "follow", signal: controller.signal })
+ response = await fetchImportUrl(fetch, url, controller.signal)
} finally {
clearTimeout(timeout)
}