Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
Feat/code UI (#8431)
jjchen01f66fb956de52
diff --git a/.gitignore b/.gitignoreindex bcec1fcdd..9064ea68d 100644--- a/.gitignore+++ b/.gitignore@@ -1,5 +1,7 @@.enverror.log+# Runtime agent workspace scaffolded by ensure_project (not source)+.jan/node_modules*.tgzdistdiff --git a/src-tauri/src/core/agent/commands.rs b/src-tauri/src/core/agent/commands.rsindex 1a3bf4e30..12f73b120 100644--- a/src-tauri/src/core/agent/commands.rs+++ b/src-tauri/src/core/agent/commands.rs@@ -14,8 +14,13 @@ use tokio::sync::{mpsc, oneshot, Mutex};use crate::core::agent::events::StreamEvent;use crate::core::agent::permissions::ToolPermissions;-use crate::core::agent::project::{ensure_project, load_agent_config, permissions_from};+use crate::core::agent::project::{+ agent_toml_path, ensure_project, load_agent_config, permissions_from,+ set_skills_enabled_in_agent_toml,+};use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs};+use crate::core::agent::skill_hub;+use crate::core::agent::skills::{self, SkillMeta};use crate::core::agent::tools::gate::PermissionDecision;use crate::core::app::commands::get_jan_data_folder_path;use crate::core::state::AppState;@@ -146,3 +151,83 @@ pub async fn agent_permission_respond(}Ok(())}++/// Strip the internal `ERROR: ` prefix (an agent-tool-output convention) so the+/// message reads cleanly in a UI toast.+fn ui_error(e: String) -> String {+ e.strip_prefix("ERROR: ").map(str::to_string).unwrap_or(e)+}++/// List the skills under `<project>/.jan/agent/skills/` (folder `<name>/SKILL.md`+/// and legacy flat `<name>.md`). These are the same skills `load_skills` injects+/// into the agent's system prompt; managing them here is CRUD over that+/// directory. Read-only: returns empty when the project isn't scaffolded yet.+#[tauri::command]+pub async fn agent_skill_list(project: String) -> Result<Vec<SkillMeta>, String> {+ let root = std::path::PathBuf::from(&project);+ Ok(skills::list_meta(&root))+}++/// Read one skill's raw SKILL.md (frontmatter included) for the editor.+#[tauri::command]+pub async fn agent_skill_read(project: String, name: String) -> Result<String, String> {+ let root = std::path::PathBuf::from(&project);+ skills::read_raw(&root, &name).map_err(ui_error)+}++/// Create or overwrite a skill. New skills are written as `<name>/SKILL.md`;+/// existing ones keep their on-disk form. `name` is sanitized (no path escape).+#[tauri::command]+pub async fn agent_skill_write(+ project: String,+ name: String,+ content: String,+) -> Result<(), String> {+ let root = std::path::PathBuf::from(&project);+ ensure_project(&root)?;+ skills::write(&root, &name, &content).map_err(ui_error)+}++/// Delete a skill by name. Idempotent: a missing skill is treated as success.+#[tauri::command]+pub async fn agent_skill_delete(project: String, name: String) -> Result<(), String> {+ let root = std::path::PathBuf::from(&project);+ skills::delete(&root, &name).map_err(ui_error)+}++/// List the skills available on Anthropic's public skill hub (name + purpose).+#[tauri::command]+pub async fn agent_skill_hub_list() -> Result<Vec<skill_hub::HubSkill>, String> {+ skill_hub::list().await.map_err(ui_error)+}++/// Download a hub skill (SKILL.md + bundled files) into the project as+/// `<name>/SKILL.md`. Scaffolds the project on first use.+#[tauri::command]+pub async fn agent_skill_hub_import(project: String, name: String) -> Result<(), String> {+ let root = std::path::PathBuf::from(&project);+ ensure_project(&root)?;+ skill_hub::import(&root, &name).await.map_err(ui_error)+}++/// Read the project's enabled-skill whitelist (`[skills].enabled`). An empty+/// list means all skills are enabled.+#[tauri::command]+pub async fn agent_skill_enabled_get(project: String) -> Result<Vec<String>, String> {+ let root = std::path::PathBuf::from(&project);+ Ok(load_agent_config(&root)+ .map(|c| c.skills.enabled)+ .unwrap_or_default())+}++/// Set the project's enabled-skill whitelist. Empty = all skills enabled.+/// Persisted to `[skills].enabled` in agent.toml (format-preserving).+#[tauri::command]+pub async fn agent_skill_enabled_set(+ project: String,+ enabled: Vec<String>,+) -> Result<(), String> {+ let root = std::path::PathBuf::from(&project);+ ensure_project(&root)?;+ set_skills_enabled_in_agent_toml(&agent_toml_path(&root), &enabled).map_err(ui_error)+}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 3f2645d87..5e698dee1 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -4,44 +4,45 @@use std::path::Path;+use crate::core::agent::skills;+/// Built-in guide teaching the model the skills/memory file conventions. Always/// injected for project runs so the model can read and maintain both without/// prior knowledge. Embedded in the binary at compile time.const DEFAULT_SKILL_GUIDE: &str = include_str!("default_skill.md");-/// Read `<project_root>/.jan/agent/skills/*.md`, sorted by filename, and-/// concatenate them into one skills block. Empty files are skipped. Returns-/// None when the skills dir is absent or holds no non-empty markdown.+/// Build the skills catalog for the system prompt: one `## Skill: <name>` entry+/// per skill with its one-line description only — NOT the full body. Progressive+/// disclosure: the model calls `skill_read` to pull a skill's full instructions+/// on demand, so a large skill library costs ~a description each, not full text.+/// Covers folder skills (`<name>/SKILL.md`) and legacy flat `<name>.md`. Returns+/// None when no advertisable skill exists.pub(crate) fn load_skills(project_root: &Path) -> Option<String> {- let skills_dir = project_root.join(".jan").join("agent").join("skills");- let mut paths: Vec<_> = std::fs::read_dir(&skills_dir)- .ok()?- .filter_map(|e| e.ok().map(|e| e.path()))- .filter(|p| p.extension().and_then(|e| e.to_str()) == Some("md"))- .collect();- paths.sort();-- let mut sections = Vec::new();- for path in paths {- let Ok(content) = std::fs::read_to_string(&path) else {- continue;- };- let trimmed = content.trim();- if trimmed.is_empty() {- continue;- }- let name = path- .file_stem()- .and_then(|s| s.to_str())- .unwrap_or("skill");- sections.push(format!("## Skill: {name}\n\n{trimmed}"));- }-- if sections.is_empty() {- None- } else {- Some(format!("# Available Skills\n\n{}", sections.join("\n\n")))+ // Honor the project's `[skills].enabled` whitelist (empty = all). Reading the+ // config here keeps load_skills self-contained; a missing/malformed config+ // falls back to "all skills" rather than erroring.+ let enabled = crate::core::agent::project::load_agent_config(project_root)+ .ok()+ .map(|c| c.skills.enabled)+ .unwrap_or_default();+ let entries = skills::catalog(project_root, &enabled);+ if entries.is_empty() {+ return None;}+ let list = entries+ .iter()+ .map(|m| {+ if m.description.is_empty() {+ format!("## Skill: {}", m.name)+ } else {+ format!("## Skill: {}\n\n{}", m.name, m.description)+ }+ })+ .collect::<Vec<_>>()+ .join("\n\n");+ Some(format!(+ "# Available Skills\n\nEach skill below lists its name and purpose. Before applying a skill, call `skill_read` with its name to load its full instructions.\n\n{list}"+ ))}/// Assemble the project system prompt: the optional base prompt, the always-on@@ -104,6 +105,23 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ #[test]+ fn catalog_advertises_description_not_full_body() {+ let root = scratch_project("catalog");+ write_skill(+ &root,+ "deploy.md",+ "---\ndescription: How to deploy\n---\n\nSECRET_BODY_MARKER run ./deploy.sh",+ );+ let block = load_skills(&root).expect("skills block");+ assert!(block.contains("## Skill: deploy"));+ assert!(block.contains("How to deploy"));+ // Progressive disclosure: the body stays out of the prompt until read.+ assert!(!block.contains("SECRET_BODY_MARKER"));+ assert!(block.contains("skill_read"));+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn build_system_prompt_orders_base_guide_then_skills() {let root = scratch_project("merge");diff --git a/src-tauri/src/core/agent/default_skill.md b/src-tauri/src/core/agent/default_skill.mdindex 971c58b98..ea2e20f58 100644--- a/src-tauri/src/core/agent/default_skill.md+++ b/src-tauri/src/core/agent/default_skill.md@@ -9,13 +9,17 @@ naming for you.## SkillsA skill is a reusable procedure for this project: how to run the tests, how to-deploy, a coding convention, a checklist. Every skill is loaded into your-context automatically at the start of each run, so you already have their-contents and do not need to read them.--- `skill_list` - see which skills exist before adding or changing one.+deploy, a coding convention, a checklist. The "Available Skills" section of your+system prompt is a catalog: it lists each skill's name and a one-line purpose,+but NOT its full instructions. When a skill's purpose matches the task, call+`skill_read` to load its complete instructions before applying it.++- `skill_list` - list skills with their descriptions.+- `skill_read` (name) - load a skill's full instructions. Do this before+ applying a skill; the catalog only shows its purpose.- `skill_write` (name, content) - create a new skill or update an existing one(same name overwrites). Use a short, descriptive name; keep the skill concise.+ Start the skill with a one-line description so the catalog can summarize it.Create or update a skill when you discover a procedure worth reusing on laterruns. Refine an existing skill instead of duplicating it.diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex f2a92732d..566999e04 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -106,6 +106,7 @@ pub fn describe_tool_call(name: &str, args: &serde_json::Value) -> String {"skill_list" => Some(("Reading", "skill", String::new())),"memory_read" => Some(("Reading", "memory", arg_name(args))),"memory_write" => Some(("Updating", "memory", arg_name(args))),+ "skill_read" => Some(("Reading", "skill", arg_name(args))),"skill_write" => Some(("Updating", "skill", arg_name(args))),_ => None,};diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex b7f7fa98b..462bda42b 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -11,6 +11,8 @@ pub mod memory;pub mod permissions;pub mod project;pub mod session;+pub mod skill_hub;+pub mod skills;pub mod subagent;pub mod tools;pub mod upstream;diff --git a/src-tauri/src/core/agent/project.rs b/src-tauri/src/core/agent/project.rsindex da23f4ed7..704aca3c6 100644--- a/src-tauri/src/core/agent/project.rs+++ b/src-tauri/src/core/agent/project.rs@@ -16,6 +16,17 @@ pub(crate) struct AgentToml {pub agent: AgentSection,#[serde(default)]pub tools: ToolsSection,+ #[serde(default)]+ pub skills: SkillsSection,+}++/// `[skills]` — which project skills are advertised to the model. An empty+/// `enabled` list means "all skills" (backward-compatible with the scaffold+/// template, which ships `enabled = []`); a non-empty list is a whitelist.+#[derive(Debug, Clone, Default, Deserialize)]+pub(crate) struct SkillsSection {+ #[serde(default)]+ pub enabled: Vec<String>,}/// `[agent]` — resolves the model and default turn cap for CLI agent runs.@@ -147,6 +158,29 @@ pub(crate) fn set_model_in_agent_toml(path: &Path, model: &str) -> Result<(), St.map_err(|e| format!("Failed to write {}: {e}", path.display()))}+/// Persist `[skills].enabled` into the agent.toml at `path`, format-preserving+/// (comments kept). An empty list clears the whitelist (= all skills enabled).+pub(crate) fn set_skills_enabled_in_agent_toml(+ path: &Path,+ enabled: &[String],+) -> Result<(), String> {+ let raw = std::fs::read_to_string(path)+ .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;+ let mut doc = raw+ .parse::<toml_edit::DocumentMut>()+ .map_err(|e| format!("Failed to parse {}: {e}", path.display()))?;++ let skills = doc["skills"].or_insert(toml_edit::Item::Table(toml_edit::Table::new()));+ let mut arr = toml_edit::Array::new();+ for name in enabled {+ arr.push(name.as_str());+ }+ skills["enabled"] = toml_edit::value(arr);++ std::fs::write(path, doc.to_string())+ .map_err(|e| format!("Failed to write {}: {e}", path.display()))+}+#[cfg(test)]mod tests {use super::*;diff --git a/src-tauri/src/core/agent/skill_hub.rs b/src-tauri/src/core/agent/skill_hub.rsnew file mode 100644index 000000000..a6db2e4ac--- /dev/null+++ b/src-tauri/src/core/agent/skill_hub.rs@@ -0,0 +1,185 @@+//! Import skills from Anthropic's public skill hub (github.com/anthropics/skills).+//! Skills live at `skills/<name>/SKILL.md` with optional bundled files; import+//! copies the whole folder into the project's `.jan/agent/skills/<name>/`.+//!+//! All network I/O goes through the backend (no CORS/CSP limits) using the git+//! tree API (1 request to enumerate paths) plus raw.githubusercontent.com for+//! file contents (not subject to the API's 60/hr unauthenticated limit).++use std::path::Path;++use futures::future::join_all;++use crate::core::agent::skills;++const TREE_URL: &str =+ "https://api.github.com/repos/anthropics/skills/git/trees/main?recursive=1";+const RAW_BASE: &str = "https://raw.githubusercontent.com/anthropics/skills/main/";+const SKILLS_PREFIX: &str = "skills/";+const USER_AGENT: &str = "jan-agent-skill-import";++/// A skill available on the hub: folder name + its frontmatter description.+#[derive(serde::Serialize)]+pub struct HubSkill {+ pub name: String,+ pub description: String,+}++fn client() -> Result<reqwest::Client, String> {+ reqwest::Client::builder()+ .user_agent(USER_AGENT)+ .build()+ .map_err(|e| format!("ERROR: {e}"))+}++/// All blob paths in the repo, via the recursive git tree API (one request).+async fn tree_paths(client: &reqwest::Client) -> Result<Vec<String>, String> {+ let resp = client+ .get(TREE_URL)+ .header("Accept", "application/vnd.github+json")+ .send()+ .await+ .map_err(|e| format!("ERROR: fetching skill hub index: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("ERROR: skill hub index returned {}", resp.status()));+ }+ let json: serde_json::Value = resp+ .json()+ .await+ .map_err(|e| format!("ERROR: parsing skill hub index: {e}"))?;+ let tree = json+ .get("tree")+ .and_then(|t| t.as_array())+ .ok_or("ERROR: unexpected skill hub index shape")?;+ Ok(tree+ .iter()+ .filter(|e| e.get("type").and_then(|t| t.as_str()) == Some("blob"))+ .filter_map(|e| e.get("path").and_then(|p| p.as_str()).map(String::from))+ .collect())+}++/// The skill folder name for a `skills/<name>/SKILL.md` path, else None.+fn skill_name_of(path: &str) -> Option<&str> {+ path.strip_prefix(SKILLS_PREFIX)?+ .strip_suffix("/SKILL.md")+ .filter(|n| !n.is_empty() && !n.contains('/'))+}++async fn fetch_text(client: &reqwest::Client, url: &str) -> Result<String, String> {+ let resp = client+ .get(url)+ .send()+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("ERROR: {} returned {}", url, resp.status()));+ }+ resp.text().await.map_err(|e| format!("ERROR: {e}"))+}++/// List the skills available on the hub with their descriptions. Descriptions+/// are read from each skill's SKILL.md frontmatter (fetched concurrently).+pub async fn list() -> Result<Vec<HubSkill>, String> {+ let client = client()?;+ let paths = tree_paths(&client).await?;+ let names: Vec<String> = paths+ .iter()+ .filter_map(|p| skill_name_of(p).map(String::from))+ .collect();++ let fetches = names.into_iter().map(|name| {+ let client = client.clone();+ async move {+ let url = format!("{RAW_BASE}{SKILLS_PREFIX}{name}/SKILL.md");+ let description = match fetch_text(&client, &url).await {+ Ok(raw) => skills::parse(&raw).description.unwrap_or_default(),+ Err(_) => String::new(),+ };+ HubSkill { name, description }+ }+ });+ let mut out = join_all(fetches).await;+ out.sort_by(|a, b| a.name.cmp(&b.name));+ Ok(out)+}++/// Download one hub skill (SKILL.md + every bundled file) into the project's+/// `.jan/agent/skills/<name>/`, replacing any existing skill of the same name.+///+/// Atomic on failure: every file is fetched into memory first, and only once all+/// downloads succeed is the destination cleared and rewritten — a mid-download+/// error leaves the existing skill untouched, and re-import never leaves stale+/// files from a prior version behind.+pub async fn import(root: &Path, name: &str) -> Result<(), String> {+ // Reuse the shared workspace name guard (rejects separators, `..`, `.`, empty).+ let stem = skills::safe_stem(name)?;+ let client = client()?;+ let prefix = format!("{SKILLS_PREFIX}{stem}/");+ let files: Vec<String> = tree_paths(&client)+ .await?+ .into_iter()+ .filter(|p| p.starts_with(&prefix) && !p.ends_with('/'))+ .collect();+ if files.is_empty() {+ return Err(format!("ERROR: skill '{name}' not found on the hub"));+ }++ // Phase 1: fetch every file into memory (relative path + bytes). No writes yet.+ let downloads = files.into_iter().map(|path| {+ let client = client.clone();+ let prefix = prefix.clone();+ async move {+ // Path came from GitHub and is prefix-checked; guard components anyway.+ let rel = path.strip_prefix(&prefix).unwrap_or(&path).to_string();+ if rel.split('/').any(|seg| seg == "..") {+ return Err(format!("ERROR: unsafe path '{path}'"));+ }+ let resp = client+ .get(format!("{RAW_BASE}{path}"))+ .send()+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("ERROR: downloading {path}: {}", resp.status()));+ }+ let bytes = resp.bytes().await.map_err(|e| format!("ERROR: {e}"))?;+ Ok::<_, String>((rel, bytes))+ }+ });+ let mut fetched = Vec::new();+ for result in join_all(downloads).await {+ fetched.push(result?);+ }++ // Phase 2: replace the destination with the freshly fetched files.+ let dest_root = skills::skills_dir(root).join(&stem);+ let flat = skills::skills_dir(root).join(format!("{stem}.md"));+ let _ = tokio::fs::remove_dir_all(&dest_root).await;+ let _ = tokio::fs::remove_file(&flat).await; // drop a legacy flat form, if any+ for (rel, bytes) in fetched {+ let target = dest_root.join(&rel);+ if let Some(parent) = target.parent() {+ tokio::fs::create_dir_all(parent)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ }+ tokio::fs::write(&target, &bytes)+ .await+ .map_err(|e| format!("ERROR: {e}"))?;+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn skill_name_extracted_from_skill_md_path() {+ assert_eq!(skill_name_of("skills/pdf/SKILL.md"), Some("pdf"));+ assert_eq!(skill_name_of("skills/pdf/scripts/x.py"), None);+ assert_eq!(skill_name_of("skills/pdf/reference.md"), None);+ assert_eq!(skill_name_of("README.md"), None);+ assert_eq!(skill_name_of("skills/a/b/SKILL.md"), None);+ }+}diff --git a/src-tauri/src/core/agent/skills.rs b/src-tauri/src/core/agent/skills.rsnew file mode 100644index 000000000..b4734bdd5--- /dev/null+++ b/src-tauri/src/core/agent/skills.rs@@ -0,0 +1,381 @@+//! Per-project skill storage. A skill is either a folder `<name>/SKILL.md`+//! (SKILL.md-ecosystem compatible; may bundle scripts/resources alongside) or a+//! legacy flat `<name>.md`. Both may carry leading YAML frontmatter (`name`,+//! `description`); the folder form is what new/imported skills are written as.+//!+//! Sync (std::fs) so the sync `context::load_skills` and the async `agent_skill_*`+//! commands share one code path; the ops are tiny single-file reads/writes.++use std::path::{Path, PathBuf};++use serde::Deserialize;++use crate::core::agent::tools::handlers::workspace_filename;++/// `<project_root>/.jan/agent/skills`.+pub(crate) fn skills_dir(root: &Path) -> PathBuf {+ root.join(".jan").join("agent").join("skills")+}++/// One skill on disk, located by its identity name (folder name or flat stem).+pub(crate) struct SkillEntry {+ pub name: String,+ /// The markdown file to read (the `SKILL.md`, or the flat `<name>.md`).+ pub file: PathBuf,+ /// True for the folder form `<name>/SKILL.md`, false for legacy flat.+ pub is_folder: bool,+}++/// Summary for the management UI / prompt catalog.+#[derive(serde::Serialize)]+pub struct SkillMeta {+ pub name: String,+ pub description: String,+}++/// Frontmatter fields we recognize; everything else is ignored.+#[derive(Debug, Default, Deserialize)]+struct Frontmatter {+ #[allow(dead_code)]+ name: Option<String>,+ description: Option<String>,+}++/// A skill's parsed content: optional frontmatter description + markdown body+/// (body has the frontmatter fence stripped so it never leaks into the prompt).+pub(crate) struct ParsedSkill {+ pub description: Option<String>,+ pub body: String,+}++/// Split leading `---\n...\n---` YAML frontmatter from the markdown body.+/// Tolerant: no opening/closing fence -> no frontmatter, whole input is body.+pub(crate) fn parse(content: &str) -> ParsedSkill {+ let content = content.strip_prefix('\u{feff}').unwrap_or(content);+ let mut lines = content.lines();+ if lines.next().map(str::trim_end) != Some("---") {+ return ParsedSkill {+ description: None,+ body: content.to_string(),+ };+ }+ let mut yaml = String::new();+ let mut body: Vec<&str> = Vec::new();+ let mut closed = false;+ for line in lines {+ if !closed {+ if line.trim_end() == "---" {+ closed = true;+ continue;+ }+ yaml.push_str(line);+ yaml.push('\n');+ } else {+ body.push(line);+ }+ }+ if !closed {+ // Unterminated fence: treat the whole file as body (no frontmatter).+ return ParsedSkill {+ description: None,+ body: content.to_string(),+ };+ }+ let fm = serde_yaml::from_str::<Frontmatter>(&yaml).unwrap_or_default();+ ParsedSkill {+ description: fm.description.map(|d| d.trim().to_string()),+ body: body.join("\n").trim_start_matches('\n').to_string(),+ }+}++/// First non-empty, non-heading line of `body`, capped at 120 chars. Fallback+/// description when a skill has no frontmatter `description`.+fn first_line(body: &str) -> String {+ body.lines()+ .map(str::trim)+ .find(|l| !l.is_empty() && !l.starts_with('#'))+ .unwrap_or("")+ .chars()+ .take(120)+ .collect()+}++/// Sanitized identity stem (no path escape, no `.md`). Reuses the workspace name+/// guard so a caller-supplied name can never escape the skills directory.+pub(crate) fn safe_stem(name: &str) -> Result<String, String> {+ let file = workspace_filename(name)?;+ Ok(file.trim_end_matches(".md").to_string())+}++/// All skills in the project, sorted by name. Folder skills (`<name>/SKILL.md`)+/// and legacy flat skills (`<name>.md`) are both discovered. When both forms+/// share a name, the folder form wins so a skill is never listed/injected twice.+pub(crate) fn discover(root: &Path) -> Vec<SkillEntry> {+ let dir = skills_dir(root);+ let Ok(rd) = std::fs::read_dir(&dir) else {+ return Vec::new();+ };+ // Keyed by name so a duplicate stem collapses to one entry; BTreeMap also+ // gives the sorted-by-name order for free.+ let mut by_name: std::collections::BTreeMap<String, SkillEntry> = std::collections::BTreeMap::new();+ let mut consider = |entry: SkillEntry| {+ match by_name.get(&entry.name) {+ // Keep an existing folder entry over an incoming flat one.+ Some(existing) if existing.is_folder && !entry.is_folder => {}+ _ => {+ by_name.insert(entry.name.clone(), entry);+ }+ }+ };+ for entry in rd.flatten() {+ let path = entry.path();+ let Ok(ft) = entry.file_type() else { continue };+ if ft.is_dir() {+ let skill_md = path.join("SKILL.md");+ if skill_md.is_file() {+ if let Some(name) = path.file_name().and_then(|s| s.to_str()) {+ consider(SkillEntry {+ name: name.to_string(),+ file: skill_md,+ is_folder: true,+ });+ }+ }+ } else if path.extension().and_then(|x| x.to_str()) == Some("md") {+ if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {+ consider(SkillEntry {+ name: stem.to_string(),+ file: path,+ is_folder: false,+ });+ }+ }+ }+ let mut out: Vec<SkillEntry> = by_name.into_values().collect();+ out.sort_by(|a, b| a.name.cmp(&b.name));+ out+}++/// Locate an existing skill by name, preferring the folder form.+fn resolve(root: &Path, name: &str) -> Result<SkillEntry, String> {+ let stem = safe_stem(name)?;+ let dir = skills_dir(root);+ let folder = dir.join(&stem).join("SKILL.md");+ if folder.is_file() {+ return Ok(SkillEntry {+ name: stem,+ file: folder,+ is_folder: true,+ });+ }+ let flat = dir.join(format!("{stem}.md"));+ if flat.is_file() {+ return Ok(SkillEntry {+ name: stem,+ file: flat,+ is_folder: false,+ });+ }+ Err(format!("ERROR: skill '{name}' not found"))+}++/// Whether a skill is advertised given the `[skills].enabled` whitelist. An+/// empty whitelist means every skill is enabled.+pub(crate) fn is_enabled(enabled: &[String], name: &str) -> bool {+ enabled.is_empty() || enabled.iter().any(|n| n == name)+}++/// A skill's summary line: the frontmatter `description`, or the first body line.+fn describe(parsed: &ParsedSkill) -> String {+ parsed+ .description+ .clone()+ .filter(|d| !d.is_empty())+ .unwrap_or_else(|| first_line(&parsed.body))+}++/// Metadata for every discovered skill (name + description) — for the UI list.+/// Keeps empty stubs so the user can see and edit them.+pub(crate) fn list_meta(root: &Path) -> Vec<SkillMeta> {+ discover(root)+ .into_iter()+ .filter_map(|e| {+ let parsed = parse(&std::fs::read_to_string(&e.file).ok()?);+ Some(SkillMeta {+ name: e.name,+ description: describe(&parsed),+ })+ })+ .collect()+}++/// Skills worth advertising in the system prompt: name + description, skipping+/// skills with neither a description nor a body. This is the progressive-+/// disclosure catalog — the model calls `skill_read` to load a body on demand.+///+/// `enabled` is a whitelist of skill names; an empty list means "all skills"+/// (backward-compatible with the agent.toml scaffold, which ships `enabled = []`).+pub(crate) fn catalog(root: &Path, enabled: &[String]) -> Vec<SkillMeta> {+ let allow: Option<std::collections::HashSet<&str>> =+ (!enabled.is_empty()).then(|| enabled.iter().map(String::as_str).collect());+ discover(root)+ .into_iter()+ .filter_map(|e| {+ if let Some(allow) = &allow {+ if !allow.contains(e.name.as_str()) {+ return None;+ }+ }+ let parsed = parse(&std::fs::read_to_string(&e.file).ok()?);+ let description = describe(&parsed);+ if description.is_empty() && parsed.body.trim().is_empty() {+ return None;+ }+ Some(SkillMeta {+ name: e.name,+ description,+ })+ })+ .collect()+}++/// Raw SKILL.md text (frontmatter included) for the editor.+pub(crate) fn read_raw(root: &Path, name: &str) -> Result<String, String> {+ let entry = resolve(root, name)?;+ std::fs::read_to_string(&entry.file).map_err(|e| format!("ERROR: {e}"))+}++/// A skill's markdown body with the frontmatter fence stripped — what the+/// `skill_read` tool hands the model when it loads a skill on demand.+pub(crate) fn read_body(root: &Path, name: &str) -> Result<String, String> {+ Ok(parse(&read_raw(root, name)?).body)+}++/// Create or overwrite a skill. Existing skills are written in place (preserving+/// their form); new skills are written as the folder form `<name>/SKILL.md`.+pub(crate) fn write(root: &Path, name: &str, content: &str) -> Result<(), String> {+ let stem = safe_stem(name)?;+ let dir = skills_dir(root);+ let flat = dir.join(format!("{stem}.md"));+ let target = if flat.is_file() {+ flat+ } else {+ let folder = dir.join(&stem);+ std::fs::create_dir_all(&folder).map_err(|e| format!("ERROR: {e}"))?;+ folder.join("SKILL.md")+ };+ std::fs::write(&target, content).map_err(|e| format!("ERROR: {e}"))+}++/// Delete a skill (folder or flat form). Idempotent: a missing skill is Ok.+pub(crate) fn delete(root: &Path, name: &str) -> Result<(), String> {+ let stem = safe_stem(name)?;+ let dir = skills_dir(root);+ let folder = dir.join(&stem);+ let flat = dir.join(format!("{stem}.md"));+ if folder.is_dir() {+ std::fs::remove_dir_all(&folder).map_err(|e| format!("ERROR: {e}"))+ } else if flat.is_file() {+ std::fs::remove_file(&flat).map_err(|e| format!("ERROR: {e}"))+ } else {+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_extracts_description_and_strips_frontmatter() {+ let p = parse("---\nname: deploy\ndescription: Ship it\n---\n\nRun the script.");+ assert_eq!(p.description.as_deref(), Some("Ship it"));+ assert_eq!(p.body, "Run the script.");+ }++ #[test]+ fn parse_without_frontmatter_returns_whole_body() {+ let p = parse("Just a body.\nMore.");+ assert!(p.description.is_none());+ assert_eq!(p.body, "Just a body.\nMore.");+ }++ #[test]+ fn parse_unterminated_fence_is_all_body() {+ let p = parse("---\nname: x\nbody without close");+ assert!(p.description.is_none());+ assert!(p.body.starts_with("---"));+ }++ #[test]+ fn discover_finds_folder_and_flat_skills_sorted() {+ let root = std::env::temp_dir().join(format!(+ "jan_skills_test_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ));+ let dir = skills_dir(&root);+ std::fs::create_dir_all(dir.join("b_folder")).unwrap();+ std::fs::write(dir.join("b_folder").join("SKILL.md"), "folder body").unwrap();+ std::fs::write(dir.join("a_flat.md"), "flat body").unwrap();++ let names: Vec<_> = discover(&root).into_iter().map(|e| e.name).collect();+ assert_eq!(names, vec!["a_flat", "b_folder"]);+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn write_new_creates_folder_form_read_delete_roundtrip() {+ let root = std::env::temp_dir().join(format!(+ "jan_skills_rt_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ));+ write(&root, "deploy", "---\ndescription: d\n---\nbody").unwrap();+ assert!(skills_dir(&root).join("deploy").join("SKILL.md").is_file());++ let meta = list_meta(&root);+ assert_eq!(meta.len(), 1);+ assert_eq!(meta[0].name, "deploy");+ assert_eq!(meta[0].description, "d");++ assert!(read_raw(&root, "deploy").unwrap().contains("body"));+ delete(&root, "deploy").unwrap();+ assert!(!skills_dir(&root).join("deploy").exists());+ delete(&root, "deploy").unwrap(); // idempotent+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn catalog_enabled_whitelist_filters() {+ let root = std::env::temp_dir().join(format!(+ "jan_skills_wl_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ));+ write(&root, "a", "body a").unwrap();+ write(&root, "b", "body b").unwrap();++ // Empty whitelist = all skills.+ assert_eq!(catalog(&root, &[]).len(), 2);++ // Non-empty whitelist restricts to the listed names.+ let only_a = catalog(&root, &["a".to_string()]);+ assert_eq!(only_a.len(), 1);+ assert_eq!(only_a[0].name, "a");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn write_existing_flat_stays_flat() {+ let root = std::env::temp_dir().join(format!(+ "jan_skills_flat_{}",+ std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_nanos()+ ));+ let dir = skills_dir(&root);+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("legacy.md"), "old").unwrap();++ write(&root, "legacy", "new").unwrap();+ assert_eq!(std::fs::read_to_string(dir.join("legacy.md")).unwrap(), "new");+ assert!(!dir.join("legacy").exists());+ let _ = std::fs::remove_dir_all(&root);+ }+}diff --git a/src-tauri/src/core/agent/tools/handlers.rs b/src-tauri/src/core/agent/tools/handlers.rsindex be97b93e0..4ed13c198 100644--- a/src-tauri/src/core/agent/tools/handlers.rs+++ b/src-tauri/src/core/agent/tools/handlers.rs@@ -11,6 +11,8 @@ use std::sync::{Mutex, OnceLock};use ignore::WalkBuilder;use tokio::sync::oneshot;+use crate::core::agent::project::load_agent_config;+use crate::core::agent::skills;use crate::core::agent::tools::sandbox::is_restricted_agent_path;use crate::core::agent::tools::BuiltinTool;@@ -102,8 +104,11 @@ pub async fn execute_builtin("memory_list" => workspace_list(project_root, "memory").await,"memory_read" => workspace_read(args, project_root, "memory").await,"memory_write" => workspace_write(args, project_root, "memory").await,- "skill_list" => workspace_list(project_root, "skills").await,- "skill_write" => workspace_write(args, project_root, "skills").await,+ // Skills go through the skills module so the tool honors the folder form+ // (`<name>/SKILL.md`) and frontmatter, matching what the UI writes.+ "skill_list" => skill_list(project_root),+ "skill_read" => skill_read(args, project_root),+ "skill_write" => skill_write(args, project_root),other => format!("ERROR: unknown built-in tool '{other}'"),}}@@ -229,14 +234,14 @@ fn render_write_diff(prior: Option<&str>, content: &str) -> String {}/// `.jan/agent/<kind>` directory for the agent's own workspace.-fn workspace_dir(root: &Path, kind: &str) -> PathBuf {+pub(crate) fn workspace_dir(root: &Path, kind: &str) -> PathBuf {root.join(".jan").join("agent").join(kind)}/// Sanitize a caller-supplied entry name into a safe `<stem>.md` filename./// Rejects path separators and `..` so the result can never escape the/// workspace. `.md` is appended if absent.-fn workspace_filename(name: &str) -> Result<String, String> {+pub(crate) fn workspace_filename(name: &str) -> Result<String, String> {let trimmed = name.trim();if trimmed.is_empty()|| trimmed.contains('/')@@ -250,6 +255,61 @@ fn workspace_filename(name: &str) -> Result<String, String> {Ok(format!("{stem}.md"))}+/// The project's enabled-skill whitelist (`[skills].enabled`; empty = all).+/// A missing/malformed config falls back to "all enabled".+fn enabled_skills(root: &Path) -> Vec<String> {+ load_agent_config(root)+ .ok()+ .map(|c| c.skills.enabled)+ .unwrap_or_default()+}++/// `skill_list` tool: catalog of `name — description` lines for ENABLED skills+/// only (disabled skills must stay invisible to the model). Empty if none.+fn skill_list(root: &Path) -> String {+ let enabled = enabled_skills(root);+ skills::catalog(root, &enabled)+ .iter()+ .map(|m| {+ if m.description.is_empty() {+ m.name.clone()+ } else {+ format!("{} — {}", m.name, m.description)+ }+ })+ .collect::<Vec<_>>()+ .join("\n")+}++/// `skill_read` tool: a skill's full instructions (frontmatter stripped). A+/// disabled skill is treated as absent so it never reaches the model.+fn skill_read(args: &serde_json::Value, root: &Path) -> String {+ let Some(name) = arg_str(args, "name") else {+ return "ERROR: missing required argument 'name'".to_string();+ };+ if !skills::is_enabled(&enabled_skills(root), name) {+ return format!("ERROR: skill '{name}' not found");+ }+ match skills::read_body(root, name) {+ Ok(body) => body,+ Err(e) => e,+ }+}++/// `skill_write` tool: create/update a skill (new ones as `<name>/SKILL.md`).+fn skill_write(args: &serde_json::Value, root: &Path) -> String {+ let Some(name) = arg_str(args, "name") else {+ return "ERROR: missing required argument 'name'".to_string();+ };+ let Some(content) = arg_str(args, "content") else {+ return "ERROR: missing required argument 'content'".to_string();+ };+ match skills::write(root, name, content) {+ Ok(()) => format!("Wrote skill '{name}'"),+ Err(e) => e,+ }+}+async fn workspace_list(root: &Path, kind: &str) -> String {let dir = workspace_dir(root, kind);let mut entries = match tokio::fs::read_dir(&dir).await {@@ -1219,7 +1279,7 @@ mod tests {}#[tokio::test]- async fn skill_write_targets_skills_dir_and_strips_md() {+ async fn skill_write_creates_folder_form_and_skill_read_returns_body() {let root = unique_root();let w = execute_builtin(lookup("skill_write").unwrap(),@@ -1227,8 +1287,69 @@ mod tests {&root,).await;- assert!(w.contains("skills/deploy.md"), "unexpected: {w}");- assert!(root.join(".jan/agent/skills/deploy.md").exists());+ assert!(w.contains("deploy"), "unexpected: {w}");+ // New skills are written as the folder form `<name>/SKILL.md`.+ assert!(root.join(".jan/agent/skills/deploy/SKILL.md").exists());++ // skill_read returns the body on demand (progressive disclosure).+ let r = execute_builtin(+ lookup("skill_read").unwrap(),+ &json!({"name": "deploy"}),+ &root,+ )+ .await;+ assert_eq!(r, "steps");++ // skill_list surfaces the catalog line.+ let l = execute_builtin(lookup("skill_list").unwrap(), &json!({}), &root).await;+ assert!(l.contains("deploy"), "unexpected list: {l}");+ let _ = std::fs::remove_dir_all(&root);+ }++ #[tokio::test]+ async fn skill_tools_hide_disabled_skills() {+ let root = unique_root();+ execute_builtin(+ lookup("skill_write").unwrap(),+ &json!({"name": "on", "content": "on body"}),+ &root,+ )+ .await;+ execute_builtin(+ lookup("skill_write").unwrap(),+ &json!({"name": "off", "content": "off body"}),+ &root,+ )+ .await;+ // Whitelist only "on".+ crate::core::agent::project::ensure_project(&root).unwrap();+ crate::core::agent::project::set_skills_enabled_in_agent_toml(+ &crate::core::agent::project::agent_toml_path(&root),+ &["on".to_string()],+ )+ .unwrap();++ let list = execute_builtin(lookup("skill_list").unwrap(), &json!({}), &root).await;+ assert!(list.contains("on"), "list: {list}");+ assert!(!list.contains("off body"), "disabled skill leaked: {list}");++ // Disabled skill is unreadable.+ let read_off = execute_builtin(+ lookup("skill_read").unwrap(),+ &json!({"name": "off"}),+ &root,+ )+ .await;+ assert!(read_off.starts_with("ERROR"), "disabled read: {read_off}");++ // Enabled skill still readable.+ let read_on = execute_builtin(+ lookup("skill_read").unwrap(),+ &json!({"name": "on"}),+ &root,+ )+ .await;+ assert_eq!(read_on, "on body");let _ = std::fs::remove_dir_all(&root);}diff --git a/src-tauri/src/core/agent/tools/mod.rs b/src-tauri/src/core/agent/tools/mod.rsindex f96c61499..0fd0e74f7 100644--- a/src-tauri/src/core/agent/tools/mod.rs+++ b/src-tauri/src/core/agent/tools/mod.rs@@ -82,6 +82,11 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[capability: Capability::Read,path_args: &[],},+ BuiltinTool {+ name: "skill_read",+ capability: Capability::Read,+ path_args: &[],+ },BuiltinTool {name: "skill_write",capability: Capability::Write,@@ -95,7 +100,12 @@ pub const BUILTIN_TOOLS: &[BuiltinTool] = &[pub fn is_workspace_tool(name: &str) -> bool {matches!(name,- "memory_list" | "memory_read" | "memory_write" | "skill_list" | "skill_write"+ "memory_list"+ | "memory_read"+ | "memory_write"+ | "skill_list"+ | "skill_read"+ | "skill_write")}@@ -133,8 +143,8 @@ mod tests {#[test]fn builtin_count_matches_expected() {- // 7 coding tools + 5 dedicated skill/memory tools.- assert_eq!(BUILTIN_TOOLS.len(), 12);+ // 7 coding tools + 6 dedicated skill/memory tools.+ assert_eq!(BUILTIN_TOOLS.len(), 13);}#[test]diff --git a/src-tauri/src/core/agent/tools/schema.rs b/src-tauri/src/core/agent/tools/schema.rsindex 092fbb1af..b3f60fb41 100644--- a/src-tauri/src/core/agent/tools/schema.rs+++ b/src-tauri/src/core/agent/tools/schema.rs@@ -172,10 +172,24 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "skill_list",- "description": "List the names of the project skills (reusable procedures). Skills are already loaded into your context; use this to see what exists before adding or updating one. No arguments.",+ "description": "List the project skills (reusable procedures) with a one-line description of each. No arguments.","parameters": { "type": "object", "properties": {}, "required": [] }}}),+ json!({+ "type": "function",+ "function": {+ "name": "skill_read",+ "description": "Load a skill's full instructions by name. The system prompt lists each skill's name and purpose; call this to read the complete procedure before applying a skill.",+ "parameters": {+ "type": "object",+ "properties": {+ "name": { "type": "string", "description": "Skill name (without the .md extension)." }+ },+ "required": ["name"]+ }+ }+ }),json!({"type": "function","function": {@@ -202,7 +216,7 @@ mod tests {#[test]fn schemas_match_builtin_tools() {let schemas = builtin_tool_schemas();- assert_eq!(schemas.len(), 12);+ assert_eq!(schemas.len(), 13);for schema in &schemas {assert_eq!(schema["type"], "function");}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 9b90d9f34..5c3e31a30 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -77,6 +77,14 @@ macro_rules! invoke_commands_with_extras {core::agent::commands::agent_run,core::agent::commands::agent_cancel,core::agent::commands::agent_permission_respond,+ core::agent::commands::agent_skill_list,+ core::agent::commands::agent_skill_read,+ core::agent::commands::agent_skill_write,+ core::agent::commands::agent_skill_delete,+ core::agent::commands::agent_skill_hub_list,+ core::agent::commands::agent_skill_hub_import,+ core::agent::commands::agent_skill_enabled_get,+ core::agent::commands::agent_skill_enabled_set,// Remote provider commandscore::server::remote_provider_commands::register_provider_config,core::server::remote_provider_commands::unregister_provider_config,diff --git a/web-app/src/components/DiffView.tsx b/web-app/src/components/DiffView.tsxnew file mode 100644index 000000000..f76db8dcc--- /dev/null+++ b/web-app/src/components/DiffView.tsx@@ -0,0 +1,26 @@+import { cn } from '@/lib/utils'+import { CodeBlock } from '@/components/ai-elements/code-block'++/**+ * Renders the line-prefixed diff emitted by the agent loop for `write`/`edit`+ * using the shared Shiki `CodeBlock` with the `diff` grammar, so agent diffs are+ * highlighted the same way code and tool output are elsewhere in the app.+ */+export function DiffView({+ diff,+ className,+}: {+ diff: string+ className?: string+}) {+ return (+ <div+ className={cn(+ 'max-h-56 overflow-auto rounded-md border text-xs',+ className+ )}+ >+ <CodeBlock code={diff} language="diff" />+ </div>+ )+}diff --git a/web-app/src/components/left-sidebar/NavCode.tsx b/web-app/src/components/left-sidebar/NavCode.tsxnew file mode 100644index 000000000..000f3a092--- /dev/null+++ b/web-app/src/components/left-sidebar/NavCode.tsx@@ -0,0 +1,182 @@+import {+ SidebarMenu,+ SidebarMenuButton,+ SidebarMenuItem,+ SidebarMenuAction,+ SidebarGroup,+ SidebarGroupLabel,+ useSidebar,+} from '@/components/ui/sidebar'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useNavigate } from '@tanstack/react-router'+import { route } from '@/constants/routes'+import {+ MessageSquarePlus,+ Box,+ SlidersHorizontal,+ MoreHorizontal,+ Trash2,+ type LucideIcon,+} from 'lucide-react'+import { useCodeSessions } from '@/hooks/useCodeSessions'+import { useState } from 'react'+import SkillsManagerDialog from '@/containers/dialogs/SkillsManagerDialog'++type CodeNavItem = {+ title: string+ icon: LucideIcon+ onClick: () => void+}++export function NavCode() {+ const { t } = useTranslation()+ const navigate = useNavigate()+ const { isMobile } = useSidebar()+ const sessions = useCodeSessions((s) => s.sessions)+ const currentId = useCodeSessions((s) => s.currentId)+ const [skillsOpen, setSkillsOpen] = useState(false)+ // Session pending deletion; drives the confirm dialog (null = closed).+ const [pendingDelete, setPendingDelete] = useState<{+ id: string+ title: string+ } | null>(null)++ const goCode = () => navigate({ to: route.code })++ const items: CodeNavItem[] = [+ {+ title: t('common:newSession'),+ icon: MessageSquarePlus,+ onClick: () => {+ useCodeSessions.getState().createSession()+ goCode()+ },+ },+ {+ title: t('common:artifacts'),+ icon: Box,+ onClick: goCode,+ },+ {+ title: t('common:customize'),+ icon: SlidersHorizontal,+ onClick: () => setSkillsOpen(true),+ },+ ]++ const confirmDelete = () => {+ if (pendingDelete) useCodeSessions.getState().deleteSession(pendingDelete.id)+ setPendingDelete(null)+ }++ return (+ <>+ <SidebarMenu>+ {items.map((item) => {+ const Icon = item.icon+ return (+ <SidebarMenuItem key={item.title}>+ <SidebarMenuButton onClick={item.onClick}>+ <Icon className="text-foreground/70" size={16} />+ <span>{item.title}</span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ )+ })}+ </SidebarMenu>++ {sessions.length > 0 && (+ <SidebarGroup className="group-data-[collapsible=icon]:hidden">+ <SidebarGroupLabel>{t('common:sessions')}</SidebarGroupLabel>+ <SidebarMenu>+ {sessions.map((session) => (+ <SidebarMenuItem key={session.id}>+ <SidebarMenuButton+ isActive={session.id === currentId}+ onClick={() => {+ useCodeSessions.getState().selectSession(session.id)+ goCode()+ }}+ >+ <span className="truncate">{session.title}</span>+ </SidebarMenuButton>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <SidebarMenuAction+ showOnHover+ className="hover:bg-sidebar-foreground/8"+ >+ <MoreHorizontal />+ <span className="sr-only">More</span>+ </SidebarMenuAction>+ </DropdownMenuTrigger>+ <DropdownMenuContent+ className="w-48"+ side={isMobile ? 'bottom' : 'right'}+ align={isMobile ? 'end' : 'start'}+ >+ <DropdownMenuItem+ variant="destructive"+ onSelect={() =>+ setPendingDelete({+ id: session.id,+ title: session.title,+ })+ }+ >+ <Trash2 />+ <span>{t('common:deleteSession')}</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </SidebarMenuItem>+ ))}+ </SidebarMenu>+ </SidebarGroup>+ )}++ <SkillsManagerDialog open={skillsOpen} onOpenChange={setSkillsOpen} />++ <Dialog+ open={pendingDelete !== null}+ onOpenChange={(open) => !open && setPendingDelete(null)}+ >+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('common:deleteSessionTitle')}</DialogTitle>+ <DialogDescription>+ {t('common:deleteSessionBody', { title: pendingDelete?.title })}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <Button+ variant="ghost"+ size="sm"+ onClick={() => setPendingDelete(null)}+ >+ {t('common:cancel')}+ </Button>+ <Button variant="destructive" size="sm" onClick={confirmDelete}>+ {t('common:delete')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ </>+ )+}diff --git a/web-app/src/components/left-sidebar/NavTabs.tsx b/web-app/src/components/left-sidebar/NavTabs.tsxnew file mode 100644index 000000000..196442e33--- /dev/null+++ b/web-app/src/components/left-sidebar/NavTabs.tsx@@ -0,0 +1,52 @@+import { Link, useLocation } from '@tanstack/react-router'+import { HomeIcon, CodeIcon } from 'lucide-react'+import { route } from '@/constants/routes'+import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'++type TabItem = {+ label: string+ to: string+ icon: typeof HomeIcon+ isActive: boolean+}++export function NavTabs() {+ const { t } = useTranslation()+ const { pathname } = useLocation()++ const isCode = pathname === route.code+ // Home owns the chat surfaces (new chat, threads, projects); Code owns /code.+ const isHome =+ pathname === route.home ||+ pathname.startsWith('/threads') ||+ pathname.startsWith('/project')++ const tabs: TabItem[] = [+ { label: t('common:home'), to: route.home, icon: HomeIcon, isActive: isHome },+ { label: t('common:code'), to: route.code, icon: CodeIcon, isActive: isCode },+ ]++ return (+ <div className="mt-1 flex items-center gap-0.5 rounded-lg bg-sidebar-foreground/5 p-0.5">+ {tabs.map((tab) => {+ const Icon = tab.icon+ return (+ <Link+ key={tab.to}+ to={tab.to}+ className={cn(+ 'flex flex-1 items-center justify-center gap-1.5 rounded-md px-2 py-1 text-sm font-medium transition-colors',+ tab.isActive+ ? 'bg-sidebar text-foreground shadow-sm'+ : 'text-muted-foreground hover:text-foreground'+ )}+ >+ <Icon size={15} />+ <span>{tab.label}</span>+ </Link>+ )+ })}+ </div>+ )+}diff --git a/web-app/src/components/left-sidebar/index.tsx b/web-app/src/components/left-sidebar/index.tsxindex 1a72bd834..02bac2a83 100644--- a/web-app/src/components/left-sidebar/index.tsx+++ b/web-app/src/components/left-sidebar/index.tsx@@ -1,7 +1,9 @@import { DownloadManagement } from '@/containers/DownloadManegement'import { NavChats } from './NavChats'+import { NavCode } from './NavCode'import { NavMain } from './NavMain'import { NavProjects } from './NavProjects'+import { NavTabs } from './NavTabs'import { useLeftPanel } from '@/hooks/useLeftPanel'import {@@ -13,9 +15,13 @@ import {} from '@/components/ui/sidebar'import { cn } from '@/lib/utils'import { useTitlebarLayout } from '@/stores/titlebar-layout-store'+import { useLocation } from '@tanstack/react-router'+import { route } from '@/constants/routes'export function LeftSidebar() {const { open: isLeftPanelOpen } = useLeftPanel()+ const { pathname } = useLocation()+ const isCode = pathname === route.code// Right-align the header when native controls own the top-left (macOS, or a Linux// DE placing buttons left); "Jan" moves into the right cluster except on macOS.const leftButtons = useTitlebarLayout((s) => s.layout.left.length)@@ -35,11 +41,16 @@ export function LeftSidebar() {<SidebarTrigger className="text-muted-foreground rounded-full hover:bg-sidebar-foreground/8! -mt-0.5 relative z-50 ml-0.5" /></div></div>- <NavMain />+ <NavTabs />+ {isCode ? <NavCode /> : <NavMain />}</SidebarHeader><SidebarContent className="mask-b-from-95% mask-t-from-98%">- <NavProjects />- <NavChats />+ {!isCode && (+ <>+ <NavProjects />+ <NavChats />+ </>+ )}</SidebarContent><SidebarRail /></Sidebar>diff --git a/web-app/src/constants/localStorage.ts b/web-app/src/constants/localStorage.tsindex 9fd9fd60e..9450dc1b6 100644--- a/web-app/src/constants/localStorage.ts+++ b/web-app/src/constants/localStorage.ts@@ -31,6 +31,7 @@ export const localStorageKey = {latestJanModel: 'latest-jan-model',defaultEmbeddingModel: 'default-embedding-model',pausedDownloads: 'paused-downloads',+ codeSessions: 'code-sessions',}export const CACHE_EXPIRY_MS = 1000 * 60 * 60 * 24diff --git a/web-app/src/constants/routes.ts b/web-app/src/constants/routes.tsindex 2e36dddb6..e1e9fbf16 100644--- a/web-app/src/constants/routes.ts+++ b/web-app/src/constants/routes.ts@@ -1,6 +1,7 @@export const route = {// home as new chat or threadhome: '/',+ code: '/code',appLogs: '/logs',project: '/project',projectDetail: '/project/$projectId',diff --git a/web-app/src/containers/SkillSelector.tsx b/web-app/src/containers/SkillSelector.tsxnew file mode 100644index 000000000..d44a4214f--- /dev/null+++ b/web-app/src/containers/SkillSelector.tsx@@ -0,0 +1,76 @@+import { Sparkles } from 'lucide-react'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/components/ui/popover'+import { Button } from '@/components/ui/button'+import { Switch } from '@/components/ui/switch'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useSkills, effectiveEnabled, storedEnabled } from '@/hooks/useSkills'++/**+ * Top-of-input control showing which skills will be advertised to the agent this+ * run, with per-skill on/off toggles. Backed by the project's `[skills].enabled`+ * whitelist — an empty whitelist means every skill is enabled.+ */+export default function SkillSelector({ folder }: { folder: string | null }) {+ const { t } = useTranslation()+ const { skills, enabled, setEnabled } = useSkills(folder)++ if (!folder || skills.length === 0) return null++ const allNames = skills.map((s) => s.name)+ const effective = effectiveEnabled(enabled, allNames)++ const toggle = (name: string) => {+ const next = new Set(effective)+ if (next.has(name)) next.delete(name)+ else next.add(name)+ setEnabled(storedEnabled(next, allNames))+ }++ return (+ <Popover>+ <PopoverTrigger asChild>+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 rounded-full"+ title={t('common:skillsInContext')}+ >+ <Sparkles size={14} className="text-muted-foreground" />+ <span>+ {t('common:skills')} {effective.size}/{allNames.length}+ </span>+ </Button>+ </PopoverTrigger>+ <PopoverContent align="end" className="w-72 p-1">+ <div className="px-2 py-1.5 text-xs text-muted-foreground">+ {t('common:skillsInContext')}+ </div>+ <div className="max-h-64 overflow-y-auto">+ {skills.map((s) => (+ <label+ key={s.name}+ className="flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 hover:bg-accent"+ >+ <div className="flex-1 min-w-0">+ <div className="truncate text-sm font-medium">{s.name}</div>+ {s.description && (+ <div className="truncate text-xs text-muted-foreground">+ {s.description}+ </div>+ )}+ </div>+ <Switch+ checked={effective.has(s.name)}+ onCheckedChange={() => toggle(s.name)}+ />+ </label>+ ))}+ </div>+ </PopoverContent>+ </Popover>+ )+}diff --git a/web-app/src/containers/dialogs/CodePermissionDialog.tsx b/web-app/src/containers/dialogs/CodePermissionDialog.tsxnew file mode 100644index 000000000..33188ff23--- /dev/null+++ b/web-app/src/containers/dialogs/CodePermissionDialog.tsx@@ -0,0 +1,77 @@+import { useTranslation } from '@/i18n/react-i18next-compat'+import { DiffView } from '@/components/DiffView'+import {+ ToolApprovalDialog,+ type ApprovalDecision,+} from '@/containers/dialogs/ToolApprovalDialog'++export type PermissionDecision = 'allow_once' | 'allow_always' | 'deny'++/** A gated tool call awaiting the user's approval, mirrors the Rust+ * `permission_request` StreamEvent (see events.rs). */+export type PendingPermission = {+ requestId: string+ toolName: string+ capability: string+ path?: string+ command?: string+ diff?: string+ promptKind: string+ offersAlways: boolean+}++// The shared dialog speaks hyphenated decisions; the Rust command+// (`agent_permission_respond`) expects the snake_case wire values.+const WIRE: Record<ApprovalDecision, PermissionDecision> = {+ 'allow-once': 'allow_once',+ 'allow-always': 'allow_always',+ deny: 'deny',+}++/**+ * Approval dialog for a single gated agent tool call. A thin wrapper over the+ * shared `ToolApprovalDialog`: it maps the head of the pending-permission queue+ * onto the shared shell and injects the command/path/diff body. Closing the+ * dialog counts as a deny so the agent never proceeds without an explicit allow.+ */+export default function CodePermissionDialog({+ request,+ onRespond,+}: {+ request: PendingPermission | null+ onRespond: (requestId: string, decision: PermissionDecision) => void+}) {+ const { t } = useTranslation()+ if (!request) return null++ const { requestId, toolName, capability, path, command, diff, offersAlways } =+ request++ return (+ <ToolApprovalDialog+ open={!!request}+ toolName={toolName}+ offersAlways={offersAlways}+ description={+ <>+ {t('tools:toolApproval.description')}{' '}+ <span className="font-semibold">{toolName}</span>+ {capability ? ` (${capability})` : ''}.+ </>+ }+ onDecision={(decision) => onRespond(requestId, WIRE[decision])}+ >+ {command && (+ <pre className="rounded-md bg-sidebar-foreground/5 px-2 py-1.5 text-xs font-mono break-all whitespace-pre-wrap">+ {command}+ </pre>+ )}+ {path && !command && (+ <pre className="rounded-md bg-sidebar-foreground/5 px-2 py-1.5 text-xs font-mono break-all">+ {path}+ </pre>+ )}+ {diff && <DiffView diff={diff} className="mt-1" />}+ </ToolApprovalDialog>+ )+}diff --git a/web-app/src/containers/dialogs/SkillsManagerDialog.tsx b/web-app/src/containers/dialogs/SkillsManagerDialog.tsxnew file mode 100644index 000000000..85de2b76c--- /dev/null+++ b/web-app/src/containers/dialogs/SkillsManagerDialog.tsx@@ -0,0 +1,301 @@+import { useState } from 'react'+import { toast } from 'sonner'+import { Plus, Trash2, FileText, DownloadCloud, Loader2, Check } from 'lucide-react'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Textarea } from '@/components/ui/textarea'+import { cn } from '@/lib/utils'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { useCodeSessions } from '@/hooks/useCodeSessions'+import { useSkills, type HubSkill } from '@/hooks/useSkills'++export default function SkillsManagerDialog({+ open,+ onOpenChange,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const sessions = useCodeSessions((s) => s.sessions)+ const currentId = useCodeSessions((s) => s.currentId)+ const folder = sessions.find((s) => s.id === currentId)?.folder ?? null++ const { skills, remove, write, read, hubList, hubImport } = useSkills(folder)+ const localNames = new Set(skills.map((s) => s.name))++ // `selected` is the skill being edited; '' with isNew means a fresh draft.+ const [selected, setSelected] = useState<string | null>(null)+ const [isNew, setIsNew] = useState(false)+ const [name, setName] = useState('')+ const [content, setContent] = useState('')+ const [saving, setSaving] = useState(false)++ // Hub browse state.+ const [hubMode, setHubMode] = useState(false)+ const [hubSkills, setHubSkills] = useState<HubSkill[]>([])+ const [hubLoading, setHubLoading] = useState(false)+ const [importing, setImporting] = useState<string | null>(null)++ const openSkill = async (skillName: string) => {+ try {+ const body = await read(skillName)+ setHubMode(false)+ setSelected(skillName)+ setIsNew(false)+ setName(skillName)+ setContent(body)+ } catch (e) {+ toast.error(String(e))+ }+ }++ const startNew = () => {+ setHubMode(false)+ setSelected(null)+ setIsNew(true)+ setName('')+ // Prefill the SKILL.md frontmatter so new (folder-form) skills carry a+ // name/description the catalog can read.+ setContent('---\nname: \ndescription: \n---\n\n')+ }++ const closeEditor = () => {+ setSelected(null)+ setIsNew(false)+ setName('')+ setContent('')+ }++ const openHub = async () => {+ closeEditor()+ setHubMode(true)+ if (hubSkills.length === 0) {+ setHubLoading(true)+ try {+ setHubSkills(await hubList())+ } catch (e) {+ toast.error(String(e))+ } finally {+ setHubLoading(false)+ }+ }+ }++ const handleImport = async (skillName: string) => {+ setImporting(skillName)+ try {+ await hubImport(skillName)+ toast.success(t('common:skillImported', { name: skillName }))+ } catch (e) {+ toast.error(String(e))+ } finally {+ setImporting(null)+ }+ }++ const handleSave = async () => {+ const trimmed = name.trim()+ if (!trimmed) {+ toast.error(t('common:skillNameRequired'))+ return+ }+ setSaving(true)+ try {+ await write(trimmed, content)+ setSelected(trimmed)+ setIsNew(false)+ toast.success(t('common:skillSaved'))+ } catch (e) {+ toast.error(String(e))+ } finally {+ setSaving(false)+ }+ }++ const handleDelete = async (skillName: string) => {+ try {+ await remove(skillName)+ if (selected === skillName) closeEditor()+ } catch (e) {+ toast.error(String(e))+ }+ }++ const editing = isNew || selected !== null++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="max-w-3xl">+ <DialogHeader>+ <DialogTitle>{t('common:skillsTitle')}</DialogTitle>+ </DialogHeader>++ {!folder ? (+ <div className="py-10 text-center text-sm text-muted-foreground">+ {t('common:skillsSelectFolder')}+ </div>+ ) : (+ <div className="flex gap-4 h-[60vh] overflow-hidden">+ {/* Skill list */}+ <div className="w-1/3 min-h-0 flex flex-col gap-2 border-r pr-3">+ <Button+ variant="outline"+ size="sm"+ className="gap-1.5 justify-start"+ onClick={startNew}+ >+ <Plus size={14} />+ {t('common:skillNew')}+ </Button>+ <Button+ variant="outline"+ size="sm"+ className={cn(+ 'gap-1.5 justify-start',+ hubMode && 'bg-accent'+ )}+ onClick={openHub}+ >+ <DownloadCloud size={14} />+ {t('common:skillHubImport')}+ </Button>+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col gap-1">+ {skills.length === 0 ? (+ <p className="text-xs text-muted-foreground px-1 py-2">+ {t('common:skillsEmpty')}+ </p>+ ) : (+ skills.map((s) => (+ <div+ key={s.name}+ className={cn(+ 'group flex items-center gap-2 rounded-md px-2 py-1.5 text-sm cursor-pointer hover:bg-accent',+ !hubMode && selected === s.name && 'bg-accent'+ )}+ onClick={() => openSkill(s.name)}+ >+ <FileText size={14} className="shrink-0 text-muted-foreground" />+ <div className="flex-1 min-w-0">+ <div className="truncate font-medium">{s.name}</div>+ {s.description && (+ <div className="line-clamp-2 break-words text-xs text-muted-foreground">+ {s.description}+ </div>+ )}+ </div>+ <button+ className="opacity-0 group-hover:opacity-100 text-muted-foreground hover:text-destructive"+ onClick={(e) => {+ e.stopPropagation()+ handleDelete(s.name)+ }}+ title={t('common:skillDelete')}+ >+ <Trash2 size={14} />+ </button>+ </div>+ ))+ )}+ </div>+ </div>++ {/* Right pane: hub browser, editor, or placeholder */}+ <div className="flex-1 min-w-0 min-h-0 flex flex-col gap-2">+ {hubMode ? (+ <>+ <div className="text-sm font-medium">+ {t('common:skillHubTitle')}+ </div>+ {hubLoading ? (+ <div className="flex-1 flex items-center justify-center text-muted-foreground">+ <Loader2 className="animate-spin" size={18} />+ </div>+ ) : hubSkills.length === 0 ? (+ <div className="flex-1 flex items-center justify-center text-sm text-muted-foreground">+ {t('common:skillHubEmpty')}+ </div>+ ) : (+ <div className="flex-1 min-h-0 overflow-y-auto flex flex-col gap-1">+ {hubSkills.map((s) => {+ const imported = localNames.has(s.name)+ return (+ <div+ key={s.name}+ className="flex items-center gap-2 rounded-md px-2 py-1.5 min-w-0"+ >+ <div className="flex-1 min-w-0">+ <div className="truncate font-medium text-sm">+ {s.name}+ </div>+ {s.description && (+ <div className="line-clamp-2 break-words text-xs text-muted-foreground">+ {s.description}+ </div>+ )}+ </div>+ <Button+ variant="outline"+ size="xs"+ className="gap-1 shrink-0"+ disabled={importing !== null}+ onClick={() => handleImport(s.name)}+ >+ {importing === s.name ? (+ <Loader2 className="animate-spin" size={12} />+ ) : imported ? (+ <Check size={12} />+ ) : (+ <DownloadCloud size={12} />+ )}+ {imported+ ? t('common:skillReimport')+ : t('common:skillImport')}+ </Button>+ </div>+ )+ })}+ </div>+ )}+ </>+ ) : editing ? (+ <>+ <Input+ value={name}+ onChange={(e) => setName(e.target.value)}+ placeholder={t('common:skillNamePlaceholder')}+ disabled={!isNew}+ />+ <Textarea+ value={content}+ onChange={(e) => setContent(e.target.value)}+ placeholder={t('common:skillContentPlaceholder')}+ className="flex-1 font-mono text-xs resize-none"+ />+ <div className="flex justify-end gap-2">+ <Button variant="ghost" size="sm" onClick={closeEditor}>+ {t('common:cancel')}+ </Button>+ <Button size="sm" onClick={handleSave} disabled={saving}>+ {t('common:skillSave')}+ </Button>+ </div>+ </>+ ) : (+ <div className="flex-1 flex items-center justify-center text-sm text-muted-foreground">+ {t('common:skillsPickOrNew')}+ </div>+ )}+ </div>+ </div>+ )}+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/containers/dialogs/ToolApprovalDialog.tsx b/web-app/src/containers/dialogs/ToolApprovalDialog.tsxnew file mode 100644index 000000000..e6951e462--- /dev/null+++ b/web-app/src/containers/dialogs/ToolApprovalDialog.tsx@@ -0,0 +1,121 @@+import type { ReactNode } from 'react'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { AlertTriangle } from 'lucide-react'+import { useTranslation } from '@/i18n/react-i18next-compat'++export type ApprovalDecision = 'allow-once' | 'allow-always' | 'deny'++/**+ * Presentational approval dialog shared by the chat MCP tool-approval flow+ * (`ToolApproval`) and the code agent's permission prompt (`CodePermissionDialog`).+ *+ * It owns only the shell — the shared `tools:toolApproval.*` copy, the+ * deny / allow-once / allow-always footer, and close-as-deny semantics (Esc or+ * click-away resolves to `deny`, the safe default). Callers inject the+ * request-specific body (parameters, command, path, diff) as `children` and map+ * the returned decision onto their own plumbing.+ */+export function ToolApprovalDialog({+ open,+ toolName,+ description,+ offersAlways = true,+ showSecurityNotice = false,+ children,+ onDecision,+}: {+ open: boolean+ toolName: string+ /** Override the default "assistant wants to use {toolName}" description line. */+ description?: ReactNode+ /** Show the allow-always button (defaults to true, matching the chat flow). */+ offersAlways?: boolean+ showSecurityNotice?: boolean+ children?: ReactNode+ onDecision: (decision: ApprovalDecision) => void+}) {+ const { t } = useTranslation()++ return (+ <Dialog+ open={open}+ onOpenChange={(next) => {+ if (!next) onDecision('deny')+ }}+ >+ <DialogContent showCloseButton={false}>+ <DialogHeader>+ <div className="flex items-start gap-3">+ <div className="shrink-0 text-muted-foreground">+ <AlertTriangle className="size-4" />+ </div>+ <div>+ <DialogTitle>{t('tools:toolApproval.title')}</DialogTitle>+ <DialogDescription className="mt-1 text-muted-foreground">+ {description ?? (+ <>+ {t('tools:toolApproval.description')}{' '}+ <span className="font-semibold">{toolName}</span>. + <span className="text-sm">+ {t('tools:toolApproval.permissionScope')}+ </span>+ </>+ )}+ </DialogDescription>+ </div>+ </div>+ </DialogHeader>++ {children}++ {showSecurityNotice && (+ <div className="p-2 border bg-secondary rounded-lg">+ <p className="text-xs text-muted-foreground leading-relaxed">+ {t('tools:toolApproval.securityNotice')}+ </p>+ </div>+ )}++ <DialogFooter className="flex flex-col gap-2 sm:flex-row sm:justify-between">+ <Button+ variant="ghost"+ size="sm"+ onClick={() => onDecision('deny')}+ className="flex-1 text-right sm:flex-none"+ >+ {t('tools:toolApproval.deny')}+ </Button>+ <div className="flex flex-col sm:flex-row gap-2 items-center">+ <Button+ variant="ghost"+ size="sm"+ autoFocus={!offersAlways}+ onClick={() => onDecision('allow-once')}+ >+ {t('tools:toolApproval.allowOnce')}+ </Button>+ {offersAlways && (+ <Button+ variant="default"+ size="sm"+ autoFocus+ className="capitalize"+ onClick={() => onDecision('allow-always')}+ >+ {t('tools:toolApproval.alwaysAllow')}+ </Button>+ )}+ </div>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/web-app/src/hooks/useCodeSessions.ts b/web-app/src/hooks/useCodeSessions.tsnew file mode 100644index 000000000..1d667d2d3--- /dev/null+++ b/web-app/src/hooks/useCodeSessions.ts@@ -0,0 +1,131 @@+import { create } from 'zustand'+import { persist, createJSONStorage } from 'zustand/middleware'+import { localStorageKey } from '@/constants/localStorage'+import { backendStorage } from '@/lib/backendStorage'++// A single visible transcript entry. `tool` rows are display-only and carry the+// structured call/result so the UI can render a tool card. The extra fields are+// optional for backward-compat with sessions persisted before they existed.+export type CodeTurn = {+ role: 'user' | 'assistant' | 'tool'+ content: string+ // Tool-row only: merged from the `tool_call` + matching `tool_result` events.+ callId?: string+ name?: string+ args?: unknown+ result?: string+ isError?: boolean+ diff?: string+ status?: 'running' | 'done'+}++// OpenAI-style history replayed to the agent on the next turn (no tool rows).+export type CodeMessage = {+ role: 'user' | 'assistant'+ content: string+}++export type CodeSession = {+ id: string+ title: string+ folder: string | null+ turns: CodeTurn[]+ history: CodeMessage[]+ updated: number+}++type CodeSessionsState = {+ sessions: CodeSession[]+ currentId: string | null+ createSession: () => string+ selectSession: (id: string) => void+ deleteSession: (id: string) => void+ setFolder: (id: string, folder: string) => void+ setTitle: (id: string, title: string) => void+ commitTurns: (id: string, turns: CodeTurn[], history: CodeMessage[]) => void+ clearSession: (id: string) => void+}++const now = () => Date.now()++export const useCodeSessions = create<CodeSessionsState>()(+ persist(+ (set) => ({+ sessions: [],+ currentId: null,++ createSession: () => {+ const id = crypto.randomUUID()+ const session: CodeSession = {+ id,+ title: 'New session',+ folder: null,+ turns: [],+ history: [],+ updated: now(),+ }+ set((s) => ({ sessions: [session, ...s.sessions], currentId: id }))+ return id+ },++ selectSession: (id) => set({ currentId: id }),++ deleteSession: (id) =>+ set((s) => {+ const sessions = s.sessions.filter((x) => x.id !== id)+ const currentId =+ s.currentId === id ? (sessions[0]?.id ?? null) : s.currentId+ return { sessions, currentId }+ }),++ setFolder: (id, folder) =>+ set((s) => ({+ sessions: s.sessions.map((x) =>+ x.id === id ? { ...x, folder, updated: now() } : x+ ),+ })),++ setTitle: (id, title) =>+ set((s) => ({+ sessions: s.sessions.map((x) => (x.id === id ? { ...x, title } : x)),+ })),++ commitTurns: (id, turns, history) =>+ set((s) => ({+ sessions: s.sessions.map((x) =>+ x.id === id+ ? {+ ...x,+ turns: [...x.turns, ...turns],+ history,+ updated: now(),+ }+ : x+ ),+ })),++ clearSession: (id) =>+ set((s) => ({+ sessions: s.sessions.map((x) =>+ x.id === id ? { ...x, turns: [], history: [], updated: now() } : x+ ),+ })),+ }),+ {+ name: localStorageKey.codeSessions,+ // Persist through the Rust settings store (see backendStorage) so sessions+ // live in <jan_data>/settings.json instead of webview localStorage.+ // Async storage requires skipHydration + explicit rehydrate in+ // hydrateBackendStores() once the ServiceHub is ready.+ storage: createJSONStorage(() => backendStorage),+ skipHydration: true,+ }+ )+)++/** Return the current session, creating one if none is selected. */+export function ensureCurrentSession(): string {+ const { currentId, sessions, createSession } = useCodeSessions.getState()+ if (currentId && sessions.some((s) => s.id === currentId)) return currentId+ return createSession()+}diff --git a/web-app/src/hooks/useSkills.ts b/web-app/src/hooks/useSkills.tsnew file mode 100644index 000000000..e5701e21b--- /dev/null+++ b/web-app/src/hooks/useSkills.ts@@ -0,0 +1,160 @@+import { invoke } from '@tauri-apps/api/core'+import { useCallback, useEffect, useRef, useState } from 'react'+import { create } from 'zustand'+import { toast } from 'sonner'++export type SkillMeta = { name: string; description: string }+export type HubSkill = { name: string; description: string }++// The `[skills].enabled` whitelist uses three shapes:+// [] -> all skills enabled (scaffold default; backward compatible)+// ['a','b'] -> only the named skills+// [SKILLS_NONE] -> no skills enabled+// SKILLS_NONE is the empty string, which a real skill name can never be (skill+// names are non-empty file/folder stems). The backend already advertises nothing+// for a whitelist that matches no real skill, so this needs no backend special+// case — it just makes "none" representable, unlike a bare [] (which means all).+export const SKILLS_NONE = ''++/** Resolve the stored whitelist to the set of skills actually enabled. */+export function effectiveEnabled(+ enabled: string[],+ allNames: string[]+): Set<string> {+ if (enabled.length === 0) return new Set(allNames)+ // Drop the sentinel and any stale names (e.g. a since-deleted skill).+ return new Set(+ enabled.filter((n) => n !== SKILLS_NONE && allNames.includes(n))+ )+}++/** Encode a desired enabled-set back into the stored whitelist shape. */+export function storedEnabled(next: Set<string>, allNames: string[]): string[] {+ if (next.size >= allNames.length) return [] // all -> canonical empty+ if (next.size === 0) return [SKILLS_NONE] // none -> sentinel+ return [...next]+}++// Shared mutation counter so every useSkills instance (e.g. the manager dialog+// and the input's SkillSelector) re-fetches when any of them changes a skill.+const useSkillsVersion = create<{ v: number; bump: () => void }>((set) => ({+ v: 0,+ bump: () => set((s) => ({ v: s.v + 1 })),+}))++/**+ * CRUD over the agent's per-project skills (`<folder>/.jan/agent/skills/*.md`),+ * backed by the `agent_skill_*` Tauri commands. All operations are scoped to+ * `folder`; with no folder there are no skills to manage.+ */+export function useSkills(folder: string | null) {+ const [skills, setSkills] = useState<SkillMeta[]>([])+ // Enabled-skill whitelist from `[skills].enabled`; empty = all skills enabled.+ const [enabled, setEnabledState] = useState<string[]>([])+ const [loading, setLoading] = useState(false)+ const version = useSkillsVersion((s) => s.v)+ const bump = useSkillsVersion((s) => s.bump)+ // Mirrors `enabled` so `setEnabled` can roll back to the last known value after+ // an await without depending on (and being recreated by) the state itself.+ const enabledRef = useRef<string[]>([])++ const refresh = useCallback(async () => {+ if (!folder) {+ setSkills([])+ setEnabledState([])+ enabledRef.current = []+ return+ }+ setLoading(true)+ try {+ const [list, en] = await Promise.all([+ invoke<SkillMeta[]>('agent_skill_list', { project: folder }),+ invoke<string[]>('agent_skill_enabled_get', { project: folder }),+ ])+ setSkills(list)+ setEnabledState(en)+ enabledRef.current = en+ } finally {+ setLoading(false)+ }+ }, [folder])++ // Persist the enabled whitelist (empty = all). Optimistic local update; on a+ // write failure, roll back so the UI never diverges from the on-disk config.+ // Errors are surfaced and swallowed here so fire-and-forget callers (e.g. the+ // SkillSelector toggle) don't produce unhandled rejections.+ const setEnabled = useCallback(+ async (names: string[]) => {+ const prev = enabledRef.current+ setEnabledState(names)+ enabledRef.current = names+ try {+ await invoke('agent_skill_enabled_set', {+ project: folder,+ enabled: names,+ })+ bump()+ } catch (e) {+ setEnabledState(prev)+ enabledRef.current = prev+ toast.error(String(e))+ }+ },+ [folder, bump]+ )++ // Re-fetch on folder change AND whenever any instance mutates skills.+ useEffect(() => {+ refresh()+ }, [refresh, version])++ const read = useCallback(+ (name: string) =>+ invoke<string>('agent_skill_read', { project: folder, name }),+ [folder]+ )++ const write = useCallback(+ async (name: string, content: string) => {+ await invoke('agent_skill_write', { project: folder, name, content })+ bump()+ },+ [folder, bump]+ )++ const remove = useCallback(+ async (name: string) => {+ await invoke('agent_skill_delete', { project: folder, name })+ bump()+ },+ [folder, bump]+ )++ // Anthropic skill hub. `hubList` is project-independent; `hubImport` downloads+ // into the current folder, then bumps so all instances re-fetch.+ const hubList = useCallback(+ () => invoke<HubSkill[]>('agent_skill_hub_list'),+ []+ )++ const hubImport = useCallback(+ async (name: string) => {+ await invoke('agent_skill_hub_import', { project: folder, name })+ bump()+ },+ [folder, bump]+ )++ return {+ skills,+ enabled,+ setEnabled,+ loading,+ refresh,+ read,+ write,+ remove,+ hubList,+ hubImport,+ }+}diff --git a/web-app/src/lib/__tests__/messages.test.ts b/web-app/src/lib/__tests__/messages.test.tsindex 9f1e31ef2..8018f38db 100644--- a/web-app/src/lib/__tests__/messages.test.ts+++ b/web-app/src/lib/__tests__/messages.test.ts@@ -19,6 +19,10 @@ describe('parseReasoning', () => {['completed <thought>', '<thought>reason</thought>answer', { reasoningSegment: '<thought>reason</thought>', textSegment: 'answer' }],['text before tags', 'Some prefix <think>Internal thought</think>Some suffix', { reasoningSegment: 'Some prefix <think>Internal thought</think>', textSegment: 'Some suffix' }],['multiple tags', '<think>First</think><think>Second</think>Answer', { reasoningSegment: '<think>First</think>', textSegment: '<think>Second</think>Answer' }],+ ['in-progress namespaced <mm:think>', '<mm:think>reasoning...', { reasoningSegment: '<mm:think>reasoning...', textSegment: '' }],+ ['completed namespaced <mm:think>', '<mm:think>reason</mm:think>answer', { reasoningSegment: '<mm:think>reason</mm:think>', textSegment: 'answer' }],+ ['completed <thinking>', '<thinking>reason</thinking>answer', { reasoningSegment: '<thinking>reason</thinking>', textSegment: 'answer' }],+ ['completed <reasoning>', '<reasoning>reason</reasoning>answer', { reasoningSegment: '<reasoning>reason</reasoning>', textSegment: 'answer' }],])('handles %s', (_label, input, expected) => {expect(parseReasoning(input)).toEqual(expected)})@@ -167,6 +171,14 @@ describe('convertThreadMessageToUIMessage', () => {expect(result.parts).toContainEqual({ type: 'text', text: 'answer text' })})+ it('handles namespaced <mm:think> reasoning', () => {+ const result = convertThreadMessageToUIMessage(makeTm({+ content: [{ type: ContentType.Text, text: { value: '<mm:think>reason</mm:think>answer text', annotations: [] } }],+ }) as any)+ expect(result.parts).toContainEqual({ type: 'reasoning', text: 'reason' })+ expect(result.parts).toContainEqual({ type: 'text', text: 'answer text' })+ })+it('handles in-progress think tag', () => {const result = convertThreadMessageToUIMessage(makeTm({content: [{ type: ContentType.Text, text: { value: '<think>thinking...', annotations: [] } }],diff --git a/web-app/src/lib/codeTurns.ts b/web-app/src/lib/codeTurns.tsnew file mode 100644index 000000000..b42605aec--- /dev/null+++ b/web-app/src/lib/codeTurns.ts@@ -0,0 +1,91 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import type { UIMessage } from 'ai'+import type { CodeTurn } from '@/hooks/useCodeSessions'+import { reasoningPartsFromText } from '@/lib/messages'++/**+ * Adapts the code screen's flat `CodeTurn[]` transcript into the AI SDK+ * `UIMessage[]` shape that `MessageItem` (the shared chat renderer) consumes.+ *+ * Grouping: each `user` turn starts a user message; every following+ * `assistant`/`tool` turn folds into a single assistant message (assistant text+ * as reasoning/`text` parts, tool calls as `tool-<name>` parts) until the next user turn —+ * mirroring how one agent turn maps to one assistant message with ordered parts.+ *+ * `diff` has no dedicated slot in the UIMessage tool part, so it is prepended to+ * the tool output as text (per the chosen tradeoff — non-colored).+ */+export function codeTurnsToUIMessages(+ turns: CodeTurn[],+ idPrefix = 'code'+): UIMessage[] {+ const messages: UIMessage[] = []+ let assistant: any = null++ const flushAssistant = () => {+ if (assistant && assistant.parts.length > 0) messages.push(assistant)+ assistant = null+ }++ const ensureAssistant = (index: number) => {+ if (!assistant) {+ assistant = { id: `${idPrefix}-asst-${index}`, role: 'assistant', parts: [] }+ }+ return assistant+ }++ turns.forEach((turn, i) => {+ if (turn.role === 'user') {+ flushAssistant()+ messages.push({+ id: `${idPrefix}-user-${i}`,+ role: 'user',+ parts: [{ type: 'text', text: turn.content }],+ } as any)+ return+ }++ if (turn.role === 'assistant') {+ // Split out <think>/<thought> reasoning into reasoning parts (same helper+ // the chat loader uses) so the agent's chain-of-thought renders in the+ // collapsible reasoning UI instead of leaking into the transcript as text.+ if (turn.content) {+ const asst = ensureAssistant(i)+ for (const part of reasoningPartsFromText(turn.content)) {+ asst.parts.push(part)+ }+ }+ return+ }++ // tool turn -> a `tool-<name>` part on the current assistant message.+ const name = turn.name ?? 'tool'+ const running = turn.status === 'running'+ const part: any = {+ type: `tool-${name}`,+ toolCallId: turn.callId ?? `code-tool-${i}`,+ input: turn.args,+ state: running+ ? 'input-available'+ : turn.isError+ ? 'output-error'+ : 'output-available',+ }++ if (!running) {+ // Legacy turns carry only `content`; new turns carry result (+optional diff).+ const body = turn.result ?? turn.content ?? ''+ const output = turn.diff ? `${turn.diff}\n\n${body}` : body+ if (turn.isError) {+ part.errorText = output+ } else {+ part.output = output+ }+ }++ ensureAssistant(i).parts.push(part)+ })++ flushAssistant()+ return messages+}diff --git a/web-app/src/lib/hydrateStores.ts b/web-app/src/lib/hydrateStores.tsindex d4abd3dc1..f94b309b9 100644--- a/web-app/src/lib/hydrateStores.ts+++ b/web-app/src/lib/hydrateStores.ts@@ -20,6 +20,7 @@ import { useJanModelPromptDismissed } from '@/hooks/useJanModelPrompt'import { useDefaultEmbeddingModel } from '@/hooks/useDefaultEmbeddingModel'import { useAgentMode } from '@/hooks/useAgentMode'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'+import { useCodeSessions } from '@/hooks/useCodeSessions'/*** Stores persisted through `backendStorage` set `skipHydration: true` so they@@ -51,6 +52,7 @@ const secondaryStores = [useDefaultEmbeddingModel,useAgentMode,useWebSearchConfig,+ useCodeSessions,] as constexport async function hydrateBackendStores(): Promise<void> {diff --git a/web-app/src/lib/messages.ts b/web-app/src/lib/messages.tsindex 74f518ebe..cacf054b2 100644--- a/web-app/src/lib/messages.ts+++ b/web-app/src/lib/messages.ts@@ -153,16 +153,26 @@ export type ToolResult = {error?: string}+// Reasoning models wrap their chain-of-thought in a tag we strip out: <think>,+// <thought> (Gemma), <thinking>, <reasoning>, plus namespaced variants like+// <mm:think> (MiniMax). Matches an optional `ns:` prefix + a known keyword and+// tolerates attributes on the opening tag. `\1` binds the close tag to the open.+const REASONING_TAG = '(?:[a-zA-Z][a-zA-Z0-9]*:)?(?:think|thinking|thought|reasoning)'+const openReasoningTagRe = () => new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>`, 'i')+const completedReasoningTagRe = () =>+ new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*?)</\\1>`, 'i')+/*** Parse reasoning segments from the given text.* @param text - The text to parse reasoning from.* @returns*/export const parseReasoning = (text: string) => {- // Check for thinking formats- const hasThinkTag =- (text.includes('<think>') && !text.includes('</think>')) ||- (text.includes('<thought>') && !text.includes('</thought>'))+ // In-progress reasoning: an opening tag whose matching close hasn't streamed yet.+ const openTag = text.match(openReasoningTagRe())+ const hasThinkTag = openTag+ ? !new RegExp(`</${openTag[1]}>`, 'i').test(text)+ : falseconst hasAnalysisChannel =text.includes('<|channel|>analysis<|message|>') &&!text.includes('<|start|>assistant<|channel|>final<|message|>')@@ -171,7 +181,7 @@ export const parseReasoning = (text: string) => {return { reasoningSegment: text, textSegment: '' }// Check for completed think tag format- const thinkMatch = text.match(/<(think|thought)>([\s\S]*?)<\/\1>/)+ const thinkMatch = text.match(completedReasoningTagRe())if (thinkMatch?.index !== undefined) {const splitIndex = thinkMatch.index + thinkMatch[0].lengthreturn {@@ -195,6 +205,48 @@ export const parseReasoning = (text: string) => {return { reasoningSegment: undefined, textSegment: text }}+export type ReasoningTextPart = { type: 'reasoning' | 'text'; text: string }++/**+ * Split a raw assistant string into reasoning/text UIMessage parts, pulling out+ * `<think>`/`<thought>`-wrapped reasoning (via {@link parseReasoning}) so it+ * renders in the collapsible reasoning UI instead of inline as literal tags.+ * Shared by the chat message loader and the code agent transcript so both+ * surface reasoning the same way.+ */+export function reasoningPartsFromText(text: string): ReasoningTextPart[] {+ const parts: ReasoningTextPart[] = []+ const { reasoningSegment, textSegment } = parseReasoning(text)++ if (reasoningSegment) {+ // Extract the reasoning text from inside the tag (group 2 = content).+ const completedMatch = reasoningSegment.match(+ new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*)</\\1>`, 'i')+ )+ if (completedMatch) {+ parts.push({ type: 'reasoning', text: completedMatch[2] })+ } else {+ // In-progress reasoning - content after an unclosed reasoning tag.+ const inProgressMatch = reasoningSegment.match(+ new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*)`, 'i')+ )+ if (inProgressMatch) {+ parts.push({ type: 'reasoning', text: inProgressMatch[2] })+ }+ }+ }++ if (textSegment) {+ const trimmedText = textSegment.trim()+ if (trimmedText) parts.push({ type: 'text', text: trimmedText })+ } else if (!reasoningSegment) {+ // No reasoning segment, just add the text as-is.+ parts.push({ type: 'text', text })+ }++ return parts+}+/*** Convert Jan's ThreadMessage format to AI SDK UIMessage format.* This is used to load existing messages into the AI SDK chat.@@ -214,50 +266,9 @@ export function convertThreadMessageToUIMessage(text: content.text.value,})} else if (content.type === 'text' && content.text?.value) {- // Text content - check if it contains old-format reasoning in <think> tags- const { reasoningSegment, textSegment } = parseReasoning(- content.text.value- )-- // BACKWARD COMPATIBILITY: Handle old format with <think> tags- if (reasoningSegment) {- // Extract reasoning text from <think> or <thought> tags- const completedMatch = reasoningSegment.match(- /<(think|thought)>([\s\S]*)<\/\1>/- )- if (completedMatch) {- parts.push({- type: 'reasoning',- text: completedMatch[2],- })- } else {- // In-progress reasoning - extract content after <think> or <thought> tag- const inProgressMatch = reasoningSegment.match(/<(think|thought)>([\s\S]*)/)- if (inProgressMatch) {- parts.push({- type: 'reasoning',- text: inProgressMatch[2],- })- }- }- }-- if (textSegment) {- // Trim leading whitespace/newlines from the text segment- const trimmedText = textSegment.trim()- if (trimmedText) {- parts.push({- type: 'text',- text: trimmedText,- })- }- } else if (!reasoningSegment) {- // No reasoning segment, just add the text as-is- parts.push({- type: 'text',- text: content.text.value,- })- }+ // Text content - split out any legacy <think>/<thought> reasoning so it+ // renders in the reasoning UI instead of inline (see reasoningPartsFromText).+ parts.push(...reasoningPartsFromText(content.text.value))} else if (content.type === 'image_url' && content.image_url?.url) {parts.push({type: 'file',diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex e7edeb56b..e5049a989 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -29,6 +29,45 @@"appearance": "Appearance","privacy": "Privacy","keyboardShortcuts": "Shortcuts",+ "home": "Home",+ "code": "Code",+ "newSession": "New session",+ "artifacts": "Artifacts",+ "customize": "Customize",+ "local": "Local",+ "selectFolder": "Select folder",+ "selectModel": "Select a model first",+ "commands": "Commands",+ "cmdHelp": "List available commands",+ "cmdClear": "Clear this session",+ "cmdModels": "Switch the active model",+ "cmdModelsHint": "Type /models then pick a model from the list",+ "cmdModelSwitched": "Switched to {{name}}",+ "cmdUnknown": "Unknown command: {{name}}. Try /help",+ "cmdBusy": "Can't do that while the agent is running",+ "skills": "Skills",+ "skillsInContext": "Skills available to the agent this run",+ "skillsTitle": "Manage skills",+ "skillsSelectFolder": "Select a project folder in the code screen first to manage its skills.",+ "skillsEmpty": "No skills yet",+ "skillsPickOrNew": "Select a skill to edit, or create a new one.",+ "skillNew": "New skill",+ "skillDelete": "Delete skill",+ "skillSave": "Save",+ "skillSaved": "Skill saved",+ "skillNameRequired": "Skill name is required",+ "skillNamePlaceholder": "skill-name",+ "skillContentPlaceholder": "Describe the reusable procedure in Markdown…",+ "skillHubImport": "Import from hub",+ "skillHubTitle": "Anthropic skill hub",+ "skillHubEmpty": "No skills found on the hub",+ "skillImport": "Import",+ "skillReimport": "Re-import",+ "skillImported": "Imported {{name}}",+ "sessions": "Sessions",+ "deleteSession": "Delete session",+ "deleteSessionTitle": "Delete session?",+ "deleteSessionBody": "\"{{title}}\" and its transcript will be permanently deleted. This can't be undone.","newChat": "New Chat","newAgentChat": "New Agent Chat","chats": "Chats",diff --git a/web-app/src/routeTree.gen.ts b/web-app/src/routeTree.gen.tsindex a2a333a4c..1cb42c97c 100644--- a/web-app/src/routeTree.gen.ts+++ b/web-app/src/routeTree.gen.ts@@ -11,6 +11,7 @@import { Route as rootRouteImport } from './routes/__root'import { Route as SystemMonitorRouteImport } from './routes/system-monitor'import { Route as LogsRouteImport } from './routes/logs'+import { Route as CodeRouteImport } from './routes/code'import { Route as IndexRouteImport } from './routes/index'import { Route as HubIndexRouteImport } from './routes/hub/index'import { Route as ThreadsThreadIdRouteImport } from './routes/threads/$threadId'@@ -43,6 +44,11 @@ const LogsRoute = LogsRouteImport.update({path: '/logs',getParentRoute: () => rootRouteImport,} as any)+const CodeRoute = CodeRouteImport.update({+ id: '/code',+ path: '/code',+ getParentRoute: () => rootRouteImport,+} as any)const IndexRoute = IndexRouteImport.update({id: '/',path: '/',@@ -152,6 +158,7 @@ const SettingsProvidersProviderNameRoute =export interface FileRoutesByFullPath {'/': typeof IndexRoute+ '/code': typeof CodeRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -177,6 +184,7 @@ export interface FileRoutesByFullPath {}export interface FileRoutesByTo {'/': typeof IndexRoute+ '/code': typeof CodeRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -203,6 +211,7 @@ export interface FileRoutesByTo {export interface FileRoutesById {__root__: typeof rootRouteImport'/': typeof IndexRoute+ '/code': typeof CodeRoute'/logs': typeof LogsRoute'/system-monitor': typeof SystemMonitorRoute'/hub/$modelId': typeof HubModelIdRoute@@ -230,6 +239,7 @@ export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPathfullPaths:| '/'+ | '/code'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -255,6 +265,7 @@ export interface FileRouteTypes {fileRoutesByTo: FileRoutesByToto:| '/'+ | '/code'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -280,6 +291,7 @@ export interface FileRouteTypes {id:| '__root__'| '/'+ | '/code'| '/logs'| '/system-monitor'| '/hub/$modelId'@@ -306,6 +318,7 @@ export interface FileRouteTypes {}export interface RootRouteChildren {IndexRoute: typeof IndexRoute+ CodeRoute: typeof CodeRouteLogsRoute: typeof LogsRouteSystemMonitorRoute: typeof SystemMonitorRouteHubModelIdRoute: typeof HubModelIdRoute@@ -346,6 +359,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof LogsRouteImportparentRoute: typeof rootRouteImport}+ '/code': {+ id: '/code'+ path: '/code'+ fullPath: '/code'+ preLoaderRoute: typeof CodeRouteImport+ parentRoute: typeof rootRouteImport+ }'/': {id: '/'path: '/'@@ -498,6 +518,7 @@ declare module '@tanstack/react-router' {const rootRouteChildren: RootRouteChildren = {IndexRoute: IndexRoute,+ CodeRoute: CodeRoute,LogsRoute: LogsRoute,SystemMonitorRoute: SystemMonitorRoute,HubModelIdRoute: HubModelIdRoute,diff --git a/web-app/src/routes/code.tsx b/web-app/src/routes/code.tsxnew file mode 100644index 000000000..f3f3af7a2--- /dev/null+++ b/web-app/src/routes/code.tsx@@ -0,0 +1,673 @@+/* eslint-disable @typescript-eslint/no-explicit-any */+import { createFileRoute } from '@tanstack/react-router'+import ChatInput from '@/containers/ChatInput'+import HeaderPage from '@/containers/HeaderPage'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { route } from '@/constants/routes'+import { Button } from '@/components/ui/button'+import { useServiceHub } from '@/hooks/useServiceHub'+import { Laptop, Folder } from 'lucide-react'+import { useEffect, useMemo, useRef, useState } from 'react'+import { toast } from 'sonner'+import { invoke, Channel } from '@tauri-apps/api/core'+import { cn, getProviderTitle, getModelDisplayName } from '@/lib/utils'+import { predefinedProviders } from '@/constants/providers'+import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'+import {+ useCodeSessions,+ ensureCurrentSession,+ type CodeTurn,+ type CodeMessage,+} from '@/hooks/useCodeSessions'+import DropdownModelProvider from '@/containers/DropdownModelProvider'+import { useModelProvider } from '@/hooks/useModelProvider'+import { usePrompt } from '@/hooks/usePrompt'+import CodePermissionDialog, {+ type PendingPermission,+ type PermissionDecision,+} from '@/containers/dialogs/CodePermissionDialog'+import { MessageItem } from '@/containers/MessageItem'+import SkillSelector from '@/containers/SkillSelector'+import { codeTurnsToUIMessages } from '@/lib/codeTurns'+import { PromptProgress } from '@/components/PromptProgress'+import { useAppState } from '@/hooks/useAppState'+import { useAutoScroll } from '@/hooks/useAutoScroll'+import {+ Conversation,+ ConversationContent,+ ConversationScrollButton,+} from '@/components/ai-elements/conversation'++export const Route = createFileRoute(route.code as any)({+ component: CodePage,+})++// StreamEvent shapes emitted by the Rust agent loop (events.rs, tag = "type").+type StreamEvent =+ | { type: 'token'; text: string }+ | { type: 'step'; index: number; max: number }+ | { type: 'tool_call'; id: string; name: string; args: unknown }+ | { type: 'tool_result'; id: string; content: string; is_error: boolean; diff?: string }+ | { type: 'done'; stop_reason: string; usage: unknown }+ | { type: 'error'; code: string; message: string }+ | {+ type: 'permission_request'+ request_id: string+ tool_name: string+ capability: string+ path?: string+ command?: string+ diff?: string+ prompt_kind: string+ offers_always: boolean+ }++// Per-run token ceiling. `max_turns: 0` lets a multi-step task run to completion;+// this budget is the real bound that stops a runaway loop (see loop.rs).+const MAX_SESSION_TOKENS = 200_000++// Cap the history replayed to the agent so a long session never sends more than+// the model can take (rough ~4 chars/token estimate → well under the ceiling).+// Keeps the most recent messages; older ones roll off. Display keeps everything.+const MAX_HISTORY_CHARS = 400_000++function capHistory(messages: CodeMessage[]): CodeMessage[] {+ let budget = MAX_HISTORY_CHARS+ const kept: CodeMessage[] = []+ for (let i = messages.length - 1; i >= 0; i--) {+ budget -= messages[i].content.length+ if (budget < 0 && kept.length > 0) break+ kept.unshift(messages[i])+ }+ return kept+}++// Strict chat templates (llama.cpp Jinja) require strictly alternating+// user/assistant roles and reject empty content. Drop empties and merge+// consecutive same-role messages so a turn that produced no assistant text+// (tool-only / cancelled / errored) can't leave two user messages adjacent.+const normalizeAlternating = (messages: CodeMessage[]): CodeMessage[] => {+ const out: CodeMessage[] = []+ for (const m of messages) {+ if (!m.content.trim()) continue+ // The template also requires the conversation to START with user; drop any+ // leading assistant message (e.g. after aggressive trimming).+ if (out.length === 0 && m.role !== 'user') continue+ const last = out[out.length - 1]+ if (last && last.role === m.role) {+ last.content = `${last.content}\n\n${m.content}`+ } else {+ out.push({ role: m.role, content: m.content })+ }+ }+ return out+}++// Slash commands available from the input. Client-side actions — they never hit+// the agent. `descKey` is an i18n key resolved at render time. mode 'run'+// executes immediately; 'args' fills the input so the user can pick an argument+// (e.g. /models → model picker).+const SLASH_COMMANDS = [+ { name: '/help', descKey: 'common:cmdHelp', mode: 'run' },+ { name: '/clear', descKey: 'common:cmdClear', mode: 'run' },+ { name: '/models', descKey: 'common:cmdModels', mode: 'args' },+] as const++// A row in the slash menu — commands and model options share one shape so the+// keyboard navigation works uniformly across both.+type MenuItem = {+ key: string+ label: string+ description: string+ onSelect: () => void+}++function CodePage() {+ const { t } = useTranslation()+ const serviceHub = useServiceHub()++ const sessions = useCodeSessions((s) => s.sessions)+ const currentId = useCodeSessions((s) => s.currentId)+ const current = sessions.find((s) => s.id === currentId)+ const selectedModel = useModelProvider((s) => s.selectedModel)+ const selectedProvider = useModelProvider((s) => s.selectedProvider)+ const providers = useModelProvider((s) => s.providers)++ const folder = current?.folder ?? null+ const folderName = folder ? folder.split(/[/\\]/).pop() : undefined++ // In-flight transcript for the active run; committed to the store on `done`.+ const [liveTurns, setLiveTurns] = useState<CodeTurn[]>([])+ const [running, setRunning] = useState(false)+ // Mirrors `running` for reads from closures that outlive a render (the slash+ // menu's onSelect is memoized without a `running` dep, so it would otherwise+ // see a stale value).+ const runningRef = useRef(false)+ const liveTurnsRef = useRef<CodeTurn[]>([])+ const runIdRef = useRef<string | null>(null)++ // Local (llamacpp) models can take a while to load before the first token.+ // The router emits `llamacpp-model-load-progress`, which LlamacppOomListener+ // pipes into the global useAppState load state; we just flip `loadingModel`+ // (the flag PromptProgress keys off) on for the code run so the shared+ // progress card shows here too. Cleared once generation starts or the run ends.+ const modelLoadingRef = useRef(false)+ const finishModelLoad = () => {+ if (!modelLoadingRef.current) return+ modelLoadingRef.current = false+ useAppState.getState().updateLoadingModel(false)+ useAppState.getState().updateModelLoadProgress(undefined)+ }+ // Clear the shared load flag if the user navigates away mid-load.+ useEffect(() => finishModelLoad, [])++ // Same auto-scroll wiring the chat route uses, so the streaming reasoning+ // block scrolls and shows the scroll-to-bottom button identically here.+ const {+ containerRef: reasoningContainerRef,+ isAtBottom: isReasoningAtBottom,+ handleScroll: handleReasoningScroll,+ forceScrollToBottom: forceScrollReasoningToBottom,+ } = useAutoScroll()++ // Queue of gated tool calls awaiting the user's approval. The agent loop+ // awaits each one, so in practice there is at most one live at a time, but we+ // queue defensively. The head is shown in the approval dialog.+ const [pendingPerms, setPendingPerms] = useState<PendingPermission[]>([])++ const respondPermission = (requestId: string, decision: PermissionDecision) => {+ invoke('agent_permission_respond', { requestId, decision }).catch(() => {})+ setPendingPerms((prev) => prev.filter((p) => p.requestId !== requestId))+ }++ const displayedTurns: CodeTurn[] = useMemo(+ () => [...(current?.turns ?? []), ...liveTurns],+ [current?.turns, liveTurns]+ )+ // Committed turns are stable during a run; only the live tail changes per+ // token. Memoize them separately so streaming rebuilds just the small tail,+ // not the whole transcript. Distinct id prefixes keep React keys unique.+ const committedMessages = useMemo(+ () => codeTurnsToUIMessages(current?.turns ?? [], 'c'),+ [current?.turns]+ )+ const liveMessages = useMemo(+ () => codeTurnsToUIMessages(liveTurns, 'l'),+ [liveTurns]+ )+ const uiMessages = useMemo(+ () => [...committedMessages, ...liveMessages],+ [committedMessages, liveMessages]+ )++ // Slash commands: the input text lives in the shared usePrompt store, so we can+ // drive the menu (and keyboard nav) without touching ChatInput.+ const prompt = usePrompt((s) => s.prompt)+ const [menuIndex, setMenuIndex] = useState(0)++ // Switchable models for /models — mirrors DropdownModelProvider's filtering:+ // active providers only, no embedding models, and skip remote providers that+ // have no API key configured (they can't actually be used).+ const allModels = useMemo(() => {+ const items: { providerName: string; id: string; label: string }[] = []+ providers.forEach((p) => {+ if (!p.active) return+ const isPredefined = predefinedProviders.some((e) =>+ e.provider.includes(p.provider)+ )+ if (+ p.provider !== 'llamacpp' &&+ !providerHasRemoteApiKeys(p) &&+ (isPredefined || p.models.length === 0)+ )+ return+ p.models.forEach((m) => {+ if (m.embedding) return+ items.push({+ providerName: p.provider,+ id: m.id,+ label: getModelDisplayName(m),+ })+ })+ })+ return items+ }, [providers])++ const runCommand = (raw: string) => {+ const parts = raw.trim().split(/\s+/)+ const name = parts[0]+ const arg = parts.slice(1).join(' ')+ switch (name) {+ case '/help':+ toast(t('common:commands'), {+ description: SLASH_COMMANDS.map(+ (c) => `${c.name} — ${t(c.descKey)}`+ ).join('\n'),+ })+ break+ case '/clear':+ // Clearing mid-run would wipe the session the in-flight run is about to+ // commit its transcript into, leaving it inconsistent.+ if (runningRef.current) {+ toast.error(t('common:cmdBusy'))+ break+ }+ if (currentId) useCodeSessions.getState().clearSession(currentId)+ break+ case '/models': {+ const q = arg.toLowerCase()+ const found = allModels.find(+ (m) => m.id.toLowerCase() === q || m.label.toLowerCase() === q+ )+ if (found) switchModel(found.providerName, found.id)+ else toast(t('common:cmdModelsHint'))+ break+ }+ default:+ toast.error(t('common:cmdUnknown', { name }))+ }+ }++ const switchModel = (providerName: string, modelId: string) => {+ useModelProvider.getState().selectModelProvider(providerName, modelId)+ usePrompt.getState().setPrompt('')+ toast.success(t('common:cmdModelSwitched', { name: modelId }))+ }++ // Build the current menu: model picker when the text is `/models[ filter]`,+ // otherwise the command list filtered by the typed `/token`.+ const menuItems: MenuItem[] = useMemo(() => {+ const inModelMode = prompt === '/models' || prompt.startsWith('/models ')+ if (inModelMode) {+ const filter = prompt.slice('/models'.length).trim().toLowerCase()+ return allModels+ .filter((m) => `${m.id} ${m.label}`.toLowerCase().includes(filter))+ .slice(0, 50)+ .map((m) => ({+ key: `${m.providerName}/${m.id}`,+ label: m.label,+ description: getProviderTitle(m.providerName),+ onSelect: () => switchModel(m.providerName, m.id),+ }))+ }+ if (prompt.startsWith('/') && !prompt.includes(' ')) {+ const q = prompt.slice(1)+ return SLASH_COMMANDS.filter((c) => c.name.slice(1).startsWith(q)).map(+ (c) => ({+ key: c.name,+ label: c.name,+ description: t(c.descKey),+ onSelect: () =>+ c.mode === 'args'+ ? usePrompt.getState().setPrompt(`${c.name} `)+ : (usePrompt.getState().setPrompt(''), runCommand(c.name)),+ })+ )+ }+ return []+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [prompt, allModels, t])++ // Reset the highlighted row whenever the menu contents change.+ useEffect(() => setMenuIndex(0), [prompt])++ // Capture-phase keydown so ↑/↓/Enter/Esc drive the menu BEFORE ChatInput's+ // textarea sees them (no ChatInput changes needed).+ const onMenuKeyDown = (e: React.KeyboardEvent) => {+ if (menuItems.length === 0) return+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ e.stopPropagation()+ setMenuIndex((i) => Math.min(i + 1, menuItems.length - 1))+ } else if (e.key === 'ArrowUp') {+ e.preventDefault()+ e.stopPropagation()+ setMenuIndex((i) => Math.max(i - 1, 0))+ } else if (e.key === 'Enter') {+ e.preventDefault()+ e.stopPropagation()+ menuItems[Math.min(menuIndex, menuItems.length - 1)]?.onSelect()+ } else if (e.key === 'Escape') {+ e.preventDefault()+ e.stopPropagation()+ usePrompt.getState().setPrompt('')+ }+ }++ const pushLive = (turn: CodeTurn) => {+ liveTurnsRef.current = [...liveTurnsRef.current, turn]+ setLiveTurns(liveTurnsRef.current)+ }++ const appendToken = (text: string) => {+ const arr = liveTurnsRef.current+ const last = arr[arr.length - 1]+ if (last && last.role === 'assistant') {+ liveTurnsRef.current = [+ ...arr.slice(0, -1),+ { ...last, content: last.content + text },+ ]+ } else {+ liveTurnsRef.current = [...arr, { role: 'assistant', content: text }]+ }+ setLiveTurns(liveTurnsRef.current)+ }++ // Merge a `tool_result` into the tool turn its `tool_call` created.+ const updateToolTurn = (callId: string, patch: Partial<CodeTurn>) => {+ const arr = liveTurnsRef.current+ const idx = arr.findIndex((tn) => tn.role === 'tool' && tn.callId === callId)+ if (idx === -1) return+ liveTurnsRef.current = [+ ...arr.slice(0, idx),+ { ...arr[idx], ...patch },+ ...arr.slice(idx + 1),+ ]+ setLiveTurns(liveTurnsRef.current)+ }++ const handleSelectFolder = async () => {+ const selected = await serviceHub.dialog().open({+ multiple: false,+ directory: true,+ defaultPath: folder ?? undefined,+ })+ if (typeof selected === 'string') {+ const sid = ensureCurrentSession()+ useCodeSessions.getState().setFolder(sid, selected)+ }+ }++ const handleSubmit = async (text: string) => {+ // Slash commands are client-side actions; they never reach the agent.+ if (text.trim().startsWith('/')) {+ runCommand(text)+ return+ }+ if (running) return++ const sid = ensureCurrentSession()+ const store = useCodeSessions.getState()+ const session = store.sessions.find((s) => s.id === sid)+ if (!session?.folder) {+ toast.error(t('common:selectFolder'))+ return+ }+ if (!selectedModel?.id) {+ toast.error(t('common:selectModel'))+ return+ }+ if (session.title === 'New session') {+ store.setTitle(sid, text.slice(0, 40))+ }++ // Mirror the CLI agent: replay the full history each turn (capped only by a+ // coarse sliding window against runaway growth). normalizeAlternating is the+ // one guard the CLI lacks — it keeps roles strictly alternating so a turn+ // that produced no assistant text can't leave two user messages adjacent.+ // Real out-of-context handling belongs in the shared Rust loop, not here.+ const outgoing: CodeMessage[] = normalizeAlternating([+ ...capHistory(session.history),+ { role: 'user', content: text },+ ])+ liveTurnsRef.current = [{ role: 'user', content: text }]+ setLiveTurns(liveTurnsRef.current)+ runningRef.current = true+ setRunning(true)++ // Local models load before the first token — but only on a cold start.+ // Probe the router (as the chat transport does) so the load card shows only+ // when the model isn't already loaded, not on every warm run.+ if (selectedProvider === 'llamacpp') {+ try {+ const loaded = await invoke<string[]>('plugin:llamacpp|get_loaded_models')+ if (!loaded.includes(selectedModel.id)) {+ modelLoadingRef.current = true+ useAppState.getState().updateModelLoadProgress(undefined)+ useAppState.getState().updateLoadingModel(true)+ }+ } catch {+ // Probe failed; skip the load card rather than flash it every run.+ }+ }++ const runId = crypto.randomUUID()+ runIdRef.current = runId++ // Captured across the stream + catch so a failed run leaves a visible marker+ // in the transcript (not just a transient toast).+ let runError: string | null = null++ const onEvent = new Channel<StreamEvent>()+ onEvent.onmessage = (ev) => {+ switch (ev.type) {+ case 'token':+ // First actual output means the model finished loading and is now+ // generating; drop the load card. (`step` fires before invoke/load,+ // so clearing on it would hide the card during the real load.)+ finishModelLoad()+ appendToken(ev.text)+ break+ case 'tool_call':+ // A tool call is model output too — loading is done.+ finishModelLoad()+ pushLive({+ role: 'tool',+ content: '',+ callId: ev.id,+ name: ev.name,+ args: ev.args,+ status: 'running',+ })+ break+ case 'tool_result':+ updateToolTurn(ev.id, {+ result: ev.content,+ isError: ev.is_error,+ diff: ev.diff,+ status: 'done',+ })+ break+ case 'permission_request':+ setPendingPerms((prev) => [+ ...prev,+ {+ requestId: ev.request_id,+ toolName: ev.tool_name,+ capability: ev.capability,+ path: ev.path,+ command: ev.command,+ diff: ev.diff,+ promptKind: ev.prompt_kind,+ offersAlways: ev.offers_always,+ },+ ])+ break+ case 'error':+ if (ev.code !== 'cancelled') {+ runError = ev.message+ toast.error(ev.message)+ }+ break+ case 'done':+ break+ }+ }++ try {+ await invoke('agent_run', {+ runId,+ onEvent,+ body: {+ project: session.folder,+ messages: outgoing,+ max_turns: 0,+ max_session_tokens: MAX_SESSION_TOKENS,+ model: selectedModel.id,+ },+ })+ } catch (e) {+ runError = String(e)+ toast.error(String(e))+ } finally {+ // Drop the load card if the run ended before any stream event (error,+ // cancel, or an unloaded model that never produced output).+ finishModelLoad()+ // Any tool call still 'running' when the run ends was interrupted (cancel+ // or error mid-tool); finalize it so it doesn't render as a forever spinner.+ liveTurnsRef.current = liveTurnsRef.current.map((tn) =>+ tn.role === 'tool' && tn.status === 'running'+ ? { ...tn, status: 'done', isError: true, result: tn.result || '(interrupted)' }+ : tn+ )+ // Surface a failed run in the transcript so it is not silently empty.+ if (runError) {+ liveTurnsRef.current = [+ ...liveTurnsRef.current,+ {+ role: 'tool',+ content: '',+ name: 'error',+ result: runError,+ isError: true,+ status: 'done',+ },+ ]+ }+ // Commit the whole in-flight transcript into the session.+ const assistantText = liveTurnsRef.current+ .filter((tn) => tn.role === 'assistant')+ .map((tn) => tn.content)+ .join('\n')+ const history: CodeMessage[] = assistantText+ ? [...outgoing, { role: 'assistant', content: assistantText }]+ : outgoing+ useCodeSessions.getState().commitTurns(sid, liveTurnsRef.current, history)+ liveTurnsRef.current = []+ setLiveTurns([])+ runningRef.current = false+ setRunning(false)+ runIdRef.current = null+ // The loop has dropped any outstanding permission receivers; drop the UI.+ setPendingPerms([])+ }+ }++ const handleStop = () => {+ if (runIdRef.current)+ invoke('agent_cancel', { runId: runIdRef.current }).catch(() => {})+ }++ return (+ <div className="flex flex-col h-[calc(100dvh-(env(safe-area-inset-bottom)+env(safe-area-inset-top)))]">+ <HeaderPage>+ <div className="flex items-center justify-between w-full pr-2">+ <DropdownModelProvider useLastUsedModel />+ </div>+ </HeaderPage>++ <div className="flex flex-1 flex-col h-full overflow-hidden">+ {/* Scroll area fills the remaining space; absolute inset-0 keeps message+ volume from ever pushing the fixed input off-screen. */}+ <div className="flex-1 relative">+ {displayedTurns.length === 0 ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center px-3">+ <h1 className="text-2xl font-studio font-medium">+ {t('common:newSession')}+ </h1>+ </div>+ ) : (+ <Conversation className="absolute inset-0 text-start">+ <ConversationContent className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}>+ {uiMessages.map((message, i) => (+ <MessageItem+ key={message.id}+ message={message}+ isFirstMessage={i === 0}+ isLastMessage={i === uiMessages.length - 1}+ status={running ? 'streaming' : 'ready'}+ reasoningContainerRef={reasoningContainerRef}+ isReasoningAtBottom={isReasoningAtBottom}+ onReasoningScroll={handleReasoningScroll}+ onReasoningScrollToBottom={forceScrollReasoningToBottom}+ />+ ))}+ {/* Shared load card; renders only while a local model is loading+ (hideIdle suppresses the generic "Working…" fallback). */}+ {running && <PromptProgress hideIdle />}+ </ConversationContent>+ <ConversationScrollButton />+ </Conversation>+ )}+ </div>++ {/* Fixed input dock at the bottom. */}+ <div className="pb-4 shrink-0">+ <div className="mx-auto w-full md:w-4/5 xl:w-4/6">+ <div className="flex items-center gap-2 px-1 pb-2">+ <Button variant="outline" size="sm" className="h-7 gap-1.5 rounded-full">+ <Laptop size={14} className="text-muted-foreground" />+ <span>{t('common:local')}</span>+ </Button>+ <Button+ variant="outline"+ size="sm"+ className="h-7 gap-1.5 rounded-full max-w-[220px]"+ onClick={handleSelectFolder}+ title={folder ?? undefined}+ >+ <Folder size={14} className="text-muted-foreground" />+ <span className="truncate">+ {folderName ?? t('common:selectFolder')}+ </span>+ </Button>+ <div className="ml-auto">+ <SkillSelector folder={folder} />+ </div>+ </div>+ <div className="relative" onKeyDownCapture={onMenuKeyDown}>+ {menuItems.length > 0 && (+ <div className="absolute left-0 right-0 bottom-full mb-2 z-10 max-h-64 overflow-y-auto rounded-md border bg-popover shadow-md">+ {menuItems.map((item, i) => (+ <button+ key={item.key}+ type="button"+ ref={+ i === menuIndex+ ? (el) => el?.scrollIntoView({ block: 'nearest' })+ : undefined+ }+ onClick={item.onSelect}+ onMouseEnter={() => setMenuIndex(i)}+ className={cn(+ 'flex w-full items-center gap-3 px-3 py-2 text-left text-sm',+ i === menuIndex ? 'bg-accent' : 'hover:bg-accent'+ )}+ >+ <span className="font-mono font-medium">{item.label}</span>+ <span className="truncate text-xs text-muted-foreground">+ {item.description}+ </span>+ </button>+ ))}+ </div>+ )}+ <ChatInput+ showSpeedToken={false}+ initialMessage={true}+ onSubmit={handleSubmit}+ onStop={handleStop}+ chatStatus={running ? 'streaming' : 'ready'}+ />+ </div>+ </div>+ </div>+ </div>++ <CodePermissionDialog+ request={pendingPerms[0] ?? null}+ onRespond={respondPermission}+ />+ </div>+ )+}