LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。
TypeScript
feat: add single-page vector indexing API
nash_su5427eb56ae68
diff --git a/README.md b/README.mdindex cf261e1f..d094bfbe 100644--- a/README.md+++ b/README.md@@ -447,6 +447,7 @@ LLM Wiki ships a built-in local HTTP API at `http://127.0.0.1:19828` (token-prot- `POST /api/v1/projects/{id}/chat` — backend Agent chat endpoint for wiki/source/web/AnyTXT retrieval. JSON requests remain non-streaming by default; send `"stream": true` or `Accept: text/event-stream` for SSE events (`meta`, incremental `agent`, then `done`, `cancelled`, or `error`). The terminal `done` frame contains the complete aggregate response, so clients should not render both message deltas and the final message as separate answers. `mode: "deep"` broadens evidence collection, while the full Deep Research workspace remains available in the desktop UI- `GET /api/v1/projects/{id}/graph` — wikilinks graph- `POST /api/v1/projects/{id}/sources/rescan` — trigger a backend rescan+- `POST /api/v1/projects/{id}/pages/embed` — index one externally created or updated `wiki/*.md` page without rebuilding the whole vector databaseEnable the API, generate a token, and choose whether local unauthenticated access is allowed in **Settings → API + MCP**.diff --git a/README_CN.md b/README_CN.mdindex 9c4f7ebf..99f18d50 100644--- a/README_CN.md+++ b/README_CN.md@@ -444,6 +444,7 @@ LLM Wiki 内置一个本地 HTTP API(监听 `http://127.0.0.1:19828`,Token- `POST /api/v1/projects/{id}/chat` —— 非流式 Rust 后端 Agent 聊天接口,返回助手消息、引用、用量和工具事件;支持 Wiki/Source/Web/AnyTXT 检索,`mode: "deep"` 会扩展证据收集范围- `GET /api/v1/projects/{id}/graph` —— Wikilinks 知识图谱- `POST /api/v1/projects/{id}/sources/rescan` —— 触发后端重新扫描+- `POST /api/v1/projects/{id}/pages/embed` —— 为外部创建或更新的单个 `wiki/*.md` 页面建立向量索引,无需重建整个向量数据库在 **设置 → API + MCP** 中开启 API、生成 Token,并按需选择是否允许本机无鉴权访问。diff --git a/README_JA.md b/README_JA.mdindex 10a4229c..76f9c74b 100644--- a/README_JA.md+++ b/README_JA.md@@ -453,6 +453,7 @@ LLM Wiki は組み込みのローカル HTTP API(`http://127.0.0.1:19828` で- `POST /api/v1/projects/{id}/chat` — 非ストリーミングの Rust バックエンド Agent chat エンドポイント。assistant message、references、usage、tool events を返し、Wiki / Source / Web / AnyTXT 検索に対応します。`mode: "deep"` では証拠収集範囲を広げます- `GET /api/v1/projects/{id}/graph` — wikilinks の知識グラフ- `POST /api/v1/projects/{id}/sources/rescan` — バックエンドの再スキャンをトリガー+- `POST /api/v1/projects/{id}/pages/embed` — 外部で作成・更新された単一の `wiki/*.md` ページを、ベクトル DB 全体を再構築せずにインデックス化**設定 → API + MCP** から API を有効化し、Token を発行できます。必要に応じて、ローカルからの認証なしアクセスも切り替えられます。diff --git a/README_KO.md b/README_KO.mdindex b4e51904..ed60fad1 100644--- a/README_KO.md+++ b/README_KO.md@@ -453,6 +453,7 @@ LLM Wiki에는 `http://127.0.0.1:19828`의 내장 로컬 HTTP API가 포함되- `POST /api/v1/projects/{id}/chat` — 비스트리밍 Rust 백엔드 Agent chat 엔드포인트로 assistant message, references, usage, tool events를 반환하며 Wiki/Source/Web/AnyTXT 검색을 지원합니다. `mode: "deep"`은 증거 수집 범위를 넓힙니다- `GET /api/v1/projects/{id}/graph` — wikilinks graph- `POST /api/v1/projects/{id}/sources/rescan` — backend rescan trigger+- `POST /api/v1/projects/{id}/pages/embed` — 전체 벡터 DB를 재구축하지 않고 외부에서 생성하거나 수정한 `wiki/*.md` 페이지 하나를 인덱싱**Settings → API + MCP**에서 API를 활성화하고 token을 생성할 수 있습니다. 필요하면 로컬 unauthenticated access도 켜거나 끌 수 있습니다.diff --git a/mcp-server/src/api-client.ts b/mcp-server/src/api-client.tsindex af078330..652297a7 100644--- a/mcp-server/src/api-client.ts+++ b/mcp-server/src/api-client.ts@@ -37,6 +37,15 @@ export interface ApiSearchResponse {vectorHits?: number}+export interface ApiPageEmbeddingResult {+ path: string+ pageId: string+ revision: string+ chunks: number+ vectorsWritten: number+ status: string+}+export interface ApiChatReference {title: stringpath: string@@ -157,6 +166,20 @@ function numberOrUndefined(value: unknown): number | undefined {return typeof value === "number" && Number.isFinite(value) ? value : undefined}+function requireString(value: unknown, context: string): string {+ if (typeof value !== "string" || !value) {+ throw new Error(`${context}: expected non-empty string`)+ }+ return value+}++function requireNumber(value: unknown, context: string): number {+ if (typeof value !== "number" || !Number.isFinite(value)) {+ throw new Error(`${context}: expected finite number`)+ }+ return value+}+export class LlmWikiApiClient {private readonly baseUrl: stringprivate readonly token?: string@@ -296,6 +319,22 @@ export class LlmWikiApiClient {})}+ async embedPage(path: string, projectId = "current", force = false): Promise<ApiPageEmbeddingResult> {+ const json = await this.request(`/projects/${encodeURIComponent(projectId)}/pages/embed`, {+ method: "POST",+ body: { path, force },+ })+ const result = requireObject(json.result, "page embedding result")+ return {+ path: requireString(result.path, "page embedding result.path"),+ pageId: requireString(result.pageId, "page embedding result.pageId"),+ revision: requireString(result.revision, "page embedding result.revision"),+ chunks: requireNumber(result.chunks, "page embedding result.chunks"),+ vectorsWritten: requireNumber(result.vectorsWritten, "page embedding result.vectorsWritten"),+ status: requireString(result.status, "page embedding result.status"),+ }+ }+private async request(path: string, options: { method?: "GET" | "POST"; body?: unknown; auth?: boolean } = {}): Promise<Record<string, unknown>> {const url = `${this.baseUrl}${apiPath(path)}`const headers: Record<string, string> = { Accept: "application/json" }diff --git a/mcp-server/src/index.ts b/mcp-server/src/index.tsindex 49cc3189..a6bad289 100644--- a/mcp-server/src/index.ts+++ b/mcp-server/src/index.ts@@ -169,6 +169,20 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({additionalProperties: false,},},+ {+ name: "llm_wiki_embed_page",+ description: "Create or replace the vector index for one existing Markdown page under a project's wiki/ directory.",+ inputSchema: {+ type: "object",+ properties: {+ project_id: { type: "string", description: "Project UUID, project path, or 'current'. Defaults to current." },+ path: { type: "string", description: "Project-relative Markdown path, for example wiki/ideas/example.md." },+ force: { type: "boolean", description: "Force rebuilding vectors even when the page content and embedding configuration are unchanged." },+ },+ required: ["path"],+ additionalProperties: false,+ },+ },],}))@@ -268,6 +282,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {const scope = await resolveProjectScope(args)return textResult(withActiveProject(JSON.stringify(await client.rescan(scope.id), null, 2), scope.project, scope.id))}+ case "llm_wiki_embed_page": {+ await assertMcpEnabled()+ const path = stringArg(args.path, "path")+ const scope = await resolveProjectScope(args)+ const result = await client.embedPage(path, scope.id, boolArg(args.force, false))+ return textResult(withActiveProject(JSON.stringify(result, null, 2), scope.project, scope.id))+ }default:throw new McpError(ErrorCode.MethodNotFound, `Unknown tool: ${request.params.name}`)}diff --git a/mcp-server/test/api-client.test.ts b/mcp-server/test/api-client.test.tsindex 678a852a..b2275c73 100644--- a/mcp-server/test/api-client.test.ts+++ b/mcp-server/test/api-client.test.ts@@ -67,6 +67,54 @@ test("search posts JSON body to current project", async () => {assert.equal(results.results[0]?.vectorScore, 0.9)})+test("embedPage posts a project-relative wiki path", async () => {+ const fetchImpl: typeof fetch = async (input, init) => {+ assert.equal(String(input), "http://127.0.0.1:19828/api/v1/projects/project-a/pages/embed")+ assert.equal(init?.method, "POST")+ assert.deepEqual(JSON.parse(String(init?.body)), { path: "wiki/ideas/page.md", force: true })+ return new Response(JSON.stringify({+ ok: true,+ result: {+ path: "wiki/ideas/page.md",+ pageId: "page",+ revision: "sha256:abc",+ chunks: 2,+ vectorsWritten: 2,+ status: "indexed",+ },+ }), { status: 200, headers: { "Content-Type": "application/json" } })+ }+ const client = new LlmWikiApiClient({ fetchImpl })+ assert.deepEqual(await client.embedPage("wiki/ideas/page.md", "project-a", true), {+ path: "wiki/ideas/page.md",+ pageId: "page",+ revision: "sha256:abc",+ chunks: 2,+ vectorsWritten: 2,+ status: "indexed",+ })+})++test("embedPage rejects malformed success payloads", async () => {+ const fetchImpl: typeof fetch = async () => new Response(JSON.stringify({+ ok: true,+ result: {+ path: "wiki/page.md",+ pageId: "page",+ revision: "sha256:abc",+ chunks: "2",+ vectorsWritten: 2,+ status: "indexed",+ },+ }), { status: 200, headers: { "Content-Type": "application/json" } })+ const client = new LlmWikiApiClient({ fetchImpl })++ await assert.rejects(+ () => client.embedPage("wiki/page.md"),+ /page embedding result\.chunks: expected finite number/,+ )+})+test("chat posts agent request and parses references", async () => {let url = ""let body = ""diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0dfe2769..df565d67 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -48,7 +48,7 @@ futures = "0.3"# Claude Code CLI subprocess transport: spawn `claude` as a child process,# stream stdout line-by-line back to the frontend. tokio::process gives us# async io and clean cancellation; `which` locates the binary on PATH.-tokio = { version = "1", features = ["process", "io-util", "sync", "macros", "rt"] }+tokio = { version = "1", features = ["process", "io-util", "sync", "macros", "rt", "time"] }which = "7"uuid = { version = "1", features = ["v4"] }# Multimodal image extraction (Phase 1):diff --git a/src-tauri/src/api_server.rs b/src-tauri/src/api_server.rsindex 121ae964..796c75c0 100644--- a/src-tauri/src/api_server.rs+++ b/src-tauri/src/api_server.rs@@ -36,6 +36,7 @@ const RATE_LIMIT_WINDOW: Duration = Duration::from_secs(1);const RATE_LIMIT_MAX_REQUESTS: usize = 120;const MAX_IN_FLIGHT_REQUESTS: usize = 64;const MAX_IN_FLIGHT_CHAT_STREAMS: usize = 8;+const MAX_IN_FLIGHT_PAGE_EMBEDS: usize = 4;const SSE_QUEUE_CAPACITY: usize = 64;const SSE_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);@@ -43,6 +44,7 @@ const SSE_HEARTBEAT_INTERVAL: Duration = Duration::from_secs(10);static API_STATUS: AtomicU8 = AtomicU8::new(0);static IN_FLIGHT_REQUESTS: AtomicUsize = AtomicUsize::new(0);static IN_FLIGHT_CHAT_STREAMS: AtomicUsize = AtomicUsize::new(0);+static IN_FLIGHT_PAGE_EMBEDS: AtomicUsize = AtomicUsize::new(0);static APP_STATE_CACHE: OnceLock<Mutex<Option<CachedAppState>>> = OnceLock::new();static RATE_LIMIT: OnceLock<Mutex<VecDeque<Instant>>> = OnceLock::new();@@ -323,7 +325,7 @@ fn handle_request(// retry instantly the way 401 would.return err(503, "API server is disabled in Settings → API Server");}- if is_agent_chat_request(&method, &path) && !is_token_authorized(app, query, headers) {+ if is_token_required_request(&method, &path) && !is_token_authorized(app, query, headers) {return err(401, "Unauthorized");}if !is_authorized(app, query, headers) {@@ -357,6 +359,9 @@ fn handle_request((&Method::Post, ["projects", project_id, "sources", "rescan"]) => {handle_rescan(app, project_id)}+ (&Method::Post, ["projects", project_id, "pages", "embed"]) => {+ handle_embed_page(app, project_id, body)+ }(&Method::Post, ["projects", project_id, "chat"]) => handle_chat(app, project_id, body),(&Method::Post, ["projects", project_id, "chat", session_id, "cancel"]) => {handle_cancel_chat(app, project_id, session_id)@@ -401,6 +406,16 @@ fn is_agent_chat_request(method: &Method, path: &str) -> bool {)}+fn is_token_required_request(method: &Method, path: &str) -> bool {+ if is_agent_chat_request(method, path) {+ return true;+ }+ let Some(parts) = api_path_parts(path) else {+ return false;+ };+ method == &Method::Post && matches!(parts.as_slice(), ["projects", _, "pages", "embed"])+}+fn chat_project_id<'a>(method: &Method, path: &'a str) -> Option<&'a str> {if method != &Method::Post {return None;@@ -1743,6 +1758,75 @@ struct SearchRequest {query_embedding: Option<Vec<f32>>,}+#[derive(Deserialize)]+#[serde(rename_all = "camelCase")]+struct EmbedPageRequest {+ path: String,+ #[serde(default)]+ force: bool,+}++struct PageEmbedSlot;++impl Drop for PageEmbedSlot {+ fn drop(&mut self) {+ IN_FLIGHT_PAGE_EMBEDS.fetch_sub(1, Ordering::Relaxed);+ }+}++fn try_acquire_page_embed_slot() -> Option<PageEmbedSlot> {+ IN_FLIGHT_PAGE_EMBEDS+ .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {+ (current < MAX_IN_FLIGHT_PAGE_EMBEDS).then_some(current + 1)+ })+ .ok()+ .map(|_| PageEmbedSlot)+}++fn handle_embed_page(app: &AppHandle, project_id: &str, body: &str) -> ApiResponse {+ let project = match resolve_project(app, project_id) {+ Ok(project) => project,+ Err(e) => return err(404, e),+ };+ let req: EmbedPageRequest = match serde_json::from_str(body) {+ Ok(req) => req,+ Err(e) => return err(400, format!("Invalid JSON: {e}")),+ };+ if req.path.trim().is_empty() {+ return err(400, "path is required");+ }+ let Some(config) = load_embedding_config(app) else {+ return err(400, "Embedding is not configured");+ };+ let Some(_slot) = try_acquire_page_embed_slot() else {+ return err(503, "Too many page indexing requests are already running");+ };+ let result = tauri::async_runtime::block_on(commands::page_embedding::embed_wiki_page(+ &project.path,+ &req.path,+ config,+ req.force,+ ));+ match result {+ Ok(result) => ok(json!({+ "ok": true,+ "projectId": project.id,+ "result": result,+ })),+ Err(error) => {+ let status = match error.kind {+ commands::page_embedding::PageEmbeddingErrorKind::InvalidRequest => 400,+ commands::page_embedding::PageEmbeddingErrorKind::NotFound => 404,+ commands::page_embedding::PageEmbeddingErrorKind::Provider => 502,+ commands::page_embedding::PageEmbeddingErrorKind::Storage => 500,+ commands::page_embedding::PageEmbeddingErrorKind::Conflict => 409,+ commands::page_embedding::PageEmbeddingErrorKind::Timeout => 504,+ };+ err(status, error.message)+ }+ }+}+fn handle_search(app: &AppHandle, project_id: &str, body: &str) -> ApiResponse {let project = match resolve_project(app, project_id) {Ok(project) => project,@@ -3094,6 +3178,26 @@ mod tests {));}+ #[test]+ fn paid_or_mutating_agent_routes_always_require_a_token() {+ assert!(is_token_required_request(+ &Method::Post,+ "/api/v1/projects/current/pages/embed"+ ));+ assert!(is_token_required_request(+ &Method::Post,+ "/api/v1/projects/current/chat"+ ));+ assert!(!is_token_required_request(+ &Method::Post,+ "/api/v1/projects/current/search"+ ));+ assert!(!is_token_required_request(+ &Method::Get,+ "/api/v1/projects/current/pages/embed"+ ));+ }+#[test]fn chat_streaming_is_enabled_by_body_or_accept_header() {let path = "/api/v1/projects/current/chat";diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 5adf4416..d741809d 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -7,6 +7,7 @@ pub mod extract_images;pub mod file_history;pub mod file_sync;pub mod fs;+pub mod page_embedding;pub mod project;pub mod project_maintenance;pub mod search;diff --git a/src-tauri/src/commands/page_embedding.rs b/src-tauri/src/commands/page_embedding.rsnew file mode 100644index 00000000..d8048446--- /dev/null+++ b/src-tauri/src/commands/page_embedding.rs@@ -0,0 +1,899 @@+use std::collections::BTreeMap;+use std::fs;+use std::path::{Component, Path, PathBuf};+use std::sync::{Mutex, OnceLock};+use std::time::Duration;++use serde::Serialize;+use sha2::{Digest, Sha256};+use walkdir::WalkDir;++use super::search::{+ fetch_embedding_batch, fetch_embedding_with_retry, supports_embedding_batch,+ SearchEmbeddingConfig,+};+use super::vectorstore::{self, ChunkUpsertInput};++const DEFAULT_CHUNK_CHARS: usize = 1_000;+const DEFAULT_OVERLAP_CHARS: usize = 200;+const MIN_CHUNK_CHARS: usize = 64;+const MAX_CHUNK_CHARS: usize = 32_000;+const MAX_PAGE_BYTES: u64 = 2 * 1024 * 1024;+const MAX_PAGE_CHUNKS: usize = 512;+const EMBEDDING_BATCH_SIZE: usize = 64;+const PROVIDER_PHASE_TIMEOUT: Duration = Duration::from_secs(300);+const REVISION_FILE: &str = ".llm-wiki/embedding-revisions.json";+static REVISION_LOCK: OnceLock<Mutex<()>> = OnceLock::new();++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PageEmbeddingResult {+ pub path: String,+ pub page_id: String,+ pub revision: String,+ pub chunks: usize,+ pub vectors_written: usize,+ pub status: String,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum PageEmbeddingErrorKind {+ InvalidRequest,+ NotFound,+ Provider,+ Storage,+ Conflict,+ Timeout,+}++#[derive(Debug, Clone)]+pub struct PageEmbeddingError {+ pub kind: PageEmbeddingErrorKind,+ pub message: String,+}++impl PageEmbeddingError {+ fn new(kind: PageEmbeddingErrorKind, message: impl Into<String>) -> Self {+ Self {+ kind,+ message: message.into(),+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq)]+struct MarkdownChunk {+ text: String,+ heading_path: String,+}++pub async fn embed_wiki_page(+ project_path: &str,+ relative_path: &str,+ config: SearchEmbeddingConfig,+ force: bool,+) -> Result<PageEmbeddingResult, PageEmbeddingError> {+ if !config.enabled || config.model.trim().is_empty() {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "Embedding is not enabled or no embedding model is configured",+ ));+ }++ let (page_path, normalized_path) = resolve_wiki_markdown_path(project_path, relative_path)?;+ let metadata = fs::metadata(&page_path).map_err(|err| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::NotFound,+ format!("Failed to inspect wiki page: {err}"),+ )+ })?;+ if metadata.len() > MAX_PAGE_BYTES {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ format!(+ "Wiki page exceeds the {} MiB indexing limit",+ MAX_PAGE_BYTES / 1024 / 1024+ ),+ ));+ }+ let content = fs::read_to_string(&page_path).map_err(|err| {+ let kind = if err.kind() == std::io::ErrorKind::NotFound {+ PageEmbeddingErrorKind::NotFound+ } else {+ PageEmbeddingErrorKind::InvalidRequest+ };+ PageEmbeddingError::new(+ kind,+ format!("Failed to read wiki page as UTF-8 text: {err}"),+ )+ })?;++ let page_id = page_path+ .file_stem()+ .and_then(|value| value.to_str())+ .filter(|value| !value.is_empty())+ .ok_or_else(|| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "Invalid wiki page name",+ )+ })?+ .to_string();+ vectorstore::validate_page_id_for_v2(&page_id)+ .map_err(|err| PageEmbeddingError::new(PageEmbeddingErrorKind::InvalidRequest, err))?;+ if matches!(+ page_id.to_ascii_lowercase().as_str(),+ "index" | "log" | "overview"+ ) {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "Aggregate wiki pages index.md, log.md, and overview.md are maintained by the app and are not vector-indexed",+ ));+ }+ ensure_unique_page_stem(project_path, &page_path, &page_id)?;++ let revision = format!("sha256:{:x}", Sha256::digest(content.as_bytes()));+ let fingerprint = embedding_fingerprint(&revision, &config);+ if !force {+ let existing_chunks = vectorstore::vector_page_revision_match(+ project_path,+ &page_id,+ &normalized_path,+ &fingerprint,+ )+ .await+ .map_err(|err| PageEmbeddingError::new(PageEmbeddingErrorKind::Storage, err))?;+ if let Some(existing_chunks) = existing_chunks {+ return Ok(PageEmbeddingResult {+ path: normalized_path,+ page_id,+ revision,+ chunks: existing_chunks,+ vectors_written: 0,+ status: "unchanged".to_string(),+ });+ }+ }++ let title = extract_title(&content, &page_id);+ let chunk_chars = config+ .max_chunk_chars+ .unwrap_or(DEFAULT_CHUNK_CHARS)+ .clamp(MIN_CHUNK_CHARS, MAX_CHUNK_CHARS);+ let overlap_chars = config+ .overlap_chunk_chars+ .unwrap_or(DEFAULT_OVERLAP_CHARS)+ .min(chunk_chars / 2);+ let chunks = chunk_markdown(&content, chunk_chars, overlap_chars);+ if chunks.is_empty() {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "Wiki page has no indexable content",+ ));+ }+ if chunks.len() > MAX_PAGE_CHUNKS {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ format!(+ "Wiki page produces {} chunks, exceeding the {} chunk limit; increase maxChunkChars or split the page",+ chunks.len(), MAX_PAGE_CHUNKS+ ),+ ));+ }++ // Only provider work is cancellable. Once storage replacement starts, let+ // it complete so a timeout cannot remove the previous page index midway.+ let rows = tokio::time::timeout(+ PROVIDER_PHASE_TIMEOUT,+ prepare_embedding_rows(&title, &chunks, &config),+ )+ .await+ .map_err(|_| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::Timeout,+ format!(+ "Embedding provider timed out after {} seconds",+ PROVIDER_PHASE_TIMEOUT.as_secs()+ ),+ )+ })??;++ vectorstore::vector_upsert_chunks_with_revision(+ project_path,+ &page_id,+ rows,+ &normalized_path,+ &fingerprint,+ )+ .await+ .map_err(|err| PageEmbeddingError::new(PageEmbeddingErrorKind::Storage, err))?;+ Ok(PageEmbeddingResult {+ path: normalized_path,+ page_id,+ revision,+ chunks: chunks.len(),+ vectors_written: chunks.len(),+ status: "indexed".to_string(),+ })+}++async fn prepare_embedding_rows(+ title: &str,+ chunks: &[MarkdownChunk],+ config: &SearchEmbeddingConfig,+) -> Result<Vec<ChunkUpsertInput>, PageEmbeddingError> {+ // Build every vector before replacing the page in LanceDB. A provider+ // failure therefore leaves the previous, known-good page index intact.+ let mut rows = Vec::with_capacity(chunks.len());+ if supports_embedding_batch(&config) {+ for batch in chunks.chunks(EMBEDDING_BATCH_SIZE) {+ let texts = batch+ .iter()+ .map(|chunk| enrich_chunk(&title, chunk))+ .collect::<Vec<_>>();+ let embeddings = fetch_embedding_batch(&texts, &config)+ .await+ .map_err(|err| PageEmbeddingError::new(PageEmbeddingErrorKind::Provider, err))?;+ if embeddings.len() != batch.len() {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::Provider,+ "Embedding provider returned an incomplete batch",+ ));+ }+ for (chunk, embedding) in batch.iter().zip(embeddings) {+ rows.push(chunk_row(rows.len(), chunk, embedding));+ }+ }+ } else {+ for (index, chunk) in chunks.iter().enumerate() {+ let embedding_text = enrich_chunk(&title, chunk);+ let embedding = fetch_embedding_with_retry(&embedding_text, &config, 3)+ .await+ .map_err(|err| PageEmbeddingError::new(PageEmbeddingErrorKind::Provider, err))?;+ rows.push(chunk_row(index, chunk, embedding));+ }+ }+ Ok(rows)+}++fn chunk_row(index: usize, chunk: &MarkdownChunk, embedding: Vec<f32>) -> ChunkUpsertInput {+ ChunkUpsertInput {+ chunk_index: index as u32,+ chunk_text: chunk.text.clone(),+ heading_path: chunk.heading_path.clone(),+ embedding,+ }+}++fn embedding_fingerprint(revision: &str, config: &SearchEmbeddingConfig) -> String {+ let signature = serde_json::json!({+ "revision": revision,+ "endpoint": config.endpoint.trim(),+ "model": config.model.trim(),+ "outputDimensionality": config.output_dimensionality,+ "extraHeaders": config.extra_headers,+ "maxChunkChars": config.max_chunk_chars.unwrap_or(DEFAULT_CHUNK_CHARS),+ "overlapChunkChars": config.overlap_chunk_chars.unwrap_or(DEFAULT_OVERLAP_CHARS),+ });+ format!(+ "sha256:{:x}",+ Sha256::digest(signature.to_string().as_bytes())+ )+}++fn ensure_unique_page_stem(+ project_path: &str,+ page_path: &Path,+ page_id: &str,+) -> Result<(), PageEmbeddingError> {+ let wiki_root = fs::canonicalize(Path::new(project_path).join("wiki")).map_err(|err| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::NotFound,+ format!("Failed to resolve project wiki directory: {err}"),+ )+ })?;+ let mut collisions = WalkDir::new(wiki_root)+ .follow_links(false)+ .into_iter()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_type().is_file())+ .filter(|entry| {+ entry+ .path()+ .extension()+ .and_then(|value| value.to_str())+ .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))+ && entry+ .path()+ .file_stem()+ .and_then(|value| value.to_str())+ .is_some_and(|stem| stem.eq_ignore_ascii_case(page_id))+ })+ .filter_map(|entry| fs::canonicalize(entry.path()).ok())+ .filter(|path| path != page_path);+ if let Some(collision) = collisions.next() {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::Conflict,+ format!(+ "Cannot index this page because another wiki page has the same filename stem: {}",+ collision.to_string_lossy()+ ),+ ));+ }+ Ok(())+}++fn revision_path(project_path: &str) -> PathBuf {+ Path::new(project_path).join(REVISION_FILE)+}++fn load_revisions(project_path: &str) -> BTreeMap<String, String> {+ fs::read_to_string(revision_path(project_path))+ .ok()+ .and_then(|raw| serde_json::from_str(&raw).ok())+ .unwrap_or_default()+}++pub(crate) fn load_revision(project_path: &str, page_path: &str) -> Option<String> {+ let _guard = REVISION_LOCK.get_or_init(|| Mutex::new(())).lock().ok()?;+ load_revisions(project_path).get(page_path).cloned()+}++pub(crate) fn save_revision(+ project_path: &str,+ page_path: &str,+ revision: &str,+) -> Result<(), String> {+ let _guard = REVISION_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .map_err(|_| "Embedding revision lock is poisoned".to_string())?;+ let path = revision_path(project_path);+ let parent = path+ .parent()+ .ok_or_else(|| "Invalid embedding revision path".to_string())?;+ fs::create_dir_all(parent)+ .map_err(|err| format!("Failed to create revision directory: {err}"))?;+ let mut revisions = load_revisions(project_path);+ revisions.retain(|relative, _| Path::new(project_path).join(relative).is_file());+ revisions.insert(page_path.to_string(), revision.to_string());+ let serialized = serde_json::to_string_pretty(&revisions)+ .map_err(|err| format!("Failed to serialize embedding revisions: {err}"))?;+ let temp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));+ fs::write(&temp, serialized)+ .map_err(|err| format!("Failed to write embedding revision temp file: {err}"))?;+ if let Err(err) = fs::rename(&temp, &path) {+ // Windows does not replace an existing destination. The metadata is+ // only an optimization; restore the old valid file if replacement fails.+ if path.exists() {+ let previous = fs::read(&path).ok();+ fs::remove_file(&path).map_err(|remove_err| {+ format!("Failed to replace embedding revisions: {remove_err}")+ })?;+ if let Err(rename_err) = fs::rename(&temp, &path) {+ if let Some(previous) = previous {+ let _ = fs::write(&path, previous);+ }+ return Err(format!(+ "Failed to replace embedding revisions: {rename_err}"+ ));+ }+ } else {+ let _ = fs::remove_file(&temp);+ return Err(format!("Failed to save embedding revisions: {err}"));+ }+ }+ Ok(())+}++pub(crate) fn invalidate_page_revision(project_path: &str, page_id: &str) -> Result<(), String> {+ let _guard = REVISION_LOCK+ .get_or_init(|| Mutex::new(()))+ .lock()+ .map_err(|_| "Embedding revision lock is poisoned".to_string())?;+ let path = revision_path(project_path);+ let mut revisions = load_revisions(project_path);+ let original_len = revisions.len();+ revisions.retain(|relative, _| {+ Path::new(relative)+ .file_stem()+ .and_then(|value| value.to_str())+ != Some(page_id)+ });+ if revisions.len() == original_len {+ return Ok(());+ }+ let serialized = serde_json::to_string_pretty(&revisions)+ .map_err(|err| format!("Failed to serialize embedding revisions: {err}"))?;+ fs::write(path, serialized)+ .map_err(|err| format!("Failed to invalidate embedding revision: {err}"))+}++fn resolve_wiki_markdown_path(+ project_path: &str,+ relative_path: &str,+) -> Result<(PathBuf, String), PageEmbeddingError> {+ let raw = relative_path.trim().replace('\\', "/");+ if raw.is_empty() {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "path is required",+ ));+ }+ let relative = Path::new(&raw);+ if relative.is_absolute()+ || relative.components().any(|component| {+ matches!(+ component,+ Component::ParentDir | Component::RootDir | Component::Prefix(_)+ )+ })+ || relative.components().next() != Some(Component::Normal("wiki".as_ref()))+ || relative+ .extension()+ .and_then(|value| value.to_str())+ .map(str::to_ascii_lowercase)+ .as_deref()+ != Some("md")+ {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "path must be a project-relative Markdown file under wiki/",+ ));+ }++ let project = fs::canonicalize(project_path).map_err(|err| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::NotFound,+ format!("Failed to resolve project path: {err}"),+ )+ })?;+ let wiki = fs::canonicalize(project.join("wiki")).map_err(|err| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::NotFound,+ format!("Failed to resolve project wiki directory: {err}"),+ )+ })?;+ let page = fs::canonicalize(project.join(relative)).map_err(|err| {+ PageEmbeddingError::new(+ PageEmbeddingErrorKind::NotFound,+ format!("Wiki page not found: {err}"),+ )+ })?;+ if !page.starts_with(&wiki)+ || !page.is_file()+ || !page+ .extension()+ .and_then(|value| value.to_str())+ .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))+ {+ return Err(PageEmbeddingError::new(+ PageEmbeddingErrorKind::InvalidRequest,+ "path must resolve to a file inside the project wiki directory",+ ));+ }+ let normalized = page+ .strip_prefix(&project)+ .map_err(|_| {+ PageEmbeddingError::new(PageEmbeddingErrorKind::InvalidRequest, "Invalid page path")+ })?+ .to_string_lossy()+ .replace('\\', "/");+ Ok((page, normalized))+}++fn extract_title(content: &str, fallback: &str) -> String {+ let normalized = content.replace("\r\n", "\n");+ if let Some(frontmatter) = leading_frontmatter(&normalized) {+ for line in frontmatter.lines() {+ if let Some(value) = line.trim().strip_prefix("title:") {+ let title = value.trim().trim_matches(['\"', '\'']);+ if !title.is_empty() {+ return title.to_string();+ }+ }+ }+ }+ normalized+ .lines()+ .find_map(|line| line.trim().strip_prefix("# ").map(str::trim))+ .filter(|title| !title.is_empty())+ .unwrap_or(fallback)+ .to_string()+}++fn leading_frontmatter(content: &str) -> Option<&str> {+ let rest = content.strip_prefix("---\n")?;+ let (end, _) = find_frontmatter_close(rest)?;+ Some(&rest[..end])+}++fn strip_frontmatter(content: &str) -> &str {+ let Some(rest) = content.strip_prefix("---\n") else {+ return content;+ };+ let Some((end, close_len)) = find_frontmatter_close(rest) else {+ return content;+ };+ let after_fence = &rest[end + close_len..];+ after_fence.strip_prefix('\n').unwrap_or(after_fence)+}++fn find_frontmatter_close(rest: &str) -> Option<(usize, usize)> {+ let mut offset = 0usize;+ for line in rest.split_inclusive('\n') {+ if line.trim_end_matches(['\r', '\n']).trim() == "---" {+ return Some((offset, line.len()));+ }+ offset += line.len();+ }+ (rest.trim() == "---").then_some((0, rest.len()))+}++fn chunk_markdown(content: &str, target_chars: usize, overlap_chars: usize) -> Vec<MarkdownChunk> {+ let normalized = content.replace("\r\n", "\n");+ let body = strip_frontmatter(&normalized);+ let mut chunks = Vec::new();+ let mut heading_stack: Vec<(usize, String)> = Vec::new();+ let mut heading_path = String::new();+ let mut section = String::new();++ let flush = |section: &mut String, heading_path: &str, chunks: &mut Vec<MarkdownChunk>| {+ let text = section.trim();+ if !text.is_empty() {+ for piece in split_preserving_atomic_blocks(text, target_chars, overlap_chars) {+ chunks.push(MarkdownChunk {+ text: piece,+ heading_path: heading_path.to_string(),+ });+ }+ }+ section.clear();+ };++ let mut open_fence: Option<(char, usize)> = None;+ for line in body.lines() {+ let trimmed = line.trim_start();+ if let Some((marker, width)) = fence_marker(trimmed) {+ match open_fence {+ None => open_fence = Some((marker, width)),+ Some((open, open_width)) if open == marker && width >= open_width => {+ open_fence = None+ }+ Some(_) => {}+ }+ }+ let heading = if open_fence.is_none() {+ parse_heading(line)+ } else {+ None+ };+ if let Some((level, title)) = heading {+ flush(&mut section, &heading_path, &mut chunks);+ heading_stack.retain(|(existing, _)| *existing < level);+ heading_stack.push((level, title.to_string()));+ heading_path = heading_stack+ .iter()+ .map(|(level, title)| format!("{} {}", "#".repeat(*level), title))+ .collect::<Vec<_>>()+ .join(" > ");+ }+ if !section.is_empty() {+ section.push('\n');+ }+ section.push_str(line);+ }+ flush(&mut section, &heading_path, &mut chunks);+ chunks+}++fn split_preserving_atomic_blocks(+ text: &str,+ target_chars: usize,+ overlap_chars: usize,+) -> Vec<String> {+ let lines = text.lines().collect::<Vec<_>>();+ let mut chunks = Vec::new();+ let mut normal = Vec::new();+ let mut index = 0usize;++ let flush_normal = |normal: &mut Vec<&str>, chunks: &mut Vec<String>| {+ if normal.is_empty() {+ return;+ }+ chunks.extend(split_with_overlap(+ &normal.join("\n"),+ target_chars,+ overlap_chars,+ ));+ normal.clear();+ };++ while index < lines.len() {+ if let Some((marker, width)) = fence_marker(lines[index]) {+ flush_normal(&mut normal, &mut chunks);+ let start = index;+ index += 1;+ while index < lines.len() {+ let is_close =+ fence_marker(lines[index]).is_some_and(|(candidate, candidate_width)| {+ candidate == marker && candidate_width >= width+ });+ index += 1;+ if is_close {+ break;+ }+ }+ push_atomic_chunk(&mut chunks, lines[start..index].join("\n"));+ continue;+ }++ if lines[index].trim_start().starts_with('|') {+ flush_normal(&mut normal, &mut chunks);+ let start = index;+ while index < lines.len() && lines[index].trim_start().starts_with('|') {+ index += 1;+ }+ push_atomic_chunk(&mut chunks, lines[start..index].join("\n"));+ continue;+ }++ normal.push(lines[index]);+ index += 1;+ }+ flush_normal(&mut normal, &mut chunks);+ chunks+ .into_iter()+ .filter(|chunk| !chunk.trim().is_empty())+ .collect()+}++fn push_atomic_chunk(chunks: &mut Vec<String>, chunk: String) {+ if chunk.chars().count() <= MAX_CHUNK_CHARS {+ chunks.push(chunk);+ } else {+ // Preserve ordinary code/table blocks as a unit, but never send an+ // unbounded payload to an embedding provider.+ chunks.extend(split_with_overlap(+ &chunk,+ MAX_CHUNK_CHARS,+ DEFAULT_OVERLAP_CHARS,+ ));+ }+}++fn fence_marker(line: &str) -> Option<(char, usize)> {+ let trimmed = line.trim_start();+ let marker = trimmed.chars().next()?;+ if marker != '`' && marker != '~' {+ return None;+ }+ let width = trimmed.chars().take_while(|ch| *ch == marker).count();+ (width >= 3).then_some((marker, width))+}++fn parse_heading(line: &str) -> Option<(usize, &str)> {+ let hashes = line.chars().take_while(|ch| *ch == '#').count();+ if !(1..=6).contains(&hashes) || line.chars().nth(hashes) != Some(' ') {+ return None;+ }+ let title = line[hashes + 1..].trim();+ (!title.is_empty()).then_some((hashes, title))+}++fn split_with_overlap(text: &str, target_chars: usize, overlap_chars: usize) -> Vec<String> {+ let chars: Vec<char> = text.chars().collect();+ if chars.len() <= target_chars {+ return vec![text.to_string()];+ }+ let mut out = Vec::new();+ let mut start = 0usize;+ while start < chars.len() {+ let hard_end = (start + target_chars).min(chars.len());+ let end = if hard_end < chars.len() {+ (start + target_chars / 2..hard_end)+ .rev()+ .find(|index| {+ chars[*index].is_whitespace()+ || matches!(+ chars[*index],+ '。' | '!' | '?' | '.' | '!' | '?' | ';' | ';'+ )+ })+ .map(|index| index + 1)+ .unwrap_or(hard_end)+ } else {+ hard_end+ };+ let piece: String = chars[start..end].iter().collect();+ if !piece.trim().is_empty() {+ out.push(piece.trim().to_string());+ }+ if end == chars.len() {+ break;+ }+ start = end.saturating_sub(overlap_chars).max(start + 1);+ }+ out+}++fn enrich_chunk(title: &str, chunk: &MarkdownChunk) -> String {+ [title.trim(), chunk.heading_path.trim(), chunk.text.trim()]+ .into_iter()+ .filter(|part| !part.is_empty())+ .collect::<Vec<_>>()+ .join("\n\n")+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::collections::BTreeMap;+ use uuid::Uuid;++ fn project() -> PathBuf {+ let root = std::env::temp_dir().join(format!("llm-wiki-page-embed-{}", Uuid::new_v4()));+ fs::create_dir_all(root.join("wiki/nested")).unwrap();+ root+ }++ fn embedding_config(model: &str) -> SearchEmbeddingConfig {+ SearchEmbeddingConfig {+ enabled: true,+ endpoint: "https://example.com/v1/embeddings".to_string(),+ api_key: "secret".to_string(),+ model: model.to_string(),+ output_dimensionality: Some(768.0),+ extra_headers: Some(BTreeMap::from([("X-Route".to_string(), "a".to_string())])),+ max_chunk_chars: Some(1_000),+ overlap_chunk_chars: Some(200),+ }+ }++ #[test]+ fn path_guard_accepts_only_existing_markdown_inside_wiki() {+ let root = project();+ fs::write(root.join("wiki/nested/page.md"), "# Page").unwrap();+ fs::write(root.join("outside.md"), "# Outside").unwrap();++ let (_, relative) =+ resolve_wiki_markdown_path(root.to_str().unwrap(), "wiki\\nested/page.md").unwrap();+ assert_eq!(relative, "wiki/nested/page.md");+ assert!(resolve_wiki_markdown_path(root.to_str().unwrap(), "../outside.md").is_err());+ assert!(resolve_wiki_markdown_path(root.to_str().unwrap(), "outside.md").is_err());+ assert!(resolve_wiki_markdown_path(root.to_str().unwrap(), "wiki/missing.md").is_err());+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn chunker_strips_crlf_frontmatter_and_preserves_heading_context() {+ let input =+ "---\r\ntitle: 测试页面\r\n---\r\n# 第一章\r\n\r\n内容一。\r\n## 第二节\r\n内容二。";+ let chunks = chunk_markdown(input, 64, 8);+ assert_eq!(extract_title(input, "fallback"), "测试页面");+ assert!(chunks.iter().all(|chunk| !chunk.text.contains("title:")));+ assert!(chunks+ .iter()+ .any(|chunk| chunk.heading_path.contains("# 第一章")));+ assert!(chunks+ .iter()+ .any(|chunk| chunk.heading_path.contains("## 第二节")));+ }++ #[test]+ fn cjk_hard_split_uses_character_boundaries_and_overlap() {+ let text = "中文内容用于验证字符边界不会发生截断异常。".repeat(20);+ let chunks = split_with_overlap(&text, 64, 8);+ assert!(chunks.len() > 1);+ assert!(chunks.iter().all(|chunk| chunk.chars().count() <= 64));+ for pair in chunks.windows(2) {+ let suffix: String = pair[0]+ .chars()+ .rev()+ .take(8)+ .collect::<Vec<_>>()+ .into_iter()+ .rev()+ .collect();+ assert!(pair[1].starts_with(&suffix));+ }+ }++ #[test]+ fn fingerprint_changes_with_embedding_semantics_but_not_api_key_rotation() {+ let base = embedding_config("model-a");+ let mut changed_model = base.clone();+ changed_model.model = "model-b".to_string();+ let mut rotated_key = base.clone();+ rotated_key.api_key = "rotated".to_string();+ assert_ne!(+ embedding_fingerprint("sha256:content", &base),+ embedding_fingerprint("sha256:content", &changed_model)+ );+ assert_eq!(+ embedding_fingerprint("sha256:content", &base),+ embedding_fingerprint("sha256:content", &rotated_key)+ );+ }++ #[test]+ fn frontmatter_close_requires_a_standalone_fence() {+ let input = "---\ntitle: Kept\nnote: ---not-a-fence\n---\n# Body";+ assert_eq!(extract_title(input, "fallback"), "Kept");+ assert_eq!(strip_frontmatter(input), "# Body");+ }++ #[test]+ fn duplicate_stems_in_different_wiki_folders_are_rejected() {+ let root = project();+ let first = root.join("wiki/nested/page.md");+ fs::write(&first, "# First").unwrap();+ fs::create_dir_all(root.join("wiki/other")).unwrap();+ fs::write(root.join("wiki/other/page.md"), "# Second").unwrap();+ let error = ensure_unique_page_stem(root.to_str().unwrap(), &first, "page").unwrap_err();+ assert_eq!(error.kind, PageEmbeddingErrorKind::Conflict);+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn chunker_keeps_fenced_code_and_tables_atomic() {+ let code = format!("```rust\n{}\n```", "let value = 1;\n".repeat(12));+ let table = format!(+ "| Name | Value |\n| --- | --- |\n{}",+ "| A | B |\n".repeat(12)+ );+ let input = format!("# Page\n\nBefore text.\n\n{code}\n\n{table}\n\nAfter text.");++ let chunks = chunk_markdown(&input, 64, 8);++ assert!(chunks.iter().any(|chunk| chunk.text.trim() == code.trim()));+ assert!(chunks.iter().any(|chunk| chunk.text.trim() == table.trim()));+ assert_eq!(+ chunks+ .iter()+ .filter(|chunk| chunk.text.contains("```rust"))+ .count(),+ 1+ );+ assert_eq!(+ chunks+ .iter()+ .filter(|chunk| chunk.text.contains("| Name | Value |"))+ .count(),+ 1+ );+ }++ #[test]+ fn oversized_atomic_blocks_respect_the_hard_provider_limit() {+ let input = format!("```text\n{}\n", "x".repeat(MAX_CHUNK_CHARS + 500));+ let chunks = chunk_markdown(&input, 1_000, 200);++ assert!(chunks.len() > 1);+ assert!(chunks+ .iter()+ .all(|chunk| chunk.text.chars().count() <= MAX_CHUNK_CHARS));+ }++ #[test]+ fn saving_revision_prunes_deleted_pages() {+ let root = project();+ fs::write(root.join("wiki/current.md"), "# Current").unwrap();+ fs::create_dir_all(root.join(".llm-wiki")).unwrap();+ fs::write(+ revision_path(root.to_str().unwrap()),+ r#"{"wiki/deleted.md":"old"}"#,+ )+ .unwrap();++ save_revision(root.to_str().unwrap(), "wiki/current.md", "sha256:current").unwrap();+ let revisions = load_revisions(root.to_str().unwrap());++ assert_eq!(revisions.len(), 1);+ assert_eq!(+ revisions.get("wiki/current.md").map(String::as_str),+ Some("sha256:current")+ );+ let _ = fs::remove_dir_all(root);+ }+}diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 47a1de39..f3604499 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -98,6 +98,10 @@ pub struct SearchEmbeddingConfig {/// by the client.#[serde(default)]pub extra_headers: Option<BTreeMap<String, String>>,+ #[serde(default)]+ pub max_chunk_chars: Option<usize>,+ #[serde(default)]+ pub overlap_chunk_chars: Option<usize>,}#[tauri::command]@@ -1059,7 +1063,7 @@ pub fn extract_image_refs(content: &str) -> Vec<SearchImageRef> {out}-async fn fetch_embedding_with_retry(+pub(crate) async fn fetch_embedding_with_retry(text: &str,cfg: &SearchEmbeddingConfig,max_retries: usize,@@ -1093,7 +1097,7 @@ async fn fetch_embedding_with_retry(}}-async fn fetch_embedding_batch(+pub(crate) async fn fetch_embedding_batch(texts: &[String],cfg: &SearchEmbeddingConfig,) -> Result<Vec<Vec<f32>>, String> {@@ -1159,6 +1163,10 @@ async fn fetch_embedding_batch(parse_embedding_batch_values(&data, texts.len())}+pub(crate) fn supports_embedding_batch(cfg: &SearchEmbeddingConfig) -> bool {+ !is_google_embedding_config(cfg) && !is_doubao_multimodal_embedding_config(cfg)+}+fn parse_embedding_batch_values(data: &Value, expected: usize) -> Result<Vec<Vec<f32>>, String> {let entries = data.get("data")@@ -1734,6 +1742,8 @@ mod tests {model: "gemini-embedding-001".to_string(),output_dimensionality: Some(768.0),extra_headers: None,+ max_chunk_chars: None,+ overlap_chunk_chars: None,};let endpoint = google_embedding_endpoint(&cfg);@@ -1756,6 +1766,8 @@ mod tests {model: "doubao-embedding-text-240715".to_string(),output_dimensionality: None,extra_headers: None,+ max_chunk_chars: None,+ overlap_chunk_chars: None,};assert_eq!(volcengine_embedding_endpoint(&cfg),@@ -1782,6 +1794,8 @@ mod tests {model: "doubao-embedding-vision".to_string(),output_dimensionality: None,extra_headers: None,+ max_chunk_chars: None,+ overlap_chunk_chars: None,};assert_eq!(@@ -1805,6 +1819,8 @@ mod tests {model: "doubao-embedding-text-240715".to_string(),output_dimensionality: None,extra_headers: None,+ max_chunk_chars: None,+ overlap_chunk_chars: None,};assert_eq!(volcengine_embedding_endpoint(&cfg),@@ -1840,6 +1856,8 @@ mod tests {model: "doubao-embedding-vision".to_string(),output_dimensionality: None,extra_headers: None,+ max_chunk_chars: None,+ overlap_chunk_chars: None,};assert!(is_doubao_multimodal_embedding_config(&cfg));diff --git a/src-tauri/src/commands/vectorstore.rs b/src-tauri/src/commands/vectorstore.rsindex 6342434b..ab1c7df3 100644--- a/src-tauri/src/commands/vectorstore.rs+++ b/src-tauri/src/commands/vectorstore.rs@@ -1,5 +1,6 @@use arrow_array::{- ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, StringArray, UInt32Array,+ ArrayRef, FixedSizeListArray, Float32Array, RecordBatch, RecordBatchIterator, StringArray,+ UInt32Array,};use arrow_schema::{DataType, Field, Schema};use chrono::Duration;@@ -375,7 +376,7 @@ pub async fn vector_count(project_path: String) -> Result<usize, String> {// plus exposes the chunk metadata for a future "matched in X section" UI.// ──────────────────────────────────────────────────────────────────────────-fn validate_page_id_for_v2(page_id: &str) -> Result<(), String> {+pub(crate) fn validate_page_id_for_v2(page_id: &str) -> Result<(), String> {validate_page_id_common(page_id)}@@ -464,66 +465,131 @@ pub async fn vector_upsert_chunks(chunks: Vec<ChunkUpsertInput>,) -> Result<(), String> {run_guarded_async("vector_upsert_chunks", async move {- validate_page_id_for_v2(&page_id)?;- let lock = vectorstore_v2_lock(&project_path);- let _guard = lock.write().await;+ vector_upsert_chunks_inner(&project_path, &page_id, chunks, None).await+ })+ .await+}- if chunks.is_empty() {- return Ok(());- }+pub(crate) async fn vector_upsert_chunks_with_revision(+ project_path: &str,+ page_id: &str,+ chunks: Vec<ChunkUpsertInput>,+ page_path: &str,+ fingerprint: &str,+) -> Result<(), String> {+ vector_upsert_chunks_inner(+ project_path,+ page_id,+ chunks,+ Some((page_path, fingerprint)),+ )+ .await+}- let dim = chunks[0].embedding.len() as i32;- if dim == 0 {- return Err("Chunk #0 has empty embedding".to_string());- }+async fn vector_upsert_chunks_inner(+ project_path: &str,+ page_id: &str,+ chunks: Vec<ChunkUpsertInput>,+ revision: Option<(&str, &str)>,+) -> Result<(), String> {+ validate_page_id_for_v2(&page_id)?;+ let lock = vectorstore_v2_lock(project_path);+ let _guard = lock.write().await;- let db = connect(&db_path(&project_path))+ if chunks.is_empty() {+ return Ok(());+ }++ let dim = chunks[0].embedding.len() as i32;+ if dim == 0 {+ return Err("Chunk #0 has empty embedding".to_string());+ }++ let db = connect(&db_path(project_path))+ .execute()+ .await+ .map_err(|e| format!("DB connect error: {e}"))?;++ let schema = make_schema_v2(dim);+ let batch = make_batch_v2(schema.clone(), &page_id, &chunks, dim)?;+ let tables = db+ .table_names()+ .execute()+ .await+ .map_err(|e| format!("List tables error: {e}"))?;++ if tables.contains(&TABLE_V2.to_string()) {+ let table = db+ .open_table(TABLE_V2).execute().await- .map_err(|e| format!("DB connect error: {e}"))?;-- let schema = make_schema_v2(dim);- let batch = make_batch_v2(schema.clone(), &page_id, &chunks, dim)?;- let data = vec![batch];+ .map_err(|e| format!("Open table error: {e}"))?;- let tables = db- .table_names()+ let data = RecordBatchIterator::new(vec![Ok(batch)], schema);+ let mut merge = table.merge_insert(&["chunk_id"]);+ merge+ .when_matched_update_all(None)+ .when_not_matched_insert_all()+ .when_not_matched_by_source_delete(Some(format!("page_id = '{}'", page_id)));+ merge+ .execute(Box::new(data))+ .await+ .map_err(|e| format!("Atomic page upsert failed: {e}"))?;+ } else {+ db.create_table(TABLE_V2, vec![batch]).execute().await- .map_err(|e| format!("List tables error: {e}"))?;+ .map_err(|e| format!("Create table error: {e}"))?;+ }- if tables.contains(&TABLE_V2.to_string()) {- let table = db- .open_table(TABLE_V2)- .execute()- .await- .map_err(|e| format!("Open table error: {e}"))?;+ if let Some((page_path, fingerprint)) = revision {+ if let Err(err) = super::page_embedding::save_revision(project_path, page_path, fingerprint)+ {+ let _ = super::page_embedding::invalidate_page_revision(project_path, page_id);+ eprintln!("[page-embedding] failed to save revision metadata: {err}");+ }+ } else {+ let _ = super::page_embedding::invalidate_page_revision(project_path, page_id);+ }- table- .delete(&format!("page_id = '{}'", page_id))- .await- .map_err(|e| {- format!(- "Delete existing chunks before upsert failed for page '{}': {}",- page_id, e- )- })?;+ Ok(())+}- table- .add(data)- .execute()- .await- .map_err(|e| format!("Add error: {e}"))?;- } else {- db.create_table(TABLE_V2, data)- .execute()- .await- .map_err(|e| format!("Create table error: {e}"))?;- }+pub(crate) async fn vector_page_revision_match(+ project_path: &str,+ page_id: &str,+ page_path: &str,+ fingerprint: &str,+) -> Result<Option<usize>, String> {+ validate_page_id_for_v2(page_id)?;+ let lock = vectorstore_v2_lock(project_path);+ let _guard = lock.read().await;+ if super::page_embedding::load_revision(project_path, page_path).as_deref() != Some(fingerprint)+ {+ return Ok(None);+ }- Ok(())- })- .await+ let db = connect(&db_path(project_path))+ .execute()+ .await+ .map_err(|e| format!("DB connect error: {e}"))?;+ let tables = db+ .table_names()+ .execute()+ .await+ .map_err(|e| format!("List tables error: {e}"))?;+ if !tables.contains(&TABLE_V2.to_string()) {+ return Ok(None);+ }+ let count = db+ .open_table(TABLE_V2)+ .execute()+ .await+ .map_err(|e| format!("Open table error: {e}"))?+ .count_rows(Some(format!("page_id = '{}'", page_id)))+ .await+ .map_err(|e| format!("Count page chunks error: {e}"))?;+ Ok((count > 0).then_some(count))}/// Top-K chunk search. Returns every matching chunk's metadata + scorediff --git a/src/components/settings/sections/api-server-section.tsx b/src/components/settings/sections/api-server-section.tsxindex 113ca975..09630e39 100644--- a/src/components/settings/sections/api-server-section.tsx+++ b/src/components/settings/sections/api-server-section.tsx@@ -53,6 +53,7 @@ export const API_ENDPOINTS: Array<{ method: "GET" | "POST" | "PATCH"; path: stri{ method: "POST", path: "/api/v1/projects/{id}/search", noteKey: "endpointSearchNote" },{ method: "GET", path: "/api/v1/projects/{id}/graph", noteKey: "endpointGraphNote" },{ method: "POST", path: "/api/v1/projects/{id}/sources/rescan", noteKey: "endpointRescanNote" },+ { method: "POST", path: "/api/v1/projects/{id}/pages/embed", noteKey: "endpointEmbedPageNote" },{ method: "POST", path: "/api/v1/projects/{id}/chat", noteKey: "endpointChatNote" },{ method: "POST", path: "/api/v1/projects/{id}/chat/{sessionId}/cancel", noteKey: "endpointChatCancelNote" },]diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 917accc3..b8426142 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -807,7 +807,7 @@"statusUnknown": "Unknown","baseUrl": "Base URL","openHealth": "Open /health",- "openHealthHint": "/health never requires authentication. Other endpoints follow the access mode below, except Agent chat, which always requires a token.",+ "openHealthHint": "/health never requires authentication. Other endpoints follow the access mode below, except Agent chat, cancellation, and page embedding, which always require a token.","allowUnauthenticated": "Allow access without a token","allowUnauthenticatedHint": "Use only for trusted local agents. Any process or browser page on this machine can call the API while this is enabled.","allowLanAccess": "Allow API and Clip server access from the local network",@@ -818,7 +818,7 @@"mcpUsageHint": "Build once with `npm run mcp:build`, then configure your MCP client to run the server below. Use LLM_WIKI_API_TOKEN unless unauthenticated access is enabled.","mcpPathUnavailable": "MCP server entry was not found. Run `npm run mcp:build` from the LLM Wiki repository, then reopen Settings.","token": "Access token",- "tokenHint": "Send as `Authorization: Bearer <token>` or `X-LLM-Wiki-Token: <token>`. Read endpoints may omit it when unauthenticated access is enabled, but Agent chat and cancellation always require it. The environment variable LLM_WIKI_API_TOKEN overrides this field if set.",+ "tokenHint": "Send as `Authorization: Bearer <token>` or `X-LLM-Wiki-Token: <token>`. Read endpoints may omit it when unauthenticated access is enabled, but Agent chat, cancellation, and page embedding always require it. The environment variable LLM_WIKI_API_TOKEN overrides this field if set.","tokenPlaceholder": "Paste an existing token or click Generate","generate": "Generate new token","show": "Show",@@ -853,6 +853,7 @@"endpointSearchNote": "JSON body: { query, topK?, includeContent?, queryEmbedding? }. Uses shared keyword + vector retrieval when embeddings are configured.","endpointGraphNote": "?q=…&nodeType=…&limit=N — wikilinks graph derived from wiki/*.md.","endpointRescanNote": "Triggers a backend rescan using your Source Watch config.",+ "endpointEmbedPageNote": "Index one existing wiki/*.md page. JSON body: { path, force? }. Returns its revision and written chunk count. A token is always required.","endpointChatNote": "Agent chat. Returns JSON by default; use stream: true or Accept: text/event-stream for SSE. A token is always required.","endpointChatCancelNote": "Cancels the active Agent turn for a session. A token is always required."},diff --git a/src/i18n/it.json b/src/i18n/it.jsonindex 16fc62de..0d83badd 100644--- a/src/i18n/it.json+++ b/src/i18n/it.json@@ -807,7 +807,7 @@"statusUnknown": "Sconosciuto","baseUrl": "URL di base","openHealth": "Apri /health",- "openHealthHint": "/health non richiede mai autenticazione. Gli altri endpoint seguono la modalità di accesso seguente, tranne la chat Agent che richiede sempre un token.",+ "openHealthHint": "/health non richiede mai autenticazione. Gli altri endpoint seguono la modalità di accesso seguente, ma chat Agent, annullamento e indicizzazione pagina richiedono sempre un token.","allowUnauthenticated": "Consenti l'accesso senza token","allowUnauthenticatedHint": "Usalo solo con agent locali fidati. Con questa opzione attiva, qualsiasi processo o pagina del browser su questa macchina può chiamare l'API.","allowLanAccess": "Consenti l'accesso ad API e server Clip dalla rete locale",@@ -818,7 +818,7 @@"mcpUsageHint": "Compila una volta con `npm run mcp:build`, poi configura il tuo client MCP per avviare il server qui sotto. Usa LLM_WIKI_API_TOKEN a meno che non sia attivo l'accesso senza autenticazione.","mcpPathUnavailable": "Entry point del server MCP non trovato. Esegui `npm run mcp:build` dal repository di LLM Wiki, poi riapri le Impostazioni.","token": "Token di accesso",- "tokenHint": "Invialo come `Authorization: Bearer <token>` oppure `X-LLM-Wiki-Token: <token>`. Gli endpoint di lettura possono ometterlo quando l'accesso senza autenticazione è attivo, ma chat Agent e annullamento lo richiedono sempre. LLM_WIKI_API_TOKEN ha la precedenza.",+ "tokenHint": "Invialo come `Authorization: Bearer <token>` oppure `X-LLM-Wiki-Token: <token>`. Gli endpoint di lettura possono ometterlo quando l'accesso senza autenticazione è attivo, ma chat Agent, annullamento e indicizzazione pagina richiedono sempre un token. LLM_WIKI_API_TOKEN ha la precedenza.","tokenPlaceholder": "Incolla un token esistente o clicca su Genera","generate": "Genera un nuovo token","show": "Mostra",@@ -853,6 +853,7 @@"endpointSearchNote": "Corpo JSON: { query, topK?, includeContent?, queryEmbedding? }. Usa il recupero condiviso per parole chiave e vettori quando gli embedding sono configurati.","endpointGraphNote": "?q=…&nodeType=…&limit=N — grafo dei wikilink derivato da wiki/*.md.","endpointRescanNote": "Avvia una nuova scansione lato backend con la tua configurazione di Monitoraggio fonti.",+ "endpointEmbedPageNote": "Indicizza una pagina wiki/*.md esistente. Corpo JSON: { path, force? }. Restituisce revisione e numero di blocchi scritti. Richiede sempre un token.","endpointChatNote": "Chat Agent. Restituisce JSON per impostazione predefinita; usa stream: true o Accept: text/event-stream per SSE. Richiede sempre un token.","endpointChatCancelNote": "Annulla il turno Agent attivo per una sessione. Richiede sempre un token."},diff --git a/src/i18n/ru.json b/src/i18n/ru.jsonindex 398a1331..ddeb74a8 100644--- a/src/i18n/ru.json+++ b/src/i18n/ru.json@@ -807,7 +807,7 @@"statusUnknown": "Неизвестно","baseUrl": "Базовый URL","openHealth": "Открыть /health",- "openHealthHint": "/health никогда не требует аутентификации. Остальные эндпоинты следуют режиму ниже, кроме чата Agent, которому всегда нужен токен.",+ "openHealthHint": "/health никогда не требует аутентификации. Остальные эндпоинты следуют режиму ниже, но чат Agent, отмена и индексация страницы всегда требуют токен.","allowUnauthenticated": "Разрешить доступ без токена","allowUnauthenticatedHint": "Используйте только для доверенных локальных агентов. Пока включено, любой процесс или страница браузера на этом компьютере может обращаться к API.","allowLanAccess": "Разрешить доступ к API и серверу Clip из локальной сети",@@ -818,7 +818,7 @@"mcpUsageHint": "Соберите один раз с помощью `npm run mcp:build`, затем настройте MCP-клиент на запуск сервера ниже. Используйте LLM_WIKI_API_TOKEN, если не включён доступ без аутентификации.","mcpPathUnavailable": "Точка входа MCP-сервера не найдена. Выполните `npm run mcp:build` из репозитория LLM Wiki, затем откройте Настройки заново.","token": "Токен доступа",- "tokenHint": "Отправляйте как `Authorization: Bearer <token>` или `X-LLM-Wiki-Token: <token>`. Эндпоинты чтения могут обходиться без него в открытом режиме, но чат Agent и отмена всегда требуют токен. LLM_WIKI_API_TOKEN имеет приоритет.",+ "tokenHint": "Отправляйте как `Authorization: Bearer <token>` или `X-LLM-Wiki-Token: <token>`. Эндпоинты чтения могут обходиться без него в открытом режиме, но чат Agent, отмена и индексация страницы всегда требуют токен. LLM_WIKI_API_TOKEN имеет приоритет.","tokenPlaceholder": "Вставьте существующий токен или нажмите «Сгенерировать»","generate": "Сгенерировать новый токен","show": "Показать",@@ -853,6 +853,7 @@"endpointSearchNote": "JSON-тело: { query, topK?, includeContent?, queryEmbedding? }. Использует общий поиск по ключевым словам и векторам, если настроены эмбеддинги.","endpointGraphNote": "?q=…&nodeType=…&limit=N — граф вики-ссылок, построенный из wiki/*.md.","endpointRescanNote": "Запускает пересканирование бэкенда с использованием вашей конфигурации «Мониторинг источников».",+ "endpointEmbedPageNote": "Индексирует одну существующую страницу wiki/*.md. JSON: { path, force? }. Возвращает ревизию и число записанных фрагментов. Всегда требуется токен.","endpointChatNote": "Чат Agent. По умолчанию возвращает JSON; для SSE используйте stream: true или Accept: text/event-stream. Всегда требуется токен.","endpointChatCancelNote": "Отменяет активный ход Agent для сессии. Всегда требуется токен."},diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 2385d3db..4d4ebffb 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -807,7 +807,7 @@"statusUnknown": "未知","baseUrl": "服务地址","openHealth": "打开 /health",- "openHealthHint": "/health 始终无需鉴权。其他接口遵循下方的访问模式,但 Agent 对话始终需要 token。",+ "openHealthHint": "/health 始终无需鉴权。其他接口遵循下方的访问模式,但 Agent 对话、取消和单页向量化始终需要 token。","allowUnauthenticated": "允许无 token 访问","allowUnauthenticatedHint": "仅用于可信的本地智能体。启用后,这台机器上的任何进程或浏览器页面都可以调用 API。","allowLanAccess": "允许 API 和 Clip server 局域网访问",@@ -818,7 +818,7 @@"mcpUsageHint": "先执行一次 `npm run mcp:build`,然后让 MCP 客户端运行下面的服务配置。除非启用了无认证访问,否则需要设置 LLM_WIKI_API_TOKEN。","mcpPathUnavailable": "没有找到 MCP 服务入口。请在 LLM Wiki 仓库中先执行 `npm run mcp:build`,然后重新打开设置。","token": "访问令牌",- "tokenHint": "通过 `Authorization: Bearer <token>` 或 `X-LLM-Wiki-Token: <token>` 发送。启用无认证访问后,读取类接口可以省略 token,但 Agent 对话和取消接口始终需要 token。环境变量 LLM_WIKI_API_TOKEN 优先生效。",+ "tokenHint": "通过 `Authorization: Bearer <token>` 或 `X-LLM-Wiki-Token: <token>` 发送。启用无认证访问后,读取类接口可以省略 token,但 Agent 对话、取消和单页向量化接口始终需要 token。环境变量 LLM_WIKI_API_TOKEN 优先生效。","tokenPlaceholder": "粘贴已有 token,或点击生成","generate": "生成新 token","show": "显示",@@ -853,6 +853,7 @@"endpointSearchNote": "JSON body:{ query, topK?, includeContent?, queryEmbedding? }。配置嵌入后使用统一的关键词 + 向量检索。","endpointGraphNote": "?q=…&nodeType=…&limit=N —— 基于 wiki/*.md 的双链图谱。","endpointRescanNote": "使用你的资料文件夹监控配置触发后端重新扫描。",+ "endpointEmbedPageNote": "为一个已有的 wiki/*.md 页面建立向量索引。JSON body:{ path, force? }。返回 revision 和写入的分块数量。始终需要 Token。","endpointChatNote": "Agent 对话。默认返回 JSON;使用 stream: true 或 Accept: text/event-stream 可启用 SSE 流式输出。此接口始终需要 Token。","endpointChatCancelNote": "取消指定会话当前正在执行的 Agent 回合。此接口始终需要 Token。"},