Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: harden agent skill paths and outputs

nash_sub3145f448116
diff --git a/src-tauri/src/agent/runtime.rs b/src-tauri/src/agent/runtime.rs
index d0d7327c..e748536c 100644
--- a/src-tauri/src/agent/runtime.rs
+++ b/src-tauri/src/agent/runtime.rs
@@ -2156,6 +2156,36 @@ impl AgentRuntime {
"shell.exec" => {
let output: tools::ShellExecToolOutput = serde_json::from_value(value)
.map_err(|err| format!("Invalid shell.exec result: {err}"))?;
+ for generated in &output.generated_files {
+ let reference = AgentReference {
+ title: Path::new(&generated.path)
+ .file_name()
+ .and_then(|name| name.to_str())
+ .unwrap_or(&generated.path)
+ .to_string(),
+ path: generated.path.clone(),
+ kind: "workspace".to_string(),
+ snippet: Some(format!(
+ "Generated file written by shell.exec ({} bytes).",
+ generated.bytes
+ )),
+ score: None,
+ };
+ push_unique_reference(references, events, event_sink, reference);
+ }
+ let generated_summary = if output.generated_files.is_empty() {
+ String::new()
+ } else {
+ format!(
+ "\nGenerated files:\n{}",
+ output
+ .generated_files
+ .iter()
+ .map(|file| format!("- {}", file.path))
+ .collect::<Vec<_>>()
+ .join("\n")
+ )
+ };
Ok(format!(
"`{}` exit={:?} timedOut={}\nstdout:\n{}\nstderr:\n{}",
output.command,
@@ -2163,7 +2193,7 @@ impl AgentRuntime {
output.timed_out,
trim_chars(&output.stdout, 8_000),
trim_chars(&output.stderr, 4_000)
- ))
+ ) + &generated_summary)
}
_ => Ok(value.to_string()),
}
@@ -4865,6 +4895,50 @@ mod tests {
assert_eq!(events.len(), 1);
}
+ #[test]
+ fn shell_exec_generated_files_are_added_as_references() {
+ let project = tempdir_for_agent_runtime_test();
+ let runtime = AgentRuntime::new(
+ "project-1",
+ project.to_string_lossy(),
+ None,
+ None,
+ None,
+ None,
+ );
+ let mut references = Vec::new();
+ let mut events = Vec::new();
+
+ let summary = runtime
+ .record_loop_tool_success(
+ "shell.exec",
+ serde_json::json!({
+ "command": "printf image > images/cover.png",
+ "exitCode": 0,
+ "stdout": "",
+ "stderr": "",
+ "timedOut": false,
+ "generatedFiles": [
+ {
+ "path": "agent-workspace/images/cover.png",
+ "bytes": 5
+ }
+ ]
+ }),
+ &mut references,
+ &mut events,
+ &None,
+ )
+ .unwrap();
+
+ assert!(summary.contains("Generated files:"));
+ assert!(summary.contains("agent-workspace/images/cover.png"));
+ assert_eq!(references.len(), 1);
+ assert_eq!(references[0].kind, "workspace");
+ assert_eq!(references[0].path, "agent-workspace/images/cover.png");
+ assert_eq!(events.len(), 1);
+ }
+
#[test]
fn iteration_limit_answer_reports_generated_workspace_files() {
let references = vec![
diff --git a/src-tauri/src/agent/skills.rs b/src-tauri/src/agent/skills.rs
index fd364110..71b9bacb 100644
--- a/src-tauri/src/agent/skills.rs
+++ b/src-tauri/src/agent/skills.rs
@@ -99,9 +99,23 @@ fn skill_roots(project_path: &str) -> Vec<SkillRoot> {
}
fn home_dir() -> Option<PathBuf> {
- std::env::var_os("HOME")
- .or_else(|| std::env::var_os("USERPROFILE"))
- .map(PathBuf::from)
+ #[cfg(windows)]
+ {
+ std::env::var_os("USERPROFILE")
+ .or_else(|| {
+ let drive = std::env::var_os("HOMEDRIVE")?;
+ let path = std::env::var_os("HOMEPATH")?;
+ let mut home = PathBuf::from(drive);
+ home.push(path);
+ Some(home.into_os_string())
+ })
+ .or_else(|| std::env::var_os("HOME"))
+ .map(PathBuf::from)
+ }
+ #[cfg(not(windows))]
+ {
+ std::env::var_os("HOME").map(PathBuf::from)
+ }
}
fn load_one_skill_from_roots(roots: &[SkillRoot], name: &str) -> Option<AgentSkill> {
@@ -164,7 +178,11 @@ fn discover_skill_candidates_inner(dir: &Path, depth: usize, out: &mut Vec<Skill
continue;
}
if meta.is_file() {
- if path.file_name().and_then(|s| s.to_str()) == Some("SKILL.md") {
+ if path
+ .file_name()
+ .and_then(|s| s.to_str())
+ .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md"))
+ {
if let Some(id) = path
.parent()
.and_then(|parent| parent.file_name())
@@ -175,7 +193,11 @@ fn discover_skill_candidates_inner(dir: &Path, depth: usize, out: &mut Vec<Skill
}
continue;
}
- if path.extension().and_then(|s| s.to_str()) == Some("md") {
+ if path
+ .extension()
+ .and_then(|s| s.to_str())
+ .is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
+ {
if let Some(id) = path
.file_stem()
.and_then(|s| s.to_str())
@@ -254,7 +276,7 @@ fn load_skill_directory(dir: &Path, fallback_name: &str) -> Result<AgentSkill, S
if meta.file_type().is_symlink() || !meta.is_dir() {
return Err("Skill folder is not readable".to_string());
}
- let main_path = dir.join("SKILL.md");
+ let main_path = find_skill_main_file(dir).unwrap_or_else(|| dir.join("SKILL.md"));
let skill = load_skill_file(&main_path, fallback_name)?;
// Only SKILL.md is injected into the Agent prompt. Supporting Markdown
// files stay on disk and should be read lazily after the Agent has chosen
@@ -263,6 +285,19 @@ fn load_skill_directory(dir: &Path, fallback_name: &str) -> Result<AgentSkill, S
Ok(skill)
}
+fn find_skill_main_file(dir: &Path) -> Option<PathBuf> {
+ fs::read_dir(dir)
+ .ok()?
+ .flatten()
+ .find(|entry| {
+ entry
+ .file_name()
+ .to_str()
+ .is_some_and(|name| name.eq_ignore_ascii_case("SKILL.md"))
+ })
+ .map(|entry| entry.path())
+}
+
fn normalize_skill_name(value: &str) -> Option<String> {
let trimmed = value.trim();
if trimmed.is_empty()
@@ -296,6 +331,9 @@ fn split_frontmatter(raw: &str) -> (Option<String>, String) {
}
fn is_portable_skill_name(value: &str) -> bool {
+ if value.ends_with([' ', '.']) {
+ return false;
+ }
if value
.chars()
.any(|ch| matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*') || ch <= '\u{1f}')
@@ -412,7 +450,15 @@ mod tests {
#[test]
fn load_project_skills_rejects_windows_reserved_names() {
- let skills = load_project_skills("/tmp/missing", &["con".to_string(), "a:b".to_string()]);
+ let skills = load_project_skills(
+ "/tmp/missing",
+ &[
+ "con".to_string(),
+ "a:b".to_string(),
+ "topic.".to_string(),
+ "topic ".to_string(),
+ ],
+ );
assert!(skills.is_empty());
}
@@ -494,6 +540,36 @@ mod tests {
let _ = fs::remove_dir_all(root);
}
+ #[test]
+ fn list_available_skills_accepts_case_insensitive_markdown_names() {
+ let root = std::env::temp_dir().join(format!("llm-wiki-skills-{}", Uuid::new_v4()));
+ let skills_dir = root.join(".llm-wiki").join("skills");
+ fs::create_dir_all(skills_dir.join("designer")).unwrap();
+ fs::write(
+ skills_dir.join("Reviewer.MD"),
+ "---\nname: reviewer\ndescription: Review source quality\n---\nCheck claims.",
+ )
+ .unwrap();
+ fs::write(
+ skills_dir.join("designer").join("SKILL.MD"),
+ "---\nname: designer\ndescription: Design assets\n---\nCreate image prompts.",
+ )
+ .unwrap();
+
+ let skills = list_available_skills(root.to_str().unwrap());
+ let ids = skills
+ .into_iter()
+ .map(|skill| skill.id)
+ .collect::<BTreeSet<_>>();
+
+ assert!(ids.contains("Reviewer"));
+ assert!(ids.contains("designer"));
+ let loaded = load_project_skills(root.to_str().unwrap(), &["designer".to_string()]);
+ assert_eq!(loaded.len(), 1);
+ assert!(loaded[0].location.ends_with("/designer/SKILL.MD"));
+ let _ = fs::remove_dir_all(root);
+ }
+
#[test]
fn nested_skill_folder_is_listed_and_loadable() {
let root = std::env::temp_dir().join(format!("llm-wiki-skills-{}", Uuid::new_v4()));
diff --git a/src-tauri/src/agent/tools.rs b/src-tauri/src/agent/tools.rs
index ed498ceb..98e97d72 100644
--- a/src-tauri/src/agent/tools.rs
+++ b/src-tauri/src/agent/tools.rs
@@ -1,10 +1,14 @@
+use std::collections::hash_map::DefaultHasher;
use std::collections::BTreeMap;
use std::fs;
use std::fs::OpenOptions;
use std::future::Future;
+use std::hash::{Hash, Hasher};
+use std::io::{Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
use std::pin::Pin;
use std::process::Stdio;
+use std::time::SystemTime;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
@@ -33,6 +37,7 @@ const WEB_SEARCH_TIMEOUT_SECS: u64 = 30;
const SHELL_EXEC_TIMEOUT_SECS: u64 = 30;
const MAX_SHELL_COMMAND_CHARS: usize = 4_000;
const MAX_SHELL_OUTPUT_CHARS: usize = 20_000;
+const MAX_SHELL_GENERATED_FILES: usize = 50;
const SHELL_OUTPUT_DRAIN_TIMEOUT_SECS: u64 = 1;
const DEFAULT_ANYTXT_ENDPOINT: &str = "http://127.0.0.1:9920";
const DEFAULT_ANYTXT_LIMIT: usize = 20;
@@ -280,6 +285,8 @@ pub struct ShellExecToolOutput {
pub stdout: String,
pub stderr: String,
pub timed_out: bool,
+ #[serde(default)]
+ pub generated_files: Vec<WorkspaceWriteOutput>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -788,6 +795,8 @@ async fn run_shell_exec(
let workspace = agent_workspace_path(cwd);
fs::create_dir_all(&workspace)
.map_err(|err| format!("shell.exec failed to create {AGENT_WORKSPACE_DIR}: {err}"))?;
+ ensure_project_bound_path(project_path, &workspace)?;
+ let before_files = snapshot_workspace_files(&workspace);
#[cfg(windows)]
let mut child = {
let shell = std::env::var_os("ComSpec").unwrap_or_else(|| "cmd".into());
@@ -848,9 +857,93 @@ async fn run_shell_exec(
stdout,
stderr,
timed_out,
+ generated_files: changed_workspace_files(&workspace, before_files),
})
}
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+struct WorkspaceFileSnapshot {
+ len: u64,
+ modified: Option<SystemTime>,
+ content_hash: Option<u64>,
+}
+
+fn snapshot_workspace_files(workspace: &Path) -> BTreeMap<String, WorkspaceFileSnapshot> {
+ let mut files = BTreeMap::new();
+ for entry in WalkDir::new(workspace).into_iter().filter_map(Result::ok) {
+ if !entry.file_type().is_file() {
+ continue;
+ }
+ let Ok(rel) = entry.path().strip_prefix(workspace) else {
+ continue;
+ };
+ let Some(rel) = rel.to_str().map(|value| value.replace('\\', "/")) else {
+ continue;
+ };
+ let Ok(metadata) = entry.metadata() else {
+ continue;
+ };
+ files.insert(
+ rel,
+ WorkspaceFileSnapshot {
+ len: metadata.len(),
+ modified: metadata.modified().ok(),
+ content_hash: workspace_file_content_hash(entry.path(), metadata.len()),
+ },
+ );
+ }
+ files
+}
+
+fn workspace_file_content_hash(path: &Path, len: u64) -> Option<u64> {
+ // Shell-generated artifacts can be rewritten faster than some filesystems
+ // update mtimes, especially on Windows/external/network volumes. A bounded
+ // content signature prevents same-size rewrites from disappearing from the
+ // generated-output list without turning every shell command into an
+ // unbounded full-workspace read.
+ const FULL_HASH_LIMIT_BYTES: u64 = 8 * 1024 * 1024;
+ const EDGE_SAMPLE_BYTES: u64 = 64 * 1024;
+
+ let mut file = fs::File::open(path).ok()?;
+ let mut hasher = DefaultHasher::new();
+ len.hash(&mut hasher);
+ if len <= FULL_HASH_LIMIT_BYTES {
+ let mut bytes = Vec::new();
+ file.read_to_end(&mut bytes).ok()?;
+ bytes.hash(&mut hasher);
+ } else {
+ let sample = EDGE_SAMPLE_BYTES as usize;
+ let mut head = vec![0_u8; sample];
+ file.read_exact(&mut head).ok()?;
+ head.hash(&mut hasher);
+ file.seek(SeekFrom::End(-(EDGE_SAMPLE_BYTES as i64))).ok()?;
+ let mut tail = vec![0_u8; sample];
+ file.read_exact(&mut tail).ok()?;
+ tail.hash(&mut hasher);
+ }
+ Some(hasher.finish())
+}
+
+fn changed_workspace_files(
+ workspace: &Path,
+ before: BTreeMap<String, WorkspaceFileSnapshot>,
+) -> Vec<WorkspaceWriteOutput> {
+ let after = snapshot_workspace_files(workspace);
+ after
+ .into_iter()
+ .filter_map(|(rel, snapshot)| {
+ if before.get(&rel) == Some(&snapshot) {
+ return None;
+ }
+ Some(WorkspaceWriteOutput {
+ path: format!("{AGENT_WORKSPACE_DIR}/{rel}"),
+ bytes: snapshot.len as usize,
+ })
+ })
+ .take(MAX_SHELL_GENERATED_FILES)
+ .collect()
+}
+
async fn await_shell_output(mut handle: JoinHandle<String>, label: &str) -> Result<String, String> {
match timeout(
Duration::from_secs(SHELL_OUTPUT_DRAIN_TIMEOUT_SECS),
@@ -876,42 +969,57 @@ fn apply_sanitized_shell_env(command: &mut Command, project_path: &str, workspac
// Keep generated artifacts in `LLM_WIKI_AGENT_WORKSPACE`, but do not imply
// stronger process isolation here without adding a real sandbox layer.
command.env_clear();
- if let Some(path) = std::env::var_os("PATH") {
- command.env("PATH", path);
- }
- if let Some(lang) = std::env::var_os("LANG") {
- command.env("LANG", lang);
- }
+ preserve_shell_env(command, &["PATH", "LANG", "LC_ALL", "LC_CTYPE"]);
#[cfg(not(windows))]
{
- for key in ["HOME", "USER", "LOGNAME", "SHELL"] {
- if let Some(value) = std::env::var_os(key) {
- command.env(key, value);
- }
- }
+ preserve_shell_env(
+ command,
+ &[
+ "HOME",
+ "USER",
+ "LOGNAME",
+ "SHELL",
+ "TMPDIR",
+ "XDG_CONFIG_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_DATA_HOME",
+ ],
+ );
}
#[cfg(windows)]
{
- for key in [
- "ComSpec",
- "SystemRoot",
- "WINDIR",
- "PATHEXT",
- "USERPROFILE",
- "USERNAME",
- "HOMEDRIVE",
- "HOMEPATH",
- ] {
- if let Some(value) = std::env::var_os(key) {
- command.env(key, value);
- }
- }
+ preserve_shell_env(
+ command,
+ &[
+ "ComSpec",
+ "SystemRoot",
+ "WINDIR",
+ "PATHEXT",
+ "USERPROFILE",
+ "USERNAME",
+ "HOMEDRIVE",
+ "HOMEPATH",
+ "TEMP",
+ "TMP",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "ProgramData",
+ ],
+ );
}
command.env("LLM_WIKI_PROJECT", project_path);
command.env("LLM_WIKI_PROJECT_PATH", project_path);
command.env("LLM_WIKI_AGENT_WORKSPACE", workspace);
}
+fn preserve_shell_env(command: &mut Command, keys: &[&str]) {
+ for key in keys {
+ if let Some(value) = std::env::var_os(key) {
+ command.env(key, value);
+ }
+ }
+}
+
async fn read_limited_output<R>(mut reader: R, max_chars: usize) -> String
where
R: tokio::io::AsyncRead + Unpin,
@@ -2069,6 +2177,12 @@ fn validate_portable_path_segment(segment: &str) -> Result<(), String> {
if segment.is_empty() {
return Err("wiki.write_page path contains an empty segment".to_string());
}
+ if segment.ends_with([' ', '.']) {
+ return Err(
+ "wiki.write_page path contains a segment ending with a space or dot, which is not portable to Windows"
+ .to_string(),
+ );
+ }
if segment
.chars()
.any(|ch| matches!(ch, '<' | '>' | ':' | '"' | '|' | '?' | '*') || ch <= '\u{1f}')
@@ -2361,6 +2475,74 @@ mod tests {
.stdout
.replace('\\', "/")
.contains(&workspace.to_string_lossy().replace('\\', "/")));
+ assert!(output
+ .generated_files
+ .iter()
+ .any(|file| file.path == "agent-workspace/generated.txt"));
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[tokio::test]
+ async fn shell_exec_reports_changed_workspace_files() {
+ let root =
+ std::env::temp_dir().join(format!("llm-wiki-shell-generated-{}", Uuid::new_v4()));
+ fs::create_dir_all(&root).unwrap();
+ #[cfg(windows)]
+ let command = "mkdir images && echo image>images\\cover.png";
+ #[cfg(not(windows))]
+ let command = "mkdir -p images && printf image > images/cover.png";
+
+ let output = run_shell_exec(root.to_str().unwrap(), command, 5)
+ .await
+ .unwrap();
+
+ assert!(output
+ .generated_files
+ .iter()
+ .any(|file| { file.path == "agent-workspace/images/cover.png" && file.bytes > 0 }));
+ let _ = fs::remove_dir_all(root);
+ }
+
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn shell_exec_rejects_symlinked_agent_workspace_escape() {
+ use std::os::unix::fs::symlink;
+
+ let root =
+ std::env::temp_dir().join(format!("llm-wiki-shell-workspace-link-{}", Uuid::new_v4()));
+ let outside = std::env::temp_dir().join(format!(
+ "llm-wiki-shell-workspace-outside-{}",
+ Uuid::new_v4()
+ ));
+ fs::create_dir_all(&root).unwrap();
+ fs::create_dir_all(&outside).unwrap();
+ symlink(&outside, root.join(AGENT_WORKSPACE_DIR)).unwrap();
+
+ let err = run_shell_exec(root.to_str().unwrap(), "pwd", 5)
+ .await
+ .unwrap_err();
+
+ assert!(err.contains("escapes project directory"));
+ let _ = fs::remove_dir_all(root);
+ let _ = fs::remove_dir_all(outside);
+ }
+
+ #[test]
+ fn changed_workspace_files_detects_same_size_rewrites() {
+ let root =
+ std::env::temp_dir().join(format!("llm-wiki-shell-same-size-{}", Uuid::new_v4()));
+ let workspace = root.join(AGENT_WORKSPACE_DIR);
+ fs::create_dir_all(&workspace).unwrap();
+ let file = workspace.join("artifact.html");
+ fs::write(&file, "before").unwrap();
+
+ let before = snapshot_workspace_files(&workspace);
+ fs::write(&file, "after!").unwrap();
+ let changed = changed_workspace_files(&workspace, before);
+
+ assert!(changed
+ .iter()
+ .any(|file| file.path == "agent-workspace/artifact.html"));
let _ = fs::remove_dir_all(root);
}
@@ -2381,6 +2563,8 @@ mod tests {
assert!(write_workspace_file(root.to_str().unwrap(), "../escape.txt", "x").is_err());
assert!(write_workspace_file(root.to_str().unwrap(), "wiki/page.md", "x").is_err());
assert!(write_workspace_file(root.to_str().unwrap(), ".hidden/file.txt", "x").is_err());
+ assert!(write_workspace_file(root.to_str().unwrap(), "cover./file.txt", "x").is_err());
+ assert!(write_workspace_file(root.to_str().unwrap(), "cover /file.txt", "x").is_err());
assert!(write_workspace_file(
root.to_str().unwrap(),
"large.txt",
@@ -2514,6 +2698,20 @@ mod tests {
write_wiki_page_with_options(root.to_str().unwrap(), "wiki/a?b.md", "# A", false)
.is_err()
);
+ assert!(write_wiki_page_with_options(
+ root.to_str().unwrap(),
+ "wiki/topic./a.md",
+ "# A",
+ false
+ )
+ .is_err());
+ assert!(write_wiki_page_with_options(
+ root.to_str().unwrap(),
+ "wiki/topic /a.md",
+ "# A",
+ false
+ )
+ .is_err());
assert!(write_wiki_page_with_options(
root.to_str().unwrap(),
"wiki/queries/huge.md",
diff --git a/src/App.tsx b/src/App.tsx
index 6bf92b33..3d5b522a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -39,13 +39,30 @@ function App() {
async function hydrateProjectChatStore(proj: WikiProject): Promise<void> {
try {
+ const activeBeforeLoad = useChatStore.getState().activeConversationId
const savedChat = await loadChatHistory(proj.path)
if (!isCurrentProject(proj)) return
+ const stateAfterLoad = useChatStore.getState()
+ const activeChangedDuringLoad = stateAfterLoad.activeConversationId !== activeBeforeLoad
if (savedChat.conversations.length > 0) {
- useChatStore.getState().setConversations(savedChat.conversations)
- useChatStore.getState().setMessages(savedChat.messages)
+ const existingConversations = activeChangedDuringLoad ? stateAfterLoad.conversations : []
+ const existingMessages = activeChangedDuringLoad ? stateAfterLoad.messages : []
+ const mergedConversations = [
+ ...existingConversations,
+ ...savedChat.conversations.filter(
+ (conversation) => !existingConversations.some((existing) => existing.id === conversation.id)
+ ),
+ ]
+ const mergedMessages = [
+ ...existingMessages,
+ ...savedChat.messages.filter(
+ (message) => !existingMessages.some((existing) => existing.id === message.id)
+ ),
+ ]
+ useChatStore.getState().setConversations(mergedConversations)
+ useChatStore.getState().setMessages(mergedMessages)
const sorted = [...savedChat.conversations].sort((a, b) => b.updatedAt - a.updatedAt)
- if (sorted[0]) {
+ if (!activeChangedDuringLoad && sorted[0]) {
useChatStore.getState().setActiveConversation(sorted[0].id)
}
}
diff --git a/src/components/chat/chat-input.test.ts b/src/components/chat/chat-input.test.ts
index bcd668b0..0ad103a5 100644
--- a/src/components/chat/chat-input.test.ts
+++ b/src/components/chat/chat-input.test.ts
@@ -70,6 +70,16 @@ describe("chat slash skill helpers", () => {
])
})
+ it("returns every matching skill by default", () => {
+ const manySkills = Array.from({ length: 12 }, (_, index) => ({
+ id: `skill-${index}`,
+ name: `Skill ${index}`,
+ source: "project",
+ }))
+
+ expect(filterSlashSkillOptions(manySkills, "", (source) => source)).toHaveLength(12)
+ })
+
it("maps boundary deletion to whole skill chips without hijacking forward-delete text editing", () => {
expect(skillChipDeleteTarget("Backspace", "hello", 0, 0, 2)).toBe("last")
expect(skillChipDeleteTarget("Delete", "", 0, 0, 2)).toBe("first")
diff --git a/src/components/chat/chat-input.tsx b/src/components/chat/chat-input.tsx
index bccc072d..e115f6f0 100644
--- a/src/components/chat/chat-input.tsx
+++ b/src/components/chat/chat-input.tsx
@@ -26,7 +26,6 @@ export interface ChatSendOptions {
}
const AGENT_MODE_OPTIONS: ChatAgentMode[] = ["fast", "standard", "deep", "local_first"]
-const MAX_SLASH_SKILL_RESULTS = 8
export interface ChatSkillOption {
id: string
@@ -67,7 +66,7 @@ export function filterSlashSkillOptions(
skills: ChatSkillOption[],
query: string,
sourceLabel: (source: string) => string,
- limit = MAX_SLASH_SKILL_RESULTS,
+ limit = Number.POSITIVE_INFINITY,
): ChatSkillOption[] {
const normalized = query.trim().toLowerCase()
return skills
diff --git a/src/components/chat/chat-message.tsx b/src/components/chat/chat-message.tsx
index d51afc71..07a6c115 100644
--- a/src/components/chat/chat-message.tsx
+++ b/src/components/chat/chat-message.tsx
@@ -1,5 +1,6 @@
import { memo, useCallback, useEffect, useRef, useState, useMemo } from "react"
import { useTranslation } from "react-i18next"
+import { convertFileSrc } from "@tauri-apps/api/core"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
import remarkMath from "remark-math"
@@ -18,7 +19,7 @@ import type { DisplayMessage, MessageReference } from "@/stores/chat-store"
import type { FileNode } from "@/types/wiki"
import { convertLatexToUnicode } from "@/lib/latex-to-unicode"
-import { normalizePath, getFileName } from "@/lib/path-utils"
+import { normalizePath, getFileName, isAbsolutePath } from "@/lib/path-utils"
import { makeQueryFileName } from "@/lib/wiki-filename"
import { hasUsableLlm } from "@/lib/has-usable-llm"
import { messageImageToDataUrl } from "@/lib/chat-image-utils"
@@ -33,7 +34,7 @@ import { cleanAssistantContentForWikiSave, titleFromCleanAssistantContent } from
import type { ChatAgentEvent, ChatAgentEventStage, ChatAgentStep, ChatUserInputField, ChatUserInputRequest } from "@/lib/chat-agent-types"
import { filterRawSourceTree } from "@/lib/source-filter"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
-import { getFileCategory, isTextReadable } from "@/lib/file-types"
+import { getFileCategory, getFileExtension, isTextReadable } from "@/lib/file-types"
// Module-level cache of source file names
let cachedSourceFiles: string[] = []
@@ -651,10 +652,19 @@ function projectAbsolutePath(projectPath: string, path: string): string {
const pp = normalizePath(projectPath)
const normalized = normalizePath(path)
if (normalized.startsWith(`${pp}/`)) return normalized
- if (normalized.startsWith("/")) return normalized
+ if (isAbsolutePath(normalized)) return normalized
return `${pp}/${normalized.replace(/^\/+/, "")}`
}
+function isAgentWorkspacePath(filePath: string): boolean {
+ return normalizePath(filePath).split("/").includes("agent-workspace")
+}
+
+function isGeneratedOutputImage(filePath: string): boolean {
+ const category = getFileCategory(filePath)
+ return category === "image" || (getFileExtension(filePath) === "svg" && isAgentWorkspacePath(filePath))
+}
+
/**
* Markdown image-reference regex used to count `![](url)` occurrences
* in cited pages AND extract the first URL (so the image-badge
@@ -983,19 +993,36 @@ function CitedReferencesPanel({
const refType = getRefType(page.path, page)
const config = REF_TYPE_CONFIG[refType] ?? REF_TYPE_CONFIG.source
const Icon = config.icon
+ const absoluteOutputPath = project ? projectAbsolutePath(project.path, page.path) : page.path
+ const isImageOutput = isGeneratedOutputImage(absoluteOutputPath)
+ const imageSrc = isImageOutput ? convertFileSrc(absoluteOutputPath) : null
return (
<div
key={page.path}
- className="flex w-full items-center gap-1.5 rounded text-left"
+ className="flex w-full items-start gap-1.5 rounded text-left"
title={page.path}
>
- <span className="text-[10px] text-primary/60 w-4 shrink-0 text-right">[{i + 1}]</span>
+ <span className="mt-1 text-[10px] text-primary/60 w-4 shrink-0 text-right">[{i + 1}]</span>
<button
type="button"
onClick={() => openCitedPage(page)}
- className="flex min-w-0 flex-1 items-center gap-1.5 rounded px-1 py-0.5 text-left hover:bg-primary/10 transition-colors"
+ className="flex min-w-0 flex-1 items-start gap-2 rounded px-1 py-1 text-left hover:bg-primary/10 transition-colors"
>
- <Icon className={`h-3 w-3 shrink-0 ${config.color}`} />
+ {imageSrc ? (
+ <span className="h-14 w-20 shrink-0 overflow-hidden rounded border border-primary/20 bg-background/80">
+ <img
+ src={imageSrc}
+ alt={page.title}
+ loading="lazy"
+ className="h-full w-full object-cover"
+ onError={(event) => {
+ event.currentTarget.style.opacity = "0"
+ }}
+ />
+ </span>
+ ) : (
+ <Icon className={`mt-0.5 h-3 w-3 shrink-0 ${config.color}`} />
+ )}
<span className="min-w-0 flex-1 text-foreground/90">
<span className="block truncate">{page.title}</span>
<span className="mt-0.5 block truncate text-[10px] text-muted-foreground/75">
diff --git a/src/components/chat/chat-panel.tsx b/src/components/chat/chat-panel.tsx
index db4fc699..ca7900e7 100644
--- a/src/components/chat/chat-panel.tsx
+++ b/src/components/chat/chat-panel.tsx
@@ -1,6 +1,6 @@
import { useRef, useEffect, useCallback, useState } from "react"
import { useTranslation } from "react-i18next"
-import { invoke } from "@tauri-apps/api/core"
+import { convertFileSrc, invoke } from "@tauri-apps/api/core"
import { listen } from "@tauri-apps/api/event"
import { BookOpen, Plus, Trash2, MessageSquare, X, Maximize2, FolderOpen, FileText } from "lucide-react"
import { Button } from "@/components/ui/button"
@@ -12,7 +12,7 @@ import { isReasoningOnlyResponseError, streamChat } from "@/lib/llm-client"
import { supportsImageInput } from "@/lib/llm-providers"
import { executeIngestWrites } from "@/lib/ingest"
import { deleteFile, readFile } from "@/commands/fs"
-import { getFileName, normalizePath } from "@/lib/path-utils"
+import { getFileName, isAbsolutePath, normalizePath } from "@/lib/path-utils"
import { hasConfiguredAnyTxt } from "@/lib/anytxt-search"
import type { ChatAgentEvent, ChatAgentStep, ChatUserInputRequest } from "@/lib/chat-agent-types"
import type { ChatMessage as LlmChatMessage, ContentBlock } from "@/lib/llm-client"
@@ -20,7 +20,7 @@ import { FilePreview } from "@/components/editor/file-preview"
import { WikiReader } from "@/components/editor/wiki-reader"
import { FrontmatterPanel } from "@/components/editor/frontmatter-panel"
import { parseFrontmatter } from "@/lib/frontmatter"
-import { getFileCategory, isTextReadable } from "@/lib/file-types"
+import { getFileCategory, getFileExtension, isTextReadable } from "@/lib/file-types"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
type InternalChatSendOptions = ChatSendOptions & {
@@ -212,10 +212,19 @@ function projectAbsolutePath(projectPath: string, path: string): string {
const pp = normalizePath(projectPath)
const normalized = normalizePath(path)
if (normalized.startsWith(`${pp}/`)) return normalized
- if (normalized.startsWith("/")) return normalized
+ if (isAbsolutePath(normalized)) return normalized
return `${pp}/${normalized.replace(/^\/+/, "")}`
}
+function isAgentWorkspacePath(filePath: string): boolean {
+ return normalizePath(filePath).split("/").includes("agent-workspace")
+}
+
+function isGeneratedOutputImage(filePath: string): boolean {
+ const category = getFileCategory(filePath)
+ return category === "image" || (getFileExtension(filePath) === "svg" && isAgentWorkspacePath(filePath))
+}
+
function backendToolToAgentStep(event: BackendAgentToolEvent, index: number) {
if (event.tool === "agent.plan_tools") {
return {
@@ -384,6 +393,7 @@ export function ChatPanel() {
const activeRunSessionIdRef = useRef<string | null>(null)
const activeRunIdRef = useRef<string | null>(null)
const runIdRef = useRef(0)
+ const dismissedGeneratedOutputsKeyRef = useRef<string | null>(null)
const scrollContainerRef = useRef<HTMLDivElement>(null)
const bottomRef = useRef<HTMLDivElement>(null)
const [agentEvents, setAgentEvents] = useState<ChatAgentEvent[]>([])
@@ -447,7 +457,12 @@ export function ChatPanel() {
const activeStreaming = Boolean(isStreaming && activeConversationId && streamingConversationId === activeConversationId)
const activeAgentEvents = activeStreaming ? agentEvents : []
const lastMessage = activeMessages[activeMessages.length - 1]
- const lastAssistantMessage = [...activeMessages].reverse().find((message) => message.role === "assistant")
+ const latestGeneratedOutputMessage = [...activeMessages]
+ .reverse()
+ .find((message) =>
+ message.role === "assistant"
+ && (message.references ?? []).some((ref) => ref.kind === "workspace")
+ )
const scrollKey = [
activeConversationId ?? "",
activeMessages.length,
@@ -468,11 +483,12 @@ export function ChatPanel() {
setReferencePreview(null)
setGeneratedOutputPreviews([])
setGeneratedOutputPreview(null)
+ dismissedGeneratedOutputsKeyRef.current = null
}, [activeConversationId])
useEffect(() => {
- if (!project || activeStreaming || !lastAssistantMessage) return
- const outputs = (lastAssistantMessage.references ?? []).filter((ref) => ref.kind === "workspace")
+ if (!project || activeStreaming || !latestGeneratedOutputMessage) return
+ const outputs = (latestGeneratedOutputMessage.references ?? []).filter((ref) => ref.kind === "workspace")
if (outputs.length === 0) return
const previews = outputs.map((ref) => {
const outputPath = projectAbsolutePath(project.path, ref.path)
@@ -486,10 +502,12 @@ export function ChatPanel() {
})
const currentKey = generatedOutputPreviews.map((preview) => preview.path).join("\n")
const nextKey = previews.map((preview) => preview.path).join("\n")
+ const scopedNextKey = `${activeConversationId ?? ""}:${nextKey}`
+ if (dismissedGeneratedOutputsKeyRef.current === scopedNextKey) return
if (currentKey === nextKey) return
setReferencePreview(null)
setGeneratedOutputPreviews(previews)
- }, [activeStreaming, generatedOutputPreviews, lastAssistantMessage, project])
+ }, [activeConversationId, activeStreaming, generatedOutputPreviews, latestGeneratedOutputMessage, project])
const loadGeneratedOutputPreview = useCallback(async (preview: ChatReferencePreview): Promise<ChatReferencePreview> => {
const category = getFileCategory(preview.path)
@@ -509,6 +527,13 @@ export function ChatPanel() {
void loadGeneratedOutputPreview(preview).then(setGeneratedOutputPreview)
}, [loadGeneratedOutputPreview])
+ const closeGeneratedOutputsPanel = useCallback(() => {
+ const currentKey = generatedOutputPreviews.map((preview) => preview.path).join("\n")
+ dismissedGeneratedOutputsKeyRef.current = `${activeConversationId ?? ""}:${currentKey}`
+ setGeneratedOutputPreviews([])
+ setGeneratedOutputPreview(null)
+ }, [activeConversationId, generatedOutputPreviews])
+
const handleOpenReferencePreview = useCallback((preview: ChatReferencePreview, relatedPreviews?: ChatReferencePreview[]) => {
const isGeneratedOutput = preview.source === "Workspace"
|| normalizePath(preview.path).split("/").includes("agent-workspace")
@@ -677,6 +702,22 @@ export function ChatPanel() {
seenRefs.add(key)
references.push(ref)
}
+ if (ref.kind === "workspace" && project) {
+ const outputPath = projectAbsolutePath(project.path, ref.path)
+ const preview: ChatReferencePreview = {
+ title: ref.title || getFileName(outputPath),
+ path: outputPath,
+ source: ref.source ?? "Workspace",
+ content: "",
+ snippet: ref.snippet,
+ }
+ dismissedGeneratedOutputsKeyRef.current = null
+ setReferencePreview(null)
+ setGeneratedOutputPreviews((prev) => {
+ if (prev.some((item) => item.path === preview.path)) return prev
+ return [...prev, preview]
+ })
+ }
return
}
if (agentEvent.type === "userInputRequired" && agentEvent.request) {
@@ -1210,10 +1251,7 @@ export function ChatPanel() {
<GeneratedOutputsPanel
outputs={generatedOutputPreviews}
onOpen={openGeneratedOutputModal}
- onClose={() => {
- setGeneratedOutputPreviews([])
- setGeneratedOutputPreview(null)
- }}
+ onClose={closeGeneratedOutputsPanel}
/>
)}
{generatedOutputPreview && (
@@ -1260,6 +1298,8 @@ function GeneratedOutputsPanel({
<div className="space-y-1">
{outputs.map((output) => {
const title = output.title || getFileName(output.path)
+ const isImageOutput = isGeneratedOutputImage(output.path)
+ const imageSrc = isImageOutput ? convertFileSrc(output.path) : null
return (
<button
key={output.path}
@@ -1268,7 +1308,21 @@ function GeneratedOutputsPanel({
className="group flex w-full items-start gap-2 rounded-md border border-border/60 bg-muted/20 px-2 py-2 text-left transition-colors hover:border-primary/30 hover:bg-primary/5"
title={output.path}
>
- <FileText className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground group-hover:text-primary" />
+ {imageSrc ? (
+ <span className="h-10 w-12 shrink-0 overflow-hidden rounded border border-primary/20 bg-background/80">
+ <img
+ src={imageSrc}
+ alt={title}
+ loading="lazy"
+ className="h-full w-full object-cover"
+ onError={(event) => {
+ event.currentTarget.style.opacity = "0"
+ }}
+ />
+ </span>
+ ) : (
+ <FileText className="mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground group-hover:text-primary" />
+ )}
<span className="min-w-0 flex-1">
<span className="block truncate text-xs font-medium text-foreground">{title}</span>
<span className="mt-0.5 block truncate text-[10px] text-muted-foreground">{output.path}</span>
diff --git a/src/components/settings/sections/skills-section.tsx b/src/components/settings/sections/skills-section.tsx
index 3c3d3cc6..894dd5cc 100644
--- a/src/components/settings/sections/skills-section.tsx
+++ b/src/components/settings/sections/skills-section.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { invoke } from "@tauri-apps/api/core"
-import { RefreshCw, Sparkles } from "lucide-react"
+import { RefreshCw, Search, Sparkles } from "lucide-react"
import { Button } from "@/components/ui/button"
import { useChatStore } from "@/stores/chat-store"
import { useWikiStore } from "@/stores/wiki-store"
@@ -32,9 +32,24 @@ export function SkillsSection() {
const [skills, setSkills] = useState<AvailableAgentSkill[]>([])
const [loading, setLoading] = useState(false)
const [status, setStatus] = useState<string | null>(null)
+ const [searchQuery, setSearchQuery] = useState("")
const disabled = useMemo(() => new Set(disabledSkills), [disabledSkills])
const enabledCount = skills.filter((skill) => !disabled.has(skill.id)).length
+ const filteredSkills = useMemo(() => {
+ const query = searchQuery.trim().toLowerCase()
+ if (!query) return skills
+ return skills.filter((skill) => {
+ const fields = [
+ skill.name,
+ skill.id,
+ skill.description ?? "",
+ sourceLabel(skill.source, t),
+ skill.source,
+ ]
+ return fields.some((field) => field.toLowerCase().includes(query))
+ })
+ }, [searchQuery, skills, t])
const persist = useCallback(async (nextSelected: string[], nextDisabled: string[]) => {
if (!project?.path) return
@@ -130,25 +145,39 @@ export function SkillsSection() {
})}
</div>
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="text-sm text-muted-foreground">
- {t("settings.sections.skills.summary", {
- defaultValue: "{{enabled}} enabled / {{total}} discovered",
- enabled: enabledCount,
- total: skills.length,
- })}
+ <div className="space-y-2">
+ <div className="relative">
+ <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ <input
+ type="search"
+ value={searchQuery}
+ onChange={(event) => setSearchQuery(event.target.value)}
+ placeholder={t("settings.sections.skills.searchPlaceholder", {
+ defaultValue: "Search skills by name, id, description, or source...",
+ })}
+ className="h-10 w-full rounded-md border bg-background pl-9 pr-3 text-sm outline-none transition-colors placeholder:text-muted-foreground focus:border-primary"
+ />
</div>
- <div className="flex items-center gap-2">
- <Button type="button" variant="outline" size="sm" onClick={() => void setAllEnabled(true)} disabled={skills.length === 0}>
- {t("settings.sections.skills.enableAll", { defaultValue: "Enable all" })}
- </Button>
- <Button type="button" variant="outline" size="sm" onClick={() => void setAllEnabled(false)} disabled={skills.length === 0}>
- {t("settings.sections.skills.disableAll", { defaultValue: "Disable all" })}
- </Button>
- <Button type="button" variant="outline" size="sm" onClick={() => void scan()} disabled={loading || !project}>
- <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
- {t("settings.sections.skills.refresh", { defaultValue: "Rescan" })}
- </Button>
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="text-sm text-muted-foreground">
+ {t("settings.sections.skills.summary", {
+ defaultValue: "{{enabled}} enabled / {{total}} discovered",
+ enabled: enabledCount,
+ total: skills.length,
+ })}
+ </div>
+ <div className="flex items-center gap-2">
+ <Button type="button" variant="outline" size="sm" onClick={() => void setAllEnabled(true)} disabled={skills.length === 0}>
+ {t("settings.sections.skills.enableAll", { defaultValue: "Enable all" })}
+ </Button>
+ <Button type="button" variant="outline" size="sm" onClick={() => void setAllEnabled(false)} disabled={skills.length === 0}>
+ {t("settings.sections.skills.disableAll", { defaultValue: "Disable all" })}
+ </Button>
+ <Button type="button" variant="outline" size="sm" onClick={() => void scan()} disabled={loading || !project}>
+ <RefreshCw className={`mr-1.5 h-3.5 w-3.5 ${loading ? "animate-spin" : ""}`} />
+ {t("settings.sections.skills.refresh", { defaultValue: "Rescan" })}
+ </Button>
+ </div>
</div>
</div>
@@ -161,9 +190,16 @@ export function SkillsSection() {
defaultValue: "No skills found. Add SKILL.md files to a scanned folder, then rescan.",
})}
</div>
+ ) : filteredSkills.length === 0 ? (
+ <div className="rounded-md border border-dashed p-6 text-center text-sm text-muted-foreground">
+ <Search className="mx-auto mb-2 h-5 w-5 opacity-50" />
+ {t("settings.sections.skills.noSearchResults", {
+ defaultValue: "No skills match this search.",
+ })}
+ </div>
) : (
<div className="space-y-2">
- {skills.map((skill) => {
+ {filteredSkills.map((skill) => {
const active = !disabled.has(skill.id)
return (
<div
diff --git a/src/i18n/en.json b/src/i18n/en.json
index 9e4ffe5a..e407cdb6 100644
--- a/src/i18n/en.json
+++ b/src/i18n/en.json
@@ -321,8 +321,10 @@
"enableAll": "Enable all",
"disableAll": "Disable all",
"refresh": "Rescan",
+ "searchPlaceholder": "Search skills by name, id, description, or source...",
"scanDone": "Found {{count}} skills.",
"empty": "No skills found. Add SKILL.md files to a scanned folder, then rescan.",
+ "noSearchResults": "No skills match this search.",
"enabled": "Enabled",
"disabled": "Disabled"
},
diff --git a/src/i18n/zh.json b/src/i18n/zh.json
index 6eb15654..63df7612 100644
--- a/src/i18n/zh.json
+++ b/src/i18n/zh.json
@@ -321,8 +321,10 @@
"enableAll": "全部启用",
"disableAll": "全部禁用",
"refresh": "重新扫描",
+ "searchPlaceholder": "按名称、ID、描述或来源搜索 Skill...",
"scanDone": "发现 {{count}} 个 Skill。",
"empty": "未找到 Skill。请在扫描目录中添加 SKILL.md 后重新扫描。",
+ "noSearchResults": "没有匹配当前搜索的 Skill。",
"enabled": "已启用",
"disabled": "已禁用"
},
diff --git a/src/stores/chat-store.test.ts b/src/stores/chat-store.test.ts
index 700a3b55..74dee93f 100644
--- a/src/stores/chat-store.test.ts
+++ b/src/stores/chat-store.test.ts
@@ -54,6 +54,29 @@ describe("chat-store conversation isolation", () => {
expect(useChatStore.getState().isStreaming).toBe(true)
})
+ it("clears stale stream content when creating or switching conversations", () => {
+ const first = useChatStore.getState().createConversation()
+ useChatStore.setState({
+ streamingContent: "old conversation tokens",
+ isStreaming: true,
+ })
+
+ const second = useChatStore.getState().createConversation()
+
+ expect(useChatStore.getState().activeConversationId).toBe(second)
+ expect(useChatStore.getState().streamingContent).toBe("")
+ expect(useChatStore.getState().isStreaming).toBe(false)
+
+ useChatStore.setState({
+ streamingContent: "more stale tokens",
+ isStreaming: true,
+ })
+ useChatStore.getState().setActiveConversation(first)
+
+ expect(useChatStore.getState().activeConversationId).toBe(first)
+ expect(useChatStore.getState().streamingContent).toBe("")
+ })
+
it("stores selected skills per conversation and starts new conversations empty", () => {
const first = useChatStore.getState().createConversation()
useChatStore.getState().setSelectedSkills(["cover-image"])
diff --git a/src/stores/chat-store.ts b/src/stores/chat-store.ts
index c15ec4bb..4bd1359e 100644
--- a/src/stores/chat-store.ts
+++ b/src/stores/chat-store.ts
@@ -128,6 +128,8 @@ export const useChatStore = create<ChatState>((set, get) => ({
set((state) => ({
conversations: [newConversation, ...state.conversations],
activeConversationId: id,
+ isStreaming: false,
+ streamingContent: "",
selectedSkills: [],
}))
return id
@@ -151,6 +153,7 @@ export const useChatStore = create<ChatState>((set, get) => ({
setActiveConversation: (id) =>
set((state) => ({
activeConversationId: id,
+ streamingContent: "",
selectedSkills: state.conversations.find((conversation) => conversation.id === id)?.selectedSkills ?? [],
})),