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: import source URLs in batches
nash_suc0fbc1b5f750
diff --git a/src/components/sources/sources-view.tsx b/src/components/sources/sources-view.tsxindex 2e54889b..f10a2413 100644--- a/src/components/sources/sources-view.tsx+++ b/src/components/sources/sources-view.tsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useMemo, useRef } from "react"import { open } from "@tauri-apps/plugin-dialog"-import { Plus, FileText, RefreshCw, BookOpen, Trash2, Folder, ChevronRight, ChevronDown } from "lucide-react"+import { Plus, FileText, RefreshCw, BookOpen, Trash2, Folder, ChevronRight, ChevronDown, Link } from "lucide-react"import { Button } from "@/components/ui/button"import { ScrollArea } from "@/components/ui/scroll-area"import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip"@@ -21,6 +21,8 @@ import {} from "@/lib/source-lifecycle"import { filterRawSourceTree } from "@/lib/source-filter"import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"+import { importSourceUrls, parseImportUrls, type UrlImportResult } from "@/lib/url-source-import"const SOURCE_TREE_INITIAL_ROWS = 160const SOURCE_TREE_LOAD_BATCH = 160@@ -39,6 +41,10 @@ export function SourcesView() {const [ingestingPath, setIngestingPath] = useState<string | null>(null)const [refreshing, setRefreshing] = useState(false)const [refreshError, setRefreshError] = useState<string | null>(null)+ const [urlDialogOpen, setUrlDialogOpen] = useState(false)+ const [urlInput, setUrlInput] = useState("")+ const [urlError, setUrlError] = useState<string | null>(null)+ const [urlResults, setUrlResults] = useState<UrlImportResult[]>([])/*** Path of the source-tree node currently in "click again to* confirm delete" state. Lifted up here (rather than living@@ -166,6 +172,29 @@ export function SourcesView() {}}+ async function handleImportUrls() {+ if (!project || importing) return+ let urls: string[]+ try {+ urls = parseImportUrls(urlInput)+ if (urls.length === 0) throw new Error(t("sources.urlImport.empty"))+ } catch (error) {+ setUrlError(error instanceof Error ? error.message : String(error))+ return+ }+ setImporting(true)+ setUrlError(null)+ setUrlResults([])+ try {+ const results = await importSourceUrls(project, urls, llmConfig, sourceWatchConfig)+ setUrlResults(results)+ await loadSources()+ if (results.every((result) => result.path && !result.error)) setUrlInput("")+ } finally {+ setImporting(false)+ }+ }+async function handleOpenSource(node: FileNode) {try {const content = await readFile(node.path)@@ -290,9 +319,52 @@ 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}>+ <Link className="mr-1 h-4 w-4" />+ {t("sources.importUrls")}+ </Button></div></div>+ <Dialog open={urlDialogOpen} onOpenChange={setUrlDialogOpen}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t("sources.urlImport.title")}</DialogTitle>+ <DialogDescription>{t("sources.urlImport.description")}</DialogDescription>+ </DialogHeader>+ <textarea+ className="min-h-44 w-full resize-y rounded-md border bg-background px-3 py-2 font-mono text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"+ value={urlInput}+ onChange={(event) => {+ setUrlInput(event.target.value)+ setUrlError(null)+ setUrlResults([])+ }}+ placeholder={t("sources.urlImport.placeholder")}+ disabled={importing}+ />+ {urlError && <p className="text-sm text-destructive">{urlError}</p>}+ {urlResults.length > 0 && (+ <div className="max-h-40 space-y-1 overflow-auto rounded-md border p-2 text-xs">+ {urlResults.map((result) => (+ <div key={result.url} className={result.error ? "text-destructive" : "text-muted-foreground"}>+ <span className="break-all">{result.url}</span>+ <span className="ml-2">{result.error ?? t("sources.urlImport.imported")}</span>+ </div>+ ))}+ </div>+ )}+ <DialogFooter>+ <Button variant="outline" onClick={() => setUrlDialogOpen(false)} disabled={importing}>+ {t("common.close")}+ </Button>+ <Button onClick={() => void handleImportUrls()} disabled={importing || !urlInput.trim()}>+ {importing ? t("sources.importing") : t("sources.urlImport.submit")}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+<ScrollArea className="min-h-0 flex-1 overflow-hidden">{refreshError && (<div className="mx-4 mt-3 rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 89da3bce..4e9f3c2c 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -167,8 +167,17 @@"importHint": "Import documents to start building your wiki","importFiles": "Import Files","importFolder": "Folder",+ "importUrls": "URLs","importSourceFiles": "Import Source Files","importSourceFolder": "Import Source Folder",+ "urlImport": {+ "title": "Import web pages",+ "description": "Enter one HTTP(S) URL per line. Each page is saved as a source and queued for ingest; failed URLs do not stop the rest of the batch.",+ "placeholder": "https://example.com/article-one\nhttps://example.com/article-two",+ "submit": "Import URLs",+ "empty": "Enter at least one URL.",+ "imported": "Imported"+ },"refresh": "Refresh","refreshFolder": "Refresh folder","refreshingFolder": "Refreshing...",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex b0c41c10..5f7aeba9 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -167,8 +167,17 @@"importHint": "导入文档,开始构建你的 Wiki","importFiles": "导入文件","importFolder": "文件夹",+ "importUrls": "网址","importSourceFiles": "导入源文件","importSourceFolder": "导入源文件夹",+ "urlImport": {+ "title": "导入网页",+ "description": "每行输入一个 HTTP(S) 网址。网页会保存为原始资料并进入提取队列;单个网址失败不会中断整批任务。",+ "placeholder": "https://example.com/article-one\nhttps://example.com/article-two",+ "submit": "导入网址",+ "empty": "请至少输入一个网址。",+ "imported": "已导入"+ },"refresh": "刷新","refreshFolder": "刷新文件夹","refreshingFolder": "刷新中...",diff --git a/src/lib/source-lifecycle.ts b/src/lib/source-lifecycle.tsindex d901ef28..9ae6d025 100644--- a/src/lib/source-lifecycle.ts+++ b/src/lib/source-lifecycle.ts@@ -572,7 +572,7 @@ export async function cleanupDeletedWikiPages(}}-async function getUniqueDestPath(dir: string, fileName: string): Promise<string> {+export async function getUniqueDestPath(dir: string, fileName: string): Promise<string> {const basePath = `${dir}/${fileName}`if (!(await fileExists(basePath))) {diff --git a/src/lib/url-source-import.test.ts b/src/lib/url-source-import.test.tsnew file mode 100644index 00000000..1e4fcf6c--- /dev/null+++ b/src/lib/url-source-import.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest"+import { MAX_BATCH_URLS, parseImportUrls, urlSourceFileName } from "./url-source-import"++describe("parseImportUrls", () => {+ it("normalizes fragments, removes duplicates, and preserves order", () => {+ expect(parseImportUrls(" https://example.com/a#part\nhttps://example.com/a\nhttp://例子.测试/b ")).toEqual([+ "https://example.com/a",+ "http://xn--fsqu00a.xn--0zwm56d/b",+ ])+ })++ it("rejects malformed and non-http URLs", () => {+ expect(() => parseImportUrls("not-a-url")).toThrow("Invalid URL")+ expect(() => parseImportUrls("file:///tmp/secret")).toThrow("Unsupported URL scheme")+ expect(() => parseImportUrls("https://user:[email protected]/page")).toThrow("embedded credentials")+ })++ it("caps batch size", () => {+ const urls = Array.from({ length: MAX_BATCH_URLS + 1 }, (_, index) => `https://example.com/${index}`)+ expect(() => parseImportUrls(urls.join("\n"))).toThrow(`at most ${MAX_BATCH_URLS}`)+ })+})++describe("urlSourceFileName", () => {+ it("prefers a safe HTML title", () => {+ expect(urlSourceFileName(+ "https://example.com/post/123",+ "text/html; charset=utf-8",+ "<html><head><title>安全 / Useful: Guide</title></head></html>",+ )).toBe("安全-Useful-Guide.html")+ })++ it("uses the URL leaf for plain text", () => {+ expect(urlSourceFileName("https://example.com/docs/readme.md", "text/plain", "hello"))+ .toBe("readme.txt")+ })++ it("avoids Windows reserved names and tolerates malformed escapes", () => {+ expect(urlSourceFileName("https://example.com/AUX", "text/plain", "hello"))+ .toBe("AUX-web.txt")+ expect(urlSourceFileName("https://example.com/bad%escape", "text/plain", "hello"))+ .toBe("bad-escape.txt")+ })+})diff --git a/src/lib/url-source-import.ts b/src/lib/url-source-import.tsnew file mode 100644index 00000000..a3aca2fe--- /dev/null+++ b/src/lib/url-source-import.ts@@ -0,0 +1,134 @@+import { writeFile } from "@/commands/fs"+import type { LlmConfig, SourceWatchConfig } from "@/stores/wiki-store"+import type { WikiProject } from "@/types/wiki"+import { getHttpFetch } from "@/lib/tauri-fetch"+import { normalizeSourceWatchConfig } from "@/lib/source-watch-config"+import { enqueueSourceIngest, getUniqueDestPath } from "@/lib/source-lifecycle"+import { normalizePath } from "@/lib/path-utils"++export const MAX_BATCH_URLS = 50++export interface UrlImportResult {+ url: string+ path?: string+ error?: string+}++export function parseImportUrls(input: string): string[] {+ const unique = new Set<string>()+ for (const line of input.split(/\r?\n/)) {+ const candidate = line.trim()+ if (!candidate) continue+ let parsed: URL+ try {+ parsed = new URL(candidate)+ } catch {+ throw new Error(`Invalid URL: ${candidate}`)+ }+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {+ throw new Error(`Unsupported URL scheme: ${candidate}`)+ }+ if (parsed.username || parsed.password) {+ throw new Error(`URLs with embedded credentials are not allowed: ${candidate}`)+ }+ parsed.hash = ""+ unique.add(parsed.toString())+ if (unique.size > MAX_BATCH_URLS) {+ throw new Error(`A batch can contain at most ${MAX_BATCH_URLS} URLs`)+ }+ }+ return [...unique]+}++function safeSlug(value: string): string {+ const slug = value+ .normalize("NFKC")+ .replace(/[^\p{L}\p{N}._-]+/gu, "-")+ .replace(/^-+|-+$/g, "")+ .slice(0, 100)+ const stem = slug.split(".")[0]?.toUpperCase()+ return /^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/.test(stem) ? `${slug}-web` : slug+}++export function urlSourceFileName(url: string, contentType: string, body: string): string {+ const parsed = new URL(url)+ const html = /(?:text\/html|application\/xhtml\+xml)/i.test(contentType)+ const title = html ? body.match(/<title\b[^>]*>([\s\S]*?)<\/title>/i)?.[1] : undefined+ const decodedTitle = title?.replace(/<[^>]+>/g, " ").replace(/&(?:amp|#38);/gi, "&").trim()+ const encodedLeaf = parsed.pathname.split("/").filter(Boolean).pop() ?? ""+ let pathLeaf = encodedLeaf+ try {+ pathLeaf = decodeURIComponent(encodedLeaf)+ } catch {+ // Keep the encoded path leaf. A malformed percent sequence in a remote+ // URL should not prevent importing an otherwise valid response.+ }+ const base = safeSlug(decodedTitle || pathLeaf.replace(/\.[^.]+$/, "") || parsed.hostname) || "web-page"+ return `${base}.${html ? "html" : "txt"}`+}++function attachSourceUrl(url: string, contentType: string, body: string): string {+ if (/(?:text\/html|application\/xhtml\+xml)/i.test(contentType)) {+ const escaped = url.replace(/&/g, "&").replace(/"/g, """)+ const meta = `<meta name="llm-wiki-source-url" content="${escaped}">`+ return /<head\b[^>]*>/i.test(body)+ ? body.replace(/<head\b[^>]*>/i, (head) => `${head}\n${meta}`)+ : `${meta}\n${body}`+ }+ return `Source URL: ${url}\n\n${body}`+}++export async function importSourceUrls(+ project: WikiProject,+ urls: string[],+ llmConfig: LlmConfig,+ sourceWatchConfig?: SourceWatchConfig,+): Promise<UrlImportResult[]> {+ const fetch = await getHttpFetch()+ const maxBytes = normalizeSourceWatchConfig(sourceWatchConfig).maxFileSizeMb * 1024 * 1024+ const sourceRoot = `${normalizePath(project.path)}/raw/sources`+ const results: UrlImportResult[] = []+ const importedPaths: string[] = []++ for (const url of urls) {+ try {+ const controller = new AbortController()+ const timeout = setTimeout(() => controller.abort(), 60_000)+ let response: Response+ try {+ response = await fetch(url, { redirect: "follow", signal: controller.signal })+ } finally {+ clearTimeout(timeout)+ }+ if (!response.ok) throw new Error(`HTTP ${response.status}`)+ const declaredSize = Number(response.headers.get("content-length") ?? "0")+ if (Number.isFinite(declaredSize) && declaredSize > maxBytes) {+ throw new Error("Response exceeds the source file size limit")+ }+ const bytes = new Uint8Array(await response.arrayBuffer())+ if (bytes.byteLength > maxBytes) throw new Error("Response exceeds the source file size limit")+ const contentType = response.headers.get("content-type") ?? "text/plain"+ if (!/(?:text\/|application\/(?:xhtml\+xml|json|xml))/i.test(contentType)) {+ throw new Error(`Unsupported content type: ${contentType.split(";")[0]}`)+ }+ const body = new TextDecoder().decode(bytes)+ const fileName = urlSourceFileName(url, contentType, body)+ const path = await getUniqueDestPath(sourceRoot, fileName)+ await writeFile(path, attachSourceUrl(url, contentType, body))+ importedPaths.push(path)+ results.push({ url, path })+ } catch (error) {+ results.push({ url, error: error instanceof Error ? error.message : String(error) })+ }+ }++ try {+ await enqueueSourceIngest(project, importedPaths, llmConfig)+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error)+ for (const result of results) {+ if (result.path) result.error = `Saved, but failed to queue ingest: ${message}`+ }+ }+ return results+}