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 in-page selection assistant and page links
nash_suf9ebc32f0e59
diff --git a/package-lock.json b/package-lock.jsonindex 4463a91c..5f5e79da 100644--- a/package-lock.json+++ b/package-lock.json@@ -1,12 +1,12 @@{"name": "llm-wiki",- "version": "0.6.0",+ "version": "0.6.1","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "llm-wiki",- "version": "0.6.0",+ "version": "0.6.1","dependencies": {"@base-ui/react": "^1.3.0","@fontsource-variable/geist": "^5.2.8",diff --git a/package.json b/package.jsonindex be1c8813..0332f336 100644--- a/package.json+++ b/package.json@@ -1,7 +1,7 @@{"name": "llm-wiki","private": true,- "version": "0.6.0",+ "version": "0.6.1","type": "module","scripts": {"dev": "vite",diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex fa9ba3ae..bf3ce046 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -4461,7 +4461,7 @@ checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092"[[package]]name = "llm-wiki"-version = "0.6.0"+version = "0.6.1"dependencies = ["arrow-array","arrow-schema",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0a52f560..d91c1cfd 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -1,6 +1,6 @@[package]name = "llm-wiki"-version = "0.6.0"+version = "0.6.1"description = "LLM Wiki - A personal knowledge base for LLM concepts"authors = []edition = "2021"diff --git a/src-tauri/src/commands/fs.rs b/src-tauri/src/commands/fs.rsindex e8acf3e2..fb0571e2 100644--- a/src-tauri/src/commands/fs.rs+++ b/src-tauri/src/commands/fs.rs@@ -1072,6 +1072,74 @@ pub async fn write_file_atomic(path: String, contents: String) -> Result<(), Str.map_err(|e| format!("write_file_atomic blocking task join error: {e}"))?}+fn apply_text_selection_edit_inner(+ project_path: &str,+ file_path: &str,+ prefix: &str,+ selected_text: &str,+ suffix: &str,+ replacement: &str,+) -> Result<String, String> {+ let project = fs::canonicalize(project_path)+ .map_err(|err| format!("Failed to resolve project path: {err}"))?;+ let file = fs::canonicalize(file_path)+ .map_err(|err| format!("Failed to resolve selected file: {err}"))?;+ if !file.starts_with(&project) || !file.is_file() {+ return Err(+ "Selection edit target must be an existing file inside the project".to_string(),+ );+ }+ let current = fs::read_to_string(&file)+ .map_err(|err| format!("Failed to read selection edit target: {err}"))?;+ let expected = format!("{prefix}{selected_text}{suffix}");+ if current != expected {+ return Err(+ "The file changed after the selection was captured. Re-select the text before applying the Agent suggestion."+ .to_string(),+ );+ }+ let updated = format!("{prefix}{replacement}{suffix}");+ file_sync::mark_app_write_path(&file);+ crate::commands::file_history::record_file_version(+ &file,+ "baseline",+ "before.agent.selection_edit",+ );+ fs::write(&file, &updated)+ .map_err(|err| format!("Failed to apply Agent selection edit: {err}"))?;+ crate::commands::file_history::record_file_version(&file, "agent", "agent.selection_edit");+ file_sync::mark_app_write_path(&file);+ Ok(updated)+}++/// Apply one Agent-proposed replacement without overwriting intervening user+/// edits. The full prefix/selection/suffix snapshot is intentionally checked at+/// the Rust write boundary; a frontend-only check would leave a TOCTOU window.+#[tauri::command]+pub async fn apply_text_selection_edit(+ project_path: String,+ file_path: String,+ prefix: String,+ selected_text: String,+ suffix: String,+ replacement: String,+) -> Result<String, String> {+ tauri::async_runtime::spawn_blocking(move || {+ run_guarded("apply_text_selection_edit", || {+ apply_text_selection_edit_inner(+ &project_path,+ &file_path,+ &prefix,+ &selected_text,+ &suffix,+ &replacement,+ )+ })+ })+ .await+ .map_err(|err| format!("apply_text_selection_edit blocking task join error: {err}"))?+}+/// Whether a directory entry should appear in a listing.////// Hidden (dot-prefixed) entries are shown only when `include_hidden`@@ -2271,4 +2339,40 @@ mod tests {let _ = std::fs::remove_dir_all(&src);let _ = std::fs::remove_dir_all(&dest);}++ #[test]+ fn selection_edit_rejects_stale_content_and_preserves_user_changes() {+ let root = make_temp_dir("selection-edit");+ let file = root.join("wiki/page.md");+ std::fs::create_dir_all(file.parent().unwrap()).unwrap();+ std::fs::write(&file, "before selected after").unwrap();++ let updated = apply_text_selection_edit_inner(+ root.to_str().unwrap(),+ file.to_str().unwrap(),+ "before ",+ "selected",+ " after",+ "replacement",+ )+ .unwrap();+ assert_eq!(updated, "before replacement after");++ std::fs::write(&file, "user changed the file").unwrap();+ let error = apply_text_selection_edit_inner(+ root.to_str().unwrap(),+ file.to_str().unwrap(),+ "before ",+ "selected",+ " after",+ "second replacement",+ )+ .unwrap_err();+ assert!(error.contains("changed after the selection"));+ assert_eq!(+ std::fs::read_to_string(&file).unwrap(),+ "user changed the file"+ );+ let _ = std::fs::remove_dir_all(root);+ }}diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsindex 1e401b0f..3315c373 100644--- a/src-tauri/src/commands/search.rs+++ b/src-tauri/src/commands/search.rs@@ -67,6 +67,22 @@ struct GraphPage {links: Vec<String>,}+#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PageLinkEntry {+ pub title: String,+ pub path: Option<String>,+ pub snippet: Option<String>,+}++#[derive(Debug, Clone, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PageLinksResponse {+ pub outgoing: Vec<PageLinkEntry>,+ pub backlinks: Vec<PageLinkEntry>,+ pub missing: Vec<PageLinkEntry>,+}+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SearchEmbeddingConfig {@@ -120,6 +136,131 @@ pub async fn embedding_fetch(.await}+#[tauri::command]+pub async fn get_page_links(+ project_path: String,+ file_path: String,+) -> Result<PageLinksResponse, String> {+ tokio::task::spawn_blocking(move || get_page_links_inner(&project_path, &file_path))+ .await+ .map_err(|err| format!("page links worker failed: {err}"))?+}++/// Build link relationships from Markdown source rather than the UI's lazy+/// file tree. Canonical paths enforce the project/wiki boundary, while the+/// returned paths stay project-relative so all desktop platforms share one+/// wire format and Windows separators never leak into frontend routing.+fn get_page_links_inner(project_path: &str, file_path: &str) -> Result<PageLinksResponse, String> {+ let project = fs::canonicalize(project_path)+ .map_err(|err| format!("Failed to resolve project path: {err}"))?;+ let 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() {+ return Err("Page links target must be an existing Markdown file under wiki/".to_string());+ }++ let mut pages = BTreeMap::<String, GraphPage>::new();+ let canonical_project = project.to_string_lossy();+ for entry in WalkDir::new(&wiki_root).into_iter().filter_map(Result::ok) {+ if pages.len() >= MAX_SEARCH_FILES+ || !entry.file_type().is_file()+ || entry.path().extension().and_then(|value| value.to_str()) != Some("md")+ {+ continue;+ }+ let Ok(content) = fs::read_to_string(entry.path()) else {+ continue;+ };+ let path = relative_to_project(&canonical_project, entry.path());+ let title = extract_title(+ &content,+ entry+ .path()+ .file_name()+ .and_then(|value| value.to_str())+ .unwrap_or_default(),+ );+ pages.insert(+ normalize_path(&path),+ GraphPage {+ path,+ title,+ links: extract_wikilinks(&content),+ content,+ },+ );+ }++ let current_path = normalize_path(&relative_to_project(&canonical_project, &file));+ let 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) = pages.get(target_path) {+ outgoing.push(PageLinkEntry {+ title: target.title.clone(),+ path: Some(target.path.clone()),+ snippet: None,+ });+ }+ } else {+ missing.push(PageLinkEntry {+ title: link.clone(),+ path: None,+ snippet: None,+ });+ }+ }++ let mut backlinks = Vec::new();+ for (path, page) in &pages {+ if path == ¤t_path {+ continue;+ }+ let links_here = page.links.iter().any(|link| {+ aliases+ .get(&normalize_graph_alias(link))+ .is_some_and(|target| target == ¤t_path)+ });+ if links_here {+ backlinks.push(PageLinkEntry {+ title: page.title.clone(),+ path: Some(page.path.clone()),+ snippet: Some(build_snippet(&page.content, ¤t.title)),+ });+ }+ }++ outgoing.sort_by(|a, b| a.title.cmp(&b.title));+ outgoing.dedup_by(|a, b| a.path == b.path);+ backlinks.sort_by(|a, b| a.title.cmp(&b.title));+ missing.sort_by(|a, b| a.title.cmp(&b.title));+ missing.dedup_by(|a, b| a.title == b.title);+ Ok(PageLinksResponse {+ outgoing,+ backlinks,+ missing,+ })+}+pub async fn resolve_query_embedding(query: &str,explicit_embedding: Option<Vec<f32>>,@@ -1798,6 +1939,44 @@ mod tests {let _ = fs::remove_dir_all(root);}+ #[test]+ fn page_links_resolve_outgoing_backlinks_and_missing_targets() {+ let root = tmp_project();+ write_page(+ &root,+ "wiki/concepts/alpha.md",+ "---\ntitle: Alpha\n---\n# Alpha\n\n[[Beta]] and [[Missing Page]].",+ );+ write_page(+ &root,+ "wiki/concepts/beta.md",+ "---\ntitle: Beta\n---\n# Beta\n\nBeta details.",+ );+ write_page(+ &root,+ "wiki/concepts/gamma.md",+ "---\ntitle: Gamma\n---\n# Gamma\n\nGamma references [[Alpha]] here.",+ );++ let links = get_page_links_inner(+ root.to_str().unwrap(),+ root.join("wiki/concepts/alpha.md").to_str().unwrap(),+ )+ .unwrap();+ assert_eq!(links.outgoing.len(), 1);+ assert_eq!(links.outgoing[0].title, "Beta");+ assert_eq!(links.backlinks.len(), 1);+ assert_eq!(links.backlinks[0].title, "Gamma");+ assert!(links.backlinks[0]+ .snippet+ .as_deref()+ .unwrap()+ .contains("Alpha"));+ assert_eq!(links.missing.len(), 1);+ assert_eq!(links.missing[0].title, "Missing Page");+ let _ = fs::remove_dir_all(root);+ }+#[tokio::test]async fn keyword_search_handles_cjk_bigram_queries() {let root = tmp_project();diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e8d7ffd7..6dc757f0 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -622,6 +622,7 @@ pub fn run() {commands::fs::write_file,commands::fs::write_file_base64,commands::fs::write_file_atomic,+ commands::fs::apply_text_selection_edit,commands::file_history::list_file_history,commands::file_history::restore_file_history,commands::fs::list_directory,@@ -642,6 +643,7 @@ pub fn run() {commands::project::open_path_in_project,commands::search::search_project,commands::search::embedding_fetch,+ commands::search::get_page_links,commands::external_search::web_search,commands::external_search::anytxt_search,clip_server_status,diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex 1eeadb51..d1d89d7c 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -1,7 +1,7 @@{"$schema": "https://schema.tauri.app/config/2","productName": "LLM Wiki",- "version": "0.6.0",+ "version": "0.6.1","identifier": "com.llmwiki.app","build": {"beforeDevCommand": "npm run dev",diff --git a/src/commands/fs.ts b/src/commands/fs.tsindex 451e54f6..7b28d776 100644--- a/src/commands/fs.ts+++ b/src/commands/fs.ts@@ -158,6 +158,33 @@ export async function restoreFileHistory(projectPath: string, filePath: string,return invoke<string>("restore_file_history", { projectPath, filePath, entryId })}+export async function applyTextSelectionEdit(input: {+ projectPath: string+ filePath: string+ prefix: string+ selectedText: string+ suffix: string+ replacement: string+}): Promise<string> {+ return invoke<string>("apply_text_selection_edit", input)+}++export interface PageLinkEntry {+ title: string+ path?: string+ snippet?: string+}++export interface PageLinksResponse {+ outgoing: PageLinkEntry[]+ backlinks: PageLinkEntry[]+ missing: PageLinkEntry[]+}++export async function getPageLinks(projectPath: string, filePath: string): Promise<PageLinksResponse> {+ return invoke<PageLinksResponse>("get_page_links", { projectPath, filePath })+}+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.tsxnew file mode 100644index 00000000..064c6de8--- /dev/null+++ b/src/components/editor/page-links-panel.tsx@@ -0,0 +1,120 @@+import { useEffect, useMemo, useState } from "react"+import { CornerUpLeft, FileQuestion, Link2, Loader2, X } from "lucide-react"+import { useTranslation } from "react-i18next"+import { getPageLinks, type PageLinkEntry, type PageLinksResponse } from "@/commands/fs"+import { normalizePath } from "@/lib/path-utils"+import { useWikiStore } from "@/stores/wiki-store"++const EMPTY_LINKS: PageLinksResponse = { outgoing: [], backlinks: [], missing: [] }++export function PageLinksPanel({ filePath, onClose }: { filePath: string; onClose: () => void }) {+ const { t } = useTranslation()+ const project = useWikiStore((state) => state.project)+ const dataVersion = useWikiStore((state) => state.dataVersion)+ const openPathInPreview = useWikiStore((state) => state.openPathInPreview)+ const [links, setLinks] = useState<PageLinksResponse>(EMPTY_LINKS)+ const [loading, setLoading] = useState(true)+ const [error, setError] = useState("")++ useEffect(() => {+ if (!project) return+ let cancelled = false+ setLoading(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)+ })+ return () => {+ cancelled = true+ }+ }, [dataVersion, filePath, project])++ const total = useMemo(+ () => links.outgoing.length + links.backlinks.length + links.missing.length,+ [links],+ )++ const openEntry = (entry: PageLinkEntry) => {+ if (!project || !entry.path) return+ const normalized = normalizePath(entry.path)+ const absolute = normalized.startsWith(`${normalizePath(project.path)}/`)+ ? normalized+ : `${normalizePath(project.path)}/${normalized.replace(/^\/+/, "")}`+ openPathInPreview(absolute)+ }++ 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">+ <Link2 className="h-4 w-4 text-primary" />+ <h2 className="min-w-0 flex-1 truncate text-sm font-medium">{t("editor.pageLinks.title")}</h2>+ {!loading && <span className="text-[10px] text-muted-foreground">{total}</span>}+ <button type="button" onClick={onClose} className="p-1 text-muted-foreground hover:text-foreground" aria-label={t("editor.pageLinks.title")}>+ <X className="h-4 w-4" />+ </button>+ </header>+ <div className="flex-1 overflow-y-auto">+ {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 />+ </>+ )}+ </div>+ </aside>+ )+}++function LinkSection({+ icon: Icon,+ title,+ entries,+ empty,+ onOpen,+ missing = false,+}: {+ icon: typeof Link2+ title: string+ entries: PageLinkEntry[]+ empty: string+ onOpen: (entry: PageLinkEntry) => void+ missing?: boolean+}) {+ return (+ <section className="border-b border-border">+ <div className="flex items-center gap-2 bg-muted/30 px-3 py-2">+ <Icon className="h-3.5 w-3.5 text-muted-foreground" />+ <h3 className="flex-1 text-xs font-medium">{title}</h3>+ <span className="text-[10px] text-muted-foreground">{entries.length}</span>+ </div>+ {entries.length === 0 ? (+ <p className="px-3 py-3 text-xs text-muted-foreground">{empty}</p>+ ) : (+ entries.map((entry, index) => (+ <button+ key={`${entry.path ?? entry.title}:${index}`}+ type="button"+ disabled={missing || !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>+ {entry.snippet && <span className="mt-0.5 line-clamp-2 block text-[11px] leading-4 text-muted-foreground">{entry.snippet}</span>}+ </button>+ ))+ )}+ </section>+ )+}diff --git a/src/components/editor/wiki-editor.tsx b/src/components/editor/wiki-editor.tsxindex eff7a294..4f3549ae 100644--- a/src/components/editor/wiki-editor.tsx+++ b/src/components/editor/wiki-editor.tsx@@ -1,9 +1,25 @@-import { useCallback, useEffect, useMemo, useRef, useState } from "react"+import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"import "katex/dist/katex.min.css"-import { Pencil, Eye } from "lucide-react"+import { Pencil, Eye, Link2, Sparkles, X } from "lucide-react"import { parseFrontmatter } from "@/lib/frontmatter"import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"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 { streamChat } from "@/lib/llm-client"+import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"++interface EditorSelectionRequest {+ id: string+ filePath: string+ prefix: string+ selectedText: string+ suffix: string+ sourceMapped: boolean+}interface WikiEditorProps {content: string@@ -13,11 +29,28 @@ interface WikiEditorProps {filePath?: string}+// Selection actions update the parent editor state. Keeping the rendered body+// stable prevents React from replacing selected text nodes and clearing the+// browser's visible selection highlight when the side panel opens.+const StableWikiReader = memo(WikiReader)+const StableFrontmatterPanel = memo(FrontmatterPanel)+export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {+ const { t } = useTranslation()// Default to read mode (ReactMarkdown render). Edit mode is a raw Markdown// textarea so metadata/frontmatter can be edited without a WYSIWYG serializer// rewriting YAML, wikilinks, or other wiki-specific source syntax.const [mode, setMode] = useState<"read" | "edit">("read")+ const [selectionRequest, setSelectionRequest] = useState<EditorSelectionRequest | null>(null)+ const [selectionInstruction, setSelectionInstruction] = useState("")+ const [showPageLinks, setShowPageLinks] = useState(false)+ const [selectionResult, setSelectionResult] = useState<{ intent: "ask" | "edit"; 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 project = useWikiStore((state) => state.project)+ const llmConfig = useWikiStore((state) => state.llmConfig)// Read mode renders frontmatter as UI plus the Markdown body. Edit mode uses// a plain-text Markdown editor for the full file so frontmatter can be edited@@ -26,6 +59,7 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {() => parseFrontmatter(content),[content],)+ const bodySourceOffset = useMemo(() => editableMarkdownIndex(content, body), [body, content])const editableMarkdown = contentconst [draftMarkdown, setDraftMarkdown] = useState(editableMarkdown)@@ -42,9 +76,151 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {onSave(latestMarkdownRef.current, { immediate: true })}, [onSave])+ const captureSelection = useCallback((markdown: string, start: number, end: number) => {+ if (!filePath || start === end) {+ setSelectionRequest(null)+ return+ }+ const selectedText = markdown.slice(start, end)+ if (!selectedText.trim()) {+ setSelectionRequest(null)+ return+ }+ setSelectionRequest({+ id: `selection-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,+ filePath,+ prefix: markdown.slice(0, start),+ selectedText,+ suffix: markdown.slice(end),+ sourceMapped: true,+ })+ setSelectionResult(null)+ setSelectionError("")+ setSelectionInstruction("")+ }, [filePath])++ const captureRenderedSelection = useCallback(() => {+ if (!filePath) {+ setSelectionRequest(null)+ return+ }+ const root = readerRef.current+ const selection = window.getSelection()+ if (!root || !selection || selection.isCollapsed || !selection.anchorNode || !root.contains(selection.anchorNode)) {+ setSelectionRequest(null)+ return+ }+ const renderedSelection = selection.toString().trim()+ if (!renderedSelection) {+ setSelectionRequest(null)+ return+ }+ const snapshot = bodySourceOffset >= 0+ ? findDomTextSelection(editableMarkdown, selection, root)+ : null+ const fallbackSnapshot = snapshot ?? findUniqueTextSelection(editableMarkdown, renderedSelection)+ setShowPageLinks(false)+ setSelectionRequest({+ id: `selection-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,+ filePath,+ prefix: fallbackSnapshot?.prefix ?? "",+ selectedText: fallbackSnapshot?.selectedText ?? renderedSelection,+ suffix: fallbackSnapshot?.suffix ?? "",+ sourceMapped: Boolean(fallbackSnapshot),+ })+ setSelectionResult(null)+ setSelectionError("")+ setSelectionInstruction("")+ }, [bodySourceOffset, editableMarkdown, filePath])++ useEffect(() => () => selectionAbortRef.current?.abort(), [])++ const submitSelectionToAgent = useCallback(async (intent: "ask" | "edit") => {+ if (!selectionRequest || !selectionInstruction.trim() || selectionRunning) return+ if (intent === "edit" && !selectionRequest.sourceMapped) return+ if (selectionRequest.sourceMapped) {+ onSave(`${selectionRequest.prefix}${selectionRequest.selectedText}${selectionRequest.suffix}`, { immediate: true })+ }+ const instruction = selectionInstruction.trim()+ 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}`,+ `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.",+ "<selected_text>",+ selectionRequest.selectedText,+ "</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.",+ ].join("\n\n")+ const controller = new AbortController()+ selectionAbortRef.current?.abort()+ selectionAbortRef.current = controller+ setSelectionResult({ intent, content: "" })+ setSelectionError("")+ setSelectionRunning(true)+ try {+ await streamChat(+ llmConfig,+ [{ role: "user", content: prompt }],+ {+ onToken: (token) => setSelectionResult((current) => current ? { ...current, content: current.content + token } : { intent, content: token }),+ onDone: () => setSelectionRunning(false),+ onError: (error) => {+ setSelectionError(error.message)+ setSelectionRunning(false)+ },+ },+ controller.signal,+ { temperature: intent === "edit" ? 0.2 : 0.4 },+ )+ } catch (error) {+ setSelectionError(error instanceof Error ? error.message : String(error))+ setSelectionRunning(false)+ }+ }, [llmConfig, onSave, selectionInstruction, selectionRequest, selectionRunning])++ const acceptSelectionEdit = useCallback(async () => {+ if (!project || !selectionRequest?.sourceMapped || selectionResult?.intent !== "edit") return+ const replacement = normalizeSelectionReplacement(selectionResult.content)+ try {+ setSelectionError("")+ const updated = await applyTextSelectionEdit({+ projectPath: project.path,+ filePath: selectionRequest.filePath,+ prefix: selectionRequest.prefix,+ selectedText: selectionRequest.selectedText,+ suffix: selectionRequest.suffix,+ replacement,+ })+ if (useWikiStore.getState().selectedFile === selectionRequest.filePath) {+ useWikiStore.getState().setFileContent(updated)+ }+ setSelectionRequest(null)+ setSelectionResult(null)+ setSelectionInstruction("")+ await refreshProjectFileTree(project.path, { bumpDataVersion: true })+ } catch (error) {+ setSelectionError(error instanceof Error ? error.message : String(error))+ }+ }, [project, selectionRequest, selectionResult])++ const closeSelectionPanel = useCallback(() => {+ selectionAbortRef.current?.abort()+ selectionAbortRef.current = null+ setSelectionRunning(false)+ setSelectionRequest(null)+ setSelectionResult(null)+ setSelectionError("")+ setSelectionInstruction("")+ }, [])+return (<div- className="relative h-full overflow-auto"+ className="relative h-full overflow-hidden"tabIndex={-1}onKeyDownCapture={(event) => {if (mode !== "edit") return@@ -54,32 +230,45 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {}}}>- <button- type="button"- onClick={() => {- if (mode === "edit") saveLatestNow()- 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- }- setMode((m) => (m === "read" ? "edit" : "read"))- }}- title={mode === "read" ? "Edit (raw markdown)" : "Done editing"}- className="absolute right-3 top-3 z-10 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"- >- {mode === "read" ? <Pencil className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}- {mode === "read" ? "Edit" : "Done"}- </button>+ <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">+ <Link2 className="h-3.5 w-3.5" />+ {t("editor.pageLinks.button")}+ </button>+ )}+ <button+ type="button"+ onClick={() => {+ if (mode === "edit") saveLatestNow()+ 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+ }+ setMode((m) => (m === "read" ? "edit" : "read"))+ }}+ title={mode === "read" ? t("editor.editRaw") : t("editor.doneEditing")}+ 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"+ >+ {mode === "read" ? <Pencil className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}+ {mode === "read" ? t("editor.edit") : t("editor.done")}+ </button>+ </div>{mode === "read" ? (- <div className="px-6 py-6">- {frontmatter && <FrontmatterPanel data={frontmatter} />}- <WikiReader body={body} filePath={filePath} />+ <div ref={readerRef} className="h-full overflow-auto px-6 py-6" onMouseUp={captureRenderedSelection}>+ {frontmatter && <StableFrontmatterPanel data={frontmatter} />}+ <StableWikiReader+ body={body}+ sourceBody={bodySourceOffset >= 0 ? body : undefined}+ sourceOffset={bodySourceOffset >= 0 ? bodySourceOffset : undefined}+ filePath={filePath}+ /></div>) : (- <div className="h-full p-6">+ <div className="h-full overflow-auto p-6"><textareaaria-label="Raw Markdown editor"value={draftMarkdown}@@ -89,11 +278,96 @@ export function WikiEditor({ content, onSave, filePath }: WikiEditorProps) {latestMarkdownRef.current = nextonSave(next)}}+ onSelect={(event) => {+ captureSelection(+ draftMarkdown,+ event.currentTarget.selectionStart,+ event.currentTarget.selectionEnd,+ )+ }}spellCheck={false}className="h-full min-h-[60vh] w-full resize-none rounded-md border border-border/60 bg-background/70 p-4 font-mono text-sm leading-6 text-foreground outline-none focus:border-primary/60 focus:ring-2 focus:ring-primary/20"/></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")}>+ <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">+ {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">+ {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"+ />}+ {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>+ )}+ <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>}+ {selectionResult.intent === "edit" ? (+ <div className="whitespace-pre-wrap break-words">{selectionResult.content || (selectionRunning ? t("editor.selection.generating") : "")}</div>+ ) : selectionResult.content ? (+ <WikiReader body={selectionResult.content} filePath={selectionRequest.filePath} />+ ) : selectionRunning ? (+ <p className="text-muted-foreground">{t("editor.selection.generating")}</p>+ ) : null}+ </div>+ </div>+ )}+ {selectionError && <p className="mt-3 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>+ </aside>+ )}+ {showPageLinks && filePath && <PageLinksPanel filePath={filePath} onClose={() => setShowPageLinks(false)} />}</div>)}++function editableMarkdownIndex(markdown: string, body: string): number {+ if (!body) return markdown.length+ return markdown.indexOf(body)+}diff --git a/src/components/editor/wiki-reader.tsx b/src/components/editor/wiki-reader.tsxindex 39961151..ff6c1392 100644--- a/src/components/editor/wiki-reader.tsx+++ b/src/components/editor/wiki-reader.tsx@@ -15,6 +15,10 @@ import { MermaidDiagram, unwrapMermaidPre } from "@/components/mermaid-diagram"interface WikiReaderProps {body: string+ /** Original, untransformed Markdown body used for DOM-to-source mapping. */+ sourceBody?: string+ /** Character offset where sourceBody begins in the full Markdown file. */+ sourceOffset?: number/*** Absolute path of the markdown file being rendered. Used to* resolve relative image references against the file's own@@ -37,7 +41,7 @@ interface WikiReaderProps {* against the project's wiki tree and routed to the wiki preview,* giving the user single-click navigation between pages.*/-export function WikiReader({ body, filePath }: WikiReaderProps) {+export function WikiReader({ body, sourceBody, sourceOffset = 0, filePath }: WikiReaderProps) {const project = useWikiStore((s) => s.project)const projectPathIndex = useWikiStore((s) => s.projectPathIndex)const openPathInPreview = useWikiStore((s) => s.openPathInPreview)@@ -49,6 +53,26 @@ export function WikiReader({ body, filePath }: WikiReaderProps) {() => transformWikilinks(transformImageEmbeds(body)),[body],)+ const sourceLineStarts = useMemo(() => {+ if (sourceBody === undefined) return null+ const starts = [0]+ for (let index = 0; index < sourceBody.length; index += 1) {+ if (sourceBody.charCodeAt(index) === 10) starts.push(index + 1)+ }+ return starts+ }, [sourceBody])++ const sourceAttrs = (node: unknown): Record<string, number> => {+ if (!sourceLineStarts) return {}+ const position = (node as { position?: { start?: { line?: number }; end?: { line?: number } } } | undefined)?.position+ const startLine = position?.start?.line+ const endLine = position?.end?.line+ if (!startLine || !endLine) return {}+ const start = sourceLineStarts[startLine - 1]+ const end = sourceLineStarts[endLine] ?? sourceBody?.length+ if (start === undefined || end === undefined) return {}+ return { "data-source-start": sourceOffset + start, "data-source-end": sourceOffset + end }+ }const renderLanguage = detectLanguage(body)const direction = getTextDirection(renderLanguage)const htmlLang = getHtmlLang(renderLanguage)@@ -89,6 +113,9 @@ export function WikiReader({ body, filePath }: WikiReaderProps) {remarkPlugins={[remarkGfm, remarkMath]}rehypePlugins={[rehypeKatex]}components={{+ p: ({ node, children, ...props }) => <p {...sourceAttrs(node)} {...props}>{children}</p>,+ li: ({ node, children, ...props }) => <li {...sourceAttrs(node)} {...props}>{children}</li>,+ blockquote: ({ node, children, ...props }) => <blockquote {...sourceAttrs(node)} {...props}>{children}</blockquote>,a: ({ href, children, ...props }) => {const h = typeof href === "string" ? href : ""const isWikilink = h.startsWith("#")@@ -107,24 +134,27 @@ export function WikiReader({ body, filePath }: WikiReaderProps) {</a>)},- h1: ({ children, ...props }) => (+ h1: ({ node, children, ...props }) => (<h1+ {...sourceAttrs(node)}className="mb-4 mt-0 border-b border-border/60 pb-3 text-3xl font-semibold leading-tight tracking-normal text-foreground"{...props}>{children}</h1>),- h2: ({ children, ...props }) => (+ h2: ({ node, children, ...props }) => (<h2+ {...sourceAttrs(node)}className="mb-3 mt-8 border-b border-border/40 pb-2 text-2xl font-semibold leading-tight tracking-normal text-foreground"{...props}>{children}</h2>),- h3: ({ children, ...props }) => (+ h3: ({ node, children, ...props }) => (<h3+ {...sourceAttrs(node)}className="mb-2 mt-6 text-xl font-semibold leading-snug tracking-normal text-foreground"{...props}>@@ -157,16 +187,17 @@ export function WikiReader({ body, filePath }: WikiReaderProps) {{children}</thead>),- th: ({ children, ...props }) => (+ th: ({ node, children, ...props }) => (<th+ {...sourceAttrs(node)}className="border border-border/80 bg-muted px-3 py-1.5 text-start font-semibold"{...props}>{children}</th>),- td: ({ children, ...props }) => (- <td className="border border-border/60 px-3 py-1.5" {...props}>+ td: ({ node, children, ...props }) => (+ <td {...sourceAttrs(node)} className="border border-border/60 px-3 py-1.5" {...props}>{children}</td>),diff --git a/src/i18n/en.json b/src/i18n/en.jsonindex 446f35e4..47e6a077 100644--- a/src/i18n/en.json+++ b/src/i18n/en.json@@ -31,6 +31,33 @@"knowledge": "Knowledge","files": "Files"},+ "editor": {+ "edit": "Edit",+ "done": "Done",+ "editRaw": "Edit raw Markdown",+ "doneEditing": "Done editing",+ "selection": {+ "askAgent": "Ask Agent about selection",+ "placeholder": "Explain, rewrite, shorten...",+ "send": "Send",+ "ask": "Ask",+ "edit": "Edit",+ "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."+ },+ "pageLinks": {+ "button": "Links",+ "title": "Page links",+ "outgoing": "Outgoing links",+ "backlinks": "Backlinks",+ "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."+ }+ },"research": {"title": "Deep Research","notConfigured": "Deep Research sources are not configured. Go to Settings → External Information Sources to configure Web Search or AnyTXT.",@@ -123,6 +150,15 @@"sourceCount_plural": "{{count}} sources"},"chat": {+ "selectionEdit": {+ "title": "Proposed selection edit",+ "reviewHint": "Review before writing",+ "original": "Original",+ "replacement": "Replacement",+ "accept": "Accept",+ "reject": "Reject",+ "applying": "Applying..."+ },"agentChanges": {"title": "Agent file changes","taskTitle": "Agent activity",diff --git a/src/i18n/zh.json b/src/i18n/zh.jsonindex 1a3f7614..d6c7bf20 100644--- a/src/i18n/zh.json+++ b/src/i18n/zh.json@@ -31,6 +31,33 @@"knowledge": "知识库","files": "文件"},+ "editor": {+ "edit": "编辑",+ "done": "完成",+ "editRaw": "编辑原始 Markdown",+ "doneEditing": "完成编辑",+ "selection": {+ "askAgent": "让 Agent 处理选中内容",+ "placeholder": "解释、改写、缩短……",+ "send": "发送",+ "ask": "询问",+ "edit": "修改",+ "generating": "正在生成……",+ "stop": "停止",+ "askAgain": "继续询问",+ "askOnlyHint": "该渲染选区无法唯一映射到 Markdown 源码位置。你仍可询问,但为防止误改,当前不能直接写回修改。"+ },+ "pageLinks": {+ "button": "链接",+ "title": "页面链接",+ "outgoing": "出站链接",+ "backlinks": "反向链接",+ "missing": "缺失链接",+ "noOutgoing": "当前页面没有出站 Wiki 链接。",+ "noBacklinks": "暂无其他页面链接到这里。",+ "noMissing": "所有 Wiki 链接都能解析到现有页面。"+ }+ },"research": {"title": "深度研究","notConfigured": "深度研究信息来源尚未配置。请到设置 → 外部信息源中配置网页搜索或 AnyTXT。",@@ -123,6 +150,15 @@"sourceCount_plural": "{{count}} 个资料"},"chat": {+ "selectionEdit": {+ "title": "选中内容修改建议",+ "reviewHint": "写入前请确认",+ "original": "原文",+ "replacement": "替换内容",+ "accept": "接受",+ "reject": "拒绝",+ "applying": "正在应用……"+ },"agentChanges": {"title": "Agent 文件修改","taskTitle": "Agent 活动",diff --git a/src/lib/selection-edit.test.ts b/src/lib/selection-edit.test.tsnew file mode 100644index 00000000..f68634da--- /dev/null+++ b/src/lib/selection-edit.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it } from "vitest"+import { findUniqueTextSelection, normalizeSelectionReplacement } from "./selection-edit"++describe("normalizeSelectionReplacement", () => {+ it("removes one complete outer Markdown fence", () => {+ expect(normalizeSelectionReplacement("```markdown\nreplacement\n```"))+ .toBe("replacement")+ })++ it("preserves whitespace and incomplete or embedded fences", () => {+ expect(normalizeSelectionReplacement(" replacement ")).toBe(" replacement ")+ expect(normalizeSelectionReplacement("before\n```text\ninside\n```\nafter"))+ .toBe("before\n```text\ninside\n```\nafter")+ })+})++describe("findUniqueTextSelection", () => {+ it("maps a unique rendered selection to its exact source range", () => {+ expect(findUniqueTextSelection("before selected after", "selected")).toEqual({+ prefix: "before ",+ selectedText: "selected",+ suffix: " after",+ })+ })++ it("accepts browser-collapsed whitespace when the match is unique", () => {+ expect(findUniqueTextSelection("before\nselected words\nafter", "selected words")?.selectedText)+ .toBe("selected words")+ })++ it("rejects empty and ambiguous selections", () => {+ expect(findUniqueTextSelection("same and same", "same")).toBeNull()+ expect(findUniqueTextSelection("content", " ")).toBeNull()+ })+})diff --git a/src/lib/selection-edit.ts b/src/lib/selection-edit.tsnew file mode 100644index 00000000..07c22f2f--- /dev/null+++ b/src/lib/selection-edit.ts@@ -0,0 +1,126 @@+/**+ * Models occasionally wrap an otherwise valid replacement in one Markdown+ * fence. Strip only that complete outer fence; partial or embedded fences are+ * user content and must remain untouched.+ */+export function normalizeSelectionReplacement(content: string): string {+ const trimmed = content.trim()+ const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/)+ return fenced ? fenced[1] : content+}++export interface TextSelectionSnapshot {+ prefix: string+ selectedText: string+ suffix: string+}++/**+ * Resolve rendered text back to one unambiguous Markdown source range. Browser+ * rendering can collapse line breaks and repeated spaces, so a whitespace-+ * flexible fallback is allowed. Ambiguous matches are rejected because an edit+ * action must never guess which occurrence the user selected.+ */+export function findUniqueTextSelection(+ markdown: string,+ renderedSelection: string,+): TextSelectionSnapshot | null {+ const selected = renderedSelection.trim()+ if (!selected) return null++ const exactStart = markdown.indexOf(selected)+ if (exactStart >= 0 && markdown.indexOf(selected, exactStart + selected.length) < 0) {+ return snapshot(markdown, exactStart, exactStart + selected.length)+ }++ const tokens = selected.split(/\s+/u).filter(Boolean)+ if (tokens.length < 2) return null+ const pattern = tokens.map(escapeRegExp).join("\\s+")+ const matches = [...markdown.matchAll(new RegExp(pattern, "gu"))]+ if (matches.length !== 1 || matches[0].index === undefined) return null+ const start = matches[0].index+ return snapshot(markdown, start, start + matches[0][0].length)+}++/**+ * Resolve a browser Range through source-position attributes emitted by the+ * Markdown renderer. The renderer narrows each endpoint to its source block;+ * walking text nodes in DOM order then disambiguates repeated text without+ * relying on a project-wide string match.+ */+export function findDomTextSelection(+ markdown: string,+ selection: Selection,+ root: HTMLElement,+): TextSelectionSnapshot | null {+ if (selection.rangeCount === 0 || selection.isCollapsed) return null+ const range = selection.getRangeAt(0)+ if (!root.contains(range.startContainer) || !root.contains(range.endContainer)) return null+ const start = domPointToSourceOffset(markdown, range.startContainer, range.startOffset, root)+ const end = domPointToSourceOffset(markdown, range.endContainer, range.endOffset, root)+ if (start === null || end === null || start >= end) return null+ return snapshot(markdown, start, end)+}++function domPointToSourceOffset(+ markdown: string,+ container: Node,+ offset: number,+ root: HTMLElement,+): number | null {+ const textPoint = normalizeToTextPoint(container, offset)+ if (!textPoint) return null+ const [target, targetOffset] = textPoint+ const parent = target.parentElement?.closest<HTMLElement>("[data-source-start][data-source-end]")+ if (!parent || !root.contains(parent)) return null+ const start = Number(parent.dataset.sourceStart)+ const end = Number(parent.dataset.sourceEnd)+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end > markdown.length || start >= end) return null++ const walker = document.createTreeWalker(parent, NodeFilter.SHOW_TEXT)+ let cursor = start+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {+ const value = node.nodeValue ?? ""+ if (!value) continue+ const match = findTextFrom(markdown, value, cursor, end)+ if (!match) continue+ if (node === target) return Math.min(match.start + targetOffset, match.end)+ cursor = match.end+ }+ return null+}++function normalizeToTextPoint(container: Node, offset: number): [Text, number] | null {+ if (container.nodeType === Node.TEXT_NODE) {+ const text = container as Text+ return [text, Math.min(offset, text.data.length)]+ }+ const element = container as Element+ const child = element.childNodes[Math.min(offset, element.childNodes.length - 1)]+ if (!child) return null+ const walker = document.createTreeWalker(child, NodeFilter.SHOW_TEXT)+ const text = child.nodeType === Node.TEXT_NODE ? child as Text : walker.nextNode() as Text | null+ return text ? [text, 0] : null+}++function findTextFrom(markdown: string, value: string, from: number, to: number): { start: number; end: number } | null {+ const exact = markdown.indexOf(value, from)+ if (exact >= from && exact + value.length <= to) return { start: exact, end: exact + value.length }+ const tokens = value.trim().split(/\s+/u).filter(Boolean)+ if (tokens.length === 0) return null+ const match = new RegExp(tokens.map(escapeRegExp).join("\\s+"), "u").exec(markdown.slice(from, to))+ if (!match?.[0]) return null+ return { start: from + match.index, end: from + match.index + match[0].length }+}++function snapshot(markdown: string, start: number, end: number): TextSelectionSnapshot {+ return {+ prefix: markdown.slice(0, start),+ selectedText: markdown.slice(start, end),+ suffix: markdown.slice(end),+ }+}++function escapeRegExp(value: string): string {+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")+}