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: expand in-page knowledge editing
nash_sud49d5577d249
diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex fb0571e2..195690b4 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -1140,6 +1140,147 @@ pub async fn apply_text_selection_edit(.map_err(|err| format!("apply_text_selection_edit blocking task join error: {err}"))?}+fn create_missing_wiki_page_inner(+ project_path: &str,+ title: &str,+ content: Option<&str>,+) -> Result<String, String> {+ let project = fs::canonicalize(project_path)+ .map_err(|err| format!("Failed to resolve project path: {err}"))?;+ let title = title.trim();+ if title.is_empty() || title.chars().count() > 200 {+ return Err("Missing-link page title must contain 1 to 200 characters".to_string());+ }+ let normalized_title = title+ .chars()+ .map(|character| {+ if character.is_control() {+ ' '+ } else {+ character+ }+ })+ .collect::<String>();+ let title = normalized_title.trim();+ if content.is_some_and(|value| value.len() > 2 * 1024 * 1024) {+ return Err("Missing-link page content exceeds the 2 MB limit".to_string());+ }+ let wiki_root = project.join("wiki");+ let canonical_wiki = fs::canonicalize(&wiki_root)+ .map_err(|err| format!("Failed to resolve wiki directory: {err}"))?;+ if !canonical_wiki.starts_with(&project) {+ return Err("Wiki directory escapes the project boundary".to_string());+ }+ let directory = canonical_wiki.join("concepts");+ fs::create_dir_all(&directory)+ .map_err(|err| format!("Failed to create wiki concepts directory: {err}"))?;+ let canonical_directory = fs::canonicalize(&directory)+ .map_err(|err| format!("Failed to resolve wiki concepts directory: {err}"))?;+ if !canonical_directory.starts_with(&project) {+ return Err("Wiki concepts directory escapes the project boundary".to_string());+ }+ let base = safe_missing_page_stem(title);+ let mut target = canonical_directory.join(format!("{base}.md"));+ for suffix in 2..=9999 {+ if !target.exists() {+ break;+ }+ target = canonical_directory.join(format!("{base}-{suffix}.md"));+ }+ if target.exists() {+ return Err("Could not allocate a unique wiki page filename".to_string());+ }+ let today = chrono::Utc::now().format("%Y-%m-%d");+ let escaped_title = title.replace('"', "\\\"");+ let default_content = format!(+ "---\ntype: concept\ntitle: \"{escaped_title}\"\ncreated: {today}\nupdated: {today}\ntags: []\nrelated: []\n---\n\n# {title}\n"+ );+ let body = content+ .filter(|value| !value.trim().is_empty())+ .unwrap_or(&default_content);+ file_sync::mark_app_write_path(&target);+ use std::io::Write as _;+ let mut output = fs::OpenOptions::new()+ .write(true)+ .create_new(true)+ .open(&target)+ .map_err(|err| format!("Failed to reserve missing-link page: {err}"))?;+ if let Err(err) = output.write_all(body.as_bytes()) {+ drop(output);+ let _ = fs::remove_file(&target);+ return Err(format!("Failed to create missing-link page: {err}"));+ }+ crate::commands::file_history::record_file_version(+ &target,+ "agent",+ "wiki.missing_link.create",+ );+ file_sync::mark_app_write_path(&target);+ target+ .strip_prefix(&project)+ .map(|path| path.to_string_lossy().replace('\\', "/"))+ .map_err(|_| "Created page escaped the project boundary".to_string())+}++fn safe_missing_page_stem(title: &str) -> String {+ let mut stem = title+ .chars()+ .map(|character| {+ if character.is_control()+ || matches!(+ character,+ '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*'+ )+ {+ '-'+ } else if character.is_whitespace() {+ ' '+ } else {+ character+ }+ })+ .collect::<String>();+ while stem.contains("--") {+ stem = stem.replace("--", "-");+ }+ stem = stem.trim_matches([' ', '.', '-']).to_string();+ if stem.is_empty() {+ stem = "untitled".to_string();+ }+ let device = stem+ .split('.')+ .next()+ .unwrap_or_default()+ .to_ascii_uppercase();+ if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL")+ || (device.len() == 4+ && (device.starts_with("COM") || device.starts_with("LPT"))+ && device.as_bytes()[3].is_ascii_digit()+ && device.as_bytes()[3] != b'0')+ {+ stem = format!("page-{stem}");+ }+ stem.chars().take(120).collect()+}++/// Create a page for an unresolved wikilink. Filename allocation and the final+/// write stay in Rust so UI callers cannot escape the project or overwrite an+/// existing page, including through Windows device names or illegal characters.+#[tauri::command]+pub async fn create_missing_wiki_page(+ project_path: String,+ title: String,+ content: Option<String>,+) -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(move || {+ run_guarded("create_missing_wiki_page", || {+ create_missing_wiki_page_inner(&project_path, &title, content.as_deref())+ })+ })+ .await+ .map_err(|err| format!("create_missing_wiki_page blocking task join error: {err}"))?+}+/// Whether a directory entry should appear in a listing.////// Hidden (dot-prefixed) entries are shown only when `include_hidden`@@ -1906,13 +2047,7 @@ mod tests {// would be surfaced here and then wrongly deleted downstream.fn make_wiki(files: &[(&str, &str)]) -> std::path::PathBuf {- let dir = std::env::temp_dir().join(format!(- "wiki-test-{}",- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_nanos()- ));+ let dir = std::env::temp_dir().join(format!("wiki-test-{}", uuid::Uuid::new_v4()));fs::create_dir_all(&dir).unwrap();for (rel, body) in files {let p = dir.join(rel);@@ -2111,13 +2246,8 @@ mod tests {// folder import button.fn make_temp_dir(label: &str) -> std::path::PathBuf {- let dir = std::env::temp_dir().join(format!(- "llmwiki-copydir-{label}-{}",- std::time::SystemTime::now()- .duration_since(std::time::UNIX_EPOCH)- .unwrap()- .as_nanos()- ));+ let dir =+ std::env::temp_dir().join(format!("llmwiki-copydir-{label}-{}", uuid::Uuid::new_v4()));std::fs::create_dir_all(&dir).unwrap();dir}@@ -2375,4 +2505,83 @@ mod tests {);let _ = std::fs::remove_dir_all(root);}++ #[test]+ fn missing_link_page_uses_safe_unique_cross_platform_names() {+ let root = make_temp_dir("missing-link-page");+ std::fs::create_dir_all(root.join("wiki")).unwrap();+ let first =+ create_missing_wiki_page_inner(root.to_str().unwrap(), "AUX: Safety / Notes?", None)+ .unwrap();+ let second = create_missing_wiki_page_inner(+ root.to_str().unwrap(),+ "AUX: Safety / Notes?",+ Some("# Draft"),+ )+ .unwrap();+ assert_eq!(first, "wiki/concepts/AUX- Safety - Notes.md");+ assert_eq!(second, "wiki/concepts/AUX- Safety - Notes-2.md");+ assert_eq!(+ std::fs::read_to_string(root.join(second)).unwrap(),+ "# Draft"+ );+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn missing_link_page_handles_reserved_cjk_and_traversal_titles_without_overwrite() {+ let root = make_temp_dir("missing-link-adversarial");+ std::fs::create_dir_all(root.join("wiki/concepts")).unwrap();+ std::fs::write(root.join("wiki/concepts/Existing Page.md"), "user content").unwrap();++ let reserved = create_missing_wiki_page_inner(root.to_str().unwrap(), "AUX", None).unwrap();+ let cjk =+ create_missing_wiki_page_inner(root.to_str().unwrap(), "知识 图谱", None).unwrap();+ let traversal =+ create_missing_wiki_page_inner(root.to_str().unwrap(), "../../escape", None).unwrap();+ let allocated =+ create_missing_wiki_page_inner(root.to_str().unwrap(), "Existing Page", None).unwrap();++ assert_eq!(reserved, "wiki/concepts/page-AUX.md");+ assert_eq!(cjk, "wiki/concepts/知识 图谱.md");+ assert_eq!(traversal, "wiki/concepts/escape.md");+ assert_eq!(allocated, "wiki/concepts/Existing Page-2.md");+ assert_eq!(+ std::fs::read_to_string(root.join("wiki/concepts/Existing Page.md")).unwrap(),+ "user content"+ );+ assert!(!root.parent().unwrap().join("escape.md").exists());+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn missing_link_page_rejects_content_over_two_megabytes() {+ let root = make_temp_dir("missing-link-size");+ std::fs::create_dir_all(root.join("wiki")).unwrap();+ let content = "x".repeat(2 * 1024 * 1024 + 1);+ let error = create_missing_wiki_page_inner(root.to_str().unwrap(), "large", Some(&content))+ .unwrap_err();+ assert!(error.contains("2 MB"));+ let _ = std::fs::remove_dir_all(root);+ }++ #[test]+ fn selection_edit_rejects_files_outside_project() {+ let root = make_temp_dir("selection-boundary");+ let outside = make_temp_dir("selection-outside").join("outside.md");+ std::fs::write(&outside, "selected").unwrap();+ let error = apply_text_selection_edit_inner(+ root.to_str().unwrap(),+ outside.to_str().unwrap(),+ "",+ "selected",+ "",+ "replacement",+ )+ .unwrap_err();+ assert!(error.contains("inside the project"));+ assert_eq!(std::fs::read_to_string(&outside).unwrap(), "selected");+ let _ = std::fs::remove_dir_all(root);+ let _ = std::fs::remove_dir_all(outside.parent().unwrap());+ }}diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 3315c373..658b6d06 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -156,7 +156,10 @@ fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinkslet file =fs::canonicalize(file_path).map_err(|err| format!("Failed to resolve page path: {err}"))?;let wiki_root = project.join("wiki");- if !file.starts_with(&wiki_root) || !file.is_file() {+ if !file.starts_with(&wiki_root)+ || !file.is_file()+ || file.extension().and_then(|value| value.to_str()) != Some("md")+ {return Err("Page links target must be an existing Markdown file under wiki/".to_string());}@@ -196,24 +199,13 @@ fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinkslet current = pages.get(¤t_path).ok_or_else(|| "Page is not available in the current wiki index".to_string())?;- let mut aliases = BTreeMap::<String, String>::new();- for (path, page) in &pages {- let wiki_relative = page.path.strip_prefix("wiki/").unwrap_or(&page.path);- let stem = file_stem(&page.path);- for alias in [- page.path.as_str(),- wiki_relative,- stem.as_str(),- page.title.as_str(),- ] {- aliases.insert(normalize_graph_alias(alias), path.clone());- }- }-let mut outgoing = Vec::new();let mut missing = Vec::new();for link in ¤t.links {- if let Some(target_path) = aliases.get(&normalize_graph_alias(link)) {+ if let Some(target_path) = resolve_reader_wikilink(&pages, link) {+ if target_path.as_str() == current_path {+ continue;+ }if let Some(target) = pages.get(target_path) {outgoing.push(PageLinkEntry {title: target.title.clone(),@@ -236,9 +228,8 @@ fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinkscontinue;}let links_here = page.links.iter().any(|link| {- aliases- .get(&normalize_graph_alias(link))- .is_some_and(|target| target == ¤t_path)+ resolve_reader_wikilink(&pages, link)+ .is_some_and(|target| target.as_str() == current_path)});if links_here {backlinks.push(PageLinkEntry {@@ -261,6 +252,30 @@ fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinks})}+/// Mirror `resolveRelatedSlug` in the frontend reader. Path-shaped links must+/// match their project-relative path exactly; bare links resolve by exact+/// filename after adding `.md`. Deliberately avoid title and fuzzy aliases so+/// the links panel never claims a target that the rendered page cannot open.+fn resolve_reader_wikilink<'a>(+ pages: &'a BTreeMap<String, GraphPage>,+ link: &str,+) -> Option<&'a String> {+ let link = link.trim().replace('\\', "/");+ if link.contains('/') {+ return pages.get_key_value(&link).map(|(path, _)| path);+ }+ let filename = if link.ends_with(".md") {+ link+ } else {+ format!("{link}.md")+ };+ pages.keys().find(|path| {+ std::path::Path::new(path.as_str())+ .file_name()+ .is_some_and(|name| name == filename.as_str())+ })+}+pub async fn resolve_query_embedding(query: &str,explicit_embedding: Option<Vec<f32>>,@@ -1944,14 +1959,19 @@ mod tests {let root = tmp_project();write_page(&root,- "wiki/concepts/alpha.md",- "---\ntitle: Alpha\n---\n# Alpha\n\n[[Beta]] and [[Missing Page]].",+ "wiki/concepts/Alpha.md",+ "---\ntitle: Alpha\n---\n# Alpha\n\n[[Beta|label]], [[Alpha]], [[Title Only]], and [[Missing Page]].",);write_page(&root,- "wiki/concepts/beta.md",+ "wiki/concepts/Beta.md","---\ntitle: Beta\n---\n# Beta\n\nBeta details.",);+ write_page(+ &root,+ "wiki/concepts/different-filename.md",+ "---\ntitle: Title Only\n---\n# Title Only\n",+ );write_page(&root,"wiki/concepts/gamma.md",@@ -1960,7 +1980,7 @@ mod tests {let links = get_page_links_inner(root.to_str().unwrap(),- root.join("wiki/concepts/alpha.md").to_str().unwrap(),+ root.join("wiki/concepts/Alpha.md").to_str().unwrap(),).unwrap();assert_eq!(links.outgoing.len(), 1);@@ -1972,8 +1992,50 @@ mod tests {.as_deref().unwrap().contains("Alpha"));+ assert_eq!(links.missing.len(), 2);+ assert!(links+ .missing+ .iter()+ .any(|entry| entry.title == "Missing Page"));+ assert!(links+ .missing+ .iter()+ .any(|entry| entry.title == "Title Only"));+ let _ = fs::remove_dir_all(root);+ }++ #[test]+ fn page_links_require_markdown_input_and_exact_reader_paths() {+ let root = tmp_project();+ write_page(+ &root,+ "wiki/concepts/current.md",+ "[[wiki/concepts/target.md]] [[target#section]]",+ );+ write_page(&root, "wiki/concepts/target.md", "# Target");+ write_page(&root, "wiki/concepts/not-markdown.txt", "text");++ let links = get_page_links_inner(+ root.to_str().unwrap(),+ root.join("wiki/concepts/current.md").to_str().unwrap(),+ )+ .unwrap();+ assert_eq!(links.outgoing.len(), 1);+ assert_eq!(+ links.outgoing[0].path.as_deref(),+ Some("wiki/concepts/target.md")+ );assert_eq!(links.missing.len(), 1);- assert_eq!(links.missing[0].title, "Missing Page");+ assert_eq!(links.missing[0].title, "target#section");++ let error = get_page_links_inner(+ root.to_str().unwrap(),+ root.join("wiki/concepts/not-markdown.txt")+ .to_str()+ .unwrap(),+ )+ .unwrap_err();+ assert!(error.contains("Markdown"));let _ = fs::remove_dir_all(root);}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 6dc757f0..4517777d 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -623,6 +623,7 @@ pub fn run() {commands::fs::write_file_base64,commands::fs::write_file_atomic,commands::fs::apply_text_selection_edit,+ commands::fs::create_missing_wiki_page,commands::file_history::list_file_history,commands::file_history::restore_file_history,commands::fs::list_directory,diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex 7b28d776..b78953c6 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -185,6 +185,14 @@ export async function getPageLinks(projectPath: string, filePath: string): Promireturn invoke<PageLinksResponse>("get_page_links", { projectPath, filePath })}+export async function createMissingWikiPage(+ projectPath: string,+ title: string,+ content?: string,+): Promise<string> {+ return invoke<string>("create_missing_wiki_page", { projectPath, title, content })+}+function assertAbsoluteFsPath(operation: string, path: string): void {if (!isAbsolutePath(path)) {throw new Error(`${operation} requires an absolute path: ${path}`)diff --git a/src/components/editor/page-links-panel.tsx b/src/components/editor/page-links-panel.tsxindex 064c6de8..948b087b 100644--- a/src/components/editor/page-links-panel.tsx+++ b/src/components/editor/page-links-panel.tsx@@ -1,9 +1,12 @@-import { useEffect, useMemo, useState } from "react"-import { CornerUpLeft, FileQuestion, Link2, Loader2, X } from "lucide-react"+import { useEffect, useMemo, useRef, useState } from "react"+import { CornerUpLeft, FileQuestion, Link2, Loader2, Plus, Sparkles, X } from "lucide-react"import { useTranslation } from "react-i18next"-import { getPageLinks, type PageLinkEntry, type PageLinksResponse } from "@/commands/fs"+import { createMissingWikiPage, getPageLinks, readFile, type PageLinkEntry, type PageLinksResponse } from "@/commands/fs"import { normalizePath } from "@/lib/path-utils"import { useWikiStore } from "@/stores/wiki-store"+import { streamChat } from "@/lib/llm-client"+import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"+import { normalizeSelectionReplacement } from "@/lib/selection-edit"const EMPTY_LINKS: PageLinksResponse = { outgoing: [], backlinks: [], missing: [] }@@ -12,29 +15,40 @@ export function PageLinksPanel({ filePath, onClose }: { filePath: string; onClosconst project = useWikiStore((state) => state.project)const dataVersion = useWikiStore((state) => state.dataVersion)const openPathInPreview = useWikiStore((state) => state.openPathInPreview)+ const llmConfig = useWikiStore((state) => state.llmConfig)const [links, setLinks] = useState<PageLinksResponse>(EMPTY_LINKS)const [loading, setLoading] = useState(true)const [error, setError] = useState("")+ const [creatingTitle, setCreatingTitle] = useState("")+ const draftAbortRef = useRef<AbortController | null>(null)++ useEffect(() => () => draftAbortRef.current?.abort(), [])useEffect(() => {if (!project) returnlet cancelled = falsesetLoading(true)setError("")- getPageLinks(project.path, filePath)- .then((result) => {- if (!cancelled) setLinks(result)- })- .catch((err) => {- if (!cancelled) setError(err instanceof Error ? err.message : String(err))- })- .finally(() => {- if (!cancelled) setLoading(false)- })+ // Coalesce save/watcher bursts that bump dataVersion repeatedly. The Rust+ // command scans Markdown files, so one trailing refresh avoids redundant IO.+ const timer = window.setTimeout(() => {+ getPageLinks(project.path, filePath)+ .then((result) => {+ if (!cancelled) setLinks(result)+ })+ .catch((err) => {+ console.error("Failed to load page links", err)+ if (!cancelled) setError(t("editor.pageLinks.loadFailed"))+ })+ .finally(() => {+ if (!cancelled) setLoading(false)+ })+ }, 200)return () => {cancelled = true+ window.clearTimeout(timer)}- }, [dataVersion, filePath, project])+ }, [dataVersion, filePath, project, t])const total = useMemo(() => links.outgoing.length + links.backlinks.length + links.missing.length,@@ -50,6 +64,47 @@ export function PageLinksPanel({ filePath, onClose }: { filePath: string; onClosopenPathInPreview(absolute)}+ const createMissing = async (entry: PageLinkEntry, withDraft: boolean) => {+ if (!project || creatingTitle) return+ setCreatingTitle(entry.title)+ setError("")+ const controller = new AbortController()+ draftAbortRef.current?.abort()+ draftAbortRef.current = controller+ try {+ let content: string | undefined+ if (withDraft) {+ const current = await readFile(filePath)+ if (controller.signal.aborted) return+ content = normalizeSelectionReplacement(+ await generateMissingPageDraft(+ llmConfig,+ entry.title,+ current.slice(0, 6000),+ t("editor.pageLinks.emptyDraftError"),+ controller.signal,+ ),+ )+ }+ const relativePath = await createMissingWikiPage(project.path, entry.title, content)+ if (controller.signal.aborted) return+ await refreshProjectFileTree(project.path, { bumpDataVersion: true })+ if (controller.signal.aborted) return+ openEntry({ title: entry.title, path: relativePath })+ } catch (err) {+ if (controller.signal.aborted) return+ console.error("Failed to create missing wiki page", err)+ setError(+ err instanceof Error && err.message === t("editor.pageLinks.emptyDraftError")+ ? err.message+ : t("editor.pageLinks.createFailed"),+ )+ } finally {+ if (!controller.signal.aborted) setCreatingTitle("")+ if (draftAbortRef.current === controller) draftAbortRef.current = null+ }+ }+return (<aside className="absolute inset-y-0 right-0 z-20 flex w-[min(22rem,90%)] flex-col border-l border-border bg-background shadow-xl" aria-label={t("editor.pageLinks.title")}><header className="flex h-11 items-center gap-2 border-b border-border px-3">@@ -61,15 +116,14 @@ export function PageLinksPanel({ filePath, onClose }: { filePath: string; onClos</button></header><div className="flex-1 overflow-y-auto">+ {error && <p className="m-3 border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{error}</p>}{loading ? (<div className="flex h-24 items-center justify-center text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /></div>- ) : error ? (- <p className="m-3 border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{error}</p>) : (<><LinkSection icon={Link2} title={t("editor.pageLinks.outgoing")} entries={links.outgoing} empty={t("editor.pageLinks.noOutgoing")} onOpen={openEntry} /><LinkSection icon={CornerUpLeft} title={t("editor.pageLinks.backlinks")} entries={links.backlinks} empty={t("editor.pageLinks.noBacklinks")} onOpen={openEntry} />- <LinkSection icon={FileQuestion} title={t("editor.pageLinks.missing")} entries={links.missing} empty={t("editor.pageLinks.noMissing")} onOpen={openEntry} missing />+ <LinkSection icon={FileQuestion} title={t("editor.pageLinks.missing")} entries={links.missing} empty={t("editor.pageLinks.noMissing")} onOpen={openEntry} onCreate={createMissing} creatingTitle={creatingTitle} missing /></>)}</div>@@ -84,6 +138,8 @@ function LinkSection({empty,onOpen,missing = false,+ onCreate,+ creatingTitle = "",}: {icon: typeof Link2title: string@@ -91,7 +147,10 @@ function LinkSection({empty: stringonOpen: (entry: PageLinkEntry) => voidmissing?: boolean+ onCreate?: (entry: PageLinkEntry, withDraft: boolean) => Promise<void>+ creatingTitle?: string}) {+ const { t } = useTranslation()return (<section className="border-b border-border"><div className="flex items-center gap-2 bg-muted/30 px-3 py-2">@@ -102,15 +161,25 @@ function LinkSection({{entries.length === 0 ? (<p className="px-3 py-3 text-xs text-muted-foreground">{empty}</p>) : (- entries.map((entry, index) => (+ entries.map((entry, index) => missing ? (+ <div key={`${entry.title}:${index}`} className="border-t border-border/50 px-3 py-2 first:border-t-0">+ <span className="block truncate text-xs font-medium text-amber-700 dark:text-amber-300">{entry.title}</span>+ <div className="mt-1.5 flex gap-1">+ <button type="button" disabled={Boolean(creatingTitle)} onClick={() => void onCreate?.(entry, false)} className="inline-flex items-center gap-1 border border-border px-1.5 py-1 text-[10px] text-foreground hover:bg-accent disabled:opacity-50"><Plus className="h-3 w-3" />{t("editor.pageLinks.create")}</button>+ <button type="button" disabled={Boolean(creatingTitle)} onClick={() => void onCreate?.(entry, true)} className="inline-flex items-center gap-1 bg-primary px-1.5 py-1 text-[10px] text-primary-foreground disabled:opacity-50">+ {creatingTitle === entry.title ? <Loader2 className="h-3 w-3 animate-spin" /> : <Sparkles className="h-3 w-3" />} {t("editor.pageLinks.draft")}+ </button>+ </div>+ </div>+ ) : (<buttonkey={`${entry.path ?? entry.title}:${index}`}type="button"- disabled={missing || !entry.path}+ disabled={!entry.path}onClick={() => onOpen(entry)}className="block w-full border-t border-border/50 px-3 py-2 text-left first:border-t-0 enabled:hover:bg-accent disabled:cursor-default">- <span className={`block truncate text-xs font-medium ${missing ? "text-amber-700 dark:text-amber-300" : "text-foreground"}`}>{entry.title}</span>+ <span className="block truncate text-xs font-medium text-foreground">{entry.title}</span>{entry.snippet && <span className="mt-0.5 line-clamp-2 block text-[11px] leading-4 text-muted-foreground">{entry.snippet}</span>}</button>))@@ -118,3 +187,32 @@ function LinkSection({</section>)}++async function generateMissingPageDraft(+ llmConfig: ReturnType<typeof useWikiStore.getState>["llmConfig"],+ title: string,+ currentPage: string,+ emptyDraftError: string,+ signal: AbortSignal,+): Promise<string> {+ return new Promise<string>((resolve, reject) => {+ let content = ""+ void streamChat(+ llmConfig,+ [{ role: "user", content: [+ "Create a concise standalone Markdown wiki page for an unresolved link.",+ "Return the complete page only. Include YAML frontmatter with type, title, tags, and related, followed by useful content. Do not wrap it in a code fence.",+ `Target title: ${title}`,+ "Context from the linking page:",+ currentPage,+ ].join("\n\n") }],+ {+ onToken: (token) => { content += token },+ onDone: () => content.trim() ? resolve(content) : reject(new Error(emptyDraftError)),+ onError: reject,+ },+ signal,+ { temperature: 0.3 },+ ).catch(reject)+ })+}diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsxindex 4f3549ae..cf7b5a00 100644--- a/src/components/editor/wiki-editor.tsx+++ b/src/components/editor/wiki-editor.tsx@@ -7,10 +7,12 @@ import { WikiReader } from "@/components/editor/wiki-reader"import { useWikiStore } from "@/stores/wiki-store"import { PageLinksPanel } from "@/components/editor/page-links-panel"import { useTranslation } from "react-i18next"-import { findDomTextSelection, findUniqueTextSelection, normalizeSelectionReplacement } from "@/lib/selection-edit"-import { applyTextSelectionEdit } from "@/commands/fs"+import { buildWordDiff, findDomTextSelection, findUniqueTextSelection, normalizeEditableMarkdown, normalizeSelectionReplacement } from "@/lib/selection-edit"+import { applyTextSelectionEdit, readFile } from "@/commands/fs"import { streamChat } from "@/lib/llm-client"import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"+import { searchWiki, type SearchResult } from "@/lib/search"+import { normalizePath } from "@/lib/path-utils"interface EditorSelectionRequest {id: string@@ -21,6 +23,12 @@ interface EditorSelectionRequest {sourceMapped: boolean}+interface SelectionConversationTurn {+ question: string+ answer: string+ references: SearchResult[]+}+interface WikiEditorProps {content: stringonSave: (markdown: string, options?: { immediate?: boolean }) => void@@ -43,12 +51,18 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {const [mode, setMode] = useState<"read" | "edit">("read")const [selectionRequest, setSelectionRequest] = useState<EditorSelectionRequest | null>(null)const [selectionInstruction, setSelectionInstruction] = useState("")+ // The first action defines the interaction for this selection. Mixing Q&A+ // turns with replacement generation creates ambiguous follow-up semantics.+ const [selectionMode, setSelectionMode] = useState<"ask" | "edit" | null>(null)const [showPageLinks, setShowPageLinks] = useState(false)const [selectionResult, setSelectionResult] = useState<{ intent: "ask" | "edit"; content: string } | null>(null)+ const [selectionTurns, setSelectionTurns] = useState<SelectionConversationTurn[]>([])+ const [citationPreview, setCitationPreview] = useState<{ path: string; title: string; content: string } | null>(null)const [selectionError, setSelectionError] = useState("")const [selectionRunning, setSelectionRunning] = useState(false)const readerRef = useRef<HTMLDivElement>(null)const selectionAbortRef = useRef<AbortController | null>(null)+ const selectionRunIdRef = useRef(0)const project = useWikiStore((state) => state.project)const llmConfig = useWikiStore((state) => state.llmConfig)@@ -62,13 +76,14 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {const bodySourceOffset = useMemo(() => editableMarkdownIndex(content, body), [body, content])const editableMarkdown = content- const [draftMarkdown, setDraftMarkdown] = useState(editableMarkdown)- const latestMarkdownRef = useRef(editableMarkdown)+ const [draftMarkdown, setDraftMarkdown] = useState(() => normalizeEditableMarkdown(editableMarkdown))+ const latestMarkdownRef = useRef(normalizeEditableMarkdown(editableMarkdown))useEffect(() => {if (mode !== "edit") {- setDraftMarkdown(editableMarkdown)- latestMarkdownRef.current = editableMarkdown+ const normalized = normalizeEditableMarkdown(editableMarkdown)+ setDraftMarkdown(normalized)+ latestMarkdownRef.current = normalized}}, [editableMarkdown, mode])@@ -97,6 +112,12 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {setSelectionResult(null)setSelectionError("")setSelectionInstruction("")+ setSelectionMode(null)+ setSelectionTurns([])+ setCitationPreview(null)+ selectionRunIdRef.current += 1+ selectionAbortRef.current?.abort()+ setSelectionRunning(false)}, [filePath])const captureRenderedSelection = useCallback(() => {@@ -131,22 +152,48 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {setSelectionResult(null)setSelectionError("")setSelectionInstruction("")+ setSelectionMode(null)+ setSelectionTurns([])+ setCitationPreview(null)+ selectionRunIdRef.current += 1+ selectionAbortRef.current?.abort()+ setSelectionRunning(false)}, [bodySourceOffset, editableMarkdown, filePath])- useEffect(() => () => selectionAbortRef.current?.abort(), [])+ useEffect(() => () => {+ selectionRunIdRef.current += 1+ selectionAbortRef.current?.abort()+ }, [])const submitSelectionToAgent = useCallback(async (intent: "ask" | "edit") => {if (!selectionRequest || !selectionInstruction.trim() || selectionRunning) return+ if (selectionMode && selectionMode !== intent) returnif (intent === "edit" && !selectionRequest.sourceMapped) return+ setSelectionMode(intent)if (selectionRequest.sourceMapped) {onSave(`${selectionRequest.prefix}${selectionRequest.selectedText}${selectionRequest.suffix}`, { immediate: true })}+ const runId = ++selectionRunIdRef.current+ setSelectionRunning(true)const instruction = selectionInstruction.trim()+ const projectRoot = project ? normalizePath(project.path).replace(/\/+$/, "") : ""+ const relativeFilePath = projectRoot && normalizePath(selectionRequest.filePath).startsWith(`${projectRoot}/`)+ ? normalizePath(selectionRequest.filePath).slice(projectRoot.length + 1)+ : selectionRequest.filePath+ const references = intent === "ask" && project+ ? await searchWiki(project.path, `${instruction} ${selectionRequest.selectedText.slice(0, 500)}`)+ .then((results) => results.slice(0, 5))+ .catch(() => [])+ : []+ if (runId !== selectionRunIdRef.current) return+ const retrievedContext = references.length > 0+ ? references.map((reference, index) => `[${index + 1}] ${reference.title}\nPath: ${projectRelativePath(projectRoot, reference.path)}\n${reference.snippet}`).join("\n\n")+ : "No additional knowledge-base results were retrieved."const prompt = [intent === "edit"? "Edit the selected text according to the user's instruction. Return only the replacement text without explanation or an outer Markdown fence.": "Answer the user's instruction about the selected text. Use the nearby text only as supporting context.",- `File: ${selectionRequest.filePath}`,+ `File: ${relativeFilePath}`,`Instruction: ${instruction}`,"Context before selection:",selectionRequest.sourceMapped ? selectionRequest.prefix.slice(-1200) : "Unavailable because the rendered selection could not be mapped safely to one source range.",@@ -155,22 +202,47 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {"</selected_text>","Context after selection:",selectionRequest.sourceMapped ? selectionRequest.suffix.slice(0, 1200) : "Unavailable because the rendered selection could not be mapped safely to one source range.",+ "Knowledge-base context:",+ retrievedContext,+ "When knowledge-base context supports the answer, cite it using [1], [2], and so on. Do not invent citations.",].join("\n\n")const controller = new AbortController()selectionAbortRef.current?.abort()selectionAbortRef.current = controllersetSelectionResult({ intent, content: "" })setSelectionError("")- setSelectionRunning(true)+ let accumulated = ""+ const history = selectionTurns.slice(-6).flatMap((turn) => [+ { role: "user" as const, content: turn.question },+ { role: "assistant" as const, content: turn.answer.slice(-6000) },+ ])try {await streamChat(llmConfig,- [{ role: "user", content: prompt }],+ [...history, { role: "user", content: prompt }],{- onToken: (token) => setSelectionResult((current) => current ? { ...current, content: current.content + token } : { intent, content: token }),- onDone: () => setSelectionRunning(false),+ onToken: (token) => {+ if (runId !== selectionRunIdRef.current) return+ accumulated += token+ setSelectionResult({ intent, content: accumulated })+ },+ onDone: () => {+ if (runId !== selectionRunIdRef.current) return+ if (intent === "ask") {+ setSelectionResult(null)+ if (accumulated.trim()) {+ setSelectionTurns((turns) => [...turns, { question: instruction, answer: accumulated, references }])+ setSelectionInstruction("")+ } else {+ setSelectionError(t("editor.selection.emptyResponse"))+ }+ }+ setSelectionRunning(false)+ },onError: (error) => {- setSelectionError(error.message)+ if (runId !== selectionRunIdRef.current) return+ console.error("Selection assistant request failed", error)+ setSelectionError(t("editor.selection.requestFailed"))setSelectionRunning(false)},},@@ -178,10 +250,12 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {{ temperature: intent === "edit" ? 0.2 : 0.4 },)} catch (error) {- setSelectionError(error instanceof Error ? error.message : String(error))+ if (runId !== selectionRunIdRef.current) return+ console.error("Selection assistant request failed", error)+ setSelectionError(t("editor.selection.requestFailed"))setSelectionRunning(false)}- }, [llmConfig, onSave, selectionInstruction, selectionRequest, selectionRunning])+ }, [llmConfig, onSave, project, selectionInstruction, selectionMode, selectionRequest, selectionRunning, selectionTurns, t])const acceptSelectionEdit = useCallback(async () => {if (!project || !selectionRequest?.sourceMapped || selectionResult?.intent !== "edit") return@@ -204,11 +278,17 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {setSelectionInstruction("")await refreshProjectFileTree(project.path, { bumpDataVersion: true })} catch (error) {- setSelectionError(error instanceof Error ? error.message : String(error))+ console.error("Failed to apply selection edit", error)+ setSelectionError(+ error instanceof Error && error.message.includes("changed after the selection")+ ? t("editor.selection.sourceChanged")+ : t("editor.selection.applyFailed"),+ )}- }, [project, selectionRequest, selectionResult])+ }, [project, selectionRequest, selectionResult, t])const closeSelectionPanel = useCallback(() => {+ selectionRunIdRef.current += 1selectionAbortRef.current?.abort()selectionAbortRef.current = nullsetSelectionRunning(false)@@ -216,11 +296,33 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {setSelectionResult(null)setSelectionError("")setSelectionInstruction("")+ setSelectionMode(null)+ setSelectionTurns([])+ setCitationPreview(null)}, [])+ const stopSelectionRun = useCallback(() => {+ selectionRunIdRef.current += 1+ selectionAbortRef.current?.abort()+ selectionAbortRef.current = null+ setSelectionRunning(false)+ setSelectionResult(null)+ }, [])++ const openCitation = useCallback(async (reference: SearchResult) => {+ try {+ setSelectionError("")+ const content = await readFile(reference.path)+ setCitationPreview({ path: reference.path, title: reference.title, content })+ } catch (error) {+ console.error("Failed to open selection reference", error)+ setSelectionError(t("editor.selection.referenceFailed"))+ }+ }, [t])+return (<div- className="relative h-full overflow-hidden"+ className="flex h-full overflow-hidden"tabIndex={-1}onKeyDownCapture={(event) => {if (mode !== "edit") return@@ -230,6 +332,7 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {}}}>+ <div className="relative min-w-0 flex-1 overflow-hidden"><div className="absolute right-3 top-3 z-10 flex items-center gap-1">{filePath && (<button type="button" onClick={() => { setSelectionRequest(null); setShowPageLinks((shown) => !shown) }} title={t("editor.pageLinks.title")} className="inline-flex items-center gap-1 rounded-md border border-border/60 bg-background/90 px-2 py-1 text-xs text-muted-foreground shadow-sm hover:bg-accent hover:text-foreground">@@ -244,8 +347,9 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {if (mode === "read") {// Seed edit mode from the latest raw file content before switching;// the sync effect intentionally does not reset drafts while editing.- setDraftMarkdown(editableMarkdown)- latestMarkdownRef.current = editableMarkdown+ const normalized = normalizeEditableMarkdown(editableMarkdown)+ setDraftMarkdown(normalized)+ latestMarkdownRef.current = normalized}setMode((m) => (m === "read" ? "edit" : "read"))}}@@ -270,7 +374,7 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {) : (<div className="h-full overflow-auto p-6"><textarea- aria-label="Raw Markdown editor"+ aria-label={t("editor.rawMarkdownEditor")}value={draftMarkdown}onChange={(event) => {const next = event.currentTarget.value@@ -290,49 +394,66 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {/></div>)}+ {showPageLinks && filePath && <PageLinksPanel filePath={filePath} onClose={() => setShowPageLinks(false)} />}+ </div>{selectionRequest && (- <aside className="absolute inset-y-0 right-0 z-20 flex w-[min(22rem,90%)] flex-col border-l border-border bg-background shadow-xl" aria-label={t("editor.selection.askAgent")}>- <header className="flex h-11 items-center gap-2 border-b border-border px-3">- <Sparkles className="h-3.5 w-3.5 text-primary" />- <span className="min-w-0 flex-1 truncate">{t("editor.selection.askAgent")}</span>- <button type="button" onClick={closeSelectionPanel} className="p-1 text-muted-foreground hover:text-foreground" aria-label={t("editor.selection.askAgent")}>+ <aside className="flex h-full w-[360px] max-w-[45%] shrink-0 flex-col border-l border-border bg-background" aria-label={t("editor.selection.askAgent")}>+ <header className="flex min-h-11 items-center gap-2 border-b border-border px-3 py-2">+ <Sparkles className="h-4 w-4 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{t("editor.selection.askAgent")}</span>+ <button type="button" onClick={closeSelectionPanel} className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground" aria-label={t("editor.selection.askAgent")}><X className="h-3.5 w-3.5" /></button></header><div className="flex-1 overflow-y-auto p-3">- <div className="mb-3 border-l-2 border-primary/40 bg-muted/30 px-2.5 py-2 text-xs leading-5 text-muted-foreground">+ <div className="mb-3 rounded-md border border-border/60 bg-muted/30 px-3 py-2 text-xs leading-5 text-muted-foreground">{selectionRequest.selectedText}</div>{!selectionRequest.sourceMapped && (- <p className="mb-3 border border-amber-500/30 bg-amber-500/5 p-2 text-xs leading-5 text-amber-700 dark:text-amber-300">+ <p className="mb-3 rounded-md border border-border bg-muted/40 p-2 text-xs leading-5 text-muted-foreground">{t("editor.selection.askOnlyHint")}</p>)}- {!selectionResult && <textarea- value={selectionInstruction}- onChange={(event) => setSelectionInstruction(event.target.value)}- onKeyDown={(event) => {- if (event.key === "Enter" && !event.shiftKey) {- event.preventDefault()- submitSelectionToAgent("ask")- }- }}- placeholder={t("editor.selection.placeholder")}- rows={5}- className="w-full resize-none border border-border bg-background p-2 text-sm outline-none focus:border-primary"- />}+ {selectionTurns.map((turn, index) => (+ <div key={`${index}:${turn.question}`} className="mb-4 space-y-2 border-b border-border/60 pb-4">+ <div className="ml-6 rounded-md bg-accent px-2.5 py-1.5 text-xs text-accent-foreground">{turn.question}</div>+ <WikiReader body={turn.answer} filePath={selectionRequest.filePath} />+ {turn.references.length > 0 && (+ <div className="flex flex-wrap gap-1 pt-1">+ {turn.references.map((reference, referenceIndex) => (+ <button key={reference.path} type="button" onClick={() => void openCitation(reference)} title={reference.path} className="max-w-full truncate rounded border border-border px-1.5 py-1 text-[10px] text-muted-foreground hover:bg-accent hover:text-foreground">[{referenceIndex + 1}] {reference.title}</button>+ ))}+ </div>+ )}+ </div>+ ))}+ {citationPreview && (+ <section className="mb-4 overflow-hidden rounded-md border border-border bg-background">+ <div className="flex items-center gap-2 border-b border-border px-2 py-1.5">+ <span className="min-w-0 flex-1 truncate text-xs font-medium">{citationPreview.title}</span>+ <button type="button" onClick={() => setCitationPreview(null)} className="text-xs text-muted-foreground hover:text-foreground">{t("editor.selection.closeReference")}</button>+ </div>+ <div className="max-h-72 overflow-auto p-2"><WikiReader body={parseFrontmatter(citationPreview.content).body} filePath={citationPreview.path} /></div>+ </section>+ )}{selectionResult && (<div className="space-y-3">{selectionResult.intent === "edit" && (- <div className="border border-red-500/20 bg-red-500/5 p-2">- <div className="mb-1 text-[10px] font-semibold uppercase text-red-600 dark:text-red-400">- {t("chat.selectionEdit.original")}</div>- <pre className="whitespace-pre-wrap break-words font-mono text-xs text-foreground/80">{selectionRequest.selectedText}</pre>+ <div className="rounded-md border border-border bg-muted/20 p-2">+ <div className="mb-1 text-[10px] font-semibold uppercase text-muted-foreground">{t("editor.selection.wordDiff")}</div>+ <div className="whitespace-pre-wrap break-words font-mono text-xs leading-5">+ {buildWordDiff(selectionRequest.selectedText, normalizeSelectionReplacement(selectionResult.content)).map((part, index) => (+ <span key={`${index}:${part.type}`} className={part.type === "delete" ? "bg-destructive/10 text-destructive line-through" : part.type === "insert" ? "bg-primary/10 text-primary" : "text-foreground/80"}>{part.value}</span>+ ))}+ </div></div>)}- <div className={selectionResult.intent === "edit" ? "border border-green-500/20 bg-green-500/5 p-2" : "min-w-0 text-sm text-foreground"}>- {selectionResult.intent === "edit" && <div className="mb-1 text-[10px] font-semibold uppercase text-green-700 dark:text-green-400">+ {t("chat.selectionEdit.replacement")}</div>}+ <div className={selectionResult.intent === "edit" ? "rounded-md border border-border bg-muted/20 p-2" : "min-w-0 text-sm text-foreground"}>+ {selectionResult.intent === "edit" && <div className="mb-1 text-[10px] font-semibold uppercase text-muted-foreground">+ {t("chat.selectionEdit.replacement")}</div>}{selectionResult.intent === "edit" ? (- <div className="whitespace-pre-wrap break-words">{selectionResult.content || (selectionRunning ? t("editor.selection.generating") : "")}</div>+ selectionRunning ? <div className="whitespace-pre-wrap break-words">{selectionResult.content || t("editor.selection.generating")}</div> : (+ <textarea value={selectionResult.content} onChange={(event) => setSelectionResult({ intent: "edit", content: event.target.value })} rows={8} className="w-full resize-y bg-transparent font-mono text-xs leading-5 outline-none" />+ )) : selectionResult.content ? (<WikiReader body={selectionResult.content} filePath={selectionRequest.filePath} />) : selectionRunning ? (@@ -341,28 +462,47 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {</div></div>)}- {selectionError && <p className="mt-3 border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{selectionError}</p>}+ {selectionError && <p className="mt-3 rounded-md border border-destructive/30 bg-destructive/5 p-2 text-xs text-destructive">{selectionError}</p>}</div>- <footer className="flex justify-end gap-1.5 border-t border-border p-3">- {selectionRunning ? (- <button type="button" onClick={() => selectionAbortRef.current?.abort()} className="border border-border px-2 py-1 text-xs text-foreground hover:bg-accent">{t("editor.selection.stop")}</button>- ) : selectionResult?.intent === "edit" ? (- <>- <button type="button" onClick={() => setSelectionResult(null)} className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground">{t("chat.selectionEdit.reject")}</button>- <button type="button" onClick={() => void acceptSelectionEdit()} disabled={!selectionResult.content} className="bg-primary px-2 py-1 text-xs text-primary-foreground disabled:opacity-50">{t("chat.selectionEdit.accept")}</button>- </>- ) : selectionResult ? (- <button type="button" onClick={() => setSelectionResult(null)} className="border border-border px-2 py-1 text-xs text-foreground hover:bg-accent">{t("editor.selection.askAgain")}</button>- ) : (- <>- <button type="button" onClick={() => void submitSelectionToAgent("ask")} disabled={!selectionInstruction.trim()} className="border border-border px-2 py-1 text-xs text-foreground hover:bg-accent disabled:opacity-50">{t("editor.selection.ask")}</button>- <button type="button" onClick={() => void submitSelectionToAgent("edit")} disabled={!selectionInstruction.trim() || !selectionRequest.sourceMapped} title={!selectionRequest.sourceMapped ? t("editor.selection.askOnlyHint") : undefined} className="bg-primary px-2 py-1 text-xs text-primary-foreground disabled:opacity-50">{t("editor.selection.edit")}</button>- </>+ <footer className="space-y-2 border-t border-border bg-background p-3">+ {!selectionResult && !selectionRunning && (+ <textarea+ value={selectionInstruction}+ onChange={(event) => setSelectionInstruction(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.shiftKey) {+ event.preventDefault()+ submitSelectionToAgent(selectionMode ?? "ask")+ }+ }}+ placeholder={t("editor.selection.placeholder")}+ rows={3}+ className="w-full resize-none rounded-md border border-input bg-background p-2 text-sm outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"+ />)}+ <div className="flex min-h-7 justify-end gap-1.5">+ {selectionRunning ? (+ <button type="button" onClick={stopSelectionRun} className="rounded-md border border-border px-2 py-1 text-xs text-foreground hover:bg-accent">{t("editor.selection.stop")}</button>+ ) : selectionResult?.intent === "edit" ? (+ <>+ <button type="button" onClick={() => setSelectionResult(null)} className="rounded-md px-2 py-1 text-xs text-muted-foreground hover:bg-accent hover:text-foreground">{t("chat.selectionEdit.reject")}</button>+ <button type="button" onClick={() => void submitSelectionToAgent("edit")} className="rounded-md border border-border px-2 py-1 text-xs text-foreground hover:bg-accent">{t("editor.selection.regenerate")}</button>+ <button type="button" onClick={() => void acceptSelectionEdit()} disabled={!selectionResult.content} className="rounded-md bg-primary px-2 py-1 text-xs text-primary-foreground disabled:opacity-50">{t("chat.selectionEdit.accept")}</button>+ </>+ ) : !selectionResult ? (+ <>+ {selectionMode !== "edit" && (+ <button type="button" onClick={() => void submitSelectionToAgent("ask")} disabled={!selectionInstruction.trim()} className="rounded-md border border-border px-2 py-1 text-xs text-foreground hover:bg-accent disabled:opacity-50">{t("editor.selection.ask")}</button>+ )}+ {selectionMode !== "ask" && (+ <button type="button" onClick={() => void submitSelectionToAgent("edit")} disabled={!selectionInstruction.trim() || !selectionRequest.sourceMapped} title={!selectionRequest.sourceMapped ? t("editor.selection.askOnlyHint") : undefined} className="rounded-md bg-primary px-2 py-1 text-xs text-primary-foreground disabled:opacity-50">{t("editor.selection.edit")}</button>+ )}+ </>+ ) : null}+ </div></footer></aside>)}- {showPageLinks && filePath && <PageLinksPanel filePath={filePath} onClose={() => setShowPageLinks(false)} />}</div>)}@@ -371,3 +511,10 @@ function editableMarkdownIndex(markdown: string, body: string): number {if (!body) return markdown.lengthreturn markdown.indexOf(body)}++function projectRelativePath(projectRoot: string, path: string): string {+ const normalized = normalizePath(path)+ return projectRoot && normalized.startsWith(`${projectRoot}/`)+ ? normalized.slice(projectRoot.length + 1)+ : normalized+}diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 47e6a077..e71f03c0 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -45,7 +45,15 @@"generating": "Generating...","stop": "Stop","askAgain": "Ask again",- "askOnlyHint": "This rendered selection cannot be mapped to one exact Markdown source range. You can ask about it, but editing is disabled to prevent changing the wrong text."+ "askOnlyHint": "This rendered selection cannot be mapped to one exact Markdown source range. You can ask about it, but editing is disabled to prevent changing the wrong text.",+ "wordDiff": "Word-level changes",+ "regenerate": "Regenerate",+ "closeReference": "Close",+ "requestFailed": "The selection assistant could not complete this request.",+ "applyFailed": "The selected text could not be updated.",+ "sourceChanged": "The file changed after this text was selected. Select the text again before applying the edit.",+ "referenceFailed": "The referenced page could not be opened.",+ "emptyResponse": "The model returned no answer. Please try again."},"pageLinks": {"button": "Links",@@ -55,8 +63,14 @@"missing": "Missing links","noOutgoing": "This page has no outgoing wiki links.","noBacklinks": "No other page links here yet.",- "noMissing": "All wiki links resolve to existing pages."- }+ "noMissing": "All wiki links resolve to existing pages.",+ "create": "Create",+ "draft": "Agent draft",+ "loadFailed": "Page links could not be loaded.",+ "createFailed": "The missing page could not be created.",+ "emptyDraftError": "The model returned an empty draft."+ },+ "rawMarkdownEditor": "Raw Markdown editor"},"research": {"title": "Deep Research",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex d6c7bf20..a2c3251d 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -45,7 +45,15 @@"generating": "正在生成……","stop": "停止","askAgain": "继续询问",- "askOnlyHint": "该渲染选区无法唯一映射到 Markdown 源码位置。你仍可询问,但为防止误改,当前不能直接写回修改。"+ "askOnlyHint": "该渲染选区无法唯一映射到 Markdown 源码位置。你仍可询问,但为防止误改,当前不能直接写回修改。",+ "wordDiff": "词级修改",+ "regenerate": "重新生成",+ "closeReference": "关闭",+ "requestFailed": "选区助手未能完成本次请求。",+ "applyFailed": "无法更新选中的文本。",+ "sourceChanged": "选中文本后文件已经发生变化。请重新选择文本,再应用修改。",+ "referenceFailed": "无法打开引用页面。",+ "emptyResponse": "模型没有返回回答,请重试。"},"pageLinks": {"button": "链接",@@ -55,8 +63,14 @@"missing": "缺失链接","noOutgoing": "当前页面没有出站 Wiki 链接。","noBacklinks": "暂无其他页面链接到这里。",- "noMissing": "所有 Wiki 链接都能解析到现有页面。"- }+ "noMissing": "所有 Wiki 链接都能解析到现有页面。",+ "create": "创建",+ "draft": "Agent 草稿",+ "loadFailed": "无法加载页面链接。",+ "createFailed": "无法创建缺失页面。",+ "emptyDraftError": "模型返回了空白草稿。"+ },+ "rawMarkdownEditor": "Markdown 源码编辑器"},"research": {"title": "深度研究",diff --git a/src/lib/selection-edit.test.ts b/src/lib/selection-edit.test.tsindex f68634da..e549dac5 100644--- a/src/lib/selection-edit.test.ts+++ b/src/lib/selection-edit.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest"-import { findUniqueTextSelection, normalizeSelectionReplacement } from "./selection-edit"+import { buildWordDiff, findUniqueTextSelection, normalizeEditableMarkdown, normalizeSelectionReplacement } from "./selection-edit"describe("normalizeSelectionReplacement", () => {it("removes one complete outer Markdown fence", () => {@@ -14,6 +14,30 @@ describe("normalizeSelectionReplacement", () => {})})+describe("normalizeEditableMarkdown", () => {+ it("normalizes CRLF and lone CR without changing existing LF", () => {+ expect(normalizeEditableMarkdown("first\r\nsecond\rthird\nfourth"))+ .toBe("first\nsecond\nthird\nfourth")+ })+})++describe("buildWordDiff", () => {+ it("marks inserted and deleted words while preserving equal text", () => {+ const parts = buildWordDiff("The old text", "The new text")+ expect(parts.some((part) => part.type === "delete" && part.value.includes("old"))).toBe(true)+ expect(parts.some((part) => part.type === "insert" && part.value.includes("new"))).toBe(true)+ expect(parts.filter((part) => part.type === "equal").map((part) => part.value).join(""))+ .toContain("The ")+ })++ it("keeps unchanged CJK characters instead of replacing the whole sentence", () => {+ const parts = buildWordDiff("知识图谱检索", "知识图谱搜索")+ expect(parts.some((part) => part.type === "equal" && part.value.includes("知识图谱"))).toBe(true)+ expect(parts.some((part) => part.type === "delete" && part.value === "检")).toBe(true)+ expect(parts.some((part) => part.type === "insert" && part.value === "搜")).toBe(true)+ })+})+describe("findUniqueTextSelection", () => {it("maps a unique rendered selection to its exact source range", () => {expect(findUniqueTextSelection("before selected after", "selected")).toEqual({@@ -32,4 +56,8 @@ describe("findUniqueTextSelection", () => {expect(findUniqueTextSelection("same and same", "same")).toBeNull()expect(findUniqueTextSelection("content", " ")).toBeNull()})++ it("returns null when the rendered text does not exist in the source", () => {+ expect(findUniqueTextSelection("existing content", "missing content")).toBeNull()+ })})diff --git a/src/lib/selection-edit.ts b/src/lib/selection-edit.tsindex 07c22f2f..4f330439 100644--- a/src/lib/selection-edit.ts+++ b/src/lib/selection-edit.ts@@ -9,12 +9,73 @@ export function normalizeSelectionReplacement(content: string): string {return fenced ? fenced[1] : content}+/**+ * Textarea selection offsets use browser-normalized LF line endings even when+ * its assigned value came from a CRLF file. Normalize the editable snapshot so+ * those offsets always address the same string that selectionStart describes.+ */+export function normalizeEditableMarkdown(content: string): string {+ return content.replace(/\r\n?/g, "\n")+}+export interface TextSelectionSnapshot {prefix: stringselectedText: stringsuffix: string}+export interface WordDiffPart {+ type: "equal" | "insert" | "delete"+ value: string+}++/** Small, deterministic LCS diff for selection-sized text candidates. */+export function buildWordDiff(original: string, replacement: string): WordDiffPart[] {+ const left = tokenizeDiff(original)+ const right = tokenizeDiff(replacement)+ // Keep pathological whole-document selections from allocating an unbounded+ // LCS matrix. The coarse fallback remains truthful and responsive.+ if (left.length * right.length > 250_000) {+ return [+ ...(original ? [{ type: "delete" as const, value: original }] : []),+ ...(replacement ? [{ type: "insert" as const, value: replacement }] : []),+ ]+ }+ const rows = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1))+ for (let i = left.length - 1; i >= 0; i -= 1) {+ for (let j = right.length - 1; j >= 0; j -= 1) {+ rows[i][j] = left[i] === right[j]+ ? rows[i + 1][j + 1] + 1+ : Math.max(rows[i + 1][j], rows[i][j + 1])+ }+ }+ const parts: WordDiffPart[] = []+ let i = 0+ let j = 0+ while (i < left.length || j < right.length) {+ if (i < left.length && j < right.length && left[i] === right[j]) {+ pushDiff(parts, "equal", left[i]); i += 1; j += 1+ } else if (j < right.length && (i === left.length || rows[i][j + 1] >= rows[i + 1][j])) {+ pushDiff(parts, "insert", right[j]); j += 1+ } else {+ pushDiff(parts, "delete", left[i]); i += 1+ }+ }+ return parts+}++function tokenizeDiff(value: string): string[] {+ // Segment scripts that are commonly written without spaces by character so+ // a short CJK edit does not mark the entire sentence as replaced.+ return value.match(/\s+|[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu) ?? []+}++function pushDiff(parts: WordDiffPart[], type: WordDiffPart["type"], value: string): void {+ const previous = parts[parts.length - 1]+ if (previous?.type === type) previous.value += value+ else parts.push({ type, value })+}+/*** Resolve rendered text back to one unambiguous Markdown source range. Browser* rendering can collapse line breaks and repeated spaces, so a whitespace-